Skip to content

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

fix(channels): honour the profile suffix, watch the real soul file, render identity last

Shanude46c516e72d
diff --git a/src/openhuman/agent/context/channels_prompt.rs b/src/openhuman/agent/context/channels_prompt.rs
index 96a7966f3b..ccaf17f636 100644
--- a/src/openhuman/agent/context/channels_prompt.rs
+++ b/src/openhuman/agent/context/channels_prompt.rs
@@ -45,6 +45,34 @@ pub struct PromptIdentityOverride<'a> {
pub memory_md: Option<&'a str>,
}
+/// Where [`build_system_prompt_with_identity`] puts the `## Project Context`
+/// block — the identity files.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ProjectContextPlacement {
+ /// Between the Workspace and Date & Time sections: the historical layout,
+ /// and what [`build_system_prompt`] renders.
+ Inline,
+ /// Not rendered here; the caller appends [`render_project_context`] where
+ /// it wants it. The channel runtime puts the persona *after* its tool
+ /// schemas — a one-line soul followed by ~140k chars of schemas was not
+ /// being honoured, while the same soul near the end of the prompt is
+ /// (#6027).
+ Omitted,
+}
+
+/// Appends the `## Project Context` block — the identity files, with a
+/// profile's soul / memory substituted per `identity` — to `prompt`.
+pub fn render_project_context(
+ prompt: &mut String,
+ workspace_dir: &Path,
+ bootstrap_max_chars: Option<usize>,
+ identity: PromptIdentityOverride<'_>,
+) {
+ prompt.push_str("## Project Context\n\n");
+ let max_chars = bootstrap_max_chars.unwrap_or(BOOTSTRAP_MAX_CHARS);
+ load_openclaw_bootstrap_files(prompt, workspace_dir, max_chars, identity);
+}
+
/// Load OpenClaw format bootstrap files into the prompt.
fn load_openclaw_bootstrap_files(
prompt: &mut String,
@@ -121,11 +149,13 @@ pub fn build_system_prompt(
bootstrap_max_chars,
channel_name,
PromptIdentityOverride::default(),
+ ProjectContextPlacement::Inline,
)
}
/// [`build_system_prompt`] with the active profile's identity substituted
-/// into the bootstrap section (see [`PromptIdentityOverride`]).
+/// into the bootstrap section (see [`PromptIdentityOverride`]) and that
+/// section rendered per `placement`.
pub fn build_system_prompt_with_identity(
workspace_dir: &Path,
model_name: &str,
@@ -134,6 +164,7 @@ pub fn build_system_prompt_with_identity(
bootstrap_max_chars: Option<usize>,
channel_name: Option<&str>,
identity: PromptIdentityOverride<'_>,
+ placement: ProjectContextPlacement,
) -> String {
use std::fmt::Write;
let mut prompt = String::with_capacity(8192);
@@ -207,9 +238,9 @@ pub fn build_system_prompt_with_identity(
);
// ── 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, identity);
+ if placement == ProjectContextPlacement::Inline {
+ render_project_context(&mut prompt, workspace_dir, bootstrap_max_chars, identity);
+ }
// ── 6. Date & Time ──────────────────────────────────────────
let now = chrono::Local::now();
diff --git a/src/openhuman/agent/context/channels_prompt_tests.rs b/src/openhuman/agent/context/channels_prompt_tests.rs
index c111b9619b..c352f1a6ec 100644
--- a/src/openhuman/agent/context/channels_prompt_tests.rs
+++ b/src/openhuman/agent/context/channels_prompt_tests.rs
@@ -138,6 +138,7 @@ fn identity_override_replaces_root_soul_and_memory() {
soul_md: Some("I am Alice, a meticulous archivist."),
memory_md: Some("alice private memory marker"),
},
+ ProjectContextPlacement::Inline,
);
assert!(prompt.contains("### SOUL.md"), "SOUL slot keeps its header");
@@ -173,6 +174,7 @@ fn memory_override_renders_even_when_root_memory_is_absent() {
soul_md: None,
memory_md: Some("profile-only memory"),
},
+ ProjectContextPlacement::Inline,
);
assert!(prompt.contains("root soul"), "no soul override → root soul");
assert!(prompt.contains("### MEMORY.md"));
@@ -192,9 +194,48 @@ fn empty_identity_override_matches_root_render_byte_for_byte() {
Some(50),
Some("Discord"),
PromptIdentityOverride::default(),
+ ProjectContextPlacement::Inline,
);
assert_eq!(
root, overridden,
"the wrapper and an empty override are one render"
);
}
+
+#[test]
+fn omitted_placement_leaves_the_project_context_to_the_caller() {
+ let tmp = identity_workspace();
+ let identity = PromptIdentityOverride {
+ soul_md: Some("I am Alice, a meticulous archivist."),
+ memory_md: None,
+ };
+ let mut prompt = build_system_prompt_with_identity(
+ tmp.path(),
+ "model",
+ &[],
+ &[],
+ None,
+ Some("Discord"),
+ identity,
+ ProjectContextPlacement::Omitted,
+ );
+ assert!(
+ !prompt.contains("## Project Context"),
+ "omitted → nothing rendered"
+ );
+ assert!(!prompt.contains("I am Alice"));
+ assert!(
+ prompt.contains("## Channel Capabilities"),
+ "the rest still renders"
+ );
+
+ prompt.push_str("tool schemas go here\n");
+ render_project_context(&mut prompt, tmp.path(), None, identity);
+ let ctx = prompt
+ .find("## Project Context")
+ .expect("appended by the caller");
+ assert!(ctx > prompt.find("tool schemas go here").unwrap());
+ assert!(prompt.contains("I am Alice, a meticulous archivist."));
+ assert!(!prompt.contains("conflicting workspace-root identity"));
+ assert!(prompt.contains("Name: OpenHuman"));
+}
diff --git a/src/openhuman/agent/profiles/paths.rs b/src/openhuman/agent/profiles/paths.rs
index dde1913342..b291e4293e 100644
--- a/src/openhuman/agent/profiles/paths.rs
+++ b/src/openhuman/agent/profiles/paths.rs
@@ -1,7 +1,7 @@
//! Personality-scoped path resolution and context for multi-agent sessions.
use std::hash::{Hash, Hasher};
-use std::path::{Component, Path};
+use std::path::{Component, Path, PathBuf};
use super::home::validate_profile_id;
use super::types::AgentProfile;
@@ -46,6 +46,43 @@ pub fn session_raw_subdir_for_suffix(suffix: &str) -> String {
}
}
+/// 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
@@ -97,44 +134,16 @@ pub fn resolve_personality_soul(workspace_dir: &Path, profile: &AgentProfile) ->
}
}
- if let Some(ref rel_path) = profile.soul_md_path {
- 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"
- );
- // Fall through to inline check below.
+ 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();
- }
- 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.
- // Note: synchronous fs calls here are intentional — soul_md is loaded
- // during prompt construction on a tokio blocking thread; the workspace
- // is always local disk (never a remote mount).
- 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 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!(
diff --git a/src/openhuman/agent/profiles/prompt_section.rs b/src/openhuman/agent/profiles/prompt_section.rs
index c6761b60ea..9e234d284a 100644
--- a/src/openhuman/agent/profiles/prompt_section.rs
+++ b/src/openhuman/agent/profiles/prompt_section.rs
@@ -54,20 +54,31 @@ impl PromptSection for AgentProfilePromptSection {
}
fn build(&self, _ctx: &PromptContext<'_>) -> Result<String> {
- let body = self.body.trim();
- let notice = self.workspace_notice.as_deref().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 Ok(String::new());
- }
- Ok(format!("## Agent profile\n\n{}", parts.join("\n\n")))
+ 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)]
diff --git a/src/openhuman/channels/README.md b/src/openhuman/channels/README.md
index 982c95e23b..17bf8bad32 100644
--- a/src/openhuman/channels/README.md
+++ b/src/openhuman/channels/README.md
@@ -9,7 +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.
+- `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 — with the `## Project Context` identity block placed *after* the tool schemas and access context, and the profile's `system_prompt_suffix` as the trailing `## Agent profile` block — 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/system_prompt.rs b/src/openhuman/channels/system_prompt.rs
index 8889f1522d..241de6d26f 100644
--- a/src/openhuman/channels/system_prompt.rs
+++ b/src/openhuman/channels/system_prompt.rs
@@ -23,7 +23,8 @@
//! bytes, which is the whole point.
use crate::openhuman::agent::context::channels_prompt::{
- build_system_prompt_with_identity, PromptIdentityOverride,
+ build_system_prompt_with_identity, render_project_context, ProjectContextPlacement,
+ PromptIdentityOverride,
};
use crate::openhuman::agent::profiles::{
self, AgentProfile, AgentProfileStore, DEFAULT_PROFILE_ID,
@@ -67,9 +68,13 @@ pub(crate) struct ChannelIdentity {
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.
+ /// 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>,
}
impl ChannelIdentity {
@@ -80,6 +85,7 @@ impl ChannelIdentity {
soul_md: None,
memory_md: None,
soul_md_path: None,
+ prompt_suffix: None,
}
}
@@ -88,12 +94,13 @@ impl ChannelIdentity {
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
+ soul_md_path: profiles::paths::soul_md_file_path(workspace_dir, profile),
+ prompt_suffix: profile
+ .system_prompt_suffix
.as_deref()
.map(str::trim)
- .filter(|path| !path.is_empty())
- .map(PathBuf::from),
+ .filter(|suffix| !suffix.is_empty())
+ .map(str::to_string),
}
}
}
@@ -297,6 +304,10 @@ fn render(inputs: &ChannelPromptInputs, identity: &ChannelIdentity) -> String {
.iter()
.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(),
+ };
// `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(
@@ -306,15 +317,45 @@ fn render(inputs: &ChannelPromptInputs, identity: &ChannelIdentity) -> String {
&inputs.skills,
inputs.bootstrap_max_chars,
None,
- PromptIdentityOverride {
- soul_md: identity.soul_md.as_deref(),
- memory_md: identity.memory_md.as_deref(),
- },
+ identity_override,
+ ProjectContextPlacement::Omitted,
);
prompt.push_str(&inputs.suffix);
+ // Identity after the tool schemas and the access context: a one-line
+ // soul followed by ~140k chars of schemas was not honoured by the model,
+ // while the same soul near the end of the prompt is (#6027).
+ ensure_blank_line(&mut prompt);
+ render_project_context(
+ &mut prompt,
+ &inputs.workspace_dir,
+ 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
}
+/// Ends `prompt` with exactly one blank line so the next `##` section is
+/// separated the way the builder separates its own.
+fn ensure_blank_line(prompt: &mut String) {
+ if prompt.is_empty() || prompt.ends_with("\n\n") {
+ return;
+ }
+ if prompt.ends_with('\n') {
+ prompt.push('\n');
+ } else {
+ prompt.push_str("\n\n");
+ }
+}
+
/// 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() {
@@ -329,11 +370,17 @@ fn log_render(workspace_dir: &Path, identity: &ChannelIdentity, rendered: &str,
} 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/src/openhuman/channels/system_prompt_tests.rs b/src/openhuman/channels/system_prompt_tests.rs
index 5c505f8126..64e93a05b7 100644
--- a/src/openhuman/channels/system_prompt_tests.rs
+++ b/src/openhuman/channels/system_prompt_tests.rs
@@ -28,12 +28,24 @@ fn inputs(workspace_dir: &Path) -> ChannelPromptInputs {
/// 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) {
+ activate_profile_with(workspace_dir, id, soul, |_| {});
+}
+
+/// Like [`activate_profile`], with a hook to adjust the record before it is
+/// stored (a `system_prompt_suffix`, a `soul_md_path`, …).
+fn activate_profile_with(
+ workspace_dir: &Path,
+ id: &str,
+ soul: &str,
+ adjust: impl FnOnce(&mut crate::openhuman::agent::profiles::AgentProfile),
+) {
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;
+ adjust(&mut profile);
let store = AgentProfileStore::new(workspace_dir.to_path_buf());
store.upsert(profile).expect("upsert profile");
store.select(id).expect("select profile");
@@ -62,7 +74,7 @@ fn refreshing_prompt_renders_root_identity_and_suffix_at_construction() {
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");
+ assert!(text.contains("static tail"), "suffix appended verbatim");
}
#[test]
@@ -218,3 +230,75 @@ fn debug_output_names_the_variant_without_leaking_the_prompt() {
assert!(refreshing.contains(DEFAULT_PROFILE_ID));
assert!(!refreshing.contains("Be helpful"));
}
+
+#[test]
+fn profile_prompt_suffix_renders_as_the_desktop_agent_profile_block() {
+ let ws = workspace();
+ let prompt = ChannelSystemPrompt::refreshing(inputs(ws.path()));
+ assert!(!prompt.current().contains("## Agent profile"));
+
+ activate_profile_with(ws.path(), "haiku", ALICE_SOUL, |profile| {
+ profile.system_prompt_suffix = Some(" Always answer in haiku. ".to_string());
+ });
+ let text = prompt.current();
+ let block = crate::openhuman::agent::profiles::prompt_section::render_agent_profile_block(
+ "Always answer in haiku.",
+ None,
+ );
+ assert!(
+ text.contains(&block),
+ "the profile suffix must render as the same block desktop chat appends"
+ );
+ assert!(
+ text.ends_with(&format!("{block}\n\n")),
+ "the profile block is the last thing in the prompt"
+ );
+ assert!(text.contains(ALICE_SOUL));
+}
+
+#[test]
+fn identity_fingerprint_watches_a_workspace_relative_soul_md_path() {
+ let ws = workspace();
+ std::fs::create_dir_all(ws.path().join("custom")).expect("custom dir");
+ std::fs::write(
+ ws.path().join("custom/soul.md"),
+ "I am the custom file soul.",
+ )
+ .expect("soul");
+ activate_profile_with(ws.path(), "filed", "", |profile| {
+ profile.soul_md_path = Some("custom/soul.md".to_string());
+ });
+ // An empty profile-home SOUL.md falls through to soul_md_path.
+ let prompt = ChannelSystemPrompt::refreshing(inputs(ws.path()));
+ assert!(prompt.current().contains("I am the custom file soul."));
+
+ std::fs::write(
+ ws.path().join("custom/soul.md"),
+ "I am the custom file soul, freshly edited.",
+ )
+ .expect("edit soul");
+ let text = prompt.current();
+ assert!(
+ text.contains("freshly edited"),
+ "an edit to the workspace-relative soul file must be picked up"
+ );
+}
+
+#[test]
+fn identity_is_rendered_after_the_tool_suffix_on_channels() {
+ let ws = workspace();
+ let prompt = ChannelSystemPrompt::refreshing(inputs(ws.path()));
+ let text = prompt.current();
+ let suffix_at = text.find("static tail").expect("suffix present");
+ let context_at = text.find("## Project Context").expect("identity present");
+ assert!(
+ context_at > suffix_at,
+ "the identity block must follow the tool schemas / access context"
+ );
+ assert_eq!(
+ text.matches("## Project Context").count(),
+ 1,
+ "rendered exactly once"
+ );
+ assert!(text.find("Be helpful").unwrap() > context_at);
+}