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
refactor(agent): split large modules into smaller files
Steven Enamakel3ecbb6269e0b
diff --git a/crates/openhuman-core/src/agent/learning/schemas.rs b/crates/openhuman-core/src/agent/learning/schemas.rsindex 2769cd7cb2..9959cb3552 100644--- a/crates/openhuman-core/src/agent/learning/schemas.rs+++ b/crates/openhuman-core/src/agent/learning/schemas.rs@@ -1,7 +1,447 @@//! Controller schemas for the learning domain.+mod cache_helpers;+mod facet_handlers;+mod profile_handlers;++use crate::core::all::{ControllerFuture, RegisteredController};+use crate::core::{ControllerSchema, FieldSchema, TypeSchema};++use cache_helpers::{facet_to_json, forget_facet_log, full_key, get_cache};+use facet_handlers::{+ handle_forget_facet, handle_get_facet, handle_list_facets, handle_pin_facet,+ handle_reset_cache, handle_unpin_facet, handle_update_facet,+};+use profile_handlers::{+ handle_cache_stats, handle_linkedin_enrichment, handle_rebuild_cache, handle_save_profile,+};+#[cfg(test)]#[path = "schemas_tests.rs"]mod tests;-include!("schemas_part_01.rs");-include!("schemas_part_02.rs");++pub fn all_learning_controller_schemas() -> Vec<ControllerSchema> {+ vec![+ learning_schemas("learning_linkedin_enrichment"),+ learning_schemas("learning_save_profile"),+ learning_schemas("learning_rebuild_cache"),+ learning_schemas("learning_cache_stats"),+ learning_schemas("learning_list_facets"),+ learning_schemas("learning_get_facet"),+ learning_schemas("learning_update_facet"),+ learning_schemas("learning_pin_facet"),+ learning_schemas("learning_unpin_facet"),+ learning_schemas("learning_forget_facet"),+ learning_schemas("learning_reset_cache"),+ ]+}++pub fn all_learning_registered_controllers() -> Vec<RegisteredController> {+ vec![+ RegisteredController {+ schema: learning_schemas("learning_linkedin_enrichment"),+ handler: handle_linkedin_enrichment,+ },+ RegisteredController {+ schema: learning_schemas("learning_save_profile"),+ handler: handle_save_profile,+ },+ RegisteredController {+ schema: learning_schemas("learning_rebuild_cache"),+ handler: handle_rebuild_cache,+ },+ RegisteredController {+ schema: learning_schemas("learning_cache_stats"),+ handler: handle_cache_stats,+ },+ RegisteredController {+ schema: learning_schemas("learning_list_facets"),+ handler: handle_list_facets,+ },+ RegisteredController {+ schema: learning_schemas("learning_get_facet"),+ handler: handle_get_facet,+ },+ RegisteredController {+ schema: learning_schemas("learning_update_facet"),+ handler: handle_update_facet,+ },+ RegisteredController {+ schema: learning_schemas("learning_pin_facet"),+ handler: handle_pin_facet,+ },+ RegisteredController {+ schema: learning_schemas("learning_unpin_facet"),+ handler: handle_unpin_facet,+ },+ RegisteredController {+ schema: learning_schemas("learning_forget_facet"),+ handler: handle_forget_facet,+ },+ RegisteredController {+ schema: learning_schemas("learning_reset_cache"),+ handler: handle_reset_cache,+ },+ ]+}++pub fn learning_schemas(function: &str) -> ControllerSchema {+ match function {+ "learning_linkedin_enrichment" => ControllerSchema {+ namespace: "learning",+ function: "linkedin_enrichment",+ description: "Search Gmail for LinkedIn profile URLs, scrape the profile via Apify, \+ and persist the result to memory. Runs the full enrichment pipeline.",+ inputs: vec![FieldSchema {+ name: "profile_url",+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),+ comment: "Pre-found LinkedIn profile URL (skips the Gmail-search stage). \+ The frontend supplies this when it has already located the URL via \+ the webview-driven `gmail_find_linkedin_profile_url` Tauri command.",+ required: false,+ }],+ outputs: vec![+ FieldSchema {+ name: "profile_url",+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),+ comment: "LinkedIn profile URL found in Gmail, if any.",+ required: false,+ },+ FieldSchema {+ name: "profile_data",+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),+ comment: "Scraped LinkedIn profile JSON from Apify, if successful.",+ required: false,+ },+ FieldSchema {+ name: "log",+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),+ comment: "Human-readable log of each pipeline stage.",+ required: true,+ },+ ],+ },+ "learning_save_profile" => ControllerSchema {+ namespace: "learning",+ function: "save_profile",+ description: "Persist a markdown profile to `{workspace_dir}/PROFILE.md`. \+ When `summarize=true`, runs the body through the LLM compressor \+ first (same prompt as the LinkedIn-enrichment pipeline) so callers \+ can hand in raw scraped material and get the same end-state.",+ inputs: vec![+ FieldSchema {+ name: "markdown",+ ty: TypeSchema::String,+ comment: "Markdown body to persist (or to summarize first).",+ required: true,+ },+ FieldSchema {+ name: "summarize",+ ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),+ comment: "Compress through LLM before writing (default false).",+ required: false,+ },+ ],+ outputs: vec![+ FieldSchema {+ name: "path",+ ty: TypeSchema::String,+ comment: "Absolute path of the written PROFILE.md.",+ required: true,+ },+ FieldSchema {+ name: "bytes",+ ty: TypeSchema::U64,+ comment: "Bytes written.",+ required: true,+ },+ ],+ },+ "learning_rebuild_cache" => ControllerSchema {+ namespace: "learning",+ function: "rebuild_cache",+ description: "Manually trigger a stability-detector rebuild cycle. \+ Drains the candidate buffer, scores all (class, key) pairs, \+ applies class budgets, and persists the updated ambient cache. \+ Returns rebuild statistics.",+ inputs: vec![],+ outputs: vec![+ FieldSchema {+ name: "added",+ ty: TypeSchema::U64,+ comment: "Facet rows newly created in this cycle.",+ required: true,+ },+ FieldSchema {+ name: "evicted",+ ty: TypeSchema::U64,+ comment: "Facet rows demoted to Dropped or deleted.",+ required: true,+ },+ FieldSchema {+ name: "kept",+ ty: TypeSchema::U64,+ comment: "Facet rows carried over unchanged.",+ required: true,+ },+ FieldSchema {+ name: "total_size",+ ty: TypeSchema::U64,+ comment: "Total Active rows after the rebuild.",+ required: true,+ },+ ],+ },+ "learning_cache_stats" => ControllerSchema {+ namespace: "learning",+ function: "cache_stats",+ description: "Return current ambient cache statistics — total row count, \+ per-state breakdown, and per-class breakdown.",+ inputs: vec![],+ outputs: vec![+ FieldSchema {+ name: "total",+ ty: TypeSchema::U64,+ comment: "Total rows in the cache (all states).",+ required: true,+ },+ FieldSchema {+ name: "active",+ ty: TypeSchema::U64,+ comment: "Rows with state=active.",+ required: true,+ },+ FieldSchema {+ name: "provisional",+ ty: TypeSchema::U64,+ comment: "Rows with state=provisional.",+ required: true,+ },+ FieldSchema {+ name: "candidate",+ ty: TypeSchema::U64,+ comment: "Rows with state=candidate.",+ required: true,+ },+ FieldSchema {+ name: "dropped",+ ty: TypeSchema::U64,+ comment: "Rows with state=dropped.",+ required: true,+ },+ FieldSchema {+ name: "by_class",+ ty: TypeSchema::Json,+ comment: "Map of class name → row count (active rows only).",+ required: true,+ },+ ],+ },+ "learning_list_facets" => ControllerSchema {+ namespace: "learning",+ function: "list_facets",+ description: "List all facets in the ambient cache (active + provisional). \+ Optionally filter by class.",+ inputs: vec![FieldSchema {+ name: "class",+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),+ comment:+ "Optional class filter: style | identity | tooling | veto | goal | channel.",+ required: false,+ }],+ outputs: vec![+ FieldSchema {+ name: "facets",+ ty: TypeSchema::Array(Box::new(TypeSchema::Json)),+ comment:+ "Array of facet objects with key, value, state, user_state, stability.",+ required: true,+ },+ FieldSchema {+ name: "count",+ ty: TypeSchema::U64,+ comment: "Total number of facets returned.",+ required: true,+ },+ ],+ },+ "learning_get_facet" => ControllerSchema {+ namespace: "learning",+ function: "get_facet",+ description:+ "Fetch a single facet by class and key suffix (e.g. class=style, key=verbosity).",+ inputs: vec![+ FieldSchema {+ name: "class",+ ty: TypeSchema::String,+ comment: "Facet class: style | identity | tooling | veto | goal | channel.",+ required: true,+ },+ FieldSchema {+ name: "key",+ ty: TypeSchema::String,+ comment:+ "Key suffix within the class (e.g. \"verbosity\" for style/verbosity).",+ required: true,+ },+ ],+ outputs: vec![+ FieldSchema {+ name: "facet",+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),+ comment: "The facet object, or null if not found.",+ required: false,+ },+ FieldSchema {+ name: "found",+ ty: TypeSchema::Bool,+ comment: "Whether the facet was found.",+ required: true,+ },+ ],+ },+ "learning_update_facet" => ControllerSchema {+ namespace: "learning",+ function: "update_facet",+ description: "Update the value of an existing facet and pin it (user_state=Pinned). \+ Returns the updated facet.",+ inputs: vec![+ FieldSchema {+ name: "class",+ ty: TypeSchema::String,+ comment: "Facet class: style | identity | tooling | veto | goal | channel.",+ required: true,+ },+ FieldSchema {+ name: "key",+ ty: TypeSchema::String,+ comment: "Key suffix within the class.",+ required: true,+ },+ FieldSchema {+ name: "value",+ ty: TypeSchema::String,+ comment: "New value to set.",+ required: true,+ },+ ],+ outputs: vec![FieldSchema {+ name: "facet",+ ty: TypeSchema::Json,+ comment: "The updated facet object.",+ required: true,+ }],+ },+ "learning_pin_facet" => ControllerSchema {+ namespace: "learning",+ function: "pin_facet",+ description:+ "Pin a facet (user_state=Pinned): locks Active regardless of stability score.",+ inputs: vec![+ FieldSchema {+ name: "class",+ ty: TypeSchema::String,+ comment: "Facet class.",+ required: true,+ },+ FieldSchema {+ name: "key",+ ty: TypeSchema::String,+ comment: "Key suffix within the class.",+ required: true,+ },+ ],+ outputs: vec![FieldSchema {+ name: "facet",+ ty: TypeSchema::Json,+ comment: "The updated facet object.",+ required: true,+ }],+ },+ "learning_unpin_facet" => ControllerSchema {+ namespace: "learning",+ function: "unpin_facet",+ description:+ "Unpin a facet (user_state=Auto): returns stability management to the detector.",+ inputs: vec![+ FieldSchema {+ name: "class",+ ty: TypeSchema::String,+ comment: "Facet class.",+ required: true,+ },+ FieldSchema {+ name: "key",+ ty: TypeSchema::String,+ comment: "Key suffix within the class.",+ required: true,+ },+ ],+ outputs: vec![FieldSchema {+ name: "facet",+ ty: TypeSchema::Json,+ comment: "The updated facet object.",+ required: true,+ }],+ },+ "learning_forget_facet" => ControllerSchema {+ namespace: "learning",+ function: "forget_facet",+ description:+ "Forget a facet (user_state=Forgotten): locks Dropped and blocks re-promotion.",+ inputs: vec![+ FieldSchema {+ name: "class",+ ty: TypeSchema::String,+ comment: "Facet class.",+ required: true,+ },+ FieldSchema {+ name: "key",+ ty: TypeSchema::String,+ comment: "Key suffix within the class.",+ required: true,+ },+ ],+ outputs: vec![FieldSchema {+ name: "facet",+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),+ comment: "The facet in its Dropped state, or null if it didn't exist.",+ required: false,+ }],+ },+ "learning_reset_cache" => ControllerSchema {+ namespace: "learning",+ function: "reset_cache",+ description: "Reset the ambient cache: delete all Auto rows, preserve Pinned rows. \+ The next rebuild repopulates from the substrate.",+ inputs: vec![],+ outputs: vec![+ FieldSchema {+ name: "deleted",+ ty: TypeSchema::U64,+ comment: "Number of Auto rows deleted.",+ required: true,+ },+ FieldSchema {+ name: "pinned_preserved",+ ty: TypeSchema::U64,+ comment: "Number of Pinned rows kept.",+ required: true,+ },+ ],+ },+ _ => ControllerSchema {+ namespace: "learning",+ function: "unknown",+ description: "Unknown learning controller.",+ inputs: vec![],+ outputs: vec![FieldSchema {+ name: "error",+ ty: TypeSchema::String,+ comment: "Lookup error details.",+ required: true,+ }],+ },+ }+}diff --git a/crates/openhuman-core/src/agent/learning/schemas/cache_helpers.rs b/crates/openhuman-core/src/agent/learning/schemas/cache_helpers.rsnew file mode 100644index 0000000000..01a5672f4b--- /dev/null+++ b/crates/openhuman-core/src/agent/learning/schemas/cache_helpers.rs@@ -0,0 +1,59 @@+//! Shared helpers for the facet controllers: cache access, key construction,+//! JSON serialisation, and the `forget_facet` log line.++/// Build a [`FacetCache`] from the bound memory driver, or return a string+/// error.+///+/// Async since facets moved behind the module: there is no process-global+/// memory client to ask any more.+pub(super) async fn get_cache() -> Result<crate::agent::learning::cache::FacetCache, String> {+ let guard = crate::memory::ops::guard::active_memory_guard()+ .await+ .map_err(|e| format!("memory unavailable: {e}"))?;+ Ok(crate::agent::learning::cache::FacetCache::new(+ guard,+ ))+}++/// Build the full facet key from class string + key suffix.+/// E.g. (`"style"`, `"verbosity"`) → `"style/verbosity"`.+pub(super) fn full_key(class_str: &str, key_suffix: &str) -> String {+ format!("{class_str}/{key_suffix}")+}++/// Serialize a [`ProfileFacet`] to a serde_json [`Value`] for RPC output.+pub(super) fn facet_to_json(f: &tinymemory_api::provider::ProfileFacet) -> serde_json::Value {+ serde_json::json!({+ "key": f.key,+ "value": f.value,+ "state": f.state.as_str(),+ "user_state": f.user_state.as_str(),+ "stability": f.stability,+ "confidence": f.confidence,+ "evidence_count": f.evidence_count,+ "first_seen_at": f.first_seen_at,+ "last_seen_at": f.last_seen_at,+ "class": f.class,+ // Provenance the store already persists and row_to_facet hydrates, but+ // the serializer previously dropped: the citations behind the facet and+ // the per-cue-family evidence counts. `None`/empty serialize to+ // `null`/`[]`.+ "cue_families": f.cue_families,+ "evidence_refs": f.evidence_refs,+ })+}++/// The log line `learning.forget_facet` emits, given whether a row was actually+/// written.+///+/// Split out so the claim can be unit-tested without a cache: the defect this+/// replaces built the "state=dropped user_state=forgotten" line unconditionally,+/// *before* the read told it whether there was anything to drop, so an absent key+/// produced a log asserting a state change that never happened (#6108).+pub(super) fn forget_facet_log(full_key: &str, dropped: bool) -> Vec<String> {+ vec![if dropped {+ format!("learning.forget_facet: key={full_key} state=dropped user_state=forgotten")+ } else {+ format!("learning.forget_facet: key={full_key} not present — no change")+ }]+}diff --git a/crates/openhuman-core/src/agent/learning/schemas_part_02.rs b/crates/openhuman-core/src/agent/learning/schemas/facet_handlers.rssimilarity index 91%rename from crates/openhuman-core/src/agent/learning/schemas_part_02.rsrename to crates/openhuman-core/src/agent/learning/schemas/facet_handlers.rsindex 3bc99ecc75..acb9945558 100644--- a/crates/openhuman-core/src/agent/learning/schemas_part_02.rs+++ b/crates/openhuman-core/src/agent/learning/schemas/facet_handlers.rs@@ -1,6 +1,16 @@+//! Handlers for the per-facet learning controllers: list, get, update, pin,+//! unpin, forget, and cache reset.++use serde_json::{Map, Value};++use crate::core::all::ControllerFuture;+use crate::rpc::RpcOutcome;++use super::{facet_to_json, forget_facet_log, full_key, get_cache};+// ── list_facets ───────────────────────────────────────────────────────────────-fn handle_list_facets(params: Map<String, Value>) -> ControllerFuture {+pub(super) fn handle_list_facets(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {use tinymemory_api::provider::FacetState;@@ -65,7 +75,7 @@ fn handle_list_facets(params: Map<String, Value>) -> ControllerFuture {// ── get_facet ─────────────────────────────────────────────────────────────────-fn handle_get_facet(params: Map<String, Value>) -> ControllerFuture {+pub(super) fn handle_get_facet(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {// These refusals are reachable from a dispatched call, not only from a// direct one. An *absent* `class`/`key` is refused earlier by@@ -108,7 +118,7 @@ fn handle_get_facet(params: Map<String, Value>) -> ControllerFuture {// ── update_facet ──────────────────────────────────────────────────────────────-fn handle_update_facet(params: Map<String, Value>) -> ControllerFuture {+pub(super) fn handle_update_facet(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {use tinymemory_api::provider::UserState;@@ -166,7 +176,7 @@ fn handle_update_facet(params: Map<String, Value>) -> ControllerFuture {// ── pin_facet ─────────────────────────────────────────────────────────────────-fn handle_pin_facet(params: Map<String, Value>) -> ControllerFuture {+pub(super) fn handle_pin_facet(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {use tinymemory_api::provider::UserState;@@ -210,7 +220,7 @@ fn handle_pin_facet(params: Map<String, Value>) -> ControllerFuture {// ── unpin_facet ───────────────────────────────────────────────────────────────-fn handle_unpin_facet(params: Map<String, Value>) -> ControllerFuture {+pub(super) fn handle_unpin_facet(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {use tinymemory_api::provider::UserState;@@ -254,22 +264,8 @@ fn handle_unpin_facet(params: Map<String, Value>) -> ControllerFuture {// ── forget_facet ──────────────────────────────────────────────────────────────-/// The log line `learning.forget_facet` emits, given whether a row was actually-/// written.-///-/// Split out so the claim can be unit-tested without a cache: the defect this-/// replaces built the "state=dropped user_state=forgotten" line unconditionally,-/// *before* the read told it whether there was anything to drop, so an absent key-/// produced a log asserting a state change that never happened (#6108).-fn forget_facet_log(full_key: &str, dropped: bool) -> Vec<String> {- vec![if dropped {- format!("learning.forget_facet: key={full_key} state=dropped user_state=forgotten")- } else {- format!("learning.forget_facet: key={full_key} not present — no change")- }]-}-fn handle_forget_facet(params: Map<String, Value>) -> ControllerFuture {+pub(super) fn handle_forget_facet(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {use tinymemory_api::provider::{FacetState, UserState};@@ -327,7 +323,7 @@ fn handle_forget_facet(params: Map<String, Value>) -> ControllerFuture {// ── reset_cache ───────────────────────────────────────────────────────────────-fn handle_reset_cache(_params: Map<String, Value>) -> ControllerFuture {+pub(super) fn handle_reset_cache(_params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {tracing::debug!("[learning.reset_cache] called");diff --git a/crates/openhuman-core/src/agent/learning/schemas/profile_handlers.rs b/crates/openhuman-core/src/agent/learning/schemas/profile_handlers.rsnew file mode 100644index 0000000000..3ae15afc1a--- /dev/null+++ b/crates/openhuman-core/src/agent/learning/schemas/profile_handlers.rs@@ -0,0 +1,185 @@+//! Handlers for the profile-level learning controllers: LinkedIn enrichment,+//! `PROFILE.md` saving, and facet-cache rebuild / statistics.++use serde_json::{Map, Value};++use crate::config::rpc as config_rpc;+use crate::core::all::ControllerFuture;+use crate::rpc::RpcOutcome;++use super::get_cache;++pub(super) fn handle_linkedin_enrichment(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let preset_profile_url = params+ .get("profile_url")+ .and_then(Value::as_str)+ .map(str::to_string);+ let config = config_rpc::load_config_with_timeout().await?;+ let result =+ crate::agent::learning::linkedin_enrichment::run_linkedin_enrichment(&config, preset_profile_url)+ .await+ .map_err(|e| format!("linkedin enrichment failed: {e:#}"))?;++ let payload = serde_json::json!({+ "profile_url": result.profile_url,+ "profile_data": result.profile_data,+ "stages": result.stages,+ "log": result.log,+ });++ RpcOutcome::new(payload, result.log.clone()).into_cli_compatible_json()+ })+}++pub(super) fn handle_save_profile(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let markdown = params+ .get("markdown")+ .and_then(Value::as_str)+ .map(str::to_string)+ .ok_or_else(|| "missing required `markdown`".to_string())?;+ let summarize = params+ .get("summarize")+ .and_then(Value::as_bool)+ .unwrap_or(false);++ let config = config_rpc::load_config_with_timeout().await?;++ let body = if summarize {+ crate::agent::learning::linkedin_enrichment::summarise_profile_with_llm(&config, &markdown)+ .await+ .map_err(|e| format!("LLM summarisation failed: {e:#}"))?+ } else {+ markdown+ };++ let path = config.workspace_dir.join("PROFILE.md");+ if let Some(parent) = path.parent() {+ tokio::fs::create_dir_all(parent)+ .await+ .map_err(|e| format!("create workspace dir failed: {e}"))?;+ }+ tokio::fs::write(&path, &body)+ .await+ .map_err(|e| format!("write PROFILE.md failed: {e}"))?;++ let bytes = body.len();+ let path_display = path.display().to_string();+ let payload = serde_json::json!({+ "path": path_display,+ "bytes": bytes,+ });+ let log = vec![format!(+ "learning.save_profile: wrote {bytes} bytes to {path_display} (summarize={summarize})"+ )];+ RpcOutcome::new(payload, log).into_cli_compatible_json()+ })+}++pub(super) fn handle_rebuild_cache(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ use crate::agent::learning::cache::FacetCache;+ use crate::agent::learning::stability_detector::StabilityDetector;+ use std::time::{SystemTime, UNIX_EPOCH};++ tracing::debug!("[learning.rebuild_cache] manual rebuild requested via RPC");++ let cache = FacetCache::new(+ crate::memory::ops::guard::active_memory_guard()+ .await+ .map_err(|e| format!("memory unavailable: {e}"))?,+ );+ let detector = StabilityDetector::new(cache);++ let now = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_secs_f64();++ let outcome = detector+ .rebuild(now)+ .await+ .map_err(|e| format!("rebuild failed: {e:#}"))?;++ let log = vec![format!(+ "learning.rebuild_cache: added={} evicted={} kept={} total={}",+ outcome.added, outcome.evicted, outcome.kept, outcome.total_size,+ )];++ let payload = serde_json::json!({+ "added": outcome.added,+ "evicted": outcome.evicted,+ "kept": outcome.kept,+ "total_size": outcome.total_size,+ });++ RpcOutcome::new(payload, log).into_cli_compatible_json()+ })+}++pub(super) fn handle_cache_stats(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ use crate::agent::learning::cache::FacetCache;+ use tinymemory_api::provider::FacetState;++ tracing::debug!("[learning.cache_stats] cache stats requested via RPC");++ let cache = FacetCache::new(+ crate::memory::ops::guard::active_memory_guard()+ .await+ .map_err(|e| format!("memory unavailable: {e}"))?,+ );++ let all_facets = cache+ .list_all()+ .await+ .map_err(|e| format!("list_all failed: {e:#}"))?;++ let total = all_facets.len();+ let active = all_facets+ .iter()+ .filter(|f| f.state == FacetState::Active)+ .count();+ let provisional = all_facets+ .iter()+ .filter(|f| f.state == FacetState::Provisional)+ .count();+ let candidate = all_facets+ .iter()+ .filter(|f| f.state == FacetState::Candidate)+ .count();+ let dropped = all_facets+ .iter()+ .filter(|f| f.state == FacetState::Dropped)+ .count();++ // Per-class count (Active rows only, keyed by class field or key prefix).+ let mut by_class: std::collections::HashMap<String, usize> =+ std::collections::HashMap::new();+ for f in all_facets.iter().filter(|f| f.state == FacetState::Active) {+ let cls = f+ .class+ .clone()+ .or_else(|| f.key.split_once('/').map(|(p, _)| p.to_string()))+ .unwrap_or_else(|| "_other".to_string());+ *by_class.entry(cls).or_insert(0) += 1;+ }++ let log = vec![format!(+ "learning.cache_stats: total={total} active={active} provisional={provisional} \+ candidate={candidate} dropped={dropped}"+ )];++ let payload = serde_json::json!({+ "total": total,+ "active": active,+ "provisional": provisional,+ "candidate": candidate,+ "dropped": dropped,+ "by_class": by_class,+ });++ RpcOutcome::new(payload, log).into_cli_compatible_json()+ })+}diff --git a/crates/openhuman-core/src/agent/learning/schemas_part_01.rs b/crates/openhuman-core/src/agent/learning/schemas_part_01.rsdeleted file mode 100644index 65142391b9..0000000000--- a/crates/openhuman-core/src/agent/learning/schemas_part_01.rs+++ /dev/null@@ -1,651 +0,0 @@-use serde_json::{Map, Value};--use crate::core::all::{ControllerFuture, RegisteredController};-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};-use crate::config::rpc as config_rpc;-use crate::rpc::RpcOutcome;--pub fn all_learning_controller_schemas() -> Vec<ControllerSchema> {- vec![- learning_schemas("learning_linkedin_enrichment"),- learning_schemas("learning_save_profile"),- learning_schemas("learning_rebuild_cache"),- learning_schemas("learning_cache_stats"),- learning_schemas("learning_list_facets"),- learning_schemas("learning_get_facet"),- learning_schemas("learning_update_facet"),- learning_schemas("learning_pin_facet"),- learning_schemas("learning_unpin_facet"),- learning_schemas("learning_forget_facet"),- learning_schemas("learning_reset_cache"),- ]-}--pub fn all_learning_registered_controllers() -> Vec<RegisteredController> {- vec![- RegisteredController {- schema: learning_schemas("learning_linkedin_enrichment"),- handler: handle_linkedin_enrichment,- },- RegisteredController {- schema: learning_schemas("learning_save_profile"),- handler: handle_save_profile,- },- RegisteredController {- schema: learning_schemas("learning_rebuild_cache"),- handler: handle_rebuild_cache,- },- RegisteredController {- schema: learning_schemas("learning_cache_stats"),- handler: handle_cache_stats,- },- RegisteredController {- schema: learning_schemas("learning_list_facets"),- handler: handle_list_facets,- },- RegisteredController {- schema: learning_schemas("learning_get_facet"),- handler: handle_get_facet,- },- RegisteredController {- schema: learning_schemas("learning_update_facet"),- handler: handle_update_facet,- },- RegisteredController {- schema: learning_schemas("learning_pin_facet"),- handler: handle_pin_facet,- },- RegisteredController {- schema: learning_schemas("learning_unpin_facet"),- handler: handle_unpin_facet,- },- RegisteredController {- schema: learning_schemas("learning_forget_facet"),- handler: handle_forget_facet,- },- RegisteredController {- schema: learning_schemas("learning_reset_cache"),- handler: handle_reset_cache,- },- ]-}--pub fn learning_schemas(function: &str) -> ControllerSchema {- match function {- "learning_linkedin_enrichment" => ControllerSchema {- namespace: "learning",- function: "linkedin_enrichment",- description: "Search Gmail for LinkedIn profile URLs, scrape the profile via Apify, \- and persist the result to memory. Runs the full enrichment pipeline.",- inputs: vec![FieldSchema {- name: "profile_url",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Pre-found LinkedIn profile URL (skips the Gmail-search stage). \- The frontend supplies this when it has already located the URL via \- the webview-driven `gmail_find_linkedin_profile_url` Tauri command.",- required: false,- }],- outputs: vec![- FieldSchema {- name: "profile_url",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "LinkedIn profile URL found in Gmail, if any.",- required: false,- },- FieldSchema {- name: "profile_data",- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),- comment: "Scraped LinkedIn profile JSON from Apify, if successful.",- required: false,- },- FieldSchema {- name: "log",- ty: TypeSchema::Array(Box::new(TypeSchema::String)),- comment: "Human-readable log of each pipeline stage.",- required: true,- },- ],- },- "learning_save_profile" => ControllerSchema {- namespace: "learning",- function: "save_profile",- description: "Persist a markdown profile to `{workspace_dir}/PROFILE.md`. \- When `summarize=true`, runs the body through the LLM compressor \- first (same prompt as the LinkedIn-enrichment pipeline) so callers \- can hand in raw scraped material and get the same end-state.",- inputs: vec![- FieldSchema {- name: "markdown",- ty: TypeSchema::String,- comment: "Markdown body to persist (or to summarize first).",- required: true,- },- FieldSchema {- name: "summarize",- ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),- comment: "Compress through LLM before writing (default false).",- required: false,- },- ],- outputs: vec![- FieldSchema {- name: "path",- ty: TypeSchema::String,- comment: "Absolute path of the written PROFILE.md.",- required: true,- },- FieldSchema {- name: "bytes",- ty: TypeSchema::U64,- comment: "Bytes written.",- required: true,- },- ],- },- "learning_rebuild_cache" => ControllerSchema {- namespace: "learning",- function: "rebuild_cache",- description: "Manually trigger a stability-detector rebuild cycle. \- Drains the candidate buffer, scores all (class, key) pairs, \- applies class budgets, and persists the updated ambient cache. \- Returns rebuild statistics.",- inputs: vec![],- outputs: vec![- FieldSchema {- name: "added",- ty: TypeSchema::U64,- comment: "Facet rows newly created in this cycle.",- required: true,- },- FieldSchema {- name: "evicted",- ty: TypeSchema::U64,- comment: "Facet rows demoted to Dropped or deleted.",- required: true,- },- FieldSchema {- name: "kept",- ty: TypeSchema::U64,- comment: "Facet rows carried over unchanged.",- required: true,- },- FieldSchema {- name: "total_size",- ty: TypeSchema::U64,- comment: "Total Active rows after the rebuild.",- required: true,- },- ],- },- "learning_cache_stats" => ControllerSchema {- namespace: "learning",- function: "cache_stats",- description: "Return current ambient cache statistics — total row count, \- per-state breakdown, and per-class breakdown.",- inputs: vec![],- outputs: vec![- FieldSchema {- name: "total",- ty: TypeSchema::U64,- comment: "Total rows in the cache (all states).",- required: true,- },- FieldSchema {- name: "active",- ty: TypeSchema::U64,- comment: "Rows with state=active.",- required: true,- },- FieldSchema {- name: "provisional",- ty: TypeSchema::U64,- comment: "Rows with state=provisional.",- required: true,- },- FieldSchema {- name: "candidate",- ty: TypeSchema::U64,- comment: "Rows with state=candidate.",- required: true,- },- FieldSchema {- name: "dropped",- ty: TypeSchema::U64,- comment: "Rows with state=dropped.",- required: true,- },- FieldSchema {- name: "by_class",- ty: TypeSchema::Json,- comment: "Map of class name → row count (active rows only).",- required: true,- },- ],- },- "learning_list_facets" => ControllerSchema {- namespace: "learning",- function: "list_facets",- description: "List all facets in the ambient cache (active + provisional). \- Optionally filter by class.",- inputs: vec![FieldSchema {- name: "class",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment:- "Optional class filter: style | identity | tooling | veto | goal | channel.",- required: false,- }],- outputs: vec![- FieldSchema {- name: "facets",- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),- comment:- "Array of facet objects with key, value, state, user_state, stability.",- required: true,- },- FieldSchema {- name: "count",- ty: TypeSchema::U64,- comment: "Total number of facets returned.",- required: true,- },- ],- },- "learning_get_facet" => ControllerSchema {- namespace: "learning",- function: "get_facet",- description:- "Fetch a single facet by class and key suffix (e.g. class=style, key=verbosity).",- inputs: vec![- FieldSchema {- name: "class",- ty: TypeSchema::String,- comment: "Facet class: style | identity | tooling | veto | goal | channel.",- required: true,- },- FieldSchema {- name: "key",- ty: TypeSchema::String,- comment:- "Key suffix within the class (e.g. \"verbosity\" for style/verbosity).",- required: true,- },- ],- outputs: vec![- FieldSchema {- name: "facet",- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),- comment: "The facet object, or null if not found.",- required: false,- },- FieldSchema {- name: "found",- ty: TypeSchema::Bool,- comment: "Whether the facet was found.",- required: true,- },- ],- },- "learning_update_facet" => ControllerSchema {- namespace: "learning",- function: "update_facet",- description: "Update the value of an existing facet and pin it (user_state=Pinned). \- Returns the updated facet.",- inputs: vec![- FieldSchema {- name: "class",- ty: TypeSchema::String,- comment: "Facet class: style | identity | tooling | veto | goal | channel.",- required: true,- },- FieldSchema {- name: "key",- ty: TypeSchema::String,- comment: "Key suffix within the class.",- required: true,- },- FieldSchema {- name: "value",- ty: TypeSchema::String,- comment: "New value to set.",- required: true,- },- ],- outputs: vec![FieldSchema {- name: "facet",- ty: TypeSchema::Json,- comment: "The updated facet object.",- required: true,- }],- },- "learning_pin_facet" => ControllerSchema {- namespace: "learning",- function: "pin_facet",- description:- "Pin a facet (user_state=Pinned): locks Active regardless of stability score.",- inputs: vec![- FieldSchema {- name: "class",- ty: TypeSchema::String,- comment: "Facet class.",- required: true,- },- FieldSchema {- name: "key",- ty: TypeSchema::String,- comment: "Key suffix within the class.",- required: true,- },- ],- outputs: vec![FieldSchema {- name: "facet",- ty: TypeSchema::Json,- comment: "The updated facet object.",- required: true,- }],- },- "learning_unpin_facet" => ControllerSchema {- namespace: "learning",- function: "unpin_facet",- description:- "Unpin a facet (user_state=Auto): returns stability management to the detector.",- inputs: vec![- FieldSchema {- name: "class",- ty: TypeSchema::String,- comment: "Facet class.",- required: true,- },- FieldSchema {- name: "key",- ty: TypeSchema::String,- comment: "Key suffix within the class.",- required: true,- },- ],- outputs: vec![FieldSchema {- name: "facet",- ty: TypeSchema::Json,- comment: "The updated facet object.",- required: true,- }],- },- "learning_forget_facet" => ControllerSchema {- namespace: "learning",- function: "forget_facet",- description:- "Forget a facet (user_state=Forgotten): locks Dropped and blocks re-promotion.",- inputs: vec![- FieldSchema {- name: "class",- ty: TypeSchema::String,- comment: "Facet class.",- required: true,- },- FieldSchema {- name: "key",- ty: TypeSchema::String,- comment: "Key suffix within the class.",- required: true,- },- ],- outputs: vec![FieldSchema {- name: "facet",- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),- comment: "The facet in its Dropped state, or null if it didn't exist.",- required: false,- }],- },- "learning_reset_cache" => ControllerSchema {- namespace: "learning",- function: "reset_cache",- description: "Reset the ambient cache: delete all Auto rows, preserve Pinned rows. \- The next rebuild repopulates from the substrate.",- inputs: vec![],- outputs: vec![- FieldSchema {- name: "deleted",- ty: TypeSchema::U64,- comment: "Number of Auto rows deleted.",- required: true,- },- FieldSchema {- name: "pinned_preserved",- ty: TypeSchema::U64,- comment: "Number of Pinned rows kept.",- required: true,- },- ],- },- _ => ControllerSchema {- namespace: "learning",- function: "unknown",- description: "Unknown learning controller.",- inputs: vec![],- outputs: vec![FieldSchema {- name: "error",- ty: TypeSchema::String,- comment: "Lookup error details.",- required: true,- }],- },- }-}--fn handle_linkedin_enrichment(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let preset_profile_url = params- .get("profile_url")- .and_then(Value::as_str)- .map(str::to_string);- let config = config_rpc::load_config_with_timeout().await?;- let result =- super::linkedin_enrichment::run_linkedin_enrichment(&config, preset_profile_url)- .await- .map_err(|e| format!("linkedin enrichment failed: {e:#}"))?;-- let payload = serde_json::json!({- "profile_url": result.profile_url,- "profile_data": result.profile_data,- "stages": result.stages,- "log": result.log,- });-- RpcOutcome::new(payload, result.log.clone()).into_cli_compatible_json()- })-}--fn handle_save_profile(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let markdown = params- .get("markdown")- .and_then(Value::as_str)- .map(str::to_string)- .ok_or_else(|| "missing required `markdown`".to_string())?;- let summarize = params- .get("summarize")- .and_then(Value::as_bool)- .unwrap_or(false);-- let config = config_rpc::load_config_with_timeout().await?;-- let body = if summarize {- super::linkedin_enrichment::summarise_profile_with_llm(&config, &markdown)- .await- .map_err(|e| format!("LLM summarisation failed: {e:#}"))?- } else {- markdown- };-- let path = config.workspace_dir.join("PROFILE.md");- if let Some(parent) = path.parent() {- tokio::fs::create_dir_all(parent)- .await- .map_err(|e| format!("create workspace dir failed: {e}"))?;- }- tokio::fs::write(&path, &body)- .await- .map_err(|e| format!("write PROFILE.md failed: {e}"))?;-- let bytes = body.len();- let path_display = path.display().to_string();- let payload = serde_json::json!({- "path": path_display,- "bytes": bytes,- });- let log = vec![format!(- "learning.save_profile: wrote {bytes} bytes to {path_display} (summarize={summarize})"- )];- RpcOutcome::new(payload, log).into_cli_compatible_json()- })-}--fn handle_rebuild_cache(_params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- use crate::agent::learning::cache::FacetCache;- use crate::agent::learning::stability_detector::StabilityDetector;- use std::time::{SystemTime, UNIX_EPOCH};-- tracing::debug!("[learning.rebuild_cache] manual rebuild requested via RPC");-- let cache = FacetCache::new(- crate::memory::ops::guard::active_memory_guard()- .await- .map_err(|e| format!("memory unavailable: {e}"))?,- );- let detector = StabilityDetector::new(cache);-- let now = SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap_or_default()- .as_secs_f64();-- let outcome = detector- .rebuild(now)- .await- .map_err(|e| format!("rebuild failed: {e:#}"))?;-- let log = vec![format!(- "learning.rebuild_cache: added={} evicted={} kept={} total={}",- outcome.added, outcome.evicted, outcome.kept, outcome.total_size,- )];-- let payload = serde_json::json!({- "added": outcome.added,- "evicted": outcome.evicted,- "kept": outcome.kept,- "total_size": outcome.total_size,- });-- RpcOutcome::new(payload, log).into_cli_compatible_json()- })-}--fn handle_cache_stats(_params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- use crate::agent::learning::cache::FacetCache;- use tinymemory_api::provider::FacetState;-- tracing::debug!("[learning.cache_stats] cache stats requested via RPC");-- let cache = FacetCache::new(- crate::memory::ops::guard::active_memory_guard()- .await- .map_err(|e| format!("memory unavailable: {e}"))?,- );-- let all_facets = cache- .list_all()- .await- .map_err(|e| format!("list_all failed: {e:#}"))?;-- let total = all_facets.len();- let active = all_facets- .iter()- .filter(|f| f.state == FacetState::Active)- .count();- let provisional = all_facets- .iter()- .filter(|f| f.state == FacetState::Provisional)- .count();- let candidate = all_facets- .iter()- .filter(|f| f.state == FacetState::Candidate)- .count();- let dropped = all_facets- .iter()- .filter(|f| f.state == FacetState::Dropped)- .count();-- // Per-class count (Active rows only, keyed by class field or key prefix).- let mut by_class: std::collections::HashMap<String, usize> =- std::collections::HashMap::new();- for f in all_facets.iter().filter(|f| f.state == FacetState::Active) {- let cls = f- .class- .clone()- .or_else(|| f.key.split_once('/').map(|(p, _)| p.to_string()))- .unwrap_or_else(|| "_other".to_string());- *by_class.entry(cls).or_insert(0) += 1;- }-- let log = vec![format!(- "learning.cache_stats: total={total} active={active} provisional={provisional} \- candidate={candidate} dropped={dropped}"- )];-- let payload = serde_json::json!({- "total": total,- "active": active,- "provisional": provisional,- "candidate": candidate,- "dropped": dropped,- "by_class": by_class,- });-- RpcOutcome::new(payload, log).into_cli_compatible_json()- })-}--// ── Helper: shared cache access ───────────────────────────────────────────────--/// Build a [`FacetCache`] from the bound memory driver, or return a string-/// error.-///-/// Async since facets moved behind the module: there is no process-global-/// memory client to ask any more.-async fn get_cache() -> Result<crate::agent::learning::cache::FacetCache, String> {- let guard = crate::memory::ops::guard::active_memory_guard()- .await- .map_err(|e| format!("memory unavailable: {e}"))?;- Ok(crate::agent::learning::cache::FacetCache::new(- guard,- ))-}--/// Build the full facet key from class string + key suffix.-/// E.g. (`"style"`, `"verbosity"`) → `"style/verbosity"`.-fn full_key(class_str: &str, key_suffix: &str) -> String {- format!("{class_str}/{key_suffix}")-}--/// Serialize a [`ProfileFacet`] to a serde_json [`Value`] for RPC output.-fn facet_to_json(f: &tinymemory_api::provider::ProfileFacet) -> serde_json::Value {- serde_json::json!({- "key": f.key,- "value": f.value,- "state": f.state.as_str(),- "user_state": f.user_state.as_str(),- "stability": f.stability,- "confidence": f.confidence,- "evidence_count": f.evidence_count,- "first_seen_at": f.first_seen_at,- "last_seen_at": f.last_seen_at,- "class": f.class,- // Provenance the store already persists and row_to_facet hydrates, but- // the serializer previously dropped: the citations behind the facet and- // the per-cue-family evidence counts. `None`/empty serialize to- // `null`/`[]`.- "cue_families": f.cue_families,- "evidence_refs": f.evidence_refs,- })-}diff --git a/crates/openhuman-core/src/agent/progress_tracing/langfuse/environment.rs b/crates/openhuman-core/src/agent/progress_tracing/langfuse/environment.rsindex 0a9db5750b..eac4a5ffc5 100644--- a/crates/openhuman-core/src/agent/progress_tracing/langfuse/environment.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/langfuse/environment.rs@@ -13,8 +13,6 @@ use super::LOG_TARGET;/// clients POST here, NOT to `/api/public/ingestion` (which is unexposed and/// carries no keys).const INGESTION_PATH: &str = "/telemetry/langfuse/ingestion";-/// Cap the push so a slow/hung Langfuse never stalls run teardown.-const PUSH_TIMEOUT: Duration = Duration::from_secs(10);/// Resolve the Langfuse ingestion URL from the current backend host. Joins the/// proxy path onto [`effective_backend_api_url`] — the exact base-server@@ -27,15 +25,6 @@ pub(crate) fn ingestion_url(config: &Config) -> String {crate::api::config::api_url(&base, INGESTION_PATH)}-/// Epoch-milliseconds → RFC 3339 / ISO-8601 string (Langfuse requires ISO-- }- if let Ok(kind) = serde_json::to_value(span.kind) {- map.insert("kind".to_string(), kind);- }- Value::Object(map)-}-/// The domain the deployed backends live under. A host outside it cannot be/// one of ours, so it cannot be staging however it is spelled.const DEPLOYMENT_DOMAIN: &str = "tinyhumans.ai";@@ -147,3 +136,15 @@ static SKIP_LOGGED: std::sync::Once = std::sync::Once::new();/// thing being avoided.fn skip_push(environment: &str) -> bool {if push_allowed(environment) {+ return false;+ }+ SKIP_LOGGED.call_once(|| {+ tracing::info!(+ target: LOG_TARGET,+ "[agent-tracing] Langfuse push disabled for environment {environment:?} \+ (enabled in: {}) — traces stay local for the rest of this process",+ LANGFUSE_PUSH_ENVIRONMENTS.join(", ")+ );+ });+ true+}diff --git a/crates/openhuman-core/src/agent/progress_tracing/langfuse/ingestion_batch.rs b/crates/openhuman-core/src/agent/progress_tracing/langfuse/ingestion_batch.rsnew file mode 100644index 0000000000..9b38ea546e--- /dev/null+++ b/crates/openhuman-core/src/agent/progress_tracing/langfuse/ingestion_batch.rs@@ -0,0 +1,50 @@+//! Shared ingestion-batch helpers: ISO timestamps, per-event ids, and the+//! 500-event chunking Langfuse imposes on a single ingestion request.++use serde_json::Value;+++/// Epoch-milliseconds → RFC 3339 / ISO-8601 string (Langfuse requires ISO+/// timestamps, not epoch integers). Falls back to "now" only if the value is+/// somehow out of range — `start_unix_ms` comes from a monotonic wall clock so+/// this is defensive.+fn iso_millis(unix_ms: u64) -> String {+ chrono::DateTime::from_timestamp_millis(unix_ms as i64)+ .unwrap_or_else(chrono::Utc::now)+ .to_rfc3339()+}++/// Fresh per-event id. Langfuse dedupes ingestion events by this id, so it must+/// be unique per event (distinct from the observation/trace id in `body`).+fn new_event_id() -> String {+ uuid::Uuid::new_v4().to_string()+}++/// is explicitly enabled.+/// Langfuse rejects an ingestion request whose `batch` holds more than 500+/// events (`400 "Langfuse ingestion batch cannot exceed 500 events"`). Large+/// turns — especially ones that spawn sub-agents — routinely exceed this.+const LANGFUSE_MAX_BATCH_EVENTS: usize = 500;++/// Split a `{"batch": [...]}` ingestion payload into multiple payloads, each+/// carrying at most `max` events and preserving any other top-level keys.+///+/// Langfuse dedupes ingestion events by id and resolves each observation to its+/// trace by `traceId`, so delivering one run's events across several requests is+/// safe (the `trace-create` event stays in the first chunk). A payload at or+/// under the limit — or without a `batch` array — passes through unchanged as a+/// single element.+fn split_ingestion_batch(payload: Value, max: usize) -> Vec<Value> {+ let events = match payload.get("batch").and_then(Value::as_array) {+ Some(events) if max > 0 && events.len() > max => events.clone(),+ _ => return vec![payload],+ };+ events+ .chunks(max)+ .map(|chunk| {+ let mut part = payload.clone();+ part["batch"] = Value::Array(chunk.to_vec());+ part+ })+ .collect()+}diff --git a/crates/openhuman-core/src/agent/progress_tracing/langfuse/journal_export.rs b/crates/openhuman-core/src/agent/progress_tracing/langfuse/journal_export.rsnew file mode 100644index 0000000000..2fbe47fd92--- /dev/null+++ b/crates/openhuman-core/src/agent/progress_tracing/langfuse/journal_export.rs@@ -0,0 +1,275 @@+//! Journal export: pushes a run's durable tinyagents observations through the+//! tinyagents Langfuse exporter, stamping run lineage and trace attribution,+//! gating content on `capture_content`, and folding the run-ledger telemetry+//! aggregate into the batch.++use std::borrow::Cow;++use serde_json::{json, Map, Value};+use tinyagents_harness::events::AgentEvent;+use tinyagents_harness::observability::{AgentObservation, LangfuseClient, LangfuseTraceConfig};+use tinyagents_session::run_ledger::RunTelemetry;++use crate::config::Config;+use crate::security::credentials::session_support::require_live_session_token;++use super::ingestion_batch::{new_event_id, split_ingestion_batch, LANGFUSE_MAX_BATCH_EVENTS};+use super::{environment_for_base, ingestion_url, skip_push, LOG_TARGET, PUSH_TIMEOUT};+use super::TraceContext;+++/// Enrich `trace_ctx` with the run lineage (`run_id` / `parent_run_id` /+/// `root_run_id`) carried by the run's journalled `observations` (#4657).+///+/// A single export corresponds to one run's observation stream (the journal is+/// read per run id), so every observation shares the same lineage and the first+/// is representative. For a spawned sub-agent that lineage points back at the+/// spawning turn, which is exactly what links the sub-agent's trace to its+/// parent. Returns the context unchanged when there are no observations.+fn trace_ctx_with_run_lineage(+ trace_ctx: &TraceContext,+ observations: &[AgentObservation],+) -> TraceContext {+ let Some(first) = observations.first() else {+ return trace_ctx.clone();+ };+ trace_ctx.clone().with_run_lineage(+ Some(first.run_id.as_str().to_string()),+ first+ .parent_run_id+ .as_ref()+ .map(|id| id.as_str().to_string()),+ Some(first.root_run_id.as_str().to_string()),+ )+}++fn trace_config_from_context(trace_ctx: &TraceContext, environment: &str) -> LangfuseTraceConfig {+ let mut metadata = Map::new();+ if let Some(client_id) = &trace_ctx.client_id {+ metadata.insert("client.id".into(), json!(client_id));+ }+ if let Some(agent_id) = &trace_ctx.agent_id {+ metadata.insert("agent.id".into(), json!(agent_id));+ }+ if let Some(source) = &trace_ctx.channel_source {+ metadata.insert("channel.source".into(), json!(source));+ }+ metadata.insert("run_type".into(), json!(trace_ctx.run_type.as_str()));+ metadata.insert("app.version".into(), json!(env!("CARGO_PKG_VERSION")));+ // Run lineage (#4657): stamp the run/parent/root ids so a spawned sub-agent's+ // trace is navigable from — and threadable under — its parent turn. Omitted+ // keys (e.g. `parent_run_id` for a top-level turn) simply stay absent.+ if let Some(run_id) = &trace_ctx.run_id {+ metadata.insert("run_id".into(), json!(run_id));+ }+ if let Some(parent_run_id) = &trace_ctx.parent_run_id {+ metadata.insert("parent_run_id".into(), json!(parent_run_id));+ }+ if let Some(root_run_id) = &trace_ctx.root_run_id {+ metadata.insert("root_run_id".into(), json!(root_run_id));+ }++ let mut tags = vec![format!("run:{}", trace_ctx.run_type.as_str())];+ if let Some(source) = &trace_ctx.channel_source {+ tags.push(format!("source:{source}"));+ }++ LangfuseTraceConfig {+ trace_id: Some(trace_ctx.session_id.clone()),+ name: Some(match &trace_ctx.agent_id {+ Some(agent_id) => format!("agent.turn:{agent_id}"),+ None => "agent.turn".to_string(),+ }),+ user_id: trace_ctx.user_id.clone(),+ session_id: trace_ctx+ .session_group+ .clone()+ .or_else(|| Some(trace_ctx.session_id.clone())),+ environment: Some(environment.to_string()),+ release: Some(env!("CARGO_PKG_VERSION").to_string()),+ version: Some(env!("CARGO_PKG_VERSION").to_string()),+ tags,+ metadata: Value::Object(metadata),+ }+}++fn observations_for_export<'a>(+ trace_ctx: &TraceContext,+ observations: &'a [AgentObservation],+) -> Cow<'a, [AgentObservation]> {+ if trace_ctx.capture_content {+ return Cow::Borrowed(observations);+ }++ Cow::Owned(+ observations+ .iter()+ .cloned()+ .map(strip_observation_content)+ .collect(),+ )+}++fn strip_observation_content(mut observation: AgentObservation) -> AgentObservation {+ match &mut observation.event {+ AgentEvent::ModelCompleted { input, output, .. }+ | AgentEvent::ToolCompleted { input, output, .. } => {+ *input = None;+ *output = None;+ }+ _ => {}+ }+ observation+}++fn insert_run_telemetry_generation(payload: &mut Value, telemetry: Option<&RunTelemetry>) -> bool {+ let Some(telemetry) = telemetry else {+ return false;+ };+ if telemetry.input_tokens == 0 && telemetry.output_tokens == 0 && telemetry.cost_usd == 0.0 {+ return false;+ }++ let Some(batch) = payload.get_mut("batch").and_then(Value::as_array_mut) else {+ return false;+ };+ let Some(trace_id) = batch+ .first()+ .and_then(|event| event.get("body"))+ .and_then(|body| body.get("id"))+ .and_then(Value::as_str)+ .map(str::to_string)+ else {+ return false;+ };+ let start_time = batch+ .first()+ .and_then(|event| event.get("timestamp"))+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string();+ let end_time = batch+ .last()+ .and_then(|event| event.get("timestamp"))+ .and_then(Value::as_str)+ .unwrap_or(start_time.as_str())+ .to_string();++ let non_cached_input = telemetry+ .input_tokens+ .saturating_sub(telemetry.cached_input_tokens);+ let mut body = json!({+ "id": format!("{trace_id}:openhuman-run-telemetry"),+ "traceId": trace_id,+ "name": "run.total",+ "startTime": start_time,+ "endTime": end_time,+ "usageDetails": {+ "input": non_cached_input,+ "output": telemetry.output_tokens,+ "total": telemetry.input_tokens.saturating_add(telemetry.output_tokens),+ "cache_read_input_tokens": telemetry.cached_input_tokens,+ },+ "costDetails": {+ "total": telemetry.cost_usd,+ },+ "metadata": {+ "source": "openhuman.run_telemetry",+ "run_id": telemetry.run_id.as_str(),+ "tool_count": telemetry.tool_count,+ },+ });+ if let Some(model) = &telemetry.model {+ body["model"] = json!(model);+ }+ if let Some(provider) = &telemetry.provider {+ body["metadata"]["provider"] = json!(provider);+ }+ if let Some(error) = &telemetry.error {+ body["level"] = json!("ERROR");+ body["statusMessage"] = json!(error);+ }++ batch.insert(+ 1,+ json!({+ "id": new_event_id(),+ "type": "generation-create",+ "timestamp": body["startTime"].clone(),+ "body": body,+ }),+ );+ true+}+++/// Push durable journal observations through the tinyagents crate Langfuse+/// exporter. The journal is already redacted before persistence, and this+/// exporter additionally strips model/tool payloads unless `capture_content`++pub(crate) async fn push_observations(+ config: &Config,+ trace_ctx: &TraceContext,+ observations: &[AgentObservation],+ run_telemetry: Option<&RunTelemetry>,+) -> Result<(), String> {+ if observations.is_empty() {+ return Ok(());+ }+ let url = ingestion_url(config);+ // Same gate, same reasons as `push_spans` — both entry points are on the+ // per-turn path, so both skip before doing any work.+ let environment = environment_for_base(&url);+ if skip_push(environment) {+ return Ok(());+ }+ if !url.starts_with("http") {+ return Err(format!(+ "could not resolve Langfuse ingestion URL from backend host (got {url:?})"+ ));+ }+ let token = require_live_session_token(config)?;+ // Stamp the run lineage from the run's own observations so a spawned+ // sub-agent's trace links back to its parent turn (#4657).+ let trace_ctx = trace_ctx_with_run_lineage(trace_ctx, observations);+ let trace = trace_config_from_context(&trace_ctx, environment);+ let observation_count = observations.len();+ let observations = observations_for_export(&trace_ctx, observations);++ tracing::debug!(+ target: LOG_TARGET,+ "[agent-tracing] pushing {observation_count} journal observations to Langfuse at {url}"+ );++ let client = LangfuseClient::proxy(url, token)+ .map_err(|err| format!("Langfuse client setup failed: {err}"))?;+ let mut payload = client+ .build_ingestion_batch(trace, observations.as_ref())+ .map_err(|err| format!("Langfuse journal batch build failed: {err}"))?;+ if insert_run_telemetry_generation(&mut payload, run_telemetry) {+ tracing::debug!(+ target: LOG_TARGET,+ "[agent-tracing] added run telemetry aggregate to Langfuse journal batch"+ );+ } else {+ tracing::debug!(+ target: LOG_TARGET,+ "[agent-tracing] no run telemetry aggregate added to Langfuse journal batch"+ );+ }+ // Langfuse caps a single ingestion request at 500 events; a large run (e.g.+ // one that spawns sub-agents) can far exceed that and previously had its+ // ENTIRE trace rejected with a 400. Send in <=500-event chunks instead.+ for chunk in split_ingestion_batch(payload, LANGFUSE_MAX_BATCH_EVENTS) {+ tokio::time::timeout(PUSH_TIMEOUT, client.send_batch(chunk))+ .await+ .map_err(|_| format!("Langfuse journal push timed out after {PUSH_TIMEOUT:?}"))?+ .map_err(|err| format!("Langfuse journal ingestion failed: {err}"))?;+ }++ tracing::debug!(+ target: LOG_TARGET,+ "[agent-tracing] pushed {observation_count} journal observations to Langfuse"+ );+ Ok(())+}diff --git a/crates/openhuman-core/src/agent/progress_tracing/langfuse/span_export.rs b/crates/openhuman-core/src/agent/progress_tracing/langfuse/span_export.rsnew file mode 100644index 0000000000..95cae0f6cd--- /dev/null+++ b/crates/openhuman-core/src/agent/progress_tracing/langfuse/span_export.rs@@ -0,0 +1,324 @@+//! Span-tree export: converts the in-memory [`TraceSpan`] tree into a Langfuse+//! ingestion batch (trace-create + one observation per span, usage promoted to+//! `generation` observations) and pushes it to the backend proxy.++use serde_json::{json, Map, Value};++use crate::api::jwt::bearer_authorization_value;+use crate::config::Config;+use crate::security::credentials::session_support::require_live_session_token;++use super::ingestion_batch::{iso_millis, new_event_id};+use super::{environment_for_base, ingestion_url, skip_push, LOG_TARGET, PUSH_TIMEOUT};+use super::{SpanStatus, TraceSpan};++++/// Langfuse observation level for a span status. Only `Error` is elevated so+/// failed tool calls / turns surface in the Langfuse UI.+fn level_for(status: SpanStatus) -> &'static str {+ match status {+ SpanStatus::Error => "ERROR",+ SpanStatus::Ok | SpanStatus::Unset => "DEFAULT",+ }+}++/// Build the Langfuse `metadata` object from the span's (secret-free)+/// attributes plus its structured kind.+fn langfuse_metadata(span: &TraceSpan) -> Value {+ let mut map = Map::new();+ for (key, value) in &span.attributes {+ map.insert(key.clone(), value.clone());+ }+ if let Ok(kind) = serde_json::to_value(span.kind) {+ map.insert("kind".to_string(), kind);+ }+ Value::Object(map)+}++/// Convert finished spans into a Langfuse `/api/public/ingestion` batch payload:+/// a single `trace-create` for the shared trace id followed by one+/// `span-create` observation per span. Field names are Langfuse's camelCase+/// (`traceId`, `startTime`, `parentObservationId`); timestamps are ISO strings.+/// `environment` lands as the trace's top-level Langfuse environment.+pub(crate) fn spans_to_langfuse_batch(+ spans: &[TraceSpan],+ include_content: bool,+ environment: &str,+) -> Value {+ let mut batch: Vec<Value> = Vec::with_capacity(spans.len() + 1);++ // One trace-create for the run, keyed by the shared trace id. Prefer the+ // root (parentless) span for the trace name/start; fall back to the first.+ if let Some(root) = spans+ .iter()+ .find(|s| s.parent_span_id.is_none())+ .or_else(|| spans.first())+ {+ let mut trace_body = json!({+ "id": root.trace_id,+ "name": root.name,+ "timestamp": iso_millis(root.start_unix_ms),+ // Top-level Langfuse trace fields (not metadata): deployment+ // environment + the core release that produced the trace.+ "environment": environment,+ "release": env!("CARGO_PKG_VERSION"),+ });+ // Attribute the trace to the user and group per-turn traces under the+ // conversation via Langfuse's native `userId`/`sessionId` (read from the+ // turn span's stamped attributes). Every trace gets a sessionId: the+ // stamped thread.id when present, else the trace id itself.+ if let Some(user) = root.attributes.get("user.id").and_then(Value::as_str) {+ trace_body["userId"] = json!(user);+ }+ let session = root+ .attributes+ .get("thread.id")+ .and_then(Value::as_str)+ .unwrap_or(root.trace_id.as_str());+ trace_body["sessionId"] = json!(session);+ // Trace-level metadata: transport client, agent attribution, run+ // origin, and the core version — all secret-free identifiers.+ let mut trace_meta = Map::new();+ for key in ["client.id", "agent.id", "channel.source", "gen_ai.provider"] {+ if let Some(value) = root.attributes.get(key) {+ trace_meta.insert(key.to_string(), value.clone());+ }+ }+ trace_meta.insert("app.version".to_string(), json!(env!("CARGO_PKG_VERSION")));+ // Run-type tags so traces filter by kind of run in the Langfuse UI:+ // `run:<type>` (interactive_chat / autonomous_task /+ // channel_inbound) plus `source:<channel.source>` when known.+ let mut tags: Vec<String> = Vec::with_capacity(2);+ if let Some(run_type) = root.attributes.get("run.type").and_then(Value::as_str) {+ tags.push(format!("run:{run_type}"));+ trace_meta.insert("run_type".to_string(), json!(run_type));+ }+ if let Some(source) = root+ .attributes+ .get("channel.source")+ .and_then(Value::as_str)+ {+ tags.push(format!("source:{source}"));+ }+ if !tags.is_empty() {+ trace_body["tags"] = json!(tags);+ }+ trace_body["metadata"] = Value::Object(trace_meta);+ // Trace-level input/output mirror the root turn span's content so the+ // Langfuse trace list shows the prompt/reply at a glance. Same opt-out+ // gate as the observations.+ if include_content {+ if let Some(input) = &root.input {+ trace_body["input"] = input.clone();+ }+ if let Some(output) = &root.output {+ trace_body["output"] = output.clone();+ }+ }+ batch.push(json!({+ "id": new_event_id(),+ "type": "trace-create",+ "timestamp": iso_millis(root.start_unix_ms),+ "body": trace_body,+ }));+ }++ for span in spans {+ let mut body = json!({+ "id": span.span_id,+ "traceId": span.trace_id,+ "name": span.name,+ "startTime": iso_millis(span.start_unix_ms),+ "metadata": langfuse_metadata(span),+ "level": level_for(span.status),+ });+ if let Some(end) = span.end_unix_ms {+ body["endTime"] = json!(iso_millis(end));+ }+ if let Some(parent) = &span.parent_span_id {+ body["parentObservationId"] = json!(parent);+ }+ // Failed spans surface their captured error text as the Langfuse+ // statusMessage (the collector already truncated + content-gated it).+ if let Some(message) = span.attributes.get("error.message").and_then(Value::as_str) {+ body["statusMessage"] = json!(message);+ }+ // Prompt/reply content is transmitted only when the caller opted in+ // (`observability.agent_tracing.capture_content`); otherwise it never+ // leaves the device even though it may sit on the in-memory span.+ if include_content {+ if let Some(input) = &span.input {+ body["input"] = input.clone();+ }+ if let Some(output) = &span.output {+ body["output"] = output.clone();+ }+ }+ // A span carrying `gen_ai.usage.*` attributes (today only the root turn+ // span) is emitted as a Langfuse `generation` so the UI renders native+ // token usage + cost instead of burying them in metadata. Token counts+ // and cost are non-PII, so this promotion is unconditional.+ let event_type = if apply_usage_fields(&mut body, span) {+ "generation-create"+ } else {+ "span-create"+ };+ batch.push(json!({+ "id": new_event_id(),+ "type": event_type,+ "timestamp": iso_millis(span.start_unix_ms),+ "body": body,+ }));+ }++ json!({ "batch": batch })+}++/// Promote a span's `gen_ai.usage.*` / `gen_ai.request.model` attributes into+/// Langfuse's native `model` / `usageDetails` / `costDetails` fields so the+/// trace surfaces real token counts and cost (Langfuse only renders these on+/// `generation` observations). Returns `true` when usage was found, so the+/// caller emits the span as a `generation-create`. Only token/cost figures are+/// touched — never prompt text or PII.+fn apply_usage_fields(body: &mut Value, span: &TraceSpan) -> bool {+ let attrs = &span.attributes;+ let input = attrs+ .get("gen_ai.usage.input_tokens")+ .and_then(Value::as_u64);+ let output = attrs+ .get("gen_ai.usage.output_tokens")+ .and_then(Value::as_u64);+ if input.is_none() && output.is_none() {+ return false;+ }+ let input = input.unwrap_or(0);+ let output = output.unwrap_or(0);+ let cached = attrs+ .get("gen_ai.usage.cached_input_tokens")+ .and_then(Value::as_u64)+ .unwrap_or(0);+ // #4454: `input_tokens` is INCLUSIVE of cached prompt tokens (cost.rs treats+ // cached as a subset of input). Langfuse sums `usageDetails` components as+ // disjoint buckets, so emit the NON-cached input (input - cached) — the+ // components (non_cached_input + cache_read + output) are then disjoint and+ // reconcile to `total` = input_tokens + output_tokens.+ let non_cached_input = input.saturating_sub(cached);+ let mut usage = Map::new();+ usage.insert("input".to_string(), json!(non_cached_input));+ usage.insert("output".to_string(), json!(output));+ usage.insert("total".to_string(), json!(input.saturating_add(output)));+ // Cache reads always flow into usageDetails (0 included) so the figure is+ // explicit rather than absent when no cache was hit.+ usage.insert("cache_read_input_tokens".to_string(), json!(cached));+ // Reasoning + cache-write tokens ride along whenever the span carries them+ // (the collector stamps them when > 0). Langfuse accepts arbitrary+ // usageDetails keys.+ if let Some(reasoning) = attrs+ .get("gen_ai.usage.reasoning_tokens")+ .and_then(Value::as_u64)+ {+ usage.insert("reasoning_tokens".to_string(), json!(reasoning));+ }+ if let Some(cache_write) = attrs+ .get("gen_ai.usage.cache_creation_tokens")+ .and_then(Value::as_u64)+ {+ usage.insert(+ "cache_creation_input_tokens".to_string(),+ json!(cache_write),+ );+ }+ body["usageDetails"] = Value::Object(usage);+ if let Some(model) = attrs.get("gen_ai.request.model").and_then(Value::as_str) {+ body["model"] = json!(model);+ }+ if let Some(cost) = attrs.get("gen_ai.usage.cost_usd").and_then(Value::as_f64) {+ body["costDetails"] = json!({ "total": cost });+ }+ true+}++/// Push `spans` to the co-hosted Langfuse server. Resolves the endpoint from the+/// current backend host and authenticates with the live session bearer. Returns+/// `Err` (for the caller to log + fall back) when there is no live session, the+/// host is unresolvable, the request fails, or Langfuse rejects the batch.+pub(crate) async fn push_spans(config: &Config, spans: &[TraceSpan]) -> Result<(), String> {+ if spans.is_empty() {+ return Ok(());+ }+ let url = ingestion_url(config);+ // Ahead of the URL check, the session lookup and the request: a skipped+ // environment must cost nothing per turn. An unresolvable URL lands in+ // `environment_for_base`'s catch-all, which is `production` — so a garbage+ // host skips rather than erroring, which is the right way round.+ let environment = environment_for_base(&url);+ if skip_push(environment) {+ return Ok(());+ }+ if !url.starts_with("http") {+ return Err(format!(+ "could not resolve Langfuse ingestion URL from backend host (got {url:?})"+ ));+ }+ let token = require_live_session_token(config)?;+ let include_content = config.observability.agent_tracing.capture_content;+ let batch = spans_to_langfuse_batch(spans, include_content, environment);+ let span_count = spans.len();++ tracing::debug!(+ target: LOG_TARGET,+ "[agent-tracing] pushing {span_count} spans to Langfuse at {url}"+ );++ // `ingestion_url` resolves to the backend's own Langfuse proxy route on the+ // backend host, authenticated with a TinyHumans session token — backend+ // traffic, so it carries the product identity. This is a bare+ // `reqwest::Client`, not `BackendOAuthClient`'s, so nothing is inherited+ // from that path's default headers; see [`crate::api::product`].+ let (product_header, product_value) = crate::api::product::product_identity_header();+ let response = reqwest::Client::new()+ .post(&url)+ .header(+ reqwest::header::AUTHORIZATION,+ bearer_authorization_value(&token),+ )+ .header(product_header, product_value)+ .timeout(PUSH_TIMEOUT)+ .json(&batch)+ .send()+ .await+ .map_err(|err| format!("POST {url} failed: {err}"))?;++ let status = response.status();+ let body = response.text().await.unwrap_or_default();+ if !status.is_success() {+ let excerpt: String = body.chars().take(200).collect();+ return Err(format!("Langfuse ingestion returned {status}: {excerpt}"));+ }+ // Langfuse returns 207 Multi-Status even when individual events are rejected+ // — the failures live in the response `errors` array, not the HTTP status.+ // Surface them (a partial rejection is logged but never fails the turn).+ let rejected = serde_json::from_str::<Value>(&body)+ .ok()+ .and_then(|v| v.get("errors").and_then(Value::as_array).cloned())+ .filter(|errs| !errs.is_empty());+ if let Some(errs) = rejected {+ let excerpt: String = serde_json::to_string(&errs)+ .unwrap_or_default()+ .chars()+ .take(400)+ .collect();+ tracing::warn!(+ target: LOG_TARGET,+ "[agent-tracing] Langfuse ({status}) rejected {} of {span_count} span event(s): {excerpt}",+ errs.len()+ );+ } else {+ tracing::debug!(+ target: LOG_TARGET,+ "[agent-tracing] pushed {span_count} spans to Langfuse ({status})"+ );+ }+ Ok(())+}diff --git a/crates/openhuman-core/src/agent/prompts/render_helpers.rs b/crates/openhuman-core/src/agent/prompts/render_helpers.rsindex 8a8ac26143..0b146936c3 100644--- a/crates/openhuman-core/src/agent/prompts/render_helpers.rs+++ b/crates/openhuman-core/src/agent/prompts/render_helpers.rs@@ -5,6 +5,26 @@//! structs in [`super::sections`] — `agents/<id>/prompt.rs` builders call//! these to assemble their own final system prompt without needing the full//! [`super::builder::SystemPromptBuilder`] machinery.+//!+//! Split by responsibility:+//! - [`section_renderers`] — the `render_*` wrappers, per-turn datetime stamp,+//! ambient-environment composer, and memory date label.+//! - [`subagent`] — the narrow KV-cache-stable sub-agent prompt renderer.+//! - [`workspace_files`] — workspace-file seeding and prompt injection.++mod section_renderers;+mod subagent;+mod workspace_files;-include!("render_helpers_part_01.rs");-include!("render_helpers_part_02.rs");+pub use section_renderers::{+ current_datetime_line, memory_date_label, render_agents_md, render_ambient_environment,+ render_datetime, render_grounding, render_identity, render_runtime, render_safety,+ render_tools, render_user_files, render_user_identity, render_user_memory,+ render_user_reflections, render_workspace,+};+pub use subagent::{render_subagent_system_prompt, render_subagent_system_prompt_with_format};+pub use workspace_files::{+ default_workspace_file_content, inject_inline_content, inject_snapshot_content,+ inject_workspace_file, inject_workspace_file_capped, sync_workspace_file,+};+pub(crate) use workspace_files::write_agents_md_blocks;diff --git a/crates/openhuman-core/src/agent/prompts/render_helpers/section_renderers.rs b/crates/openhuman-core/src/agent/prompts/render_helpers/section_renderers.rsindex 54bcfdb1af..58e6777605 100644--- a/crates/openhuman-core/src/agent/prompts/render_helpers/section_renderers.rs+++ b/crates/openhuman-core/src/agent/prompts/render_helpers/section_renderers.rs@@ -1,5 +1,5 @@//! Functional `render_*` wrappers over the section structs in-//! [`super::super::sections`], plus the per-turn datetime stamp and the+//! [`crate::agent::prompts::sections`], plus the per-turn datetime stamp and the//! ambient-environment composer that `agents/<id>/prompt.rs` builders call.use super::super::sections::*;@@ -160,7 +160,7 @@ pub fn render_user_identity(ctx: &PromptContext<'_>) -> Result<String> {/// Datetime is appended last so the time-volatile section sits at the/// tail of the prompt and the rest of the prefix stays cache-stable/// across turns within the same minute, matching the convention used-/// by [`super::builder::SystemPromptBuilder::with_defaults`].+/// by [`crate::agent::prompts::builder::SystemPromptBuilder::with_defaults`].pub fn render_ambient_environment(ctx: &PromptContext<'_>) -> Result<String> {let mut out = String::with_capacity(512);let runtime = render_runtime(ctx)?;diff --git a/crates/openhuman-core/src/agent/prompts/render_helpers/subagent.rs b/crates/openhuman-core/src/agent/prompts/render_helpers/subagent.rsindex eacc43310b..1970252727 100644--- a/crates/openhuman-core/src/agent/prompts/render_helpers/subagent.rs+++ b/crates/openhuman-core/src/agent/prompts/render_helpers/subagent.rs@@ -20,7 +20,7 @@ use std::path::Path;/// Render a narrow, KV-cache-stable system prompt for a typed sub-agent.////// This is a purpose-built alternative to-/// [`super::builder::SystemPromptBuilder::for_subagent`] for call sites+/// [`crate::agent::prompts::builder::SystemPromptBuilder::for_subagent`] for call sites/// that only have indices into the parent's `&[Box<dyn Tool>]` vec (so they/// can't cheaply build a filtered owning slice for `ToolsSection`). The/// output mirrors what `for_subagent` would emit with the matching@@ -85,7 +85,7 @@ pub fn render_subagent_system_prompt(/// backwards compatibility.////// `agents_md_global` / `agents_md_local` are the pre-loaded AGENTS.md layers-/// (see [`super::agents_md::load_agents_md_layers`]); `None`/`None` (the value+/// (see [`crate::agent::prompts::agents_md::load_agents_md_layers`]); `None`/`None` (the value/// the public wrapper passes) renders no AGENTS.md block. When present they are/// injected as `## Project instructions (AGENTS.md)` right after the user files/// and before the tool catalogue — matching the section order of the default /@@ -322,6 +322,9 @@ pub fn render_subagent_system_prompt_with_format(out}+/// Build a P-Format signature line (`name[a|b|c]`) from a `&dyn Tool`.+/// Used by `render_subagent_system_prompt` which operates on `Box<dyn Tool>`+/// directly (no intermediate `PromptTool`). Mirrors the `PromptTool` variant/// below — both BTreeMap-iterate the schema's `properties` in the same order.fn render_pformat_signature_for_box_tool(tool: &dyn crate::tools::Tool) -> String {let schema = tool.parameters_schema();diff --git a/crates/openhuman-core/src/agent/prompts/render_helpers/workspace_files.rs b/crates/openhuman-core/src/agent/prompts/render_helpers/workspace_files.rsindex e4f381bf1c..f8e9b36a28 100644--- a/crates/openhuman-core/src/agent/prompts/render_helpers/workspace_files.rs+++ b/crates/openhuman-core/src/agent/prompts/render_helpers/workspace_files.rs@@ -145,7 +145,7 @@ pub fn inject_inline_content(prompt: &mut String, label: &str, content: &str, ma/// Shared `## Project instructions (AGENTS.md)` block writer.///-/// Used by both [`super::sections::AgentsInstructionsSection`] (the default /+/// Used by both [`crate::agent::prompts::sections::AgentsInstructionsSection`] (the default //// sub-agent builder chains) and the narrow sub-agent renderer/// ([`render_subagent_system_prompt_with_format`]) so the two paths never/// drift. The heading is emitted only when at least one layer carries content;@@ -154,7 +154,7 @@ pub fn inject_inline_content(prompt: &mut String, label: &str, content: &str, ma/// capped at [`BOOTSTRAP_MAX_CHARS`] with a `[... truncated]` marker.////// Both inputs are already-loaded, pre-trimmed strings (see-/// [`super::agents_md::load_agents_md`]) — this writer does no file I/O, keeping+/// [`crate::agent::prompts::agents_md::load_agents_md`]) — this writer does no file I/O, keeping/// the rendered bytes a pure function of its inputs for KV-cache stability.pub(crate) fn write_agents_md_blocks(out: &mut String, global: Option<&str>, local: Option<&str>) {let mut body = String::new();@@ -278,8 +278,8 @@ pub fn inject_workspace_file_capped(pub fn default_workspace_file_content(filename: &str) -> &'static str {// The bundled identity files live at `crates/openhuman-core/src/agent/prompts/`// (owned by the `agent/` tree because they describe agent identity).- // This module is under `crates/openhuman-core/src/agent/context/`, so the relative path- // walks up one level and back into `agent/prompts/`.+ // This module is under `agent/prompts/render_helpers/`, so the relative path+ // walks up one level back into `agent/prompts/`.match filename {"SOUL.md" => include_str!("../SOUL.md"),"IDENTITY.md" => include_str!("../IDENTITY.md"),diff --git a/crates/openhuman-core/src/agent/prompts/render_helpers_part_01.rs b/crates/openhuman-core/src/agent/prompts/render_helpers_part_01.rsdeleted file mode 100644index 0cc9f2947c..0000000000--- a/crates/openhuman-core/src/agent/prompts/render_helpers_part_01.rs+++ /dev/null@@ -1,645 +0,0 @@-use super::builder::GLOBAL_STYLE_SUFFIX;-use super::sections::*;-use super::types::*;-use anyhow::Result;-use chrono::{DateTime, Utc};-use std::fmt::Write;-use std::hash::{Hash, Hasher};-use std::path::Path;-use std::sync::OnceLock;--// ─────────────────────────────────────────────────────────────────────────────-// Section render helpers (functional wrappers over section structs)-// ─────────────────────────────────────────────────────────────────────────────--/// Render the `## Project Context` identity block-/// (`SOUL.md` / `IDENTITY.md` / `ROLE.md` for the user-facing agent).-pub fn render_identity(ctx: &PromptContext<'_>) -> Result<String> {- IdentitySection.build(ctx)-}--/// Render the `PROFILE.md` + `MEMORY.md` user-file injection.-/// Empty when neither `ctx.include_profile` nor `ctx.include_memory_md`-/// is set.-pub fn render_user_files(ctx: &PromptContext<'_>) -> Result<String> {- UserFilesSection.build(ctx)-}--/// Render the tree-summariser user-memory block.-pub fn render_user_memory(ctx: &PromptContext<'_>) -> Result<String> {- UserMemorySection.build(ctx)-}--/// Render the `## Project instructions (AGENTS.md)` block from the pre-loaded-/// global + local content on [`PromptContext`]. Empty when neither layer-/// carries content. Dynamic `agents/<id>/prompt.rs` builders call this so they-/// inherit the same AGENTS.md injection as the default section chain.-pub fn render_agents_md(ctx: &PromptContext<'_>) -> Result<String> {- AgentsInstructionsSection.build(ctx)-}--/// Render the privileged `## User Reflections` block. Empty when the-/// learning subsystem has not captured any reflections yet.-pub fn render_user_reflections(ctx: &PromptContext<'_>) -> Result<String> {- UserReflectionsSection.build(ctx)-}--/// Render the `## Tools` catalogue in the dispatcher's tool-call format.-pub fn render_tools(ctx: &PromptContext<'_>) -> Result<String> {- ToolsSection.build(ctx)-}--/// Render the static `## Safety` block.-pub fn render_safety() -> String {- SafetySection- .build(&empty_prompt_context_for_static_sections())- .expect("SafetySection::build is infallible")-}--/// Render the canonical grounding / anti-hallucination contract-/// ([`GROUNDING_BODY`]). Dynamic `agents/<id>/prompt.rs` builders call this-/// so they inherit the exact same anti-fabrication floor as the static-/// section chain — single source of truth, no drift.-pub fn render_grounding() -> &'static str {- GROUNDING_BODY-}--// `render_skills` and `render_connected_integrations` helpers are-// gone — `## Available Skills` lives in `integrations_agent/prompt.rs`, and-// the connected-integrations / delegation-guide blocks each live in-// their owning agent's `prompt.rs` so no branching-on-agent-id logic-// needs to exist here.--/// Render the `## Workspace` block (working directory + file listing-/// bounds) — part of the dynamic, per-request suffix.-pub fn render_workspace(ctx: &PromptContext<'_>) -> Result<String> {- WorkspaceSection.build(ctx)-}--/// Render the `## Runtime` block (model name, dispatcher format) —-/// dynamic.-pub fn render_runtime(ctx: &PromptContext<'_>) -> Result<String> {- RuntimeSection.build(ctx)-}--/// Render the `## Current Date & Time` block: the static time-discipline-/// *rules* (greeting/clock grounding + the gated `resolve_time` rule). The-/// concrete "now" is **not** here — it rides the user message per turn via-/// [`current_datetime_line`] so it stays fresh and keeps this section-/// byte-stable for prefix caching (#3602).-pub fn render_datetime(ctx: &PromptContext<'_>) -> Result<String> {- DateTimeSection.build(ctx)-}--/// Canonical one-line "now" stamp, injected per turn alongside the user-/// message by both the main session loop (`session::turn`) and the-/// sub-agent runner so every flow reports the current time identically-/// (#3602). Local time + IANA zone + `%Z`/offset + weekday, so the model-/// can localize greetings and date math without a tool call.-///-/// Deliberately lives on the *user message*, never the cached-/// system-prompt prefix: `Local::now()` is volatile, so freezing it into-/// the prefix both busts the KV cache and goes stale across a long-lived-/// session. The static grounding *rule* that tells the model to read this-/// line lives in [`DateTimeSection`] / [`render_datetime`].-pub fn current_datetime_line() -> String {- // `library-cpu.sh` sets `OPENHUMAN_PROFILE_FORCE_UTC=1` to skip- // `iana_time_zone`/CoreFoundation timezone resolution, which is itself a- // measurable cost in a cold CPU profile. Gated on `rss-bench`, so it does- // not exist in any shipped build.- #[cfg(feature = "rss-bench")]- if std::env::var_os("OPENHUMAN_PROFILE_FORCE_UTC").is_some() {- let now = chrono::Utc::now();- return format!(- "Current Date & Time: {} UTC (UTC, UTC+00:00), {}",- now.format("%Y-%m-%d %H:%M:%S"),- now.format("%A"),- );- }-- // When the host resolves an IANA zone, stamp local time + that zone. When- // it can't (CI, stripped containers), fall back to true UTC — formatting- // `Utc::now()` so the time, offset, and zone label all agree rather than- // pairing a "UTC" label with a local clock/offset.- match iana_time_zone::get_timezone() {- Ok(iana) => {- let now = chrono::Local::now();- format!(- "Current Date & Time: {} {} ({}, UTC{}), {}",- now.format("%Y-%m-%d %H:%M:%S"),- iana,- now.format("%Z"),- now.format("%:z"),- now.format("%A"),- )- }- Err(_) => {- let now = chrono::Utc::now();- format!(- "Current Date & Time: {} UTC (UTC, UTC+00:00), {}",- now.format("%Y-%m-%d %H:%M:%S"),- now.format("%A"),- )- }- }-}--/// Render the `## User` identity block. Empty when-/// [`PromptContext::user_identity`] is unset or has no populated-/// fields. See issue #926.-pub fn render_user_identity(ctx: &PromptContext<'_>) -> Result<String> {- UserIdentitySection.build(ctx)-}--/// Compose the full ambient-environment block — runtime + user-/// identity + current date/time, in that order.-///-/// Per-agent `prompt.rs` builders call this once near the end of their-/// assembly so every agent reports the same machine-readable view of-/// "where am I, who is the user, what time is it" (issue #926).-/// Datetime is appended last so the time-volatile section sits at the-/// tail of the prompt and the rest of the prefix stays cache-stable-/// across turns within the same minute, matching the convention used-/// by [`super::builder::SystemPromptBuilder::with_defaults`].-pub fn render_ambient_environment(ctx: &PromptContext<'_>) -> Result<String> {- let mut out = String::with_capacity(512);- let runtime = render_runtime(ctx)?;- if !runtime.trim().is_empty() {- out.push_str(runtime.trim_end());- out.push_str("\n\n");- }- let user = render_user_identity(ctx)?;- if !user.trim().is_empty() {- out.push_str(user.trim_end());- out.push_str("\n\n");- }- let datetime = render_datetime(ctx)?;- if !datetime.trim().is_empty() {- out.push_str(datetime.trim_end());- out.push('\n');- }- Ok(out)-}--/// Format a memory item's `updated_at` as an absolute UTC date label-/// for prompt injection, e.g. `2026-05-25`.-///-/// Absolute (not relative "N days ago") on purpose: memory sections sit-/// near the front of the KV-cache-stable system prompt, so a label that-/// changes daily would bust the cached prefix for everything after it.-/// An absolute date only changes when the underlying memory does. The-/// model judges staleness by comparing this against the injected current-/// date. Shared by [`UserMemorySection`] and the working-memory block in-/// `agent_memory::memory_loader`. (#2944)-pub fn memory_date_label(updated_at: DateTime<Utc>) -> String {- updated_at.format("%Y-%m-%d").to_string()-}--// ─────────────────────────────────────────────────────────────────────────────-// Sub-agent prompt renderer-// ─────────────────────────────────────────────────────────────────────────────--/// Render a narrow, KV-cache-stable system prompt for a typed sub-agent.-///-/// This is a purpose-built alternative to-/// [`super::builder::SystemPromptBuilder::for_subagent`] for call sites-/// that only have indices into the parent's `&[Box<dyn Tool>]` vec (so they-/// can't cheaply build a filtered owning slice for `ToolsSection`). The-/// output mirrors what `for_subagent` would emit with the matching-/// `omit_*` flags, plus a sub-agent-specific calling-convention-/// preamble and a model-only runtime banner.-///-/// `archetype_body` is the already-loaded archetype markdown — for-/// `PromptSource::Inline` this is the inline string, for-/// `PromptSource::File` this is the file contents loaded by the caller.-/// Callers resolve the source exactly once and hand the body in, so-/// this renderer works uniformly for both definition shapes.-///-/// `options` carries the per-definition rendering flags (safety, etc.)-/// inverted into positive-sense `include_*` form.-/// [`SubagentRenderOptions::narrow`] preserves the historical behaviour.-///-/// # KV cache stability-///-/// The rendered bytes MUST be a pure function of:-/// - the `archetype_body` (archetype role prompt)-/// - the filtered tool set (names, descriptions, schemas)-/// - the workspace directory-/// - the resolved model name-/// - the `options` (all static per definition)-///-/// Anything that varies across invocations at the *same* call site-/// (e.g. `chrono::Local::now()`, hostnames, pids, turn counters) is-/// forbidden here. Repeat spawns of the same sub-agent within a session-/// must produce byte-identical system prompts so the inference-/// backend's automatic prefix caching can reuse the prefill from the-/// previous run. Time-of-day information, if a sub-agent needs it,-/// belongs in the user message — not the system prompt.-pub fn render_subagent_system_prompt(- workspace_dir: &Path,- model_name: &str,- allowed_indices: &[usize],- parent_tools: &[Box<dyn crate::tools::Tool>],- extra_tools: &[Box<dyn crate::tools::Tool>],- archetype_body: &str,- options: SubagentRenderOptions,- tool_call_format: ToolCallFormat,- connected_integrations: &[ConnectedIntegration],-) -> String {- render_subagent_system_prompt_with_format(- workspace_dir,- model_name,- allowed_indices,- parent_tools,- extra_tools,- archetype_body,- options,- tool_call_format,- connected_integrations,- None,- None,- )-}--/// Inner renderer that accepts an explicit [`ToolCallFormat`] so callers-/// that know the active dispatcher format can thread it through. The-/// public [`render_subagent_system_prompt`] defaults to PFormat for-/// backwards compatibility.-///-/// `agents_md_global` / `agents_md_local` are the pre-loaded AGENTS.md layers-/// (see [`super::agents_md::load_agents_md_layers`]); `None`/`None` (the value-/// the public wrapper passes) renders no AGENTS.md block. When present they are-/// injected as `## Project instructions (AGENTS.md)` right after the user files-/// and before the tool catalogue — matching the section order of the default /-/// sub-agent builders.-#[allow(clippy::too_many_arguments)]-pub fn render_subagent_system_prompt_with_format(- workspace_dir: &Path,- model_name: &str,- allowed_indices: &[usize],- parent_tools: &[Box<dyn crate::tools::Tool>],- extra_tools: &[Box<dyn crate::tools::Tool>],- archetype_body: &str,- options: SubagentRenderOptions,- tool_call_format: ToolCallFormat,- _connected_integrations: &[ConnectedIntegration],- agents_md_global: Option<&str>,- agents_md_local: Option<&str>,-) -> String {- let mut out = String::new();-- // 1. Archetype role prompt. Works for `PromptSource::Inline`,- // `PromptSource::File`, and `PromptSource::Dynamic` because the- // caller preloaded the body via `load_prompt_source`.- let trimmed = archetype_body.trim();- if !trimmed.is_empty() {- out.push_str(trimmed);- out.push_str("\n\n");- }-- // 1b. Optional identity block. Off by default; turned on when the- // definition sets `omit_identity = false`. Renders the same- // OpenClaw bootstrap files the main agent loads, keeping the- // byte layout stable across repeat spawns of the same- // definition within a session.- if options.include_identity {- out.push_str("## Project Context\n\n");- out.push_str(- "The following workspace files define your identity, behavior, and context.\n\n",- );- for file in &["SOUL.md", "IDENTITY.md"] {- inject_workspace_file(&mut out, workspace_dir, file);- }- }-- // 1c. PROFILE.md (onboarding enrichment output) and MEMORY.md- // (archivist-curated long-term memory). Each is gated on its own- // flag and capped at `USER_FILE_MAX_CHARS` (~1000 tokens) so a- // growing on-disk file can't push the system prompt out of the- // cache-friendly prefix range.- //- // KV-cache contract: once these files land in a session's- // rendered prompt the bytes are frozen for the remainder of that- // session. Do not re-read them mid-turn — a byte change breaks- // the backend's automatic prefix cache. Mid-session writes to- // either file are intentionally only visible on the NEXT session.- if options.include_profile {- inject_workspace_file_capped(&mut out, workspace_dir, "PROFILE.md", USER_FILE_MAX_CHARS);- }- if options.include_memory_md {- // Frame MEMORY.md as durable, cross-session background memory —- // byte-identical to `UserFilesSection::build` (GH-4745). Without the- // frame an Inline/File sub-agent on a brand-new thread reads the bare- // `### MEMORY.md` block as prior in-thread conversation and asserts- // continuity that isn't there. Buffer first so the note is emitted- // only when the file actually carries content — a dangling frame- // pointing at nothing would itself imply phantom history.- let mut mem = String::new();- inject_workspace_file_capped(&mut mem, workspace_dir, "MEMORY.md", USER_FILE_MAX_CHARS);- if !mem.trim().is_empty() {- out.push_str(MEMORY_MD_FRAMING);- out.push_str(&mem);- }- }-- // 1d. Project instructions (AGENTS.md), pre-loaded by the caller and shared- // with the section-based builders through `write_agents_md_blocks` so- // the byte layout can never drift between the two paths. Placed after- // the user files and before the tool catalogue, matching the default- // section order. Skipped entirely when both layers are `None`.- write_agents_md_blocks(&mut out, agents_md_global, agents_md_local);-- // 2. Filtered tool catalogue. Indices are taken in ascending order- // from `allowed_indices`, which itself preserves `parent_tools`- // order, so the rendering is deterministic. We use `.get(i)`- // defensively even though the current caller (subagent_runner)- // only produces in-range indices — a future caller that derives- // indices from a different source must not be able to panic this- // renderer with a stale index.- //- // Rendering uses the caller-specified `tool_call_format` so- // sub-agents and the main dispatcher stay in lockstep.- // Tool catalogue rendering is dispatcher-format-aware:- //- // - **Native**: The provider receives full tool schemas through- // the request body's `tools` field (via `filtered_specs` in the- // sub-agent runner) and emits structured `tool_calls`. Listing- // the same tools again as prose in the system prompt is pure- // duplication — for a integrations_agent spawn with 62 dynamic gmail- // tools, that duplication added ~54k tokens and blew past the- // model's context window. We skip the prose `## Tools` section- // entirely in this mode.- //- // - **PFormat / Json**: Both are prompt-driven formats — the- // model discovers tools by reading the prose `## Tools` section- // and emits text-wrapped tool calls (`<tool_call>name[a|b]</tool_call>`- // for PFormat, `<tool_call>{"name":...}</tool_call>` for Json).- // Neither uses the native `tools` request field, so we MUST- // list each tool in prose — including dynamically-registered- // `extra_tools` — or the model has no way to know they exist.- if !matches!(tool_call_format, ToolCallFormat::Native) {- out.push_str("## Tools\n\n");- let render_one =- |out: &mut String, tool: &dyn crate::tools::Tool| match tool_call_format {- ToolCallFormat::PFormat => {- let sig = render_pformat_signature_for_box_tool(tool);- let _ = writeln!(- out,- "- **{}**: {}\n Call as: `{}`",- tool.name(),- tool.description(),- sig- );- }- ToolCallFormat::Json => {- let _ = writeln!(- out,- "- **{}**: {}\n Parameters: `{}`",- tool.name(),- tool.description(),- tool.parameters_schema()- );- }- ToolCallFormat::Native => {- // Unreachable — outer guard skips Native entirely.- }- };- for &i in allowed_indices {- let Some(tool) = parent_tools.get(i) else {- tracing::warn!(- index = i,- tool_count = parent_tools.len(),- "[context::prompt] dropping out-of-range tool index in subagent render"- );- continue;- };- render_one(&mut out, tool.as_ref());- }- for tool in extra_tools {- render_one(&mut out, tool.as_ref());- }- }-- // 3. Sub-agent calling-convention preamble — format-aware.- // Sub-agents need the same call format the main dispatcher expects- // so their output parses correctly.- out.push('\n');- match tool_call_format {- ToolCallFormat::PFormat => {- out.push_str(- "## Tool Use Protocol\n\n\- Tool calls use **P-Format**: compact, positional, pipe-delimited syntax \- wrapped in `<tool_call>` tags.\n\n\- ```\n<tool_call>\ntool_name[arg1|arg2]\n</tool_call>\n```\n\n\- Arguments are positional — match the order shown in each tool's `Call as:` \- signature above (alphabetical by parameter name). \- Escape `|` as `\\|`, `]` as `\\]` inside values. \- You may emit multiple `<tool_call>` blocks per response.\n\n\- Use the provided tools to accomplish the task. Reply with a concise, dense \- final answer when you have one — the parent agent will weave it back into the \- user-visible response.\n\n",- );- }- ToolCallFormat::Json => {- out.push_str(- "## Tool Use Protocol\n\n\- To use a tool, wrap a JSON object in `<tool_call></tool_call>` tags:\n\n\- ```\n<tool_call>\n{\"name\": \"tool_name\", \"arguments\": {\"param\": \"value\"}}\n</tool_call>\n```\n\n\- You may emit multiple `<tool_call>` blocks in a single response.\n\n\- Use the provided tools to accomplish the task. Reply with a concise, dense \- final answer when you have one — the parent agent will weave it back into the \- user-visible response.\n\n",- );- }- ToolCallFormat::Native => {- out.push_str(- "Use the provided tools via the model's native tool-calling output. \- Reply with a concise, dense final answer when you have one — the parent \- agent will weave it back into the user-visible response.\n\n",- );- }- }-- // 3b. Optional safety preamble. Definitions that do work with real- // side-effects (code_executor, tool_maker, integrations_agent) set- // `omit_safety_preamble = false` so the narrow renderer used to- // silently drop that instruction — we now honour the flag.- // Byte-identical to `SafetySection::build`.- if options.include_safety_preamble {- out.push_str(- "## Safety\n\n- Do not exfiltrate private data.\n- Do not run destructive commands without asking.\n- Do not bypass oversight or approval mechanisms.\n- Prefer `trash` over `rm`.\n- When in doubt, ask before acting externally.\n\n",- );- }-- // 3b'. Grounding / anti-hallucination contract. Always emitted (like the- // static chain): every spawned sub-agent gets the same floor.- // Sourced from the shared `GROUNDING_BODY` const so this narrow- // renderer can never drift from `GroundingSection`.- out.push_str(GROUNDING_BODY);- out.push_str("\n\n");-- // 3c/3d. `## Available Skills` and `## Connected Integrations`- // are no longer emitted here. Each agent that needs them- // renders its own block in its `prompt.rs` (integrations_agent- // owns the executor voice, orchestrator/welcome own the- // delegator voice). Legacy Inline/File-sourced TOML agents- // that still route through this helper simply don't get- // either block — which matches the fact that none of them- // currently opt in.-- // 4. Workspace so the model knows where it is. Intentionally stable:- // no datetime, no hostname, no pid — see the KV-cache note above.- let _ = writeln!(- out,- "## Workspace\n\nWorking directory: `{}`\n",- workspace_dir.display()- );-- // 6. Runtime banner — model name only. Stable for the lifetime of- // this sub-agent's definition.- let _ = writeln!(out, "## Runtime\n\nModel: {model_name}");- out.push('\n');- out.push_str(GLOBAL_STYLE_SUFFIX);-- out-}--// ─────────────────────────────────────────────────────────────────────────────-// Workspace-file I/O helpers-// ─────────────────────────────────────────────────────────────────────────────--/// Ensure the workspace file is up-to-date with the compiled-in default.-///-/// On first install the file doesn't exist → write it. On subsequent runs-/// we store a hash of the compiled-in content in a sidecar file-/// (`.{filename}.builtin-hash`). If the hash changes (code was updated),-/// the disk file is overwritten so prompt improvements ship automatically.-/// User edits between code releases are preserved — we only overwrite when-/// the built-in default itself changes.-pub fn sync_workspace_file(workspace_dir: &Path, filename: &str) {- let default_content = default_workspace_file_content(filename);- if default_content.is_empty() {- return;- }-- // A real workspace is always an absolute path (`~/.openhuman/users/<id>/- // workspace`, or a temp dir under test). A relative one means the caller- // never had a workspace to begin with — overwhelmingly `Path::new(".")`- // from the ~20 prompt-test fixtures — and joining onto it seeds SOUL.md,- // IDENTITY.md and ROLE.md plus their- // `.builtin-hash` siblings into the process's current directory. That is- // the repo root when the suite runs, which is how they briefly ended up- // committed (#5701).- //- // Refusing is safe because seeding into a relative path is never the- // intent: a caller with a genuine workspace always has an absolute one.- if !workspace_dir.is_absolute() {- tracing::debug!(- "[workspace-sync] refusing to seed {filename} into non-absolute workspace {} \- — no workspace configured",- workspace_dir.display()- );- return;- }-- let path = workspace_dir.join(filename);- let hash_path = workspace_dir.join(format!(".{filename}.builtin-hash"));-- // Compute a simple hash of the current compiled-in content.- let current_hash = {- let mut hasher = std::collections::hash_map::DefaultHasher::new();- default_content.hash(&mut hasher);- format!("{:016x}", hasher.finish())- };-- // Read the last-written hash (if any).- let stored_hash = std::fs::read_to_string(&hash_path).unwrap_or_default();- let stored_hash = stored_hash.trim();-- if stored_hash == current_hash && path.exists() {- // Built-in hasn't changed and file exists — nothing to do.- return;- }-- // Decide whether to overwrite the existing file. Two safe cases:- // 1. File doesn't exist yet — first install, write the default.- // 2. File exists AND its current hash matches the stored builtin- // hash — the user hasn't edited it since we last wrote it, so- // it's safe to ship the new default.- // Otherwise the file has been hand-edited between releases; leave- // the user's version in place and just update the stored hash so we- // stop re-comparing against the old default on every boot.- let file_exists = path.exists();- let user_unmodified = if file_exists {- match std::fs::read_to_string(&path) {- Ok(disk) => {- let mut hasher = std::collections::hash_map::DefaultHasher::new();- disk.hash(&mut hasher);- let disk_hash = format!("{:016x}", hasher.finish());- disk_hash == stored_hash- }- Err(_) => false,- }- } else {- false- };-- if let Some(parent) = path.parent() {- let _ = std::fs::create_dir_all(parent);- }-- if !file_exists || user_unmodified {- if let Err(e) = std::fs::write(&path, default_content) {- log::warn!("[agent:prompt] failed to write workspace file {filename}: {e}");- return;- }- log::info!("[agent:prompt] updated workspace file {filename} (builtin content changed)");- } else {- log::info!(- "[agent:prompt] keeping user-edited workspace file {filename} (builtin changed but disk contents diverge)"- );- }- let _ = std::fs::write(&hash_path, ¤t_hash);-}--/// Inject `filename` from `workspace_dir` into `prompt`, truncated to-/// [`BOOTSTRAP_MAX_CHARS`]. Thin wrapper around-/// [`inject_workspace_file_capped`] for bootstrap-class files-/// (`SOUL.md`, `IDENTITY.md`, `ROLE.md`).-pub fn inject_workspace_file(prompt: &mut String, workspace_dir: &Path, filename: &str) {- inject_workspace_file_capped(prompt, workspace_dir, filename, BOOTSTRAP_MAX_CHARS);-}--/// Inject pre-loaded string content into `prompt` under a `### label` heading,-/// capped at `max_chars`. Mirrors the format of [`inject_snapshot_content`]-/// and [`inject_workspace_file_capped`] but takes a `&str` instead of a file-/// path. Used for personality-specific overrides (`personality_soul_md`,-/// `personality_memory_md`) on [`PromptContext`] so a swap from the file-based-/// loader to an inline override is byte-compatible with the workspace-file path.-///-/// Empty/whitespace content is silently skipped.-pub fn inject_inline_content(prompt: &mut String, label: &str, content: &str, max_chars: usize) {- let trimmed = content.trim();- if trimmed.is_empty() {- return;- }- let _ = writeln!(prompt, "### {label}\n");- let truncated = if trimmed.chars().count() > max_chars {- trimmed- .char_indices()- .nth(max_chars)- .map(|(idx, _)| &trimmed[..idx])- .unwrap_or(trimmed)- } else {- trimmed- };- prompt.push_str(truncated);- if truncated.len() < trimmed.len() {- let _ = writeln!(- prompt,- "\n\n[... truncated at {max_chars} chars — use `read` for full file]\n"- );- } else {- prompt.push_str("\n\n");- }-}diff --git a/crates/openhuman-core/src/agent/prompts/render_helpers_part_02.rs b/crates/openhuman-core/src/agent/prompts/render_helpers_part_02.rsdeleted file mode 100644index 2d022e0891..0000000000--- a/crates/openhuman-core/src/agent/prompts/render_helpers_part_02.rs+++ /dev/null@@ -1,211 +0,0 @@--/// Shared `## Project instructions (AGENTS.md)` block writer.-///-/// Used by both [`super::sections::AgentsInstructionsSection`] (the default /-/// sub-agent builder chains) and the narrow sub-agent renderer-/// ([`render_subagent_system_prompt_with_format`]) so the two paths never-/// drift. The heading is emitted only when at least one layer carries content;-/// the global layer renders first, then the local/project layer. Each layer is-/// injected via [`inject_inline_content`] under its own `###` sub-heading and-/// capped at [`BOOTSTRAP_MAX_CHARS`] with a `[... truncated]` marker.-///-/// Both inputs are already-loaded, pre-trimmed strings (see-/// [`super::agents_md::load_agents_md`]) — this writer does no file I/O, keeping-/// the rendered bytes a pure function of its inputs for KV-cache stability.-pub(crate) fn write_agents_md_blocks(out: &mut String, global: Option<&str>, local: Option<&str>) {- let mut body = String::new();- if let Some(g) = global {- inject_inline_content(&mut body, "AGENTS.md (workspace)", g, BOOTSTRAP_MAX_CHARS);- }- if let Some(l) = local {- inject_inline_content(&mut body, "AGENTS.md (project)", l, BOOTSTRAP_MAX_CHARS);- }- if body.trim().is_empty() {- log::debug!("[agents_md] no AGENTS.md content to inject; skipping section");- return;- }- log::debug!(- "[agents_md] injecting AGENTS.md section (global={}, local={})",- global.is_some(),- local.is_some()- );- out.push_str("## Project instructions (AGENTS.md)\n\n");- out.push_str(- "Configurable standing instructions loaded from AGENTS.md files. Treat these as \- durable guidance for how to operate here. The workspace layer applies globally; \- the project layer applies to the current working directory and takes precedence \- where the two conflict. They are background guidance, not messages in this \- conversation.\n\n",- );- out.push_str(&body);-}--/// for the output header and truncation semantics.-///-/// Empty/whitespace content is silently skipped, mirroring the file-/// loader's "no noisy placeholder" behaviour.-pub fn inject_snapshot_content(prompt: &mut String, label: &str, content: &str, max_chars: usize) {- let trimmed = content.trim();- if trimmed.is_empty() {- return;- }- let _ = writeln!(prompt, "### {label}\n");- let truncated = if trimmed.chars().count() > max_chars {- trimmed- .char_indices()- .nth(max_chars)- .map(|(idx, _)| &trimmed[..idx])- .unwrap_or(trimmed)- } else {- trimmed- };- prompt.push_str(truncated);- if truncated.len() < trimmed.len() {- let _ = writeln!(- prompt,- "\n\n[... truncated at {max_chars} chars — use `read` for full file]\n"- );- } else {- prompt.push_str("\n\n");- }-}--/// Inject `filename` into `prompt` with an explicit character budget.-///-/// Used directly by callers that want a tighter cap than-/// [`BOOTSTRAP_MAX_CHARS`] — notably `PROFILE.md` and `MEMORY.md` which-/// are user-specific, potentially growing, and do not warrant a full-/// 20K-char budget (see [`USER_FILE_MAX_CHARS`]).-///-/// Missing / empty files are silently skipped so callers can inject-/// optional files unconditionally without emitting a noisy placeholder.-///-/// **KV-cache contract:** the output is a pure function of `filename`,-/// file bytes at call time, and `max_chars`. Callers must invoke this-/// once per session — re-reading mid-session breaks the inference-/// backend's automatic prefix cache. See the byte-stability note on-/// [`render_subagent_system_prompt`].-pub fn inject_workspace_file_capped(- prompt: &mut String,- workspace_dir: &Path,- filename: &str,- max_chars: usize,-) {- 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");- let truncated = if trimmed.chars().count() > max_chars {- trimmed- .char_indices()- .nth(max_chars)- .map(|(idx, _)| &trimmed[..idx])- .unwrap_or(trimmed)- } else {- trimmed- };- prompt.push_str(truncated);- if truncated.len() < trimmed.len() {- let _ = writeln!(- prompt,- "\n\n[... truncated at {max_chars} chars — use `read` for full file]\n"- );- } else {- prompt.push_str("\n\n");- }- }- Err(e) => match e.kind() {- std::io::ErrorKind::NotFound => {- // Keep prompt focused: missing optional identity/bootstrap files should not- // add noisy placeholders that dilute tool-calling instructions.- }- _ => {- log::debug!("[prompt] failed to read {}: {e}", path.display());- }- },- }-}--pub fn default_workspace_file_content(filename: &str) -> &'static str {- // The bundled identity files live at `crates/openhuman-core/src/agent/prompts/`- // (owned by the `agent/` tree because they describe agent identity).- // This module is under `crates/openhuman-core/src/agent/context/`, so the relative path- // walks up one level and back into `agent/prompts/`.- match filename {- "SOUL.md" => include_str!("SOUL.md"),- "IDENTITY.md" => include_str!("IDENTITY.md"),- // The user-facing agent's role brief and writing style, moved out of- // the compiled `orchestrator/prompt.md` so both are tunable on disk- // without a rebuild (#5701). Same sync-and-inject contract as- // SOUL.md / IDENTITY.md: the bundled copy seeds the workspace, and a- // user edit wins from the next session on.- "ROLE.md" => include_str!("ROLE.md"),- "STYLE.md" => include_str!("STYLE.md"),-- _ => "",- }-}--// ─────────────────────────────────────────────────────────────────────────────-// Internal helpers-// ─────────────────────────────────────────────────────────────────────────────--/// Build a throwaway `PromptContext` for sections whose `build` only-/// uses static/immutable inputs (currently just `SafetySection`). Keeps-/// the `render_safety()` free function from forcing callers to-/// manufacture a full context when they only need the static text.-fn empty_prompt_context_for_static_sections() -> PromptContext<'static> {- static EMPTY_TOOLS: &[PromptTool<'static>] = &[];- static EMPTY_WORKFLOWS: &[crate::skills::Workflow] = &[];- static EMPTY_INTEGRATIONS: &[ConnectedIntegration] = &[];- // SAFETY: the &HashSet reference must outlive the returned context;- // a leaked OnceLock-style allocation gives us a permanent 'static- // anchor without adding runtime cost on the hot path.- static EMPTY_VISIBLE: OnceLock<std::collections::HashSet<String>> = OnceLock::new();- let visible = EMPTY_VISIBLE.get_or_init(std::collections::HashSet::new);- PromptContext {- workspace_dir: std::path::Path::new(""),- model_name: "",- agent_id: "",- tools: EMPTY_TOOLS,- workflows: EMPTY_WORKFLOWS,- dispatcher_instructions: "",- learned: LearnedContextData::default(),- visible_tool_names: visible,- tool_call_format: ToolCallFormat::PFormat,- connected_integrations: EMPTY_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,- }-}--/// Build a P-Format signature line (`name[a|b|c]`) from a `&dyn Tool`.-/// Used by `render_subagent_system_prompt` which operates on `Box<dyn Tool>`-/// directly (no intermediate `PromptTool`). Mirrors the `PromptTool` variant-/// below — both BTreeMap-iterate the schema's `properties` in the same order.-fn render_pformat_signature_for_box_tool(tool: &dyn crate::tools::Tool) -> String {- let schema = tool.parameters_schema();- let names: Vec<String> = schema- .get("properties")- .and_then(|p| p.as_object())- .map(|m| m.keys().cloned().collect())- .unwrap_or_default();- if names.is_empty() {- format!("{}[]", tool.name())- } else {- format!("{}[{}]", tool.name(), names.join("|"))- }-}