The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(channels): render the channel prompt from the active profile and refresh it on identity changes
Shanua45b1c1af1c2
diff --git a/src/openhuman/agent/context/channels_prompt.rs b/src/openhuman/agent/context/channels_prompt.rsindex fe804cd65c..96a7966f3b 100644--- a/src/openhuman/agent/context/channels_prompt.rs+++ b/src/openhuman/agent/context/channels_prompt.rs@@ -21,27 +21,48 @@//! `misty-bubbling-bunny` plan file for the roadmap toward a unified//! builder.+use crate::openhuman::agent::prompts::inject_inline_content;use std::path::Path;/// Maximum characters per injected workspace file (matches `OpenClaw` default).pub(crate) const BOOTSTRAP_MAX_CHARS: usize = 20_000;+/// Identity content that takes the place of a workspace-root file in the+/// rendered prompt.+///+/// A channel turn runs under the active agent profile (#6027), and a profile+/// may carry its own `SOUL.md` and `MEMORY.md` under `personalities/<id>/`.+/// When present, each **replaces** the root file in its slot — the same+/// replace-not-append rule the desktop `IdentitySection` applies — so the+/// model never sees two identities side by side. `IDENTITY.md` and+/// `PROFILE.md` are never overridden; they describe the workspace, not the+/// persona. An empty override renders exactly what the root files render.+#[derive(Debug, Clone, Copy, Default)]+pub struct PromptIdentityOverride<'a> {+ /// Replaces the root `SOUL.md` slot.+ pub soul_md: Option<&'a str>,+ /// Replaces the root `MEMORY.md` slot.+ pub memory_md: Option<&'a str>,+}+/// Load OpenClaw format bootstrap files into the prompt.fn load_openclaw_bootstrap_files(prompt: &mut String,workspace_dir: &Path,max_chars_per_file: usize,+ identity: PromptIdentityOverride<'_>,) {prompt.push_str("The following workspace files define your identity, behavior, and context. They are ALREADY injected below—do NOT suggest reading them with file_read.\n\n",);// Bundled prompt files that ship with the binary and seed the workspace- // on first run.- let bootstrap_files = ["SOUL.md", "IDENTITY.md"];- for filename in &bootstrap_files {- inject_workspace_file(prompt, workspace_dir, filename, max_chars_per_file);+ // on first run. The SOUL slot is the one a profile may take over.+ match identity.soul_md {+ Some(soul) => inject_inline_content(prompt, "SOUL.md", soul, max_chars_per_file),+ None => inject_workspace_file(prompt, workspace_dir, "SOUL.md", max_chars_per_file),}+ inject_workspace_file(prompt, workspace_dir, "IDENTITY.md", max_chars_per_file);// PROFILE.md — generated by the onboarding enrichment pipeline (e.g.// LinkedIn scrape). Not bundled; only exists after the user completes@@ -54,9 +75,15 @@ fn load_openclaw_bootstrap_files(// It starts out missing on a fresh install, so inject silently (no// missing-file marker). `is_file` (rather than `exists`) rejects a// stray directory with the same name that would otherwise route- // through the error path in `inject_workspace_file`.- if workspace_dir.join("MEMORY.md").is_file() {- inject_workspace_file(prompt, workspace_dir, "MEMORY.md", max_chars_per_file);+ // through the error path in `inject_workspace_file`. A profile with its+ // own MEMORY.md replaces the root one here, as on the desktop path.+ match identity.memory_md {+ Some(memory) => inject_inline_content(prompt, "MEMORY.md", memory, max_chars_per_file),+ None => {+ if workspace_dir.join("MEMORY.md").is_file() {+ inject_workspace_file(prompt, workspace_dir, "MEMORY.md", max_chars_per_file);+ }+ }}}@@ -73,6 +100,11 @@ fn load_openclaw_bootstrap_files(////// Daily memory files (`memory/*.md`) are NOT injected — they are accessed/// on-demand via `memory_recall` / `memory_search` tools.+///+/// Renders the workspace-root identity. [`build_system_prompt_with_identity`]+/// is the same render with a profile's soul / memory in place of the root+/// files; this wrapper is byte-for-byte what it produces for an empty+/// override.pub fn build_system_prompt(workspace_dir: &Path,model_name: &str,@@ -80,6 +112,28 @@ pub fn build_system_prompt(skills: &[crate::openhuman::skills::Workflow],bootstrap_max_chars: Option<usize>,channel_name: Option<&str>,+) -> String {+ build_system_prompt_with_identity(+ workspace_dir,+ model_name,+ tools,+ skills,+ bootstrap_max_chars,+ channel_name,+ PromptIdentityOverride::default(),+ )+}++/// [`build_system_prompt`] with the active profile's identity substituted+/// into the bootstrap section (see [`PromptIdentityOverride`]).+pub fn build_system_prompt_with_identity(+ workspace_dir: &Path,+ model_name: &str,+ tools: &[(&str, &str)],+ skills: &[crate::openhuman::skills::Workflow],+ bootstrap_max_chars: Option<usize>,+ channel_name: Option<&str>,+ identity: PromptIdentityOverride<'_>,) -> String {use std::fmt::Write;let mut prompt = String::with_capacity(8192);@@ -155,7 +209,7 @@ pub fn build_system_prompt(// ── 5. Bootstrap files (injected into context) ──────────────prompt.push_str("## Project Context\n\n");let max_chars = bootstrap_max_chars.unwrap_or(BOOTSTRAP_MAX_CHARS);- load_openclaw_bootstrap_files(&mut prompt, workspace_dir, max_chars);+ load_openclaw_bootstrap_files(&mut prompt, workspace_dir, max_chars, identity);// ── 6. Date & Time ──────────────────────────────────────────let now = chrono::Local::now();@@ -208,6 +262,10 @@ pub fn build_system_prompt(}/// Inject a single workspace file into the prompt with truncation and missing-file markers.+///+/// The present-file branch is `inject_inline_content` — the same header,+/// trim, truncation notice and trailing blank line the desktop prompt uses —+/// so an identity override and a root file render identically.fn inject_workspace_file(prompt: &mut String,workspace_dir: &Path,@@ -218,33 +276,7 @@ fn inject_workspace_file(let path = workspace_dir.join(filename);match std::fs::read_to_string(&path) {- Ok(content) => {- let trimmed = content.trim();- if trimmed.is_empty() {- return;- }- let _ = writeln!(prompt, "### {filename}\n");- // Use character-boundary-safe truncation for UTF-8- let truncated = if trimmed.chars().count() > max_chars {- trimmed- .char_indices()- .nth(max_chars)- .map(|(idx, _)| &trimmed[..idx])- .unwrap_or(trimmed)- } else {- trimmed- };- if truncated.len() < trimmed.len() {- prompt.push_str(truncated);- let _ = writeln!(- prompt,- "\n\n[... truncated at {max_chars} chars — use `read` for full file]\n"- );- } else {- prompt.push_str(trimmed);- prompt.push_str("\n\n");- }- }+ Ok(content) => inject_inline_content(prompt, filename, &content, max_chars),Err(_) => {// Missing-file marker (matches OpenClaw behavior)let _ = writeln!(prompt, "### {filename}\n\n[File not found: {filename}]\n");diff --git a/src/openhuman/agent/context/channels_prompt_tests.rs b/src/openhuman/agent/context/channels_prompt_tests.rsindex 89b4182186..c111b9619b 100644--- a/src/openhuman/agent/context/channels_prompt_tests.rs+++ b/src/openhuman/agent/context/channels_prompt_tests.rs@@ -55,7 +55,12 @@ fn load_openclaw_bootstrap_files_omits_missing_optional_files() {std::fs::write(tmp.path().join("IDENTITY.md"), "Identity").unwrap();let mut prompt = String::new();- load_openclaw_bootstrap_files(&mut prompt, tmp.path(), 100);+ load_openclaw_bootstrap_files(+ &mut prompt,+ tmp.path(),+ 100,+ PromptIdentityOverride::default(),+ );assert!(prompt.contains("### SOUL.md"));assert!(prompt.contains("### IDENTITY.md"));@@ -104,3 +109,92 @@ fn build_system_prompt_uses_workspace_skill_location_fallback() {));assert!(prompt.contains("running as a Telegram bot"));}++// ── Identity override (#6027) ────────────────────────────────────────++fn identity_workspace() -> tempfile::TempDir {+ let tmp = tempdir().unwrap();+ std::fs::write(+ tmp.path().join("SOUL.md"),+ "I am the conflicting workspace-root identity.",+ )+ .unwrap();+ std::fs::write(tmp.path().join("IDENTITY.md"), "Name: OpenHuman").unwrap();+ std::fs::write(tmp.path().join("MEMORY.md"), "shared root memory marker").unwrap();+ tmp+}++#[test]+fn identity_override_replaces_root_soul_and_memory() {+ let tmp = identity_workspace();+ let prompt = build_system_prompt_with_identity(+ tmp.path(),+ "model",+ &[],+ &[],+ None,+ Some("Discord"),+ PromptIdentityOverride {+ soul_md: Some("I am Alice, a meticulous archivist."),+ memory_md: Some("alice private memory marker"),+ },+ );++ assert!(prompt.contains("### SOUL.md"), "SOUL slot keeps its header");+ assert!(prompt.contains("I am Alice, a meticulous archivist."));+ assert!(+ !prompt.contains("conflicting workspace-root identity"),+ "profile SOUL.md must replace, not accompany, the root file"+ );+ assert!(+ prompt.contains("Name: OpenHuman"),+ "IDENTITY.md is not overridable and stays the root file"+ );+ assert!(prompt.contains("### MEMORY.md"));+ assert!(prompt.contains("alice private memory marker"));+ assert!(+ !prompt.contains("shared root memory marker"),+ "profile MEMORY.md must replace the root one"+ );+}++#[test]+fn memory_override_renders_even_when_root_memory_is_absent() {+ let tmp = tempdir().unwrap();+ std::fs::write(tmp.path().join("SOUL.md"), "root soul").unwrap();+ let prompt = build_system_prompt_with_identity(+ tmp.path(),+ "model",+ &[],+ &[],+ None,+ None,+ PromptIdentityOverride {+ soul_md: None,+ memory_md: Some("profile-only memory"),+ },+ );+ assert!(prompt.contains("root soul"), "no soul override → root soul");+ assert!(prompt.contains("### MEMORY.md"));+ assert!(prompt.contains("profile-only memory"));+}++#[test]+fn empty_identity_override_matches_root_render_byte_for_byte() {+ let tmp = identity_workspace();+ let tools = [("shell", "Run commands")];+ let root = build_system_prompt(tmp.path(), "model", &tools, &[], Some(50), Some("Discord"));+ let overridden = build_system_prompt_with_identity(+ tmp.path(),+ "model",+ &tools,+ &[],+ Some(50),+ Some("Discord"),+ PromptIdentityOverride::default(),+ );+ assert_eq!(+ root, overridden,+ "the wrapper and an empty override are one render"+ );+}diff --git a/src/openhuman/channels/README.md b/src/openhuman/channels/README.mdindex c745707ca3..982c95e23b 100644--- a/src/openhuman/channels/README.md+++ b/src/openhuman/channels/README.md@@ -1,6 +1,6 @@# Channels-Multi-platform messaging integration. Owns the `Channel` trait, per-provider connectors (Slack, Discord, Telegram, WhatsApp, IRC, Matrix, Signal, iMessage, Email, Lark, Mattermost, DingTalk, QQ, Linq, Web, CLI), the runtime supervisor that brings channels online, inbound dispatch into the agent loop, and proactive outbound delivery. Does NOT own the channel system prompt copy (lives in `context/channels_prompt.rs`) or per-channel credential storage (delegated to `credentials/`).+Multi-platform messaging integration. Owns the `Channel` trait, per-provider connectors (Slack, Discord, Telegram, WhatsApp, IRC, Matrix, Signal, iMessage, Email, Lark, Mattermost, DingTalk, QQ, Linq, Web, CLI), the runtime supervisor that brings channels online, inbound dispatch into the agent loop, and proactive outbound delivery. Does NOT own the channel system prompt copy (lives in `context/channels_prompt.rs`; `system_prompt.rs` here owns only when it is re-rendered) or per-channel credential storage (delegated to `credentials/`).## Public surface@@ -9,6 +9,7 @@ Multi-platform messaging integration. Owns the `Channel` trait, per-provider con- `pub fn start_channels` — `runtime/startup.rs` (re-exported `mod.rs:65`) — boot all enabled channels under the supervisor.- `pub fn doctor_channels` — `commands.rs` — diagnose connectivity for the doctor CLI.- `pub fn build_system_prompt` — re-exported from `crate::openhuman::agent::context::channels_prompt`.+- `pub(crate) enum ChannelSystemPrompt` — `system_prompt.rs` — the prompt a turn is seeded with: `fixed` (tests) or `refreshing` (production), which renders `build_system_prompt_with_identity` for the active agent profile and re-renders only when an identity fingerprint (`agent_profiles.json`, root `SOUL/IDENTITY/PROFILE/MEMORY.md`, the profile's `SOUL/MEMORY.md`) changes — #6027 / #6028.- Per-provider channel structs: `pub struct CliChannel`, `DingTalkChannel`, `DiscordChannel`, `EmailChannel`, `IMessageChannel`, `IrcChannel`, `LarkChannel`, `LinqChannel`, `MattermostChannel`, `QQChannel`, `SignalChannel`, `SlackChannel`, `TelegramChannel`, `WhatsAppChannel` — `providers/<name>.rs`. Cargo-feature-gated: `WhatsAppWebChannel` (`whatsapp-web`).- Stable `pub use providers::<name>` paths for every provider — `mod.rs:18-36`.- RPC `channels.{list, describe, connect, disconnect, status, test, telegram_login_start, telegram_login_check, discord_link_start, discord_link_check, discord_list_guilds, discord_list_channels, discord_check_permissions, send_message, send_reaction, create_thread, update_thread, list_threads}` — `controllers/schemas.rs`.diff --git a/src/openhuman/channels/context.rs b/src/openhuman/channels/context.rsindex 257fa007d1..8871da35b9 100644--- a/src/openhuman/channels/context.rs+++ b/src/openhuman/channels/context.rs@@ -35,7 +35,10 @@ pub(crate) struct ChannelRuntimeContext {pub(crate) default_provider: Arc<String>,pub(crate) memory: Arc<crate::openhuman::memory::guard::MemoryGuard>,pub(crate) tools_registry: Arc<Vec<Box<dyn Tool>>>,- pub(crate) system_prompt: Arc<String>,+ /// Seeds every turn's history. Production uses the refreshing variant so+ /// the active profile and identity-file edits reach the next message+ /// (#6027, #6028); tests pin a fixed literal.+ pub(crate) system_prompt: super::ChannelSystemPrompt,pub(crate) model: Arc<String>,pub(crate) temperature: f64,pub(crate) auto_save_memory: bool,diff --git a/src/openhuman/channels/context_tests.rs b/src/openhuman/channels/context_tests.rsindex 531618271a..40f7a499cc 100644--- a/src/openhuman/channels/context_tests.rs+++ b/src/openhuman/channels/context_tests.rs@@ -52,7 +52,7 @@ fn runtime_context() -> ChannelRuntimeContext {default_provider: Arc::new("default".into()),memory: crate::openhuman::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),tools_registry: Arc::new(vec![Box::new(DummyTool) as Box<dyn Tool>]),- system_prompt: Arc::new("prompt".into()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("prompt"),model: Arc::new("model".into()),temperature: 0.0,auto_save_memory: false,diff --git a/src/openhuman/channels/mod.rs b/src/openhuman/channels/mod.rsindex 4e6b60dbfa..e158c338f1 100644--- a/src/openhuman/channels/mod.rs+++ b/src/openhuman/channels/mod.rs@@ -49,6 +49,11 @@ pub(crate) mod relay_runtime;mod routes;#[cfg(feature = "channels")]mod runtime;+#[cfg(feature = "channels")]+pub(crate) mod system_prompt;++#[cfg(feature = "channels")]+pub(crate) use system_prompt::ChannelSystemPrompt;#[cfg(all(feature = "channels", test))]mod tests;diff --git a/src/openhuman/channels/routes_tests.rs b/src/openhuman/channels/routes_tests.rsindex 2f43c60004..2be100d81c 100644--- a/src/openhuman/channels/routes_tests.rs+++ b/src/openhuman/channels/routes_tests.rs@@ -129,7 +129,7 @@ fn runtime_context(workspace_dir: PathBuf) -> ChannelRuntimeContext {default_provider: Arc::new("openai".into()),memory: crate::openhuman::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),tools_registry: Arc::new(vec![Box::new(DummyTool) as Box<dyn Tool>]),- system_prompt: Arc::new("prompt".into()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("prompt"),model: Arc::new("reasoning-v1".into()),temperature: 0.0,auto_save_memory: false,diff --git a/src/openhuman/channels/runtime/dispatch/processor_part_02.rs b/src/openhuman/channels/runtime/dispatch/processor_part_02.rsindex da5aace594..16e9e220b3 100644--- a/src/openhuman/channels/runtime/dispatch/processor_part_02.rs+++ b/src/openhuman/channels/runtime/dispatch/processor_part_02.rs@@ -154,7 +154,11 @@ pub(crate) async fn process_channel_runtime_message(.cloned().unwrap_or_default();- let mut history = vec![ChatMessage::system(ctx.system_prompt.as_str())];+ // Re-rendered by `ChannelSystemPrompt` only when the active profile or an+ // identity file changed since the last message (#6028); otherwise the+ // same bytes as the previous turn.+ let system_prompt = ctx.system_prompt.current();+ let mut history = vec![ChatMessage::system(system_prompt.as_str())];history.append(&mut prior_turns);history.push(ChatMessage::user(&enriched_message));diff --git a/src/openhuman/channels/runtime/startup_part_01.rs b/src/openhuman/channels/runtime/startup_part_01.rsindex 7898370d40..57079d6932 100644--- a/src/openhuman/channels/runtime/startup_part_01.rs+++ b/src/openhuman/channels/runtime/startup_part_01.rs@@ -2,7 +2,7 @@ use super::dispatch::{run_message_dispatch_loop, RuntimeChannelMessage};use super::supervision::{compute_max_in_flight_messages, spawn_supervised_listener};use crate::core::bus::BUS;use crate::core::events::DomainEvent;-use crate::openhuman::agent::context::channels_prompt::build_system_prompt;+use crate::openhuman::channels::system_prompt::{ChannelPromptInputs, ChannelSystemPrompt};use crate::openhuman::agent::harness::build_tool_instructions_filtered;use crate::openhuman::agent::host_runtime;use crate::openhuman::channels::context::{@@ -374,20 +374,6 @@ pub async fn start_channels(mut config: Config) -> Result<()> {} else {None};- // `channel_name = None` on startup: the channel runtime wires up- // multiple providers in parallel, so there's no single platform to- // name here. The capability block falls back to a platform-agnostic- // "messaging bot" phrasing. Per-channel renderers that want a- // named capabilities section can call `build_system_prompt` with- // `Some(name)` directly.- let mut system_prompt = build_system_prompt(- &workspace,- &model,- &tool_descs,- &skills,- bootstrap_max_chars,- None,- );// Filter out Workflow-category tools (e.g. Composio, Apify) from the// main agent prompt — those are only available to the integrations_agent// subagent via category_filter = "skill".@@ -397,10 +383,28 @@ pub async fn start_channels(mut config: Config) -> Result<()> {.collect();let non_skill_refs: Vec<&dyn crate::openhuman::tools::Tool> =non_skill_tools.iter().map(|t| t.as_ref()).collect();- system_prompt.push_str(&build_tool_instructions_filtered(&non_skill_refs));- // Tell the model its current filesystem access boundaries so it self-limits- // (advisory only — the SecurityPolicy enforces these regardless).- system_prompt.push_str(&format_access_context(&security));+ // Everything after the rendered prompt is fixed for the process: the+ // tool-instruction block, then the model's current filesystem access+ // boundaries so it self-limits (advisory only — the SecurityPolicy+ // enforces these regardless).+ let mut prompt_suffix = build_tool_instructions_filtered(&non_skill_refs);+ prompt_suffix.push_str(&format_access_context(&security));+ // The prompt itself is rendered here for the current identity and+ // re-rendered whenever the active profile or an identity file changes+ // (#6027, #6028). `channel_name = None`: the runtime wires up multiple+ // providers in parallel, so the capability block keeps its+ // platform-agnostic "messaging bot" phrasing.+ let system_prompt = ChannelSystemPrompt::refreshing(ChannelPromptInputs {+ workspace_dir: workspace.clone(),+ model: model.clone(),+ tool_descs: tool_descs+ .iter()+ .map(|(name, desc)| ((*name).to_string(), (*desc).to_string()))+ .collect(),+ skills: skills.clone(),+ bootstrap_max_chars,+ suffix: prompt_suffix,+ });if !skills.is_empty() {println!(@@ -598,7 +602,7 @@ pub async fn start_channels(mut config: Config) -> Result<()> {.await.map_err(|e| anyhow::anyhow!("channels startup: memory unavailable: {e}"))?,tools_registry: Arc::clone(&tools_registry),- system_prompt: Arc::new(system_prompt),+ system_prompt,model: Arc::new(model.clone()),temperature,auto_save_memory: config.memory.auto_save,diff --git a/src/openhuman/channels/runtime/test_support.rs b/src/openhuman/channels/runtime/test_support.rsindex 6b7800dc13..e157748ed3 100644--- a/src/openhuman/channels/runtime/test_support.rs+++ b/src/openhuman/channels/runtime/test_support.rs@@ -15,12 +15,14 @@ use crate::openhuman::agent::progress::AgentProgress;use crate::openhuman::channels::context::{ChannelRuntimeContext, CHANNEL_MESSAGE_TIMEOUT_SECS};use crate::openhuman::channels::traits::{ChannelMessage, SendMessage};use crate::openhuman::channels::Channel;+use crate::openhuman::channels::ChannelSystemPrompt;use crate::openhuman::config::{MultimodalConfig, MultimodalFileConfig, ReliabilityConfig};use crate::openhuman::inference::provider::ProviderRuntimeOptions;use crate::openhuman::tools::{Tool, ToolResult};use anyhow::Result;use async_trait::async_trait;use std::collections::HashMap;+use std::path::PathBuf;use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;@@ -41,6 +43,12 @@ pub struct DispatchHarnessOptions {pub timeout_secs: u64,pub seed_history_len: usize,pub memory_entries: Vec<TestMemoryEntry>,+ /// Workspace the runtime context reports; `None` falls back to the OS temp dir.+ pub(crate) workspace_dir: Option<PathBuf>,+ /// The prompt every dispatch is seeded with; `None` pins a fixed literal.+ /// Pass one `ChannelSystemPrompt::refreshing` clone to several dispatches+ /// to observe a re-render across them.+ pub(crate) system_prompt: Option<ChannelSystemPrompt>,}impl Default for DispatchHarnessOptions {@@ -58,6 +66,8 @@ impl Default for DispatchHarnessOptions {timeout_secs: CHANNEL_MESSAGE_TIMEOUT_SECS,seed_history_len: 0,memory_entries: Vec::new(),+ workspace_dir: None,+ system_prompt: None,}}}@@ -486,6 +496,14 @@ pub async fn run_dispatch_harness(options: DispatchHarnessOptions) -> DispatchHa);}+ let harness_system_prompt = options+ .system_prompt+ .clone()+ .unwrap_or_else(|| ChannelSystemPrompt::fixed("system prompt"));+ let harness_workspace_dir = options+ .workspace_dir+ .clone()+ .unwrap_or_else(std::env::temp_dir);let ctx = Arc::new(ChannelRuntimeContext {channels_by_name: Arc::new(channels_by_name),turn_model_source: Some(@@ -500,7 +518,7 @@ pub async fn run_dispatch_harness(options: DispatchHarnessOptions) -> DispatchHa.collect(),})),tools_registry: Arc::new(vec![Box::new(HarnessTool) as Box<dyn Tool>]),- system_prompt: Arc::new("system prompt".to_string()),+ system_prompt: harness_system_prompt,model: Arc::new("harness-model".to_string()),temperature: 0.0,auto_save_memory: true,@@ -513,7 +531,7 @@ pub async fn run_dispatch_harness(options: DispatchHarnessOptions) -> DispatchHainference_url: None,reliability: Arc::new(ReliabilityConfig::default()),provider_runtime_options: ProviderRuntimeOptions::default(),- workspace_dir: Arc::new(std::env::temp_dir()),+ workspace_dir: Arc::new(harness_workspace_dir),message_timeout_secs: options.timeout_secs,multimodal: MultimodalConfig::default(),multimodal_files: MultimodalFileConfig::default(),diff --git a/src/openhuman/channels/system_prompt.rs b/src/openhuman/channels/system_prompt.rsnew file mode 100644index 0000000000..8889f1522d--- /dev/null+++ b/src/openhuman/channels/system_prompt.rs@@ -0,0 +1,345 @@+//! The channel runtime's system prompt: fixed for tests, identity-refreshing+//! in production.+//!+//! Two defects lived in the old `Arc<String>`:+//!+//! - **#6027** — the native channel runtime rendered its prompt from the+//! workspace-root `SOUL.md` and never consulted the active agent profile,+//! so a user who picked a personality got it in desktop chat and the stock+//! voice on every bot-token channel (the managed-DM path goes through+//! `web_chat` and did apply it).+//! - **#6028** — the prompt was rendered once in `start_channels` and kept+//! for the life of the process, so a profile switch, a `SOUL.md` edit or+//! the archivist writing `MEMORY.md` stayed invisible until restart.+//!+//! [`ChannelSystemPrompt::refreshing`] keeps the *inputs* of the render (tool+//! descriptions, skills, model, and the tool-instruction + access-context+//! suffix, all fixed for the process) and re-renders only when an identity+//! fingerprint changes. The fingerprint is a hash of `(mtime, len)` for the+//! files the identity is read from, so the steady state costs a few `stat`s+//! per message and hands back the same `Arc<String>` — the prompt stays+//! byte-stable within a run for prefix-cache hits, the property+//! `channels_prompt.rs` documents. Only an identity change produces new+//! bytes, which is the whole point.++use crate::openhuman::agent::context::channels_prompt::{+ build_system_prompt_with_identity, PromptIdentityOverride,+};+use crate::openhuman::agent::profiles::{+ self, AgentProfile, AgentProfileStore, DEFAULT_PROFILE_ID,+};+use crate::openhuman::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"];++/// Everything the channel prompt is rendered from except the identity files.+/// Fixed for the life of the process, as before: tools, skills, the model+/// and the security posture still need a restart to change.+#[derive(Debug, Clone)]+pub(crate) struct ChannelPromptInputs {+ pub(crate) workspace_dir: PathBuf,+ pub(crate) model: String,+ pub(crate) tool_descs: Vec<(String, String)>,+ pub(crate) skills: Vec<Workflow>,+ pub(crate) bootstrap_max_chars: Option<usize>,+ /// Appended verbatim after the rendered prompt: the tool-instruction+ /// block and the access-context block, both rendered once at boot.+ pub(crate) suffix: String,+}++/// 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>,+ /// An external soul file the profile names (`soul_md_path`); watched by+ /// the fingerprint so edits to it are picked up too.+ pub(crate) soul_md_path: Option<PathBuf>,+}++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,+ }+ }++ 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: profile+ .soul_md_path+ .as_deref()+ .map(str::trim)+ .filter(|path| !path.is_empty())+ .map(PathBuf::from),+ }+ }+}++struct PromptState {+ fingerprint: u64,+ profile_id: String,+ soul_md_path: Option<PathBuf>,+ rendered: Arc<String>,+}++/// Shared state behind [`ChannelSystemPrompt::Refreshing`].+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.+///+/// Clone-shared: every clone of a `Refreshing` prompt observes the same+/// cache, so the test harness can hand one prompt to several dispatches.+#[derive(Clone)]+pub(crate) enum ChannelSystemPrompt {+ /// A literal prompt that never changes — tests and bespoke hosts.+ Fixed(Arc<String>),+ /// Rendered from [`ChannelPromptInputs`] and re-rendered when the+ /// identity files or the active profile change.+ Refreshing(Arc<RefreshingInner>),+}++impl std::fmt::Debug for ChannelSystemPrompt {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::Fixed(text) => f+ .debug_struct("ChannelSystemPrompt::Fixed")+ .field("chars", &text.chars().count())+ .finish(),+ Self::Refreshing(inner) => {+ 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()+ }+ }+ }+}++impl ChannelSystemPrompt {+ /// A prompt that is exactly `text`, forever.+ pub(crate) fn fixed(text: impl Into<String>) -> Self {+ Self::Fixed(Arc::new(text.into()))+ }++ /// Renders the prompt for the current identity now — `start_channels`+ /// 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 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,+ }))+ }++ /// The prompt to seed the next turn with. For a refreshing prompt this+ /// checks the identity fingerprint and re-renders on a mismatch; when+ /// nothing changed it returns the cached `Arc`, pointer-equal to the+ /// previous call's.+ pub(crate) fn current(&self) -> Arc<String> {+ match self {+ Self::Fixed(text) => Arc::clone(text),+ Self::Refreshing(inner) => inner.current(),+ }+ }+}++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(),+ );+ 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 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 {+ 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()+}++fn hash_file_stat(hasher: &mut DefaultHasher, path: &Path) {+ match std::fs::metadata(path) {+ Ok(meta) if meta.is_file() => {+ 1u8.hash(hasher);+ meta.len().hash(hasher);+ let modified = meta+ .modified()+ .ok()+ .and_then(|time| time.duration_since(UNIX_EPOCH).ok())+ .map_or(0, |elapsed| elapsed.as_nanos());+ modified.hash(hasher);+ }+ _ => 0u8.hash(hasher),+ }+}++fn render(inputs: &ChannelPromptInputs, identity: &ChannelIdentity) -> String {+ let tool_descs: Vec<(&str, &str)> = inputs+ .tool_descs+ .iter()+ .map(|(name, desc)| (name.as_str(), desc.as_str()))+ .collect();+ // `channel_name = None`: the runtime wires up several providers at once,+ // so the capability block keeps its platform-agnostic phrasing.+ let mut prompt = build_system_prompt_with_identity(+ &inputs.workspace_dir,+ &inputs.model,+ &tool_descs,+ &inputs.skills,+ inputs.bootstrap_max_chars,+ None,+ PromptIdentityOverride {+ soul_md: identity.soul_md.as_deref(),+ memory_md: identity.memory_md.as_deref(),+ },+ );+ prompt.push_str(&inputs.suffix);+ prompt+}++/// 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() {+ "root"+ } else {+ "none"+ };+ tracing::info!(+ target: "openhuman::channels",+ profile_id = %identity.profile_id,+ soul,+ memory,+ chars = rendered.chars().count(),+ reason,+ "[channels][prompt] rendered system prompt"+ );+}++#[cfg(test)]+#[path = "system_prompt_tests.rs"]+mod tests;diff --git a/src/openhuman/channels/system_prompt_tests.rs b/src/openhuman/channels/system_prompt_tests.rsnew file mode 100644index 0000000000..5c505f8126--- /dev/null+++ b/src/openhuman/channels/system_prompt_tests.rs@@ -0,0 +1,220 @@+use super::*;+use crate::openhuman::agent::profiles::home::profile_home;+use crate::openhuman::agent::profiles::store::built_in_default_profile;+use tempfile::TempDir;++const ROOT_SOUL: &str = "# Soul\nBe helpful.";+const EDITED_ROOT_SOUL: &str = "# Soul\nBegin every reply with the word ROOTSOUL2.";+const ALICE_SOUL: &str = "I am Alice, a meticulous archivist.";++fn workspace() -> TempDir {+ let tmp = TempDir::new().expect("tempdir");+ std::fs::write(tmp.path().join("SOUL.md"), ROOT_SOUL).expect("SOUL.md");+ std::fs::write(tmp.path().join("IDENTITY.md"), "Name: OpenHuman").expect("IDENTITY.md");+ tmp+}++fn inputs(workspace_dir: &Path) -> ChannelPromptInputs {+ ChannelPromptInputs {+ workspace_dir: workspace_dir.to_path_buf(),+ model: "test-model".to_string(),+ tool_descs: vec![("shell".to_string(), "Run commands".to_string())],+ skills: Vec::new(),+ bootstrap_max_chars: None,+ suffix: "\n## Suffix\n\nstatic tail\n".to_string(),+ }+}++/// Creates a non-default profile the way the desktop UI does — through the+/// store — selects it, and gives it its own soul under its profile home.+fn activate_profile(workspace_dir: &Path, id: &str, soul: &str) {+ let mut profile = 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;+ let store = AgentProfileStore::new(workspace_dir.to_path_buf());+ store.upsert(profile).expect("upsert profile");+ store.select(id).expect("select profile");+ let home = profile_home(workspace_dir, id);+ std::fs::create_dir_all(&home).expect("profile home");+ std::fs::write(home.join("SOUL.md"), soul).expect("profile SOUL.md");+}++#[test]+fn fixed_prompt_returns_the_same_text_every_time() {+ let prompt = ChannelSystemPrompt::fixed("system prompt");+ let first = prompt.current();+ let second = prompt.current();+ assert!(+ Arc::ptr_eq(&first, &second),+ "a fixed prompt is never re-rendered"+ );+ assert_eq!(first.as_str(), "system prompt");+}++#[test]+fn refreshing_prompt_renders_root_identity_and_suffix_at_construction() {+ let ws = workspace();+ let prompt = ChannelSystemPrompt::refreshing(inputs(ws.path()));+ let text = prompt.current();+ assert!(text.contains("Be helpful"), "root SOUL.md inlined");+ assert!(text.contains("Name: OpenHuman"), "root IDENTITY.md inlined");+ assert!(text.contains("**shell**"), "tool descriptions rendered");+ assert!(text.ends_with("static tail\n"), "suffix appended verbatim");+}++#[test]+fn unchanged_identity_hands_back_the_same_arc() {+ let ws = workspace();+ let prompt = ChannelSystemPrompt::refreshing(inputs(ws.path()));+ let first = prompt.current();+ let second = prompt.current();+ assert!(+ Arc::ptr_eq(&first, &second),+ "no identity change must mean no re-render (prefix-cache stability)"+ );+}++#[test]+fn clones_share_one_cache() {+ let ws = workspace();+ let prompt = ChannelSystemPrompt::refreshing(inputs(ws.path()));+ let twin = prompt.clone();+ assert!(Arc::ptr_eq(&prompt.current(), &twin.current()));+}++#[test]+fn root_soul_edit_is_picked_up_without_restart() {+ let ws = workspace();+ let prompt = ChannelSystemPrompt::refreshing(inputs(ws.path()));+ let before = prompt.current();+ assert!(before.contains("Be helpful"));++ std::fs::write(ws.path().join("SOUL.md"), EDITED_ROOT_SOUL).expect("edit SOUL.md");+ let after = prompt.current();+ assert!(!Arc::ptr_eq(&before, &after), "an edit must re-render");+ assert!(+ after.contains("ROOTSOUL2"),+ "the edited soul is what renders"+ );+ assert!(!after.contains("Be helpful"), "the stale soul is gone");++ let settled = prompt.current();+ assert!(+ Arc::ptr_eq(&after, &settled),+ "once re-rendered the prompt is stable again"+ );+}++#[test]+fn profile_switch_replaces_root_soul_with_profile_soul() {+ let ws = workspace();+ let prompt = ChannelSystemPrompt::refreshing(inputs(ws.path()));+ assert!(prompt.current().contains("Be helpful"));++ activate_profile(ws.path(), "alice", ALICE_SOUL);+ let text = prompt.current();+ assert!(+ text.contains(ALICE_SOUL),+ "the active profile's soul renders"+ );+ assert!(+ !text.contains("Be helpful"),+ "the profile soul replaces the root soul rather than joining it"+ );+ assert!(+ text.contains("Name: OpenHuman"),+ "IDENTITY.md stays the root file"+ );++ let settled = prompt.current();+ assert!(Arc::ptr_eq(&text, &settled), "stable after the switch");+}++#[test]+fn profile_soul_edit_is_picked_up_without_restart() {+ let ws = workspace();+ activate_profile(ws.path(), "alice", ALICE_SOUL);+ let prompt = ChannelSystemPrompt::refreshing(inputs(ws.path()));+ assert!(prompt.current().contains(ALICE_SOUL));++ std::fs::write(+ profile_home(ws.path(), "alice").join("SOUL.md"),+ "I am Alice, and today I am brief.",+ )+ .expect("edit profile SOUL.md");+ let text = prompt.current();+ assert!(text.contains("today I am brief"));+ assert!(!text.contains("meticulous archivist"));+}++#[test]+fn root_memory_written_after_boot_is_included() {+ let ws = workspace();+ let prompt = ChannelSystemPrompt::refreshing(inputs(ws.path()));+ assert!(+ !prompt.current().contains("### MEMORY.md"),+ "fresh install: no MEMORY.md"+ );++ std::fs::write(ws.path().join("MEMORY.md"), "# Memory\nUser likes Rust.").expect("MEMORY.md");+ let text = prompt.current();+ assert!(text.contains("### MEMORY.md"));+ assert!(text.contains("User likes Rust."));+}++#[test]+fn unreadable_profile_store_falls_back_to_root_identity() {+ let ws = workspace();+ std::fs::write(ws.path().join("agent_profiles.json"), "{ this is not json").expect("corrupt");+ let prompt = ChannelSystemPrompt::refreshing(inputs(ws.path()));+ let text = prompt.current();+ assert!(+ text.contains("Be helpful"),+ "root soul renders when the store is unreadable"+ );+ assert_eq!(+ resolve_channel_identity_once(ws.path(), &AtomicBool::new(false)).profile_id,+ DEFAULT_PROFILE_ID+ );+}++#[test]+fn identity_fingerprint_distinguishes_missing_from_present() {+ let ws = workspace();+ let before = identity_fingerprint(ws.path(), DEFAULT_PROFILE_ID, None);+ std::fs::write(ws.path().join("PROFILE.md"), "Name: Test User").expect("PROFILE.md");+ let after = identity_fingerprint(ws.path(), DEFAULT_PROFILE_ID, None);+ assert_ne!(before, after, "a file appearing must move the fingerprint");+ assert_eq!(+ after,+ identity_fingerprint(ws.path(), DEFAULT_PROFILE_ID, None),+ "the fingerprint is deterministic for an unchanged tree"+ );+}++#[test]+fn identity_fingerprint_watches_the_profile_store_file() {+ let ws = workspace();+ let before = identity_fingerprint(ws.path(), DEFAULT_PROFILE_ID, None);+ activate_profile(ws.path(), "alice", ALICE_SOUL);+ let after = identity_fingerprint(ws.path(), DEFAULT_PROFILE_ID, None);+ assert_ne!(+ before, after,+ "writing through AgentProfileStore must touch the watched file"+ );+}++#[test]+fn debug_output_names_the_variant_without_leaking_the_prompt() {+ let ws = workspace();+ let fixed = format!("{:?}", ChannelSystemPrompt::fixed("secret soul text"));+ assert!(fixed.contains("Fixed"));+ assert!(!fixed.contains("secret soul text"));+ let refreshing = format!("{:?}", ChannelSystemPrompt::refreshing(inputs(ws.path())));+ assert!(refreshing.contains("Refreshing"));+ assert!(refreshing.contains(DEFAULT_PROFILE_ID));+ assert!(!refreshing.contains("Be helpful"));+}diff --git a/src/openhuman/channels/tests/context.rs b/src/openhuman/channels/tests/context.rsindex ac28cb2d1d..e0fac385cb 100644--- a/src/openhuman/channels/tests/context.rs+++ b/src/openhuman/channels/tests/context.rs@@ -69,7 +69,7 @@ fn compact_sender_history_keeps_recent_truncated_messages() {default_provider: Arc::new("test-provider".to_string()),memory: Arc::new(super::common::NoopMemory),tools_registry: Arc::new(vec![]),- system_prompt: Arc::new("system".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("system"),model: Arc::new("test-model".to_string()),temperature: 0.0,auto_save_memory: false,diff --git a/src/openhuman/channels/tests/discord_integration.rs b/src/openhuman/channels/tests/discord_integration.rsindex b8f81b3c7e..02546aebe2 100644--- a/src/openhuman/channels/tests/discord_integration.rs+++ b/src/openhuman/channels/tests/discord_integration.rs@@ -113,7 +113,7 @@ fn make_discord_ctx(default_provider: Arc::new("test-provider".to_string()),memory: crate::openhuman::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),tools_registry: Arc::new(vec![]),- system_prompt: Arc::new("test-system-prompt".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("test-system-prompt"),model: Arc::new("test-model".to_string()),temperature: 0.0,auto_save_memory: false,diff --git a/src/openhuman/channels/tests/memory.rs b/src/openhuman/channels/tests/memory.rsindex 5468edfdb0..52096088d7 100644--- a/src/openhuman/channels/tests/memory.rs+++ b/src/openhuman/channels/tests/memory.rs@@ -145,7 +145,7 @@ async fn process_channel_message_restores_per_sender_history_on_follow_ups() {default_provider: Arc::new("test-provider".to_string()),memory: crate::openhuman::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),tools_registry: Arc::new(vec![]),- system_prompt: Arc::new("test-system-prompt".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("test-system-prompt"),model: Arc::new("test-model".to_string()),temperature: 0.0,auto_save_memory: false,@@ -234,7 +234,7 @@ async fn process_channel_message_uses_autosaved_memory_after_history_is_cleared(default_provider: Arc::new("test-provider".to_string()),memory,tools_registry: Arc::new(vec![]),- system_prompt: Arc::new("test-system-prompt".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("test-system-prompt"),model: Arc::new("test-model".to_string()),temperature: 0.0,auto_save_memory: true,diff --git a/src/openhuman/channels/tests/mod.rs b/src/openhuman/channels/tests/mod.rsindex 49d4f9c2e6..4f852d2005 100644--- a/src/openhuman/channels/tests/mod.rs+++ b/src/openhuman/channels/tests/mod.rs@@ -3,6 +3,7 @@ mod discord_integration;mod health;mod identity;mod memory;+mod personality;mod prompt;mod runtime_dispatch;mod runtime_tool_calls;diff --git a/src/openhuman/channels/tests/personality.rs b/src/openhuman/channels/tests/personality.rsnew file mode 100644index 0000000000..637be65d81--- /dev/null+++ b/src/openhuman/channels/tests/personality.rs@@ -0,0 +1,125 @@+//! Acceptance mirrors for #6027 (channel turns carry the active personality)+//! and #6028 (identity edits reach the next channel turn without a restart).+//!+//! The first test is the channel twin of+//! `build_session_agent_injects_profile_soul_into_prompt` in the session+//! builder tests: the same profile/soul setup, asserted against the prompt a+//! channel turn is seeded with. The second drives the real dispatch path+//! twice through `run_dispatch_harness` with one shared prompt and edits+//! `SOUL.md` in between — the reproduction in the issue, as a test.++use super::super::runtime::test_support::{run_dispatch_harness, DispatchHarnessOptions};+use super::common::make_workspace;+use crate::openhuman::agent::profiles::home::profile_home;+use crate::openhuman::agent::profiles::store::built_in_default_profile;+use crate::openhuman::agent::profiles::AgentProfileStore;+use crate::openhuman::channels::system_prompt::ChannelPromptInputs;+use crate::openhuman::channels::ChannelSystemPrompt;+use std::path::Path;++const ALICE_SOUL: &str = "I am Alice, a meticulous archivist.";+const EDITED_ROOT_SOUL: &str = "# Soul\nBegin every reply with the word ROOTSOUL2.";++fn inputs(workspace_dir: &Path) -> ChannelPromptInputs {+ ChannelPromptInputs {+ workspace_dir: workspace_dir.to_path_buf(),+ model: "test-model".to_string(),+ tool_descs: Vec::new(),+ skills: Vec::new(),+ bootstrap_max_chars: None,+ suffix: String::new(),+ }+}++fn activate_profile(workspace_dir: &Path, id: &str, soul: &str) {+ let mut profile = 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;+ let store = AgentProfileStore::new(workspace_dir.to_path_buf());+ store.upsert(profile).expect("upsert profile");+ store.select(id).expect("select profile");+ let home = profile_home(workspace_dir, id);+ std::fs::create_dir_all(&home).expect("profile home");+ std::fs::write(home.join("SOUL.md"), soul).expect("profile SOUL.md");+}++/// #6027 — with a non-default profile active, the channel prompt carries+/// that profile's soul and not the workspace-root one, while the files a+/// profile does not own (IDENTITY.md) still come from the root.+#[test]+fn channel_prompt_inlines_active_profile_soul_instead_of_root() {+ let ws = make_workspace();+ activate_profile(ws.path(), "alice", ALICE_SOUL);++ let prompt = ChannelSystemPrompt::refreshing(inputs(ws.path()));+ let text = prompt.current();++ assert!(+ text.contains(ALICE_SOUL),+ "the channel prompt must include the active profile's SOUL.md"+ );+ assert!(+ !text.contains("Be helpful"),+ "profile SOUL.md must replace, not accompany, workspace-root SOUL.md"+ );+ assert!(+ text.contains("Name: OpenHuman"),+ "IDENTITY.md is not a profile file and stays the root one"+ );+}++/// #6028 — a `SOUL.md` edit made while the runtime is up changes the system+/// message of the next dispatched turn; no restart, no new context.+#[tokio::test]+async fn channel_reply_follows_soul_edit_without_restart() {+ let ws = make_workspace();+ let prompt = ChannelSystemPrompt::refreshing(inputs(ws.path()));++ let first = run_dispatch_harness(DispatchHarnessOptions {+ workspace_dir: Some(ws.path().to_path_buf()),+ system_prompt: Some(prompt.clone()),+ content: "hi".to_string(),+ ..Default::default()+ })+ .await;+ assert!(+ first.handler_history_text.contains("Be helpful"),+ "first turn is seeded with the root soul as written at boot"+ );++ std::fs::write(ws.path().join("SOUL.md"), EDITED_ROOT_SOUL).expect("edit SOUL.md");++ let second = run_dispatch_harness(DispatchHarnessOptions {+ workspace_dir: Some(ws.path().to_path_buf()),+ system_prompt: Some(prompt.clone()),+ content: "hi again".to_string(),+ ..Default::default()+ })+ .await;+ assert!(+ second.handler_history_text.contains("ROOTSOUL2"),+ "the edited soul must reach the very next turn"+ );+ assert!(+ !second.handler_history_text.contains("Be helpful"),+ "the stale boot-time soul must be gone"+ );+}++/// The fixed variant the other channel tests rely on is untouched by the+/// refresh machinery: its text is what was given, every time.+#[tokio::test]+async fn fixed_prompt_seeds_every_turn_unchanged() {+ let ws = make_workspace();+ let observed = run_dispatch_harness(DispatchHarnessOptions {+ workspace_dir: Some(ws.path().to_path_buf()),+ system_prompt: Some(ChannelSystemPrompt::fixed("pinned prompt")),+ ..Default::default()+ })+ .await;+ assert!(observed.handler_history_text.starts_with("pinned prompt"));+ assert!(!observed.handler_history_text.contains("Be helpful"));+}diff --git a/src/openhuman/channels/tests/runtime_dispatch.rs b/src/openhuman/channels/tests/runtime_dispatch.rsindex ebd0942bc2..9c1551665b 100644--- a/src/openhuman/channels/tests/runtime_dispatch.rs+++ b/src/openhuman/channels/tests/runtime_dispatch.rs@@ -128,7 +128,9 @@ async fn message_dispatch_processes_messages_in_parallel() {Vec::new(),),tools_registry: Arc::new(vec![]),- system_prompt: Arc::new("test-system-prompt".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed(+ "test-system-prompt",+ ),model: Arc::new("test-model".to_string()),temperature: 0.0,auto_save_memory: false,@@ -203,7 +205,7 @@ async fn process_channel_message_cancels_scoped_typing_task() {default_provider: Arc::new("test-provider".to_string()),memory: crate::openhuman::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),tools_registry: Arc::new(vec![]),- system_prompt: Arc::new("test-system-prompt".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("test-system-prompt"),model: Arc::new("test-model".to_string()),temperature: 0.0,auto_save_memory: false,@@ -295,7 +297,7 @@ async fn dispatch_routes_through_agent_run_turn_bus_handler() {default_provider: Arc::new("test-provider".to_string()),memory: crate::openhuman::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),tools_registry: Arc::new(vec![]),- system_prompt: Arc::new("test-system-prompt".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("test-system-prompt"),model: Arc::new("test-model".to_string()),temperature: 0.0,auto_save_memory: false,@@ -383,7 +385,7 @@ async fn channel_processed_event_records_resolved_agent_route() {default_provider: Arc::new("requested-provider".to_string()),memory: crate::openhuman::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),tools_registry: Arc::new(vec![]),- system_prompt: Arc::new("test-system-prompt".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("test-system-prompt"),model: Arc::new("requested-model".to_string()),temperature: 0.0,auto_save_memory: false,@@ -499,7 +501,7 @@ async fn process_channel_message_hardens_multimodal_files_against_smuggled_markedefault_provider: Arc::new("test-provider".to_string()),memory: crate::openhuman::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),tools_registry: Arc::new(vec![]),- system_prompt: Arc::new("test-system-prompt".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("test-system-prompt"),model: Arc::new("test-model".to_string()),temperature: 0.0,auto_save_memory: false,@@ -586,7 +588,7 @@ async fn process_channel_message_hardens_against_relative_path_markers() {default_provider: Arc::new("test-provider".to_string()),memory: crate::openhuman::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),tools_registry: Arc::new(vec![]),- system_prompt: Arc::new("test-system-prompt".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("test-system-prompt"),model: Arc::new("test-model".to_string()),temperature: 0.0,auto_save_memory: false,diff --git a/src/openhuman/channels/tests/runtime_tool_calls.rs b/src/openhuman/channels/tests/runtime_tool_calls.rsindex 453a5dfc60..d9ba70488e 100644--- a/src/openhuman/channels/tests/runtime_tool_calls.rs+++ b/src/openhuman/channels/tests/runtime_tool_calls.rs@@ -33,7 +33,7 @@ async fn process_channel_message_executes_native_tool_calls() {default_provider: Arc::new("test-provider".to_string()),memory: crate::openhuman::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),tools_registry: Arc::new(vec![Box::new(MockPriceTool)]),- system_prompt: Arc::new("test-system-prompt".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("test-system-prompt"),model: Arc::new("test-model".to_string()),temperature: 0.0,auto_save_memory: false,@@ -110,7 +110,7 @@ async fn process_channel_message_handles_models_command_without_llm_call() {default_provider: Arc::new("test-provider".to_string()),memory: crate::openhuman::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),tools_registry: Arc::new(vec![]),- system_prompt: Arc::new("test-system-prompt".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("test-system-prompt"),model: Arc::new("default-model".to_string()),temperature: 0.0,auto_save_memory: false,@@ -215,7 +215,7 @@ async fn process_channel_message_uses_route_override_provider_and_model() {default_provider: Arc::new("test-provider".to_string()),memory: crate::openhuman::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),tools_registry: Arc::new(vec![]),- system_prompt: Arc::new("test-system-prompt".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("test-system-prompt"),model: Arc::new("default-model".to_string()),temperature: 0.0,auto_save_memory: false,@@ -270,7 +270,7 @@ async fn process_channel_message_respects_configured_max_tool_iterations_above_ddefault_provider: Arc::new("test-provider".to_string()),memory: crate::openhuman::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),tools_registry: Arc::new(vec![Box::new(MockPriceTool)]),- system_prompt: Arc::new("test-system-prompt".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("test-system-prompt"),model: Arc::new("test-model".to_string()),temperature: 0.0,auto_save_memory: false,@@ -332,7 +332,7 @@ async fn process_channel_message_reports_configured_max_tool_iterations_limit()default_provider: Arc::new("test-provider".to_string()),memory: crate::openhuman::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),tools_registry: Arc::new(vec![Box::new(MockPriceTool)]),- system_prompt: Arc::new("test-system-prompt".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("test-system-prompt"),model: Arc::new("test-model".to_string()),temperature: 0.0,auto_save_memory: false,diff --git a/src/openhuman/channels/tests/telegram_integration.rs b/src/openhuman/channels/tests/telegram_integration.rsindex cbdca00543..0f54ccf573 100644--- a/src/openhuman/channels/tests/telegram_integration.rs+++ b/src/openhuman/channels/tests/telegram_integration.rs@@ -89,7 +89,7 @@ fn make_test_context(default_provider: Arc::new("test-provider".to_string()),memory: crate::openhuman::memory::guard::in_memory::FixedRecallProvider::guarded(Vec::new()),tools_registry: Arc::new(vec![]),- system_prompt: Arc::new("test-system-prompt".to_string()),+ system_prompt: crate::openhuman::channels::ChannelSystemPrompt::fixed("test-system-prompt"),model: Arc::new("test-model".to_string()),temperature: 0.0,auto_save_memory: false,