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
Merge remote-tracking branch 'upstream/main' into epic-7929-upstream-rollup
Steven Enamakel834966b91e40
diff --cc Cargo.lockindex ef3b430b6a,5ec263b8bc..f39c9191b1--- a/Cargo.lock+++ b/Cargo.lock@@@ -5599,10 -5600,10 +5601,11 @@@ dependencies ="tinyagents-definition","tinyagents-graph","tinyagents-harness",+ "tinyagents-hooks","tinyagents-session","tinybus",- "tinyflows-schedule",+ "tinyflows-bus",+ "tinyflows-module","tinyinference-embeddings","tinyinference-llm 0.4.1","tinymcp-bus",diff --cc crates/openhuman-core/src/agent/hooks.rsindex 66216f8a1d,d9f8e27d01..d7d0d167be--- a/crates/openhuman-core/src/agent/hooks.rs+++ b/crates/openhuman-core/src/agent/hooks.rs@@@ -1,60 -1,40 +1,60 @@@-//! Post-turn hook infrastructure for agent self-learning.+//! Process-wide hooks supplied by an embedding host.//!-//! Hooks fire asynchronously after a turn completes, receiving a snapshot of-//! what happened (user message, assistant response, tool calls with outcomes).-//! The agent does not wait for hooks — they run in the background via `tokio::spawn`.+//! Hook contracts and their per-agent scope are owned by `tinyagents-hooks`;+//! this module only keeps the embedder registries and the host identity bridge.-#[path = "hooks_scope.rs"]-mod scope;-pub use scope::HookScope;--use async_trait::async_trait;-use serde::{Deserialize, Serialize};use std::sync::Arc;-/// Post-turn hooks supplied by a process embedding OpenHuman.-static EMBEDDER_POST_TURN_HOOKS: std::sync::LazyLock<std::sync::Mutex<Vec<Arc<dyn PostTurnHook>>>> =+use tinyagents_harness::host::LearningSink;+use tinyagents_hooks::tool::{HookIdentity, ToolHook};++use crate::agent::tinyagents::host::OpenHumanRunContext;++type NamedLearningSink = (Option<String>, Arc<dyn LearningSink>);+type NamedToolHook = (Option<String>, Arc<dyn ToolHook<OpenHumanRunContext>>);++static EMBEDDER_POST_TURN_HOOKS: std::sync::LazyLock<std::sync::Mutex<Vec<NamedLearningSink>>> =std::sync::LazyLock::new(|| std::sync::Mutex::new(Vec::new()));+static EMBEDDER_TOOL_HOOKS: std::sync::LazyLock<std::sync::Mutex<Vec<NamedToolHook>>> =+ std::sync::LazyLock::new(|| std::sync::Mutex::new(Vec::new()));++impl HookIdentity for OpenHumanRunContext {+ fn session_id(&self) -> Option<String> {+ self.thread_id.clone()+ }-/// Register a hook that is copied into subsequently-created agent sessions.-pub fn register_embedder_post_turn_hook(hook: Arc<dyn PostTurnHook>) {+ fn agent_id(&self) -> Option<String> {+ self.dispatch_ctx()+ .core()- .and_then(|context| context.session_agent().map(str::to_owned))++ .and_then(|context| crate::core::runtime::Tenant::of(context).agent)+ }++ fn cwd(&self) -> Option<std::path::PathBuf> {+ self.workspace+ .as_ref()+ .map(|workspace| workspace.root.clone())+ .or_else(|| {+ self.dispatch_ctx()+ .core()+ .and_then(|context| context.workspace_dir().ok())+ })+ }+}++pub fn register_embedder_post_turn_hook(hook: Arc<dyn LearningSink>) {EMBEDDER_POST_TURN_HOOKS.lock()- .expect("embedder post-turn hooks poisoned")- .push(hook);+ .expect("embedder learning sinks poisoned")+ .push((None, hook));}-/// Replace an embedder post-turn hook by name, or remove it when absent.-///-/// This prevents a host that rebuilds its core from retaining callbacks from a-/// previous configuration in the process-global registry.-pub fn replace_embedder_post_turn_hook(name: &str, hook: Option<Arc<dyn PostTurnHook>>) {+pub fn replace_embedder_post_turn_hook(name: &str, hook: Option<Arc<dyn LearningSink>>) {let mut hooks = EMBEDDER_POST_TURN_HOOKS.lock()- .expect("embedder post-turn hooks poisoned");- hooks.retain(|registered| registered.name() != name);+ .expect("embedder learning sinks poisoned");+ hooks.retain(|(registered, _)| registered.as_deref() != Some(name));if let Some(hook) = hook {- hooks.push(hook);+ hooks.push((Some(name.to_owned()), hook));}}diff --cc crates/openhuman-core/src/agent/orchestration/agent_teams/runtime_tests.rsindex 4a4b08a74b,8f31b8a41d..12389ff010--- a/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime_tests.rs@@@ -300,14 -277,20 +300,14 @@@ async fn run_member_loop_drives_member_Some("test-model".into()),Some(mock_parent(provider)),)- .await;-- let done = run_ledger::get_agent_team_task(&config.workspace_dir, "task-a")- .unwrap()- .unwrap();- assert_eq!(- done.status,- AgentTeamTaskStatus::Done,- "run_member_loop drove the member to completion through with_root_parent"- );+ .await+ .expect("run_member_loop returns evidence through with_root_parent");+ assert_eq!(evidence.len(), 1);+ assert!(evidence[0].contains("teamrun-y"));}- #[tokio::test]+ #[tokio::test(start_paused = true)]-async fn drive_member_releases_task_when_worker_fails() {+async fn owner_releases_task_when_host_worker_fails() {AgentDefinitionRegistry::init_global_builtins().unwrap();let (_dir, config) = test_config();seed_team(&config, "team-1");diff --cc crates/openhuman-core/src/agent/orchestration/subagent_sessions/mod.rsindex 6dc9e2c7a3,48f34a86ae..b42fb4dee3--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/mod.rs+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/mod.rs@@@ -1,7 -1,8 +1,9 @@@mod ops;+ mod storage_schema;mod store;+ pub use storage_schema::storage_schema;mod store_documents;+mod tiny_port;mod types;pub use ops::{diff --cc crates/openhuman-core/src/agent/subagent_host/lifecycle.rsindex a586944861,679a91cb88..720d9f1378--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs@@@ -1,16 -1,17 +1,14 @@@-//! OpenHuman's three host seams for the neutral subagent lifecycle.-//!-//! The old runner deliberately remains the execution leaf while its policy-rich-//! prompt/tool assembly is decomposed. This adapter makes the ownership-//! boundary explicit now: TinyAgents owns the lifecycle and OpenHuman owns the-//! plan, execution details, and translation back to its public DTOs.-+//! OpenHuman supplies plans, execution, persistence, and DTO projection;+//! TinyAgents owns subagent lifecycle coordination.-++use async_trait::async_trait;++use sha2::{Digest, Sha256};use std::{collections::HashMap,+ future::Future,path::PathBuf,+ pin::Pin,sync::{Arc, Mutex},};----use async_trait::async_trait;- use sha2::{Digest, Sha256};use tinyagents_harness::context::{RunConfig, RunContext};use tinyagents_orchestration::subagent::{ArtifactReference, PreparedSubagent, SubagentCapabilities, SubagentDriver, SubagentError,@@@ -727,17 -408,613 +725,19 @@@ impl OpenHumanSubagentHost}}-#[derive(Clone)]-struct HostRequest {- definition: crate::agent::harness::host_definition::AgentDefinition,- options: SubagentRunOptions,-}--struct PreparedHostPlan {- definition: crate::agent::harness::host_definition::AgentDefinition,- options: SubagentRunOptions,-}--struct OpenHumanPlanner {- plan: Arc<Mutex<Option<PreparedHostPlan>>>,-}--/// Appends the new continuation input to the exact durable history supplied by-/// TinyAgents. Kept separate so the no-drop/no-duplicate resume contract has a-/// focused regression test independent of provider execution.-pub(super) fn merged_resume_history(mut history: Vec<Message>, input: String) -> Vec<Message> {- if !input.is_empty() {- history.push(Message::user(input));- }- history-}--#[async_trait]-impl SubagentPlanner<crate::agent::tinyagents::host::OpenHumanRunContext, HostRequest>- for OpenHumanPlanner-{- async fn prepare(- &self,- request: SubagentRequest<crate::agent::tinyagents::host::OpenHumanRunContext, HostRequest>,- ) -> Result<PreparedSubagent<crate::agent::tinyagents::host::OpenHumanRunContext>, SubagentError>- {- let request = request.into_parts();- let mut options = request.host_request.options;- let input = request.input;- // The generic persistence seam supplies the pause *before* host- // options are prepared. A continuation's new user answer belongs- // after that durable history, exactly once; never overwrite a- // caller-provided answer with the loaded checkpoint.- let planned_input = if let Some(resume) = request.resume {- let history = merged_resume_history(resume.history, input);- options.initial_history = Some(- history- .iter()- .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)- .collect(),- );- history- } else {- vec![Message::user(input)]- };- options.task_id = Some(request.task_key.task_id.clone());- options.run_context = request.run_context.data.clone();- *self.plan.lock().unwrap_or_else(|p| p.into_inner()) = Some(PreparedHostPlan {- definition: request.host_request.definition.clone(),- options,- });- // The host leaf resolves the real tool snapshot and policy; an empty- // declaration here advertises no unresolved authority.- Ok(PreparedSubagent::new(- request.task_key.task_id,- request.host_request.definition.id,- planned_input,- ToolSnapshot::default(),- request.run_context,- ))- }-}--struct OpenHumanExecutor {- plan: Arc<Mutex<Option<PreparedHostPlan>>>,- failures: Arc<Mutex<Option<SubagentRunError>>>,- host_outcome: Arc<Mutex<Option<SubagentRunOutcome>>>,-}--#[async_trait]-impl SubagentExecutor<crate::agent::tinyagents::host::OpenHumanRunContext> for OpenHumanExecutor {- async fn execute(- &self,- execution: SubagentExecution<crate::agent::tinyagents::host::OpenHumanRunContext>,- ) -> Result<SubagentOutcome, SubagentError> {- let PreparedHostPlan {- definition,- mut options,- } = self- .plan- .lock()- .unwrap_or_else(|p| p.into_inner())- .take()- .ok_or_else(|| {- SubagentError::Execution("OpenHuman subagent plan was consumed".into())- })?;- // Both carriers observe one token. The generic driver installs this- // token on the prepared RunContext; the host graph polls the copy in- // its explicit OpenHuman carrier.- options.run_context = execution.prepared.run_context.data.clone();- options.run_context.cancellation = execution.cancellation.clone();- match Box::pin(super::ops::run_subagent_direct(- &definition,- &execution- .prepared- .input- .last()- .map(Message::text)- .unwrap_or_default(),- options.clone(),- ))- .await- {- Ok(outcome) => {- *self.host_outcome.lock().unwrap_or_else(|p| p.into_inner()) =- Some(outcome.clone());- Ok(host_outcome_to_neutral(outcome, &definition, &options))- }- Err(error) => {- *self.failures.lock().unwrap_or_else(|p| p.into_inner()) = Some(error);- Err(SubagentError::Execution(- "OpenHuman execution failed".into(),- ))- }- }- }-}--/// Durable OpenHuman pause/terminal records scoped by the complete neutral-/// task key, on the storage port ([`store::LifecycleStore`]). The key is-/// encoded rather than used raw, so equally named children of separate-/// roots/parents can never resume or close one another's lifecycle.-pub(super) struct OpenHumanPersistence {- checkpoint_dir: std::path::PathBuf,- host_outcome: Arc<Mutex<Option<SubagentRunOutcome>>>,-}--use store::{LifecycleRecord, LifecycleStore, TerminalRecord};--/// What a pause or terminal write decided, so the compare-and-swap closure-/// can report an error without unwinding it.-type Decision<T> = Result<T, String>;--impl OpenHumanPersistence {- pub(super) fn new(checkpoint_dir: std::path::PathBuf) -> Self {- Self {- checkpoint_dir,- host_outcome: Arc::new(Mutex::new(None)),- }- }-- fn with_host_outcome(mut self, host_outcome: Arc<Mutex<Option<SubagentRunOutcome>>>) -> Self {- self.host_outcome = host_outcome;- self- }-- /// The name callers report for `key`'s pause. The pause itself is a- /// storage record now; this keeps the historical- /// `lifecycle/<component>.pause.json` spelling so reported checkpoint- /// names are unchanged and stay unique per scoped key.- fn pause_path(&self, key: &SubagentTaskKey) -> std::path::PathBuf {- self.checkpoint_dir- .join("lifecycle")- .join(format!("{}.pause.json", store::key_component(key)))- }-- fn store(&self) -> Result<LifecycleStore, SubagentError> {- LifecycleStore::open(&self.checkpoint_dir)- }-- /// The record's pause, refusing one stored under a different key.- fn pause_of(- record: &LifecycleRecord,- key: &SubagentTaskKey,- ) -> Result<Option<super::SubagentCheckpointData>, SubagentError> {- match &record.pause {- Some(checkpoint) if checkpoint.task_key.as_ref() != Some(key) => {- Err(SubagentError::Persistence("checkpoint key mismatch".into()))- }- other => Ok(other.clone()),- }- }-- fn durable_host_metadata(- &self,- key: &SubagentTaskKey,- ) -> Result<Option<(String, u64)>, SubagentError> {- let record = self.store()?.record(key)?;- if let Some(terminal) = record.terminal {- let named = !terminal.agent_id.is_empty();- return Ok(named.then_some((terminal.agent_id, terminal.elapsed_ms)));- }- Ok(Self::pause_of(&record, key)?.and_then(|checkpoint| {- (!checkpoint.agent_id.is_empty())- .then_some((checkpoint.agent_id, checkpoint.elapsed_ms))- }))- }-- fn checkpoint_resume(checkpoint: &super::SubagentCheckpointData) -> SubagentResume {- SubagentResume {- history: checkpoint- .history- .iter()- .map(crate::agent::message_convert::chat_message_to_message)- .collect(),- checkpoint: checkpoint.resume_checkpoint.clone(),- metadata: checkpoint.resume_metadata.clone(),- }- }-- fn checkpoint_outcome(checkpoint: super::SubagentCheckpointData) -> SubagentOutcome {- let resume = Self::checkpoint_resume(&checkpoint);- SubagentOutcome {- task_id: checkpoint.task_id,- output: checkpoint.output,- history: checkpoint- .history- .iter()- .map(crate::agent::message_convert::chat_message_to_message)- .collect(),- status: SubagentOutcomeKind::AwaitingInput(SubagentPause {- reason: checkpoint.question,- resume,- }),- usage: UsageTotals {- calls: checkpoint.iterations as u64,- usage: Usage {- input_tokens: checkpoint.usage.input_tokens,- output_tokens: checkpoint.usage.output_tokens,- total_tokens: checkpoint- .usage- .input_tokens- .saturating_add(checkpoint.usage.output_tokens),- cache_read_tokens: checkpoint.usage.cached_input_tokens,- // An unknown cost crosses as no charge at all, never as $0.- charged_amount: checkpoint- .usage- .cost()- .usd()- .map(|usd| ChargedAmount::usd_micros((usd * 1_000_000.0).round() as i64)),- ..Usage::default()- },- },- artifacts: checkpoint- .artifact_paths- .into_iter()- .map(|id| ArtifactReference {- id,- ..ArtifactReference::default()- })- .collect(),- ..SubagentOutcome::cancelled(String::new())- }- }-- fn live_checkpoint(- &self,- key: &SubagentTaskKey,- ) -> Result<Option<super::SubagentCheckpointData>, SubagentError> {- let record = self.store()?.record(key)?;- if record.terminal.is_some() {- return Ok(None);- }- Self::pause_of(&record, key)- }-- fn checkpoint_for_task(- &self,- task_id: &str,- ) -> Result<super::SubagentCheckpointData, SubagentRunError> {- if !super::ops::is_safe_task_id(task_id) {- return Err(SubagentRunError::Provider(anyhow::anyhow!(- "unsafe task id"- )));- }- let keys = self- .store()- .and_then(|store| store.index_keys(task_id))- .map_err(map_lifecycle_error)?;- let mut live = Vec::new();- for key in keys {- if let Some(checkpoint) = self.live_checkpoint(&key).map_err(map_lifecycle_error)? {- live.push(checkpoint);- }- }- match live.len() {- 1 => Ok(live.remove(0)),- 0 => Err(SubagentRunError::Provider(anyhow::anyhow!(- "no live subagent pause checkpoint for task id"- ))),- _ => Err(SubagentRunError::Provider(anyhow::anyhow!(- "ambiguous subagent task id; select a scoped lifecycle key"- ))),- }- }-- pub(crate) fn recover_key(- checkpoint_dir: &std::path::Path,- task_id: &str,- ) -> Result<SubagentTaskKey, SubagentRunError> {- let persistence = Self::new(checkpoint_dir.to_path_buf());- let checkpoint = persistence.checkpoint_for_task(task_id)?;- checkpoint.task_key.ok_or_else(|| {- SubagentRunError::Provider(anyhow::anyhow!("checkpoint omitted original task key"))- })- }-}--#[async_trait]-impl tinyagents_orchestration::subagent::SubagentPersistence for OpenHumanPersistence {- async fn load_terminal(- &self,- key: &SubagentTaskKey,- ) -> Result<Option<SubagentOutcome>, SubagentError> {- Ok(self- .store()?- .record(key)?- .terminal- .map(|record| record.outcome))- }- async fn load(&self, key: &SubagentTaskKey) -> Result<Option<SubagentResume>, SubagentError> {- let record = self.store()?.record(key)?;- if record.terminal.is_some() {- return Ok(None);- }- Ok(Self::pause_of(&record, key)?- .as_ref()- .map(Self::checkpoint_resume))- }-- async fn load_pause(- &self,- key: &SubagentTaskKey,- ) -> Result<Option<SubagentOutcome>, SubagentError> {- let record = self.store()?.record(key)?;- if record.terminal.is_some() {- return Ok(None);- }- Ok(Self::pause_of(&record, key)?.map(Self::checkpoint_outcome))- }-- async fn save_pause(- &self,- pause: tinyagents_orchestration::subagent::PersistedSubagentPause,- ) -> Result<SubagentPausePersistenceDisposition, SubagentError> {- let store = self.store()?;- let paused = match &pause.outcome.status {- SubagentOutcomeKind::AwaitingInput(paused) => paused,- _ => {- return Err(SubagentError::Persistence(- "attempted to persist a non-paused subagent outcome as a pause".into(),- ));- }- };- let metadata = &paused.resume.metadata;- let optional_metadata = |name: &str| {- metadata- .get(name)- .filter(|value| !value.is_empty())- .cloned()- };- let checkpoint = super::SubagentCheckpointData {- task_key: Some(pause.key.clone()),- task_id: pause.key.task_id.clone(),- agent_id: optional_metadata("agent_id").unwrap_or_default(),- worker_thread_id: optional_metadata("worker_thread_id"),- history: pause- .outcome- .history- .iter()- .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)- .collect(),- question: paused.reason.clone(),- options: None,- skill_filter_override: optional_metadata("skill_filter_override"),- model_override: optional_metadata("model_override"),- created_at: chrono::Utc::now().to_rfc3339(),- resume_checkpoint: paused.resume.checkpoint.clone(),- resume_metadata: metadata.clone(),- output: pause.outcome.output.clone(),- iterations: pause.outcome.usage.calls as usize,- usage: SubagentUsage {- input_tokens: pause.outcome.usage.usage.input_tokens,- output_tokens: pause.outcome.usage.usage.output_tokens,- cached_input_tokens: pause.outcome.usage.usage.cache_read_tokens,- charged_amount_usd: pause- .outcome- .usage- .usage- .charged_amount- .map(|amount| amount.micros as f64 / 1_000_000.0)- .unwrap_or_default(),- cost_source: cost_source_of(pause.outcome.usage.usage.charged_amount.as_ref()),- },- artifact_paths: pause- .outcome- .artifacts- .iter()- .map(|artifact| artifact.id.clone())- .collect(),- elapsed_ms: self- .host_outcome- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner())- .as_ref()- .map(|outcome| outcome.elapsed.as_millis() as u64)- .unwrap_or_default(),- };- // Index first: a failed data write can leave a stale index, which- // readers filter by the live pause record. A successful pause can- // never be unresumable through a missing index.- store.add_index_key(&pause.key)?;- let (key, replaces) = (pause.key.clone(), pause.replaces.clone());- let decided: Decision<SubagentPausePersistenceDisposition> = store.update(&pause.key, {- move |record| {- if record.terminal.is_some() {- return (- Ok(SubagentPausePersistenceDisposition::TerminalExisting),- false,- );- }- let current = match Self::pause_of(record, &key) {- Ok(current) => current,- Err(error) => return (Err(error.to_string()), false),- };- match (replaces.as_ref(), current) {- (None, None) => {- record.pause = Some(checkpoint.clone());- (Ok(SubagentPausePersistenceDisposition::Inserted), true)- }- (Some(expected), Some(current))- if Self::checkpoint_resume(¤t) == *expected =>- {- record.pause = Some(checkpoint.clone());- (Ok(SubagentPausePersistenceDisposition::Replaced), true)- }- _ => (Ok(SubagentPausePersistenceDisposition::Existing), false),- }- }- })?;- decided.map_err(SubagentError::Persistence)- }-- async fn record_terminal(- &self,- key: &SubagentTaskKey,- outcome: &SubagentOutcome,- replaces: Option<&SubagentResume>,- ) -> Result<SubagentTerminalPersistenceDisposition, SubagentError> {- let store = self.store()?;- let host = self- .host_outcome- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner())- .clone();- let terminal = TerminalRecord {- outcome: outcome.clone(),- agent_id: host- .as_ref()- .map(|outcome| outcome.agent_id.clone())- .unwrap_or_default(),- elapsed_ms: host- .as_ref()- .map(|outcome| outcome.elapsed.as_millis() as u64)- .unwrap_or_default(),- };- let (scoped, replaces) = (key.clone(), replaces.cloned());- let decided: Decision<SubagentTerminalPersistenceDisposition> = store.update(key, {- move |record| {- if record.terminal.is_some() {- return (Ok(SubagentTerminalPersistenceDisposition::Existing), false);- }- match Self::pause_of(record, &scoped) {- Err(error) => return (Err(error.to_string()), false),- Ok(Some(current)) => {- let can_consume_pause = replaces- .as_ref()- .is_some_and(|expected| Self::checkpoint_resume(¤t) == *expected);- if !can_consume_pause {- return (- Ok(SubagentTerminalPersistenceDisposition::PauseExisting),- false,- );- }- }- Ok(None) if replaces.is_some() => {- return (- Err("terminal continuation lost its expected durable pause".into()),- false,- );- }- Ok(None) => {}- }- // Terminal is the durable winner. Retiring a matching pause in- // the same write means it can never reopen the lifecycle.- record.terminal = Some(terminal.clone());- record.pause = None;- (Ok(SubagentTerminalPersistenceDisposition::Inserted), true)- }- })?;- let disposition = decided.map_err(SubagentError::Persistence)?;- if disposition == SubagentTerminalPersistenceDisposition::Inserted {- // A stale task-id index is harmless because recovery filters- // terminal keys. Never turn a durable terminal success into an- // error merely because cleanup of a derived index failed.- if let Err(error) = store.remove_index_key(key) {- tracing::warn!(task_id = %key.task_id, error = %error, "[subagent] terminal committed but task-id index cleanup failed");- }- }- Ok(disposition)- }-}-+#[path = "lifecycle/driver_adapter.rs"]+mod driver_adapter;+/// One configured OpenHuman lifecycle driver and its request-keyed host+/// projections. Keeping this factory separate lets registered TinyAgents+/// dispatchers reuse the same planner, executor and persistence adapters+/// without routing through `OpenHumanSubagentHost::run` (which would create a+/// second generic driver).+#[path = "lifecycle/persistence.rs"]+mod persistence;+ #[path = "lifecycle_store.rs"]+ mod store;-#[path = "lifecycle_outcome.rs"]-mod outcome;-use outcome::{host_outcome_to_neutral, HostInFlightMap};--fn outcome_to_host(- result: SubagentRunResult,- host: Option<SubagentRunOutcome>,- persistence: &OpenHumanPersistence,- task_key: &SubagentTaskKey,- fallback_agent_id: &str,-) -> SubagentRunOutcome {- let persistence_disposition = result.disposition;- let outcome = result.outcome;- // A driver that lost a pause/terminal CAS may have a perfectly valid local- // execution result, but it is not the authoritative lifecycle outcome.- // Reconstruct the durable winner instead of leaking the loser’s output,- // usage, or artifacts to an observer.- let host = if persistence_disposition.should_emit_host_effects() {- host- } else {- None- };- let durable_metadata = if host.is_none() {- persistence.durable_host_metadata(task_key).ok().flatten()- } else {- None- };- let mut host = host.unwrap_or_else(|| SubagentRunOutcome {- task_id: outcome.task_id.clone(),- agent_id: durable_metadata- .as_ref()- .map(|(agent_id, _)| agent_id.clone())- .unwrap_or_else(|| fallback_agent_id.to_owned()),- output: outcome.output.clone(),- iterations: outcome.usage.calls as usize,- elapsed: std::time::Duration::from_millis(- durable_metadata- .map(|(_, elapsed_ms)| elapsed_ms)- .unwrap_or_default(),- ),- mode: super::SubagentMode::Typed,- status: SubagentRunStatus::Completed,- final_history: outcome- .history- .iter()- .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)- .collect(),- usage: SubagentUsage {- input_tokens: outcome.usage.usage.input_tokens,- output_tokens: outcome.usage.usage.output_tokens,- cached_input_tokens: outcome.usage.usage.cache_read_tokens,- charged_amount_usd: outcome- .usage- .usage- .charged_amount- .map(|amount| amount.micros as f64 / 1_000_000.0)- .unwrap_or_default(),- cost_source: cost_source_of(outcome.usage.usage.charged_amount.as_ref()),- },- artifact_paths: outcome- .artifacts- .iter()- .map(|artifact| artifact.id.clone())- .collect(),- persistence_disposition,- });- let is_awaiting_input = matches!(outcome.status, SubagentOutcomeKind::AwaitingInput(_));- let status = match outcome.status {- SubagentOutcomeKind::Completed => SubagentRunStatus::Completed,- SubagentOutcomeKind::AwaitingInput(pause) => SubagentRunStatus::AwaitingUser {- question: pause.reason,- options: None,- checkpoint: None,- },- SubagentOutcomeKind::Incomplete(incomplete) => SubagentRunStatus::Incomplete {- reason: incomplete.reason,- },- SubagentOutcomeKind::Cancelled => SubagentRunStatus::Cancelled,- };- host.status = status;- host.persistence_disposition = persistence_disposition;- if is_awaiting_input {- host.status = SubagentRunStatus::AwaitingUser {- question: match host.status {- SubagentRunStatus::AwaitingUser { ref question, .. } => question.clone(),- _ => String::new(),- },- options: None,- checkpoint: Some(persistence.pause_path(task_key)),- };- }- host-}+pub(super) use driver_adapter::{HostRequest, OpenHumanDriverBundle};fn map_lifecycle_error(error: SubagentError) -> SubagentRunError {SubagentRunError::Provider(anyhow::anyhow!(error.to_string()))diff --cc crates/openhuman-core/src/agent/subagent_host/lifecycle/persistence.rsindex 4b7549b80d,0000000000..e9b45d4364mode 100644,000000..100644--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle/persistence.rs+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle/persistence.rs@@@ -1,663 -1,0 +1,681 @@@+use super::*;+use crate::agent::subagent_host::types::SubagentCheckpointData;++pub(in crate::agent::subagent_host) struct OpenHumanPersistence {+ checkpoint_dir: std::path::PathBuf,- file_store: tinyagents_orchestration::subagent::FileSubagentPersistence,+ host_outcome: Arc<Mutex<HashMap<SubagentTaskKey, SubagentRunOutcome>>>,+}++#[derive(serde::Serialize, serde::Deserialize)]+struct TerminalRecord {+ outcome: SubagentOutcome,+ #[serde(default)]+ agent_id: String,+ #[serde(default)]+ elapsed_ms: u64,+}++#[derive(serde::Deserialize)]+#[serde(untagged)]+enum CompatibleTerminalRecord {+ Current(TerminalRecord),+ Legacy(SubagentOutcome),+}++impl OpenHumanPersistence {+ pub(in crate::agent::subagent_host) fn new(checkpoint_dir: std::path::PathBuf) -> Self {+ Self {- file_store: tinyagents_orchestration::subagent::FileSubagentPersistence::new(- checkpoint_dir.clone(),- ),+ checkpoint_dir,+ host_outcome: Arc::new(Mutex::new(HashMap::new())),+ }+ }++ pub(in crate::agent::subagent_host) fn with_host_outcome(+ mut self,+ host_outcome: Arc<Mutex<HashMap<SubagentTaskKey, SubagentRunOutcome>>>,+ ) -> Self {+ self.host_outcome = host_outcome;+ self+ }++ fn set_host_disposition(+ &self,+ key: &SubagentTaskKey,+ disposition: tinyagents_orchestration::subagent::SubagentPersistenceDisposition,+ ) {+ if let Some(outcome) = self+ .host_outcome+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .get_mut(key)+ {+ outcome.persistence_disposition = disposition;+ }+ }++ fn key_component(key: &SubagentTaskKey) -> String {+ fn hex(value: &str) -> String {+ value+ .as_bytes()+ .iter()+ .map(|byte| format!("{byte:02x}"))+ .collect()+ }+ let encoded = format!(+ "{}-{}-{}-{}",+ hex(&key.root_run_id),+ hex(&key.parent_run_id),+ hex(key.thread_id.as_deref().unwrap_or("")),+ hex(&key.task_id),+ );+ // A task key normally contains short UUID-like identifiers, for which+ // the reversible encoding preserves existing checkpoint paths. A+ // background child may inherit a rendered parent identifier, however;+ // hex-encoding that value can exceed the filesystem filename limit.+ // Hash only that exceptional form while keeping all key fields in the+ // digest input so distinct lifecycle scopes cannot alias.+ if encoded.len() <= 180 {+ encoded+ } else {+ format!("sha256-{:x}", Sha256::digest(encoded.as_bytes()))+ }+ }+++ fn store(++ &self,++ ) -> Result<tinyagents_orchestration::subagent::DocumentSubagentPersistence, SubagentError>++ {++ super::store::LifecycleStore::open(&self.checkpoint_dir)?.neutral_store()++ }+++ pub(super) fn pause_path(&self, key: &SubagentTaskKey) -> std::path::PathBuf {- self.file_store- .pause_path(key)- .expect("valid subagent pause key has a persistence path")++ // A public checkpoint name, retained for compatibility. Durable data++ // lives in the acting scope's document store, never at this path.++ self.legacy_pause_path(key)+ }++ pub(in crate::agent::subagent_host) fn legacy_pause_path(+ &self,+ key: &SubagentTaskKey,+ ) -> std::path::PathBuf {+ self.checkpoint_dir+ .join("lifecycle")+ .join(format!("{}.pause.json", Self::key_component(key)))+ }++ fn terminal_path(&self, key: &SubagentTaskKey) -> std::path::PathBuf {+ self.checkpoint_dir+ .join("lifecycle")+ .join(format!("{}.terminal.json", Self::key_component(key)))+ }++ pub(in crate::agent::subagent_host) fn index_path(&self, task_id: &str) -> std::path::PathBuf {+ self.checkpoint_dir+ .join("lifecycle")+ .join(format!("task-{}.index.json", Self::task_component(task_id)))+ }++ fn task_component(task_id: &str) -> String {+ let encoded = task_id+ .as_bytes()+ .iter()+ .map(|byte| format!("{byte:02x}"))+ .collect::<String>();+ if encoded.len() <= 180 {+ encoded+ } else {+ format!("sha256-{:x}", Sha256::digest(encoded.as_bytes()))+ }+ }++ fn read_index_keys(&self, task_id: &str) -> Result<Vec<SubagentTaskKey>, SubagentError> {+ let raw = match std::fs::read_to_string(self.index_path(task_id)) {+ Ok(raw) => raw,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),+ Err(error) => return Err(SubagentError::Persistence(error.to_string())),+ };+ let value: serde_json::Value = serde_json::from_str(&raw)+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;+ // Accept both legacy index shapes during read-only migration. New- // writes and indexes are owned by FileSubagentPersistence.++ // writes and task lookup are owned by DocumentSubagentPersistence.+ let keys = value+ .get("keys")+ .cloned()+ .map(serde_json::from_value)+ .transpose()+ .map_err(|error| SubagentError::Persistence(error.to_string()))?+ .or_else(|| {+ value+ .get("key")+ .cloned()+ .and_then(|key| serde_json::from_value(key).ok())+ .map(|key| vec![key])+ })+ .unwrap_or_default();+ Ok(keys)+ }++ fn read_pause_checkpoint(+ &self,+ key: &SubagentTaskKey,+ ) -> Result<Option<SubagentCheckpointData>, SubagentError> {++ let store = self.store()?;++ if store.terminal_outcome(key)?.is_some() {++ return Ok(None);++ }++ if let Some(outcome) = store.pause_outcome(key)? {++ return Self::checkpoint_from_persisted_pause(++ tinyagents_orchestration::subagent::PersistedSubagentPause {++ key: key.clone(),++ outcome,++ replaces: None,++ },++ )++ .map(Some);++ }+ let raw = match std::fs::read_to_string(self.pause_path(key)) {+ Ok(raw) => raw,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ match std::fs::read_to_string(self.legacy_pause_path(key)) {+ Ok(raw) => raw,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(error) => return Err(SubagentError::Persistence(error.to_string())),+ }+ }+ Err(error) => return Err(SubagentError::Persistence(error.to_string())),+ };+ let checkpoint = match serde_json::from_str::<SubagentCheckpointData>(&raw) {+ Ok(checkpoint) => checkpoint,+ Err(legacy_error) => {+ let persisted = serde_json::from_str::<+ tinyagents_orchestration::subagent::PersistedSubagentPause,+ >(&raw)+ .map_err(|_| SubagentError::Persistence(legacy_error.to_string()))?;+ Self::checkpoint_from_persisted_pause(persisted)?+ }+ };+ if checkpoint.task_key.as_ref() != Some(key) {+ return Err(SubagentError::Persistence("checkpoint key mismatch".into()));+ }+ Ok(Some(checkpoint))+ }+- fn checkpoint_from_persisted_pause(++ pub(in crate::agent::subagent_host) fn checkpoint_from_persisted_pause(+ persisted: tinyagents_orchestration::subagent::PersistedSubagentPause,+ ) -> Result<SubagentCheckpointData, SubagentError> {+ let host = persisted+ .outcome+ .extensions+ .get("openhuman_checkpoint")+ .cloned()+ .unwrap_or_default();+ let outcome = persisted.outcome;+ let paused = match &outcome.status {+ SubagentOutcomeKind::AwaitingInput(paused) => paused.clone(),+ _ => {+ return Err(SubagentError::Persistence(+ "persisted subagent checkpoint was not awaiting input".into(),+ ));+ }+ };+ let metadata = paused.resume.metadata;+ let host_string = |name: &str| {+ host.get(name)+ .and_then(serde_json::Value::as_str)+ .unwrap_or_default()+ .to_owned()+ };+ let task_key = Some(persisted.key.clone());+ let task_id = persisted.key.task_id.clone();+ Ok(SubagentCheckpointData {+ task_key,+ task_id,+ agent_id: metadata+ .get("agent_id")+ .cloned()+ .or_else(|| {+ host.get("agent_id")+ .and_then(serde_json::Value::as_str)+ .map(str::to_owned)+ })+ .unwrap_or_default(),+ worker_thread_id: metadata.get("worker_thread_id").cloned().or_else(|| {+ host.get("worker_thread_id")+ .and_then(serde_json::Value::as_str)+ .map(str::to_owned)+ }),+ history: outcome+ .history+ .iter()+ .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)+ .collect(),+ question: paused.reason,+ options: host+ .get("options")+ .and_then(|value| serde_json::from_value(value.clone()).ok()),+ skill_filter_override: metadata.get("skill_filter_override").cloned().or_else(|| {+ host.get("skill_filter_override")+ .and_then(serde_json::Value::as_str)+ .map(str::to_owned)+ }),+ model_override: metadata.get("model_override").cloned().or_else(|| {+ host.get("model_override")+ .and_then(serde_json::Value::as_str)+ .map(str::to_owned)+ }),+ created_at: host_string("created_at"),+ resume_checkpoint: paused.resume.checkpoint,+ resume_metadata: metadata,+ output: outcome.output,+ iterations: outcome.usage.calls as usize,+ usage: SubagentUsage {+ input_tokens: outcome.usage.usage.input_tokens,+ output_tokens: outcome.usage.usage.output_tokens,+ cached_input_tokens: outcome.usage.usage.cache_read_tokens,+ charged_amount_usd: outcome+ .usage+ .usage+ .charged_amount+ .map(|amount| amount.micros as f64 / 1_000_000.0)+ .unwrap_or_default(),+ cost_source: outcome+ .cost_source+ .or_else(|| {+ host.get("cost_source")+ .cloned()+ .and_then(|value| serde_json::from_value(value).ok())+ })+ .unwrap_or_else(|| cost_source_of(outcome.usage.usage.charged_amount.as_ref())),+ },+ artifact_paths: outcome+ .artifacts+ .into_iter()+ .map(|artifact| artifact.id)+ .collect(),+ elapsed_ms: host+ .get("elapsed_ms")+ .and_then(serde_json::Value::as_u64)+ .unwrap_or_default(),+ })+ }++ fn read_terminal_record(+ &self,+ key: &SubagentTaskKey,+ ) -> Result<Option<TerminalRecord>, SubagentError> {+ let raw = match std::fs::read_to_string(self.terminal_path(key)) {+ Ok(raw) => raw,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(error) => return Err(SubagentError::Persistence(error.to_string())),+ };+ match serde_json::from_str(&raw)+ .map_err(|error| SubagentError::Persistence(error.to_string()))?+ {+ CompatibleTerminalRecord::Current(record) => Ok(Some(record)),+ CompatibleTerminalRecord::Legacy(outcome) => Ok(Some(TerminalRecord {+ outcome,+ agent_id: String::new(),+ elapsed_ms: 0,+ })),+ }+ }++ pub(super) fn terminal_outcome(+ &self,+ key: &SubagentTaskKey,+ ) -> Result<Option<SubagentOutcome>, SubagentError> {- if let Some(outcome) = self.file_store.terminal_outcome(key)? {++ if let Some(outcome) = self.store()?.terminal_outcome(key)? {+ return Ok(Some(outcome));+ }+ Ok(self.read_terminal_record(key)?.map(|record| record.outcome))+ }++ pub(super) fn durable_host_metadata(+ &self,+ key: &SubagentTaskKey,+ ) -> Result<Option<(String, u64)>, SubagentError> {- if let Some(outcome) = self.file_store.terminal_outcome(key)? {++ if let Some(outcome) = self.store()?.terminal_outcome(key)? {+ let agent_id = outcome+ .extensions+ .get("agent_id")+ .and_then(serde_json::Value::as_str)+ .unwrap_or_default();+ if !agent_id.is_empty() {+ let elapsed_ms = outcome+ .extensions+ .get("elapsed_ms")+ .and_then(serde_json::Value::as_u64)+ .unwrap_or_default();+ return Ok(Some((agent_id.to_owned(), elapsed_ms)));+ }+ }+ if let Some(record) = self.read_terminal_record(key)? {+ return Ok(+ (!record.agent_id.is_empty()).then_some((record.agent_id, record.elapsed_ms))+ );+ }+ Ok(self.read_pause_checkpoint(key)?.and_then(|checkpoint| {+ (!checkpoint.agent_id.is_empty())+ .then_some((checkpoint.agent_id, checkpoint.elapsed_ms))+ }))+ }++ pub(crate) fn checkpoint_resume(checkpoint: &SubagentCheckpointData) -> SubagentResume {+ SubagentResume {+ history: checkpoint+ .history+ .iter()+ .map(crate::agent::message_convert::chat_message_to_message)+ .collect(),+ checkpoint: checkpoint.resume_checkpoint.clone(),+ metadata: checkpoint.resume_metadata.clone(),+ }+ }+- fn checkpoint_outcome(checkpoint: SubagentCheckpointData) -> SubagentOutcome {++ pub(in crate::agent::subagent_host) fn checkpoint_outcome(++ checkpoint: SubagentCheckpointData,++ ) -> SubagentOutcome {+ let resume = Self::checkpoint_resume(&checkpoint);+ let host_checkpoint = serde_json::json!({+ "agent_id": checkpoint.agent_id.clone(),+ "worker_thread_id": checkpoint.worker_thread_id.clone(),+ "created_at": checkpoint.created_at.clone(),+ "options": checkpoint.options.clone(),+ "skill_filter_override": checkpoint.skill_filter_override.clone(),+ "model_override": checkpoint.model_override.clone(),+ "elapsed_ms": checkpoint.elapsed_ms,+ "elapsed_ns": checkpoint.elapsed_ms.saturating_mul(1_000_000),+ "cost_source": checkpoint.usage.cost_source,+ });+ let mut outcome =+ SubagentOutcome {+ task_id: checkpoint.task_id,+ output: checkpoint.output,+ history: checkpoint+ .history+ .iter()+ .map(crate::agent::message_convert::chat_message_to_message)+ .collect(),+ status: SubagentOutcomeKind::AwaitingInput(SubagentPause {+ reason: checkpoint.question,+ resume,+ }),+ usage: UsageTotals {+ calls: checkpoint.iterations as u64,+ usage: Usage {+ input_tokens: checkpoint.usage.input_tokens,+ output_tokens: checkpoint.usage.output_tokens,+ total_tokens: checkpoint+ .usage+ .input_tokens+ .saturating_add(checkpoint.usage.output_tokens),+ cache_read_tokens: checkpoint.usage.cached_input_tokens,+ // An unknown cost crosses as no charge at all, never as $0.+ charged_amount: checkpoint.usage.cost().usd().map(|usd| {+ ChargedAmount::usd_micros((usd * 1_000_000.0).round() as i64)+ }),+ ..Usage::default()+ },+ },+ artifacts: checkpoint+ .artifact_paths+ .into_iter()+ .map(|id| ArtifactReference {+ id,+ ..ArtifactReference::default()+ })+ .collect(),+ cost_usd: checkpoint.usage.cost().usd(),+ cost_source: Some(checkpoint.usage.cost_source),+ ..SubagentOutcome::cancelled(String::new())+ };+ outcome+ .extensions+ .insert("openhuman_checkpoint".into(), host_checkpoint);+ outcome+ }++ pub(in crate::agent::subagent_host) async fn migrate_legacy_pause(+ &self,+ key: &SubagentTaskKey,+ checkpoint: SubagentCheckpointData,+ ) -> Result<Option<SubagentOutcome>, SubagentError> {+ let outcome = Self::checkpoint_outcome(checkpoint);+ let disposition = tinyagents_orchestration::subagent::SubagentPersistence::save_pause(- &self.file_store,++ &self.store()?,+ tinyagents_orchestration::subagent::PersistedSubagentPause {+ key: key.clone(),+ outcome: outcome.clone(),+ replaces: None,+ },+ )+ .await?;+ use tinyagents_orchestration::subagent::SubagentPausePersistenceDisposition as Pause;+ match disposition {+ Pause::Inserted | Pause::Replaced => Ok(Some(outcome)),+ Pause::Existing => {- if self.file_store.terminal_outcome(key)?.is_some() {++ if self.store()?.terminal_outcome(key)?.is_some() {+ return Ok(None);+ }+ tinyagents_orchestration::subagent::SubagentPersistence::load_pause(- &self.file_store,++ &self.store()?,+ key,+ )+ .await+ }+ Pause::TerminalExisting => Ok(None),+ }+ }++ fn live_checkpoint(+ &self,+ key: &SubagentTaskKey,+ ) -> Result<Option<SubagentCheckpointData>, SubagentError> {- if self.file_store.terminal_outcome(key)?.is_some() {++ if self.store()?.terminal_outcome(key)?.is_some() {+ return Ok(None);+ }+ if self.terminal_path(key).exists() {+ return Ok(None);+ }+ self.read_pause_checkpoint(key)+ }++ pub(super) fn checkpoint_for_task(+ &self,+ task_id: &str,+ ) -> Result<SubagentCheckpointData, SubagentRunError> {+ if !crate::agent::subagent_host::ops::is_safe_task_id(task_id) {+ return Err(SubagentRunError::Provider(anyhow::anyhow!(+ "unsafe task id"+ )));+ }+ let mut keys = self- .file_store- .keys_for_task(task_id)++ .store()++ .and_then(|store| store.keys_for_task(task_id))+ .map_err(map_lifecycle_error)?;+ let legacy_keys = self.read_index_keys(task_id).map_err(map_lifecycle_error)?;+ for key in legacy_keys {+ if !keys.contains(&key) {+ keys.push(key);+ }+ }+ let mut live = Vec::new();+ for key in keys {+ if let Some(checkpoint) = self.live_checkpoint(&key).map_err(map_lifecycle_error)? {+ live.push(checkpoint);+ }+ }+ match live.len() {+ 1 => Ok(live.remove(0)),+ 0 => Err(SubagentRunError::Provider(anyhow::anyhow!(+ "no live subagent pause checkpoint for task id"+ ))),+ _ => Err(SubagentRunError::Provider(anyhow::anyhow!(+ "ambiguous subagent task id; select a scoped lifecycle key"+ ))),+ }+ }++ pub(crate) fn recover_key(+ checkpoint_dir: &std::path::Path,+ task_id: &str,+ ) -> Result<SubagentTaskKey, SubagentRunError> {+ let persistence = Self::new(checkpoint_dir.to_path_buf());+ let checkpoint = persistence.checkpoint_for_task(task_id)?;+ checkpoint.task_key.ok_or_else(|| {+ SubagentRunError::Provider(anyhow::anyhow!("checkpoint omitted original task key"))+ })+ }+}++#[async_trait]+impl tinyagents_orchestration::subagent::SubagentPersistence for OpenHumanPersistence {+ async fn load_terminal(+ &self,+ key: &SubagentTaskKey,+ ) -> Result<Option<SubagentOutcome>, SubagentError> {- if let Some(outcome) = self.file_store.terminal_outcome(key)? {++ if let Some(outcome) = self.store()?.terminal_outcome(key)? {+ return Ok(Some(outcome));+ }+ Ok(self.read_terminal_record(key)?.map(|record| record.outcome))+ }+ async fn load(&self, key: &SubagentTaskKey) -> Result<Option<SubagentResume>, SubagentError> {+ if self.load_terminal(key).await?.is_some() {+ return Ok(None);+ }+ if let Some(resume) =- tinyagents_orchestration::subagent::SubagentPersistence::load(&self.file_store, key)++ tinyagents_orchestration::subagent::SubagentPersistence::load(&self.store()?, key)+ .await?+ {+ return Ok(Some(resume));+ }+ let Some(checkpoint) = self.read_pause_checkpoint(key)? else {+ return Ok(None);+ };+ let Some(outcome) = self.migrate_legacy_pause(key, checkpoint).await? else {+ return Ok(None);+ };+ let SubagentOutcomeKind::AwaitingInput(paused) = outcome.status else {+ return Err(SubagentError::Persistence(+ "legacy pause migration produced a non-paused outcome".into(),+ ));+ };+ Ok(Some(paused.resume))+ }++ async fn load_pause(+ &self,+ key: &SubagentTaskKey,+ ) -> Result<Option<SubagentOutcome>, SubagentError> {+ if self.load_terminal(key).await?.is_some() {+ return Ok(None);+ }- if let Some(outcome) = tinyagents_orchestration::subagent::SubagentPersistence::load_pause(- &self.file_store,- key,- )- .await?++ if let Some(outcome) =++ tinyagents_orchestration::subagent::SubagentPersistence::load_pause(&self.store()?, key)++ .await?+ {+ return Ok(Some(outcome));+ }+ match self.read_pause_checkpoint(key)? {+ Some(checkpoint) => self.migrate_legacy_pause(key, checkpoint).await,+ None => Ok(None),+ }+ }++ async fn save_pause(+ &self,+ mut pause: tinyagents_orchestration::subagent::PersistedSubagentPause,+ ) -> Result<SubagentPausePersistenceDisposition, SubagentError> {+ let host_elapsed = self+ .host_outcome+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .get(&pause.key)+ .map(|outcome| outcome.elapsed)+ .unwrap_or_default();+ // Product checkpoint fields absent from the neutral pause stay in a+ // namespaced extension; reserved TinyAgents fields remain untouched.+ let host_checkpoint = serde_json::json!({+ "created_at": chrono::Utc::now().to_rfc3339(),+ "options": pause.outcome.extensions.get("options"),+ "elapsed_ms": host_elapsed.as_millis() as u64,+ "elapsed_ns": host_elapsed.as_nanos().min(u64::MAX as u128) as u64,+ });+ pause+ .outcome+ .extensions+ .entry("openhuman_checkpoint".into())+ .or_insert(host_checkpoint);+ let disposition = tinyagents_orchestration::subagent::SubagentPersistence::save_pause(- &self.file_store,++ &self.store()?,+ pause.clone(),+ )+ .await?;+ let host_disposition = match disposition {+ SubagentPausePersistenceDisposition::Inserted => {+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::PauseCommitted+ }+ SubagentPausePersistenceDisposition::Replaced => {+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::PauseReplaced+ }+ SubagentPausePersistenceDisposition::Existing => {+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::PauseExisting+ }+ SubagentPausePersistenceDisposition::TerminalExisting => {+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::TerminalExisting+ }+ };+ self.set_host_disposition(&pause.key, host_disposition);+ Ok(disposition)+ }++ async fn record_terminal(+ &self,+ key: &SubagentTaskKey,+ outcome: &SubagentOutcome,+ replaces: Option<&SubagentResume>,+ ) -> Result<SubagentTerminalPersistenceDisposition, SubagentError> {+ let host = self+ .host_outcome+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .get(key)+ .cloned();+ let mut durable_outcome = outcome.clone();+ if let Some(host) = host.as_ref() {+ durable_outcome.extensions.insert(+ "agent_id".into(),+ serde_json::Value::String(host.agent_id.clone()),+ );+ durable_outcome.extensions.insert(+ "elapsed_ms".into(),+ serde_json::json!(host.elapsed.as_millis() as u64),+ );+ durable_outcome.extensions.insert(+ "elapsed_ns".into(),+ serde_json::json!(host.elapsed.as_nanos().min(u64::MAX as u128) as u64),+ );+ }+ let disposition = tinyagents_orchestration::subagent::SubagentPersistence::record_terminal(- &self.file_store,++ &super::store::LifecycleStore::before_terminal(&self.checkpoint_dir)?++ .neutral_store()?,+ key,+ &durable_outcome,+ replaces,+ )+ .await?;+ let host_disposition = match disposition {+ SubagentTerminalPersistenceDisposition::Inserted => {+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::TerminalInserted+ }+ SubagentTerminalPersistenceDisposition::Existing => {+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::TerminalExisting+ }+ SubagentTerminalPersistenceDisposition::PauseExisting => {+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::PauseExisting+ }+ };+ self.set_host_disposition(key, host_disposition);+ Ok(disposition)+ }+}diff --cc crates/openhuman-core/src/agent/subagent_host/lifecycle_storage_adoption_tests.rsindex 0000000000,0000000000..1027a70535new file mode 100644--- /dev/null+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle_storage_adoption_tests.rs@@@ -1,0 -1,0 +1,162 @@@++use super::*;++use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};++use tinyagents_orchestration::subagent::{++ PersistedSubagentPause, SubagentOutcomeKind, SubagentPause, SubagentPersistence,++ SubagentResume, SubagentTerminalPersistenceDisposition,++};++++fn task() -> SubagentTaskKey {++ SubagentTaskKey {++ root_run_id: "storage-root".into(),++ parent_run_id: "storage-parent".into(),++ thread_id: Some("same-thread".into()),++ task_id: "same-child".into(),++ }++}++++fn paused(key: &SubagentTaskKey) -> PersistedSubagentPause {++ let mut outcome = SubagentOutcome::cancelled(&key.task_id);++ outcome.output = "durable partial".into();++ outcome.status = SubagentOutcomeKind::AwaitingInput(SubagentPause {++ reason: "which source?".into(),++ resume: SubagentResume::default(),++ });++ PersistedSubagentPause {++ key: key.clone(),++ outcome,++ replaces: None,++ }++}++++fn actor(workspace: &Path, profile: &str) -> std::sync::Arc<CoreContext> {++ let mut config = crate::config::Config::default();++ config.workspace_dir = workspace.to_path_buf();++ config.config_path = workspace.join("config.toml");++ CoreContext::for_test(DomainSet::full(), None).derive_with(++ ContextOverlay::new(config, DomainSet::full(), Default::default())++ .profile(profile)++ .session_agent("same-agent"),++ )++}++++#[tokio::test]++async fn production_lifecycle_persistence_follows_the_explicit_actor_scope_on_reopen() {++ let workspace = tempfile::tempdir().unwrap();++ let checkpoints = workspace.path().join(".openhuman/subagent_checkpoints");++ let key = task();++ let alice = actor(workspace.path(), "lifecycle-alice");++ let bob = actor(workspace.path(), "lifecycle-bob");++ CoreContext::scope(alice.clone(), async {++ let adapter = super::super::persistence::OpenHumanPersistence::new(checkpoints.clone());++ adapter.save_pause(paused(&key)).await.unwrap();++ assert_eq!(++ adapter.checkpoint_for_task(&key.task_id).unwrap().output,++ "durable partial"++ );++ })++ .await;++ CoreContext::scope(bob, async {++ let adapter = super::super::persistence::OpenHumanPersistence::new(checkpoints.clone());++ assert!(adapter.load_pause(&key).await.unwrap().is_none());++ assert!(adapter.checkpoint_for_task(&key.task_id).is_err());++ })++ .await;++ CoreContext::scope(alice, async {++ let reopened = super::super::persistence::OpenHumanPersistence::new(checkpoints.clone());++ let durable = reopened.load_pause(&key).await.unwrap().unwrap();++ assert_eq!(durable.output, "durable partial");++ let SubagentOutcomeKind::AwaitingInput(pause) = durable.status else {++ panic!("durable pause")++ };++ let mut terminal = SubagentOutcome::cancelled(&key.task_id);++ terminal.output = "terminal winner".into();++ terminal++ .extensions++ .insert("agent_id".into(), serde_json::json!("researcher"));++ terminal++ .extensions++ .insert("elapsed_ms".into(), serde_json::json!(97));++ assert_eq!(++ reopened++ .record_terminal(&key, &terminal, Some(&pause.resume))++ .await++ .unwrap(),++ SubagentTerminalPersistenceDisposition::Inserted++ );++ let restarted = super::super::persistence::OpenHumanPersistence::new(checkpoints.clone());++ assert!(restarted.load_pause(&key).await.unwrap().is_none());++ // A stale legacy copy may still exist after read-only migration.++ let stale_path = restarted.legacy_pause_path(&key);++ std::fs::create_dir_all(stale_path.parent().unwrap()).unwrap();++ let stale =++ super::super::persistence::OpenHumanPersistence::checkpoint_from_persisted_pause(++ paused(&key),++ )++ .unwrap();++ std::fs::write(&stale_path, serde_json::to_vec(&stale).unwrap()).unwrap();++ assert!(restarted.checkpoint_for_task(&key.task_id).is_err());++ assert!(super::super::load_subagent_checkpoint(&checkpoints, &key.task_id).is_err());++ let terminal = restarted.load_terminal(&key).await.unwrap().unwrap();++ assert_eq!(terminal.output, "terminal winner");++ assert_eq!(terminal.extensions["agent_id"], "researcher");++ assert_eq!(terminal.extensions["elapsed_ms"], 97);++ })++ .await;++}++++#[test]++fn legacy_host_kv_pause_is_converted_without_rewriting_the_source_record() {++ let workspace = tempfile::tempdir().unwrap();++ let store = LifecycleStore::open(workspace.path()).unwrap();++ let key = task();++ let mut checkpoint =++ super::super::persistence::OpenHumanPersistence::checkpoint_from_persisted_pause(paused(++ &key,++ ))++ .unwrap();++ checkpoint.agent_id = "researcher".into();++ checkpoint.elapsed_ms = 73;++ let record = LifecycleRecord {++ pause: Some(checkpoint),++ terminal: None,++ };++ store++ .kv++ .put(&LifecycleStore::record_name(&key), &record)++ .unwrap();++ let before = serde_json::to_value(store.record(&key).unwrap()).unwrap();++ let owner = store.neutral_store().unwrap();++ let durable = owner.pause_outcome(&key).unwrap().unwrap();++ assert_eq!(++ durable.extensions["openhuman_checkpoint"]["agent_id"],++ "researcher"++ );++ assert_eq!(durable.extensions["openhuman_checkpoint"]["elapsed_ms"], 73);++ assert_eq!(++ owner.keys_for_task(&key.task_id).unwrap(),++ vec![key.clone()]++ );++ assert_eq!(++ serde_json::to_value(store.record(&key).unwrap()).unwrap(),++ before++ );++}++++#[test]++fn owner_file_pause_is_imported_and_the_original_bytes_stay_unchanged() {++ let workspace = tempfile::tempdir().unwrap();++ let key = task();++ let file_store =++ tinyagents_orchestration::subagent::FileSubagentPersistence::new(workspace.path());++ let file = file_store.pause_path(&key).unwrap();++ std::fs::create_dir_all(file.parent().unwrap()).unwrap();++ let bytes = serde_json::to_vec(&paused(&key)).unwrap();++ std::fs::write(&file, &bytes).unwrap();++ let store = LifecycleStore::open(workspace.path()).unwrap();++ let owner = store.neutral_store().unwrap();++ assert_eq!(++ owner.pause_outcome(&key).unwrap().unwrap().output,++ "durable partial"++ );++ assert_eq!(std::fs::read(file).unwrap(), bytes);++}diff --cc crates/openhuman-core/src/agent/subagent_host/lifecycle_store.rsindex 0000000000,5b32a9b038..156d13802bmode 000000,100644..100644--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle_store.rs+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle_store.rs@@@ -1,0 -1,317 +1,412 @@@+ //! The sub-agent lifecycle records on the storage port.+ //!+ //! One record per scoped task key (`record/<key component>` in `tsd.kv`, owner+ //! `subagents`, namespace `lifecycle`) holds the key's pause checkpoint and+ //! its terminal outcome together, so "a terminal closes the pause" is one+ //! compare-and-swap rather than two files under a lock. A second value per task id+ //! (`index/<task component>`) lists the scoped keys that share the id.+ //!+ //! Before schema v2 these were `<workspace>/.openhuman/subagent_checkpoints/+ //! lifecycle/<component>.{pause,terminal}.json` and `task-<component>.index.json`+ //! guarded by `flock` files. [`LifecycleStore::open`] imports them once per+ //! backend and scope (`tsd.migrations`) and leaves the files in place.++ use std::path::{Path, PathBuf};++ use sha2::{Digest, Sha256};+ use tinyagents_orchestration::subagent::{SubagentError, SubagentOutcome, SubagentTaskKey};++ use crate::agent::subagent_host::SubagentCheckpointData;+ use crate::storage::state_kv::StateKv;++ const OWNER: &str = "subagents";+ const NS: &str = "lifecycle";-const IMPORT: &str = "lifecycle_dir";++const IMPORT: &str = "lifecycle_dir_owner_adoption";++ /// A task's terminal outcome with the host facts the neutral outcome lacks.+ #[derive(Clone, serde::Serialize, serde::Deserialize)]+ pub(super) struct TerminalRecord {++ #[serde(default)]++ key: Option<SubagentTaskKey>,+ pub(super) outcome: SubagentOutcome,+ #[serde(default)]+ pub(super) agent_id: String,+ #[serde(default)]+ pub(super) elapsed_ms: u64,+ }++ /// A terminal file as older builds wrote it: the record, or the bare outcome.+ #[derive(serde::Deserialize)]+ #[serde(untagged)]+ enum CompatibleTerminalRecord {+ Current(TerminalRecord),+ Legacy(SubagentOutcome),+ }++ impl From<CompatibleTerminalRecord> for TerminalRecord {+ fn from(record: CompatibleTerminalRecord) -> Self {+ match record {+ CompatibleTerminalRecord::Current(record) => record,+ CompatibleTerminalRecord::Legacy(outcome) => Self {++ key: None,+ outcome,+ agent_id: String::new(),+ elapsed_ms: 0,+ },+ }+ }+ }++ /// Everything durable about one scoped task key.+ #[derive(Clone, Default, serde::Serialize, serde::Deserialize)]+ pub(super) struct LifecycleRecord {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub(super) pause: Option<SubagentCheckpointData>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub(super) terminal: Option<TerminalRecord>,+ }++ #[derive(Clone, Default, serde::Serialize, serde::Deserialize)]+ struct TaskIndex {+ #[serde(default)]+ keys: Vec<SubagentTaskKey>,+ }++ fn failure(error: impl std::fmt::Display) -> SubagentError {+ SubagentError::Persistence(format!("{error:#}"))+ }++ fn hex(value: &str) -> String {+ value+ .as_bytes()+ .iter()+ .map(|byte| format!("{byte:02x}"))+ .collect()+ }++ /// A task key normally contains short UUID-like identifiers, for which the+ /// reversible encoding preserves the old file names. A background child may+ /// inherit a rendered parent identifier, however; that exceptional form is+ /// hashed while keeping every key field in the digest input so distinct+ /// lifecycle scopes cannot alias.+ fn bounded(encoded: String) -> String {+ if encoded.len() <= 180 {+ encoded+ } else {+ format!("sha256-{:x}", Sha256::digest(encoded.as_bytes()))+ }+ }++ pub(super) fn key_component(key: &SubagentTaskKey) -> String {+ bounded(format!(+ "{}-{}-{}-{}",+ hex(&key.root_run_id),+ hex(&key.parent_run_id),+ hex(key.thread_id.as_deref().unwrap_or("")),+ hex(&key.task_id),+ ))+ }++ pub(super) fn task_component(task_id: &str) -> String {+ bounded(hex(task_id))+ }++ /// The workspace a checkpoint directory belongs to: the one above+ /// `.openhuman/subagent_checkpoints`, else the directory itself.+ fn workspace_of(checkpoint_dir: &Path) -> PathBuf {+ let tail = checkpoint_dir.file_name().and_then(|name| name.to_str());+ let parent = checkpoint_dir.parent();+ if tail == Some("subagent_checkpoints")+ && parent+ .and_then(Path::file_name)+ .and_then(|name| name.to_str())+ == Some(".openhuman")+ {+ if let Some(workspace) = parent.and_then(Path::parent) {+ return workspace.to_path_buf();+ }+ }+ checkpoint_dir.to_path_buf()+ }++ /// The lifecycle store of one checkpoint directory's workspace.+ pub(super) struct LifecycleStore {+ kv: StateKv,++ documents: std::sync::Arc<dyn tinystoragedrivers::DocumentStore>,+ }++ impl LifecycleStore {+ /// Opens the store for `checkpoint_dir`, importing its legacy lifecycle+ /// files once.+ pub(super) fn open(checkpoint_dir: &Path) -> Result<Self, SubagentError> {++ Self::with_file_import(checkpoint_dir, true)++ }++++ /// A new terminal commit must win over an unadopted legacy file, while a++ /// pause already in the previous document namespace remains authoritative.++ pub(super) fn before_terminal(checkpoint_dir: &Path) -> Result<Self, SubagentError> {++ Self::with_file_import(checkpoint_dir, false)++ }++++ fn with_file_import(checkpoint_dir: &Path, import_files: bool) -> Result<Self, SubagentError> {+ let kv = StateKv::open(&workspace_of(checkpoint_dir), OWNER, NS).map_err(failure)?;- let legacy = checkpoint_dir.join("lifecycle");- kv.import_once(IMPORT, || import_legacy(&kv, &legacy))++ if import_files {++ let legacy = checkpoint_dir.join("lifecycle");++ kv.import_once(IMPORT, || import_legacy(&kv, &legacy))++ .map_err(failure)?;++ }++ let opened = crate::storage::local::open("subagents", &workspace_of(checkpoint_dir))+ .map_err(failure)?;- Ok(Self { kv })++ let scoped = opened.scoped().map_err(failure)?;++ Ok(Self {++ kv,++ documents: std::sync::Arc::clone(scoped.documents()),++ })++ }++++ /// Converts the retired host checkpoint schema into the owner's neutral++ /// record namespace. Existing owner records win; source records and files++ /// remain unchanged, and terminal records cannot reopen as pauses.++ pub(super) fn neutral_store(++ &self,++ ) -> Result<tinyagents_orchestration::subagent::DocumentSubagentPersistence, SubagentError>++ {++ use super::persistence::OpenHumanPersistence;++ use tinyagents_orchestration::subagent::{++ DocumentSubagentPersistence, PersistedSubagentPause,++ };++ let store = DocumentSubagentPersistence::new(std::sync::Arc::clone(&self.documents))++ .map_err(failure)?;++ for (name, record) in self++ .kv++ .list::<LifecycleRecord>("record/")++ .map_err(failure)?++ {++ let component = name.strip_prefix("record/").expect("listed record prefix");++ let pause = record.pause.and_then(|checkpoint| {++ let key = checkpoint.task_key.clone()?;++ Some(PersistedSubagentPause {++ key,++ outcome: OpenHumanPersistence::checkpoint_outcome(checkpoint),++ replaces: None,++ })++ });++ let terminal_key = record++ .terminal++ .as_ref()++ .and_then(|record| record.key.clone());++ let terminal = record.terminal.map(|record| {++ let mut outcome = record.outcome;++ if !record.agent_id.is_empty() {++ outcome++ .extensions++ .entry("agent_id".into())++ .or_insert(serde_json::json!(record.agent_id));++ }++ outcome++ .extensions++ .entry("elapsed_ms".into())++ .or_insert(serde_json::json!(record.elapsed_ms));++ outcome++ });++ // Host files used a reversible component; owner files used a SHA++ // of the serialized key. Pauses carry the key and can normalize.++ if let Some(pause) = pause {++ store.import_record(&pause.key.clone(), Some(pause), terminal)?;++ } else if let Some(key) = terminal_key {++ store.import_record(&key, None, terminal)?;++ } else {++ store.import_record_at(component, None, terminal)?;++ }++ }++ Ok(store)+ }++ fn record_name(key: &SubagentTaskKey) -> String {+ format!("record/{}", key_component(key))+ }++ fn index_name(task_id: &str) -> String {+ format!("index/{}", task_component(task_id))+ }++ /// The record of `key` (empty when nothing was written).+ pub(super) fn record(&self, key: &SubagentTaskKey) -> Result<LifecycleRecord, SubagentError> {+ Ok(self+ .kv+ .get(&Self::record_name(key))+ .map_err(failure)?+ .unwrap_or_default())+ }++ /// Changes the record of `key` under compare-and-swap; `change` may run+ /// more than once, and returns its result and whether it changed the record.+ pub(super) fn update<R: Send + 'static>(+ &self,+ key: &SubagentTaskKey,+ change: impl Fn(&mut LifecycleRecord) -> (R, bool) + Send + Sync + 'static,+ ) -> Result<R, SubagentError> {+ self.kv+ .update(&Self::record_name(key), change)+ .map_err(failure)+ }++ /// The scoped keys that share `task_id`.+ pub(super) fn index_keys(&self, task_id: &str) -> Result<Vec<SubagentTaskKey>, SubagentError> {+ Ok(self+ .kv+ .get::<TaskIndex>(&Self::index_name(task_id))+ .map_err(failure)?+ .unwrap_or_default()+ .keys)+ }++ pub(super) fn add_index_key(&self, key: &SubagentTaskKey) -> Result<(), SubagentError> {+ let key = key.clone();+ self.kv+ .update::<TaskIndex, ()>(&Self::index_name(&key.task_id), {+ let key = key.clone();+ move |index| {+ if index.keys.contains(&key) {+ return ((), false);+ }+ index.keys.push(key.clone());+ ((), true)+ }+ })+ .map_err(failure)+ }++ pub(super) fn remove_index_key(&self, key: &SubagentTaskKey) -> Result<(), SubagentError> {+ let key = key.clone();+ self.kv+ .update::<TaskIndex, ()>(&Self::index_name(&key.task_id), {+ let key = key.clone();+ move |index| {+ let before = index.keys.len();+ index.keys.retain(|candidate| candidate != &key);+ ((), index.keys.len() != before)+ }+ })+ .map_err(failure)+ }+ }++ /// Copies the legacy lifecycle files of `dir`, never replacing a record that+ /// already holds the part a file carries.+ fn import_legacy(kv: &StateKv, dir: &Path) -> anyhow::Result<()> {+ let entries = match std::fs::read_dir(dir) {+ Ok(entries) => entries,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(error) => return Err(error.into()),+ };+ let mut imported = 0usize;+ for entry in entries {+ let path = entry?.path();+ let Some(file) = path.file_name().and_then(|name| name.to_str()) else {+ continue;+ };+ let bytes = match std::fs::read(&path) {+ Ok(bytes) => bytes,+ Err(error) => {+ log::warn!("[subagent:lifecycle] legacy {file} unreadable ({error}); skipped");+ continue;+ }+ };+ if let Some(component) = file.strip_suffix(".pause.json") {- match serde_json::from_slice::<SubagentCheckpointData>(&bytes) {++ let checkpoint =++ serde_json::from_slice::<SubagentCheckpointData>(&bytes).or_else(|original| {++ let persisted = serde_json::from_slice::<++ tinyagents_orchestration::subagent::PersistedSubagentPause,++ >(&bytes)++ .map_err(|_| original)?;++ super::persistence::OpenHumanPersistence::checkpoint_from_persisted_pause(++ persisted,++ )++ .map_err(serde::de::Error::custom)++ });++ match checkpoint {+ Ok(pause) => {+ kv.update::<LifecycleRecord, ()>(&format!("record/{component}"), move |r| {+ if r.pause.is_none() {+ r.pause = Some(pause.clone());+ ((), true)+ } else {+ ((), false)+ }+ })?;+ imported += 1;+ }+ Err(error) => log::warn!(+ "[subagent:lifecycle] legacy pause {component} unparsable ({error}); skipped"+ ),+ }+ } else if let Some(component) = file.strip_suffix(".terminal.json") {+ match serde_json::from_slice::<CompatibleTerminalRecord>(&bytes) {+ Ok(terminal) => {+ let terminal = TerminalRecord::from(terminal);+ kv.update::<LifecycleRecord, ()>(&format!("record/{component}"), move |r| {+ if r.terminal.is_none() {+ r.terminal = Some(terminal.clone());+ ((), true)+ } else {+ ((), false)+ }+ })?;+ imported += 1;+ }+ Err(error) => log::warn!(+ "[subagent:lifecycle] legacy terminal {component} unparsable ({error}); skipped"+ ),+ }+ } else if let Some(component) = file+ .strip_prefix("task-")+ .and_then(|rest| rest.strip_suffix(".index.json"))+ {+ let value: serde_json::Value = match serde_json::from_slice(&bytes) {+ Ok(value) => value,+ Err(error) => {+ log::warn!(+ "[subagent:lifecycle] legacy index {component} unparsable ({error})"+ );+ continue;+ }+ };+ // The short-lived single-key format of the first lifecycle+ // extraction is read as a one-key list.+ let keys: Vec<SubagentTaskKey> = value+ .get("keys")+ .cloned()+ .and_then(|keys| serde_json::from_value(keys).ok())+ .or_else(|| {+ value+ .get("key")+ .cloned()+ .and_then(|key| serde_json::from_value(key).ok())+ .map(|key| vec![key])+ })+ .unwrap_or_default();+ kv.update::<TaskIndex, ()>(&format!("index/{component}"), move |index| {+ let mut changed = false;+ for key in &keys {+ if !index.keys.contains(key) {+ index.keys.push(key.clone());+ changed = true;+ }+ }+ ((), changed)+ })?;+ imported += 1;+ }+ }+ log::debug!("[subagent:lifecycle] imported {imported} legacy lifecycle files");+ Ok(())+ }++ #[cfg(test)]+ #[path = "lifecycle_store_tests.rs"]+ mod tests;++++#[cfg(test)]++#[path = "lifecycle_storage_adoption_tests.rs"]++mod adoption_tests;diff --cc crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rsindex 4ac9b6c371,9f7a1e263d..91c080f9ce--- a/crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rs@@@ -63,8 -63,8 +63,8 @@@ fn a_subagent_writes_to_its_turn_trees_.expect("a workspace store names its destination");assert!(fallback.ends_with(&format!(- "/{}/transcripts",+ "/local/agent:{}/transcripts",- crate::agent::session_store::DEFAULT_AGENT+ crate::storage::sessions::DEFAULT_AGENT)),"{fallback}");diff --cc crates/openhuman-core/src/agent/tinyagents/host/operation_context.rsindex 4a10b5f433,24dee6ae61..c0d60d3232--- a/crates/openhuman-core/src/agent/tinyagents/host/operation_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/operation_context.rs@@@ -1,10 -1,10 +1,10 @@@//! The immutable authority view the run exposes to shared tools through the//! harness's typed state-view seam, and the readers tools use on it.-use crate::agent::turn_origin::AgentTurnOrigin;+use crate::security::turn_origin::AgentTurnOrigin;use tinyagents_definition::SandboxMode;- use std::time::Duration;+ use std::{sync::Arc, time::Duration};/// OpenHuman product values that tools read from the run through/// `ToolExecutionContext::host::<OpenHumanRunExt>()`, installed bydiff --cc crates/openhuman-core/src/agent/tinyagents/journal.rsindex 1ccbc12678,a8de3de41d..4f29022f1c--- a/crates/openhuman-core/src/agent/tinyagents/journal.rs+++ b/crates/openhuman-core/src/agent/tinyagents/journal.rs@@@ -124,20 -124,31 +124,36 @@@ pub(crate) struct TurnJournalrun_id: RunId,status_store: Arc<DriverStatusStore>,event_sink: Arc<JournalSink>,+ /// The journal the sink appends to, kept to seal the run's stream once the+ /// append worker has drained.+ journal: Arc<dyn HarnessEventJournal>,/// The in-flight status snapshot, mutated in place to `completed`/`failed`.- status: Mutex<HarnessRunStatus>,+ status: Arc<Mutex<HarnessRunStatus>>,}impl TurnJournal {- /// Flush events appended after the terminal status write without changing- /// that status. Child host persistence may finish after a typed RunFailed.++ /// Flush child host effects appended after a terminal status.+ pub(crate) fn flush_events(&self) {+ self.event_sink.flush();+ }++ /// Flush the append worker, then seal the run's journal stream: nothing is+ /// appended to a finished run, and a sealed journal reads back identically+ /// while the storage maintenance sweep applies its retention. Non-fatal.+ async fn flush_and_seal(&self) {+ self.event_sink.flush();+ match self.journal.seal_run(self.run_id.as_str()).await {+ Ok(()) => log::debug!("[journal] sealed run_id={}", self.run_id.as_str()),+ Err(err) => log::debug!(+ "[journal] seal failed run_id={} err={err}",+ self.run_id.as_str()+ ),+ }+ }+/// Best-effort terminal write: mark the run completed and persist. Non-fatal.pub(crate) async fn finish_completed(&self) {- self.event_sink.flush();+ self.flush_and_seal().await;let snapshot = {let mut guard = self.status.lock().unwrap();guard.mark_completed();@@@ -231,10 -223,7 +247,10 @@@ pub(crate) async fn attach_turn_journal// `events` was seeded with `with_stream_id(run_id)`, every persisted// observation's `event_id` is the stable `{run_id}-evt-{offset}`.let journal: Arc<dyn HarnessEventJournal> = Arc::new(StoreEventJournal::new(journal_store));- let journal_sink = Arc::new(JournalSink::new(Arc::clone(&journal), run_id.clone()));+ let journal_sink = Arc::new(- JournalSink::new(journal, run_id.clone())++ JournalSink::new(Arc::clone(&journal), run_id.clone())+ .with_lineage(parent_run_id.clone(), root_run_id.clone()),+ );let redacting = RedactingSink::new(journal_sink.clone(), process_env_secrets());// FanOutSink is the durable-observer composition seam (05.2 adds graph sinks@@@ -269,7 -256,8 +285,8 @@@run_id,status_store,event_sink: journal_sink,+ journal,- status: Mutex::new(status),+ status: Arc::new(Mutex::new(status)),})}diff --cc crates/openhuman-core/src/artifacts/publisher_slot.rsindex 0000000000,b1b10405d0..b1b10405d0mode 000000,100644..100644--- a/crates/openhuman-core/src/artifacts/publisher_slot.rs+++ b/crates/openhuman-core/src/artifacts/publisher_slot.rsdiff --cc crates/openhuman-core/src/artifacts/publisher_slot_tests.rsindex 0000000000,6817ed5968..6817ed5968mode 000000,100644..100644--- a/crates/openhuman-core/src/artifacts/publisher_slot_tests.rs+++ b/crates/openhuman-core/src/artifacts/publisher_slot_tests.rsdiff --cc crates/openhuman-core/src/artifacts/storage_schema.rsindex 0000000000,d4d189bb43..d4d189bb43mode 000000,100644..100644--- a/crates/openhuman-core/src/artifacts/storage_schema.rs+++ b/crates/openhuman-core/src/artifacts/storage_schema.rsdiff --cc crates/openhuman-core/src/artifacts/storage_schema_tests.rsindex 0000000000,50d9313722..50d9313722mode 000000,100644..100644--- a/crates/openhuman-core/src/artifacts/storage_schema_tests.rs+++ b/crates/openhuman-core/src/artifacts/storage_schema_tests.rsdiff --cc crates/openhuman-core/src/core/observability.rsindex d18c538a63,999b5d0e78..66bf9e7edb--- a/crates/openhuman-core/src/core/observability.rs+++ b/crates/openhuman-core/src/core/observability.rs@@@ -13,13 -13,6 +13,13 @@@//! canonical example — `run_single` used to publish a `DomainEvent::AgentError`//! and return `Err(_)`, but Sentry never saw it. Funnel error sites through//! `report_error` so they show up tagged and grep-friendly in Sentry.-+pub(crate) mod progress_tracing;++pub(crate) mod telemetry;++#[path = "observability_channel_message.rs"]+mod channel_message;+#[cfg(feature = "crash-reporting")]+pub use channel_message::is_channel_message_not_found_event;use std::fmt::Display;diff --cc crates/openhuman-core/src/core/observability/progress_tracing/export.rsindex 4247276161,08de1d9924..bcde661e9c--- a/crates/openhuman-core/src/core/observability/progress_tracing/export.rs+++ b/crates/openhuman-core/src/core/observability/progress_tracing/export.rs@@@ -4,66 -4,11 +4,65 @@@use crate::config::schema::AgentTracingConfig;use crate::config::Config;-use super::langfuse;-use super::otlp;use crate::config::schema::AgentTracingBackend;+use std::time::Duration;+use tinyagents_harness::observability::trace_export::otlp::otlp_requests;use tinyagents_harness::observability::trace_export::serialize::{spans_to_ndjson, SpanEnvelope};-use tinyagents_harness::observability::trace_export::{RunType, TraceContext, TraceSpan};+use tinyagents_harness::observability::trace_export::{TraceContext, TraceSpan};+use tinyagents_harness::observability::AgentObservation;+use tinyagents_harness::observability::LangfuseClient;++const PUSH_TIMEOUT: Duration = Duration::from_secs(10);++fn reject_partial_success(response: &serde_json::Value) -> Result<(), String> {+ if response["partialSuccess"]["errorMessage"]+ .as_str()+ .is_some_and(|message| !message.is_empty())+ {+ Err("Langfuse OTLP proxy reported partial success".to_string())+ } else {+ Ok(())+ }+}++async fn push_spans(config: &Config, spans: &[TraceSpan]) -> Result<(), String> {+ if spans.is_empty() {+ return Ok(());+ }- let url = crate::backend::telemetry::langfuse::ingestion_url(config);- let environment = crate::backend::telemetry::langfuse::environment_for_base(&url);- if crate::backend::telemetry::langfuse::skip_push(environment) {++ let url = crate::core::observability::telemetry::langfuse::otlp_url(config);++ let environment =++ crate::core::observability::telemetry::langfuse::environment_for_base(config, &url);++ if crate::core::observability::telemetry::langfuse::skip_push(environment) {+ return Ok(());+ }+ if !url.starts_with("http") {+ return Err("Langfuse backend proxy URL is unavailable".to_string());+ }+ let token = match crate::security::credentials::session_support::direct_backend_credential(+ config,+ "langfuse otlp push",+ ) {+ Some(crate::security::credentials::session_support::BackendCredential::Session(token)) => {+ token+ }+ _ => return Ok(()),+ };- let transport = crate::backend::resolve_backend_transport()- .map_err(|err| format!("Langfuse OTLP push has no backend transport: {err}"))?;+ let client = LangfuseClient::proxy_with_transport(+ url,+ token,- transport.http_client(crate::backend::TransportProfile::Api),- transport.attribution_headers(),++ crate::config::build_runtime_proxy_client_with_timeouts("telemetry.otlp", 10, 10),++ config.resolved_endpoints.attribution_header_map(),+ )+ .map_err(|_| "Langfuse OTLP proxy client could not be configured".to_string())?;+ for payload in otlp_requests(spans, environment, &super::export_brand()) {+ let response = tokio::time::timeout(PUSH_TIMEOUT, client.send_otlp(payload))+ .await+ .map_err(|_| "Langfuse OTLP proxy request timed out".to_string())?+ .map_err(|_| "Langfuse OTLP proxy request failed".to_string())?;+ reject_partial_success(&response)?;+ }+ Ok(())+}/// Map the configured backend onto the upstream NDJSON envelope.pub(crate) fn envelope_for(backend: AgentTracingBackend) -> SpanEnvelope {@@@ -224,7 -143,10 +223,7 @@@ pub(crate) async fn export_subagent_jouif !config.observability.share_usage_data {return;}- if !crate::backend::telemetry::langfuse::journal_push_ready(config) {- // Check the push gates before reading the child's journal: without a live- // session the push refuses anyway, and the read and observation build were- // pure cost — on every delegated turn, since usage sharing defaults on.- if !langfuse::journal_push_ready(config) {++ if !crate::core::observability::telemetry::langfuse::journal_push_ready(config) {log::debug!("[agent-tracing] child trace export skipped: push not possible run_id={journal_run_id}");diff --cc crates/openhuman-core/src/core/observability/progress_tracing/export_tests.rsindex 4825cb8dde,0000000000..2e01dc6010mode 100644,000000..100644--- a/crates/openhuman-core/src/core/observability/progress_tracing/export_tests.rs+++ b/crates/openhuman-core/src/core/observability/progress_tracing/export_tests.rs@@@ -1,144 -1,0 +1,142 @@@+use super::*;+use std::collections::BTreeMap;+use tinyagents_harness::observability::trace_export::{SpanKind, SpanStatus};++#[test]+fn partial_success_error_message_is_rejected_even_when_rejected_count_is_zero() {+ let response = serde_json::json!({+ "partialSuccess": { "rejectedSpans": "0", "errorMessage": "receiver warning" }+ });+ assert!(reject_partial_success(&response).is_err());+}++#[test]+fn partial_success_positive_rejected_count_is_rejected() {+ let response = serde_json::json!({+ "partialSuccess": { "rejectedSpans": "2", "errorMessage": "some spans rejected" }+ });+ assert!(reject_partial_success(&response).is_err());+}++#[test]+fn empty_partial_success_response_is_accepted() {+ assert!(reject_partial_success(&serde_json::json!({ "partialSuccess": {} })).is_ok());+ assert!(reject_partial_success(&serde_json::json!({})).is_ok());+}++fn file_fixture_span() -> TraceSpan {+ TraceSpan {+ trace_id: "writer-trace".into(),+ span_id: "writer-root".into(),+ parent_span_id: None,+ name: "agent.turn".into(),+ kind: SpanKind::Turn,+ start_unix_ms: 1_000,+ end_unix_ms: Some(1_100),+ status: SpanStatus::Ok,+ attributes: BTreeMap::new(),+ input: None,+ output: None,+ }+}++#[test]+fn local_export_appends_valid_selected_ndjson_envelopes() {+ let scratch = tempfile::tempdir().expect("isolated trace output");+ let path = scratch.path().join("trace.ndjson");+ let mut config = AgentTracingConfig {+ enabled: true,+ export_path: Some(path.to_string_lossy().into_owned()),+ ..Default::default()+ };++ export_spans(&config, &[file_fixture_span()]);+ config.backend = AgentTracingBackend::Langfuse;+ export_spans(&config, &[file_fixture_span()]);++ let lines: Vec<_> = std::fs::read_to_string(&path)+ .expect("trace file was created")+ .lines()+ .map(|line| serde_json::from_str::<serde_json::Value>(line).expect("valid NDJSON"))+ .collect();+ assert_eq!(lines.len(), 2, "each call appends exactly one span line");+ assert_eq!(+ lines[0]["trace_id"], "writer-trace",+ "OTel envelope selected"+ );+ assert_eq!(+ lines[1]["body"]["trace_id"], "writer-trace",+ "Langfuse envelope selected"+ );+}++#[test]+fn disabled_local_export_and_log_only_export_are_safe() {+ let scratch = tempfile::tempdir().expect("isolated trace output");+ let path = scratch.path().join("disabled.ndjson");+ let config = AgentTracingConfig {+ enabled: false,+ export_path: Some(path.to_string_lossy().into_owned()),+ ..Default::default()+ };+ export_spans(&config, &[file_fixture_span()]);+ assert!(+ !path.exists(),+ "disabled local tracing has no filesystem effect"+ );++ let config = AgentTracingConfig {+ enabled: true,+ export_path: None,+ ..Default::default()+ };+ export_spans(&config, &[file_fixture_span()]);+}++#[tokio::test]+async fn external_backend_is_skipped_before_session_lookup() {+ let mut config = Config::default();+ config.api_url = Some("https://external.example.invalid/openai/v1".into());+ let spans = [TraceSpan {+ trace_id: "thread-one:turn-one".into(),+ span_id: "root".into(),+ parent_span_id: None,+ name: "agent.turn".into(),+ kind: SpanKind::Turn,+ start_unix_ms: 1_000,+ end_unix_ms: Some(2_000),+ status: SpanStatus::Ok,+ attributes: BTreeMap::new(),+ input: None,+ output: None,+ }];+ assert!(push_spans(&config, &spans).await.is_ok());+}++#[tokio::test]+async fn child_export_obeys_sharing_and_readiness_gates_before_reading() {+ let dispatch = crate::core::runtime::DispatchCtx::ambient();+ let mut config = Config::default();+ crate::core::observability::progress_tracing::export_subagent_journal_trace(+ &dispatch,+ &config,+ "missing-child-run",+ None,+ "worker",+ "task-1",+ )+ .await;++ config.observability.share_usage_data = true;+ config.api_url = Some("https://external.invalid/api".into());- assert!(!crate::backend::telemetry::langfuse::journal_push_ready(- &config- ));++ assert!(!crate::core::observability::telemetry::langfuse::journal_push_ready(&config));+ crate::core::observability::progress_tracing::export_subagent_journal_trace(+ &dispatch,+ &config,+ "missing-child-run",+ None,+ "worker",+ "task-1",+ )+ .await;+}diff --cc crates/openhuman-core/src/core/observability/telemetry/langfuse/environment.rsindex 0000000000,5b9c77ce60..040cb1ed8bmode 000000,100644..100644--- a/crates/openhuman-core/src/core/observability/telemetry/langfuse/environment.rs+++ b/crates/openhuman-core/src/core/observability/telemetry/langfuse/environment.rs@@@ -1,0 -1,114 +1,138 @@@+ //! Backend-host resolution and the deployment-environment push gate for the+ //! Langfuse exporter: where the OTLP proxy lives, which environment the+ //! resolved host belongs to, and whether that environment may push at all.++ use crate::config::Config;++use crate::security::credentials::session_support::direct_backend_credential;+-use super::LOG_TARGET;++const LOG_TARGET: &str = "agent-tracing::langfuse";++ /// The OTLP/HTTP traces URL the host resolved+ /// (`config.resolved_endpoints.tracing_otlp_url`). Empty when no host resolved+ /// one; callers treat a non-`http` URL as "proxy unavailable".+ pub(crate) fn otlp_url(config: &Config) -> String {+ config+ .resolved_endpoints+ .tracing_otlp_url+ .clone()+ .unwrap_or_default()+ }++ /// Derive the Langfuse `environment` for a tracing base URL. Chosen signal:+ /// the resolved backend host is the single existing config-driven fact that+ /// distinguishes deployments (there is no NODE_ENV-style flag in the core+ /// config) — loopback/local → development; a non-local HTTPS host takes the+ /// bucket the installed host resolved for its control plane+ /// (`config.resolved_endpoints.deployment_environment`: production, staging);+ /// anything else → external. With no host registered nothing is resolved, so+ /// every non-local host is external and does not push.+ ///+ /// # Why the host is parsed rather than substring-matched+ ///+ /// The answer decides whether a push happens at all ([`skip_push`]), so a+ /// sloppy match is load-bearing in both directions. A substring test on+ /// `staging` let `https://staging-attacker.invalid` through, and missed an+ /// IPv6 loopback backend (`http://[::1]:7788`). Local classification is+ /// delegated to [`crate::util::url::host_is_local`], which parses the URL and+ /// handles IPv4 loopback/unspecified/private, IPv6 loopback/unspecified and+ /// `localhost` / `*.localhost`; one local-host predicate keeps the gates in+ /// agreement. The hosted bucket is classified by the host that owns the+ /// domain, anchored to its own deployment domain so the classifier fails+ /// *closed*.+ ///+ /// An unparseable URL is external — the fail-closed default. `otlp_url`+ /// can return a non-URL placeholder when no backend host resolves, and the+ /// caller checks `starts_with("http")` separately; classifying that as+ /// anything pushable would defeat the gate.+ pub(crate) fn environment_for_base(config: &Config, base: &str) -> &'static str {+ let Ok(parsed) = url::Url::parse(base) else {+ return "external";+ };+ if crate::util::url::host_is_local(&parsed) {+ return "development";+ }+ if parsed.scheme() != "https" {+ return "external";+ }+ // Only the known buckets are honoured, so a host cannot invent a+ // pushable one; the allowlist in [`push_allowed`] still has the final say.+ match config.resolved_endpoints.deployment_environment.as_deref() {+ Some("production") => "production",+ Some("staging") => "staging",+ Some("development") => "development",+ _ => "external",+ }+ }++ /// The environments this client may push to Langfuse from.+ ///+ /// An allowlist keeps the fail-closed property structural — if+ /// [`environment_for_base`] ever grows a fourth bucket, that bucket does not+ /// push until someone adds it here on purpose.+ ///+ /// `test` appears in the backend's list but not here because there is no such+ /// bucket on this side: [`environment_for_base`] maps loopback hosts to+ /// `development`, and that is what the Rust suite resolves to.+ pub(super) const LANGFUSE_PUSH_ENVIRONMENTS: &[&str] = &["production", "staging", "development"];++ /// Whether a push is permitted for a resolved environment.+ pub(super) fn push_allowed(environment: &str) -> bool {+ LANGFUSE_PUSH_ENVIRONMENTS.contains(&environment)+ }++ /// Emitted at most once per process by [`skip_push`].+ static SKIP_LOGGED: std::sync::Once = std::sync::Once::new();++ /// Whether this push should be dropped before any work, logging the reason+ /// once per process.+ ///+ /// # Why skip at all, when the backend already refuses+ ///+ /// Defence in depth: an unknown backend origin must not receive a session+ /// bearer merely because usage sharing is enabled.+ ///+ /// # Why once per process, and at info+ ///+ /// This is on the path of every completed run. A warning per turn would move+ /// the noise rather than remove it, and a skip for an external host is the configured+ /// outcome, not a fault — so it is `info`, said once, and then silence. The+ /// caller receives `Ok(())`: skipping is a successful no-op, and returning+ /// `Err` would make the caller log the same line on every turn, which is the+ /// thing being avoided.+ pub(crate) 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+ }++++/// Whether a journal push would actually send for `config`: the URL gate, the++/// environment gate and a live session credential. Callers must read a journal++/// and build observations first, so without a live session (unit tests, a++/// signed-out or embedder host) or on a skipped environment that work is++/// discarded anyway, and reading a whole child journal is not free.++pub(crate) fn journal_push_ready(config: &Config) -> bool {++ let url = otlp_url(config);++ !skip_push(environment_for_base(config, &url))++ && url.starts_with("http")++ && matches!(++ direct_backend_credential(config, "langfuse journal push"),++ Some(crate::security::credentials::session_support::BackendCredential::Session(_))++ )++}++++#[cfg(test)]++#[path = "environment_policy_tests.rs"]++mod tests;++++#[cfg(test)]++#[path = "environment_parse_tests.rs"]++mod parse_tests;diff --cc crates/openhuman-core/src/core/observability/telemetry/langfuse/environment_policy_tests.rsindex 0000000000,3dc6b75c66..3dc6b75c66mode 000000,100644..100644--- a/crates/openhuman-core/src/core/observability/telemetry/langfuse/environment_policy_tests.rs+++ b/crates/openhuman-core/src/core/observability/telemetry/langfuse/environment_policy_tests.rsdiff --cc crates/openhuman-core/src/core/observability/telemetry/mod.rsindex 658395fc48,0000000000..658395fc48mode 100644,000000..100644--- a/crates/openhuman-core/src/core/observability/telemetry/mod.rs+++ b/crates/openhuman-core/src/core/observability/telemetry/mod.rsdiff --cc crates/openhuman-core/src/core/runtime/context.rsindex b60bd6fea4,8dca29e71e..48b6e8d05d--- a/crates/openhuman-core/src/core/runtime/context.rs+++ b/crates/openhuman-core/src/core/runtime/context.rs@@@ -98,16 -98,13 +98,13 @@@ pub struct CoreContext/// [`CoreContext::derive_with`] can turn it off so an embedded agent sees/// only the skills its host installed for it, never the operator's.user_skill_roots: bool,- /// The backend transport this context's handlers reach the hosted- /// TinyHumans backend through, when the host supplied one via- /// [`CoreBuilder::backend_transport`](crate::core::runtime::CoreBuilder::backend_transport).- /// `None` means "fall back to the process-global transport" — see- /// [`crate::backend::transport::resolve_backend_transport`] for the order.- /// Inherited unchanged by every context derived through- /// [`CoreContext::derive_with`].- backend_transport: Option<Arc<dyn crate::backend::transport::BackendTransport>>,+ /// Hook registrations bound to this context (see [`crate::core::slots`]).+ /// Empty unless the host supplied some through+ /// [`CoreBuilder::extensions`](crate::core::runtime::CoreBuilder::extensions);+ /// inherited by every context derived through [`CoreContext::derive_with`].+ extensions: crate::core::slots::Extensions,/// Explicit authority on this derived turn context.- turn_origin: Option<crate::agent::turn_origin::AgentTurnOrigin>,+ turn_origin: Option<crate::security::turn_origin::AgentTurnOrigin>,/// Durable relay conversation carried by the immutable turn context.channel_thread: Option<String>,/// The agent whose stores a host-installed session storediff --cc crates/openhuman-core/src/cron/origin.rsindex df03404d4e,ef8710375b..22b3759623--- a/crates/openhuman-core/src/cron/origin.rs+++ b/crates/openhuman-core/src/cron/origin.rs@@@ -7,11 -7,11 +7,11 @@@//! from an external channel keeps running as that channel's turn, so its own//! external-effect tools stay gated exactly like its creator's were.-use crate::agent::turn_origin::{self, AgentTurnOrigin};+use crate::security::turn_origin::{self, AgentTurnOrigin};use serde_json::Value;use {- tinyflows_schedule::types::delivery_mode, tinyflows_schedule::types::CronJob,- tinyflows_schedule::types::JobOrigin,+ tinyflows_bus::schedule::types::delivery_mode, tinyflows_bus::schedule::types::CronJob,+ tinyflows_bus::schedule::types::JobOrigin,};/// Map a live turn origin onto the origin a job created in it records.diff --cc crates/openhuman-core/src/cron/origin_tests.rsindex 66b9efb8e9,0dcd8ecae1..6c5133cef0--- a/crates/openhuman-core/src/cron/origin_tests.rs+++ b/crates/openhuman-core/src/cron/origin_tests.rs@@@ -1,7 -1,7 +1,7 @@@use super::*;-use crate::agent::turn_origin::{with_origin, TrustedAutomationSource};+use crate::security::turn_origin::{with_origin, TrustedAutomationSource};use serde_json::json;- use tinyflows_schedule::types::Schedule;+ use tinyflows_bus::schedule::types::Schedule;fn channel_turn(history_key: Option<&str>) -> AgentTurnOrigin {AgentTurnOrigin::ExternalChannel {diff --cc crates/openhuman-core/src/inference/mod.rsindex 8043b4128f,4cd00fac56..e1abc33ec8--- a/crates/openhuman-core/src/inference/mod.rs+++ b/crates/openhuman-core/src/inference/mod.rs@@@ -32,10 -32,9 +32,11 @@@ pub mod httppub mod model_context;pub mod ops;pub mod provider;+pub(crate) mod reasoning;+ pub mod registry;mod schemas;pub mod tokenjuice;+pub mod turn_models;pub use ops as rpc;pub use schemas::{diff --cc crates/openhuman-core/src/inference/provider/mod.rsindex d54a21531c,4cb08b961f..3771d5ae52--- a/crates/openhuman-core/src/inference/provider/mod.rs+++ b/crates/openhuman-core/src/inference/provider/mod.rs@@@ -9,9 -9,8 +9,9 @@@ pub mod error_classifypub mod error_code;pub mod factory;pub(crate) mod fallback_diagnostics;+pub(crate) mod model;pub(crate) mod openai_codex;- /// Crate-native managed OpenHuman backend as a host `ChatModel` (issue #4727).+ /// Provider-neutral managed-provider pieces that stay in the core.pub mod openhuman_backend_model;pub mod ops;pub mod types;diff --cc crates/openhuman-core/src/integrations/composio/mod.rsindex 980655a711,93f3fe8c42..19d43ab4ec--- a/crates/openhuman-core/src/integrations/composio/mod.rs+++ b/crates/openhuman-core/src/integrations/composio/mod.rs@@@ -60,10 -62,9 +63,10 @@@ pub mod toolspub(crate) mod trigger_history;pub mod types;-pub use crate::agent::prompts::types::ConnectedIntegration;++pub use crate::agent::prompts::ConnectedIntegration;pub use crate::integrations::composio::contract::ProviderUserProfile;- pub use crate::integrations::types::ConnectedIntegration;pub use action_tool::ComposioActionTool;+pub(crate) use auth_probe::user_is_signed_in_to_composio;pub use bus::{register_composio_trigger_subscriber, ComposioConfigChangedSubscriber,ComposioConnectionCreatedSubscriber, ComposioTriggerSubscriber,diff --cc crates/openhuman-core/src/integrations/mod.rsindex f6304718a7,1716b9e985..659bb907bd--- a/crates/openhuman-core/src/integrations/mod.rs+++ b/crates/openhuman-core/src/integrations/mod.rs@@@ -1,29 -1,12 +1,16 @@@- //! Agent integration tools.+ //! Agent integrations that run through the core itself.//!- //! Most integrations proxy through backend endpoints authenticated with the- //! user's session token, so billing, rate limiting, and provider markup stay- //! server-side. Some integrations, such as SearXNG, call user-configured- //! endpoints directly when enabled; those callers must keep configured base URLs- //! trusted because requests leave the local core process.+ //! Composio connectors ([`composio`]) and task sources ([`task_sources`]) live+ //! here. The hosted integrations client, its managed tools (Google+ //! Places, stock data, file storage, media generation) and the web3 crypto+ //! client are not part of the core: a host that has such a service plugs them+ //! in through the generic registries (tool sources, the Composio route+ //! builders, the wallet-backend hook). With none registered the core runs+ //! without them.- pub mod client;++pub(crate) mod announcement_notes;pub mod composio;+mod connected_identities;- pub mod file_storage;- pub mod task_sources;- pub mod tools;- pub mod types;-- pub(crate) mod announcement_notes;+pub(crate) mod recorded_tools;+ pub mod task_sources;+pub use connected_identities::render_connected_identities;-- pub use client::{build_client, pricing_for_config, IntegrationClient};- pub use types::{- BackendResponse, ConnectedIntegration, ConnectedIntegrationTool, GatedIntegrationTool,- IntegrationConnection, IntegrationPricing, IntegrationPricingEntry, PricingIntegrations,- };-- #[cfg(test)]- #[path = "mod_tests.rs"]- mod tests;diff --cc crates/openhuman-core/src/integrations/task_sources/README.mdindex 8dd58210e0,020eb9ebbe..98335722b1--- a/crates/openhuman-core/src/integrations/task_sources/README.md+++ b/crates/openhuman-core/src/integrations/task_sources/README.md@@@ -142,8 -142,8 +142,8 @@@ SQL cascade). With no backend configure- `crate::core::bus` (`BUS`) + `crate::core::events::DomainEvent`: `BUS.publish`/`BUS.subscribe` for event publish/subscribe.- `crate::config` (+ `config::rpc`), `Config`, `load_config_with_timeout`; reads the `[task_sources]` block for defaults and the master switch.- `crate::integrations::composio::contract`: `NormalizedTask`, `TaskContainer`, `TaskFetchFilter`, `TaskKind` (contract types re-exported from `tinymemory_api::composio::tasks`). The old `get_provider` / `ProviderContext` / `ComposioProvider::fetch_tasks` registry no longer exists; `mod.rs`'s intra-doc link to `fetch_tasks` is stale.-- `crate::agent::triage`: `run_triage`, `apply_decision`, `TriageOutcome`, `TriggerEnvelope`; dispatches the proactive agent turn for `AgentTodoProactive` sources.+- `crate::triage`: `run_triage`, `apply_decision`, `TriageOutcome`, `TriggerEnvelope`; dispatches the proactive agent turn for `AgentTodoProactive` sources.- - `crate::cron::scheduler_gate`: `wait_for_capacity` capacity semaphore; gates proactive triage turns behind background-AI throttling.+ - `crate::platform::llm_gate`: `wait_for_capacity` capacity semaphore; gates proactive triage turns behind background-AI throttling.## Used bydiff --cc crates/openhuman-core/src/integrations/task_sources/route.rsindex f2317be865,68f9f880ee..c0fb3fcdd8--- a/crates/openhuman-core/src/integrations/task_sources/route.rs+++ b/crates/openhuman-core/src/integrations/task_sources/route.rs@@@ -16,12 -16,12 +16,12 @@@use serde_json::json;-use crate::agent::triage::{- apply_decision, remote_trigger_origin, run_triage, TriageOutcome, TriggerEnvelope,-};-use crate::agent::turn_origin::with_origin;use crate::config::Config;- use crate::cron::scheduler_gate;+ use crate::platform::llm_gate;+use crate::security::turn_origin::with_origin;+use crate::triage::{+ apply_decision, remote_trigger_origin, run_triage, TriageOutcome, TriggerEnvelope,+};use super::types::{EnrichedTask, SourceTarget, TaskSource};diff --cc crates/openhuman-core/src/lib.rsindex d43f84b1e8,db5be2908d..b1f540d9bc--- a/crates/openhuman-core/src/lib.rs+++ b/crates/openhuman-core/src/lib.rs@@@ -53,11 -53,6 +53,10 @@@#![allow(dead_code)]pub mod agent;+pub mod agent_registry;+pub mod agent_runs;+pub mod artifacts;+pub mod attachments;- pub mod backend;pub mod channels;pub mod commands;pub mod config;diff --cc crates/openhuman-core/src/media/README.mdindex 112e57c927,5465736590..a0e5e7940d--- a/crates/openhuman-core/src/media/README.md+++ b/crates/openhuman-core/src/media/README.md@@@ -101,8 -96,9 +96,9 @@@ Inside `generation/``tinyhumansai/tinyinference`), reached through `tinyagents_harness`.- Argument parsing, writing files into the workspace, and result wordingbelong to TinyAgents (`tinyagents_harness::media`, in `vendor/tinyagents`).- - Provider keys, billing, and the proxy route belong to the backend.+ - Provider keys, billing, the proxy route and the generators that reach it+ belong to the host (`openhuman-tinyhumans`: `integrations/media`).-- Artifact storage belongs to `agent::artifacts`.+- Artifact storage belongs to `artifacts`.## Gotchasdiff --cc crates/openhuman-core/src/media/generation/tools.rsindex 366d63ae4c,7f7ce56fb2..fc5397782a--- a/crates/openhuman-core/src/media/generation/tools.rs+++ b/crates/openhuman-core/src/media/generation/tools.rs@@@ -19,8 -19,8 +19,8 @@@ use tinyagents_harness::tinyinference_vuse tinytools::{PermissionLevel, Tool, ToolCategory, ToolResult};use super::artifact_tool::MediaArtifactTool;- use super::provider::{managed_generators, MediaGenerators};+ use super::provider::MediaGenerators;-use crate::agent::artifacts::ArtifactKind;+use crate::artifacts::ArtifactKind;use crate::config::Config;/// Image tool name (pinned by the `media` pack and agent allowlists).diff --cc crates/openhuman-core/src/modules/mod.rsindex 5d989e2558,d4169d5987..b174d36ac2--- a/crates/openhuman-core/src/modules/mod.rs+++ b/crates/openhuman-core/src/modules/mod.rs@@@ -121,7 -112,9 +112,8 @@@ mod storage_import_tinyjuice_savingsmod storage_import_tinymcp;#[cfg(all(feature = "modules", feature = "web3"))]mod storage_import_tinywallet;-#[cfg(feature = "modules")]pub mod tinybox;+ pub(crate) mod tinyflows;#[cfg(feature = "modules")]mod tokenjuice_host;pub mod types;diff --cc crates/openhuman-core/src/modules/storage_import_tinyjuice_savings.rsindex 0000000000,e3f0d30d75..d62e80de2emode 000000,100644..100644--- a/crates/openhuman-core/src/modules/storage_import_tinyjuice_savings.rs+++ b/crates/openhuman-core/src/modules/storage_import_tinyjuice_savings.rs@@@ -1,0 -1,110 +1,111 @@@+ //! One-time import of tinyjuice's legacy savings snapshot.+ //!+ //! The savings totals used to live in `<workspace>/state/tokenjuice_savings.json`+ //! (a camelCase `SavingsAggregate`). The module now keeps them as one document+ //! in its own `juice.savings` collection, so the host reads the old file and+ //! hands the aggregate to the module (`ImportSavings`), which adopts it only+ //! while it has recorded nothing.+ //!+ //! * **The file is only read.** It is never modified or deleted here; the+ //! layout migration archives it with the rest of `state/` (classified `Move`,+ //! "runtime state files", in `storage/layout/plan.rs`).+ //! * **The path is fixed.** It is `state/tokenjuice_savings.json` under the+ //! workspace, read without following a symlink and capped in size; nothing+ //! in the file can name another path.+ //! * **Runs once per file.** A marker in `tsd.migrations` records it. A+ //! snapshot that does not parse is marked too (the old ledger ignored it as+ //! well), so a corrupt file is not retried forever. A failed hand-over writes+ //! no marker and is retried at the next install.++ use std::future::Future;+ use std::path::{Path, PathBuf};++ use anyhow::{Context, Result};+ use tinyjuice_bus::savings::SavingsAggregate;+ use tinystoragedrivers::ScopedStorage;++ use super::storage_grant_schemas::tinyjuice::MODULE_ID;+ use super::storage_import_support as support;+ use super::storage_import_tinyjuice::read_regular;+ use crate::core::runtime::DispatchCtx;++ const LOG_PREFIX: &str = "[tinyjuice-savings-import]";+ /// Marker collection name, shared with the CCR importer's host-only family.+ const MARKER_KIND: &str = "tinyjuice_host_import";+ /// A real snapshot is a few KiB; anything past this is not one.+ const MAX_BYTES: usize = 4 * 1024 * 1024;++ /// The legacy snapshot's location under `workspace`.+ pub(crate) fn legacy_file(workspace: &Path) -> PathBuf {+ workspace.join("state").join("tokenjuice_savings.json")+ }++ /// How one import attempt ended.+ #[derive(Debug, PartialEq, Eq)]+ pub(crate) enum Outcome {+ /// No storage backend is installed; the module is not using this storage.+ NoBackend,+ /// The marker says this file was already imported.+ AlreadyDone,+ /// There is no snapshot file.+ NoSource,+ /// The file was handled; `adopted` is whether the module took its totals.+ Imported { adopted: bool },+ }++ /// Hands the snapshot at `file` to the module through `adopt`.+ pub(crate) async fn import_legacy<F, Fut>(+ ctx: &DispatchCtx,+ file: &Path,+ adopt: F,+ ) -> Result<Outcome>+ where+ F: FnOnce(SavingsAggregate) -> Fut,+ Fut: Future<Output = Result<bool>>,+ {+ let Some(scoped) = support::module_scope(ctx, MODULE_ID)? else {+ return Ok(Outcome::NoBackend);+ };+ import_into(&scoped, file, adopt).await+ }++ async fn import_into<F, Fut>(scoped: &ScopedStorage, file: &Path, adopt: F) -> Result<Outcome>+ where+ F: FnOnce(SavingsAggregate) -> Fut,+ Fut: Future<Output = Result<bool>>,+ {+ let marker = support::marker_id("savings", file);+ if support::already_imported(scoped, MARKER_KIND, &marker).await? {+ return Ok(Outcome::AlreadyDone);+ }+ if std::fs::symlink_metadata(file).is_err() {+ return Ok(Outcome::NoSource);+ }+ let path = file.to_owned();- let bytes = tokio::task::spawn_blocking(move || read_regular(&path))++ let bytes = crate::core::runtime::DispatchCtx::ambient()++ .spawn_blocking(move || read_regular(&path))+ .await+ .context("the legacy reader panicked")??;+ let Some((_, bytes)) = bytes else {+ return Ok(Outcome::NoSource);+ };+ let parsed = if bytes.len() > MAX_BYTES {+ None+ } else {+ serde_json::from_slice::<SavingsAggregate>(&bytes).ok()+ };+ let adopted = match parsed {+ Some(aggregate) => adopt(aggregate).await?,+ None => {+ log::warn!("{LOG_PREFIX} snapshot unreadable or too large, skipped");+ false+ }+ };+ support::mark_imported(scoped, MARKER_KIND, &marker).await?;+ log::debug!("{LOG_PREFIX} adopted={adopted}");+ Ok(Outcome::Imported { adopted })+ }++ #[cfg(test)]+ #[path = "storage_import_tinyjuice_savings_tests.rs"]+ mod tests;diff --cc crates/openhuman-core/src/platform/llm_gate/README.mdindex 7c05653c98,e4f6de6da8..560889a188--- a/crates/openhuman-core/src/platform/llm_gate/README.md+++ b/crates/openhuman-core/src/platform/llm_gate/README.md@@@ -56,9 -56,9 +56,9 @@@ No dependency on any other `openhuman`## Used by- Consumed in-process across the codebase (discoverable via `grep scheduler_gate`):+ Consumed in-process across the codebase (discoverable via `grep llm_gate`):-- Background workers / pipelines: `autocomplete/core/engine.rs`, `task_sources/route.rs`, [`agent/triage/evaluator.rs`](../../agent/triage/evaluator.rs).+- Background workers / pipelines: `autocomplete/core/engine.rs`, `task_sources/route.rs`, [`triage/evaluator.rs`](../../triage/evaluator.rs).- Inference layer: `inference/provider/openhuman_backend.rs`, [`inference/provider/factory.rs`](../../inference/provider/factory.rs), `inference/local/service/{vision_embed.rs,public_infer.rs}`, `inference/voice/postprocess.rs`.- Credentials lifecycle (signed-out kill switch): `credentials/ops.rs`, `credentials/bus.rs`.- Bootstrap / transport: [`core/runtime/subscribers.rs`](../../core/runtime/subscribers.rs) (calls `init_global` during server bootstrap), [`core/observability.rs`](../../core/observability.rs), plus the domain wiring in `openhuman/mod.rs` and config schema in [`config/schema/scheduler_gate.rs`](../../config/schema/scheduler_gate.rs).diff --cc crates/openhuman-core/src/storage/import/sessions.rsindex 5511184a65,f36af3d31f..f320444154--- a/crates/openhuman-core/src/storage/import/sessions.rs+++ b/crates/openhuman-core/src/storage/import/sessions.rs@@@ -40,9 -40,9 +40,9 @@@ use tinyagents_session::DriverSessionStuse super::tinyflows::{finish, marked};use super::{Outcome, Report, Snapshot};-use crate::agent::session_store::DEFAULT_AGENT;use crate::config::Config;+use crate::storage::sessions::DEFAULT_AGENT;- use crate::storage::StorageBackend;+ use crate::storage::{Scope, StorageBackend};/// The marker name of the session import.pub const SESSIONS_DOMAIN: &str = "sessions";diff --cc crates/openhuman-core/src/storage/mod.rsindex 0e8d2d2148,11814b9263..1461ab6c7a--- a/crates/openhuman-core/src/storage/mod.rs+++ b/crates/openhuman-core/src/storage/mod.rs@@@ -37,8 -41,14 +41,15 @@@ mod lease_documentsmod lease_local;pub mod local;pub mod rebind;+ pub mod schema;+ pub mod schema_support;+ pub mod scope;+ pub mod scope_move;pub mod secrets;+pub mod sessions;+ pub mod state_kv;++ pub use scope::{scope_for_agent, scope_for_module, scope_for_profile, tenant_scope};use std::future::Future;use std::sync::{Arc, LazyLock, Mutex, OnceLock, RwLock};diff --cc crates/openhuman-core/src/storage/schema.rsindex 0000000000,67b04cd307..6bf375303emode 000000,100644..100644--- a/crates/openhuman-core/src/storage/schema.rs+++ b/crates/openhuman-core/src/storage/schema.rs@@@ -1,0 -1,118 +1,118 @@@+ //! The composed storage schema: every owner's `storage_schema()` in one+ //! [`Registry`].+ //!+ //! Each crate that stores records declares what it stores (collections,+ //! streams, blob prefixes, and the v1 -> v2 steps that bring older data+ //! forward). The host composes them once, `prepare`s the backend from the+ //! result, migrates every scope ([`super::boot`]) and generates each module's+ //! storage grant from the module-scoped items+ //! ([`crate::modules::storage_grants`]). Composition refuses a name outside its+ //! owner's prefix, a name claimed twice, a version that goes down and a step+ //! gap, so a collision between two owners fails here, at boot and in+ //! `scripts/ci/check-storage-schema.mjs`, never at a first write.+ //!+ //! Module owners come from their `*-bus` contract crates (optional `storage` feature),+ //! never from the implementation libraries. Owners whose crate is gated off in a build are absent from its registry, as+ //! their data is.++ use std::sync::OnceLock;++ use tinystoragedrivers::schema::{Item, Registry, Schema, ScopeClass};++ /// Every owner's schema that this build links.+ pub fn owner_schemas() -> Vec<Schema> {+ let mut schemas = vec![+ tinyagents_harness::storage_schema(),+ tinyagents_session::storage_schema(),+ tinyagents_session::ledger_storage_schema(),+ tinyagents_session::history_storage_schema(),+ tinyagents_session::conversations_storage_schema(),+ tinyagents_graph::storage_schema(),+ tinyagents_tasks::storage_schema(),+ crate::security::approval::storage_schema(),+ crate::security::devices::storage_schema(),+ crate::desktop::notifications::storage_schema(),+ crate::integrations::task_sources::storage_schema(),- crate::agent::artifacts::storage_schema(),++ crate::artifacts::storage_schema(),+ crate::platform::cost::storage_schema(),+ crate::config::schema::config_storage_schema(),+ crate::profiles::storage_schema(),+ crate::threads::store::storage_schema(),+ crate::agent::orchestration::subagent_sessions::storage_schema(),+ super::agents::storage_schema(),+ ];+ #[cfg(feature = "flows")]+ {+ schemas.push(tinyflows_drivers::storage_schema());+ schemas.push(tinyflows_drivers::cron_storage_schema());+ }+ #[cfg(feature = "skills")]+ schemas.push(tinyskills_drivers::storage_schema());+ #[cfg(feature = "modules")]+ {+ schemas.push(tinymcp_bus::storage::storage_schema());+ schemas.push(tinychannels_bus::storage::storage_schema());+ schemas.push(tinyconnectors_bus::storage::storage_schema());+ schemas.push(tinybox_bus::storage::storage_schema());+ schemas.push(tinyjuice_bus::storage::storage_schema());+ }+ #[cfg(feature = "web3")]+ schemas.push(tinywallet_bus::storage::storage_schema());+ #[cfg(feature = "tinymemes")]+ schemas.push(tinymemes_bus::storage::storage_schema());+ schemas+ }++ /// The registry composed from [`owner_schemas`].+ ///+ /// # Errors+ ///+ /// The composition error naming the owner and item at fault. A build that+ /// links two owners claiming one name never gets this far in CI.+ pub fn registry() -> Result<&'static Registry, super::StorageError> {+ static REGISTRY: OnceLock<Result<Registry, String>> = OnceLock::new();+ REGISTRY+ .get_or_init(|| Registry::compose(owner_schemas()).map_err(|error| error.to_string()))+ .as_ref()+ .map_err(|message| super::StorageError::invalid_input(message.clone()))+ }++ /// The module-scoped declarations of owner `owner`, for the module's grant:+ /// `(collections, stream names, blob prefixes, secret prefixes)`.+ pub fn module_items(owner: &str) -> ModuleItems {+ let mut items = ModuleItems::default();+ for schema in owner_schemas()+ .into_iter()+ .filter(|schema| schema.owner.as_str() == owner)+ {+ for item in schema.items {+ if item.scope() != ScopeClass::Module {+ continue;+ }+ match item {+ Item::Collection { spec, .. } => items.collections.push(spec),+ Item::Stream { name, .. } => items.streams.push(name),+ Item::Blobs { prefix, .. } => items.blobs.push(prefix),+ Item::Secrets { prefix, .. } => items.secrets.push(prefix),+ }+ }+ }+ items+ }++ /// What one owner declares at module scope.+ #[derive(Debug, Default, Clone)]+ pub struct ModuleItems {+ /// Collections, with their indexes.+ pub collections: Vec<tinystoragedrivers::CollectionSpec>,+ /// Stream family names.+ pub streams: Vec<String>,+ /// Blob key prefixes.+ pub blobs: Vec<String>,+ /// Secret key prefixes.+ pub secrets: Vec<String>,+ }++ #[cfg(test)]+ #[path = "schema_tests.rs"]+ mod tests;diff --cc crates/openhuman-core/src/storage/sessions/mod.rsindex 3dc8d79a4a,92507e771f..ad6c2f2f92--- a/crates/openhuman-core/src/storage/sessions/mod.rs+++ b/crates/openhuman-core/src/storage/sessions/mod.rs@@@ -19,7 -19,9 +19,8 @@@ use std::sync::{Arc, LazyLock, Mutex, Puse tinyagents_session::port::{AgentStores, SessionStoreProvider};-pub mod ledger_sync;mod rebound;+ mod tenant_router;mod workspace;pub use rebound::{rebind_all, ReboundSessionStores, StoreRegistry};@@@ -313,10 -316,8 +315,9 @@@ pub fn context_workspace_dir() -> std::/// together, as the shared workspace always did.pub const DEFAULT_AGENT: &str = "default";- #[cfg(test)]#[cfg(test)]-pub(crate) mod splice_fixture;+#[path = "splice_fixture_tests.rs"]+pub(crate) mod splice_fixture_tests;#[cfg(test)]#[path = "mod_tests.rs"]diff --cc crates/openhuman-core/src/storage/sessions/tenant_router.rsindex 0000000000,3906fef9c5..3906fef9c5mode 000000,100644..100644--- a/crates/openhuman-core/src/storage/sessions/tenant_router.rs+++ b/crates/openhuman-core/src/storage/sessions/tenant_router.rsdiff --cc crates/openhuman-core/src/storage/sessions/tenant_router_tests.rsindex 0000000000,08e23d9804..08e23d9804mode 000000,100644..100644--- a/crates/openhuman-core/src/storage/sessions/tenant_router_tests.rs+++ b/crates/openhuman-core/src/storage/sessions/tenant_router_tests.rsdiff --cc crates/openhuman-core/src/tools/delegate.rsindex 2bbe0251fd,c94d878e6f..1336278433--- a/crates/openhuman-core/src/tools/delegate.rs+++ b/crates/openhuman-core/src/tools/delegate.rs@@@ -11,9 -10,9 +10,9 @@@ use std::collections::HashMapuse std::sync::Arc;use std::time::Duration;use tinyagents_harness::context::RunContext;-use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};+use tinyagents_harness::tool::ToolDispatch;use tinyinference_llm::message::Message;- use tinyinference_llm::model::{ChatModel, ModelRequest};+ use tinyinference_llm::model::ModelRequest;use tinytools::{Tool, ToolCallOptions, ToolResult, ToolRunContext};/// Tool that delegates a subtask to a named agent with a differentdiff --cc crates/openhuman-core/src/tools/impl/system/shell.rsindex aa9e7ef389,6549bf44c4..39c527234a--- a/crates/openhuman-core/src/tools/impl/system/shell.rs+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs@@@ -2,10 -2,12 +2,12 @@@ use super::shell_description::{command_#[cfg(feature = "modules")]use super::shell_support::container_environment;use super::shell_support::{command_failure, exec_result, python_utf8_env, tool_timeout_message};- use crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool;-use crate::agent::host_runtime::RuntimeAdapter;+ use crate::agent::tinyagents::host::run_context::{+ command_environment_for_tool, dispatch_ctx_for_tool,+ };use crate::config::Config;use crate::core::runtime::DispatchCtx;+use crate::modules::tinybox::host_runtime::RuntimeAdapter;use crate::security::{AuditLogger, CommandExecutionLog, SecurityPolicy};use async_trait::async_trait;use serde_json::json;diff --cc crates/openhuman-core/src/tools/ops.rsindex 42fe1a3b87,a3f33ec2db..d217f6f98d--- a/crates/openhuman-core/src/tools/ops.rs+++ b/crates/openhuman-core/src/tools/ops.rs@@@ -168,11 -168,11 +168,11 @@@ pub fn all_tools_with_runtime// default-OFF via `tools::user_filter` (their toggle IDs default off// in onboarding). The per-call permission ladder still gates them.]);- tools.extend(crate::agent::artifacts::tiny_store::registered_tools(+ tools.extend(crate::artifacts::tiny_store::registered_tools(&config.workspace_dir,- crate::agent::artifacts::FileRoots::from_config(&config),+ crate::artifacts::FileRoots::from_config(&config),action_dir,- crate::integrations::file_storage::artifact_publisher(&config),- crate::agent::artifacts::artifact_publisher(&config),++ crate::artifacts::artifact_publisher(&config),));tools.extend(crate::integrations::task_sources::tools::registered_tools(config.clone(),@@@ -413,19 -415,28 +415,28 @@@.media_files_roots.lock().unwrap_or_else(std::sync::PoisonError::into_inner) =- Some(crate::agent::artifacts::FileRoots::from_config(root_config));+ Some(crate::artifacts::FileRoots::from_config(root_config));- tools.extend(crate::media::generation::build_media_tools_with_allowlist(- root_config,- action_dir,- Arc::clone(&security.media_artifact_paths),- ));}- // Managed cloud file storage (S3 via the backend). Skipped when no- // integration client is configured; downloads land under `action_dir`.- tools.extend(crate::integrations::file_storage::build_file_storage_tools(+ // What every registered tool source can see (`tools::sources`).+ let source_ctx = crate::tools::sources::ToolSourceCtx {+ config: &config,root_config,+ security,+ runtime: &runtime,+ audit: &audit,+ browser_config,+ http_config,action_dir,+ agents,+ approval_workspace_root,+ };++ // Sources placed after the search tools (a host's media and file-storage+ // tools), where the catalogue has always listed them.+ tools.extend(crate::tools::sources::build_registered_tool_sources(+ &source_ctx,+ Some(crate::tools::sources::ANCHOR_AFTER_SEARCH),));// Hosting tools — deploy a workspace directory through the compileddiff --cc crates/openhuman-core/src/tools/sources.rsindex 0000000000,be0728ed60..8b0ff901camode 000000,100644..100644--- a/crates/openhuman-core/src/tools/sources.rs+++ b/crates/openhuman-core/src/tools/sources.rs@@@ -1,0 -1,168 +1,168 @@@+ //! Tool sources: id-keyed factories an outside crate registers so its tools+ //! join the agent catalogue.+ //!+ //! [`all_tools_with_runtime`](super::ops::all_tools_with_runtime) builds the+ //! built-in catalogue, splicing every registered source in at its+ //! [`ToolSourcePlacement`], then applies the capability filters (`DomainSet`,+ //! memory capability, `ToolGroups`). A registered tool is therefore filtered+ //! exactly like a built-in one. With nothing registered the catalogue is+ //! unchanged.+ //!+ //! The catalogue order is part of the prompt-cache layout, so a source can ask+ //! to sit after a named anchor point instead of at the end. Sources sharing a+ //! placement keep registration order.+ //!+ //! The registry is generic: it knows nothing about what a source builds.++ use std::collections::HashMap;+ use std::path::Path;+ use std::sync::Arc;++ use tinytools::Tool;+-use crate::agent::host_runtime::RuntimeAdapter;+ use crate::config::{BrowserConfig, Config, DelegateAgentConfig, HttpRequestConfig};+ use crate::core::slots::HookSlot;++use crate::modules::tinybox::host_runtime::RuntimeAdapter;+ use crate::security::{AuditLogger, SecurityPolicy};++ /// What a tool source can see while the catalogue is assembled: the same+ /// handles `all_tools_with_runtime` was given.+ pub struct ToolSourceCtx<'a> {+ /// The session's configuration snapshot.+ pub config: &'a Arc<Config>,+ /// The root configuration the catalogue is assembled under.+ pub root_config: &'a Config,+ pub security: &'a Arc<SecurityPolicy>,+ pub runtime: &'a Arc<dyn RuntimeAdapter>,+ pub audit: &'a Arc<AuditLogger>,+ pub browser_config: &'a BrowserConfig,+ pub http_config: &'a HttpRequestConfig,+ /// The agent's permitted read/write root.+ pub action_dir: &'a Path,+ pub agents: &'a HashMap<String, DelegateAgentConfig>,+ pub approval_workspace_root: Option<&'a Path>,+ }++ /// A registered tool source.+ pub type ToolSourceFactory =+ Arc<dyn for<'a> Fn(&ToolSourceCtx<'a>) -> Vec<Box<dyn Tool>> + Send + Sync>;++ /// Anchor point: right after the search tools, before hosting.+ pub const ANCHOR_AFTER_SEARCH: &str = "after_search";+ /// Anchor point: right after the delegation tool, before the Composio tools.+ pub const ANCHOR_AFTER_DELEGATE: &str = "after_delegate";+ /// Every anchor `all_tools_with_runtime` splices sources into.+ pub const ANCHORS: [&str; 2] = [ANCHOR_AFTER_SEARCH, ANCHOR_AFTER_DELEGATE];++ /// Where in the catalogue a source's tools go.+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+ pub enum ToolSourcePlacement {+ /// After every built-in tool (the default).+ #[default]+ End,+ /// Right after the named anchor point (one of [`ANCHORS`]). An unknown+ /// anchor falls back to [`ToolSourcePlacement::End`] and logs a warning.+ After(&'static str),+ }++ #[derive(Clone)]+ struct ToolSourceEntry {+ placement: ToolSourcePlacement,+ factory: ToolSourceFactory,+ }++ static TOOL_SOURCES: HookSlot<ToolSourceEntry> = HookSlot::new("tools::sources");++ /// Registers `factory` as the tool source `id` for the whole process, at the+ /// end of the catalogue. Re-registering an id replaces its factory and keeps+ /// its position.+ pub fn register_tool_source<F>(id: impl Into<String>, factory: F)+ where+ F: for<'a> Fn(&ToolSourceCtx<'a>) -> Vec<Box<dyn Tool>> + Send + Sync + 'static,+ {+ register_tool_source_at(id, ToolSourcePlacement::End, factory);+ }++ /// Registers a tool source for the whole process at `placement`.+ pub fn register_tool_source_at<F>(id: impl Into<String>, placement: ToolSourcePlacement, factory: F)+ where+ F: for<'a> Fn(&ToolSourceCtx<'a>) -> Vec<Box<dyn Tool>> + Send + Sync + 'static,+ {+ TOOL_SOURCES.register(+ id,+ ToolSourceEntry {+ placement,+ factory: Arc::new(factory),+ },+ );+ }++ /// Registers a tool source for the context built from `extensions`, at the end+ /// of the catalogue.+ pub fn register_tool_source_in<F>(+ extensions: &crate::core::slots::Extensions,+ id: impl Into<String>,+ factory: F,+ ) where+ F: for<'a> Fn(&ToolSourceCtx<'a>) -> Vec<Box<dyn Tool>> + Send + Sync + 'static,+ {+ TOOL_SOURCES.register_in(+ extensions,+ id,+ ToolSourceEntry {+ placement: ToolSourcePlacement::End,+ factory: Arc::new(factory),+ },+ );+ }++ /// Removes the process-wide tool source `id`.+ pub fn unregister_tool_source(id: &str) -> bool {+ TOOL_SOURCES.unregister(id)+ }++ /// The placement of every registered source, in registration order.+ pub fn registered_tool_source_placements() -> Vec<(String, ToolSourcePlacement)> {+ TOOL_SOURCES+ .entries()+ .into_iter()+ .map(|(id, entry)| (id, entry.placement))+ .collect()+ }++ /// Builds the tools of every registered source placed at `anchor`+ /// (`Some(name)`) or at the end (`None`, which also collects sources whose+ /// anchor is unknown), in registration order.+ pub(crate) fn build_registered_tool_sources(+ ctx: &ToolSourceCtx<'_>,+ anchor: Option<&str>,+ ) -> Vec<Box<dyn Tool>> {+ let mut tools = Vec::new();+ for (id, entry) in TOOL_SOURCES.entries() {+ let applies = match (entry.placement, anchor) {+ (ToolSourcePlacement::After(a), Some(wanted)) => a == wanted,+ (ToolSourcePlacement::After(a), None) if !ANCHORS.contains(&a) => {+ tracing::warn!(source = %id, anchor = a, "[tools::sources] unknown anchor; appending at the end");+ true+ }+ (ToolSourcePlacement::End, None) => true,+ _ => false,+ };+ if !applies {+ continue;+ }+ let built = (entry.factory)(ctx);+ tracing::debug!(+ source = %id,+ anchor = ?anchor,+ count = built.len(),+ "[tools::sources] registered tool source built"+ );+ tools.extend(built);+ }+ tools+ }++ #[cfg(test)]+ #[path = "sources_tests.rs"]+ mod tests;diff --cc crates/openhuman-core/src/tools/sources_tests.rsindex 0000000000,a5f2b8aae6..0fa3bf8904mode 000000,100644..100644--- a/crates/openhuman-core/src/tools/sources_tests.rs+++ b/crates/openhuman-core/src/tools/sources_tests.rs@@@ -1,0 -1,205 +1,205 @@@+ use super::*;-use crate::agent::host_runtime::NativeRuntime;++use crate::modules::tinybox::host_runtime::NativeRuntime;+ use crate::tools::ops::all_tools_with_runtime;+ use tempfile::TempDir;+ use tinytools::ToolResult;++ struct FakeTool(&'static str);++ #[async_trait::async_trait]+ impl Tool for FakeTool {+ fn name(&self) -> &str {+ self.0+ }++ fn description(&self) -> &str {+ "fake tool from a registered source"+ }++ fn parameters_schema(&self) -> serde_json::Value {+ serde_json::json!({ "type": "object", "properties": {} })+ }++ async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {+ Ok(ToolResult::success("ok"))+ }+ }++ fn assemble(tmp: &TempDir) -> Vec<String> {+ let cfg = Config {+ workspace_dir: tmp.path().join("workspace"),+ action_dir: tmp.path().join("workspace"),+ config_path: tmp.path().join("config.toml"),+ ..Config::default()+ };+ let security = Arc::new(SecurityPolicy::default());+ let browser = BrowserConfig {+ enabled: false,+ ..BrowserConfig::default()+ };+ let http = HttpRequestConfig::default();+ all_tools_with_runtime(+ Arc::new(cfg.clone()),+ &security,+ Arc::new(NativeRuntime::new()),+ AuditLogger::disabled(),+ &browser,+ &http,+ tmp.path(),+ &HashMap::new(),+ &cfg,+ None,+ )+ .iter()+ .map(|t| t.name().to_string())+ .collect()+ }++ #[test]+ fn nothing_registered_leaves_the_catalogue_without_source_tools() {+ let tmp = TempDir::new().unwrap();+ let names = assemble(&tmp);+ assert!(!names.is_empty());+ assert!(!names.iter().any(|n| n.starts_with("source_fake_")));+ }++ #[test]+ fn registered_sources_append_in_registration_order_after_built_ins() {+ let tmp = TempDir::new().unwrap();+ let baseline = assemble(&tmp);++ register_tool_source("test::second", |_| {+ vec![Box::new(FakeTool("source_fake_b"))]+ });+ register_tool_source("test::first", |_| {+ vec![+ Box::new(FakeTool("source_fake_a1")),+ Box::new(FakeTool("source_fake_a2")),+ ]+ });+ let names = assemble(&tmp);+ unregister_tool_source("test::second");+ unregister_tool_source("test::first");++ let position = |name: &str| names.iter().position(|n| n == name).unwrap();+ assert!(position("source_fake_b") < position("source_fake_a1"));+ assert_eq!(position("source_fake_a2"), position("source_fake_a1") + 1);+ // Built-ins precede registered sources.+ assert!(position("file_read") < position("source_fake_b"));+ assert_eq!(names.len(), baseline.len() + 3);+ }++ #[test]+ fn a_source_receives_the_catalogue_context() {+ let tmp = TempDir::new().unwrap();+ let seen = Arc::new(std::sync::Mutex::new(None));+ let sink = Arc::clone(&seen);+ register_tool_source("test::ctx", move |ctx| {+ *sink.lock().unwrap() = Some((ctx.action_dir.to_path_buf(), ctx.agents.len()));+ Vec::new()+ });+ let _ = assemble(&tmp);+ unregister_tool_source("test::ctx");+ let (action_dir, agents) = seen.lock().unwrap().clone().expect("source ran");+ assert_eq!(action_dir, tmp.path());+ assert_eq!(agents, 0);+ }++ #[test]+ fn unregistering_a_source_removes_its_tools() {+ let tmp = TempDir::new().unwrap();+ register_tool_source("test::gone", |_| {+ vec![Box::new(FakeTool("source_fake_gone"))]+ });+ assert!(assemble(&tmp).contains(&"source_fake_gone".to_string()));+ assert!(unregister_tool_source("test::gone"));+ assert!(!assemble(&tmp).contains(&"source_fake_gone".to_string()));+ }++ #[test]+ fn anchored_sources_sit_where_the_catalogue_always_listed_them() {+ // The pre-refactor catalogue built a host's media / file-storage tools+ // right after the search tools (before hosting, web3 and image_info) and+ // its place / market-data tools right after the delegation tool, ahead of+ // the Composio tools; the order is a prompt-cache input.+ let tmp = TempDir::new().unwrap();+ let anchor_tools = |names: &[&str]| -> Vec<Box<dyn Tool>> {+ names+ .iter()+ .map(|n| Box::new(FakeTool(Box::leak(n.to_string().into_boxed_str()))) as Box<dyn Tool>)+ .collect()+ };++ register_tool_source_at(+ "test::after_search_a",+ ToolSourcePlacement::After(ANCHOR_AFTER_SEARCH),+ move |_| anchor_tools(&["anchor_fake_search_a"]),+ );+ register_tool_source_at(+ "test::after_search_b",+ ToolSourcePlacement::After(ANCHOR_AFTER_SEARCH),+ move |_| anchor_tools(&["anchor_fake_search_b"]),+ );+ register_tool_source_at(+ "test::after_delegate",+ ToolSourcePlacement::After(ANCHOR_AFTER_DELEGATE),+ move |_| anchor_tools(&["anchor_fake_delegate"]),+ );+ register_tool_source("test::end", |_| vec![Box::new(FakeTool("anchor_fake_end"))]);+ register_tool_source_at(+ "test::unknown_anchor",+ ToolSourcePlacement::After("nowhere"),+ |_| vec![Box::new(FakeTool("anchor_fake_unknown"))],+ );+ let names = assemble(&tmp);+ for id in [+ "test::after_search_a",+ "test::after_search_b",+ "test::after_delegate",+ "test::end",+ "test::unknown_anchor",+ ] {+ unregister_tool_source(id);+ }++ let pos = |name: &str| {+ names+ .iter()+ .position(|n| n == name)+ .unwrap_or_else(|| panic!("{name} missing"))+ };+ // Registration order within an anchor.+ assert_eq!(pos("anchor_fake_search_b"), pos("anchor_fake_search_a") + 1);+ // After-search sources precede the image-info built-in registered after+ // hosting/web3, and follow the built-ins that precede the search tools.+ assert!(pos("file_read") < pos("anchor_fake_search_a"));+ assert!(pos("anchor_fake_search_b") < pos("image_info"));+ // End sources, and sources with an unknown anchor, trail every built-in+ // and keep registration order.+ assert!(pos("image_info") < pos("anchor_fake_delegate"));+ assert!(pos("anchor_fake_delegate") < pos("anchor_fake_end"));+ assert!(pos("anchor_fake_end") < pos("anchor_fake_unknown"));+ // Sibling tests register sources on the same process-wide slot, so only+ // relative positions are asserted, never the total length.+ }++ /// A media source that reads the security policy's files roots while it builds+ /// must find them already recorded.+ #[cfg(feature = "media")]+ #[test]+ fn media_files_roots_are_recorded_before_any_source_builds() {+ let tmp = TempDir::new().unwrap();+ let seen = Arc::new(std::sync::Mutex::new(None));+ let sink = Arc::clone(&seen);+ register_tool_source_at(+ "test::roots",+ ToolSourcePlacement::After(ANCHOR_AFTER_SEARCH),+ move |ctx| {+ *sink.lock().unwrap() = Some(ctx.security.media_files_roots.lock().unwrap().is_some());+ Vec::new()+ },+ );+ let _ = assemble(&tmp);+ unregister_tool_source("test::roots");+ assert_eq!(*seen.lock().unwrap(), Some(true));+ }diff --cc crates/openhuman-core/src/triage/README.mdindex d0245e349f,0dfc717880..563eeb5a11--- a/crates/openhuman-core/src/triage/README.md+++ b/crates/openhuman-core/src/triage/README.md@@@ -103,12 -103,12 +103,12 @@@ Re-exported from [`mod.rs`](./mod.rs)## Related-- [`crates/openhuman-core/src/agent/registry/agents/trigger_triage/`](../registry/agents/trigger_triage/): the+- [`crates/openhuman-core/src/agent_registry/agents/trigger_triage/`](../../agent_registry/agents/trigger_triage/): theclassifier agent definition; `prompt.md` describes the JSON contract`decision.rs` parses.-- [`crates/openhuman-core/src/agent/registry/agents/trigger_reactor/`](../registry/agents/trigger_reactor/): the+- [`crates/openhuman-core/src/agent_registry/agents/trigger_reactor/`](../../agent_registry/agents/trigger_reactor/): thesingle-step sub-agent `react` decisions dispatch to.- - [`crates/openhuman-core/src/cron/scheduler_gate/README.md`](../../cron/scheduler_gate/README.md): the LLM-permit+ - [`crates/openhuman-core/src/platform/llm_gate/README.md`](../../platform/llm_gate/README.md): the LLM-permitgate the local arm waits on.- [Parent module README](../README.md)- [Triggers](../../../../../docs/gitbooks/en/features/integrations/triggers.md)diff --cc crates/openhuman-core/src/triage/evaluator/chain.rsindex 35deea886e,19230ed7f3..a0e3c236b8--- a/crates/openhuman-core/src/triage/evaluator/chain.rs+++ b/crates/openhuman-core/src/triage/evaluator/chain.rs@@@ -7,11 -8,7 +7,11 @@@ use std::time::{Duration, Instant}use anyhow::Context;- use crate::cron::scheduler_gate::LlmPermit;+ use crate::platform::llm_gate::LlmPermit;+use tinyagents_harness::retry::{+ decide, BreakerRejection, FailoverDecision, FailoverReason, FailoverState,+ PersistentFailoverAttempt, PersistentFailoverBreaker, PersistentFailoverBreakerConfig,+};use super::super::envelope::TriggerEnvelope;use super::super::events;diff --cc crates/openhuman-embed/src/agent/mod.rsindex b1bbc7d3db,1ed2a3c968..20c1ddadd9--- a/crates/openhuman-embed/src/agent/mod.rs+++ b/crates/openhuman-embed/src/agent/mod.rs@@@ -135,11 -140,9 +140,12 @@@ pub(crate) struct AgentInner/// The agent's own in-process tools, rebuilt per turn. See/// [`AgentSpec::tools`](super::AgentSpec::tools) for why it is a factory.pub(crate) host_tools: Option<openhuman_core::agent::HostTools>,- pub(crate) hooks: openhuman_core::agent::hooks::HookScope,+ pub(crate) hooks: tinyagents_hooks::scope::HookScope<+ openhuman_core::agent::tinyagents::host::OpenHumanRunContext,+ tinyagents_harness::cost::TurnCost,+ >,pub(crate) lifecycle: lifecycle::Lifecycle,+ pub(crate) mcp_cleanup: std::sync::Mutex<Option<openhuman_core::mcp::host::AgentMcpCleanup>>,/// Built from [`ToolScopeSpec::HostOnly`]: every turn's session is built/// from the host tools alone.pub(crate) host_only: bool,diff --cc crates/openhuman-embed/src/host_internals.rsindex 5d3e6ae447,3270d8912d..0a66c73ee0--- a/crates/openhuman-embed/src/host_internals.rs+++ b/crates/openhuman-embed/src/host_internals.rs@@@ -151,9 -148,15 +148,15 @@@ pub mod agentinstall_tool_ranker, installed_tool_ranker,};}+ // tinyhumans integrations: the turn's approval context for a tool call.+ pub mod host {+ pub mod run_context {+ pub use openhuman_core::agent::tinyagents::host::run_context::approval_for_tool;+ }+ }// rpc: Socket.IO run-mode toggles.pub mod run_mode {- pub use openhuman_core::agent::tinyagents::run_mode::{parse_mode_label, set_mode};+ pub use openhuman_core::threads::{parse_mode_label, set_mode};}}// rpc: shutdown, plan review over Socket.IO, and the session store install.@@@ -262,6 -274,140 +274,140 @@@ pub mod util}}+ // ---------------------------------------------------------------------------+ // Extension points (tinyhumans). Generic, id-keyed registries the hosted layer+ // fills at install time; the core knows nothing about what it is handed. Each+ // `register_*` has an `_in` variant that binds to a `CoreBuilder::extensions`+ // set instead of the process.+ // ---------------------------------------------------------------------------++ /// Tool sources: tools an outside crate appends to the agent catalogue.+ pub mod tool_sources {+ pub use openhuman_core::tools::sources::{+ register_tool_source, register_tool_source_at, register_tool_source_in,+ registered_tool_source_placements, unregister_tool_source, ToolSourceCtx,+ ToolSourceFactory, ToolSourcePlacement, ANCHOR_AFTER_DELEGATE, ANCHOR_AFTER_SEARCH,+ };+ }++ /// The artifact publisher slot: the service that shares an artifact version.+ pub mod artifact_publisher {- pub use openhuman_core::agent::artifacts::{++ pub use openhuman_core::artifacts::{+ register_artifact_publisher, register_artifact_publisher_in, unregister_artifact_publisher,+ ArtifactPublisherFactory,+ };+ // tinyhumans file-storage publisher: the protected-path guard it re-checks+ // before upload, and the store its tests save artifacts into.- pub use openhuman_core::agent::artifacts::tiny_store::{refused_path, versioned_store};++ pub use openhuman_core::artifacts::tiny_store::{refused_path, versioned_store};+ }++ /// Egress disclosure, for hosted calls that leave the machine.+ pub mod egress {+ pub use openhuman_core::security::egress::{+ emit_external_transfer, emit_external_transfer_in, enforce_egress, local_only_blocks,+ DataKind, EgressDescriptor, EgressLedger, EgressReason, IdentificationRisk,+ };+ }++ /// Config enrichers and the resolved fields they fill.+ pub mod config_enrichers {+ pub use openhuman_core::config::schema::resolved_endpoints::ResolvedEndpoints;+ pub use openhuman_core::config::{+ register_enricher, register_enricher_in, run_enrichers, unregister_enricher, ConfigEnricher,+ };+ }++ /// Composio route builders (`composio.mode` -> route).+ pub mod composio {+ pub use openhuman_core::integrations::composio::client::{+ register_composio_route_builder, unregister_composio_route_builder, ComposioRoute,+ ComposioRouteBuilder,+ };+ // The proxy route's target (origin + bearer) for `composio.mode = backend`.+ #[cfg(feature = "modules")]+ pub use openhuman_core::modules::connectors::{+ register_proxy_target, unregister_proxy_target, ProxyTarget, ProxyTargetResolver,+ };+ }++ /// Media-generation tool building over host-supplied generators (tinyhumans).+ #[cfg(feature = "media")]+ pub mod media {+ pub mod generation {+ pub use openhuman_core::media::generation::{+ media_tools_for_config, GeneratorRouter, MediaGenerators, MediaReferenceAllowlist,+ };+ }+ }++ /// The wallet module's authenticated backend hook (tinyhumans web3).+ #[cfg(feature = "web3")]+ pub mod wallet_backend {+ pub use openhuman_core::modules::wallet_backend::{+ register_wallet_backend, register_wallet_backend_in, unregister_wallet_backend,+ WalletBackendCall, WalletBackendFuture, WalletBackendHandler,+ };+ }++ /// Model-provider registries: chat models, embeddings, catalogs.+ pub mod inference_registry {+ pub use openhuman_core::inference::provider::factory::PROVIDER_OPENHUMAN;+ pub use openhuman_core::inference::provider::openhuman_backend_model::REASONING_OFF_METADATA_KEY;+ pub use openhuman_core::inference::registry::{+ register_catalog, register_catalog_in, register_chat_model, register_chat_model_in,+ register_embedding, register_embedding_in, unregister_catalog, unregister_chat_model,+ unregister_embedding, BoxFuture, CatalogEntry, CatalogLimits, CatalogListing,+ CatalogRequest, ChatModelEntry, ChatModelFactory, ChatModelRequest, EmbeddingFactory,+ EmbeddingRequest, ReadinessProbe,+ };+ }++ /// Memory engines by id, and the free-background-work predicate.+ pub mod memory_engines {+ pub use openhuman_core::memory::engine::{+ build_cached, rooted, BearerSource, Binding, BoundEngine, EngineCredential, EngineSettings,+ TINYHUMANS_ENGINE,+ };+ pub use openhuman_core::memory::engine_registry::{+ bound_engine, register_memory_engine, register_memory_engine_in, unregister_memory_engine,+ EngineBuilder, EngineEntry, EngineFuture, EngineRequest, FreeBackground,+ };+ }++ /// The channel callback slot.+ #[cfg(feature = "channels")]+ pub mod channel_callback {+ pub use openhuman_core::channels::callback_slot::{+ register_channel_callback, register_channel_callback_in, unregister_channel_callback,+ CallbackFuture, ChannelCallback, ChannelCallbackCtx,+ };+ }++ /// Voice provider registries: STT, TTS and live sessions by slug.+ #[cfg(feature = "voice")]+ pub mod voice_registry {+ pub use openhuman_core::config::schema::voice_live::{+ LIVE_PROVIDER_ELEVENLABS_HOSTED, LIVE_PROVIDER_GEMINI_HOSTED,+ };+ pub use openhuman_core::voice::factory::registry::{+ register_stt_provider, register_stt_provider_in, register_tts_provider,+ register_tts_provider_in, unregister_stt_provider, unregister_tts_provider,+ SttProviderFactory, TtsProviderFactory,+ };+ pub use openhuman_core::voice::factory::{+ create_stt_provider, create_tts_provider, SttProvider, SttResult, TtsProvider,+ };+ pub use openhuman_core::voice::live::ops::live_providers;+ pub use openhuman_core::voice::live::registry::{+ register_live_provider, register_live_provider_in, unregister_live_provider, ConfigureFn,+ ConfiguredFn, LiveFuture, LiveProviderEntry, LiveProviderPlacement, PrepareFn,+ };+ pub use openhuman_core::voice::live::types::{LiveProviderInfo, LiveProviderKind};+ pub use openhuman_core::voice::live::{+ LiveVoiceError, PreparedProvider, GEMINI_LANGUAGES, GEMINI_VOICES,+ };+ }+// The rest is the rpc server alone.pub mod desktop {diff --cc crates/openhuman-embed/src/runtime/build.rsindex 759b478712,cf43e9f173..305e6a59c6--- a/crates/openhuman-embed/src/runtime/build.rs+++ b/crates/openhuman-embed/src/runtime/build.rs@@@ -190,9 -190,11 +190,11 @@@ impl RuntimeBuilder};if self.session_store.is_none() {if let Some(backend) = &storage_backend {- let stores = tinyagents_session::DriverSessionStores::new(backend.clone())- .map_err(|e| RuntimeError::Build(e.into()))?- .recover_on_open(!openhuman_core::storage::driver_is_shared(backend.driver()));- let stores = openhuman_core::agent::session_store::TenantSessionStores::new(++ let stores = openhuman_core::storage::sessions::TenantSessionStores::new(+ backend.clone(),+ !openhuman_core::storage::driver_is_shared(backend.driver()),+ )+ .map_err(|e| RuntimeError::Build(e.into()))?;self.session_store = Some(Arc::new(stores));}}diff --cc crates/openhuman-embed/src/turn.rsindex 4f792ea507,16aa479ac2..d17710fe34--- a/crates/openhuman-embed/src/turn.rs+++ b/crates/openhuman-embed/src/turn.rs@@@ -98,12 -98,9 +98,12 @@@ pub struct Turncontrol_deadline: Option<tokio::time::Instant>,observer: Option<Arc<dyn crate::observe::TurnObserver>>,trace_content: crate::observe::TraceContent,- hooks: openhuman_core::agent::hooks::HookScope,+ hooks: tinyagents_hooks::scope::HookScope<+ openhuman_core::agent::tinyagents::host::OpenHumanRunContext,+ tinyagents_harness::cost::TurnCost,+ >,tools: Option<openhuman_core::agent::HostTools>,- tool_env: Option<tinytools_std::timeout::CommandEnvironment>,+ tool_env: Option<Arc<std::collections::BTreeMap<String, String>>>,}impl Turn {diff --cc scripts/__tests__/storage-bypass-debt.test.mjsindex 0000000000,dbd65e0dbc..b27da811damode 000000,100644..100644--- a/scripts/__tests__/storage-bypass-debt.test.mjs+++ b/scripts/__tests__/storage-bypass-debt.test.mjs@@@ -1,0 -1,319 +1,362 @@@+ import assert from "node:assert/strict";+ import test from "node:test";+ import {+ mkdtempSync,+ rmSync,+ mkdirSync,+ writeFileSync,+ symlinkSync,+ } from "node:fs";+ import { tmpdir } from "node:os";+ import { join } from "node:path";+ import { fileURLToPath } from "node:url";+ import { execFileSync, spawnSync } from "node:child_process";+ import {+ validateCoverageDebt,+ validateAllowances,+ historicalFindings,+ } from "../ci/storage-bypass-debt.mjs";+ import {+ compare,+ scan,+ CURATED_VENDOR_ROOTS,+ collectFindings,+ } from "../ci/check-storage-bypass.mjs";+ const row = {+ rule: "json-write",+ path: "crates/openhuman-embed/src/state.rs",+ text: "tokio::fs::write(path, bytes);",+ occurrence: 1,+ classification: "unmigrated",+ reason: "Existing native backend migration debt at this exact source site.",+ issue: "https://github.com/tinyhumansai/openhuman/issues/7428",+ };+ const history = { baseline: [], extension: null, findings: [row] };+ test("initial extension admits only exact existing canonical coverage", () => {+ assert.deepEqual(validateCoverageDebt([row], [], [row], history), []);+ const added = { ...row, path: "crates/openhuman-embed/src/new.rs" };+ assert.match(+ validateCoverageDebt([added], [], [added], history).join("\n"),+ /branch-added writer/,+ );+ });+ test("moving or copying a recorded writer cannot reuse its identity", () => {+ const moved = { ...row, path: "crates/openhuman-rpc/src/state.rs" };+ assert.equal(compare([moved], [row]).added.length, 1);+ const copied = { ...row, occurrence: 2 };+ assert.equal(compare([row, copied], [row]).added.length, 1);+ });+ test("extension records may shrink but never grow after establishment", () => {+ const old = { ...history, extension: [row] };+ assert.deepEqual(validateCoverageDebt([], [], [], old), []);+ const added = { ...row, text: "tokio::fs::write(other, bytes);" };+ assert.match(+ validateCoverageDebt([row, added], [], [row, added], old).join("\n"),+ /Extension growth forbidden/,+ );+ });+ test("removing a debt record does not grandfather a surviving writer", () => {+ assert.equal(compare([row], []).added.length, 1);+ });+ test("original core debt cannot move into the extension or grow", () => {+ const core = { ...row, path: "crates/openhuman-core/src/state.rs" };+ assert.match(+ validateCoverageDebt([core], [], [core], history).join("\n"),+ /cannot conceal original core debt/,+ );+ assert.match(+ validateCoverageDebt([core], [core], [], history).join("\n"),+ /Core baseline growth forbidden/,+ );+ });+ test("reasons, exact occurrence and issue links are mandatory", () => {+ for (const bad of [+ { reason: "" },+ { issue: "" },+ { classification: "approved" },+ { occurrence: 2 },+ ]) {+ assert.ok(+ validateCoverageDebt([row], [], [{ ...row, ...bad }], history).length,+ );+ }+ });+ test("an initial allowance cannot exempt a newly introduced branch writer", () => {+ const record = { ...row, site: row.text };+ assert.match(+ validateAllowances([row], [record], {+ rawFindings: [],+ allowances: null,+ }).join("\n"),+ /branch-added writer/,+ );+ assert.deepEqual(+ validateAllowances([row], [record], {+ rawFindings: [row],+ allowances: null,+ }),+ [],+ );+ });+ test("later allowances cannot grow or excuse a copied site", () => {+ const record = { ...row, site: row.text };+ const copy = { ...record, path: "crates/openhuman-embed/src/copy.rs" };+ assert.match(+ validateAllowances([{ ...row, path: copy.path }], [copy], {+ rawFindings: [row],+ allowances: [record],+ }).join("\n"),+ /growth forbidden/,+ );+ });+ test("curated vendor coverage excludes native drivers but not host adapter writes", () => {+ assert.ok(+ CURATED_VENDOR_ROOTS.every((p) => !p.includes("tinystoragedrivers")),+ );+ assert.ok(CURATED_VENDOR_ROOTS.some((p) => p.includes("tinymcp")));+ assert.ok(CURATED_VENDOR_ROOTS.some((p) => p.includes("run_ledger")));+ assert.equal(+ scan(+ "crates/openhuman-embed/src/adapter.rs",+ "tokio::fs::write(path, bytes);",+ ).length,+ 1,+ );+ });+ test("new serializer and helper rules ignore quoted and commented fixture text", () => {+ assert.deepEqual(+ scan(+ "x.rs",+ 'let fixture = "serde_json::to_writer(file, value);";\n/* fn write_atomic(path) {} */',+ ),+ [],+ );+ });++ test("missing canonical base history fails closed", () => {+ const root = mkdtempSync(join(tmpdir(), "storage-history-"));+ try {+ execFileSync("git", ["init"], { cwd: root, stdio: "ignore" });+ assert.throws(() =>+ historicalFindings(root, {+ scan,+ withoutAllowed: (_, x) => x,+ isTestFile: () => false,+ CURATED_VENDOR_ROOTS: [],+ }),+ );+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });+ test("quoted database opener examples do not count as host persistence", () => {+ assert.deepEqual(+ scan(+ "crates/openhuman-embed/src/example.rs",+ 'let example = r#"OtherStore::open(root.join("cache.db"))"#;',+ ),+ [],+ );+ });++ test("duplicate original core identities cannot inflate the retained baseline", () => {+ const core = { ...row, path: "crates/openhuman-core/src/state.rs" };+ assert.match(+ validateCoverageDebt([core], [core, core], [], {+ baseline: [core],+ extension: [],+ findings: [core],+ }).join("\n"),+ /Duplicate core baseline record/,+ );+ });++ test("real checkouts refuse missing curated vendor source instead of shrinking debt", async () => {+ const root = mkdtempSync(join(tmpdir(), "storage-curated-source-"));+ try {+ execFileSync("git", ["init"], { cwd: root, stdio: "ignore" });+ mkdirSync(join(root, "crates"));+ await assert.rejects(collectFindings(root), /Missing curated source/);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ test("present but empty curated vendor directories cannot appear as debt shrinkage", async () => {+ const root = mkdtempSync(join(tmpdir(), "storage-empty-curated-"));+ try {+ execFileSync("git", ["init"], { cwd: root, stdio: "ignore" });+ mkdirSync(join(root, "crates"));+ for (const path of CURATED_VENDOR_ROOTS) {+ if (path.endsWith(".rs")) {+ mkdirSync(join(root, path, ".."), { recursive: true });+ writeFileSync(join(root, path), "// no writer\n");+ } else mkdirSync(join(root, path), { recursive: true });+ }+ await assert.rejects(collectFindings(root), /Empty curated source/);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ test("symlinked real checkouts still refuse missing curated source", async () => {+ const fixture = mkdtempSync(join(tmpdir(), "storage-symlink-source-"));+ const root = join(fixture, "checkout");+ const linked = join(fixture, "linked");+ try {+ mkdirSync(root);+ execFileSync("git", ["init"], { cwd: root, stdio: "ignore" });+ mkdirSync(join(root, "crates"));+ symlinkSync(root, linked, "junction");+ await assert.rejects(collectFindings(linked), /Missing curated source/);+ } finally {+ rmSync(fixture, { recursive: true, force: true });+ }+ });++ test("symlinked --root checkouts cannot bypass required canonical history", () => {+ const fixture = mkdtempSync(join(tmpdir(), "storage-symlink-history-"));+ const root = join(fixture, "checkout");+ const linked = join(fixture, "linked");+ try {+ mkdirSync(root);+ execFileSync("git", ["init"], { cwd: root, stdio: "ignore" });+ mkdirSync(join(root, "crates"));+ for (const path of CURATED_VENDOR_ROOTS) {+ if (path.endsWith(".rs")) {+ mkdirSync(join(root, path, ".."), { recursive: true });+ writeFileSync(join(root, path), "// no writer\n");+ } else {+ mkdirSync(join(root, path), { recursive: true });+ writeFileSync(join(root, path, "store.rs"), "// no writer\n");+ }+ }+ mkdirSync(join(root, "scripts", "ci"), { recursive: true });+ writeFileSync(+ join(root, "scripts", "ci", "storage-bypass-baseline.json"),+ "[]\n",+ );+ symlinkSync(root, linked, "junction");+ const result = spawnSync(+ process.execPath,+ [+ fileURLToPath(+ new URL("../ci/check-storage-bypass.mjs", import.meta.url),+ ),+ "--root",+ linked,+ ],+ { encoding: "utf8" },+ );+ assert.equal(result.status, 1, result.stdout + result.stderr);+ assert.match(result.stderr, /merge-base|origin\/main|upstream\/main/);+ } finally {+ rmSync(fixture, { recursive: true, force: true });+ }+ });++ test("new-based file stores are findings without matching memory stores", () => {+ const findings = scan(+ "crates/openhuman-core/src/catalog.rs",+ [+ "let cache = FileCatalogStore::new(dir);",+ "let cache = tinyskills::FileCatalogStore::new(dir);",+ "let memory = MemoryCatalogStore::new();",+ ].join("\n"),+ );+ assert.deepEqual(+ findings.map((f) => f.rule),+ ["file-store-new", "file-store-new"],+ );+ });++ for (const [name, source] of [+ ["task stores", "vendor/tinyagents/crates/tinyagents-tasks/src/store.rs"],+ [+ "catalog store",+ "vendor/tinyskills/crates/tinyskills/src/registry/store.rs",+ ],+ ]) {+ test(`${name} owning writers are included in curated coverage`, async () => {+ const root = mkdtempSync(join(tmpdir(), "storage-owner-coverage-"));+ try {+ mkdirSync(join(root, "crates"));+ mkdirSync(join(root, source, ".."), { recursive: true });+ writeFileSync(+ join(root, source),+ "pub fn persist() { std::fs::write(path, bytes); }\n",+ );+ const findings = await collectFindings(root);+ assert.equal(findings.length, 1);+ assert.equal(findings[0].path, source);+ assert.equal(findings[0].rule, "json-write");+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });+ }++ test("host calls to the JSONL task opener cannot hide their persistent path", () => {+ const findings = scan(+ "crates/openhuman-core/src/tasks.rs",+ "let store = tinyagents::open_jsonl_task_store_or_memory(path, None);",+ );+ assert.equal(findings.length, 1);+ assert.equal(findings[0].rule, "task-store-open");+ });++ test("current thread and turn-state host facades remain curated after storage migration", () => {+ assert.ok(+ CURATED_VENDOR_ROOTS.includes(+ "vendor/tinyagents/crates/tinyagents-session/src/threads/mod.rs",+ ),+ );+ assert.ok(+ CURATED_VENDOR_ROOTS.includes(+ "vendor/tinyagents/crates/tinyagents-session/src/turn_state/mirror",+ ),+ );+ });++++test("a Git-recorded move preserves only the original writer and allowance", () => {++ const root = mkdtempSync(join(tmpdir(), "storage-debt-move-"));++ const git = (...args) => execFileSync("git", args, {++ cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"],++ });++ const oldPath = "crates/openhuman-core/src/old/state.rs";++ const newPath = "crates/openhuman-core/src/new/state.rs";++ const source = Array.from({ length: 30 }, (_, i) => "// original comment " + i).join("\n") +++ "\ntokio::fs::write(path, bytes);\n";++ const old = { ...row, path: oldPath };++ const moved = { ...old, path: newPath };++ const scanner = { scan, withoutAllowed: (_, x) => x, isTestFile: () => false, CURATED_VENDOR_ROOTS: [] };++ try {++ git("init", "-b", "main");++ git("config", "user.name", "Test");++ git("config", "user.email", "[email protected]");++ mkdirSync(join(root, oldPath, ".."), { recursive: true });++ mkdirSync(join(root, "scripts/ci"), { recursive: true });++ writeFileSync(join(root, oldPath), source);++ writeFileSync(join(root, "scripts/ci/storage-bypass-baseline.json"), JSON.stringify([old]));++ writeFileSync(join(root, "scripts/ci/storage-bypass-extension.json"), "[]");++ writeFileSync(join(root, "scripts/ci/storage-bypass-allow-reasons.json"), JSON.stringify([{ ...old, site: old.text }]));++ git("add", ".");++ git("commit", "-m", "original writer");++ git("update-ref", "refs/remotes/upstream/main", "HEAD");++ git("switch", "-c", "move");++ mkdirSync(join(root, newPath, ".."), { recursive: true });++ git("mv", oldPath, newPath);++ writeFileSync(join(root, newPath), source + "tokio::fs::write(other, bytes);\n");++ git("add", ".");++ const previous = historicalFindings(root, scanner);++ assert.deepEqual(validateCoverageDebt([moved], [moved], [], previous), []);++ assert.deepEqual(validateAllowances([moved], [{ ...moved, site: moved.text }], previous), []);++ const added = { ...moved, text: "tokio::fs::write(other, bytes);" };++ assert.match(validateCoverageDebt([moved, added], [moved, added], [], previous).join("\n"), /growth forbidden/);++ assert.match(validateAllowances([moved, added], [{ ...added, site: added.text }], previous).join("\n"), /growth forbidden/);++ const copied = { ...moved, path: "crates/openhuman-core/src/copied.rs" };++ assert.match(validateCoverageDebt([copied], [copied], [], previous).join("\n"), /growth forbidden/);++ } finally {++ rmSync(root, { recursive: true, force: true });++ }++});diff --cc scripts/ci/check-openhuman-rust-layout.mjsindex 059f2b230f,02ca6c67e6..594b5a46cc--- a/scripts/ci/check-openhuman-rust-layout.mjs+++ b/scripts/ci/check-openhuman-rust-layout.mjs@@@ -39,7 -40,7 +39,7 @@@ const LEGACY_LIMIT_ENTRIES =// their current sizes while follow-up work separates their test concerns.// `core/` was pruned from the line limit by name until these pins; its// oversized files are pinned at the size they had when enforcement began.- ["crates/openhuman-core/src/core/all.rs", 1220],- ["crates/openhuman-core/src/core/all.rs", 1234],++ ["crates/openhuman-core/src/core/all.rs", 1224],["crates/openhuman-core/src/core/all_tests.rs", 1465],["crates/openhuman-core/src/core/events.rs", 1803],["crates/openhuman-core/src/core/events_tests.rs", 997],diff --cc scripts/ci/process-statics.jsonindex aa1eb0250d,9f664d3a2b..0244dff983--- a/scripts/ci/process-statics.json+++ b/scripts/ci/process-statics.json@@@ -127,8 -137,148 +137,148 @@@"count": 1,"category": "A","reason": "The process's registry of weak handles to the rebindable session-store providers a host installed, so a workspace switch (storage::rebind) can point each at the new backend. It holds no records and no tenant state, only Weak references; the stores' data lives in the storage backend. A test builds its own StoreRegistry, so rebinding one never moves another's stores.",- "verification": "agent/session_store/rebound_tests.rs: a_registry_rebind_leaves_other_registries_alone"+ "verification": "storage/sessions/rebound_tests.rs: a_registry_rebind_leaves_other_registries_alone"},+ {- "file": "crates/openhuman-core/src/agent/artifacts/publisher_slot.rs",++ "file": "crates/openhuman-core/src/artifacts/publisher_slot.rs",+ "scope": "",+ "name": "PUBLISHERS",+ "type": "HookSlot<ArtifactPublisherFactory>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",- "verification": "agent/artifacts/publisher_slot_tests.rs: the_first_factory_that_answers_serves_sharing"++ "verification": "artifacts/publisher_slot_tests.rs: the_first_factory_that_answers_serves_sharing"+ },+ {+ "file": "crates/openhuman-core/src/channels/callback_slot.rs",+ "scope": "",+ "name": "CALLBACKS",+ "type": "HookSlot<ChannelCallback>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "channels/callback_slot_tests.rs: the_first_registered_callback_serves_requests"+ },+ {+ "file": "crates/openhuman-core/src/config/enrichers.rs",+ "scope": "",+ "name": "ENRICHERS",+ "type": "HookSlot<ConfigEnricher>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "config/enrichers_tests.rs: enrichers_run_in_registration_order"+ },+ {+ "file": "crates/openhuman-core/src/inference/registry.rs",+ "scope": "",+ "name": "CHAT_MODELS",+ "type": "HookSlot<ChatModelEntry>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "inference/registry_tests.rs: a_registered_chat_model_serves_the_managed_provider_for_a_thread"+ },+ {+ "file": "crates/openhuman-core/src/inference/registry.rs",+ "scope": "",+ "name": "EMBEDDINGS",+ "type": "HookSlot<EmbeddingFactory>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "inference/registry_tests.rs: a_registered_embedding_factory_builds_the_managed_embedding_model"+ },+ {+ "file": "crates/openhuman-core/src/inference/registry.rs",+ "scope": "",+ "name": "CATALOGS",+ "type": "HookSlot<CatalogEntry>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "inference/registry_tests.rs: a_registered_catalog_answers_the_model_listing_for_its_provider"+ },+ {+ "file": "crates/openhuman-core/src/integrations/composio/client/factory.rs",+ "scope": "",+ "name": "ROUTE_BUILDERS",+ "type": "HookSlot<ComposioRouteBuilder>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "integrations/composio/client/factory_tests.rs: a_registered_route_builder_resolves_the_backend_mode"+ },+ {+ "file": "crates/openhuman-core/src/modules/connectors.rs",+ "scope": "",+ "name": "MODULE_PROXY_TARGETS",+ "type": "HookSlot<ProxyTargetResolver>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of handlers the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "modules/connectors_tests.rs: the_backend_route_is_unavailable_without_a_registered_target"+ },+ {+ "file": "crates/openhuman-core/src/memory/engine_registry.rs",+ "scope": "",+ "name": "ENGINES",+ "type": "HookSlot<EngineEntry>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "memory/engine_registry_tests.rs: the_layout_root_reaches_the_registered_builder"+ },+ {+ "file": "crates/openhuman-core/src/tools/sources.rs",+ "scope": "",+ "name": "TOOL_SOURCES",+ "type": "HookSlot<ToolSourceEntry>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "tools/sources_tests.rs: registered_sources_append_in_registration_order_after_built_ins"+ },+ {+ "file": "crates/openhuman-core/src/voice/factory/registry.rs",+ "scope": "",+ "name": "STT_PROVIDERS",+ "type": "HookSlot<SttProviderFactory>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "voice/factory/registry_tests.rs: a_registered_stt_slug_is_built_with_the_effective_model"+ },+ {+ "file": "crates/openhuman-core/src/voice/factory/registry.rs",+ "scope": "",+ "name": "TTS_PROVIDERS",+ "type": "HookSlot<TtsProviderFactory>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "voice/factory/registry_tests.rs: a_registered_tts_provider_gets_the_resolved_voice_and_returns_reply_speech"+ },+ {+ "file": "crates/openhuman-core/src/voice/live/registry.rs",+ "scope": "",+ "name": "LIVE_PROVIDERS",+ "type": "HookSlot<LiveProviderEntry>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "voice/live/registry_tests.rs: a_registered_provider_is_listed_after_the_built_in_ones"+ },+ {+ "file": "crates/openhuman-core/src/core/slots.rs",+ "scope": "",+ "name": "TEST_GLOBALS",+ "type": "std::cell::RefCell<HashMap<&'static str,Box<dyn Any>>>",+ "count": 1,+ "category": "A",+ "reason": "cfg(test) only: replaces a slot's process table with a per-thread one so a test's fake registration cannot reach a test on another thread. Not compiled into any shipped build.",+ "verification": "core/slots_tests.rs: entries_keep_registration_order_and_re_registering_keeps_position"+ },{"file": "crates/openhuman-core/src/threads/artifact_rows.rs","scope": "",@@@ -139,234 -289,14 +289,244 @@@"reason": "Keeps the one process-wide event-bus subscription that writes artifact rows alive and makes registration idempotent; it holds no data, and each event names the workspace and thread its row is written to.","verification": "threads/artifact_rows_tests.rs: recording_an_artifact_twice_writes_one_row"},+ {+ "file": "crates/openhuman-core/src/agent/tinyagents/turn_exec.rs",+ "scope": "",+ "name": "ROOT_HOSTED_HARNESS",+ "type": "LazyLock<AgentHarness<(),OpenHumanRunContext>>",+ "count": 1,+ "category": "A",+ "reason": "One unconfigured harness is process infrastructure; per-invocation models, tools, middleware, progress, and host capabilities are supplied through each invocation, so the singleton carries no tenant authority or data.",+ "verification": "agent/tinyagents/turn_exec_tests.rs: hosted_roots_share_only_an_unconfigured_process_harness"+ },+ {+ "file": "crates/openhuman-core/src/agent_registry/host_definition.rs",+ "scope": "",+ "name": "GLOBAL",+ "type": "OnceLock<Arc<AgentDefinitionRegistry>>",+ "count": 1,+ "category": "A",+ "reason": "The process registry is operator configuration in single-user hosts; SaaS startup installs built-ins only and refuses workspace or home overrides, so it cannot carry one SaaS profile's definitions into another.",+ "verification": "core/runtime/saas_tests.rs: boot_refuses_a_registry_with_workspace_definitions"+ },+ {+ "file": "crates/openhuman-core/src/agent_runs/context_breakdown.rs",+ "scope": "",+ "name": "REPORT_CACHE",+ "type": "Lazy<Mutex<HashMap<ReportCacheKey,(u64,PromptSizeReport)>>>",+ "count": 1,+ "category": "B",+ "reason": "Each cache key includes the dispatch tenant (profile and agent), requested agent id, workspace, and config path; the serialized-config fingerprint only validates freshness within that scope.",+ "verification": "agent_runs/context_breakdown_tests.rs: report_cache_key_isolated_by_tenant_even_for_identical_config"+ },+ {+ "file": "crates/openhuman-core/src/artifacts/store_documents.rs",+ "scope": "",+ "name": "TEST_OVERRIDE",+ "type": "std::cell::RefCell<Option<Docs>>",+ "count": 1,+ "category": "A",+ "reason": "This cfg(test) thread-local override substitutes an explicitly constructed in-memory document store for one test thread; it is test instrumentation and is not installed in production builds.",+ "verification": "artifacts/store_documents_tests.rs: the_store_dispatches_to_documents_when_a_backend_is_pinned"+ },+ {+ "file": "crates/openhuman-core/src/plan_review/gate.rs",+ "scope": "",+ "name": "GATE",+ "type": "OnceLock<PlanReviewGate>",+ "count": 1,+ "category": "B",+ "reason": "The process gate is infrastructure, and its waiter, parked-review, and thread lookup tables use the profile-only tenant key plus request/thread id; agent requests remain available to their profile-level UI while other profiles cannot reach them.",+ "verification": "plan_review/gate_tests.rs: parked_reviews_are_isolated_by_tenant"+ },+ {+ "file": "crates/openhuman-core/src/storage/sessions/mod.rs",+ "scope": "",+ "name": "PROVIDER",+ "type": "LazyLock<RwLock<Option<Arc<dyn SessionStoreProvider>>>>",+ "count": 1,+ "category": "D",+ "reason": "The installed provider is a routing handle to the session storage backend; callers select AgentStores with the authenticated tenant's session_key, and durable records remain in the backend.",+ "verification": "storage/sessions/mod_tests.rs: two_profiles_default_agents_keep_separate_session_keys_and_stores; threads/ops/edit_tests.rs: a_profile_prefixed_key_round_trips_through_edit_and_regenerate"+ },+ {+ "file": "crates/openhuman-core/src/storage/sessions/workspace.rs",+ "scope": "",+ "name": "FALLBACKS",+ "type": "LazyLock<Mutex<HashMap<PathBuf,Fallback>>>",+ "count": 1,+ "category": "D",+ "reason": "Each entry routes one workspace path to its storage backend and DriverSessionStores provider; returned stores still require the caller's tenant session key, while authoritative session data remains in the backend.",+ "verification": "storage/sessions/mod_tests.rs: each_workspace_keeps_its_sessions_in_its_own_database; storage/sessions/mod_tests.rs: two_profiles_default_agents_keep_separate_session_keys_and_stores; threads/ops/edit_tests.rs: a_profile_prefixed_key_round_trips_through_edit_and_regenerate"+ },+ {+ "file": "crates/openhuman-core/src/storage/sessions/workspace.rs",+ "scope": "",+ "name": "MEMORY",+ "type": "LazyLock<Mutex<HashMap<PathBuf,Arc<dyn SessionStoreProvider>>>>",+ "count": 1,+ "category": "D",+ "reason": "The in-memory provider is a workspace-keyed fallback routing handle; its AgentStores are selected with the caller's tenant session key, and an unusable workspace cannot read another workspace's provider.",+ "verification": "storage/sessions/workspace_tests.rs: an_unusable_workspace_degrades_to_an_in_memory_store; storage/sessions/mod_tests.rs: two_profiles_default_agents_keep_separate_session_keys_and_stores; threads/ops/edit_tests.rs: a_profile_prefixed_key_round_trips_through_edit_and_regenerate"+ },+ {+ "file": "crates/openhuman-core/src/triage/evaluator/chain.rs",+ "scope": "",+ "name": "TRIAGE_MONOTONIC_START",+ "type": "OnceLock<Instant>",+ "count": 1,+ "category": "A",+ "reason": "Provides one monotonic millisecond epoch for provider/model outage-breaker timestamps across all calls in the process; it stores no tenant or trigger data.",+ "verification": "triage/evaluator/chain_tests.rs: monotonic_clock_does_not_move_backwards; triage/evaluator/chain_tests.rs: only_one_initial_outage_attempt_can_be_in_flight"+ },+ {+ "file": "crates/openhuman-core/src/triage/evaluator/chain.rs",+ "scope": "",+ "name": "TRIAGE_RETRY_STATE",+ "type": "OnceLock<RetryState>",+ "count": 1,+ "category": "A",+ "reason": "This process-wide retry table stores only outage counters, timestamps, and in-flight flags keyed by provider name and model; it holds no trigger payload or tenant record, and deliberately shares provider health backoff.",+ "verification": "triage/evaluator/chain_tests.rs: only_one_initial_outage_attempt_can_be_in_flight; triage/evaluator_deferral_tests.rs: outage_state_isolated_by_model"+ },+ {+ "file": "crates/openhuman-core/src/triage/events.rs",+ "scope": "",+ "name": "TEST_EVENTS",+ "type": "std::sync::Mutex<Vec<DomainEvent>>",+ "count": 1,+ "category": "A",+ "reason": "This cfg(test)-only recorder captures trigger events emitted by unit-test fixtures so assertions can inspect helper output; it is absent from production builds and is not an application event store.",+ "verification": "triage/escalation_tests.rs: apply_decision_escalate_failure_publishes_failed_event"+ },+ {+ "file": "crates/openhuman-core/src/agent/hooks.rs",+ "scope": "",+ "name": "EMBEDDER_POST_TURN_HOOKS",+ "type": "std::sync::LazyLock<std::sync::Mutex<Vec<NamedLearningSink>>>",+ "count": 1,+ "category": "A",+ "reason": "Embedder post-turn hooks are intentionally registered process-wide as host defaults; per-agent and per-turn hooks live in CoreContext host overrides, and this registry does not store tenant identifiers or per-agent callback entries.",+ "verification": "openhuman-embed/tests/scoped_hooks.rs: hooks_are_additive_and_isolated_across_agents_turns_and_reused_ids"+ },+ {+ "file": "crates/openhuman-core/src/agent/hooks.rs",+ "scope": "",+ "name": "EMBEDDER_TOOL_HOOKS",+ "type": "std::sync::LazyLock<std::sync::Mutex<Vec<NamedToolHook>>>",+ "count": 1,+ "category": "A",+ "reason": "Embedder tool hooks are intentionally process-wide host defaults; per-agent and per-turn hooks live in CoreContext host overrides, and each invocation receives its own OpenHumanRunContext rather than registry-held tenant state.",+ "verification": "openhuman-embed/tests/scoped_hooks.rs: hooks_are_additive_and_isolated_across_agents_turns_and_reused_ids"+ },+ {- "file": "crates/openhuman-core/src/backend/telemetry/langfuse/environment.rs",++ "file": "crates/openhuman-core/src/core/observability/telemetry/langfuse/environment.rs",+ "scope": "",+ "name": "SKIP_LOGGED",+ "type": "std::sync::Once",+ "count": 1,+ "category": "A",+ "reason": "This process-wide latch suppresses duplicate informational messages when Langfuse pushes are disabled for an environment; it stores no request, credential, or tenant data.",- "verification": "backend/telemetry/langfuse/environment.rs: skip_push calls Once::call_once"++ "verification": "core/observability/telemetry/langfuse/environment.rs: skip_push calls Once::call_once"+ },+ {+ "file": "crates/openhuman-core/src/hooks/host.rs",+ "scope": "",+ "name": "ENGINE",+ "type": "LazyLock<Arc<HookEngine>>",+ "count": 1,+ "category": "A",+ "reason": "The command-hook engine is process-wide configuration and infrastructure shared by runtimes; per-call execution receives a DispatchCtx, while no tenant data is retained in the engine handle.",+ "verification": "hooks/README.md: configured command HookEngine is installed for the process"+ },+ {+ "file": "crates/openhuman-core/src/prompts/section_renderers.rs",+ "scope": "",+ "name": "EMPTY_TOOLS",+ "type": "&[PromptTool<'static>]",+ "count": 1,+ "category": "A",+ "reason": "This immutable empty slice is a construction sentinel for a static safety-section PromptContext; it carries no prompt or tenant data.",+ "verification": "agent/prompts/mod_tests_tools_sections_tests.rs: tools_section_empty_for_native"+ },+ {+ "file": "crates/openhuman-core/src/prompts/section_renderers.rs",+ "scope": "",+ "name": "EMPTY_WORKFLOWS",+ "type": "&[tinyskills::Skill]",+ "count": 1,+ "category": "A",+ "reason": "This immutable empty slice is a construction sentinel for a static safety-section PromptContext; it carries no workflow or tenant data.",+ "verification": "agent/prompts/mod_tests_builder_sections_tests.rs: prompt_builder_assembles_sections"+ },+ {+ "file": "crates/openhuman-core/src/prompts/section_renderers.rs",+ "scope": "",+ "name": "EMPTY_INTEGRATIONS",+ "type": "&[ConnectedIntegration]",+ "count": 1,+ "category": "A",+ "reason": "This immutable empty slice is a construction sentinel for a static safety-section PromptContext; it carries no integration or tenant data.",+ "verification": "agent/prompts/mod_tests_builder_sections_tests.rs: prompt_builder_assembles_sections"+ },+ {+ "file": "crates/openhuman-core/src/prompts/section_renderers.rs",+ "scope": "",+ "name": "EMPTY_VISIBLE",+ "type": "OnceLock<std::collections::HashSet<String>>",+ "count": 1,+ "category": "A",+ "reason": "This once-initialized empty set is the immutable visibility sentinel used by the static safety-section PromptContext; no agent or tenant-specific tool names are inserted.",+ "verification": "agent/prompts/mod_tests_tools_sections_tests.rs: tools_section_empty_for_native"+ },+ {+ "file": "crates/openhuman-core/src/agent/orchestration/background_completions/store_adapter.rs",+ "scope": "",+ "name": "POOL",+ "type": "OnceLock<CompletionRouterPool<RouterScope>>",+ "count": 1,+ "category": "D",+ "reason": "This process-local router cache is keyed by RouterScope (authenticated profile key plus workspace path); each router retains the matching driver's storage scope, and storage opens run under that explicit context.",+ "verification": "agent/orchestration/background_completions_tenant_tests.rs: explicit_profiles_share_a_workspace_without_sharing_completion_routers"+ },+ {+ "file": "crates/openhuman-core/src/agent/orchestration/background_completions/store_adapter.rs",+ "scope": "",+ "name": "STORES",+ "type": "OnceLock<Mutex<HashMap<RouterScope,Arc<dyn CompletionStore>>>>",+ "count": 1,+ "category": "B",+ "reason": "Test-only store overrides use the same profile-and-workspace RouterScope key as the production router cache, so test fixtures cannot cross profile or workspace boundaries.",+ "verification": "agent/orchestration/background_completions_migration_tests.rs: reopening_a_durable_store_preserves_pending_memory_fallback_records"+ },+ {+ "file": "crates/openhuman-core/src/agent/orchestration/background_delivery.rs",+ "scope": "",+ "name": "LEASES",+ "type": "OnceLock<ThreadDeliveryLeases>",+ "count": 1,+ "category": "B",+ "reason": "Each in-flight delivery lease key combines the calling profile key with its thread id; it stores only active per-thread exclusion keys and no completion contents.",+ "verification": "agent/orchestration/background_delivery_slots_tests.rs: one_profiles_busy_turn_does_not_block_anothers_thread"+ },+ {+ "file": "crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs",+ "scope": "",+ "name": "SUPERVISOR",+ "type": "OnceLock<WorkflowRunSupervisor>",+ "count": 1,+ "category": "D",+ "reason": "The process-local supervisor holds generation cancellation handles keyed by run id, not durable workflow state or tenant data. Durable run transitions remain fenced by the storage driver's revision and lease checks.",+ "verification": "agent/orchestration/workflow_runs/engine/lifecycle_tests.rs: losing_resume_cas_keeps_the_installed_workflow_generation"++ },+ {+ "file": "crates/openhuman-core/src/mcp/host_cleanup.rs",+ "scope": "",+ "name": "CLIENTS",+ "type": "OnceLock<ClientTable<CleanupClient>>",+ "count": 1,+ "category": "B",+ "reason": "The canonical TinyMCP client table is keyed by the resolved agent directory. Host completion and exact-client eviction preserve the same directory fence across close and purge; no runtime guard is retained in the table.",+ "verification": "mcp/module_client_owner_tests.rs: orphaned_shutdown_cleanup_keeps_a_host_directory_reservation_until_confirmed; mcp/module_client/cleanup_tests.rs: a_pending_close_fences_the_folder_under_another_spelling"}]diff --cc scripts/ci/saas-ambient-baseline.jsonindex 6c9dfffdc7,9f15f1ccf0..3a265ddaba--- a/scripts/ci/saas-ambient-baseline.json+++ b/scripts/ci/saas-ambient-baseline.json@@@ -20,18 -20,18 +20,11 @@@"text": "crate::core::runtime::CoreContext::current()","occurrence": 1},-- {-- "rule": "bare-spawn",-- "path": "crates/openhuman-core/src/agent/hooks.rs",- "line": 343,- "line": 355,-- "text": "tokio::spawn(async move {",-- "occurrence": 1-- },{"rule": "bare-spawn","path": "crates/openhuman-core/src/agent/orchestration/ops.rs","line": 416,-- "text": "let handle = tokio::spawn(crate::agent::turn_origin::propagate(async move {",++ "text": "let handle = tokio::spawn(crate::security::turn_origin::propagate(async move {","occurrence": 1},{@@@ -85,7 -99,7 +78,7 @@@},{"rule": "bare-spawn",-- "path": "crates/openhuman-core/src/agent/turn_origin.rs",++ "path": "crates/openhuman-core/src/security/turn_origin.rs","line": 356,"text": "tokio::spawn(propagate(fut))","occurrence": 1diff --cc scripts/ci/storage-bypass-allow-reasons.jsonindex 0000000000,08ea361f25..1f21dd3c98mode 000000,100644..100644--- a/scripts/ci/storage-bypass-allow-reasons.json+++ b/scripts/ci/storage-bypass-allow-reasons.json@@@ -1,0 -1,121 +1,121 @@@+ [+ {+ "path": "crates/openhuman-core/src/config/schema/profile_layout.rs",+ "rule": "json-write",+ "site": "std::fs::write(dir.join(PROFILE_LAYOUT_MARKER), \"2\\n\")",+ "reason": "bootstrap marker that says which on-disk layout a profile directory is; it must be readable before any storage backend can be opened (it decides where the backend lives)",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7428"+ },+ {+ "path": "crates/openhuman-core/src/util/classic_transcript_fixture.rs",+ "rule": "json-write",+ "site": "std::fs::write(path, classic_jsonl(messages, meta)).expect(\"write the classic transcript\");",+ "reason": "test-only fixture (compiled under cfg(test)) that writes a retired-layout `session_raw/*.jsonl` file for the importer and rewrite tests; no store reads it back",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7434"+ },+ {+ "path": "crates/openhuman-core/src/security/approval/store_import.rs",+ "rule": "sqlite-open",+ "site": "let conn = Connection::open(&db_path).with_context(|| {",+ "reason": "the storage importer's read-only reader of a legacy database, opened on a scratch copy of it (never the real file) to bring older installs' rows into the backend",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7434"+ },+ {+ "path": "crates/openhuman-core/src/security/devices/store_import.rs",+ "rule": "sqlite-open",+ "site": "let conn = Connection::open(&db_path)",+ "reason": "the storage importer's read-only reader of a legacy database, opened on a scratch copy of it (never the real file) to bring older installs' rows into the backend",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7434"+ },+ {+ "path": "crates/openhuman-core/src/desktop/notifications/store_import.rs",+ "rule": "sqlite-open",+ "site": "let conn = Connection::open(&db_path).with_context(|| {",+ "reason": "the storage importer's read-only reader of a legacy database, opened on a scratch copy of it (never the real file) to bring older installs' rows into the backend",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7434"+ },+ {+ "path": "crates/openhuman-core/src/integrations/task_sources/store_import.rs",+ "rule": "sqlite-open",+ "site": "let mut conn = Connection::open(&db_path)",+ "reason": "the storage importer's read-only reader of a legacy database, opened on a scratch copy of it (never the real file) to bring older installs' rows into the backend",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7433"+ },+ {+ "path": "crates/openhuman-core/src/modules/storage_import_tinymcp.rs",+ "rule": "sqlite-open",+ "site": "Connection::open_with_flags(©, OpenFlags::SQLITE_OPEN_READ_WRITE)",+ "reason": "the storage importer's read-only reader of a legacy database, opened on a scratch copy of it (never the real file) to bring older installs' rows into the backend",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7430"+ },+ {+ "path": "crates/openhuman-core/src/config/workspace/state.rs",+ "rule": "sqlite-open",+ "site": "let conn = Connection::open(db_path)?;",+ "reason": "vault watcher state is absolute local paths and their mtimes: per-machine filesystem state that is meaningless on, and must not be shared through, another host's database",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7434"+ },+ {+ "path": "crates/openhuman-core/src/desktop/control/ops.rs",+ "rule": "json-write",+ "site": "let mut temporary = tempfile::NamedTempFile::new_in(parent)",+ "reason": "this machine's own consent to drive its desktop: per-machine, and it must fail closed rather than follow a shared backend to another host",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7434"+ },+ {+ "path": "crates/openhuman-core/src/desktop/app_state/ops/state_file.rs",+ "rule": "json-write",+ "site": "let mut temp_file = NamedTempFile::new_in(parent)",+ "reason": "holds the local encryption key and keyring consent, which are needed before any storage backend is open (bootstrap state is never read from storage)",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7428"+ },+ {+ "path": "crates/openhuman-core/src/web3/wallet/ops/state.rs",+ "rule": "json-write",+ "site": "let mut temp_file = NamedTempFile::new_in(parent)",+ "reason": "paired with the OS keychain mnemonic (and holds it when there is no keychain): moves with the secrets work, not as a plain document",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7430"+ },+ {+ "path": "crates/openhuman-core/src/agent/harness/artifact_offload/mod.rs",+ "rule": "json-write",+ "site": "tokio::fs::write(&target, body)",+ "reason": "a derived view of a blob-stored artifact, placed in the action dir so file_read can open the path a pointer hands back; the tenant's blob store stays the source of truth",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ },+ {+ "path": "crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs",+ "rule": "json-write",+ "site": "tokio::fs::write(&target, body).await?;",+ "reason": "a derived view of a blob-stored tool-result artifact, written under the workspace's read-only artifacts root so file_read can open the key a pointer hands back; re-derived from the tenant's blob store on every read, which stays the source of truth",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ },+ {+ "path": "crates/openhuman-core/src/modules/browser_task_report.rs",+ "rule": "json-write",+ "site": "let mut options = tokio::fs::OpenOptions::new();",+ "reason": "opt-in debug trace (`[computer] trace`): the module's full task report, written as a file beside the module's own traces in the same trace directory so a person can open both; page text stays in a file only its owner can read and no store reads it back",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7434"+ },+ {- "path": "crates/openhuman-core/src/agent/artifacts/files.rs",++ "path": "crates/openhuman-core/src/artifacts/files.rs",+ "rule": "json-write",+ "site": "match tokio::fs::OpenOptions::new()",+ "reason": "Historical local artifact content reservation; a native BlobStore now exists, so this is migration debt, not a missing blob capability.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ },+ {- "path": "crates/openhuman-core/src/agent/artifacts/tiny_store.rs",++ "path": "crates/openhuman-core/src/artifacts/tiny_store.rs",+ "rule": "json-write",+ "site": "tokio::fs::write(&dest, latest.body.as_bytes()).await?;",+ "reason": "writes a text artifact's newest version into its file in the user-visible files folder; the deliverable is a user file on every backend, the versioned record itself goes through the artifact store",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ },+ {+ "path": "crates/openhuman-core/src/media/generation/artifact_tool.rs",+ "rule": "json-write",+ "site": "let mut file = tokio::fs::OpenOptions::new()",+ "reason": "User-visible artifact content is retained as a local deliverable; versioned records and native blob storage are separate capabilities and this file does not establish shared storage authority.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ }+ ]diff --cc scripts/ci/storage-bypass-debt.mjsindex 0000000000,8fdf0af8b0..6fb2f1b61cmode 000000,100644..100644--- a/scripts/ci/storage-bypass-debt.mjs+++ b/scripts/ci/storage-bypass-debt.mjs@@@ -1,0 -1,188 +1,207 @@@+ import { execFileSync } from "node:child_process";++ const CORE = "crates/openhuman-core/src/";+ const BASELINE = "scripts/ci/storage-bypass-baseline.json";+ const EXTENSION = "scripts/ci/storage-bypass-extension.json";+ const key = (x) => JSON.stringify([x.rule, x.path, x.text, x.occurrence]);+ const original = (x) =>+ x.path.startsWith(CORE) && ["sqlite-open", "json-write"].includes(x.rule);++ /** Exact existing-debt records never authorize another site or later growth. */+ export function validateCoverageDebt(findings, baseline, extension, history) {+ if (!Array.isArray(baseline) || !Array.isArray(extension))+ return ["Storage debt manifests must be arrays"];+ const errors = [];+ const actual = new Set(findings.map(key));+ const seen = new Set();+ const coreSeen = new Set();+ for (const record of baseline) {+ const id = key(record);+ if (coreSeen.has(id))+ errors.push("Duplicate core baseline record: " + record.path);+ coreSeen.add(id);+ if (!original(record))+ errors.push(+ `Core baseline cannot accept extended coverage: ${record.path}`,+ );+ }+ for (const record of extension) {+ const id = key(record);+ if (seen.has(id)) errors.push(`Duplicate extension record: ${record.path}`);+ seen.add(id);+ if (original(record))+ errors.push(+ `Extension cannot conceal original core debt: ${record.path}`,+ );+ if (!actual.has(id))+ errors.push(`Stale extension record: ${record.path}: ${record.text}`);+ if (+ ![+ "classic",+ "machine",+ "scratch",+ "external-export",+ "read-only",+ "unmigrated",+ ].includes(record.classification) ||+ typeof record.reason !== "string" ||+ record.reason.trim().length < 20 ||+ !/^https:\/\/github\.com\/tinyhumansai\/openhuman\/issues\/\d+$/.test(+ record.issue ?? "",+ )+ ) {+ errors.push(`Incomplete audited extension record: ${record.path}`);+ }+ }+ if (history) {+ const oldCore = new Set(history.baseline.map(key));+ for (const record of baseline)+ if (!oldCore.has(key(record)))+ errors.push(+ `Core baseline growth forbidden: ${record.path}: ${record.text}`,+ );+ const oldExtension =+ history.extension === null ? null : new Set(history.extension.map(key));+ const oldSites = new Set(history.findings.map(key));+ for (const record of extension) {+ if (oldExtension && !oldExtension.has(key(record)))+ errors.push(+ `Extension growth forbidden: ${record.path}: ${record.text}`,+ );+ if (!oldExtension && !oldSites.has(key(record)))+ errors.push(+ `Initial extension cannot approve a branch-added writer: ${record.path}: ${record.text}`,+ );+ }+ }+ return errors;+ }++ /** Re-scan canonical merge-base source, including the recorded curated gitlinks. */+ export function historicalFindings(root, scanner) {+ const git = (args, cwd = root) =>+ execFileSync("git", args, {+ cwd,+ encoding: "utf8",+ stdio: ["ignore", "pipe", "pipe"],+ });+ let ref = process.env.GITHUB_BASE_REF+ ? `origin/${process.env.GITHUB_BASE_REF}`+ : "upstream/main";+ if (!process.env.GITHUB_BASE_REF) {+ try {+ git(["rev-parse", "--verify", ref]);+ } catch {+ ref = "origin/main";+ }+ }+ const base = git(["merge-base", ref, "HEAD"]).trim();++ // Git must identify a rename (the original path disappears). Copies and++ // new files retain their own identity. Only the path changes: exact writer++ // text and occurrence remain part of every debt/allowance key.++ const changes = git([++ "diff", "--name-status", "-z", "--find-renames=50%", base, "--", "crates",++ ]).split("\0");++ const renamed = new Map();++ for (let at = 0; at < changes.length && changes[at];) {++ const status = changes[at++];++ const from = changes[at++];++ if (/^[RC]/.test(status)) {++ const to = changes[at++];++ if (status.startsWith("R")) renamed.set(from, to);++ }++ }++ const relocated = (record) => renamed.has(record.path)++ ? { ...record, path: renamed.get(record.path) }++ : record;+ const files = git([+ "ls-tree",+ "-r",+ "-z",+ "--name-only",+ base,+ "--",+ "crates",+ ])+ .split("\0")+ .filter((p) => /^crates\/[^/]+\/src\/.*\.rs$/.test(p));+ const findings = [];+ const rawFindings = [];+ const add = (path, source) => {+ if (!scanner.isTestFile(path)) {- const raw = scanner.scan(path, source);++ const destination = renamed.get(path) ?? path;++ const raw = scanner.scan(destination, source);+ rawFindings.push(...raw);- findings.push(...scanner.withoutAllowed(path, raw));++ findings.push(...scanner.withoutAllowed(destination, raw));+ }+ };+ for (const file of files) add(file, git(["show", `${base}:${file}`]));+ for (const directory of scanner.CURATED_VENDOR_ROOTS) {+ const parts = directory.split("/");+ const module = parts.slice(0, 2).join("/");+ const inside = parts.slice(2).join("/");+ const entry = git(["ls-tree", base, "--", module]);+ const commit = /^160000 commit ([a-f0-9]{40})\t/.exec(entry)?.[1];+ if (!commit) throw new Error(`Missing canonical gitlink for ${module}`);+ const cwd = `${root}/${module}`;+ const names = git(+ ["ls-tree", "-r", "-z", "--name-only", commit, "--", inside],+ cwd,+ )+ .split("\0")+ .filter((p) => p.endsWith(".rs"));+ for (const file of names)+ add(`${module}/${file}`, git(["show", `${commit}:${file}`], cwd));+ }+ const json = (path, optional = false) => {+ if (!git(["ls-tree", "--name-only", base, "--", path]).trim()) {+ if (optional) return null;+ throw new Error(`Canonical baseline missing: ${path}`);+ }+ const value = JSON.parse(git(["show", `${base}:${path}`]));+ if (!Array.isArray(value))+ throw new Error(`Canonical manifest must be an array: ${path}`);- return value;++ return value.map(relocated);+ };+ return {+ base,+ findings,+ rawFindings,+ baseline: json(BASELINE),+ extension: json(EXTENSION, true),+ allowances: json("scripts/ci/storage-bypass-allow-reasons.json", true),+ };+ }++ /** Initial audited exclusions must exist in canonical source; later exclusions cannot grow. */+ export function validateAllowances(raw, records, history) {+ const errors = [];+ const current = new Set(raw.map(key));+ const oldSites = history ? new Set(history.rawFindings.map(key)) : null;+ const oldRecords =+ history?.allowances === null+ ? null+ : history+ ? new Set(+ history.allowances.map((x) =>+ key({ ...x, text: x.site, occurrence: 1 }),+ ),+ )+ : null;+ const seen = new Set();+ for (const record of records) {+ const id = key({ ...record, text: record.site, occurrence: 1 });+ if (seen.has(id))+ errors.push(`Duplicate audited allowance: ${record.path}`);+ seen.add(id);+ if (!current.has(id))+ errors.push(`Stale audited allowance: ${record.path}: ${record.site}`);+ if (oldRecords && !oldRecords.has(id))+ errors.push(`Audited allowance growth forbidden: ${record.path}`);+ if (history && !oldRecords && !oldSites.has(id))+ errors.push(+ `Initial allowance cannot approve a branch-added writer: ${record.path}`,+ );+ }+ return errors;+ }diff --cc scripts/ci/storage-bypass-extension.jsonindex 0000000000,bdf9293419..547ece7783mode 000000,100644..100644--- a/scripts/ci/storage-bypass-extension.json+++ b/scripts/ci/storage-bypass-extension.json@@@ -1,0 -1,672 +1,672 @@@+ [+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-app/src/artifact_commands.rs",+ "line": 41,+ "text": "tokio::fs::copy(source, dest)",+ "occurrence": 1,+ "classification": "external-export",+ "reason": "Explicit user-selected artifact export copies bytes to an external destination; native stored artifact content and export admission are separate.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ },+ {+ "rule": "json-write",+ "path": "crates/openhuman-app/src/core_process.rs",+ "line": 269,+ "text": "let mut options = std::fs::OpenOptions::new();",+ "occurrence": 1,+ "classification": "machine",+ "reason": "Debug-only owner-restricted per-launch RPC token file used by the local E2E host; not signed-in user state.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7432"+ },+ {+ "rule": "json-write",+ "path": "crates/openhuman-app/src/gateway/store.rs",+ "line": 155,+ "text": "let mut options = std::fs::OpenOptions::new();",+ "occurrence": 1,+ "classification": "machine",+ "reason": "Saved remote gateway endpoint and local SSH identity/bearer selection belong to the desktop host connection bootstrap; credentials must not become plain shared documents.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7432"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-app/src/gateway/store.rs",+ "line": 165,+ "text": "std::fs::rename(&temp_path, &path)?;",+ "occurrence": 1,+ "classification": "machine",+ "reason": "Saved remote gateway endpoint and local SSH identity/bearer selection belong to the desktop host connection bootstrap; credentials must not become plain shared documents.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7432"+ },+ {+ "rule": "sqlite-open",+ "path": "crates/openhuman-app/src/imessage_scanner/chatdb.rs",+ "line": 37,+ "text": "Connection::open_with_flags(",+ "occurrence": 1,+ "classification": "read-only",+ "reason": "Apple chat.db is explicitly opened SQLITE_OPEN_READ_ONLY; the external machine source is read, not an OpenHuman durable store.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7434"+ },+ {+ "rule": "json-write",+ "path": "crates/openhuman-app/src/imessage_scanner/mod.rs",+ "line": 272,+ "text": "std::fs::write(path, rowid.to_string())",+ "occurrence": 1,+ "classification": "machine",+ "reason": "The last seen Apple chat.db ROWID cursor belongs to this machine source and cannot identify another host database.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7434"+ },+ {+ "rule": "json-write",+ "path": "crates/openhuman-app/src/mcp_commands.rs",+ "line": 238,+ "text": "std::fs::write(&path, b\"{}\")",+ "occurrence": 1,+ "classification": "external-export",+ "reason": "Explicitly creates an external installed MCP client configuration for the operating-system editor; not an OpenHuman authoritative store.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7430"+ },+ {+ "rule": "json-write",+ "path": "crates/openhuman-app/src/window_state.rs",+ "line": 144,+ "text": "if let Err(err) = std::fs::write(&path, raw) {",+ "occurrence": 1,+ "classification": "machine",+ "reason": "Window position and size reflect this machine display geometry, not cloud user state.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7434"+ },+ {+ "rule": "json-write",+ "path": "crates/openhuman-cli/src/bin/fleet.rs",+ "line": 522,+ "text": "let mut file = std::fs::OpenOptions::new()",+ "occurrence": 1,+ "classification": "external-export",+ "reason": "Explicit owner-only output of minted edge tokens to the requested fleet operator destination; not an internal user state store.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7432"+ },+ {+ "rule": "file-mutation",- "path": "crates/openhuman-core/src/agent/artifacts/migrate.rs",++ "path": "crates/openhuman-core/src/artifacts/migrate.rs",+ "line": 183,+ "text": "tokio::fs::copy(src, &partial)",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Historical artifact/attachment file publication or source-preserving import; native BlobStore availability does not authorize local historical source ownership.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ },+ {+ "rule": "file-mutation",- "path": "crates/openhuman-core/src/agent/artifacts/migrate.rs",++ "path": "crates/openhuman-core/src/artifacts/migrate.rs",+ "line": 206,+ "text": "if let Err(e) = tokio::fs::rename(&partial, &target).await {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Historical artifact/attachment file publication or source-preserving import; native BlobStore availability does not authorize local historical source ownership.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ },+ {+ "rule": "file-mutation",- "path": "crates/openhuman-core/src/agent/artifacts/tiny_store.rs",++ "path": "crates/openhuman-core/src/artifacts/tiny_store.rs",+ "line": 146,+ "text": "tokio::fs::copy(source, owned).await?",+ "occurrence": 1,+ "classification": "external-export",+ "reason": "Materializes versioned artifact bytes in the user-visible artifact file; the versioned record and native blob storage remain separate from this local deliverable.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ },+ {+ "rule": "file-mutation",- "path": "crates/openhuman-core/src/agent/artifacts/tiny_store.rs",++ "path": "crates/openhuman-core/src/artifacts/tiny_store.rs",+ "line": 180,+ "text": "tokio::fs::copy(&source, &dest).await?",+ "occurrence": 1,+ "classification": "external-export",+ "reason": "Materializes versioned artifact bytes in the user-visible artifact file; the versioned record and native blob storage remain separate from this local deliverable.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ },+ {+ "rule": "file-mutation",- "path": "crates/openhuman-core/src/agent/attachments/legacy.rs",++ "path": "crates/openhuman-core/src/attachments/legacy.rs",+ "line": 156,+ "text": "let linked = tokio::fs::hard_link(&temp, &path).await;",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Historical artifact/attachment file publication or source-preserving import; native BlobStore availability does not authorize local historical source ownership.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ },+ {+ "rule": "file-mutation",- "path": "crates/openhuman-core/src/agent/attachments/provider_cache.rs",++ "path": "crates/openhuman-core/src/attachments/provider_cache.rs",+ "line": 173,+ "text": "tokio::fs::rename(&temp, cache).await",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Historical artifact/attachment file publication or source-preserving import; native BlobStore availability does not authorize local historical source ownership.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ },+ {+ "rule": "file-mutation",- "path": "crates/openhuman-core/src/agent/attachments/provider_source.rs",++ "path": "crates/openhuman-core/src/attachments/provider_source.rs",+ "line": 245,+ "text": "let linked = tokio::fs::hard_link(&temp, &path).await;",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Historical artifact/attachment file publication or source-preserving import; native BlobStore availability does not authorize local historical source ownership.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/config/schema/load/atomic_commit.rs",+ "line": 44,+ "text": "let replace = fs::rename(temp_path, config_path).await;",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Classic configuration atomic publication/backup/recovery helper; native document loading must avoid entering this filesystem path.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7428"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/config/schema/load/atomic_commit.rs",+ "line": 57,+ "text": "fs::rename(temp_path, config_path).await",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Classic configuration atomic publication/backup/recovery helper; native document loading must avoid entering this filesystem path.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7428"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/config/schema/load/atomic_commit.rs",+ "line": 163,+ "text": "if fs::copy(config_path, backup_path).await.is_err() {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Classic configuration atomic publication/backup/recovery helper; native document loading must avoid entering this filesystem path.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7428"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/config/schema/load/branches.rs",+ "line": 203,+ "text": "match fs::rename(&config_path, &corrupted_path).await {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Classic configuration atomic publication/backup/recovery helper; native document loading must avoid entering this filesystem path.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7428"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/config/schema/load/impl_load.rs",+ "line": 107,+ "text": "if let Err(rename_err) = std::fs::rename(config_path, &corrupted_path) {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Classic configuration atomic publication/backup/recovery helper; native document loading must avoid entering this filesystem path.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7428"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/config/schema/load_user_state.rs",+ "line": 193,+ "text": "if let Err(error) = std::fs::rename(&temp_path, &path) {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Classic configuration atomic publication/backup/recovery helper; native document loading must avoid entering this filesystem path.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7428"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/desktop/app_state/ops/state_file.rs",+ "line": 55,+ "text": "if let Err(rename_error) = fs::rename(path, &quarantine_path) {",+ "occurrence": 1,+ "classification": "machine",+ "reason": "Local bootstrap state quarantine publication; user preferences and accessibility/key bootstrap require separate authority.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7428"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/desktop/control/ops.rs",+ "line": 157,+ "text": "serde_json::to_writer(&mut temporary, &LocalState { enabled: value })",+ "occurrence": 1,+ "classification": "machine",+ "reason": "Serialization of this machine desktop-control consent into its local temporary file; consent must not follow another host backend.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7432"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/media/generation/artifact_tool.rs",+ "line": 473,+ "text": "if tokio::fs::rename(src, dest).await.is_err() {",+ "occurrence": 1,+ "classification": "scratch",+ "reason": "Generated tool-output relocation between temporary native-tool paths before publication; authoritative artifact capture remains a separate host boundary.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/media/generation/artifact_tool.rs",+ "line": 474,+ "text": "tokio::fs::copy(src, dest).await.map_err(|e| {",+ "occurrence": 1,+ "classification": "scratch",+ "reason": "Generated tool-output relocation between temporary native-tool paths before publication; authoritative artifact capture remains a separate host boundary.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ },+ {+ "rule": "file-store-new",+ "path": "crates/openhuman-core/src/memory/import.rs",+ "line": 99,+ "text": "FileCheckpointStore::new(workspace_dir).load()",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Legacy memory import checkpoint adapter reads and saves resume, error and credit-pause bookkeeping through the existing host state store; this constructor is not proof of native migration authority.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7427"+ },+ {+ "rule": "file-store-new",+ "path": "crates/openhuman-core/src/memory/import.rs",+ "line": 122,+ "text": "Arc::new(FileCheckpointStore::new(&config.workspace_dir)),",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Legacy memory import checkpoint adapter reads and saves resume, error and credit-pause bookkeeping through the existing host state store; this constructor is not proof of native migration authority.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7427"+ },+ {+ "rule": "file-store-new",+ "path": "crates/openhuman-core/src/memory/import.rs",+ "line": 265,+ "text": "let store = FileCheckpointStore::new(&config.workspace_dir);",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Legacy memory import checkpoint adapter reads and saves resume, error and credit-pause bookkeeping through the existing host state store; this constructor is not proof of native migration authority.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7427"+ },+ {+ "rule": "file-store-new",+ "path": "crates/openhuman-core/src/memory/layout_migration/app_host.rs",+ "line": 28,+ "text": "let store = FileStateStore::new(&config.workspace_dir);",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Legacy memory layout migration host retains its checkpoint and claim state through the existing file-state adapter; engine migration and checkpoint routing are separate obligations.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7427"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/memory/layout_migration/claim.rs",+ "line": 111,+ "text": "serde_json::to_writer(temp.as_file(), &marker).map_err(std::io::Error::other)?;",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Legacy memory layout migration claim/state marker publication; historical source capture and native migration admission remain separate.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7427"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/memory/layout_migration/claim.rs",+ "line": 114,+ "text": "std::fs::hard_link(temp.path(), &key.marker)",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Legacy memory layout migration claim/state marker publication; historical source capture and native migration admission remain separate.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7427"+ },+ {+ "rule": "file-store-new",+ "path": "crates/openhuman-core/src/memory/layout_migration/test_host.rs",+ "line": 50,+ "text": "store: FileStateStore::new(&config.workspace_dir),",+ "occurrence": 1,+ "classification": "scratch",+ "reason": "Test-only layout migration host, wired under cfg(test), instantiates the file-state fixture for migration controls; it is not a product storage route.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7427"+ },+ {+ "rule": "writer-helper",+ "path": "crates/openhuman-core/src/modules/browser_task_report.rs",+ "line": 297,+ "text": "async fn write_private(path: &Path, report: &TaskReport) -> std::io::Result<usize> {",+ "occurrence": 1,+ "classification": "unmigrated",+ "reason": "Canonical browser site/report local publication helper; native scoped store selection requires its owning migration and trusted historical source admission.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7431"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/modules/storage_import_tinymcp.rs",+ "line": 214,+ "text": "std::fs::copy(path, ©).with_context(|| format!(\"copy {}\", path.display()))?;",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Source-preserving legacy MCP SQLite import copies the database and WAL companion into scratch storage before opening the copy; durable imported records are written through the module storage contract.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7430"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/modules/storage_import_tinymcp.rs",+ "line": 222,+ "text": "std::fs::copy(&companion, PathBuf::from(target))",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Source-preserving legacy MCP SQLite import copies the database and WAL companion into scratch storage before opening the copy; durable imported records are written through the module storage contract.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7430"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/platform/cost/tracker.rs",+ "line": 402,+ "text": "if let Err(error) = fs::rename(&legacy_path, &storage_path) {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Historical cost snapshot relocation/quarantine used by the classic/import path; native document accounting is a separate API.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7431"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/platform/cost/tracker.rs",+ "line": 408,+ "text": "fs::copy(&legacy_path, &storage_path).with_context(|| {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Historical cost snapshot relocation/quarantine used by the classic/import path; native document accounting is a separate API.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7431"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/platform/cost/tracker_documents.rs",+ "line": 189,+ "text": "match std::fs::rename(path, &target) {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Historical cost snapshot relocation/quarantine used by the classic/import path; native document accounting is a separate API.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7431"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/platform/update/core.rs",+ "line": 164,+ "text": "std::fs::rename(tmp, dest).map_err(|e| {",+ "occurrence": 1,+ "classification": "machine",+ "reason": "Downloaded executable update atomically replaces the local installed binary; deployment artifact is not tenant state.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7434"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/profiles/lifecycle.rs",+ "line": 190,+ "text": "std::fs::rename(&layout.dir, &dest)",+ "occurrence": 1,+ "classification": "machine",+ "reason": "Desktop profile directory archive/rollback lifecycle operation; backend purge and ownership/drain authority are separate.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7432"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/profiles/lifecycle.rs",+ "line": 198,+ "text": "if let Err(e) = std::fs::rename(&dest, &layout.dir) {",+ "occurrence": 1,+ "classification": "machine",+ "reason": "Desktop profile directory archive/rollback lifecycle operation; backend purge and ownership/drain authority are separate.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7432"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/security/audit.rs",+ "line": 330,+ "text": "let _ = std::fs::rename(&old_name, &new_name);",+ "occurrence": 1,+ "classification": "unmigrated",+ "reason": "Canonical security audit file rotation; native scoped stream migration must retain captured producer authority.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7431"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/security/audit.rs",+ "line": 334,+ "text": "std::fs::rename(&self.log_path, &rotated)?;",+ "occurrence": 1,+ "classification": "unmigrated",+ "reason": "Canonical security audit file rotation; native scoped stream migration must retain captured producer authority.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7431"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/security/credentials/http_creds.rs",+ "line": 426,+ "text": "if let Err(e) = fs::rename(&tmp_path, &self.path) {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Historical encrypted credential persistence/quarantine publication; native secret port and trusted source/key ownership are separate.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7421"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/security/credentials/profiles.rs",+ "line": 577,+ "text": "fs::rename(path, &candidate).with_context(|| {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Historical encrypted credential persistence/quarantine publication; native secret port and trusted source/key ownership are separate.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7421"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/security/credentials/profiles/persistence.rs",+ "line": 277,+ "text": "fs::rename(&tmp_path, &self.path).context(\"rename auth profile tmp -> store\")",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Classic encrypted credential profile fallback persists AuthProfilesData and token fields; native SecretStore routing requires trusted machine key and source admission, not directory rollback authority.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7421"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/security/secret_storage/encrypted_file_backend.rs",+ "line": 580,+ "text": "std::fs::rename(legacy_path, &archive_path)",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Historical encrypted credential persistence/quarantine publication; native secret port and trusted source/key ownership are separate.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7421"+ },+ {+ "rule": "writer-helper",+ "path": "crates/openhuman-core/src/security/secret_storage/file_store.rs",+ "line": 201,+ "text": "pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), SecretStorageError> {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Owner-only atomic encrypted-secret/bootstrap file helper; native SecretStore and machine master-key policy have separate admission.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7421"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/security/secret_storage/file_store.rs",+ "line": 316,+ "text": "std::fs::rename(source, destination)?;",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Owner-only atomic encrypted-secret/bootstrap file helper; native SecretStore and machine master-key policy have separate admission.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7421"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/security/secret_storage/file_store.rs",+ "line": 406,+ "text": "match std::fs::hard_link(path, &target) {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Owner-only atomic encrypted-secret/bootstrap file helper; native SecretStore and machine master-key policy have separate admission.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7421"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/security/secret_storage/file_store.rs",+ "line": 433,+ "text": "return match std::fs::rename(path, &target) {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Owner-only atomic encrypted-secret/bootstrap file helper; native SecretStore and machine master-key policy have separate admission.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7421"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/threads/welcome_migration.rs",+ "line": 310,+ "text": "fs::rename(path, destination).map_err(|e| {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Explicit legacy welcome-thread file relocation; native thread metadata/streams do not grant historical import ownership.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7424"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/threads/welcome_migration.rs",+ "line": 366,+ "text": "if let Err(err) = fs::rename(&old_path, &new_path) {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Explicit legacy welcome-thread file relocation; native thread metadata/streams do not grant historical import ownership.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7424"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/tinymemes/docs.rs",+ "line": 81,+ "text": "match std::fs::rename(&path, &migrated) {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Retires the legacy JSON document by renaming it only after the native document-port write succeeds; the native document remains authoritative after adoption.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7431"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-core/src/web3/wallet/ops/state.rs",+ "line": 156,+ "text": "if let Err(rename_error) = fs::rename(path, &quarantine_path) {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Classic wallet state quarantine coupled to local keychain secrets; not eligible for plain-document relocation.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7430"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-embed/src/harness/skills.rs",+ "line": 162,+ "text": "std::fs::copy(entry.path(), &target).map_err(|source| HarnessError::Workspace {",+ "occurrence": 1,+ "classification": "machine",+ "reason": "Library AgentSpec skill provisioning copies caller-supplied bundles into the agent directory because discovery rejects symlinks.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7429"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-embed/src/harness/workspace.rs",+ "line": 174,+ "text": "let temp = tempfile::Builder::new()",+ "occurrence": 1,+ "classification": "scratch",+ "reason": "Library harness temporary workspace builder allocates a requested scratch directory; not durable user state.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7434"+ },+ {+ "rule": "json-write",+ "path": "crates/openhuman-embed/src/profiles.rs",+ "line": 420,+ "text": "let mut options = std::fs::OpenOptions::new();",+ "occurrence": 1,+ "classification": "machine",+ "reason": "Fresh owner-only service token written before any served gateway; installation/connection bootstrap is deliberately local.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7432"+ },+ {+ "rule": "file-mutation",+ "path": "crates/openhuman-embed/src/profiles.rs",+ "line": 436,+ "text": "std::fs::rename(&temp_path, path)",+ "occurrence": 1,+ "classification": "machine",+ "reason": "Fresh owner-only service token written before any served gateway; installation/connection bootstrap is deliberately local.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7432"+ },+ {+ "rule": "json-write",+ "path": "crates/openhuman-tinyhumans/src/integrations/file_storage/tools/download.rs",+ "line": 89,+ "text": "if let Err(e) = tokio::fs::write(&path, &body).await {",+ "occurrence": 1,+ "classification": "external-export",+ "reason": "Downloads remote file bytes into the acting directory as a user-visible deliverable; local exported bytes do not replace the authoritative remote file record.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7425"+ },+ {+ "rule": "json-write",+ "path": "crates/openhuman-tui/src/app/artifacts.rs",+ "line": 79,+ "text": "match std::fs::write(&path, state.export_markdown()) {",+ "occurrence": 1,+ "classification": "external-export",+ "reason": "Explicit transcript Markdown export to the operator-selected path; the authoritative conversation journal is not replaced by this export.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7424"+ },+ {+ "rule": "json-write",+ "path": "vendor/tinyagents/crates/tinyagents-session/src/transcript/writer.rs",+ "line": 441,+ "text": "let mut file = fs::OpenOptions::new()",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Classic transcript generation/adoption/migration publication; scoped native session stores are a distinct implementation and historical source admission remains separate.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7426"+ },+ {+ "rule": "file-mutation",+ "path": "vendor/tinyagents/crates/tinyagents-session/src/transcript/writer.rs",+ "line": 464,+ "text": "fs::rename(&tmp_path, path).with_context(|| {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Classic transcript generation/adoption/migration publication; scoped native session stores are a distinct implementation and historical source admission remains separate.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7426"+ },+ {+ "rule": "file-mutation",+ "path": "vendor/tinyagents/crates/tinyagents-session/src/transcript/writer.rs",+ "line": 503,+ "text": "let published = match fs::hard_link(&tmp_path, path) {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Classic transcript generation/adoption/migration publication; scoped native session stores are a distinct implementation and historical source admission remains separate.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7426"+ },+ {+ "rule": "json-write",+ "path": "vendor/tinyagents/crates/tinyagents-session/src/transcript/writer.rs",+ "line": 522,+ "text": "let mut file = fs::OpenOptions::new()",+ "occurrence": 2,+ "classification": "classic",+ "reason": "Classic transcript generation/adoption/migration publication; scoped native session stores are a distinct implementation and historical source admission remains separate.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7426"+ },+ {+ "rule": "json-write",+ "path": "vendor/tinyagents/crates/tinyagents-session/src/transcript/writer.rs",+ "line": 586,+ "text": "if let Err(err) = fs::write(&md_path, md.as_bytes()) {",+ "occurrence": 1,+ "classification": "classic",+ "reason": "Classic transcript generation/adoption/migration publication; scoped native session stores are a distinct implementation and historical source admission remains separate.",+ "issue": "https://github.com/tinyhumansai/openhuman/issues/7426"+ }+ ]diff --cc vendor/tinyagentsindex d3e77cef90,6fa6ff7688..31cc57180f--- a/vendor/tinyagents+++ b/vendor/tinyagents@@@ -1,1 -1,1 +1,1 @@@- Subproject commit d3e77cef90dafdd9362af3d543deb925ac3ddd02-Subproject commit 6fa6ff7688018ccf3fd35fe31aebf0dda7e92c2f++Subproject commit 31cc57180f67b2f539a3c98d03388251084f0da0