Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(agent): remove profile runtime

Steven Enamakel4ba6e80a22c6
diff --git a/crates/openhuman-core/src/agent/experience/ops.rs b/crates/openhuman-core/src/agent/experience/ops.rs
index e62d4d6074..1080b5c67b 100644
--- a/crates/openhuman-core/src/agent/experience/ops.rs
+++ b/crates/openhuman-core/src/agent/experience/ops.rs
@@ -297,20 +297,11 @@ pub struct DismissResult {
}
fn profile_memory_subdir(
- workspace_dir: &std::path::Path,
+ _workspace_dir: &std::path::Path,
profile_id: Option<&str>,
) -> Result<String, String> {
- let Some(profile_id) = profile_id.map(str::trim).filter(|id| !id.is_empty()) else {
- return Ok("memory".to_string());
- };
- let state = crate::agent::profiles::load_profiles(workspace_dir)?;
- let profile = state
- .profiles
- .iter()
- .find(|profile| profile.id == profile_id)
- .ok_or_else(|| format!("agent profile '{profile_id}' not found"))?;
- let suffix = crate::agent::profiles::effective_memory_suffix(profile);
- Ok(crate::agent::profiles::memory_subdir_for_suffix(&suffix))
+ let _ = profile_id;
+ Ok("memory".to_string())
}
/// The experience store for `profile_id`'s memory subtree.
@@ -358,29 +349,11 @@ async fn open_store_in_subdir(
}
fn query_memory_subdirs(
- workspace_dir: &std::path::Path,
+ _workspace_dir: &std::path::Path,
profile_id: Option<&str>,
) -> Result<Vec<String>, String> {
- let state = crate::agent::profiles::load_profiles(workspace_dir)?;
- let mut subdirs = BTreeSet::from(["memory".to_string()]);
- let profile_id = profile_id.map(str::trim).filter(|id| !id.is_empty());
-
- for profile in &state.profiles {
- if profile_id.is_none_or(|id| profile.id == id) {
- let suffix = crate::agent::profiles::effective_memory_suffix(profile);
- subdirs.insert(crate::agent::profiles::memory_subdir_for_suffix(&suffix));
- }
- }
- if let Some(profile_id) = profile_id {
- if !state
- .profiles
- .iter()
- .any(|profile| profile.id == profile_id)
- {
- return Err(format!("agent profile '{profile_id}' not found"));
- }
- }
- Ok(subdirs.into_iter().collect())
+ let _ = profile_id;
+ Ok(vec!["memory".to_string()])
}
async fn open_query_stores(profile_id: Option<&str>) -> Result<Vec<AgentExperienceStore>, String> {
diff --git a/crates/openhuman-core/src/agent/harness/run_queue/types.rs b/crates/openhuman-core/src/agent/harness/run_queue/types.rs
index 5ccb6618fd..bab98d41af 100644
--- a/crates/openhuman-core/src/agent/harness/run_queue/types.rs
+++ b/crates/openhuman-core/src/agent/harness/run_queue/types.rs
@@ -48,6 +48,5 @@ pub struct QueuedMessage {
pub queued_at_ms: u64,
pub model_override: Option<String>,
pub temperature: Option<f64>,
- pub profile_id: Option<String>,
pub locale: Option<String>,
}
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests.rs b/crates/openhuman-core/src/agent/harness/session/builder/builder_tests.rs
index 3213b6be20..ed09915864 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/builder/builder_tests.rs
@@ -47,28 +47,10 @@ fn builtin_def(id: &str) -> crate::agent::harness::definition::AgentDefinition {
.unwrap_or_else(|| panic!("builtin agent definition not found: {id}"))
}
-// ── Finding #1 (Codex): dedicated memory subtree on the ordinary session path ─
-
-/// Build a non-default profile with the given id + dedicated-memory flag.
-fn custom_profile(id: &str, dedicated_memory: bool) -> crate::agent::profiles::AgentProfile {
- let mut profile = crate::agent::profiles::store::built_in_default_profile();
- profile.id = id.to_string();
- profile.name = id.to_string();
- profile.built_in = false;
- profile.is_master = false;
- profile.memory_dir_suffix = None;
- profile.dedicated_memory = dedicated_memory;
- profile
-}
-
#[path = "builder_tests_explicit_definition_tests.rs"]
mod explicit_definition_tests;
#[path = "builder_tests_memory_write_instruction_tests.rs"]
mod memory_write_instruction_tests;
-#[path = "builder_tests_profile_soul_prompt_tests.rs"]
-mod profile_soul_prompt_tests;
-#[path = "builder_tests_session_agent_profile_tests.rs"]
-mod session_agent_profile_tests;
#[path = "builder_tests_tool_exposure_tests.rs"]
mod tool_exposure_tests;
#[path = "builder_tests_tool_spec_views_tests.rs"]
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_profile_soul_prompt_tests.rs b/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_profile_soul_prompt_tests.rs
deleted file mode 100644
index 85c880dc59..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_profile_soul_prompt_tests.rs
+++ /dev/null
@@ -1,93 +0,0 @@
-use super::*;
-
-#[tokio::test]
-async fn build_session_agent_injects_default_profile_soul_into_prompt() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
- use crate::agent::prompts::LearnedContextData;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let config = test_config(&tmp);
- let home = config.workspace_dir.join("personalities").join("default");
- std::fs::create_dir_all(&home).unwrap();
- std::fs::write(
- home.join("SOUL.md"),
- "I am the user-edited Default profile identity.",
- )
- .unwrap();
-
- let profile = crate::agent::profiles::store::built_in_default_profile();
- let agent = Agent::build_session_agent_inner(
- &config,
- "orchestrator",
- None,
- None,
- false,
- Some(&profile),
- )
- .expect("build default-profile session");
-
- let prompt = agent
- .build_system_prompt(LearnedContextData::default())
- .expect("build_system_prompt");
- assert!(
- prompt.contains("I am the user-edited Default profile identity."),
- "the live Default profile prompt must include personalities/default/SOUL.md"
- );
-}
-
-#[tokio::test]
-async fn build_session_agent_profile_less_prompt_has_no_personality_soul() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
- use crate::agent::prompts::LearnedContextData;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let config = test_config(&tmp);
- // A personalities/alice/SOUL.md exists on disk, but a profile-less session
- // must never pull it — the prompt stays byte-identical to today.
- let home = config.workspace_dir.join("personalities").join("alice");
- std::fs::create_dir_all(&home).unwrap();
- std::fs::write(home.join("SOUL.md"), "I am Alice, a meticulous archivist.").unwrap();
-
- let agent = Agent::build_session_agent_inner(&config, "orchestrator", None, None, false, None)
- .expect("build_session_agent_inner without a profile should succeed");
-
- let prompt = agent
- .build_system_prompt(LearnedContextData::default())
- .expect("build_system_prompt");
- assert!(
- !prompt.contains("I am Alice, a meticulous archivist."),
- "a profile-less session must not inject any profile SOUL.md"
- );
-}
-
-#[tokio::test]
-async fn from_config_for_agent_still_errors_for_a_genuinely_unknown_id() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let config = test_config(&tmp);
-
- // No harness definition AND no config.agent_registry entry for this id —
- // the factory must still hard-error rather than silently building an
- // unfiltered/legacy agent.
- //
- // Note: `Agent` intentionally has no `Debug` impl (it holds `Box<dyn
- // Tool>` / provider trait objects), so this must use `match` +
- // `.is_err()` rather than `.expect_err()`, which requires `T: Debug`.
- let result = Agent::from_config_for_agent(&config, "totally_unknown_agent_id_b38");
- assert!(
- result.is_err(),
- "an id with no harness definition and no custom entry must error"
- );
- let err = result.err().unwrap();
- assert!(
- err.to_string().contains("totally_unknown_agent_id_b38"),
- "error should name the unresolved agent id: {err}"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_session_agent_profile_tests.rs b/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_session_agent_profile_tests.rs
deleted file mode 100644
index 484dd5f491..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_session_agent_profile_tests.rs
+++ /dev/null
@@ -1,730 +0,0 @@
-use super::*;
-
-#[test]
-fn recovery_tool_joins_a_named_allowlist() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::inference::tokenjuice::RETRIEVE_TOOL_NAME as RECOVERY_TOOL_NAME;
- use std::collections::HashSet;
-
- // A curated Named-scope allowlist gains retrieve_tool_output as a *real*
- // member, so the policy session, advertised specs, and the run-time
- // visible-name gate (all driven by this set) make a compaction footer
- // actionable.
- let mut visible: HashSet<String> = ["file_read".to_string(), "grep".to_string()]
- .into_iter()
- .collect();
- ensure_recovery_tool_visible(&mut visible);
- assert!(
- visible.contains(RECOVERY_TOOL_NAME),
- "recovery tool must join: {visible:?}"
- );
- assert!(visible.contains("file_read"));
-}
-
-#[test]
-fn empty_allowlist_stays_empty() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use std::collections::HashSet;
- // Empty == "no filter" (all tools visible) AND the deliberately tool-less
- // Named([]) case — both must stay empty so the invariant holds.
- let mut visible: HashSet<String> = HashSet::new();
- ensure_recovery_tool_visible(&mut visible);
- assert!(visible.is_empty(), "empty allowlist must not gain a tool");
-}
-
-#[test]
-fn drops_duplicates_first_wins() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- // Real-world collision: researcher's `delegate_name = "research"`
- // synthesises a delegate tool that shadows a same-named skill.
- // Anthropic 400s on duplicate tool names; the dedup helper must
- // keep the *first* occurrence so registration order semantics
- // are preserved (the underlying tool dispatch lookup-by-name
- // still resolves the right tool).
- let specs = vec![
- spec("research"), // skill
- spec("plan"),
- spec("research"), // delegate, dropped
- spec("run_code"),
- spec("plan"), // dropped
- ];
-
- let deduped = dedup_visible_tool_specs(specs);
-
- let names: Vec<&str> = deduped.iter().map(|s| s.name.as_str()).collect();
- assert_eq!(names, vec!["research", "plan", "run_code"]);
-}
-
-#[test]
-fn passes_through_when_no_duplicates() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- let specs = vec![spec("a"), spec("b"), spec("c")];
- let deduped = dedup_visible_tool_specs(specs);
- assert_eq!(deduped.len(), 3);
- assert_eq!(deduped[0].name, "a");
- assert_eq!(deduped[1].name, "b");
- assert_eq!(deduped[2].name, "c");
-}
-
-#[test]
-fn handles_empty_input() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- let deduped = dedup_visible_tool_specs(Vec::<ToolSpec>::new());
- assert!(deduped.is_empty());
-}
-
-#[test]
-fn preserves_full_spec_content_for_kept_entries() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- // Description + parameters must survive the dedup pass intact —
- // the LLM uses both for tool-call decisions, and corrupting them
- // would silently degrade function-calling quality.
- let mut spec_a = spec("alpha");
- spec_a.description = "first alpha — should win".to_string();
- spec_a.parameters = json!({"type": "object", "required": ["x"]});
-
- let mut spec_a_dup = spec("alpha");
- spec_a_dup.description = "second alpha — should be dropped".to_string();
-
- let deduped = dedup_visible_tool_specs(vec![spec_a.clone(), spec_a_dup]);
-
- assert_eq!(deduped.len(), 1);
- assert_eq!(deduped[0].description, "first alpha — should win");
- assert_eq!(
- deduped[0].parameters,
- json!({"type": "object", "required": ["x"]})
- );
-}
-
-#[test]
-fn automatic_memory_policy_does_not_synthesize_delegate_tools() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- let defs = crate::agent::registry::agents::load_builtins().unwrap();
- let help = defs
- .iter()
- .find(|def| def.id == "help")
- .expect("help agent is built in");
- let orchestrator = defs
- .iter()
- .find(|def| def.id == "orchestrator")
- .expect("orchestrator is built in");
-
- assert!(
- !should_synthesize_delegation_tools(help),
- "automatic memory policy should not add delegate tools"
- );
- assert!(
- should_synthesize_delegation_tools(orchestrator),
- "orchestrator still needs synthesized delegate tools"
- );
-}
-
-#[tokio::test]
-async fn build_session_agent_applies_extended_policy_definition_cap() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let config = test_config(&tmp);
- assert_eq!(
- config.agent.max_tool_iterations, 10,
- "precondition: global default must be 10 for this test to distinguish the two"
- );
-
- // `code_executor` declares `iteration_policy = "extended"` with
- // `max_iterations = 10` in its agent.toml, so its effective cap is
- // `EXTENDED_MAX_TOOL_ITERATIONS` (50) — not the raw `max_iterations`.
- let def = builtin_def("code_executor");
- assert_eq!(def.effective_max_iterations(), 50);
-
- let agent =
- Agent::build_session_agent_inner(&config, "code_executor", Some(&def), None, false, None)
- .expect(
- "build_session_agent_inner should succeed for a valid extended-policy definition",
- );
-
- assert_eq!(
- agent.agent_config().max_tool_iterations,
- 50,
- "extended-policy agent must carry its definition's effective cap (50), not the global \
- default (10)"
- );
-}
-
-#[tokio::test]
-async fn build_session_agent_applies_strict_cap_below_global_default() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let config = test_config(&tmp);
- assert_eq!(config.agent.max_tool_iterations, 10);
-
- // `archivist` is strict-policy with a declared `max_iterations = 3` —
- // well below the global default of 10. The definition cap must still
- // win (lowering the runtime cap), not just raise it.
- let def = builtin_def("archivist");
- assert_eq!(def.effective_max_iterations(), 3);
-
- let agent =
- Agent::build_session_agent_inner(&config, "archivist", Some(&def), None, false, None)
- .expect("build_session_agent_inner should succeed for a valid strict-low definition");
-
- assert_eq!(
- agent.agent_config().max_tool_iterations,
- 3,
- "strict-policy agent below the global default must still get its own (lower) cap"
- );
-}
-
-#[tokio::test]
-async fn build_session_agent_falls_back_to_global_default_when_no_definition() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let config = test_config(&tmp);
- assert_eq!(config.agent.max_tool_iterations, 10);
-
- // No `target_def` at all (e.g. registry not yet initialised, or a
- // legacy caller that never resolved one) — must fall back to the
- // unmodified global `config.agent.max_tool_iterations`.
- let agent = Agent::build_session_agent_inner(&config, "orchestrator", None, None, false, None)
- .expect("build_session_agent_inner should succeed with no definition");
-
- assert_eq!(
- agent.agent_config().max_tool_iterations,
- 10,
- "with no definition, the global config default must be used unchanged"
- );
-}
-
-// ── 1a: active profile id plumbed onto the built session ─────────────────────
-
-#[tokio::test]
-async fn build_session_agent_carries_active_profile_id_when_profile_present() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let config = test_config(&tmp);
-
- let mut profile = crate::agent::profiles::store::built_in_default_profile();
- profile.id = "alice".to_string();
- profile.built_in = false;
- profile.is_master = false;
-
- let agent = Agent::build_session_agent_inner(
- &config,
- "orchestrator",
- None,
- None,
- false,
- Some(&profile),
- )
- .expect("build_session_agent_inner with a profile should succeed");
-
- assert_eq!(
- agent.active_profile_id.as_deref(),
- Some("alice"),
- "an active profile must plumb its id onto the built session"
- );
-}
-
-#[tokio::test]
-async fn profile_allowed_tools_restrict_shared_session_builder() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let config = test_config(&tmp);
- let orchestrator = builtin_def("orchestrator");
- let mut profile = crate::agent::profiles::store::built_in_default_profile();
- profile.id = "alice".to_string();
- profile.built_in = false;
- // `shell` rather than `file_read`: this test is about a profile's
- // `allowed_tools` reaching every caller, and `file_read` moved into the
- // `files` tool pack, so the visible set would come back as the `use_skill`
- // proxy and the assertion would be about packing instead.
- profile.allowed_tools = Some(vec!["shell".to_string()]);
-
- let agent = Agent::build_session_agent_inner(
- &config,
- "orchestrator",
- Some(&orchestrator),
- None,
- false,
- Some(&profile),
- )
- .expect("build profile-scoped session");
-
- assert_eq!(
- agent.visible_tool_names_for_test(),
- &["shell".to_string()].into_iter().collect(),
- "every profile-aware caller must inherit the same tool restriction"
- );
- assert_eq!(
- agent.subagent_tool_ceiling_names_for_test(),
- &["shell".to_string()].into_iter().collect(),
- "an explicit profile tool restriction must also ceiling delegated agents"
- );
-}
-
-#[tokio::test]
-async fn channel_ceiling_does_not_inherit_orchestrator_role_visibility() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let mut config = test_config(&tmp);
- config
- .agent
- .channel_permissions
- .insert("internal".to_string(), "execute".to_string());
- let def = builtin_def("orchestrator");
-
- let agent =
- Agent::build_session_agent_inner(&config, "orchestrator", Some(&def), None, false, None)
- .expect("build channel-scoped orchestrator session");
-
- // Withheld from the parent: `shell` covers reading and writing a file, so
- // the `files` pack takes the dedicated tools off the Master Agent's wire.
- assert!(
- !agent.visible_tool_names_for_test().contains("file_write"),
- "`file_write` belongs to the `files` pack and must not be advertised \
- to the Master Agent, which reaches it through `use_skill`"
- );
- // …and that withholding must NOT travel down. The ceiling is built from
- // the full spec list against the channel policy, deliberately independent
- // of pack disclosure, so `code_executor` — which owns the pack — still
- // inherits the real tool. A ceiling computed from the parent's advertised
- // set instead would silently strip every packed tool from every child,
- // which is the regression this half exists to catch.
- assert!(
- agent
- .subagent_tool_ceiling_names_for_test()
- .contains("file_write"),
- "an execute-capable channel must let code_executor inherit file_write \
- even though the parent no longer advertises it"
- );
- assert!(
- !agent
- .subagent_tool_ceiling_names_for_test()
- .contains("update_apply"),
- "the execute channel ceiling must still exclude dangerous tools"
- );
-}
-
-#[tokio::test]
-async fn dedicated_memory_profile_scopes_tree_and_transcript_storage() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let config = test_config(&tmp);
- let mut profile = crate::agent::profiles::store::built_in_default_profile();
- profile.id = "alice".to_string();
- profile.built_in = false;
- profile.dedicated_memory = true;
-
- let agent = Agent::build_session_agent_inner(
- &config,
- "orchestrator",
- None,
- None,
- false,
- Some(&profile),
- )
- .expect("build dedicated-memory session");
-
- assert_eq!(agent.memory_subdir, "memory-alice");
- assert_eq!(agent.session_raw_subdir, "session_raw-alice");
-}
-
-#[tokio::test]
-async fn build_session_agent_leaves_active_profile_id_none_without_profile() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let config = test_config(&tmp);
-
- // The profile-less path (the legacy default) must stay byte-identical:
- // no active profile id is stamped.
- let agent = Agent::build_session_agent_inner(&config, "orchestrator", None, None, false, None)
- .expect("build_session_agent_inner with no profile should succeed");
-
- assert_eq!(
- agent.active_profile_id, None,
- "the profile-less session must not carry an active profile id"
- );
-}
-
-#[tokio::test]
-async fn build_session_agent_routes_dedicated_memory_to_profile_subtree() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let config = test_config(&tmp);
- let profile = custom_profile("alice", true);
-
- let _agent = Agent::build_session_agent_inner(
- &config,
- "orchestrator",
- None,
- None,
- false,
- Some(&profile),
- )
- .expect("build_session_agent_inner with a dedicated-memory profile should succeed");
-
- // Asserted on the binding, not on a file. Session memory is bound through
- // `DriverMemory::for_subtree`, and a module-backed driver opens its subtree
- // lazily on the first `OpenStore` call — so building an agent puts nothing
- // on disk, and the one call that would is a module round trip that times
- // out in a unit test. The binding knows the answer at bind time, which is
- // where the routing decision is actually made.
- let bound = crate::memory::binding::for_subtree(
- &config.workspace_dir,
- "memory-alice",
- &config.subsystems.memory,
- )
- .expect("the dedicated subtree must be bound");
- assert_eq!(
- bound.memory_subdir(),
- "memory-alice",
- "a dedicatedMemory profile must route session memory to memory-<id>"
- );
- assert_ne!(
- bound.memory_subdir(),
- "memory",
- "a dedicatedMemory profile must not share the common memory subtree"
- );
-}
-
-#[tokio::test]
-async fn build_session_agent_profile_less_uses_shared_memory_subtree() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let config = test_config(&tmp);
-
- // Profile-less path stays byte-identical: session memory uses the shared
- // `memory/` subtree, and no per-profile subtree is created.
- let _agent = Agent::build_session_agent_inner(&config, "orchestrator", None, None, false, None)
- .expect("build_session_agent_inner without a profile should succeed");
-
- // Same reasoning as the dedicated-memory case above: the routing decision
- // lives on the binding, and nothing reaches disk until memory is used.
- let bound = crate::memory::binding::for_subtree(
- &config.workspace_dir,
- "memory",
- &config.subsystems.memory,
- )
- .expect("the shared subtree must be bound");
- assert_eq!(
- bound.memory_subdir(),
- "memory",
- "the profile-less session must use the shared memory subtree"
- );
- // The companion "and no per-profile subtree exists" check is deliberately
- // gone rather than repointed. It asserted the ABSENCE of a directory that a
- // module-backed driver no longer creates for anyone at bind time, so it
- // passed whatever the routing did — vacuous, and worse than nothing because
- // it read like coverage. The positive assertion above is the whole property
- // this test can honestly make.
-}
-
-// ── Finding #2 (Codex): profile SOUL.md injected into the live session prompt ─
-
-#[tokio::test]
-async fn build_session_agent_injects_profile_soul_into_prompt() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
- use crate::agent::prompts::LearnedContextData;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let config = test_config(&tmp);
- std::fs::write(
- config.workspace_dir.join("SOUL.md"),
- "I am the conflicting workspace-root identity.",
- )
- .unwrap();
- // Seed the non-default profile's home SOUL.md (as ensure_profile_home would).
- let home = config.workspace_dir.join("personalities").join("alice");
- std::fs::create_dir_all(&home).unwrap();
- std::fs::write(home.join("SOUL.md"), "I am Alice, a meticulous archivist.").unwrap();
-
- let profile = custom_profile("alice", false);
- let agent = Agent::build_session_agent_inner(
- &config,
- "orchestrator",
- None,
- None,
- false,
- Some(&profile),
- )
- .expect("build_session_agent_inner with a profile should succeed");
-
- let prompt = agent
- .build_system_prompt(LearnedContextData::default())
- .expect("build_system_prompt");
- assert!(
- prompt.contains("I am Alice, a meticulous archivist."),
- "the live profile session prompt must include the profile SOUL.md content"
- );
- assert!(
- !prompt.contains("I am the conflicting workspace-root identity."),
- "profile SOUL.md must replace, not accompany, workspace-root SOUL.md"
- );
-}
-
-#[tokio::test]
-async fn build_session_agent_uses_profile_memory_instead_of_root_memory() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
- use crate::agent::prompts::LearnedContextData;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let config = test_config(&tmp);
- std::fs::write(
- config.workspace_dir.join("MEMORY.md"),
- "shared root memory marker",
- )
- .unwrap();
- let home = config.workspace_dir.join("personalities").join("alice");
- std::fs::create_dir_all(&home).unwrap();
- std::fs::write(home.join("MEMORY.md"), "alice private memory marker").unwrap();
-
- let profile = custom_profile("alice", false);
- let orchestrator = builtin_def("orchestrator");
- let agent = Agent::build_session_agent_inner(
- &config,
- "orchestrator",
- Some(&orchestrator),
- None,
- false,
- Some(&profile),
- )
- .expect("build profile session");
-
- let prompt = agent
- .build_system_prompt(LearnedContextData::default())
- .expect("build_system_prompt");
- assert!(prompt.contains("alice private memory marker"));
- assert!(!prompt.contains("shared root memory marker"));
-}
-
-/// #6040 — the memory-access instruction is about the memory tools, not the
-/// learning subsystem, so it must be in the prompt with `learning.enabled`
-/// off (the default) whenever a retrieval tool is registered and visible.
-///
-/// Passes the definition explicitly via [`builtin_def`] rather than letting the
-/// factory resolve `"orchestrator"` from the registry, and that is load-bearing
-/// rather than ceremony.
-///
-/// The section is gated on `memory_recall` being **registered and visible after
-/// tool filtering** (`any_tool_offered`), and the visible set comes from the
-/// resolved definition's tool scope. With `None` here the factory reads
-/// `AgentDefinitionRegistry`'s `static GLOBAL: OnceLock<…>`
-/// (`harness/definition/registry.rs:22`) — first-write-wins and never reset — so
-/// the test was asserting against whichever definition set some *other* test in
-/// the binary had installed first. That is exactly the hazard `builtin_def`
-/// was written for: it loads fresh from the bundled TOML, "entirely independent
-/// of the global registry singleton".
-///
-/// It is why this passed run alone and failed inside the full
-/// `openhuman::agent` run (`ci-lite` scopes the Rust lane per changed domain,
-/// so the whole scope only runs when a PR touches `agent/`), and why the
-/// sibling write-side test in `builder_tests_memory_write_instruction_tests.rs` never flaked —
-/// it already supplied `builtin_def("orchestrator")`.
-#[tokio::test]
-async fn memory_access_instruction_is_present_with_learning_disabled() {
- use crate::agent::harness::session::types::Agent;
- use crate::agent::learning::MEMORY_ACCESS_INSTRUCTION;
- use crate::agent::prompts::LearnedContextData;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let mut config = test_config(&tmp);
- config.learning.enabled = false;
-
- let orchestrator = builtin_def("orchestrator");
- let agent = Agent::build_session_agent_inner(
- &config,
- "orchestrator",
- Some(&orchestrator),
- None,
- false,
- None,
- )
- .expect("build session agent");
- let prompt = agent
- .build_system_prompt(LearnedContextData::default())
- .expect("build_system_prompt");
-
- assert!(
- prompt.contains(MEMORY_ACCESS_INSTRUCTION.trim()),
- "the memory-access section must not be gated on learning.enabled"
- );
- assert!(
- prompt.contains("Never say something is not stored"),
- "the instruction must forbid claiming absence without a retrieval"
- );
-}
-
-// ─────────────────────────────────────────────────────────────────────────────
-// B38 (Gap 2) — a custom (non-shipped) `AgentRegistryEntry` must synthesize a
-// real `AgentDefinition` and run with its own `ToolScope::Named` filter,
-// instead of the factory hard-erroring "agent definition '…' not found in
-// registry" (chat / task-dispatcher) because it never consulted
-// `config.agent_registry.entries`.
-//
-// Regression note: this test deliberately does NOT call
-// `AgentDefinitionRegistry::init_global*` itself, so — depending on whether
-// an earlier test in this binary already initialised the process-wide
-// `OnceLock` singleton — it exercises `build_session_agent_inner`'s tool-
-// visibility computation under EITHER state: `(Some(def), Some(registry))`
-// or `(Some(def), None)`. Both arms must apply `def.tools` (the synthesized
-// `ToolScope::Named` from `definition_from_registry_entry`); the `None`
-// (registry-uninitialized) arm previously fell through to the catch-all
-// "no registry, no filter" case and silently discarded the custom agent's
-// allowlist, leaving `visible_tool_names_for_test()` empty. See the
-// `(Some(def), None)` match arm in `factory.rs`'s delegation-tool-and-
-// visibility block for the fix.
-// ─────────────────────────────────────────────────────────────────────────────
-
-#[tokio::test]
-async fn from_config_for_agent_synthesizes_custom_registry_entry_with_named_scope() {
- // Building a session agent constructs a memory store, which reaches
- // the embedding seam; before the extraction this needed no setup.
- use crate::agent::harness::session::types::Agent;
- use crate::agent::registry::types::{
- AgentRegistryEntry, AgentRegistrySource, AgentSubagentPolicy,
- };
- use crate::inference::tokenjuice::RETRIEVE_TOOL_NAME;
-
- let tmp = tempfile::TempDir::new().unwrap();
- let mut config = test_config(&tmp);
- config.agent_registry.entries = vec![AgentRegistryEntry {
- id: "finance_analyst_b38".to_string(),
- name: "Finance Analyst".to_string(),
- description: "Reviews spend and drafts finance summaries.".to_string(),
- source: AgentRegistrySource::Custom,
- enabled: true,
- model: Some("hint:reasoning".to_string()),
- system_prompt: Some("You are a meticulous finance analyst.".to_string()),
- tool_allowlist: vec!["memory_search".to_string(), "web_search".to_string()],
- tool_denylist: Vec::new(),
- subagents: AgentSubagentPolicy::default(),
- tags: Vec::new(),
- metadata: serde_json::Value::Null,
- }];
-
- // Precondition: this id must NOT be a harness definition (built-in or
- // workspace TOML) — the whole point is that only the config-backed
- // custom registry knows about it.
- assert!(
- crate::agent::harness::definition::AgentDefinitionRegistry::global()
- .map(|reg| reg.get("finance_analyst_b38").is_none())
- .unwrap_or(true),
- "test id must not collide with a real harness definition"
- );
-
- let agent = Agent::from_config_for_agent(&config, "finance_analyst_b38").expect(
- "a custom agent_registry entry must synthesize a real AgentDefinition and build \
- successfully instead of erroring",
- );
-
- let visible = agent.visible_tool_names_for_test();
- assert!(
- visible.contains("memory_search") && visible.contains("web_search"),
- "the custom agent's tool_allowlist must become a real ToolScope::Named filter: {visible:?}"
- );
- assert!(
- visible.contains(RETRIEVE_TOOL_NAME),
- "the compaction recovery tool must join any non-empty Named allowlist: {visible:?}"
- );
- assert!(
- !visible.contains("automate"),
- "a tool outside the custom agent's allowlist must not be visible: {visible:?}"
- );
-}
-
-/// `from_config` hands the build-time delegation tools to the builder's
-/// synthesised set rather than folding them into the durable registry.
-///
-/// Before #6145 the factory appended them to `tools`, so the first
-/// `refresh_delegation_tools` — which replaces `Agent::synthesized_tools` and
-/// never touches `tools` — would have left the build-time instances behind:
-/// duplicated in the prompt catalogue next to their fresh replacements, and
-/// only kept off the dispatch path by set ordering.
-#[test]
-fn from_config_keeps_build_time_delegation_tools_out_of_the_durable_registry() {
- crate::agent::harness::AgentDefinitionRegistry::init_global_builtins().unwrap();
- let tmp = tempfile::TempDir::new().unwrap();
- let config = test_config(&tmp);
-
- let agent = crate::agent::Agent::from_config_for_agent(&config, "orchestrator")
- .expect("orchestrator session build");
-
- let synthesized: Vec<String> = agent
- .synthesized_tools_arc()
- .iter()
- .map(|tool| tool.name().to_string())
- .collect();
- assert!(
- !synthesized.is_empty(),
- "the orchestrator declares sub-agents, so the factory must synthesise delegates"
- );
- for name in &synthesized {
- assert!(
- agent.tools().iter().all(|tool| tool.name() != name),
- "build-time delegate `{name}` must not also sit in the durable registry"
- );
- assert!(
- agent.tool_specs().iter().any(|spec| &spec.name == name),
- "build-time delegate `{name}` must be advertised"
- );
- assert!(
- agent.tool_policy_session.decisions.contains_key(name),
- "build-time delegate `{name}` must carry a policy decision"
- );
- }
- let expected_mask: std::collections::HashSet<String> = synthesized.iter().cloned().collect();
- assert_eq!(
- agent.synthesized_tool_names, expected_mask,
- "the refresh mask must be seeded with exactly the synthesised names"
- );
- // What a sub-agent is handed: the durable registry and its specs, index
- // for index, with no synthesised delegate among them.
- let durable_specs = agent.durable_tool_specs_arc();
- assert_eq!(durable_specs.len(), agent.tools().len());
- for (tool, spec) in agent.tools().iter().zip(durable_specs.iter()) {
- assert_eq!(
- tool.name(),
- spec.name,
- "durable specs must track the registry index for index"
- );
- }
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/factory.rs b/crates/openhuman-core/src/agent/harness/session/builder/factory.rs
index 0fd89b4191..412e498b2c 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/factory.rs
+++ b/crates/openhuman-core/src/agent/harness/session/builder/factory.rs
@@ -102,26 +102,7 @@ impl Agent {
.unwrap_or(config.default_temperature)
);
- Self::build_session_agent_inner(config, agent_id, target_def.as_ref(), None, false, None)
- }
-
- /// Construct a session agent with an additional profile prompt section. Used by the web channel when the user
- /// selects a persistent agent profile for the thread.
- pub fn from_config_for_agent_with_profile(
- config: &Config,
- agent_id: &str,
- profile_prompt_suffix: Option<String>,
- profile: Option<&crate::agent::profiles::AgentProfile>,
- ) -> Result<Self> {
- let target_def = resolve_target_definition(config, agent_id)?;
- Self::build_session_agent_inner(
- config,
- agent_id,
- target_def.as_ref(),
- profile_prompt_suffix,
- false,
- profile,
- )
+ Self::build_session_agent_inner(config, agent_id, target_def.as_ref(), false)
}
/// Build a session agent from a definition the caller already holds,
@@ -137,23 +118,13 @@ impl Agent {
pub fn from_config_with_definition(
config: &Config,
definition: &crate::agent::harness::definition::AgentDefinition,
- profile: Option<&crate::agent::profiles::AgentProfile>,
- profile_prompt_suffix: Option<String>,
) -> Result<Self> {
log::debug!(
- "[agent] from_config_with_definition id={} sandbox={:?} profile={:?}",
+ "[agent] from_config_with_definition id={} sandbox={:?}",
definition.id,
definition.sandbox_mode,
- profile.map(|p| p.id.as_str())
);
- Self::build_session_agent_inner(
- config,
- &definition.id,
- Some(definition),
- profile_prompt_suffix,
- false,
- profile,
- )
+ Self::build_session_agent_inner(config, &definition.id, Some(definition), false)
}
/// Internal constructor that consumes the optionally-resolved agent
@@ -170,92 +141,26 @@ impl Agent {
config: &Config,
agent_id: &str,
target_def: Option<&crate::agent::harness::definition::AgentDefinition>,
- profile_prompt_suffix: Option<String>,
read_only_tools_only: bool,
- profile: Option<&crate::agent::profiles::AgentProfile>,
) -> Result<Self> {
- if let Some(p) = profile {
- tracing::debug!(
- profile_id = %p.id,
- include_agent_conversations = p.include_agent_conversations,
- allowed_tools = p.allowed_tools.as_ref().map_or(0, |t| t.len()),
- allowed_skills = p.allowed_skills.as_ref().map_or(0, |s| s.len()),
- allowed_mcp_servers = p.allowed_mcp_servers.as_ref().map_or(0, |m| m.len()),
- memory_sources = p.memory_sources.as_ref().map_or(0, |s| s.len()),
- "[profiles] applying per-profile session gate"
- );
- }
-
- // Section D — per-profile dedicated workspace. When the active profile
- // opts into `dedicated_workspace` (and its id passes validation), derive
- // a `WorkspaceDescriptor` rooted at `<action_dir>/profiles/<id>` and
- // thread it into the top-level chat turn so acting tools (shell/file/git)
- // resolve their default cwd there. Because the dir is under `action_dir`,
- // `SecurityPolicy` already permits it — no hardening change, and the
- // agent's broad write root is left intact (cross-profile write guarding
- // is a deliberate follow-up). `None` (the common case) preserves the
- // shared-`action_dir` cwd behaviour byte-for-byte.
- //
- // NOTE (deliberate): this `ctx.workspace` descriptor propagates to
- // subagents spawned from this session, so they too root under
- // `<action_dir>/profiles/<id>` rather than the bare `action_dir`. That
- // propagation is *intended* profile isolation, not a leak — a profile's
- // subagents should share its dedicated workspace. Do not "fix" it by
- // clearing the descriptor for child sessions.
- //
- // The expression is extracted into [`derive_profile_workspace_descriptor`]
- // so the unit tests exercise the *same* code path rather than a
- // hand-copied mirror.
- //
- // When no profile binds one, an embedder may still have scoped a
- // per-turn root (`agent::turn_workspace`) — a workflow node running
- // this turn against the checkout it names. The profile's dedicated
- // workspace wins where both exist: it is the stronger, persisted
- // isolation boundary, and a profile that asked for its own home must
- // not be relocated by an ambient host hint.
- let profile_workspace_descriptor =
- derive_profile_workspace_descriptor(&config.action_dir, profile)
- .or_else(derive_turn_workspace_descriptor);
+ let workspace_descriptor = derive_turn_workspace_descriptor();
let runtime: Arc<dyn host_runtime::RuntimeAdapter> = Arc::from(
host_runtime::create_runtime(&config.runtime, config.shell.hide_window)?,
);
- // 1b — arm the cross-profile write guard for every active profile,
- // independently of whether that profile uses (or successfully created)
- // a dedicated workspace. A shared/default profile still must not reach
- // another profile's `<action_dir>/profiles/<Q>` subtree from the broad
- // action root. Profile-less sessions remain byte-identical.
- let security = Arc::new(build_profile_security(config, profile));
+ let security = Arc::new(SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ ));
// Phase 1 of #1401: see comment in channels/runtime/startup.rs.
let audit = crate::security::get_or_create_workspace_audit_logger(
crate::config::AuditConfig::default(),
config.workspace_dir.clone(),
)?;
- // Route this session's captures + recall into the active profile's memory
- // subtree so `dedicatedMemory` isolation takes effect on the ordinary
- // session path (web chat, cron), not just delegation preambles. The
- // profile-less / default / shared cases resolve to `"memory"`
- // (byte-identical): `effective_memory_suffix` returns `""` for them and
- // `memory_subdir_for_suffix("")` == `"memory"`. A dedicated-memory profile
- // yields `"memory-<id>"`; a legacy numeric-suffix profile `"memory-<n>"`.
- let memory_subdir = profile
- .map(|p| {
- crate::agent::profiles::memory_subdir_for_suffix(
- &crate::agent::profiles::effective_memory_suffix(p),
- )
- })
- .unwrap_or_else(|| "memory".to_string());
- let memory_suffix = profile
- .map(crate::agent::profiles::effective_memory_suffix)
- .unwrap_or_default();
- let session_raw_subdir =
- crate::agent::profiles::session_raw_subdir_for_suffix(&memory_suffix);
- tracing::debug!(
- memory_subdir = %memory_subdir,
- has_profile = profile.is_some(),
- "[profiles] session memory subtree selected"
- );
+ let memory_subdir = "memory".to_string();
+ let session_raw_subdir = "raw".to_string();
// The session's store, through the same binding the archivist resolves
// two statements down — so one subtree yields one store rather than an
// engine handle beside a driver over the same files.
@@ -286,48 +191,7 @@ impl Agent {
// exclusively the engine's. Lane C (#6040) rides the same binding.
let (archivist_provider, auto_recall) =
super::helpers::bind_session_memory(config, &memory_subdir)?;
- // Dedicated profiles still recall unstamped experiences written by
- // pre-profile versions from the shared memory DB. Resolve that shared
- // store once, here, and hand it to the session rather than making the
- // hot turn path reload config.
- //
- // This was `global::init(workspace).memory_handle()` — booting the
- // second, in-process engine purely to borrow its `Arc<dyn Memory>`
- // (#5560). `DriverMemory` serves the same trait off the driver already
- // bound for this workspace's shared `memory` subtree, so the recall
- // reads the same rows without a second engine over the same file. Only
- // recall goes here; writes stay on the session's own store, which is
- // what keeps new records inside the profile subtree.
- let shared_experience_memory = if memory_subdir == "memory" {
- None
- } else {
- Some(
- crate::agent::experience::ops::DriverMemory::for_config(config)
- .map_err(anyhow::Error::msg)?,
- )
- };
-
- // Per-profile skill (workflow) + MCP-server allowlists. `None` = all.
- let profile_skill_allowlist: Option<std::collections::HashSet<String>> = profile
- .and_then(|p| p.allowed_skills.clone())
- .map(|v| v.into_iter().collect());
- let profile_mcp_allowlist: Option<Vec<String>> =
- profile.and_then(|p| p.allowed_mcp_servers.clone());
-
- // 2a — profile-local skills root (`<workspace>/personalities/<id>/skills/`).
- // Threaded into the harness workflow catalog AND the discovery/list tools
- // so a turn running under this profile sees its private skills (implicitly
- // allowed for their owner, winning same-name collisions). `None` for the
- // profile-less session / legacy ids keeps discovery byte-identical.
- let profile_skills_root: Option<std::path::PathBuf> = profile.and_then(|p| {
- crate::agent::profiles::profile_skills_root(&config.workspace_dir, &p.id)
- });
- if let Some(root) = profile_skills_root.as_deref() {
- tracing::debug!(
- skills_root = %root.display(),
- "[profiles] profile-local skills root active for this session"
- );
- }
+ let shared_experience_memory = None;
// Load the user's persisted tool preferences once. They drive two
// things below: granting the App UI Control / App Automation mutation
@@ -366,11 +230,7 @@ impl Agent {
&tool_config.action_dir,
&tool_config.agents,
&tool_config,
- profile,
- profile_skill_allowlist.as_ref(),
- profile_mcp_allowlist.as_deref(),
- profile_skills_root.as_deref(),
- profile_workspace_descriptor
+ workspace_descriptor
.as_ref()
.map(|descriptor| descriptor.root.as_path()),
);
@@ -619,35 +479,6 @@ impl Agent {
);
}
- // Compose the profile prompt section: the persona suffix, plus (1b) the
- // cross-profile workspace notice when a dedicated workspace is active.
- // The notice discloses the boundary the guard enforces, so it is added
- // even when the profile carries no persona suffix.
- let profile_suffix = profile_prompt_suffix
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty());
- let workspace_notice = profile_workspace_descriptor
- .as_ref()
- .and_then(|descriptor| {
- profile.map(|p| {
- crate::agent::profiles::cross_profile_workspace_notice(&p.id, &descriptor.root)
- })
- });
- if profile_suffix.is_some() || workspace_notice.is_some() {
- log::debug!(
- "[agent:builder] profile prompt section injected suffix_chars={} workspace_notice={}",
- profile_suffix.as_deref().map(|s| s.chars().count()).unwrap_or(0),
- workspace_notice.is_some(),
- );
- let mut section = crate::agent::profiles::AgentProfilePromptSection::new(
- profile_suffix.unwrap_or_default(),
- );
- if let Some(notice) = workspace_notice {
- section = section.with_workspace_notice(notice);
- }
- prompt_builder = prompt_builder.add_section(Box::new(section));
- }
-
// Build post-turn hooks when learning is enabled
let mut post_turn_hooks: Vec<Arc<dyn crate::agent::hooks::PostTurnHook>> = Vec::new();
if config.learning.enabled {
@@ -703,15 +534,8 @@ impl Agent {
}
if config.learning.tool_memory_capture_enabled {
- // 1c — stamp captured experiences with the active profile id so
- // retrieval can partition them. `None` for the profile-less
- // session leaves records unstamped (shared/legacy).
post_turn_hooks.push(Arc::new(
- crate::agent::experience::AgentExperienceCaptureHook::with_profile(
- memory.clone(),
- true,
- profile.map(|p| p.id.clone()),
- ),
+ crate::agent::experience::AgentExperienceCaptureHook::new(memory.clone(), true),
));
log::info!("[learning] agent_experience_capture hook registered");
}
@@ -752,26 +576,6 @@ impl Agent {
// delegation surface.
let prewarmed_integrations =
crate::integrations::composio::cached_active_integrations(config);
- // Per-profile connector gate: scope the connected-integration view to the
- // active profile's `composio_integrations` allowlist (None = all). This
- // governs both the system-prompt "connected integrations" surface and the
- // agent's `connected_integrations` field below, so a profile only ever
- // sees the toolkits it was granted.
- let prewarmed_integrations = match (
- prewarmed_integrations,
- profile.and_then(|p| p.composio_integrations.as_deref()),
- ) {
- (Some(list), Some(allow)) => {
- let filtered = crate::agent::profiles::filter_integrations(&list, Some(allow));
- tracing::debug!(
- before = list.len(),
- after = filtered.len(),
- "[profiles] composio connectors scoped to profile allowlist"
- );
- Some(filtered)
- }
- (other, _) => other,
- };
let prewarmed_integrations_slice = prewarmed_integrations.as_deref().unwrap_or(&[]);
// Resolve the per-agent delegation tool set and visible-tool
@@ -982,35 +786,6 @@ impl Agent {
}
}
- // Profile tool selection is a restriction on the resolved agent
- // definition, never a replacement for it. Apply it here at the shared
- // session-builder seam so web chat, cron, tasks, and delegated profile
- // runs all enforce the same callable surface. The web wrapper used to
- // replace this set after construction, which both missed background
- // runs and could broaden a named agent definition.
- if let Some(allowed_tools) = profile
- .and_then(|profile| profile.allowed_tools.as_ref())
- .filter(|tools| !tools.is_empty())
- {
- let profile_visible: std::collections::HashSet<&str> = allowed_tools
- .iter()
- .map(|tool| tool.trim())
- .filter(|tool| !tool.is_empty())
- .collect();
- if visible.is_empty() {
- visible = profile_visible.into_iter().map(str::to_string).collect();
- } else {
- visible.retain(|tool| profile_visible.contains(tool.as_str()));
- // Empty is the Agent's historical "all tools" sentinel. A
- // disjoint profile/definition intersection must instead stay
- // non-empty with an unregistered name so it advertises and
- // permits zero tools rather than accidentally broadening.
- if visible.is_empty() {
- visible.insert(NO_TOOLS_SENTINEL.to_string());
- }
- }
- }
-
// Memory prompt sections — the read side (#566) and the write side
// (#6048); both gates live in `helpers::add_memory_prompt_sections`.
prompt_builder = super::helpers::add_memory_prompt_sections(
@@ -1075,13 +850,10 @@ impl Agent {
pformat_registry.len()
);
- // Temperature override: an active profile is the user-selected runtime
- // default; otherwise use the target definition's TOML value (welcome is
- // 0.7, orchestrator is 0.4, etc). Fall back to config for the legacy
- // no-definition path.
- let effective_temperature = profile
- .and_then(|profile| profile.temperature)
- .or_else(|| target_def.map(|def| def.temperature))
+ // The resolved definition's TOML value takes precedence over the
+ // configured default for canonical agent runs.
+ let effective_temperature = target_def
+ .map(|def| def.temperature)
.unwrap_or(config.default_temperature);
// Thread PROFILE.md + MEMORY.md inclusion from the resolved
@@ -1205,17 +977,6 @@ impl Agent {
);
effective_agent_config.max_tool_iterations = def_cap;
}
- let profile_subagent_tool_ceiling = profile
- .and_then(|profile| profile.allowed_tools.as_ref())
- .filter(|tools| !tools.is_empty())
- .map(|tools| {
- tools
- .iter()
- .map(|tool| tool.trim())
- .filter(|tool| !tool.is_empty())
- .map(str::to_string)
- .collect()
- });
let mut builder = Agent::builder()
.crate_native_provider(provider_role, Arc::clone(&base_config))
.tools(tools)
@@ -1233,27 +994,10 @@ impl Agent {
.temperature(effective_temperature)
.workspace_dir(config.workspace_dir.clone())
.action_dir(config.action_dir.clone())
- .workspace_descriptor(profile_workspace_descriptor)
- // 1a — carry the active profile id (any active profile, not just
- // dedicated-workspace ones) so profile-scoped post-turn hooks can
- // see which profile the turn ran under. `None` for the profile-less
- // session keeps every consumer byte-identical.
- .active_profile_id(profile.map(|p| p.id.clone()))
- .personality_soul_md(profile.and_then(|profile| {
- crate::agent::profiles::resolve_personality_soul(&config.workspace_dir, profile)
- }))
- .personality_memory_md(profile.and_then(|profile| {
- crate::agent::profiles::resolve_personality_memory_md(
- &config.workspace_dir,
- profile,
- )
- }))
+ .workspace_descriptor(workspace_descriptor)
.profile_memory_storage(memory_subdir, session_raw_subdir)
.workflows({
- let mut catalogue = crate::skills::load_workflow_metadata_for_profile(
- &config.workspace_dir,
- profile_skills_root.as_deref(),
- );
+ let mut catalogue = crate::skills::load_workflow_metadata(&config.workspace_dir);
#[cfg(feature = "flows")]
catalogue.extend(crate::flows::catalogue::flow_entries(config));
catalogue
@@ -1267,9 +1011,6 @@ impl Agent {
.omit_memory_md(effective_omit_memory_md)
.trigger_memory_agent(effective_trigger_memory_agent)
.tokenjuice_compression(effective_tokenjuice_compression);
- if let Some(ceiling) = profile_subagent_tool_ceiling {
- builder = builder.subagent_tool_ceiling_names(ceiling);
- }
if let Some(ps) = payload_summarizer {
builder = builder.payload_summarizer(ps);
}
@@ -1494,37 +1235,6 @@ pub(crate) fn provider_role_for_definition(
provider_role_for(agent_id, master_hint.as_deref().or(default_model))
}
-pub(crate) fn derive_profile_workspace_descriptor(
- action_dir: &std::path::Path,
- profile: Option<&crate::agent::profiles::AgentProfile>,
-) -> Option<tinytools::WorkspaceDescriptor> {
- let (profile_id, dir) = profile.and_then(|p| {
- crate::agent::profiles::dedicated_workspace_dir(action_dir, p)
- .map(|dir| (p.id.clone(), dir))
- })?;
- if let Err(e) = std::fs::create_dir_all(&dir) {
- tracing::warn!(
- profile_id = %profile_id,
- dir = %dir.display(),
- error = %e,
- "[profiles] failed to create dedicated workspace dir — \
- falling back to the shared action_dir cwd for this session"
- );
- // Return None so callers fall back to the shared action_dir rather than
- // binding every acting tool (shell/file/git) to a cwd that doesn't exist.
- return None;
- }
- tracing::debug!(
- profile_id = %profile_id,
- dir = %dir.display(),
- "[profiles] session bound to dedicated workspace as default cwd"
- );
- Some(
- tinytools::WorkspaceDescriptor::new(dir)
- .with_policy_id(crate::agent::profiles::workspace_policy_id(&profile_id)),
- )
-}
-
fn derive_turn_workspace_descriptor() -> Option<tinytools::WorkspaceDescriptor> {
let root = crate::agent::turn_workspace::current()?;
if !root.is_dir() {
@@ -1541,19 +1251,3 @@ fn derive_turn_workspace_descriptor() -> Option<tinytools::WorkspaceDescriptor>
);
Some(tinytools::WorkspaceDescriptor::new(root).with_policy_id("turn-workspace"))
}
-
-fn build_profile_security(
- config: &crate::config::Config,
- profile: Option<&crate::agent::profiles::AgentProfile>,
-) -> SecurityPolicy {
- let base =
- SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir);
- match profile {
- Some(profile) => base.with_active_profile(profile.id.clone(), config.action_dir.clone()),
- None => base,
- }
-}
-
-#[cfg(test)]
-#[path = "factory_profile_workspace_descriptor_tests_tests.rs"]
-mod profile_workspace_descriptor_tests;
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/factory_profile_workspace_descriptor_tests_tests.rs b/crates/openhuman-core/src/agent/harness/session/builder/factory_profile_workspace_descriptor_tests_tests.rs
deleted file mode 100644
index 9cbcd96ccd..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/builder/factory_profile_workspace_descriptor_tests_tests.rs
+++ /dev/null
@@ -1,89 +0,0 @@
-use super::{build_profile_security, derive_profile_workspace_descriptor};
-use crate::agent::profiles::store::built_in_default_profile;
-
-fn profile(id: &str, dedicated_workspace: bool) -> crate::agent::profiles::AgentProfile {
- let mut p = built_in_default_profile();
- p.id = id.to_string();
- p.name = id.to_string();
- p.built_in = false;
- p.is_master = false;
- p.memory_dir_suffix = None;
- p.dedicated_workspace = dedicated_workspace;
- p
-}
-
-#[test]
-fn dedicated_workspace_profile_roots_descriptor_at_profile_dir() {
- // Real temp action_dir: the production fn creates the profile dir as a
- // side effect, so assert against the resolved path suffix.
- let action = tempfile::tempdir().expect("action tempdir");
- let p = profile("alice", true);
- let desc = derive_profile_workspace_descriptor(action.path(), Some(&p))
- .expect("dedicated_workspace profile yields a descriptor");
- let expected = action.path().join("profiles").join("alice");
- assert_eq!(desc.root.as_path(), expected.as_path());
- // The production path really created the dir.
- assert!(desc.root.is_dir());
-}
-
-#[test]
-fn shared_profile_yields_no_descriptor() {
- let action = tempfile::tempdir().expect("action tempdir");
- let p = profile("bob", false);
- assert!(derive_profile_workspace_descriptor(action.path(), Some(&p)).is_none());
-}
-
-#[test]
-fn none_profile_yields_no_descriptor() {
- let action = tempfile::tempdir().expect("action tempdir");
- assert!(derive_profile_workspace_descriptor(action.path(), None).is_none());
-}
-
-#[test]
-fn legacy_invalid_id_yields_no_descriptor_even_when_opted_in() {
- let action = tempfile::tempdir().expect("action tempdir");
- // An id that fails validation can't mint a workspace path → no descriptor,
- // so the session falls back to the shared action_dir cwd.
- let p = profile("Bad Id", true);
- assert!(derive_profile_workspace_descriptor(action.path(), Some(&p)).is_none());
-}
-
-#[test]
-fn create_dir_failure_yields_no_descriptor() {
- // Point `action_dir` at a regular file so `profiles/…` can't be created.
- // The function must fall back to `None` (shared action_dir cwd) rather
- // than hand tools a descriptor rooted at a nonexistent dir.
- let tmp = tempfile::tempdir().expect("tempdir");
- let action_file = tmp.path().join("not-a-dir");
- std::fs::write(&action_file, b"x").expect("write file");
- let p = profile("alice", true);
- assert!(
- derive_profile_workspace_descriptor(&action_file, Some(&p)).is_none(),
- "a create_dir_all failure must fall back to None"
- );
-}
-
-#[test]
-fn shared_profile_still_arms_cross_profile_guard() {
- let temp = tempfile::tempdir().expect("tempdir");
- let mut config = crate::config::Config::default();
- config.action_dir = temp.path().join("actions");
- config.workspace_dir = temp.path().join("state");
- let profile = profile("default", false);
-
- let security = build_profile_security(&config, Some(&profile));
-
- let guard = security
- .active_profile
- .expect("every active profile must arm the guard");
- assert_eq!(guard.profile_id, "default");
- assert_eq!(guard.action_dir, config.action_dir);
-}
-
-#[test]
-fn profile_less_session_leaves_cross_profile_guard_disarmed() {
- let config = crate::config::Config::default();
- assert!(build_profile_security(&config, None)
- .active_profile
- .is_none());
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/tools.rs b/crates/openhuman-core/src/agent/harness/session/turn/tools.rs
index 5ae23b0872..8ab245cc29 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/tools.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/tools.rs
@@ -369,31 +369,14 @@ impl Agent {
w.dir_name.clone()
}
};
- // Keep the mid-session refresh consistent with the initial catalog
- // (built in the session factory): include the active profile's private
- // skills root so profile-local installs are tracked/announced too. `None`
- // for the profile-less session reproduces the prior behaviour.
- let profile_skills_root = self
- .active_profile_id
- .as_deref()
- .and_then(|id| crate::agent::profiles::profile_skills_root(&self.workspace_dir, id));
- // An invalid/absent active profile id silently falls back to shared
- // discovery. Log the branch id-free (boolean only, never the profile id or
- // resolved path) per the observability convention for new/changed flows.
- let profile_local_skills_active = profile_skills_root.is_some();
- log::debug!(
- "[agent_loop] refreshing installed-skills metadata (trigger={trigger}, profile_local_skills_active={profile_local_skills_active})"
- );
- let mut latest = crate::skills::load_workflow_metadata_for_profile(
- &self.workspace_dir,
- profile_skills_root.as_deref(),
- );
+ log::debug!("[agent_loop] refreshing installed-skills metadata (trigger={trigger})");
+ let mut latest = crate::skills::load_workflow_metadata(&self.workspace_dir);
#[cfg(feature = "flows")]
if let Some(config) = self.runtime_config.as_deref() {
latest.extend(crate::flows::catalogue::flow_entries(config));
}
log::debug!(
- "[agent_loop] refreshed installed-skills metadata (trigger={trigger}, profile_local_skills_active={profile_local_skills_active}, workflow_count={})",
+ "[agent_loop] refreshed installed-skills metadata (trigger={trigger}, workflow_count={})",
latest.len()
);
let current_ids: std::collections::HashSet<String> =
diff --git a/crates/openhuman-core/src/agent/mod.rs b/crates/openhuman-core/src/agent/mod.rs
index 046a5db05e..37762e6268 100644
--- a/crates/openhuman-core/src/agent/mod.rs
+++ b/crates/openhuman-core/src/agent/mod.rs
@@ -42,7 +42,6 @@ pub mod plan_review;
/// agree on `cmd.exe` (Windows) vs `bash`/`sh` (Unix). Fixes #4705 where
/// the sandbox paths hardcoded `sh` and failed at spawn on Windows.
pub mod platform_shell;
-pub mod profiles;
pub mod progress;
/// Task-local [`progress::AgentProgress`] sink — how an in-process embedder
/// observes a turn driven through an RPC that returns only a final string.
diff --git a/crates/openhuman-core/src/agent/profiles/README.md b/crates/openhuman-core/src/agent/profiles/README.md
deleted file mode 100644
index b7b39bcda4..0000000000
--- a/crates/openhuman-core/src/agent/profiles/README.md
+++ /dev/null
@@ -1,145 +0,0 @@
-# profiles
-
-Persistent, user-selectable agent "flavours". A profile carries a name,
-description, an `agent_id`, runtime defaults (model override, temperature,
-system-prompt suffix, SOUL.md), and configurable allowlists for tools, skills,
-MCP servers, Composio integrations, and memory sources. Selecting a profile
-changes how the agent introduces itself, what it remembers, and what it can do.
-State persists under `<workspace>/agent_profiles.json`; the module also owns
-each profile's on-disk "home" (identity/memory files under `workspace_dir`,
-optional dedicated workspace under `action_dir`) and the guard that keeps
-dedicated-workspace profiles from writing into a sibling's directory.
-
-## Responsibilities
-
-- Define the `AgentProfile` / `AgentProfilesState` serde types and the
- built-in profile set (`default`, `reasoning`, `research`, `planner`,
- `review`).
-- Persist and normalise profile state (`AgentProfileStore`): merge built-ins
- into any loaded/saved state, slugify ids, drop empty allowlist entries to
- `None`, auto-assign a stable numeric `memory_dir_suffix` to new custom
- profiles, and pin non-dedicated built-ins back to the shared memory subtree
- on every load/save.
-- Materialize and reconcile each profile's on-disk "home" — `SOUL.md`,
- `MEMORY.md`, a private `skills/` dir, and (opt-in) a dedicated workspace.
-- Resolve profile-scoped paths for prompt building: which SOUL.md content and
- MEMORY.md to use, the effective memory subtree suffix, and a session
- signature that changes when a profile's resolved inputs change.
-- Enforce the cross-profile write guard: block a dedicated-workspace profile's
- tool calls from targeting a sibling profile's workspace.
-- Expose the `profiles` RPC namespace (list/select/upsert/delete), wired into
- the core registry.
-
-## Key files
-
-| File | Role |
-| --- | --- |
-| `mod.rs` | Module docs, `mod` decls, and the re-export surface. |
-| `types.rs` | `AgentProfile`, `AgentProfilesState`, `DEFAULT_PROFILE_ID`, `profile_signature` (a serialized cache key for prompt construction). |
-| `store.rs` | `AgentProfileStore` (load/save/select/upsert/delete/resolve) over `<workspace>/agent_profiles.json`; `built_in_profiles`, `load_profiles`, id normalisation/slugification (`normalise_profile_id`, applied before `validate_profile_id` on every `upsert`), and the numeric `memory_dir_suffix` allocator. `delete` refuses built-in ids. |
-| `home.rs` | Per-profile home materialization: `profile_home`, `profile_action_workspace`, `profile_skills_dir`/`profile_skills_root`, `validate_profile_id`, `ensure_profile_home` (idempotent seed), `sync_soul_md_on_upsert` (reconcile an edited inline soul into the on-disk file), `dedicated_workspace_dir`. |
-| `paths.rs` | Personality-scoped path/content resolution: `resolve_personality_soul` (home `SOUL.md` → `soul_md_path` → inline `soul_md` → `None`), `resolve_personality_memory_md`, `effective_memory_suffix`, the `*_subdir_for_suffix` helpers, `profile_session_signature`, `PersonalityContext`, `filter_integrations`/`HasToolkit`, and the `pub(crate)` `soul_md_file_path` shared with the channel runtime's identity fingerprint. |
-| `guard.rs` | Cross-profile identity plumbing and write guard: `workspace_policy_id`/`profile_id_from_policy_id` (encode/decode the `openhuman.profile:<id>` `WorkspaceDescriptor::policy_id`; only the encoder has a non-test caller, in the session builder), `classify_cross_profile_target` (file tools), `scan_command_for_cross_profile` (shell/process tools, best-effort), `PROFILES_ROOT_SENTINEL`. |
-| `prompt_section.rs` | `AgentProfilePromptSection` (a `PromptSection` named `agent_profile`), `render_agent_profile_block` (the same `## Agent profile` text for prompt paths without a `PromptContext`, used by `channels/system_prompt.rs`), and `cross_profile_workspace_notice`. |
-| `ops.rs` | `list`/`select`/`upsert`/`delete` business logic: `agent_id` validation against the global agent registry, home materialization, SOUL.md reconciliation, and read-only path enrichment (`soulMdFile`, `skillsDir`, `workspaceDir`) on the returned payload. |
-| `schemas.rs` | Controller schemas + thin handlers for the `profiles` namespace; re-exported as `all_profiles_controller_schemas` / `all_profiles_registered_controllers`. |
-| `*_tests.rs` | Sibling test suites per file (via `#[path]`). |
-
-## Profile home layout (hermes-agent style)
-
-```text
-<workspace>/personalities/<id>/SOUL.md identity (hot-read each prompt)
-<workspace>/personalities/<id>/MEMORY.md curated per-profile memory
-<workspace>/personalities/<id>/skills/ private skills (owner-only discovery)
-<workspace>/{memory,memory_tree,session_raw}-<id>/ dedicated memory subtree (opt-in)
-<action_dir>/profiles/<id>/ agent-writable workspace (opt-in)
-```
-
-Identity/memory files live under `workspace_dir`, which the agent's write
-tools cannot reach; the writable working dir lives under `action_dir`, which
-acting tools are allowed to touch. `SOUL.md` is re-read on every prompt build
-so identity edits take effect live. `dedicated_memory` derives a `-<id>`
-suffix and wins over the auto-assigned numeric suffix; `dedicated_workspace`
-roots a per-profile default cwd for acting tools. `ensure_profile_home` never
-overwrites a user's edited files.
-
-## RPC / controllers
-
-Namespace `profiles`, registered via `all_profiles_registered_controllers()`.
-On the JSON-RPC wire the methods are `openhuman.profiles_list`,
-`openhuman.profiles_select`, `openhuman.profiles_upsert`, and
-`openhuman.profiles_delete` (`core::all::rpc_method_name`).
-
-| Controller | Inputs | Output |
-| --- | --- | --- |
-| `profiles.list` | — | `{ profiles, activeProfileId }`, each profile enriched with `soulMdFile`/`skillsDir`/`workspaceDir` when present on disk |
-| `profiles.select` | `profile_id: string` | updated state payload |
-| `profiles.upsert` | `profile: AgentProfile` (camelCase JSON) | updated state payload |
-| `profiles.delete` | `profile_id: string` | updated state payload; built-in ids are rejected |
-
-`upsert` fails closed on a non-empty, non-`orchestrator` `agent_id` when the
-global `AgentDefinitionRegistry` is not yet initialised, rather than persist a
-reference it cannot validate. Built-in profiles have their home materialized
-on first `select`; custom profiles are materialized on `upsert`. Soul edits are
-reconciled into the on-disk `SOUL.md` on every `upsert`, built-in included.
-
-## Cron attribution
-
-A cron job may carry a `profile_id` (`cron::CronJob::profile_id`). When set and
-the profile still exists, the scheduled run is built under that profile (soul,
-memory scope, dedicated workspace, allowlists) via the same profile-aware
-session path the task dispatcher uses; a deleted profile falls back to a
-profile-less run rather than failing the job.
-
-## Used by
-
-- `crates/openhuman-core/src/core/all.rs` registers the controllers.
-- `agent/harness/session/builder/factory.rs` is the primary consumer: resolves
- memory suffix/subdirs, soul/memory content, the dedicated workspace
- descriptor (`workspace_policy_id`), the cross-profile prompt notice, and
- integration filtering when building a session.
-- `agent/harness/session/turn/tools.rs` resolves `profile_skills_root` for
- workflow discovery.
-- `security/policy/path_checks.rs` (file tools) calls
- `classify_cross_profile_target` once the session builder has armed
- `SecurityPolicy::with_active_profile(profile_id, action_dir)`;
- `tools/impl/system/mod.rs` (process tools) classifies the cwd and then adds
- `scan_command_for_cross_profile`. Both map `PROFILES_ROOT_SENTINEL` to a
- root-specific `[policy-blocked]` denial.
-- `cron/scheduler/agent_run.rs` resolves a job's attributed profile via
- `load_profiles` and builds the run with
- `Agent::from_config_for_agent_with_profile`.
-- `agent/task_dispatcher/executor.rs` and
- `agent/tools/delegate_to_personality.rs` build a `PersonalityContext` for the
- target profile; `agent/tools/run_workflow.rs`, `skills/tools.rs`,
- `skills/runtime/run_machinery.rs`, and `tools/ops.rs` thread the active
- `AgentProfile` through skill listing and execution. `skills/ops_discover.rs`
- does not import this module: it receives the already-resolved
- `profile_skills_root` path (`discover_workflows_with_profile`,
- `load_workflow_metadata_for_profile`).
-- `agent/experience/ops.rs` maps profiles to memory subdirs with
- `effective_memory_suffix` / `memory_subdir_for_suffix`.
-- `channels/system_prompt.rs` resolves soul/memory content and
- `soul_md_file_path` for the native channel runtime and renders the block via
- `render_agent_profile_block`; `web_chat/session.rs` stores
- `profile_session_signature` for cache invalidation; `web_chat/run_task.rs`
- reads the store.
-- `agent/tinyagents/host/definition_registry.rs` reads
- `AgentProfile::model_override` through its `ModelResolver` adapter.
-
-## Notes / gotchas
-
-- `validate_profile_id` (hermes grammar `^[a-z0-9][a-z0-9_-]{0,63}$`) gates
- every home read/write path and every store `upsert`; a legacy id that fails
- validation still loads from the JSON store but gets no home, no dedicated
- workspace, no dedicated-memory suffix, and no profile-local skills — reads
- and writes stay symmetric. The `home.rs` doc comment saying it is "only
- enforced when creating a new custom profile" understates this.
-- `scan_command_for_cross_profile` is explicitly best-effort defense in depth
- for process tools (static token scan, not a real shell parser); the hard
- boundary for file mutations is `SecurityPolicy::validate_path`.
-- The mod-level doc comment's "Relocated from `openhuman::agent::profiles` /
- `::personality_paths`" line dates from the original domain split (#3632),
- when `agent/profiles.rs` and `agent/personality_paths.rs` were merged into
- this directory; it predates the crate flattening. The module is addressed as
- `crate::agent::profiles` in-crate (`openhuman::agent::profiles` from outside).
diff --git a/crates/openhuman-core/src/agent/profiles/guard.rs b/crates/openhuman-core/src/agent/profiles/guard.rs
deleted file mode 100644
index 54848fcb98..0000000000
--- a/crates/openhuman-core/src/agent/profiles/guard.rs
+++ /dev/null
@@ -1,369 +0,0 @@
-//! Active-profile identity plumbing + the cross-profile write guard.
-//!
-//! Two concerns, both keyed off *which* profile a turn runs under:
-//!
-//! 1. **Identity plumbing (1a).** When a dedicated-workspace profile is active,
-//! its id is carried to the tool layer inside the
-//! [`WorkspaceDescriptor`](tinyagents_harness::workspace::WorkspaceDescriptor)'s
-//! `policy_id` field as `openhuman.profile:<id>`. [`workspace_policy_id`] and
-//! [`profile_id_from_policy_id`] are the single encode/decode pair so the
-//! session builder and the tool gates can never drift on the wire format.
-//!
-//! 2. **Cross-profile write guard (1b).** A hermes `file_safety` equivalent:
-//! while a turn runs under a dedicated-workspace profile `P`, any tool
-//! write/command whose resolved target lands in a *sibling* profile's
-//! workspace `<action_dir>/profiles/<Q>/` (Q != P) is blocked. See
-//! [`classify_cross_profile_target`] (file tools) and
-//! [`scan_command_for_cross_profile`] (shell / `node_exec` / `npm_exec`). The
-//! guard only ever **tightens**: with no active profile the classifier is
-//! never consulted and behaviour is byte-identical to today.
-
-use std::path::{Component, Path, PathBuf};
-
-/// Wire prefix for the per-profile `WorkspaceDescriptor::policy_id`. The suffix
-/// is the profile id. Kept private-behind-helpers so the encode/decode pair is
-/// the only way this string is produced or parsed.
-const PROFILE_POLICY_ID_PREFIX: &str = "openhuman.profile:";
-/// Marker returned when the protected target is the shared `profiles/` root
-/// rather than one named sibling profile.
-pub const PROFILES_ROOT_SENTINEL: &str = "<profiles-root>";
-
-/// Encode a profile id as the `WorkspaceDescriptor::policy_id` the session
-/// builder stamps onto a dedicated-workspace descriptor (`openhuman.profile:<id>`).
-///
-/// Paired with [`profile_id_from_policy_id`]; the two are the sole owners of the
-/// wire format so the encode and decode sites can never disagree.
-pub fn workspace_policy_id(profile_id: &str) -> String {
- format!("{PROFILE_POLICY_ID_PREFIX}{profile_id}")
-}
-
-/// Decode the active profile id from a `WorkspaceDescriptor::policy_id`.
-///
-/// Returns `Some(id)` only for the `openhuman.profile:<id>` shape
-/// [`workspace_policy_id`] produces (and only when `<id>` is non-empty); every
-/// other policy_id — the worktree-isolation ids, test ids, or an empty string —
-/// yields `None`, so a non-profile session reads as "no active profile" and the
-/// tool gates stay on their shared-path behaviour.
-pub fn profile_id_from_policy_id(policy_id: &str) -> Option<&str> {
- policy_id
- .strip_prefix(PROFILE_POLICY_ID_PREFIX)
- .filter(|id| !id.is_empty())
-}
-
-/// Outcome of classifying a resolved write/command target against the active
-/// profile's isolation boundary.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum CrossProfileDecision {
- /// The target is not inside a *sibling* profile's workspace — permitted (the
- /// active profile's own dir, the shared `action_dir`, or anywhere outside
- /// `<action_dir>/profiles/` entirely).
- Allow,
- /// The target lands inside `<action_dir>/profiles/<other_id>/` with
- /// `other_id != active_profile`, or is the shared profiles root itself —
- /// blocked. Root targets carry [`PROFILES_ROOT_SENTINEL`].
- Block {
- /// The sibling profile whose workspace the target tried to reach.
- other_id: String,
- },
-}
-
-/// Classify a resolved target path against the active profile's cross-profile
-/// isolation boundary (the hermes `classify_cross_profile_target` analogue).
-///
-/// `action_dir` is the agent's **broad** action root; sibling profile
-/// workspaces live under `<action_dir>/profiles/<id>/`. `active_profile` is the
-/// id of the profile the turn runs under. `target` is the write/command target
-/// — ideally already resolved to an absolute path, but relative inputs are
-/// joined onto `action_dir` first so the classifier is robust to either.
-///
-/// Returns [`CrossProfileDecision::Block`] iff the canonicalized `target` is
-/// the shared `<action_dir>/profiles/` root or is inside
-/// `<action_dir>/profiles/<Q>/` for some `Q != active_profile`, otherwise
-/// [`CrossProfileDecision::Allow`].
-///
-/// **Symlink safety.** The comparison is done on canonicalized paths: the
-/// profiles root and the target's deepest *existing* ancestor are both resolved
-/// through the filesystem, so a symlink inside profile `P` pointing at profile
-/// `Q`'s dir still classifies as a cross-profile target. A not-yet-existing
-/// target (a fresh write) canonicalizes its nearest existing ancestor and
-/// re-appends the missing tail, matching the `validate_parent_path` strategy.
-pub fn classify_cross_profile_target(
- action_dir: &Path,
- active_profile: &str,
- target: &Path,
-) -> CrossProfileDecision {
- let profiles_root = action_dir.join("profiles");
- // Resolve the profiles root through the filesystem so a symlinked
- // action_dir (macOS `/tmp` -> `/private/tmp`, sandbox bind-mounts) compares
- // against the same canonical prefix the target resolves to.
- let canon_profiles_root = canonicalize_best_effort(&profiles_root);
-
- let absolute_target = if target.is_absolute() {
- target.to_path_buf()
- } else {
- action_dir.join(target)
- };
- let canon_target = canonicalize_deepest_existing(&absolute_target);
-
- let Ok(relative) = canon_target.strip_prefix(&canon_profiles_root) else {
- return CrossProfileDecision::Allow;
- };
- if relative.as_os_str().is_empty() {
- return CrossProfileDecision::Block {
- other_id: PROFILES_ROOT_SENTINEL.to_string(),
- };
- }
- // First component under `profiles/` is the owning profile id.
- let Some(Component::Normal(owner)) = relative.components().next() else {
- return CrossProfileDecision::Allow;
- };
- let owner = owner.to_string_lossy();
- if owner == active_profile {
- CrossProfileDecision::Allow
- } else {
- CrossProfileDecision::Block {
- other_id: owner.into_owned(),
- }
- }
-}
-
-/// Best-effort scan of a process `command` for a token that targets a sibling
-/// profile's workspace, given the command's working directory `cwd` (the active
-/// profile's own dir).
-///
-/// # Guarantee level (read before relying on this)
-///
-/// This is **best-effort defense-in-depth for model-facing process tools, not a
-/// hard boundary.** It is a static, pre-execution token scan — it cannot see
-/// what the process will actually do at runtime. Known, deliberate gaps:
-///
-/// - **Variable / command substitution.** `$HOME`, `${VAR}`, `$(cmd)`, and
-/// backtick substitution resolve to paths only at runtime; a token like
-/// `$SOME_VAR` is not path-shaped textually and is skipped.
-/// - **Paths embedded inside interpreter code.** `python -c 'open("../bob/x","w")'`
-/// or any inline script hides the path inside a program string. The tokenizer
-/// below splits on quotes/parens/commas/`=` so the *simple* embedded cases are
-/// still isolated and classified, but an arbitrary interpreter can construct a
-/// path the scanner never sees.
-///
-/// The **hard** cross-profile boundary for file mutations is
-/// [`SecurityPolicy::validate_path`](crate::security) at the file-tool
-/// call site (every write funnels through it). Process commands do **not** funnel
-/// through that gate, so this scan is their only in-Rust backstop — and
-/// airtight process confinement (an OS sandbox: cwd_jail / Seatbelt / Landlock
-/// restricting the process to its own subtree) is deliberate follow-up work, not
-/// provided here. Do not treat a `None` result as proof a command cannot reach a
-/// sibling profile.
-///
-/// # What it does catch
-///
-/// It splits the command into simple `;` / `&&` / `||` segments, tracks a
-/// leading literal `cd <path>` across those segments, then splits each segment
-/// on whitespace, redirect/pipe operators, and common
-/// shell punctuation (quotes, parens, backtick, `,`, `=`, `{`, `}`, `&`), keeps
-/// path-shaped tokens (those containing a path separator or a leading `~`),
-/// plus bare operands naming an existing profile when the tracked cwd is the
-/// profiles root, resolves each against `cwd`, and classifies it via
-/// [`classify_cross_profile_target`]. This reliably catches the realistic
-/// non-adversarial escape vectors: an absolute path into `profiles/<Q>`, a
-/// `../<Q>/…` traversal, a `--flag=../<Q>/…` form, and simple quoted paths.
-/// Returns the first sibling profile id it would write into, or `None` when no
-/// scanned token lands in another profile.
-pub fn scan_command_for_cross_profile(
- command: &str,
- cwd: &Path,
- action_dir: &Path,
- active_profile: &str,
-) -> Option<String> {
- let mut effective_cwd = cwd.to_path_buf();
- for segment in split_command_segments(command) {
- if let Some(other_id) =
- scan_command_segment(segment, &effective_cwd, action_dir, active_profile)
- {
- return Some(other_id);
- }
-
- let Some(next_cwd) = simple_cd_target(segment, &effective_cwd) else {
- continue;
- };
- if let CrossProfileDecision::Block { other_id } =
- classify_cross_profile_target(action_dir, active_profile, &next_cwd)
- {
- return Some(other_id);
- }
- effective_cwd = next_cwd;
- }
- None
-}
-
-/// Split at top-level shell sequencing operators while leaving separators
-/// inside simple quotes alone. This is intentionally not a complete shell
-/// parser; it only supplies enough ordering for literal `cd` tracking.
-fn split_command_segments(command: &str) -> Vec<&str> {
- let bytes = command.as_bytes();
- let mut segments = Vec::new();
- let mut start = 0;
- let mut quote: Option<u8> = None;
- let mut i = 0;
- while i < bytes.len() {
- let byte = bytes[i];
- if matches!(byte, b'\'' | b'"' | b'`') {
- if quote == Some(byte) {
- quote = None;
- } else if quote.is_none() {
- quote = Some(byte);
- }
- i += 1;
- continue;
- }
- if quote.is_none()
- && (byte == b';'
- || (i + 1 < bytes.len()
- && ((byte == b'&' && bytes[i + 1] == b'&')
- || (byte == b'|' && bytes[i + 1] == b'|'))))
- {
- segments.push(&command[start..i]);
- i += if byte == b';' { 1 } else { 2 };
- start = i;
- continue;
- }
- i += 1;
- }
- segments.push(&command[start..]);
- segments
-}
-
-fn scan_command_segment(
- command: &str,
- cwd: &Path,
- action_dir: &Path,
- active_profile: &str,
-) -> Option<String> {
- let profiles_root = canonicalize_best_effort(&action_dir.join("profiles"));
- let cwd_is_action_root = canonicalize_best_effort(cwd) == canonicalize_best_effort(action_dir);
- let cwd_is_profiles_root = canonicalize_best_effort(cwd) == profiles_root;
- let mut token_index = 0usize;
- // Split on shell punctuation as well as whitespace/redirects so a path
- // embedded in a quoted string, a `flag=value`, a comma list, or a brace
- // expansion is isolated into its own token. Splitting only ever produces
- // substrings of the original command, so it cannot invent a path that
- // resolves into a sibling — it can only surface one that was genuinely
- // referenced (no new false positives, strictly better coverage).
- for raw in command.split(|c: char| {
- c.is_whitespace()
- || matches!(
- c,
- '>' | '<' | '|' | ';' | ',' | '=' | '"' | '\'' | '(' | ')' | '`' | '{' | '}' | '&'
- )
- }) {
- // Residual wrapper chars the split didn't consume at the edges.
- let token = raw.trim_matches(|c| matches!(c, '"' | '\'' | '(' | ')' | '`'));
- if token.is_empty() {
- continue;
- }
- let is_command_word = token_index == 0;
- token_index += 1;
- // Ordinarily only path-shaped tokens can reach another directory. Once
- // a preceding `cd` has moved cwd to `<action_dir>/profiles`, however, a
- // bare operand can name a sibling directly (`rm -rf bob`). Scan such an
- // operand only when it resolves to an existing profile directory; this
- // avoids treating ordinary arguments (`echo hi`) as profile ids.
- let path_shaped =
- token == ".." || token.contains('/') || token.contains('\\') || token.starts_with('~');
- let bare_profile_operand = cwd_is_profiles_root
- && !is_command_word
- && !token.starts_with('-')
- && cwd.join(token).is_dir();
- // From the shared action root, the literal bare operand `profiles`
- // names the protected collection root itself (`rm -rf profiles`,
- // `mv profiles backup`). It has no slash, so classify it explicitly
- // before spawning just as we do bare sibling ids from inside that root.
- let bare_profiles_root_operand =
- cwd_is_action_root && !is_command_word && token == "profiles";
- if !path_shaped && !bare_profile_operand && !bare_profiles_root_operand {
- continue;
- }
- let expanded = crate::config::expand_tilde(token);
- let candidate = Path::new(&expanded);
- let absolute = if candidate.is_absolute() {
- candidate.to_path_buf()
- } else {
- cwd.join(candidate)
- };
- if let CrossProfileDecision::Block { other_id } =
- classify_cross_profile_target(action_dir, active_profile, &absolute)
- {
- return Some(other_id);
- }
- }
- None
-}
-
-/// Resolve a literal leading `cd` for the next sequenced command. Dynamic
-/// targets (`$VAR`, command substitution) remain in the documented best-effort
-/// gap. Nonexistent/non-directory targets are ignored because the shell's `cd`
-/// would fail and leave cwd unchanged.
-fn simple_cd_target(segment: &str, cwd: &Path) -> Option<PathBuf> {
- let mut words = segment.split_whitespace();
- if words.next()? != "cd" {
- return None;
- }
- let mut target = words.next()?;
- if target == "--" {
- target = words.next()?;
- }
- let target = target.trim_matches(|c| matches!(c, '"' | '\''));
- if target.is_empty() || target.contains('$') || target.contains('`') || target.contains("$(") {
- return None;
- }
- let expanded = crate::config::expand_tilde(target);
- let path = Path::new(&expanded);
- let candidate = if path.is_absolute() {
- path.to_path_buf()
- } else {
- cwd.join(path)
- };
- candidate
- .is_dir()
- .then(|| canonicalize_best_effort(&candidate))
-}
-
-/// Canonicalize `path`, falling back to the raw path when it does not exist.
-fn canonicalize_best_effort(path: &Path) -> PathBuf {
- path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
-}
-
-/// Canonicalize `path` when it exists; otherwise canonicalize its deepest
-/// existing ancestor and re-append the missing tail. Mirrors
-/// `SecurityPolicy::validate_parent_path`'s symlink-safe resolution so a fresh
-/// (not-yet-created) write target is still classified against the real
-/// filesystem layout.
-fn canonicalize_deepest_existing(path: &Path) -> PathBuf {
- if let Ok(canonical) = path.canonicalize() {
- return canonical;
- }
- // Walk up to the deepest existing ancestor, collecting the non-existent tail.
- let mut existing = path;
- let mut tail: Vec<Component<'_>> = Vec::new();
- loop {
- if existing.exists() {
- break;
- }
- match (existing.parent(), existing.components().next_back()) {
- (Some(parent), Some(comp)) => {
- tail.push(comp);
- existing = parent;
- }
- _ => break,
- }
- }
- let mut resolved = canonicalize_best_effort(existing);
- for component in tail.into_iter().rev() {
- resolved.push(component);
- }
- resolved
-}
-
-#[cfg(test)]
-#[path = "guard_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/profiles/guard_tests.rs b/crates/openhuman-core/src/agent/profiles/guard_tests.rs
deleted file mode 100644
index 1e384dc428..0000000000
--- a/crates/openhuman-core/src/agent/profiles/guard_tests.rs
+++ /dev/null
@@ -1,272 +0,0 @@
-use super::*;
-
-#[test]
-fn workspace_policy_id_round_trips() {
- let encoded = workspace_policy_id("alice");
- assert_eq!(encoded, "openhuman.profile:alice");
- assert_eq!(profile_id_from_policy_id(&encoded), Some("alice"));
-}
-
-#[test]
-fn profile_id_from_policy_id_rejects_non_profile_ids() {
- // Worktree-isolation / test ids and empty strings are not profiles.
- assert_eq!(profile_id_from_policy_id("test-worktree"), None);
- assert_eq!(profile_id_from_policy_id(""), None);
- assert_eq!(profile_id_from_policy_id("openhuman.profile:"), None);
- assert_eq!(
- profile_id_from_policy_id("openhuman.profile:bob"),
- Some("bob")
- );
-}
-
-// ── Cross-profile classifier (1b) ─────────────────────────────────────
-
-fn profiles_layout() -> (tempfile::TempDir, PathBuf) {
- let action = tempfile::tempdir().expect("action tempdir");
- let profiles = action.path().join("profiles");
- for id in ["alice", "bob"] {
- std::fs::create_dir_all(profiles.join(id)).unwrap();
- }
- let action_dir = action.path().to_path_buf();
- (action, action_dir)
-}
-
-#[test]
-fn same_profile_target_is_allowed() {
- let (_g, action) = profiles_layout();
- let target = action.join("profiles").join("alice").join("notes.txt");
- assert_eq!(
- classify_cross_profile_target(&action, "alice", &target),
- CrossProfileDecision::Allow
- );
-}
-
-#[test]
-fn other_profile_target_is_blocked() {
- let (_g, action) = profiles_layout();
- let target = action.join("profiles").join("bob").join("secret.txt");
- assert_eq!(
- classify_cross_profile_target(&action, "alice", &target),
- CrossProfileDecision::Block {
- other_id: "bob".into()
- }
- );
-}
-
-#[test]
-fn target_outside_profiles_root_is_allowed() {
- let (_g, action) = profiles_layout();
- // A plain file under action_dir (the shared workspace) — not under
- // profiles/ at all.
- let target = action.join("scratch.txt");
- assert_eq!(
- classify_cross_profile_target(&action, "alice", &target),
- CrossProfileDecision::Allow
- );
-}
-
-#[test]
-fn nonexistent_sibling_target_is_blocked_via_ancestor() {
- let (_g, action) = profiles_layout();
- // File does not exist yet, but its parent (profiles/bob) does → the
- // deepest-existing-ancestor resolution still classifies it as bob's.
- let target = action
- .join("profiles")
- .join("bob")
- .join("nested")
- .join("fresh.txt");
- assert_eq!(
- classify_cross_profile_target(&action, "alice", &target),
- CrossProfileDecision::Block {
- other_id: "bob".into()
- }
- );
-}
-
-#[test]
-fn relative_traversal_into_sibling_is_blocked() {
- let (_g, action) = profiles_layout();
- // A relative `../bob/x` composed from the active profile's own dir.
- let target = action
- .join("profiles")
- .join("alice")
- .join("..")
- .join("bob")
- .join("x.txt");
- assert_eq!(
- classify_cross_profile_target(&action, "alice", &target),
- CrossProfileDecision::Block {
- other_id: "bob".into()
- }
- );
-}
-
-#[cfg(unix)]
-#[test]
-fn symlink_into_sibling_profile_is_blocked() {
- use std::os::unix::fs::symlink;
- let (_g, action) = profiles_layout();
- // Inside alice, a symlink `link -> ../bob`. Writing `link/hijack.txt`
- // must resolve to bob's dir and block.
- let alice = action.join("profiles").join("alice");
- let bob = action.join("profiles").join("bob");
- symlink(&bob, alice.join("link")).unwrap();
- let target = alice.join("link").join("hijack.txt");
- assert_eq!(
- classify_cross_profile_target(&action, "alice", &target),
- CrossProfileDecision::Block {
- other_id: "bob".into()
- }
- );
-}
-
-#[test]
-fn profiles_root_itself_is_blocked() {
- // Mutating the shared root can affect every sibling at once.
- let (_g, action) = profiles_layout();
- let target = action.join("profiles");
- assert_eq!(
- classify_cross_profile_target(&action, "alice", &target),
- CrossProfileDecision::Block {
- other_id: PROFILES_ROOT_SENTINEL.into()
- }
- );
-}
-
-// ── Shell command scan (1b) ───────────────────────────────────────────
-
-#[test]
-fn scan_command_allows_same_profile_and_bare_tokens() {
- let (_g, action) = profiles_layout();
- let cwd = action.join("profiles").join("alice");
- // Relative writes under cwd, plain words, and reads under cwd are fine.
- assert_eq!(
- scan_command_for_cross_profile("echo hi > notes.txt", &cwd, &action, "alice"),
- None
- );
- assert_eq!(
- scan_command_for_cross_profile("ls -la sub/dir", &cwd, &action, "alice"),
- None
- );
-}
-
-#[test]
-fn scan_command_blocks_absolute_sibling_target() {
- let (_g, action) = profiles_layout();
- let cwd = action.join("profiles").join("alice");
- let sibling = action.join("profiles").join("bob").join("loot.txt");
- let command = format!("cat secret > {}", sibling.display());
- assert_eq!(
- scan_command_for_cross_profile(&command, &cwd, &action, "alice"),
- Some("bob".to_string())
- );
-}
-
-#[test]
-fn scan_command_blocks_relative_traversal_into_sibling() {
- let (_g, action) = profiles_layout();
- let cwd = action.join("profiles").join("alice");
- assert_eq!(
- scan_command_for_cross_profile("cp x ../bob/y", &cwd, &action, "alice"),
- Some("bob".to_string())
- );
-}
-
-#[test]
-fn scan_command_tracks_cd_before_sibling_write() {
- let (_g, action) = profiles_layout();
- let cwd = action.join("profiles").join("alice");
- assert_eq!(
- scan_command_for_cross_profile("cd .. && printf x > bob/loot.txt", &cwd, &action, "alice"),
- Some(PROFILES_ROOT_SENTINEL.to_string())
- );
-}
-
-#[test]
-fn scan_command_tracks_cd_before_bare_sibling_operand() {
- let (_g, action) = profiles_layout();
- let cwd = action.join("profiles").join("alice");
- assert_eq!(
- scan_command_for_cross_profile("cd ..; rm -rf bob", &cwd, &action, "alice"),
- Some(PROFILES_ROOT_SENTINEL.to_string())
- );
-}
-
-#[test]
-fn scan_command_blocks_parent_profiles_root_operand() {
- let (_g, action) = profiles_layout();
- let cwd = action.join("profiles").join("alice");
- assert_eq!(
- scan_command_for_cross_profile("rm -rf ..", &cwd, &action, "alice"),
- Some(PROFILES_ROOT_SENTINEL.to_string())
- );
-}
-
-#[test]
-fn scan_command_blocks_bare_profiles_root_from_action_dir() {
- let (_g, action) = profiles_layout();
- assert_eq!(
- scan_command_for_cross_profile("rm -rf profiles", &action, &action, "alice"),
- Some(PROFILES_ROOT_SENTINEL.to_string())
- );
-}
-
-#[test]
-fn scan_command_tracks_chained_bare_cd_into_sibling() {
- let (_g, action) = profiles_layout();
- let cwd = action.join("profiles").join("alice");
- assert_eq!(
- scan_command_for_cross_profile(
- "cd ..; cd bob; printf x > loot.txt",
- &cwd,
- &action,
- "alice"
- ),
- Some(PROFILES_ROOT_SENTINEL.to_string())
- );
-}
-
-#[test]
-fn scan_command_blocks_path_embedded_in_quoted_interpreter_arg() {
- // The path is buried inside a python -c program string. Splitting on
- // quotes/parens/commas isolates `../bob/loot.txt` so the simple embedded
- // case is still caught.
- let (_g, action) = profiles_layout();
- let cwd = action.join("profiles").join("alice");
- let command = r#"python -c 'open("../bob/loot.txt","w").write("x")'"#;
- assert_eq!(
- scan_command_for_cross_profile(command, &cwd, &action, "alice"),
- Some("bob".to_string())
- );
-}
-
-#[test]
-fn scan_command_blocks_flag_equals_sibling_path() {
- // A `--flag=../bob/…` form: splitting on `=` isolates the path token.
- let (_g, action) = profiles_layout();
- let cwd = action.join("profiles").join("alice");
- assert_eq!(
- scan_command_for_cross_profile(
- "tar --directory=../bob/x -cf a.tar .",
- &cwd,
- &action,
- "alice"
- ),
- Some("bob".to_string())
- );
-}
-
-#[test]
-fn scan_command_documents_variable_expansion_gap() {
- // Documented best-effort limitation: a shell variable that expands to a
- // sibling path at runtime is not statically resolvable, so the scan does
- // not catch it. The hard boundary for this is an OS sandbox (follow-up);
- // this test pins the known gap so it's a conscious contract, not a
- // surprise regression.
- let (_g, action) = profiles_layout();
- let cwd = action.join("profiles").join("alice");
- assert_eq!(
- scan_command_for_cross_profile("cp x $TARGET_DIR/y", &cwd, &action, "alice"),
- None
- );
-}
diff --git a/crates/openhuman-core/src/agent/profiles/home.rs b/crates/openhuman-core/src/agent/profiles/home.rs
deleted file mode 100644
index 7ee1d6f9a1..0000000000
--- a/crates/openhuman-core/src/agent/profiles/home.rs
+++ /dev/null
@@ -1,458 +0,0 @@
-//! Per-profile "home" materialization — hermes-agent-style agent homes.
-//!
-//! Each profile can own an identity file (`SOUL.md`, re-read on every prompt
-//! build), a curated per-profile memory file (`MEMORY.md`), an optional
-//! dedicated memory subtree, and an optional agent-writable workspace. The two
-//! roots are deliberately split (see [`crate::config`]):
-//!
-//! ```text
-//! <workspace>/personalities/<id>/SOUL.md identity (hot-read each prompt)
-//! <workspace>/personalities/<id>/MEMORY.md curated per-profile memory
-//! <action_dir>/profiles/<id>/ agent-writable workspace
-//! ```
-//!
-//! Identity + memory files live under `workspace_dir` (core-managed reads only —
-//! the agent's write tools cannot reach there, enforced fail-closed by
-//! `is_workspace_internal_path`). The agent's *writable* working dir lives under
-//! `action_dir`, which acting tools (shell/file/git) are allowed to touch.
-
-use std::io;
-use std::path::{Path, PathBuf};
-
-use super::types::{AgentProfile, DEFAULT_PROFILE_ID};
-
-/// Directory holding a profile's core-managed identity + memory files:
-/// `<workspace>/personalities/<id>/`.
-pub fn profile_home(workspace_dir: &Path, profile_id: &str) -> PathBuf {
- workspace_dir.join("personalities").join(profile_id)
-}
-
-/// The agent-writable per-profile workspace: `<action_dir>/profiles/<id>/`.
-///
-/// Because this lives under `action_dir`, the `SecurityPolicy` already permits
-/// acting tools to read/write here — no hardening change is needed.
-pub fn profile_action_workspace(action_dir: &Path, profile_id: &str) -> PathBuf {
- action_dir.join("profiles").join(profile_id)
-}
-
-/// A profile's private skills directory: `<workspace>/personalities/<id>/skills/`.
-///
-/// SKILL.md / WORKFLOW.md bundles placed here are discovered ONLY for turns
-/// running under this profile (see
-/// `skills::discover_workflows_with_profile`). Seeded empty by
-/// [`ensure_profile_home`].
-pub fn profile_skills_dir(workspace_dir: &Path, profile_id: &str) -> PathBuf {
- profile_home(workspace_dir, profile_id).join("skills")
-}
-
-/// The profile-local skills discovery root for `profile_id`, iff the id passes
-/// [`validate_profile_id`].
-///
-/// The discovery/list seam (harness catalog build, `list_workflows` /
-/// `describe_workflow` / resource-read tools) passes this into
-/// `skills::discover_workflows_with_profile` /
-/// `skills::load_workflow_metadata_for_profile`. Returns `None` for legacy ids
-/// that fail validation — matching [`profile_skills_dir`]'s companion guards on
-/// the home/workspace paths, so a home the read paths would never load never
-/// contributes skills either.
-pub fn profile_skills_root(workspace_dir: &Path, profile_id: &str) -> Option<PathBuf> {
- if let Err(e) = validate_profile_id(profile_id) {
- tracing::debug!(
- profile_id = %profile_id,
- error = %e,
- "[profiles][home] profile_skills_root: id fails validation, no profile-local skills root"
- );
- return None;
- }
- Some(profile_skills_dir(workspace_dir, profile_id))
-}
-
-/// Validate a profile id against the hermes-style name grammar
-/// `^[a-z0-9][a-z0-9_-]{0,63}$`.
-///
-/// Only enforced when creating a *new* custom profile — legacy / built-in ids
-/// (which may not satisfy the grammar) keep loading, so this is never applied on
-/// the read/resolve paths.
-pub fn validate_profile_id(id: &str) -> Result<(), String> {
- if id.is_empty() {
- return Err("profile id must not be empty".to_string());
- }
- if id.len() > 64 {
- return Err(format!("profile id '{id}' is too long (max 64 characters)"));
- }
- let mut chars = id.chars();
- let first = chars.next().expect("non-empty checked above");
- if !(first.is_ascii_lowercase() || first.is_ascii_digit()) {
- return Err(format!(
- "profile id '{id}' must start with a lowercase letter or digit"
- ));
- }
- for c in id.chars() {
- let ok = c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-';
- if !ok {
- return Err(format!(
- "profile id '{id}' may only contain lowercase letters, digits, '_' or '-'"
- ));
- }
- }
- Ok(())
-}
-
-/// Write `contents` through a temp file in the same directory, then move it to
-/// `target`. Unix `rename` atomically replaces an existing target. Windows
-/// `rename` cannot overwrite, so rewrites remove the old target immediately
-/// before the move; this is the platform-safe remove/replace fallback used by
-/// Settings SOUL edits and clear tombstones. First-time seeds stay atomic on
-/// every platform, and no reader can observe a partially-written file.
-fn seed_file_atomic(dir: &Path, target: &Path, contents: &[u8]) -> io::Result<()> {
- let base = target
- .file_name()
- .and_then(|n| n.to_str())
- .unwrap_or("seed");
- let tmp = dir.join(format!(".{base}.tmp-{}", std::process::id()));
- std::fs::write(&tmp, contents)?;
-
- #[cfg(windows)]
- match std::fs::remove_file(target) {
- Ok(()) => {}
- Err(error) if error.kind() == io::ErrorKind::NotFound => {}
- Err(error) => {
- let _ = std::fs::remove_file(&tmp);
- return Err(error);
- }
- }
-
- match std::fs::rename(&tmp, target) {
- Ok(()) => Ok(()),
- Err(e) => {
- // Best-effort cleanup so a failed rename doesn't leave a stray temp.
- let _ = std::fs::remove_file(&tmp);
- Err(e)
- }
- }
-}
-
-/// Render the default seed persona for a profile lacking an inline `soul_md`.
-///
-/// Kept intentionally short — a real persona is authored by the user by editing
-/// the seeded `SOUL.md`. Never contains PII or secrets.
-fn default_soul_template(profile: &AgentProfile) -> String {
- let name = if profile.name.trim().is_empty() {
- profile.id.as_str()
- } else {
- profile.name.trim()
- };
- let description = profile.description.trim();
- let mut out = format!("# {name}\n\n");
- if !description.is_empty() {
- out.push_str(description);
- out.push_str("\n\n");
- }
- out.push_str(&format!(
- "You are {name}. Keep your own voice, working style, and memory distinct \
- from other profiles. Edit this file to shape your identity.\n"
- ));
- out
-}
-
-/// Materialize a profile's home on disk. Idempotent — existing files are never
-/// overwritten, so a user's edited `SOUL.md` / `MEMORY.md` survive re-runs.
-///
-/// Creates:
-/// - `<workspace>/personalities/<id>/` (always),
-/// - `SOUL.md` seeded from `profile.soul_md` when non-empty, else a short
-/// default persona template (only when the file is absent),
-/// - an empty `MEMORY.md` (only when absent),
-/// - `<action_dir>/profiles/<id>/` when `profile.dedicated_workspace`.
-pub fn ensure_profile_home(
- workspace_dir: &Path,
- action_dir: &Path,
- profile: &AgentProfile,
-) -> io::Result<()> {
- // Guard: only materialize a home for ids the read paths will actually load.
- // `resolve_personality_soul`, `dedicated_workspace_dir`, and
- // `effective_memory_suffix` all skip ids that fail `validate_profile_id`, so
- // seeding `personalities/<id>/` for such an id would leave a home nothing
- // ever reads. Early-return (no dir, no seed) to keep write/read symmetric.
- if let Err(e) = validate_profile_id(&profile.id) {
- tracing::warn!(
- profile_id = %profile.id,
- error = %e,
- "[profiles][home] ensure_profile_home skipped: id fails validation, \
- no home materialized (read paths would never load it)"
- );
- return Ok(());
- }
-
- let home = profile_home(workspace_dir, &profile.id);
- tracing::debug!(
- profile_id = %profile.id,
- home = %home.display(),
- dedicated_memory = profile.dedicated_memory,
- dedicated_workspace = profile.dedicated_workspace,
- "[profiles][home] ensure_profile_home entry"
- );
- std::fs::create_dir_all(&home).map_err(|e| {
- tracing::debug!(
- profile_id = %profile.id,
- home = %home.display(),
- error = %e,
- "[profiles][home] create_dir_all home failed"
- );
- e
- })?;
-
- let soul_path = home.join("SOUL.md");
- let has_inline_soul = profile
- .soul_md
- .as_ref()
- .is_some_and(|soul| !soul.trim().is_empty());
- if soul_path.exists() {
- tracing::debug!(
- profile_id = %profile.id,
- "[profiles][home] SOUL.md already present, not overwriting"
- );
- } else if profile.id == DEFAULT_PROFILE_ID && !has_inline_soul {
- // Backward compatibility: the built-in Default profile represents the
- // legacy workspace identity. Selecting it must not create a generic
- // profile-local template that shadows the user's root SOUL.md. Once a
- // user authors a Default soul it is seeded normally; an explicit clear
- // writes an existing empty tombstone in `sync_soul_md_on_upsert`.
- tracing::debug!(
- profile_id = %profile.id,
- "[profiles][home] Default has no authored soul; preserving root SOUL.md fallback"
- );
- } else {
- let contents = profile
- .soul_md
- .as_ref()
- .map(|s| s.trim())
- .filter(|s| !s.is_empty())
- .map(|s| {
- // Persist inline souls with a trailing newline for tidy files.
- if s.ends_with('\n') {
- s.to_string()
- } else {
- format!("{s}\n")
- }
- })
- .unwrap_or_else(|| default_soul_template(profile));
- let seeded_from_inline = has_inline_soul;
- seed_file_atomic(&home, &soul_path, contents.as_bytes()).map_err(|e| {
- tracing::debug!(
- profile_id = %profile.id,
- soul_path = %soul_path.display(),
- error = %e,
- "[profiles][home] seed SOUL.md failed"
- );
- e
- })?;
- tracing::debug!(
- profile_id = %profile.id,
- seeded_from_inline,
- "[profiles][home] SOUL.md seeded"
- );
- }
-
- let memory_path = home.join("MEMORY.md");
- if memory_path.exists() {
- tracing::debug!(
- profile_id = %profile.id,
- "[profiles][home] MEMORY.md already present, not overwriting"
- );
- } else {
- seed_file_atomic(&home, &memory_path, b"").map_err(|e| {
- tracing::debug!(
- profile_id = %profile.id,
- memory_path = %memory_path.display(),
- error = %e,
- "[profiles][home] create empty MEMORY.md failed"
- );
- e
- })?;
- tracing::debug!(
- profile_id = %profile.id,
- "[profiles][home] MEMORY.md created (empty)"
- );
- }
-
- // Profile-local skills root: `<workspace>/personalities/<id>/skills/`.
- // Created empty so the user has an obvious place to drop private SKILL.md
- // bundles; discovery surfaces them only for this profile's turns.
- let skills_dir = profile_skills_dir(workspace_dir, &profile.id);
- std::fs::create_dir_all(&skills_dir).map_err(|e| {
- tracing::debug!(
- profile_id = %profile.id,
- skills_dir = %skills_dir.display(),
- error = %e,
- "[profiles][home] create profile skills dir failed"
- );
- e
- })?;
- tracing::debug!(
- profile_id = %profile.id,
- skills_dir = %skills_dir.display(),
- "[profiles][home] profile skills dir ensured"
- );
-
- if let Some(ws) = dedicated_workspace_dir(action_dir, profile) {
- std::fs::create_dir_all(&ws).map_err(|e| {
- tracing::debug!(
- profile_id = %profile.id,
- workspace = %ws.display(),
- error = %e,
- "[profiles][home] create dedicated workspace failed"
- );
- e
- })?;
- tracing::debug!(
- profile_id = %profile.id,
- workspace = %ws.display(),
- "[profiles][home] dedicated workspace ensured"
- );
- }
-
- tracing::debug!(profile_id = %profile.id, "[profiles][home] ensure_profile_home ok");
- Ok(())
-}
-
-/// Reconcile the on-disk `SOUL.md` with an edited inline `soul_md` on an
-/// **explicit profile save** (upsert only — never on select).
-///
-/// [`ensure_profile_home`] seeds `SOUL.md` only when the file is *absent*, so a
-/// persona edited in Settings after the home already exists would update
-/// `agent_profiles.json` but leave the file stale — and because
-/// [`resolve_personality_soul`](super::paths::resolve_personality_soul) reads
-/// the file first, the agent would keep using the old identity. This closes that
-/// gap by overwriting the file (atomic temp+rename, same as the seed path) when:
-/// - the id passes [`validate_profile_id`] (read paths would load it),
-/// - `profile.soul_md` is `Some(non-empty)` and differs from the previously
-/// persisted inline value, and
-/// - the trimmed inline content differs from the current file content.
-///
-/// When `soul_md` was already empty/`None`, the file is left untouched so a
-/// manual `SOUL.md` remains authoritative. A transition from a previously
-/// non-empty inline value to empty replaces the synced file with an empty
-/// tombstone, allowing the normal root fallback while preventing a later
-/// `ensure_profile_home` call from re-seeding the default template. Only ever
-/// called from the upsert path; select must not clobber a manually edited file
-/// with a stale inline value. Returns `Ok(true)` when the file was rewritten.
-pub fn sync_soul_md_on_upsert(
- workspace_dir: &Path,
- profile: &AgentProfile,
- previous_soul_md: Option<&str>,
-) -> io::Result<bool> {
- if let Err(e) = validate_profile_id(&profile.id) {
- tracing::debug!(
- profile_id = %profile.id,
- error = %e,
- "[profiles][home] sync_soul_md_on_upsert skipped: id fails validation"
- );
- return Ok(false);
- }
- let home = profile_home(workspace_dir, &profile.id);
- let soul_path = home.join("SOUL.md");
-
- // Clearing a previously persisted inline soul is an explicit Settings edit:
- // replace the file that prior inline value created with an empty tombstone.
- // `ensure_profile_home` treats that existing file as materialized, while
- // `resolve_personality_soul` treats it as empty and falls back to root.
- // If inline was already empty, preserve any manual file exactly as before.
- let desired = match profile
- .soul_md
- .as_ref()
- .map(|s| s.trim())
- .filter(|s| !s.is_empty())
- {
- Some(s) => s,
- None => {
- let previously_inline = previous_soul_md
- .map(str::trim)
- .is_some_and(|value| !value.is_empty());
- if previously_inline {
- std::fs::create_dir_all(&home)?;
- seed_file_atomic(&home, &soul_path, b"")?;
- tracing::debug!(
- profile_id = %profile.id,
- "[profiles][home] sync_soul_md_on_upsert: cleared synced SOUL.md with tombstone"
- );
- return Ok(true);
- }
- tracing::debug!(
- profile_id = %profile.id,
- "[profiles][home] sync_soul_md_on_upsert: inline soul_md empty, file left as-is"
- );
- return Ok(false);
- }
- };
-
- // The editor submits the complete profile on every save. If the inline
- // soul did not change, this is an unrelated settings update and the
- // hot-read file remains authoritative (it may have been edited manually
- // since the profile was loaded).
- if previous_soul_md.map(str::trim) == Some(desired) {
- tracing::debug!(
- profile_id = %profile.id,
- "[profiles][home] sync_soul_md_on_upsert: inline soul_md unchanged, file left as-is"
- );
- return Ok(false);
- }
-
- // No-op when the file already matches the edited value (compare trimmed so a
- // trailing-newline difference doesn't churn the file).
- if let Ok(current) = std::fs::read_to_string(&soul_path) {
- if current.trim() == desired {
- tracing::debug!(
- profile_id = %profile.id,
- "[profiles][home] sync_soul_md_on_upsert: file already matches inline soul_md"
- );
- return Ok(false);
- }
- }
-
- // Persist with a trailing newline for tidy files, matching the seed path.
- let contents = format!("{desired}\n");
- std::fs::create_dir_all(&home)?;
- seed_file_atomic(&home, &soul_path, contents.as_bytes()).map_err(|e| {
- tracing::debug!(
- profile_id = %profile.id,
- soul_path = %soul_path.display(),
- error = %e,
- "[profiles][home] sync_soul_md_on_upsert: overwrite SOUL.md failed"
- );
- e
- })?;
- tracing::debug!(
- profile_id = %profile.id,
- "[profiles][home] sync_soul_md_on_upsert: SOUL.md overwritten from edited inline soul_md"
- );
- Ok(true)
-}
-
-/// Resolve the agent-writable workspace directory for a profile *iff* it opts
-/// into a dedicated workspace and its id passes [`validate_profile_id`].
-///
-/// Returns `None` for shared-workspace profiles (the common case) and for
-/// legacy ids that would fail id validation — in both cases the caller falls
-/// back to the shared `action_dir`. This is the seam the session builder uses to
-/// derive a per-profile default cwd (section D): a `WorkspaceDescriptor` rooted
-/// at this path is threaded into the top-level chat turn.
-pub fn dedicated_workspace_dir(action_dir: &Path, profile: &AgentProfile) -> Option<PathBuf> {
- if !profile.dedicated_workspace {
- return None;
- }
- if let Err(e) = validate_profile_id(&profile.id) {
- tracing::warn!(
- profile_id = %profile.id,
- error = %e,
- "[profiles][home] dedicated_workspace requested but id fails validation, \
- falling back to shared action_dir"
- );
- return None;
- }
- Some(profile_action_workspace(action_dir, &profile.id))
-}
-
-#[cfg(test)]
-#[path = "home_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/profiles/home_tests.rs b/crates/openhuman-core/src/agent/profiles/home_tests.rs
deleted file mode 100644
index dc71daac44..0000000000
--- a/crates/openhuman-core/src/agent/profiles/home_tests.rs
+++ /dev/null
@@ -1,339 +0,0 @@
-use super::*;
-use tempfile::TempDir;
-
-fn test_profile(id: &str) -> AgentProfile {
- let mut p = crate::agent::profiles::store::built_in_default_profile();
- p.id = id.to_string();
- p.name = id.to_string();
- p.built_in = false;
- p.is_master = false;
- p.memory_dir_suffix = None;
- p.soul_md = None;
- p.dedicated_memory = false;
- p.dedicated_workspace = false;
- p
-}
-
-#[test]
-fn profile_home_and_action_workspace_paths() {
- let ws = Path::new("/tmp/ws");
- let action = Path::new("/tmp/act");
- assert_eq!(
- profile_home(ws, "alice"),
- Path::new("/tmp/ws/personalities/alice")
- );
- assert_eq!(
- profile_action_workspace(action, "alice"),
- Path::new("/tmp/act/profiles/alice")
- );
-}
-
-#[test]
-fn validate_profile_id_matrix() {
- // Valid.
- let max_len = "x".repeat(64);
- for id in [
- "a",
- "a1",
- "alice",
- "alice-bob",
- "alice_bob",
- "0",
- max_len.as_str(),
- ] {
- assert!(validate_profile_id(id).is_ok(), "expected ok: {id}");
- }
- // Invalid.
- for id in [
- "", // empty
- "-alice", // leading dash
- "_alice", // leading underscore
- "Alice", // uppercase
- "alice bob", // space
- "alice.bob", // dot
- "alice/bob", // slash
- "über", // non-ascii
- ] {
- assert!(validate_profile_id(id).is_err(), "expected err: {id}");
- }
- // Too long (65).
- assert!(validate_profile_id(&"a".repeat(65)).is_err());
-}
-
-#[test]
-fn ensure_profile_home_creates_and_seeds() {
- let ws = TempDir::new().unwrap();
- let action = TempDir::new().unwrap();
- let mut profile = test_profile("alice");
- profile.description = "A tidy writer.".to_string();
-
- ensure_profile_home(ws.path(), action.path(), &profile).expect("ensure");
-
- let home = profile_home(ws.path(), "alice");
- assert!(home.is_dir());
- let soul = std::fs::read_to_string(home.join("SOUL.md")).unwrap();
- // Default template used (no inline soul_md).
- assert!(soul.contains("alice"));
- assert!(soul.contains("A tidy writer."));
- assert!(home.join("MEMORY.md").exists());
- // No dedicated workspace requested.
- assert!(!profile_action_workspace(action.path(), "alice").exists());
-}
-
-#[test]
-fn ensure_profile_home_seeds_soul_from_inline() {
- let ws = TempDir::new().unwrap();
- let action = TempDir::new().unwrap();
- let mut profile = test_profile("bob");
- profile.soul_md = Some("I am Bob, terse and exact.".to_string());
-
- ensure_profile_home(ws.path(), action.path(), &profile).expect("ensure");
- let soul = std::fs::read_to_string(profile_home(ws.path(), "bob").join("SOUL.md")).unwrap();
- assert_eq!(soul, "I am Bob, terse and exact.\n");
-}
-
-#[test]
-fn ensure_default_profile_without_authored_soul_preserves_root_fallback() {
- let ws = TempDir::new().unwrap();
- let action = TempDir::new().unwrap();
- std::fs::write(ws.path().join("SOUL.md"), "Established root identity").unwrap();
- let mut profile = test_profile(DEFAULT_PROFILE_ID);
- profile.built_in = true;
- profile.soul_md = None;
-
- ensure_profile_home(ws.path(), action.path(), &profile).expect("ensure");
-
- assert!(profile_home(ws.path(), DEFAULT_PROFILE_ID)
- .join("MEMORY.md")
- .exists());
- assert!(!profile_home(ws.path(), DEFAULT_PROFILE_ID)
- .join("SOUL.md")
- .exists());
- assert_eq!(
- super::super::paths::resolve_personality_soul(ws.path(), &profile),
- None,
- "no profile override leaves prompt construction on the root SOUL.md"
- );
-}
-
-#[test]
-fn ensure_profile_home_is_idempotent_and_preserves_edits() {
- let ws = TempDir::new().unwrap();
- let action = TempDir::new().unwrap();
- let profile = test_profile("carol");
-
- ensure_profile_home(ws.path(), action.path(), &profile).expect("ensure 1");
- let home = profile_home(ws.path(), "carol");
- // User edits both files.
- std::fs::write(home.join("SOUL.md"), "EDITED SOUL").unwrap();
- std::fs::write(home.join("MEMORY.md"), "EDITED MEMORY").unwrap();
-
- // Second run must not clobber.
- ensure_profile_home(ws.path(), action.path(), &profile).expect("ensure 2");
- assert_eq!(
- std::fs::read_to_string(home.join("SOUL.md")).unwrap(),
- "EDITED SOUL"
- );
- assert_eq!(
- std::fs::read_to_string(home.join("MEMORY.md")).unwrap(),
- "EDITED MEMORY"
- );
-}
-
-#[test]
-fn ensure_profile_home_creates_empty_skills_dir() {
- let ws = TempDir::new().unwrap();
- let action = TempDir::new().unwrap();
- let profile = test_profile("frank");
-
- ensure_profile_home(ws.path(), action.path(), &profile).expect("ensure");
-
- let skills = profile_skills_dir(ws.path(), "frank");
- assert!(skills.is_dir(), "profile skills dir must be created");
- // Empty — the user drops private SKILL.md bundles here.
- assert_eq!(std::fs::read_dir(&skills).unwrap().count(), 0);
-}
-
-#[test]
-fn profile_skills_dir_and_root_paths() {
- let ws = Path::new("/tmp/ws");
- assert_eq!(
- profile_skills_dir(ws, "alice"),
- Path::new("/tmp/ws/personalities/alice/skills")
- );
- // Valid id → Some(root); invalid id → None (read paths never load it).
- assert_eq!(
- profile_skills_root(ws, "alice"),
- Some(Path::new("/tmp/ws/personalities/alice/skills").to_path_buf())
- );
- assert_eq!(profile_skills_root(ws, "Bad Id"), None);
-}
-
-#[test]
-fn ensure_profile_home_creates_dedicated_workspace_when_opted_in() {
- let ws = TempDir::new().unwrap();
- let action = TempDir::new().unwrap();
- let mut profile = test_profile("dave");
- profile.dedicated_workspace = true;
-
- ensure_profile_home(ws.path(), action.path(), &profile).expect("ensure");
- assert!(profile_action_workspace(action.path(), "dave").is_dir());
-}
-
-#[test]
-fn ensure_profile_home_skips_invalid_id() {
- let ws = TempDir::new().unwrap();
- let action = TempDir::new().unwrap();
- // An id that fails validate_profile_id must not materialize a home — the
- // read paths would never load it, so a seeded dir would be dead weight.
- let mut profile = test_profile("placeholder");
- profile.id = "Bad Id".to_string();
- profile.dedicated_workspace = true;
-
- ensure_profile_home(ws.path(), action.path(), &profile).expect("ensure");
-
- assert!(
- !profile_home(ws.path(), "Bad Id").exists(),
- "no home dir should be materialized for an invalid id"
- );
- assert!(
- !profile_action_workspace(action.path(), "Bad Id").exists(),
- "no dedicated workspace should be materialized for an invalid id"
- );
- // The `personalities/` root itself must not be created for it either.
- assert!(!ws.path().join("personalities").join("Bad Id").exists());
-}
-
-#[test]
-fn sync_soul_md_on_upsert_overwrites_edited_inline_soul() {
- let ws = TempDir::new().unwrap();
- let action = TempDir::new().unwrap();
- let mut profile = test_profile("grace");
- profile.soul_md = Some("Original identity.".to_string());
- // Seed the home once (writes SOUL.md from the original inline value).
- ensure_profile_home(ws.path(), action.path(), &profile).expect("ensure");
- let soul_path = profile_home(ws.path(), "grace").join("SOUL.md");
- assert_eq!(
- std::fs::read_to_string(&soul_path).unwrap(),
- "Original identity.\n"
- );
-
- // User edits the persona in Settings → the stored inline value changes.
- profile.soul_md = Some("Rewritten identity from Settings.".to_string());
- let rewritten =
- sync_soul_md_on_upsert(ws.path(), &profile, Some("Original identity.")).expect("sync");
- assert!(
- rewritten,
- "differing inline soul_md must overwrite the file"
- );
- assert_eq!(
- std::fs::read_to_string(&soul_path).unwrap(),
- "Rewritten identity from Settings.\n"
- );
-
- // Idempotent: a second sync with the same value is a no-op.
- let again = sync_soul_md_on_upsert(
- ws.path(),
- &profile,
- Some("Rewritten identity from Settings."),
- )
- .expect("sync 2");
- assert!(!again, "matching inline soul_md must not rewrite the file");
-}
-
-#[test]
-fn sync_soul_md_on_upsert_leaves_file_when_inline_empty() {
- let ws = TempDir::new().unwrap();
- let action = TempDir::new().unwrap();
- // Seed with a default template (no inline soul_md).
- let mut profile = test_profile("heidi");
- ensure_profile_home(ws.path(), action.path(), &profile).expect("ensure");
- let soul_path = profile_home(ws.path(), "heidi").join("SOUL.md");
- // User edits the file manually; inline soul_md stays empty/None.
- std::fs::write(&soul_path, "MANUALLY EDITED SOUL").unwrap();
-
- profile.soul_md = None;
- let none_written = sync_soul_md_on_upsert(ws.path(), &profile, None).expect("sync none");
- assert!(!none_written);
- profile.soul_md = Some(" ".to_string()); // whitespace-only → treated as empty
- let blank_written = sync_soul_md_on_upsert(ws.path(), &profile, None).expect("sync blank");
- assert!(!blank_written);
-
- // The manual edit stays authoritative.
- assert_eq!(
- std::fs::read_to_string(&soul_path).unwrap(),
- "MANUALLY EDITED SOUL"
- );
-}
-
-#[test]
-fn sync_soul_md_on_upsert_persists_empty_tombstone_when_inline_is_cleared() {
- let ws = TempDir::new().unwrap();
- let action = TempDir::new().unwrap();
- let mut profile = test_profile("judy");
- profile.soul_md = Some("Settings identity".to_string());
- ensure_profile_home(ws.path(), action.path(), &profile).expect("ensure");
- let soul_path = profile_home(ws.path(), "judy").join("SOUL.md");
- assert!(soul_path.exists());
-
- profile.soul_md = None;
- assert!(
- sync_soul_md_on_upsert(ws.path(), &profile, Some("Settings identity"))
- .expect("clear synced soul")
- );
- assert_eq!(std::fs::read_to_string(&soul_path).unwrap(), "");
-
- // Selecting/materializing the profile again must not resurrect the
- // default profile template over the explicit clear.
- ensure_profile_home(ws.path(), action.path(), &profile).expect("ensure after clear");
- assert_eq!(std::fs::read_to_string(&soul_path).unwrap(), "");
-}
-
-#[test]
-fn sync_soul_md_on_upsert_skips_invalid_id() {
- let ws = TempDir::new().unwrap();
- let mut profile = test_profile("placeholder");
- profile.id = "Bad Id".to_string();
- profile.soul_md = Some("ignored".to_string());
- assert!(!sync_soul_md_on_upsert(ws.path(), &profile, None).expect("sync"));
- assert!(!profile_home(ws.path(), "Bad Id").join("SOUL.md").exists());
-}
-
-#[test]
-fn sync_soul_md_on_upsert_preserves_manual_file_when_inline_unchanged() {
- let ws = TempDir::new().unwrap();
- let action = TempDir::new().unwrap();
- let mut profile = test_profile("ivy");
- profile.soul_md = Some("Stored identity.".to_string());
- ensure_profile_home(ws.path(), action.path(), &profile).expect("ensure");
- let soul_path = profile_home(ws.path(), "ivy").join("SOUL.md");
- std::fs::write(&soul_path, "MANUALLY EDITED IDENTITY\n").unwrap();
-
- let rewritten = sync_soul_md_on_upsert(ws.path(), &profile, Some("Stored identity."))
- .expect("sync unchanged");
-
- assert!(!rewritten);
- assert_eq!(
- std::fs::read_to_string(soul_path).unwrap(),
- "MANUALLY EDITED IDENTITY\n"
- );
-}
-
-#[test]
-fn dedicated_workspace_dir_gates_on_flag_and_id() {
- let action = Path::new("/tmp/act");
- let mut shared = test_profile("eve");
- assert_eq!(dedicated_workspace_dir(action, &shared), None);
-
- shared.dedicated_workspace = true;
- assert_eq!(
- dedicated_workspace_dir(action, &shared),
- Some(Path::new("/tmp/act/profiles/eve").to_path_buf())
- );
-
- // Legacy invalid id + dedicated_workspace → None (falls back to shared).
- let mut legacy = test_profile("Legacy Id");
- legacy.id = "Legacy Id".to_string();
- legacy.dedicated_workspace = true;
- assert_eq!(dedicated_workspace_dir(action, &legacy), None);
-}
diff --git a/crates/openhuman-core/src/agent/profiles/mod.rs b/crates/openhuman-core/src/agent/profiles/mod.rs
deleted file mode 100644
index 7d685f833e..0000000000
--- a/crates/openhuman-core/src/agent/profiles/mod.rs
+++ /dev/null
@@ -1,83 +0,0 @@
-//! Profiles domain — persistent, user-selectable agent "flavours".
-//!
-//! Each profile carries a custom name + SOUL.md, runtime defaults (model,
-//! temperature, system-prompt suffix), and configurable allowlists for tools,
-//! skills, MCP servers, connectors, and memory sources. Selecting a profile
-//! changes how the agent introduces itself, what it remembers, and what it can
-//! do. State persists under `<workspace>/agent_profiles.json`.
-//!
-//! Relocated from `openhuman::agent::profiles` / `::personality_paths` so the
-//! domain is addressable on its own (`openhuman::agent::profiles`).
-//!
-//! # Profile home layout (hermes-agent style)
-//!
-//! Beyond the shared JSON store, each profile can own an on-disk "home" — an
-//! identity file, curated memory, an optional dedicated memory subtree, and an
-//! optional agent-writable workspace. The two path roots are deliberately split
-//! (see [`crate::config`]): core-managed identity/memory files live
-//! under `workspace_dir` (which the agent's write tools cannot reach), while the
-//! agent's writable working dir lives under `action_dir`.
-//!
-//! ```text
-//! <workspace>/personalities/<id>/SOUL.md identity (hot-read each prompt)
-//! <workspace>/personalities/<id>/MEMORY.md curated per-profile memory
-//! <workspace>/personalities/<id>/skills/ private skills (owner-only discovery)
-//! <workspace>/{memory,memory_tree,session_raw}-<id>/ dedicated memory subtree (opt-in)
-//! <action_dir>/profiles/<id>/ agent-writable workspace (opt-in)
-//! ```
-//!
-//! - `SOUL.md` is re-read on every prompt build (see
-//! [`resolve_personality_soul`]) so identity edits take effect live.
-//! - `dedicated_memory` derives a `-<id>` memory suffix (see
-//! [`effective_memory_suffix`]) and, as an explicit user opt-in, wins over the
-//! store's auto-assigned numeric `memory_dir_suffix`; the numeric suffix is
-//! retained only when `dedicated_memory` is off (back-compat).
-//! - `dedicated_workspace` roots a per-profile default cwd for acting tools (see
-//! [`dedicated_workspace_dir`] and the session builder's section-D wiring).
-//! - `skills/` (see [`profile_skills_dir`]) holds SKILL.md/WORKFLOW.md bundles
-//! private to this profile: discovered ONLY for turns running under it,
-//! implicitly allowed for their owner, and winning same-name collisions
-//! against global skills (`skills::discover_workflows_with_profile`). Advertised
-//! read-only as `skillsDir` in the enriched RPC payload when present.
-//! - [`ensure_profile_home`] materializes the home idempotently (never
-//! overwriting a user's edited files) on upsert/select — including the empty
-//! `skills/` dir.
-//!
-//! # Cron attribution
-//!
-//! A cron job may carry a `profile_id` (`cron::CronJob::profile_id`). When it is
-//! set and the profile still exists, the scheduled run is built under that
-//! profile (soul, memory scope, dedicated workspace, allowlists) via the same
-//! profile-aware session path the task dispatcher uses; a deleted profile falls
-//! back to a profile-less run rather than failing the job.
-
-pub mod guard;
-pub mod home;
-pub mod ops;
-pub mod paths;
-pub mod prompt_section;
-mod schemas;
-pub mod store;
-pub mod types;
-
-pub use guard::{
- classify_cross_profile_target, profile_id_from_policy_id, scan_command_for_cross_profile,
- workspace_policy_id, CrossProfileDecision, PROFILES_ROOT_SENTINEL,
-};
-pub use home::{
- dedicated_workspace_dir, ensure_profile_home, profile_action_workspace, profile_home,
- profile_skills_dir, profile_skills_root, validate_profile_id,
-};
-pub use paths::{
- effective_memory_suffix, filter_integrations, memory_subdir_for_suffix,
- memory_tree_subdir_for_suffix, profile_session_signature, resolve_personality_memory_md,
- resolve_personality_soul, session_raw_subdir_for_suffix, HasToolkit, PersonalityContext,
-};
-pub use prompt_section::{cross_profile_workspace_notice, AgentProfilePromptSection};
-pub use store::{built_in_profiles, load_profiles, AgentProfileStore};
-pub use types::{profile_signature, AgentProfile, AgentProfilesState, DEFAULT_PROFILE_ID};
-
-pub use schemas::{
- all_controller_schemas as all_profiles_controller_schemas,
- all_registered_controllers as all_profiles_registered_controllers,
-};
diff --git a/crates/openhuman-core/src/agent/profiles/ops.rs b/crates/openhuman-core/src/agent/profiles/ops.rs
deleted file mode 100644
index 90f52eaee4..0000000000
--- a/crates/openhuman-core/src/agent/profiles/ops.rs
+++ /dev/null
@@ -1,296 +0,0 @@
-//! Business logic for the `profiles` RPC surface.
-//!
-//! Per the OpenHuman domain contract, controller handlers in [`super::schemas`]
-//! stay thin (deserialize + delegate) and the real work — config loading,
-//! `agent_id` validation, and store mutation — lives here, returning the JSON
-//! payload the controller emits. The persistence itself is owned by
-//! [`AgentProfileStore`](super::store::AgentProfileStore).
-
-use std::path::{Path, PathBuf};
-
-use serde_json::{Map, Value};
-
-use super::home::{
- dedicated_workspace_dir, ensure_profile_home, profile_home, validate_profile_id,
-};
-use super::store::AgentProfileStore;
-use super::types::{AgentProfile, AgentProfilesState};
-use crate::config::rpc as config_rpc;
-
-/// Enrich one stored profile with resolved, read-only path info the UI shows but
-/// the [`AgentProfile`] struct never persists (section E):
-/// - `soulMdFile`: absolute path of `personalities/<id>/SOUL.md` when it exists;
-/// - `workspaceDir`: absolute path of the dedicated workspace when opted in.
-///
-/// Derived on read from the two path roots — never round-tripped back into the
-/// store, so the stored payload stays clean.
-fn enrich_profile(workspace_dir: &Path, action_dir: &Path, profile: &AgentProfile) -> Value {
- let mut obj: Map<String, Value> = match serde_json::to_value(profile) {
- Ok(Value::Object(map)) => map,
- _ => {
- // A profile must serialize to a JSON object; anything else drops every
- // field. This should be unreachable for `AgentProfile`, so warn (but
- // keep the empty-map fallback so the RPC still returns a value).
- tracing::warn!(
- profile_id = %profile.id,
- "[profiles][ops] enrich_profile: profile did not serialize to a JSON \
- object; enrichment yields an empty object"
- );
- Map::new()
- }
- };
- // Skip the derived path enrichment for ids the read paths would never load
- // (they fail `validate_profile_id`). `dedicated_workspace_dir` already gates
- // on the same check, so `workspaceDir` was never emitted for them; matching
- // that for `soulMdFile` keeps the advertised paths symmetric with what the
- // core will actually read, and — paired with the `ensure_profile_home` guard
- // — such an id has no SOUL.md on disk to advertise anyway.
- if validate_profile_id(&profile.id).is_err() {
- return Value::Object(obj);
- }
- let soul = profile_home(workspace_dir, &profile.id).join("SOUL.md");
- if soul.exists() {
- obj.insert(
- "soulMdFile".to_string(),
- Value::String(soul.to_string_lossy().into_owned()),
- );
- }
- // 2a — advertise the profile-local skills dir when it exists on disk (seeded
- // by `ensure_profile_home`). Read-only, derived, never persisted. The UI
- // (Phase 3) surfaces it as "skills placed here are private to this profile".
- let skills_dir = super::home::profile_skills_dir(workspace_dir, &profile.id);
- if skills_dir.is_dir() {
- obj.insert(
- "skillsDir".to_string(),
- Value::String(skills_dir.to_string_lossy().into_owned()),
- );
- }
- if let Some(ws) = dedicated_workspace_dir(action_dir, profile) {
- obj.insert(
- "workspaceDir".to_string(),
- Value::String(ws.to_string_lossy().into_owned()),
- );
- }
- Value::Object(obj)
-}
-
-/// Shape the `{ profiles, activeProfileId }` payload every profiles RPC returns,
-/// enriching each profile with its resolved read-only path info.
-fn enriched_state_payload(
- workspace_dir: &Path,
- action_dir: &Path,
- state: &AgentProfilesState,
-) -> Value {
- let profiles: Vec<Value> = state
- .profiles
- .iter()
- .map(|p| enrich_profile(workspace_dir, action_dir, p))
- .collect();
- serde_json::json!({
- "profiles": profiles,
- "activeProfileId": state.active_profile_id,
- })
-}
-
-/// Resolve the workspace-scoped profile store plus the `(workspace, action)`
-/// path roots from a single config load, so the id-scoped store call, the home
-/// materialization, and payload enrichment all share one load.
-async fn store_and_roots() -> Result<(AgentProfileStore, PathBuf, PathBuf), String> {
- let config = config_rpc::load_config_with_timeout().await?;
- let store = AgentProfileStore::new(config.workspace_dir.clone());
- Ok((store, config.workspace_dir, config.action_dir))
-}
-
-/// Best-effort materialization of a profile's home directory. Logs and swallows
-/// filesystem errors — a failed home seed must never fail the RPC (the profile
-/// is already persisted; the identity/memory files are lazily re-created on the
-/// next select/upsert or read).
-fn materialize_home(workspace_dir: &Path, action_dir: &Path, profile: &AgentProfile) {
- if let Err(e) = ensure_profile_home(workspace_dir, action_dir, profile) {
- tracing::warn!(
- profile_id = %profile.id,
- error = %e,
- "[profiles][ops] ensure_profile_home failed (non-fatal)"
- );
- }
-}
-
-/// List all persistent profiles and the active id.
-pub async fn list() -> Result<Value, String> {
- let request_id = format!("profiles-list-{}", uuid::Uuid::new_v4());
- tracing::debug!(request_id = %request_id, "[profiles][ops] list entry");
- let (store, workspace_dir, action_dir) = store_and_roots().await?;
- let state = store.load().map_err(|e| {
- tracing::debug!(request_id = %request_id, error = %e, "[profiles][ops] list error");
- e
- })?;
- tracing::debug!(
- request_id = %request_id,
- active_profile_id = %state.active_profile_id,
- profile_count = state.profiles.len(),
- "[profiles][ops] list ok"
- );
- Ok(enriched_state_payload(&workspace_dir, &action_dir, &state))
-}
-
-/// Select the active profile by id.
-pub async fn select(profile_id: &str) -> Result<Value, String> {
- let request_id = format!("profile-select-{}", uuid::Uuid::new_v4());
- tracing::debug!(request_id = %request_id, profile_id, "[profiles][ops] select entry");
- let (store, workspace_dir, action_dir) = store_and_roots().await?;
- let state = store.select(profile_id).map_err(|e| {
- tracing::debug!(request_id = %request_id, profile_id, error = %e, "[profiles][ops] select error");
- e
- })?;
- // Materialize the selected profile's home (covers built-ins, which are only
- // seeded when a user first activates them).
- if let Some(profile) = state
- .profiles
- .iter()
- .find(|p| p.id == state.active_profile_id)
- {
- materialize_home(&workspace_dir, &action_dir, profile);
- }
- tracing::debug!(
- request_id = %request_id,
- profile_id,
- active_profile_id = %state.active_profile_id,
- "[profiles][ops] select ok"
- );
- Ok(enriched_state_payload(&workspace_dir, &action_dir, &state))
-}
-
-/// Create or update a profile.
-///
-/// The profile's `agent_id` is validated against the global
-/// [`AgentDefinitionRegistry`](crate::agent::harness::AgentDefinitionRegistry)
-/// when it is available. When the registry is *not* initialised we **fail
-/// closed** for any non-default `agent_id` rather than persist a reference we
-/// can't validate — otherwise a startup init-order race would be saved as a
-/// permanently-broken profile. The implicit `orchestrator` default (and an empty
-/// id, normalised to `orchestrator`) are always valid, mirroring the session
-/// builder, so they are admitted without the registry.
-pub async fn upsert(profile: AgentProfile) -> Result<Value, String> {
- let request_id = format!("profile-upsert-{}", uuid::Uuid::new_v4());
- let agent_id = profile.agent_id.trim().to_string();
- tracing::debug!(
- request_id = %request_id,
- profile_id = %profile.id,
- agent_id = %agent_id,
- "[profiles][ops] upsert entry"
- );
- match crate::agent::harness::AgentDefinitionRegistry::global() {
- Some(registry) => {
- if !agent_id.is_empty() && registry.get(&agent_id).is_none() {
- tracing::debug!(
- request_id = %request_id,
- agent_id = %agent_id,
- "[profiles][ops] upsert unknown_agent"
- );
- return Err(format!("agent definition '{agent_id}' not found"));
- }
- }
- None => {
- // No registry → can only admit the always-valid default agent.
- if !agent_id.is_empty() && agent_id != DEFAULT_AGENT_ID {
- tracing::debug!(
- request_id = %request_id,
- agent_id = %agent_id,
- "[profiles][ops] upsert registry_unavailable fail_closed"
- );
- return Err(format!(
- "agent definition registry unavailable — cannot validate agent_id '{agent_id}'"
- ));
- }
- }
- }
- let upserted_id = profile.id.clone();
- let upserted_name = profile.name.clone();
- let (store, workspace_dir, action_dir) = store_and_roots().await?;
- // Keep the previous inline value so SOUL.md is rewritten only when the
- // persona field itself changed. The editor submits the full profile for
- // unrelated settings saves; comparing only against the file would clobber
- // a newer manual edit with the unchanged, stale inline value.
- let normalised_id = super::store::normalise_profile_id(&upserted_id, &upserted_name);
- let previous_soul_md = store
- .load()
- .map_err(|e| {
- tracing::debug!(request_id = %request_id, error = %e, "[profiles][ops] upsert preload error");
- e
- })?
- .profiles
- .into_iter()
- .find(|p| p.id == normalised_id)
- .and_then(|p| p.soul_md);
- let state = store.upsert(profile).map_err(|e| {
- tracing::debug!(request_id = %request_id, error = %e, "[profiles][ops] upsert error");
- e
- })?;
- // Materialize the home for the just-upserted profile. The store normalises
- // the id (slugify), so resolve the persisted profile from the returned state
- // rather than trusting the raw input id. Built-ins are seeded on select, not
- // here, matching the spec.
- if let Some(persisted) = state.profiles.iter().find(|p| p.id == normalised_id) {
- // Full home materialization (SOUL.md seed + MEMORY.md + skills/ +
- // dedicated workspace) is for CUSTOM profiles here; built-ins are seeded
- // on `select` (first activation), matching the spec.
- if !persisted.built_in {
- materialize_home(&workspace_dir, &action_dir, persisted);
- }
- // Reconcile an edited persona into the on-disk SOUL.md for EVERY profile,
- // built-in included. `ensure_profile_home` only seeds SOUL.md when absent,
- // and `select` seeds built-in homes on first activation — so a user who
- // selects Default/Research once and later edits its Soul in Settings would
- // otherwise keep a stale `personalities/<id>/SOUL.md` that
- // `resolve_personality_soul` reads before the inline value. The sync is a
- // no-op when `soul_md` is empty/None or unchanged (manual file edits
- // stay authoritative) and creates the home dir if needed. Non-fatal —
- // the profile is already persisted.
- if let Err(e) = super::home::sync_soul_md_on_upsert(
- &workspace_dir,
- persisted,
- previous_soul_md.as_deref(),
- ) {
- tracing::warn!(
- profile_id = %persisted.id,
- error = %e,
- "[profiles][ops] sync_soul_md_on_upsert failed (non-fatal)"
- );
- }
- }
- tracing::debug!(
- request_id = %request_id,
- active_profile_id = %state.active_profile_id,
- profile_count = state.profiles.len(),
- "[profiles][ops] upsert ok"
- );
- Ok(enriched_state_payload(&workspace_dir, &action_dir, &state))
-}
-
-/// Delete a custom profile by id.
-pub async fn delete(profile_id: &str) -> Result<Value, String> {
- let request_id = format!("profile-delete-{}", uuid::Uuid::new_v4());
- tracing::debug!(request_id = %request_id, profile_id, "[profiles][ops] delete entry");
- let (store, workspace_dir, action_dir) = store_and_roots().await?;
- let state = store.delete(profile_id).map_err(|e| {
- tracing::debug!(request_id = %request_id, profile_id, error = %e, "[profiles][ops] delete error");
- e
- })?;
- tracing::debug!(
- request_id = %request_id,
- profile_id,
- active_profile_id = %state.active_profile_id,
- profile_count = state.profiles.len(),
- "[profiles][ops] delete ok"
- );
- Ok(enriched_state_payload(&workspace_dir, &action_dir, &state))
-}
-
-/// The implicit orchestrator agent that requires no registry entry — the
-/// built-in default profile uses it and the session builder treats it as always
-/// resolvable.
-const DEFAULT_AGENT_ID: &str = "orchestrator";
-
-#[cfg(test)]
-#[path = "ops_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/profiles/ops_tests.rs b/crates/openhuman-core/src/agent/profiles/ops_tests.rs
deleted file mode 100644
index cbfad37349..0000000000
--- a/crates/openhuman-core/src/agent/profiles/ops_tests.rs
+++ /dev/null
@@ -1,224 +0,0 @@
-use super::*;
-use crate::agent::profiles::DEFAULT_PROFILE_ID;
-use crate::config::TEST_ENV_LOCK as ENV_LOCK;
-use serde_json::json;
-
-struct WorkspaceEnvGuard {
- previous: Option<std::ffi::OsString>,
-}
-impl WorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- unsafe {
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- }
- Self { previous }
- }
-}
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- match self.previous.take() {
- Some(value) => unsafe { std::env::set_var("OPENHUMAN_WORKSPACE", value) },
- None => unsafe { std::env::remove_var("OPENHUMAN_WORKSPACE") },
- }
- }
-}
-
-struct ActionDirEnvGuard {
- previous: Option<std::ffi::OsString>,
-}
-impl ActionDirEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- let previous = std::env::var_os("OPENHUMAN_ACTION_DIR");
- unsafe {
- std::env::set_var("OPENHUMAN_ACTION_DIR", path);
- }
- Self { previous }
- }
-}
-impl Drop for ActionDirEnvGuard {
- fn drop(&mut self) {
- match self.previous.take() {
- Some(value) => unsafe { std::env::set_var("OPENHUMAN_ACTION_DIR", value) },
- None => unsafe { std::env::remove_var("OPENHUMAN_ACTION_DIR") },
- }
- }
-}
-
-fn profile(id: &str, agent_id: &str) -> AgentProfile {
- let mut p = super::super::store::built_in_default_profile();
- p.id = id.to_string();
- p.name = id.to_string();
- p.agent_id = agent_id.to_string();
- p.built_in = false;
- p.is_master = false;
- p.memory_dir_suffix = None;
- p
-}
-
-#[tokio::test]
-async fn upsert_materializes_home_and_list_enriches_paths() {
- let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let ws = tempfile::tempdir().expect("ws tempdir");
- let action = tempfile::tempdir().expect("action tempdir");
- let _env_ws = WorkspaceEnvGuard::set(ws.path());
- let _env_action = ActionDirEnvGuard::set(action.path());
-
- let mut p = profile("writer", "orchestrator");
- p.dedicated_workspace = true;
- let out = upsert(p).await.expect("upsert");
-
- // The enriched payload surfaces resolved read-only paths. `soulMdFile` is
- // only inserted when the file exists on disk, so its presence proves the
- // home was materialized (workspace_dir is config-derived, so we assert on
- // the resolved suffix rather than the raw temp root). `workspaceDir` is
- // present only for a `dedicated_workspace` profile, proving the opt-in
- // dir path was resolved and created.
- let writer = out["profiles"]
- .as_array()
- .expect("profiles array")
- .iter()
- .find(|p| p["id"] == "writer")
- .expect("writer profile present");
- let soul_file = writer["soulMdFile"]
- .as_str()
- .expect("soulMdFile present (SOUL.md was seeded on disk)");
- assert!(
- soul_file.ends_with("personalities/writer/SOUL.md"),
- "soulMdFile should end at the profile home, got {soul_file}"
- );
- // The resolved SOUL.md really exists on disk.
- assert!(std::path::Path::new(soul_file).exists());
- let workspace_dir = writer["workspaceDir"]
- .as_str()
- .expect("workspaceDir present for dedicated_workspace profile");
- assert!(
- workspace_dir.ends_with("profiles/writer"),
- "workspaceDir should end at the profile workspace, got {workspace_dir}"
- );
- // The dedicated workspace dir was actually created.
- assert!(std::path::Path::new(workspace_dir).is_dir());
- assert_eq!(writer["dedicatedWorkspace"], json!(true));
- // 2a — the profile-local skills dir is seeded by `ensure_profile_home`
- // and advertised read-only as `skillsDir`.
- let skills_dir = writer["skillsDir"]
- .as_str()
- .expect("skillsDir present (skills dir was seeded on disk)");
- assert!(
- skills_dir.ends_with("personalities/writer/skills"),
- "skillsDir should end at the profile skills dir, got {skills_dir}"
- );
- assert!(std::path::Path::new(skills_dir).is_dir());
-}
-
-#[tokio::test]
-async fn shared_profile_has_no_workspace_dir_in_payload() {
- let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let ws = tempfile::tempdir().expect("ws tempdir");
- let action = tempfile::tempdir().expect("action tempdir");
- let _env_ws = WorkspaceEnvGuard::set(ws.path());
- let _env_action = ActionDirEnvGuard::set(action.path());
-
- // A shared-workspace profile: soulMdFile resolves (home is seeded) but no
- // workspaceDir key is present.
- let out = upsert(profile("shared", "orchestrator"))
- .await
- .expect("upsert");
- let shared = out["profiles"]
- .as_array()
- .unwrap()
- .iter()
- .find(|p| p["id"] == "shared")
- .expect("shared profile present");
- // A shared-workspace profile never surfaces workspaceDir, but its home
- // (SOUL.md) is still seeded, so soulMdFile resolves.
- assert!(shared.get("workspaceDir").is_none());
- assert!(shared["soulMdFile"].as_str().is_some());
-}
-
-#[test]
-fn enrich_profile_skips_paths_for_invalid_id() {
- let ws = tempfile::tempdir().expect("ws tempdir");
- let action = tempfile::tempdir().expect("action tempdir");
- let mut p = profile("placeholder", "orchestrator");
- p.id = "Bad Id".to_string();
- p.dedicated_workspace = true;
-
- // Even if a SOUL.md somehow exists at the would-be home, an invalid id must
- // not advertise soulMdFile/workspaceDir — the read paths would never load
- // it, so the enriched payload must stay symmetric with what core reads.
- let home = super::profile_home(ws.path(), "Bad Id");
- std::fs::create_dir_all(&home).unwrap();
- std::fs::write(home.join("SOUL.md"), "x").unwrap();
-
- let enriched = super::enrich_profile(ws.path(), action.path(), &p);
- assert!(
- enriched.get("soulMdFile").is_none(),
- "invalid id must not advertise soulMdFile even when the file exists"
- );
- assert!(
- enriched.get("workspaceDir").is_none(),
- "invalid id must not advertise workspaceDir"
- );
-
- // Control: a valid id with the same on-disk SOUL.md does advertise it.
- let mut valid = p.clone();
- valid.id = "goodid".to_string();
- let valid_home = super::profile_home(ws.path(), "goodid");
- std::fs::create_dir_all(&valid_home).unwrap();
- std::fs::write(valid_home.join("SOUL.md"), "x").unwrap();
- let enriched_valid = super::enrich_profile(ws.path(), action.path(), &valid);
- assert!(enriched_valid["soulMdFile"].as_str().is_some());
- assert!(enriched_valid["workspaceDir"].as_str().is_some());
-}
-
-#[tokio::test]
-async fn upsert_default_agent_allowed_without_registry() {
- let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let temp = tempfile::tempdir().expect("tempdir");
- let _env = WorkspaceEnvGuard::set(temp.path());
- // orchestrator is always valid even with no registry initialised.
- let out = upsert(profile("writer", "orchestrator"))
- .await
- .expect("upsert");
- assert!(out["profiles"]
- .as_array()
- .unwrap()
- .iter()
- .any(|p| p["id"] == "writer"));
-}
-
-#[tokio::test]
-async fn upsert_unknown_agent_is_rejected() {
- let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let temp = tempfile::tempdir().expect("tempdir");
- let _env = WorkspaceEnvGuard::set(temp.path());
- // A bogus non-default agent_id must never persist. Depending on whether
- // another test already initialised the process-global registry, the
- // rejection comes either from registry validation ("not found") or from
- // the fail-closed no-registry path ("registry unavailable") — both are
- // acceptable; the invariant is that it errors rather than saving.
- let err = upsert(profile("bad", "__missing_agent__"))
- .await
- .expect_err("must reject unknown agent");
- assert!(
- err.contains("registry unavailable") || err.contains("not found"),
- "err: {err}"
- );
-}
-
-#[tokio::test]
-async fn list_select_delete_roundtrip() {
- let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let temp = tempfile::tempdir().expect("tempdir");
- let _env = WorkspaceEnvGuard::set(temp.path());
- upsert(profile("writer", "orchestrator"))
- .await
- .expect("upsert");
- let selected = select("writer").await.expect("select");
- assert_eq!(selected["activeProfileId"], "writer");
- let listed = list().await.expect("list");
- assert_eq!(listed["activeProfileId"], "writer");
- let deleted = delete("writer").await.expect("delete");
- assert_eq!(deleted["activeProfileId"], json!(DEFAULT_PROFILE_ID));
-}
diff --git a/crates/openhuman-core/src/agent/profiles/paths.rs b/crates/openhuman-core/src/agent/profiles/paths.rs
deleted file mode 100644
index 25074a6438..0000000000
--- a/crates/openhuman-core/src/agent/profiles/paths.rs
+++ /dev/null
@@ -1,361 +0,0 @@
-//! Personality-scoped path resolution and context for multi-agent sessions.
-
-use std::hash::{Hash, Hasher};
-use std::path::{Component, Path, PathBuf};
-
-use super::home::validate_profile_id;
-use super::types::AgentProfile;
-
-/// Reject path strings that could escape the workspace: absolute paths,
-/// root/prefix components, or any `..` segment.
-fn is_safe_relative_path(rel: &Path) -> bool {
- !rel.is_absolute()
- && rel.components().all(|c| {
- !matches!(
- c,
- Component::ParentDir | Component::RootDir | Component::Prefix(_)
- )
- })
-}
-
-/// Resolve the memory subdirectory name for a given suffix.
-/// `""` → `"memory"`, `"-1"` → `"memory-1"`, `"-2"` → `"memory-2"`.
-pub fn memory_subdir_for_suffix(suffix: &str) -> String {
- if suffix.is_empty() {
- "memory".to_string()
- } else {
- format!("memory{suffix}")
- }
-}
-
-/// Resolve the memory_tree subdirectory name for a given suffix.
-pub fn memory_tree_subdir_for_suffix(suffix: &str) -> String {
- if suffix.is_empty() {
- "memory_tree".to_string()
- } else {
- format!("memory_tree{suffix}")
- }
-}
-
-/// Resolve the session_raw subdirectory name for a given suffix.
-pub fn session_raw_subdir_for_suffix(suffix: &str) -> String {
- if suffix.is_empty() {
- "session_raw".to_string()
- } else {
- format!("session_raw{suffix}")
- }
-}
-
-/// The workspace file a profile's `soul_md_path` points at, or `None` when
-/// the profile names no file, the relative path is unsafe, or it escapes the
-/// workspace after canonicalization. Shared by [`resolve_personality_soul`]
-/// (which reads it) and the channel runtime's identity fingerprint (which
-/// stats it) so both agree on what "the soul file" is.
-///
-/// Synchronous fs calls are intentional — this runs during prompt construction
-/// on a blocking thread and the workspace is always local disk.
-pub(crate) fn soul_md_file_path(workspace_dir: &Path, profile: &AgentProfile) -> Option<PathBuf> {
- let rel_path = profile.soul_md_path.as_deref()?;
- let rel = Path::new(rel_path);
- if !is_safe_relative_path(rel) {
- tracing::debug!(
- profile_id = %profile.id,
- soul_md_path = %rel_path,
- "[personality] rejected unsafe soul_md_path, trying inline"
- );
- return None;
- }
- let path = workspace_dir.join(rel);
- // Guard against symlink traversal: a symlink inside the workspace can
- // point outside it. Canonicalize both sides and reject if the resolved
- // path escapes the workspace root.
- if let (Ok(canonical_ws), Ok(canonical_p)) = (workspace_dir.canonicalize(), path.canonicalize())
- {
- if !canonical_p.starts_with(&canonical_ws) {
- tracing::warn!(
- path = %path.display(),
- profile_id = %profile.id,
- "[personality] soul_md_path escapes workspace after canonicalization, trying inline"
- );
- return None;
- }
- }
- Some(path)
-}
-
-/// Resolve the SOUL.md content for a personality.
-///
-/// Resolution order (hermes-style — the per-profile identity file wins and is
-/// re-read on every prompt build):
-/// 1. `personalities/<id>/SOUL.md` — the canonical per-profile identity file
-/// (skipped when the profile id fails [`validate_profile_id`], so legacy
-/// profiles with arbitrary ids can't construct an unexpected path).
-/// 2. `soul_md_path` — read the file at that relative path under workspace.
-/// 3. `soul_md` — inline content from the profile.
-/// 4. `None` — caller falls back to the workspace root `SOUL.md`.
-pub fn resolve_personality_soul(workspace_dir: &Path, profile: &AgentProfile) -> Option<String> {
- // Step 1: the per-profile home SOUL.md. Only attempted for ids that pass the
- // hermes name grammar — a legacy/built-in id that fails validation skips
- // straight to the existing (2)/(3)/(4) resolution below, unchanged.
- match validate_profile_id(&profile.id) {
- Ok(()) => {
- let home_soul = super::home::profile_home(workspace_dir, &profile.id).join("SOUL.md");
- match std::fs::read_to_string(&home_soul) {
- Ok(content) if !content.trim().is_empty() => {
- tracing::debug!(
- path = %home_soul.display(),
- profile_id = %profile.id,
- "[personality] soul_md loaded from profile home"
- );
- return Some(content);
- }
- Ok(_) => {
- tracing::debug!(
- profile_id = %profile.id,
- "[personality] profile-home SOUL.md empty, trying soul_md_path/inline"
- );
- }
- Err(e) => {
- tracing::debug!(
- path = %home_soul.display(),
- profile_id = %profile.id,
- error = %e,
- "[personality] profile-home SOUL.md absent, trying soul_md_path/inline"
- );
- }
- }
- }
- Err(e) => {
- tracing::debug!(
- profile_id = %profile.id,
- error = %e,
- "[personality] profile id fails validation, skipping profile-home SOUL.md"
- );
- }
- }
-
- if profile.soul_md_path.is_some() {
- // An unsafe or escaping path is rejected (logged by the resolver) and
- // falls through to the inline soul, as before.
- let Some(path) = soul_md_file_path(workspace_dir, profile) else {
- return profile
- .soul_md
- .as_ref()
- .filter(|s| !s.trim().is_empty())
- .cloned();
- };
- match std::fs::read_to_string(&path) {
- Ok(content) if !content.trim().is_empty() => {
- tracing::debug!(
- path = %path.display(),
- profile_id = %profile.id,
- "[personality] soul_md loaded from file"
- );
- return Some(content);
- }
- Ok(_) => {
- tracing::debug!(
- path = %path.display(),
- profile_id = %profile.id,
- "[personality] soul_md_path file empty, trying inline"
- );
- }
- Err(e) => {
- tracing::debug!(
- path = %path.display(),
- profile_id = %profile.id,
- error = %e,
- "[personality] soul_md_path read failed, trying inline"
- );
- }
- }
- }
-
- if let Some(ref inline) = profile.soul_md {
- if !inline.trim().is_empty() {
- tracing::debug!(
- profile_id = %profile.id,
- len = inline.len(),
- "[personality] soul_md loaded from inline"
- );
- return Some(inline.clone());
- }
- }
-
- tracing::debug!(
- profile_id = %profile.id,
- "[personality] no personality-specific soul_md, falling back to root"
- );
- None
-}
-
-/// Resolve a personality's MEMORY.md content.
-///
-/// Looks for `personalities/{profile_id}/MEMORY.md` under the workspace.
-/// Returns `None` if the file doesn't exist or is empty — caller falls
-/// back to the workspace root `MEMORY.md`.
-pub fn resolve_personality_memory_md(
- workspace_dir: &Path,
- profile: &AgentProfile,
-) -> Option<String> {
- let path = workspace_dir
- .join("personalities")
- .join(&profile.id)
- .join("MEMORY.md");
- match std::fs::read_to_string(&path) {
- Ok(content) if !content.trim().is_empty() => {
- tracing::debug!(
- path = %path.display(),
- profile_id = %profile.id,
- "[personality] memory_md loaded from personality dir"
- );
- Some(content)
- }
- _ => None,
- }
-}
-
-/// Fingerprint every profile input baked into a cached session agent.
-///
-/// The profile record alone is insufficient because users may edit the
-/// canonical SOUL.md or MEMORY.md files directly. Hashing their resolved
-/// contents makes the next web-chat turn rebuild its cached agent without
-/// retaining the files themselves in cache metadata or logs.
-pub fn profile_session_signature(workspace_dir: &Path, profile: &AgentProfile) -> String {
- let mut hasher = std::collections::hash_map::DefaultHasher::new();
- super::types::profile_signature(profile).hash(&mut hasher);
- resolve_personality_soul(workspace_dir, profile).hash(&mut hasher);
- resolve_personality_memory_md(workspace_dir, profile).hash(&mut hasher);
- format!("{:016x}", hasher.finish())
-}
-
-/// Derive the effective memory directory suffix for a profile.
-///
-/// Precedence:
-/// 1. when `dedicated_memory` is set, derive `"-<id>"` from the profile id
-/// (id must pass [`validate_profile_id`], else fall back to the shared `""`
-/// and warn — a legacy id can't mint an unexpected directory name). This is
-/// an explicit user opt-in and **wins over** the auto-assigned numeric
-/// suffix: the store stamps every non-default profile with `Some("-1")`,
-/// `Some("-2")`, … on upsert, so if the numeric suffix took precedence the
-/// isolation toggle could never take effect (it would be dead code). Toggling
-/// `dedicated_memory` on therefore switches the profile to its own
-/// `memory-<id>` subtree — the intended behaviour of the toggle.
-/// 2. else, an explicit `memory_dir_suffix` (the legacy auto-assigned numeric
-/// suffix, e.g. `"-1"`) — pre-existing non-dedicated profiles keep their
-/// directories;
-/// 3. else `""` (the shared/global memory tree).
-///
-/// The returned suffix feeds the existing
-/// [`memory_subdir_for_suffix`] / [`memory_tree_subdir_for_suffix`] /
-/// [`session_raw_subdir_for_suffix`] helpers unchanged.
-pub fn effective_memory_suffix(profile: &AgentProfile) -> String {
- if profile.dedicated_memory {
- match validate_profile_id(&profile.id) {
- Ok(()) => {
- let suffix = format!("-{}", profile.id);
- tracing::debug!(
- profile_id = %profile.id,
- suffix = %suffix,
- "[personality] effective_memory_suffix derived from dedicated_memory"
- );
- return suffix;
- }
- Err(e) => {
- tracing::warn!(
- profile_id = %profile.id,
- error = %e,
- "[personality] dedicated_memory requested but id fails validation, \
- falling back to legacy/shared memory tree"
- );
- }
- }
- }
- if let Some(suffix) = profile
- .memory_dir_suffix
- .as_ref()
- .map(|s| s.trim())
- .filter(|s| !s.is_empty())
- {
- tracing::debug!(
- profile_id = %profile.id,
- suffix = %suffix,
- "[personality] effective_memory_suffix using legacy numeric suffix"
- );
- return suffix.to_string();
- }
- tracing::debug!(
- profile_id = %profile.id,
- "[personality] effective_memory_suffix using shared memory tree"
- );
- String::new()
-}
-
-/// All personality-resolved overrides needed to build a scoped agent session.
-#[derive(Debug, Clone)]
-pub struct PersonalityContext {
- pub profile: AgentProfile,
- pub memory_suffix: String,
- pub soul_md_override: Option<String>,
- pub memory_md_override: Option<String>,
- pub composio_allowlist: Option<Vec<String>>,
- pub voice_id: Option<String>,
-}
-
-impl PersonalityContext {
- /// Build from a resolved `AgentProfile`, reading personality files from the workspace.
- pub fn from_profile(workspace_dir: &Path, profile: AgentProfile) -> Self {
- let memory_suffix = effective_memory_suffix(&profile);
- let soul_md_override = resolve_personality_soul(workspace_dir, &profile);
- let memory_md_override = resolve_personality_memory_md(workspace_dir, &profile);
- let composio_allowlist = profile.composio_integrations.clone();
- let voice_id = profile.voice_id.clone();
-
- Self {
- profile,
- memory_suffix,
- soul_md_override,
- memory_md_override,
- composio_allowlist,
- voice_id,
- }
- }
-}
-
-/// Filter connected integrations by an allowlist of toolkit slugs.
-///
-/// - `None` → passthrough (all integrations).
-/// - `Some([])` → no integrations.
-/// - `Some(["slack", "gmail"])` → only those toolkits.
-pub fn filter_integrations<T: Clone + HasToolkit>(
- all: &[T],
- allowlist: Option<&[String]>,
-) -> Vec<T> {
- match allowlist {
- None => all.to_vec(),
- Some(allowed) => all
- .iter()
- .filter(|ci| {
- allowed
- .iter()
- .any(|a| a.eq_ignore_ascii_case(ci.toolkit_name()))
- })
- .cloned()
- .collect(),
- }
-}
-
-/// Trait to abstract over integration types that have a toolkit name.
-pub trait HasToolkit {
- fn toolkit_name(&self) -> &str;
-}
-
-impl HasToolkit for crate::agent::prompts::ConnectedIntegration {
- fn toolkit_name(&self) -> &str {
- &self.toolkit
- }
-}
-
-#[cfg(test)]
-#[path = "paths_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/profiles/paths_tests.rs b/crates/openhuman-core/src/agent/profiles/paths_tests.rs
deleted file mode 100644
index 5443149325..0000000000
--- a/crates/openhuman-core/src/agent/profiles/paths_tests.rs
+++ /dev/null
@@ -1,336 +0,0 @@
-use super::*;
-use tempfile::TempDir;
-
-fn test_profile(id: &str) -> AgentProfile {
- AgentProfile {
- id: id.to_string(),
- name: id.to_string(),
- description: String::new(),
- agent_id: "orchestrator".to_string(),
- model_override: None,
- temperature: None,
- system_prompt_suffix: None,
- allowed_tools: None,
- built_in: false,
- avatar_url: None,
- voice_id: None,
- soul_md: None,
- soul_md_path: None,
- composio_integrations: None,
- memory_sources: None,
- include_agent_conversations: true,
- allowed_skills: None,
- allowed_mcp_servers: None,
- memory_dir_suffix: None,
- is_master: false,
- sort_order: None,
- dedicated_memory: false,
- dedicated_workspace: false,
- }
-}
-
-#[test]
-fn memory_subdir_for_suffix_patterns() {
- assert_eq!(memory_subdir_for_suffix(""), "memory");
- assert_eq!(memory_subdir_for_suffix("-1"), "memory-1");
- assert_eq!(memory_subdir_for_suffix("-2"), "memory-2");
- assert_eq!(memory_subdir_for_suffix("-10"), "memory-10");
-}
-
-#[test]
-fn memory_tree_subdir_for_suffix_patterns() {
- assert_eq!(memory_tree_subdir_for_suffix(""), "memory_tree");
- assert_eq!(memory_tree_subdir_for_suffix("-1"), "memory_tree-1");
-}
-
-#[test]
-fn session_raw_subdir_for_suffix_patterns() {
- assert_eq!(session_raw_subdir_for_suffix(""), "session_raw");
- assert_eq!(session_raw_subdir_for_suffix("-1"), "session_raw-1");
-}
-
-#[test]
-fn resolve_soul_prefers_profile_home_file() {
- let tmp = TempDir::new().unwrap();
- let home = tmp.path().join("personalities").join("alice");
- std::fs::create_dir_all(&home).unwrap();
- std::fs::write(home.join("SOUL.md"), "Home identity for Alice").unwrap();
-
- let mut profile = test_profile("alice");
- // Both inline and soul_md_path present — the profile-home file still wins.
- profile.soul_md = Some("Inline soul".to_string());
- let result = resolve_personality_soul(tmp.path(), &profile);
- assert_eq!(result.as_deref(), Some("Home identity for Alice"));
-}
-
-#[test]
-fn resolve_soul_skips_home_file_for_invalid_legacy_id() {
- let tmp = TempDir::new().unwrap();
- // A legacy id that fails validate_profile_id (space + uppercase).
- let legacy_id = "Legacy Id";
- let home = tmp.path().join("personalities").join(legacy_id);
- std::fs::create_dir_all(&home).unwrap();
- std::fs::write(home.join("SOUL.md"), "SHOULD BE SKIPPED").unwrap();
-
- let mut profile = test_profile("placeholder");
- profile.id = legacy_id.to_string();
- profile.soul_md = Some("Legacy inline soul".to_string());
- // Step 1 (profile-home SOUL.md) is skipped for the invalid id; resolution
- // falls through to the inline value.
- let result = resolve_personality_soul(tmp.path(), &profile);
- assert_eq!(result.as_deref(), Some("Legacy inline soul"));
-}
-
-#[test]
-fn resolve_soul_empty_home_file_falls_through_to_inline() {
- let tmp = TempDir::new().unwrap();
- let home = tmp.path().join("personalities").join("alice");
- std::fs::create_dir_all(&home).unwrap();
- std::fs::write(home.join("SOUL.md"), " \n").unwrap(); // whitespace only
-
- let mut profile = test_profile("alice");
- profile.soul_md = Some("Inline wins over empty home file".to_string());
- let result = resolve_personality_soul(tmp.path(), &profile);
- assert_eq!(result.as_deref(), Some("Inline wins over empty home file"));
-}
-
-#[test]
-fn effective_memory_suffix_dedicated_wins_over_numeric() {
- let mut profile = test_profile("alice");
- // The store auto-assigns a numeric suffix to every non-default profile,
- // so `dedicated_memory` must win over it — otherwise the toggle would be
- // dead code and could never route to the `memory-<id>` subtree.
- profile.memory_dir_suffix = Some("-3".to_string());
- profile.dedicated_memory = true;
- assert_eq!(effective_memory_suffix(&profile), "-alice");
-}
-
-#[test]
-fn effective_memory_suffix_numeric_retained_when_not_dedicated() {
- let mut profile = test_profile("alice");
- // With dedicated_memory off, the persisted legacy numeric suffix is
- // retained so an existing memory directory is never orphaned.
- profile.memory_dir_suffix = Some("-3".to_string());
- profile.dedicated_memory = false;
- assert_eq!(effective_memory_suffix(&profile), "-3");
-}
-
-#[test]
-fn effective_memory_suffix_invalid_id_dedicated_falls_back_to_numeric() {
- let mut profile = test_profile("placeholder");
- profile.id = "Bad Id".to_string();
- // An invalid id can't mint a `-<id>` directory even with dedicated on, so
- // it falls back to the persisted numeric suffix rather than the shared
- // tree.
- profile.memory_dir_suffix = Some("-2".to_string());
- profile.dedicated_memory = true;
- assert_eq!(effective_memory_suffix(&profile), "-2");
-}
-
-#[test]
-fn effective_memory_suffix_dedicated_derives_from_id() {
- let mut profile = test_profile("alice");
- profile.memory_dir_suffix = None;
- profile.dedicated_memory = true;
- assert_eq!(effective_memory_suffix(&profile), "-alice");
-}
-
-#[test]
-fn effective_memory_suffix_shared_default() {
- let mut profile = test_profile("alice");
- profile.memory_dir_suffix = None;
- profile.dedicated_memory = false;
- assert_eq!(effective_memory_suffix(&profile), "");
-}
-
-#[test]
-fn effective_memory_suffix_invalid_id_falls_back_to_shared() {
- let mut profile = test_profile("placeholder");
- profile.id = "Bad Id".to_string();
- profile.memory_dir_suffix = None;
- profile.dedicated_memory = true;
- // Invalid id cannot mint a directory name — fall back to shared "".
- assert_eq!(effective_memory_suffix(&profile), "");
-}
-
-#[test]
-fn effective_memory_suffix_empty_string_suffix_is_not_legacy() {
- let mut profile = test_profile("alice");
- // The default profile stores Some("") — treated as "no legacy suffix", so
- // dedicated_memory (if set) still derives, else shared.
- profile.memory_dir_suffix = Some(String::new());
- profile.dedicated_memory = false;
- assert_eq!(effective_memory_suffix(&profile), "");
-}
-
-#[test]
-fn resolve_soul_inline_fallback() {
- let tmp = TempDir::new().unwrap();
- let mut profile = test_profile("alice");
- profile.soul_md = Some("I am Alice, a friendly assistant.".to_string());
- let result = resolve_personality_soul(tmp.path(), &profile);
- assert_eq!(result.as_deref(), Some("I am Alice, a friendly assistant."));
-}
-
-#[test]
-fn resolve_soul_file_takes_precedence() {
- let tmp = TempDir::new().unwrap();
- let soul_path = tmp.path().join("souls").join("alice.md");
- std::fs::create_dir_all(soul_path.parent().unwrap()).unwrap();
- std::fs::write(&soul_path, "File-based soul").unwrap();
-
- let mut profile = test_profile("alice");
- profile.soul_md_path = Some("souls/alice.md".to_string());
- profile.soul_md = Some("Inline soul".to_string());
- let result = resolve_personality_soul(tmp.path(), &profile);
- assert_eq!(result.as_deref(), Some("File-based soul"));
-}
-
-#[test]
-fn resolve_soul_returns_none_when_empty() {
- let tmp = TempDir::new().unwrap();
- let profile = test_profile("alice");
- let result = resolve_personality_soul(tmp.path(), &profile);
- assert!(result.is_none());
-}
-
-#[test]
-fn resolve_memory_md_from_personality_dir() {
- let tmp = TempDir::new().unwrap();
- let mem_path = tmp
- .path()
- .join("personalities")
- .join("alice")
- .join("MEMORY.md");
- std::fs::create_dir_all(mem_path.parent().unwrap()).unwrap();
- std::fs::write(&mem_path, "Alice remembers things.").unwrap();
-
- let profile = test_profile("alice");
- let result = resolve_personality_memory_md(tmp.path(), &profile);
- assert_eq!(result.as_deref(), Some("Alice remembers things."));
-}
-
-#[test]
-fn resolve_memory_md_returns_none_when_missing() {
- let tmp = TempDir::new().unwrap();
- let profile = test_profile("alice");
- let result = resolve_personality_memory_md(tmp.path(), &profile);
- assert!(result.is_none());
-}
-
-#[test]
-fn profile_session_signature_tracks_profile_file_edits() {
- let tmp = TempDir::new().unwrap();
- let home = tmp.path().join("personalities/alice");
- std::fs::create_dir_all(&home).unwrap();
- std::fs::write(home.join("SOUL.md"), "first soul").unwrap();
- std::fs::write(home.join("MEMORY.md"), "first memory").unwrap();
- let profile = test_profile("alice");
-
- let original = profile_session_signature(tmp.path(), &profile);
- std::fs::write(home.join("SOUL.md"), "second soul").unwrap();
- let after_soul_edit = profile_session_signature(tmp.path(), &profile);
- assert_ne!(original, after_soul_edit);
-
- std::fs::write(home.join("MEMORY.md"), "second memory").unwrap();
- let after_memory_edit = profile_session_signature(tmp.path(), &profile);
- assert_ne!(after_soul_edit, after_memory_edit);
-}
-
-#[test]
-fn personality_context_from_profile() {
- let tmp = TempDir::new().unwrap();
- let mut profile = test_profile("bob");
- profile.memory_dir_suffix = Some("-1".to_string());
- profile.voice_id = Some("voice-xyz".to_string());
- profile.composio_integrations = Some(vec!["slack".to_string()]);
- profile.soul_md = Some("I am Bob.".to_string());
-
- let ctx = PersonalityContext::from_profile(tmp.path(), profile);
- assert_eq!(ctx.memory_suffix, "-1");
- assert_eq!(ctx.voice_id.as_deref(), Some("voice-xyz"));
- assert_eq!(ctx.soul_md_override.as_deref(), Some("I am Bob."));
- assert_eq!(ctx.composio_allowlist.as_ref().unwrap(), &["slack"]);
-}
-
-#[derive(Clone)]
-struct FakeIntegration {
- toolkit: String,
-}
-impl HasToolkit for FakeIntegration {
- fn toolkit_name(&self) -> &str {
- &self.toolkit
- }
-}
-
-#[test]
-fn filter_integrations_none_passthrough() {
- let all = vec![
- FakeIntegration {
- toolkit: "slack".into(),
- },
- FakeIntegration {
- toolkit: "gmail".into(),
- },
- ];
- let filtered = filter_integrations(&all, None);
- assert_eq!(filtered.len(), 2);
-}
-
-#[test]
-fn filter_integrations_allowlist() {
- let all = vec![
- FakeIntegration {
- toolkit: "slack".into(),
- },
- FakeIntegration {
- toolkit: "gmail".into(),
- },
- FakeIntegration {
- toolkit: "notion".into(),
- },
- ];
- let allowed = vec!["slack".to_string(), "notion".to_string()];
- let filtered = filter_integrations(&all, Some(&allowed));
- assert_eq!(filtered.len(), 2);
- assert_eq!(filtered[0].toolkit, "slack");
- assert_eq!(filtered[1].toolkit, "notion");
-}
-
-#[test]
-fn filter_integrations_empty_allowlist() {
- let all = vec![FakeIntegration {
- toolkit: "slack".into(),
- }];
- let allowed: Vec<String> = vec![];
- let filtered = filter_integrations(&all, Some(&allowed));
- assert!(filtered.is_empty());
-}
-
-fn connected_integration(toolkit: &str) -> crate::agent::prompts::ConnectedIntegration {
- crate::agent::prompts::ConnectedIntegration {
- toolkit: toolkit.to_string(),
- description: String::new(),
- tools: Vec::new(),
- gated_tools: Vec::new(),
- connected: true,
- connections: Vec::new(),
- non_active_status: None,
- }
-}
-
-#[test]
-fn filter_connected_integrations_by_profile_allowlist() {
- // The HasToolkit impl lets the per-profile connector gate reuse
- // filter_integrations on the real ConnectedIntegration type.
- let all = vec![
- connected_integration("gmail"),
- connected_integration("slack"),
- connected_integration("notion"),
- ];
- assert_eq!(filter_integrations(&all, None).len(), 3);
- let allow = vec!["gmail".to_string(), "notion".to_string()];
- let filtered = filter_integrations(&all, Some(&allow));
- let kept: Vec<&str> = filtered.iter().map(|c| c.toolkit_name()).collect();
- assert_eq!(kept, vec!["gmail", "notion"]);
-}
diff --git a/crates/openhuman-core/src/agent/profiles/prompt_section.rs b/crates/openhuman-core/src/agent/profiles/prompt_section.rs
deleted file mode 100644
index 52542ada64..0000000000
--- a/crates/openhuman-core/src/agent/profiles/prompt_section.rs
+++ /dev/null
@@ -1,86 +0,0 @@
-//! Prompt section that injects a profile's free-form persona blurb, plus the
-//! optional cross-profile workspace notice (1b) that tells the model where its
-//! dedicated workspace is and that other profiles' directories are off-limits.
-
-use std::path::Path;
-
-use crate::agent::prompts::{PromptContext, PromptSection};
-use anyhow::Result;
-
-/// One-sentence system-prompt notice, mirroring hermes's cross-profile
-/// disclosure: names the profile's dedicated workspace and states that other
-/// profiles' directories are off-limits. Rendered only when a dedicated
-/// workspace is active (the enforcement backstop is the guard in
-/// [`crate::agent::profiles::guard`]).
-pub fn cross_profile_workspace_notice(profile_id: &str, workspace_path: &Path) -> String {
- format!(
- "Your dedicated workspace for profile `{profile_id}` is `{}`. Work only there; the \
- directories of other profiles are off-limits.",
- workspace_path.display()
- )
-}
-
-/// Renders a profile's `system_prompt_suffix` (or any free-form persona body)
-/// as a `## Agent profile` block in the system prompt, optionally followed by
-/// the cross-profile workspace notice.
-pub struct AgentProfilePromptSection {
- body: String,
- workspace_notice: Option<String>,
-}
-
-impl AgentProfilePromptSection {
- pub fn new(body: String) -> Self {
- Self {
- body,
- workspace_notice: None,
- }
- }
-
- /// Attach the cross-profile workspace notice (1b). Rendered under the
- /// persona body — or on its own when the body is empty — so a
- /// dedicated-workspace profile always discloses its boundary even without a
- /// custom persona suffix.
- #[must_use]
- pub fn with_workspace_notice(mut self, notice: String) -> Self {
- let notice = notice.trim().to_string();
- self.workspace_notice = (!notice.is_empty()).then_some(notice);
- self
- }
-}
-
-impl PromptSection for AgentProfilePromptSection {
- fn name(&self) -> &str {
- "agent_profile"
- }
-
- fn build(&self, _ctx: &PromptContext<'_>) -> Result<String> {
- Ok(render_agent_profile_block(
- &self.body,
- self.workspace_notice.as_deref(),
- ))
- }
-}
-
-/// The `## Agent profile` block as text — what [`AgentProfilePromptSection`]
-/// renders, exposed so a prompt path without a [`PromptContext`] (the native
-/// channel runtime) emits byte-identical output. Empty when both inputs are
-/// blank.
-pub fn render_agent_profile_block(body: &str, workspace_notice: Option<&str>) -> String {
- let body = body.trim();
- let notice = workspace_notice.map(str::trim).unwrap_or_default();
- let mut parts: Vec<&str> = Vec::new();
- if !body.is_empty() {
- parts.push(body);
- }
- if !notice.is_empty() {
- parts.push(notice);
- }
- if parts.is_empty() {
- return String::new();
- }
- format!("## Agent profile\n\n{}", parts.join("\n\n"))
-}
-
-#[cfg(test)]
-#[path = "prompt_section_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/profiles/prompt_section_tests.rs b/crates/openhuman-core/src/agent/profiles/prompt_section_tests.rs
deleted file mode 100644
index 5fe66a489f..0000000000
--- a/crates/openhuman-core/src/agent/profiles/prompt_section_tests.rs
+++ /dev/null
@@ -1,100 +0,0 @@
-use super::*;
-use crate::agent::prompts::{LearnedContextData, PromptContext, ToolCallFormat};
-use std::collections::HashSet;
-
-#[test]
-fn prompt_section_renders_expected_text() {
- let section = AgentProfilePromptSection::new(" Be concise. ".into());
- assert_eq!(section.name(), "agent_profile");
- let visible_tool_names = HashSet::new();
- let ctx = PromptContext {
- workspace_dir: std::path::Path::new("/tmp"),
- model_name: "test-model",
- agent_id: "orchestrator",
- tools: &[],
- workflows: &[],
- dispatcher_instructions: "",
- learned: LearnedContextData::default(),
- visible_tool_names: &visible_tool_names,
- tool_call_format: ToolCallFormat::PFormat,
- connected_integrations: &[],
- connected_identities_md: String::new(),
- include_profile: false,
- include_memory_md: false,
- curated_snapshot: None,
- user_identity: None,
- personality_soul_md: None,
- personality_memory_md: None,
- personality_roster: vec![],
- agents_md_global: None,
- agents_md_local: None,
- };
- let rendered = section.build(&ctx).expect("render profile section");
- assert!(rendered.starts_with("## Agent profile"));
- assert!(rendered.contains("Be concise."));
-
- let empty = AgentProfilePromptSection::new(" ".into());
- assert_eq!(empty.build(&ctx).expect("empty profile section"), "");
-}
-
-fn empty_ctx<'a>(visible: &'a HashSet<String>) -> PromptContext<'a> {
- PromptContext {
- workspace_dir: std::path::Path::new("/tmp"),
- model_name: "test-model",
- agent_id: "orchestrator",
- tools: &[],
- workflows: &[],
- dispatcher_instructions: "",
- learned: LearnedContextData::default(),
- visible_tool_names: visible,
- tool_call_format: ToolCallFormat::PFormat,
- connected_integrations: &[],
- connected_identities_md: String::new(),
- include_profile: false,
- include_memory_md: false,
- curated_snapshot: None,
- user_identity: None,
- personality_soul_md: None,
- personality_memory_md: None,
- personality_roster: vec![],
- agents_md_global: None,
- agents_md_local: None,
- }
-}
-
-#[test]
-fn cross_profile_workspace_notice_names_path_and_boundary() {
- let notice =
- cross_profile_workspace_notice("alice", std::path::Path::new("/act/profiles/alice"));
- assert!(notice.contains("alice"));
- assert!(notice.contains("/act/profiles/alice"));
- assert!(notice.contains("off-limits"));
-}
-
-#[test]
-fn workspace_notice_renders_with_and_without_body() {
- let visible = HashSet::new();
- let ctx = empty_ctx(&visible);
-
- // Notice-only (no persona body) still emits the block + the notice.
- let notice_only = AgentProfilePromptSection::new(String::new())
- .with_workspace_notice("boundary sentence.".into());
- let rendered = notice_only.build(&ctx).expect("render notice-only");
- assert!(rendered.starts_with("## Agent profile"));
- assert!(rendered.contains("boundary sentence."));
-
- // Body + notice: both present, body first.
- let both = AgentProfilePromptSection::new("Be terse.".into())
- .with_workspace_notice("boundary sentence.".into());
- let rendered = both.build(&ctx).expect("render both");
- let body_at = rendered.find("Be terse.").expect("body present");
- let notice_at = rendered.find("boundary sentence.").expect("notice present");
- assert!(body_at < notice_at, "persona body must precede the notice");
-
- // A blank notice is dropped, leaving only the body.
- let blank_notice =
- AgentProfilePromptSection::new("Be terse.".into()).with_workspace_notice(" ".into());
- let rendered = blank_notice.build(&ctx).expect("render blank notice");
- assert!(rendered.contains("Be terse."));
- assert!(!rendered.contains("off-limits"));
-}
diff --git a/crates/openhuman-core/src/agent/profiles/schemas.rs b/crates/openhuman-core/src/agent/profiles/schemas.rs
deleted file mode 100644
index ed764cb38c..0000000000
--- a/crates/openhuman-core/src/agent/profiles/schemas.rs
+++ /dev/null
@@ -1,175 +0,0 @@
-//! Controller schemas + handlers for the `profiles` RPC namespace.
-//!
-//! JSON-RPC methods: `openhuman.profiles_list`, `openhuman.profiles_select`,
-//! `openhuman.profiles_upsert`, `openhuman.profiles_delete` (see
-//! `core::all::rpc_method_name`).
-
-use serde::de::DeserializeOwned;
-use serde::Deserialize;
-use serde_json::{Map, Value};
-
-use super::types::AgentProfile;
-use crate::core::all::{ControllerFuture, RegisteredController};
-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
-
-pub fn all_controller_schemas() -> Vec<ControllerSchema> {
- vec![
- schemas("list"),
- schemas("select"),
- schemas("upsert"),
- schemas("delete"),
- ]
-}
-
-pub fn all_registered_controllers() -> Vec<RegisteredController> {
- vec![
- RegisteredController {
- schema: schemas("list"),
- handler: handle_profiles_list,
- },
- RegisteredController {
- schema: schemas("select"),
- handler: handle_profile_select,
- },
- RegisteredController {
- schema: schemas("upsert"),
- handler: handle_profile_upsert,
- },
- RegisteredController {
- schema: schemas("delete"),
- handler: handle_profile_delete,
- },
- ]
-}
-
-pub fn schemas(function: &str) -> ControllerSchema {
- match function {
- "list" => ControllerSchema {
- namespace: "profiles",
- function: "list",
- description: "List persistent agent profiles and the active profile id. Each \
- profile is enriched with resolved read-only path info: soulMdFile \
- (personalities/<id>/SOUL.md if present) and workspaceDir (the \
- dedicated workspace when opted in).",
- inputs: vec![],
- outputs: vec![json_output("profiles", "Agent profile state payload.")],
- },
- "select" => ControllerSchema {
- namespace: "profiles",
- function: "select",
- description: "Select the active persistent agent profile.",
- inputs: vec![required_string("profile_id", "Agent profile id.")],
- outputs: vec![json_output(
- "profiles",
- "Updated agent profile state payload.",
- )],
- },
- "upsert" => ControllerSchema {
- namespace: "profiles",
- function: "upsert",
- description: "Create or update an agent profile. The `profile` payload may include \
- memory_sources, includeAgentConversations, allowedSkills, \
- allowedMcpServers, composioIntegrations, allowedTools, soulMd, \
- dedicatedMemory (own memory subtree), and dedicatedWorkspace (own \
- working dir under action_dir); an omitted/empty allowlist means \"all\".",
- inputs: vec![FieldSchema {
- name: "profile",
- ty: TypeSchema::Json,
- comment: "Agent profile payload.",
- required: true,
- }],
- outputs: vec![json_output(
- "profiles",
- "Updated agent profile state payload.",
- )],
- },
- "delete" => ControllerSchema {
- namespace: "profiles",
- function: "delete",
- description: "Delete a custom agent profile.",
- inputs: vec![required_string("profile_id", "Agent profile id.")],
- outputs: vec![json_output(
- "profiles",
- "Updated agent profile state payload.",
- )],
- },
- _ => ControllerSchema {
- namespace: "profiles",
- function: "unknown",
- description: "Unknown profiles controller function.",
- inputs: vec![],
- outputs: vec![FieldSchema {
- name: "error",
- ty: TypeSchema::String,
- comment: "Lookup error details.",
- required: true,
- }],
- },
- }
-}
-
-#[derive(Debug, Deserialize)]
-struct ProfileSelectParams {
- profile_id: String,
-}
-
-#[derive(Debug, Deserialize)]
-struct ProfileUpsertParams {
- profile: AgentProfile,
-}
-
-#[derive(Debug, Deserialize)]
-struct ProfileDeleteParams {
- profile_id: String,
-}
-
-fn handle_profiles_list(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(super::ops::list())
-}
-
-fn handle_profile_select(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let p = deserialize_params::<ProfileSelectParams>(params)?;
- super::ops::select(&p.profile_id).await
- })
-}
-
-fn handle_profile_upsert(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let p = deserialize_params::<ProfileUpsertParams>(params)?;
- super::ops::upsert(p.profile).await
- })
-}
-
-fn handle_profile_delete(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let p = deserialize_params::<ProfileDeleteParams>(params)?;
- super::ops::delete(&p.profile_id).await
- })
-}
-
-fn deserialize_params<T: DeserializeOwned>(params: Map<String, Value>) -> Result<T, String> {
- serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))
-}
-
-fn required_string(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::String,
- comment,
- required: true,
- }
-}
-
-fn json_output(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Json,
- comment,
- required: true,
- }
-}
-
-#[cfg(test)]
-#[path = "schemas_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/profiles/schemas_tests.rs b/crates/openhuman-core/src/agent/profiles/schemas_tests.rs
deleted file mode 100644
index 13070dd3e3..0000000000
--- a/crates/openhuman-core/src/agent/profiles/schemas_tests.rs
+++ /dev/null
@@ -1,219 +0,0 @@
-use super::*;
-use crate::agent::profiles::DEFAULT_PROFILE_ID;
-use crate::config::TEST_ENV_LOCK as ENV_LOCK;
-use serde_json::json;
-
-#[test]
-fn controller_schema_inventory_is_stable() {
- let schemas = all_controller_schemas();
- let functions: Vec<_> = schemas.iter().map(|schema| schema.function).collect();
- assert_eq!(functions, vec!["list", "select", "upsert", "delete"]);
- assert_eq!(schemas.len(), all_registered_controllers().len());
- assert!(schemas.iter().all(|s| s.namespace == "profiles"));
-}
-
-#[test]
-fn unknown_function_falls_back() {
- let unknown = schemas("nope");
- assert_eq!(unknown.function, "unknown");
- assert_eq!(unknown.outputs[0].name, "error");
-}
-
-struct WorkspaceEnvGuard {
- previous: Option<std::ffi::OsString>,
-}
-
-impl WorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- unsafe {
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- }
- Self { previous }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- match self.previous.take() {
- Some(value) => unsafe {
- std::env::set_var("OPENHUMAN_WORKSPACE", value);
- },
- None => unsafe {
- std::env::remove_var("OPENHUMAN_WORKSPACE");
- },
- }
- }
-}
-
-#[tokio::test]
-async fn profile_handlers_persist_and_return_profile_state() {
- let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let temp = tempfile::tempdir().expect("tempdir");
- let _env = WorkspaceEnvGuard::set(temp.path());
-
- let upserted = handle_profile_upsert(Map::from_iter([(
- "profile".into(),
- json!({
- "id": "writer",
- "name": "Writer",
- "description": "Draft concise copy",
- "agentId": "orchestrator",
- "modelOverride": "agentic-v1",
- "temperature": 0.2,
- "systemPromptSuffix": "Use a crisp tone.",
- "allowedTools": ["todo"],
- "memorySources": ["slack-eng"],
- "allowedSkills": ["deep-research"],
- "includeAgentConversations": false,
- "builtIn": false,
- }),
- )]))
- .await
- .expect("profile upsert");
- assert_eq!(upserted["activeProfileId"], DEFAULT_PROFILE_ID);
- let writer = upserted["profiles"]
- .as_array()
- .expect("profiles array")
- .iter()
- .find(|profile| profile["id"] == "writer")
- .expect("writer profile present");
- assert_eq!(writer["memorySources"], json!(["slack-eng"]));
- assert_eq!(writer["allowedSkills"], json!(["deep-research"]));
- assert_eq!(writer["includeAgentConversations"], json!(false));
-
- let selected = handle_profile_select(Map::from_iter([(
- "profile_id".into(),
- Value::String("writer".into()),
- )]))
- .await
- .expect("profile select");
- assert_eq!(selected["activeProfileId"], "writer");
-
- let listed = handle_profiles_list(Map::new())
- .await
- .expect("profiles list");
- assert_eq!(listed["activeProfileId"], "writer");
-
- let deleted = handle_profile_delete(Map::from_iter([(
- "profile_id".into(),
- Value::String("writer".into()),
- )]))
- .await
- .expect("profile delete");
- assert_eq!(deleted["activeProfileId"], DEFAULT_PROFILE_ID);
-}
-
-/// Resolve the enriched `soulMdFile` absolute path for `profile_id` from a
-/// profiles-state payload (present once the home's SOUL.md exists on disk).
-fn soul_md_file(payload: &Value, profile_id: &str) -> Option<String> {
- payload["profiles"]
- .as_array()?
- .iter()
- .find(|p| p["id"] == profile_id)?
- .get("soulMdFile")?
- .as_str()
- .map(str::to_string)
-}
-
-#[tokio::test]
-async fn built_in_profile_soul_edit_syncs_to_disk() {
- // Regression (PR #5118 review, Codex): select() seeds a built-in's home on
- // first activation, so a later Soul edit through the editor must reconcile
- // the on-disk SOUL.md — the sync path must NOT be gated on `!built_in`.
- let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let temp = tempfile::tempdir().expect("tempdir");
- let _env = WorkspaceEnvGuard::set(temp.path());
-
- const PROFILE_ID: &str = "reasoning";
- // Seed a non-default built-in home the way first activation does; the
- // unedited Default intentionally keeps using the legacy root SOUL.md.
- // enriched payload advertises the resolved SOUL.md path once it exists.
- let selected = handle_profile_select(Map::from_iter([(
- "profile_id".into(),
- Value::String(PROFILE_ID.into()),
- )]))
- .await
- .expect("select built-in");
- let soul_path = soul_md_file(&selected, PROFILE_ID).expect("select seeds built-in SOUL.md");
-
- // User later edits the built-in's Soul in Settings.
- handle_profile_upsert(Map::from_iter([(
- "profile".into(),
- json!({
- "id": PROFILE_ID,
- "name": "Reasoning",
- "description": "",
- "agentId": "orchestrator",
- "soulMd": "Edited built-in persona.",
- "builtIn": true,
- }),
- )]))
- .await
- .expect("upsert default with edited soul");
-
- assert_eq!(
- std::fs::read_to_string(&soul_path).unwrap(),
- "Edited built-in persona.\n",
- "editing a built-in's soul must overwrite its seeded SOUL.md"
- );
-}
-
-#[tokio::test]
-async fn built_in_profile_empty_soul_leaves_file_untouched() {
- // The sync is a no-op when soulMd is empty/None, so a user's manual edit
- // to a built-in's SOUL.md stays authoritative.
- let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let temp = tempfile::tempdir().expect("tempdir");
- let _env = WorkspaceEnvGuard::set(temp.path());
-
- const PROFILE_ID: &str = "reasoning";
- let selected = handle_profile_select(Map::from_iter([(
- "profile_id".into(),
- Value::String(PROFILE_ID.into()),
- )]))
- .await
- .expect("select built-in");
- let soul_path = soul_md_file(&selected, PROFILE_ID).expect("select seeds built-in SOUL.md");
- std::fs::write(&soul_path, "MANUAL EDIT").unwrap();
-
- // Upsert with no soulMd — must not touch the manually edited file.
- handle_profile_upsert(Map::from_iter([(
- "profile".into(),
- json!({
- "id": PROFILE_ID,
- "name": "Reasoning",
- "description": "",
- "agentId": "orchestrator",
- "builtIn": true,
- }),
- )]))
- .await
- .expect("upsert default without soul");
-
- assert_eq!(
- std::fs::read_to_string(&soul_path).unwrap(),
- "MANUAL EDIT",
- "empty soulMd must leave a manually edited built-in SOUL.md untouched"
- );
-}
-
-#[tokio::test]
-async fn profile_upsert_rejects_unknown_registered_agent_id() {
- let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let _ = crate::agent::harness::AgentDefinitionRegistry::init_global_builtins();
-
- let err = handle_profile_upsert(Map::from_iter([(
- "profile".into(),
- json!({
- "id": "bad",
- "name": "Bad",
- "description": "",
- "agentId": "__missing_agent__",
- "builtIn": false,
- }),
- )]))
- .await
- .expect_err("unknown agent should fail before store write");
- assert!(err.contains("agent definition"), "err: {err}");
-}
diff --git a/crates/openhuman-core/src/agent/profiles/store.rs b/crates/openhuman-core/src/agent/profiles/store.rs
deleted file mode 100644
index 285bd761ae..0000000000
--- a/crates/openhuman-core/src/agent/profiles/store.rs
+++ /dev/null
@@ -1,691 +0,0 @@
-//! Persistence layer for agent profiles.
-//!
-//! State is stored under `<workspace>/agent_profiles.json` and merged with
-//! built-in profiles on load so new releases can add defaults without
-//! overwriting user-created profiles.
-
-use super::types::{AgentProfile, AgentProfilesState, DEFAULT_PROFILE_ID};
-use anyhow::Result;
-use std::collections::BTreeMap;
-use std::fs;
-use std::io::{Read, Write};
-use std::path::{Path, PathBuf};
-
-const PROFILE_FILE: &str = "agent_profiles.json";
-
-#[derive(Debug, Clone)]
-pub struct AgentProfileStore {
- workspace_dir: PathBuf,
-}
-
-impl AgentProfileStore {
- pub fn new(workspace_dir: PathBuf) -> Self {
- Self { workspace_dir }
- }
-
- pub fn load(&self) -> Result<AgentProfilesState, String> {
- let path = self.path();
- tracing::debug!(path = %path.display(), "[profiles] load entry");
- let state = if path.exists() {
- let mut buf = String::new();
- fs::File::open(&path)
- .map_err(|e| {
- tracing::debug!(
- path = %path.display(),
- error = %e,
- "[profiles] load open_error"
- );
- format!("open agent profiles {}: {e}", path.display())
- })?
- .read_to_string(&mut buf)
- .map_err(|e| {
- tracing::debug!(
- path = %path.display(),
- error = %e,
- "[profiles] load read_error"
- );
- format!("read agent profiles {}: {e}", path.display())
- })?;
- serde_json::from_str::<AgentProfilesState>(&buf).map_err(|e| {
- tracing::debug!(
- path = %path.display(),
- error = %e,
- "[profiles] load parse_error"
- );
- format!("parse agent profiles {}: {e}", path.display())
- })?
- } else {
- tracing::debug!(path = %path.display(), "[profiles] load default_state");
- AgentProfilesState::default()
- };
- let state = normalise_state(state);
- tracing::debug!(
- path = %path.display(),
- active_profile_id = %state.active_profile_id,
- profile_count = state.profiles.len(),
- "[profiles] load ok"
- );
- Ok(state)
- }
-
- pub fn save(&self, state: AgentProfilesState) -> Result<AgentProfilesState, String> {
- tracing::debug!(
- active_profile_id = %state.active_profile_id,
- profile_count = state.profiles.len(),
- "[profiles] save entry"
- );
- let state = normalise_state(state);
- let path = self.path();
- let parent = path.parent().ok_or_else(|| {
- tracing::debug!(
- path = %path.display(),
- "[profiles] save invalid_path"
- );
- format!("invalid agent profiles path {}", path.display())
- })?;
- fs::create_dir_all(parent).map_err(|e| {
- tracing::debug!(
- path = %path.display(),
- parent = %parent.display(),
- error = %e,
- "[profiles] save create_dir_error"
- );
- format!("create agent profiles dir {}: {e}", parent.display())
- })?;
- let mut tmp = tempfile::NamedTempFile::new_in(parent).map_err(|e| {
- tracing::debug!(
- parent = %parent.display(),
- error = %e,
- "[profiles] save tempfile_error"
- );
- format!(
- "create agent profiles tempfile in {}: {e}",
- parent.display()
- )
- })?;
- let bytes = serde_json::to_vec_pretty(&state).map_err(|e| {
- tracing::debug!(error = %e, "[profiles] save serialize_error");
- format!("serialize agent profiles: {e}")
- })?;
- tmp.write_all(&bytes).map_err(|e| {
- tracing::debug!(error = %e, "[profiles] save write_error");
- format!("write agent profiles tempfile: {e}")
- })?;
- tmp.as_file().sync_all().map_err(|e| {
- tracing::debug!(error = %e, "[profiles] save fsync_error");
- format!("fsync agent profiles tempfile: {e}")
- })?;
- tmp.persist(&path).map_err(|e| {
- tracing::debug!(
- path = %path.display(),
- error = %e,
- "[profiles] save persist_error"
- );
- format!("persist agent profiles {}: {e}", path.display())
- })?;
- tracing::debug!(
- path = %path.display(),
- active_profile_id = %state.active_profile_id,
- profile_count = state.profiles.len(),
- "[profiles] save ok"
- );
- Ok(state)
- }
-
- pub fn select(&self, profile_id: &str) -> Result<AgentProfilesState, String> {
- let mut state = self.load()?;
- let profile_id = profile_id.trim();
- tracing::debug!(profile_id, "[profiles] select entry");
- if !state.profiles.iter().any(|p| p.id == profile_id) {
- tracing::debug!(profile_id, "[profiles] select not_found");
- return Err(format!("agent profile '{profile_id}' not found"));
- }
- state.active_profile_id = profile_id.to_string();
- tracing::debug!(profile_id, "[profiles] select active_profile_changed");
- self.save(state)
- }
-
- pub fn upsert(&self, profile: AgentProfile) -> Result<AgentProfilesState, String> {
- let mut state = self.load()?;
- let profile = normalise_profile(profile);
- super::home::validate_profile_id(&profile.id)?;
- tracing::debug!(
- profile_id = %profile.id,
- agent_id = %profile.agent_id,
- "[profiles] upsert entry"
- );
- let profile = if profile.id == DEFAULT_PROFILE_ID {
- tracing::debug!("[profiles] upsert built_in_default_merge");
- let mut default = built_in_default_profile();
- default.name = profile.name;
- default.description = profile.description;
- default.model_override = profile.model_override;
- default.temperature = profile.temperature;
- default.system_prompt_suffix = profile.system_prompt_suffix;
- default.allowed_tools = profile.allowed_tools;
- default.avatar_url = profile.avatar_url;
- default.voice_id = profile.voice_id;
- default.soul_md = profile.soul_md;
- default.soul_md_path = profile.soul_md_path;
- default.composio_integrations = profile.composio_integrations;
- default.memory_sources = profile.memory_sources;
- default.include_agent_conversations = profile.include_agent_conversations;
- default.allowed_skills = profile.allowed_skills;
- default.allowed_mcp_servers = profile.allowed_mcp_servers;
- default.dedicated_memory = profile.dedicated_memory;
- default.dedicated_workspace = profile.dedicated_workspace;
- // memory_dir_suffix stays as built-in default (don't let user override the default's suffix)
- default.sort_order = profile.sort_order;
- default
- } else {
- AgentProfile {
- built_in: profile.built_in
- || built_in_profiles()
- .iter()
- .any(|builtin| builtin.id == profile.id),
- is_master: false, // only DEFAULT_PROFILE_ID may be master
- ..profile
- }
- };
-
- let profile = if profile.id != DEFAULT_PROFILE_ID && profile.memory_dir_suffix.is_none() {
- // Re-upsert of an existing profile without a suffix → reuse the stored
- // suffix so its memory directory doesn't migrate (and silently orphan
- // its database).
- if let Some(existing) = state.profiles.iter().find(|p| p.id == profile.id) {
- if let Some(ref existing_suffix) = existing.memory_dir_suffix {
- AgentProfile {
- memory_dir_suffix: Some(existing_suffix.clone()),
- ..profile
- }
- } else {
- // Pre-personality profile getting its first suffix assignment.
- let existing_suffixes: std::collections::HashSet<String> = state
- .profiles
- .iter()
- .filter(|p| p.id != profile.id)
- .filter_map(|p| p.memory_dir_suffix.clone())
- .filter(|s| !s.is_empty())
- .collect();
- AgentProfile {
- memory_dir_suffix: Some(next_available_suffix(&existing_suffixes)),
- ..profile
- }
- }
- } else {
- // New non-default profile: assign the lowest unused suffix.
- let existing_suffixes: std::collections::HashSet<String> = state
- .profiles
- .iter()
- .filter_map(|p| p.memory_dir_suffix.clone())
- .filter(|s| !s.is_empty())
- .collect();
- AgentProfile {
- memory_dir_suffix: Some(next_available_suffix(&existing_suffixes)),
- ..profile
- }
- }
- } else {
- profile
- };
-
- if let Some(existing) = state.profiles.iter_mut().find(|p| p.id == profile.id) {
- tracing::debug!(profile_id = %profile.id, "[profiles] upsert replace_existing");
- *existing = profile;
- } else {
- tracing::debug!(profile_id = %profile.id, "[profiles] upsert insert_new");
- state.profiles.push(profile);
- }
- self.save(state)
- }
-
- pub fn delete(&self, profile_id: &str) -> Result<AgentProfilesState, String> {
- let profile_id = profile_id.trim();
- tracing::debug!(profile_id, "[profiles] delete entry");
- if built_in_profiles()
- .iter()
- .any(|profile| profile.id == profile_id)
- {
- tracing::debug!(profile_id, "[profiles] delete built_in_rejected");
- return Err(format!(
- "built-in agent profile '{profile_id}' cannot be deleted"
- ));
- }
- let mut state = self.load()?;
- let before = state.profiles.len();
- state.profiles.retain(|p| p.id != profile_id);
- if state.profiles.len() == before {
- tracing::debug!(profile_id, "[profiles] delete not_found");
- return Err(format!("agent profile '{profile_id}' not found"));
- }
- if state.active_profile_id == profile_id {
- state.active_profile_id = DEFAULT_PROFILE_ID.to_string();
- tracing::debug!(profile_id, "[profiles] delete active_profile_fallback");
- }
- tracing::debug!(
- profile_id,
- profile_count = state.profiles.len(),
- "[profiles] delete removed"
- );
- self.save(state)
- }
-
- pub fn resolve(
- &self,
- requested_profile_id: Option<&str>,
- ) -> Result<(AgentProfilesState, AgentProfile), String> {
- let state = self.load()?;
- let requested = requested_profile_id
- .map(str::trim)
- .filter(|id| !id.is_empty())
- .unwrap_or(state.active_profile_id.as_str());
- tracing::debug!(requested_profile_id = requested, "[profiles] resolve entry");
- let profile = state
- .profiles
- .iter()
- .find(|profile| profile.id == requested)
- .or_else(|| {
- state
- .profiles
- .iter()
- .find(|profile| profile.id == DEFAULT_PROFILE_ID)
- })
- .cloned()
- .unwrap_or_else(built_in_default_profile);
- tracing::debug!(
- requested_profile_id = requested,
- resolved_profile_id = %profile.id,
- agent_id = %profile.agent_id,
- "[profiles] resolve ok"
- );
- Ok((state, profile))
- }
-
- fn path(&self) -> PathBuf {
- self.workspace_dir.join(PROFILE_FILE)
- }
-}
-
-pub fn load_profiles(workspace_dir: &Path) -> Result<AgentProfilesState, String> {
- AgentProfileStore::new(workspace_dir.to_path_buf()).load()
-}
-
-pub fn built_in_profiles() -> Vec<AgentProfile> {
- vec![
- built_in_default_profile(),
- AgentProfile {
- id: "reasoning".to_string(),
- name: "Reasoning".to_string(),
- description: "Deep reasoning mode with extended thinking.".to_string(),
- agent_id: "orchestrator".to_string(),
- model_override: Some("hint:reasoning".to_string()),
- temperature: None,
- system_prompt_suffix: None,
- allowed_tools: None,
- built_in: true,
- avatar_url: None,
- voice_id: None,
- soul_md: None,
- soul_md_path: None,
- composio_integrations: None,
- memory_sources: None,
- include_agent_conversations: true,
- allowed_skills: None,
- allowed_mcp_servers: None,
- memory_dir_suffix: None,
- is_master: false,
- sort_order: None,
- dedicated_memory: false,
- dedicated_workspace: false,
- },
- AgentProfile {
- id: "research".to_string(),
- name: "Research".to_string(),
- description: "Source-grounded research with web and memory tools.".to_string(),
- agent_id: "researcher".to_string(),
- model_override: Some("agentic-v1".to_string()),
- temperature: Some(0.2),
- system_prompt_suffix: Some(
- "Prioritize source-grounded findings, quote evidence sparingly, and separate facts from inference."
- .to_string(),
- ),
- allowed_tools: None,
- built_in: true,
- avatar_url: None,
- voice_id: None,
- soul_md: None,
- soul_md_path: None,
- composio_integrations: None,
- memory_sources: None,
- include_agent_conversations: true,
- allowed_skills: None,
- allowed_mcp_servers: None,
- memory_dir_suffix: None,
- is_master: false,
- sort_order: None,
- dedicated_memory: false,
- dedicated_workspace: false,
- },
- AgentProfile {
- id: "planner".to_string(),
- name: "Planner".to_string(),
- description: "Breaks ambiguous work into ordered task plans.".to_string(),
- agent_id: "planner".to_string(),
- model_override: Some("agentic-v1".to_string()),
- temperature: Some(0.3),
- system_prompt_suffix: Some(
- "Favor explicit task decomposition, dependencies, risks, and concrete next actions."
- .to_string(),
- ),
- allowed_tools: None,
- built_in: true,
- avatar_url: None,
- voice_id: None,
- soul_md: None,
- soul_md_path: None,
- composio_integrations: None,
- memory_sources: None,
- include_agent_conversations: true,
- allowed_skills: None,
- allowed_mcp_servers: None,
- memory_dir_suffix: None,
- is_master: false,
- sort_order: None,
- dedicated_memory: false,
- dedicated_workspace: false,
- },
- AgentProfile {
- id: "review".to_string(),
- name: "Review".to_string(),
- description: "Critical review mode for bugs, regressions, and missing tests.".to_string(),
- agent_id: "critic".to_string(),
- model_override: Some("agentic-v1".to_string()),
- temperature: Some(0.1),
- system_prompt_suffix: Some(
- "Lead with concrete findings, cite files or evidence, and avoid broad rewrites unless required."
- .to_string(),
- ),
- allowed_tools: None,
- built_in: true,
- avatar_url: None,
- voice_id: None,
- soul_md: None,
- soul_md_path: None,
- composio_integrations: None,
- memory_sources: None,
- include_agent_conversations: true,
- allowed_skills: None,
- allowed_mcp_servers: None,
- memory_dir_suffix: None,
- is_master: false,
- sort_order: None,
- dedicated_memory: false,
- dedicated_workspace: false,
- },
- ]
-}
-
-pub(crate) fn built_in_default_profile() -> AgentProfile {
- AgentProfile {
- id: DEFAULT_PROFILE_ID.to_string(),
- name: "Default".to_string(),
- description: "The standard OpenHuman orchestrator.".to_string(),
- agent_id: "orchestrator".to_string(),
- model_override: None,
- temperature: None,
- system_prompt_suffix: None,
- allowed_tools: None,
- built_in: true,
- avatar_url: None,
- voice_id: None,
- soul_md: None,
- soul_md_path: None,
- composio_integrations: None,
- memory_sources: None,
- include_agent_conversations: true,
- allowed_skills: None,
- allowed_mcp_servers: None,
- memory_dir_suffix: Some("".into()),
- is_master: true,
- sort_order: None,
- dedicated_memory: false,
- dedicated_workspace: false,
- }
-}
-
-fn normalise_state(state: AgentProfilesState) -> AgentProfilesState {
- tracing::trace!(
- active_profile_id = %state.active_profile_id,
- profile_count = state.profiles.len(),
- "[profiles] normalise_state entry"
- );
- let mut by_id: BTreeMap<String, AgentProfile> = built_in_profiles()
- .into_iter()
- .map(|profile| (profile.id.clone(), profile))
- .collect();
- // `by_id` currently holds exactly the built-in profile ids — capture them so
- // the overlay loop below can recognise a persisted override of a built-in.
- let built_in_ids: std::collections::HashSet<String> = by_id.keys().cloned().collect();
-
- for profile in state.profiles {
- let mut profile = normalise_profile(profile);
- if profile.id.is_empty() {
- continue;
- }
- if profile.id == DEFAULT_PROFILE_ID {
- profile.is_master = true;
- profile.memory_dir_suffix = Some(String::new());
- } else if built_in_ids.contains(&profile.id) && !profile.dedicated_memory {
- tracing::debug!(
- profile_id = %profile.id,
- had_suffix = profile.memory_dir_suffix.is_some(),
- "[profiles] normalise pinning built-in profile to shared memory/session_raw subtree"
- );
- // #5351: the built-in helper profiles (reasoning/research/planner/
- // review) ship `dedicated_memory: false` and are meant to SHARE the
- // default memory + `session_raw` subtree. An earlier `upsert` path
- // (store.rs `upsert`) wrongly stamped them with a numeric
- // `memory_dir_suffix` ("-1") — isolating their transcripts + memory
- // recall into `session_raw-1/` / `memory-1/`, which dropped all prior
- // context when the user flipped the Quick/Reasoning toggle mid-thread.
- // Pin them back to the shared subtree here (mirroring how `default` is
- // pinned above, the canonical normalization point that runs on every
- // load AND save), so both a fresh mis-assignment and an
- // already-persisted stale suffix are healed. A user who genuinely
- // wants isolated memory sets `dedicated_memory` (honoured by the guard
- // above) or creates a custom (non-built-in) profile — neither is
- // touched here.
- profile.memory_dir_suffix = None;
- }
- by_id.insert(profile.id.clone(), profile);
- }
-
- let mut profiles: Vec<AgentProfile> = by_id.into_values().collect();
- profiles.sort_by(|a, b| {
- let rank = |id: &str| match id {
- DEFAULT_PROFILE_ID => 0,
- "research" => 1,
- "planner" => 2,
- "review" => 3,
- _ => 10,
- };
- rank(&a.id)
- .cmp(&rank(&b.id))
- .then_with(|| a.name.cmp(&b.name))
- });
-
- let active_profile_id = state.active_profile_id.trim().to_string();
- let active_profile_id = if profiles.iter().any(|p| p.id == active_profile_id) {
- active_profile_id
- } else {
- DEFAULT_PROFILE_ID.to_string()
- };
-
- AgentProfilesState {
- active_profile_id,
- profiles,
- }
-}
-
-/// Trim + drop empty entries from an optional string-list allowlist; an empty
-/// result normalises to `None` (the "all / unrestricted" sentinel).
-fn normalise_allowlist(list: Option<Vec<String>>) -> Option<Vec<String>> {
- let cleaned = list.map(|items| {
- items
- .into_iter()
- .map(|item| item.trim().to_string())
- .filter(|item| !item.is_empty())
- .collect::<Vec<_>>()
- });
- match cleaned {
- Some(items) if items.is_empty() => None,
- other => other,
- }
-}
-
-fn normalise_profile(mut profile: AgentProfile) -> AgentProfile {
- profile.id = normalise_profile_id(&profile.id, &profile.name);
- profile.name = profile.name.trim().to_string();
- if profile.name.is_empty() {
- profile.name = profile.id.clone();
- }
- profile.description = profile.description.trim().to_string();
- profile.agent_id = profile.agent_id.trim().to_string();
- if profile.agent_id.is_empty() {
- profile.agent_id = "orchestrator".to_string();
- }
- profile.model_override = profile
- .model_override
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty());
- profile.system_prompt_suffix = profile
- .system_prompt_suffix
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty());
- profile.allowed_tools = normalise_allowlist(profile.allowed_tools);
- profile.avatar_url = profile
- .avatar_url
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty());
- profile.voice_id = profile
- .voice_id
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty());
- profile.soul_md = profile
- .soul_md
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty());
- profile.soul_md_path = profile
- .soul_md_path
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty());
- profile.composio_integrations = normalise_allowlist(profile.composio_integrations);
- profile.memory_sources = normalise_allowlist(profile.memory_sources);
- profile.allowed_skills = normalise_allowlist(profile.allowed_skills);
- profile.allowed_mcp_servers = normalise_allowlist(profile.allowed_mcp_servers);
- // Note: `Some("")` is the sentinel used exclusively by the default profile
- // to indicate the legacy `memory/` directory (no suffix). `normalise_state`
- // re-applies it after the filter below, so any `Some("")` on a non-default
- // profile is silently dropped to `None` here, causing it to receive the
- // next available numbered suffix on the following `upsert` path.
- profile.memory_dir_suffix = profile
- .memory_dir_suffix
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty());
- profile
-}
-
-/// Return the lowest available numbered suffix (`"-1"`, `"-2"`, …) not present
-/// in `existing`. Used during `upsert` to auto-assign a unique memory directory
-/// suffix to a new non-default personality profile.
-fn next_available_suffix(existing: &std::collections::HashSet<String>) -> String {
- let mut n = 1u32;
- loop {
- let candidate = format!("-{n}");
- if !existing.contains(&candidate) {
- return candidate;
- }
- n += 1;
- }
-}
-
-/// Normalise a raw profile id into its persisted slug form, mirroring the
-/// transformation `normalise_profile` applies on upsert. Exposed so callers
-/// (e.g. `ops::upsert`) can locate the persisted profile by its stored id after
-/// the store has normalised it.
-///
-/// Takes the name as well as the id because the rule needs both: an id that
-/// slugifies to nothing falls back to the name, and a name that slugifies to
-/// nothing falls back to a digest of it. A caller that mirrors only the first
-/// step looks up an id the store never wrote.
-pub(crate) fn normalise_profile_id(id: &str, name: &str) -> String {
- let from_id = slugify_profile_id(id);
- if !from_id.is_empty() {
- return from_id;
- }
- let from_name = slugify_profile_id(name);
- if !from_name.is_empty() {
- return from_name;
- }
- profile_id_from_name_digest(name)
-}
-
-/// Profile id for a name that slugifies to nothing.
-///
-/// `slugify_profile_id` keeps only ASCII alphanumerics, so a name written
-/// entirely outside that range - Japanese, Chinese, Greek, Cyrillic, Arabic -
-/// reduces to the empty string and `validate_profile_id` rejects the upsert
-/// with "profile id must not be empty". The user supplied a name; the error
-/// blames an id they never typed.
-///
-/// Derive one from the name instead. A digest keeps it deterministic, so
-/// saving the same profile twice updates it rather than creating a second one.
-///
-/// 16 bytes, not 4: at 32 bits the birthday bound is ~65k names, and upsert
-/// replaces by id, so a collision silently overwrites someone's profile. The
-/// resulting 40-character id stays under the 64-character cap in
-/// `validate_profile_id`.
-fn profile_id_from_name_digest(name: &str) -> String {
- use sha2::{Digest, Sha256};
-
- let trimmed = name.trim();
- if trimmed.is_empty() {
- return String::new();
- }
- let digest = Sha256::digest(trimmed.as_bytes());
- let short: String = digest
- .iter()
- .take(16)
- .map(|byte| format!("{byte:02x}"))
- .collect();
- format!("profile-{short}")
-}
-
-fn slugify_profile_id(input: &str) -> String {
- let mut out = String::new();
- let mut last_was_sep = false;
- for c in input.trim().chars() {
- let c = c.to_ascii_lowercase();
- if c.is_ascii_alphanumeric() {
- out.push(c);
- last_was_sep = false;
- } else if !last_was_sep {
- out.push('-');
- last_was_sep = true;
- }
- }
- out.trim_matches('-').to_string()
-}
-
-impl Default for AgentProfilesState {
- fn default() -> Self {
- Self {
- active_profile_id: DEFAULT_PROFILE_ID.to_string(),
- profiles: built_in_profiles(),
- }
- }
-}
-
-#[cfg(test)]
-#[path = "store_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/profiles/store_tests.rs b/crates/openhuman-core/src/agent/profiles/store_tests.rs
deleted file mode 100644
index 74f2679a41..0000000000
--- a/crates/openhuman-core/src/agent/profiles/store_tests.rs
+++ /dev/null
@@ -1,471 +0,0 @@
-use super::*;
-use tempfile::tempdir;
-
-/// Minimal custom profile literal for tests, with all allowlists unset.
-fn custom(id: &str, name: &str, agent_id: &str) -> AgentProfile {
- AgentProfile {
- id: id.into(),
- name: name.into(),
- description: String::new(),
- agent_id: agent_id.into(),
- model_override: None,
- temperature: None,
- system_prompt_suffix: None,
- allowed_tools: None,
- built_in: false,
- avatar_url: None,
- voice_id: None,
- soul_md: None,
- soul_md_path: None,
- composio_integrations: None,
- memory_sources: None,
- include_agent_conversations: true,
- allowed_skills: None,
- allowed_mcp_servers: None,
- memory_dir_suffix: None,
- is_master: false,
- sort_order: None,
- dedicated_memory: false,
- dedicated_workspace: false,
- }
-}
-
-#[test]
-fn profile_store_roundtrips_active_profile_and_custom_entries() {
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
- let mut profile = custom(" Custom Profile ", " Custom Profile ", " planner ");
- profile.description = " My custom profile ".into();
- profile.model_override = Some(" agentic-v1 ".into());
- profile.temperature = Some(0.25);
- profile.system_prompt_suffix = Some(" Be brief. ".into());
- profile.allowed_tools = Some(vec![" todo ".into(), "".into()]);
- let state = store.upsert(profile).expect("upsert");
- assert!(state.profiles.iter().any(|p| p.id == "custom-profile"));
-
- let selected = store.select("custom-profile").expect("select");
- assert_eq!(selected.active_profile_id, "custom-profile");
-
- let loaded = store.load().expect("load");
- let custom = loaded
- .profiles
- .iter()
- .find(|profile| profile.id == "custom-profile")
- .expect("custom profile");
- assert_eq!(custom.agent_id, "planner");
- assert_eq!(
- custom.allowed_tools.as_deref(),
- Some(vec!["todo".to_string()].as_slice())
- );
-
- let resolved = store.resolve(Some("custom-profile")).expect("resolve").1;
- assert_eq!(resolved.id, "custom-profile");
-}
-
-#[test]
-fn normalise_state_heals_stale_numeric_suffix_on_built_in_profiles() {
- // An earlier `upsert` bug stamped the built-in `reasoning` profile with a
- // scoped `memory_dir_suffix`, isolating its transcripts + memory into
- // `session_raw-1/` / `memory-1/` and dropping context on a mid-thread
- // Quick↔Reasoning switch (#5351). Loading must heal it back to the shared
- // subtree; a genuine custom profile's suffix must be left alone.
- let mut reasoning = custom("reasoning", "Reasoning", "orchestrator");
- reasoning.built_in = true;
- reasoning.memory_dir_suffix = Some("-1".into());
- let mut sidekick = custom("sidekick", "Sidekick", "orchestrator");
- sidekick.memory_dir_suffix = Some("-2".into());
-
- let state = normalise_state(AgentProfilesState {
- active_profile_id: DEFAULT_PROFILE_ID.into(),
- profiles: vec![reasoning, sidekick],
- });
-
- let reasoning = state
- .profiles
- .iter()
- .find(|p| p.id == "reasoning")
- .expect("reasoning present");
- assert_eq!(
- reasoning.memory_dir_suffix, None,
- "built-in reasoning must be pinned to the shared memory/session_raw subtree"
- );
- let sidekick = state
- .profiles
- .iter()
- .find(|p| p.id == "sidekick")
- .expect("custom sidekick present");
- assert_eq!(
- sidekick.memory_dir_suffix.as_deref(),
- Some("-2"),
- "a genuine custom profile's isolated-memory suffix must be preserved"
- );
-}
-
-#[test]
-fn upsert_of_built_in_reasoning_stays_on_shared_subtree() {
- // Editing + saving the built-in Reasoning profile must NOT scope its
- // memory: it ships `dedicated_memory:false` and shares the default
- // subtree, so a mid-thread switch keeps context (#5351).
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
- let mut reasoning = custom("reasoning", "Reasoning", "orchestrator");
- reasoning.built_in = true;
- reasoning.model_override = Some("hint:reasoning".into());
- // ProfileEditorPage submits without a `memory_dir_suffix`.
- reasoning.memory_dir_suffix = None;
-
- store.upsert(reasoning).expect("upsert reasoning");
-
- let loaded = store.load().expect("load");
- let reasoning = loaded
- .profiles
- .iter()
- .find(|p| p.id == "reasoning")
- .expect("reasoning present");
- assert_eq!(
- reasoning.memory_dir_suffix, None,
- "upsert must never stamp a built-in profile with a scoped memory suffix"
- );
-}
-
-#[test]
-fn upsert_rejects_profile_ids_longer_than_home_path_limit() {
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
- let profile = custom(&"a".repeat(65), "Overlong", "orchestrator");
-
- let error = store
- .upsert(profile)
- .expect_err("overlong id must be rejected");
- assert!(error.contains("too long"));
- assert!(store
- .load()
- .expect("load")
- .profiles
- .iter()
- .all(|profile| profile.name != "Overlong"));
-}
-
-#[test]
-fn built_in_profiles_are_merged_when_file_is_missing() {
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
- let loaded = store.load().expect("load");
- let ids: Vec<&str> = loaded.profiles.iter().map(|p| p.id.as_str()).collect();
- assert!(ids.contains(&DEFAULT_PROFILE_ID));
- assert!(ids.contains(&"research"));
- assert_eq!(loaded.active_profile_id, DEFAULT_PROFILE_ID);
-}
-
-#[test]
-fn load_profiles_helper_reads_defaults() {
- let dir = tempdir().expect("tempdir");
- let loaded = load_profiles(dir.path()).expect("load profiles");
- assert!(loaded
- .profiles
- .iter()
- .any(|profile| profile.id == DEFAULT_PROFILE_ID));
-}
-
-#[test]
-fn normalise_state_falls_back_to_default_active_profile() {
- let mut bad = custom(" ", " ", " ");
- bad.description = " ignored ".into();
- bad.model_override = Some(" ".into());
- bad.system_prompt_suffix = Some(" ".into());
- bad.allowed_tools = Some(vec![" ".into()]);
- let state = normalise_state(AgentProfilesState {
- active_profile_id: "missing".into(),
- profiles: vec![bad],
- });
-
- assert_eq!(state.active_profile_id, DEFAULT_PROFILE_ID);
- assert!(!state.profiles.iter().any(|profile| profile.id.is_empty()));
-}
-
-#[test]
-fn normalise_profile_drops_empty_allowlists_to_none() {
- let mut profile = custom("scoped", "Scoped", "orchestrator");
- profile.memory_sources = Some(vec![" ".into(), "".into()]);
- profile.allowed_skills = Some(vec![" deep-research ".into()]);
- profile.allowed_mcp_servers = Some(vec![]);
- profile.composio_integrations = Some(vec![" ".into()]);
- let normalised = normalise_profile(profile);
- assert_eq!(normalised.memory_sources, None);
- assert_eq!(
- normalised.allowed_skills.as_deref(),
- Some(vec!["deep-research".to_string()].as_slice())
- );
- assert_eq!(normalised.allowed_mcp_servers, None);
- assert_eq!(normalised.composio_integrations, None);
-}
-
-#[test]
-fn upsert_default_profile_preserves_builtin_default_identity() {
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
- let mut profile = custom(DEFAULT_PROFILE_ID, " Default Custom ", " planner ");
- profile.description = " custom description ".into();
- profile.model_override = Some(" agentic-v1 ".into());
- profile.temperature = Some(0.3);
- profile.system_prompt_suffix = Some(" suffix ".into());
- profile.allowed_tools = Some(vec![" todo ".into()]);
- profile.memory_sources = Some(vec!["slack-eng".into()]);
- profile.dedicated_memory = true;
- profile.dedicated_workspace = true;
- let state = store.upsert(profile).expect("upsert default");
- let default = state
- .profiles
- .iter()
- .find(|profile| profile.id == DEFAULT_PROFILE_ID)
- .expect("default profile");
- assert!(default.built_in);
- assert_eq!(default.agent_id, "orchestrator");
- assert_eq!(default.name, "Default Custom");
- assert_eq!(default.system_prompt_suffix.as_deref(), Some("suffix"));
- // New allowlist fields round-trip through the default merge branch.
- assert_eq!(
- default.memory_sources.as_deref(),
- Some(vec!["slack-eng".to_string()].as_slice())
- );
- assert!(default.dedicated_memory);
- assert!(default.dedicated_workspace);
-}
-
-#[test]
-fn select_missing_and_delete_builtin_return_errors() {
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
-
- let select_err = store.select("missing").expect_err("missing select");
- assert!(select_err.contains("not found"));
-
- let delete_err = store
- .delete(DEFAULT_PROFILE_ID)
- .expect_err("builtin delete rejected");
- assert!(delete_err.contains("cannot be deleted"));
-}
-
-#[test]
-fn delete_missing_custom_profile_returns_error() {
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
- let err = store.delete("not-there").expect_err("missing delete");
- assert!(err.contains("not found"));
-}
-
-#[test]
-fn resolve_uses_active_profile_and_falls_back_to_default() {
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
- store
- .upsert(custom("writer", "Writer", "planner"))
- .expect("upsert");
- store.select("writer").expect("select");
-
- let active = store.resolve(None).expect("resolve active").1;
- assert_eq!(active.id, "writer");
- let fallback = store.resolve(Some("missing")).expect("resolve missing").1;
- assert_eq!(fallback.id, DEFAULT_PROFILE_ID);
-}
-
-#[test]
-fn deleting_active_custom_profile_falls_back_to_default() {
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
- store
- .upsert(custom("tmp", "Tmp", "orchestrator"))
- .expect("upsert");
- store.select("tmp").expect("select");
- let state = store.delete("tmp").expect("delete");
- assert_eq!(state.active_profile_id, DEFAULT_PROFILE_ID);
- assert!(!state.profiles.iter().any(|p| p.id == "tmp"));
-}
-
-#[test]
-fn memory_dir_suffix_auto_assigned_on_upsert() {
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
- // First custom profile gets "-1"
- let state = store
- .upsert(custom("alice", "Alice", "orchestrator"))
- .expect("upsert alice");
- let alice = state.profiles.iter().find(|p| p.id == "alice").unwrap();
- assert_eq!(alice.memory_dir_suffix.as_deref(), Some("-1"));
-
- // Second custom profile gets "-2"
- let state = store
- .upsert(custom("bob", "Bob", "orchestrator"))
- .expect("upsert bob");
- let bob = state.profiles.iter().find(|p| p.id == "bob").unwrap();
- assert_eq!(bob.memory_dir_suffix.as_deref(), Some("-2"));
-
- // Delete alice, create charlie — should reuse "-1"
- store.delete("alice").expect("delete alice");
- let state = store
- .upsert(custom("charlie", "Charlie", "orchestrator"))
- .expect("upsert charlie");
- let charlie = state.profiles.iter().find(|p| p.id == "charlie").unwrap();
- assert_eq!(charlie.memory_dir_suffix.as_deref(), Some("-1"));
-}
-
-#[test]
-fn upsert_roundtrips_dedicated_home_fields() {
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
- let mut profile = custom("iso", "Iso", "orchestrator");
- profile.dedicated_memory = true;
- profile.dedicated_workspace = true;
- store.upsert(profile).expect("upsert");
-
- let loaded = store.load().expect("load");
- let iso = loaded
- .profiles
- .iter()
- .find(|p| p.id == "iso")
- .expect("iso profile");
- assert!(iso.dedicated_memory);
- assert!(iso.dedicated_workspace);
-}
-
-#[test]
-fn default_profile_has_master_and_memory_suffix() {
- let default = built_in_default_profile();
- assert!(default.is_master);
- assert_eq!(default.memory_dir_suffix.as_deref(), Some(""));
- assert!(default.include_agent_conversations);
-}
-
-/// A name written entirely outside ASCII slugifies to nothing, and the
-/// upsert used to fail with "profile id must not be empty" - an error about
-/// a field the user never filled in.
-#[test]
-fn a_profile_named_only_in_non_ascii_can_be_saved() {
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
- let name = "\u{7814}\u{7a76}\u{30a2}\u{30b7}\u{30b9}\u{30bf}\u{30f3}\u{30c8}";
-
- let state = store
- .upsert(custom("", name, "orchestrator"))
- .expect("a profile named in Japanese must be saveable");
-
- let saved = state
- .profiles
- .iter()
- .find(|p| p.name == name)
- .expect("the profile is in the list");
- assert!(
- super::super::home::validate_profile_id(&saved.id).is_ok(),
- "derived id must be a valid one: {}",
- saved.id
- );
-}
-
-/// The id comes from a digest of the name, so re-saving the same profile
-/// edits it instead of adding a second copy.
-#[test]
-fn re_saving_a_non_ascii_profile_updates_it() {
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
- let name = "\u{7814}\u{7a76}\u{30a2}\u{30b7}\u{30b9}\u{30bf}\u{30f3}\u{30c8}";
-
- store
- .upsert(custom("", name, "orchestrator"))
- .expect("first");
- let state = store.upsert(custom("", name, "planner")).expect("second");
-
- let matching: Vec<_> = state.profiles.iter().filter(|p| p.name == name).collect();
- assert_eq!(
- matching.len(),
- 1,
- "re-saving must not duplicate the profile"
- );
- assert_eq!(matching[0].agent_id, "planner", "the edit must be applied");
-}
-
-/// Two different non-ASCII names must not collapse onto one profile.
-#[test]
-fn two_non_ascii_profiles_keep_separate_ids() {
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
-
- store
- .upsert(custom("", "\u{7814}\u{7a76}", "orchestrator"))
- .expect("first");
- let state = store
- .upsert(custom("", "\u{5206}\u{6790}", "orchestrator"))
- .expect("second");
-
- assert!(state.profiles.iter().any(|p| p.name == "\u{7814}\u{7a76}"));
- assert!(state.profiles.iter().any(|p| p.name == "\u{5206}\u{6790}"));
-}
-
-/// An ASCII name still gets the readable slug it always had.
-#[test]
-fn an_ascii_name_is_unaffected() {
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
- let state = store
- .upsert(custom("", "Research Buddy", "orchestrator"))
- .expect("upsert");
- assert!(state.profiles.iter().any(|p| p.id == "research-buddy"));
-}
-
-/// `ops::upsert` looks the persisted profile up by re-deriving its id, and
-/// skips home materialization and SOUL.md sync when the lookup misses. The
-/// helper it uses has to produce exactly what the store wrote, including
-/// the digest fallback.
-#[test]
-fn normalise_profile_id_matches_what_the_store_persists() {
- let dir = tempdir().expect("tempdir");
- let store = AgentProfileStore::new(dir.path().to_path_buf());
- let name = "\u{7814}\u{7a76}\u{30a2}\u{30b7}\u{30b9}\u{30bf}\u{30f3}\u{30c8}";
-
- let state = store
- .upsert(custom("", name, "orchestrator"))
- .expect("upsert");
- let persisted = state
- .profiles
- .iter()
- .find(|p| p.name == name)
- .expect("saved profile");
-
- assert_eq!(normalise_profile_id("", name), persisted.id);
- assert_eq!(
- normalise_profile_id(" Custom Profile ", "ignored"),
- "custom-profile"
- );
- assert_eq!(
- normalise_profile_id("", " Custom Profile "),
- "custom-profile"
- );
-}
-
-/// Upsert replaces by id, so two names sharing one derived id silently
-/// overwrite each other. A 32-bit digest collides within ~65k names; these
-/// two are a measured collision at that width.
-#[test]
-fn the_derived_id_does_not_collide_for_known_32_bit_collisions() {
- let a = "\u{7814}\u{7a76}\u{30d7}\u{30ed}\u{30d5}\u{30a3}\u{30fc}\u{30eb}110131";
- let b = "\u{7814}\u{7a76}\u{30d7}\u{30ed}\u{30d5}\u{30a3}\u{30fc}\u{30eb}211703";
- let id_a = profile_id_from_name_digest(a);
- let id_b = profile_id_from_name_digest(b);
- assert_ne!(id_a, id_b, "these two collide at a 4-byte digest");
- for id in [&id_a, &id_b] {
- assert!(id.len() <= 64, "id must fit the 64-char cap: {id}");
- assert!(
- super::super::home::validate_profile_id(id).is_ok(),
- "derived id must be valid: {id}"
- );
- }
-}
-
-#[test]
-fn the_derived_id_is_stable_for_the_same_name() {
- let name = "\u{7814}\u{7a76}";
- assert_eq!(
- profile_id_from_name_digest(name),
- profile_id_from_name_digest(" \u{7814}\u{7a76} "),
- );
- assert_eq!(profile_id_from_name_digest(" "), "");
-}
diff --git a/crates/openhuman-core/src/agent/profiles/types.rs b/crates/openhuman-core/src/agent/profiles/types.rs
deleted file mode 100644
index 3e88e35598..0000000000
--- a/crates/openhuman-core/src/agent/profiles/types.rs
+++ /dev/null
@@ -1,101 +0,0 @@
-//! Serde domain types for persistent agent profiles.
-//!
-//! Profiles let the UI choose a primary agent persona plus runtime defaults
-//! (model, temperature, soul, allowed tools/skills/connectors, memory sources)
-//! without editing built-in agent TOML.
-
-use serde::{Deserialize, Serialize};
-
-pub const DEFAULT_PROFILE_ID: &str = "default";
-
-/// A user-selectable agent "flavour".
-///
-/// `None` on any allowlist field (`allowed_tools`, `allowed_skills`,
-/// `allowed_mcp_servers`, `composio_integrations`, `memory_sources`) is the
-/// "all / unrestricted" sentinel. An empty vec normalises to `None`.
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct AgentProfile {
- pub id: String,
- pub name: String,
- pub description: String,
- pub agent_id: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub model_override: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub temperature: Option<f64>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub system_prompt_suffix: Option<String>,
- /// Tool `name()` allowlist this profile can see. None = all tools.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub allowed_tools: Option<Vec<String>>,
- #[serde(default)]
- pub built_in: bool,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub avatar_url: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub voice_id: Option<String>,
- /// Inline SOUL.md content for this personality. Falls back to workspace root.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub soul_md: Option<String>,
- /// Relative path to a personality-specific SOUL.md file (checked before inline).
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub soul_md_path: Option<String>,
- /// Composio toolkit slugs this personality can access. None = all integrations.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub composio_integrations: Option<Vec<String>>,
- /// Memory-source entry ids this profile recalls from. None = all sources.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub memory_sources: Option<Vec<String>>,
- /// Whether this profile recalls prior agent conversations / cross-chat
- /// context. Default true (preserves legacy behaviour).
- #[serde(default = "default_true")]
- pub include_agent_conversations: bool,
- /// Skill / workflow ids this profile can list and run. None = all skills.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub allowed_skills: Option<Vec<String>>,
- /// MCP server names this profile can reach. None = all configured servers.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub allowed_mcp_servers: Option<Vec<String>>,
- /// Auto-assigned memory directory suffix: "" for default, "-1", "-2", etc.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub memory_dir_suffix: Option<String>,
- /// Whether this profile is the master orchestrator personality.
- #[serde(default)]
- pub is_master: bool,
- /// Display order (lower = shown first).
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub sort_order: Option<u32>,
- /// Give this profile its own memory subtree (`memory-<id>`,
- /// `memory_tree-<id>`, `session_raw-<id>`) instead of the shared/global one.
- /// Default false. See [`super::paths::effective_memory_suffix`].
- #[serde(default)]
- pub dedicated_memory: bool,
- /// Give this profile its own working directory under `action_dir`
- /// (`<action_dir>/profiles/<id>`) used as the default cwd for its tool runs.
- /// Default false. See [`super::home::dedicated_workspace_dir`].
- #[serde(default)]
- pub dedicated_workspace: bool,
-}
-
-/// serde default for `include_agent_conversations` (true).
-pub(crate) fn default_true() -> bool {
- true
-}
-
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct AgentProfilesState {
- pub active_profile_id: String,
- pub profiles: Vec<AgentProfile>,
-}
-
-/// A stable, serialized signature of a profile — used as a cache/identity key
-/// for prompt construction.
-pub fn profile_signature(profile: &AgentProfile) -> String {
- serde_json::to_string(profile).unwrap_or_else(|_| profile.id.clone())
-}
-
-#[cfg(test)]
-#[path = "types_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/profiles/types_tests.rs b/crates/openhuman-core/src/agent/profiles/types_tests.rs
deleted file mode 100644
index 29fdbbf37a..0000000000
--- a/crates/openhuman-core/src/agent/profiles/types_tests.rs
+++ /dev/null
@@ -1,82 +0,0 @@
-use super::*;
-use serde_json::json;
-
-#[test]
-fn profile_signature_includes_id() {
- let profile = AgentProfile {
- id: "planner".into(),
- name: "Planner".into(),
- description: String::new(),
- agent_id: "planner".into(),
- model_override: None,
- temperature: None,
- system_prompt_suffix: None,
- allowed_tools: None,
- built_in: true,
- avatar_url: None,
- voice_id: None,
- soul_md: None,
- soul_md_path: None,
- composio_integrations: None,
- memory_sources: None,
- include_agent_conversations: true,
- allowed_skills: None,
- allowed_mcp_servers: None,
- memory_dir_suffix: None,
- is_master: false,
- sort_order: None,
- dedicated_memory: false,
- dedicated_workspace: false,
- };
- assert!(profile_signature(&profile).contains("\"planner\""));
-}
-
-#[test]
-fn backwards_compat_deserialize_without_new_fields() {
- // Pre-profiles-feature payload: none of the new allowlist fields, no
- // include_agent_conversations. Must deserialize with safe defaults.
- let json = json!({
- "activeProfileId": "default",
- "profiles": [{
- "id": "default",
- "name": "Default",
- "description": "The standard OpenHuman orchestrator.",
- "agentId": "orchestrator",
- "builtIn": true
- }]
- });
- let state: AgentProfilesState = serde_json::from_value(json).expect("deserialize");
- let profile = &state.profiles[0];
- assert_eq!(profile.avatar_url, None);
- assert_eq!(profile.voice_id, None);
- assert_eq!(profile.memory_dir_suffix, None);
- assert_eq!(profile.memory_sources, None);
- assert_eq!(profile.allowed_skills, None);
- assert_eq!(profile.allowed_mcp_servers, None);
- // Defaults to true so existing users keep cross-chat recall.
- assert!(profile.include_agent_conversations);
- assert!(!profile.is_master);
- // New home fields default to false so legacy payloads keep behaving.
- assert!(!profile.dedicated_memory);
- assert!(!profile.dedicated_workspace);
-}
-
-#[test]
-fn new_home_fields_roundtrip_over_camelcase() {
- let json = json!({
- "id": "alice",
- "name": "Alice",
- "description": "",
- "agentId": "orchestrator",
- "builtIn": false,
- "dedicatedMemory": true,
- "dedicatedWorkspace": true
- });
- let profile: AgentProfile = serde_json::from_value(json).expect("deserialize");
- assert!(profile.dedicated_memory);
- assert!(profile.dedicated_workspace);
- // Serializes back out as camelCase.
- let out = serde_json::to_value(&profile).expect("serialize");
- assert_eq!(out["dedicatedMemory"], serde_json::json!(true));
- assert_eq!(out["dedicatedWorkspace"], serde_json::json!(true));
-}
diff --git a/crates/openhuman-core/src/agent/task_dispatcher/executor.rs b/crates/openhuman-core/src/agent/task_dispatcher/executor.rs
index 609c17cc4d..a1aafe7a9e 100644
--- a/crates/openhuman-core/src/agent/task_dispatcher/executor.rs
+++ b/crates/openhuman-core/src/agent/task_dispatcher/executor.rs
@@ -12,7 +12,6 @@ use crate::agent::harness::definition::AgentDefinitionRegistry;
use crate::agent::harness::definition::PromptSource;
use crate::agent::harness::session::Agent;
use crate::agent::harness::subagent_runner::with_autonomous_iter_cap;
-use crate::agent::profiles::PersonalityContext;
use crate::agent::task_session;
use crate::agent::todos::ops::{self, BoardLocation, CardPatch};
use crate::agent::todos::runs::{self, RunOutcome};
@@ -32,12 +31,10 @@ pub(super) const TASK_RUN_MAX_ITERATIONS: usize = 200;
/// Max chars of the agent's final output retained as board `evidence`.
pub(super) const EVIDENCE_MAX_CHARS: usize = 2_000;
-/// Map a card's `assigned_agent` handle to one of three executor presets:
-/// **personality** (scoped SOUL/MEMORY folded into the prompt suffix, run as
-/// that profile's agent), **skill** (orchestrator seeded with the skill's
-/// `SKILL.md` guidelines), or **built-in agent**. An unset or unresolved handle
-/// degrades to the default `orchestrator` — "use the personality if valid,
-/// otherwise the default agent."
+/// Map a card's `assigned_agent` handle to an executor preset: a skill
+/// (orchestrator seeded with its `SKILL.md` guidelines) or a canonical agent
+/// definition. An unset or unresolved handle degrades to the default
+/// `orchestrator`.
pub(super) fn resolve_executor(workspace_dir: &Path, assigned: Option<&str>) -> ResolvedExecutor {
let Some(handle) = assigned.map(str::trim).filter(|s| !s.is_empty()) else {
return ResolvedExecutor::default_agent();
@@ -46,32 +43,7 @@ pub(super) fn resolve_executor(workspace_dir: &Path, assigned: Option<&str>) ->
return ResolvedExecutor::default_agent();
}
- // 1) Personality (#2895): a user-defined profile with scoped identity.
- if let Ok(state) = crate::agent::profiles::load_profiles(workspace_dir) {
- if let Some(profile) = state.profiles.iter().find(|p| p.id == handle) {
- let ctx = PersonalityContext::from_profile(workspace_dir, profile.clone());
- let mut preamble = format!(
- "You are acting as the personality `{}` (\"{}\"). {}",
- profile.id, profile.name, profile.description
- );
- if let Some(soul) = &ctx.soul_md_override {
- preamble.push_str("\n\n[Personality SOUL.md]\n");
- preamble.push_str(&truncate_chars(soul, EXECUTOR_PREAMBLE_MAX_CHARS));
- }
- if let Some(mem) = &ctx.memory_md_override {
- preamble.push_str("\n\n[Personality MEMORY.md]\n");
- preamble.push_str(&truncate_chars(mem, EXECUTOR_PREAMBLE_MAX_CHARS));
- }
- return ResolvedExecutor {
- agent_id: profile.agent_id.clone(),
- prompt_suffix: Some(preamble),
- profile: Some(profile.clone()),
- label: format!("personality:{handle}"),
- };
- }
- }
-
- // 2) Workflow (#2824): the same autonomous run, seeded with SKILL.md.
+ // 1) Workflow (#2824): the same autonomous run, seeded with SKILL.md.
//
// `#[cfg]` rather than a stubbed `get_workflow`: the real one returns
// `Option<WorkflowDefinition>`, which flattens in `AgentDefinition` and is
@@ -93,12 +65,11 @@ pub(super) fn resolve_executor(workspace_dir: &Path, assigned: Option<&str>) ->
return ResolvedExecutor {
agent_id: "orchestrator".to_string(),
prompt_suffix: Some(suffix),
- profile: None,
label: format!("skill:{handle}"),
};
}
- // 3) Built-in agent definition.
+ // 2) Canonical agent definition.
if AgentDefinitionRegistry::global()
.and_then(|r| r.get(handle))
.is_some()
@@ -106,15 +77,14 @@ pub(super) fn resolve_executor(workspace_dir: &Path, assigned: Option<&str>) ->
return ResolvedExecutor {
agent_id: handle.to_string(),
prompt_suffix: None,
- profile: None,
label: format!("agent:{handle}"),
};
}
- // 4) Unresolved → degrade to the default agent (don't fail the card).
+ // 3) Unresolved → degrade to the default agent (don't fail the card).
tracing::warn!(
handle = %handle,
- "[task_dispatcher] assigned executor did not resolve to a personality/skill/agent; \
+ "[task_dispatcher] assigned executor did not resolve to a skill/agent; \
using default orchestrator"
);
ResolvedExecutor {
@@ -154,13 +124,8 @@ pub(super) async fn run_autonomous(
config.http_request.allowed_domains = vec!["*".to_string()];
}
- let mut agent = Agent::from_config_for_agent_with_profile(
- &config,
- &executor.agent_id,
- executor.prompt_suffix.clone(),
- executor.profile.as_ref(),
- )
- .map_err(|e| format!("build agent: {e:#}"))?;
+ let mut agent = Agent::from_config_for_agent(&config, &executor.agent_id)
+ .map_err(|e| format!("build agent: {e:#}"))?;
// Issue #4868 — apply the autonomous task-run iteration budget AFTER
// construction. The session builder now stamps the resolved agent
// definition's own cap onto the agent; an autonomous task run
@@ -216,19 +181,10 @@ pub(super) async fn run_autonomous(
// already authorized the parent turn that dispatched this task. Label
// as CLI so the approval gate doesn't fail closed on internal
// sub-agent invocations.
- // Gate memory-source recall for this background run to the profile's
- // allowlist (None = unrestricted), mirroring the web chat turn.
- let memory_scope = executor
- .profile
- .as_ref()
- .and_then(|p| p.memory_sources.clone());
agent.set_thread_id(session_thread_id.as_deref());
- let run = crate::memory::source_scope::with_source_scope(
- memory_scope,
- crate::agent::turn_origin::with_origin(
- crate::agent::turn_origin::AgentTurnOrigin::Cli,
- with_autonomous_iter_cap(TASK_RUN_MAX_ITERATIONS, agent.run_single(prompt)),
- ),
+ let run = crate::agent::turn_origin::with_origin(
+ crate::agent::turn_origin::AgentTurnOrigin::Cli,
+ with_autonomous_iter_cap(TASK_RUN_MAX_ITERATIONS, agent.run_single(prompt)),
);
let result = run.await.map_err(|e| format!("{e:#}"));
diff --git a/crates/openhuman-core/src/agent/task_dispatcher/types.rs b/crates/openhuman-core/src/agent/task_dispatcher/types.rs
index 6b78f22d52..fe24fdaa2c 100644
--- a/crates/openhuman-core/src/agent/task_dispatcher/types.rs
+++ b/crates/openhuman-core/src/agent/task_dispatcher/types.rs
@@ -17,18 +17,12 @@ use crate::agent::todos::ops::BoardLocation;
pub(super) type ActiveRun = tinyagents_graph::todos::dispatch::ActiveRun<BoardLocation>;
/// A resolved executor: which built-in agent definition to build, an optional
-/// system-prompt suffix carrying a personality identity or skill guidelines,
-/// the resolved agent profile (when the handle is a personality) so its
-/// per-profile allowlists are enforced, and a label for logs/telemetry.
+/// system-prompt suffix carrying skill guidelines, and a label for
+/// logs/telemetry.
#[derive(Debug, Clone, PartialEq)]
pub(super) struct ResolvedExecutor {
pub(super) agent_id: String,
pub(super) prompt_suffix: Option<String>,
- /// The resolved profile for personality executors. `None` for skill /
- /// built-in / default executors → unrestricted (legacy behaviour). When
- /// present, the autonomous run applies the profile's tool/skill/MCP/
- /// connector and memory-source gates, not just its SOUL/MEMORY text.
- pub(super) profile: Option<crate::agent::profiles::AgentProfile>,
pub(super) label: String,
}
@@ -37,7 +31,6 @@ impl ResolvedExecutor {
Self {
agent_id: "orchestrator".to_string(),
prompt_suffix: None,
- profile: None,
label: "default".to_string(),
}
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
index fde3e59a12..5027426ab1 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
@@ -20,9 +20,7 @@ use crate::agent::orchestration::tools::{
use crate::agent::tinyagents::host::OpenHumanRunContext;
use crate::agent::tinyagents::tools::{CanonicalSharedToolAdapter, EarlyExitHook};
use crate::agent::tinyagents::turn_policy::is_subagent_spawn_or_delegate_tool;
-use crate::agent::tools::{
- DelegateToPersonalityDispatch, DelegateToolDispatch, TodoToolDispatch, UpdateTaskDispatch,
-};
+use crate::agent::tools::{DelegateToolDispatch, TodoToolDispatch, UpdateTaskDispatch};
/// Register every admitted tool from `tool_sets` onto `harness` (and its
/// `capability_registry` projection), project the visible agent set as
@@ -127,10 +125,6 @@ pub(super) fn register_turn_tools_and_agents(
harness.register_tool_dispatch(Arc::new(AgentPrepareContextDispatch::new(
adapter,
)));
- } else if name == "delegate_to_personality" {
- harness.register_tool_dispatch(Arc::new(DelegateToPersonalityDispatch::new(
- adapter,
- )));
} else if name == "delegate_graph" {
harness.register_tool_dispatch(Arc::new(DelegateGraphDispatch::new(adapter)));
} else if name == "delegate" {
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rs b/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rs
index 6f251aee0e..e573e14745 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rs
@@ -10,9 +10,6 @@
//! user-authored fallback
//! ([`crate::agent::registry::find_custom_in_config`] →
//! [`crate::agent::registry::definition_from_registry_entry`]).
-//! * [`crate::agent::profiles::AgentProfile`] — the active personality,
-//! whose `allowed_tools` list is a **restriction** on the resolved
-//! definition's tool surface.
//!
//! This is `docs/specs/plan-agents.md` Phase 4. The crate-side
//! [`AgentDefinition`] is inert (`serde` + `std`); OpenHuman's harness
@@ -79,25 +76,14 @@ use async_trait::async_trait;
use tinyagents_definition::Result;
use tinyagents_definition::{AgentDefinition, DefinitionRegistry};
+use crate::agent::harness::definition::NO_TOOLS_SENTINEL;
use crate::agent::harness::definition::{
AgentDefinition as HostAgentDefinition, AgentDefinitionRegistry, AgentTier, ModelSpec,
SubagentEntry, ToolScope,
};
-use crate::agent::profiles::AgentProfile;
use crate::agent::registry::{definition_from_registry_entry, find_custom_in_config};
use crate::config::Config;
-/// Sentinel inserted when a profile allowlist and a definition's named scope
-/// are disjoint.
-///
-/// Was a verbatim copy of the session builder's own literal, with a comment
-/// saying so. Two spellings of one sentinel is a silent bug waiting for
-/// someone to change one of them: the sets would stop agreeing about what
-/// "no tools" is spelled as, and the disagreement surfaces as an agent quietly
-/// advertising the whole registry. It is one constant now — see
-/// [`NO_TOOLS_SENTINEL`] for why the value exists at all.
-use crate::agent::harness::definition::NO_TOOLS_SENTINEL as PROFILE_NO_TOOLS_SENTINEL;
-
// ── Registry handle ───────────────────────────────────────────────────────────
/// Where this adapter reads harness definitions from.
@@ -138,9 +124,8 @@ impl std::fmt::Debug for RegistryHandle {
/// [`DefinitionRegistry`] seam.
///
/// Read-only by construction: it borrows the harness registry, an optional
-/// [`Config`] (for the user-authored custom-agent fallback), and an optional
-/// active [`AgentProfile`] (for the tool restriction), and never mutates any of
-/// them. That matches the trait's rationale — a catalogue the runtime could
+/// [`Config`] (for the user-authored custom-agent fallback), and never mutates
+/// either. That matches the trait's rationale — a catalogue the runtime could
/// mutate would let a turn grant itself a delegate or a tool.
#[derive(Debug)]
pub struct OpenHumanDefinitionRegistry {
@@ -150,9 +135,6 @@ pub struct OpenHumanDefinitionRegistry {
/// absent, custom config agents are simply not in the catalogue — an
/// honest miss, never an error.
config: Option<Arc<Config>>,
- /// Active personality. Its `allowed_tools` narrows every projected tool
- /// list, exactly as the session builder narrows the visible tool set.
- profile: Option<Arc<AgentProfile>>,
/// Every tool name registered for this session, used to materialize a
/// [`ToolScope::Wildcard`] definition that also carries a denylist.
///
@@ -164,7 +146,7 @@ pub struct OpenHumanDefinitionRegistry {
registered_tools: Option<Arc<Vec<String>>>,
}
-/// Outcome of resolving a definition's own scope, before the profile allowlist.
+/// Outcome of resolving a definition's own scope.
///
/// Modelled explicitly because the crate's `Vec<String>` overloads *empty* to
/// mean "unrestricted". Inferring wildcard from emptiness is what let a
@@ -183,7 +165,6 @@ impl OpenHumanDefinitionRegistry {
Self {
registry: RegistryHandle::Shared(registry),
config: None,
- profile: None,
registered_tools: None,
}
}
@@ -198,7 +179,6 @@ impl OpenHumanDefinitionRegistry {
AgentDefinitionRegistry::global().map(|registry| Self {
registry: RegistryHandle::Global(registry),
config: None,
- profile: None,
registered_tools: None,
})
}
@@ -215,13 +195,6 @@ impl OpenHumanDefinitionRegistry {
self
}
- /// Attaches the active personality whose `allowed_tools` restricts every
- /// projected tool list.
- pub fn with_profile(mut self, profile: Arc<AgentProfile>) -> Self {
- self.profile = Some(profile);
- self
- }
-
/// Attaches the session's registered tool names.
///
/// Required to project a [`ToolScope::Wildcard`] definition that also
@@ -298,47 +271,13 @@ impl OpenHumanDefinitionRegistry {
}
}
- /// Tool names for `def`, after the definition's own denylist and the active
- /// profile's allowlist.
- ///
- /// Both filters mirror the session builder rather than reinventing policy:
- /// a profile's tool selection is *a restriction on the resolved definition,
- /// never a replacement for it*.
+ /// Tool names for `def`, after the definition's own denylist.
fn tools_for(&self, def: &HostAgentDefinition) -> Vec<String> {
- let scope = self.resolved_scope(def);
-
- let Some(allowed) = self
- .profile
- .as_deref()
- .and_then(|profile| profile.allowed_tools.as_ref())
- .filter(|tools| !tools.is_empty())
- else {
- return Self::emit(scope);
- };
-
- let profile_visible: Vec<String> = allowed
- .iter()
- .map(|tool| tool.trim().to_string())
- .filter(|tool| !tool.is_empty())
- .collect();
- if profile_visible.is_empty() {
- return Self::emit(scope);
- }
-
- let mut names = match scope {
- // A true wildcard has no denylist left to honour (see
- // `resolved_scope`), so the profile allowlist *is* the visible set.
- ResolvedScope::Wildcard => return profile_visible,
- ResolvedScope::Named(names) => names,
- };
-
- let allowed_set: HashSet<&str> = profile_visible.iter().map(String::as_str).collect();
- names.retain(|name| allowed_set.contains(name.as_str()));
- Self::emit(ResolvedScope::Named(names))
+ Self::emit(self.resolved_scope(def))
}
/// Resolves the definition's own scope, applying `extra_tools` and the
- /// denylist, without consulting the profile.
+ /// denylist.
fn resolved_scope(&self, def: &HostAgentDefinition) -> ResolvedScope {
match &def.tools {
ToolScope::Named(named) => {
@@ -397,7 +336,7 @@ impl OpenHumanDefinitionRegistry {
match scope {
ResolvedScope::Wildcard => Vec::new(),
ResolvedScope::Named(mut names) if names.is_empty() => {
- names.push(PROFILE_NO_TOOLS_SENTINEL.to_string());
+ names.push(NO_TOOLS_SENTINEL.to_string());
names
}
ResolvedScope::Named(names) => names,
diff --git a/crates/openhuman-core/src/agent/tools.rs b/crates/openhuman-core/src/agent/tools.rs
index 3008b6cf6e..b12d0a1588 100644
--- a/crates/openhuman-core/src/agent/tools.rs
+++ b/crates/openhuman-core/src/agent/tools.rs
@@ -8,8 +8,7 @@
//! question as its output; the turn actually pauses only because callers
//! list this name in the harness seam's `early_exit_tools`.
//! - [`DelegateTool`] — hands a subtask to a named agent with its own
-//! provider/model configuration. [`DelegateToPersonalityTool`] does the
-//! same for a named personality.
+//! provider/model configuration.
//! - [`PlanExitTool`] — ends a plan-mode pass by returning the plan plus
//! [`PLAN_EXIT_MARKER`]. The mode switch itself lives outside the tool;
//! nothing in this crate consumes the marker yet.
@@ -30,7 +29,6 @@
//! tools into the catalog.
mod ask_clarification;
mod delegate;
-mod delegate_to_personality;
mod plan_exit;
pub mod remember_preference;
// Pure `skill_runtime` client (spawn + await a workflow run) — compiled out
@@ -45,8 +43,6 @@ mod update_task;
pub use ask_clarification::AskClarificationTool;
pub use delegate::DelegateTool;
pub(crate) use delegate::DelegateToolDispatch;
-pub(crate) use delegate_to_personality::DelegateToPersonalityDispatch;
-pub use delegate_to_personality::DelegateToPersonalityTool;
pub use plan_exit::{PlanExitTool, PLAN_EXIT_MARKER};
pub use remember_preference::RememberPreferenceTool;
#[cfg(feature = "skills")]
diff --git a/crates/openhuman-core/src/agent/tools/delegate_to_personality.rs b/crates/openhuman-core/src/agent/tools/delegate_to_personality.rs
deleted file mode 100644
index b713843231..0000000000
--- a/crates/openhuman-core/src/agent/tools/delegate_to_personality.rs
+++ /dev/null
@@ -1,328 +0,0 @@
-//! Tool: `delegate_to_personality` — delegate a task to a personality-specific agent.
-
-use crate::agent::harness::definition::AgentDefinitionRegistry;
-use crate::agent::harness::subagent_runner::{run_subagent, SubagentRunOptions};
-use crate::agent::profiles::AgentProfileStore;
-use crate::agent::profiles::PersonalityContext;
-use async_trait::async_trait;
-use serde_json::json;
-use std::sync::Arc;
-use tinyagents_harness::context::RunContext;
-use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};
-use tinytools::ToolRunContext;
-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult};
-
-pub struct DelegateToPersonalityTool;
-
-/// Typed harness dispatch for personality delegation.
-pub(crate) struct DelegateToPersonalityDispatch {
- tool: Arc<dyn Tool>,
-}
-
-impl DelegateToPersonalityDispatch {
- pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {
- Self { tool }
- }
-}
-
-#[async_trait]
-impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>
- for DelegateToPersonalityDispatch
-{
- fn tool(&self) -> Arc<dyn Tool> {
- self.tool.clone()
- }
-
- async fn execute(
- &self,
- _state: &(),
- arguments: serde_json::Value,
- _options: ToolCallOptions,
- parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
- ) -> anyhow::Result<ToolResult> {
- let context = ToolExecutionContext::from_run_context(parent);
- execute_delegate_to_personality(arguments, Some(&context), parent.data.child()).await
- }
-}
-
-impl Default for DelegateToPersonalityTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl DelegateToPersonalityTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl Tool for DelegateToPersonalityTool {
- fn name(&self) -> &str {
- "delegate_to_personality"
- }
-
- fn description(&self) -> &str {
- "Delegate a task to another personality agent. Each personality has its own \
- memory, identity (SOUL.md), and integration access. Use when the task aligns \
- with a specific personality's expertise or context. The personality roster \
- in the system prompt lists available personalities."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "required": ["personality_id", "prompt"],
- "properties": {
- "personality_id": {
- "type": "string",
- "description": "The profile id of the target personality (from the personality roster)."
- },
- "prompt": {
- "type": "string",
- "description": "Clear, specific instruction for the personality agent. Include all context needed — the personality has its own memory but no awareness of the current conversation."
- },
- "context": {
- "type": "string",
- "description": "Optional context blob from prior task results."
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Execute
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_context(args, ToolCallOptions::default(), None)
- .await
- }
-
- async fn execute_with_context(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- tool_context: Option<&dyn ToolRunContext>,
- ) -> anyhow::Result<ToolResult> {
- let mut run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new();
- run_context.thread_id = tool_context
- .and_then(ToolRunContext::thread_id)
- .map(ToOwned::to_owned);
- execute_delegate_to_personality(args, tool_context, run_context).await
- }
-}
-
-/// Execute personality delegation with an explicit child run carrier.
-pub(crate) async fn execute_delegate_to_personality(
- args: serde_json::Value,
- tool_context: Option<&dyn ToolRunContext>,
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
-) -> anyhow::Result<ToolResult> {
- let personality_id = args
- .get("personality_id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
-
- let prompt = args
- .get("prompt")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
-
- let context = args
- .get("context")
- .and_then(|v| v.as_str())
- .map(|s| s.to_string());
-
- if personality_id.is_empty() {
- return Ok(ToolResult::error(
- "delegate_to_personality: `personality_id` is required.",
- ));
- }
- if prompt.is_empty() {
- return Ok(ToolResult::error(
- "delegate_to_personality: `prompt` is required.",
- ));
- }
-
- let parent_ctx = match run_context.parent.clone() {
- Some(ctx) => ctx,
- None => {
- return Ok(ToolResult::error(
- "delegate_to_personality: no parent execution context available.",
- ));
- }
- };
-
- tracing::debug!(
- personality_id = %personality_id,
- "[delegate_to_personality] resolving personality profile"
- );
-
- let store = AgentProfileStore::new(parent_ctx.workspace_dir.clone());
-
- // Guard: only the master personality may delegate. This prevents a
- // delegated sub-agent from recursing back through this tool — there is
- // no built-in depth counter on cross-personality delegation, so we gate
- // at the entry point.
- let (state, active_profile) = match store.resolve(None) {
- Ok(result) => result,
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "delegate_to_personality: failed to resolve active profile: {e}"
- )));
- }
- };
- if !active_profile.is_master {
- tracing::debug!(
- active_profile_id = %active_profile.id,
- "[delegate_to_personality] rejected — caller is not the master personality"
- );
- return Ok(ToolResult::error(format!(
- "delegate_to_personality: only the master personality may delegate \
- (active='{}', is_master=false).",
- active_profile.id
- )));
- }
-
- // Reuse the state already loaded above — no second store.resolve() call needed.
- let profile = match state.profiles.iter().find(|p| p.id == personality_id) {
- Some(p) => p.clone(),
- None => {
- tracing::debug!(
- personality_id = %personality_id,
- "[delegate_to_personality] profile resolve failed"
- );
- return Ok(ToolResult::error(format!(
- "delegate_to_personality: personality '{personality_id}' not found."
- )));
- }
- };
-
- let personality_ctx =
- PersonalityContext::from_profile(&parent_ctx.workspace_dir, profile.clone());
-
- tracing::debug!(
- personality_id = %personality_id,
- agent_id = %profile.agent_id,
- memory_suffix = %personality_ctx.memory_suffix,
- "[delegate_to_personality] personality resolved, delegating"
- );
-
- // TODO(phase-2): Memory isolation not yet enforced during delegation.
- // The personality gets its own SQLite DB (plumbing exists in
- // UnifiedMemory::new_with_memory_dir), but run_subagent currently
- // receives the parent's memory instance. To fix: construct a new
- // UnifiedMemory using personality_ctx.memory_suffix and pass it through
- // SubagentRunOptions (needs an additional field there).
- // Also: composio_integrations allowlist is not yet filtered during
- // delegation — personality_ctx.composio_allowlist exists but is not
- // applied to the SubagentRunOptions toolkit_override.
- //
- // Until these are wired, the sub-agent gets the personality's
- // voice/identity at the prompt level but still writes to the parent's
- // memory store and has access to all parent integrations.
- let mut personality_preamble = format!(
- "You are acting as the personality `{}` (\"{}\"). {}",
- profile.id, profile.name, profile.description
- );
- if let Some(ref soul) = personality_ctx.soul_md_override {
- let soul_truncated: String = soul.chars().take(800).collect();
- personality_preamble.push_str("\n\n[Personality SOUL.md]\n");
- personality_preamble.push_str(&soul_truncated);
- }
- if let Some(ref mem) = personality_ctx.memory_md_override {
- let mem_truncated: String = mem.chars().take(800).collect();
- personality_preamble.push_str("\n\n[Personality MEMORY.md]\n");
- personality_preamble.push_str(&mem_truncated);
- }
- let combined_context = match context.as_deref() {
- Some(ctx_str) => format!("{personality_preamble}\n\n[Caller Context]\n{ctx_str}"),
- None => personality_preamble,
- };
-
- // Look up the agent definition for this personality's agent_id
- let registry = match AgentDefinitionRegistry::global() {
- Some(reg) => reg,
- None => {
- return Ok(ToolResult::error(
- "delegate_to_personality: agent definition registry not initialized.",
- ));
- }
- };
-
- let definition = match registry.get(&profile.agent_id) {
- Some(def) => def,
- None => {
- return Ok(ToolResult::error(format!(
- "delegate_to_personality: agent definition '{}' not found in registry.",
- profile.agent_id
- )));
- }
- };
-
- let workspace_descriptor = tool_context
- .and_then(|ctx| ctx.workspace().cloned())
- .or_else(|| run_context.workspace.clone());
- let worktree_action_dir = workspace_descriptor
- .as_ref()
- .map(|descriptor| descriptor.root.clone());
- if let Some(descriptor) = workspace_descriptor.as_ref() {
- tracing::debug!(
- personality_id = %personality_id,
- workspace_root = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- "[delegate_to_personality] using ToolExecutionContext workspace root"
- );
- }
-
- let options = SubagentRunOptions {
- context: Some(combined_context),
- model_override: profile.model_override.clone(),
- toolkit_override: None,
- skill_filter_override: None,
- task_id: None,
- thread_id: tool_context
- .and_then(ToolRunContext::thread_id)
- .or(run_context.thread_id.as_deref())
- .map(str::to_owned),
- run_context,
- worker_thread_id: None,
- initial_history: None,
- checkpoint_dir: None,
- worktree_action_dir,
- workspace_descriptor,
- run_queue: None,
- };
-
- match run_subagent(definition, &prompt, options).await {
- Ok(outcome) => {
- tracing::debug!(
- personality_id = %personality_id,
- iterations = outcome.iterations,
- elapsed_ms = outcome.elapsed.as_millis(),
- "[delegate_to_personality] delegation completed"
- );
- Ok(ToolResult::success(format!(
- "[Personality: {}]\n{}",
- profile.name, outcome.output
- )))
- }
- Err(e) => {
- tracing::debug!(
- personality_id = %personality_id,
- error = %e,
- "[delegate_to_personality] delegation failed"
- );
- Ok(ToolResult::error(format!(
- "delegate_to_personality failed for '{}': {e}",
- personality_id
- )))
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/tools/run_workflow.rs b/crates/openhuman-core/src/agent/tools/run_workflow.rs
index 098ad2f22d..6ca6a5fc82 100644
--- a/crates/openhuman-core/src/agent/tools/run_workflow.rs
+++ b/crates/openhuman-core/src/agent/tools/run_workflow.rs
@@ -33,7 +33,7 @@
use async_trait::async_trait;
use serde_json::json;
-use crate::skills::runtime::{await_run_outcome, spawn_workflow_run_background_with_profile};
+use crate::skills::runtime::{await_run_outcome, spawn_workflow_run_background};
use crate::skills::schemas::resolve_workspace_dir;
use tinytools::{PermissionLevel, Tool, ToolResult};
@@ -207,17 +207,7 @@ fn outcome_to_result(
/// `run_workflow` — orchestrator-callable spawn + inline await of another
/// workflow.
-pub struct RunWorkflowTool {
- /// Full active profile context inherited by the autonomous workflow agent.
- active_profile: Option<crate::agent::profiles::AgentProfile>,
- /// Per-profile allowlist of runnable workflow `dir_name` slugs. `None`
- /// (the default) means every installed workflow may be run.
- skill_allowlist: Option<std::collections::HashSet<String>>,
- /// Active profile's private skills root
- /// (`<workspace>/personalities/<id>/skills/`). Resolves + implicitly allows
- /// the owner's profile-local skills. `None` = byte-identical to today.
- profile_skills_root: Option<std::path::PathBuf>,
-}
+pub struct RunWorkflowTool;
impl Default for RunWorkflowTool {
fn default() -> Self {
@@ -227,35 +217,7 @@ impl Default for RunWorkflowTool {
impl RunWorkflowTool {
pub fn new() -> Self {
- Self {
- active_profile: None,
- skill_allowlist: None,
- profile_skills_root: None,
- }
- }
-
- pub fn with_active_profile(
- mut self,
- profile: Option<crate::agent::profiles::AgentProfile>,
- ) -> Self {
- self.active_profile = profile;
- self
- }
-
- /// Restrict which workflows this tool may run to a per-profile allowlist.
- pub fn with_skill_allowlist(
- mut self,
- allowlist: Option<std::collections::HashSet<String>>,
- ) -> Self {
- self.skill_allowlist = allowlist;
- self
- }
-
- /// Resolve (and implicitly allow) the active profile's private skills so a
- /// turn under profile P can run P's own skills.
- pub fn with_profile_skills_root(mut self, root: Option<std::path::PathBuf>) -> Self {
- self.profile_skills_root = root;
- self
+ Self
}
}
@@ -330,32 +292,13 @@ impl Tool for RunWorkflowTool {
));
}
};
- if let Some(allow) = &self.skill_allowlist {
- // Profile-local skills are implicitly allowed for their owner (they
- // bypass `allowed_skills`), mirroring `list_workflows`.
- let profile_local =
- crate::skills::profile_local_skill_ids(self.profile_skills_root.as_deref());
- if !profile_local.contains(&workflow_id) && !allow.contains(&workflow_id) {
- log::debug!("[profiles] run_workflow blocked by profile allowlist: {workflow_id}");
- return Ok(ToolResult::error(format!(
- "run_workflow: workflow `{workflow_id}` is not available to the active agent profile"
- )));
- }
- }
let inputs = args.get("inputs").cloned();
let wait_seconds = parse_wait_seconds(&args);
// Fire-and-forget: only the spawn backstop applies — no await, so no
// re-entrancy/nesting slot to take.
if wait_seconds == 0 {
- return match spawn_workflow_run_background_with_profile(
- workflow_id.clone(),
- inputs,
- self.profile_skills_root.clone(),
- self.active_profile.clone(),
- )
- .await
- {
+ return match spawn_workflow_run_background(workflow_id.clone(), inputs).await {
// Count only spawns that actually start against the backstop —
// unknown-workflow / bad-input rejections (the Err arm) must not
// burn the budget, or rejected calls accumulate and trip the
@@ -389,14 +332,7 @@ impl Tool for RunWorkflowTool {
Err(e) => return Ok(ToolResult::error(format!("run_workflow: {e}"))),
};
- let started = match spawn_workflow_run_background_with_profile(
- workflow_id.clone(),
- inputs,
- self.profile_skills_root.clone(),
- self.active_profile.clone(),
- )
- .await
- {
+ let started = match spawn_workflow_run_background(workflow_id.clone(), inputs).await {
Ok(s) => {
if let Err(e) = guard::account_spawn() {
return Ok(ToolResult::error(format!("run_workflow: {e}")));
@@ -426,11 +362,7 @@ impl Tool for RunWorkflowTool {
}
/// `await_workflow` — re-attach to a detached run by `run_id` and wait.
-pub struct AwaitWorkflowTool {
- active_profile_id: Option<String>,
- skill_allowlist: Option<std::collections::HashSet<String>>,
- profile_skills_root: Option<std::path::PathBuf>,
-}
+pub struct AwaitWorkflowTool;
impl Default for AwaitWorkflowTool {
fn default() -> Self {
@@ -440,44 +372,8 @@ impl Default for AwaitWorkflowTool {
impl AwaitWorkflowTool {
pub fn new() -> Self {
- Self {
- active_profile_id: None,
- skill_allowlist: None,
- profile_skills_root: None,
- }
+ Self
}
-
- pub fn with_active_profile(
- mut self,
- profile: Option<crate::agent::profiles::AgentProfile>,
- ) -> Self {
- self.active_profile_id = profile.map(|profile| profile.id);
- self
- }
-
- pub fn with_skill_allowlist(
- mut self,
- allowlist: Option<std::collections::HashSet<String>>,
- ) -> Self {
- self.skill_allowlist = allowlist;
- self
- }
-
- pub fn with_profile_skills_root(mut self, root: Option<std::path::PathBuf>) -> Self {
- self.profile_skills_root = root;
- self
- }
-}
-
-fn run_visible_to_profile(
- run: &crate::skills::run_log::ScannedRun,
- active_profile_id: Option<&str>,
- skill_allowlist: Option<&std::collections::HashSet<String>>,
- profile_local_ids: &std::collections::HashSet<String>,
-) -> bool {
- run.profile_id.as_deref() == active_profile_id
- && (profile_local_ids.contains(&run.workflow_id)
- || skill_allowlist.is_none_or(|allowlist| allowlist.contains(&run.workflow_id)))
}
#[async_trait]
@@ -528,19 +424,9 @@ impl Tool for AwaitWorkflowTool {
let wait_seconds = parse_wait_seconds(&args);
let workspace = resolve_workspace_dir().await;
- let profile_local_ids =
- crate::skills::profile_local_skill_ids(self.profile_skills_root.as_deref());
let visible_run = crate::skills::run_log::scan_runs(&workspace, None, usize::MAX)
.into_iter()
- .find(|run| {
- run.run_id == run_id
- && run_visible_to_profile(
- run,
- self.active_profile_id.as_deref(),
- self.skill_allowlist.as_ref(),
- &profile_local_ids,
- )
- });
+ .find(|run| run.run_id == run_id);
let Some(visible_run) = visible_run else {
return Ok(ToolResult::error(format!(
"await_workflow: no run found for run_id `{run_id}` (it may not exist, is not \
diff --git a/crates/openhuman-core/src/channels/system_prompt.rs b/crates/openhuman-core/src/channels/system_prompt.rs
index f66603ab63..e567bcf8fa 100644
--- a/crates/openhuman-core/src/channels/system_prompt.rs
+++ b/crates/openhuman-core/src/channels/system_prompt.rs
@@ -26,20 +26,13 @@ use crate::agent::context::channels_prompt::{
build_system_prompt_with_identity, render_project_context, ProjectContextPlacement,
PromptIdentityOverride,
};
-use crate::agent::profiles::{self, AgentProfile, AgentProfileStore, DEFAULT_PROFILE_ID};
use crate::skills::Workflow;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
-use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::UNIX_EPOCH;
-/// The file `AgentProfileStore` persists the active profile id in
-/// (`<workspace>/agent_profiles.json`, see `profiles/store.rs`). Watched so a
-/// profile switch made in the desktop UI reaches the next channel turn.
-const AGENT_PROFILES_FILE: &str = "agent_profiles.json";
-
/// Workspace-root files `build_system_prompt` inlines.
const ROOT_IDENTITY_FILES: [&str; 4] = ["SOUL.md", "IDENTITY.md", "PROFILE.md", "MEMORY.md"];
@@ -60,53 +53,17 @@ pub(crate) struct ChannelPromptInputs {
/// The identity one render was produced from.
#[derive(Debug, Clone, PartialEq, Eq)]
-pub(crate) struct ChannelIdentity {
- pub(crate) profile_id: String,
- /// The profile's own soul, replacing root `SOUL.md`; `None` renders the root file.
- pub(crate) soul_md: Option<String>,
- /// The profile's own memory, replacing root `MEMORY.md`; `None` renders the root file.
- pub(crate) memory_md: Option<String>,
- /// The workspace file the profile's `soul_md_path` resolves to (safe,
- /// absolute — see `profiles::paths::soul_md_file_path`); watched by the
- /// fingerprint so edits to it are picked up too.
- pub(crate) soul_md_path: Option<PathBuf>,
- /// The profile's `system_prompt_suffix`, rendered as the same
- /// `## Agent profile` block desktop chat appends (trimmed, non-empty).
- pub(crate) prompt_suffix: Option<String>,
-}
+pub(crate) struct ChannelIdentity {}
impl ChannelIdentity {
/// The identity a workspace has with no usable profile store: the root files.
fn root() -> Self {
- Self {
- profile_id: DEFAULT_PROFILE_ID.to_string(),
- soul_md: None,
- memory_md: None,
- soul_md_path: None,
- prompt_suffix: None,
- }
- }
-
- fn for_profile(workspace_dir: &Path, profile: &AgentProfile) -> Self {
- Self {
- profile_id: profile.id.clone(),
- soul_md: profiles::paths::resolve_personality_soul(workspace_dir, profile),
- memory_md: profiles::paths::resolve_personality_memory_md(workspace_dir, profile),
- soul_md_path: profiles::paths::soul_md_file_path(workspace_dir, profile),
- prompt_suffix: profile
- .system_prompt_suffix
- .as_deref()
- .map(str::trim)
- .filter(|suffix| !suffix.is_empty())
- .map(str::to_string),
- }
+ Self {}
}
}
struct PromptState {
fingerprint: u64,
- profile_id: String,
- soul_md_path: Option<PathBuf>,
rendered: Arc<String>,
}
@@ -114,10 +71,6 @@ struct PromptState {
pub(crate) struct RefreshingInner {
inputs: ChannelPromptInputs,
state: Mutex<PromptState>,
- /// An unreadable profile store is reported once per runtime, not once
- /// per message: the fallback is the root identity, which is what the
- /// runtime rendered before profiles existed.
- store_warned: AtomicBool,
}
/// The system prompt a channel turn is seeded with.
@@ -144,7 +97,6 @@ impl std::fmt::Debug for ChannelSystemPrompt {
let state = inner.state.lock().unwrap_or_else(|e| e.into_inner());
f.debug_struct("ChannelSystemPrompt::Refreshing")
.field("workspace_dir", &inner.inputs.workspace_dir)
- .field("profile_id", &state.profile_id)
.field("chars", &state.rendered.chars().count())
.finish()
}
@@ -162,24 +114,16 @@ impl ChannelSystemPrompt {
/// needs a prompt before the first message — and keeps `inputs` to
/// re-render when the identity changes.
pub(crate) fn refreshing(inputs: ChannelPromptInputs) -> Self {
- let store_warned = AtomicBool::new(false);
- let identity = resolve_channel_identity_once(&inputs.workspace_dir, &store_warned);
- let fingerprint = identity_fingerprint(
- &inputs.workspace_dir,
- &identity.profile_id,
- identity.soul_md_path.as_deref(),
- );
+ let identity = ChannelIdentity::root();
+ let fingerprint = identity_fingerprint(&inputs.workspace_dir);
let rendered = Arc::new(render(&inputs, &identity));
log_render(&inputs.workspace_dir, &identity, &rendered, "boot");
Self::Refreshing(Arc::new(RefreshingInner {
inputs,
state: Mutex::new(PromptState {
fingerprint,
- profile_id: identity.profile_id,
- soul_md_path: identity.soul_md_path,
rendered,
}),
- store_warned,
}))
}
@@ -199,84 +143,35 @@ impl RefreshingInner {
fn current(&self) -> Arc<String> {
let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
let workspace_dir = &self.inputs.workspace_dir;
- let observed = identity_fingerprint(
- workspace_dir,
- &state.profile_id,
- state.soul_md_path.as_deref(),
- );
+ let observed = identity_fingerprint(workspace_dir);
if observed == state.fingerprint {
return Arc::clone(&state.rendered);
}
tracing::debug!(
target: "openhuman::channels",
- profile_id = %state.profile_id,
"[channels][prompt] identity fingerprint changed; re-rendering system prompt"
);
- let identity = resolve_channel_identity_once(workspace_dir, &self.store_warned);
- // Fingerprint against the identity we just rendered — a profile
- // switch changes which files are watched, and pinning the old set
- // would re-render on every message that follows.
- let fingerprint = identity_fingerprint(
- workspace_dir,
- &identity.profile_id,
- identity.soul_md_path.as_deref(),
- );
+ let identity = ChannelIdentity::root();
+ let fingerprint = identity_fingerprint(workspace_dir);
let rendered = Arc::new(render(&self.inputs, &identity));
log_render(workspace_dir, &identity, &rendered, "refresh");
*state = PromptState {
fingerprint,
- profile_id: identity.profile_id,
- soul_md_path: identity.soul_md_path,
rendered: Arc::clone(&rendered),
};
rendered
}
}
-/// Resolves the active profile the way desktop chat does per turn
-/// (`AgentProfileStore::resolve(None)` → active id → built-in default), then
-/// the profile's soul and memory. A store that cannot be read is a warning
-/// (once per `warned` flag) and the root identity — a channel runtime must
-/// come up regardless.
-fn resolve_channel_identity_once(workspace_dir: &Path, warned: &AtomicBool) -> ChannelIdentity {
- match AgentProfileStore::new(workspace_dir.to_path_buf()).resolve(None) {
- Ok((_state, profile)) => {
- warned.store(false, Ordering::Relaxed);
- ChannelIdentity::for_profile(workspace_dir, &profile)
- }
- Err(error) => {
- if !warned.swap(true, Ordering::Relaxed) {
- tracing::warn!(
- target: "openhuman::channels",
- error = %error,
- "[channels][prompt] agent profile store unreadable; rendering the workspace-root identity"
- );
- }
- ChannelIdentity::root()
- }
- }
-}
-
/// A hash of `(mtime, len)` for every file the identity is read from —
/// missing files hash distinctly from present ones, so a `MEMORY.md` the
/// archivist writes after boot flips it. Cheap enough to run per message.
-pub(crate) fn identity_fingerprint(
- workspace_dir: &Path,
- profile_id: &str,
- soul_md_path: Option<&Path>,
-) -> u64 {
+pub(crate) fn identity_fingerprint(workspace_dir: &Path) -> u64 {
let mut hasher = DefaultHasher::new();
- hash_file_stat(&mut hasher, &workspace_dir.join(AGENT_PROFILES_FILE));
for name in ROOT_IDENTITY_FILES {
hash_file_stat(&mut hasher, &workspace_dir.join(name));
}
- let home = profiles::home::profile_home(workspace_dir, profile_id);
- hash_file_stat(&mut hasher, &home.join("SOUL.md"));
- hash_file_stat(&mut hasher, &home.join("MEMORY.md"));
- if let Some(path) = soul_md_path {
- hash_file_stat(&mut hasher, path);
- }
hasher.finish()
}
@@ -303,8 +198,8 @@ fn render(inputs: &ChannelPromptInputs, identity: &ChannelIdentity) -> String {
.map(|(name, desc)| (name.as_str(), desc.as_str()))
.collect();
let identity_override = PromptIdentityOverride {
- soul_md: identity.soul_md.as_deref(),
- memory_md: identity.memory_md.as_deref(),
+ soul_md: None,
+ memory_md: None,
};
// `channel_name = None`: the runtime wires up several providers at once,
// so the capability block keeps its platform-agnostic phrasing.
@@ -329,15 +224,6 @@ fn render(inputs: &ChannelPromptInputs, identity: &ChannelIdentity) -> String {
inputs.bootstrap_max_chars,
identity_override,
);
- // The profile's own instructions come last, as the block desktop chat
- // renders through `AgentProfilePromptSection` (#6027: both paths agree).
- if let Some(suffix) = identity.prompt_suffix.as_deref() {
- ensure_blank_line(&mut prompt);
- prompt.push_str(&profiles::prompt_section::render_agent_profile_block(
- suffix, None,
- ));
- prompt.push_str("\n\n");
- }
prompt
}
@@ -356,29 +242,14 @@ fn ensure_blank_line(prompt: &mut String) {
/// Names the profile and which files were inlined — never their contents.
fn log_render(workspace_dir: &Path, identity: &ChannelIdentity, rendered: &str, reason: &str) {
- let soul = if identity.soul_md.is_some() {
- "profile"
- } else {
- "root"
- };
- let memory = if identity.memory_md.is_some() {
- "profile"
- } else if workspace_dir.join("MEMORY.md").is_file() {
+ let memory = if workspace_dir.join("MEMORY.md").is_file() {
"root"
} else {
"none"
};
- let suffix = if identity.prompt_suffix.is_some() {
- "profile"
- } else {
- "none"
- };
tracing::info!(
target: "openhuman::channels",
- profile_id = %identity.profile_id,
- soul,
memory,
- suffix,
chars = rendered.chars().count(),
reason,
"[channels][prompt] rendered system prompt"
diff --git a/crates/openhuman-core/src/core/all.rs b/crates/openhuman-core/src/core/all.rs
index 50794d5303..63546d1773 100644
--- a/crates/openhuman-core/src/core/all.rs
+++ b/crates/openhuman-core/src/core/all.rs
@@ -456,12 +456,6 @@ fn build_registered_controllers() -> Vec<GroupedController> {
DomainGroup::Agent,
crate::agent::tinyagents::replay::all_agent_replay_registered_controllers(),
);
- // Persistent agent profiles (flavours): name, soul, memory sources, skills, MCP, connectors.
- push(
- &mut controllers,
- DomainGroup::Agent,
- crate::agent::profiles::all_profiles_registered_controllers(),
- );
// User-facing agent registry: defaults, enablement, custom agents, tool policy.
push(
&mut controllers,
diff --git a/crates/openhuman-core/src/core/socketio.rs b/crates/openhuman-core/src/core/socketio.rs
index a19b8303f5..74e12d8e2d 100644
--- a/crates/openhuman-core/src/core/socketio.rs
+++ b/crates/openhuman-core/src/core/socketio.rs
@@ -471,8 +471,6 @@ struct ChatStartPayload {
#[serde(default)]
temperature: Option<f64>,
#[serde(default)]
- profile_id: Option<String>,
- #[serde(default)]
locale: Option<String>,
#[serde(default)]
queue_mode: Option<String>,
@@ -679,7 +677,6 @@ pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {
&payload.message,
model_override,
payload.temperature,
- payload.profile_id,
payload.locale,
payload.queue_mode,
crate::web_chat::ChatRequestMetadata::default(),
diff --git a/crates/openhuman-core/src/cron/scheduler/agent_run.rs b/crates/openhuman-core/src/cron/scheduler/agent_run.rs
index 36b223cde5..1fa2fde90a 100644
--- a/crates/openhuman-core/src/cron/scheduler/agent_run.rs
+++ b/crates/openhuman-core/src/cron/scheduler/agent_run.rs
@@ -232,114 +232,14 @@ pub(super) fn run_flow_schedule_job(job: &CronJob) -> (bool, String) {
/// no text. Never delivered to chat — used only for the run-history record.
pub(super) const EMPTY_AGENT_OUTPUT: &str = "agent job executed";
-/// Resolve the agent profile a cron job is attributed to, if any.
-///
-/// Returns `Some(profile)` only when `job.profile_id` is set AND that profile
-/// still exists in the store. A deleted profile yields `Ok(None)` so the caller
-/// runs the job without a profile rather than failing it (2b). Profile-store
-/// failures are returned: attribution must not fail open when the scheduler
-/// cannot determine whether the referenced profile still exists.
-pub(super) fn resolve_cron_profile(
- config: &Config,
- job: &CronJob,
-) -> anyhow::Result<Option<crate::agent::profiles::AgentProfile>> {
- let Some(profile_id) = job.profile_id.as_deref() else {
- return Ok(None);
- };
- match crate::agent::profiles::load_profiles(&config.workspace_dir) {
- Ok(state) => {
- let found = state.profiles.into_iter().find(|p| p.id == profile_id);
- if found.is_none() {
- tracing::warn!(
- job_id = %job.id,
- profile_id = %profile_id,
- "[cron] attributed profile no longer exists — running job without a profile"
- );
- }
- Ok(found)
- }
- Err(e) => Err(anyhow::anyhow!(
- "failed to load attributed profile {profile_id:?} for cron job {}: {e}",
- job.id
- )),
- }
-}
-
pub(super) struct BuiltCronAgent {
pub(crate) agent: Agent,
- pub(crate) profile: Option<crate::agent::profiles::AgentProfile>,
-}
-
-pub(super) fn apply_cron_profile_runtime_defaults(
- config: &Config,
- job: &CronJob,
- profile: &crate::agent::profiles::AgentProfile,
-) -> Config {
- let mut effective = config.clone();
- if let Some(model) = profile.model_override.clone() {
- effective.default_model = Some(model);
- }
- if let Some(temperature) = profile.temperature {
- effective.default_temperature = temperature;
- }
- // A job-level pin is the most specific model choice.
- if let Some(model) = job.model.clone() {
- effective.default_model = Some(model);
- }
- effective
}
pub(super) fn build_agent_for_cron_job(
config: &Config,
job: &CronJob,
) -> anyhow::Result<BuiltCronAgent> {
- // 2b — profile attribution. When the job names a profile that still exists,
- // build the run under it via the SAME profile-aware session path the task
- // dispatcher uses (`from_config_for_agent_with_profile`), so the run inherits
- // the profile's SOUL, memory scope, dedicated-workspace descriptor, and
- // tool/skill/MCP allowlists. A deleted profile falls through (warned in
- // `resolve_cron_profile`) to the profile-less path below.
- if let Some(profile) = resolve_cron_profile(config, job)? {
- // Apply the same profile runtime defaults as interactive chat. A
- // per-job model pin remains the most specific choice and therefore
- // wins over the profile model. The profile-aware builder consumes the
- // prompt suffix directly and gives profile temperature precedence over
- // the selected agent definition.
- let effective = apply_cron_profile_runtime_defaults(config, job, &profile);
- // A job may pin a built-in `agent_id`; otherwise the profile picks its
- // own agent definition.
- let agent_id = job
- .agent_id
- .clone()
- .unwrap_or_else(|| profile.agent_id.clone());
- let agent = Agent::from_config_for_agent_with_profile(
- &effective,
- &agent_id,
- profile.system_prompt_suffix.clone(),
- Some(&profile),
- )
- .inspect(|_| {
- tracing::debug!(
- job_id = %job.id,
- profile_id = %profile.id,
- agent_id = %agent_id,
- "[cron] built scheduled job agent under attributed profile"
- );
- })
- .map_err(|e| {
- anyhow::anyhow!(
- "failed to build cron job {} under attributed profile {:?} with agent {:?}: {e:#}",
- job.id,
- profile.id,
- agent_id
- )
- })?;
- return Ok(BuiltCronAgent {
- agent,
- profile: Some(profile),
- });
- }
-
if let Some(agent_id) = job.agent_id.as_deref() {
match Agent::from_config_for_agent(config, agent_id) {
Ok(agent) => {
@@ -348,10 +248,7 @@ pub(super) fn build_agent_for_cron_job(
agent_id = %agent_id,
"[cron] built scheduled job agent from definition"
);
- Ok(BuiltCronAgent {
- agent,
- profile: None,
- })
+ Ok(BuiltCronAgent { agent })
}
Err(e) => {
tracing::warn!(
@@ -360,16 +257,10 @@ pub(super) fn build_agent_for_cron_job(
error = %e,
"[cron] failed to build agent from definition; falling back to generic agent"
);
- Agent::from_config(config).map(|agent| BuiltCronAgent {
- agent,
- profile: None,
- })
+ Agent::from_config(config).map(|agent| BuiltCronAgent { agent })
}
}
} else {
- Agent::from_config(config).map(|agent| BuiltCronAgent {
- agent,
- profile: None,
- })
+ Agent::from_config(config).map(|agent| BuiltCronAgent { agent })
}
}
diff --git a/crates/openhuman-core/src/cron/scheduler_tests.rs b/crates/openhuman-core/src/cron/scheduler_tests.rs
index 382051e64c..c16f3d2a8f 100644
--- a/crates/openhuman-core/src/cron/scheduler_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler_tests.rs
@@ -41,7 +41,6 @@ fn test_job(command: &str) -> CronJob {
session_target: SessionTarget::Isolated,
model: None,
agent_id: None,
- profile_id: None,
enabled: true,
delivery: DeliveryConfig::default(),
delete_after_run: false,
diff --git a/crates/openhuman-core/src/cron/schemas.rs b/crates/openhuman-core/src/cron/schemas.rs
index 3a9ccababa..a9cc5b0423 100644
--- a/crates/openhuman-core/src/cron/schemas.rs
+++ b/crates/openhuman-core/src/cron/schemas.rs
@@ -116,13 +116,6 @@ pub fn schemas(function: &str) -> ControllerSchema {
comment: "Built-in agent or skill definition ID.",
required: false,
},
- FieldSchema {
- name: "profile_id",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Agent profile id to run the job under (soul, memory scope, \
- workspace, allowlists). Ignored if the profile is deleted.",
- required: false,
- },
FieldSchema {
name: "delivery",
ty: TypeSchema::Option(Box::new(TypeSchema::Ref("DeliveryConfig"))),
@@ -316,18 +309,6 @@ fn handle_add(params: Map<String, Value>) -> ControllerFuture {
.get("agent_id")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
- // 2b — optional agent-profile attribution. Snake_case `profile_id` matches
- // the existing cron wire convention (`agent_id`, `session_target`).
- let profile_id = params
- .get("profile_id")
- .and_then(|v| v.as_str())
- .map(|s| s.to_string());
- // Privacy-safe diagnostic: whether the created job carries profile
- // attribution, never the profile id itself.
- tracing::debug!(
- has_profile_attribution = profile_id.is_some(),
- "[cron][schemas] create: parsed agent-profile attribution"
- );
let delivery: Option<crate::cron::DeliveryConfig> = match params.get("delivery") {
None | Some(Value::Null) => None,
Some(v) => Some(
@@ -374,7 +355,6 @@ fn handle_add(params: Map<String, Value>) -> ControllerFuture {
agent_id,
// RPC-created jobs default to enabled (current behaviour).
true,
- profile_id,
)
.map_err(|e| e.to_string())?
}
@@ -397,19 +377,6 @@ fn handle_update(params: Map<String, Value>) -> ControllerFuture {
let config = config_rpc::load_config_with_timeout().await?;
let job_id = read_required::<String>(&params, "job_id")?;
let patch = read_required::<CronJobPatch>(&params, "patch")?;
- // Privacy-safe diagnostic for the profile-attribution patch. Double-option
- // `profile_id`: `None` = no change, `Some(None)` = clear, `Some(Some)` =
- // (re)attribute. Log only the state, never the profile id.
- let (patches_profile_attribution, clears_profile_attribution) = match &patch.profile_id {
- None => (false, false),
- Some(None) => (true, true),
- Some(Some(_)) => (true, false),
- };
- tracing::debug!(
- patches_profile_attribution,
- clears_profile_attribution,
- "[cron][schemas] update: parsed agent-profile attribution patch"
- );
to_json(crate::cron::rpc::cron_update(&config, job_id.trim(), patch).await?)
})
}
diff --git a/crates/openhuman-core/src/cron/store/jobs.rs b/crates/openhuman-core/src/cron/store/jobs.rs
index 9ababf4fce..89bd801be6 100644
--- a/crates/openhuman-core/src/cron/store/jobs.rs
+++ b/crates/openhuman-core/src/cron/store/jobs.rs
@@ -80,7 +80,6 @@ pub fn add_agent_job(
delete_after_run,
None,
true,
- None,
)
}
@@ -99,7 +98,6 @@ pub fn add_agent_job_with_definition(
delete_after_run: bool,
agent_id: Option<String>,
enabled: bool,
- profile_id: Option<String>,
) -> Result<CronJob> {
let now = Utc::now();
// Agent runs are inference turns: on top of the generic checks, refuse a
@@ -119,8 +117,8 @@ pub fn add_agent_job_with_definition(
conn.execute(
"INSERT INTO cron_jobs (
id, expression, command, schedule, job_type, prompt, name, session_target, model,
- enabled, delivery, delete_after_run, created_at, next_run, agent_id, profile_id
- ) VALUES (?1, ?2, '', ?3, 'agent', ?4, ?5, ?6, ?7, ?13, ?8, ?9, ?10, ?11, ?12, ?14)",
+ enabled, delivery, delete_after_run, created_at, next_run, agent_id
+ ) VALUES (?1, ?2, '', ?3, 'agent', ?4, ?5, ?6, ?7, ?13, ?8, ?9, ?10, ?11, ?12)",
params![
id,
expression,
@@ -135,7 +133,6 @@ pub fn add_agent_job_with_definition(
next_run.to_rfc3339(),
agent_id,
if enabled { 1 } else { 0 },
- profile_id,
],
)
.context("Failed to insert cron agent job")?;
@@ -225,7 +222,7 @@ pub fn find_flow_schedule_job(config: &Config, flow_id: &str) -> Result<Option<C
let mut stmt = conn.prepare(
"SELECT id, expression, command, schedule, job_type, prompt, name, session_target, model,
enabled, delivery, delete_after_run, created_at, next_run, last_run, last_status, last_output,
- agent_id, profile_id
+ agent_id
FROM cron_jobs WHERE job_type = 'flow' AND command = ?1 LIMIT 1",
)?;
let mut rows = stmt.query(params![flow_id])?;
@@ -241,7 +238,7 @@ pub fn list_jobs(config: &Config) -> Result<Vec<CronJob>> {
let mut stmt = conn.prepare(
"SELECT id, expression, command, schedule, job_type, prompt, name, session_target, model,
enabled, delivery, delete_after_run, created_at, next_run, last_run, last_status, last_output,
- agent_id, profile_id
+ agent_id
FROM cron_jobs ORDER BY next_run ASC",
)?;
@@ -260,7 +257,7 @@ pub fn get_job(config: &Config, job_id: &str) -> Result<CronJob> {
let mut stmt = conn.prepare(
"SELECT id, expression, command, schedule, job_type, prompt, name, session_target, model,
enabled, delivery, delete_after_run, created_at, next_run, last_run, last_status, last_output,
- agent_id, profile_id
+ agent_id
FROM cron_jobs WHERE id = ?1",
)?;
@@ -382,7 +379,7 @@ pub fn due_jobs(config: &Config, now: DateTime<Utc>) -> Result<Vec<CronJob>> {
let mut stmt = conn.prepare(
"SELECT id, expression, command, schedule, job_type, prompt, name, session_target, model,
enabled, delivery, delete_after_run, created_at, next_run, last_run, last_status, last_output,
- agent_id, profile_id
+ agent_id
FROM cron_jobs
WHERE enabled = 1 AND next_run <= ?1
ORDER BY next_run ASC
@@ -443,10 +440,6 @@ pub fn update_job(config: &Config, job_id: &str, patch: CronJobPatch) -> Result<
if let Some(agent_id) = patch.agent_id {
job.agent_id = agent_id;
}
- if let Some(profile_id) = patch.profile_id {
- job.profile_id = profile_id;
- }
-
if schedule_changed {
job.next_run = next_run_for_schedule(&job.schedule, Utc::now())?;
} else if job.enabled && !was_enabled {
@@ -474,7 +467,7 @@ pub fn update_job(config: &Config, job_id: &str, patch: CronJobPatch) -> Result<
"UPDATE cron_jobs
SET expression = ?1, command = ?2, schedule = ?3, job_type = ?4, prompt = ?5, name = ?6,
session_target = ?7, model = ?8, enabled = ?9, delivery = ?10, delete_after_run = ?11,
- next_run = ?12, agent_id = ?14, profile_id = ?15
+ next_run = ?12, agent_id = ?14
WHERE id = ?13",
params![
job.expression,
@@ -491,7 +484,6 @@ pub fn update_job(config: &Config, job_id: &str, patch: CronJobPatch) -> Result<
job.next_run.to_rfc3339(),
job.id,
job.agent_id,
- job.profile_id,
],
)
.context("Failed to update cron job")?;
diff --git a/crates/openhuman-core/src/cron/store/schema.rs b/crates/openhuman-core/src/cron/store/schema.rs
index 9a7d447ddd..8d9c869190 100644
--- a/crates/openhuman-core/src/cron/store/schema.rs
+++ b/crates/openhuman-core/src/cron/store/schema.rs
@@ -32,7 +32,6 @@ pub(super) fn map_cron_job_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Cron
session_target: SessionTarget::parse(&row.get::<_, String>(7)?),
model: row.get(8)?,
agent_id: row.get(17)?,
- profile_id: row.get(18)?,
enabled: row.get::<_, i64>(9)? != 0,
delivery,
delete_after_run: row.get::<_, i64>(11)? != 0,
@@ -181,7 +180,6 @@ pub(super) fn with_connection<T>(
add_column_if_missing(&conn, "delivery", "TEXT")?;
add_column_if_missing(&conn, "delete_after_run", "INTEGER NOT NULL DEFAULT 0")?;
add_column_if_missing(&conn, "agent_id", "TEXT")?;
- add_column_if_missing(&conn, "profile_id", "TEXT")?;
f(&conn)
}
diff --git a/crates/openhuman-core/src/cron/types.rs b/crates/openhuman-core/src/cron/types.rs
index 2b70d9a26a..d730e2cdd6 100644
--- a/crates/openhuman-core/src/cron/types.rs
+++ b/crates/openhuman-core/src/cron/types.rs
@@ -232,15 +232,6 @@ pub struct CronJob {
/// definition's prompt, tool allowlist, iteration cap, and model hint
/// instead of the generic `Agent::from_config` path.
pub agent_id: Option<String>,
- /// Optional agent-profile id (`profiles::AgentProfile::id`) this job runs
- /// under. When set and the profile still exists, the triggered run is built
- /// via the profile-aware session path so it inherits the profile's SOUL,
- /// memory scope, workspace descriptor, and allowlists. When the profile was
- /// deleted, the scheduler warns and runs without a profile (never fails the
- /// job). `#[serde(default)]` keeps legacy rows / payloads without the field
- /// deserializing unchanged.
- #[serde(default)]
- pub profile_id: Option<String>,
pub enabled: bool,
pub delivery: DeliveryConfig,
pub delete_after_run: bool,
@@ -303,10 +294,6 @@ pub struct CronJobPatch {
/// to honor a wire `null` as a clear rather than a silent no-op.
#[serde(default, deserialize_with = "deserialize_double_option")]
pub agent_id: Option<Option<String>>,
- /// `Option<Option<String>>` distinguishes "no change" (`None`) from
- /// "clear the profile" (`Some(None)`) — same shape as `agent_id`.
- #[serde(default, deserialize_with = "deserialize_double_option")]
- pub profile_id: Option<Option<String>>,
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
index 827e082ae0..7b6ec2291e 100644
--- a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
+++ b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
@@ -84,8 +84,6 @@ pub enum AgentChatTarget<'a> {
/// [`Agent::from_config_with_definition`].
Definition {
definition: &'a crate::agent::harness::definition::AgentDefinition,
- profile: Option<&'a crate::agent::profiles::AgentProfile>,
- profile_prompt_suffix: Option<&'a str>,
},
}
@@ -96,16 +94,9 @@ fn build_turn_agent(config: &Config, target: &AgentChatTarget<'_>) -> Result<Age
log::debug!("[inference] agent_chat building agent_id={id}");
Agent::from_config_for_agent(config, id)
}
- AgentChatTarget::Definition {
- definition,
- profile,
- profile_prompt_suffix,
- } => Agent::from_config_with_definition(
- config,
- definition,
- *profile,
- profile_prompt_suffix.map(str::to_string),
- ),
+ AgentChatTarget::Definition { definition } => {
+ Agent::from_config_with_definition(config, definition)
+ }
}
.map_err(|e| e.to_string())
}
diff --git a/crates/openhuman-core/src/security/policy/path_checks.rs b/crates/openhuman-core/src/security/policy/path_checks.rs
index 4907979b51..d411411717 100644
--- a/crates/openhuman-core/src/security/policy/path_checks.rs
+++ b/crates/openhuman-core/src/security/policy/path_checks.rs
@@ -368,47 +368,7 @@ impl SecurityPolicy {
Ok(result)
}
- /// Cross-profile write guard (1b). A no-op unless the session runs under an
- /// active profile (`active_profile` armed via
- /// [`SecurityPolicy::with_active_profile`]). When armed, a resolved target
- /// that lands inside a *sibling* profile's workspace
- /// (`<action_dir>/profiles/<Q>/`, `Q != active`) is refused with the
- /// permanent `[policy-blocked]` marker so the harness halts instead of
- /// retrying. This only ever tightens: `None` leaves every path check
- /// byte-identical, and it never loosens `is_workspace_internal_path` or any
- /// other `SecurityPolicy` check.
pub(super) fn check_cross_profile(&self, resolved: &Path) -> Result<(), String> {
- let Some(guard) = self.active_profile.as_ref() else {
- return Ok(());
- };
- if let crate::agent::profiles::CrossProfileDecision::Block { other_id } =
- crate::agent::profiles::classify_cross_profile_target(
- &guard.action_dir,
- &guard.profile_id,
- resolved,
- )
- {
- tracing::warn!(
- active_profile = %guard.profile_id,
- other_profile = %other_id,
- target = %resolved.display(),
- "[profiles] cross-profile write blocked"
- );
- if other_id == crate::agent::profiles::PROFILES_ROOT_SENTINEL {
- return Err(format!(
- "{POLICY_BLOCKED_MARKER} Cross-profile access blocked: profile '{}' may not \
- write to the shared profiles root. Stay within your own profile directory; \
- do not retry this path.",
- guard.profile_id
- ));
- }
- return Err(format!(
- "{POLICY_BLOCKED_MARKER} Cross-profile access blocked: profile '{}' may not write \
- into profile '{}'s workspace. Stay within your own profile directory; do not \
- retry this path.",
- guard.profile_id, other_id
- ));
- }
Ok(())
}
diff --git a/crates/openhuman-core/src/skills/runtime/mod.rs b/crates/openhuman-core/src/skills/runtime/mod.rs
index ed3bbdc36e..e59633c469 100644
--- a/crates/openhuman-core/src/skills/runtime/mod.rs
+++ b/crates/openhuman-core/src/skills/runtime/mod.rs
@@ -27,10 +27,7 @@ pub mod schemas;
pub mod tools;
#[cfg(feature = "skills")]
-pub use run_machinery::{
- await_run_outcome, spawn_workflow_run_background, spawn_workflow_run_background_with_profile,
- WorkflowRunStarted,
-};
+pub use run_machinery::{await_run_outcome, spawn_workflow_run_background, WorkflowRunStarted};
#[cfg(feature = "skills")]
pub use schemas::{
all_skill_runtime_controller_schemas, all_skill_runtime_registered_controllers,
diff --git a/crates/openhuman-core/src/skills/runtime/run_machinery.rs b/crates/openhuman-core/src/skills/runtime/run_machinery.rs
index 5c731238c8..b8aae4e632 100644
--- a/crates/openhuman-core/src/skills/runtime/run_machinery.rs
+++ b/crates/openhuman-core/src/skills/runtime/run_machinery.rs
@@ -14,20 +14,6 @@ use crate::skills::{preflight, registry, run_log};
use crate::skills::schemas::resolve_workspace_dir;
-async fn with_profile_memory_source_scope<F, T>(
- active_profile: Option<&crate::agent::profiles::AgentProfile>,
- fut: F,
-) -> T
-where
- F: std::future::Future<Output = T>,
-{
- crate::memory::source_scope::with_source_scope(
- active_profile.and_then(|profile| profile.memory_sources.clone()),
- fut,
- )
- .await
-}
-
/// Iteration cap for an autonomous skill run (orchestrator + sub-agents). High
/// enough to "run until done", while the repeated-failure circuit breaker still
/// stops dead-end grinding — deliberately bounded (not infinite) to cap spend.
@@ -55,30 +41,10 @@ pub struct WorkflowRunStarted {
pub async fn spawn_workflow_run_background(
skill_id_param: String,
inputs_param: Option<Value>,
-) -> Result<WorkflowRunStarted, String> {
- spawn_workflow_run_background_with_profile(skill_id_param, inputs_param, None, None).await
-}
-
-/// Like [`spawn_workflow_run_background`], but resolves the target skill against
-/// the active profile's private skills root too
-/// (`<workspace>/personalities/<id>/skills/`) when `profile_skills_root` is
-/// supplied — so `run_workflow` under profile P can run P's private skills, with
-/// profile-local winning same-name collisions. `None` is byte-identical to
-/// [`spawn_workflow_run_background`]. The root is passed by value (owned) so it
-/// can cross the resolution boundary without borrowing across the spawn.
-pub async fn spawn_workflow_run_background_with_profile(
- skill_id_param: String,
- inputs_param: Option<Value>,
- profile_skills_root: Option<std::path::PathBuf>,
- active_profile: Option<crate::agent::profiles::AgentProfile>,
) -> Result<WorkflowRunStarted, String> {
let workspace = resolve_workspace_dir().await;
- let skill = registry::get_workflow_with_profile(
- &workspace,
- &skill_id_param,
- profile_skills_root.as_deref(),
- )
- .ok_or_else(|| format!("workflow_run: unknown skill '{skill_id_param}'"))?;
+ let skill = registry::get_workflow(&workspace, &skill_id_param)
+ .ok_or_else(|| format!("workflow_run: unknown skill '{skill_id_param}'"))?;
let inputs = inputs_param.unwrap_or(Value::Null);
let missing = registry::missing_required_inputs(&skill.inputs, &inputs);
if !missing.is_empty() {
@@ -121,13 +87,12 @@ pub async fn spawn_workflow_run_background_with_profile(
gate decision: FAILED ({tag})\n\
detail: {body}"
);
- if let Err(e) = run_log::write_header_with_profile(
+ if let Err(e) = run_log::write_header(
&gate_log_path,
&skill.definition.id,
&gate_run_id,
&inputs,
&header_prompt,
- active_profile.as_ref().map(|profile| profile.id.as_str()),
)
.await
{
@@ -192,18 +157,9 @@ pub async fn spawn_workflow_run_background_with_profile(
let inputs = inputs.clone();
let log_path = log_path.clone();
let inherited_origin = inherited_origin.clone();
- let active_profile = active_profile.clone();
- let run_profile_id = active_profile.as_ref().map(|profile| profile.id.clone());
tokio::spawn(async move {
- if let Err(e) = run_log::write_header_with_profile(
- &log_path,
- &workflow_id,
- &run_id,
- &inputs,
- &task_prompt,
- run_profile_id.as_deref(),
- )
- .await
+ if let Err(e) =
+ run_log::write_header(&log_path, &workflow_id, &run_id, &inputs, &task_prompt).await
{
tracing::warn!(run_id = %run_id, error = %e, "[skills] workflow_run: header write failed");
}
@@ -226,14 +182,7 @@ pub async fn spawn_workflow_run_background_with_profile(
if config.http_request.allowed_domains.is_empty() {
config.http_request.allowed_domains = vec!["*".to_string()];
}
- let mut agent = match Agent::from_config_for_agent_with_profile(
- &config,
- "orchestrator",
- active_profile
- .as_ref()
- .and_then(|profile| profile.system_prompt_suffix.clone()),
- active_profile.as_ref(),
- ) {
+ let mut agent = match Agent::from_config_for_agent(&config, "orchestrator") {
Ok(a) => a,
Err(e) => {
let _ = run_log::write_footer(
@@ -286,14 +235,11 @@ pub async fn spawn_workflow_run_background_with_profile(
let result = tokio::select! {
biased;
_ = cancel_token.cancelled() => None,
- r = with_profile_memory_source_scope(
- active_profile.as_ref(),
- crate::agent::turn_origin::with_origin(
- inherited_origin,
- with_autonomous_iter_cap(
- WORKFLOW_RUN_MAX_ITERATIONS,
- agent.run_single(&task_prompt),
- ),
+ r = crate::agent::turn_origin::with_origin(
+ inherited_origin,
+ with_autonomous_iter_cap(
+ WORKFLOW_RUN_MAX_ITERATIONS,
+ agent.run_single(&task_prompt),
),
) => Some(r),
};
diff --git a/crates/openhuman-core/src/skills/tools/read.rs b/crates/openhuman-core/src/skills/tools/read.rs
index 54decd4713..818401e9a6 100644
--- a/crates/openhuman-core/src/skills/tools/read.rs
+++ b/crates/openhuman-core/src/skills/tools/read.rs
@@ -326,38 +326,14 @@ impl Tool for WorkflowReadResourceTool {
/// List recent skill runs.
pub struct WorkflowRecentRunsTool {
workspace_dir: PathBuf,
- active_profile_id: Option<String>,
- skill_allowlist: SkillAllowlist,
- profile_skills_root: Option<PathBuf>,
}
impl WorkflowRecentRunsTool {
pub fn new(config: Arc<Config>) -> Self {
Self {
workspace_dir: config.workspace_dir.clone(),
- active_profile_id: None,
- skill_allowlist: None,
- profile_skills_root: None,
}
}
-
- pub fn with_active_profile(
- mut self,
- profile: Option<crate::agent::profiles::AgentProfile>,
- ) -> Self {
- self.active_profile_id = profile.map(|profile| profile.id);
- self
- }
-
- pub fn with_skill_allowlist(mut self, allowlist: SkillAllowlist) -> Self {
- self.skill_allowlist = allowlist;
- self
- }
-
- pub fn with_profile_skills_root(mut self, root: Option<PathBuf>) -> Self {
- self.profile_skills_root = root;
- self
- }
}
#[async_trait]
@@ -396,19 +372,8 @@ impl Tool for WorkflowRecentRunsTool {
.and_then(serde_json::Value::as_u64)
.map(|v| v as usize)
.unwrap_or(20);
- let profile_local = profile_local_skill_ids(self.profile_skills_root.as_deref());
let runs = scan_runs(&self.workspace_dir, skill_id, usize::MAX)
.into_iter()
- .filter(|run| {
- run.profile_id.as_deref() == self.active_profile_id.as_deref()
- && skill_allowed_including_profile(
- &self.skill_allowlist,
- &profile_local,
- &self.workspace_dir,
- self.profile_skills_root.as_deref(),
- &run.workflow_id,
- )
- })
.take(limit)
.collect::<Vec<_>>();
Ok(ToolResult::success(serde_json::to_string(&json!({
@@ -425,38 +390,14 @@ impl Tool for WorkflowRecentRunsTool {
/// Read a slice of a run log.
pub struct WorkflowReadRunLogTool {
workspace_dir: PathBuf,
- active_profile_id: Option<String>,
- skill_allowlist: SkillAllowlist,
- profile_skills_root: Option<PathBuf>,
}
impl WorkflowReadRunLogTool {
pub fn new(config: Arc<Config>) -> Self {
Self {
workspace_dir: config.workspace_dir.clone(),
- active_profile_id: None,
- skill_allowlist: None,
- profile_skills_root: None,
}
}
-
- pub fn with_active_profile(
- mut self,
- profile: Option<crate::agent::profiles::AgentProfile>,
- ) -> Self {
- self.active_profile_id = profile.map(|profile| profile.id);
- self
- }
-
- pub fn with_skill_allowlist(mut self, allowlist: SkillAllowlist) -> Self {
- self.skill_allowlist = allowlist;
- self
- }
-
- pub fn with_profile_skills_root(mut self, root: Option<PathBuf>) -> Self {
- self.profile_skills_root = root;
- self
- }
}
#[async_trait]
@@ -496,20 +437,9 @@ impl Tool for WorkflowReadRunLogTool {
.and_then(serde_json::Value::as_u64)
.map(|v| v as usize)
.unwrap_or(65536);
- let profile_local = profile_local_skill_ids(self.profile_skills_root.as_deref());
let run = scan_runs(&self.workspace_dir, None, usize::MAX)
.into_iter()
- .find(|run| {
- run.run_id == run_id
- && run.profile_id.as_deref() == self.active_profile_id.as_deref()
- && skill_allowed_including_profile(
- &self.skill_allowlist,
- &profile_local,
- &self.workspace_dir,
- self.profile_skills_root.as_deref(),
- &run.workflow_id,
- )
- })
+ .find(|run| run.run_id == run_id)
.ok_or_else(|| anyhow::anyhow!("read_workflow_run_log: run `{run_id}` not found"))?;
let path = PathBuf::from(run.log_path);
let slice = read_run_log_slice(&path, offset, max_bytes)
diff --git a/crates/openhuman-core/src/tools/impl/system/mod.rs b/crates/openhuman-core/src/tools/impl/system/mod.rs
index 0c6385ee13..c98485c2c5 100644
--- a/crates/openhuman-core/src/tools/impl/system/mod.rs
+++ b/crates/openhuman-core/src/tools/impl/system/mod.rs
@@ -103,52 +103,6 @@ pub(super) fn check_cross_profile_command(
cwd: &Path,
tool: &str,
) -> Result<(), String> {
- let Some(guard) = security.active_profile.as_ref() else {
- return Ok(());
- };
- // Classify cwd itself before scanning command tokens. A process tool may
- // accept a syntactically in-profile directory that is actually a symlink
- // into a sibling; once spawned there, npm lifecycle hooks or a shell can
- // mutate that sibling without mentioning its path in the command.
- let other_id = match crate::agent::profiles::classify_cross_profile_target(
- &guard.action_dir,
- &guard.profile_id,
- cwd,
- ) {
- crate::agent::profiles::CrossProfileDecision::Block { other_id } => Some(other_id),
- crate::agent::profiles::CrossProfileDecision::Allow => {
- crate::agent::profiles::scan_command_for_cross_profile(
- command,
- cwd,
- &guard.action_dir,
- &guard.profile_id,
- )
- }
- };
- let Some(other_id) = other_id else {
- return Ok(());
- };
-
- tracing::warn!(
- tool,
- active_profile = %guard.profile_id,
- other_profile = %other_id,
- "[profiles] cross-profile process command blocked"
- );
- if other_id == crate::agent::profiles::PROFILES_ROOT_SENTINEL {
- Err(format!(
- "{} Cross-profile access blocked: profile '{}' may not modify the shared profiles \
- root. Stay within your own profile directory; do not retry this command.",
- crate::security::POLICY_BLOCKED_MARKER,
- guard.profile_id,
- ))
- } else {
- Err(format!(
- "{} Cross-profile access blocked: profile '{}' may not touch profile '{}'s workspace. \
- Stay within your own profile directory; do not retry this command.",
- crate::security::POLICY_BLOCKED_MARKER,
- guard.profile_id,
- other_id
- ))
- }
+ let _ = (security, command, cwd, tool);
+ Ok(())
}
diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rs
index d28c028992..b59c0270ef 100644
--- a/crates/openhuman-core/src/tools/ops.rs
+++ b/crates/openhuman-core/src/tools/ops.rs
@@ -77,18 +77,11 @@ pub fn all_tools(
agents,
root_config,
None,
- None,
- None,
- None,
- None,
)
}
/// Create full tool registry including memory tools.
///
-/// `skill_allowlist` / `mcp_allowlist` scope the skill (workflow) and MCP-server
-/// surfaces to an active agent profile's selection. `None` for either means
-/// "all" (the default for every non-profile caller).
#[allow(clippy::implicit_hasher, clippy::too_many_arguments)]
pub fn all_tools_with_runtime(
config: Arc<Config>,
@@ -100,18 +93,8 @@ pub fn all_tools_with_runtime(
action_dir: &std::path::Path,
agents: &HashMap<String, DelegateAgentConfig>,
root_config: &crate::config::Config,
- active_profile: Option<&crate::agent::profiles::AgentProfile>,
- skill_allowlist: Option<&std::collections::HashSet<String>>,
- mcp_allowlist: Option<&[String]>,
- profile_skills_root: Option<&std::path::Path>,
approval_workspace_root: Option<&std::path::Path>,
) -> Vec<Box<dyn Tool>> {
- // `skill_allowlist` / `profile_skills_root` scope only the `skills`-gated
- // tool registrations below, so they are genuinely unread when that feature
- // is compiled out.
- #[cfg(not(feature = "skills"))]
- let _ = (active_profile, skill_allowlist, profile_skills_root);
-
// One shared snapshot of this session's configuration for both language
// clients. They each hand it to the `tinyruntime` module on every call —
// the module holds no configuration of its own — so the two must not be
@@ -220,7 +203,6 @@ pub fn all_tools_with_runtime(
Box::new(CloseSubagentTool::new()),
Box::new(ContinueSubagentTool::new()),
Box::new(SpawnParallelAgentsTool::new()),
- Box::new(DelegateToPersonalityTool::new()),
// Multi-stage durable delegation (issue #4249, Phase 3): runs the chosen
// sub-agent through the tinyagents plan→execute→review→finalize graph,
// checkpointed to the session DB. Heavier than spawn_subagent; for
@@ -248,19 +230,9 @@ pub fn all_tools_with_runtime(
// `await_run_outcome` — the same spawn path `openhuman.skills_run`
// JSON-RPC uses, so RPC and tool callers stay in sync.
#[cfg(feature = "skills")]
- Box::new(
- RunWorkflowTool::new()
- .with_active_profile(active_profile.cloned())
- .with_skill_allowlist(skill_allowlist.cloned())
- .with_profile_skills_root(profile_skills_root.map(|p| p.to_path_buf())),
- ),
+ Box::new(RunWorkflowTool::new()),
#[cfg(feature = "skills")]
- Box::new(
- AwaitWorkflowTool::new()
- .with_active_profile(active_profile.cloned())
- .with_skill_allowlist(skill_allowlist.cloned())
- .with_profile_skills_root(profile_skills_root.map(|p| p.to_path_buf())),
- ),
+ Box::new(AwaitWorkflowTool::new()),
Box::new(CurrentTimeTool::new()),
// Reversibility for native tool-output compaction (Stage 1a): when a
// large result is compacted with a `retrieve_tool_output("<hash>")`
@@ -509,23 +481,11 @@ pub fn all_tools_with_runtime(
// create/install/uninstall mutators ship default-OFF via
// `tools::user_filter` (install also fetches remote content).
#[cfg(feature = "skills")]
- Box::new(
- WorkflowListTool::new(config.clone())
- .with_skill_allowlist(skill_allowlist.cloned())
- .with_profile_skills_root(profile_skills_root.map(|p| p.to_path_buf())),
- ),
+ Box::new(WorkflowListTool::new(config.clone())),
#[cfg(feature = "skills")]
- Box::new(
- WorkflowDescribeTool::new(config.clone())
- .with_skill_allowlist(skill_allowlist.cloned())
- .with_profile_skills_root(profile_skills_root.map(|p| p.to_path_buf())),
- ),
+ Box::new(WorkflowDescribeTool::new(config.clone())),
#[cfg(feature = "skills")]
- Box::new(
- SkillSearchTool::new(config.clone())
- .with_skill_allowlist(skill_allowlist.cloned())
- .with_profile_skills_root(profile_skills_root.map(|p| p.to_path_buf())),
- ),
+ Box::new(SkillSearchTool::new(config.clone())),
// Skill registry tools — browse/search/install from remote registries.
// Browse and search are read-only (default-ON); install is a write
// operation (fetches remote content and writes to disk).
@@ -544,25 +504,11 @@ pub fn all_tools_with_runtime(
#[cfg(feature = "skills")]
Box::new(SkillRuntimeResolveRuntimesTool::new(config.clone())),
#[cfg(feature = "skills")]
- Box::new(
- WorkflowReadResourceTool::new(config.clone())
- .with_skill_allowlist(skill_allowlist.cloned())
- .with_profile_skills_root(profile_skills_root.map(|p| p.to_path_buf())),
- ),
+ Box::new(WorkflowReadResourceTool::new(config.clone())),
#[cfg(feature = "skills")]
- Box::new(
- WorkflowRecentRunsTool::new(config.clone())
- .with_active_profile(active_profile.cloned())
- .with_skill_allowlist(skill_allowlist.cloned())
- .with_profile_skills_root(profile_skills_root.map(|p| p.to_path_buf())),
- ),
+ Box::new(WorkflowRecentRunsTool::new(config.clone())),
#[cfg(feature = "skills")]
- Box::new(
- WorkflowReadRunLogTool::new(config.clone())
- .with_active_profile(active_profile.cloned())
- .with_skill_allowlist(skill_allowlist.cloned())
- .with_profile_skills_root(profile_skills_root.map(|p| p.to_path_buf())),
- ),
+ Box::new(WorkflowReadRunLogTool::new(config.clone())),
#[cfg(feature = "skills")]
Box::new(WorkflowCreateTool::new(config.clone())),
#[cfg(feature = "skills")]
@@ -813,15 +759,7 @@ pub fn all_tools_with_runtime(
// gitbooks — answers questions about OpenHuman by calling the
// GitBook MCP server. Two tools mirroring the upstream MCP tools.
- // Gitbooks is modelled as a legacy MCP server (`McpServerRegistry`), so it
- // honours the same per-profile `mcp_allowlist`: a profile that scopes its
- // MCP servers and omits "gitbooks" must not see this surface either.
- let gitbooks_allowed = mcp_allowlist.is_none_or(|allowed| {
- allowed
- .iter()
- .any(|name| name.eq_ignore_ascii_case("gitbooks"))
- });
- if root_config.gitbooks.enabled && gitbooks_allowed {
+ if root_config.gitbooks.enabled {
// Building the client can fail on a malformed proxy or an unusable TLS
// setting. Both are logged and the tools are simply not registered:
// taking the whole surface down over a documentation server would cost
@@ -845,8 +783,6 @@ pub fn all_tools_with_runtime(
tracing::warn!("[gitbooks] tools not registered: {error}");
}
}
- } else if root_config.gitbooks.enabled {
- tracing::debug!("[profiles] gitbooks tools suppressed by profile mcp allowlist");
}
// MCP setup-agent tool surface (search/get/request_secret/test/install).
@@ -881,12 +817,7 @@ pub fn all_tools_with_runtime(
// logged and treated as empty: a malformed proxy or TLS setting
// must not take the whole tool surface down with it.
let base = crate::mcp::host::static_registry(root_config);
- // Scope the MCP surface to the active profile's allowlist. `None` keeps
- // every configured server; `Some(&[])` yields an empty registry.
- match mcp_allowlist {
- Some(allowed) => Arc::new(base.retaining_servers(allowed)),
- None => Arc::new(base),
- }
+ Arc::new(base)
};
log::debug!(
"[tools::ops][mcp_client] static servers={}",
diff --git a/crates/openhuman-core/src/web_chat/mod.rs b/crates/openhuman-core/src/web_chat/mod.rs
index 96702c610f..49806ee97f 100644
--- a/crates/openhuman-core/src/web_chat/mod.rs
+++ b/crates/openhuman-core/src/web_chat/mod.rs
@@ -92,8 +92,7 @@ pub(crate) use schemas::{
#[cfg(any(test, debug_assertions))]
#[allow(unused_imports)]
pub(crate) use session::{
- compose_system_prompt_suffix, locale_reply_directive, normalize_model_override,
- provider_role_for_model_override,
+ locale_reply_directive, normalize_model_override, provider_role_for_model_override,
};
#[cfg(any(test, debug_assertions))]
#[allow(unused_imports)]
diff --git a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs b/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
index 841ad1e00b..2bb71b53d9 100644
--- a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
+++ b/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
@@ -112,7 +112,6 @@ pub async fn channel_web_chat(
message: &str,
model_override: Option<String>,
temperature: Option<f64>,
- profile_id: Option<String>,
locale: Option<String>,
queue_mode: Option<String>,
metadata: ChatRequestMetadata,
@@ -123,7 +122,6 @@ pub async fn channel_web_chat(
message,
model_override,
temperature,
- profile_id,
locale,
queue_mode,
metadata,
diff --git a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs
index a0ae7bd699..84b1482fe6 100644
--- a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs
+++ b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs
@@ -31,7 +31,6 @@ pub(crate) async fn spawn_parallel_turn(
message: &str,
model_override: Option<String>,
temperature: Option<f64>,
- profile_id: Option<String>,
locale: Option<String>,
metadata: ChatRequestMetadata,
) {
@@ -68,7 +67,6 @@ pub(crate) async fn spawn_parallel_turn(
&user_message,
model_override,
temperature,
- profile_id,
locale,
run_queue,
metadata,
diff --git a/crates/openhuman-core/src/web_chat/ops/start_chat.rs b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
index 4a643b6741..8dd6b5e85d 100644
--- a/crates/openhuman-core/src/web_chat/ops/start_chat.rs
+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
@@ -41,7 +41,6 @@ pub async fn start_chat(
message: &str,
model_override: Option<String>,
temperature: Option<f64>,
- profile_id: Option<String>,
locale: Option<String>,
queue_mode: Option<String>,
metadata: ChatRequestMetadata,
@@ -250,7 +249,6 @@ pub async fn start_chat(
&message,
model_override,
temperature,
- profile_id,
locale,
metadata,
)
@@ -276,7 +274,6 @@ pub async fn start_chat(
.as_millis() as u64,
model_override: model_override.clone(),
temperature,
- profile_id: profile_id.clone(),
locale: locale.clone(),
};
existing.run_queue.push(queued_msg).await;
@@ -376,7 +373,6 @@ pub async fn start_chat(
&user_message,
model_override,
temperature,
- profile_id,
locale,
turn_run_queue_task,
metadata,
@@ -543,7 +539,6 @@ fn dispatch_followups(followups: Vec<crate::agent::harness::run_queue::QueuedMes
&fup.text,
fup.model_override,
fup.temperature,
- fup.profile_id,
fup.locale,
Some("followup".to_string()),
ChatRequestMetadata::default(),
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs
index 3b18bdab18..b169cf7843 100644
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@ -6,7 +6,6 @@
use std::sync::Arc;
-use crate::agent::profiles::AgentProfileStore;
use crate::config::rpc as config_rpc;
use crate::threads::turn_state::TurnStateStore;
@@ -33,7 +32,6 @@ pub(crate) async fn run_chat_task(
message: &str,
model_override: Option<String>,
temperature: Option<f64>,
- profile_id: Option<String>,
locale: Option<String>,
run_queue: Arc<crate::agent::harness::run_queue::RunQueue>,
metadata: ChatRequestMetadata,
@@ -92,13 +90,9 @@ pub(crate) async fn run_chat_task(
}
let config = config_rpc::load_config_with_timeout().await?;
- let (_profiles_state, profile) =
- AgentProfileStore::new(config.workspace_dir.clone()).resolve(profile_id.as_deref())?;
let map_key = key_for(thread_id);
- let model_override = normalize_model_override(profile.model_override.clone())
- .or_else(|| normalize_model_override(model_override));
- let temperature = profile.temperature.or(temperature);
- let target_agent_id = pick_target_agent_id(&config, &profile);
+ let model_override = normalize_model_override(model_override);
+ let target_agent_id = pick_target_agent_id(&config);
let provider_role = provider_role_for_model_override(model_override.as_deref());
let current_fp = build_session_fingerprint(
&config,
@@ -106,7 +100,6 @@ pub(crate) async fn run_chat_task(
temperature,
target_agent_id.clone(),
provider_role,
- &profile,
);
// A forked (parallel) turn never reuses or evicts the shared cached agent —
@@ -146,7 +139,6 @@ pub(crate) async fn run_chat_task(
client_id,
thread_id,
&target_agent_id,
- &profile,
model_override.clone(),
temperature,
locale.as_deref(),
@@ -160,7 +152,6 @@ pub(crate) async fn run_chat_task(
client_id,
thread_id,
&target_agent_id,
- &profile,
model_override.clone(),
temperature,
locale.as_deref(),
@@ -254,21 +245,12 @@ pub(crate) async fn run_chat_task(
config.clone(),
);
- // Scope source-memory recall to the active profile's allowlist for the
- // duration of the turn (None = all). Nested inside the thread-id scope so
- // every memory-tree query the agent makes this turn is gated. See
- // memory::source_scope.
// `run_single`'s future is very large; box it so the two ambient-scope
// wrappers below hold a pointer rather than inlining the whole future into
// this already-large `run_chat_task` frame (which otherwise overflows the
// default test-thread stack — see the channels web-turn coverage tests).
let turn = Box::pin(agent.run_single(message));
- let result = match crate::memory::source_scope::with_source_scope(
- profile.memory_sources.clone(),
- turn,
- )
- .await
- {
+ let result = match turn.await {
Ok(response) => {
// A successful turn proves the thread's balance is usable, so drop
// any stale budget-exhausted signal before it could mislabel a
diff --git a/crates/openhuman-core/src/web_chat/schemas.rs b/crates/openhuman-core/src/web_chat/schemas.rs
index 7e32ef27c5..aace6fd1c5 100644
--- a/crates/openhuman-core/src/web_chat/schemas.rs
+++ b/crates/openhuman-core/src/web_chat/schemas.rs
@@ -55,7 +55,6 @@ pub fn schemas(function: &str) -> ControllerSchema {
required_string("message", "User message."),
optional_string("model_override", "Optional model override."),
optional_f64("temperature", "Optional temperature override."),
- optional_string("profile_id", "Optional agent profile id."),
optional_string(
"locale",
"Optional BCP-47 UI locale (e.g. 'ar', 'zh-CN'). Drives the \"reply in this language\" system-prompt directive.",
@@ -123,7 +122,6 @@ fn handle_chat(params: Map<String, Value>) -> ControllerFuture {
&p.message,
p.model_override,
p.temperature,
- p.profile_id,
p.locale,
p.queue_mode,
ChatRequestMetadata {
diff --git a/crates/openhuman-core/src/web_chat/session.rs b/crates/openhuman-core/src/web_chat/session.rs
index e8742cc2a4..a0c2e5f9d1 100644
--- a/crates/openhuman-core/src/web_chat/session.rs
+++ b/crates/openhuman-core/src/web_chat/session.rs
@@ -3,7 +3,6 @@
//! `SessionCacheFingerprint` that decides whether a cached agent can be
//! reused for the next turn on a thread.
-use crate::agent::profiles::{AgentProfile, DEFAULT_PROFILE_ID};
use crate::agent::Agent;
use crate::config::Config;
use serde_json::json;
@@ -22,12 +21,8 @@ pub(super) fn model_registry_signature(config: &Config) -> String {
serde_json::to_string(&config.model_registry).unwrap_or_default()
}
-pub(super) fn pick_target_agent_id(_config: &Config, profile: &AgentProfile) -> String {
- if profile.id == DEFAULT_PROFILE_ID {
- "orchestrator".to_string()
- } else {
- profile.agent_id.clone()
- }
+pub(super) fn pick_target_agent_id(_config: &Config) -> String {
+ "orchestrator".to_string()
}
pub(crate) fn normalize_model_override(model_override: Option<String>) -> Option<String> {
@@ -51,7 +46,6 @@ pub(super) fn build_session_agent(
client_id: &str,
thread_id: &str,
target_agent_id: &str,
- profile: &AgentProfile,
model_override: Option<String>,
temperature: Option<f64>,
locale: Option<&str>,
@@ -66,19 +60,15 @@ pub(super) fn build_session_agent(
}
log::info!(
- "[web-channel] routing chat turn to '{}' via profile '{}' provider_role='{}' (client_id={}, thread_id={})",
+ "[web-channel] routing chat turn to '{}' provider_role='{}' (client_id={}, thread_id={})",
target_agent_id,
- profile.id,
provider_role,
client_id,
thread_id
);
let locale_directive = locale.and_then(locale_reply_directive);
- let composed_suffix = compose_system_prompt_suffix(
- locale_directive.as_deref(),
- profile.system_prompt_suffix.as_deref(),
- );
+ let composed_suffix = locale_directive;
if let Some(s) = locale_directive.as_deref() {
log::info!(
"[web-channel] injecting locale directive client={} thread={} locale={} directive={:?}",
@@ -89,12 +79,7 @@ pub(super) fn build_session_agent(
);
}
- let agent_result = Agent::from_config_for_agent_with_profile(
- &effective,
- target_agent_id,
- composed_suffix,
- Some(profile),
- );
+ let agent_result = Agent::from_config_for_agent(&effective, target_agent_id);
agent_result
.map(|mut agent| {
@@ -134,25 +119,12 @@ pub(crate) fn locale_reply_directive(locale: &str) -> Option<String> {
))
}
-pub(crate) fn compose_system_prompt_suffix(
- locale_directive: Option<&str>,
- profile_suffix: Option<&str>,
-) -> Option<String> {
- match (locale_directive, profile_suffix) {
- (None, None) => None,
- (Some(d), None) => Some(d.to_string()),
- (None, Some(p)) => Some(p.to_string()),
- (Some(d), Some(p)) => Some(format!("{d}\n\n{p}")),
- }
-}
-
pub(super) fn build_session_fingerprint(
config: &Config,
model_override: Option<String>,
temperature: Option<f64>,
target_agent_id: String,
provider_role: &str,
- profile: &AgentProfile,
) -> SessionCacheFingerprint {
SessionCacheFingerprint {
model_override,
@@ -161,11 +133,5 @@ pub(super) fn build_session_fingerprint(
target_agent_id,
autonomy_signature: autonomy_signature(config),
model_registry_signature: model_registry_signature(config),
- // Any change to the resolved profile record or its canonical on-disk
- // SOUL/MEMORY files forces a session-agent rebuild — see the field doc.
- profile_signature: crate::agent::profiles::profile_session_signature(
- &config.workspace_dir,
- profile,
- ),
}
}
diff --git a/crates/openhuman-core/src/web_chat/types.rs b/crates/openhuman-core/src/web_chat/types.rs
index 0223343726..bca38bf481 100644
--- a/crates/openhuman-core/src/web_chat/types.rs
+++ b/crates/openhuman-core/src/web_chat/types.rs
@@ -30,15 +30,6 @@ pub(crate) struct SessionCacheFingerprint {
/// change) — without this the stale session would be reused. Mirrors
/// [`Self::autonomy_signature`].
pub(super) model_registry_signature: String,
- /// Hashed signature of the active agent profile record and its resolved
- /// SOUL/MEMORY file contents. The cached `Agent`
- /// bakes in the profile's tool/skill/MCP/connector visibility and SOUL/MEMORY
- /// overrides at build time; switching profiles on the same thread keeps the
- /// same model/agent/provider, so without this the previous profile's
- /// capability surface would leak into the new profile's turns. Any change to
- /// the resolved profile or a direct edit to either profile file forces a
- /// rebuild on the next turn.
- pub(super) profile_signature: String,
}
pub(super) struct SessionEntry {
@@ -111,7 +102,6 @@ pub(crate) struct WebChatParams {
pub(super) message: String,
pub(super) model_override: Option<String>,
pub(super) temperature: Option<f64>,
- pub(super) profile_id: Option<String>,
/// BCP-47 locale of the frontend UI (e.g. `ar`, `zh-CN`). When set
/// and not English, the system prompt is augmented to ask the
/// agent to reply in that language. `None` keeps the agent's