Skip to content

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

chore(bench): remove library profiling and life-scenario harnesses

Steven Enamakel9f2586dc4064
diff --git a/crates/openhuman-cli/src/bin/library_profile/harness.rs b/crates/openhuman-cli/src/bin/library_profile/harness.rs
deleted file mode 100644
index 08cd8c1c4c..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/harness.rs
+++ /dev/null
@@ -1,489 +0,0 @@
-//! Shared profiling harness: hermetic fixture, RSS sampling, and the
-//! `measure()` wrapper that every scenario runs its workload through.
-//!
-//! All diagnostics go to **stderr** (stdout must stay pure JSON) using the
-//! stable `[library-profile]` prefix.
-
-use std::sync::atomic::{AtomicU64, Ordering};
-use std::sync::{Arc, Mutex};
-use std::time::{Duration, Instant};
-
-use anyhow::{Context, Result};
-use openhuman_core::config::Config;
-use openhuman_core::platform::proc_metrics::{self, ProcSample, TreeSample};
-use serde::Serialize;
-
-/// One sampled point inside a measured workload. `delta_kib` is the RSS change
-/// versus the *previous* checkpoint (or the baseline for the first one).
-#[derive(Debug, Clone, Serialize)]
-pub struct Checkpoint {
- pub label: String,
- pub at_ms: u128,
- pub rss_kib: u64,
- pub delta_kib: i64,
-}
-
-/// Turn wall-latency percentiles (milliseconds) collected under overlapping
-/// load by the `fleet` scenario.
-#[derive(Debug, Clone, Copy, Serialize)]
-pub struct TurnLatency {
- pub p50: u128,
- pub p95: u128,
- pub p99: u128,
- pub max: u128,
-}
-
-/// Per-descendant RSS entry in a [`TreeReport`].
-#[derive(Debug, Clone, Serialize)]
-pub struct TreeChild {
- pub name: String,
- pub rss_kib: u64,
-}
-
-/// Process-*tree* RSS reporting: this process plus every descendant
-/// (interpreter children such as `node` / `python` a skill run spawns). Folds a
-/// [`TreeSample`] down to the reported shape. `tree_rss_kib` counts self + all
-/// descendants, so it exceeds `settled.rss_kib` whenever a child was live at
-/// sample time.
-#[derive(Debug, Clone, Serialize)]
-pub struct TreeReport {
- pub tree_rss_kib: u64,
- pub child_count: usize,
- pub children: Vec<TreeChild>,
-}
-
-impl TreeReport {
- pub fn from_sample(sample: &TreeSample) -> Self {
- Self {
- tree_rss_kib: sample.tree_rss_kib,
- child_count: sample.children.len(),
- children: sample
- .children
- .iter()
- .map(|child| TreeChild {
- name: child.name.clone(),
- rss_kib: child.rss_kib,
- })
- .collect(),
- }
- }
-}
-
-/// Fleet capacity budget math (purely informational — scripts turn `fits` into
-/// pass/fail). `projected_rss_mib_at_target = settled_base + marginal * target`.
-#[derive(Debug, Clone, Copy, Serialize)]
-pub struct FleetBudget {
- pub target_agents: u64,
- pub ram_budget_mib: u64,
- pub projected_rss_mib_at_target: f64,
- pub fits: bool,
-}
-
-/// Pinned JSON output contract (schema_version = 2). New optional fields are
-/// skipped when absent so the two original scenarios stay byte-identical.
-#[derive(Debug, Serialize)]
-pub struct ProfileResult {
- pub schema_version: u32,
- pub scenario: &'static str,
- pub workload_units: usize,
- pub duration_ms: u128,
- pub baseline: ProcSample,
- pub settled: ProcSample,
- pub peak_rss_kib: u64,
- pub retained_delta_kib: i64,
- pub peak_delta_kib: u64,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub turns: Option<usize>,
- /// (`fleet`) requested live-agent count.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub agents: Option<usize>,
- /// (`fleet`) agents actually constructed (may be < `agents` on fd/OOM).
- #[serde(skip_serializing_if = "Option::is_none")]
- pub agents_built: Option<usize>,
- /// (`fleet`) marginal RSS cost per agent (`baseline → constructed`), KiB.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub marginal_rss_kib_per_agent: Option<f64>,
- /// (`fleet`) user+system CPU delta over the 10 s idle window, ms.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub idle_cpu_ms: Option<u64>,
- /// (`fleet`) turn wall-latency percentiles under overlapping load.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub turn_latency_ms: Option<TurnLatency>,
- /// (`fleet`) capacity budget projection.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub budget: Option<FleetBudget>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub checkpoints: Option<Vec<Checkpoint>>,
- /// (`subagent-storm`) K parallel `vision_agent` subagents fanned out in the turn.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub subagents: Option<usize>,
- /// (`skill-run`) process-tree RSS including interpreter child processes.
- /// Reports the richest tree seen — the peak-during-workload sample when a
- /// short-lived child (e.g. `node`) has already exited by settle time.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub tree: Option<TreeReport>,
- /// Present (and `true`) only when the dhat heap profiler is active, since
- /// RSS/time numbers are perturbed by dhat's global allocator.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub dhat: Option<bool>,
-}
-
-/// Restores (or removes) an environment variable on drop.
-pub struct EnvGuard {
- key: &'static str,
- old: Option<String>,
-}
-
-impl EnvGuard {
- pub fn set(key: &'static str, value: &str) -> Self {
- let old = std::env::var(key).ok();
- std::env::set_var(key, value);
- Self { key, old }
- }
-}
-
-impl Drop for EnvGuard {
- fn drop(&mut self) {
- match &self.old {
- Some(value) => std::env::set_var(self.key, value),
- None => std::env::remove_var(self.key),
- }
- }
-}
-
-/// A hermetic config rooted in a throwaway temp workspace. Local inference,
-/// Python and embeddings are all disabled so runs are offline.
-pub struct Fixture {
- pub config: Config,
- _workspace_env: EnvGuard,
- _keyring_env: EnvGuard,
- _action_env: EnvGuard,
- _tmp: tempfile::TempDir,
-}
-
-pub fn fixture() -> Result<Fixture> {
- let tmp = tempfile::tempdir().context("create profile workspace")?;
- let root = tmp.path();
- let workspace = root.join("workspace");
- std::fs::create_dir_all(&workspace)?;
- // A real, writable action sandbox so acting tools (e.g. `node_exec`, which
- // spawns `node` in the action dir) have a valid cwd. Harmless for scenarios
- // that never act.
- let action_dir = root.join("action");
- std::fs::create_dir_all(&action_dir)?;
-
- let mut config_toml = r#"api_url = "http://127.0.0.1:9"
-default_model = "profile-mock"
-default_temperature = 0.0
-chat_onboarding_completed = true
-
-[secrets]
-encrypt = false
-
-[local_ai]
-enabled = false
-runtime_enabled = false
-
-[runtime_python]
-enabled = false
-"#
- .to_string();
- if std::env::var_os("OPENHUMAN_PROFILE_DISABLE_MEMORY_WRITES").is_some() {
- config_toml.push_str(
- r#"
-[memory.conversations]
-enabled = false
-
-[memory.recall]
-enabled = false
-"#,
- );
- }
- // `skill-run` executes real acting tools (`node_exec`); those need the Full
- // autonomy tier so the write-class gate does not park the turn on approval.
- // Config::load_or_init inside the detached workflow run re-reads this file,
- // so the tier must live in config.toml (not just the in-memory Config).
- if std::env::var_os("OPENHUMAN_PROFILE_FULL_AUTONOMY").is_some() {
- config_toml.push_str(
- r#"
-[autonomy]
-level = "full"
-"#,
- );
- }
- std::fs::write(root.join("config.toml"), &config_toml)?;
-
- let workspace_env = EnvGuard::set("OPENHUMAN_WORKSPACE", &root.to_string_lossy());
- let keyring_env = EnvGuard::set("OPENHUMAN_KEYRING_BACKEND", "file");
- let action_env = EnvGuard::set("OPENHUMAN_ACTION_DIR", &action_dir.to_string_lossy());
- let mut config: Config = toml::from_str(&config_toml)?;
- config.workspace_dir = workspace;
- config.action_dir = action_dir;
-
- Ok(Fixture {
- config,
- _workspace_env: workspace_env,
- _keyring_env: keyring_env,
- _action_env: action_env,
- _tmp: tmp,
- })
-}
-
-/// Background task that polls `proc_metrics::sample_self()` every 5 ms and
-/// keeps the running peak RSS.
-pub struct PeakSampler {
- peak: Arc<AtomicU64>,
- stop: Arc<AtomicU64>,
- task: tokio::task::JoinHandle<()>,
-}
-
-impl PeakSampler {
- pub fn start(initial_kib: u64) -> Self {
- let peak = Arc::new(AtomicU64::new(initial_kib));
- let stop = Arc::new(AtomicU64::new(0));
- let task_peak = Arc::clone(&peak);
- let task_stop = Arc::clone(&stop);
- let task = tokio::spawn(async move {
- while task_stop.load(Ordering::Relaxed) == 0 {
- if let Ok(sample) = proc_metrics::sample_self() {
- task_peak.fetch_max(sample.rss_kib, Ordering::Relaxed);
- }
- tokio::time::sleep(Duration::from_millis(5)).await;
- }
- });
- Self { peak, stop, task }
- }
-
- pub async fn stop(self) -> u64 {
- self.stop.store(1, Ordering::Relaxed);
- let _ = self.task.await;
- self.peak.load(Ordering::Relaxed)
- }
-}
-
-/// Background task that polls `proc_metrics::sample_tree()` and keeps the
-/// [`TreeSample`] with the highest `tree_rss_kib` seen — capturing the moment a
-/// short-lived interpreter child (e.g. a `node -e` step) is resident, which a
-/// settle-time-only sample would miss because the child has already exited.
-pub struct TreePeakSampler {
- best: Arc<Mutex<Option<TreeSample>>>,
- stop: Arc<AtomicU64>,
- task: tokio::task::JoinHandle<()>,
-}
-
-impl TreePeakSampler {
- pub fn start() -> Self {
- let best: Arc<Mutex<Option<TreeSample>>> = Arc::new(Mutex::new(None));
- let stop = Arc::new(AtomicU64::new(0));
- let task_best = Arc::clone(&best);
- let task_stop = Arc::clone(&stop);
- let task = tokio::spawn(async move {
- while task_stop.load(Ordering::Relaxed) == 0 {
- if let Ok(sample) = proc_metrics::sample_tree() {
- let mut guard = task_best.lock().expect("tree peak lock");
- let replace = guard
- .as_ref()
- .map(|prev| sample.tree_rss_kib > prev.tree_rss_kib)
- .unwrap_or(true);
- if replace {
- *guard = Some(sample);
- }
- }
- tokio::time::sleep(Duration::from_millis(15)).await;
- }
- });
- Self { best, stop, task }
- }
-
- pub async fn stop(self) -> Option<TreeSample> {
- self.stop.store(1, Ordering::Relaxed);
- let _ = self.task.await;
- self.best.lock().expect("tree peak lock").clone()
- }
-}
-
-/// Collects per-phase / per-turn checkpoints inside a measured workload.
-/// Cloneable (shares one buffer) so it can be handed to closures freely.
-#[derive(Clone)]
-pub struct Recorder {
- inner: Arc<Mutex<RecorderState>>,
- started: Instant,
-}
-
-struct RecorderState {
- checkpoints: Vec<Checkpoint>,
- last_rss_kib: u64,
-}
-
-impl Recorder {
- fn new(baseline_kib: u64, started: Instant) -> Self {
- Self {
- inner: Arc::new(Mutex::new(RecorderState {
- checkpoints: Vec::new(),
- last_rss_kib: baseline_kib,
- })),
- started,
- }
- }
-
- /// Sample RSS now and append a labelled checkpoint whose `delta_kib` is
- /// relative to the previous checkpoint (baseline for the first).
- pub fn checkpoint(&self, label: impl Into<String>) -> Result<()> {
- let label = label.into();
- let sample = proc_metrics::sample_self()?;
- let at_ms = self.started.elapsed().as_millis();
- let mut state = self.inner.lock().expect("recorder lock");
- let delta_kib = sample.rss_kib as i64 - state.last_rss_kib as i64;
- state.last_rss_kib = sample.rss_kib;
- eprintln!(
- "[library-profile] checkpoint label={label} at_ms={at_ms} rss_kib={} delta_kib={delta_kib}",
- sample.rss_kib
- );
- state.checkpoints.push(Checkpoint {
- label,
- at_ms,
- rss_kib: sample.rss_kib,
- delta_kib,
- });
- Ok(())
- }
-
- fn take(self) -> Vec<Checkpoint> {
- self.inner
- .lock()
- .expect("recorder lock")
- .checkpoints
- .clone()
- }
-}
-
-/// Run `workload` between a settled baseline and a settled post-run sample,
-/// tracking peak RSS throughout. `turns` and any checkpoints pushed via the
-/// `Recorder` are folded into the result (both `None`/omitted when unused).
-pub async fn measure<F, Fut>(
- scenario: &'static str,
- workload_units: usize,
- turns: Option<usize>,
- workload: F,
-) -> Result<ProfileResult>
-where
- F: FnOnce(Recorder) -> Fut,
- Fut: std::future::Future<Output = Result<()>>,
-{
- measure_impl(scenario, workload_units, turns, false, workload).await
-}
-
-/// Like [`measure`], but also samples the process **tree** (self + descendant
-/// interpreter processes). A [`TreePeakSampler`] runs alongside the RSS peak
-/// sampler, and the settle-time tree is captured too; the reported `tree` is
-/// whichever of the two has the higher `tree_rss_kib`, so a `node` child that
-/// exits before settle is still attributed. Used by `skill-run`.
-pub async fn measure_with_tree<F, Fut>(
- scenario: &'static str,
- workload_units: usize,
- turns: Option<usize>,
- workload: F,
-) -> Result<ProfileResult>
-where
- F: FnOnce(Recorder) -> Fut,
- Fut: std::future::Future<Output = Result<()>>,
-{
- measure_impl(scenario, workload_units, turns, true, workload).await
-}
-
-async fn measure_impl<F, Fut>(
- scenario: &'static str,
- workload_units: usize,
- turns: Option<usize>,
- sample_tree: bool,
- workload: F,
-) -> Result<ProfileResult>
-where
- F: FnOnce(Recorder) -> Fut,
- Fut: std::future::Future<Output = Result<()>>,
-{
- tokio::time::sleep(Duration::from_millis(250)).await;
- let baseline = proc_metrics::sample_self()?;
- if let Some(seconds) = std::env::var("OPENHUMAN_PROFILE_HOLD_BEFORE_SECS")
- .ok()
- .and_then(|value| value.parse::<u64>().ok())
- .filter(|seconds| *seconds > 0)
- {
- eprintln!(
- "[library-profile] pid={} holding at baseline for {seconds}s",
- std::process::id()
- );
- tokio::time::sleep(Duration::from_secs(seconds)).await;
- }
- let sampler = PeakSampler::start(baseline.rss_kib);
- let tree_sampler = if sample_tree {
- Some(TreePeakSampler::start())
- } else {
- None
- };
- let started = Instant::now();
- let recorder = Recorder::new(baseline.rss_kib, started);
- eprintln!("[library-profile] scenario={scenario} workload starting");
- workload(recorder.clone()).await?;
- let duration_ms = started.elapsed().as_millis();
- eprintln!("[library-profile] scenario={scenario} workload done duration_ms={duration_ms}");
- tokio::time::sleep(Duration::from_millis(500)).await;
- let settled = proc_metrics::sample_self()?;
- let peak_rss_kib = sampler.stop().await.max(settled.rss_kib);
-
- // Fold the process-tree samples (peak-during-workload + settle-time) into a
- // single report: whichever has the higher tree RSS wins, so a short-lived
- // interpreter child that already exited by settle is still attributed.
- let tree = if let Some(tree_sampler) = tree_sampler {
- let peak_tree = tree_sampler.stop().await;
- let settle_tree = proc_metrics::sample_tree().ok();
- let best = match (peak_tree, settle_tree) {
- (Some(peak), Some(settle)) => {
- if peak.tree_rss_kib >= settle.tree_rss_kib {
- Some(peak)
- } else {
- Some(settle)
- }
- }
- (peak, settle) => peak.or(settle),
- };
- if let Some(best) = best.as_ref() {
- eprintln!(
- "[library-profile] scenario={scenario} tree_rss_kib={} child_count={}",
- best.tree_rss_kib,
- best.children.len()
- );
- }
- best.map(|sample| TreeReport::from_sample(&sample))
- } else {
- None
- };
- let checkpoints = recorder.take();
- let checkpoints = if checkpoints.is_empty() {
- None
- } else {
- Some(checkpoints)
- };
- Ok(ProfileResult {
- schema_version: 2,
- scenario,
- workload_units,
- duration_ms,
- baseline,
- settled,
- peak_rss_kib,
- retained_delta_kib: settled.rss_kib as i64 - baseline.rss_kib as i64,
- peak_delta_kib: peak_rss_kib.saturating_sub(baseline.rss_kib),
- turns,
- agents: None,
- agents_built: None,
- marginal_rss_kib_per_agent: None,
- idle_cpu_ms: None,
- turn_latency_ms: None,
- budget: None,
- checkpoints,
- subagents: None,
- tree,
- dhat: None,
- })
-}
diff --git a/crates/openhuman-cli/src/bin/library_profile/main.rs b/crates/openhuman-cli/src/bin/library_profile/main.rs
deleted file mode 100644
index edc37ab526..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/main.rs
+++ /dev/null
@@ -1,126 +0,0 @@
-//! Hermetic, Rust-only library profiling workloads.
-//!
-//! This binary never enters shipped builds (it requires the default-off
-//! `rss-bench` feature). It measures production code paths in fresh processes
-//! with network inference replaced by a deterministic provider.
-//!
-//! Scenarios (`library-profile <scenario>`):
-//! - `agent-turn` — a single cold agent turn (minimal library unit).
-//! - `long-agent` — N warmed sequential turns with a per-turn checkpoint series.
-//! - `workflow` — a real flows trigger->transform->agent graph, end to end.
-//! - `fleet` — N live agents: marginal RSS, idle CPU, fd/thread growth, turn latency.
-//! - `skill-run` — a skill step executing on a real `node` child: process-tree RSS.
-//! - `subagent-storm`— K parallel `agent_memory` subagents in one instance: marginal RSS per subagent.
-//!
-//! `memory-ingest` and `cold-phases` were removed with the in-process memory
-//! engine (openhuman#6161); see `scenarios/mod.rs`.
-//!
-//! stdout is ALWAYS a single pretty JSON object (the pinned schema in
-//! `harness::ProfileResult`); every diagnostic goes to stderr with the stable
-//! `[library-profile]` prefix.
-//!
-//! With the `rss-bench-dhat` feature, dhat's global allocator + profiler are
-//! active: RSS/time numbers are perturbed, the result carries `"dhat": true`,
-//! and a `dhat-<scenario>.json` heap profile is written under
-//! `target/profile/rust-library/` (override via `OPENHUMAN_PROFILE_DHAT_OUT`).
-
-mod harness;
-mod mock;
-mod scenarios;
-
-use std::time::Duration;
-
-use anyhow::{Context, Result};
-
-use harness::ProfileResult;
-
-#[cfg(feature = "rss-bench-dhat")]
-#[global_allocator]
-static ALLOC: dhat::Alloc = dhat::Alloc;
-
-/// Builds the dhat profiler (feature-gated), writing to the requested path.
-/// Kept alive by the caller until after the JSON result is printed.
-#[cfg(feature = "rss-bench-dhat")]
-fn start_dhat(scenario: &str) -> Result<dhat::Profiler> {
- let out = std::env::var("OPENHUMAN_PROFILE_DHAT_OUT")
- .unwrap_or_else(|_| format!("target/profile/rust-library/dhat-{scenario}.json"));
- if let Some(parent) = std::path::Path::new(&out).parent() {
- std::fs::create_dir_all(parent).context("create dhat output directory")?;
- }
- eprintln!("[library-profile] dhat active — heap profile -> {out}");
- Ok(dhat::Profiler::builder().file_name(&out).build())
-}
-
-async fn dispatch(scenario: &str) -> Result<ProfileResult> {
- match scenario {
- "agent-turn" => scenarios::agent_turn::run().await,
- "long-agent" => scenarios::long_agent::run().await,
- "workflow" => scenarios::workflow::run().await,
- "fleet" => scenarios::fleet::run().await,
- "skill-run" => scenarios::skill_run::run().await,
- "subagent-storm" => scenarios::subagent_storm::run().await,
- other => anyhow::bail!("unknown scenario: {other}"),
- }
-}
-
-/// Build the tokio runtime. When `OPENHUMAN_PROFILE_WORKER_THREADS` is set the
-/// multi-thread runtime is built manually with that worker count (set to `2` to
-/// simulate the 2 vCPU box); otherwise the standard multi-thread default runs.
-fn build_runtime() -> Result<tokio::runtime::Runtime> {
- let mut builder = tokio::runtime::Builder::new_multi_thread();
- builder.enable_all();
- if let Some(workers) = std::env::var("OPENHUMAN_PROFILE_WORKER_THREADS")
- .ok()
- .and_then(|value| value.parse::<usize>().ok())
- .filter(|n| *n > 0)
- {
- eprintln!("[library-profile] tokio worker_threads={workers}");
- builder.worker_threads(workers);
- }
- builder.build().context("build tokio runtime")
-}
-
-fn main() -> Result<()> {
- // Parse args BEFORE building the runtime so `OPENHUMAN_PROFILE_WORKER_THREADS`
- // can size the worker pool (the `fleet` scenario simulates the 2 vCPU box).
- let scenario = std::env::args().nth(1).context(
- "usage: library-profile \
- <agent-turn|long-agent|workflow|fleet|skill-run|subagent-storm>",
- )?;
-
- // Profiler must outlive the whole run + the JSON print so its Drop writes
- // the complete heap profile last.
- #[cfg(feature = "rss-bench-dhat")]
- let _dhat = start_dhat(&scenario)?;
-
- eprintln!(
- "[library-profile] pid={} scenario={scenario} start",
- std::process::id()
- );
-
- let runtime = build_runtime()?;
- runtime.block_on(async move {
- #[cfg_attr(not(feature = "rss-bench-dhat"), allow(unused_mut))]
- let mut result = dispatch(&scenario).await?;
-
- #[cfg(feature = "rss-bench-dhat")]
- {
- result.dhat = Some(true);
- }
-
- println!("{}", serde_json::to_string_pretty(&result)?);
-
- if let Some(seconds) = std::env::var("OPENHUMAN_PROFILE_HOLD_SECS")
- .ok()
- .and_then(|value| value.parse::<u64>().ok())
- .filter(|seconds| *seconds > 0)
- {
- eprintln!(
- "[library-profile] pid={} holding for {seconds}s",
- std::process::id()
- );
- tokio::time::sleep(Duration::from_secs(seconds)).await;
- }
- Ok(())
- })
-}
diff --git a/crates/openhuman-cli/src/bin/library_profile/mock.rs b/crates/openhuman-cli/src/bin/library_profile/mock.rs
deleted file mode 100644
index ba097d46c2..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/mock.rs
+++ /dev/null
@@ -1,470 +0,0 @@
-//! Deterministic offline `ChatModel` mocks installed via
-//! `test_provider_override` (honoured only under the `rss-bench` feature).
-
-use std::sync::atomic::{AtomicU64, Ordering};
-use std::sync::{Arc, Mutex};
-use std::time::Duration;
-
-use async_trait::async_trait;
-use openhuman_core::inference::provider::types::ChatResponse;
-use tinyinference_llm::message::{AssistantMessage, ContentBlock, Message};
-use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse};
-use tinyinference_llm::tool::ToolCall as TinyAgentsToolCall;
-use tinytools_agent::dialect::NativeToolCall as ToolCall;
-
-/// A plain `ChatResponse` carrying only text (no tool calls).
-pub fn response(text: &str) -> ChatResponse {
- ChatResponse {
- text: Some(text.into()),
- tool_calls: Vec::new(),
- usage: None,
- reasoning_content: None,
- }
-}
-
-fn joined_request(request: &ModelRequest) -> String {
- request
- .messages
- .iter()
- .map(|message| {
- let role = match message {
- Message::System(_) => "system",
- Message::User(_) => "user",
- Message::Assistant(_) => "assistant",
- Message::Tool(_) => "tool",
- Message::Custom(_) => "custom",
- };
- format!("{role}: {}", message.text())
- })
- .collect::<Vec<_>>()
- .join("\n")
-}
-
-fn model_response(response: ChatResponse) -> ModelResponse {
- let content = response
- .text
- .filter(|text| !text.is_empty())
- .map(|text| vec![ContentBlock::Text(text)])
- .unwrap_or_default();
- let tool_calls = response
- .tool_calls
- .into_iter()
- .map(|call| {
- TinyAgentsToolCall::new(
- call.id,
- call.name,
- serde_json::from_str(&call.arguments).unwrap_or(serde_json::Value::Null),
- )
- })
- .collect::<Vec<_>>();
- ModelResponse {
- finish_reason: (!tool_calls.is_empty()).then(|| "tool_calls".to_string()),
- message: AssistantMessage {
- id: None,
- content,
- tool_calls,
- usage: None,
- origin: None,
- },
- usage: None,
- raw: None,
- resolved_model: None,
- continue_turn: None,
- served_from_cache: false,
- correlation: None,
- resolved_route: None,
- }
-}
-
-/// Records every prompt it sees so scenarios can assert what ran.
-fn record(prompts: &Mutex<Vec<String>>, joined: &str) {
- prompts
- .lock()
- .expect("mock prompt lock")
- .push(joined.into());
-}
-
-/// Read `key` as a `u64`, falling back to `default` when unset/unparsable.
-fn env_u64(key: &str, default: u64) -> u64 {
- std::env::var(key)
- .ok()
- .and_then(|value| value.parse::<u64>().ok())
- .unwrap_or(default)
-}
-
-/// Stable per-worker marker embedded in a delegated subagent's prompt.
-/// Zero-padded so `..._001` is never a substring of `..._011` — the storm mock
-/// routes by exact marker containment across K up to 32.
-pub fn subagent_marker(index: usize) -> String {
- format!("LIB_PROFILE_SUBAGENT_{index:03}")
-}
-
-/// The finding text a delegated worker returns for `index`. The merge turn
-/// is detected by all K of these being present in the conversation.
-pub fn finding_text(index: usize) -> String {
- format!("Finding {index:03}: worker {index} reports healthy.")
-}
-
-/// Text the orchestrator returns once it has merged every worker finding;
-/// its arrival in the conversation ends the storm turn.
-pub const MERGE_SENTINEL: &str = "STORM_MERGE_COMPLETE";
-
-/// Shared, dependency-free latency sampler driven by the standard env knobs
-/// (`OPENHUMAN_PROFILE_MOCK_LATENCY_MS` mean, `OPENHUMAN_PROFILE_MOCK_JITTER_MS`
-/// jitter, default `mean / 4`). Reused by both [`LatencyMock`] and
-/// [`SubagentMock`] so a delegated subagent turn can carry realistic latency.
-pub struct LatencyKnobs {
- mean_ms: u64,
- jitter_ms: u64,
- counter: AtomicU64,
-}
-
-impl LatencyKnobs {
- pub fn from_env() -> Self {
- let mean_ms = env_u64("OPENHUMAN_PROFILE_MOCK_LATENCY_MS", 0);
- let jitter_ms = env_u64("OPENHUMAN_PROFILE_MOCK_JITTER_MS", mean_ms / 4);
- eprintln!("[library-profile] LatencyKnobs mean_ms={mean_ms} jitter_ms={jitter_ms}");
- Self {
- mean_ms,
- jitter_ms,
- counter: AtomicU64::new(0),
- }
- }
-
- /// Sample `mean ± jitter` (clamped at zero) via a seeded xorshift step. The
- /// seed advances per call so successive turns get distinct latencies.
- pub fn sample_ms(&self) -> u64 {
- if self.mean_ms == 0 && self.jitter_ms == 0 {
- return 0;
- }
- let seed = self.counter.fetch_add(1, Ordering::Relaxed).wrapping_add(1);
- // xorshift64 — deterministic, dependency-free pseudo-randomness.
- let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15);
- x ^= x >> 12;
- x ^= x << 25;
- x ^= x >> 27;
- let span = self.jitter_ms.saturating_mul(2).saturating_add(1);
- let delta = (x % span) as i64 - self.jitter_ms as i64;
- (self.mean_ms as i64 + delta).max(0) as u64
- }
-
- /// Sleep a sampled latency and return the ms slept (0 when disabled).
- pub async fn sleep_sampled(&self) -> u64 {
- let ms = self.sample_ms();
- if ms > 0 {
- tokio::time::sleep(Duration::from_millis(ms)).await;
- }
- ms
- }
-}
-
-/// Orchestration mock: the first (orchestrator) turn emits a
-/// `spawn_parallel_agents` tool call fanning out to **K** `vision_agent` workers;
-/// each worker turn returns its finding; the final merge turn returns plain
-/// text once all K findings are present.
-///
-/// `width` = K parallel workers. [`Self::with_width`] drives the
-/// **orchestrator directly** and scripts the full delegation chain as a direct
-/// fan-out — the `subagent-storm` fuzz-width path.
-pub struct SubagentMock {
- pub prompts: Mutex<Vec<String>>,
- /// Actual wall-time (ms) of each *worker* chat call, for percentiles.
- pub worker_latencies_ms: Mutex<Vec<u128>>,
- width: usize,
- latency: LatencyKnobs,
- /// Increments per fan-out so successive `spawn_parallel_agents` calls carry
- /// distinct task prompts.
- spawn_nonce: AtomicU64,
-}
-
-impl SubagentMock {
- /// K workers with per-worker latency drawn from the env knobs, driven
- /// directly against the orchestrator agent (full agent-aware chain).
- pub fn with_width(width: usize) -> Arc<Self> {
- Arc::new(Self {
- prompts: Mutex::new(Vec::new()),
- worker_latencies_ms: Mutex::new(Vec::new()),
- width: width.max(1),
- latency: LatencyKnobs::from_env(),
- spawn_nonce: AtomicU64::new(0),
- })
- }
-
- /// Which worker (1-based) this prompt is for, if any. A worker
- /// prompt embeds exactly one `subagent_marker`.
- fn worker_index(&self, joined: &str) -> Option<usize> {
- (1..=self.width).find(|&i| joined.contains(&subagent_marker(i)))
- }
-
- /// True once every worker's finding is present — the merge turn.
- fn is_merge(&self, joined: &str) -> bool {
- (1..=self.width).all(|i| joined.contains(&finding_text(i)))
- }
-
- /// True when this call is a real `vision_agent` worker turn: exactly one task
- /// marker is present and the executing agent is not the orchestrator (its
- /// Tool Policy Boundary header names it, and its merge turn also carries
- /// every marker). The memory agent's system
- /// prompt names it a memory retrieval specialist, so it matches neither header.
- fn is_worker_turn(&self, joined: &str) -> bool {
- self.worker_index(joined).is_some() && !joined.contains("Agent: orchestrator")
- }
-
- /// Build the fan-out tool call delegating to K parallel `vision_agent` workers. Only
- /// valid on an **orchestrator** turn — other agents have no
- /// `spawn_parallel_agents` tool, so they `delegate_orchestrator` first.
- fn spawn_call(&self) -> ChatResponse {
- let nonce = self.spawn_nonce.fetch_add(1, Ordering::Relaxed);
- let tasks: Vec<serde_json::Value> = (1..=self.width)
- .map(|i| {
- serde_json::json!({
- "agent_id": "vision_agent",
- // The nonce keeps each fan-out's tasks byte-distinct so the
- // parallel-graph result cache can't short-circuit a re-spawn.
- "prompt": format!("{} [spawn {nonce}]: inspect subsystem {i}", subagent_marker(i)),
- "ownership": format!("scope: subsystem-{i}-spawn-{nonce}")
- })
- })
- .collect();
- ChatResponse {
- text: Some(format!("Delegating to {} workers.", self.width)),
- tool_calls: vec![ToolCall {
- id: "profile-parallel-call".into(),
- name: "spawn_parallel_agents".into(),
- arguments: serde_json::json!({ "tasks": tasks }).to_string(),
- extra_content: None,
- }],
- usage: None,
- reasoning_content: None,
- }
- }
-
- /// A non-orchestrator parent's first turn: hand the task to the orchestrator (which
- /// owns `spawn_parallel_agents` and allows the `vision_agent` subagent).
- fn delegate_orchestrator_call(&self) -> ChatResponse {
- ChatResponse {
- text: Some("Delegating to the orchestrator for a parallel research fan-out.".into()),
- tool_calls: vec![ToolCall {
- id: "profile-delegate-orchestrator".into(),
- name: "delegate_orchestrator".into(),
- arguments: serde_json::json!({
- "prompt": "Research every subsystem in parallel and merge the findings."
- })
- .to_string(),
- extra_content: None,
- }],
- usage: None,
- reasoning_content: None,
- }
- }
-
- /// Classify the turn by the *executing agent* (from the Tool Policy Boundary
- /// header) and script the delegation chain: orchestrator →
- /// `spawn_parallel_agents(K)` → K vision_agent workers → orchestrator merge.
- /// No latency/recording here — the async `chat` wrappers handle sleeping +
- /// latency capture around this.
- fn reply(&self, joined: &str) -> ChatResponse {
- // vision_agent worker: return its finding.
- if self.is_worker_turn(joined) {
- let i = self.worker_index(joined).expect("worker turn has a marker");
- return response(&finding_text(i));
- }
- // Orchestrator: fan out, then merge once every finding is back.
- if joined.contains("Agent: orchestrator") {
- if self.is_merge(joined) {
- return response(MERGE_SENTINEL);
- }
- return self.spawn_call();
- }
- // Any other parent: finish once the orchestrator's
- // merged result has flowed back; otherwise delegate to the orchestrator.
- if joined.contains(MERGE_SENTINEL) {
- return response("Storm complete: merged every worker's finding.");
- }
- self.delegate_orchestrator_call()
- }
-}
-
-#[async_trait]
-impl ChatModel<()> for SubagentMock {
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> Result<ModelResponse, tinyinference_llm::Error> {
- Ok(model_response(
- self.dispatch(&joined_request(&request)).await,
- ))
- }
-}
-
-impl SubagentMock {
- /// Record the prompt, sleep a sampled latency for *worker* calls (and
- /// capture their wall time), then return the classified response.
- async fn dispatch(&self, joined: &str) -> ChatResponse {
- record(&self.prompts, joined);
- let is_worker = self.is_worker_turn(joined);
- let started = std::time::Instant::now();
- if is_worker {
- self.latency.sleep_sampled().await;
- }
- let resp = self.reply(joined);
- if is_worker {
- self.worker_latencies_ms
- .lock()
- .expect("mock latency lock")
- .push(started.elapsed().as_millis());
- }
- resp
- }
-}
-
-/// Latency-configurable text-only mock used by the `fleet` scenario. Before
-/// returning its fixed answer it sleeps a sampled latency: a mean from
-/// `OPENHUMAN_PROFILE_MOCK_LATENCY_MS` (default `0` = no sleep) with jitter
-/// `± OPENHUMAN_PROFILE_MOCK_JITTER_MS` (default `mean / 4`). Per-call jitter is
-/// derived from a seeded xorshift counter — deterministic and dependency-free
-/// (no `rand` crate).
-pub struct LatencyMock {
- text: String,
- latency: LatencyKnobs,
- pub prompts: Mutex<Vec<String>>,
-}
-
-impl LatencyMock {
- /// Build from the standard env knobs.
- pub fn from_env(text: impl Into<String>) -> Arc<Self> {
- Arc::new(Self {
- text: text.into(),
- latency: LatencyKnobs::from_env(),
- prompts: Mutex::new(Vec::new()),
- })
- }
-}
-
-#[async_trait]
-impl ChatModel<()> for LatencyMock {
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> Result<ModelResponse, tinyinference_llm::Error> {
- self.latency.sleep_sampled().await;
- let joined = joined_request(&request);
- record(&self.prompts, &joined);
- Ok(model_response(response(&self.text)))
- }
-}
-
-/// Text-only mock: always returns a fixed direct answer, never a tool call.
-/// Used by the single-turn / workflow scenarios that must NOT delegate.
-pub struct PlainTextMock {
- text: String,
- pub prompts: Mutex<Vec<String>>,
-}
-
-impl PlainTextMock {
- pub fn new(text: impl Into<String>) -> Arc<Self> {
- Arc::new(Self {
- text: text.into(),
- prompts: Mutex::new(Vec::new()),
- })
- }
-}
-
-#[async_trait]
-impl ChatModel<()> for PlainTextMock {
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> Result<ModelResponse, tinyinference_llm::Error> {
- let joined = joined_request(&request);
- record(&self.prompts, &joined);
- Ok(model_response(response(&self.text)))
- }
-}
-
-/// The stdout marker the profiling `node` step prints. Its presence in the run
-/// conversation proves the real interpreter child executed (not merely that a
-/// tool call was emitted).
-pub const NODE_MARKER: &str = "PROFILE_NODE_RESULT";
-
-/// Skill-run mock: the first turn emits a `node_exec` tool call running a short,
-/// real JavaScript computation (which spawns a genuine `node` child process);
-/// once its printed JSON (carrying [`NODE_MARKER`]) rides back into the
-/// conversation, the mock returns a plain final answer so the agent turn
-/// completes. This scripts exactly the tool call the code-executor specialist
-/// needs to spawn the language runtime whose cost we measure.
-pub struct SkillRunMock {
- code: String,
- node_call_emitted: AtomicU64,
- node_output_seen: AtomicU64,
- pub prompts: Mutex<Vec<String>>,
-}
-
-impl SkillRunMock {
- pub fn new() -> Arc<Self> {
- // A real computation, a live allocation, and a ~1.2s busy-wait so the
- // child stays resident long enough for the tree sampler (15 ms poll) to
- // catch it. The JSON it prints carries NODE_MARKER.
- let code = format!(
- "const start = Date.now();\n\
- const buf = [];\n\
- let sum = 0;\n\
- for (let i = 0; i < 500000; i++) {{ buf.push(i % 97); sum += i; }}\n\
- while (Date.now() - start < 1200) {{ sum += buf.length; }}\n\
- console.log(JSON.stringify({{ marker: '{NODE_MARKER}', sum, kept: buf.length }}));\n"
- );
- Arc::new(Self {
- code,
- node_call_emitted: AtomicU64::new(0),
- node_output_seen: AtomicU64::new(0),
- prompts: Mutex::new(Vec::new()),
- })
- }
-
- /// True once the `node_exec` tool call has been emitted.
- pub fn node_call_emitted(&self) -> bool {
- self.node_call_emitted.load(Ordering::Relaxed) > 0
- }
-
- /// True once the node child's printed output flowed back into the turn —
- /// i.e. the interpreter child actually ran and printed.
- pub fn node_output_seen(&self) -> bool {
- self.node_output_seen.load(Ordering::Relaxed) > 0
- }
-
- fn reply(&self, joined: &str) -> ChatResponse {
- record(&self.prompts, joined);
- if joined.contains(NODE_MARKER) {
- self.node_output_seen.store(1, Ordering::Relaxed);
- return response(
- "Skill complete: the Node.js step computed the value and it checks out.",
- );
- }
- self.node_call_emitted.store(1, Ordering::Relaxed);
- ChatResponse {
- text: Some("Running the JavaScript computation step.".into()),
- tool_calls: vec![ToolCall {
- id: "profile-node-call".into(),
- name: "node_exec".into(),
- arguments: serde_json::json!({ "inline_code": self.code }).to_string(),
- extra_content: None,
- }],
- usage: None,
- reasoning_content: None,
- }
- }
-}
-
-#[async_trait]
-impl ChatModel<()> for SkillRunMock {
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> Result<ModelResponse, tinyinference_llm::Error> {
- Ok(model_response(self.reply(&joined_request(&request))))
- }
-}
diff --git a/crates/openhuman-cli/src/bin/library_profile/scenarios/agent_turn.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/agent_turn.rs
deleted file mode 100644
index f60607df0b..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/agent_turn.rs
+++ /dev/null
@@ -1,32 +0,0 @@
-//! `agent-turn`: the minimal "embed OpenHuman as a library" unit — a single
-//! cold agent turn built directly from config, with a plain-text mock provider
-//! (no tool calls, no delegation).
-
-use anyhow::Result;
-use openhuman_core::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::agent::OpenHumanSessionHost;
-use openhuman_core::inference::provider::factory::test_provider_override;
-
-use crate::harness::{fixture, measure, ProfileResult};
-use crate::mock::PlainTextMock;
-
-pub async fn run() -> Result<ProfileResult> {
- let fixture = fixture()?;
- openhuman_core::core::bus::init().await.expect("bus init");
- openhuman_core::agent::bus::register_agent_handlers();
- let _ = AgentDefinitionRegistry::init_global_builtins();
- let mock = PlainTextMock::new("The Phoenix migration is healthy and on track.");
- let _provider = test_provider_override::install_model(mock.clone());
- eprintln!("[library-profile] agent-turn: registries ready, mock installed");
-
- measure("agent-turn", 1, None, |_rec| async {
- let mut agent =
- OpenHumanSessionHost::from_config_for_agent(&fixture.config, "orchestrator")?;
- let reply = agent
- .run_single("Give me a one-line status on the Phoenix migration.")
- .await?;
- anyhow::ensure!(!reply.trim().is_empty(), "empty agent reply");
- Ok(())
- })
- .await
-}
diff --git a/crates/openhuman-cli/src/bin/library_profile/scenarios/fleet.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/fleet.rs
deleted file mode 100644
index 63ed475285..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/fleet.rs
+++ /dev/null
@@ -1,277 +0,0 @@
-//! `fleet`: can OpenHuman host 100–1000 live agents on a 2 GB / 2 vCPU box?
-//!
-//! Answers four questions in one process: (1) marginal RSS per live agent
-//! (`baseline → constructed`), (2) idle CPU of parked agents (CPU delta over a
-//! 10 s do-nothing window), (3) thread + fd growth vs N (rides along in
-//! `ProcSample`), and (4) turn latency percentiles under overlapping load.
-//!
-//! Env knobs:
-//! - `OPENHUMAN_PROFILE_AGENTS` (default 100) — live agents to construct.
-//! - `OPENHUMAN_PROFILE_TURNS` (default 3) — turns per agent under load.
-//! - `OPENHUMAN_PROFILE_MOCK_LATENCY_MS` / `_JITTER_MS` — mock reply latency.
-//! - `OPENHUMAN_PROFILE_TARGET_AGENTS` (default 1000) — budget projection target.
-//! - `OPENHUMAN_PROFILE_RAM_BUDGET_MIB` (default 2048) — budget ceiling.
-//!
-//! `OPENHUMAN_PROFILE_WORKER_THREADS` is honoured in `main` (runtime built
-//! manually) rather than here.
-
-use std::sync::{Arc, Mutex};
-use std::time::{Duration, Instant};
-
-use anyhow::Result;
-use openhuman_core::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::agent::OpenHumanSessionHost;
-use openhuman_core::inference::provider::factory::test_provider_override;
-use openhuman_core::platform::proc_metrics;
-
-use crate::harness::{fixture, measure, FleetBudget, ProfileResult, Recorder, TurnLatency};
-use crate::mock::LatencyMock;
-
-const DEFAULT_AGENTS: usize = 100;
-const DEFAULT_TURNS: usize = 3;
-const DEFAULT_TARGET_AGENTS: u64 = 1000;
-const DEFAULT_RAM_BUDGET_MIB: u64 = 2048;
-const IDLE_WINDOW: Duration = Duration::from_secs(10);
-const FLEET_AGENT_ID: &str = "orchestrator";
-
-fn env_usize(key: &str, default: usize) -> usize {
- std::env::var(key)
- .ok()
- .and_then(|v| v.parse::<usize>().ok())
- .filter(|n| *n > 0)
- .unwrap_or(default)
-}
-
-fn env_u64(key: &str, default: u64) -> u64 {
- std::env::var(key)
- .ok()
- .and_then(|v| v.parse::<u64>().ok())
- .filter(|n| *n > 0)
- .unwrap_or(default)
-}
-
-/// Raise `RLIMIT_NOFILE` toward its hard cap so N agents (each opening SQLite
-/// etc.) don't exhaust the default macOS 256 soft limit. Logs old/new to stderr.
-fn raise_fd_limit() {
- use std::mem::MaybeUninit;
- let mut lim = MaybeUninit::<libc::rlimit>::uninit();
- // SAFETY: `getrlimit` initialises `lim` on success.
- if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, lim.as_mut_ptr()) } != 0 {
- eprintln!("[library-profile] fleet: getrlimit(RLIMIT_NOFILE) failed");
- return;
- }
- // SAFETY: initialised by the successful `getrlimit`.
- let mut lim = unsafe { lim.assume_init() };
- let old_soft = lim.rlim_cur;
- lim.rlim_cur = lim.rlim_max;
- // SAFETY: raising the soft limit to the existing hard limit is always valid.
- let rc = unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &lim) };
- eprintln!(
- "[library-profile] fleet: RLIMIT_NOFILE soft {old_soft} -> {} (hard {}) setrlimit_rc={rc}",
- lim.rlim_cur, lim.rlim_max
- );
-}
-
-/// Shared metrics captured inside the measured closure and read back after.
-#[derive(Default)]
-struct FleetMetrics {
- agents_built: usize,
- baseline_rss_kib: u64,
- constructed_rss_kib: u64,
- idle_cpu_ms: u64,
- latency_ms: Vec<u128>,
-}
-
-/// Percentile (nearest-rank) of an already-sorted slice. `p` in `[0,100]`.
-fn percentile(sorted: &[u128], p: u128) -> u128 {
- if sorted.is_empty() {
- return 0;
- }
- let rank = (p * sorted.len() as u128).div_ceil(100);
- let idx = rank.saturating_sub(1).min(sorted.len() as u128 - 1) as usize;
- sorted[idx]
-}
-
-fn latency_summary(mut samples: Vec<u128>) -> Option<TurnLatency> {
- if samples.is_empty() {
- return None;
- }
- samples.sort_unstable();
- Some(TurnLatency {
- p50: percentile(&samples, 50),
- p95: percentile(&samples, 95),
- p99: percentile(&samples, 99),
- max: *samples.last().unwrap(),
- })
-}
-
-/// Build agents sequentially, checkpointing the marginal-RSS curve. On a
-/// mid-construction failure, records `construction-failed-<count>` and returns
-/// what was built rather than crashing.
-fn build_agents(
- config: &openhuman_core::config::Config,
- n: usize,
- rec: &Recorder,
-) -> Result<Vec<OpenHumanSessionHost>> {
- let stride = (n / 10).max(1);
- let mut agents = Vec::with_capacity(n);
- for i in 0..n {
- match OpenHumanSessionHost::from_config_for_agent(config, FLEET_AGENT_ID) {
- Ok(agent) => agents.push(agent),
- Err(err) => {
- eprintln!(
- "[library-profile] fleet: construction failed at agent {} — {err}",
- i + 1
- );
- rec.checkpoint(format!("construction-failed-{}", agents.len()))?;
- break;
- }
- }
- let built = i + 1;
- if built % stride == 0 || built == n {
- rec.checkpoint(format!("built-{built}"))?;
- }
- }
- Ok(agents)
-}
-
-pub async fn run() -> Result<ProfileResult> {
- let agents_requested = env_usize("OPENHUMAN_PROFILE_AGENTS", DEFAULT_AGENTS);
- let turns = env_usize("OPENHUMAN_PROFILE_TURNS", DEFAULT_TURNS);
- let target_agents = env_u64("OPENHUMAN_PROFILE_TARGET_AGENTS", DEFAULT_TARGET_AGENTS);
- let ram_budget_mib = env_u64("OPENHUMAN_PROFILE_RAM_BUDGET_MIB", DEFAULT_RAM_BUDGET_MIB);
-
- raise_fd_limit();
-
- let fixture = fixture()?;
- openhuman_core::core::bus::init().await.expect("bus init");
- openhuman_core::agent::bus::register_agent_handlers();
- let _ = AgentDefinitionRegistry::init_global_builtins();
- let mock = LatencyMock::from_env("Fleet agent: nothing needs your attention.");
- let _provider = test_provider_override::install_model(mock.clone());
- eprintln!(
- "[library-profile] fleet: agents={agents_requested} turns={turns} \
- target={target_agents} budget_mib={ram_budget_mib}"
- );
-
- let metrics = Arc::new(Mutex::new(FleetMetrics::default()));
- let config = fixture.config.clone();
- let metrics_for_workload = Arc::clone(&metrics);
-
- let mut result = measure(
- "fleet",
- agents_requested,
- Some(turns),
- move |rec| async move {
- rec.checkpoint("baseline")?;
- let baseline_rss = proc_metrics::sample_self()?.rss_kib;
-
- // (b) construct N agents sequentially, curve visible via checkpoints.
- let mut agents = build_agents(&config, agents_requested, &rec)?;
- let agents_built = agents.len();
- rec.checkpoint("constructed")?;
- let constructed_rss = proc_metrics::sample_self()?.rss_kib;
-
- {
- let mut m = metrics_for_workload.lock().expect("metrics lock");
- m.agents_built = agents_built;
- m.baseline_rss_kib = baseline_rss;
- m.constructed_rss_kib = constructed_rss;
- }
- eprintln!(
- "[library-profile] fleet: built {agents_built}/{agents_requested} agents; \
- baseline_rss={baseline_rss} constructed_rss={constructed_rss}"
- );
-
- // (d) idle phase — park all agents, measure CPU drift over 10 s.
- rec.checkpoint("idle-start")?;
- let idle_start = proc_metrics::sample_self()?;
- tokio::time::sleep(IDLE_WINDOW).await;
- rec.checkpoint("idle-end")?;
- let idle_end = proc_metrics::sample_self()?;
- let idle_cpu_ms = (idle_end.cpu_user_ms + idle_end.cpu_system_ms)
- .saturating_sub(idle_start.cpu_user_ms + idle_start.cpu_system_ms);
- metrics_for_workload
- .lock()
- .expect("metrics lock")
- .idle_cpu_ms = idle_cpu_ms;
- eprintln!("[library-profile] fleet: idle CPU over 10s = {idle_cpu_ms} ms");
-
- // (e) load phase — TURNS turns per agent, one task each, staggered.
- let mut handles = Vec::with_capacity(agents.len());
- for (idx, mut agent) in agents.drain(..).enumerate() {
- let stagger = Duration::from_millis(((idx as u64) * 10).min(2000));
- handles.push(tokio::spawn(async move {
- tokio::time::sleep(stagger).await;
- let mut latencies = Vec::with_capacity(turns);
- for _ in 0..turns {
- let started = Instant::now();
- let reply = agent.run_single("Give me a one-line status update.").await;
- let elapsed = started.elapsed().as_millis();
- match reply {
- Ok(text) if !text.trim().is_empty() => latencies.push(elapsed),
- Ok(_) => eprintln!("[library-profile] fleet: empty reply agent={idx}"),
- Err(err) => {
- eprintln!("[library-profile] fleet: turn error agent={idx} — {err}")
- }
- }
- }
- latencies
- }));
- }
-
- let mut all_latencies = Vec::new();
- for handle in handles {
- match handle.await {
- Ok(mut latencies) => all_latencies.append(&mut latencies),
- Err(err) => eprintln!("[library-profile] fleet: task join error — {err}"),
- }
- }
- metrics_for_workload
- .lock()
- .expect("metrics lock")
- .latency_ms = all_latencies;
- rec.checkpoint("load-done")?;
- Ok(())
- },
- )
- .await?;
-
- // Fold fleet-specific metrics into the pinned result.
- let metrics = Arc::try_unwrap(metrics)
- .map(|m| m.into_inner().expect("metrics lock"))
- .unwrap_or_default();
-
- let agents_built = metrics.agents_built;
- let marginal = if agents_built > 0 {
- Some(
- (metrics.constructed_rss_kib as f64 - metrics.baseline_rss_kib as f64)
- / agents_built as f64,
- )
- } else {
- None
- };
-
- // (4) budget projection: settled base + marginal * target.
- let base_mib = metrics.baseline_rss_kib as f64 / 1024.0;
- let marginal_mib = marginal.unwrap_or(0.0) / 1024.0;
- let projected = base_mib + marginal_mib * target_agents as f64;
- let budget = FleetBudget {
- target_agents,
- ram_budget_mib,
- projected_rss_mib_at_target: projected,
- fits: projected <= ram_budget_mib as f64,
- };
-
- result.agents = Some(agents_requested);
- result.agents_built = Some(agents_built);
- result.marginal_rss_kib_per_agent = marginal;
- result.idle_cpu_ms = Some(metrics.idle_cpu_ms);
- result.turn_latency_ms = latency_summary(metrics.latency_ms);
- result.budget = Some(budget);
- Ok(result)
-}
-
-#[cfg(test)]
-#[path = "fleet_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-cli/src/bin/library_profile/scenarios/fleet_tests.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/fleet_tests.rs
deleted file mode 100644
index bac2989769..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/fleet_tests.rs
+++ /dev/null
@@ -1,31 +0,0 @@
-use super::*;
-
-#[test]
-fn percentiles_nearest_rank() {
- let mut v: Vec<u128> = (1..=100).collect();
- v.sort_unstable();
- assert_eq!(percentile(&v, 50), 50);
- assert_eq!(percentile(&v, 95), 95);
- assert_eq!(percentile(&v, 99), 99);
- assert_eq!(percentile(&v, 100), 100);
- assert_eq!(percentile(&[], 50), 0);
- assert_eq!(percentile(&[7], 99), 7);
-}
-
-#[test]
-fn fleet_agent_is_a_shipped_definition() {
- assert!(
- AgentDefinitionRegistry::builtins_only()
- .get(FLEET_AGENT_ID)
- .is_some(),
- "fleet benchmark must construct a current shipped agent"
- );
-}
-
-#[test]
-fn latency_summary_none_when_empty() {
- assert!(latency_summary(Vec::new()).is_none());
- let s = latency_summary(vec![10, 20, 30]).unwrap();
- assert_eq!(s.max, 30);
- assert_eq!(s.p50, 20);
-}
diff --git a/crates/openhuman-cli/src/bin/library_profile/scenarios/long_agent.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/long_agent.rs
deleted file mode 100644
index 389a149966..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/long_agent.rs
+++ /dev/null
@@ -1,53 +0,0 @@
-//! `long-agent`: steady-state many-turn loop on ONE warmed agent — models a
-//! long-running opencompany agent. Builds the agent and runs one warm-up turn
-//! BEFORE the measured region, then runs N sequential turns inside it, pushing
-//! a per-turn checkpoint so the plateau/leak curve is visible.
-
-use anyhow::Result;
-use openhuman_core::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::agent::OpenHumanSessionHost;
-use openhuman_core::inference::provider::factory::test_provider_override;
-
-use crate::harness::{fixture, measure, ProfileResult};
-use crate::mock::PlainTextMock;
-
-const DEFAULT_TURNS: usize = 25;
-
-const PROMPTS: &[&str] = &[
- "Summarise today's Phoenix migration standup in one line.",
- "What is the current staging p99 latency and error rate?",
- "Who owns the rollback runbook and on-call coordination?",
- "When does the phoenix_v2_enabled flag ramp, and what gates it?",
- "Draft a one-sentence status update for the billing-ledger team.",
-];
-
-pub async fn run() -> Result<ProfileResult> {
- let turns = std::env::var("OPENHUMAN_PROFILE_TURNS")
- .ok()
- .and_then(|value| value.parse::<usize>().ok())
- .filter(|n| *n > 0)
- .unwrap_or(DEFAULT_TURNS);
-
- let fixture = fixture()?;
- openhuman_core::core::bus::init().await.expect("bus init");
- openhuman_core::agent::bus::register_agent_handlers();
- let _ = AgentDefinitionRegistry::init_global_builtins();
- let mock = PlainTextMock::new("Phoenix migration is healthy; no action needed.");
- let _provider = test_provider_override::install_model(mock.clone());
-
- let mut agent = OpenHumanSessionHost::from_config_for_agent(&fixture.config, "orchestrator")?;
- eprintln!("[library-profile] long-agent: warming agent with one pre-measure turn");
- let warm = agent.run_single("Warm-up: confirm you are ready.").await?;
- anyhow::ensure!(!warm.trim().is_empty(), "empty warm-up reply");
-
- measure("long-agent", turns, Some(turns), move |rec| async move {
- for i in 0..turns {
- let prompt = PROMPTS[i % PROMPTS.len()];
- let reply = agent.run_single(prompt).await?;
- anyhow::ensure!(!reply.trim().is_empty(), "empty reply on turn {i}");
- rec.checkpoint(format!("turn-{i}"))?;
- }
- Ok(())
- })
- .await
-}
diff --git a/crates/openhuman-cli/src/bin/library_profile/scenarios/mod.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/mod.rs
deleted file mode 100644
index 922f15e061..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/mod.rs
+++ /dev/null
@@ -1,17 +0,0 @@
-//! One module per profiling scenario. Each exposes a single
-//! `run() -> Result<ProfileResult>` entry point dispatched from `main`.
-//!
-//! `memory-ingest` and `cold-phases` are absent. Both measured the memory
-//! engine embedded in this process — `memory_ingest` drained its queue,
-//! `cold_phases` checkpointed its bootstrap through
-//! `tinymemory_core::store::MemoryClient` — and this binary no longer links
-//! one (openhuman#6161). Re-adding them means measuring the memory *module*
-//! over the bus, which is a different scenario and wants a fresh design
-//! rather than a revived file.
-
-pub mod agent_turn;
-pub mod fleet;
-pub mod long_agent;
-pub mod skill_run;
-pub mod subagent_storm;
-pub mod workflow;
diff --git a/crates/openhuman-cli/src/bin/library_profile/scenarios/skill_run.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/skill_run.rs
deleted file mode 100644
index 071d34a07d..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/skill_run.rs
+++ /dev/null
@@ -1,240 +0,0 @@
-//! `skill-run`: the true, process-*tree* cost of a skill step that executes on
-//! a real language runtime — the interpreter child process included — and the
-//! regression instrument for the shared runtime pool (issue #5106).
-//!
-//! ## What it actually runs
-//!
-//! The orchestrator carries `node_exec` as a `Deferred` tool: off the wire,
-//! found through `tool_search` (or skill `coding`), and callable by name once
-//! found. There is no separate code-executing specialist any more, so the
-//! agent that genuinely spawns the language runtime *is* the orchestrator. This
-//! scenario drives it directly — one turn, one scripted `node_exec` call —
-//! which is the real node-executing path, not a bare `std::process` spawn.
-//!
-//! ## Concurrency knob (K parallel skill runs)
-//!
-//! `OPENHUMAN_PROFILE_SKILL_RUN_CONCURRENCY=K` (default 1) drives **K**
-//! orchestrator turns in parallel, each emitting its own `node_exec` call.
-//! The point of #5106: with the runtime pool **on**, K concurrent skill runs
-//! share a small bounded set of warm `node` workers, so the process tree grows
-//! by ~one pooled worker — **not** K interpreters. This scenario asserts that
-//! (`tree.child_count <= max_workers`) whenever pooling is on and K > 1, so a
-//! regression that reintroduces per-run forking fails the profiling suite.
-//!
-//! Toggle for an A/B baseline:
-//!
-//! * `OPENHUMAN_PROFILE_SKILL_RUN_POOL=off` — disable the pool (legacy per-call
-//! spawn); the tree then shows ~K resident `node` children at peak.
-//! * `OPENHUMAN_PROFILE_SKILL_RUN_POOL_WORKERS=W` — pool size (default 1, for a
-//! tight, deterministic bound).
-//!
-//! ## No interpreter download
-//!
-//! `node.prefer_system = true` (the default) means a host `node` whose **major**
-//! matches the configured target is reused rather than downloaded. This
-//! scenario **requires** a system `node` and bails with a clear stderr error +
-//! nonzero exit if none is on `PATH` — it must never pull a runtime.
-//!
-//! The measured cost lands in `result.tree` (`tree_rss_kib`, `child_count`,
-//! per-child RSS), captured at the workload peak.
-
-use anyhow::{Context, Result};
-use openhuman_core::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::agent::OpenHumanSessionHost;
-use openhuman_core::config::Config;
-use openhuman_core::inference::provider::factory::test_provider_override;
-use openhuman_core::security::AutonomyLevel;
-
-use crate::harness::{fixture, measure_with_tree, EnvGuard, ProfileResult};
-use crate::mock::SkillRunMock;
-
-/// The agent that reaches `node_exec` (a `Deferred` tool) and spawns the
-/// runtime child.
-const CODE_AGENT: &str = "orchestrator";
-
-/// Probe for a usable system `node`. Returns its version on success; on failure
-/// prints a clear `[library-profile]` stderr error and returns `Err` (which
-/// propagates to a nonzero process exit). We must NOT download an interpreter.
-fn require_system_node() -> Result<String> {
- match std::process::Command::new("node").arg("--version").output() {
- Ok(output) if output.status.success() => {
- let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
- eprintln!("[library-profile] skill-run: using system node {version}");
- Ok(version)
- }
- Ok(output) => {
- let stderr = String::from_utf8_lossy(&output.stderr);
- eprintln!(
- "[library-profile] skill-run: `node --version` failed (status {:?}): {stderr}",
- output.status.code()
- );
- anyhow::bail!("skill-run requires a working system `node`, but `node --version` failed")
- }
- Err(err) => {
- eprintln!(
- "[library-profile] skill-run: `node` not found on PATH: {err}. Install Node.js — \
- the profiler will NOT download an interpreter."
- );
- anyhow::bail!("skill-run requires a system `node` on PATH; none found")
- }
- }
-}
-
-/// Read a `>= 1` usize from the environment. Absent ⇒ `default`; present but not
-/// a positive integer ⇒ a hard error (silently coercing a bad `0`/garbage value
-/// would change the workload and bypass the `K > 1` pool gate).
-fn env_usize(key: &str, default: usize) -> Result<usize> {
- match std::env::var(key) {
- Err(_) => Ok(default),
- Ok(raw) => {
- let n: usize = raw
- .trim()
- .parse()
- .with_context(|| format!("{key}={raw:?} is not a valid integer"))?;
- anyhow::ensure!(n >= 1, "{key}={raw:?} must be >= 1");
- Ok(n)
- }
- }
-}
-
-/// Apply the `[runtime_pool]` settings to the in-memory fixture config. The exec
-/// tools snapshot `config.runtime_pool` at construction (the pool config is
-/// injected, never re-read from disk on the hot path), so mutating the config
-/// the agent is built from is what toggles pooling for the scenario.
-fn apply_pool_config(config: &mut Config, pool_enabled: bool, workers: usize) {
- config.runtime_pool.enabled = pool_enabled;
- config.runtime_pool.node.max_workers = workers;
- config.runtime_pool.node.idle_ttl_secs = 300;
- config.runtime_pool.node.recycle_after_jobs = 0;
-}
-
-pub async fn run() -> Result<ProfileResult> {
- // Hard requirement: a system node must be present (no download).
- require_system_node()?;
-
- let concurrency = env_usize("OPENHUMAN_PROFILE_SKILL_RUN_CONCURRENCY", 1)?;
- let pool_enabled = std::env::var("OPENHUMAN_PROFILE_SKILL_RUN_POOL")
- .map(|v| !v.trim().eq_ignore_ascii_case("off"))
- .unwrap_or(true);
- let pool_workers = env_usize("OPENHUMAN_PROFILE_SKILL_RUN_POOL_WORKERS", 1)?;
-
- // `node_exec` is a Write-class acting tool. Full autonomy keeps the gate
- // from parking the turn on approval; the gate is also opted out explicitly.
- let mut fixture = fixture()?;
- fixture.config.autonomy.level = AutonomyLevel::Full;
- apply_pool_config(&mut fixture.config, pool_enabled, pool_workers);
- let _approval_env = EnvGuard::set("OPENHUMAN_APPROVAL_GATE", "0");
-
- openhuman_core::core::bus::init().await.expect("bus init");
- openhuman_core::agent::bus::register_agent_handlers();
- let _ = AgentDefinitionRegistry::init_global_builtins();
-
- let mock = SkillRunMock::new();
- let _provider = test_provider_override::install_model(mock.clone());
- eprintln!(
- "[library-profile] skill-run: registries ready, node_exec mock installed \
- (agent={CODE_AGENT}, concurrency={concurrency}, pool={}, pool_workers={pool_workers})",
- if pool_enabled { "on" } else { "off" }
- );
-
- let mock_for_workload = mock.clone();
- let config = fixture.config.clone();
- let mut result = measure_with_tree("skill-run", concurrency, None, move |rec| async move {
- rec.checkpoint("turn-start")?;
- // Drive K orchestrator turns concurrently. `join_all` gives real
- // process-level parallelism (each node_exec awaits its own child /
- // pooled job) without requiring the agent future to be `Send`.
- let futures = (0..concurrency).map(|idx| {
- let config = config.clone();
- async move {
- let mut agent = OpenHumanSessionHost::from_config_for_agent(&config, CODE_AGENT)
- .with_context(|| format!("building {CODE_AGENT} agent #{idx}"))?;
- let reply = agent
- .run_single(
- "Run a short JavaScript computation with node_exec and report the JSON it prints.",
- )
- .await
- .with_context(|| format!("{CODE_AGENT} turn #{idx}"))?;
- anyhow::ensure!(!reply.trim().is_empty(), "empty {CODE_AGENT} reply #{idx}");
- Ok::<(), anyhow::Error>(())
- }
- });
- let outcomes = futures::future::join_all(futures).await;
- for outcome in outcomes {
- outcome?;
- }
- rec.checkpoint("turn-done")?;
- anyhow::ensure!(
- mock_for_workload.node_call_emitted(),
- "the node_exec tool call was never emitted"
- );
- anyhow::ensure!(
- mock_for_workload.node_output_seen(),
- "the node child's output never flowed back — the interpreter child did not run/print"
- );
- Ok(())
- })
- .await?;
-
- match result.tree.as_ref() {
- Some(tree) if tree.child_count >= 1 => {
- eprintln!(
- "[library-profile] skill-run: captured tree_rss_kib={} child_count={} \
- concurrency={concurrency} pool={} children={:?}",
- tree.tree_rss_kib,
- tree.child_count,
- if pool_enabled { "on" } else { "off" },
- tree.children
- );
- }
- Some(tree) => {
- eprintln!(
- "[library-profile] skill-run: tree captured but no child resident at peak \
- (tree_rss_kib={}). With the pool on this is expected between jobs; with the \
- pool off the node child may have been too short-lived.",
- tree.tree_rss_kib
- );
- }
- None => {
- eprintln!("[library-profile] skill-run: WARNING no process-tree sample captured");
- }
- }
-
- // DoD gate (#5106): with pooling on, K concurrent skill runs must not fork K
- // interpreters — the tree grows by ~one pooled worker. A regression that
- // reintroduces per-run forking makes child_count scale with K and fails here.
- if pool_enabled && concurrency > 1 {
- // Require a real measurement: a missing tree or zero children would let
- // the gate "pass" without ever observing an interpreter. With the
- // scenario's 300 s idle TTL the pooled worker is resident at sample time,
- // so this must hold.
- let tree = result.tree.as_ref().ok_or_else(|| {
- anyhow::anyhow!(
- "pool gate: no process-tree sample captured for K={concurrency}; cannot verify \
- the pooled worker (tree sampling is required for this gate)"
- )
- })?;
- anyhow::ensure!(
- tree.child_count >= 1,
- "pool gate: process tree captured zero interpreter children at K={concurrency}; \
- the pooled worker was not observed"
- );
- anyhow::ensure!(
- tree.child_count <= pool_workers,
- "runtime pool failed to bound interpreters: child_count={} exceeds max_workers={} \
- at concurrency K={} — expected warm-worker reuse, not K forked children",
- tree.child_count,
- pool_workers,
- concurrency
- );
- eprintln!(
- "[library-profile] skill-run: POOL OK — {} node worker(s) served {concurrency} \
- concurrent skill runs (would be ~{concurrency} interpreters unpooled)",
- tree.child_count
- );
- }
-
- // Fold in scenario-visible fields (schema stays additive).
- result.workload_units = concurrency;
- Ok(result)
-}
diff --git a/crates/openhuman-cli/src/bin/library_profile/scenarios/subagent_storm.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/subagent_storm.rs
deleted file mode 100644
index e26e7eb5b7..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/subagent_storm.rs
+++ /dev/null
@@ -1,167 +0,0 @@
-//! `subagent-storm`: fuzz the *width* of delegation inside ONE core instance.
-//!
-//! One orchestrator turn fans out to **K** parallel `vision_agent` subagents (all
-//! in-process tokio tasks, not child processes) via `spawn_parallel_agents`.
-//! K comes from `OPENHUMAN_PROFILE_SUBAGENTS` (default 8; tested up to 32), and
-//! each worker carries per-subagent mock latency drawn from the shared
-//! `OPENHUMAN_PROFILE_MOCK_LATENCY_MS` / `_JITTER_MS` knobs.
-//!
-//! ## Measurement shape (and a hard constraint we hit)
-//!
-//! The intended shape was: prewarm one width-K fan-out, then measure a second on
-//! the same warm process so the delta is attributable to the K children rather
-//! than cold bootstrap. That is **not achievable** here: the parallel-spawn
-//! machinery is effectively one-shot per process. Once a fan-out's run ledger is
-//! finalized, a second `spawn_parallel_agents` returns an empty result and the
-//! orchestrator just re-calls the tool without re-running the workers. Worse,
-//! merely *constructing* an orchestrator/vision_agent agent beforehand perturbs
-//! the fan-out the same way. The only shape that reliably executes all K real
-//! vision_agent subagents is a single fan-out as the process's first agent
-//! activity.
-//!
-//! So this scenario measures exactly that: one cold width-K fan-out. `retained_delta_kib`
-//! therefore includes the shared per-process bootstrap (~20–30 MiB every
-//! scenario pays once) amortized across K, so a single run's
-//! `marginal_rss_kib_per_agent = retained_delta_kib / K` is an **upper bound**,
-//! not the true marginal. Read the true marginal by comparing runs: the fixed
-//! bootstrap amortizes, so `(retained(K₂) - retained(K₁)) / (K₂ - K₁)` across
-//! two widths (e.g. K=8 vs K=32) isolates the genuine per-additional-subagent
-//! cost. `peak_delta_kib` additionally captures the K-concurrent peak.
-//!
-//! Reported fields: `subagents = K`, `marginal_rss_kib_per_agent` (retained/K,
-//! upper bound), `checkpoints` (baseline → storm-turn-done), and
-//! `turn_latency_ms` (percentiles across the K vision_agent child executions).
-//! The workload asserts all K vision_agent subagents actually executed.
-//!
-//! The worker is `vision_agent`: a read-only worker-tier agent with a small
-//! memory tool surface, no spawn tools, and in the orchestrator's `[subagents] allowlist` —
-//! the closest surviving fit for the retired `researcher` archetype this
-//! scenario used to fan out to.
-
-use anyhow::Result;
-use openhuman_core::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::agent::OpenHumanSessionHost;
-use openhuman_core::inference::provider::factory::test_provider_override;
-
-use crate::harness::{fixture, measure, ProfileResult, TurnLatency};
-use crate::mock::{subagent_marker, SubagentMock};
-
-const DEFAULT_SUBAGENTS: usize = 8;
-
-/// The orchestrator's top-level task. The mock ignores the wording and always
-/// fans out to K vision_agent workers.
-const STORM_PROMPT: &str = "Research every subsystem in parallel and merge the findings.";
-
-/// Positive identity anchor for an vision_agent *worker* turn — its own
-/// system prompt (`memory/agent/agent/prompt.md`) names it. Distinguishes a real worker
-/// from the orchestrator turns that also echo every task marker in the fan-out
-/// tool call / result.
-const WORKER_IDENTITY: &str = "You are a memory retrieval specialist.";
-
-fn env_usize(key: &str, default: usize) -> usize {
- std::env::var(key)
- .ok()
- .and_then(|value| value.parse::<usize>().ok())
- .filter(|n| *n > 0)
- .unwrap_or(default)
-}
-
-/// Nearest-rank percentile of an already-sorted slice. `p` in `[0, 100]`.
-fn percentile(sorted: &[u128], p: u128) -> u128 {
- if sorted.is_empty() {
- return 0;
- }
- let rank = (p * sorted.len() as u128).div_ceil(100);
- let idx = rank.saturating_sub(1).min(sorted.len() as u128 - 1) as usize;
- sorted[idx]
-}
-
-fn latency_summary(mut samples: Vec<u128>) -> Option<TurnLatency> {
- if samples.is_empty() {
- return None;
- }
- samples.sort_unstable();
- Some(TurnLatency {
- p50: percentile(&samples, 50),
- p95: percentile(&samples, 95),
- p99: percentile(&samples, 99),
- max: *samples.last().unwrap(),
- })
-}
-
-pub async fn run() -> Result<ProfileResult> {
- let width = env_usize("OPENHUMAN_PROFILE_SUBAGENTS", DEFAULT_SUBAGENTS);
-
- let mut fixture = fixture()?;
- // `spawn_parallel_agents` rejects a fan-out wider than the orchestrator's
- // `max_parallel_tools` (default 4). Raise it to K so the full width actually
- // spawns instead of erroring back to a re-spawn loop.
- fixture.config.agent.max_parallel_tools = width.max(4);
- openhuman_core::core::bus::init().await.expect("bus init");
- openhuman_core::agent::bus::register_agent_handlers();
- let _ = AgentDefinitionRegistry::init_global_builtins();
-
- let mock = SubagentMock::with_width(width);
- let _provider = test_provider_override::install_model(mock.clone());
- eprintln!("[library-profile] subagent-storm: width={width} — single cold width-K fan-out");
-
- // We drive the `orchestrator` agent directly: it owns `spawn_parallel_agents`
- // and allows the `vision_agent` subagent. One orchestrator turn fans out to
- // K real vision_agent subagents via the parallel graph. This fan-out MUST be
- // the process's first agent activity — see the module docs for why prewarming
- // is not possible here.
- let config = fixture.config.clone();
- let mock_for_workload = mock.clone();
- let mut result = measure("subagent-storm", width, None, move |rec| async move {
- rec.checkpoint("baseline")?;
- let mut agent = OpenHumanSessionHost::from_config_for_agent(&config, "orchestrator")?;
- let reply = agent.run_single(STORM_PROMPT).await?;
- rec.checkpoint("storm-turn-done")?;
- anyhow::ensure!(!reply.trim().is_empty(), "empty storm-turn response");
- // Every one of the K vision_agent subagents must have actually executed as
- // its own worker turn: for each i there must be a prompt that carries the
- // vision_agent identity anchor AND that worker's task marker — not
- // merely an orchestrator turn echoing every marker in the fan-out call.
- let prompts = mock_for_workload.prompts.lock().expect("mock prompt lock");
- for i in 1..=width {
- anyhow::ensure!(
- prompts
- .iter()
- .any(|p| p.contains(WORKER_IDENTITY) && p.contains(&subagent_marker(i))),
- "vision_agent subagent {i}/{width} never executed as its own worker turn"
- );
- }
- Ok(())
- })
- .await?;
-
- // Marginal per subagent = retained / K. An UPPER BOUND: `retained_delta_kib`
- // still carries the one-time per-process bootstrap (see module docs), so the
- // true marginal is the cross-width delta `(retained(K₂)-retained(K₁))/(K₂-K₁)`.
- let marginal = if width > 0 {
- Some(result.retained_delta_kib as f64 / width as f64)
- } else {
- None
- };
- let latencies = mock
- .worker_latencies_ms
- .lock()
- .expect("mock latency lock")
- .clone();
- eprintln!(
- "[library-profile] subagent-storm: width={width} retained_delta_kib={} \
- marginal_rss_kib_per_agent={:?} worker_executions={}",
- result.retained_delta_kib,
- marginal,
- latencies.len()
- );
-
- result.subagents = Some(width);
- result.marginal_rss_kib_per_agent = marginal;
- result.turn_latency_ms = latency_summary(latencies);
- Ok(result)
-}
-
-#[cfg(test)]
-#[path = "subagent_storm_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-cli/src/bin/library_profile/scenarios/subagent_storm_tests.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/subagent_storm_tests.rs
deleted file mode 100644
index 78ceef8a25..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/subagent_storm_tests.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-use super::*;
-
-#[test]
-fn percentiles_nearest_rank() {
- let v: Vec<u128> = (1..=100).collect();
- assert_eq!(percentile(&v, 50), 50);
- assert_eq!(percentile(&v, 95), 95);
- assert_eq!(percentile(&v, 99), 99);
- assert_eq!(percentile(&v, 100), 100);
- assert_eq!(percentile(&[], 50), 0);
-}
-
-#[test]
-fn latency_summary_none_when_empty() {
- assert!(latency_summary(Vec::new()).is_none());
- let s = latency_summary(vec![10, 20, 30]).unwrap();
- assert_eq!(s.max, 30);
- assert_eq!(s.p50, 20);
-}
-
-#[test]
-fn env_usize_falls_back_on_zero_or_unset() {
- assert_eq!(env_usize("OPENHUMAN_PROFILE_STORM_UNSET_XYZ", 8), 8);
-}
diff --git a/crates/openhuman-cli/src/bin/library_profile/scenarios/workflow.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/workflow.rs
deleted file mode 100644
index da37f86366..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/workflow.rs
+++ /dev/null
@@ -1,71 +0,0 @@
-//! `workflow`: run a real flows-domain workflow end to end. A
-//! trigger -> transform -> agent graph is created OUTSIDE the measured region
-//! (recorded as a checkpoint), then `flows_run` is measured as the workload.
-//! The agent node's LLM routes through the plain-text mock provider.
-
-use anyhow::Result;
-use openhuman_core::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::flows::ops::{flows_create, flows_run};
-use openhuman_core::flows::FlowRunTrigger;
-use openhuman_core::inference::provider::factory::test_provider_override;
-use serde_json::json;
-
-use crate::harness::{fixture, measure, ProfileResult};
-use crate::mock::PlainTextMock;
-
-pub async fn run() -> Result<ProfileResult> {
- let fixture = fixture()?;
- openhuman_core::core::bus::init().await.expect("bus init");
- openhuman_core::agent::bus::register_agent_handlers();
- let _ = AgentDefinitionRegistry::init_global_builtins();
- let mock = PlainTextMock::new("Phoenix migration status: healthy, ramp on Friday.");
- let _provider = test_provider_override::install_model(mock.clone());
-
- let graph = json!({
- "name": "profile-workflow",
- "nodes": [
- { "id": "t", "kind": "trigger", "name": "Trigger" },
- { "id": "prep", "kind": "transform", "name": "Prep",
- "config": { "set": { "topic": "Phoenix migration" } } },
- { "id": "summarize", "kind": "agent", "name": "Summarize",
- "config": { "agent_ref": "agent_memory",
- "prompt": "Summarise the Phoenix migration status in one line." } }
- ],
- "edges": [
- { "from_node": "t", "to_node": "prep" },
- { "from_node": "prep", "to_node": "summarize" }
- ]
- });
-
- eprintln!("[library-profile] workflow: creating flow (outside measured region)");
- let flow = flows_create(&fixture.config, "profile-workflow".into(), graph, false)
- .await
- .map_err(anyhow::Error::msg)?
- .value;
- let flow_id = flow.id.clone();
-
- measure("workflow", 1, None, move |_rec| async move {
- let outcome = flows_run(
- &fixture.config,
- &flow_id,
- json!({ "topic": "Phoenix migration" }),
- serde_json::Map::new(),
- FlowRunTrigger::Rpc,
- )
- .await
- .map_err(anyhow::Error::msg)?;
- let output = outcome.value.get("output");
- anyhow::ensure!(
- output.is_some() && !output.unwrap().is_null(),
- "workflow run produced no output: {}",
- outcome.value
- );
- anyhow::ensure!(
- outcome.value.get("note").is_none(),
- "workflow with an actionable agent node unexpectedly reported nothing-to-run: {}",
- outcome.value
- );
- Ok(())
- })
- .await
-}
diff --git a/crates/openhuman-cli/src/bin/rss_bench.rs b/crates/openhuman-cli/src/bin/rss_bench.rs
deleted file mode 100644
index 735de31562..0000000000
--- a/crates/openhuman-cli/src/bin/rss_bench.rs
+++ /dev/null
@@ -1,325 +0,0 @@
-//! `rss-bench` — steady-state RSS benchmark for an embedded `openhuman_core`
-//! agent roster (#5046).
-//!
-//! Mirrors the OpenCompany embedding contract: a bare [`OpenHumanSessionHost`] built directly
-//! via [`OpenHumanSessionHost::builder`] (no `CoreBuilder`, no RPC, no background services)
-//! with an injected mock model and a per-agent temp workspace. Builds a 1-agent and an 8-agent roster, runs one
-//! deterministic warm-up turn per agent to fault in lazy allocations, settles,
-//! then samples `/proc/self/{status,smaps_rollup}`.
-//!
-//! Two modes:
-//! * `--child --roster N` builds one roster in a **fresh process**, warms up,
-//! settles, and prints one [`ProcSample`] JSON line. This is the isolated
-//! measured workload.
-//! * default (parent) re-execs itself `--repeat` times per roster size to get
-//! independent cold samples, aggregates, writes the raw JSON report
-//! (`--out`), and prints a human summary.
-//!
-//! Gated behind the default-OFF `rss-bench` feature so no benchmark code enters
-//! the shipped desktop/library build. Build & run:
-//! `cargo build --release --features rss-bench --bin rss-bench`.
-//!
-//! The pure sampling/aggregation logic lives in
-//! [`openhuman_core::platform::proc_metrics`]; this binary is the fixture +
-//! process driver.
-
-use anyhow::{Context, Result};
-use async_trait::async_trait;
-use openhuman_core::agent::OpenHumanSessionHost;
-use openhuman_core::platform::proc_metrics::{
- self, BenchReport, ProcSample, RosterResult, REPORT_SCHEMA_VERSION, RSS_BUDGET_KIB,
- RSS_HARD_CAP_KIB,
-};
-use tinytools::{Tool, ToolResult};
-use tinytools_agent::dialect::NativeDialect;
-
-use std::path::PathBuf;
-use std::process::Stdio;
-use std::sync::Arc;
-use std::time::Duration;
-use tempfile::TempDir;
-use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse};
-
-/// Roster sizes measured by default: the 1-agent baseline and the
-/// representative 8-agent company roster from #5046.
-const DEFAULT_ROSTER_SIZES: &[usize] = &[1, 8];
-/// Fresh processes sampled per roster size (≥ 5 per the issue).
-const DEFAULT_REPEAT: usize = 5;
-/// Per-child wall-clock budget. A child does bounded work (build a roster, one
-/// warm-up turn, a ≤2 s settle), so anything beyond this is a stall — kill it and
-/// fail the run rather than letting one bad child block the whole benchmark until
-/// the outer CI job timeout.
-const CHILD_TIMEOUT: Duration = Duration::from_secs(120);
-
-/// Model that never touches the network: returns a fixed assistant message
-/// with a `stop` shape (no tool calls) so a turn completes in one round-trip.
-struct MockModel;
-
-#[async_trait]
-impl ChatModel<()> for MockModel {
- async fn invoke(
- &self,
- _state: &(),
- _request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- Ok(ModelResponse::assistant("ok"))
- }
-}
-
-/// Trivial host-supplied tool so the roster mirrors a real embedding (the host
-/// injects its own tools). Never invoked — the model returns no tool calls.
-struct EchoTool;
-
-#[async_trait]
-impl Tool for EchoTool {
- fn name(&self) -> &str {
- "echo"
- }
-
- fn description(&self) -> &str {
- "echo"
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({ "type": "object" })
- }
-
- async fn execute(&self, _args: serde_json::Value) -> Result<ToolResult> {
- Ok(ToolResult::success("echo"))
- }
-}
-
-/// A built roster plus the temp workspaces that must outlive it — dropping the
-/// `TempDir`s would delete the agents' workspaces mid-measurement.
-struct Roster {
- agents: Vec<OpenHumanSessionHost>,
- _workspaces: Vec<TempDir>,
-}
-
-/// Build `n` bare agents, each with its own temp workspace, mock model,
-/// `"none"` memory backend, and a single host-supplied tool.
-fn build_roster(n: usize) -> Result<Roster> {
- // Root turns now go through the hosted TinyAgents path, which requires a
- // definition registry to supply durable host authority. This fixture has
- // no workspace-specific definitions, so the built-in catalogue is the
- // smallest representative setup.
- openhuman_core::agent::harness::AgentDefinitionRegistry::init_global_builtins()?;
-
- let mut agents = Vec::with_capacity(n);
- let mut workspaces = Vec::with_capacity(n);
- for _ in 0..n {
- let workspace = TempDir::new().context("create temp workspace")?;
- let path = workspace.path().to_path_buf();
-
- let agent = OpenHumanSessionHost::builder()
- .chat_model(Arc::new(MockModel))
- .tools(vec![Box::new(EchoTool)])
- .tool_dispatcher(Box::new(NativeDialect))
- .model_name("bench-mock".into())
- // Use a real built-in id because the hosted invocation resolves
- // root authority through the definition registry.
- .agent_definition_name("orchestrator")
- .workspace_dir(path.clone())
- .action_dir(path)
- .build()
- .context("build bench agent")?;
- agents.push(agent);
- workspaces.push(workspace);
- }
- Ok(Roster {
- agents,
- _workspaces: workspaces,
- })
-}
-
-/// One deterministic warm-up turn per agent, forcing first-touch allocations
-/// (prompt build, tokenizer, model seam) to fault in before measuring.
-async fn warm_up(roster: &mut Roster) -> Result<()> {
- for agent in &mut roster.agents {
- let _ = agent.turn("warmup").await.context("warm-up turn")?;
- }
- Ok(())
-}
-
-/// Poll RSS until it stops climbing (Δ < 256 KiB between reads ~200 ms apart)
-/// or a 2 s cap, draining async task-allocation jitter. No-op off Linux.
-async fn settle() {
- let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
- let mut last = proc_metrics::sample_self().map(|s| s.rss_kib).unwrap_or(0);
- loop {
- tokio::time::sleep(Duration::from_millis(200)).await;
- let now = proc_metrics::sample_self()
- .map(|s| s.rss_kib)
- .unwrap_or(last);
- if now.abs_diff(last) < 256 || tokio::time::Instant::now() >= deadline {
- break;
- }
- last = now;
- }
-}
-
-/// Child mode: build one roster in this fresh process, warm up, settle, sample,
-/// and print the sample as a single JSON line on stdout.
-async fn run_child(roster_size: usize) -> Result<()> {
- // Diagnostics go to stderr so they never corrupt the single JSON line the
- // parent parses from stdout.
- eprintln!("[rss-bench] child: building {roster_size}-agent roster");
- let mut roster = build_roster(roster_size)?;
- eprintln!("[rss-bench] child: warming up {roster_size} agent(s)");
- warm_up(&mut roster).await?;
- eprintln!("[rss-bench] child: settling");
- settle().await;
- let sample = proc_metrics::sample_self()?;
- eprintln!(
- "[rss-bench] child: sampled rss={}KiB threads={}",
- sample.rss_kib, sample.threads
- );
- println!("{}", serde_json::to_string(&sample)?);
- drop(roster); // keep the roster alive until after the sample is taken
- Ok(())
-}
-
-/// Parent mode: re-exec the child `repeat` times per roster size, aggregate, and
-/// write the report.
-async fn run_parent(out: Option<PathBuf>, repeat: usize, roster_sizes: &[usize]) -> Result<()> {
- let exe = std::env::current_exe().context("resolve current exe")?;
- let mut rosters = Vec::with_capacity(roster_sizes.len());
- for &size in roster_sizes {
- let mut samples = Vec::with_capacity(repeat);
- for run in 0..repeat {
- eprintln!("[rss-bench] spawn child roster={size} run={run}");
- // `kill_on_drop` + a `timeout` around `wait_with_output` gives a
- // robust kill-and-reap: on timeout the cancelled future drops the
- // child, `kill_on_drop` sends SIGKILL, and the tokio runtime reaps it.
- let child = tokio::process::Command::new(&exe)
- .arg("--child")
- .arg("--roster")
- .arg(size.to_string())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .kill_on_drop(true)
- .spawn()
- .with_context(|| format!("spawn child roster={size} run={run}"))?;
- let output = match tokio::time::timeout(CHILD_TIMEOUT, child.wait_with_output()).await {
- Ok(res) => res.with_context(|| format!("await child roster={size} run={run}"))?,
- Err(_) => {
- eprintln!(
- "[rss-bench] child roster={size} run={run} timed out after {}s; killed",
- CHILD_TIMEOUT.as_secs()
- );
- anyhow::bail!(
- "child roster={size} run={run} timed out after {}s",
- CHILD_TIMEOUT.as_secs()
- );
- }
- };
- if !output.status.success() {
- eprintln!("[rss-bench] child roster={size} run={run} exited non-zero");
- anyhow::bail!(
- "child roster={size} run={run} failed: {}",
- String::from_utf8_lossy(&output.stderr)
- );
- }
- let stdout = String::from_utf8_lossy(&output.stdout);
- let line = stdout
- .lines()
- .rev()
- .find(|l| !l.trim().is_empty())
- .unwrap_or("")
- .trim();
- let sample: ProcSample = serde_json::from_str(line)
- .with_context(|| format!("parse child sample (roster={size}): {line:?}"))?;
- eprintln!(
- "[rss-bench] child roster={size} run={run} ok rss={}KiB",
- sample.rss_kib
- );
- samples.push(sample);
- }
- rosters.push(RosterResult::from_samples(size, samples));
- }
-
- let report = BenchReport {
- schema_version: REPORT_SCHEMA_VERSION,
- git_sha: git_sha(),
- kernel: kernel(),
- rss_budget_kib: RSS_BUDGET_KIB,
- rss_hard_cap_kib: RSS_HARD_CAP_KIB,
- rosters,
- };
-
- if let Some(path) = out {
- std::fs::write(&path, serde_json::to_string_pretty(&report)?)
- .with_context(|| format!("write report to {}", path.display()))?;
- }
- println!("{}", proc_metrics::human_summary(&report));
- Ok(())
-}
-
-/// Best-effort commit id for the report header (`GITHUB_SHA` in CI).
-fn git_sha() -> String {
- std::env::var("GITHUB_SHA").unwrap_or_else(|_| "unknown".into())
-}
-
-/// Best-effort kernel version for the report header.
-fn kernel() -> String {
- std::fs::read_to_string("/proc/sys/kernel/osrelease")
- .map(|s| s.trim().to_string())
- .unwrap_or_else(|_| std::env::consts::OS.to_string())
-}
-
-/// Minimal flag parse — avoids a clap dependency for four flags.
-struct Args {
- child: bool,
- roster: usize,
- repeat: usize,
- out: Option<PathBuf>,
-}
-
-fn parse_args() -> Result<Args> {
- let mut child = false;
- let mut roster = 1usize;
- let mut repeat = DEFAULT_REPEAT;
- let mut out = None;
- let mut it = std::env::args().skip(1);
- while let Some(arg) = it.next() {
- match arg.as_str() {
- "--child" => child = true,
- "--roster" => {
- roster = it
- .next()
- .context("--roster needs a value")?
- .parse()
- .context("--roster value")?;
- }
- "--repeat" => {
- repeat = it
- .next()
- .context("--repeat needs a value")?
- .parse()
- .context("--repeat value")?;
- }
- "--out" => out = Some(PathBuf::from(it.next().context("--out needs a path")?)),
- other => anyhow::bail!("unknown argument: {other}"),
- }
- }
- Ok(Args {
- child,
- roster,
- repeat,
- out,
- })
-}
-
-#[tokio::main]
-async fn main() -> Result<()> {
- let args = parse_args()?;
- if args.child {
- run_child(args.roster).await
- } else {
- run_parent(args.out, args.repeat, DEFAULT_ROSTER_SIZES).await
- }
-}
-
-#[cfg(test)]
-#[path = "rss_bench_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-cli/src/bin/rss_bench_tests.rs b/crates/openhuman-cli/src/bin/rss_bench_tests.rs
deleted file mode 100644
index 74eef62e6e..0000000000
--- a/crates/openhuman-cli/src/bin/rss_bench_tests.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-use super::*;
-
-#[test]
-fn build_roster_constructs_bare_agents_with_isolated_workspaces() {
- let roster = build_roster(8).expect("8-agent roster builds");
- assert_eq!(roster.agents.len(), 8);
- assert_eq!(roster._workspaces.len(), 8);
- // Each agent got a distinct workspace directory.
- let mut dirs: Vec<_> = roster
- ._workspaces
- .iter()
- .map(|w| w.path().to_path_buf())
- .collect();
- dirs.sort();
- dirs.dedup();
- assert_eq!(dirs.len(), 8, "workspaces must be isolated per agent");
-}
-
-#[test]
-fn warm_up_turn_completes_without_network() {
- // The agent-turn future is large in debug builds. Run it on a worker
- // with explicit stack headroom instead of libtest's smaller default.
- let runtime = tokio::runtime::Builder::new_multi_thread()
- .worker_threads(1)
- .enable_all()
- .thread_stack_size(8 * 1024 * 1024)
- .build()
- .expect("test runtime builds");
- runtime
- .block_on(runtime.spawn(async {
- let mut roster = build_roster(1).expect("1-agent roster builds");
- warm_up(&mut roster).await.expect("warm-up turn completes");
- // The mock provider reports usage, so last_turn_usage is populated —
- // proving the embedding cost-metering contract works on the bare Agent.
- assert!(
- roster.agents[0].last_turn_usage().is_some(),
- "usage should be readable after a turn"
- );
- }))
- .expect("warm-up task joins");
-}
diff --git a/crates/openhuman-cli/src/bin/tool_dialect_bench.rs b/crates/openhuman-cli/src/bin/tool_dialect_bench.rs
deleted file mode 100644
index 8fa7a9e0b2..0000000000
--- a/crates/openhuman-cli/src/bin/tool_dialect_bench.rs
+++ /dev/null
@@ -1,709 +0,0 @@
-//! `tool-dialect-bench` — how well a local model calls tools under each text
-//! dialect, and what each dialect costs in prompt tokens.
-//!
-//! The experiment behind `agent.tool_dispatcher = "python" | "typescript"`:
-//! render the tool catalogue as function signatures instead of JSON schemas
-//! or P-Format slots, and see whether a small code-trained model (an 8B
-//! Ollama model) calls tools more reliably for fewer tokens.
-//!
-//! For every `dialect × model × task` the bench composes the system prompt
-//! exactly as OpenHuman's `ToolsSection` + the dialect's protocol block would
-//! (catalogue, then protocol), sends one user turn with **no** schemas on the
-//! wire, reads the answer back through `tinytools_agent::parse_text` with the
-//! same registry the harness builds, and records:
-//!
-//! * `usage.input_tokens` / `output_tokens` as the provider reports them
-//! (Ollama fills them from `prompt_eval_count` / `eval_count`);
-//! * system-prompt bytes;
-//! * whether a call was recovered at all, whether it named the expected tool,
-//! and whether its arguments matched (exactly, and as a superset);
-//! * latency and the `CallSource` the call came through.
-//!
-//! Manual, network-touching, never run by CI:
-//!
-//! ```text
-//! ollama pull qwen3:8b
-//! cargo run -p openhuman-cli --bin tool-dialect-bench -- \
-//! --model qwen3:8b --dialects xml,pformat,python,typescript --trials 3
-//! ```
-//!
-//! `OLLAMA_HOST` / `OPENHUMAN_LOCAL_INFERENCE_URL` pick the server, as for
-//! the product.
-
-use std::collections::BTreeMap;
-use std::sync::Arc;
-use std::time::{Duration, Instant};
-
-use anyhow::{Context, Result};
-use serde::Serialize;
-use serde_json::{json, Value};
-use tinyinference_llm::message::Message;
-use tinyinference_llm::model::{ChatModel, ModelRequest};
-use tinytools::ToolSpec;
-use tinytools_agent::dialect::{CodeDialect, CodeStyle, PFormatDialect, ToolDialect, XmlDialect};
-use tinytools_agent::render::{render_code_catalogue, render_pformat_catalogue};
-use tinytools_agent::{build_registry, parse_text, CallSource, PFormatRegistry, ParseOptions};
-
-/// The role line every prompt starts with, so the dialect block is the only
-/// thing that differs between runs.
-const BASE_SYSTEM_PROMPT: &str = "You are a helpful assistant with tools. When the user's request \
- needs a tool, call it; do not describe what you would do instead of doing it. \
- Do not ask clarifying questions for these tasks.";
-
-/// Default per-call ceiling: the answer is one call, but a thinking model
-/// (qwen3) spends most of its budget in the reasoning channel first, and a
-/// runaway 8B model can otherwise generate for minutes. `--max-output-tokens`
-/// overrides it.
-const DEFAULT_MAX_OUTPUT_TOKENS: u32 = 1500;
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
-enum Dialect {
- Xml,
- Pformat,
- Python,
- Typescript,
-}
-
-impl Dialect {
- fn parse(raw: &str) -> Result<Self> {
- match raw.trim().to_ascii_lowercase().as_str() {
- "xml" => Ok(Self::Xml),
- "pformat" => Ok(Self::Pformat),
- "python" => Ok(Self::Python),
- "typescript" => Ok(Self::Typescript),
- other => anyhow::bail!("unknown dialect {other:?} (xml|pformat|python|typescript)"),
- }
- }
-
- fn as_str(self) -> &'static str {
- match self {
- Self::Xml => "xml",
- Self::Pformat => "pformat",
- Self::Python => "python",
- Self::Typescript => "typescript",
- }
- }
-
- /// The tool section as OpenHuman renders it: catalogue first, then the
- /// dialect's protocol block. The XML dialect embeds its own catalogue in
- /// the block, so it gets no separate one.
- fn tool_section(self, specs: &[ToolSpec], registry: &PFormatRegistry) -> String {
- match self {
- Self::Xml => XmlDialect.prompt_instructions(specs),
- Self::Pformat => {
- let mut out = render_pformat_catalogue(specs);
- out.push('\n');
- out.push_str(&PFormatDialect::new(registry.clone()).prompt_instructions(specs));
- out
- }
- Self::Python | Self::Typescript => {
- let style = self.code_style();
- let mut out = render_code_catalogue(specs, style);
- out.push('\n');
- out.push_str(&CodeDialect::instructions(style));
- out
- }
- }
- }
-
- fn code_style(self) -> CodeStyle {
- match self {
- Self::Typescript => CodeStyle::TypeScript,
- _ => CodeStyle::Python,
- }
- }
-}
-
-/// One thing we ask the model to do, and the call that would do it.
-struct Task {
- prompt: &'static str,
- tool: &'static str,
- args: Value,
-}
-
-fn tool(name: &str, description: &str, parameters: Value) -> ToolSpec {
- ToolSpec {
- name: name.to_string(),
- description: description.to_string(),
- parameters,
- }
-}
-
-/// Ten tools with the shapes real OpenHuman tools have: required and optional
-/// parameters, integers, booleans, enums, lists, and one nested object.
-fn fixture_tools() -> Vec<ToolSpec> {
- vec![
- tool(
- "read_file",
- "Read a text file from the workspace.",
- json!({
- "type": "object",
- "properties": {
- "path": {"type": "string", "description": "Path relative to the workspace root"},
- "limit": {"type": "integer", "description": "Maximum number of lines to return"}
- },
- "required": ["path"]
- }),
- ),
- tool(
- "write_file",
- "Create or overwrite a text file in the workspace.",
- json!({
- "type": "object",
- "properties": {
- "path": {"type": "string"},
- "content": {"type": "string"}
- },
- "required": ["path", "content"]
- }),
- ),
- tool(
- "list_dir",
- "List the entries of a directory.",
- json!({
- "type": "object",
- "properties": {
- "path": {"type": "string", "description": "Directory to list; defaults to the workspace root"}
- }
- }),
- ),
- tool(
- "search_files",
- "Search file contents for a string.",
- json!({
- "type": "object",
- "properties": {
- "query": {"type": "string"},
- "glob": {"type": "string", "description": "Restrict to files matching this glob"},
- "max_results": {"type": "integer"}
- },
- "required": ["query"]
- }),
- ),
- tool(
- "shell",
- "Run a shell command and return its output.",
- json!({
- "type": "object",
- "properties": {
- "command": {"type": "string"},
- "background": {"type": "boolean", "description": "Run detached and return immediately"},
- "timeout_secs": {"type": "number"}
- },
- "required": ["command"]
- }),
- ),
- tool(
- "get_weather",
- "Get the current weather for a location.",
- json!({
- "type": "object",
- "properties": {
- "location": {"type": "string", "description": "City name"},
- "unit": {"type": "string", "enum": ["metric", "imperial"]}
- },
- "required": ["location"]
- }),
- ),
- tool(
- "send_email",
- "Send an email.",
- json!({
- "type": "object",
- "properties": {
- "to": {"type": "string"},
- "subject": {"type": "string"},
- "body": {"type": "string"},
- "cc": {"type": "array", "items": {"type": "string"}}
- },
- "required": ["to", "subject", "body"]
- }),
- ),
- tool(
- "calendar_create",
- "Create a calendar event.",
- json!({
- "type": "object",
- "properties": {
- "title": {"type": "string"},
- "start": {"type": "string", "description": "ISO 8601 start time"},
- "duration_minutes": {"type": "integer"},
- "attendees": {"type": "array", "items": {"type": "string"}}
- },
- "required": ["title", "start"]
- }),
- ),
- tool(
- "memory_recall",
- "Search long-term memory for relevant notes.",
- json!({
- "type": "object",
- "properties": {
- "query": {"type": "string"},
- "limit": {"type": "integer"}
- },
- "required": ["query"]
- }),
- ),
- tool(
- "http_fetch",
- "Fetch a URL.",
- json!({
- "type": "object",
- "properties": {
- "url": {"type": "string"},
- "method": {"type": "string", "enum": ["GET", "POST"]},
- "headers": {"type": "object", "description": "Extra request headers"}
- },
- "required": ["url"]
- }),
- ),
- ]
-}
-
-/// Twenty requests, each answerable by exactly one call. Optional
-/// arguments are only expected when the prompt names their value.
-fn fixture_tasks() -> Vec<Task> {
- vec![
- Task { prompt: "Show me the file README.md.", tool: "read_file", args: json!({"path": "README.md"}) },
- Task { prompt: "Read the first 20 lines of src/main.rs.", tool: "read_file", args: json!({"path": "src/main.rs", "limit": 20}) },
- Task { prompt: "Create a file called notes.txt containing exactly: hello world", tool: "write_file", args: json!({"path": "notes.txt", "content": "hello world"}) },
- Task { prompt: "What files are in the workspace root?", tool: "list_dir", args: json!({}) },
- Task { prompt: "List the contents of the docs directory.", tool: "list_dir", args: json!({"path": "docs"}) },
- Task { prompt: "Find every occurrence of the word TODO in the code.", tool: "search_files", args: json!({"query": "TODO"}) },
- Task { prompt: "Search for the string 'unwrap()' but only in Rust files (*.rs), at most 5 results.", tool: "search_files", args: json!({"query": "unwrap()", "glob": "*.rs", "max_results": 5}) },
- Task { prompt: "Run the command `cargo test`.", tool: "shell", args: json!({"command": "cargo test"}) },
- Task { prompt: "Start the dev server with `npm run dev` in the background.", tool: "shell", args: json!({"command": "npm run dev", "background": true}) },
- Task { prompt: "What's the weather in London?", tool: "get_weather", args: json!({"location": "London"}) },
- Task { prompt: "What's the weather in Chicago, in imperial units?", tool: "get_weather", args: json!({"location": "Chicago", "unit": "imperial"}) },
- Task { prompt: "Email [email protected] with the subject 'Lunch' and the body 'Are you free at noon?'", tool: "send_email", args: json!({"to": "[email protected]", "subject": "Lunch", "body": "Are you free at noon?"}) },
- Task { prompt: "Send an email to [email protected], subject 'Report', body 'Attached is the report.', and cc [email protected].", tool: "send_email", args: json!({"to": "[email protected]", "subject": "Report", "body": "Attached is the report.", "cc": ["[email protected]"]}) },
- Task { prompt: "Put a 'Standup' meeting on my calendar starting 2026-10-01T09:00:00.", tool: "calendar_create", args: json!({"title": "Standup", "start": "2026-10-01T09:00:00"}) },
- Task { prompt: "Schedule 'Design review' at 2026-10-02T14:00:00 for 45 minutes with [email protected] and [email protected].", tool: "calendar_create", args: json!({"title": "Design review", "start": "2026-10-02T14:00:00", "duration_minutes": 45, "attendees": ["[email protected]", "[email protected]"]}) },
- Task { prompt: "What do you remember about my dog's vet?", tool: "memory_recall", args: json!({"query": "dog's vet"}) },
- Task { prompt: "Recall up to 3 notes about the Berlin trip.", tool: "memory_recall", args: json!({"query": "Berlin trip", "limit": 3}) },
- Task { prompt: "Fetch https://example.com/status", tool: "http_fetch", args: json!({"url": "https://example.com/status"}) },
- Task { prompt: "POST to https://api.example.com/ping", tool: "http_fetch", args: json!({"url": "https://api.example.com/ping", "method": "POST"}) },
- Task { prompt: "Read config.toml, but only the first 5 lines.", tool: "read_file", args: json!({"path": "config.toml", "limit": 5}) },
- ]
-}
-
-#[derive(Debug, Clone, Serialize)]
-struct Row {
- model: String,
- dialect: &'static str,
- trial: usize,
- task: usize,
- expected_tool: &'static str,
- system_prompt_bytes: usize,
- input_tokens: Option<u64>,
- output_tokens: Option<u64>,
- latency_ms: u128,
- recovered: bool,
- name_ok: bool,
- args_exact: bool,
- args_superset: bool,
- source: Option<String>,
- parsed_tool: Option<String>,
- parsed_args: Option<Value>,
- raw_text: String,
- error: Option<String>,
-}
-
-#[derive(Debug, Default)]
-struct Summary {
- n: usize,
- input_tokens: u64,
- input_samples: u64,
- output_tokens: u64,
- output_samples: u64,
- system_prompt_bytes: usize,
- latency_ms: u128,
- recovered: usize,
- name_ok: usize,
- args_exact: usize,
- args_superset: usize,
- errors: usize,
- sources: BTreeMap<String, usize>,
-}
-
-impl Summary {
- fn add(&mut self, row: &Row) {
- self.n += 1;
- if let Some(tokens) = row.input_tokens {
- self.input_tokens += tokens;
- self.input_samples += 1;
- }
- if let Some(tokens) = row.output_tokens {
- self.output_tokens += tokens;
- self.output_samples += 1;
- }
- self.system_prompt_bytes = row.system_prompt_bytes;
- self.latency_ms += row.latency_ms;
- self.recovered += usize::from(row.recovered);
- self.name_ok += usize::from(row.name_ok);
- self.args_exact += usize::from(row.args_exact);
- self.args_superset += usize::from(row.args_superset);
- self.errors += usize::from(row.error.is_some());
- if let Some(source) = &row.source {
- *self.sources.entry(source.clone()).or_default() += 1;
- }
- }
-
- fn pct(&self, count: usize) -> String {
- if self.n == 0 {
- return "-".into();
- }
- format!("{:.0}%", 100.0 * count as f64 / self.n as f64)
- }
-
- fn avg(total: u64, samples: u64) -> String {
- if samples == 0 {
- return "-".into();
- }
- format!("{}", total / samples)
- }
-}
-
-struct Args {
- models: Vec<String>,
- dialects: Vec<Dialect>,
- trials: usize,
- json: bool,
- verbose: bool,
- tasks: Option<Vec<usize>>,
- max_output_tokens: u32,
-}
-
-fn parse_args() -> Result<Args> {
- let mut models = vec!["qwen3:8b".to_string()];
- let mut dialects = vec![
- Dialect::Xml,
- Dialect::Pformat,
- Dialect::Python,
- Dialect::Typescript,
- ];
- let mut trials = 1usize;
- let mut json = false;
- let mut verbose = false;
- let mut tasks = None;
- let mut max_output_tokens = DEFAULT_MAX_OUTPUT_TOKENS;
- let mut it = std::env::args().skip(1);
- while let Some(arg) = it.next() {
- match arg.as_str() {
- "--model" | "--models" => {
- models = it
- .next()
- .context("--model needs a value")?
- .split(',')
- .map(|m| m.trim().to_string())
- .filter(|m| !m.is_empty())
- .collect();
- }
- "--dialects" => {
- dialects = it
- .next()
- .context("--dialects needs a value")?
- .split(',')
- .map(Dialect::parse)
- .collect::<Result<Vec<_>>>()?;
- }
- "--trials" => {
- trials = it
- .next()
- .context("--trials needs a value")?
- .parse()
- .context("--trials value")?;
- }
- "--tasks" => {
- tasks = Some(
- it.next()
- .context("--tasks needs a value")?
- .split(',')
- .map(|t| t.trim().parse::<usize>().context("--tasks index"))
- .collect::<Result<Vec<_>>>()?,
- );
- }
- "--max-output-tokens" => {
- max_output_tokens = it
- .next()
- .context("--max-output-tokens needs a value")?
- .parse()
- .context("--max-output-tokens value")?;
- }
- "--json" => json = true,
- "--verbose" | "-v" => verbose = true,
- "--help" | "-h" => {
- eprintln!(
- "tool-dialect-bench [--model m1,m2] [--dialects xml,pformat,python,typescript] \
- [--trials N] [--tasks 0,3,5] [--max-output-tokens N] [--json] [--verbose]"
- );
- std::process::exit(0);
- }
- other => anyhow::bail!("unknown argument: {other}"),
- }
- }
- Ok(Args {
- models,
- dialects,
- trials,
- json,
- verbose,
- tasks,
- max_output_tokens,
- })
-}
-
-/// `expected ⊆ parsed`, comparing values after light normalisation (a
-/// number the model quoted still counts).
-fn is_superset(parsed: &Value, expected: &Value) -> bool {
- let (Some(parsed), Some(expected)) = (parsed.as_object(), expected.as_object()) else {
- return false;
- };
- expected
- .iter()
- .all(|(key, want)| parsed.get(key).is_some_and(|got| loosely_equal(got, want)))
-}
-
-fn loosely_equal(got: &Value, want: &Value) -> bool {
- if got == want {
- return true;
- }
- match (got, want) {
- (Value::String(g), Value::Number(w)) => g.trim() == w.to_string(),
- (Value::Number(g), Value::String(w)) => g.to_string() == w.trim(),
- (Value::String(g), Value::Bool(w)) => g.trim().eq_ignore_ascii_case(&w.to_string()),
- (Value::String(g), Value::String(w)) => g.trim() == w.trim(),
- _ => false,
- }
-}
-
-fn is_exact(parsed: &Value, expected: &Value) -> bool {
- let (Some(parsed), Some(expected)) = (parsed.as_object(), expected.as_object()) else {
- return false;
- };
- parsed.len() == expected.len()
- && is_superset(
- &Value::Object(parsed.clone()),
- &Value::Object(expected.clone()),
- )
-}
-
-#[tokio::main]
-async fn main() -> Result<()> {
- let _ = env_logger::try_init();
- let args = parse_args()?;
- let specs = fixture_tools();
- let all_tasks = fixture_tasks();
- let tasks: Vec<(usize, &Task)> = match &args.tasks {
- Some(indices) => indices
- .iter()
- .map(|&i| {
- all_tasks
- .get(i)
- .map(|t| (i, t))
- .context("task index out of range")
- })
- .collect::<Result<Vec<_>>>()?,
- None => all_tasks.iter().enumerate().collect(),
- };
- let registry = build_registry(
- specs
- .iter()
- .map(|spec| (spec.name.clone(), spec.parameters.clone())),
- );
- let known: Vec<String> = specs.iter().map(|spec| spec.name.clone()).collect();
- let config = openhuman_core::config::Config::default();
-
- let mut rows: Vec<Row> = Vec::new();
- let mut summaries: BTreeMap<(String, Dialect), Summary> = BTreeMap::new();
-
- for model_name in &args.models {
- let provider = format!("ollama:{model_name}");
- let (model, model_id): (Arc<dyn ChatModel<()>>, String) =
- openhuman_core::inference::provider::create_chat_model_from_string_with_model_id(
- "chat", &provider, &config, 0.0,
- )
- .with_context(|| format!("building model {provider}"))?;
- eprintln!("== model {model_id} ({provider})");
-
- for &dialect in &args.dialects {
- let section = dialect.tool_section(&specs, &registry);
- let system = format!("{BASE_SYSTEM_PROMPT}\n\n{section}");
- eprintln!(
- "-- dialect {} (system prompt {} bytes, ~{} tokens at 4 chars/token)",
- dialect.as_str(),
- system.len(),
- system.len() / 4
- );
- if args.verbose {
- eprintln!("{system}\n");
- }
- for trial in 0..args.trials {
- for &(task_index, task) in &tasks {
- let request = ModelRequest::new(vec![
- Message::system(system.clone()),
- Message::user(task.prompt),
- ])
- .with_model(model_id.clone())
- .with_temperature(0.0)
- .with_max_tokens(args.max_output_tokens);
- let started = Instant::now();
- let outcome =
- tokio::time::timeout(Duration::from_secs(180), model.invoke(&(), request))
- .await;
- let latency_ms = started.elapsed().as_millis();
- let mut row = Row {
- model: model_id.clone(),
- dialect: dialect.as_str(),
- trial,
- task: task_index,
- expected_tool: task.tool,
- system_prompt_bytes: system.len(),
- input_tokens: None,
- output_tokens: None,
- latency_ms,
- recovered: false,
- name_ok: false,
- args_exact: false,
- args_superset: false,
- source: None,
- parsed_tool: None,
- parsed_args: None,
- raw_text: String::new(),
- error: None,
- };
- match outcome {
- Err(_) => row.error = Some("timeout".into()),
- // An empty answer that used the whole budget is the
- // model thinking past the cap, not a dialect failure.
- Ok(Ok(response))
- if response.text().trim().is_empty()
- && response.usage.is_some_and(|u| {
- u.output_tokens >= u64::from(args.max_output_tokens)
- }) =>
- {
- row.input_tokens = response.usage.map(|u| u.input_tokens);
- row.output_tokens = response.usage.map(|u| u.output_tokens);
- row.error = Some("output cap reached with no visible text".into());
- }
- Ok(Err(error)) => row.error = Some(error.to_string()),
- Ok(Ok(response)) => {
- row.input_tokens = response.usage.map(|u| u.input_tokens);
- row.output_tokens = response.usage.map(|u| u.output_tokens);
- let text = response.text();
- row.raw_text = text.clone();
- // The same recovery the harness runs: known tools
- // for name repair, the registry for positional
- // and code-style bodies.
- let options = ParseOptions::new()
- .with_known_tools(&known)
- .with_registry(&registry);
- let (_narrative, calls) = parse_text(&text, &options).into_parts();
- if let Some(call) = calls.first() {
- row.recovered = true;
- row.name_ok = call.name == task.tool;
- row.args_exact =
- row.name_ok && is_exact(&call.arguments, &task.args);
- row.args_superset =
- row.name_ok && is_superset(&call.arguments, &task.args);
- row.source = Some(source_name(call.source).to_string());
- row.parsed_tool = Some(call.name.clone());
- row.parsed_args = Some(call.arguments.clone());
- }
- }
- }
- let mark = if row.args_exact {
- "ok "
- } else if row.args_superset {
- "sup"
- } else if row.name_ok {
- "arg"
- } else if row.recovered {
- "tool"
- } else if row.error.is_some() {
- "ERR"
- } else {
- "none"
- };
- eprintln!(
- " [{mark:>4}] task {task_index:>2} {:<16} in={:<5} out={:<4} {}ms{}",
- task.tool,
- row.input_tokens.map_or("-".to_string(), |t| t.to_string()),
- row.output_tokens.map_or("-".to_string(), |t| t.to_string()),
- row.latency_ms,
- if args.verbose || !row.args_superset {
- format!("\n raw: {}", one_line(&row.raw_text))
- } else {
- String::new()
- }
- );
- summaries
- .entry((model_id.clone(), dialect))
- .or_default()
- .add(&row);
- rows.push(row);
- }
- }
- }
- }
-
- println!();
- println!(
- "| model | dialect | n | sys bytes | in tok | out tok | recovered | tool | args ⊇ | args = | avg ms | errors | sources |"
- );
- println!("| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |");
- for ((model, dialect), s) in &summaries {
- let sources: Vec<String> = s.sources.iter().map(|(k, v)| format!("{k}:{v}")).collect();
- println!(
- "| {model} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} |",
- dialect.as_str(),
- s.n,
- s.system_prompt_bytes,
- Summary::avg(s.input_tokens, s.input_samples),
- Summary::avg(s.output_tokens, s.output_samples),
- s.pct(s.recovered),
- s.pct(s.name_ok),
- s.pct(s.args_superset),
- s.pct(s.args_exact),
- if s.n == 0 {
- 0
- } else {
- s.latency_ms / s.n as u128
- },
- s.errors,
- sources.join(" ")
- );
- }
- if args.json {
- println!();
- println!("{}", serde_json::to_string_pretty(&rows)?);
- }
- Ok(())
-}
-
-fn source_name(source: CallSource) -> &'static str {
- match source {
- CallSource::Native => "native",
- CallSource::TaggedJson => "tagged_json",
- CallSource::InvokeXml => "invoke_xml",
- CallSource::Sentinel => "sentinel",
- CallSource::Harmony => "harmony",
- CallSource::Mistral => "mistral",
- CallSource::Glm => "glm",
- CallSource::BareJson => "bare_json",
- CallSource::PFormat => "pformat",
- CallSource::Code => "code",
- _ => "other",
- }
-}
-
-fn one_line(text: &str) -> String {
- let flat: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
- if flat.chars().count() > 240 {
- let clipped: String = flat.chars().take(240).collect();
- format!("{clipped}…")
- } else {
- flat
- }
-}
diff --git a/crates/openhuman-cli/src/bin/tool_search_bench.rs b/crates/openhuman-cli/src/bin/tool_search_bench.rs
deleted file mode 100644
index 578d8ce026..0000000000
--- a/crates/openhuman-cli/src/bin/tool_search_bench.rs
+++ /dev/null
@@ -1,678 +0,0 @@
-//! `tool-search-bench` — how well does each `tool_search` ranker pick the
-//! right tool for an intent?
-//!
-//! The catalogue is the real thing: every tool the orchestrator session
-//! registers (built exactly as a session builds it, with a temp workspace),
-//! plus the recorded Composio catalogues under `tests/fixtures/composio_*.json`
-//! (≈1,000 actions across nine toolkits) as the deferred per-action tools a
-//! signed-in workspace would synthesise. The intents are
-//! `tests/fixtures/tool_search/intents.jsonl`: hand-written requests, each
-//! labelled with the tool it should reach (or `none` for a request no tool
-//! should answer).
-//!
-//! Three rankers are measured on the same rows:
-//!
-//! - `bm25` — `tinytools::Bm25Ranker`, what the harness answers with when
-//! nothing else is installed.
-//! - `overlap` — `tinyagents_harness::tool::select::rank_tools_by_prompt`,
-//! the verb-gated token overlap the Composio sub-agent narrows with today.
-//! - `jev` — `tinytools_jev::JevRanker`: BM25 retrieves the top 20, one Jev
-//! `Choice` decides. Needs a key: `OPENHUMAN_BACKEND_API_KEY` (through the
-//! TinyHumans proxy, `BACKEND_URL` to override the base) or
-//! `TYPESAFE_API_KEY` (TypeSafe directly). Skipped without one.
-//!
-//! Reported per ranker: top-1 and top-3 accuracy over the labelled rows,
-//! recall@20 of the BM25 retriever (the ceiling Jev can reach), the needless
-//! rate (a `none` row answered with a hit), p50/p95 latency, input tokens and
-//! USD from the provider's `usage`, and a per-family confusion table.
-//!
-//! ```text
-//! cargo run -p openhuman-cli --bin tool-search-bench -- --ranker all
-//! cargo run -p openhuman-cli --bin tool-search-bench -- --dump-catalogue
-//! ```
-
-use std::collections::BTreeMap;
-use std::path::PathBuf;
-use std::sync::Arc;
-use std::time::{Duration, Instant};
-
-use anyhow::{Context, Result};
-use serde::{Deserialize, Serialize};
-use tinytools::{Bm25Ranker, RankCandidate, RankContext, ToolRanker};
-
-/// jev-1.13 list price for input tokens, USD per million; output is free.
-const JEV_USD_PER_MILLION_INPUT: f64 = 0.042;
-/// Toolkits with a recorded catalogue under `tests/fixtures/`.
-const FIXTURE_TOOLKITS: &[&str] = &[
- "gmail",
- "slack",
- "github",
- "notion",
- "googledrive",
- "googlesheets",
- "reddit",
- "facebook",
- "instagram",
-];
-
-#[derive(Debug, Clone, Deserialize)]
-struct IntentRow {
- intent: String,
- /// The tool that should answer, or `"none"`.
- expected: String,
- #[serde(default)]
- family: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize)]
-struct CatalogueEntry {
- name: String,
- family: Option<String>,
- description: String,
- #[serde(skip)]
- parameters: serde_json::Value,
-}
-
-impl CatalogueEntry {
- fn candidate(&self) -> RankCandidate {
- let mut summary = String::with_capacity(self.description.len() + 64);
- summary.push_str(&self.name);
- summary.push(' ');
- summary.push_str(&self.name.replace('_', " "));
- summary.push(' ');
- summary.push_str(&self.description);
- if let Some(props) = self
- .parameters
- .get("properties")
- .and_then(|v| v.as_object())
- {
- for key in props.keys() {
- summary.push(' ');
- summary.push_str(key);
- }
- }
- RankCandidate {
- key: self.name.clone(),
- family: self.family.clone(),
- summary,
- }
- }
-}
-
-#[derive(Debug, Default, Serialize)]
-struct RankerReport {
- ranker: String,
- rows: usize,
- labelled: usize,
- top1: usize,
- top3: usize,
- /// Labelled rows whose expected tool BM25 retrieved in its top 20.
- recall_at_20: usize,
- none_rows: usize,
- needless: usize,
- errors: usize,
- latency_ms: Vec<u64>,
- input_tokens: u64,
- usd: f64,
- /// `expected family -> top-1 family -> count`, labelled rows only.
- confusion: BTreeMap<String, BTreeMap<String, usize>>,
- /// `source -> (labelled, top1, top3, recall@k)` where source is `composio`
- /// or `core`; the connector catalogue is the heavy one, so it is read on
- /// its own.
- by_source: BTreeMap<String, (usize, usize, usize, usize)>,
- misses: Vec<Miss>,
-}
-
-#[derive(Debug, Clone, Serialize)]
-struct Miss {
- intent: String,
- expected: String,
- got: Vec<String>,
-}
-
-impl RankerReport {
- fn percentile(&self, p: f64) -> u64 {
- if self.latency_ms.is_empty() {
- return 0;
- }
- let mut sorted = self.latency_ms.clone();
- sorted.sort_unstable();
- let idx = ((sorted.len() as f64 - 1.0) * p).round() as usize;
- sorted[idx.min(sorted.len() - 1)]
- }
-}
-
-struct Args {
- ranker: String,
- intents: PathBuf,
- dump_catalogue: bool,
- json_out: Option<PathBuf>,
- top_k: usize,
- retrieval_k: usize,
- misses: bool,
- family: bool,
- embedding: bool,
-}
-
-fn parse_args() -> Args {
- let mut args = Args {
- ranker: "all".to_string(),
- intents: repo_root().join("tests/fixtures/tool_search/intents.jsonl"),
- dump_catalogue: false,
- json_out: None,
- top_k: 3,
- retrieval_k: 20,
- misses: false,
- family: false,
- embedding: false,
- };
- let mut it = std::env::args().skip(1);
- while let Some(arg) = it.next() {
- match arg.as_str() {
- "--ranker" => args.ranker = it.next().unwrap_or_default(),
- "--intents" => args.intents = PathBuf::from(it.next().unwrap_or_default()),
- "--dump-catalogue" => args.dump_catalogue = true,
- "--json" => args.json_out = Some(PathBuf::from(it.next().unwrap_or_default())),
- "--top-k" => args.top_k = it.next().and_then(|v| v.parse().ok()).unwrap_or(3),
- "--retrieval-k" => {
- args.retrieval_k = it.next().and_then(|v| v.parse().ok()).unwrap_or(20)
- }
- "--misses" => args.misses = true,
- "--family" => args.family = true,
- "--embedding" => args.embedding = true,
- "-h" | "--help" => {
- eprintln!(
- "usage: tool-search-bench [--ranker all|bm25|overlap|embedding|jev] [--intents FILE] \
- [--dump-catalogue] [--json OUT] [--top-k N] [--retrieval-k N] [--misses] [--family] [--embedding]"
- );
- std::process::exit(0);
- }
- other => {
- eprintln!("unknown argument {other}");
- std::process::exit(2);
- }
- }
- }
- args
-}
-
-fn repo_root() -> PathBuf {
- PathBuf::from(env!("OPENHUMAN_REPOSITORY_ROOT"))
-}
-
-/// The orchestrator's registered tools, built the way a session builds them.
-fn core_catalogue() -> Result<Vec<CatalogueEntry>> {
- use openhuman_core::agent::harness::AgentDefinitionRegistry;
- use openhuman_core::agent::OpenHumanSessionHost;
-
- let _ = AgentDefinitionRegistry::init_global_builtins();
- let tmp = tempfile::TempDir::new()?;
- let config = openhuman_core::config::Config {
- workspace_dir: tmp.path().join("workspace"),
- action_dir: tmp.path().join("workspace"),
- config_path: tmp.path().join("config.toml"),
- ..openhuman_core::config::Config::default()
- };
- std::fs::create_dir_all(&config.workspace_dir)?;
- let host = OpenHumanSessionHost::from_config_for_agent(&config, "orchestrator")
- .context("build orchestrator session")?;
- let mut out = Vec::new();
- for spec in host.tool_specs() {
- // Pack members carry their pack as the family; everything else is a
- // core tool with no family, like the registry sees it.
- let family = openhuman_core::tools::toolpacks::pack_for_tool(&spec.name)
- .map(|pack| pack.id.to_string());
- out.push(CatalogueEntry {
- name: spec.name.clone(),
- family,
- description: spec.description.clone(),
- parameters: spec.parameters.clone(),
- });
- }
- Ok(out)
-}
-
-/// The recorded Composio catalogues, one deferred action per entry.
-fn composio_catalogue() -> Result<Vec<CatalogueEntry>> {
- let mut out = Vec::new();
- for toolkit in FIXTURE_TOOLKITS {
- let path = repo_root().join(format!("tests/fixtures/composio_{toolkit}.json"));
- let raw = std::fs::read_to_string(&path).with_context(|| format!("read {path:?}"))?;
- let parsed: serde_json::Value = serde_json::from_str(&raw)?;
- let tools = parsed
- .pointer("/result/result/tools")
- .and_then(|t| t.as_array())
- .with_context(|| format!("missing /result/result/tools in {path:?}"))?;
- for tool in tools {
- let name = tool
- .pointer("/function/name")
- .and_then(|n| n.as_str())
- .unwrap_or_default()
- .to_string();
- if name.is_empty() {
- continue;
- }
- out.push(CatalogueEntry {
- name,
- family: Some((*toolkit).to_string()),
- description: tool
- .pointer("/function/description")
- .and_then(|d| d.as_str())
- .unwrap_or_default()
- .to_string(),
- parameters: tool
- .pointer("/function/parameters")
- .cloned()
- .unwrap_or_else(|| serde_json::json!({"type": "object"})),
- });
- }
- }
- Ok(out)
-}
-
-fn load_intents(path: &PathBuf) -> Result<Vec<IntentRow>> {
- let raw = std::fs::read_to_string(path).with_context(|| format!("read {path:?}"))?;
- let mut rows = Vec::new();
- for (i, line) in raw.lines().enumerate() {
- let line = line.trim();
- if line.is_empty() || line.starts_with('#') {
- continue;
- }
- let row: IntentRow =
- serde_json::from_str(line).with_context(|| format!("{path:?}:{} bad row", i + 1))?;
- rows.push(row);
- }
- Ok(rows)
-}
-
-use openhuman_core::agent::tinyagents::discovery::OverlapRanker;
-
-#[cfg(feature = "jev")]
-fn jev_ranker(
- retrieval_k: usize,
- family: bool,
- embedding: bool,
-) -> Option<(Arc<dyn ToolRanker>, Arc<tinytools_jev::JevRanker>)> {
- use openhuman_tinyhumans::jev::TinyJevEvaluator;
- use tinyjevclient::{Client, ClientConfig};
- use tinytools_jev::JevRanker;
- let client = if let Ok(key) = std::env::var("OPENHUMAN_BACKEND_API_KEY") {
- let mut client = ClientConfig::tinyhumans_openrouter(key);
- if let Ok(base) = std::env::var("BACKEND_URL") {
- if !base.trim().is_empty() {
- client.base_url = base.trim().trim_end_matches('/').to_string();
- }
- }
- client
- } else if let Ok(key) = std::env::var("TYPESAFE_API_KEY") {
- ClientConfig::new(key)
- } else {
- // No key in the environment: rank exactly as the product does, with
- // the process's signed-in TinyHumans session resolved per search.
- eprintln!("jev: no key in the environment; using the signed-in TinyHumans session");
- return None;
- };
- let client = Client::new(client).ok()?;
- let evaluator = Arc::new(TinyJevEvaluator::new(client).with_deadline(Duration::from_secs(20)));
- let ranker = Arc::new(JevRanker::new(
- evaluator,
- jev_config(retrieval_k, family, embedding),
- ));
- Some((ranker.clone() as Arc<dyn ToolRanker>, ranker))
-}
-
-#[cfg(feature = "jev")]
-fn jev_config(retrieval_k: usize, family: bool, embedding: bool) -> tinytools_jev::JevRankerConfig {
- use tinytools_jev::{JevRankerConfig, JevStrategy};
- let mut config = JevRankerConfig::new().with_retrieval_k(retrieval_k);
- if family {
- config = config.with_strategy(JevStrategy::FamilyThenDecide);
- }
- if embedding {
- config = config.with_retriever(embedding_retriever());
- }
- config
-}
-
-#[cfg(not(feature = "jev"))]
-fn jev_ranker(
- _retrieval_k: usize,
- _family: bool,
- _embedding: bool,
-) -> Option<(Arc<dyn ToolRanker>, Arc<()>)> {
- None
-}
-
-/// The process's configured embedding provider as a `ToolRanker`, with its
-/// catalogue cache in the scratch workspace so repeated runs embed only the
-/// intents.
-fn embedding_retriever() -> Arc<dyn ToolRanker> {
- use openhuman_core::agent::tinyagents::discovery::{
- embedding_provider_is_usable, embedding_tool_ranker,
- };
- let config = tokio::task::block_in_place(|| {
- tokio::runtime::Handle::current().block_on(openhuman_core::config::Config::load_or_init())
- })
- .expect("load config for the embedding provider");
- let provider =
- openhuman_core::inference::embedding_host::default_embedding_provider_with_config(&config);
- if !embedding_provider_is_usable(provider.as_ref()) {
- eprintln!(
- "embedding: provider `{}` cannot embed; the bench retriever stays bm25",
- provider.name()
- );
- return Arc::new(Bm25Ranker);
- }
- eprintln!("embedding: {} / {}", provider.name(), provider.model_id());
- Arc::new(
- embedding_tool_ranker(provider).with_disk_cache(
- repo_root()
- .join("target")
- .join("tool_search_bench_embeddings.json"),
- ),
- )
-}
-
-fn family_of<'a>(catalogue: &'a [CatalogueEntry], name: &str) -> &'a str {
- catalogue
- .iter()
- .find(|e| e.name == name)
- .and_then(|e| e.family.as_deref())
- .unwrap_or("core")
-}
-
-#[tokio::main]
-async fn main() -> Result<()> {
- let args = parse_args();
- let mut catalogue = core_catalogue()?;
- let core_count = catalogue.len();
- catalogue.extend(composio_catalogue()?);
- eprintln!(
- "catalogue: {} tools ({} core, {} composio actions)",
- catalogue.len(),
- core_count,
- catalogue.len() - core_count
- );
- if args.dump_catalogue {
- for entry in &catalogue {
- println!(
- "{}\t{}\t{}",
- entry.name,
- entry.family.as_deref().unwrap_or("-"),
- entry.description.chars().take(100).collect::<String>()
- );
- }
- return Ok(());
- }
- let names: std::collections::HashSet<&str> =
- catalogue.iter().map(|e| e.name.as_str()).collect();
- let rows = load_intents(&args.intents)?;
- for row in &rows {
- if row.expected != "none" && !names.contains(row.expected.as_str()) {
- anyhow::bail!(
- "intent {:?} expects `{}`, which is not in the catalogue",
- row.intent,
- row.expected
- );
- }
- }
- let candidates: Vec<RankCandidate> = catalogue.iter().map(CatalogueEntry::candidate).collect();
-
- let mut rankers: Vec<(String, Arc<dyn ToolRanker>)> = Vec::new();
- let want = |k: &str| args.ranker == "all" || args.ranker == k;
- if want("bm25") {
- rankers.push(("bm25".into(), Arc::new(Bm25Ranker)));
- }
- if want("overlap") {
- rankers.push(("overlap".into(), Arc::new(OverlapRanker)));
- }
- if want("embedding") && args.embedding {
- rankers.push(("embedding".into(), embedding_retriever()));
- }
- if want("jev") {
- match jev_ranker(args.retrieval_k, args.family, args.embedding) {
- Some((ranker, _)) => rankers.push(("jev".into(), ranker)),
- None => {
- #[cfg(feature = "jev")]
- {
- let ranker = openhuman_tinyhumans::jev::TinyHumansJevRanker::with_config(
- jev_config(args.retrieval_k, args.family, args.embedding),
- )
- .with_deadline(Duration::from_secs(20));
- rankers.push(("jev".into(), Arc::new(ranker)));
- }
- #[cfg(not(feature = "jev"))]
- eprintln!("jev: skipped (build with the `jev` feature)");
- }
- }
- }
-
- let mut reports = Vec::new();
- for (kind, ranker) in &rankers {
- let mut report = RankerReport {
- ranker: if kind == "jev" {
- format!(
- "jev({}{})",
- if args.family { "family" } else { "retrieve" },
- if args.embedding {
- "+embedding"
- } else {
- "+bm25"
- }
- )
- } else {
- kind.clone()
- },
- rows: rows.len(),
- ..RankerReport::default()
- };
- for row in &rows {
- let started = Instant::now();
- let result = ranker
- .rank(&row.intent, &RankContext::empty(), &candidates, args.top_k)
- .await;
- report
- .latency_ms
- .push(u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX));
- let hits = match result {
- Ok(hits) => hits,
- Err(error) => {
- report.errors += 1;
- eprintln!("{kind}: {:?} -> {error}", row.intent);
- Vec::new()
- }
- };
- let got: Vec<String> = hits.iter().map(|h| h.key.clone()).collect();
- if row.expected == "none" {
- report.none_rows += 1;
- if !got.is_empty() {
- report.needless += 1;
- }
- continue;
- }
- report.labelled += 1;
- let source = if catalogue.iter().any(|e| {
- e.name == row.expected
- && e.family
- .as_deref()
- .is_some_and(|f| FIXTURE_TOOLKITS.contains(&f))
- }) {
- "composio"
- } else {
- "core"
- };
- let bucket = report.by_source.entry(source.to_string()).or_default();
- bucket.0 += 1;
- let hit1 = got.first().map(String::as_str) == Some(row.expected.as_str());
- let hit3 = got.iter().any(|g| g == &row.expected);
- if hit1 {
- report.top1 += 1;
- bucket.1 += 1;
- }
- if hit3 {
- report.top3 += 1;
- bucket.2 += 1;
- } else if args.misses {
- report.misses.push(Miss {
- intent: row.intent.clone(),
- expected: row.expected.clone(),
- got: got.clone(),
- });
- }
- // Recall of the retriever Jev sits on: the embedding index when
- // `--embedding`, BM25 otherwise. For the standalone rankers it is
- // their own recall at `retrieval_k`.
- let retrieved: Vec<String> = if kind == "jev" && !args.embedding || kind == "bm25" {
- Bm25Ranker::rank_sync(&candidates, &row.intent, args.retrieval_k)
- .into_iter()
- .map(|h| h.key)
- .collect()
- } else {
- let retriever: Arc<dyn ToolRanker> = if kind == "jev" {
- embedding_retriever()
- } else {
- ranker.clone()
- };
- retriever
- .rank(
- &row.intent,
- &RankContext::empty(),
- &candidates,
- args.retrieval_k,
- )
- .await
- .map(|hits| hits.into_iter().map(|h| h.key).collect())
- .unwrap_or_default()
- };
- if retrieved.iter().any(|h| h == &row.expected) {
- report.recall_at_20 += 1;
- if let Some(bucket) = report.by_source.get_mut(source) {
- bucket.3 += 1;
- }
- }
- let expected_family = row
- .family
- .clone()
- .unwrap_or_else(|| family_of(&catalogue, &row.expected).to_string());
- let got_family = got
- .first()
- .map(|g| family_of(&catalogue, g).to_string())
- .unwrap_or_else(|| "(none)".to_string());
- *report
- .confusion
- .entry(expected_family)
- .or_default()
- .entry(got_family)
- .or_default() += 1;
- }
- reports.push(report);
- }
-
- #[cfg(feature = "jev")]
- if let Some(report) = reports.iter_mut().find(|r| r.ranker == "jev") {
- // Tokens and cost: one detailed pass over the labelled rows so the
- // number is the provider's own `usage`, not an estimate.
- if let Some((_, detailed)) = jev_ranker(args.retrieval_k, args.family, args.embedding) {
- let mut tokens = 0_u64;
- let mut counted = 0_u64;
- for row in rows.iter().take(25) {
- if let Ok(ranking) = detailed
- .rank_detailed(&row.intent, &RankContext::empty(), &candidates, args.top_k)
- .await
- {
- if let Some(t) = ranking.input_tokens {
- tokens += t;
- counted += 1;
- }
- }
- }
- if counted > 0 {
- let per_search = tokens as f64 / counted as f64;
- report.input_tokens = per_search.round() as u64;
- report.usd = per_search * JEV_USD_PER_MILLION_INPUT / 1_000_000.0;
- }
- }
- }
-
- println!("| ranker | rows | top-1 | top-3 | retriever recall@{} | needless (of {}) | errors | p50 ms | p95 ms | tokens/search | USD/search |",
- args.retrieval_k,
- reports.first().map_or(0, |r| r.none_rows));
- println!("|---|---|---|---|---|---|---|---|---|---|---|");
- for r in &reports {
- let pct = |n: usize, d: usize| {
- if d == 0 {
- "n/a".to_string()
- } else {
- format!("{:.1}%", 100.0 * n as f64 / d as f64)
- }
- };
- println!(
- "| {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} |",
- r.ranker,
- r.rows,
- pct(r.top1, r.labelled),
- pct(r.top3, r.labelled),
- pct(r.recall_at_20, r.labelled),
- r.needless,
- r.errors,
- r.percentile(0.5),
- r.percentile(0.95),
- if r.input_tokens == 0 {
- "-".to_string()
- } else {
- r.input_tokens.to_string()
- },
- if r.usd == 0.0 {
- "-".to_string()
- } else {
- format!("${:.5}", r.usd)
- },
- );
- }
- println!(
- "\n| ranker | source | labelled | top-1 | top-3 | recall@{} |",
- args.retrieval_k
- );
- println!("|---|---|---|---|---|---|");
- for r in &reports {
- for (source, (n, t1, t3, rk)) in &r.by_source {
- let pct = |x: usize| {
- if *n == 0 {
- "n/a".to_string()
- } else {
- format!("{:.1}%", 100.0 * x as f64 / *n as f64)
- }
- };
- println!(
- "| {} | {} | {} | {} | {} | {} |",
- r.ranker,
- source,
- n,
- pct(*t1),
- pct(*t3),
- pct(*rk)
- );
- }
- }
- for r in &reports {
- println!(
- "\n### {} — top-1 family confusion (expected → got)",
- r.ranker
- );
- for (expected, gots) in &r.confusion {
- let line: Vec<String> = gots.iter().map(|(g, n)| format!("{g}:{n}")).collect();
- println!("- {expected}: {}", line.join(", "));
- }
- if args.misses && !r.misses.is_empty() {
- println!("\n### {} — misses", r.ranker);
- for m in &r.misses {
- println!("- {:?} expected `{}` got {:?}", m.intent, m.expected, m.got);
- }
- }
- }
- if let Some(out) = &args.json_out {
- std::fs::write(out, serde_json::to_string_pretty(&reports)?)?;
- eprintln!("wrote {out:?}");
- }
- Ok(())
-}
diff --git a/docs/harness-comparison-2026-07-22.md b/docs/harness-comparison-2026-07-22.md
deleted file mode 100644
index 36585b4b79..0000000000
--- a/docs/harness-comparison-2026-07-22.md
+++ /dev/null
@@ -1,99 +0,0 @@
-# Agent harness resource-footprint comparison
-
-Date: 2026-07-22
-Method: web research against primary sources where they exist (GitHub repos and
-issue trackers, official docs), with every weakly-sourced figure flagged. Our
-own numbers come from the reproducible drivers under `scripts/profile/`.
-
-The single most important source-quality finding: **the only fully measured,
-reproducible numbers in this comparison are ours.** Codex publishes binary
-size but no RSS; ZeroClaw's numbers are vendor marketing with no third-party
-verification; Claude Code's dramatic figures are leak bugs, not steady state;
-Hermes' figure is self-reported documentation.
-
-## Comparison table
-
-| Harness | Language / runtime | Deployment shape | RAM idle | RAM under load | Startup | Binary / install | N-agent scaling | Source quality |
-|---|---|---|---|---|---|---|---|---|
-| **OpenHuman core** (ours) | Rust, embeddable library | Library or one RPC process; agents share the process | 44-51 MiB settled (default); 35-44 MiB slim | Cold turn +26-31 MiB (first-use); warm turn +0.5-1.9 MiB | ~100-140 ms cold turn; ~0 idle CPU | 116 MiB default / 81 MiB library-minimal / 60 MiB stripped | **In-process**: ~0.4 MiB/agent cold roster, ~1.8 MiB warm marginal | Measured, reproducible (this repo) |
-| OpenAI Codex CLI (codex-rs) | Rust, single native binary | CLI process per session | no published RSS | no published RSS (qualitative claims only) | "milliseconds" (qualitative) | **80 MB** (macOS arm64, primary: issue #13091) | N independent processes | Binary size primary; RSS unpublished |
-| Codex CLI (old Node/TS) | Node.js / V8 | CLI process per session | no published data | no published data | Node startup | npm + Node runtime | N processes | none published |
-| ZeroClaw | Rust, static binary | CLI + optional daemon | **< 5 MB (self-reported, unverified)** | **no verified figure** (the oft-quoted "7.8-12 MiB" has no locatable primary source) | "< 10 ms" (self-reported) | 3.4 MB (one page says ~8.8 MB — internally inconsistent) | "multiple concurrently", no numbers | Marketing only; provenance suspect (SEO domain cluster) |
-| OpenClaw (Clawdbot → Moltbot → OpenClaw) | TypeScript / Node.js | Local daemon + channel bridge | "> 1 GB" claimed only by competitor marketing | no neutral figure | slow (Node + heavy deps) | ~28 MB (per competitor comparison) | N processes | Rebrand history primary (TechCrunch/CNBC/Forbes); RAM figure biased |
-| Claude Code | Node.js / V8 CLI | CLI process per session | ~500 MB claimed (weak SEO source) | documented **leak bugs**: 400-500 MB/min idle growth, multi-GB, extremes 14-93 GB | Node startup | npm + Node runtime | N processes | Leak bugs primary (issues #67433, #28731, #22188); baseline weak |
-| Hermes Agent (Nous Research) | **Python 81% / TS 16%** (not Rust; it bundles the Rust-written `uv`) | CLI + gateway daemon; subagents are isolated subprocesses | no granular RSS; **4 GB RAM minimum** system req | "< 500 MB without a local LLM" (self-reported docs) | not published | Python 3.11 env | N subprocesses | Repo/languages primary; RAM self-reported |
-
-## Per-harness notes
-
-**OpenAI Codex CLI.** Confirmed Rust rewrite (~June 2025) shipping one
-self-contained binary. The only hard number is 80 MB binary size on macOS
-arm64, from OpenAI's own tracker (openai/codex#13091) — which proposes
-feature-gating heavy dependencies to reach ~55-60 MB, directly analogous to
-our Cargo domain gates. Memory claims are qualitative ("no unbounded Node heap
-growth"). Scope: coding agent only — no persistent curated cross-session
-memory core, no multi-agent orchestration, no channels, no workflow engine.
-
-**ZeroClaw.** Rust single-binary positioned against OpenClaw. All numbers are
-vendor self-reported (`/usr/bin/time -l` on their own build) with zero
-third-party verification, promoted across a cluster of lookalike SEO domains.
-The "7.8-12 MiB under load" figure previously cited in our docs could not be
-found in any source and has been downgraded to unverified. ZeroClaw is a
-separate project from OpenClaw, not a rebrand.
-
-**OpenClaw lineage.** The Clawdbot → Moltbot → OpenClaw rebrand chain is
-well-sourced (TechCrunch, CNBC, Forbes, Jan 2026). The ">1 GB RAM" figure
-appears only in ZeroClaw's competitive marketing; plausible for a Node daemon
-with browser automation, but there is no neutral benchmark.
-
-**Claude Code.** Node/V8 CLI. No clean published idle baseline; ~500 MB comes
-from a third-party SEO article and leak-report starting points. What is
-well-documented (primary GitHub issues) is a family of off-heap RSS leak bugs:
-400-500 MB/min growth while idle (#67433), 14 GB OOM (#28731), 93 GB heap
-(#22188), idle CPU thrash (#18280). Those are bugs, not steady state — but
-they are a cautionary tale about native-buffer discipline in long-running
-Node agent processes.
-
-**Hermes Agent.** The closest scope match to OpenHuman (SQLite + FTS5 + WAL
-curated memory, parent/child subagent lineage, cron, unified
-Telegram/Discord/Slack/Signal/WhatsApp/WeChat gateway) — and it is Python 81% /
-TypeScript 16%, not Rust. Subagents run as isolated subprocesses, so it pays
-its base footprint per agent. Self-reported "under 500 MB without a local
-LLM", 4 GB RAM minimum.
-
-## What this means for OpenHuman
-
-**Today.** Against honest scope-matched peers we are clearly leaner: Hermes at
-similar capability self-reports ~10x our settled RSS and requires 4 GB
-minimum; Claude Code starts around a claimed ~500 MB with documented multi-GB
-leaks; Codex's binary (80 MB) is larger than our stripped library-minimal
-build (60 MB). The only harness claiming to be dramatically smaller —
-ZeroClaw at "<5 MB" — is unverified marketing carrying far less capability.
-
-**End-state.** The library-minimal + shared-services target (~15 MiB private
-footprint + ~2 MiB per in-process agent) is not a stretch goal: today's
-~42 MiB slim RSS already decomposes to 15.2 MiB private / 3.2 MiB live heap,
-the rest being reclaimable executable text and allocator high-water. State
-that with the RSS-vs-private-footprint caveat attached.
-
-**Worth borrowing / leaning into:**
-
-1. Feature-gating heavy deps is now industry practice (Codex #13091) —
- external validation of our domain-gate investment.
-2. Rust + single self-contained binary is the market direction; the
- Node-based peers are the ones with RSS horror stories.
-3. **In-process shared-services scaling is our differentiator.** Every
- scope-matched peer scales agents as N OS processes, paying the fixed base
- N times. Our ~0.4-1.8 MiB marginal per in-process agent is the entire
- basis of the 1000-agents-in-2-GB story; nobody else has it.
-4. Internalize (not borrow) Claude Code's leak history: keep the warmed
- repeated-turn plateau benchmark as a standing regression gate.
-
-## Sources
-
-- OpenAI codex#13091 — 80 MB binary / feature-gating proposal
-- devclass (2025-06) — Codex Rust rewrite announcement coverage
-- anthropics/claude-code#67433, #28731, #22188, #18280 — leak/idle-CPU bugs
-- zeroclaw.net; openclawconsult.com "lab" comparison (self-reported marketing)
-- TechCrunch / Forbes (2026-01) — OpenClaw rebrand lineage
-- github.com/nousresearch/hermes-agent — language split, architecture
-- hermes-agent.nousresearch.com docs — memory features, footprint claim
diff --git a/docs/library-benchmarking.md b/docs/library-benchmarking.md
deleted file mode 100644
index 21543d946e..0000000000
--- a/docs/library-benchmarking.md
+++ /dev/null
@@ -1,381 +0,0 @@
-# Library benchmarking environment
-
-## Purpose
-
-"opencompany" wants to embed the OpenHuman Rust core as a library: no always-on
-RPC server, no Tauri shell, just the core linked in-process and driven
-directly. That changes what "resource usage" means. There is no single steady
-process to profile; there are per-use-case workloads (a long-running agent
-loop, a delegated multi-agent turn, a saved workflow run, a memory ingest,
-a bare embed) that each have their own
-startup cost, steady-state footprint, and growth curve.
-
-This document describes the benchmark environment built to measure that: a
-pinned `library-profile` binary with seven scenarios, the driver scripts
-under `scripts/profile/`, and the comparison point the team cares about
-(ZeroClaw). It builds on an earlier manual investigation into deep memory/CPU
-attribution (removed from the tree; see git history at `0017c58d86~1` for the
-original write-up). This document is about running repeatable benchmarks, not
-re-deriving those findings.
-
-## The scenarios
-
-The binary dispatches six scenarios: `agent-turn`, `long-agent`, `workflow`,
-`fleet`, `skill-run` and `subagent-storm` (`crates/openhuman-cli/src/bin/library_profile/main.rs`).
-The default `library-bench.sh` sweep runs them. `memory-ingest` and `cold-phases` remain documented workload
-designs, but are excluded because the binary no longer links the in-process
-memory engine they measured (superseded by Memory v2, whose engine is remote). All runnable scenarios run in
-`target/release/library-profile <scenario>`, replace
-network inference with a deterministic provider (`rss-bench` feature), and
-print one pretty-printed JSON result object to stdout (diagnostics go to
-stderr). Each models a distinct embedding use case:
-
-| Scenario | Models |
-| --- | --- |
-| `subagent-storm` | A delegation turn: an orchestrator session spawns real subagents via `spawn_parallel_agents` and merges their findings. |
-| `skill-run` | One skill run end to end, the path a host takes when it ships bundles rather than ad hoc chat. |
-| `agent-turn` | The minimal embed case: one agent, one turn, no delegation, no workflow. The smallest useful "hello world" for a host that just wants a single reply. |
-| `long-agent` | A long-running agent loop (`OPENHUMAN_PROFILE_TURNS`, default 25) in one process, to see whether RSS plateaus or grows per turn. |
-| `workflow` | A saved automation run (`flows_create` + `flows_run`), representing the flows/automation embedding path rather than ad hoc chat. |
-| `fleet` | N concurrent live agents with latency-realistic mock inference — the "100-1000 agents in a 2 GB / 2 vCPU server" question. See [below](#the-2-gb--2-vcpu-server-budget). |
-
-## How to run
-
-Seven scripts under `scripts/profile/` (each has `-h`/`--help`):
-
-- **`library-bench.sh`** — the primary RSS/duration benchmark. Builds the
- binaries, runs each scenario N fresh-process repeats (default 5), and
- aggregates median/min/max into `summary.json` + `summary.md`.
-
- ```bash
- ./scripts/profile/library-bench.sh # default build, all scenarios
- ./scripts/profile/library-bench.sh --slim # --no-default-features recipe
- ./scripts/profile/library-bench.sh --scenarios "long-agent,subagents" --turns 50 --warm
- ```
-
-- **`library-cpu.sh`** — a `samply` wrapper for one scenario's CPU profile,
- isolated from persistence/timezone noise by default.
-
- ```bash
- ./scripts/profile/library-cpu.sh subagents
- samply load target/profile/rust-library/subagents-cpu.json.gz
- ```
-
-- **`library-heap.sh`** — builds the `rss-bench-dhat` variant and runs a
- scenario under dhat for live-heap attribution (allocation sites, retained
- bytes). RSS/timing under dhat are perturbed; don't compare those numbers to
- `library-bench.sh` output.
-
- ```bash
- ./scripts/profile/library-heap.sh agent-turn
- # load target/profile/rust-library/dhat-agent-turn.json at
- # https://nnethercote.github.io/dh_view/dh_view.html
- ```
-
-- **`library-fleet.sh`** — sweeps the `fleet` scenario across a list of agent
- counts and gates the result against the 2 GB / 2 vCPU server budget (see
- below).
-
- ```bash
- ./scripts/profile/library-fleet.sh --agents 100 --latency-ms 200
- ./scripts/profile/library-fleet.sh --agents "50,100,500" --target 1000 --budget-mib 2048
- ```
-
-- **`library-instances.sh`** — sweeps N independent *processes* (not agents
- in one process) of a scenario, held alive via `OPENHUMAN_PROFILE_HOLD_SECS`,
- and measures per-instance/aggregate cost — the many-processes counterpart
- to `library-fleet.sh`'s one-process model (see
- [below](#fleet-one-process-vs-instances-many-processes)).
-
- ```bash
- ./scripts/profile/library-instances.sh --instances "10,25,50" --hold-secs 30
- ```
-
-- **`library-pool-gate.sh`** — the runtime-pool regression gate (#5106). Runs
- `skill-run` with K parallel skill runs and asserts the process tree grows by
- ~one pooled worker, not K interpreters; reports pooled vs unpooled.
-
- ```bash
- ./scripts/profile/library-pool-gate.sh --concurrency 8 --workers 1
- ```
-
-### Default vs slim builds
-
-The Product/desktop feature set links every compile-time domain gate (`voice`, `web3`,
-`media`, `meet`, `skills`, `flows`, `mcp`, `tui`) — the byte-identical desktop
-recipe. The slim recipe drops everything not required by the harness:
-
-```bash
-cargo build --release \
- -p openhuman \
- --no-default-features --features rss-bench \
- --bin library-profile --bin rss-bench
-```
-
-`--slim` on `library-bench.sh` builds this recipe. Per the prior session,
-compile-time gates shrink the binary substantially but only move settled RSS
-by a few MiB — most of the RSS story is initialization and allocator
-behavior, not linked code size.
-
-### Useful env knobs
-
-| Variable | Effect |
-| --- | --- |
-| `OPENHUMAN_PROFILE_TURNS` | Turn count for `long-agent` (default 25). |
-| `OPENHUMAN_PROFILE_PREWARM_SUBAGENTS=1` | Run one warm-up turn before measuring (`subagents`), isolating first-use cost from steady state. |
-| `OPENHUMAN_PROFILE_DISABLE_MEMORY_WRITES=1` | Disable memory writes (conversation logging and the per-turn memory lifecycle), isolating orchestration from persistence. |
-| `OPENHUMAN_PROFILE_FORCE_UTC=1` | Skip `iana_time_zone`/CoreFoundation timezone resolution. |
-| `OPENHUMAN_PROFILE_HOLD_SECS` / `HOLD_BEFORE_SECS` | Pause the process at settled/baseline state for external inspection (`vmmap`, `heap`, `malloc_history`, Instruments). |
-| `OPENHUMAN_PROFILE_DHAT_OUT` | Output path for dhat JSON (set by `library-heap.sh`). |
-| `OPENHUMAN_PROFILE_SKILL_RUN_CONCURRENCY` | `skill-run`: number of parallel orchestrator turns (K), each emitting a scripted `node_exec` call (default 1). |
-| `OPENHUMAN_PROFILE_SKILL_RUN_POOL` | `skill-run`: `off` disables the shared runtime pool (legacy per-call spawn; tree then shows ~K resident `node` children). Default on. |
-| `OPENHUMAN_PROFILE_SKILL_RUN_POOL_WORKERS` | `skill-run`: pool size W when pooling is on (default 1). The scenario asserts `child_count <= W` for K > 1 — the #5106 regression gate. |
-
-## Metrics and interpretation
-
-Every run reports `baseline`/`settled`/`peak_rss_kib` (macOS: `proc_pid_rusage`
-RSS, `getrusage` peak, `proc_pidinfo` thread count), `retained_delta_kib`
-(settled minus baseline), `peak_delta_kib`, and `duration_ms`. `long-agent`
-additionally reports `checkpoints[]` so first-turn vs. last-turn growth is
-visible directly.
-
-**RSS is not private heap.** The prior session's deep attribution found a
-~42 MiB slim-build snapshot broken down as roughly 15.2 MiB private physical
-footprint, 3.18 MiB live heap, 18.7 MiB resident executable text, and ~9.4 MiB
-of resident-but-mostly-inactive malloc pages (allocator high-water
-retention). See the original profiling session write-up (removed from the
-tree; git history at `0017c58d86~1`) for the full breakdown, the
-executable-paging finding (a cold turn faults in ~15 MiB of previously
-nonresident OpenHuman code), and the warmed-process control showing
-steady-state turns cost ~0.5-1.9 MiB once warm rather than the ~26-31 MiB a
-cold turn costs. Use `library-bench.sh` for the RSS/duration
-headline numbers, `library-cpu.sh` when CPU attribution is the question, and
-`library-heap.sh` only when RSS numbers need live-allocation attribution
-(accepting the dhat perturbation).
-
-## The ZeroClaw comparison
-
-ZeroClaw self-reports idling under 5 MiB RAM; the "7.8-12 MiB under load"
-figure sometimes quoted alongside it has no locatable primary source, and even
-the idle figure is vendor marketing with no third-party verification (see
-[`docs/harness-comparison-2026-07-22.md`](harness-comparison-2026-07-22.md)).
-OpenHuman's Rust core currently settles around 35-50 MiB depending on
-scenario and feature set (see the baseline table below).
-
-Treat this as a **north star, not an apples-to-apples benchmark**. ZeroClaw's
-scope and feature set differ substantially from the OpenHuman core: OpenHuman
-links a full agent/memory/tool/orchestration stack (pluggable Memory v2
-engine host, TinyMemory secret/PII scrubbing, prompt-injection detection, a builtin-agent
-registry, tool catalogs, provider routing) that a narrower harness may not
-carry at all. A closer gap is a meaningful signal that the initialization
-graph is leaner; it is not evidence of feature parity, and a wider gap is not
-automatically a regression if it comes from carrying more capability. Every
-`library-bench.sh` summary includes a labeled comparison row/note for exactly
-this reason: visible, but explicitly called out as external.
-
-## The 2 GB / 2 vCPU server budget
-
-"opencompany" wants a single server to host 100-1000 live agents inside a 2 GB
-RAM / 2 vCPU box. That is a budget question, not a per-scenario RSS question:
-2048 MiB / 1000 agents is roughly 2 MiB per agent all-in, but the fixed
-per-process base (allocator high water, code paging, registries, detectors —
-the same ~30 MiB every scenario above pays once) amortizes across however many
-agents share the process. What actually determines whether 1000 agents fit is
-the **marginal** cost per additional agent once that base is paid, not the
-per-agent average. `library-fleet.sh` runs the `fleet` scenario (N concurrent
-live agents, latency-realistic mock inference so idle time looks like real
-network waits rather than a busy loop) across a sweep of N and reports that
-marginal cost directly (`marginal_rss_kib_per_agent`), alongside idle CPU over
-a parked 10s window, thread count, and open FD count — all of which should
-stay roughly flat as N grows if per-agent state is cheap and idle agents cost
-~zero CPU.
-
-Working targets: marginal cost ≤ 1.5 MiB/agent, threads and FDs flat (not
-linear) in N, and idle CPU low regardless of N — an agent that isn't mid-turn
-should not be spending cycles. `OPENHUMAN_PROFILE_WORKER_THREADS=2` pins the
-scenario's tokio runtime to 2 worker threads to simulate the 2 vCPU box rather
-than scaling with the host's actual core count. The `budget` block in each
-run's JSON (`target_agents`, `ram_budget_mib`, `projected_rss_mib_at_target`,
-`fits`) projects the swept marginal cost out to the real target (default 1000
-agents / 2048 MiB); `library-fleet.sh` aggregates medians per N into
-`summary.md` and exits nonzero if any swept N projects `fits: false`, making
-it usable as a CI-style regression gate (`--no-gate` to disable).
-
-**Caveats, stated plainly:** these numbers are gathered on macOS, which has no
-cgroup memory limit to enforce or observe locally — the budget check is a
-projection from measured marginal cost, not a live "did it actually get
-OOM-killed at N agents" test. macOS also lacks Linux's `/proc/<pid>/smaps_rollup`,
-which would give true PSS (proportional shared memory) instead of RSS; RSS
-overcounts shared pages (executable text, shared library mappings) in a way
-that matters more as agent count grows and more of the process footprint is
-genuinely shared. Treat the macOS numbers as an approximation of the target
-Linux server, not a substitute for it. The JSON schema already has a Linux
-path — `proc_metrics` reads `/proc/<pid>/status` and `/proc/<pid>/stat` on
-Linux — so true validation should eventually mean running the same
-`library-profile fleet` binary on a cgroup-limited Linux box (matching the 2
-vCPU / 2 GB target) rather than trusting the macOS projection alone.
-
-### Fleet (one process) vs instances (many processes)
-
-The budget section above measures one deployment shape: N agents sharing a
-single process. But "opencompany" may instead run OpenHuman as **N
-independent processes or containers** — one per tenant — rather than N
-agents inside one process. Those are different cost models and the fleet
-number does not answer the second one.
-
-- **Fleet (`library-fleet.sh`)** pays the ~30-50 MiB fixed base (allocator
- high water, code paging, registries, detectors) **once**, and amortizes it
- across however many agents share that process. Marginal cost per agent is
- what matters, and it can be well under 1 MiB once the base is paid.
-- **Instances (`library-instances.sh`)** pays that same fixed base **N
- times**, once per process — minus whatever the OS actually shares across
- processes (resident executable text, shared library mappings). Summed RSS
- across instances therefore **double-counts** those shared pages; it is an
- upper bound, not the true footprint. True per-instance marginal cost is
- better read from summed PSS (Linux only — macOS has no PSS-equivalent
- metric), which divides shared pages across the processes that share them.
-
-`library-instances.sh` spawns N held `library-profile` processes staggered
-on startup, samples aggregate sum-RSS every 2s while they hold at settled
-state, and reports median settled RSS/instance, mean and peak aggregate
-sum-RSS, and summed PSS when available, plus a labeled 2 GB-box
-extrapolation estimate:
-
-```bash
-./scripts/profile/library-instances.sh --instances "10,25,50" --hold-secs 30
-```
-
-**This is still a macOS proxy, not container validation.** True validation
-means running the same binary under real `cgroup` memory limits (e.g.
-`docker run --memory=2g`) on a Linux host and observing whether it survives
-or gets OOM-killed at the target instance count — not projecting from local
-sum-RSS. That is follow-up work, and it belongs on a Linux box. Run the
-validation on a native Linux host or under a Linux container with the target
-memory limit rather than relying on macOS Docker Desktop.
-
-## Profiling escalation path
-
-Start cheap, escalate only as needed:
-
-1. **`library-bench.sh`** — RSS/duration medians across fresh processes. Answers "did this change move the needle" for most changes.
-2. **`library-cpu.sh` (samply)** — symbolized CPU profile when a scenario is slower than expected, or to attribute cold-path CPU to a specific phase (registry init, agent build, memory construction, SQLite init, TinyAgents turn runner were the top contributors in the prior session).
-3. **`library-heap.sh` (dhat)** — live-heap allocation sites and retained bytes when RSS is high but the cause isn't obvious from CPU alone (e.g. an earlier PII `RegexSet` finding came from stack-logged allocation attribution, not CPU sampling).
-4. **Instruments / `vmmap` / `heap` / `malloc_history`** — deepest macOS-native attribution, using the `OPENHUMAN_PROFILE_HOLD_SECS` / `HOLD_BEFORE_SECS` hooks to pause the process at baseline or settled state:
-
- ```bash
- OPENHUMAN_PROFILE_HOLD_SECS=120 target/release/library-profile subagents &
- vmmap -summary <pid>
- heap -sH <pid>
-
- MallocStackLogging=1 OPENHUMAN_PROFILE_HOLD_SECS=120 \
- target/release/library-profile subagents &
- malloc_history <pid> -allBySize
- ```
-
- This is what surfaced the PII-sanitizer regex cache and the first-turn
- executable-paging finding in the prior session; reach for it only once
- `library-bench.sh`/`library-cpu.sh`/`library-heap.sh` have narrowed the
- question to a specific scenario and metric.
-
-## Current baseline numbers
-
-From the 2026-07-21 profiling session (medians over five fresh processes
-unless noted; see that document for methodology and caveats).
-
-The scenario names in the two tables below are the names that session used.
-`subagents` is now `subagent-storm`; `memory-ingest` and `cold-phases` no
-longer dispatch, so their rows cannot be reproduced from this tree and are
-kept only as the record of what was measured.
-
-| Scenario | Build | Median settled RSS | Median retained Δ |
-| --- | --- | ---: | ---: |
-| 1-agent roster | default | 38.7 MiB | - |
-| 8-agent roster | default | 41.5 MiB | +2.8 MiB total (~0.40 MiB/agent) |
-| 1-agent roster | slim | 35.5 MiB | - |
-| 8-agent roster | slim | 38.7 MiB | +3.2 MiB total |
-| `memory-ingest` (100 msgs) | default | 25.5 MiB | 9.31 MiB |
-| `memory-ingest` (100 msgs) | slim | 23.8 MiB | 8.58 MiB |
-| `subagents` (cold, 2 children) | default | 48.5 MiB | 30.8 MiB |
-| `subagents` (cold, 2 children) | slim | 42.4 MiB | 25.7 MiB |
-| `subagents` (warmed repeat, persistence off) | default | - | 0.52 MiB |
-| `subagents` (warmed repeat, normal capture) | default | - | 1.84 MiB |
-| ZeroClaw (external, idle, self-reported/unverified) | - | < 5 MiB | - |
-
-First full `library-bench.sh` run of the new scenarios (default build, 5
-fresh-process repeats, 2026-07-21, Apple Silicon macOS):
-
-| Scenario | Build | Median settled RSS | Median retained Δ | Median duration |
-| --- | --- | ---: | ---: | ---: |
-| `agent-turn` (cold, 1 turn) | default | 47.6 MiB | 29.5 MiB | 102 ms |
-| `subagents` (cold, 2 children) | default | 48.0 MiB | 29.9 MiB | 142 ms |
-| `workflow` (`flows_create` + `flows_run`) | default | 50.9 MiB | 29.9 MiB | 110 ms |
-| `long-agent` (25 warmed turns) | default | 65.8 MiB | 18.5 MiB | 1,361 ms |
-| `cold-phases` (9 bootstrap phases) | default | 51.2 MiB | 36.5 MiB | 476 ms |
-| `memory-ingest` (100 msgs) | default | 25.8 MiB | 9.3 MiB | 2,099 ms |
-
-Notable structure behind these medians:
-
-- The `long-agent` per-turn series plateaus: typical turns add 30-150 KiB,
- and the 25-turn total (~16.8 MiB first-to-last) is dominated by two async
- persistence/compaction bursts of 6-8 MiB each, matching the prior session's
- warmed-repeat outlier observation. Steady-state growth is not linear.
-- Cold `agent-turn`, `subagents`, and `workflow` all retain
- approximately the same ~29-30 MiB, confirming the cost is shared bootstrap
- (code paging, registries, detectors, allocator high water), not the
- specific workload on top of it.
-- A dhat run of `agent-turn` measured 33.4 MB total allocated across 135,756
- blocks, but only 5.0 MB peak live heap and 3.1 MB live at exit, again
- showing RSS is mostly not live heap data.
-
-### Fleet, instances, and runtime baselines (2026-07-22, post-PII-prefilter)
-
-`library-fleet.sh` sweep (default build, 3 repeats, 3 turns/agent, 200 ms
-mock latency, 2 worker threads, target 1000 agents / 2048 MiB):
-
-| N agents | Marginal KiB/agent | Settled MiB | Idle CPU ms/10s | Threads | fds | p95 turn ms | Projected MiB @1000 | Fits |
-| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | :---: |
-| 50 | 1,985 | 223 | 3 | 71 | 420 | 2,848 | 1,956 | yes |
-| 100 | 1,866 | 356 | 3 | 123 | 820 | 5,402 | 1,840 | yes |
-| 500 | 1,770 | 1,393 | 3 | 211 | 3,220 | 25,484 | 1,747 | yes |
-
-`library-instances.sh` (many-processes model, `agent-turn` held 20 s):
-~47.8-48.2 MiB per instance flat at N=10/25/50 → roughly 42 instances per
-2 GiB by sum-RSS (upper bound; macOS has no PSS). The one-process fleet
-model is ~25x denser than the per-process model.
-
-Runtime/subagent scenarios: `skill-run` measures a real `node` child at
-~72-75 MB RSS (~121 MB process tree vs ~51 MB self) — the basis of the
-runtime-pooling issue (tinyhumansai/openhuman#5106); `subagent-storm` shows
-~0.78 MiB marginal per additional parallel subagent (K=8→32 cross-width).
-
-Runtime pool (#5106): with the shared pool on (the default), a batch of K
-concurrent `skill-run` turns shares a bounded set of warm `node` workers, so
-the process tree grows by ~one pooled worker instead of K interpreters.
-Measured at **K=8** (`max_workers=1`, system node v24): pooled tree
-`child_count=1` at **~202 MiB**, vs unpooled `child_count=8` at **~690 MiB**
-(eight `node` children of ~73–75 MB each) — a ~490 MiB / 3.4× reduction that
-grows with K. Compare the two regimes directly:
-
-```bash
-# Legacy: K interpreters resident at peak.
-OPENHUMAN_PROFILE_SKILL_RUN_CONCURRENCY=8 OPENHUMAN_PROFILE_SKILL_RUN_POOL=off \
- target/release/library-profile skill-run
-# Pooled: child_count stays at the pool size (asserted), not K.
-OPENHUMAN_PROFILE_SKILL_RUN_CONCURRENCY=8 OPENHUMAN_PROFILE_SKILL_RUN_POOL_WORKERS=1 \
- target/release/library-profile skill-run
-```
-
-The pool is configured in `[runtime_pool]` (master switch + per-language
-`node`/`python` `max_workers`, `idle_ttl_secs`, `recycle_after_jobs`,
-`max_queue_depth`); `enabled = false` reverts every caller to the legacy
-per-call spawn.
-
-Watch-items from the sweep: thread count grows ~0.35/agent (needs
-attribution + cap before real 1000-agent runs), and p95 latency at N=500 on
-2 workers shows CPU saturation is the load constraint, not memory.
-
-## See also
-
-- The original profiling session write-up (deep attribution, cold-path CPU, library-design implications, recommended optimization order) was removed from the tree; see git history at `0017c58d86~1`.
-- [`scripts/profile/README.md`](../scripts/profile/README.md) — script quick reference.
-- `crates/openhuman-cli/src/bin/library_profile/main.rs` — the scenario implementations.
diff --git a/scripts/__tests__/life-scenarios-mock-search.test.mjs b/scripts/__tests__/life-scenarios-mock-search.test.mjs
deleted file mode 100644
index 7e37ef9f60..0000000000
--- a/scripts/__tests__/life-scenarios-mock-search.test.mjs
+++ /dev/null
@@ -1,145 +0,0 @@
-/**
- * Behaviour of the life-scenario mock search backend
- * (`scripts/life-scenarios/mock-search.mjs`).
- *
- * The rig exists because `web_search_tool` posts to the hosted backend, which
- * the benchmark has no session for — so the tool 401'd on every call and the
- * agent burned its iteration budget routing around it by hand. These lock in
- * the two properties that make the substitute honest: it ranks a corpus of
- * real URLs the agent must still fetch for itself, and it returns nothing at
- * all for a query the corpus does not cover.
- */
-
-import assert from "node:assert/strict";
-import test, { after, before } from "node:test";
-
-import {
- DEFAULT_INDEX_PATH,
- startMockSearch,
-} from "../life-scenarios/mock-search.mjs";
-
-let server;
-
-before(async () => {
- server = await startMockSearch({ indexPath: DEFAULT_INDEX_PATH, port: 0 });
-});
-
-after(async () => {
- await server?.close();
-});
-
-/** Post a query the way `WebSearchTool` does. */
-async function search(objective, maxResults = 5) {
- const res = await fetch(`${server.url}/agent-integrations/parallel/search`, {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({
- objective,
- searchQueries: [objective],
- mode: "fast",
- excerpts: { maxResults, maxCharsPerResult: 500 },
- }),
- });
- assert.equal(res.status, 200);
- const envelope = await res.json();
- // `integrations/client/errors.rs::parse_envelope` deserializes
- // `{ success, data, error }` and returns `data`. A bare payload fails as
- // `missing field 'success'` — and fails late enough to look like a broken
- // tool rather than an empty result, so the agent abandons the task.
- assert.equal(
- envelope.success,
- true,
- "every response must carry the backend envelope",
- );
- return envelope.data;
-}
-
-test("the corpus loads past the fixture's _comment key", () => {
- assert.ok(
- server.ctx.documents.length > 0,
- "documents should come from the `documents` array, not the whole object",
- );
-});
-
-test("a baggage query ranks delta.com pages first", async () => {
- const body = await search(
- "Delta Air Lines Basic Economy carry-on baggage allowance transatlantic",
- );
- assert.ok(body.results.length > 0, "the corpus covers this query");
- assert.match(body.results[0].url, /(^|\.)delta\.com/);
-});
-
-test("a checked-bag fee query surfaces the fee page", async () => {
- const body = await search("Delta checked bag fee first second bag Europe");
- const urls = body.results.map((r) => r.url);
- assert.ok(
- urls.some((u) => /excess-overweight-baggage/.test(u)),
- `expected the fee page among ${JSON.stringify(urls)}`,
- );
-});
-
-test("an off-topic query returns nothing rather than the least-bad rows", async () => {
- // A confidently wrong result set is worse than an empty one: the agent
- // spends fetches on it, which is the failure mode this rig removes.
- for (const query of [
- "how do I bake sourdough bread at home",
- "completely unrelated zebra topic",
- ]) {
- const body = await search(query);
- assert.deepEqual(body.results, [], `"${query}" should match nothing`);
- }
-});
-
-test("results carry live URLs, so retrieval stays real", async () => {
- const body = await search("Delta baggage overview allowance");
- for (const item of body.results) {
- assert.match(item.url, /^https:\/\//, "every hit must be fetchable");
- assert.ok(item.title, "every hit must carry a title");
- }
-});
-
-test("maxResults is honoured and clamped", async () => {
- const body = await search("Delta baggage allowance fees carry-on checked", 2);
- assert.ok(body.results.length <= 2);
-});
-
-test("the search is recorded for post-mortems", async () => {
- const before = server.ctx.searches.length;
- await search("Delta baggage overview");
- assert.equal(server.ctx.searches.length, before + 1);
- assert.ok(server.ctx.searches.at(-1).queries.length > 0);
-});
-
-test("the cost is reported as zero, because it was", async () => {
- const body = await search("Delta baggage overview");
- assert.equal(body.costUsd, 0);
-});
-
-test("the unauthenticated backend calls get benign stubs", async () => {
- // Answered so the core's log shows the run's own behaviour rather than one
- // fixed auth failure repeated every turn. Enveloped like everything else.
- const usage = await fetch(`${server.url}/teams/me/usage`);
- assert.equal(usage.status, 200);
- assert.equal((await usage.json()).success, true);
-
- const toolkits = await fetch(
- `${server.url}/agent-integrations/composio/toolkits`,
- );
- assert.equal(toolkits.status, 200);
- const body = await toolkits.json();
- assert.equal(body.success, true);
- // Empty on purpose: Composio is served by mock-composio.mjs over the direct
- // base, and a competing list here would shadow it.
- assert.deepEqual(body.data.items, []);
-});
-
-test("an unhandled route 404s and is recorded", async () => {
- const res = await fetch(`${server.url}/agent-integrations/something-new`);
- assert.equal(res.status, 404);
- assert.ok(
- server.ctx.requests.some(
- (r) => r.path === "/agent-integrations/something-new",
- ),
- "a capability that starts reaching for the backend must be visible",
- );
-});
diff --git a/scripts/bench/FINDINGS.md b/scripts/bench/FINDINGS.md
deleted file mode 100644
index ce63ef51f8..0000000000
--- a/scripts/bench/FINDINGS.md
+++ /dev/null
@@ -1,370 +0,0 @@
-# Agent-scale benchmark — findings
-
-Measured with `scripts/bench/run-agent-scale.sh` against a release
-`openhuman-core` on one Linux box, mocked LLM, concurrency 8, `fresh` thread
-mode. Every number below is reproducible with the commands shown.
-
-## Summary
-
-Under sustained agentic load the core degrades: per-turn latency climbs
-linearly, throughput falls to about a third of its starting rate, and RSS grows
-without plateauing.
-
-**It is not a memory leak, and it is not a missing index.** Memory recall loads
-the *entire* memory namespace — every document and every vector chunk — on every
-turn, decodes each embedding, and scores them in-process behind a single
-connection mutex. Cost is Θ(memories stored) per turn, so a session's total work
-is quadratic and the throughput ceiling falls as memories accumulate. RSS grows
-because the working set is the stored data.
-
-## Evidence
-
-### 1. It tracks stored data, not process uptime
-
-A fresh core process pointed at an already-populated workspace **inherits the
-full cost immediately** rather than starting fast:
-
-| Run | Workspace | Start latency | End latency |
-| --- | --- | --- | --- |
-| C1 | empty | 111 ms | 438 ms |
-| C2 | C1's, **fresh process** | **532 ms** | 534 ms |
-
-```bash
-scripts/bench/run-agent-scale.sh --duration-ms 240000 --keep-workspace --out-dir target/bench/C1
-scripts/bench/run-agent-scale.sh --duration-ms 120000 --workspace target/bench/C1/workspace --out-dir target/bench/C2
-```
-
-A leak would have been left behind with the old process. This rules that out.
-
-### 2. Turning the memory subsystem off removes every symptom
-
-```bash
-scripts/bench/run-agent-scale.sh --duration-ms 240000 --tool-depth 0 # memory on
-scripts/bench/run-agent-scale.sh --duration-ms 240000 --tool-depth 0 --memory-off
-```
-
-| | memory ON | memory OFF |
-| --- | --- | --- |
-| latency over 4 min | 111 → 438 ms | **flat ~79 ms** |
-| throughput retained | 33% | **102%** |
-| RSS growth | +109 KiB/turn | **−0.65 KiB/turn** |
-| CPU per turn | 253 ms | **28 ms** |
-| turns completed | ~8,600 | **~24,500** |
-
-Nothing else in the turn path shows the behaviour. Tool depth is irrelevant —
-`--tool-depth 0` (no `memory_search` calls at all) degrades identically, so this
-is the implicit per-turn recall, not the agent's memory tool.
-
-### 3. What the recall actually does
-
-At 8,600 turns the store held 9,660 documents and 10,127 chunks, all in one
-`global` namespace. Per recall it loads all of both:
-
-```text
-chunks : 10127 rows, 39.6 MiB of embeddings materialized
-docs : 9660 rows
- ~61 ms of SQL per recall, warm cache
-```
-
-The indexes exist and are used (`idx_vector_chunks_ns_doc`,
-`idx_memory_docs_ns_updated` — `SEARCH … USING INDEX`). They cannot help: the
-query has no selective predicate, it wants every row in the namespace.
-`query_namespace_hits_excluding_session` does take a `limit`, but applies it
-after loading and scoring everything.
-
-### 4. It is the read path, not write contention
-
-Reads and writes share one connection, and `--memory-off` disables both — so on
-its own it cannot say which is expensive. Against an already-populated
-workspace, with writes off but recall still scanning every turn:
-
-```bash
-scripts/bench/run-agent-scale.sh --duration-ms 90000 --tool-depth 0 \
- --memory-writes-off --workspace <populated>
-```
-
-| | throughput | p50 |
-| --- | --- | --- |
-| reads + writes | 14.6/s | 540 ms |
-| **reads only** | **15.8/s** | **499 ms** |
-
-Removing every write buys ~8%. The recall scan is the cost; write contention is
-a rounding error.
-
-### 5. The single connection mutex sets the ceiling
-
-`UnifiedMemory` owns one `Mutex<Connection>`, so the scan serializes across
-concurrent turns. Throughput saturates accordingly:
-
-| concurrency | p50 | throughput |
-| --- | --- | --- |
-| 1 | 212 ms | 4.7/s |
-| 2 | 239 ms | 8.2/s |
-| 8 | 550 ms | 14.5/s |
-
-Saturation at ~14.5/s implies ~65 ms per turn in a serialized section, matching
-the measured ~61 ms scan. Adding cores cannot raise this, and it falls as the
-namespace grows.
-
-## The cost is work volume, not synchronization
-
-Two plausible optimizations were implemented and measured. Neither helped. Both
-were aimed at how the scan is *synchronized*; the thing that actually costs is
-how much the scan *touches*.
-
-The measurement that settles it, at 5,162 chunks, concurrency 8:
-
-```text
-p50 = 326 ms, throughput 24.1/s
-Little's law: 24.1 × 0.326 = 7.85 ≈ concurrency 8 → every worker busy all turn
-CPU: 6.85 of 14 cores (49%), 295 ms of CPU per turn
-```
-
-295 ms of **CPU** per turn, against 28 ms with memory off. That is not a queue
-behind a lock — it is real work being done, at half the machine's capacity, with
-no contention to remove. Any fix that leaves the same rows being read, decoded
-and scored will move this number by a few percent at best, which is exactly what
-both attempts did.
-
-### Two fixes that failed — do not repeat them
-
-**Attempt 1 — decode embeddings outside the connection lock.** Rationale: ~10k
-allocations and ~10M little-endian conversions per recall were happening inside
-the critical section. Interleaved A/B, 2 reps, identical populated workspaces:
-
-| arm | rep 1 | rep 2 | mean |
-| --- | --- | --- | --- |
-| baseline | 14.87/s | 14.37/s | 14.62/s |
-| decode outside lock | 14.42/s | 14.18/s | 14.30/s |
-
-**Attempt 2 — a read-only connection pool for the two O(N) scans.** Rationale:
-WAL supports concurrent readers, but one mutex-guarded connection serializes
-them, and half the cores were idle. Verified genuinely in use (the pooled arm
-held ~19 more file descriptors, and a unit test asserted connections were
-actually parked rather than silently falling back). Measured at two corpus sizes:
-
-| corpus | arm | rep 1 | rep 2 | mean |
-| --- | --- | --- | --- | --- |
-| 2,121 chunks | baseline | 37.21/s | 35.64/s | 36.43/s |
-| 2,121 chunks | read pool | 36.04/s | 34.56/s | 35.30/s |
-| 5,162 chunks | baseline | 24.07/s | 23.91/s | 23.99/s |
-| 5,162 chunks | read pool | 23.81/s | 23.55/s | 23.68/s |
-
-Both point estimates are slightly negative, consistently, across four pairs.
-Both changes were reverted; `vendor/tinymemory` is byte-identical to upstream
-`f8bd9af` (`git diff f8bd9af` is empty, 855 tests pass).
-
-**The lesson, stated plainly so it is not re-learned:** the recall path is not
-lock-bound and not I/O-bound. It is doing ~253 ms of CPU per turn touching every
-row in the namespace, twice over. Only reducing what is touched — items 1, 2, 3
-and 7 below — can change that. Micro-optimizing around the scan has now been
-measured twice and found worthless.
-
-## Deeper dive — where the cost actually is
-
-The first pass framed this as "recall is O(N), needs a vector index". That is
-true but it is the *last* thing to fix, not the first. Looking at the caller
-side changes the picture: most of the work is not needed at all.
-
-### The turn does more recalls than you would guess
-
-**4.26 embedding calls per turn**, measured identically across three independent
-runs (4.26 / 4.27 / 4.26 — `mock-stats.json` vs `driver.json`). Each recall
-embeds its query, so that count is a direct proxy for recall operations. Per
-turn there are **three full-namespace SQL recalls plus one vector-only query**,
-all before the LLM call, all blocking:
-
-| recall | query | limit | namespace |
-| --- | --- | --- | --- |
-| citations | user message | 5 | `global` |
-| working memory | `"working.user {msg}"` | 5 | `global` |
-| prior conversations | `"conversation_memory {msg}"` | 12 | `conversation_memory` |
-| situational prefs | user message | 5 | `user_pref_situational` |
-
-Two of them scan `global`. Sub-agents do **not** re-recall (they inherit the
-parent's block), so this is per user turn, not per agent.
-
-### What all that buys
-
-At most **9 lines and ~2000 characters** — roughly 500 tokens — reach the
-prompt: three each from working memory, prior conversations and cross-chat, each
-hard-capped. Citations do not reach the prompt at all; they populate
-`last_turn_citations` for the UI.
-
-Measured waste on the vector side: over 20 queries against a real 2,121-chunk
-corpus, **99.73%** of chunks scored fell below the 0.4 relevance floor. About
-six chunks per query clear it.
-
-And the cosine is not the expensive part — scoring 2,121 chunks takes **3.5 ms
-in JavaScript**, so well under a millisecond in Rust. The cost is re-reading and
-re-decoding the corpus from SQLite every turn, plus repeated full-content
-normalization on the keyword side.
-
-### The clearest single defect
-
-The working-memory recall builds the query string `"working.user {user_message}"`
-— a text hack meant to bias ranking — scans all of `global`, takes the top 5,
-and **then** filters `key.starts_with("working.user.")`
-(`crates/openhuman-core/src/memory/agent/memory_loader.rs:218-232` in the pre-change code;
-this PR removed the file's loader implementation).
-
-So it scans the entire namespace to find entries identified by a known key
-prefix. In the benchmark corpus:
-
-```text
-global docs scanned per turn : 2025
-docs with key 'working.user.': 0
-```
-
-Every one of those scans returned nothing usable. This is not only slow, it
-**degrades silently**: as autosaved chat fills `global`, the chance that a
-`working.user.*` entry survives into the global top-5 falls toward zero, so the
-feature quietly stops working long before anyone profiles it.
-
-> Caveat worth checking with someone who owns the sync path: I found **no
-> in-repo writer** of `working.user.*` keys at all — only the query, test
-> fixtures, and a doc comment describing them as "sync-derived profile facts".
-> If nothing writes them in current builds, this block is permanently empty and
-> the scan is pure cost. I could not confirm either way.
-
-### Why `global` grows without bound
-
-Every autosaved user message is stored with an empty namespace
-(`crates/openhuman-core/src/agent/harness/session/turn/core.rs:709`), which
-`sanitize_namespace` maps to `global` — the same namespace the two hot recalls
-scan. The corpus above is 2,024 `user_msg:*` documents and one other.
-
-Namespace partitioning already exists and is already used for
-`conversation_memory` and `user_pref_situational`. It is simply not applied to
-the two expensive calls.
-
-### The ceiling is the lock, and there are idle cores
-
-The box has **14 cores**; the memory-on run used **7.2**. So this is not CPU
-saturation. `UnifiedMemory` holds a single `Mutex<Connection>` and the recall
-path acquires it ~8 times per call, so ~61 ms per turn of serialized SQL caps
-throughput near 16/s — matching the measured 14.5/s — with half the machine
-idle.
-
-## What can be done, cheapest first
-
-The first three are in **`crates/openhuman-core/src/`, not the vendored crate**, and reduce
-how much is scanned rather than how fast the scan runs.
-
-**1. Scope the working-memory recall to its own namespace.** The entries are
-already identified by a key prefix; give them a namespace and query that instead
-of filtering `global` top-5 after the fact. Removes one full `global` scan per
-turn and *fixes* the silent-degradation bug — a working-memory entry can no
-longer be crowded out by unrelated chat. Uses machinery already in use
-elsewhere. **Do this one first even if nothing else is done.**
-
-**2. Take citations off the turn's critical path.** They are UI-only and never
-enter the prompt, yet a full `global` scan blocks the response on them. Removes
-the second `global` scan from the latency path.
-
-**3. Stop autosaving raw chat messages into `global`.** This is what makes N
-unbounded in the hottest namespace. Needs a product answer first: is raw
-user-message recall still earning its place now that `conversation_memory`
-(transcript-derived durable facts) and the cross-chat JSONL scan exist? If it is
-redundant, this is a one-line namespace change that bounds the problem
-permanently.
-
-**4. Add a timeout to recall.** Every call site already treats recall as
-best-effort (`unwrap_or_default()` throughout, failures logged and skipped) —
-but there is **no timeout anywhere**, and the turn blocks. A slow recall stalls a
-turn indefinitely today. This is a robustness fix worth making regardless of the
-performance work.
-
-Then, in the vendored crate, in this order:
-
-**5. Cache normalized document text.** `keyword_score_for_text` re-normalizes
-every document's full content on every recall (three allocations and ~three
-passes per call, via `normalize_search_text`). The result depends only on the
-document, never on the query, so it is recomputed identically every turn.
-Semantics-identical.
-
-**6. ~~A read-only connection pool.~~ Tried and measured — it does not help.
-See "Two fixes that failed" above.**
-
-**7. Only then, a vector index** (sqlite-vec / HNSW). This is the real answer for
-genuinely unbounded semantic search, and the only one that makes recall
-sub-linear — but items 1–3 cut N by far more than an index would cut the
-constant, and they carry much less risk. There is precedent for bounded
-retrieval everywhere else in the crate: `episodic_search`, `event_search_fts`,
-segments and entities are all `ORDER BY … LIMIT`. This one path is the outlier.
-
-## Outcome — what shipped and what it bought
-
-Items 1, 3 and 2 were implemented (branch `memory-recall-diet`):
-
-1. **`load_context()` removed.** The per-turn `[User working memory]` /
- `[Prior conversations]` / `[Cross-chat context]` block is gone, taking the
- `MemoryLoader` trait and `DefaultMemoryLoader` with it. Memory tools are
- untouched, so the model still fetches memory on demand.
-3. **Autosave moved out of `global`** into `conversation_raw`
- (`CONVERSATION_RAW_NAMESPACE`), applied to the agent turn and the channels
- dispatcher.
-2. **Citations overlapped rather than serialized.** They are UI-only but were a
- full recall blocking every reply before the model call; now spawned and
- joined in `take_last_turn_citations()`.
-
-Measured on **fresh** workspaces, 4 minutes, concurrency 8, tool-depth 0 —
-i.e. the growth test, since both arms start empty:
-
-| | baseline | recall diet | Δ |
-| --- | --- | --- | --- |
-| turns completed | 7,806 | **16,601** | 2.13× |
-| throughput | 32.5/s | **69.1/s** | 2.13× |
-| p50 latency | 232 ms | **102 ms** | 2.3× lower |
-| CPU per turn | 223 ms | **82 ms** | 2.7× lower |
-| RSS growth | 195 KiB/turn | **26 KiB/turn** | 7.5× lower |
-| latency drift over the run | 125 → 439 ms | **86 → 162 ms** | — |
-| throughput-held verdict | **fail** (33%) | **pass** (55%) | — |
-
-Namespace change confirmed in the resulting stores: baseline wrote
-`global=8202`; the diet build wrote `conversation_raw=17552, global=1`.
-
-### The residual growth is write-side, not read-side
-
-Latency still drifts in the diet build (86 → 162 ms), so the job is not
-finished. Running the same build with memory writes also disabled isolates it
-completely:
-
-| | throughput | p50 | latency over 4 min |
-| --- | --- | --- | --- |
-| baseline | 32.5/s | 232 ms | 125 → 439 ms |
-| diet | 69.1/s | 102 ms | 86 → 162 ms |
-| diet, no memory writes | **105.5/s** | **68 ms** | **75 → 76 ms (flat)** |
-
-Flat, and throughput held **99%**. So every remaining drift is in the memory
-*write* path — upsert, embedding, chunk insert against a growing store — and
-none of it is left on the read side. That is a smaller and separate problem;
-the candidate flagged during the dive is the conversation-store index
-(`vendor/tinycortex/.../conversations/store_index.rs`), which folds
-`threads.jsonl` from scratch on nearly every operation.
-
-Assistant summaries now follow user messages into `conversation_raw` and use a
-unique key, so concurrent sessions neither overwrite one global document nor
-leak raw conversation autosaves into default-namespace recall.
-
-## Tried and rejected
-
-- **Decode embeddings outside the connection lock** — implemented, measured, no
- effect. See "Two fixes that failed".
-- **A read-only connection pool** — implemented, measured, no effect. See the
- same section.
-- **A bounded/approximate candidate set as the first move** — not tried,
- deliberately: it changes which memories surface, and items 1–3 achieve more
- without that cost.
-
-## Separate finding — journal write amplification
-
-Every agent run writes a ~604 KB journal file to `tinyagents_store/journal/`,
-for a single trivial turn. One line accounts for ~424 KB: the model-call event
-serializes the full system prompt and the complete tool schemas for ~80 tools.
-A 4-minute run left ~5 GB behind; with memory off (so more turns complete) it
-reached ~13 GB.
-
-This is O(1) per turn, so it is **not** the cause of the degradation above, and
-the benchmark does not fail on it. It is flagged because ~600 KB per turn of
-mostly-static text is a real cost for long-lived installs.
diff --git a/scripts/bench/README.md b/scripts/bench/README.md
deleted file mode 100644
index c41b4da39c..0000000000
--- a/scripts/bench/README.md
+++ /dev/null
@@ -1,252 +0,0 @@
-# `scripts/bench/`: agent-scale benchmarks
-
-Drive a **real [`openhuman-core`](../../crates/openhuman-cli/README.md) server process** at concurrency against a
-mocked LLM ([`mock-llm.mjs`](./mock-llm.mjs)), sample its CPU and memory from the outside, and report a leak
-verdict. The pieces are [`run-agent-scale.sh`](./run-agent-scale.sh), [`driver.mjs`](./driver.mjs), [`sampler.mjs`](./sampler.mjs) and [`analyze.mjs`](./analyze.mjs).
-
-## How this differs from `scripts/profile/`
-
-Both measure resources; they answer different questions, and the difference is
-the reason this directory exists rather than another scenario in the old one.
-
-| | [`scripts/profile/`](../profile/README.md) | `scripts/bench/` (here) |
-| -------------- | --------------------------------------- | --------------------------------------------- |
-| Core runs as | a library, embedded in the bench binary | a normally-built `openhuman-core serve` process |
-| Driven through | direct `Agent` calls | JSON-RPC over HTTP `/rpc` |
-| LLM mocked by | a native `ChatModel` override | an HTTP endpoint the core dials |
-| Needs | `--features rss-bench` | nothing, the shipped feature set |
-| Measures | domain and harness cost in isolation | what the OS charges the shipped binary |
-| Best for | attributing cost to a subsystem | leak hunting, capacity, tail latency |
-
-`scripts/profile/` cannot see transport, serde, connection handling or the
-scheduler, because in that tier none of them run. This one includes all of it
-but attributes less precisely. Use `profile/` to find out *what* costs; use
-`bench/` to find out whether the thing you ship *grows*.
-
-## Requirements
-
-- Linux (the sampler reads `/proc`).
-- Node 20+.
-- **Artifacts on a disk-backed filesystem, not tmpfs.** The runner puts the
- core's workspace under `--out-dir` and refuses to start if that lands on
- tmpfs. This is not fussiness: tmpfs pages *are* memory, so the core's disk
- writes would be charged against the machine's RAM while the benchmark is
- trying to attribute RAM to the core, and a sustained run fills the mount,
- after which turns fail with "Failed to write auth profile lock owner" and
- SQLite I/O errors. That looks like a leak-induced meltdown and is a full disk.
-- **Several GB free.** A 5-minute run at concurrency 8 leaves ~5 GB of memory
- chunks and embeddings behind.
-- A release core binary:
-
-```bash
-cargo build --release --bin openhuman-core \
- --no-default-features --features "$(bash scripts/ci/product-features.sh)"
-```
-
-Release matters. A debug binary's allocation behaviour and CPU cost are not the
-product's, so a leak verdict taken from one says little.
-
-## Run it
-
-```bash
-scripts/bench/run-agent-scale.sh # defaults: 8 concurrent, 300 turns
-scripts/bench/run-agent-scale.sh --concurrency 32 --turns 2000
-scripts/bench/run-agent-scale.sh --duration-ms 900000 --tool-depth 3 # 15-minute soak
-```
-
-Exit status is the verdict: non-zero when a leak or drift check fails.
-Artifacts land in `target/bench/<timestamp>/`:
-
-| File | Contents |
-| ---------------- | ----------------------------------------------- |
-| `report.json` | verdicts and the numbers behind them |
-| `samples.jsonl` | the raw resource series |
-| `driver.json` | throughput, latency percentiles, error buckets |
-| `turns.jsonl` | per-turn latency and outcome |
-| `mock-stats.json`| what the mock actually served |
-| `core.log` | core stderr |
-
-Runner options (the script's `--help`):
-
-```text
---concurrency N parallel in-flight turns (default 8)
---turns N total turns in the measured window (default 300)
---duration-ms N run for a wall-clock duration instead of a turn count
---warmup-turns N turns to run and discard before measuring (default 10)
---tool-depth N tool calls the mock drives per turn (default 1)
---latency-ms N mock inference latency (default 40)
---jitter-ms N jitter around that latency (default 20)
---reply-chars N assistant reply size (default 240)
---fail-rate F fraction of completions answered 500 (default 0)
---thread-mode M fresh | per-worker | shared (default fresh)
---interval-ms N resource sampling interval (default 250)
---tree also sample descendant processes
---keep-workspace do not delete the temp workspace on exit
---workspace DIR reuse an existing populated workspace (implies --keep-workspace)
---memory-off disable memory reads and writes (recall + learning)
---memory-writes-off disable memory writes only, keep recall reads (mutually
- exclusive with --memory-off)
---out-dir DIR where to write artifacts (default target/bench/<stamp>)
-```
-
-### Memory comparison controls
-
-- `--memory-off` disables recall, autosave, learning hooks, embeddings, and the
- memory tree. Compare it with the default run to separate memory cost from
- unrelated uptime or harness effects.
-- `--memory-writes-off` disables autosave and learning writes but keeps recall.
- Use it with `--workspace DIR` pointing at populated data to distinguish read
- cost from write cost.
-- `--workspace DIR` reuses caller-owned data and keeps it after the run. Pair
- consecutive runs against the same populated corpus to distinguish data-size
- effects from process-uptime effects.
-
-The two memory-disable flags are mutually exclusive: `--memory-off` already
-includes the write suppression performed by `--memory-writes-off`.
-
-## How it works without touching the core
-
-Two facts carry the whole design, and a change to either breaks this tier:
-
-1. **`BACKEND_URL` redirects inference.** The core derives both its inference
- base and its backend base from that one value, so pointing it at the mock
- captures chat completions, embeddings and Langfuse telemetry together.
-2. **A session token shaped `<a>.<b>.local` skips backend validation.** Storing
- one persists a profile without the `GET /auth/me` round-trip a remote JWT
- would trigger, so the benchmark needs no login and the mock needs no auth
- routes. The driver seeds it before the load starts.
-
-The mock also must not listen on 11434, 8000, 8080, 1234 or 8888, the core
-classifies those as local-AI endpoints and routes around them. `mock-llm.mjs`
-refuses to start on one rather than failing mysteriously later.
-
-Three further details the runner handles, each of which silently ruins a run if
-you reproduce this setup by hand:
-
-- **The approval gate must be off** (`OPENHUMAN_APPROVAL_GATE=0`). It is on by
- default and parks interactive chat turns pending a human decision, with a
- 10-minute TTL that resolves to Deny.
-- **The daily cost limit must be raised.** The core prices the mock's reported
- token usage against a $10/day managed-inference budget and a sustained run
- exhausts it in a few hundred turns, after which every turn fails instantly.
- The runner raises the limit rather than disabling the check, so the budget
- check's own cost stays in the measurement.
-- **The embedding width must match** (the mock serves `--embed-dims`, default
- 1024; the runner never overrides it, so only hand-launched mocks can diverge).
- A mismatch is only a warning: chunks are stored without vectors and the memory
- write path runs degraded for the entire run.
-
-## Baseline
-
-See [`FINDINGS.md`](./FINDINGS.md) for the longer write-up of these runs.
-
-From a 5-minute run at concurrency 8, tool-depth 1, on one machine, indicative,
-not a target, and not yet reproduced across hosts:
-
-| Measure | Value |
-| ---------------------- | ------------------------------ |
-| Turns | ~8,500 (0 failed) |
-| Throughput | ~29 turns/s mean |
-| Latency | p50 260 ms, p99 570 ms |
-| CPU | ~6.9 cores mean, ~245 ms/turn |
-| RSS | 1.48 → 2.33 GiB |
-| Threads / FDs | stable |
-| Workspace written | ~5 GB |
-
-Two findings from that run reproduced across repeats and are worth chasing
-rather than treating as harness noise: RSS grew ~115 KiB/turn and was **still
-growing at the end** (confounded by the 5 GB of workspace growth, needs the
-memory-disabled comparison to settle), and **throughput fell to ~37% of its
-starting rate** under constant offered load, which the workspace growth does not
-obviously explain.
-
-## Reading a verdict
-
-Memory gets three outcomes, and the middle one is the point:
-
-- **pass**: no growth trend, or growth within the per-turn budget.
-- **plateau**: grew past the budget overall, but stopped climbing by the final
- third of the window. The shape of a cache filling to its working set. Worth
- re-running longer to confirm the plateau holds.
-- **fail**: grew past the budget *and was still growing at the end*.
-
-That distinction is why the analyzer fits the tail of the series separately
-rather than comparing an early average to a late one. Early-vs-late cannot tell
-"grew then stopped" from "never grew", and treating a saturating cache as a
-leak trains people to ignore the check.
-
-**Threads and open file descriptors are held to a stricter standard.** Neither
-has a legitimate reason to climb without bound under steady load, so they are
-straight thresholds rather than trend tests, and they fail independently of
-memory. In practice they are the least ambiguous leak signal available.
-
-**Memory verdicts can be `confounded`.** `fresh` thread mode stops conversation
-history accumulating, but it does not stop the agent persisting memory chunks
-and embeddings every turn, a 5-minute run writes gigabytes. An index over data
-that genuinely grew is not a leak. So when RSS fails alongside large workspace
-growth, the report marks the verdict `confounded` and says what it cannot rule
-out, rather than asserting a leak it cannot distinguish from correct behaviour.
-To separate the two: re-run with `--memory-off` (memory capture disabled), or
-run long enough that on-disk growth levels off while RSS keeps climbing.
-
-**Throughput held / liveness.** The analyzer checks that turns kept completing,
-because on resource metrics alone a dead process is indistinguishable from a
-healthy idle one, flat memory, no CPU, stable threads. An early version of this
-report gave a confident PASS on a run where the core had stopped answering two
-thirds of the way in. A total outage additionally marks `livenessBroken`, which
-qualifies every other verdict; mere degradation does not, because the process
-was still working and its resource numbers remain real.
-
-**CPU drift** compares CPU consumed per unit wall time between the start and
-end of the window. Under constant offered load a rising figure means each turn
-is costing more than the last, the CPU analogue of a memory leak, typically an
-unbounded structure being rescanned every turn.
-
-### Thread mode decides what you can conclude
-
-```bash
---thread-mode fresh # default: a new thread per turn
---thread-mode per-worker # one long conversation per worker
---thread-mode shared # all workers on one thread
-```
-
-Only `fresh` supports a leak verdict. In the other two, conversation history
-accumulates *by design*, so RSS growth is expected and a leak is
-indistinguishable from correct behaviour, the analyzer reports the growth rate
-and explicitly declines to judge it. Use them for contention and tail latency,
-not for leak hunting.
-
-## Tuning the mock
-
-```bash
---tool-depth N tool calls per turn before the final answer (exercises the
- agent loop, not just a single completion)
---latency-ms N mean inference latency; realistic values keep many turns
---jitter-ms N in flight and change the concurrency profile entirely
---reply-chars N reply size, varies serde and allocation pressure
---fail-rate F fraction of completions answered 500, to exercise retries
-```
-
-`--tool-depth 0` measures the RPC and inference path alone. Anything above zero
-puts the agent's tool loop under test, which is where per-turn state actually
-accumulates, so a leak hunt should use at least 1.
-
-## Tests
-
-The tests are in [`analyze.test.mjs`](./analyze.test.mjs).
-
-```bash
-node --test scripts/bench/analyze.test.mjs
-```
-
-The analyzer's failure mode is silence: wrong math reports "pass" on a leaking
-run and nobody notices. The tests drive it with synthetic series whose correct
-verdict is known by construction, a steady leak, a plateau, a flat line,
-thread and FD growth, CPU drift, so a regression in the leak math fails loudly.
-
-## Further reading
-
-- [`scripts/profile/`](../profile/README.md), the in-process counterpart.
-- [Performance and footprint](../../gitbooks/developing/performance.md) for the published numbers, and the public [openhuman-benchmarks](https://github.com/tinyhumansai/openhuman-benchmarks) repo for the cross-harness rig.
-- [`docs/library-benchmarking.md`](../../docs/library-benchmarking.md) for the embedded-library methodology.
-- [`scripts/ci/product-features.sh`](../ci/README.md), which defines the shipped feature set the release build uses.
diff --git a/scripts/bench/analyze.mjs b/scripts/bench/analyze.mjs
deleted file mode 100755
index b303b2a8ac..0000000000
--- a/scripts/bench/analyze.mjs
+++ /dev/null
@@ -1,713 +0,0 @@
-#!/usr/bin/env node
-/**
- * Leak / drift analysis for the agent-scale benchmark tier.
- *
- * Consumes the sampler's JSONL series plus the driver's summary and turn log,
- * and produces a verdict per resource. Kept separate from the load run so a
- * recorded run can be re-analyzed with different thresholds without paying for
- * the load again.
- *
- * WHAT A VERDICT HERE DOES AND DOES NOT MEAN
- *
- * A rising RSS line is not proof of a leak, and a flat one is not proof of its
- * absence. Allocators return memory to the OS lazily, arenas grow to a working
- * set and stop, and caches are supposed to fill. So the RSS check does not rest
- * on slope alone — it requires BOTH a positive slope AND a final window that
- * sits meaningfully above the earlier one, i.e. growth that never plateaued.
- * A run that grows and then levels off reports `plateau`, which is the healthy
- * shape for a process with caches.
- *
- * Thread and file-descriptor counts are held to a much stricter standard,
- * because unlike memory they have no legitimate reason to climb without bound
- * under steady load. A monotonic rise in either is a leak with far less room
- * for interpretation, which is why they are checked independently rather than
- * folded into a single score.
- *
- * In `per-worker` and `shared` thread modes conversation history genuinely
- * accumulates, so RSS growth is EXPECTED. The analyzer will not call a leak in
- * those modes; it reports the growth rate and says the mode cannot distinguish
- * a leak from intended retention. Use `fresh` for a leak verdict.
- *
- * `fresh` is necessary but NOT sufficient. It removes accumulating conversation
- * history; it does not stop the agent persisting memory chunks and embeddings
- * every turn, which a real run does to the tune of gigabytes. An index over data
- * that genuinely grew is not a leak. So when RSS fails alongside large workspace
- * growth, the verdict is marked `confounded` and says so, rather than asserting
- * a leak it cannot distinguish from correct behaviour.
- *
- * Usage:
- * node scripts/bench/analyze.mjs --samples samples.jsonl --driver summary.json \
- * [--out report.json] [--rss-kib-per-turn 8] [--warmup-frac 0.25]
- */
-
-import fs from 'node:fs';
-
-function parseArgs(argv) {
- const opts = {
- samples: null,
- driver: null,
- turns: null,
- workspaceMibBefore: null,
- workspaceMibAfter: null,
- out: null,
- // Growth budget per turn before RSS growth is called a leak. Default is
- // deliberately loose; tighten it per scenario once a baseline exists.
- rssKibPerTurn: 8,
- // Fraction of the series treated as warm-up and excluded. First-touch
- // initialization dominates early samples and would fake a steep slope.
- warmupFrac: 0.25,
- // Threads/FDs may drift a little with pool churn; require real growth.
- maxThreadGrowth: 8,
- maxFdGrowth: 32,
- };
- const spec = {
- '--samples': ['samples', String],
- '--driver': ['driver', String],
- '--turns': ['turns', String],
- '--workspace-mib-before': ['workspaceMibBefore', Number],
- '--workspace-mib-after': ['workspaceMibAfter', Number],
- '--out': ['out', String],
- '--rss-kib-per-turn': ['rssKibPerTurn', Number],
- '--warmup-frac': ['warmupFrac', Number],
- '--max-thread-growth': ['maxThreadGrowth', Number],
- '--max-fd-growth': ['maxFdGrowth', Number],
- };
- for (let i = 2; i < argv.length; i += 1) {
- const entry = spec[argv[i]];
- if (!entry) throw new Error(`unknown argument: ${argv[i]}`);
- const [key, cast] = entry;
- const raw = argv[++i];
- const value = cast(raw);
- if (cast === Number && !Number.isFinite(value)) {
- throw new Error(`${argv[i - 1]} expects a number, got: ${raw}`);
- }
- opts[key] = value;
- }
- if (!opts.samples) throw new Error('--samples <file.jsonl> is required');
- if (opts.warmupFrac < 0 || opts.warmupFrac >= 1) {
- throw new Error('--warmup-frac must be in [0, 1)');
- }
- return opts;
-}
-
-function readJsonl(file) {
- let dropped = 0;
- return fs
- .readFileSync(file, 'utf8')
- .split('\n')
- .filter(line => line.trim().length > 0)
- .flatMap(line => {
- try {
- return [JSON.parse(line)];
- } catch {
- dropped += 1;
- if (dropped === 1) {
- process.stderr.write(`[analyze] skipping unparsable line in ${file}\n`);
- }
- return [];
- }
- });
-}
-
-/** Ordinary least squares. Returns slope in units of y per unit of x. */
-function linearFit(xs, ys) {
- const n = xs.length;
- if (n < 2) return { slope: null, intercept: null, r2: null };
- const meanX = xs.reduce((a, b) => a + b, 0) / n;
- const meanY = ys.reduce((a, b) => a + b, 0) / n;
- let sxy = 0;
- let sxx = 0;
- for (let i = 0; i < n; i += 1) {
- sxy += (xs[i] - meanX) * (ys[i] - meanY);
- sxx += (xs[i] - meanX) ** 2;
- }
- if (sxx === 0) return { slope: null, intercept: null, r2: null };
- const slope = sxy / sxx;
- const intercept = meanY - slope * meanX;
-
- let ssRes = 0;
- let ssTot = 0;
- for (let i = 0; i < n; i += 1) {
- ssRes += (ys[i] - (slope * xs[i] + intercept)) ** 2;
- ssTot += (ys[i] - meanY) ** 2;
- }
- return { slope, intercept, r2: ssTot === 0 ? null : 1 - ssRes / ssTot };
-}
-
-const mean = arr => (arr.length ? arr.reduce((a, b) => a + b, 0) / arr.length : null);
-
-function windowMeans(values) {
- if (values.length < 4) return { early: null, late: null };
- const q = Math.max(1, Math.floor(values.length / 4));
- return { early: mean(values.slice(0, q)), late: mean(values.slice(-q)) };
-}
-
-const opts = parseArgs(process.argv);
-const allSamples = readJsonl(opts.samples);
-if (allSamples.length === 0) {
- process.stderr.write('[analyze] sample series is empty\n');
- process.exit(1);
-}
-const driver = opts.driver ? JSON.parse(fs.readFileSync(opts.driver, 'utf8')) : null;
-
-// Clip to the window in which load was actually being applied.
-//
-// This is load-bearing, not tidying. The sampler deliberately runs before the
-// driver starts and for a few seconds after it stops, so the series has an idle
-// head and an idle tail. Analyzing those is not merely noisy — it inverts the
-// result: an idle tail is flat and consumes no CPU, so "growth stopped by the
-// end" and "CPU rate fell" both become trivially true and every check passes
-// regardless of what happened under load. A short run, where the tail is a large
-// fraction of the series, would always report a clean bill of health.
-//
-// The driver records the wall-clock bounds of its measured window; samples carry
-// epochMs for exactly this alignment.
-let loadSamples = allSamples;
-let clippedTail = [];
-if (driver?.measureStartedAtMs && driver?.wallMs) {
- const loadStart = driver.measureStartedAtMs;
- const loadEnd = loadStart + driver.wallMs;
- const withEpoch = allSamples.filter(s => typeof s.epochMs === 'number');
- if (withEpoch.length > 0) {
- const inWindow = withEpoch.filter(s => s.epochMs >= loadStart && s.epochMs <= loadEnd);
- // Only trust the clip if it left enough to analyze; otherwise fall back to
- // the full series and say so, rather than failing on a technicality.
- if (inWindow.length >= 8) {
- loadSamples = inWindow;
- clippedTail = withEpoch.filter(s => s.epochMs > loadEnd);
- }
- }
-}
-const clippedToLoadWindow = loadSamples !== allSamples;
-
-// Drop the warm-up head of what remains.
-const skip = Math.floor(loadSamples.length * opts.warmupFrac);
-const samples = loadSamples.slice(skip);
-if (samples.length < 4) {
- process.stderr.write(
- `[analyze] only ${samples.length} samples after clipping to the load window ` +
- `and dropping ${skip} warm-up samples — run longer, sample more often, or ` +
- `lower --warmup-frac\n`
- );
- process.exit(1);
-}
-
-// A leak verdict drawn from a handful of samples over a couple of seconds is
-// not worth the confidence the word "pass" conveys. Warn rather than fail: the
-// throughput and latency figures are still useful at this size.
-const UNDERPOWERED_SAMPLES = 40;
-const UNDERPOWERED_MS = 30_000;
-const underpowered =
- samples.length < UNDERPOWERED_SAMPLES ||
- samples[samples.length - 1].tMs - samples[0].tMs < UNDERPOWERED_MS;
-
-const durationMs = samples[samples.length - 1].tMs - samples[0].tMs;
-const durationMin = durationMs / 60_000;
-
-const threadMode = driver?.config?.threadMode ?? 'unknown';
-// Turn count inside the analyzed window, used to express growth per turn. The
-// driver's total covers the whole measured run; scaling it by the analyzed
-// fraction is an approximation, and is labeled as such in the report.
-const turnsTotal = driver?.turnsOk ?? null;
-// Scale by the analyzed window only: allSamples includes the idle head before
-// the driver starts and the idle tail after it stops, so dividing by it would
-// deflate per-turn figures whenever the series was clipped.
-const analyzedFrac = loadSamples.length > 0 ? samples.length / loadSamples.length : 1;
-const turnsInWindow = turnsTotal !== null ? turnsTotal * analyzedFrac : null;
-
-function seriesFor(field) {
- const xs = [];
- const ys = [];
- for (const s of samples) {
- if (typeof s[field] === 'number' && Number.isFinite(s[field])) {
- xs.push(s.tMs);
- ys.push(s[field]);
- }
- }
- return { xs, ys };
-}
-
-function analyzeMemory(field, label) {
- const { xs, ys } = seriesFor(field);
- if (ys.length < 4) return { field, label, available: false };
-
- const fit = linearFit(xs, ys);
-
- /** Convert a KiB-per-ms slope into KiB per turn, or null if not derivable. */
- const perTurn = slope =>
- slope !== null && turnsInWindow && turnsInWindow > 0 && durationMs > 0
- ? (slope * durationMs) / turnsInWindow
- : null;
-
- const kibPerMin = fit.slope === null ? null : fit.slope * 60_000;
- const kibPerTurn = perTurn(fit.slope);
-
- // Whether growth has STOPPED is a question about the end of the run, not
- // about early-vs-late averages: a series that never grew and one that grew
- // and then flattened have the same early-vs-late delta, but only the second
- // is a plateau. So fit the final third separately and ask whether the line
- // is still climbing there.
- const tailStart = Math.floor(ys.length * (2 / 3));
- const tailFit = linearFit(xs.slice(tailStart), ys.slice(tailStart));
- const tailKibPerTurn = perTurn(tailFit.slope);
-
- const { early, late } = windowMeans(ys);
- const relativeGrowth = early && early > 0 ? (late - early) / early : null;
-
- const overBudget = kibPerTurn !== null && kibPerTurn > opts.rssKibPerTurn;
- const tailWithinBudget =
- tailFit.slope !== null &&
- (tailFit.slope <= 0 || (tailKibPerTurn !== null && tailKibPerTurn <= opts.rssKibPerTurn));
-
- let verdict;
- let reason;
- if (threadMode === 'per-worker' || threadMode === 'shared') {
- verdict = 'not-assessed';
- reason =
- `thread-mode=${threadMode} accumulates conversation history by design, so ` +
- `growth here cannot be distinguished from a leak. Re-run with ` +
- `--thread-mode fresh for a verdict.`;
- } else if (fit.slope === null || fit.slope <= 0) {
- verdict = 'pass';
- reason = 'no positive growth trend in the steady-state window.';
- } else if (!overBudget) {
- verdict = 'pass';
- reason =
- kibPerTurn !== null
- ? `growth ${kibPerTurn.toFixed(2)} KiB/turn is within the ` +
- `${opts.rssKibPerTurn} KiB/turn budget.`
- : 'positive slope but no turn count available to normalize against.';
- } else if (tailWithinBudget) {
- // It grew past the budget overall, but stopped climbing by the end — the
- // shape of a cache filling to its working set rather than an unbounded leak.
- verdict = 'plateau';
- reason =
- `grew ${kibPerTurn.toFixed(2)} KiB/turn overall but leveled off: the final ` +
- `third of the window grew ${tailKibPerTurn === null ? 'not at all' : `${tailKibPerTurn.toFixed(2)} KiB/turn`}` +
- `, within the ${opts.rssKibPerTurn} KiB/turn budget. Consistent with a ` +
- `cache reaching its working set rather than an unbounded leak. Run longer ` +
- `to confirm the plateau holds.`;
- } else {
- verdict = 'fail';
- reason =
- `grew ${kibPerTurn.toFixed(2)} KiB/turn and was still growing ` +
- `${tailKibPerTurn === null ? '' : `${tailKibPerTurn.toFixed(2)} KiB/turn `}` +
- `in the final third, over the ${opts.rssKibPerTurn} KiB/turn budget.`;
- }
-
- return {
- field,
- label,
- available: true,
- verdict,
- reason,
- firstKib: ys[0],
- lastKib: ys[ys.length - 1],
- minKib: Math.min(...ys),
- maxKib: Math.max(...ys),
- earlyWindowMeanKib: early,
- lateWindowMeanKib: late,
- relativeGrowth,
- kibPerMin,
- kibPerTurn,
- tailKibPerTurn,
- r2: fit.r2,
- };
-}
-
-function analyzeCounter(field, label, maxGrowth) {
- const { ys } = seriesFor(field);
- if (ys.length < 4) return { field, label, available: false };
- const first = ys[0];
- const last = ys[ys.length - 1];
- const max = Math.max(...ys);
- const { early, late } = windowMeans(ys);
- const growth = late - early;
- // Threads and FDs have no legitimate reason to climb without bound under
- // steady load, so this is a straight threshold rather than a trend test.
- const verdict = growth > maxGrowth ? 'fail' : 'pass';
- return {
- field,
- label,
- available: true,
- verdict,
- reason:
- verdict === 'fail'
- ? `grew by ${growth.toFixed(1)} between the early and final windows, ` +
- `over the budget of ${maxGrowth}.`
- : `stable (growth ${growth.toFixed(1)}, budget ${maxGrowth}).`,
- first,
- last,
- max,
- earlyWindowMean: early,
- lateWindowMean: late,
- growth,
- };
-}
-
-/**
- * CPU drift: does a turn cost more CPU at the end of the run than at the start?
- *
- * CPU counters are cumulative, so the meaningful quantity is the DERIVATIVE —
- * CPU ms consumed per wall ms — compared between the early and final windows.
- * A rising figure under constant offered load means per-turn work is growing,
- * which is the CPU analogue of a memory leak (an unbounded list being rescanned
- * every turn, say).
- */
-function analyzeCpu() {
- const usable = samples.filter(
- s => typeof s.cpuUserMs === 'number' && typeof s.cpuSystemMs === 'number'
- );
- if (usable.length < 8) return { available: false };
-
- const totals = usable.map(s => s.cpuUserMs + s.cpuSystemMs);
- const times = usable.map(s => s.tMs);
-
- const rates = [];
- for (let i = 1; i < usable.length; i += 1) {
- const dt = times[i] - times[i - 1];
- if (dt <= 0) continue;
- rates.push({ tMs: times[i], rate: (totals[i] - totals[i - 1]) / dt });
- }
- if (rates.length < 4) return { available: false };
-
- const rateValues = rates.map(r => r.rate);
- const { early, late } = windowMeans(rateValues);
- const drift = early && early > 0 ? (late - early) / early : null;
-
- const totalCpuMs = totals[totals.length - 1] - totals[0];
- const cpuMsPerTurn = turnsInWindow && turnsInWindow > 0 ? totalCpuMs / turnsInWindow : null;
-
- // 25% more CPU per unit time for the same offered load is a real drift, not
- // scheduling noise.
- const verdict = drift !== null && drift > 0.25 ? 'fail' : 'pass';
- return {
- available: true,
- verdict,
- reason:
- verdict === 'fail'
- ? `CPU rate rose ${(drift * 100).toFixed(1)}% from the early to the final ` +
- `window under constant offered load — per-turn work is growing.`
- : drift === null
- ? 'no early-window baseline to compare against.'
- : `CPU rate change ${(drift * 100).toFixed(1)}% is within noise.`,
- totalCpuMs,
- cpuMsPerTurn,
- earlyRateCpuMsPerMs: early,
- lateRateCpuMsPerMs: late,
- drift,
- meanUtilizationCores: durationMs > 0 ? totalCpuMs / durationMs : null,
- };
-}
-
-const memory = [
- analyzeMemory('rssKib', 'RSS'),
- analyzeMemory('pssKib', 'PSS'),
- analyzeMemory('privateKib', 'Private (clean+dirty)'),
-];
-if (samples.some(s => typeof s.treeRssKib === 'number')) {
- memory.push(analyzeMemory('treeRssKib', 'RSS incl. descendants'));
-}
-
-const threads = analyzeCounter('threads', 'Threads', opts.maxThreadGrowth);
-const fds = analyzeCounter('openFds', 'Open FDs', opts.maxFdGrowth);
-const cpu = analyzeCpu();
-
-const throughput = opts.turns ? analyzeThroughput(opts.turns) : { available: false };
-
-/**
- * On-disk state the run produced.
- *
- * This is the caveat to the memory verdict, not decoration. `fresh` thread mode
- * removes accumulating CONVERSATION history, but it does not stop the agent
- * persisting memory chunks and embeddings on every turn — a run can leave
- * gigabytes behind. An index over data that genuinely grew is not a leak, so a
- * failing RSS curve that arrives alongside large workspace growth is ambiguous
- * and has to be reported that way.
- */
-const workspace =
- opts.workspaceMibBefore !== null && opts.workspaceMibAfter !== null
- ? {
- available: true,
- beforeMib: opts.workspaceMibBefore,
- afterMib: opts.workspaceMibAfter,
- growthMib: opts.workspaceMibAfter - opts.workspaceMibBefore,
- }
- : { available: false };
-
-// Enough on-disk growth that an index over it could plausibly account for a
-// rising RSS curve on its own.
-const WORKSPACE_CONFOUND_MIB = 100;
-const memoryConfounded = workspace.available && workspace.growthMib >= WORKSPACE_CONFOUND_MIB;
-
-const checks = [...memory.filter(m => m.available), threads, fds, cpu, throughput].filter(
- c => c.available !== false
-);
-const failed = checks.filter(c => c.verdict === 'fail');
-
-// If the core STOPPED, every resource check is describing an idle process and
-// none of their verdicts mean what they appear to. Degradation is different:
-// the core was still working, just less, so the resource numbers remain real
-// even though the run is unhealthy. Conflating the two would put "the core
-// stopped serving" on a report where it plainly kept serving.
-const livenessBroken = throughput.available && throughput.stopped === true;
-// PSS and Private track RSS closely; the headline verdict keys off RSS, with
-// the others reported for corroboration.
-const overall = failed.length > 0 ? 'fail' : 'pass';
-
-/**
- * What happened after load stopped.
- *
- * Not a pass/fail check — it is an observation that helps interpret the memory
- * verdict. Memory released once work stops was working-set, not retained; memory
- * still held is the part a leak would live in. CPU that keeps burning after the
- * last turn is its own finding.
- */
-function analyzeSettle() {
- if (clippedTail.length < 2) return { available: false };
- const rss = clippedTail.map(s => s.rssKib).filter(v => typeof v === 'number');
- if (rss.length < 2) return { available: false };
-
- const lastUnderLoad = samples[samples.length - 1];
- const releasedKib = (lastUnderLoad.rssKib ?? rss[0]) - rss[rss.length - 1];
-
- const cpuFirst = clippedTail[0];
- const cpuLast = clippedTail[clippedTail.length - 1];
- const idleMs = cpuLast.tMs - cpuFirst.tMs;
- const idleCpuMs =
- typeof cpuFirst.cpuUserMs === 'number' && typeof cpuLast.cpuUserMs === 'number'
- ? cpuLast.cpuUserMs + cpuLast.cpuSystemMs - (cpuFirst.cpuUserMs + cpuFirst.cpuSystemMs)
- : null;
-
- return {
- available: true,
- tailSamples: clippedTail.length,
- idleWindowMs: idleMs,
- rssAtLoadEndKib: lastUnderLoad.rssKib ?? null,
- rssAfterSettleKib: rss[rss.length - 1],
- releasedKib,
- idleCpuMs,
- idleCpuFraction: idleMs > 0 && idleCpuMs !== null ? idleCpuMs / idleMs : null,
- };
-}
-
-const settle = analyzeSettle();
-
-/**
- * Did the core keep serving at a steady rate for the whole run?
- *
- * This check exists because the analyzer once reported a confident PASS on a
- * run where the core had stopped answering entirely two thirds of the way in.
- * Every other check agreed: memory was flat, CPU had fallen, threads were
- * stable — all true, and all because nothing was happening. A dead process is
- * indistinguishable from a healthy idle one on resource metrics alone, so
- * liveness has to be judged on whether work was actually completing.
- *
- * Reads the driver's per-turn log rather than the resource series, since that
- * is the only record of when turns completed.
- */
-function analyzeThroughput(turnsPath) {
- let turns;
- try {
- turns = readJsonl(turnsPath);
- } catch {
- return { available: false };
- }
- if (driver?.measureStartedAtMs && driver?.wallMs) {
- const loadStart = driver.measureStartedAtMs;
- const loadEnd = loadStart + driver.wallMs;
- const withEpoch = turns.filter(t => typeof t.epochMs === 'number');
- if (withEpoch.length > 0) {
- turns = withEpoch
- .filter(t => t.epochMs >= loadStart && t.epochMs <= loadEnd)
- .map(t => ({ ...t, tMs: t.epochMs - loadStart }));
- }
- }
- if (turns.length < 20) return { available: false };
-
- const okTurns = turns.filter(t => t.ok);
- if (okTurns.length < 20) return { available: false };
-
- // The window must be the run's actual duration, NOT the timestamp of the last
- // logged turn. If the core stops answering and the driver's in-flight requests
- // hang or stop being recorded, the log simply ends early — and measuring
- // against its own last entry would rescale the window to fit the period when
- // things still worked, hiding exactly the outage this check exists to catch.
- const runMs = driver?.wallMs ?? turns[turns.length - 1].tMs;
- const quarter = runMs / 4;
- const firstQuarter = okTurns.filter(t => t.tMs < quarter).length;
- const lastQuarter = okTurns.filter(t => t.tMs >= 3 * quarter).length;
-
- const firstRate = firstQuarter / (quarter / 1000);
- const lastRate = lastQuarter / (quarter / 1000);
- const retained = firstRate > 0 ? lastRate / firstRate : null;
-
- let verdict;
- let reason;
- let stopped = false;
- if (lastQuarter === 0) {
- verdict = 'fail';
- stopped = true;
- reason =
- `the core completed NO successful turns in the final quarter of the run ` +
- `(${firstQuarter} in the first quarter). It stopped serving — every other ` +
- `check in this report describes an idle process, not a healthy one.`;
- } else if (retained !== null && retained < 0.5) {
- verdict = 'fail';
- reason =
- `throughput fell to ${(retained * 100).toFixed(0)}% of its starting rate ` +
- `(${firstRate.toFixed(1)} → ${lastRate.toFixed(1)} turns/s) under constant ` +
- `offered load — the core is degrading as the run proceeds.`;
- } else {
- verdict = 'pass';
- reason =
- retained === null
- ? 'no starting rate to compare against.'
- : `held ${(retained * 100).toFixed(0)}% of its starting rate ` +
- `(${firstRate.toFixed(1)} → ${lastRate.toFixed(1)} turns/s).`;
- }
- return {
- available: true,
- verdict,
- reason,
- stopped,
- firstQuarterTurnsPerSec: firstRate,
- lastQuarterTurnsPerSec: lastRate,
- retainedFraction: retained,
- };
-}
-
-const report = {
- overall,
- threadMode,
- underpowered,
- underpoweredNote: underpowered
- ? `analyzed ${samples.length} samples over ${(durationMs / 1000).toFixed(1)}s. ` +
- `A leak verdict from a window this short is weak — growth and plateau are ` +
- `hard to separate over seconds. Prefer --duration-ms 900000 or more for a ` +
- `run you intend to act on.`
- : null,
- window: {
- totalSamples: allSamples.length,
- clippedToLoadWindow,
- loadWindowSamples: loadSamples.length,
- warmupSamplesDropped: skip,
- analyzedSamples: samples.length,
- durationMs,
- turnsTotal,
- turnsInWindowApprox: turnsInWindow,
- },
- settle,
- driverSummary: driver
- ? {
- turnsOk: driver.turnsOk,
- turnsFailed: driver.turnsFailed,
- throughputTurnsPerSec: driver.throughputTurnsPerSec,
- latencyMs: driver.latencyMs,
- errors: driver.errors,
- }
- : null,
- memory: memory.map(m =>
- m.available && m.verdict === 'fail' && memoryConfounded
- ? {
- ...m,
- confounded: true,
- confoundNote:
- `the workspace grew ${workspace.growthMib} MiB during this run, so some ` +
- `of this RSS growth is likely an index over data that genuinely ` +
- `accumulated rather than a leak. To separate the two, re-run with ` +
- `memory capture disabled, or run long enough that on-disk growth ` +
- `levels off while RSS does not.`,
- }
- : m
- ),
- workspace,
- threads,
- fds,
- cpu,
- throughput,
- livenessBroken,
- livenessNote: livenessBroken
- ? 'The core stopped serving during this run, so the memory, CPU, thread and ' +
- 'FD verdicts above describe an idle process and must not be read as a ' +
- 'clean bill of health. Fix the liveness failure and re-run.'
- : null,
- failedChecks: failed.map(c => `${c.label ?? 'check'}: ${c.reason}`),
-};
-
-const rendered = JSON.stringify(report, null, 2);
-if (opts.out) fs.writeFileSync(opts.out, rendered);
-
-// Human summary to stderr so stdout stays machine-readable.
-const lines = [];
-lines.push('');
-lines.push(` agent-scale benchmark — ${overall.toUpperCase()}`);
-lines.push(
- ` thread-mode=${threadMode} samples=${samples.length}/${allSamples.length}` +
- ` window=${(durationMs / 1000).toFixed(1)}s` +
- `${clippedToLoadWindow ? ' (clipped to load)' : ''}`
-);
-if (underpowered) lines.push(` WEAK EVIDENCE: ${report.underpoweredNote}`);
-if (driver) {
- lines.push(
- ` turns: ${driver.turnsOk} ok / ${driver.turnsFailed} failed` +
- ` throughput=${driver.throughputTurnsPerSec?.toFixed(2)}/s` +
- ` p50=${driver.latencyMs?.p50?.toFixed(0)}ms p99=${driver.latencyMs?.p99?.toFixed(0)}ms`
- );
-}
-lines.push('');
-for (const m of memory) {
- if (!m.available) continue;
- lines.push(
- ` ${m.verdict.padEnd(12)} ${m.label.padEnd(24)} ` +
- `${(m.firstKib / 1024).toFixed(1)} → ${(m.lastKib / 1024).toFixed(1)} MiB` +
- (m.kibPerTurn !== null ? ` (${m.kibPerTurn.toFixed(2)} KiB/turn)` : '')
- );
- lines.push(` ${m.reason}`);
- if (m.verdict === 'fail' && memoryConfounded) {
- lines.push(
- ` CAVEAT: the workspace grew ${workspace.growthMib} MiB — some of ` +
- `this is likely index over real data, not a leak.`
- );
- }
-}
-for (const c of [threads, fds]) {
- if (!c.available) continue;
- lines.push(
- ` ${c.verdict.padEnd(12)} ${c.label.padEnd(24)} ${c.first} → ${c.last} (max ${c.max})`
- );
- lines.push(` ${c.reason}`);
-}
-if (cpu.available) {
- lines.push(
- ` ${cpu.verdict.padEnd(12)} ${'CPU'.padEnd(24)} ` +
- `${cpu.meanUtilizationCores?.toFixed(2)} cores mean` +
- (cpu.cpuMsPerTurn !== null ? `, ${cpu.cpuMsPerTurn.toFixed(1)} ms/turn` : '')
- );
- lines.push(` ${cpu.reason}`);
-}
-if (throughput.available) {
- lines.push(
- ` ${throughput.verdict.padEnd(12)} ${'Throughput held'.padEnd(24)} ` +
- `${throughput.firstQuarterTurnsPerSec.toFixed(1)} → ` +
- `${throughput.lastQuarterTurnsPerSec.toFixed(1)} turns/s`
- );
- lines.push(` ${throughput.reason}`);
-}
-if (livenessBroken) {
- lines.push('');
- lines.push(` !! ${report.livenessNote}`);
-}
-if (settle.available) {
- lines.push('');
- lines.push(
- ` after load (${(settle.idleWindowMs / 1000).toFixed(1)}s idle): ` +
- `released ${(settle.releasedKib / 1024).toFixed(1)} MiB, ` +
- `idle CPU ${settle.idleCpuFraction === null ? 'n/a' : `${(settle.idleCpuFraction * 100).toFixed(1)}% of one core`}`
- );
-}
-lines.push('');
-process.stderr.write(`${lines.join('\n')}\n`);
-process.stdout.write(`${rendered}\n`);
-
-process.exit(overall === 'fail' ? 1 : 0);
diff --git a/scripts/bench/analyze.test.mjs b/scripts/bench/analyze.test.mjs
deleted file mode 100644
index e8b718564b..0000000000
--- a/scripts/bench/analyze.test.mjs
+++ /dev/null
@@ -1,523 +0,0 @@
-#!/usr/bin/env node --test
-/**
- * Tests for the agent-scale leak analyzer.
- *
- * The analyzer is the component whose failure mode is silence: if the math is
- * wrong it reports "pass" on a leaking run and nobody notices, which is worse
- * than not having the check at all. So the cases below drive it with synthetic
- * series whose correct verdict is known by construction — a steady leak, a
- * plateau, a flat line, thread and FD growth, and CPU drift.
- *
- * Run: node --test scripts/bench/analyze.test.mjs
- */
-
-import { test } from 'node:test';
-import assert from 'node:assert/strict';
-import { execFileSync } from 'node:child_process';
-import fs from 'node:fs';
-import os from 'node:os';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const HERE = path.dirname(fileURLToPath(import.meta.url));
-const ANALYZE = path.join(HERE, 'analyze.mjs');
-
-const INTERVAL_MS = 250;
-
-/**
- * Build a sample series.
- *
- * @param {object} opts
- * @param {number} opts.count number of samples
- * @param {(i: number, n: number) => number} opts.rssKib
- * @param {(i: number, n: number) => number} [opts.threads]
- * @param {(i: number, n: number) => number} [opts.openFds]
- * @param {(i: number, n: number) => number} [opts.cpuMs] cumulative total CPU
- */
-function buildSamples({ count, rssKib, threads, openFds, cpuMs }) {
- const lines = [];
- for (let i = 0; i < count; i += 1) {
- const tMs = i * INTERVAL_MS;
- const total = cpuMs ? cpuMs(i, count) : i * 50;
- lines.push(
- JSON.stringify({
- tMs,
- epochMs: 1_700_000_000_000 + tMs,
- rssKib: Math.round(rssKib(i, count)),
- vmHwmKib: Math.round(rssKib(i, count)),
- pssKib: null,
- privateKib: null,
- // Split the cumulative total across user/system; the analyzer sums them.
- cpuUserMs: total * 0.8,
- cpuSystemMs: total * 0.2,
- threads: threads ? Math.round(threads(i, count)) : 24,
- openFds: openFds ? Math.round(openFds(i, count)) : 40,
- }),
- );
- }
- return `${lines.join('\n')}\n`;
-}
-
-/**
- * Build a turn log at a given rate over time.
- * @param {(tMs: number) => number} ratePerSec turns/sec at a point in the run
- */
-function buildTurns(durationMs, ratePerSec, { failFrom = null } = {}) {
- const lines = [];
- const stepMs = 100;
- for (let tMs = 0; tMs < durationMs; tMs += stepMs) {
- const n = Math.round((ratePerSec(tMs) * stepMs) / 1000);
- for (let k = 0; k < n; k += 1) {
- const ok = failFrom === null || tMs < failFrom;
- lines.push(JSON.stringify({ tMs, workerId: 0, index: lines.length, latencyMs: 50, ok }));
- }
- }
- return `${lines.join('\n')}\n`;
-}
-
-function runAnalyzer(samplesText, driverSummary, extraArgs = [], turnsText = null) {
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bench-analyze-'));
- try {
- const samplesPath = path.join(dir, 'samples.jsonl');
- const driverPath = path.join(dir, 'driver.json');
- fs.writeFileSync(samplesPath, samplesText);
- fs.writeFileSync(driverPath, JSON.stringify(driverSummary));
-
- const args = [ANALYZE, '--samples', samplesPath, '--driver', driverPath, ...extraArgs];
- if (turnsText !== null) {
- const turnsPath = path.join(dir, 'turns.jsonl');
- fs.writeFileSync(turnsPath, turnsText);
- args.push('--turns', turnsPath);
- }
- let stdout;
- let exitCode = 0;
- try {
- stdout = execFileSync(process.execPath, args, { encoding: 'utf8', stdio: 'pipe' });
- } catch (err) {
- // A failing verdict is a non-zero exit, which execFileSync throws on.
- // That is an expected outcome here, not an error.
- exitCode = err.status ?? 1;
- stdout = err.stdout ?? '';
- }
- return { report: JSON.parse(stdout), exitCode };
- } finally {
- fs.rmSync(dir, { recursive: true, force: true });
- }
-}
-
-const driver = (overrides = {}) => ({
- config: { concurrency: 8, turns: 400, threadMode: 'fresh', warmupTurns: 10 },
- // The measured run lasted 50s — the same span the synthetic turn logs cover.
- // The throughput check keys off this rather than the last logged turn.
- wallMs: 50_000,
- turnsOk: 400,
- turnsFailed: 0,
- throughputTurnsPerSec: 10,
- latencyMs: { p50: 80, p99: 200 },
- errors: {},
- ...overrides,
-});
-
-test('steady unbounded RSS growth is reported as a leak', () => {
- // 200 samples at 250ms = 50s, growing 400 KiB/sample = a relentless climb.
- const samples = buildSamples({ count: 200, rssKib: (i) => 120_000 + i * 400 });
- const { report, exitCode } = runAnalyzer(samples, driver());
-
- const rss = report.memory.find((m) => m.field === 'rssKib');
- assert.equal(rss.verdict, 'fail', rss.reason);
- assert.ok(rss.kibPerTurn > 0, 'should attribute growth per turn');
- assert.equal(report.overall, 'fail');
- assert.equal(exitCode, 1, 'a failing verdict must exit non-zero');
-});
-
-test('growth that levels off is reported as a plateau, not a leak', () => {
- // Climbs hard through the first part of the ANALYZED window (which starts at
- // sample 50, after the warm-up head is dropped) and then stops dead at 130.
- // Overall slope is well over budget, but the final third is flat — the shape
- // of a cache filling to its working set. Distinguishing this from a leak is
- // the whole point of fitting the tail separately.
- const samples = buildSamples({
- count: 200,
- rssKib: (i) => 120_000 + Math.min(i, 130) * 400,
- });
- const { report, exitCode } = runAnalyzer(samples, driver());
-
- const rss = report.memory.find((m) => m.field === 'rssKib');
- assert.equal(rss.verdict, 'plateau', rss.reason);
- assert.ok(rss.kibPerTurn > rss.tailKibPerTurn, 'tail should grow slower than overall');
- assert.equal(report.overall, 'pass');
- assert.equal(exitCode, 0);
-});
-
-test('a flat RSS series passes', () => {
- // Small oscillation around a fixed level, no trend.
- const samples = buildSamples({
- count: 200,
- rssKib: (i) => 120_000 + Math.sin(i / 5) * 500,
- });
- const { report } = runAnalyzer(samples, driver());
-
- const rss = report.memory.find((m) => m.field === 'rssKib');
- assert.equal(rss.verdict, 'pass', rss.reason);
- assert.equal(report.overall, 'pass');
-});
-
-test('accumulating thread modes are not assessed for leaks', () => {
- // Same leaking series as the first test, but in a mode where growth is
- // expected. The analyzer must decline to call it rather than raise a false
- // alarm on conversation history.
- const samples = buildSamples({ count: 200, rssKib: (i) => 120_000 + i * 400 });
- const { report, exitCode } = runAnalyzer(
- samples,
- driver({ config: { threadMode: 'per-worker' } }),
- );
-
- const rss = report.memory.find((m) => m.field === 'rssKib');
- assert.equal(rss.verdict, 'not-assessed');
- assert.match(rss.reason, /--thread-mode fresh/);
- assert.equal(exitCode, 0, 'declining to assess is not a failure');
-});
-
-test('thread growth fails independently of memory', () => {
- const samples = buildSamples({
- count: 200,
- rssKib: () => 120_000, // memory perfectly flat
- threads: (i) => 24 + i * 0.5, // but threads climb
- });
- const { report, exitCode } = runAnalyzer(samples, driver());
-
- assert.equal(report.memory.find((m) => m.field === 'rssKib').verdict, 'pass');
- assert.equal(report.threads.verdict, 'fail', report.threads.reason);
- assert.equal(report.overall, 'fail');
- assert.equal(exitCode, 1);
-});
-
-test('file-descriptor growth fails independently of memory', () => {
- const samples = buildSamples({
- count: 200,
- rssKib: () => 120_000,
- openFds: (i) => 40 + i * 2,
- });
- const { report } = runAnalyzer(samples, driver());
-
- assert.equal(report.fds.verdict, 'fail', report.fds.reason);
- assert.equal(report.overall, 'fail');
-});
-
-test('stable threads and fds pass', () => {
- const samples = buildSamples({
- count: 200,
- rssKib: () => 120_000,
- threads: () => 24,
- openFds: (i) => 40 + (i % 3), // churn, but no trend
- });
- const { report } = runAnalyzer(samples, driver());
-
- assert.equal(report.threads.verdict, 'pass');
- assert.equal(report.fds.verdict, 'pass');
- assert.equal(report.overall, 'pass');
-});
-
-test('rising CPU cost per unit time is reported as drift', () => {
- // Quadratic cumulative CPU means a linearly rising rate: the same offered
- // load costing steadily more, which is the CPU analogue of a leak.
- const samples = buildSamples({
- count: 200,
- rssKib: () => 120_000,
- cpuMs: (i) => 0.02 * i * i,
- });
- const { report, exitCode } = runAnalyzer(samples, driver());
-
- assert.equal(report.cpu.verdict, 'fail', report.cpu.reason);
- assert.ok(report.cpu.drift > 0.25);
- assert.equal(exitCode, 1);
-});
-
-test('constant CPU rate passes and reports per-turn cost', () => {
- const samples = buildSamples({
- count: 200,
- rssKib: () => 120_000,
- cpuMs: (i) => i * 100, // steady 100ms CPU per 250ms wall
- });
- const { report } = runAnalyzer(samples, driver());
-
- assert.equal(report.cpu.verdict, 'pass', report.cpu.reason);
- assert.ok(report.cpu.cpuMsPerTurn > 0);
- assert.ok(report.cpu.meanUtilizationCores > 0);
-});
-
-test('warm-up samples are excluded from the analyzed window', () => {
- const samples = buildSamples({ count: 200, rssKib: () => 120_000 });
- const { report } = runAnalyzer(samples, driver(), ['--warmup-frac', '0.5']);
-
- assert.equal(report.window.totalSamples, 200);
- assert.equal(report.window.warmupSamplesDropped, 100);
- assert.equal(report.window.analyzedSamples, 100);
-});
-
-test('a looser per-turn budget can accept growth a tight one rejects', () => {
- const samples = buildSamples({ count: 200, rssKib: (i) => 120_000 + i * 400 });
-
- const tight = runAnalyzer(samples, driver(), ['--rss-kib-per-turn', '1']);
- assert.equal(tight.report.memory.find((m) => m.field === 'rssKib').verdict, 'fail');
-
- const loose = runAnalyzer(samples, driver(), ['--rss-kib-per-turn', '100000']);
- assert.equal(loose.report.memory.find((m) => m.field === 'rssKib').verdict, 'pass');
-});
-
-const EPOCH0 = 1_700_000_000_000;
-
-test('an idle tail after load does not mask a leak', () => {
- // The regression this guards: the sampler runs past the end of the load, so
- // the series ends with an idle stretch that is flat and consumes no CPU.
- // Analyzed naively, that tail makes "growth stopped" and "CPU fell" trivially
- // true and EVERY run passes — the shorter the run, the more certain the false
- // clean bill of health. Here memory climbs relentlessly for the whole load and
- // then goes idle; the verdict must still be a leak.
- const LOAD_SAMPLES = 150;
- const samples = buildSamples({
- count: 200,
- rssKib: (i) => 120_000 + Math.min(i, LOAD_SAMPLES) * 400,
- // CPU accrues under load, then stops entirely.
- cpuMs: (i) => Math.min(i, LOAD_SAMPLES) * 100,
- });
- const withWindow = driver({
- measureStartedAtMs: EPOCH0,
- wallMs: LOAD_SAMPLES * INTERVAL_MS,
- });
-
- const { report, exitCode } = runAnalyzer(samples, withWindow);
-
- assert.equal(report.window.clippedToLoadWindow, true, 'must clip to the load window');
- assert.ok(
- report.window.analyzedSamples < 200,
- 'the idle tail must be excluded from the analyzed window',
- );
- const rss = report.memory.find((m) => m.field === 'rssKib');
- const expectedKibPerTurn =
- (400 * (report.window.analyzedSamples - 1)) / report.window.turnsInWindowApprox;
- assert.ok(Math.abs(rss.kibPerTurn - expectedKibPerTurn) < 1e-9);
- assert.equal(rss.verdict, 'fail');
- assert.equal(report.overall, 'fail');
- assert.equal(exitCode, 1);
-});
-
-test('a truncated final sample record is skipped without losing valid samples', () => {
- const valid = buildSamples({ count: 200, rssKib: () => 120_000 });
- const { report, exitCode } = runAnalyzer(`${valid}{"tMs":`, driver());
-
- assert.equal(report.window.totalSamples, 200);
- assert.equal(report.overall, 'pass');
- assert.equal(exitCode, 0);
-});
-
-test('the settle tail is reported separately from the verdict', () => {
- const LOAD_SAMPLES = 150;
- // Memory rises under load and is largely handed back once work stops — the
- // shape of a working set, which is exactly what the settle figures exist to
- // make visible rather than fold into the pass/fail decision.
- const samples = buildSamples({
- count: 200,
- rssKib: (i) =>
- i <= LOAD_SAMPLES ? 120_000 + i * 400 : 120_000 + LOAD_SAMPLES * 400 - (i - LOAD_SAMPLES) * 800,
- cpuMs: (i) => Math.min(i, LOAD_SAMPLES) * 100,
- });
- const { report } = runAnalyzer(
- samples,
- driver({ measureStartedAtMs: EPOCH0, wallMs: LOAD_SAMPLES * INTERVAL_MS }),
- );
-
- assert.equal(report.settle.available, true);
- assert.ok(report.settle.releasedKib > 0, 'should record memory handed back after load');
- assert.ok(report.settle.idleCpuFraction < 0.05, 'idle CPU should be near zero');
-});
-
-test('a short run is flagged as weak evidence even when it passes', () => {
- // 20 samples over 5s. The checks may well pass, but the report must not let a
- // window this small read as a confident clean bill of health.
- const samples = buildSamples({ count: 20, rssKib: () => 120_000 });
- const { report, exitCode } = runAnalyzer(samples, driver());
-
- assert.equal(report.overall, 'pass');
- assert.equal(report.underpowered, true);
- assert.match(report.underpoweredNote, /weak/i);
- assert.equal(exitCode, 0, 'weak evidence is a caveat, not a failure');
-});
-
-test('a long clean run is not flagged as underpowered', () => {
- // 200 samples at 250ms = 50s, comfortably over both thresholds.
- const samples = buildSamples({ count: 200, rssKib: () => 120_000 });
- const { report } = runAnalyzer(samples, driver());
-
- assert.equal(report.underpowered, false);
- assert.equal(report.underpoweredNote, null);
-});
-
-test('clipping is skipped when it would leave too little to analyze', () => {
- // A load window of only a few samples must fall back to the full series
- // rather than exiting, and must say that it did not clip.
- const samples = buildSamples({ count: 200, rssKib: () => 120_000 });
- const { report } = runAnalyzer(
- samples,
- driver({ measureStartedAtMs: EPOCH0, wallMs: 3 * INTERVAL_MS }),
- );
-
- assert.equal(report.window.clippedToLoadWindow, false);
- assert.equal(report.window.loadWindowSamples, 200);
-});
-
-test('a core that stops serving fails, and its resource passes are qualified', () => {
- // The regression this guards: a run where the core died two thirds of the way
- // in reported PASS on every resource check. All of them were true, and all of
- // them were true BECAUSE nothing was happening — flat memory, fallen CPU,
- // stable threads. A dead process looks exactly like a healthy idle one unless
- // liveness is judged on completed work.
- const samples = buildSamples({ count: 200, rssKib: () => 120_000 });
- const turns = buildTurns(50_000, (t) => (t < 33_000 ? 20 : 0));
-
- const { report, exitCode } = runAnalyzer(samples, driver(), [], turns);
-
- assert.equal(report.throughput.verdict, 'fail', report.throughput.reason);
- assert.match(report.throughput.reason, /stopped serving/);
- assert.equal(report.livenessBroken, true);
- assert.match(report.livenessNote, /idle process/);
- assert.equal(report.overall, 'fail');
- assert.equal(exitCode, 1);
-});
-
-test('severe throughput degradation fails even when the core is still alive', () => {
- // Still serving, but at a fraction of its starting rate under constant load.
- const samples = buildSamples({ count: 200, rssKib: () => 120_000 });
- const turns = buildTurns(50_000, (t) => (t < 12_500 ? 40 : 5));
-
- const { report } = runAnalyzer(samples, driver(), [], turns);
-
- assert.equal(report.throughput.verdict, 'fail', report.throughput.reason);
- assert.match(report.throughput.reason, /degrading/);
- assert.ok(report.throughput.retainedFraction < 0.5);
- assert.equal(report.overall, 'fail');
-});
-
-test('steady throughput passes and is not flagged as a liveness break', () => {
- const samples = buildSamples({ count: 200, rssKib: () => 120_000 });
- const turns = buildTurns(50_000, () => 20);
-
- const { report, exitCode } = runAnalyzer(samples, driver(), [], turns);
-
- assert.equal(report.throughput.verdict, 'pass', report.throughput.reason);
- assert.equal(report.livenessBroken, false);
- assert.equal(report.livenessNote, null);
- assert.equal(report.overall, 'pass');
- assert.equal(exitCode, 0);
-});
-
-test('throughput quarters are aligned to the measured epoch window', () => {
- const samples = buildSamples({ count: 200, rssKib: () => 120_000 });
- const measured = driver({ measureStartedAtMs: EPOCH0 });
- const turns = [
- ...Array.from({ length: 25 }, (_, i) => ({
- tMs: 49_000,
- epochMs: EPOCH0 - 5_000 + i,
- ok: true,
- })),
- ...Array.from({ length: 25 }, (_, i) => ({
- tMs: 49_000,
- epochMs: EPOCH0 + 1_000 + i * 400,
- ok: true,
- })),
- ...Array.from({ length: 25 }, (_, i) => ({
- tMs: 1_000,
- epochMs: EPOCH0 + 39_000 + i * 400,
- ok: true,
- })),
- ...Array.from({ length: 25 }, (_, i) => ({
- tMs: 1_000,
- epochMs: EPOCH0 + 55_000 + i,
- ok: true,
- })),
- ];
- const turnsText = `${turns.map(turn => JSON.stringify(turn)).join('\n')}\n`;
-
- const { report } = runAnalyzer(samples, measured, [], turnsText);
-
- assert.equal(report.throughput.firstQuarterTurnsPerSec, 2);
- assert.equal(report.throughput.lastQuarterTurnsPerSec, 2);
- assert.equal(report.throughput.verdict, 'pass');
-});
-
-test('throughput is simply unavailable when no turn log is supplied', () => {
- const samples = buildSamples({ count: 200, rssKib: () => 120_000 });
- const { report, exitCode } = runAnalyzer(samples, driver());
-
- assert.equal(report.throughput.available, false);
- assert.equal(report.livenessBroken, false);
- assert.equal(exitCode, 0, 'a missing turn log is not a failure');
-});
-
-test('degradation short of an outage is not called a liveness break', () => {
- // The core kept serving, just more slowly. Throughput must fail, but the
- // resource verdicts stay meaningful — so the "this describes an idle process"
- // qualifier must NOT appear, because the process plainly was not idle.
- const samples = buildSamples({ count: 200, rssKib: () => 120_000 });
- const turns = buildTurns(50_000, (t) => (t < 12_500 ? 40 : 5));
-
- const { report } = runAnalyzer(samples, driver(), [], turns);
-
- assert.equal(report.throughput.verdict, 'fail');
- assert.equal(report.throughput.stopped, false);
- assert.equal(report.livenessBroken, false, 'degradation is not an outage');
- assert.equal(report.livenessNote, null);
-});
-
-test('a leaking RSS curve is marked confounded when the workspace grew a lot', () => {
- // `fresh` mode stops conversation history accumulating, but the agent still
- // persists memory chunks every turn. RSS tracking an index over data that
- // genuinely grew is not a leak, and the report must not claim otherwise.
- const samples = buildSamples({ count: 200, rssKib: (i) => 120_000 + i * 400 });
- const { report } = runAnalyzer(samples, driver(), [
- '--workspace-mib-before', '10',
- '--workspace-mib-after', '4000',
- ]);
-
- const rss = report.memory.find((m) => m.field === 'rssKib');
- assert.equal(rss.verdict, 'fail', 'still a failure — the caveat does not excuse it');
- assert.equal(rss.confounded, true);
- assert.match(rss.confoundNote, /rather than a leak/);
- assert.equal(report.workspace.growthMib, 3990);
-});
-
-test('a leaking RSS curve is NOT confounded when the workspace barely grew', () => {
- // Same leak, but nothing accumulated on disk to explain it. This is the
- // unambiguous case, and it must read as such.
- const samples = buildSamples({ count: 200, rssKib: (i) => 120_000 + i * 400 });
- const { report } = runAnalyzer(samples, driver(), [
- '--workspace-mib-before', '10',
- '--workspace-mib-after', '12',
- ]);
-
- const rss = report.memory.find((m) => m.field === 'rssKib');
- assert.equal(rss.verdict, 'fail');
- assert.notEqual(rss.confounded, true);
- assert.equal(report.workspace.growthMib, 2);
-});
-
-test('a series too short to analyze exits non-zero rather than guessing', () => {
- const samples = buildSamples({ count: 4, rssKib: () => 120_000 });
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bench-analyze-'));
- try {
- const samplesPath = path.join(dir, 'samples.jsonl');
- fs.writeFileSync(samplesPath, samples);
- let exitCode = 0;
- try {
- execFileSync(process.execPath, [ANALYZE, '--samples', samplesPath], {
- encoding: 'utf8',
- stdio: 'pipe',
- });
- } catch (err) {
- exitCode = err.status ?? 1;
- }
- assert.notEqual(exitCode, 0);
- } finally {
- fs.rmSync(dir, { recursive: true, force: true });
- }
-});
diff --git a/scripts/bench/driver.mjs b/scripts/bench/driver.mjs
deleted file mode 100755
index 662aab97a0..0000000000
--- a/scripts/bench/driver.mjs
+++ /dev/null
@@ -1,358 +0,0 @@
-#!/usr/bin/env node
-/**
- * Load driver for the agent-scale benchmark tier.
- *
- * Fires `openhuman.agent_chat` turns at a running core over /rpc at a fixed
- * concurrency and records per-turn latency and outcome. Writes a JSON summary
- * to --out and, with --turns-out, a JSONL turn log the analyzer correlates
- * against the resource samples.
- *
- * Thread mode is the knob that decides WHICH kind of scale is under test, and
- * the two answer different questions:
- *
- * fresh every turn opens a new thread. Models many short, independent
- * sessions. This is the one that catches per-session state that
- * is allocated and never reclaimed, because nothing legitimately
- * accumulates across turns.
- * per-worker each worker keeps one thread for the whole run. Models long
- * conversations. Here RSS growth is EXPECTED — conversation
- * history genuinely grows — so a rising line is not by itself a
- * leak, and the analyzer says so.
- * shared all workers share a single thread. Contention-focused; the
- * same caveat about expected growth applies.
- *
- * Usage:
- * node scripts/bench/driver.mjs --core-url http://127.0.0.1:17788 \
- * --concurrency 8 --turns 400 --out summary.json --turns-out turns.jsonl
- */
-
-import fs from "node:fs";
-
-/** Loopback hosts are the only targets that may use cleartext http (CWE-319). */
-function isLoopbackHost(hostname) {
- return (
- hostname === "localhost" ||
- hostname === "127.0.0.1" ||
- hostname === "::1" ||
- hostname === "[::1]"
- );
-}
-
-function assertTransportAllowed(url, what) {
- const parsed = new URL(url);
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
- throw new Error(`${what} must be an http(s) URL, got: ${url}`);
- }
- if (parsed.protocol === "http:" && !isLoopbackHost(parsed.hostname)) {
- throw new Error(
- `${what} uses cleartext http for non-loopback host "${parsed.hostname}"; use https or a loopback address`,
- );
- }
- return parsed;
-}
-
-function parseArgs(argv) {
- const opts = {
- coreUrl: "http://127.0.0.1:17788",
- token: process.env.OPENHUMAN_CORE_TOKEN ?? "",
- concurrency: 4,
- turns: 100,
- durationMs: null,
- threadMode: "fresh",
- message: "Summarize the benchmark probe in one sentence.",
- timeoutMs: 120_000,
- out: null,
- turnsOut: null,
- seedSession: true,
- warmupTurns: 0,
- };
- const spec = {
- "--core-url": ["coreUrl", String],
- "--token": ["token", String],
- "--concurrency": ["concurrency", Number],
- "--turns": ["turns", Number],
- "--duration-ms": ["durationMs", Number],
- "--thread-mode": ["threadMode", String],
- "--message": ["message", String],
- "--timeout-ms": ["timeoutMs", Number],
- "--out": ["out", String],
- "--turns-out": ["turnsOut", String],
- "--warmup-turns": ["warmupTurns", Number],
- };
- for (let i = 2; i < argv.length; i += 1) {
- if (argv[i] === "--no-seed-session") {
- opts.seedSession = false;
- continue;
- }
- const entry = spec[argv[i]];
- if (!entry) throw new Error(`unknown argument: ${argv[i]}`);
- const [key, cast] = entry;
- const raw = argv[++i];
- if (raw === undefined) {
- throw new Error(`${argv[i - 1]} expects a value, got nothing`);
- }
- const value = cast(raw);
- if (cast === Number && !Number.isFinite(value)) {
- throw new Error(`${argv[i - 1]} expects a number, got: ${raw}`);
- }
- opts[key] = value;
- }
- if (!["fresh", "shared", "per-worker"].includes(opts.threadMode)) {
- throw new Error(
- `--thread-mode must be fresh|shared|per-worker, got ${opts.threadMode}`,
- );
- }
- if (opts.concurrency < 1) throw new Error("--concurrency must be >= 1");
- if (opts.durationMs === null && opts.turns < 1) {
- throw new Error("need --turns >= 1 or --duration-ms");
- }
- return opts;
-}
-
-const opts = parseArgs(process.argv);
-// Reject non-loopback cleartext targets before any bearer token is attached.
-assertTransportAllowed(opts.coreUrl, "--core-url");
-
-async function rpc(method, params, timeoutMs = opts.timeoutMs) {
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), timeoutMs);
- try {
- const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method, params });
- let url = `${opts.coreUrl}/rpc`;
- // The bearer belongs to the core we were pointed at. A redirect may land on
- // a different origin, so it is re-attached per hop rather than once up
- // front -- otherwise following one would hand the token to whoever the
- // Location header names.
- const coreOrigin = new URL(opts.coreUrl).origin;
- let res;
- for (let hop = 0; ; hop += 1) {
- if (hop >= 5) throw new Error("too many redirects");
- const headers = { "content-type": "application/json" };
- if (opts.token && new URL(url).origin === coreOrigin) {
- headers.authorization = `Bearer ${opts.token}`;
- }
- res = await fetch(url, {
- method: "POST",
- headers,
- body,
- redirect: "manual",
- signal: controller.signal,
- });
- if (res.status < 300 || res.status >= 400) break;
- const location = res.headers.get("location");
- if (!location)
- throw new Error(`HTTP ${res.status} redirect without Location`);
- url = assertTransportAllowed(
- new URL(location, url).href,
- "redirect target",
- ).href;
- }
- const text = await res.text();
- if (!res.ok) {
- throw new Error(`HTTP ${res.status}: ${text.slice(0, 400)}`);
- }
- let parsed;
- try {
- parsed = JSON.parse(text);
- } catch {
- throw new Error(`non-JSON response: ${text.slice(0, 400)}`);
- }
- if (parsed.error) {
- const { code, message } = parsed.error;
- throw new Error(`rpc error ${code}: ${message}`);
- }
- return parsed.result;
- } finally {
- clearTimeout(timer);
- }
-}
-
-/**
- * Install a local session so the managed-inference path can resolve a bearer.
- *
- * A token shaped `<a>.<b>.local` is recognized as a local session and is
- * persisted WITHOUT the `GET /auth/me` round-trip a remote JWT would trigger
- * (see is_local_session_token in crates/openhuman-core/src/security/credentials/). That is
- * what lets the benchmark skip a real login and keeps the mock's surface to the
- * inference and telemetry routes.
- */
-async function seedSession() {
- await rpc("openhuman.auth_store_session", {
- token: "bench.session.local",
- user: { name: "agent-scale-bench", email: "bench@localhost" },
- });
-}
-
-function percentile(sorted, p) {
- if (sorted.length === 0) return null;
- const idx = Math.min(
- sorted.length - 1,
- Math.max(0, Math.ceil((p / 100) * sorted.length) - 1),
- );
- return sorted[idx];
-}
-
-const turnLog = opts.turnsOut
- ? fs.createWriteStream(opts.turnsOut, { flags: "w" })
- : null;
-
-const results = { ok: 0, failed: 0, latencies: [], errors: new Map() };
-let issued = 0;
-let loadStart = Date.now();
-
-function shouldContinue() {
- if (opts.durationMs !== null) return Date.now() - loadStart < opts.durationMs;
- return issued < opts.turns;
-}
-
-async function runTurn(workerId, threadId, index) {
- const params = { message: `${opts.message} (turn ${index})` };
- if (threadId) params.thread_id = threadId;
-
- const t0 = performance.now();
- let ok = true;
- let errMessage = null;
- try {
- await rpc("openhuman.agent_chat", params);
- } catch (err) {
- ok = false;
- errMessage = String(err?.message ?? err);
- }
- const latencyMs = performance.now() - t0;
-
- if (ok) {
- results.ok += 1;
- results.latencies.push(latencyMs);
- } else {
- results.failed += 1;
- // Bucket by message so a summary shows the distinct failure modes rather
- // than one line per failed turn.
- const key = errMessage.slice(0, 200);
- results.errors.set(key, (results.errors.get(key) ?? 0) + 1);
- }
-
- if (turnLog) {
- const completedAt = Date.now();
- turnLog.write(
- `${JSON.stringify({
- tMs: completedAt - loadStart,
- epochMs: completedAt,
- workerId,
- index,
- latencyMs,
- ok,
- error: errMessage,
- })}\n`,
- );
- }
-}
-
-async function worker(workerId) {
- const threadId =
- opts.threadMode === "per-worker"
- ? `bench-worker-${workerId}`
- : opts.threadMode === "shared"
- ? "bench-shared"
- : null;
-
- while (shouldContinue()) {
- const index = issued++;
- await runTurn(workerId, threadId, index);
- }
-}
-
-async function main() {
- if (opts.seedSession) {
- process.stderr.write("[driver] seeding local session\n");
- await seedSession();
- }
-
- if (opts.warmupTurns > 0) {
- // Warm-up turns fault in lazily-initialized state (model client, stores,
- // tool registry). Measuring them as steady state would show growth that is
- // first-touch initialization, not a leak.
- process.stderr.write(`[driver] warmup: ${opts.warmupTurns} turns\n`);
- for (let i = 0; i < opts.warmupTurns; i += 1) {
- try {
- await rpc("openhuman.agent_chat", {
- message: `${opts.message} (warmup ${i})`,
- });
- } catch (err) {
- process.stderr.write(
- `[driver] warmup turn failed: ${err?.message ?? err}\n`,
- );
- }
- }
- // The warm-up must not appear in the measured window.
- results.ok = 0;
- results.failed = 0;
- results.latencies.length = 0;
- results.errors.clear();
- issued = 0;
- }
-
- // The load window starts after seeding and warm-up, so setup time is not
- // counted against --duration-ms and the turn log is measured from the same
- // instant.
- loadStart = Date.now();
- const measureStart = loadStart;
- process.stderr.write(
- `[driver] load: concurrency=${opts.concurrency} ` +
- `${opts.durationMs !== null ? `duration=${opts.durationMs}ms` : `turns=${opts.turns}`} ` +
- `thread-mode=${opts.threadMode}\n`,
- );
- await Promise.all(
- Array.from({ length: opts.concurrency }, (_, i) => worker(i)),
- );
- const wallMs = Date.now() - measureStart;
-
- const sorted = [...results.latencies].sort((a, b) => a - b);
- const completed = results.ok + results.failed;
- const summary = {
- config: {
- coreUrl: opts.coreUrl,
- concurrency: opts.concurrency,
- turns: opts.turns,
- durationMs: opts.durationMs,
- threadMode: opts.threadMode,
- warmupTurns: opts.warmupTurns,
- },
- measureStartedAtMs: measureStart,
- wallMs,
- turnsCompleted: completed,
- turnsOk: results.ok,
- turnsFailed: results.failed,
- throughputTurnsPerSec: wallMs > 0 ? (completed / wallMs) * 1000 : null,
- latencyMs: {
- min: sorted.length ? sorted[0] : null,
- p50: percentile(sorted, 50),
- p90: percentile(sorted, 90),
- p99: percentile(sorted, 99),
- max: sorted.length ? sorted[sorted.length - 1] : null,
- mean: sorted.length
- ? sorted.reduce((a, b) => a + b, 0) / sorted.length
- : null,
- },
- errors: Object.fromEntries(results.errors),
- };
-
- if (turnLog) await new Promise((resolve) => turnLog.end(resolve));
- const rendered = JSON.stringify(summary, null, 2);
- if (opts.out) fs.writeFileSync(opts.out, rendered);
- process.stdout.write(`${rendered}\n`);
-
- // A run with no completed turn, or one where every turn failed, produced no
- // usable measurement. Exit non-zero so a caller cannot mistake it for a clean
- // result.
- if (completed === 0 || results.ok === 0) {
- process.stderr.write(
- `[driver] no usable measurement (completed=${completed}, ok=${results.ok})\n`,
- );
- process.exit(1);
- }
-}
-
-main().catch((err) => {
- process.stderr.write(`[driver] fatal: ${err?.stack ?? err}\n`);
- process.exit(1);
-});
diff --git a/scripts/bench/mock-llm.mjs b/scripts/bench/mock-llm.mjs
deleted file mode 100755
index 3697f044e9..0000000000
--- a/scripts/bench/mock-llm.mjs
+++ /dev/null
@@ -1,503 +0,0 @@
-#!/usr/bin/env node
-/**
- * Mock LLM + backend endpoint for the agent-scale benchmark tier.
- *
- * This stands in for `api.tinyhumans.ai` so a NORMALLY-BUILT `openhuman-core`
- * can run real agent turns with no network and no special cargo features. The
- * core reaches it because `config.api_url` (or `BACKEND_URL`) feeds both
- * `effective_api_url` (inference, embeddings) and `effective_backend_api_url`
- * (telemetry), so one base URL captures every backend call a turn makes:
- *
- * POST /openai/v1/chat/completions the turn itself (non-streaming)
- * POST /openai/v1/embeddings memory recall/write, when it fires
- * POST /telemetry/langfuse/ingestion after every turn, unless disabled
- *
- * Two properties matter for a benchmark and are worth stating, because both
- * are easy to lose in a later edit:
- *
- * 1. REPLIES ARE DERIVED FROM THE REQUEST, NOT FROM STORED STATE. How deep a
- * turn is comes from counting `role: "tool"` messages in the body that
- * arrived. There is no session map, so N concurrent turns cannot interleave
- * into each other's scripts and the mock holds nothing that grows with load.
- * The only mutable state is a handful of integer counters.
- *
- * 2. THAT IS ALSO WHAT KEEPS THE MOCK OUT OF THE MEASUREMENT. We are trying to
- * attribute RSS growth to the core. A mock that retained a request log would
- * grow too, and (being a separate process) would not show up in the core's
- * numbers — but it would eventually change the machine's memory pressure and
- * contaminate the run. Do not add request retention here; if you need to
- * inspect traffic, add a counter or log to stderr.
- *
- * Usage:
- * node scripts/bench/mock-llm.mjs --port 18700 [options]
- *
- * Options:
- * --port <n> listen port. MUST NOT be one of 11434/8000/8080/1234/8888:
- * the core classifies those as local-AI endpoints and
- * routes around them (see LOCAL_AI_PORTS in crates/openhuman-tinyhumans/src/backend/url.rs).
- * --latency-ms <n> mean added latency per completion (default 0)
- * --jitter-ms <n> deterministic +/- jitter around that mean (default 0)
- * --tool-depth <n> tool calls to emit before the final answer (default 0)
- * --reply-chars <n> assistant reply size, to vary serde/alloc pressure (default 240)
- * --fail-rate <n> fraction [0,1) of completions answered 500, to exercise
- * the core's retry/error path (default 0)
- * --embed-dims <n> embedding width (default 1024). MUST match what the
- * memory store expects — a mismatch is only a warning,
- * and the run silently stores chunks without vectors.
- */
-
-import http from 'node:http';
-
-const LOCAL_AI_PORTS = new Set([11434, 8000, 8080, 1234, 8888]);
-
-// Tools we are willing to drive, most preferred first. Both are read-only and
-// cheap, so a deep tool loop stresses the harness rather than the filesystem.
-// The mock only ever names a tool the core actually offered in the request, so
-// an unknown name here is inert rather than an error.
-const TOOL_PREFERENCE = ['memory_search', 'glob'];
-
-/**
- * Background routes the core polls that are not part of a turn.
- *
- * Left un-stubbed these 404, and the core handles that gracefully — but not
- * freely: `/teams/me/usage` routes its 404 through the observability
- * error-reporting path, and the rest log warnings. That is CPU and allocation
- * spent on failure handling rather than on agent work, in a run whose entire
- * purpose is to attribute CPU and allocation. Answering them with empty,
- * well-shaped payloads keeps the process on its normal path.
- *
- * These are counted separately from `unknownRoutes` so the distinction between
- * "deliberately stubbed" and "we did not anticipate this" stays visible.
- */
-const ANCILLARY_ROUTES = {
- 'GET /teams/me/usage': () => ({
- success: true,
- data: { credits: 1_000_000, used: 0, plan: 'bench' },
- }),
- 'GET /agent-integrations/composio/connections': () => ({ success: true, data: [] }),
- 'GET /agent-integrations/composio/toolkits': () => ({ success: true, data: [] }),
- 'GET /orchestration/v1/sessions': () => ({ success: true, data: [] }),
-};
-
-function parseArgs(argv) {
- const opts = {
- port: 18700,
- latencyMs: 0,
- jitterMs: 0,
- toolDepth: 0,
- replyChars: 240,
- failRate: 0,
- embedDims: 1024,
- };
- const numeric = {
- '--port': 'port',
- '--latency-ms': 'latencyMs',
- '--jitter-ms': 'jitterMs',
- '--tool-depth': 'toolDepth',
- '--reply-chars': 'replyChars',
- '--fail-rate': 'failRate',
- '--embed-dims': 'embedDims',
- };
- for (let i = 2; i < argv.length; i += 1) {
- const key = numeric[argv[i]];
- if (!key) throw new Error(`unknown argument: ${argv[i]}`);
- const raw = argv[i + 1];
- i += 1;
- const value = Number(raw);
- if (!Number.isFinite(value)) {
- throw new Error(`${argv[i - 1]} expects a number, got: ${raw}`);
- }
- opts[key] = value;
- }
- if (LOCAL_AI_PORTS.has(opts.port)) {
- throw new Error(
- `--port ${opts.port} is in the transport's LOCAL_AI_PORTS set; the core would ` +
- `treat this as a local-AI endpoint and not route managed inference here. ` +
- `Pick another port.`,
- );
- }
- if (opts.failRate < 0 || opts.failRate >= 1) {
- throw new Error(`--fail-rate must be in [0, 1), got ${opts.failRate}`);
- }
- return opts;
-}
-
-/**
- * Deterministic hash of a string, so latency and failure injection are
- * reproducible across runs without a shared RNG (which would be both a lock
- * and a source of cross-request coupling).
- */
-function hash32(str) {
- let h = 0x811c9dc5;
- for (let i = 0; i < str.length; i += 1) {
- h ^= str.charCodeAt(i);
- h = Math.imul(h, 0x01000193) >>> 0;
- }
- return h >>> 0;
-}
-
-/** Stable [0,1) from a seed. */
-function unitFrom(seed) {
- return (hash32(String(seed)) % 1_000_000) / 1_000_000;
-}
-
-// Retry counters are keyed by request content. Distinct concurrent turns cannot
-// perturb one another, while a retry of the same request still gets a new draw.
-const attemptsByRequest = new Map();
-const MAX_TRACKED_REQUESTS = 4096;
-
-/** Return the next attempt for a request while bounding benchmark-side state. */
-function nextRequestAttempt(requestKey) {
- const attempt = (attemptsByRequest.get(requestKey) ?? 0) + 1;
- // Refresh insertion order so active retrying requests are evicted last.
- attemptsByRequest.delete(requestKey);
- attemptsByRequest.set(requestKey, attempt);
- if (attemptsByRequest.size > MAX_TRACKED_REQUESTS) {
- // Eviction intentionally permits a very old request to restart at attempt
- // 1. Core retries are immediate, so their refreshed keys remain resident;
- // preserving every completed request across an unbounded duration run
- // would make the mock itself accumulate benchmark-distorting state.
- attemptsByRequest.delete(attemptsByRequest.keys().next().value);
- }
- return attempt;
-}
-
-const stats = {
- startedAt: Date.now(),
- completions: 0,
- toolCallsEmitted: 0,
- finalAnswers: 0,
- embeddings: 0,
- telemetry: 0,
- ancillary: 0,
- injectedFailures: 0,
- unknownRoutes: 0,
- malformedRequests: 0,
-};
-
-function readBody(req) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- let size = 0;
- req.on('data', (chunk) => {
- size += chunk.length;
- // A runaway body would make the mock the memory problem. Cap it.
- if (size > 64 * 1024 * 1024) {
- reject(new Error('request body exceeded 64 MiB'));
- req.destroy();
- return;
- }
- chunks.push(chunk);
- });
- req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
- req.on('error', reject);
- });
-}
-
-function sendJson(res, status, payload) {
- const body = JSON.stringify(payload);
- res.writeHead(status, {
- 'content-type': 'application/json',
- 'content-length': Buffer.byteLength(body),
- });
- res.end(body);
-}
-
-const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
-
-/**
- * Pick a tool to call from the ones the core offered. Returns null when the
- * request carried no tools, which is the correct cue to answer in plain text
- * rather than inventing a call the agent cannot dispatch.
- */
-function pickTool(tools) {
- if (!Array.isArray(tools) || tools.length === 0) return null;
- const names = new Set(
- tools.map((t) => t?.function?.name).filter((n) => typeof n === 'string'),
- );
- for (const preferred of TOOL_PREFERENCE) {
- if (names.has(preferred)) return preferred;
- }
- return null;
-}
-
-/** Arguments that are valid for the tools we are willing to drive. */
-function argumentsFor(toolName) {
- switch (toolName) {
- case 'memory_search':
- return { query: 'benchmark probe' };
- case 'glob':
- return { pattern: '*.md' };
- default:
- return {};
- }
-}
-
-// A small vocabulary the reply builder samples from. Replies get stored as
-// memories, so if every reply were the same string the whole corpus would
-// collapse to one distinct document — fine for throughput, useless for asking
-// which memories a retrieval change surfaces.
-const VOCAB = [
- 'invoice', 'deployment', 'kubernetes', 'roadmap', 'latency', 'onboarding',
- 'refund', 'schema', 'migration', 'webhook', 'billing', 'timezone',
- 'passport', 'itinerary', 'recipe', 'mortgage', 'vaccination', 'landlord',
- 'guitar', 'marathon', 'thesis', 'compiler', 'telescope', 'sourdough',
-];
-
-/**
- * Deterministic, varied reply text of approximately `chars` length.
- *
- * `seed` makes it reproducible per turn while still differing between turns.
- */
-function buildReplyText(chars, seed) {
- let state = hash32(String(seed)) || 1;
- const next = () => {
- state ^= state << 13;
- state >>>= 0;
- state ^= state >> 17;
- state ^= state << 5;
- state >>>= 0;
- return state;
- };
- const words = [];
- let len = 0;
- while (len < chars) {
- const w = VOCAB[next() % VOCAB.length];
- words.push(w);
- len += w.length + 1;
- }
- return words.join(' ').slice(0, chars);
-}
-
-async function handleCompletion(req, res, body, opts) {
- let parsed;
- try {
- parsed = JSON.parse(body);
- } catch {
- stats.malformedRequests += 1;
- sendJson(res, 400, { error: { message: 'invalid JSON body' } });
- return;
- }
-
- const messages = Array.isArray(parsed.messages) ? parsed.messages : [];
- // Turn depth without stored state: every tool result already in the thread is
- // one tool call we previously emitted.
- const depth = messages.filter((m) => m?.role === 'tool').length;
-
- // Seed from stable request content so concurrent arrival order cannot change
- // which requests fail or how much latency they receive. Keep a per-content
- // attempt number so retries do not repeat the same injected failure forever.
- const requestKey = String(hash32(body));
- const attempt = nextRequestAttempt(requestKey);
- const seed = `${requestKey}:${attempt}`;
-
- if (opts.failRate > 0 && unitFrom(`fail:${seed}`) < opts.failRate) {
- stats.injectedFailures += 1;
- sendJson(res, 500, { error: { message: 'injected benchmark failure' } });
- return;
- }
-
- if (opts.latencyMs > 0 || opts.jitterMs > 0) {
- const offset = opts.jitterMs > 0 ? (unitFrom(`lat:${seed}`) * 2 - 1) * opts.jitterMs : 0;
- await sleep(Math.max(0, opts.latencyMs + offset));
- }
-
- stats.completions += 1;
- const model = typeof parsed.model === 'string' ? parsed.model : 'mock-model';
- const toolName = depth < opts.toolDepth ? pickTool(parsed.tools) : null;
-
- let message;
- let finishReason;
- if (toolName) {
- stats.toolCallsEmitted += 1;
- message = {
- role: 'assistant',
- content: null,
- tool_calls: [
- {
- id: `call_bench_${stats.completions}`,
- type: 'function',
- function: {
- name: toolName,
- // The core expects arguments as a JSON *string*.
- arguments: JSON.stringify(argumentsFor(toolName)),
- },
- },
- ],
- };
- finishReason = 'tool_calls';
- } else {
- stats.finalAnswers += 1;
- message = {
- role: 'assistant',
- content: buildReplyText(opts.replyChars, `${seed}:${stats.completions}`),
- };
- finishReason = 'stop';
- }
-
- // Rough but stable token accounting; the core records usage but does not
- // validate it against the text.
- const promptTokens = Math.max(1, Math.ceil(body.length / 4));
- const completionTokens = Math.max(1, Math.ceil(opts.replyChars / 4));
-
- sendJson(res, 200, {
- id: `chatcmpl-bench-${stats.completions}`,
- object: 'chat.completion',
- created: Math.floor(Date.now() / 1000),
- model,
- choices: [{ index: 0, message, finish_reason: finishReason }],
- usage: {
- prompt_tokens: promptTokens,
- completion_tokens: completionTokens,
- total_tokens: promptTokens + completionTokens,
- },
- });
-}
-
-/**
- * A deterministic pseudo-embedding derived from the input text.
- *
- * Returning one constant vector for every input would be simpler and is what
- * this did first — but it makes every cosine similarity identical, so retrieval
- * ranking becomes degenerate and any experiment about WHICH memories a change
- * surfaces is meaningless. Throughput measurements are unaffected either way
- * (the same work happens whatever the values are), so the flaw is invisible
- * unless you go looking for it.
- *
- * This derives a unit vector from a hash of the text: same text always yields
- * the same vector, similar-but-different texts yield different ones, and the
- * distribution is spread rather than collapsed onto a point. Not semantically
- * meaningful — nothing here models real language — but structurally realistic
- * enough to compare retrieval strategies against each other.
- */
-function embeddingFor(text, dims) {
- // xorshift32 seeded by the content hash: cheap, deterministic, no shared state.
- let state = hash32(text) || 1;
- const next = () => {
- state ^= state << 13;
- state >>>= 0;
- state ^= state >> 17;
- state ^= state << 5;
- state >>>= 0;
- return state / 0xffffffff;
- };
- const vec = new Array(dims);
- let norm = 0;
- for (let i = 0; i < dims; i += 1) {
- // Box-Muller-ish spread around zero, so vectors are not all in one orthant.
- const v = next() * 2 - 1;
- vec[i] = v;
- norm += v * v;
- }
- norm = Math.sqrt(norm) || 1;
- for (let i = 0; i < dims; i += 1) vec[i] /= norm;
- return vec;
-}
-
-function handleEmbeddings(res, body, opts) {
- stats.embeddings += 1;
- let count = 1;
- let inputs = [''];
- try {
- const parsed = JSON.parse(body);
- if (Array.isArray(parsed.input)) {
- inputs = parsed.input.map((v) => (typeof v === 'string' ? v : JSON.stringify(v)));
- count = Math.max(1, inputs.length);
- } else if (typeof parsed.input === 'string') {
- inputs = [parsed.input];
- }
- } catch {
- stats.malformedRequests += 1;
- }
- // The dimension MUST match what the memory store expects, or every chunk is
- // stored without vectors and the memory write path runs degraded for the whole
- // run — silently, as a warning rather than an error. 1536 (the usual
- // text-embedding-3-small width) is the wrong default here; the store wants
- // 1024.
- sendJson(res, 200, {
- object: 'list',
- model: 'mock-embedding',
- data: Array.from({ length: count }, (_, i) => ({
- object: 'embedding',
- index: i,
- embedding: embeddingFor(inputs[i] ?? '', opts.embedDims),
- })),
- usage: { prompt_tokens: count, total_tokens: count },
- });
-}
-
-const opts = parseArgs(process.argv);
-
-const server = http.createServer((req, res) => {
- const url = new URL(req.url, `http://127.0.0.1:${opts.port}`);
- const path = url.pathname;
-
- if (req.method === 'GET' && (path === '/health' || path === '/__bench/health')) {
- sendJson(res, 200, { ok: true });
- return;
- }
- if (req.method === 'GET' && path === '/__bench/stats') {
- sendJson(res, 200, { ...stats, uptimeMs: Date.now() - stats.startedAt });
- return;
- }
- if (req.method === 'POST' && path === '/__bench/reset') {
- for (const key of Object.keys(stats)) {
- if (key !== 'startedAt') stats[key] = 0;
- }
- sendJson(res, 200, { ok: true });
- return;
- }
-
- readBody(req)
- .then(async (body) => {
- if (req.method === 'POST' && path.endsWith('/chat/completions')) {
- await handleCompletion(req, res, body, opts);
- return;
- }
- if (req.method === 'POST' && path.endsWith('/embeddings')) {
- handleEmbeddings(res, body, opts);
- return;
- }
- if (req.method === 'POST' && path.includes('/telemetry/')) {
- stats.telemetry += 1;
- sendJson(res, 200, {});
- return;
- }
- const stub = ANCILLARY_ROUTES[`${req.method} ${path}`];
- if (stub) {
- stats.ancillary += 1;
- sendJson(res, 200, stub());
- return;
- }
- // Anything else is a route the core reached for that we did not
- // anticipate. Count it loudly — a rising number here means the benchmark
- // is silently exercising a degraded path.
- stats.unknownRoutes += 1;
- process.stderr.write(`[mock-llm] unhandled ${req.method} ${path}\n`);
- sendJson(res, 404, { error: { message: `unhandled route: ${path}` } });
- })
- .catch((err) => {
- stats.malformedRequests += 1;
- if (!res.headersSent) {
- sendJson(res, 400, { error: { message: String(err?.message ?? err) } });
- }
- });
-});
-
-// Long agent runs hold connections open; do not let Node time them out mid-turn.
-server.keepAliveTimeout = 120_000;
-server.headersTimeout = 125_000;
-
-server.listen(opts.port, '127.0.0.1', () => {
- process.stderr.write(
- `[mock-llm] listening on http://127.0.0.1:${opts.port} ` +
- `(latency=${opts.latencyMs}±${opts.jitterMs}ms tool-depth=${opts.toolDepth} ` +
- `reply-chars=${opts.replyChars} fail-rate=${opts.failRate})\n`,
- );
-});
-
-for (const signal of ['SIGINT', 'SIGTERM']) {
- process.on(signal, () => {
- server.close(() => process.exit(0));
- });
-}
diff --git a/scripts/bench/run-agent-scale.sh b/scripts/bench/run-agent-scale.sh
deleted file mode 100755
index 796b37b5af..0000000000
--- a/scripts/bench/run-agent-scale.sh
+++ /dev/null
@@ -1,489 +0,0 @@
-#!/usr/bin/env bash
-#
-# Agent-scale benchmark: drive a real openhuman-core process at concurrency
-# against a mocked LLM, sample its CPU/RSS, and report a leak verdict.
-#
-# This is the OUT-OF-PROCESS tier. It complements scripts/profile/, which
-# embeds the core as a library and measures the current process. Here the core
-# is a normally-built server binary reached over /rpc, so the numbers include
-# the transport, serde and scheduler costs a library benchmark cannot see, and
-# RSS is what the OS actually charges the shipped binary.
-#
-# It needs NO cargo test features and NO core code changes. Two facts make that
-# work, and both are load-bearing:
-#
-# * BACKEND_URL redirects managed inference. The core derives its inference
-# base and its backend base from the same value, so pointing it at the mock
-# captures chat completions, embeddings and telemetry in one move.
-# * A session token shaped `<a>.<b>.local` is stored WITHOUT the GET /auth/me
-# round-trip a remote JWT triggers, so no login and no auth mock is needed.
-# The driver seeds it before the load starts.
-#
-# Usage:
-# scripts/bench/run-agent-scale.sh [options]
-#
-# --concurrency N parallel in-flight turns (default 8)
-# --turns N total turns in the measured window (default 300)
-# --duration-ms N run for a wall-clock duration instead of a turn count
-# --warmup-turns N turns to run and discard before measuring (default 10)
-# --tool-depth N tool calls the mock drives per turn (default 1)
-# --latency-ms N mock inference latency (default 40)
-# --jitter-ms N jitter around that latency (default 20)
-# --reply-chars N assistant reply size (default 240)
-# --fail-rate F fraction of completions answered 500 (default 0)
-# --thread-mode M fresh | per-worker | shared (default fresh)
-# --interval-ms N resource sampling interval (default 250)
-# --tree also sample descendant processes
-# --keep-workspace do not delete the temp workspace on exit
-# --workspace DIR reuse an existing populated workspace (implies --keep-workspace)
-# --memory-off disable memory reads and writes (recall + learning)
-# --memory-writes-off disable only memory writes, keep recall reads (mutually
-# exclusive with --memory-off)
-# --out-dir DIR where to write artifacts (default target/bench/<stamp>)
-#
-# Exit status is the analyzer's: non-zero when a leak or drift check fails.
-
-set -euo pipefail
-
-REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
-cd "$REPO_ROOT"
-
-CONCURRENCY=8
-TURNS=300
-DURATION_MS=""
-WARMUP_TURNS=10
-TOOL_DEPTH=1
-LATENCY_MS=40
-JITTER_MS=20
-REPLY_CHARS=240
-FAIL_RATE=0
-THREAD_MODE=fresh
-INTERVAL_MS=250
-TREE=""
-KEEP_WORKSPACE=""
-REUSE_WORKSPACE=""
-MEMORY_OFF=""
-MEMORY_WRITES_OFF=""
-OUT_DIR=""
-
-while [[ $# -gt 0 ]]; do
- case "$1" in
- --concurrency) CONCURRENCY="$2"; shift 2 ;;
- --turns) TURNS="$2"; shift 2 ;;
- --duration-ms) DURATION_MS="$2"; shift 2 ;;
- --warmup-turns) WARMUP_TURNS="$2"; shift 2 ;;
- --tool-depth) TOOL_DEPTH="$2"; shift 2 ;;
- --latency-ms) LATENCY_MS="$2"; shift 2 ;;
- --jitter-ms) JITTER_MS="$2"; shift 2 ;;
- --reply-chars) REPLY_CHARS="$2"; shift 2 ;;
- --fail-rate) FAIL_RATE="$2"; shift 2 ;;
- --thread-mode) THREAD_MODE="$2"; shift 2 ;;
- --interval-ms) INTERVAL_MS="$2"; shift 2 ;;
- --tree) TREE="--tree"; shift ;;
- --memory-off) MEMORY_OFF=1; shift ;;
- --memory-writes-off) MEMORY_WRITES_OFF=1; shift ;;
- --keep-workspace) KEEP_WORKSPACE=1; shift ;;
- --workspace) REUSE_WORKSPACE="$2"; shift 2 ;;
- --out-dir) OUT_DIR="$2"; shift 2 ;;
- -h|--help) sed -n '2,/^# Exit status/p' "${BASH_SOURCE[0]}"; exit 0 ;;
- *) echo "unknown argument: $1" >&2; exit 2 ;;
- esac
-done
-
-if [[ -n "$MEMORY_OFF" && -n "$MEMORY_WRITES_OFF" ]]; then
- echo "error: --memory-off and --memory-writes-off are mutually exclusive:" >&2
- echo " --memory-off already disables writes, so combining them would emit a" >&2
- echo " config with duplicate [memory] and [learning] tables, which the core" >&2
- echo " rejects. Run with just --memory-off (both off) or just --memory-writes-off." >&2
- exit 2
-fi
-
-STAMP="$(date +%Y%m%d-%H%M%S)"
-OUT_DIR="${OUT_DIR:-$REPO_ROOT/target/bench/$STAMP}"
-mkdir -p "$OUT_DIR"
-
-# Ports chosen to avoid both the core's default 7788 (so a dev core can keep
-# running) and the LOCAL_AI_PORTS set the core routes around.
-MOCK_PORT="${BENCH_MOCK_PORT:-18700}"
-CORE_PORT="${BENCH_CORE_PORT:-17788}"
-CORE_TOKEN="bench-$(head -c 16 /dev/urandom | od -An -tx1 | tr -d ' \n')"
-
-CORE_BIN="$REPO_ROOT/target/release/openhuman-core"
-if [[ ! -x "$CORE_BIN" ]]; then
- echo "error: $CORE_BIN not found." >&2
- echo "Build it first:" >&2
- echo " cargo build --release --bin openhuman-core \\" >&2
- echo " --no-default-features --features \"\$(bash scripts/ci/product-features.sh)\"" >&2
- exit 1
-fi
-
-# The workspace goes on real disk, under the artifacts directory — NOT in /tmp.
-#
-# On a host where /tmp is tmpfs (common, and the case on the box this was
-# written on) that choice is not cosmetic, it corrupts the experiment twice
-# over. tmpfs pages ARE memory, so every byte the core writes to its workspace
-# is charged against the machine's RAM while the benchmark is trying to
-# attribute RAM to the core. And it does not merely skew the numbers: a
-# sustained run fills the mount, at which point the core starts failing with
-# "Failed to write auth profile lock owner" and SQLite "disk I/O error", and
-# throughput collapses to zero — a failure that reads like a leak-induced
-# meltdown rather than a full disk.
-#
-# --workspace reuses an existing (already populated) workspace instead of
-# starting empty. That turns the harness into a controlled experiment: run once
-# to accumulate state, then point a FRESH core process at the result. If
-# per-turn latency starts where the previous run ended, the cost is a function
-# of accumulated DATA (an O(N) path over stored state); if it starts low again,
-# the cost was a function of process uptime (an in-process leak). The two have
-# entirely different fixes, and nothing else in this harness separates them.
-if [[ -n "$REUSE_WORKSPACE" ]]; then
- if [[ ! -d "$REUSE_WORKSPACE" ]]; then
- echo "error: --workspace $REUSE_WORKSPACE does not exist" >&2
- exit 1
- fi
- WORKSPACE="$(cd "$REUSE_WORKSPACE" && pwd)"
- # Never delete a workspace the caller supplied.
- KEEP_WORKSPACE=1
- echo "==> reusing workspace: $WORKSPACE"
-else
- WORKSPACE="$OUT_DIR/workspace"
-fi
-mkdir -p "$WORKSPACE"
-
-WORKSPACE_FS="$(findmnt -no FSTYPE --target "$WORKSPACE" 2>/dev/null || echo unknown)"
-if [[ "$WORKSPACE_FS" == "tmpfs" || "$WORKSPACE_FS" == "ramfs" ]]; then
- echo "error: the benchmark workspace is on $WORKSPACE_FS ($WORKSPACE)." >&2
- echo " A RAM-backed filesystem charges the core's disk writes against machine" >&2
- echo " memory, which invalidates the memory measurement, and fills up mid-run." >&2
- echo " Use --out-dir to place artifacts on a disk-backed filesystem." >&2
- exit 1
-fi
-if [[ "$WORKSPACE_FS" == "unknown" ]]; then
- echo "error: could not determine the filesystem backing $WORKSPACE (findmnt missing or failed)." >&2
- echo " The guard exists to keep the run off tmpfs/ramfs; refusing to proceed blind." >&2
- exit 1
-fi
-
-WORKSPACE_AVAIL_MIB="$(df -Pm "$WORKSPACE" 2>/dev/null | awk 'NR==2 {print $4}')"
-if [[ -n "$WORKSPACE_AVAIL_MIB" && "$WORKSPACE_AVAIL_MIB" -lt 2048 ]]; then
- echo "warning: only ${WORKSPACE_AVAIL_MIB} MiB free at $WORKSPACE." >&2
- echo " A sustained run writes memory chunks and embeddings continuously; if the" >&2
- echo " filesystem fills, turns start failing and the run measures that instead." >&2
-fi
-
-# The core enforces a daily managed-inference spend limit, $10 by default, and
-# prices the mock's reported token usage against it. A sustained run blows
-# through that in a few hundred turns, after which EVERY remaining turn fails
-# instantly with "cost budget exceeded" — which does not look like a broken
-# benchmark, it looks like enormous throughput and a memory curve driven
-# entirely by error handling.
-#
-# The limits are raised rather than the check disabled (`[cost] enabled = false`)
-# so the budget check still runs on every turn and its cost stays in the
-# measurement. We are not benchmarking billing, but we should not silently
-# remove work the product does per turn either.
-#
-# Written to both candidate locations because the resolver accepts
-# `<workspace>/config.toml` and `<workspace>/../config.toml` depending on layout.
-BENCH_CONFIG=$(cat <<'TOML'
-[cost]
-enabled = true
-daily_limit_usd = 1000000.0
-monthly_limit_usd = 1000000.0
-TOML
-)
-
-# --memory-off is the CONTROL for the memory subsystem.
-#
-# Per-turn cost that grows with accumulated data is hard to attribute from a
-# single run, because the agent both writes memory and recalls over it every
-# turn. Turning the writes and the post-turn learning hooks off gives a
-# comparison run whose only difference is that accumulation: if per-turn latency
-# stops climbing, the growth is the memory path; if it still climbs, it is not.
-#
-# There is no single `[memory] enabled` switch — three independent producers run
-# per turn, so all three have to be named:
-# * `memory.auto_save` the UnifiedMemory document write (markdown sidecar,
-# memory_docs row, and re-inserted vector chunks)
-# * `[learning]` hooks episodic capture and chat→tree, which default ON
-# *independently* of `learning.enabled`
-# * embeddings `provider = "none"` selects the no-op embedder;
-# an unknown string here hard-errors the session
-# Agent turns still complete with all of this off — every path degrades rather
-# than failing.
-if [[ -n "$MEMORY_OFF" ]]; then
- BENCH_CONFIG="$BENCH_CONFIG$(cat <<'TOML'
-
-[memory]
-auto_save = false
-embedding_provider = "none"
-
-[learning]
-enabled = false
-episodic_capture_enabled = false
-chat_to_tree_enabled = false
-stm_recall_enabled = false
-tool_memory_capture_enabled = false
-goals_enrichment_enabled = false
-
-[memory_tree]
-spacy_enabled = false
-TOML
-)"
-fi
-
-# --memory-writes-off stops memory WRITES while leaving recall reads intact.
-#
-# `--memory-off` turns off reads and writes together, so on its own it cannot
-# say which of the two is the expensive one — and they have different fixes. Run
-# this against an already-populated workspace (`--workspace`): recall still
-# scans the whole namespace every turn, but nothing new is stored. If throughput
-# stays at the --memory-off-less level, the cost is in the read path; if it
-# recovers, write contention on the shared connection was the problem.
-if [[ -n "$MEMORY_WRITES_OFF" ]]; then
- BENCH_CONFIG="$BENCH_CONFIG$(cat <<'TOML'
-
-[memory]
-auto_save = false
-
-[learning]
-enabled = false
-episodic_capture_enabled = false
-chat_to_tree_enabled = false
-TOML
-)"
-fi
-mkdir -p "$WORKSPACE/workspace"
-printf '%s\n' "$BENCH_CONFIG" >"$WORKSPACE/config.toml"
-printf '%s\n' "$BENCH_CONFIG" >"$WORKSPACE/workspace/config.toml"
-
-MOCK_PID=""
-CORE_PID=""
-SAMPLER_PID=""
-
-cleanup() {
- local status=$?
- set +e
- [[ -n "$SAMPLER_PID" ]] && kill "$SAMPLER_PID" 2>/dev/null
- if [[ -n "$CORE_PID" ]]; then
- kill "$CORE_PID" 2>/dev/null
- # Give it a moment to flush and close cleanly before forcing.
- for _ in $(seq 1 20); do kill -0 "$CORE_PID" 2>/dev/null || break; sleep 0.25; done
- kill -9 "$CORE_PID" 2>/dev/null
- fi
- [[ -n "$MOCK_PID" ]] && kill "$MOCK_PID" 2>/dev/null
- # Record how much the run wrote before removing it — a workspace that grows
- # without bound is its own finding, and it is invisible once deleted.
- if [[ -d "$WORKSPACE" ]]; then
- du -sm "$WORKSPACE" 2>/dev/null | awk '{print "workspace on disk: " $1 " MiB"}' >&2
- fi
- if [[ -z "$KEEP_WORKSPACE" && -d "$WORKSPACE" ]]; then
- rm -rf "$WORKSPACE"
- elif [[ -n "$KEEP_WORKSPACE" ]]; then
- echo "workspace kept at $WORKSPACE" >&2
- fi
- exit $status
-}
-trap cleanup EXIT INT TERM
-
-echo "==> artifacts: $OUT_DIR"
-echo "==> workspace: $WORKSPACE"
-
-# ---------------------------------------------------------------- mock LLM
-echo "==> starting mock LLM on :$MOCK_PORT"
-node "$REPO_ROOT/scripts/bench/mock-llm.mjs" \
- --port "$MOCK_PORT" \
- --latency-ms "$LATENCY_MS" \
- --jitter-ms "$JITTER_MS" \
- --tool-depth "$TOOL_DEPTH" \
- --reply-chars "$REPLY_CHARS" \
- --fail-rate "$FAIL_RATE" \
- >"$OUT_DIR/mock-llm.log" 2>&1 &
-MOCK_PID=$!
-
-for _ in $(seq 1 50); do
- if curl -fsS "http://127.0.0.1:$MOCK_PORT/health" >/dev/null 2>&1; then break; fi
- sleep 0.2
-done
-curl -fsS "http://127.0.0.1:$MOCK_PORT/health" >/dev/null || {
- echo "error: mock LLM did not become healthy; see $OUT_DIR/mock-llm.log" >&2
- exit 1
-}
-
-# ---------------------------------------------------------------- core
-echo "==> starting openhuman-core on :$CORE_PORT"
-# BACKEND_URL is the whole redirect: it feeds both the inference base and the
-# backend base, so every outbound call lands on the mock.
-#
-# OPENHUMAN_APPROVAL_GATE=0 is not a convenience. The gate is ON by default and
-# parks interactive chat turns pending a human decision, with a 10-minute TTL
-# that resolves to Deny. Left on, every benchmark turn would block on a prompt
-# nobody is there to answer, and the run would measure a queue of parked turns
-# rather than agent throughput.
-#
-# `env -i` clears the environment so a developer's own OPENHUMAN_* or BACKEND_URL
-# settings cannot silently redirect the run at their real account or backend.
-env -i \
- PATH="$PATH" HOME="$WORKSPACE" \
- OPENHUMAN_WORKSPACE="$WORKSPACE" \
- OPENHUMAN_ACTION_DIR="$WORKSPACE/projects" \
- OPENHUMAN_CORE_HOST=127.0.0.1 \
- OPENHUMAN_CORE_PORT="$CORE_PORT" \
- OPENHUMAN_CORE_TOKEN="$CORE_TOKEN" \
- BACKEND_URL="http://127.0.0.1:$MOCK_PORT" \
- OPENHUMAN_APPROVAL_GATE=0 \
- RUST_LOG="${RUST_LOG:-warn}" \
- "$CORE_BIN" serve >"$OUT_DIR/core.log" 2>&1 &
-CORE_PID=$!
-
-for _ in $(seq 1 150); do
- if curl -fsS "http://127.0.0.1:$CORE_PORT/health" >/dev/null 2>&1; then break; fi
- if ! kill -0 "$CORE_PID" 2>/dev/null; then
- echo "error: core exited during startup; see $OUT_DIR/core.log" >&2
- tail -30 "$OUT_DIR/core.log" >&2
- exit 1
- fi
- sleep 0.2
-done
-curl -fsS "http://127.0.0.1:$CORE_PORT/health" >/dev/null || {
- echo "error: core did not become healthy; see $OUT_DIR/core.log" >&2
- tail -30 "$OUT_DIR/core.log" >&2
- exit 1
-}
-echo "==> core pid $CORE_PID healthy"
-
-# ---------------------------------------------------------------- sample + load
-# The sampler starts before the driver so the series covers warm-up too; the
-# analyzer drops that head via --warmup-frac.
-echo "==> sampling every ${INTERVAL_MS}ms"
-node "$REPO_ROOT/scripts/bench/sampler.mjs" \
- --pid "$CORE_PID" --interval-ms "$INTERVAL_MS" $TREE \
- >"$OUT_DIR/samples.jsonl" 2>"$OUT_DIR/sampler.log" &
-SAMPLER_PID=$!
-
-DRIVER_ARGS=(
- --core-url "http://127.0.0.1:$CORE_PORT"
- --token "$CORE_TOKEN"
- --concurrency "$CONCURRENCY"
- --thread-mode "$THREAD_MODE"
- --warmup-turns "$WARMUP_TURNS"
- --out "$OUT_DIR/driver.json"
- --turns-out "$OUT_DIR/turns.jsonl"
-)
-if [[ -n "$DURATION_MS" ]]; then
- DRIVER_ARGS+=(--duration-ms "$DURATION_MS")
-else
- DRIVER_ARGS+=(--turns "$TURNS")
-fi
-
-# Workspace size before and after the load. The agent persists memory chunks and
-# embeddings every turn, so this grows even in `fresh` thread mode — which means
-# RSS growth is not automatically a leak, it may be an index tracking data that
-# genuinely accumulated. Recording both lets the report say which.
-WORKSPACE_MIB_BEFORE="$(du -sm "$WORKSPACE" 2>/dev/null | awk '{print $1}')"
-
-echo "==> running load"
-DRIVER_STATUS=0
-node "$REPO_ROOT/scripts/bench/driver.mjs" "${DRIVER_ARGS[@]}" \
- >"$OUT_DIR/driver.stdout" 2>"$OUT_DIR/driver.log" || DRIVER_STATUS=$?
-
-WORKSPACE_MIB_AFTER="$(du -sm "$WORKSPACE" 2>/dev/null | awk '{print $1}')"
-
-# Let the sampler capture the post-load tail. Memory that is only released once
-# work stops shows up here, and so does a process that keeps burning CPU after
-# the last turn — which is itself a finding.
-echo "==> settling"
-sleep 3
-kill "$SAMPLER_PID" 2>/dev/null || true
-wait "$SAMPLER_PID" 2>/dev/null || true
-SAMPLER_PID=""
-
-curl -fsS "http://127.0.0.1:$MOCK_PORT/__bench/stats" >"$OUT_DIR/mock-stats.json" 2>/dev/null || true
-
-if [[ $DRIVER_STATUS -ne 0 ]]; then
- echo "error: driver failed (exit $DRIVER_STATUS); see $OUT_DIR/driver.log" >&2
- tail -20 "$OUT_DIR/driver.log" >&2
- exit $DRIVER_STATUS
-fi
-
-# ---------------------------------------------------------------- cross-check
-# A turn can return 200 while the inference call behind it silently degraded —
-# the RPC succeeds, the agent answers with an error string, and the run looks
-# green having measured nothing. Comparing what the driver thinks it ran against
-# what the mock was actually asked for is the cheapest way to catch that, and
-# without it a misconfigured BACKEND_URL would produce a confident, meaningless
-# "no leak detected".
-echo "==> verifying the mock actually served the load"
-node -e '
-const fs = require("node:fs");
-const [statsPath, driverPath] = process.argv.slice(1);
-let stats, driver;
-try {
- stats = JSON.parse(fs.readFileSync(statsPath, "utf8"));
- driver = JSON.parse(fs.readFileSync(driverPath, "utf8"));
-} catch (err) {
- console.error(` could not cross-check: ${err.message}`);
- process.exit(1);
-}
-const turns = driver.turnsOk ?? 0;
-const failed = driver.turnsFailed ?? 0;
-const total = turns + failed;
-console.error(
- ` driver: ${turns} ok turns | mock: ${stats.completions} completions, ` +
- `${stats.toolCallsEmitted} tool calls, ${stats.embeddings} embeddings, ` +
- `${stats.telemetry} telemetry`,
-);
-
-// A run where most turns errored is not a measurement of agent work — it is a
-// measurement of the error path, and its memory curve says nothing about a
-// leak in normal operation. This check exists because a run that failed 96% of
-// its turns on an exhausted cost budget still produced a confident verdict:
-// the failures were fast, so throughput looked high and nothing else complained.
-const FAILURE_BUDGET = 0.05;
-if (total > 0 && failed / total > FAILURE_BUDGET) {
- console.error(
- ` ERROR: ${failed}/${total} turns failed ` +
- `(${((failed / total) * 100).toFixed(1)}%), over the ${FAILURE_BUDGET * 100}% budget. ` +
- `This run measured the failure path, not agent work. Distinct errors:`,
- );
- for (const [msg, count] of Object.entries(driver.errors ?? {}).slice(0, 5)) {
- console.error(` ${count} x ${msg.slice(0, 180)}`);
- }
- process.exit(1);
-}
-if (failed > 0) {
- console.error(` note: ${failed}/${total} turns failed, within the tolerated budget.`);
-}
-if (stats.unknownRoutes > 0) {
- console.error(
- ` WARNING: the core called ${stats.unknownRoutes} route(s) the mock does not ` +
- `implement (see mock-llm.log). Those calls failed, so some path ran degraded.`,
- );
-}
-if (turns > 0 && stats.completions < turns) {
- console.error(
- ` ERROR: ${turns} turns reported ok but the mock served only ` +
- `${stats.completions} completions. Turns are not reaching the mocked LLM, ` +
- `so these numbers do not describe agent work.`,
- );
- process.exit(1);
-}
-' "$OUT_DIR/mock-stats.json" "$OUT_DIR/driver.json" || {
- echo "error: cross-check failed — refusing to report a verdict on this run" >&2
- exit 1
-}
-
-# ---------------------------------------------------------------- analyze
-echo "==> analyzing"
-ANALYZE_STATUS=0
-node "$REPO_ROOT/scripts/bench/analyze.mjs" \
- --samples "$OUT_DIR/samples.jsonl" \
- --driver "$OUT_DIR/driver.json" \
- --turns "$OUT_DIR/turns.jsonl" \
- --workspace-mib-before "${WORKSPACE_MIB_BEFORE:-0}" \
- --workspace-mib-after "${WORKSPACE_MIB_AFTER:-0}" \
- --out "$OUT_DIR/report.json" \
- >/dev/null || ANALYZE_STATUS=$?
-
-echo "==> artifacts in $OUT_DIR"
-exit $ANALYZE_STATUS
diff --git a/scripts/bench/sampler.mjs b/scripts/bench/sampler.mjs
deleted file mode 100755
index 0424185c82..0000000000
--- a/scripts/bench/sampler.mjs
+++ /dev/null
@@ -1,256 +0,0 @@
-#!/usr/bin/env node
-/**
- * Resource sampler for the agent-scale benchmark tier.
- *
- * Samples a running `openhuman-core` process from /proc and writes one JSON
- * object per line to stdout. The analyzer consumes that stream; keeping the two
- * apart means a run can be re-analyzed with different thresholds without
- * re-running the load.
- *
- * Why this exists alongside `crates/openhuman-core/src/platform/proc_metrics/`: that module
- * samples the CURRENT process, for benchmarks that embed the core as a library.
- * This tier deliberately measures a separate, normally-built server process
- * over RPC, so the sampling has to come from outside it.
- *
- * Fields per sample:
- * tMs ms since sampling started
- * epochMs wall-clock ms, for aligning against the driver's turn log
- * rssKib resident set size
- * vmHwmKib peak RSS the kernel has ever seen for this process
- * pssKib proportional set size (smaps_rollup; null if unreadable)
- * privateKib private clean+dirty (smaps_rollup; null if unreadable)
- * cpuUserMs cumulative user CPU
- * cpuSystemMs cumulative system CPU
- * threads thread count
- * openFds open file descriptors (null if unreadable)
- * treeRssKib self + descendants RSS, only with --tree
- * children descendant count, only with --tree
- *
- * Usage:
- * node scripts/bench/sampler.mjs --pid <pid> [--interval-ms 250] [--tree] > samples.jsonl
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const CLOCK_TICKS_PER_SEC = 100; // _SC_CLK_TCK is 100 on every mainstream Linux.
-
-function parseArgs(argv) {
- const opts = { pid: null, intervalMs: 250, tree: false, durationMs: null };
- for (let i = 2; i < argv.length; i += 1) {
- const arg = argv[i];
- if (arg === '--tree') {
- opts.tree = true;
- } else if (arg === '--pid') {
- const raw = argv[++i];
- if (raw === undefined) throw new Error('--pid expects a value');
- opts.pid = Number(raw);
- } else if (arg === '--interval-ms') {
- const raw = argv[++i];
- if (raw === undefined) throw new Error('--interval-ms expects a value');
- opts.intervalMs = Number(raw);
- } else if (arg === '--duration-ms') {
- const raw = argv[++i];
- if (raw === undefined) throw new Error('--duration-ms expects a value');
- opts.durationMs = Number(raw);
- } else {
- throw new Error(`unknown argument: ${arg}`);
- }
- }
- if (!Number.isInteger(opts.pid) || opts.pid <= 0) {
- throw new Error('--pid <pid> is required');
- }
- if (!Number.isFinite(opts.intervalMs) || opts.intervalMs <= 0) {
- throw new Error('--interval-ms must be a positive number');
- }
- if (opts.durationMs !== null && (!Number.isFinite(opts.durationMs) || opts.durationMs <= 0)) {
- throw new Error('--duration-ms must be a positive number');
- }
- return opts;
-}
-
-function readOrNull(file) {
- try {
- return fs.readFileSync(file, 'utf8');
- } catch {
- return null;
- }
-}
-
-/** VmRSS / VmHWM / Threads from /proc/<pid>/status, in KiB. */
-function parseStatus(text) {
- const out = { rssKib: null, vmHwmKib: null, threads: null };
- if (!text) return out;
- for (const line of text.split('\n')) {
- const colon = line.indexOf(':');
- if (colon < 0) continue;
- const key = line.slice(0, colon);
- const value = parseInt(line.slice(colon + 1).trim(), 10);
- if (Number.isNaN(value)) continue;
- if (key === 'VmRSS') out.rssKib = value;
- else if (key === 'VmHWM') out.vmHwmKib = value;
- else if (key === 'Threads') out.threads = value;
- }
- return out;
-}
-
-/** Pss and Private_{Clean,Dirty} from /proc/<pid>/smaps_rollup, in KiB. */
-function parseSmapsRollup(text) {
- const out = { pssKib: null, privateKib: null };
- if (!text) return out;
- let privateClean = null;
- let privateDirty = null;
- for (const line of text.split('\n')) {
- const colon = line.indexOf(':');
- if (colon < 0) continue;
- const key = line.slice(0, colon);
- const value = parseInt(line.slice(colon + 1).trim(), 10);
- if (Number.isNaN(value)) continue;
- if (key === 'Pss') out.pssKib = value;
- else if (key === 'Private_Clean') privateClean = value;
- else if (key === 'Private_Dirty') privateDirty = value;
- }
- if (privateClean !== null || privateDirty !== null) {
- out.privateKib = (privateClean ?? 0) + (privateDirty ?? 0);
- }
- return out;
-}
-
-/**
- * utime/stime from /proc/<pid>/stat, converted to ms.
- *
- * The comm field (index 1) can itself contain spaces and parentheses, so the
- * fields are located relative to the LAST ')' rather than by splitting the
- * whole line — the standard way to parse this file safely.
- */
-function parseStatCpu(text) {
- const out = { cpuUserMs: null, cpuSystemMs: null };
- if (!text) return out;
- const close = text.lastIndexOf(')');
- if (close < 0) return out;
- const rest = text.slice(close + 2).trim().split(/\s+/);
- // After comm and state, utime is field 14 and stime field 15 (1-indexed in
- // proc(5)); with the first two fields removed they land at rest[11]/rest[12].
- const utime = parseInt(rest[11], 10);
- const stime = parseInt(rest[12], 10);
- if (!Number.isNaN(utime)) out.cpuUserMs = (utime / CLOCK_TICKS_PER_SEC) * 1000;
- if (!Number.isNaN(stime)) out.cpuSystemMs = (stime / CLOCK_TICKS_PER_SEC) * 1000;
- return out;
-}
-
-/** ppid from /proc/<pid>/stat, using the same last-')' rule. */
-function parseStatPpid(text) {
- if (!text) return null;
- const close = text.lastIndexOf(')');
- if (close < 0) return null;
- const rest = text.slice(close + 2).trim().split(/\s+/);
- const ppid = parseInt(rest[1], 10);
- return Number.isNaN(ppid) ? null : ppid;
-}
-
-function countOpenFds(pid) {
- try {
- return fs.readdirSync(`/proc/${pid}/fd`).length;
- } catch {
- return null;
- }
-}
-
-/**
- * Sum RSS across the process and every descendant.
- *
- * Scans all of /proc to build the parent map. That is the only way to find
- * grandchildren, and at a 250 ms cadence the cost is negligible next to the
- * workload — but it is why --tree is opt-in rather than always on.
- */
-function sampleTree(rootPid) {
- let entries;
- try {
- entries = fs.readdirSync('/proc');
- } catch {
- return { treeRssKib: null, children: null };
- }
-
- const byParent = new Map();
- const rssByPid = new Map();
- for (const entry of entries) {
- const pid = Number(entry);
- if (!Number.isInteger(pid) || pid <= 0) continue;
- const stat = readOrNull(path.join('/proc', entry, 'stat'));
- if (!stat) continue;
- const ppid = parseStatPpid(stat);
- if (ppid === null) continue;
- if (!byParent.has(ppid)) byParent.set(ppid, []);
- byParent.get(ppid).push(pid);
- const status = parseStatus(readOrNull(path.join('/proc', entry, 'status')));
- if (status.rssKib !== null) rssByPid.set(pid, status.rssKib);
- }
-
- let total = rssByPid.get(rootPid) ?? 0;
- let children = 0;
- const queue = [rootPid];
- const seen = new Set([rootPid]);
- while (queue.length > 0) {
- const pid = queue.pop();
- for (const child of byParent.get(pid) ?? []) {
- if (seen.has(child)) continue; // guard against a cycle from pid reuse
- seen.add(child);
- children += 1;
- total += rssByPid.get(child) ?? 0;
- queue.push(child);
- }
- }
- return { treeRssKib: total, children };
-}
-
-function sampleOnce(pid, withTree) {
- const statusText = readOrNull(`/proc/${pid}/status`);
- if (statusText === null) return null; // process is gone
- const status = parseStatus(statusText);
- const smaps = parseSmapsRollup(readOrNull(`/proc/${pid}/smaps_rollup`));
- const cpu = parseStatCpu(readOrNull(`/proc/${pid}/stat`));
- const sample = {
- ...status,
- ...smaps,
- ...cpu,
- openFds: countOpenFds(pid),
- };
- if (withTree) Object.assign(sample, sampleTree(pid));
- return sample;
-}
-
-const opts = parseArgs(process.argv);
-const startedAt = Date.now();
-
-// Fail fast rather than emitting an empty series that the analyzer would have
-// to interpret.
-if (sampleOnce(opts.pid, false) === null) {
- process.stderr.write(`[sampler] pid ${opts.pid} is not readable in /proc\n`);
- process.exit(1);
-}
-
-let stopping = false;
-const stop = () => {
- if (stopping) return;
- stopping = true;
- clearInterval(timer);
- process.exit(0);
-};
-
-const timer = setInterval(() => {
- const sample = sampleOnce(opts.pid, opts.tree);
- if (sample === null) {
- process.stderr.write(`[sampler] pid ${opts.pid} exited; stopping\n`);
- stop();
- return;
- }
- const now = Date.now();
- // epochMs as well as tMs: the analyzer aligns this series against the
- // driver's turn log, which has its own time origin.
- process.stdout.write(
- `${JSON.stringify({ tMs: now - startedAt, epochMs: now, ...sample })}\n`,
- );
- if (opts.durationMs !== null && Date.now() - startedAt >= opts.durationMs) stop();
-}, opts.intervalMs);
-
-for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, stop);
diff --git a/scripts/life-scenarios/DIAGNOSIS.md b/scripts/life-scenarios/DIAGNOSIS.md
deleted file mode 100644
index 97b7687c69..0000000000
--- a/scripts/life-scenarios/DIAGNOSIS.md
+++ /dev/null
@@ -1,338 +0,0 @@
-# Diagnosis: why four of six scenarios produced no file
-
-A forensic trace of the 2026-09-22 runs, from the artifacts in
-`target/life-scenarios/`. `FINDINGS.md` is the list of defects; this is the
-causal account, with the evidence for each step and an explicit note where I am
-inferring rather than measuring.
-
-**The short version.** The headline number — four of six scenarios wrote
-nothing while spending $0.69, $0.78 and $0.13 — is not one failure. It is three,
-and the one I originally blamed (the iteration cap) is the *least* important of
-them. The dominant cause is that **the orchestrator has no working way to create
-a file**, and it burns its iteration budget discovering that.
-
----
-
-## The measurement that started it
-
-`anthropic/claude-sonnet-5`, run `2026-09-22T20-12-36-423Z`, from
-`grep "turn prompt summary" core.log` (parent turns only; rows 5 and 6 have
-`system_bytes=5130` and are sub-agent runs spawned by the `research` tool):
-
-| # | scenario | model_calls | tool_calls | outcome |
-| --- | --- | --- | --- | --- |
-| 1 | calendar-buffer | 2 | 1 | stopped early, **not** capped |
-| 2 | subscription-scan | 5 | 4 | finished naturally — 9/11 |
-| 3 | baggage-policy | **15** | 20 | **cap** |
-| 4 | meal-plan | 12 | 11 | finished naturally, wrote 1-byte files |
-| 7 | trip-itinerary | **15** | 14 | **cap** |
-| 8 | fact-check-publish | **15** | 14 | **cap** |
-
-The cap is `max_model_calls = max_iterations = 15`
-(`agent/tinyagents/turn_policy.rs:139`) — a ceiling on **model calls**, not tool
-calls, which is why row 3 shows 20 tool calls under a cap of 15.
-
-`grep -c "final permitted model call" core.log` → **3**, matching rows 3, 7 and
-8 exactly. So three of the four empty scenarios hit the cap and one (meal-plan)
-did not. calendar-buffer is a fourth, separate failure.
-
----
-
-## Cause 1 — the orchestrator cannot create a file (meal-plan, and the reason the others ran out)
-
-This is the important one, and it is fully visible in one transcript. From
-`meal-plan`'s journal, in order, with every tool result:
-
-| step | tool | result |
-| --- | --- | --- |
-| 1 | `shell` `mkdir -p out` | ok |
-| 2 | `apply_patch` | `` edit[0]: `old_string` must not be empty `` |
-| 3 | `shell` heredoc write | `Blocked: [policy-blocked] … command/process substitution ($(…), <(…)), backticks, and background (&) are not allowed` |
-| 4 | `apply_patch` | `arguments.edits[0].path is required` |
-| 5 | `shell` | `Command failed (exit code 2)` |
-| — | *(harness injects)* | `[no progress since step 5] 4 tool calls in a row have failed…` |
-| 6 | `shell` | ok |
-| 7 | `apply_patch` | `Blocked: [policy-blocked] Resolved path escapes workspace: …/sandbox/meal-plan/out/meal_plan.md` |
-| 8 | `shell ls` | orienting |
-| 9 | `apply_patch` | `Failed to resolve path 'out/meal_plan.md': No such file or directory` |
-| 10 | `shell pwd` | orienting |
-| 11 | `apply_patch` | `Failed to resolve path 'meal_plan.md': No such file` |
-
-Eleven rounds, $0.80, and the two files it left behind are **one byte each,
-containing `x`** — the placeholder `shell` created at step 1 so that
-`apply_patch` would have something to patch.
-
-Four separate mechanisms combine to close every door:
-
-### 1a. `file_write` is not on the wire
-
-`[agent] tool spec filter: total=232 visible=16` — the 16 are `shell`,
-`apply_patch`, the sub-agent tools, `todo`, `resolve_time`, memory tools,
-`http_request`, `web_fetch`, `web_search_tool`, `composio_connect`, `use_skill`.
-No `file_write`, `file_read`, `grep`, `glob` or `list`: `ToolGroups::default()`
-puts every pack in `Withheld` (`tools/toolpacks/groups.rs`).
-
-### 1b. The `use_skill` escape hatch is closed for exactly the pack that would help
-
-Withheld is documented as "reachable via `use_skill`". In the follow-up run the
-agent tried precisely that — `use_skill {"skill":"files"}` — and got:
-
-> Skill `files` has no tools available in this session. Call `plan` or
-> `run_code` or `review_code` or `run_skill` instead — that agent owns these
-> tools and runs them directly. Do not retry this skill.
-
-That is `tools/toolpacks/tools.rs:206` firing because `found == 0`: every tool
-in the pack was made non-callable by `close_handed_off_packs`
-(`agent/session_host/builder/builder_build.rs`, #6302) — *"a pack whose owner
-this agent can hand off to directly is that specialist's belt, not this
-agent's"*. So for the orchestrator the file pack is not withheld-but-reachable,
-it is **closed**, and the only route is delegating to a specialist the
-orchestrator was not told to use for "write this file".
-
-### 1c. `apply_patch` cannot create a file
-
-`` `old_string` must not be empty `` and `Failed to resolve path …: No such
-file or directory` — it canonicalizes the target, so the file must already
-exist. Combined with 1a/1b this is the whole write surface, and it is
-edit-only.
-
-### 1d. `shell` refuses to write content containing `&`
-
-This is the sharpest defect of the run. The blocked command at step 3 was a
-quoted heredoc:
-
-```
-cat > out/meal_plan.md << 'EOF'
-# 5-Day Mediterranean Dinner Plan (Family of 4)
-
-## Day 1 — Greek Chicken & Spinach Orzo Skillet
-...
-```
-
-Scanning that command string for the characters the classifier objects to finds
-four hits, all of them the same thing:
-
-```
-'&' at 106 -> '## Day 1 — Greek Chicken & Spinach Orzo Skillet'
-'&' at 2034 -> '## Day 3 — Spinach & Feta Stuffed Chicken…'
-'&' at 3044 -> '## Day 4 — Mediterranean Chickpea & Spinach Skillet'
-'&' at 3835 -> '## Day 5 — Shrimp & Vegetable Mediterranean Pasta'
-```
-
-No `$(`, no backtick, no `<(`. The command was refused because **recipe titles
-contain an ampersand**. `classify_command` reads the raw command string, so a
-`&` inside a single-quoted heredoc body — where the shell treats it as literal
-text — is indistinguishable to it from a background operator.
-
-That `subscription-scan` succeeded with the *same* `cat > … << 'EOF'` shape is
-the control: heredocs are fine. Its content simply had no `&` in it.
-
-Prose contains ampersands constantly — "Q&A", "R&D", "Chicken & Spinach", any
-URL with a query string, any HTML entity. This makes `shell` an unreliable
-writer for exactly the documents an assistant produces.
-
-The model noticed and adapted, rewriting the titles to "Chicken and Spinach" on
-its next attempt — which then failed on 1c instead.
-
-### 1e. `action_dir` is the join base but not a permitted root
-
-Step 7's `Resolved path escapes workspace:
-…/sandbox/meal-plan/out/meal_plan.md` is about a path **inside**
-`OPENHUMAN_ACTION_DIR`, which `CLAUDE.md` calls "the agent's permitted read and
-write root".
-
-`security/policy/path_checks.rs`:
-
-```rust
-// validate_path: relative paths are joined onto action_dir …
-let full_path = … self.action_dir.join(&expanded) …
-
-// …but the permission check never mentions action_dir:
-pub fn is_resolved_path_allowed_for(&self, resolved: &Path, require_write: bool) -> bool {
- if Self::is_always_forbidden(resolved) { return false; }
- let workspace_root = self.workspace_root_sync();
- resolved.starts_with(&workspace_root) || self.is_within_trusted_root(resolved, require_write)
-}
-```
-
-The write permission comes from a trusted root, and
-`security/policy/enforcement.rs:118-126` grants one for
-**`default_projects_dir()`** — which reads `OPENHUMAN_PROJECTS_DIR` and knows
-nothing about `OPENHUMAN_ACTION_DIR`
-(`config/schema/load/dirs.rs:78-90`).
-
-On a stock install `action_dir == default_projects_dir`, so this never shows.
-**Change the action dir — via `OPENHUMAN_ACTION_DIR`, or `action_dir_override`,
-which is what the Settings working-folder control writes — and the file tools
-lose write permission to the directory the agent is told to work in.**
-
-**Verified experimentally.** Re-running `meal-plan` with
-`OPENHUMAN_PROJECTS_DIR` additionally pointed at the same sandbox took
-`grep -c "policy-blocked" core.log` from several to **0**. The agent still
-failed — on 1b/1c/1d, which the grant does not touch — but the path rejection
-was gone. `run.mjs` now sets both variables and says why.
-
----
-
-## Cause 2 — the cap withdraws every tool and asks for a report (baggage-policy, trip-itinerary, fact-check-publish)
-
-At model call 15 of 15, `FinalCallWrapUpMiddleware`
-(`agent/tinyagents/middleware/final_call_wrap_up.rs`) fires:
-
-```
-[tinyagents::mw] final permitted model call — withdrawing tools and asking for
-the turn's conclusion model_calls=15 max_model_calls=15 tools_withdrawn=25
-```
-
-It clears `request.tools`, sets `tool_choice = None`, and appends
-`MAX_ITER_CHECKPOINT_INSTRUCTION` (`agent/session_host/turn_checkpoint.rs:85`):
-
-> You have reached the maximum number of tool calls allowed for this single
-> turn, so you cannot call any more tools right now. Do not attempt another
-> tool call.
->
-> First, report the substance of what this turn produced … Then close with a
-> brief **Still to do** line naming what remains, so the user can ask you to
-> carry on.
-
-The model complied exactly. baggage-policy:
-
-> Here's what I found from Delta's actual pages (I haven't written the file yet
-> — running low on tool calls this turn, so reporting findings first)
-
-**I was wrong in my first pass** to describe this as the model spontaneously
-noticing a budget. It was told, in those words, by the harness. There is no
-"running low on tool calls" string anywhere in the codebase — that phrasing is
-the model paraphrasing the injected instruction.
-
-The mechanism is deliberate and well-built (#6014 replaced a worse out-of-band
-wrap-up). The problem is the situation it is asked to rescue: with all 25 tools
-withdrawn, **the turn is structurally incapable of writing the file**, however
-much budget was spent getting ready to. And these three scenarios only reached
-call 15 because they spent rounds on Cause 1.
-
-### The caller is never told
-
-`turn_run_finalize.rs:210` computes `hit_cap`, and it does reach some consumers
-— `flows/ops/builder.rs:336` reads `last_turn_hit_cap`. But `grep hit_cap` over
-`web_chat/` returns nothing, and `TurnUsagePayload` (`openhuman-rpc/src/server/socketio.rs:353`)
-carries `input_tokens`, `output_tokens`, `cached_input_tokens`, `cost_usd`,
-`context_window`, `subagents` — and no cap flag.
-
-So on the path the desktop app uses, a capped turn arrives as an ordinary
-`chat_done`. Nothing machine-readable distinguishes "here is your answer" from
-"I ran out of room and this is a status report". This suite only found out by
-reading the reply prose.
-
----
-
-## Cause 3 — calendar-buffer refused on transcript grounds (2 model calls, no cap)
-
-Separate from both. The agent ran `cat calendar-buffer/calendar/calendar.json`,
-got the **complete** 1,821-byte file back (verified: the tool result in the
-journal ends with `ev-07`, `]`, `}`), and then answered:
-
-> I wasn't able to complete this task. The only tool result I have is a
-> truncated read of `calendar/calendar.json`, cut off after the third event
-> … I also have no tool record showing `out/meeting_buffer_plan.json` was
-> actually written — no `apply_patch` or file-write call appears in what ran.
-
-The truncation claim is false — the file was complete. **The second claim is
-true**, and it is the interesting half. From the journal:
-
-```
-0 system len=20638
-1 system len=467
-2 user len=1117 the task
-3 assistant len=0 tool_calls=false <-- no record of the call
-4 user len=806 "[Tool results] <tool_result id=…-model-1-tool-1>"
-5 assistant len=0 tool_calls=false
-6 user len=4112 "[Tool results] …-model-2-tool-1"
-```
-
-Every assistant turn that called a tool is stored with empty content and no
-tool-call array; results come back as `user` messages. The same shape appears in
-`subscription-scan`, which succeeded anyway — so this degrades reliability
-rather than guaranteeing failure.
-
-`message_convert.rs:549-563` **preserves** tool calls when they are present
-(`a.tool_calls.is_empty()` → plain chat, else `AssistantToolCalls`), so their
-absence from the journal means they were absent from `run.messages`, the live
-array. The dialect is text-based — the system prompt teaches
-`<tool_call>\nread_file(path="…")\n</tool_call>` — so the model's call lived in
-message *text* that was parsed out and not retained.
-
-**Where this stops being measurement.** `session_raw` for the same turn *does*
-contain an assistant record carrying `tool_calls`, so the two stores disagree
-and the information is not lost everywhere. Whether the live provider request
-also lacked the calls is the one thing I could not confirm: I put the repo's
-capture proxy in front of the route
-(`CAPTURE_ALL=1 … CAPTURE_UPSTREAM=https://openrouter.ai`) and the core
-**silently fell back to the managed backend** rather than dial a plain-`http://`
-loopback inference URL — `egress-surface emitting external_transfer_pending
-provider=openhuman` despite `[config][byok] pinned role(s) [chat, reasoning,
-agentic, coding] to 'byok-inference:…'` two seconds earlier. That silent
-downgrade is its own defect, and fixing it is the prerequisite for settling this
-question.
-
-Until then: the model's behaviour is *consistent* with the live request lacking
-its own tool calls, and the journal *proves* a resumed thread would lack them.
-I would not claim more than that without the wire capture.
-
----
-
-## What I got wrong in the first pass
-
-Worth stating plainly, since the point of this document is a diagnosis that
-holds up:
-
-1. **I called the iteration cap the primary cause.** It is third. Three
- scenarios hit it, but they hit it *because* of Cause 1, and meal-plan and
- calendar-buffer never approached it.
-2. **I said the harness gives the model no budget warning and the model noticed
- on its own.** The opposite: `MAX_ITER_CHECKPOINT_INSTRUCTION` tells it in
- almost exactly those words.
-3. **I repeated Sonnet's claim that the tool result was truncated.** It was not.
- The model hallucinated that detail; only its structural complaint held up.
-4. **I described the missing tool calls as a straightforward replay bug.** The
- journal shape is confirmed; the live-request claim is not, and the capture
- run that would have settled it failed for an unrelated reason.
-
----
-
-## Ranked, with the fix each one wants
-
-| # | defect | evidence | fix belongs in |
-| --- | --- | --- | --- |
-| 1 | `action_dir` is not a permitted write root unless it equals `default_projects_dir` | step 7 block; `enforcement.rs:118-126`; grant experiment took blocks 3→0 | `security/policy/enforcement.rs` — grant `config.action_dir`, not just the default |
-| 2 | `classify_command` rejects `&` inside a quoted heredoc body | four `&` hits, all recipe titles; `subscription-scan` control | command classifier — parse enough shell to know a quoted heredoc body is data |
-| 3 | the `files` pack is closed to the orchestrator, so `use_skill` cannot reach `file_write` | `use_skill {"skill":"files"}` → "no tools available in this session" | `close_handed_off_packs` / orchestrator prompt — either keep a writer, or teach delegation before the model has failed four times |
-| 4 | `apply_patch` cannot create a file | `` `old_string` must not be empty ``; `No such file or directory` | give it a create mode, or advertise a writer |
-| 5 | a capped turn is indistinguishable from a finished one on the wire | `hit_cap` absent from `web_chat/` and `TurnUsagePayload` | `web_chat/presentation.rs` + `TurnUsagePayload` |
-| 6 | plain-`http://` loopback BYOK silently downgrades to the managed backend | `provider=openhuman` after a successful `[config][byok]` pin | provider factory — honour loopback http, or fail loudly |
-| 7 | the replayed transcript carries no assistant tool calls | journal dumps above | `vendor/tinyagents` (dialect / transcript replay) |
-
-1 through 4 are one user-visible bug: **the assistant cannot reliably write a
-file.** Fixing any one of them individually would have turned some of these
-runs green; fixing 1 and 2 would turn most of them green.
-
----
-
-## Reproducing
-
-```bash
-# the three-cause run
-node scripts/life-scenarios/run.mjs --model anthropic/claude-sonnet-5
-
-# the cheapest single reproduction of Cause 1
-node scripts/life-scenarios/run.mjs --only meal-plan --model anthropic/claude-sonnet-5
-grep -c "policy-blocked" target/life-scenarios/<run>/core.log
-wc -c target/life-scenarios/<run>/sandbox/meal-plan/out/*
-```
-
-The journals that back every quote above:
-
-```
-<run>/home/.openhuman/users/*/workspace/tinyagents_store/journal/session.*.messages.jsonl
-<run>/home/.openhuman/users/*/workspace/session_raw/*.jsonl # tool call arguments
-```
diff --git a/scripts/life-scenarios/FINDINGS.md b/scripts/life-scenarios/FINDINGS.md
deleted file mode 100644
index 1066705ca5..0000000000
--- a/scripts/life-scenarios/FINDINGS.md
+++ /dev/null
@@ -1,562 +0,0 @@
-# What the life-scenario suite found
-
-Everything below is reproducible with `node scripts/life-scenarios/run.mjs`.
-Run directories referenced by timestamp live under `target/life-scenarios/`.
-
-## The numbers
-
-Six scenarios, the shipping desktop path (`channel_web_chat` + SSE, the
-orchestrator agent, approval gate on), BYOK to OpenRouter.
-
-**`deepseek/deepseek-v4.1-flash`** (run `2026-09-22T20-10-53`):
-
-| scenario | done | tools | in | cached | out | cost | latency |
-| --- | --- | --- | --- | --- | --- | --- | --- |
-| calendar-buffer | 0/1 | 0 | 5.7k | 94% | 94 | $0.0040 | 14.0s |
-| subscription-scan | 0/1 | 0 | 5.7k | 0% | 69 | $0.0181 | 7.4s |
-| baggage-policy | 0/1 | 0 | 5.6k | 0% | 104 | $0.0185 | 8.4s |
-| meal-plan | 0/2 | 0 | 5.6k | 0% | 78 | $0.0181 | 11.7s |
-| trip-itinerary | 0/1 | 0 | 5.7k | 94% | 136 | $0.0047 | 10.2s |
-| fact-check-publish | 0/3 | 0 | 5.7k | 0% | 111 | $0.0188 | 7.0s |
-| **total** | **0/9 (0%)** | **0** | 34.1k | 31.5% | 592 | **$0.0822** | 58.7s |
-
-**`anthropic/claude-sonnet-5`** (run `2026-09-22T20-12-36`):
-
-| scenario | done | tools | appr | in | cached | out | cost | latency |
-| --- | --- | --- | --- | --- | --- | --- | --- | --- |
-| calendar-buffer | 0/1 | 1 | 0 | 26.8k | 57% | 3.7k | $0.0546 | 42.6s |
-| subscription-scan | 9/11 | 4 | 4 | 49.8k | 91% | 1.4k | $0.0483 | 30.4s |
-| baggage-policy | 0/1 | 21 | 0 | 298.4k | 39% | 7.2k | $0.6880 | 147.4s |
-| meal-plan | 3/10 | 11 | 7 | 224.5k | 54% | 33.0k | $0.7971 | 290.5s |
-| trip-itinerary | 0/1 | 14 | 9 | 200.0k | 64% | 35.0k | $0.7825 | 444.1s |
-| fact-check-publish | 0/3 | 14 | 3 | 142.5k | 86% | 2.5k | $0.1341 | 89.6s |
-| **total** | **12/27 (44%)** | **65** | **23** | 941.9k | 58.1% | 82.9k | **$2.5046** | 1044.6s |
-
-Read the two tables together. The cheap model never calls a tool at all — it
-narrates and stops, so it is not a measurement of the harness. The strong model
-*works*: 65 tool calls, sixteen minutes, $2.50. And **four of six scenarios
-produced no output file whatsoever**, after spending $0.69, $0.78 and $0.13 on
-three of them. Findings 1 and 1b are why; [`DIAGNOSIS.md`](DIAGNOSIS.md) traces each one to its transcript.
-
-### After finding 1 was fixed
-
-Same model, same six scenarios, after the fixes below
-(run `2026-09-23T11-25-37-650Z`):
-
-| scenario | done | tools | appr | in | cached | out | cost | latency |
-| --- | --- | --- | --- | --- | --- | --- | --- | --- |
-| calendar-buffer | **8/8** | 9 | 0 | 77.0k | 81.1% | 16.0k | $0.3028 | 146.8s |
-| subscription-scan | **11/11** | 6 | 0 | 47.9k | 90.4% | 1.3k | $0.0466 | 14.2s |
-| baggage-policy | 0/1 | 27 | 0 | 491.9k | 71.0% | 15.6k | $0.7671 | 192.3s |
-| meal-plan | **10/10** | 8 | 0 | 63.2k | 89.9% | 12.6k | $0.2254 | 91.7s |
-| trip-itinerary | 0/1 | 22 | 0 | 1,572.0k | 64.4% | 129.9k | $1.9648 | 900.0s |
-| fact-check-publish | 0/3 | 31 | 0 | 220.2k | 80.1% | 12.4k | $0.3709 | 263.1s |
-| **total** | **29/34 (85%)** | **103** | **0** | 2,472.2k | 68.8% | 187.9k | **$3.6776** | 1608.1s |
-
-**0/9 → 29/34.** The model that made *zero* tool calls in all six scenarios now
-makes 103, because there is finally something to call: `policy-blocked` events
-are **0**, `file_write` is on the wire (`visible=17`), and no 1-byte placeholder
-files are left behind.
-
-The `appr` column is 0 by design, not by omission: the autonomy policy now
-defaults to off, so `gate_decision` answers `Allow` for every class and nothing
-parks. Set `[autonomy] enabled = true` to measure the supervised arm.
-
-The three still at zero are **finding 1b**, untouched by that fix:
-`grep -c "final permitted model call"` is 2 (baggage-policy and
-fact-check-publish reach `max_model_calls=15` after real work), and
-trip-itinerary hit the suite's own 900s turn timeout.
-
-Note the cache column against finding 8 below — the 0% collapses are gone.
-
-### After finding 1b was fixed, and a note on reading these tables
-
-Two full runs, same model, back to back (`2026-09-23T15-49-06-514Z` and
-`2026-09-23T16-15-03-159Z`):
-
-| scenario | run A | run B | baseline above |
-| ------------------ | --------------- | --------------- | -------------- |
-| calendar-buffer | 0/1 | **8/8** | **8/8** |
-| subscription-scan | **11/11** | **11/11** | **11/11** |
-| baggage-policy | 0/1 | **8/9** | 0/1 |
-| meal-plan | **10/10** | 0/2 | **10/10** |
-| trip-itinerary | **10/11** | 0/1 | 0/1 |
-| fact-check-publish | 0/3 | **12/12** | 0/3 |
-| **total** | **31/37 (84%)** | **39/43 (91%)** | 29/34 (85%) |
-
-**Read the totals with care. The denominators are not comparable** — the grader
-stops at `output_exists`, so a scenario that writes nothing contributes `0/1`
-while the same scenario passing contributes `0/12`. A run can score a higher
-percentage by failing earlier.
-
-**And every scenario but `subscription-scan` flipped between A and B.** That is
-this model, not this change: `deepseek-v4.1-flash` intermittently ends a turn
-without emitting a tool call (calendar-buffer in run A stopped at 10 of 15
-calls, mid-sentence, having just said "let me verify the gap math before writing
-the output") or emits a malformed one (baggage-policy in run A: `validation
-error: tool web_fetch arguments.url is required`, repeated identically until the
-turn was stopped). Single-run comparisons on this model are not evidence of
-much, in either direction.
-
-What **is** evidence is the behaviour of the turns that actually reached the
-cap, which is the only thing finding 1b touches:
-
-| run | turns hitting `max_model_calls=15` | artifact written |
-| -------- | ---------------------------------- | ---------------- |
-| baseline | 2 (baggage, fact-check) | **0 of 2** |
-| isolated | 1 (baggage) | **1 of 1** — 9/9 |
-| run A | 1 (trip-itinerary) | **1 of 1** |
-| run B | 2 (baggage, fact-check) | **2 of 2** |
-
-Four capped turns since the fix, four artifacts. Before it, none. The three
-scenarios that had never once produced a file — baggage-policy, trip-itinerary,
-fact-check-publish — have each now done so, and fact-check-publish went straight
-from 0/3 to **12/12** (all three of its outputs) on the run where it capped.
-
-Ordered by severity.
-
----
-
-## 1. The assistant cannot reliably create a file — FIXED
-
-**Severity: high. The cause of four of the six empty scenarios.**
-
-**Fixed** by, in order of how much each mattered: unpacking `file_write` from
-the `files` pack (`tools/toolpacks/registry.rs`) so `close_handed_off_packs` can
-no longer deny the orchestrator its only file creator; granting the configured
-`action_dir` as a `ReadWrite` trusted root in `SecurityPolicy::from_config`;
-`strip_quoted_heredoc_bodies` (`policy_command/quoting.rs`), so a `&` in a
-`<< 'EOF'` body is data rather than a background operator; an `apply_patch`
-create mode (empty `old_string` on a path that does not exist); and
-`[autonomy] enabled`, now defaulting to `false`. See the post-fix table above.
-
-Four mechanisms compose so that the orchestrator has no working route to
-writing a new file. Full trace, with the transcript for each step, in
-[`DIAGNOSIS.md`](DIAGNOSIS.md) — summarised here:
-
-- **`action_dir` is the join base for relative tool paths but is not a
- permitted write root.** `is_resolved_path_allowed_for`
- (`security/policy/path_checks.rs`) allows `workspace_root` or a trusted root;
- `enforcement.rs:118-126` grants a trusted root for `default_projects_dir()`,
- which reads `OPENHUMAN_PROJECTS_DIR` and knows nothing about
- `OPENHUMAN_ACTION_DIR`. On a stock install the two coincide and this is
- invisible. **Change the working folder — `action_dir_override`, which is what
- the Settings control writes — and file-tool writes into it are refused**
- `Resolved path escapes workspace`, for a path inside the directory
- `CLAUDE.md` calls "the agent's permitted read and write root". Verified: also
- granting the dir via `OPENHUMAN_PROJECTS_DIR` took `policy-blocked` events
- from several to zero.
-- **`classify_command` rejects `&` inside a quoted heredoc body.** The blocked
- `cat > out/meal_plan.md << 'EOF'` contained four ampersands, every one of them
- in a recipe title ("Greek Chicken **&** Spinach Orzo Skillet"), and was
- refused as command substitution / background. `subscription-scan` wrote
- successfully with the identical heredoc shape and no `&` in its content.
- Ampersands are ordinary in prose, so `shell` is an unreliable writer for the
- documents an assistant produces.
-- **`use_skill` cannot reach `file_write`.** Withheld packs are documented as
- reachable through `use_skill`; for the orchestrator the `files` pack is
- *closed* by `close_handed_off_packs` (#6302), and the call returns
- "Skill `files` has no tools available in this session."
-- **`apply_patch` cannot create a file** — `` `old_string` must not be empty ``,
- and it canonicalizes the target, so the file must already exist.
-
-`meal-plan` spent 11 rounds and $0.80 cycling through all four and left two
-**1-byte files containing `x`** — the placeholder it created so `apply_patch`
-would have something to patch.
-
----
-
-## 1b. A capped turn withdraws every tool — PARTLY FIXED
-
-**Severity: medium.** Three scenarios reached `max_model_calls=15` — and
-reached it partly because of the above.
-
-**Fixed:** the half that silently destroyed the deliverable. The reporting half
-— a capped turn being indistinguishable from a finished one on the wire — is
-still open; see the end of this section.
-
-At the last permitted call, `FinalCallWrapUpMiddleware` clears
-`request.tools` (25 of them), sets `tool_choice = None`, and injects
-`MAX_ITER_CHECKPOINT_INSTRUCTION`: *"You have reached the maximum number of tool
-calls allowed for this single turn … report the substance of what this turn
-produced … close with a brief **Still to do** line."* The turn is then
-structurally unable to write anything, and the model correctly produces a
-status report.
-
-The mechanism is deliberate (#6014) and right for a turn whose product is
-*text*. It is exactly wrong for one whose product is a **file**: the model
-arrives at that call holding the finished content and has, structurally,
-nowhere to put it.
-
-`baggage-policy` is the clean demonstration. 27 tool calls of research, a
-correct summary of Delta's published limits in the reply — and
-`out/delta_baggage_guide.md` never written, so every grader check after
-`output_exists` was unreachable and it scored 0/1. The reply's own closing line
-was *"Still to do: … write `out/delta_baggage_guide.md`"*.
-
-**The fix.** One call earlier the belt is *narrowed* to the tools that can only
-write (`DELIVERABLE_TOOLS` = `file_write`, `apply_patch`) rather than left
-whole, with its own instruction saying gathering is over and that a file marking
-its own gaps honestly beats no file. `shell` is deliberately excluded: it can
-redirect into a file but can equally run a crawler, so keeping it would leave
-the belt effectively unnarrowed. The restoration of microcompact-cleared results
-that the conclusion already got now runs here too — a call asked to write
-findings down has to be able to read them.
-
-The trade is explicit: **a capped turn spends its second-to-last round
-persisting rather than gathering**, and a turn with nothing to persist loses
-that round. That is the same trade the final call already made, moved one step
-earlier. The alternative — leaving the belt intact and the instruction advisory
-— is what `FinalCallWrapUpMiddleware`'s own doc comment records as having
-already failed.
-
-Guarded to `max_model_calls >= 3` (below that, reserving would leave no round in
-which anything could be gathered to write) and to belts that actually carry a
-writer (telling a read-only agent that "the only tools left are the ones that
-write files" would simply be false).
-
-Measured, on the same scenario and model that produced the 0/1:
-
-```
-model_calls=14 max_model_calls=15 tools_withdrawn=24 tools_kept=2
- -> file_write out/delta_baggage_guide.md (4734 bytes, tool call 31 of 32)
-model_calls=15 max_model_calls=15 tools_withdrawn=26
- -> the conclusion, as before
-```
-
-**9/9, 100%**, 12 delta.com URLs cited. The turn still hit the cap — the
-reservation is precisely what turned it from a zero into a pass. The guide also
-marks the transatlantic Basic Economy fee "NOT STATED" rather than inventing it,
-which is what the prompt asked for and what the old run never got far enough to
-do.
-
-**Still open:** the other half of this finding — **the caller cannot tell.** `turn_run_finalize.rs:210` computes `hit_cap` and
-`flows/ops/builder.rs:336` consumes it, but `grep hit_cap` over `web_chat/`
-finds nothing and `TurnUsagePayload` (`openhuman-rpc/src/server/socketio.rs:353`) has no cap field.
-On the path the desktop app uses, a truncated turn arrives as an ordinary
-`chat_done` — indistinguishable from a complete answer except by reading the
-prose.
-
----
-
-## 2. `main` does not build — three vendor gitlinks point at non-ancestor commits
-
-**Severity: critical. Nothing in Rust compiles on `main`.**
-
-Commit `f74efad5d2` ("chore(deps): update vendor submodules for tinyagents,
-tinyjuice, and tinymcp") moved all three submodules to commits that are **not
-ancestors of their own upstream `main`**, and each is missing a symbol
-OpenHuman references:
-
-| submodule | pinned at | missing | referenced from |
-| --- | --- | --- | --- |
-| `vendor/tinyagents` | `6c3105e6` (side branch) | the whole `tinyagents-runtime` crate | `crates/openhuman-core/Cargo.toml:148` |
-| `vendor/tinyjuice` | `2f02042` (release tag) | `tinyjuice_bus::types::ReadIntent`, `compressors::html::html_to_markdown` | `inference/tokenjuice/schemas.rs:314`, `tools/impl/network/web_fetch.rs:250` |
-| `vendor/tinymcp` | `8b0627d` | `ConnectedServerOverview::instructions` | `agent/registry/agents/orchestrator/prompt.rs:437` |
-
-The `tinyagents` one fails at *manifest resolution*, so it is not a compile
-error you can work around — `cargo check`, `cargo build`, `cargo test` and
-`cargo metadata` all fail before any code is read:
-
-```
-error: failed to get `tinytools-jev` as a dependency of package `openhuman-cli`
- unable to update .../vendor/tinyagents/vendor/tinytools/crates/tinytools-jev
-```
-
-The previous pin (`8582277`, tinyagents upstream `main`) satisfies all three.
-This branch repins `tinyagents` → `8582277`, `tinyjuice` → `36e9657`,
-`tinymcp` → `fe34f5b`, all upstream `main`, and the workspace builds.
-
-**Worth a CI gate**: a `cargo metadata --no-deps` on every submodule bump would
-have caught this in seconds, and a check that each gitlink is an ancestor of
-its upstream default branch would have caught the cause.
-
----
-
-## 3. The replayed transcript carries no assistant tool calls
-
-**Severity: medium — confirmed for the persisted transcript, inferred for the
-live request.** See [`DIAGNOSIS.md`](DIAGNOSIS.md) for what is measured and
-what is not.
-
-Every assistant turn that made a tool call is persisted with **empty content
-and no `tool_calls`**, and the tool result comes back as a plain `user`
-message. From
-`workspace/tinyagents_store/journal/session.*_orchestrator_ls-subscript.messages.jsonl`:
-
-```
-0 system len=20638
-1 system len=467
-2 user len=1117 the task
-3 assistant len=0 tool_calls=false <-- the tool call is gone
-4 user len=806 "[Tool results] <tool_result id=...-model-1-tool-1>"
-5 assistant len=0 tool_calls=false <-- and again
-6 user len=4112 "[Tool results] ...-model-2-tool-1"
-...
-```
-
-So from round two on, the model is looking at a conversation in which results
-arrive for requests it cannot see it made. It has to infer its own actions from
-their output.
-
-A careful model notices and refuses. `calendar-buffer` on
-`anthropic/claude-sonnet-5` read the calendar successfully and then answered:
-
-> I wasn't able to complete this task. [...] I also have no tool record showing
-> `out/meeting_buffer_plan.json` was actually written — no `apply_patch` or
-> file-write call appears in what ran.
-
-That is a correct reading of the transcript it was given. (It also asserted the
-file read had been truncated, which was **not** true — the tool result in the
-journal is the complete 1,821-byte file. The structural complaint was right;
-that particular detail was a hallucination.)
-
-Result: one tool call, two model calls, `max_iterations=15` never approached,
-and no output file. Scenarios that happen to be linear enough survive it —
-`subscription-scan` scored 9/11 with the same transcript shape — but anything
-needing the model to verify its own work does not.
-
-Per `CLAUDE.md`, tool-call dialects and transcript replay belong to
-`vendor/tinyagents`, so **the fix is an upstream tinyagents-harness change**,
-not a host-side patch.
-
----
-
-## 4. Every provider call is written to the cost log twice
-
-**Severity: medium. The cost dashboard reports 2× tokens and 2× requests.**
-
-Six model calls across a six-scenario run produced **twelve** rows in
-`workspace/state/costs.jsonl` — each call once as `provider_charged` with the
-real amount and once as `estimated` with `cost_usd: 0.0`, same tokens, same
-second:
-
-```
-rows: 12 duplicate (in,out,second) groups: 6 of 6
-cost_source: {'provider_charged': 6, 'estimated': 6}
-sum tokens: 69,392 (actual: 34,696)
-```
-
-Two independent call sites record the same call:
-
-- `agent/tinyagents/observability/event_bridge.rs:401`
-- `agent/tinyagents/host/budget_gate.rs:292` (the `BudgetGate::record` impl)
-
-`turn_outcome.rs:110-113` documents the intended invariant — *"The bridge and
-this fallback are mutually exclusive, so spend is recorded exactly once either
-way"* — and the third site (`turn_run_finalize.rs:175`) does honour it. The
-budget gate is not covered by that reasoning.
-
-`total_cost_usd` survives only by luck: the duplicate happens to price at
-`0.0` (see finding 4). `request_count` and `total_tokens` are simply doubled.
-
----
-
-## 5. A model missing from the pricing catalog is billed at $0
-
-**Severity: medium. Budget enforcement silently stops working.**
-
-`cost::catalog::estimate_cost_usd` returned `0.0` for
-`deepseek/deepseek-v4.1-flash` — a current, chargeable OpenRouter model. The
-budget gate's own comment says pricing there is *"deliberately not skipped,
-because a zero-cost ledger would silently disable `check_budget` enforcement
-altogether"* — which is exactly what an unknown model produces.
-
-An unknown model should price at a conservative fallback, not zero.
-`FALLBACK_PRICING` already exists in `agent/cost.rs:47-53`; the catalog path
-does not reach it.
-
----
-
-## 6. `config.update_model_settings` accepted a BYOK config it could not honour — FIXED on this branch
-
-**Severity: medium. Every subsequent turn fails.**
-
-The field's own schema comment says:
-
-> `inference_url` — Custom OpenAI-compatible LLM endpoint. **When set together
-> with `api_key`, inference goes direct to this URL** instead of the OpenHuman
-> backend.
-
-Setting exactly those two succeeds. The next turn then dies:
-
-```
-[chat-factory] BYOK_INCOMPLETE: inference_url is set to a custom/direct
-endpoint (https://openrouter.ai/api/v1) but no matching cloud_providers entry
-was found for role 'chat'.
-```
-
-`provider_for_role` resolves through `cloud_providers`, never through
-`inference_url`. The caller had to *also* hand-build a `cloud_providers` entry
-whose endpoint matched and pin each agent-turn role to `<slug>:<model>` — a
-failure in a different subsystem, one call later, for a write the API accepted,
-and none of it discoverable from the error.
-
-**Fixed** by `complete_byok_route` in
-`crates/openhuman-core/src/config/ops/model.rs`: when `inference_url` and
-`api_key` both arrive non-blank and no entry matches the endpoint, register one
-and pin the four roles an agent turn runs on — the same completion
-`config/schema/ephemeral_route.rs::apply` already does for a single call. It is
-deliberately narrow: both halves required, an existing entry for that endpoint
-reused rather than duplicated, a blank `default_model` declined (the grammar is
-`<slug>:<model>`), and any role the same patch pinned — or that already points
-somewhere deliberate like `ollama:…` — left alone.
-
-Covered by `config/ops/model_byok_tests.rs` (9 tests), and end-to-end by
-`run.mjs`, which now sends only the three documented fields and routes.
-
----
-
-## 7. The default agent has no file tools on the wire
-
-**Severity: medium — a capability gap, and arguably intended.**
-
-A default orchestrator turn advertises 16 tools:
-
-```
-[agent] tool spec filter: total=232 visible=16 names=[shell, apply_patch,
-spawn_async_subagent, list_subagents, continue_subagent, todo, resolve_time,
-memory_store, memory_recall, update_memory_md, goal_complete, http_request,
-web_fetch, web_search_tool, composio_connect, use_skill]
-[toolpacks] withheld packed tool schemas; use_skill advertised instead hidden=23
-```
-
-No `file_read`, `file_write`, `grep`, `glob` or `list`. `ToolGroups::default()`
-puts every pack in `Withheld`, so reading a file means `shell` (`cat`) or a
-`use_skill` round-trip. That is a deliberate prompt-budget decision and it is
-documented — but for the single most common assistant task, "read this file and
-write that one", it costs an extra hop and pushes work into a shell the sandbox
-then has to police.
-
-`--driver rpc --agent life_scenarios` runs the same scenarios with the file
-tools named explicitly, for comparison.
-
----
-
-## 8. Prompt-cache hit rate collapses between turns
-
-**Severity: medium. 4× cost difference, same work.**
-
-Six consecutive turns on `deepseek/deepseek-v4.1-flash`, identical ~21 KB
-system prompt, each a fresh thread:
-
-| scenario | input | cached | cost |
-| --- | --- | --- | --- |
-| calendar-buffer | 5.7k | **94%** | $0.0040 |
-| subscription-scan | 5.7k | 0% | $0.0181 |
-| baggage-policy | 5.6k | 0% | $0.0185 |
-| meal-plan | 5.6k | 0% | $0.0181 |
-| trip-itinerary | 5.7k | **94%** | $0.0047 |
-| fact-check-publish | 5.7k | 0% | $0.0188 |
-
-The uncached turns cost **4.5×** the cached ones for the same prompt. Part of
-this is provider-side routing (OpenRouter can move a request between backends,
-and `served_by` drift breaks the prefix cache), which is why the repo ships
-`scripts/debug/capture-first-inference.mjs` — its `cache_key` / `served_by`
-lines are the right next instrument here.
-
-### The collapses are gone, and that is a measurement artefact worth naming
-
-Same six scenarios after the finding-1 fixes
-(run `2026-09-23T11-25-37-650Z`):
-
-| scenario | input | cached | cost |
-| --- | --- | --- | --- |
-| calendar-buffer | 77.0k | 81.1% | $0.3028 |
-| subscription-scan | 47.9k | **90.4%** | $0.0466 |
-| baggage-policy | 491.9k | 71.0% | $0.7671 |
-| meal-plan | 63.2k | 89.9% | $0.2254 |
-| trip-itinerary | 1,572.0k | **64.4%** | $1.9648 |
-| fact-check-publish | 220.2k | 80.1% | $0.3709 |
-| **total** | 2,472.2k | **68.8%** | **$3.6776** |
-
-No 0% rows, and the floor is 64.4% against an overall 31.5% before. **Do not
-read that as the caching bug being fixed** — nothing here touched inference
-routing. The honest reading is that the baseline was measuring something else:
-those turns were one or two model calls long (0 tool calls, ~5.7k input), so a
-single cold call *was* the whole scenario and one `served_by` miss showed up as
-0%. These turns are 6–31 tool calls over 48k–1.6M input tokens, so a cold first
-call is amortised across many warm ones and the per-scenario number is dominated
-by the steady state.
-
-What that does establish is the steady state itself, which the baseline could
-not: the prefix cache **does** hold across the turns of one thread, at 64–90%.
-The open question from this finding is unchanged and still needs the capture
-proxy — whether `cache_key` stays identical and `served_by` stops drifting
-*within* a thread. The first call of each scenario is still cold, and at these
-prompt sizes that is now the expensive part.
-
----
-
-## 9. A turn with no hosted session retries a failing backend call ~3× per turn
-
-**Severity: low in the product. Was severe in this rig — see below.**
-
-With no hosted session, every orchestrator roster build calls
-`GET /agent-integrations/composio/toolkits`, gets 401, and logs it:
-
-```
-[backend_api] 401 on GET /teams/me/usage — session token rejected
-[integrations] backend rejected session JWT (401) path=/agent-integrations/composio/toolkits
-[composio] fetch_connected_integrations: list_toolkits (backend) failed: SESSION_EXPIRED
-[orchestrator_tools] assembled 20 delegation tool(s) ... (0 integrations connected)
-```
-
-That block repeats three times per turn — the roster is rebuilt once per
-`build`, and nothing negative-caches the 401 for the life of the turn. Measured
-cost: ~3 s of a 5 s pre-inference window.
-
-**The same 401 was not low-severity for `web_search_tool`, and that was the
-rig's fault.** `web_search_tool` posts to `/agent-integrations/parallel/search`
-on the same hosted backend, so it too came back `SESSION_EXPIRED` every time —
-but it was advertised to the model anyway (`tool spec filter: … web_search_tool`
-among 17 visible). So the model spent calls discovering the tool was dead and
-then routed around it by hand: in the 2026-09-23 run `baggage-policy` burned two
-calls on the 401s, improvised a DuckDuckGo HTML scrape, guessed delta.com paths
-and collected four 404s. That is most of how it reached the cap in finding 1b.
-
-Offering a capability the run's own configuration cannot serve is a defect in
-the benchmark, not the product. `mock-search.mjs` now serves that one route
-locally, **mocking discovery but not retrieval**: it ranks a fixture corpus of
-*real* URLs the agent still fetches over the network for itself, so the
-`cites_delta_com` and dimension checks stay honest. The README covers why it
-takes over the whole backend base, and the two things that were easy to get
-wrong — the per-user config dir race (`api_url` in `config.toml` loses to
-`users/<runtime-id>/config.toml`, so the override rides `BACKEND_URL`) and the
-`{ success, data }` envelope `parse_envelope` requires (a bare payload fails as
-`missing field 'success'`, which reads to the agent as a broken tool rather than
-an empty result — it gave up after six tries).
-
----
-
-## 10. Smaller things
-
-- **`AgentDefinition.system_prompt` rejects the spelling its own error
- suggests.** `system_prompt = "..."` fails to parse, because `PromptSource`
- deserializes as an externally-tagged enum and the accepted form is the table
- `[system_prompt] inline = '''...'''`. The validation error you get instead
- reads *"missing `system_prompt` — custom definitions must set an inline
- string or a file path"*, which describes the spelling that does not work.
-- **`approval.decide` param errors are fully redacted.** Calling it with `id`
- instead of `request_id` logs `param-validation error (message redacted;
- skip-report)` and nothing else — no field name, no expectation. A headless
- caller sees only that approvals silently stop being granted while the turn
- parks.
-- **`direct` Composio needs three things together, two undocumented.**
- `[composio] mode = "direct"` in config, **both**
- `OPENHUMAN_COMPOSIO_DIRECT_BASE_V2` and `..._V3` (the match arm is
- `(Some, Some)`; one alone silently falls through to production URLs), and a
- **debug** build (the override is `#[cfg(debug_assertions)]`-gated in
- `integrations/composio/client/factory.rs:93`). See this directory's README.
-- **`composio_list_tools` returns `{"tools":[]}` in direct mode** by
- short-circuit (`integrations/composio/tools/list_tools.rs:152-168`), so an
- agent on a direct connection cannot discover what it may call.
-
-## 11. Two things about this machine, not the codebase
-
-- The operator's `~/.openhuman/config.toml` has
- `api_url = "http://127.0.0.1:18473"`, a capture proxy that is not running, so
- the desktop app's backend calls currently all fail.
-- `~/.openhuman/dev-keychain.json` holds dozens of keys prefixed
- `.tmpXXXXXX:` (`.tmpobNPzo:auth:openai:default`, …) — test temp workspaces
- leaking into the operator's real keychain rather than their own.
diff --git a/scripts/life-scenarios/README.md b/scripts/life-scenarios/README.md
deleted file mode 100644
index 0706f0874d..0000000000
--- a/scripts/life-scenarios/README.md
+++ /dev/null
@@ -1,228 +0,0 @@
-# Life-scenario harness benchmark
-
-Six everyday assistant tasks, calendar triage, receipt scanning, live web
-research, planning, multi-source synthesis, and a fact-check-and-publish
-pipeline, run against the real OpenHuman core ([`crates/openhuman-core/`](../../crates/openhuman-core/README.md)) and scored on what actually
-landed on disk.
-
-It answers one question: **how much of a realistic task does the shipping
-harness finish, and what does that cost in tokens, cache, money and time?**
-
-```bash
-# everything, on the shipping desktop path
-node scripts/life-scenarios/run.mjs
-
-# one scenario, a stronger model
-node scripts/life-scenarios/run.mjs --only calendar-buffer --model anthropic/claude-sonnet-5
-
-# the comparison arm: a custom agent definition with file tools advertised
-node scripts/life-scenarios/run.mjs --driver rpc --agent life_scenarios
-
-# re-score an old run without spending anything
-node scripts/life-scenarios/run.mjs --grade-only target/life-scenarios/<run-id>
-```
-
-The driver is [`run.mjs`](./run.mjs) and the scenarios are defined in [`scenarios.mjs`](./scenarios.mjs). Requires a built core (`cargo build --manifest-path Cargo.toml -p openhuman-cli
---bin openhuman-core`) and `OPENROUTER_API_KEY` in the environment.
-
-## Headless, but shaped like the desktop app
-
-The default `--driver desktop` drives the core the way the Tauri composer
-does, with the UI removed and nothing else changed:
-
-| desktop app | here |
-| --- | --- |
-| Tauri spawns the core as a tokio task | spawn [`openhuman-core serve`](../../crates/openhuman-cli/README.md) |
-| composer calls `openhuman.channel_web_chat` | same RPC, same params |
-| reply streams over Socket.IO | same events over `GET /events` |
-| orchestrator agent, every tool pack withheld | same, no custom definition |
-| approval gate ON, a human clicks Approve | gate ON, a responder approves |
-| BYOK set in Settings → Models | `config.update_model_settings` |
-| signed-in session | offline local session |
-
-Three things are deliberately *not* the app, and each buys reproducibility:
-
-- **Its own `HOME`.** `default_root_openhuman_dir` resolves `<home>/.openhuman`,
- so config, keyring, auth profiles, workspace and session db all land in the
- run directory. A run cannot read or corrupt the operator's install, and
- installing a credential into a shared `~/.openhuman` would sign a running
- desktop app out.
-- **BYOK inference, not the hosted backend.** A benchmark whose price and
- availability belong to someone else is not a benchmark. `--managed` opts
- back into the account's own configured route.
-- **A mock Composio.** See below.
-- **A mock search backend.** See below.
-
-`--driver rpc` switches to `openhuman.inference_agent_chat`, the only path that
-can scope a per-turn `cwd` and name an `agent_id`. That is the comparison arm,
-not the product path.
-
-## The corpus is fictional
-
-Everything under [`fixtures/`](./fixtures) is invented: one persona (Alex Rivera
-`<[email protected]>`), eleven mail messages, a seven-event calendar day,
-a generated PDF hotel booking, and a draft article. Every domain is
-`*.example`. Nothing here came from a real mailbox, calendar or bank, so the
-whole corpus is safe to commit and a run is repeatable.
-
-The fixtures are anchored to **2026-09-22** as "today"; the scenario prompts
-say so explicitly rather than relying on the clock.
-
-Each scenario gets a fresh copy of the whole corpus in
-`target/life-scenarios/<run-id>/sandbox/<scenario-id>/`, which is the agent's
-action directory. Outputs are expected under `out/`.
-
-### Mock Composio
-
-Scenarios 1, 2 and 5 are *about* mail and calendar. Stubbing those out would
-benchmark the wrong thing, and the real Composio needs live consumer accounts,
-costs quota and is not reproducible. So [`mock-composio.mjs`](./mock-composio.mjs) serves Composio's
-wire shape over the same fixtures the file tools see: `GMAIL_FETCH_EMAILS`
-returns the fixture mailbox in Gmail's message shape,
-`GOOGLECALENDAR_EVENTS_LIST` returns the fixture calendar in Google's event
-shape, and the write actions (`GMAIL_SEND_EMAIL`, `GOOGLECALENDAR_UPDATE_EVENT`)
-record what the agent *tried* to do into `composio-outbox.json` instead of
-doing it, so a grader can assert on the attempt.
-
-Wiring it up needs three things together, and two of them are easy to miss:
-
-1. `[composio] mode = "direct"` in `config.toml`. `create_composio_client`
- dispatches on that field alone; in the default `backend` mode the env
- override is never consulted.
-2. **Both** `OPENHUMAN_COMPOSIO_DIRECT_BASE_V2` and `..._V3`. The match arm is
- `(Some, Some)`, setting only one silently falls through to the production
- Composio URLs.
-3. A **debug** build. The env override in
- [`integrations/composio/client/factory.rs`](../../crates/openhuman-core/src/integrations/composio/client/factory.rs) is `#[cfg(debug_assertions)]`-gated.
-
-### Mock search
-
-`web_search_tool` is not a local tool: it posts to
-`/agent-integrations/parallel/search` on the hosted backend, which resolves the
-query against a paid provider and bills the caller's team. This run has no
-session to spend, inference is BYOK and the credential is an offline local
-token, so every call came back `SESSION_EXPIRED … 401 Invalid token`.
-
-The tool was advertised anyway, so the model spent calls discovering it was dead
-and then routed around it by hand. In the 2026-09-23 run `baggage-policy` burned
-two calls on the 401s, improvised a DuckDuckGo HTML scrape, guessed delta.com
-paths and collected four 404s, then hit the 15-call cap with the answer
-assembled and the requested file unwritten, scoring 0/1. Offering a capability
-the run's own configuration cannot serve is a defect in the rig.
-
-[`mock-search.mjs`](./mock-search.mjs) fixes it by **mocking discovery, not retrieval**. It ranks the
-fixture corpus in [`fixtures/search-index.json`](./fixtures/search-index.json) and returns *real, live* URLs; the
-agent still fetches every page over the network with `web_fetch` and still has to
-read what the page says. So `baggage-policy`'s `cites_delta_com` and
-`states_carryon_dimensions` checks stay honest, what is gone is the search
-engine the run cannot pay for, not the comprehension being measured. Excerpts in
-the fixture stop short of the numbers the graders assert on, so an agent that
-answers from the excerpt alone still fails.
-
-Ranking is deliberately crude (weighted term overlap over keywords, title, URL
-and excerpt). A query the corpus does not cover returns **nothing** rather than
-the least-bad rows: a confidently wrong result set is worse for the agent than an
-empty one, because it spends fetches on it.
-
-Three things were easy to get wrong, and all three cost a run:
-
-1. **It has to take over the whole backend base.** `api_url` is the single base
- every backend caller resolves through ([`openhuman_tinyhumans::backend::url::effective_backend_api_url`](../../crates/openhuman-tinyhumans/src/backend/url.rs)).
- Loopback on an ephemeral port is what makes that work:
- `looks_like_local_ai_endpoint` treats loopback as an inference signal only
- when paired with an LLM-ish port or path, so a bare `http://127.0.0.1:<random>`
- passes through as a backend override.
-2. **`api_url` in `config.toml` is not enough.** `auth.set_credential` activates
- a per-user config dir whose id the core derives at runtime; `prepareHome`
- writes `users/local/`, the core activates `users/local-dragonfly/`, finds no
- `api_url` there and falls back to the hosted backend. The override that
- actually holds is `BACKEND_URL`, which `api_base_from_env` reads whichever
- config wins.
-3. **Every response needs the `{ success, data }` envelope.**
- [`integrations/client/errors.rs::parse_envelope`](../../crates/openhuman-core/src/integrations/client/errors.rs) unwraps it. A bare payload
- fails as `missing field 'success'`, and fails late enough to read as a
- broken tool rather than an empty result, so the agent abandons the task. It
- did exactly that, six times in a row.
-
-The other backend calls the run cannot authenticate (`/teams/me/usage`, the
-Composio toolkit list) get benign stubs, so the log shows the run's own
-behaviour rather than one fixed auth failure repeated every turn. Composio is
-untouched: it is redirected separately over `OPENHUMAN_COMPOSIO_DIRECT_BASE_V*`.
-
-`--no-mock-search` opts out and dials the hosted backend.
-
-Self-test: [`scripts/__tests__/life-scenarios-mock-search.test.mjs`](../__tests__/life-scenarios-mock-search.test.mjs).
-
-## Approvals are answered, not switched off
-
-The gate is installed and an `ApprovalResponder` answers it, it polls
-`approval.list_pending` and answers `approve_once`, exactly as the approval card
-does, recording every decision to `approvals.json`. A headless harness that sets
-`OPENHUMAN_APPROVAL_GATE=0` is measuring a product nobody runs; one that leaves
-the gate unanswered is measuring the ten-minute deny timeout.
-
-**How many approvals a task needed is itself a result.** A task that parks
-fourteen times is not one a supervised user would enjoy, however good the final
-artifact is. `--no-approvals` uninstalls the gate instead, for comparison.
-
-Expect that number to be near zero on the default run, and read it as a
-property of the product rather than of the harness: the shipped autonomy policy
-is **off** (`[autonomy] enabled = false`), so `gate_decision` answers `Allow`
-for every class and almost nothing parks. Flip `enabled = true` in
-`prepareHome`'s config block to measure the supervised arm, where the responder
-does the work the approval card would.
-
-## Grading
-
-"The turn completed" is not completion. A model that writes a plausible CSV
-full of invented rows has to score zero on the rows it invented, so every
-grader checks facts that are only derivable from the fixtures:
-
-- `calendar-buffer`, exactly three gaps under 15 minutes exist (`ev-02` at 0
- min, `ev-05` at 0, `ev-06` at **10**: the one that catches a model matching
- on "back-to-back" rather than "under fifteen"), and `ev-07` is a solo focus
- block that must *not* be flagged.
-- `subscription-scan`, four real subscriptions among a one-off order, a
- usage-based utility bill, a phishing mail and a bank alert that duplicates a
- receipt already counted. Only StreamFlix rose in price (13.99 → 15.99).
-- `baggage-policy`, the only scenario that leaves the sandbox. Demands cited
- `delta.com` URLs, so a model answering from memory is detectable.
-- `meal-plan`, five days, prep under 30 minutes, no duplicate grocery lines,
- and spinach/feta/olive oil each reused across at least two dinners.
-- `trip-itinerary`, facts that exist *only* inside the binary PDF (hotel name,
- address, phone), plus the flight code from the mail, plus a live weather
- source. 14 October is spent in the air and must not be scheduled.
-- `fact-check-publish`, one asset referenced by the draft is missing from
- disk and one hyperlink does not resolve; both must be named in the lint
- report and must not survive into either output.
-
-Scores are `passed/total` checks. Failed check ids are printed with the detail
-that explains them.
-
-## Output
-
-```
-target/life-scenarios/<run-id>/
- results.json per-scenario usage, grade, tool calls, files written
- approvals.json every approval decision the responder made
- composio-outbox.json writes the agent attempted through Composio
- composio-requests.json every request the mock received
- search-requests.json every query the mock search served, and what it matched
- core.log the core's own log for the whole run
- home/ the throwaway HOME (config, keyring, workspace)
- sandbox/<scenario>/ the corpus copy the agent worked in
-```
-
-## Known harness findings this suite surfaced
-
-- [`FINDINGS.md`](FINDINGS.md), the defect list, ranked, with the fix each wants.
-- [`DIAGNOSIS.md`](DIAGNOSIS.md), the causal trace behind the headline result
- (four of six scenarios wrote nothing), tool call by tool call, including the
- two claims from the first pass that did not survive checking.
-
-## See also
-
-- [`scripts/memory-scenarios/`](../memory-scenarios/README.md), the sibling harness for memory flows.
-- [Agent harness](../../gitbooks/developing/architecture/agent-harness.md) and [Approval gate](../../gitbooks/features/approval-gate.md), the product behavior being measured.
-- [Native tools](../../gitbooks/features/native-tools/README.md) and [Third-party integrations](../../gitbooks/features/integrations/README.md).
-- [`scripts/README.md`](../README.md).
diff --git a/scripts/life-scenarios/agent-life-scenarios.toml b/scripts/life-scenarios/agent-life-scenarios.toml
deleted file mode 100644
index d83c844dc4..0000000000
--- a/scripts/life-scenarios/agent-life-scenarios.toml
+++ /dev/null
@@ -1,63 +0,0 @@
-# The benchmark agent for the life-scenario suite.
-#
-# It exists because a DEFAULT orchestrator turn cannot do these tasks: every
-# tool pack ships in `GroupMode::Withheld` (crates/openhuman-core/src/tools/
-# toolpacks/groups.rs), so `file_read`, `file_write`, `grep`, `glob` and `list`
-# are never put on the wire. A default turn sees 16 tools, none of which read
-# or write a file directly. Naming the tools here is what a real embedder does
-# through `AgentSpec`; `run.mjs --agent default` runs the unmodified
-# orchestrator alongside it for comparison.
-#
-# Note `[system_prompt]` is a TABLE. `PromptSource` deserializes as an
-# externally-tagged enum, so `system_prompt = "..."` fails to parse — and the
-# error you get back ("must set an inline string or a file path") reads as
-# though a bare string were exactly the right spelling.
-
-id = "life_scenarios"
-display_name = "Life Scenarios"
-when_to_use = "Benchmark agent for the life-scenario suite."
-
-# The scenarios are multi-file and multi-step; the orchestrator's default cap
-# of 15 iterations is not enough to read a mailbox and write three artifacts.
-max_iterations = 40
-iteration_policy = "strict"
-timeout_secs = 900
-
-# Nothing in the corpus should be recalled from, or written to, the operator's
-# memory — the fixtures are the only context a scenario is allowed to use.
-omit_memory_context = true
-
-[system_prompt]
-inline = '''
-You are a capable personal assistant working inside a sandbox directory.
-
-Do the work rather than describing it. Read the files you are given before
-answering, and write every artifact the task asks for to the exact path it
-names. Paths in the task are relative to your working directory.
-
-Never invent a fact you could have read from a file or fetched from the web.
-If something cannot be determined, say so in the output instead of guessing.
-
-When you are done, verify that every requested file exists on disk with the
-requested content before you answer.
-'''
-
-[tools]
-named = [
- "file_read",
- "file_write",
- "apply_patch",
- "grep",
- "glob",
- "list",
- "shell",
- "web_search_tool",
- "web_fetch",
- "http_request",
- "resolve_time",
- "todo",
- "use_skill",
- "composio_execute",
- "composio_list_connections",
- "goal_complete",
-]
diff --git a/scripts/life-scenarios/fixtures/calendar/calendar.json b/scripts/life-scenarios/fixtures/calendar/calendar.json
deleted file mode 100644
index 73e6eafd6d..0000000000
--- a/scripts/life-scenarios/fixtures/calendar/calendar.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "owner": "Alex Rivera <[email protected]>",
- "timezone": "America/New_York",
- "generated_for": "2026-09-23",
- "events": [
- { "id": "ev-01", "title": "Engineering standup", "start": "2026-09-23T09:00:00-04:00", "end": "2026-09-23T09:30:00-04:00", "organizer": "[email protected]", "attendees": ["[email protected]", "[email protected]"] },
- { "id": "ev-02", "title": "Design review: onboarding", "start": "2026-09-23T09:30:00-04:00", "end": "2026-09-23T10:15:00-04:00", "organizer": "[email protected]", "attendees": ["[email protected]", "[email protected]"] },
- { "id": "ev-03", "title": "1:1 with Priya", "start": "2026-09-23T11:00:00-04:00", "end": "2026-09-23T11:45:00-04:00", "organizer": "[email protected]", "attendees": ["[email protected]", "[email protected]"] },
- { "id": "ev-04", "title": "Q4 roadmap sync", "start": "2026-09-23T13:00:00-04:00", "end": "2026-09-23T14:00:00-04:00", "organizer": "[email protected]", "attendees": ["[email protected]", "[email protected]"] },
- { "id": "ev-05", "title": "Vendor call: Northwind", "start": "2026-09-23T14:00:00-04:00", "end": "2026-09-23T14:45:00-04:00", "organizer": "[email protected]", "attendees": ["[email protected]", "[email protected]"] },
- { "id": "ev-06", "title": "Sprint retro", "start": "2026-09-23T14:55:00-04:00", "end": "2026-09-23T15:40:00-04:00", "organizer": "[email protected]", "attendees": ["[email protected]", "[email protected]"] },
- { "id": "ev-07", "title": "Focus block (no attendees)","start": "2026-09-23T16:30:00-04:00", "end": "2026-09-23T17:30:00-04:00", "organizer": "[email protected]", "attendees": ["[email protected]"] }
- ]
-}
diff --git a/scripts/life-scenarios/fixtures/documents/hotel_booking_tokyo.pdf b/scripts/life-scenarios/fixtures/documents/hotel_booking_tokyo.pdf
deleted file mode 100644
index 01d7bd1a70..0000000000
Binary files a/scripts/life-scenarios/fixtures/documents/hotel_booking_tokyo.pdf and /dev/null differ
diff --git a/scripts/life-scenarios/fixtures/drafts/draft.md b/scripts/life-scenarios/fixtures/drafts/draft.md
deleted file mode 100644
index 5138338711..0000000000
--- a/scripts/life-scenarios/fixtures/drafts/draft.md
+++ /dev/null
@@ -1,44 +0,0 @@
----
-title: "Why Remote Teams Still Struggle With Handoffs"
-author: "Alex Rivera"
-date: "2026-09-20"
-hero_image: "./images/handoff-hero.png"
----
-
-# Why Remote Teams Still Struggle With Handoffs
-
-Remote work is no longer an experiment. As of 2021, roughly 25% of all paid
-workdays in the United States were done from home, and most forecasts at the
-time expected that number to keep climbing.
-
-Yet the handoff — the moment one person's work becomes another person's input —
-is still where remote teams lose the most time.
-
-## The cost of a bad handoff
-
-A widely cited study found that knowledge workers spend about 60% of their time
-on "work about work": status updates, chasing context, and hunting for files.
-See the [Anatomy of Work Index](https://asana.com/resources/anatomy-of-work)
-for the methodology.
-
-The situation is worse across time zones. When a handoff misses its window, the
-work does not slip by an hour; it slips by a full working day.
-
-![Handoff latency by team size](./images/handoff-latency-chart.png)
-
-## Three things that actually help
-
-1. **Write the handoff, do not say it.** A message in a channel is searchable.
- A call is not.
-2. **State the next decision, not the status.** "Blocked on the pricing call"
- is useful. "80% done" is not.
-3. **Attach the artifact.** The single most common failure is a handoff that
- references a document nobody linked.
-
-Further reading: our [earlier piece on async standups](https://example.com/blog/async-standups-2019)
-covers the mechanics.
-
-## What we are trying next
-
-We are moving to a written-first handoff template for every cross-team task
-this quarter. I will report back with numbers.
diff --git a/scripts/life-scenarios/fixtures/drafts/images/handoff-hero.png b/scripts/life-scenarios/fixtures/drafts/images/handoff-hero.png
deleted file mode 100644
index e99b4567bb..0000000000
--- a/scripts/life-scenarios/fixtures/drafts/images/handoff-hero.png
+++ /dev/null
@@ -1,3 +0,0 @@
-�PNG
-
--- placeholder --
\ No newline at end of file
diff --git a/scripts/life-scenarios/fixtures/mailbox/2026-08-01-gympass.txt b/scripts/life-scenarios/fixtures/mailbox/2026-08-01-gympass.txt
deleted file mode 100644
index 6ba3f8a017..0000000000
--- a/scripts/life-scenarios/fixtures/mailbox/2026-08-01-gympass.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-Date: Sat, 01 Aug 2026 09:00:12 -0400
-Subject: GymPass membership renewed
-
-Your GymPass membership has renewed.
-
-Membership: All-Club (monthly)
-Amount: $45.00
-Date: August 1, 2026
diff --git a/scripts/life-scenarios/fixtures/mailbox/2026-08-03-streamflix.txt b/scripts/life-scenarios/fixtures/mailbox/2026-08-03-streamflix.txt
deleted file mode 100644
index 57c6096c4d..0000000000
--- a/scripts/life-scenarios/fixtures/mailbox/2026-08-03-streamflix.txt
+++ /dev/null
@@ -1,12 +0,0 @@
-Date: Mon, 03 Aug 2026 06:12:04 -0400
-Subject: Your StreamFlix receipt
-
-Thanks for being a StreamFlix member.
-
-Plan: Standard (monthly)
-Amount charged: $13.99
-Billing date: August 3, 2026
-Next billing date: September 3, 2026
-Payment method: Visa ending 4412
diff --git a/scripts/life-scenarios/fixtures/mailbox/2026-09-01-gympass.txt b/scripts/life-scenarios/fixtures/mailbox/2026-09-01-gympass.txt
deleted file mode 100644
index c08e91f095..0000000000
--- a/scripts/life-scenarios/fixtures/mailbox/2026-09-01-gympass.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-Date: Tue, 01 Sep 2026 09:00:44 -0400
-Subject: GymPass membership renewed
-
-Your GymPass membership has renewed.
-
-Membership: All-Club (monthly)
-Amount: $45.00
-Date: September 1, 2026
diff --git a/scripts/life-scenarios/fixtures/mailbox/2026-09-03-bank-alert.txt b/scripts/life-scenarios/fixtures/mailbox/2026-09-03-bank-alert.txt
deleted file mode 100644
index c60db40aa4..0000000000
--- a/scripts/life-scenarios/fixtures/mailbox/2026-09-03-bank-alert.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-Date: Thu, 03 Sep 2026 06:11:30 -0400
-Subject: Card transaction alert
-
-A transaction was authorized on your First Harbor card ending 4412.
-
-Merchant: STREAMFLIX
-Amount: $15.99
-Date: Sep 3, 2026
diff --git a/scripts/life-scenarios/fixtures/mailbox/2026-09-03-streamflix.txt b/scripts/life-scenarios/fixtures/mailbox/2026-09-03-streamflix.txt
deleted file mode 100644
index 667565654e..0000000000
--- a/scripts/life-scenarios/fixtures/mailbox/2026-09-03-streamflix.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-Date: Thu, 03 Sep 2026 06:10:51 -0400
-Subject: Your StreamFlix receipt
-
-Thanks for being a StreamFlix member.
-
-Plan: Standard (monthly)
-Amount charged: $15.99
-Billing date: September 3, 2026
-Next billing date: October 3, 2026
-Payment method: Visa ending 4412
-
-Note: as announced in July, the Standard plan price changed this cycle.
diff --git a/scripts/life-scenarios/fixtures/mailbox/2026-09-05-mealbox.txt b/scripts/life-scenarios/fixtures/mailbox/2026-09-05-mealbox.txt
deleted file mode 100644
index dc9f044ad4..0000000000
--- a/scripts/life-scenarios/fixtures/mailbox/2026-09-05-mealbox.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-Date: Sat, 05 Sep 2026 18:41:09 -0400
-Subject: Your MealBox order #88123 has shipped
-
-One-time order confirmation. This is not a recurring plan; you are on the
-"order when you want" setting.
-
-Order total: $32.40
-Order date: September 5, 2026
diff --git a/scripts/life-scenarios/fixtures/mailbox/2026-09-08-newsdaily.txt b/scripts/life-scenarios/fixtures/mailbox/2026-09-08-newsdaily.txt
deleted file mode 100644
index 9f97a5d6ce..0000000000
--- a/scripts/life-scenarios/fixtures/mailbox/2026-09-08-newsdaily.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-Date: Tue, 08 Sep 2026 07:30:00 -0400
-Subject: NewsDaily annual subscription confirmation
-
-Your NewsDaily Digital annual subscription has been renewed.
-
-Term: 12 months (annual)
-Amount: $79.00
-Charged: September 8, 2026
-Renews: September 8, 2027
diff --git a/scripts/life-scenarios/fixtures/mailbox/2026-09-10-utility.txt b/scripts/life-scenarios/fixtures/mailbox/2026-09-10-utility.txt
deleted file mode 100644
index 78b5d6cff1..0000000000
--- a/scripts/life-scenarios/fixtures/mailbox/2026-09-10-utility.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-Date: Thu, 10 Sep 2026 11:02:00 -0400
-Subject: Your Metro Electric bill is ready
-
-Statement period: Aug 8 - Sep 8, 2026
-Amount due: $88.20
-Due date: September 28, 2026
-This amount varies each month with usage.
diff --git a/scripts/life-scenarios/fixtures/mailbox/2026-09-12-clouddrive.txt b/scripts/life-scenarios/fixtures/mailbox/2026-09-12-clouddrive.txt
deleted file mode 100644
index cc3be262a7..0000000000
--- a/scripts/life-scenarios/fixtures/mailbox/2026-09-12-clouddrive.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-Date: Sat, 12 Sep 2026 03:22:10 -0400
-Subject: CloudDrive Pro - payment received
-
-Payment received for CloudDrive Pro.
-
-Subscription: Pro 2TB, billed monthly
-Amount: $9.99
-Payment date: September 12, 2026
diff --git a/scripts/life-scenarios/fixtures/mailbox/2026-09-14-promo.txt b/scripts/life-scenarios/fixtures/mailbox/2026-09-14-promo.txt
deleted file mode 100644
index 6651d7f568..0000000000
--- a/scripts/life-scenarios/fixtures/mailbox/2026-09-14-promo.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-Date: Mon, 14 Sep 2026 22:14:00 -0400
-Subject: URGENT: confirm your PremiumVault renewal of $49.99
-
-Your PremiumVault subscription could not be verified. Confirm your card
-details at http://streamflix-billing-support.example/verify within 24 hours
-or your account will be suspended.
diff --git a/scripts/life-scenarios/fixtures/mailbox/2026-09-18-flight.txt b/scripts/life-scenarios/fixtures/mailbox/2026-09-18-flight.txt
deleted file mode 100644
index 409f580045..0000000000
--- a/scripts/life-scenarios/fixtures/mailbox/2026-09-18-flight.txt
+++ /dev/null
@@ -1,20 +0,0 @@
-Date: Fri, 18 Sep 2026 14:05:22 -0400
-Subject: Your Pacific Air itinerary - confirmation QK7F2P
-
-PACIFIC AIR - BOOKING CONFIRMED
-Confirmation code: QK7F2P
-Passenger: ALEX RIVERA
-
-OUTBOUND PA 812
- Depart: San Francisco (SFO) Wed 14 Oct 2026, 11:40
- Arrive: Tokyo Haneda (HND) Thu 15 Oct 2026, 15:25
- Seat 27A - Economy
-
-RETURN PA 815
- Depart: Tokyo Haneda (HND) Sun 18 Oct 2026, 17:10
- Arrive: San Francisco (SFO) Sun 18 Oct 2026, 10:45
- Seat 31C - Economy
-
-Baggage: 1 carry-on + 1 checked bag included.
diff --git a/scripts/life-scenarios/fixtures/search-index.json b/scripts/life-scenarios/fixtures/search-index.json
deleted file mode 100644
index 27170079ba..0000000000
--- a/scripts/life-scenarios/fixtures/search-index.json
+++ /dev/null
@@ -1,189 +0,0 @@
-{
- "_comment": [
- "The corpus the mock search backend ranks over (scripts/life-scenarios/mock-search.mjs).",
- "",
- "Every `url` here is a REAL, live page. That is deliberate: the benchmark mocks",
- "*discovery*, not retrieval. The agent still fetches each page over the network with",
- "web_fetch and still has to read what it actually says, so `cites_delta_com` and the",
- "content checks stay honest — what the mock removes is the search engine the run has",
- "no credentials for, not the reading comprehension the scenario is testing.",
- "",
- "`excerpts` are snippets in the shape the Parallel/Exa proxy returns. They are hints",
- "for ranking and selection, never a substitute for the page: they deliberately stop",
- "short of the exact numbers the graders assert on, so an agent that answers from the",
- "excerpt alone still fails the check."
- ],
- "documents": [
- {
- "url": "https://www.delta.com/us/en/baggage/carry-on-baggage",
- "title": "Carry-On Baggage | Delta Air Lines",
- "publish_date": null,
- "keywords": [
- "delta",
- "carry-on",
- "carry on",
- "baggage",
- "personal item",
- "hand luggage",
- "basic economy",
- "dimensions",
- "size"
- ],
- "excerpts": [
- "Delta allows one carry-on bag plus one personal item free of charge on every fare, including Basic Economy. The page states the exact maximum dimensions and the linear-inch limit."
- ]
- },
- {
- "url": "https://www.delta.com/us/en/baggage/overview",
- "title": "Baggage Information Overview | Delta Air Lines",
- "publish_date": null,
- "keywords": [
- "delta",
- "baggage",
- "overview",
- "allowance",
- "checked",
- "policy",
- "rules"
- ],
- "excerpts": [
- "Entry point for Delta's baggage rules: carry-on, checked allowances, size and weight maximums, and the fee structure by cabin and route."
- ]
- },
- {
- "url": "https://www.delta.com/us/en/baggage/checked-baggage/excess-overweight-baggage",
- "title": "Excess & Overweight Baggage Fees | Delta Air Lines",
- "publish_date": null,
- "keywords": [
- "delta",
- "checked",
- "baggage",
- "fee",
- "fees",
- "overweight",
- "oversized",
- "excess",
- "transatlantic",
- "europe",
- "international"
- ],
- "excerpts": [
- "Per-piece weight and size limits by cabin, and the published excess, overweight and oversized charges for travel between North America and Europe."
- ]
- },
- {
- "url": "https://www.delta.com/us/en/baggage/checked-baggage/previous-baggage-fees",
- "title": "Previous Baggage Fees | Delta Air Lines",
- "publish_date": null,
- "keywords": [
- "delta",
- "baggage",
- "fee",
- "fees",
- "previous",
- "historical",
- "basic economy",
- "europe",
- "change"
- ],
- "excerpts": [
- "Historical record of fee changes, including first-bag pricing for Delta Main Basic on U.S./Canada/Mexico to Europe itineraries ticketed before a stated date. A change notice, not the current published fare."
- ]
- },
- {
- "url": "https://www.delta.com/us/en/baggage/additional-baggage-information/flight-partners",
- "title": "Baggage on Partner Airlines | Delta Air Lines",
- "publish_date": null,
- "keywords": [
- "delta",
- "baggage",
- "partner",
- "codeshare",
- "interline",
- "joint venture",
- "virgin atlantic",
- "klm",
- "air france"
- ],
- "excerpts": [
- "Which carrier's baggage rules govern an itinerary operated by a partner, which matters on transatlantic routes that Delta codeshares."
- ]
- },
- {
- "url": "https://www.delta.com/us/en/baggage/special-items",
- "title": "Special Items & Sports Equipment | Delta Air Lines",
- "publish_date": null,
- "keywords": [
- "delta",
- "baggage",
- "special",
- "sports",
- "equipment",
- "musical",
- "instrument",
- "bicycle"
- ],
- "excerpts": [
- "Handling and charges for items that fall outside the standard checked allowance."
- ]
- },
-
- {
- "url": "https://www.bls.gov/news.release/flex2.nr0.htm",
- "title": "Telework and Remote Work — U.S. Bureau of Labor Statistics",
- "publish_date": "2025-06-18",
- "keywords": [
- "remote work",
- "telework",
- "work from home",
- "hybrid",
- "statistic",
- "statistics",
- "percent",
- "workers",
- "survey",
- "current"
- ],
- "excerpts": [
- "Official U.S. federal survey estimates of the share of employed people who teleworked, broken out by industry and occupation. The release carries the reference period the figure belongs to."
- ]
- },
- {
- "url": "https://www.census.gov/topics/employment/telework.html",
- "title": "Telework — U.S. Census Bureau",
- "publish_date": "2025-09-04",
- "keywords": [
- "remote work",
- "telework",
- "work from home",
- "statistic",
- "statistics",
- "census",
- "survey",
- "share",
- "current"
- ],
- "excerpts": [
- "Census Bureau tables tracking work-from-home rates over time, with the year each estimate covers stated alongside it."
- ]
- },
- {
- "url": "https://www.pewresearch.org/social-trends/2023/03/30/about-a-third-of-us-workers-who-can-work-from-home-do-so-all-the-time/",
- "title": "How Americans View Their Jobs — Remote Work | Pew Research Center",
- "publish_date": "2023-03-30",
- "keywords": [
- "remote work",
- "work from home",
- "hybrid",
- "survey",
- "pew",
- "statistic",
- "statistics",
- "workers"
- ],
- "excerpts": [
- "Survey of U.S. workers whose jobs can be done from home, reporting how many do so all of the time versus some of the time. Note the fieldwork date when judging whether this is current."
- ]
- }
- ]
-}
diff --git a/scripts/life-scenarios/mock-composio.mjs b/scripts/life-scenarios/mock-composio.mjs
deleted file mode 100644
index 4d03c6aaa2..0000000000
--- a/scripts/life-scenarios/mock-composio.mjs
+++ /dev/null
@@ -1,286 +0,0 @@
-/**
- * A mock Composio server for the life-scenario benchmark.
- *
- * The real Composio is an OAuth broker in front of Gmail, Google Calendar and
- * a few hundred other SaaS tools. A benchmark cannot use it: it needs live
- * consumer accounts, it costs real quota, and nothing about it is
- * reproducible. But the scenarios are *about* mail and calendar, so stubbing
- * the tools out would benchmark the wrong thing.
- *
- * So this serves Composio's wire shape over the same fixture corpus the file
- * tools see. `GMAIL_FETCH_EMAILS` returns the fixture mailbox parsed into
- * Gmail's message shape; `GOOGLECALENDAR_EVENTS_LIST` returns the fixture
- * calendar in Google's event shape; the write actions record what the agent
- * tried to do into `outbox.json` so a grader can assert on it instead of an
- * email actually being sent.
- *
- * The core is pointed here with `OPENHUMAN_COMPOSIO_DIRECT_BASE_V3`.
- *
- * Every response is derived from the fixtures — no network, no secrets, and
- * the recorded writes are the point rather than a side effect.
- */
-
-import fs from "node:fs";
-import http from "node:http";
-import path from "node:path";
-
-const CONNECTED_ACCOUNT_ID = "ca_life_scenarios_0001";
-const USER_ID = "life-scenarios-user";
-
-// ---------------------------------------------------------------------------
-// fixture -> provider shapes
-// ---------------------------------------------------------------------------
-
-/** Parse one `Key: value` header block + body out of a fixture .txt message. */
-function parseMessage(text, file) {
- const idx = text.indexOf("\n\n");
- const headText = idx >= 0 ? text.slice(0, idx) : text;
- const body = idx >= 0 ? text.slice(idx + 2) : "";
- const headers = {};
- for (const line of headText.split("\n")) {
- const m = /^([A-Za-z-]+):\s*(.*)$/.exec(line.trim());
- if (m) headers[m[1].toLowerCase()] = m[2];
- }
- const date = headers.date ? new Date(headers.date) : null;
- return {
- messageId: file.replace(/\W+/g, "-"),
- threadId: file.replace(/\W+/g, "-"),
- sender: headers.from || "",
- to: headers.to || "",
- subject: headers.subject || "",
- messageTimestamp: date && !Number.isNaN(+date) ? date.toISOString() : null,
- labelIds: ["INBOX"],
- preview: { body: body.slice(0, 200) },
- messageText: body,
- };
-}
-
-function loadMailbox(fixtureRoot) {
- const dir = path.join(fixtureRoot, "mailbox");
- if (!fs.existsSync(dir)) return [];
- return fs
- .readdirSync(dir)
- .filter((f) => f.endsWith(".txt"))
- .sort()
- .map((f) => parseMessage(fs.readFileSync(path.join(dir, f), "utf8"), f));
-}
-
-function loadCalendar(fixtureRoot) {
- const p = path.join(fixtureRoot, "calendar", "calendar.json");
- if (!fs.existsSync(p)) return [];
- const doc = JSON.parse(fs.readFileSync(p, "utf8"));
- return (doc.events || []).map((e) => ({
- id: e.id,
- summary: e.title,
- start: { dateTime: e.start, timeZone: doc.timezone },
- end: { dateTime: e.end, timeZone: doc.timezone },
- organizer: { email: e.organizer },
- attendees: (e.attendees || []).map((a) => ({ email: a })),
- status: "confirmed",
- htmlLink: `https://calendar.example/event/${e.id}`,
- }));
-}
-
-// ---------------------------------------------------------------------------
-// actions
-// ---------------------------------------------------------------------------
-
-/**
- * Each handler returns Composio's `{ successful, data, error }` envelope.
- * `ctx.record(action, args)` appends to the outbox so writes are observable.
- */
-const ACTIONS = {
- GMAIL_FETCH_EMAILS(args, ctx) {
- const max = Number(args.max_results || args.maxResults || 25);
- const q = String(args.query || args.q || "").toLowerCase();
- let messages = ctx.mailbox;
- if (q) {
- messages = messages.filter((m) =>
- `${m.subject} ${m.sender} ${m.messageText}`.toLowerCase().includes(q),
- );
- }
- return {
- successful: true,
- data: {
- messages: messages.slice(0, max),
- resultSizeEstimate: messages.length,
- nextPageToken: null,
- },
- error: null,
- };
- },
-
- GMAIL_FETCH_MESSAGE_BY_MESSAGE_ID(args, ctx) {
- const id = String(args.message_id || args.messageId || "");
- const msg = ctx.mailbox.find((m) => m.messageId === id);
- return msg
- ? { successful: true, data: msg, error: null }
- : { successful: false, data: null, error: `no message ${id}` };
- },
-
- GMAIL_SEND_EMAIL(args, ctx) {
- ctx.record("GMAIL_SEND_EMAIL", args);
- return {
- successful: true,
- data: { id: `sent-${ctx.outbox.length}`, threadId: `sent-${ctx.outbox.length}`, labelIds: ["SENT"] },
- error: null,
- };
- },
-
- GMAIL_CREATE_EMAIL_DRAFT(args, ctx) {
- ctx.record("GMAIL_CREATE_EMAIL_DRAFT", args);
- return {
- successful: true,
- data: { id: `draft-${ctx.outbox.length}`, message: { id: `draft-${ctx.outbox.length}` } },
- error: null,
- };
- },
-
- GOOGLECALENDAR_EVENTS_LIST(args, ctx) {
- const timeMin = args.timeMin || args.time_min;
- const timeMax = args.timeMax || args.time_max;
- let items = ctx.calendar;
- if (timeMin) items = items.filter((e) => new Date(e.end.dateTime) >= new Date(timeMin));
- if (timeMax) items = items.filter((e) => new Date(e.start.dateTime) <= new Date(timeMax));
- return { successful: true, data: { items, nextPageToken: null }, error: null };
- },
-
- GOOGLECALENDAR_FIND_EVENT(args, ctx) {
- const q = String(args.query || args.q || "").toLowerCase();
- const items = q
- ? ctx.calendar.filter((e) => e.summary.toLowerCase().includes(q))
- : ctx.calendar;
- return { successful: true, data: { items }, error: null };
- },
-
- GOOGLECALENDAR_UPDATE_EVENT(args, ctx) {
- ctx.record("GOOGLECALENDAR_UPDATE_EVENT", args);
- const id = String(args.event_id || args.eventId || "");
- const ev = ctx.calendar.find((e) => e.id === id);
- if (!ev) return { successful: false, data: null, error: `no event ${id}` };
- if (args.start_datetime || args.start) ev.start.dateTime = args.start_datetime || args.start;
- if (args.end_datetime || args.end) ev.end.dateTime = args.end_datetime || args.end;
- return { successful: true, data: ev, error: null };
- },
-};
-
-const TOOLKITS = [
- { slug: "gmail", name: "Gmail", description: "Read and send mail" },
- { slug: "googlecalendar", name: "Google Calendar", description: "Read and edit events" },
-];
-
-const TOOLS = Object.keys(ACTIONS).map((slug) => ({
- slug,
- name: slug,
- description: `Mock ${slug}`,
- toolkit: { slug: slug.startsWith("GMAIL") ? "gmail" : "googlecalendar" },
- input_parameters: { type: "object", properties: {}, additionalProperties: true },
-}));
-
-// ---------------------------------------------------------------------------
-// server
-// ---------------------------------------------------------------------------
-
-export function startMockComposio({ fixtureRoot, outboxPath, port = 0 }) {
- const ctx = {
- mailbox: loadMailbox(fixtureRoot),
- calendar: loadCalendar(fixtureRoot),
- outbox: [],
- requests: [],
- record(action, args) {
- ctx.outbox.push({ at: new Date().toISOString(), action, args });
- if (outboxPath)
- fs.writeFileSync(outboxPath, JSON.stringify(ctx.outbox, null, 2));
- },
- };
-
- const json = (res, code, body) => {
- const payload = JSON.stringify(body);
- res.writeHead(code, {
- "content-type": "application/json",
- "content-length": Buffer.byteLength(payload),
- });
- res.end(payload);
- };
-
- const server = http.createServer((req, res) => {
- const url = new URL(req.url, "http://mock");
- const chunks = [];
- req.on("data", (c) => chunks.push(c));
- req.on("end", () => {
- const raw = Buffer.concat(chunks).toString("utf8");
- let body = {};
- if (raw) {
- try {
- body = JSON.parse(raw);
- } catch {
- body = {};
- }
- }
- ctx.requests.push({ method: req.method, path: url.pathname });
-
- const p = url.pathname.replace(/\/+$/, "");
-
- // Connected accounts / connections.
- if (/\/(connected_accounts|connections)$/.test(p) && req.method === "GET") {
- return json(res, 200, {
- items: TOOLKITS.map((t) => ({
- id: `${CONNECTED_ACCOUNT_ID}-${t.slug}`,
- status: "ACTIVE",
- toolkit: { slug: t.slug },
- user_id: USER_ID,
- auth_config: { id: `ac_${t.slug}` },
- })),
- total_items: TOOLKITS.length,
- });
- }
-
- if (/\/toolkits$/.test(p) && req.method === "GET")
- return json(res, 200, { items: TOOLKITS, total_items: TOOLKITS.length });
-
- if (/\/tools$/.test(p) && req.method === "GET")
- return json(res, 200, { items: TOOLS, total_items: TOOLS.length });
-
- // Execute: .../tools/execute/<ACTION> or .../actions/<ACTION>/execute
- const exec =
- /\/tools\/execute\/([A-Z0-9_]+)$/.exec(p) ||
- /\/actions\/([A-Z0-9_]+)\/execute$/.exec(p);
- if (exec && req.method === "POST") {
- const action = exec[1];
- const handler = ACTIONS[action];
- if (!handler)
- return json(res, 404, {
- successful: false,
- data: null,
- error: `mock composio has no action ${action}`,
- });
- const args = body.arguments || body.input || body.params || body || {};
- try {
- return json(res, 200, handler(args, ctx));
- } catch (e) {
- return json(res, 500, { successful: false, data: null, error: String(e.message) });
- }
- }
-
- // Anything else: answer in the envelope rather than a bare 404 so the
- // core's error classification sees a Composio-shaped failure.
- return json(res, 404, {
- successful: false,
- data: null,
- error: `mock composio: unhandled ${req.method} ${p}`,
- });
- });
- });
-
- return new Promise((resolve) => {
- server.listen(port, "127.0.0.1", () => {
- const actual = server.address().port;
- resolve({
- url: `http://127.0.0.1:${actual}`,
- port: actual,
- ctx,
- close: () => new Promise((r) => server.close(r)),
- });
- });
- });
-}
diff --git a/scripts/life-scenarios/mock-search.mjs b/scripts/life-scenarios/mock-search.mjs
deleted file mode 100644
index 097491563d..0000000000
--- a/scripts/life-scenarios/mock-search.mjs
+++ /dev/null
@@ -1,352 +0,0 @@
-/**
- * A mock TinyHumans backend for the life-scenario benchmark, serving the one
- * route the agent's `web_search_tool` needs.
- *
- * ## Why this exists
- *
- * `web_search_tool` is not a local tool: it posts to
- * `/agent-integrations/parallel/search` on the hosted backend, which resolves
- * the query against a paid search provider and bills the caller's team. The
- * benchmark has no session to spend — it runs BYOK inference on an offline
- * local token — so every call came back
- * `SESSION_EXPIRED: backend rejected session token … (401 Invalid token)`.
- *
- * The tool was advertised anyway (`tool spec filter: … web_search_tool`), so
- * the model spent calls discovering that it was dead and then routed around it
- * by hand: in the 2026-09-23 run `baggage-policy` burned two calls on the 401s
- * and then improvised a DuckDuckGo HTML scrape, guessing delta.com paths and
- * collecting four 404s. It reached the 15-call cap with the answer assembled
- * and the requested file unwritten, and graded 0/1.
- *
- * That is a defect in the benchmark rig, not in the product: the run offers a
- * capability its own configuration cannot serve. Removing the tool instead
- * would have been the other kind of dishonest — `baggage-policy` and
- * `fact-check-publish` are *about* finding things on the web.
- *
- * ## What is mocked, and what deliberately is not
- *
- * **Discovery is mocked. Retrieval is not.** This server ranks a fixture
- * corpus (`fixtures/search-index.json`) and returns real, live URLs. The agent
- * still fetches each page over the network with `web_fetch` and still has to
- * read what the page actually says. So `baggage-policy`'s `cites_delta_com`
- * and `states_carryon_dimensions` checks stay honest — what is gone is the
- * search engine the run cannot pay for, not the comprehension being measured.
- *
- * Ranking is deliberately crude (term overlap over title, URL, keywords and
- * excerpt). A cleverer ranker would start deciding the scenario's outcome,
- * which is the grader's job.
- *
- * ## Why it takes over the whole backend base URL
- *
- * `api_url` is the single base every backend caller resolves through
- * (`openhuman_tinyhumans::backend::url::effective_backend_api_url`), so pointing it here is what
- * routes the search. That also catches the other backend calls the run makes
- * and cannot authenticate — `/teams/me/usage`, the Composio toolkit list —
- * which previously logged a 401 per turn. They are answered with benign empty
- * stubs, so the log shows the run's own behaviour rather than a fixed auth
- * failure repeated once a turn. Composio itself is untouched: it is redirected
- * separately to `mock-composio.mjs` by `OPENHUMAN_COMPOSIO_DIRECT_BASE_V*`.
- *
- * Loopback with an ephemeral port is important. `effective_backend_api_url`
- * ignores an `api_url` that looks like an inference endpoint, and
- * `looks_like_local_ai_endpoint` treats loopback as a signal only when it is
- * paired with an LLM-ish port or path — so a bare `http://127.0.0.1:<random>`
- * is passed through as a backend override, which is exactly what this needs.
- *
- * Every unhandled route is recorded and answered 404, so a future capability
- * that starts reaching for the backend shows up in `search-requests.json`
- * rather than failing silently.
- */
-
-import fs from "node:fs";
-import http from "node:http";
-import path from "node:path";
-
-/** Words too common to carry a topic; dropped before scoring. */
-const STOPWORDS = new Set([
- "a",
- "an",
- "and",
- "are",
- "as",
- "at",
- "be",
- "by",
- "current",
- "do",
- "does",
- "for",
- "from",
- "how",
- "i",
- "in",
- "is",
- "it",
- "its",
- "me",
- "my",
- "of",
- "on",
- "or",
- "s",
- "that",
- "the",
- "their",
- "there",
- "they",
- "this",
- "to",
- "was",
- "what",
- "when",
- "where",
- "which",
- "who",
- "will",
- "with",
- "you",
- "your",
-]);
-
-/** Lowercase alphanumeric terms, stopwords and one-character noise removed. */
-function terms(text) {
- return (text || "")
- .toLowerCase()
- .split(/[^a-z0-9]+/)
- .filter((t) => t.length > 1 && !STOPWORDS.has(t));
-}
-
-/**
- * Does `term` match document term `h`?
- *
- * Exact, or a shared prefix of at least four characters so "fees" finds "fee"
- * and "baggage" finds "checked-baggage" without dragging in a stemmer. The
- * length floor is what stops a two-character fragment matching most of the
- * corpus.
- */
-function termMatches(term, h) {
- if (term === h) return true;
- const shorter = term.length <= h.length ? term : h;
- if (shorter.length < 4) return false;
- return term.startsWith(h) || h.startsWith(term);
-}
-
-/**
- * Score one document against the query terms.
- *
- * Fields are weighted by how deliberate a match in them is: an explicit
- * `keywords` entry is curated, a title is the page's own claim about itself,
- * a URL segment is incidental, and an excerpt is the loosest signal of all.
- *
- * Returns the weighted total alongside the count of *distinct* query terms
- * that matched anywhere, because the two answer different questions: the total
- * orders the hits, and the distinct count is what tells an off-topic query
- * apart from a weak one. Scoring alone cannot — a single incidental term
- * repeated across four fields outscores a genuine two-term match — and a
- * search that always returns something would send the agent off to fetch
- * pages that have nothing to do with the task.
- */
-function score(doc, queryTerms) {
- const fields = [
- [doc.keywords || [], 4],
- [[doc.title || ""], 3],
- [[doc.url || ""], 2],
- [doc.excerpts || [], 1],
- ];
- let total = 0;
- const matched = new Set();
- for (const [values, weight] of fields) {
- const haystack = terms(values.join(" "));
- if (haystack.length === 0) continue;
- for (const term of queryTerms) {
- if (haystack.some((h) => termMatches(term, h))) {
- total += weight;
- matched.add(term);
- }
- }
- }
- return { total, matched: matched.size };
-}
-
-/** Load the corpus, tolerating the `_comment` key the fixture carries. */
-function loadIndex(indexPath) {
- if (!fs.existsSync(indexPath)) return [];
- const parsed = JSON.parse(fs.readFileSync(indexPath, "utf8"));
- return Array.isArray(parsed) ? parsed : parsed.documents || [];
-}
-
-/**
- * Serve the backend routes the benchmark reaches.
- *
- * Resolves once the socket is listening, to `{ url, port, ctx, close }` in the
- * same shape as `startMockComposio` so `run.mjs` handles the two alike.
- */
-export function startMockSearch({ indexPath, requestsPath, port = 0 }) {
- const ctx = {
- documents: loadIndex(indexPath),
- /** Every query served, with what it matched — the record a grader or a
- * post-mortem reads to see whether discovery actually worked. */
- searches: [],
- /** Every request, including the unhandled ones. */
- requests: [],
- flush() {
- if (!requestsPath) return;
- fs.writeFileSync(
- requestsPath,
- JSON.stringify(
- { searches: ctx.searches, requests: ctx.requests },
- null,
- 2,
- ),
- );
- },
- };
-
- const json = (res, code, body) => {
- const payload = JSON.stringify(body);
- res.writeHead(code, {
- "content-type": "application/json",
- "content-length": Buffer.byteLength(payload),
- });
- res.end(payload);
- };
-
- /**
- * The envelope every backend response is unwrapped from —
- * `integrations/client/errors.rs::parse_envelope` deserializes
- * `{ success, data, error }` and hands back `data`.
- *
- * Returning the bare payload instead fails as `missing field 'success'`, and
- * fails *late*: the tool reports a malformed-response error rather than an
- * empty result, so the agent concludes search is broken and abandons the
- * task. That is exactly what the first run of this mock did, six times over.
- */
- const ok = (res, data) => json(res, 200, { success: true, data });
-
- const search = (body) => {
- // The core sends Parallel's shape: an `objective` plus `searchQueries`,
- // with the result count under `excerpts.maxResults`.
- const queries = [
- ...(Array.isArray(body.searchQueries) ? body.searchQueries : []),
- body.objective,
- body.query,
- ].filter((q) => typeof q === "string" && q.trim());
- const queryTerms = [...new Set(queries.flatMap(terms))];
- const limit = Math.min(
- Math.max(Number(body?.excerpts?.maxResults) || 5, 1),
- 10,
- );
-
- // An off-topic query must come back empty rather than with the least-bad
- // rows in the corpus: a confidently wrong result set is worse for the
- // agent than none, because it spends fetches on it. Two distinct matching
- // terms is the floor, relaxed to one when the query only has one to give.
- const floor = Math.min(2, queryTerms.length) || 1;
- const ranked = ctx.documents
- .map((doc) => ({ doc, ...score(doc, queryTerms) }))
- .filter((hit) => hit.total > 0 && hit.matched >= floor)
- .sort((a, b) => b.total - a.total || a.doc.url.localeCompare(b.doc.url))
- .slice(0, limit);
-
- ctx.searches.push({
- at: new Date().toISOString(),
- queries,
- hits: ranked.map((hit) => ({ url: hit.doc.url, score: hit.total })),
- });
- ctx.flush();
-
- return {
- searchId: `mock-${ctx.searches.length}`,
- // Zero rather than a plausible number: the benchmark's cost column must
- // report what the run actually spent, and this search cost nothing.
- costUsd: 0,
- provider: "LifeScenariosMock",
- results: ranked.map(({ doc }) => ({
- url: doc.url,
- title: doc.title || doc.url,
- publish_date: doc.publish_date ?? null,
- excerpts: doc.excerpts || [],
- })),
- };
- };
-
- const server = http.createServer((req, res) => {
- const url = new URL(req.url, "http://mock");
- const chunks = [];
- req.on("data", (c) => chunks.push(c));
- req.on("end", () => {
- const raw = Buffer.concat(chunks).toString("utf8");
- let body = {};
- if (raw) {
- try {
- body = JSON.parse(raw);
- } catch {
- body = {};
- }
- }
- const p = url.pathname.replace(/\/+$/, "");
- ctx.requests.push({
- at: new Date().toISOString(),
- method: req.method,
- path: p,
- });
-
- if (
- p === "/agent-integrations/parallel/search" &&
- req.method === "POST"
- ) {
- try {
- return ok(res, search(body));
- } catch (e) {
- return json(res, 500, {
- success: false,
- data: null,
- error: `mock search failed: ${e.message}`,
- });
- }
- }
-
- // Benign stubs for the backend calls the run makes but has no session
- // for. Answering them keeps a fixed auth failure out of the log so what
- // remains is the run's own behaviour.
- if (p === "/teams/me/usage" && req.method === "GET") {
- return ok(res, { usage: {}, limits: {}, plan: "life-scenarios-mock" });
- }
- if (p === "/agent-integrations/composio/toolkits") {
- // Empty on purpose: Composio is served by `mock-composio.mjs` over the
- // direct base, so this list must not compete with it.
- return ok(res, { items: [], total_items: 0 });
- }
-
- ctx.flush();
- return json(res, 404, {
- success: false,
- data: null,
- error: `mock search backend: unhandled ${req.method} ${p}`,
- });
- });
- });
-
- return new Promise((resolve) => {
- server.listen(port, "127.0.0.1", () => {
- const actual = server.address().port;
- resolve({
- url: `http://127.0.0.1:${actual}`,
- port: actual,
- ctx,
- close: () =>
- new Promise((r) => {
- ctx.flush();
- server.close(r);
- }),
- });
- });
- });
-}
-
-/** Where the default corpus lives, for `run.mjs` and the self-test. */
-export const DEFAULT_INDEX_PATH = path.join(
- path.dirname(new URL(import.meta.url).pathname),
- "fixtures",
- "search-index.json",
-);
diff --git a/scripts/life-scenarios/run.mjs b/scripts/life-scenarios/run.mjs
deleted file mode 100644
index cf042a731c..0000000000
--- a/scripts/life-scenarios/run.mjs
+++ /dev/null
@@ -1,1198 +0,0 @@
-#!/usr/bin/env node
-/**
- * Life-scenario harness benchmark — headless, but shaped like the desktop app.
- *
- * The point is to measure the harness the product actually ships, so the
- * default path here is the one the desktop composer takes, with the UI removed
- * and nothing else changed:
- *
- * | desktop app | here |
- * | ---------------------------------------- | ----------------------------- |
- * | Tauri spawns the core as a tokio task | spawn `openhuman-core serve` |
- * | composer calls `openhuman.channel_web_chat`| same RPC, same params |
- * | reply streams over Socket.IO | same events over `GET /events`|
- * | orchestrator agent, packs withheld | same — no custom definition |
- * | approval gate ON, user clicks Approve | gate ON, responder approves |
- * | BYOK set in Settings → Models | `config.update_model_settings`|
- * | signed-in session | offline local session |
- *
- * What is deliberately NOT the app: it runs under a `HOME` of its own, so it
- * never reads or writes the operator's `~/.openhuman` (installing a credential
- * there would sign a running desktop app out), inference goes to OpenRouter on
- * the caller's key rather than the hosted backend, and Composio is a local
- * mock over the same fixtures. Those three make a run reproducible and cost
- * what it says on the tin; everything else is the shipping path.
- *
- * `--driver rpc` switches to `openhuman.inference_agent_chat`, which is the
- * only path that can scope a per-turn `cwd` and name an `agent_id` — used for
- * the comparison arm against a custom agent definition.
- *
- * Usage:
- * node scripts/life-scenarios/run.mjs # all scenarios
- * node scripts/life-scenarios/run.mjs --only calendar-buffer
- * node scripts/life-scenarios/run.mjs --driver rpc --agent life_scenarios
- * node scripts/life-scenarios/run.mjs --grade-only <run-dir>
- */
-
-import { spawn } from "node:child_process";
-import { randomBytes } from "node:crypto";
-import fs from "node:fs";
-import fsp from "node:fs/promises";
-import net from "node:net";
-import path from "node:path";
-import { fileURLToPath } from "node:url";
-
-import { SCENARIOS, scenarioById } from "./scenarios.mjs";
-import { startMockComposio } from "./mock-composio.mjs";
-import { startMockSearch, DEFAULT_INDEX_PATH } from "./mock-search.mjs";
-
-const HERE = path.dirname(fileURLToPath(import.meta.url));
-const REPO = path.resolve(HERE, "..", "..");
-const FIXTURES = path.join(HERE, "fixtures");
-const SUPPORTED_AGENT_IDS = new Set(["life_scenarios", "orchestrator"]);
-
-// ---------------------------------------------------------------------------
-// args
-// ---------------------------------------------------------------------------
-
-function parseArgs(argv) {
- const o = {
- only: [],
- // `desktop` = channel_web_chat + SSE, exactly what the composer does.
- // `rpc` = inference_agent_chat, the only path with `cwd`/`agent_id`.
- driver: "desktop",
- // The suite's benchmark agent (scripts/life-scenarios/agent-life-scenarios.toml):
- // 40 iterations and the named tool belt these multi-step scenarios need.
- // `--agent orchestrator` runs the unmodified shipping agent for comparison,
- // capped at the 15 iterations its own definition declares.
- //
- // This now takes effect on BOTH drivers: the rpc path passes it per call,
- // the desktop path gets it through `[agent] chat_agent_id` in the generated
- // config.
- agentId: "life_scenarios",
- model: process.env.LIFE_SCENARIO_MODEL || "deepseek/deepseek-v4.1-flash",
- inferenceUrl:
- process.env.LIFE_SCENARIO_INFERENCE_URL || "https://openrouter.ai/api/v1",
- apiKey: process.env.OPENROUTER_API_KEY || "",
- managed: false,
- mockComposio: true,
- composioPort: 0,
- mockSearch: true,
- searchPort: 0,
- repeat: 1,
- turnTimeoutMs: 900_000,
- coreBin:
- process.env.OPENHUMAN_CORE_BIN ||
- path.join(REPO, "target", "debug", "openhuman-core"),
- runRoot: path.join(REPO, "target", "life-scenarios"),
- gradeOnly: "",
- // The desktop app ships the approval gate ON and a human answers it. The
- // headless equivalent is a responder, not a disabled gate — see
- // `ApprovalResponder`. `--no-approvals` disables the gate instead, which
- // is what most headless harnesses do and is worth being able to compare.
- approvals: true,
- verbose: false,
- };
- for (let i = 0; i < argv.length; i += 1) {
- const a = argv[i];
- const next = () => {
- const v = argv[++i];
- if (v === undefined) throw new Error(`missing value for ${a}`);
- return v;
- };
- if (a === "--only")
- o.only = next().split(",").map((s) => s.trim()).filter(Boolean);
- else if (a === "--driver") o.driver = next();
- else if (a === "--agent") {
- const agentId = next();
- if (!/^[A-Za-z0-9_-]+$/.test(agentId)) {
- throw new Error(
- "--agent must contain only ASCII letters, digits, '_' or '-'",
- );
- }
- if (!SUPPORTED_AGENT_IDS.has(agentId)) {
- throw new Error(
- `--agent must be one of: ${[...SUPPORTED_AGENT_IDS].join(", ")}`,
- );
- }
- o.agentId = agentId;
- }
- else if (a === "--model") o.model = next();
- else if (a === "--inference-url") o.inferenceUrl = next();
- else if (a === "--api-key") o.apiKey = next();
- else if (a === "--managed") o.managed = true;
- else if (a === "--no-mock-composio") o.mockComposio = false;
- else if (a === "--no-mock-search") o.mockSearch = false;
- else if (a === "--no-approvals") o.approvals = false;
- else if (a === "--repeat") o.repeat = Number(next());
- else if (a === "--turn-timeout-ms") o.turnTimeoutMs = Number(next());
- else if (a === "--core-bin") o.coreBin = next();
- else if (a === "--run-root") o.runRoot = next();
- else if (a === "--grade-only") o.gradeOnly = next();
- else if (a === "--verbose" || a === "-v") o.verbose = true;
- else if (a === "-h" || a === "--help") {
- console.log(fs.readFileSync(path.join(HERE, "README.md"), "utf8"));
- process.exit(0);
- } else throw new Error(`unknown flag ${a}`);
- }
- if (!["desktop", "rpc"].includes(o.driver))
- throw new Error(`--driver must be 'desktop' or 'rpc', got '${o.driver}'`);
- return o;
-}
-
-// ---------------------------------------------------------------------------
-// small utilities
-// ---------------------------------------------------------------------------
-
-const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
-
-async function freePort() {
- return new Promise((resolve, reject) => {
- const srv = net.createServer();
- srv.unref();
- srv.on("error", reject);
- srv.listen(0, "127.0.0.1", () => {
- const { port } = srv.address();
- srv.close(() => resolve(port));
- });
- });
-}
-
-async function copyDir(from, to) {
- await fsp.mkdir(to, { recursive: true });
- for (const entry of await fsp.readdir(from, { withFileTypes: true })) {
- const s = path.join(from, entry.name);
- const d = path.join(to, entry.name);
- if (entry.isDirectory()) await copyDir(s, d);
- else await fsp.copyFile(s, d);
- }
-}
-
-/** Walk a directory and return [{ rel, bytes, mtimeMs }] for every file. */
-async function snapshotTree(root) {
- const out = [];
- async function walk(dir) {
- let entries;
- try {
- entries = await fsp.readdir(dir, { withFileTypes: true });
- } catch {
- return;
- }
- for (const e of entries) {
- const p = path.join(dir, e.name);
- if (e.isDirectory()) await walk(p);
- else {
- const st = await fsp.stat(p).catch(() => null);
- if (st)
- out.push({ rel: path.relative(root, p), bytes: st.size, mtimeMs: st.mtimeMs });
- }
- }
- }
- await walk(root);
- return out;
-}
-
-/**
- * Mint the core's offline local session token.
- *
- * The desktop app installs a real session JWT after login. A headless run has
- * no login flow, but the core ships a third credential kind for exactly this:
- * a JWT-shaped token whose signature segment is the literal `local`
- * (`security::credentials::session_support::is_local_session_token`). It buys
- * no access to the hosted backend — it only lets a local host say whose turn
- * this is, which is all that is needed when inference is BYOK and Composio is
- * mocked.
- */
-function mintLocalSessionToken(userId) {
- const b64 = (o) =>
- Buffer.from(JSON.stringify(o))
- .toString("base64")
- .replace(/\+/g, "-")
- .replace(/\//g, "_")
- .replace(/=+$/, "");
- const now = Math.floor(Date.now() / 1000);
- return [
- b64({ alg: "none", typ: "JWT" }),
- b64({
- sub: userId,
- iat: now,
- exp: now + 24 * 60 * 60,
- email: "[email protected]",
- }),
- "local",
- ].join(".");
-}
-
-// ---------------------------------------------------------------------------
-// the throwaway HOME
-// ---------------------------------------------------------------------------
-
-/**
- * Write the config a freshly-onboarded desktop install would have.
- *
- * Written from scratch rather than copied: a copied `config.toml` drags along
- * whatever `api_url`, provider pins and autonomy settings that machine happens
- * to have, and a benchmark that silently inherits those measures the machine
- * rather than the harness.
- */
-async function prepareHome(runDir, opts, { searchBase } = {}) {
- const home = path.join(runDir, "home");
- const oh = path.join(home, ".openhuman");
- await fsp.mkdir(path.join(oh, "agents"), { recursive: true });
- await fsp.mkdir(path.join(oh, "users", "local"), { recursive: true });
-
- const config = [
- "schema_version = 13",
- // The backend base every non-inference call resolves through
- // (`openhuman_tinyhumans::backend::url::effective_backend_api_url`). Pointed at the local mock so
- // `web_search_tool` has something to talk to: it posts to
- // `/agent-integrations/parallel/search` on this base, and against the
- // hosted backend this run's offline token is rejected 401 every time.
- // See also BACKEND_URL in `Core.start` — this file alone is not enough.
- searchBase
- ? `api_url = "${searchBase}"`
- : 'api_url = "https://api.tinyhumans.ai"',
- "default_temperature = 0.7",
- "onboarding_completed = true",
- "chat_onboarding_completed = true",
- "",
- "[autonomy]",
- // The shipped desktop default is `enabled = false`: the policy is opt-in,
- // because the product's agents run in containers and jails that already
- // bound them. Written explicitly rather than left to the default so a
- // reader of this file can see which product is being measured, and so
- // flipping it to `true` is a one-line comparison arm.
- //
- // With it off, `gate_decision` answers Allow for every class, so nothing
- // parks and the ApprovalResponder below has little to answer. That is the
- // measurement, not a shortcut: see README.md.
- "enabled = false",
- 'level = "supervised"',
- "workspace_only = false",
- "",
- // The web-chat path (`channel_web_chat`, the desktop driver below) has no
- // per-call `agent_id` the way `inference_agent_chat` does, so this is how
- // it is pointed at the suite's benchmark agent. Without it that path runs
- // `orchestrator`. A definition cap replaces `[agent] max_tool_iterations`,
- // so only `max_tool_iterations_override` changes the budget without
- // changing which agent (prompt, tools) answers.
- "[agent]",
- `chat_agent_id = "${opts.agentId}"`,
- "",
- "[observability]",
- "analytics_enabled = false",
- "share_usage_data = false",
- "",
- // `create_composio_client` dispatches on this field alone; the
- // `OPENHUMAN_COMPOSIO_DIRECT_BASE_V*` env pair is consulted only in
- // `direct` mode, and only in a debug build. Without it the core ignores
- // the mock and dials the hosted proxy.
- "[composio]",
- 'mode = "direct"',
- 'api_key = "ck_life_scenarios_mock"',
- 'entity_id = "default"',
- "",
- ].join("\n");
- await fsp.writeFile(path.join(oh, "config.toml"), config);
- // Once a user is active the per-user config is read in preference to the
- // root one, so the composio block has to exist in both.
- await fsp.writeFile(path.join(oh, "users", "local", "config.toml"), config);
-
- // Read by both drivers now: the rpc path names it per call, the desktop path
- // selects it with `[agent] chat_agent_id` above. `--agent orchestrator` opts
- // back into the unmodified shipping agent.
- await fsp.copyFile(
- path.join(HERE, "agent-life-scenarios.toml"),
- path.join(oh, "agents", "life_scenarios.toml"),
- );
-
- return home;
-}
-
-/** Retry `fn` until it stops throwing, then give up with the last error. */
-async function withRetries(fn, { attempts, delayMs, what }) {
- let last;
- for (let i = 0; i < attempts; i += 1) {
- try {
- await fn();
- return;
- } catch (e) {
- last = e;
- await new Promise((r) => setTimeout(r, delayMs));
- }
- }
- throw new Error(`${what} never settled after ${attempts} attempts: ${last?.message ?? last}`);
-}
-
-// ---------------------------------------------------------------------------
-// core lifecycle
-// ---------------------------------------------------------------------------
-
-class Core {
- constructor(opts) {
- this.opts = opts;
- this.proc = null;
- this.port = 0;
- this.token = randomBytes(24).toString("hex");
- this.exited = null;
- }
-
- get url() {
- return `http://127.0.0.1:${this.port}`;
- }
-
- async start({ actionDir, logPath, home, composioBase, searchBase, approvals }) {
- this.port = await freePort();
- const log = fs.createWriteStream(logPath, { flags: "a" });
-
- const env = {
- ...process.env,
- // A private HOME is the isolation boundary: `default_root_openhuman_dir`
- // resolves `<home>/.openhuman`, so config, keyring, auth profiles,
- // workspace and session db all land inside the run directory.
- HOME: home,
- OPENHUMAN_HOME: path.join(home, ".openhuman"),
- OPENHUMAN_CORE_TOKEN: this.token,
- OPENHUMAN_CORE_PORT: String(this.port),
- OPENHUMAN_CORE_HOST: "127.0.0.1",
- // Just this one now. It used to need OPENHUMAN_PROJECTS_DIR beside it:
- // `action_dir` was only the base that relative tool paths are joined
- // onto, and the *permission* to write came from a trusted root that
- // `security/policy/enforcement.rs` granted for `default_projects_dir()`
- // alone — so setting ACTION_DIR by itself got every file-tool write
- // refused "Resolved path escapes workspace" (FINDINGS.md #1).
- // `from_config` now grants the configured action dir itself, which is
- // what this single variable proves end to end.
- OPENHUMAN_ACTION_DIR: actionDir,
- RUST_LOG: process.env.RUST_LOG || "info",
- };
- if (!approvals) env.OPENHUMAN_APPROVAL_GATE = "0";
- if (process.env.BACKEND_URL) env.BACKEND_URL = process.env.BACKEND_URL;
- // The same backend base as `api_url` above, set again as an env var
- // because the config file loses a race that is easy to miss:
- // `auth.set_credential` activates a per-user config dir
- // (`users/<id>/config.toml`) whose id the core derives at runtime, and a
- // config there takes precedence over the root one. `prepareHome` cannot
- // know that id, so it writes `users/local/`; the core activates
- // `users/local-dragonfly/`, finds no `api_url` and falls back to the
- // hosted backend. `api_base_from_env` reads BACKEND_URL ahead of the
- // compile-time default whichever config wins, so this is the override
- // that actually holds.
- if (searchBase) env.BACKEND_URL = searchBase;
- if (composioBase) {
- // Both are read by `integrations/composio/client/factory.rs`; the match
- // arm is `(Some, Some)`, so setting only one silently falls through to
- // the production Composio URLs.
- env.OPENHUMAN_COMPOSIO_DIRECT_BASE_V3 = composioBase;
- env.OPENHUMAN_COMPOSIO_DIRECT_BASE_V2 = composioBase;
- }
-
- // Plain `serve`, not `--jsonrpc-only`: the app boots the full service set,
- // and the background services are part of what a turn costs.
- this.proc = spawn(this.opts.coreBin, ["serve"], {
- env,
- stdio: ["ignore", "pipe", "pipe"],
- cwd: actionDir,
- });
- this.proc.stdout.pipe(log);
- this.proc.stderr.pipe(log);
- this.proc.on("exit", (code, sig) => {
- this.exited = { code, sig };
- });
-
- const deadline = Date.now() + 120_000;
- while (Date.now() < deadline) {
- if (this.exited)
- throw new Error(
- `core exited during boot (code=${this.exited.code} sig=${this.exited.sig}); see ${logPath}`,
- );
- try {
- const r = await fetch(`${this.url}/health`, {
- signal: AbortSignal.timeout(3000),
- });
- if (r.ok) return await r.json();
- } catch {
- /* not up yet */
- }
- await sleep(500);
- }
- throw new Error(`core did not become healthy on ${this.url}; see ${logPath}`);
- }
-
- async rpc(method, params, timeoutMs = 120_000) {
- const res = await fetch(`${this.url}/rpc`, {
- method: "POST",
- headers: {
- "content-type": "application/json",
- authorization: `Bearer ${this.token}`,
- },
- body: JSON.stringify({ jsonrpc: "2.0", id: `ls-${Date.now()}`, method, params }),
- signal: AbortSignal.timeout(timeoutMs),
- });
- const text = await res.text();
- if (!res.ok)
- throw new Error(`RPC ${method} HTTP ${res.status}: ${text.slice(0, 400)}`);
- let body;
- try {
- body = JSON.parse(text);
- } catch {
- throw new Error(`RPC ${method} non-JSON: ${text.slice(0, 300)}`);
- }
- if (body.error)
- throw new Error(`RPC ${method} error: ${JSON.stringify(body.error).slice(0, 500)}`);
- // `apply_log_envelope` wraps a result that carried log lines.
- const r = body.result;
- if (r && typeof r === "object" && "result" in r && "logs" in r) return r.result;
- return r;
- }
-
- async stop() {
- if (!this.proc || this.exited) return;
- this.proc.kill("SIGTERM");
- const deadline = Date.now() + 15_000;
- while (!this.exited && Date.now() < deadline) await sleep(100);
- if (!this.exited) this.proc.kill("SIGKILL");
- }
-}
-
-// ---------------------------------------------------------------------------
-// SSE — the composer's event stream
-// ---------------------------------------------------------------------------
-
-/**
- * Subscribe to `GET /events?client_id=…`, the same stream the desktop
- * frontend consumes. Events are delivered to `onEvent` as parsed objects.
- */
-class EventStream {
- constructor(core, clientId) {
- this.core = core;
- this.clientId = clientId;
- this.handlers = new Set();
- this.controller = new AbortController();
- this.closed = false;
- }
-
- onEvent(fn) {
- this.handlers.add(fn);
- return () => this.handlers.delete(fn);
- }
-
- async connect() {
- const url = `${this.core.url}/events?client_id=${encodeURIComponent(this.clientId)}`;
- const res = await fetch(url, {
- headers: { authorization: `Bearer ${this.core.token}`, accept: "text/event-stream" },
- signal: this.controller.signal,
- });
- if (!res.ok || !res.body)
- throw new Error(`events subscribe failed: HTTP ${res.status}`);
- // Pump in the background; the caller awaits chat_done, not this.
- this.pump = (async () => {
- const decoder = new TextDecoder();
- let buffer = "";
- try {
- for await (const chunk of res.body) {
- buffer += decoder.decode(chunk, { stream: true });
- let idx;
- while ((idx = buffer.indexOf("\n\n")) >= 0) {
- const frame = buffer.slice(0, idx);
- buffer = buffer.slice(idx + 2);
- for (const line of frame.split("\n")) {
- if (!line.startsWith("data:")) continue;
- const payload = line.slice(5).trim();
- if (!payload) continue;
- let event;
- try {
- event = JSON.parse(payload);
- } catch {
- continue;
- }
- for (const h of this.handlers) h(event);
- }
- }
- }
- } catch {
- /* aborted or core stopped */
- }
- this.closed = true;
- })();
- }
-
- close() {
- this.controller.abort();
- }
-}
-
-// ---------------------------------------------------------------------------
-// approvals — what the human in front of the app does
-// ---------------------------------------------------------------------------
-
-/**
- * Stand in for the person clicking "Approve" on the approval card.
- *
- * The gate stays installed exactly as it ships; this only supplies the
- * decision it is waiting for. Without a responder, a headless turn parks on
- * the first gated tool call and the request expires as DENIED after ten
- * minutes — so a harness that simply disables the gate is not measuring the
- * product, and one that leaves it unanswered is measuring the timeout.
- *
- * Every decision is recorded, because "how many approvals did this task need"
- * is itself a result: a task that needs fourteen is not one a supervised user
- * would enjoy.
- */
-class ApprovalResponder {
- constructor(core, { intervalMs = 400 } = {}) {
- this.core = core;
- this.intervalMs = intervalMs;
- this.decisions = [];
- this.seen = new Set();
- this.running = false;
- this.errors = [];
- }
-
- start() {
- this.running = true;
- this.loop = (async () => {
- while (this.running) {
- try {
- const pending = await this.core.rpc("openhuman.approval_list_pending", {}, 15_000);
- const rows = Array.isArray(pending)
- ? pending
- : (pending && (pending.requests || pending.pending || pending.items)) || [];
- for (const row of rows) {
- // `PendingApproval.request_id` — the decide RPC takes `request_id`,
- // not `id`, and a wrong key comes back as a redacted
- // param-validation error that names neither the field nor the
- // method's expectation.
- const requestId = row.request_id || row.requestId;
- if (!requestId || this.seen.has(requestId)) continue;
- this.seen.add(requestId);
- await this.core.rpc(
- "openhuman.approval_decide",
- { request_id: requestId, decision: "approve_once" },
- 15_000,
- );
- this.decisions.push({
- at: new Date().toISOString(),
- request_id: requestId,
- tool: row.tool_name || "",
- summary: (row.action_summary || "").slice(0, 200),
- });
- }
- } catch (e) {
- // A transient failure here must not kill the run; record it so a
- // silent approval stall is still visible afterwards.
- this.errors.push(String(e.message).slice(0, 200));
- }
- await sleep(this.intervalMs);
- }
- })();
- }
-
- async stop() {
- this.running = false;
- await this.loop?.catch(() => {});
- }
-
- /** Decisions made while `fn` ran. */
- countSince(mark) {
- return this.decisions.length - mark;
- }
-}
-
-// ---------------------------------------------------------------------------
-// usage accounting
-// ---------------------------------------------------------------------------
-
-/**
- * `openhuman.cost_get_usage_log` returns one row per provider call. Diffing
- * row ids across a turn is exact where a timestamp window would not be: the
- * background services (memory, learning) bill against the same log
- * while a turn runs, and a window would sweep them in.
- */
-async function usageIds(core) {
- const log = await core.rpc("openhuman.cost_get_usage_log", { days: 1, limit: 1000 });
- const records = (log && log.records) || [];
- return new Map(records.map((r) => [r.id, r]));
-}
-
-function foldUsage(rows) {
- const t = {
- calls: rows.length,
- input_tokens: 0,
- output_tokens: 0,
- cached_input_tokens: 0,
- cache_creation_tokens: 0,
- reasoning_tokens: 0,
- cost_usd: 0,
- };
- const models = new Set();
- const sources = new Set();
- for (const r of rows) {
- t.input_tokens += Number(r.input_tokens || 0);
- t.output_tokens += Number(r.output_tokens || 0);
- t.cached_input_tokens += Number(r.cached_input_tokens || 0);
- t.cache_creation_tokens += Number(r.cache_creation_tokens || 0);
- t.reasoning_tokens += Number(r.reasoning_tokens || 0);
- t.cost_usd += Number(r.cost_usd || 0);
- if (r.model) models.add(r.model);
- if (r.cost_source) sources.add(r.cost_source);
- }
- return {
- ...t,
- models: [...models],
- cost_sources: [...sources],
- cache_hit_pct: t.input_tokens > 0 ? (t.cached_input_tokens / t.input_tokens) * 100 : 0,
- };
-}
-
-/** Prefer the turn's own `chat_done.usage`; fall back to the cost-log diff. */
-function reconcileUsage(chatDoneUsage, loggedUsage) {
- if (!chatDoneUsage) return { ...loggedUsage, source: "cost_log" };
- const input = Number(chatDoneUsage.input_tokens || 0);
- const cached = Number(chatDoneUsage.cached_input_tokens || 0);
- return {
- calls: loggedUsage.calls,
- input_tokens: input,
- output_tokens: Number(chatDoneUsage.output_tokens || 0),
- cached_input_tokens: cached,
- cache_creation_tokens: loggedUsage.cache_creation_tokens,
- reasoning_tokens: loggedUsage.reasoning_tokens,
- cost_usd: Number(chatDoneUsage.cost_usd || 0) || loggedUsage.cost_usd,
- models: loggedUsage.models,
- cost_sources: loggedUsage.cost_sources,
- cache_hit_pct: input > 0 ? (cached / input) * 100 : 0,
- context_window: Number(chatDoneUsage.context_window || 0),
- subagents: chatDoneUsage.subagents || [],
- source: "chat_done",
- };
-}
-
-// ---------------------------------------------------------------------------
-// grading
-// ---------------------------------------------------------------------------
-
-function gradeScenario(scenario, sandbox, transcript) {
- const ctx = {
- read(rel) {
- try {
- return fs.readFileSync(path.join(sandbox, rel), "utf8");
- } catch {
- return null;
- }
- },
- exists(rel) {
- return fs.existsSync(path.join(sandbox, rel));
- },
- transcript: transcript || "",
- sandbox,
- };
- let checks;
- try {
- ({ checks } = scenario.grade(ctx));
- } catch (e) {
- checks = [
- { id: "grader_crashed", ok: false, detail: String(e.message).slice(0, 200) },
- ];
- }
- const passed = checks.filter((c) => c.ok).length;
- return {
- checks,
- passed,
- total: checks.length,
- score: checks.length ? passed / checks.length : 0,
- };
-}
-
-// ---------------------------------------------------------------------------
-// the two drivers
-// ---------------------------------------------------------------------------
-
-/**
- * The desktop path: `channel_web_chat` acks immediately and the answer arrives
- * on the event stream as `chat_done`, carrying the turn's own usage payload.
- */
-async function sendDesktopTurn({ core, events, clientId, threadId, message, opts }) {
- const toolCalls = [];
- let done = null;
- let requestId = null;
-
- const finished = new Promise((resolve) => {
- const off = events.onEvent((ev) => {
- if (ev.client_id && ev.client_id !== clientId) return;
- if (ev.event === "tool_call")
- toolCalls.push({
- name: ev.tool_name || ev.tool || "",
- label: ev.tool_display_label || "",
- });
- // A failed turn ends in `chat_error`, not `chat_done` — a driver that
- // waits only for `chat_done` hangs until its own timeout on every
- // provider misconfiguration, and reports it as a timeout.
- if (ev.event === "chat_done" || ev.event === "chat_error") {
- // The ack may not have landed yet, so match loosely on thread when the
- // request id is not yet known.
- if (requestId && ev.request_id && ev.request_id !== requestId) return;
- if (!requestId && ev.thread_id && ev.thread_id !== threadId) return;
- done = ev;
- off();
- resolve(ev);
- }
- });
- });
-
- const ack = await core.rpc(
- "openhuman.channel_web_chat",
- {
- client_id: clientId,
- thread_id: threadId,
- message,
- source: "type",
- queue_mode: "interrupt",
- ...(opts.model ? { model_override: opts.model } : {}),
- },
- 120_000,
- );
- requestId = (ack && (ack.request_id || ack.requestId)) || null;
-
- const timeout = sleep(opts.turnTimeoutMs).then(() => "timeout");
- const outcome = await Promise.race([finished, timeout]);
- if (outcome === "timeout")
- return { error: `turn did not emit chat_done within ${opts.turnTimeoutMs}ms`, requestId, toolCalls };
-
- if (done && done.event === "chat_error")
- return {
- error: `chat_error (${done.error_type || "unknown"}): ${String(done.message || "").slice(0, 300)}`,
- requestId: requestId || done.request_id || null,
- toolCalls,
- };
-
- return {
- reply: (done && (done.full_response || done.response)) || "",
- usage: done && done.usage,
- requestId: requestId || (done && done.request_id) || null,
- toolCalls,
- };
-}
-
-/** The RPC path: synchronous, and the only one that can scope `cwd`. */
-async function sendRpcTurn({ core, threadId, message, sandbox, opts }) {
- const reply = await core.rpc(
- "openhuman.inference_agent_chat",
- {
- message,
- thread_id: threadId,
- cwd: sandbox,
- ...(opts.agentId ? { agent_id: opts.agentId } : {}),
- ...(opts.managed
- ? opts.model
- ? { model_override: opts.model }
- : {}
- : {
- model_override: opts.model,
- inference_url: opts.inferenceUrl,
- api_key: opts.apiKey,
- }),
- },
- opts.turnTimeoutMs,
- );
- return { reply: typeof reply === "string" ? reply : "", usage: null, requestId: null, toolCalls: [] };
-}
-
-// ---------------------------------------------------------------------------
-// run one scenario
-// ---------------------------------------------------------------------------
-
-async function runScenario({ core, events, clientId, approvals, scenario, runDir, opts, attempt }) {
- const sandboxRoot = path.join(runDir, "sandbox");
- const sandbox = path.join(sandboxRoot, scenario.id);
- await fsp.rm(sandbox, { recursive: true, force: true });
- await copyDir(FIXTURES, sandbox);
- await fsp.mkdir(path.join(sandbox, "out"), { recursive: true });
- const before = await snapshotTree(sandbox);
-
- const usageBefore = await usageIds(core);
- const approvalsMark = approvals ? approvals.decisions.length : 0;
- const threadId = `ls-${scenario.id}-${attempt}-${randomBytes(3).toString("hex")}`;
-
- // The desktop driver has no per-turn `cwd`: the action dir is the whole
- // sandbox root, so the task has to say which folder inside it is its own.
- // The RPC driver scopes `cwd` to the folder itself and needs no preamble.
- const message =
- opts.driver === "desktop"
- ? `All paths in this task are relative to the folder \`${scenario.id}/\` inside your action directory. Work only inside that folder.\n\n${scenario.prompt}`
- : scenario.prompt;
-
- const t0 = Date.now();
- let turn;
- let error = null;
- try {
- turn =
- opts.driver === "desktop"
- ? await sendDesktopTurn({ core, events, clientId, threadId, message, opts })
- : await sendRpcTurn({ core, threadId, message, sandbox, opts });
- if (turn.error) error = turn.error;
- } catch (e) {
- error = String(e.message).slice(0, 600);
- turn = { reply: "", usage: null, requestId: null, toolCalls: [] };
- }
- const latencyMs = Date.now() - t0;
-
- // Cost rows can land a beat after the turn reports done.
- await sleep(1500);
- const usageAfter = await usageIds(core);
- const newRows = [...usageAfter.entries()]
- .filter(([id]) => !usageBefore.has(id))
- .map(([, r]) => r);
- const usage = reconcileUsage(turn.usage, foldUsage(newRows));
-
- // The run ledger is written only by the web-chat bridge, so it exists on the
- // desktop driver and not the RPC one.
- let ledger = null;
- if (turn.requestId) {
- ledger = await core
- .rpc("openhuman.run_ledger_get", { id: turn.requestId })
- .then((r) => (r && r.run) || null)
- .catch(() => null);
- }
-
- const after = await snapshotTree(sandbox);
- const beforeSet = new Map(before.map((f) => [f.rel, f]));
- const written = after.filter(
- (f) => !beforeSet.has(f.rel) || beforeSet.get(f.rel).mtimeMs !== f.mtimeMs,
- );
-
- const grade = gradeScenario(scenario, sandbox, turn.reply);
-
- return {
- scenario: scenario.id,
- title: scenario.title,
- attempt,
- driver: opts.driver,
- thread_id: threadId,
- request_id: turn.requestId,
- ok: !error,
- error,
- latency_ms: latencyMs,
- ledger_elapsed_ms: ledger && ledger.telemetry ? ledger.telemetry.elapsedMs : null,
- tool_calls: turn.toolCalls,
- tool_call_count:
- ledger && ledger.telemetry && ledger.telemetry.toolCount != null
- ? ledger.telemetry.toolCount
- : turn.toolCalls.length,
- approvals_requested: approvals ? approvals.countSince(approvalsMark) : 0,
- reply_chars: (turn.reply || "").length,
- reply: (turn.reply || "").slice(0, 4000),
- files_written: written.map((f) => ({ rel: f.rel, bytes: f.bytes })),
- usage,
- grade,
- sandbox,
- };
-}
-
-// ---------------------------------------------------------------------------
-// reporting
-// ---------------------------------------------------------------------------
-
-const fmtUsd = (n) => `$${n.toFixed(4)}`;
-const fmtTok = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
-
-function printReport(results) {
- console.log("");
- console.table(
- results.map((r) => ({
- scenario: r.scenario,
- done: `${r.grade.passed}/${r.grade.total}`,
- pct: `${Math.round(r.grade.score * 100)}%`,
- tools: r.tool_call_count,
- appr: r.approvals_requested,
- in: fmtTok(r.usage.input_tokens),
- cached: `${r.usage.cache_hit_pct.toFixed(0)}%`,
- out: fmtTok(r.usage.output_tokens),
- cost: fmtUsd(r.usage.cost_usd),
- latency: `${(r.latency_ms / 1000).toFixed(1)}s`,
- status: r.ok ? "ok" : "ERROR",
- })),
- );
-
- const tot = results.reduce(
- (a, r) => {
- a.input += r.usage.input_tokens;
- a.cached += r.usage.cached_input_tokens;
- a.output += r.usage.output_tokens;
- a.cost += r.usage.cost_usd;
- a.latency += r.latency_ms;
- a.tools += r.tool_call_count;
- a.approvals += r.approvals_requested;
- a.passed += r.grade.passed;
- a.total += r.grade.total;
- return a;
- },
- { input: 0, cached: 0, output: 0, cost: 0, latency: 0, tools: 0, approvals: 0, passed: 0, total: 0 },
- );
- console.log(
- `TOTAL completion ${tot.passed}/${tot.total} (${Math.round(
- (tot.passed / Math.max(1, tot.total)) * 100,
- )}%) tools ${tot.tools} approvals ${tot.approvals} in ${fmtTok(
- tot.input,
- )} cached ${((tot.cached / Math.max(1, tot.input)) * 100).toFixed(
- 1,
- )}% out ${fmtTok(tot.output)} cost ${fmtUsd(tot.cost)} wall ${(
- tot.latency / 1000
- ).toFixed(1)}s`,
- );
-
- for (const r of results) {
- const failed = r.grade.checks.filter((c) => !c.ok);
- if (!failed.length && r.ok) continue;
- console.log(`\n ${r.scenario}:`);
- if (r.error) console.log(` ! turn error: ${r.error}`);
- for (const f of failed)
- console.log(` x ${f.id}${f.detail ? ` — ${f.detail}` : ""}`);
- }
- console.log("");
-}
-
-// ---------------------------------------------------------------------------
-// main
-// ---------------------------------------------------------------------------
-
-async function main() {
- const opts = parseArgs(process.argv.slice(2));
-
- if (opts.gradeOnly) {
- const results = [];
- for (const s of SCENARIOS) {
- const sandbox = path.join(opts.gradeOnly, "sandbox", s.id);
- if (!fs.existsSync(sandbox)) continue;
- results.push({
- scenario: s.id,
- ok: true,
- error: null,
- latency_ms: 0,
- tool_call_count: 0,
- approvals_requested: 0,
- usage: foldUsage([]),
- grade: gradeScenario(s, sandbox, ""),
- });
- }
- printReport(results);
- return;
- }
-
- const selected = opts.only.length ? opts.only.map(scenarioById) : SCENARIOS;
- const runId = new Date().toISOString().replace(/[:.]/g, "-");
- const runDir = path.join(opts.runRoot, runId);
- const actionRoot = path.join(runDir, "sandbox");
- await fsp.mkdir(actionRoot, { recursive: true });
-
- if (!fs.existsSync(opts.coreBin))
- throw new Error(
- `core binary not found at ${opts.coreBin}\n` +
- `build it: cargo build --manifest-path Cargo.toml -p openhuman-cli --bin openhuman-core`,
- );
- if (!opts.managed && !opts.apiKey)
- throw new Error(
- "no inference key: set OPENROUTER_API_KEY, pass --api-key, or use --managed",
- );
-
- console.log(`run dir : ${runDir}`);
- console.log(`driver : ${opts.driver}${opts.agentId ? ` agent=${opts.agentId}` : " agent=orchestrator"}`);
-
- let search = null;
- if (opts.mockSearch) {
- search = await startMockSearch({
- indexPath: DEFAULT_INDEX_PATH,
- requestsPath: path.join(runDir, "search-requests.json"),
- port: opts.searchPort,
- });
- console.log(
- `search : mock at ${search.url} (${search.ctx.documents.length} documents)`,
- );
- }
-
- const home = await prepareHome(runDir, opts, {
- searchBase: search ? search.url : "",
- });
-
- let composio = null;
- if (opts.mockComposio) {
- composio = await startMockComposio({
- fixtureRoot: FIXTURES,
- outboxPath: path.join(runDir, "composio-outbox.json"),
- port: opts.composioPort,
- });
- console.log(
- `composio: mock at ${composio.url} (${composio.ctx.mailbox.length} messages, ${composio.ctx.calendar.length} events)`,
- );
- }
-
- const core = new Core(opts);
- const health = await core.start({
- actionDir: actionRoot,
- logPath: path.join(runDir, "core.log"),
- home,
- composioBase: composio ? composio.url : "",
- searchBase: search ? search.url : "",
- approvals: opts.approvals,
- });
- console.log(`core : ${core.url} (pid ${health.pid}, healthy=${health.healthy})`);
-
- // Stand in for login.
- const localUserId = "life-scenarios-local";
- await core.rpc("openhuman.auth_set_credential", {
- token: mintLocalSessionToken(localUserId),
- kind: "local",
- userId: localUserId,
- user: {
- _id: localUserId,
- email: "[email protected]",
- name: "Life Scenarios",
- },
- });
-
- // Point inference at OpenRouter the way the Settings → Models screen does.
- // `channel_web_chat` carries no per-turn route, so on the desktop path this
- // is the only way to run BYOK — which is also how a BYOK desktop user runs.
- if (!opts.managed) {
- // The three documented BYOK fields, and nothing else. Until
- // `complete_byok_route` (crates/openhuman-core/src/config/ops/model.rs)
- // this was accepted and then every turn died `BYOK_INCOMPLETE`, because
- // role resolution goes through `cloud_providers` and nothing had put the
- // endpoint there; the caller had to hand-build a provider entry and pin
- // four roles. That this short form now routes is the end-to-end check on
- // that fix.
- //
- // Written in a loop, and read back, because of a startup race: the write
- // lands in whichever config is active *now*, and `auth_set_credential`
- // above activates a per-user dir (`users/<id>/config.toml`) a moment
- // later, whose config then takes precedence and carries no BYOK route.
- // Lose that race and every scenario dies in under a second with
- // `provider=openhuman ... 401 Invalid token` — which reads like a broken
- // harness and is really a config that arrived too early. Observed doing
- // exactly that: one run green, the next 0/9 on the same binary.
- await withRetries(
- async () => {
- await core.rpc("openhuman.config_update_model_settings", {
- inference_url: opts.inferenceUrl,
- api_key: opts.apiKey,
- default_model: opts.model,
- });
- // `config.get` wraps the config under `config` (see
- // `snapshot_config_json`), and the RPC envelope may wrap that again.
- const snap = await core.rpc("openhuman.config_get", {});
- const cfg = snap?.config ?? snap?.snapshot?.config ?? snap?.snapshot ?? snap ?? {};
- const providers = cfg.cloud_providers ?? [];
- const routed =
- cfg.inference_url === opts.inferenceUrl &&
- providers.some((p) => p?.endpoint === opts.inferenceUrl);
- if (!routed)
- throw new Error(
- `BYOK route not in the active config yet (inference_url=${cfg.inference_url ?? "unset"}, ` +
- `${providers.length} cloud_providers)`,
- );
- },
- { attempts: 10, delayMs: 500, what: "BYOK route" },
- );
- }
-
- // The web-chat driver has no per-call `agent_id`, so the agent is chosen by
- // `[agent] chat_agent_id`. Set it through the running core rather than by
- // pre-writing the file, for exactly the reason the BYOK block above gives:
- // `prepareHome` writes `users/local/config.toml`, but the active user dir is
- // minted at boot (`users/local-dragonfly/...`) and its config wins. The
- // pre-written value is read by nothing, and the turn silently runs the
- // orchestrator at its own 15-iteration cap — which looks like the benchmark
- // agent failing when it never ran at all.
- const chatAgentId = opts.agentId.trim() || null;
- await withRetries(
- async () => {
- await core.rpc("openhuman.config_update_agent_settings", {
- chat_agent_id: opts.agentId,
- });
- const snap = await core.rpc("openhuman.config_get", {});
- const cfg = snap?.config ?? snap?.snapshot?.config ?? snap?.snapshot ?? snap ?? {};
- const got = cfg.agent?.chat_agent_id ?? null;
- if (got !== chatAgentId)
- throw new Error(
- `chat_agent_id not in the active config yet (want ${chatAgentId ?? "unset"}, got ${got ?? "unset"})`,
- );
- },
- { attempts: 10, delayMs: 500, what: "chat_agent_id" },
- );
-
- console.log(
- `route : ${opts.managed ? "managed backend" : opts.inferenceUrl} model=${opts.model}`,
- );
-
- const clientId = `life-scenarios-${runId.slice(0, 12)}`;
- const events = new EventStream(core, clientId);
- if (opts.driver === "desktop") await events.connect();
-
- const approvals = opts.approvals ? new ApprovalResponder(core) : null;
- approvals?.start();
- console.log(
- `approve : ${opts.approvals ? "gate ON, headless responder approving" : "gate DISABLED"}`,
- );
-
- const results = [];
- try {
- for (let attempt = 1; attempt <= opts.repeat; attempt += 1) {
- for (const scenario of selected) {
- process.stdout.write(`running ${scenario.id} (attempt ${attempt}) ... `);
- const r = await runScenario({
- core,
- events,
- clientId,
- approvals,
- scenario,
- runDir,
- opts,
- attempt,
- });
- results.push(r);
- console.log(
- `${r.ok ? "ok" : "ERROR"} ${(r.latency_ms / 1000).toFixed(1)}s ` +
- `${r.grade.passed}/${r.grade.total} tools=${r.tool_call_count} ${fmtUsd(
- r.usage.cost_usd,
- )}`,
- );
- await fsp.writeFile(
- path.join(runDir, "results.json"),
- JSON.stringify(results, null, 2),
- );
- }
- }
- } finally {
- await approvals?.stop();
- events.close();
- await core.stop();
- if (approvals)
- await fsp.writeFile(
- path.join(runDir, "approvals.json"),
- JSON.stringify({ decisions: approvals.decisions, errors: approvals.errors }, null, 2),
- );
- if (composio) {
- await fsp.writeFile(
- path.join(runDir, "composio-requests.json"),
- JSON.stringify(
- { requests: composio.ctx.requests, outbox: composio.ctx.outbox },
- null,
- 2,
- ),
- );
- await composio.close();
- }
- // `close` flushes the search log itself, so the record survives a run that
- // failed partway: it is the only evidence of what discovery returned, and
- // a post-mortem needs it most on the runs that went wrong.
- if (search) await search.close();
- }
-
- printReport(results);
- console.log(`results : ${path.join(runDir, "results.json")}`);
- console.log(`core log: ${path.join(runDir, "core.log")}`);
-}
-
-main().catch((e) => {
- console.error(`\nfatal: ${e.stack || e.message}`);
- process.exit(1);
-});
diff --git a/scripts/life-scenarios/scenarios.mjs b/scripts/life-scenarios/scenarios.mjs
deleted file mode 100644
index 9b04202bac..0000000000
--- a/scripts/life-scenarios/scenarios.mjs
+++ /dev/null
@@ -1,542 +0,0 @@
-/**
- * Six "real life" assistant tasks, rewritten over a mock corpus that lives in
- * `fixtures/`. Nothing here touches a real mailbox, calendar or bank: the
- * corpus is fictional (Alex Rivera <[email protected]>) and every domain
- * is `*.example`, so a run is reproducible and safe to commit.
- *
- * Each scenario is a prompt plus a *grader*. The grader is the part that makes
- * the number mean something — "the turn completed" is not completion, and a
- * model that writes a plausible-looking CSV full of invented rows has to score
- * zero on the rows it invented. Graders therefore check facts that are only
- * derivable from the fixtures.
- *
- * Grader contract: `grade(ctx) -> { checks: [{ id, ok, detail }] }` where
- * `ctx.read(relPath)` returns the file's text (or null), `ctx.exists(relPath)`,
- * and `ctx.transcript` is the final assistant message.
- */
-
-import path from "node:path";
-
-const TODAY = "2026-09-22"; // fixtures are anchored here; see README.md
-
-// ---------------------------------------------------------------------------
-// helpers shared by graders
-// ---------------------------------------------------------------------------
-
-const norm = (s) => (s || "").toLowerCase();
-
-/** Case-insensitive "does the text mention all of these". */
-function mentionsAll(text, needles) {
- const t = norm(text);
- return needles.filter((n) => !t.includes(norm(n)));
-}
-
-/** Parse a CSV into rows of trimmed cells. Tolerates quoted fields. */
-function parseCsv(text) {
- const rows = [];
- let row = [];
- let cell = "";
- let quoted = false;
- for (let i = 0; i < text.length; i += 1) {
- const c = text[i];
- if (quoted) {
- if (c === '"') {
- if (text[i + 1] === '"') {
- cell += '"';
- i += 1;
- } else quoted = false;
- } else cell += c;
- continue;
- }
- if (c === '"') quoted = true;
- else if (c === ",") {
- row.push(cell.trim());
- cell = "";
- } else if (c === "\n") {
- row.push(cell.trim());
- if (row.some((x) => x !== "")) rows.push(row);
- row = [];
- cell = "";
- } else if (c !== "\r") cell += c;
- }
- row.push(cell.trim());
- if (row.some((x) => x !== "")) rows.push(row);
- return rows;
-}
-
-/** Pull every `$12.34` / `12.34 USD` style amount out of a string. */
-function amounts(text) {
- return [...(text || "").matchAll(/\$?\s?(\d+(?:\.\d{2}))/g)].map((m) =>
- Number(m[1]),
- );
-}
-
-const check = (id, ok, detail = "") => ({ id, ok: Boolean(ok), detail });
-
-// ---------------------------------------------------------------------------
-// scenarios
-// ---------------------------------------------------------------------------
-
-export const SCENARIOS = [
- // -------------------------------------------------------------------------
- {
- id: "calendar-buffer",
- title: "Smart calendar & meeting buffer",
- capabilities: ["file_read", "file_write", "temporal reasoning"],
- // 7 events on 2026-09-23. Three of them start less than 15 minutes after
- // the previous one ends: ev-02 (0 min), ev-05 (0 min), ev-06 (10 min).
- prompt: `Today is ${TODAY}. My calendar for tomorrow is the JSON file at \`calendar/calendar.json\` (relative to your working directory).
-
-Find every pair of consecutive meetings on 2026-09-23 where the second meeting starts less than 15 minutes after the first one ends. Ignore events that have no attendee other than me.
-
-For each one, decide whether to push the second meeting back so there is at least a 15 minute gap, and draft a short rescheduling email to that meeting's organizer asking for the adjustment.
-
-Write your result to \`out/meeting_buffer_plan.json\` with exactly this shape:
-
-{
- "conflicts": [
- { "event_id": "...", "title": "...", "gap_minutes": 0, "proposed_start": "2026-09-23T09:45:00-04:00", "organizer": "..." }
- ],
- "emails": [
- { "to": "...", "subject": "...", "body": "..." }
- ]
-}
-
-Do not invent meetings that are not in the file.`,
- grade(ctx) {
- const raw = ctx.read("out/meeting_buffer_plan.json");
- if (!raw) return { checks: [check("output_exists", false, "file missing")] };
- let doc;
- try {
- doc = JSON.parse(raw);
- } catch (e) {
- return {
- checks: [
- check("output_exists", true),
- check("valid_json", false, String(e.message).slice(0, 120)),
- ],
- };
- }
- const conflicts = Array.isArray(doc.conflicts) ? doc.conflicts : [];
- const ids = new Set(conflicts.map((c) => String(c.event_id || "").trim()));
- const emails = Array.isArray(doc.emails) ? doc.emails : [];
- const expected = ["ev-02", "ev-05", "ev-06"];
- const missing = expected.filter((e) => !ids.has(e));
- const spurious = [...ids].filter((i) => !expected.includes(i));
- // ev-06 already has a 10 minute gap; getting that one right is the test
- // of "less than 15" rather than "zero".
- const gapOk = conflicts.every((c) => {
- if (c.event_id === "ev-06") return Number(c.gap_minutes) === 10;
- if (c.event_id === "ev-02" || c.event_id === "ev-05")
- return Number(c.gap_minutes) === 0;
- return true;
- });
- const organizers = new Set(
- conflicts.map((c) => norm(c.organizer)).filter(Boolean),
- );
- return {
- checks: [
- check("output_exists", true),
- check("valid_json", true),
- check(
- "found_all_three_conflicts",
- missing.length === 0,
- missing.length ? `missing ${missing.join(",")}` : "",
- ),
- check(
- "no_hallucinated_conflicts",
- spurious.length === 0,
- spurious.length ? `extra ${spurious.join(",")}` : "",
- ),
- check("gap_minutes_correct", gapOk),
- check(
- "skipped_solo_event",
- !ids.has("ev-07"),
- ids.has("ev-07") ? "flagged the solo focus block" : "",
- ),
- check(
- "drafted_an_email_per_conflict",
- emails.length >= Math.min(3, conflicts.length) && emails.length > 0,
- `${emails.length} emails for ${conflicts.length} conflicts`,
- ),
- check(
- "emails_address_real_organizers",
- emails.length > 0 &&
- emails.every((e) =>
- [...organizers].some((o) => norm(e.to).includes(o)),
- ),
- ),
- ],
- };
- },
- },
-
- // -------------------------------------------------------------------------
- {
- id: "subscription-scan",
- title: "Subscription & recurring expense scanner",
- capabilities: ["file_read", "grep", "file_write", "parsing"],
- prompt: `Today is ${TODAY}. The directory \`mailbox/\` (relative to your working directory) holds my recent receipt and bank-notification emails as plain text files.
-
-Read them and identify every genuine recurring subscription. A one-off purchase, a usage-based utility bill, and a phishing email are not subscriptions. A bank card alert that duplicates a merchant receipt you already counted is not a second subscription.
-
-Write \`out/subscriptions.csv\` with exactly this header and one row per subscription:
-
-service,cost,frequency,last_billed,price_increase
-
-- \`cost\` is the most recent amount as a plain number, e.g. 15.99
-- \`frequency\` is \`monthly\` or \`yearly\`
-- \`last_billed\` is ISO \`YYYY-MM-DD\`
-- \`price_increase\` is \`yes\` if an earlier receipt in the mailbox shows a lower price for the same service, otherwise \`no\`
-
-Then write a one-paragraph summary of what you flagged to \`out/subscriptions_notes.md\`.`,
- grade(ctx) {
- const raw = ctx.read("out/subscriptions.csv");
- if (!raw) return { checks: [check("output_exists", false, "file missing")] };
- const rows = parseCsv(raw);
- const header = (rows[0] || []).map((h) => norm(h));
- const body = rows.slice(1);
- const byService = new Map();
- for (const r of body) {
- if (!r[0]) continue;
- byService.set(norm(r[0]).replace(/[^a-z]/g, ""), r);
- }
- const get = (name) => byService.get(name.replace(/[^a-z]/g, ""));
- const streamflix = get("streamflix");
- const clouddrive = get("clouddrivepro") || get("clouddrive");
- const newsdaily = get("newsdaily");
- const gympass = get("gympass");
- const found = [streamflix, clouddrive, newsdaily, gympass].filter(Boolean);
- const distractors = ["mealbox", "metroelectric", "premiumvault", "firstharbor"];
- const leaked = distractors.filter((d) =>
- [...byService.keys()].some((k) => k.includes(d.replace(/[^a-z]/g, ""))),
- );
- const col = (row, name) => {
- const i = header.indexOf(name);
- return i >= 0 && row ? row[i] : undefined;
- };
- return {
- checks: [
- check("output_exists", true),
- check(
- "header_exact",
- header.join(",") ===
- "service,cost,frequency,last_billed,price_increase",
- header.join(","),
- ),
- check(
- "all_four_subscriptions",
- found.length === 4,
- `found ${found.length}/4`,
- ),
- check(
- "no_distractors",
- leaked.length === 0,
- leaked.length ? `counted ${leaked.join(",")}` : "",
- ),
- check("row_count_is_four", body.length === 4, `${body.length} rows`),
- check(
- "streamflix_cost_1599",
- streamflix && Number(col(streamflix, "cost")) === 15.99,
- ),
- check(
- "streamflix_price_increase_yes",
- streamflix && norm(col(streamflix, "price_increase")).startsWith("y"),
- ),
- check(
- "gympass_price_increase_no",
- gympass && norm(col(gympass, "price_increase")).startsWith("n"),
- ),
- check(
- "newsdaily_yearly",
- newsdaily && norm(col(newsdaily, "frequency")).includes("year"),
- ),
- check(
- "clouddrive_last_billed",
- clouddrive && String(col(clouddrive, "last_billed")).includes("2026-09-12"),
- ),
- check("notes_written", ctx.exists("out/subscriptions_notes.md")),
- ],
- };
- },
- },
-
- // -------------------------------------------------------------------------
- {
- id: "baggage-policy",
- title: "Airline baggage policy summariser (live web)",
- capabilities: ["web_search", "web_fetch", "file_write"],
- // The only scenario that leaves the sandbox. Airline baggage rules are
- // public, non-personal, and change often enough that a model answering
- // from memory is detectable: the grader demands a cited source URL.
- prompt: `I am flying Skyward Atlantic (a real airline you should look up as "Delta Air Lines" — use Delta's own published policy) from JFK to LHR in Basic Economy.
-
-Search the web for Delta Air Lines' current published baggage policy and read the official delta.com pages. Extract the actual allowance for Basic Economy on a transatlantic route: carry-on dimensions and any weight limit, personal item allowance, checked bag allowance, and the fee for the first and second checked bag.
-
-Write \`out/delta_baggage_guide.md\` as a short markdown guide. It must contain:
-- a table of the limits with exact numbers and units
-- a "Fees" section
-- a "Sources" section listing the delta.com URLs you actually fetched, one per line
-
-If the live pages do not state something, say so explicitly rather than filling it in from memory.`,
- grade(ctx) {
- const doc = ctx.read("out/delta_baggage_guide.md");
- if (!doc) return { checks: [check("output_exists", false, "file missing")] };
- const urls = [...doc.matchAll(/https?:\/\/[^\s)\]]+/g)].map((m) => m[0]);
- const deltaUrls = urls.filter((u) => /(^|\/\/|\.)delta\.com/i.test(u));
- const hasDims = /\b22\s*(x|×)\s*14\s*(x|×)\s*9\b/i.test(doc) ||
- /\b\d{2}\s*(x|×)\s*\d{2}\s*(x|×)\s*\d{1,2}\s*(in|inch|cm)/i.test(doc);
- return {
- checks: [
- check("output_exists", true),
- check("has_table", /\|.*\|/.test(doc)),
- check("has_fees_section", /##\s*fees/i.test(doc)),
- check("has_sources_section", /##\s*sources/i.test(doc)),
- check(
- "cites_delta_com",
- deltaUrls.length > 0,
- `${urls.length} urls, ${deltaUrls.length} on delta.com`,
- ),
- check("states_carryon_dimensions", hasDims),
- check(
- "mentions_personal_item",
- /personal item/i.test(doc),
- ),
- check("mentions_basic_economy", /basic economy/i.test(doc)),
- check(
- "mentions_checked_allowance",
- /checked/i.test(doc) && /(fee|\$|free|included)/i.test(doc),
- ),
- ],
- };
- },
- },
-
- // -------------------------------------------------------------------------
- {
- id: "meal-plan",
- title: "Weekly meal plan & deduplicated grocery list",
- capabilities: ["generation", "constraint satisfaction", "file_write"],
- prompt: `Create a 5-day dinner meal plan for a family of 4 that is Mediterranean-diet friendly and keeps active prep time under 30 minutes per night. Reuse shared ingredients across nights so nothing is bought for a single meal — spinach, feta and olive oil should each appear in at least two dinners.
-
-Write \`out/meal_plan.md\`. Use one \`## Day N — <dish>\` heading per night, and under each give an \`Active prep: N minutes\` line, an ingredient list with quantities scaled for 4 people, and brief steps.
-
-Then write \`out/grocery_list.txt\`: a single consolidated shopping checklist for all five dinners. Group it under supermarket aisle headings written as \`[Aisle name]\` on their own line, with one \`- item — quantity\` per line underneath. Every ingredient must appear exactly once, with the quantities summed across all five nights.`,
- grade(ctx) {
- const plan = ctx.read("out/meal_plan.md");
- const list = ctx.read("out/grocery_list.txt");
- if (!plan || !list)
- return {
- checks: [
- check("plan_exists", Boolean(plan)),
- check("list_exists", Boolean(list)),
- ],
- };
- const days = [...plan.matchAll(/^##\s*Day\s*(\d)/gim)].map((m) => m[1]);
- const prepTimes = [...plan.matchAll(/active prep:\s*(\d+)/gi)].map((m) =>
- Number(m[1]),
- );
- const aisles = [...list.matchAll(/^\s*\[([^\]]+)\]\s*$/gm)].map((m) =>
- m[1].trim(),
- );
- const items = [...list.matchAll(/^\s*[-*]\s*(.+?)(?:\s+[—–-]\s+|:)/gm)].map(
- (m) => norm(m[1]).replace(/[^a-z ]/g, "").trim(),
- );
- const dupes = items.filter((it, i) => items.indexOf(it) !== i);
- const shared = ["spinach", "feta", "olive oil"];
- const sharedCounts = shared.map((ing) => ({
- ing,
- n: (plan.match(new RegExp(ing, "gi")) || []).length,
- }));
- return {
- checks: [
- check("plan_exists", true),
- check("list_exists", true),
- check("five_days", new Set(days).size === 5, `days: ${days.join(",")}`),
- check(
- "prep_times_stated",
- prepTimes.length >= 5,
- `${prepTimes.length} stated`,
- ),
- check(
- "prep_under_30",
- prepTimes.length > 0 && prepTimes.every((p) => p <= 30),
- `max ${Math.max(0, ...prepTimes)}`,
- ),
- check(
- "aisle_headings",
- aisles.length >= 3,
- `aisles: ${aisles.join(" / ")}`,
- ),
- check("items_parsed", items.length >= 12, `${items.length} items`),
- check(
- "no_duplicate_items",
- dupes.length === 0,
- dupes.length ? `dupes: ${[...new Set(dupes)].join(", ")}` : "",
- ),
- check(
- "shared_ingredients_reused",
- sharedCounts.every((s) => s.n >= 2),
- sharedCounts.map((s) => `${s.ing}=${s.n}`).join(" "),
- ),
- check(
- "quantities_present",
- (list.match(/\d/g) || []).length >= 10,
- ),
- ],
- };
- },
- },
-
- // -------------------------------------------------------------------------
- {
- id: "trip-itinerary",
- title: "Multi-source trip itinerary & logistics",
- capabilities: [
- "file_read",
- "pdf extraction",
- "web_fetch",
- "synthesis",
- "file_write",
- ],
- // The hardest one: three sources in three formats (text email, binary PDF,
- // live web) plus a routing/ordering judgement, into one HTML artifact.
- prompt: `Today is ${TODAY}. Build a complete 3-day Tokyo itinerary from my own documents.
-
-Sources, relative to your working directory:
-- \`mailbox/2026-09-18-flight.txt\` — my flight confirmation
-- \`documents/hotel_booking_tokyo.pdf\` — my hotel booking (a real PDF; extract the text from it, do not guess)
-
-Do this:
-1. Read both and establish the exact dates I am actually in Tokyo, the hotel name, its address, and its nearest station.
-2. Look up the typical mid-October weather for Tokyo and say where you got it. Put outdoor activities on the better days and indoor ones (museums, markets, galleries) on the wetter or colder days.
-3. Plan each day as a sequence of venues that are geographically sensible from the hotel, and give an estimated walking or train time between consecutive venues.
-4. Write \`out/tokyo_trip_master.html\` — a single self-contained HTML page with a section per day, a table of venues with arrival times and transit times, and an "Emergency information" section with Japan's emergency numbers and the address and phone number of my hotel.
-
-Only use dates when I am actually in Tokyo. Do not schedule anything for a travel day I spend in the air.`,
- grade(ctx) {
- const html = ctx.read("out/tokyo_trip_master.html");
- if (!html) return { checks: [check("output_exists", false, "file missing")] };
- const t = norm(html);
- const missingFacts = mentionsAll(html, [
- "Sakura View Hotel",
- "Nishi-Shinjuku",
- "+81 3-5555-0142",
- "QK7F2P",
- ]);
- // In Tokyo 15–18 Oct; 14 Oct is spent in the air.
- const mentions14 = /(oct(ober)?\s*14|14\s*oct|2026-10-14)/i.test(html);
- const dayCount = (html.match(/<h2[^>]*>/gi) || []).length;
- return {
- checks: [
- check("output_exists", true),
- check("is_html", /<html/i.test(html) && /<\/html>/i.test(html)),
- check(
- "read_the_pdf",
- missingFacts.filter((f) => f !== "QK7F2P").length === 0,
- missingFacts.length ? `missing: ${missingFacts.join(", ")}` : "",
- ),
- check("has_flight_confirmation", /QK7F2P/i.test(html)),
- check(
- "correct_stay_dates",
- /15/.test(html) && /18/.test(html) && /oct/i.test(html),
- ),
- check(
- "excludes_travel_day",
- !mentions14,
- mentions14 ? "scheduled something on 14 Oct (in the air)" : "",
- ),
- check("three_day_sections", dayCount >= 3, `${dayCount} <h2>`),
- check("has_venue_table", /<table/i.test(html)),
- check(
- "has_transit_times",
- /(\d+\s*(min|minute))/i.test(html) &&
- /(walk|train|metro|subway|line)/i.test(html),
- ),
- check(
- "emergency_numbers",
- t.includes("110") && t.includes("119"),
- ),
- check("weather_sourced", /(weather|climate)/i.test(html) && /https?:\/\//.test(html)),
- ],
- };
- },
- },
-
- // -------------------------------------------------------------------------
- {
- id: "fact-check-publish",
- title: "Fact-check, reformat and lint a draft",
- capabilities: ["file_read", "web_search", "transform", "verification"],
- prompt: `Today is ${TODAY}. My draft article is at \`drafts/draft.md\` (relative to your working directory).
-
-1. Read it and list every factual claim and every hyperlink.
-2. Verify the claims against current sources on the web. The remote-work statistic in the opening is several years old — replace it with a current, verified figure and cite the source inline.
-3. Check every hyperlink and every image path. Image paths are relative to \`drafts/\`; at least one asset referenced by the draft does not exist on disk, and at least one hyperlink does not resolve. Find them.
-4. Produce two versions:
- - \`out/dist/newsletter.html\` — a self-contained HTML email template (inline styles, table-based layout, no external CSS)
- - \`out/dist/post.md\` — a markdown post keeping the YAML front matter, with the corrected stats and links
-5. Write \`out/dist/lint_report.md\` listing every broken link and missing image path you found, each with the exact path or URL and why it failed. Do not ship a broken reference into either output.`,
- grade(ctx) {
- const html = ctx.read("out/dist/newsletter.html");
- const md = ctx.read("out/dist/post.md");
- const lint = ctx.read("out/dist/lint_report.md");
- const checks = [
- check("newsletter_exists", Boolean(html)),
- check("post_exists", Boolean(md)),
- check("lint_report_exists", Boolean(lint)),
- ];
- if (!html || !md || !lint) return { checks };
- const brokenImg = "handoff-latency-chart.png";
- const brokenLink = "example.com/blog/async-standups-2019";
- checks.push(
- check("newsletter_is_html", /<html/i.test(html) || /<table/i.test(html)),
- check(
- "newsletter_inline_styles",
- /style\s*=\s*"/i.test(html) && !/<link[^>]+stylesheet/i.test(html),
- ),
- check("post_keeps_front_matter", /^---[\s\S]*?title:/m.test(md)),
- check(
- "lint_names_missing_image",
- norm(lint).includes(brokenImg),
- "expected the missing chart asset",
- ),
- check(
- "lint_names_broken_link",
- norm(lint).includes(norm(brokenLink)) ||
- norm(lint).includes("async-standups"),
- ),
- check(
- "missing_image_not_shipped",
- !norm(html).includes(brokenImg) && !norm(md).includes(brokenImg),
- ),
- check(
- "broken_link_not_shipped",
- !norm(html).includes(norm(brokenLink)) &&
- !norm(md).includes(norm(brokenLink)),
- ),
- check(
- "stat_updated",
- !/as of 2021/i.test(md),
- "the 2021 remote-work stat survived unchanged",
- ),
- check(
- "stat_has_citation",
- /\[[^\]]+\]\(https?:\/\/[^)]+\)/.test(md),
- ),
- );
- return { checks };
- },
- },
-];
-
-export function scenarioById(id) {
- const s = SCENARIOS.find((x) => x.id === id);
- if (!s) throw new Error(`unknown scenario '${id}'`);
- return s;
-}
-
-export const FIXTURES_DIR = path.join(
- path.dirname(new URL(import.meta.url).pathname),
- "fixtures",
-);
diff --git a/scripts/profile/README.md b/scripts/profile/README.md
deleted file mode 100644
index 1aca638065..0000000000
--- a/scripts/profile/README.md
+++ /dev/null
@@ -1,145 +0,0 @@
-# `scripts/profile/`
-
-Reproducible benchmarking scripts for the OpenHuman Rust core as an embedded
-library (no RPC server), built around the `library-profile` and `rss-bench`
-binaries (see [`crates/openhuman-cli/src/bin/library_profile/main.rs`](../../crates/openhuman-cli/src/bin/library_profile/main.rs) and [`rss_bench.rs`](../../crates/openhuman-cli/src/bin/rss_bench.rs)).
-
-Six driver scripts: [`library-bench.sh`](./library-bench.sh) (per-scenario RSS/duration),
-[`library-cpu.sh`](./library-cpu.sh) (samply), [`library-heap.sh`](./library-heap.sh) (dhat), [`library-fleet.sh`](./library-fleet.sh)
-(fleet-scale sweep + budget gate), [`library-instances.sh`](./library-instances.sh) (multi-process
-instance sweep), and [`rss-bench.sh`](./rss-bench.sh) (embedded-roster RSS, #5046). A seventh, [`library-pool-gate.sh`](./library-pool-gate.sh), is the runtime-pool regression gate.
-
-Benchmarks run from these scripts, not in CI. For the server-process counterpart see [`scripts/bench/`](../bench/README.md).
-
-## Scripts
-
-### `rss-bench.sh`: embedded agent-roster RSS (#5046)
-
-Builds the stripped-release `rss-bench` binary, runs its fixture tests, then
-measures steady-state RSS/PSS of 5 fresh processes × {1, 8} agents against the
-20 MiB target and 30 MiB hard cap. This was the report-only `rust-rss-bench`
-CI job until benchmarks moved out of CI.
-
-```bash
-./scripts/profile/rss-bench.sh # build + run, JSON to target/profile/rss-bench.json
-./scripts/profile/rss-bench.sh --skip-build --out /path/rss.json
-```
-
-### `library-bench.sh`: RSS/duration benchmark
-
-Builds `library-profile` + `rss-bench`, runs each scenario N times as a fresh
-process, and aggregates median/min/max duration, settled RSS, retained delta,
-and peak delta into `summary.json` + `summary.md`.
-
-```bash
-./scripts/profile/library-bench.sh # all 6 scenarios, default build, 5 repeats
-./scripts/profile/library-bench.sh --slim --repeat 7 # slim (no-default-features) build
-./scripts/profile/library-bench.sh --scenarios "long-agent,subagent-storm" --turns 50 --warm
-```
-
-Results land in `target/profile/rust-library/bench-<timestamp>/` (or `--out DIR`).
-
-### `library-cpu.sh`: CPU profile via samply
-
-Wraps `samply record` around one scenario, isolated from persistence/timezone
-noise by default (matching the documented cold-path CPU recipe).
-
-```bash
-./scripts/profile/library-cpu.sh subagent-storm
-./scripts/profile/library-cpu.sh long-agent -- OPENHUMAN_PROFILE_TURNS=50
-samply load target/profile/rust-library/subagent-storm-cpu.json.gz
-```
-
-### `library-heap.sh`: live heap attribution via dhat
-
-Builds the `rss-bench-dhat` variant and runs one scenario under dhat. RSS and
-timing numbers from this build are perturbed by instrumentation; use it only
-for allocation-site/retained-bytes attribution, not for RSS comparisons.
-
-```bash
-./scripts/profile/library-heap.sh agent-turn
-# open https://nnethercote.github.io/dh_view/dh_view.html and load
-# target/profile/rust-library/dhat-agent-turn.json
-```
-
-### `library-fleet.sh`: fleet sweep + 2 GB / 2 vCPU budget gate
-
-Builds `library-profile` + `rss-bench`, sweeps the `fleet` scenario (N
-concurrent live agents with latency-realistic mock inference) across a list
-of agent counts, aggregates medians per N, and gates on whether the
-projected footprint at the target agent count fits the RAM budget.
-
-```bash
-./scripts/profile/library-fleet.sh --agents 100 --latency-ms 200
-./scripts/profile/library-fleet.sh --agents "50,100,500" --target 1000 --budget-mib 2048
-```
-
-Results land in `target/profile/rust-library/fleet-<timestamp>/` (or
-`--out DIR`). Exits nonzero if any swept N reports `fits: false` (use
-`--no-gate` to report only). The script's `--help` documents the budget math.
-
-### `library-instances.sh`: multi-instance (many-processes) sweep
-
-Spawns N independent `library-profile` processes (each a live instance held
-alive via `OPENHUMAN_PROFILE_HOLD_SECS`), staggered on startup, and measures
-**per-process** cost and box survivability, the opencompany "N independent
-processes/containers" deployment model, as opposed to `library-fleet.sh`'s
-"N agents in one process" model. Samples aggregate sum-RSS + live count every
-2s while instances hold, captures a `vm_stat` snapshot at peak (and a
-best-effort `footprint` sample if that macOS tool is present), then
-aggregates per swept N: launched/ok counts, median settled RSS per instance,
-mean and peak aggregate sum-RSS, and, on Linux, where it's meaningful ,
-summed PSS.
-
-```bash
-./scripts/profile/library-instances.sh --instances "10,50" --hold-secs 30
-./scripts/profile/library-instances.sh --instances "100,500" --max-instances 500 --gate
-```
-
-Results land in `target/profile/rust-library/instances-<timestamp>/` (or
-`--out DIR`). Refuses to spawn more than `--max-instances` (default 200)
-without an explicit raise, see the script's `--help` for the RAM math. Exits
-nonzero with `--gate` if any instance failed to complete cleanly (nonzero
-exit or missing/invalid JSON); default is report-only.
-
-### `library-pool-gate.sh`: runtime pool regression gate (#5106)
-
-Drives the `skill-run` scenario with K parallel skill runs and asserts the DoD:
-with the shared runtime pool ON, the process tree grows by ~one pooled worker,
-**not** K interpreters. The scenario hard-asserts `tree.child_count <= max_workers`
-for K > 1 (nonzero exit); this script runs it and reports a pooled-vs-unpooled
-comparison. A regression that reintroduces per-run forking fails the gate.
-
-```bash
-./scripts/profile/library-pool-gate.sh # K=8, max_workers=1
-./scripts/profile/library-pool-gate.sh --concurrency 16 --skip-build
-```
-
-Exits 0 = pass, 1 = regression. SKIPs (exit 0) when no system `node` is on
-`PATH` (the scenario must never download an interpreter), so node-less CI
-runners don't false-fail.
-
-## Quick start
-
-```bash
-# 1. Baseline RSS/duration across all scenarios
-./scripts/profile/library-bench.sh
-
-# 2. CPU attribution for the slowest/most interesting scenario
-./scripts/profile/library-cpu.sh subagent-storm
-
-# 3. If a scenario's RSS looks off, drill into live heap
-./scripts/profile/library-heap.sh subagent-storm
-```
-
-All scripts require `jq` for JSON parsing/aggregation; `library-cpu.sh` also
-requires `samply` (`cargo install samply`). Build commands use
-`GGML_NATIVE=OFF` to work around the Apple Silicon whisper-rs/llama.cpp NEON
-fp16 build issue.
-
-## Further reading
-
-- [`docs/library-benchmarking.md`](../../docs/library-benchmarking.md) and [`docs/library-minimal-recipe.md`](../../docs/library-minimal-recipe.md), the methodology behind these scripts.
-- [Performance and footprint](../../gitbooks/developing/performance.md) for the published numbers and [Embedding OpenHuman](../../gitbooks/developing/embedding.md) for the library these scripts measure.
-- [`crates/openhuman-embed/`](../../crates/openhuman-embed/README.md), the facade the scenarios drive.
-- The public [openhuman-benchmarks](https://github.com/tinyhumansai/openhuman-benchmarks) repo.
diff --git a/scripts/profile/library-bench.sh b/scripts/profile/library-bench.sh
deleted file mode 100755
index f21d9843c1..0000000000
--- a/scripts/profile/library-bench.sh
+++ /dev/null
@@ -1,318 +0,0 @@
-#!/usr/bin/env bash
-# library-bench.sh — reproducible RSS/duration benchmark for the OpenHuman
-# core as an embedded library, using the `library-profile` binary.
-#
-# Runs each scenario N times as a FRESH process (no state shared across
-# repeats), captures each run's JSON, and aggregates medians/min/max into a
-# markdown + JSON summary. Companion scripts: library-cpu.sh (samply),
-# library-heap.sh (dhat).
-#
-# Usage:
-# ./scripts/profile/library-bench.sh [options]
-#
-# Options:
-# --slim Build with --no-default-features (slim library recipe)
-# --repeat N Fresh-process repeats per scenario (default: 5)
-# --scenarios "a,b,c" Comma-separated scenario list (default: all seven)
-# --turns N OPENHUMAN_PROFILE_TURNS for long-agent (default binary default: 25)
-# --skip-build Reuse the existing target/release binaries
-# --warm Also run PREWARM_SUBAGENTS=1 variants for subagent-storm
-# --out DIR Output directory (default: target/profile/rust-library/bench-<timestamp>)
-# -h, --help Show this help
-#
-# Examples:
-# ./scripts/profile/library-bench.sh
-# ./scripts/profile/library-bench.sh --slim --repeat 7
-# ./scripts/profile/library-bench.sh --scenarios "long-agent,subagent-storm" --turns 50 --warm
-
-set -euo pipefail
-
-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
-
-# The scenarios `library-profile` actually dispatches — keep in sync with
-# `crates/openhuman-cli/src/bin/library_profile/scenarios/mod.rs`, which is the source of truth.
-#
-# This list had drifted before openhuman#6161 touched it: it named two
-# scenarios that had not existed for some time. `dispatch` answers "unknown
-# scenario: …" for those, so a full sweep exited non-zero on two entries that
-# could never run. `memory-ingest` and `cold-phases` leave now
-# for a different reason: both measured the in-process memory engine, which
-# this binary no longer links.
-ALL_SCENARIOS="agent-turn,long-agent,workflow,fleet,skill-run,subagent-storm"
-WARM_ELIGIBLE=("subagent-storm")
-
-SLIM=0
-REPEAT=5
-SCENARIOS="$ALL_SCENARIOS"
-TURNS=""
-SKIP_BUILD=0
-WARM=0
-OUT_DIR=""
-
-usage() {
- sed -n '2,26p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
- exit "${1:-0}"
-}
-
-while [[ $# -gt 0 ]]; do
- case "$1" in
- --slim) SLIM=1; shift ;;
- --repeat)
- REPEAT="${2:?--repeat requires a value}"; shift 2 ;;
- --scenarios)
- SCENARIOS="${2:?--scenarios requires a value}"; shift 2 ;;
- --turns)
- TURNS="${2:?--turns requires a value}"; shift 2 ;;
- --skip-build) SKIP_BUILD=1; shift ;;
- --warm) WARM=1; shift ;;
- --out)
- OUT_DIR="${2:?--out requires a value}"; shift 2 ;;
- -h|--help) usage 0 ;;
- *)
- echo "ERROR: unknown argument: $1" >&2
- usage 1 ;;
- esac
-done
-
-if ! command -v jq >/dev/null 2>&1; then
- echo "ERROR: jq is required (aggregation over run JSON). Install it (e.g. 'brew install jq')." >&2
- exit 1
-fi
-
-if [[ -z "$OUT_DIR" ]]; then
- OUT_DIR="$REPO_ROOT/target/profile/rust-library/bench-$(date +%Y%m%d-%H%M%S)"
-fi
-mkdir -p "$OUT_DIR"
-
-BIN="$REPO_ROOT/target/release/library-profile"
-
-log() { echo "[library-bench] $*" >&2; }
-
-build_binaries() {
- if [[ "$SKIP_BUILD" -eq 1 ]]; then
- log "skipping build (--skip-build)"
- return
- fi
- local feature_args=(--features rss-bench)
- if [[ "$SLIM" -eq 1 ]]; then
- feature_args=(--no-default-features --features rss-bench)
- log "building slim library-profile + rss-bench (GGML_NATIVE=OFF)"
- else
- log "building default-feature library-profile + rss-bench (GGML_NATIVE=OFF)"
- fi
- (
- cd "$REPO_ROOT"
- GGML_NATIVE=OFF cargo build --release \
- "${feature_args[@]}" \
- --bin library-profile --bin rss-bench
- )
-}
-
-run_scenario() {
- local scenario="$1"
- local variant="$2" # "" or "warm"
- local label="$scenario"
- [[ -n "$variant" ]] && label="${scenario}-${variant}"
-
- local scenario_dir="$OUT_DIR/$label"
- mkdir -p "$scenario_dir"
-
- log "running scenario '$label' x$REPEAT (fresh process each run)"
-
- local i
- for ((i = 1; i <= REPEAT; i++)); do
- local run_file="$scenario_dir/run-$i.json"
- local env_args=()
- if [[ "$scenario" == "long-agent" && -n "$TURNS" ]]; then
- env_args+=(env "OPENHUMAN_PROFILE_TURNS=$TURNS")
- fi
- if [[ "$variant" == "warm" ]]; then
- env_args+=(env "OPENHUMAN_PROFILE_PREWARM_SUBAGENTS=1")
- fi
-
- if [[ ${#env_args[@]} -gt 0 ]]; then
- "${env_args[@]}" "$BIN" "$scenario" >"$run_file"
- else
- "$BIN" "$scenario" >"$run_file"
- fi
-
- if ! jq empty "$run_file" >/dev/null 2>&1; then
- echo "ERROR: run $i for scenario '$label' did not produce valid JSON: $run_file" >&2
- exit 1
- fi
-
- # library-heap.sh clobbers target/release/library-profile with the
- # rss-bench-dhat build, whose allocator perturbs RSS/timing. The dhat
- # binary marks its output, so refuse to benchmark it.
- if [[ "$(jq -r '.dhat // false' "$run_file")" == "true" ]]; then
- echo "ERROR: $BIN was built with rss-bench-dhat (library-heap.sh clobbered it)." >&2
- echo " Re-run without --skip-build to rebuild the plain rss-bench binary." >&2
- exit 1
- fi
- done
-}
-
-# Emit the median (lower-middle for even N), min, and max of a jq numeric
-# field across the run files for one scenario, as a JSON object on stdout.
-aggregate_field() {
- local scenario_dir="$1"
- local jq_path="$2"
- jq -s "
- [ .[] | $jq_path | select(. != null) ] as \$vals |
- (\$vals | sort) as \$sorted |
- (\$sorted | length) as \$n |
- {
- median: (if \$n == 0 then null else \$sorted[(( \$n - 1) / 2 | floor)] end),
- min: (\$sorted[0] // null),
- max: (\$sorted[-1] // null),
- n: \$n
- }
- " "$scenario_dir"/run-*.json
-}
-
-aggregate_scenario() {
- local label="$1"
- local scenario_dir="$OUT_DIR/$label"
-
- local duration settled_rss retained_delta peak_delta
- duration=$(aggregate_field "$scenario_dir" ".duration_ms")
- settled_rss=$(aggregate_field "$scenario_dir" ".settled.rss_kib")
- retained_delta=$(aggregate_field "$scenario_dir" ".retained_delta_kib")
- peak_delta=$(aggregate_field "$scenario_dir" ".peak_delta_kib")
-
- local turn_growth="null"
- if [[ "$label" == long-agent* ]]; then
- # first-turn vs last-turn checkpoint rss delta (steady-state growth).
- turn_growth=$(jq -s '
- [ .[] |
- (.checkpoints // []) as $cps |
- if ($cps | length) >= 2 then
- ($cps[-1].rss_kib - $cps[0].rss_kib)
- else empty end
- ] as $vals |
- ($vals | sort) as $sorted |
- ($sorted | length) as $n |
- if $n == 0 then null
- else $sorted[((($n - 1) / 2) | floor)]
- end
- ' "$scenario_dir"/run-*.json)
- fi
-
- jq -n \
- --arg scenario "$label" \
- --argjson duration "$duration" \
- --argjson settled_rss "$settled_rss" \
- --argjson retained_delta "$retained_delta" \
- --argjson peak_delta "$peak_delta" \
- --argjson turn_growth_kib "$turn_growth" \
- '{
- scenario: $scenario,
- duration_ms: $duration,
- settled_rss_kib: $settled_rss,
- retained_delta_kib: $retained_delta,
- peak_delta_kib: $peak_delta,
- long_agent_turn_growth_kib: $turn_growth_kib
- }'
-}
-
-kib_to_mib() {
- # $1: kib value (may be null). Prints "n/a" for null.
- local kib="$1"
- if [[ "$kib" == "null" || -z "$kib" ]]; then
- echo "n/a"
- return
- fi
- jq -n --argjson kib "$kib" '($kib / 1024 * 100 | round) / 100'
-}
-
-write_summary() {
- local summary_json="$OUT_DIR/summary.json"
- local summary_md="$OUT_DIR/summary.md"
-
- jq -s '{ generated_at: (now | todate), build: ($ENV.LIBRARY_BENCH_BUILD // "default"), repeat: ($ENV.LIBRARY_BENCH_REPEAT | tonumber), scenarios: . }' \
- "$OUT_DIR"/*.scenario.json >"$summary_json"
-
- {
- echo "# Library benchmark summary"
- echo
- echo "Build: \`${LIBRARY_BENCH_BUILD}\` "
- echo "Repeats per scenario: ${LIBRARY_BENCH_REPEAT} "
- echo "Generated: $(date)"
- echo
- echo "| Scenario | Median settled RSS (MiB) | Median retained Δ (MiB) | Median peak Δ (MiB) | Median duration (ms) |"
- echo "| --- | ---: | ---: | ---: | ---: |"
- local f
- for f in "$OUT_DIR"/*.scenario.json; do
- local scenario settled retained peak duration
- scenario=$(jq -r '.scenario' "$f")
- settled=$(kib_to_mib "$(jq -r '.settled_rss_kib.median' "$f")")
- retained=$(kib_to_mib "$(jq -r '.retained_delta_kib.median' "$f")")
- peak=$(kib_to_mib "$(jq -r '.peak_delta_kib.median' "$f")")
- duration=$(jq -r '.duration_ms.median // "n/a"' "$f")
- echo "| $scenario | $settled | $retained | $peak | $duration |"
- done
- echo
- local long_growth_file
- for long_growth_file in "$OUT_DIR"/long-agent*.scenario.json; do
- [[ -e "$long_growth_file" ]] || continue
- local growth
- growth=$(jq -r '.long_agent_turn_growth_kib // "n/a"' "$long_growth_file")
- if [[ "$growth" != "n/a" && "$growth" != "null" ]]; then
- local growth_mib
- growth_mib=$(kib_to_mib "$growth")
- echo "**$(jq -r '.scenario' "$long_growth_file") steady-state growth** (first-turn to last-turn checkpoint delta, median across runs): ${growth_mib} MiB."
- echo
- fi
- done
- cat <<'EOF'
-## External comparison point (not apples-to-apples)
-
-ZeroClaw self-reports (unverified) idling under 5 MiB RAM and roughly 8-12 MiB
-under load. OpenHuman's Rust core currently settles around 35-50 MiB depending
-on scenario and feature set. Treat this as
-a north star, not a like-for-like comparison: ZeroClaw's feature surface and
-scope differ substantially from the OpenHuman core.
-EOF
- } >"$summary_md"
-}
-
-main() {
- build_binaries
-
- if [[ ! -x "$BIN" ]]; then
- echo "ERROR: $BIN not found or not executable. Build it or drop --skip-build." >&2
- exit 1
- fi
-
- IFS=',' read -r -a scenario_list <<<"$SCENARIOS"
-
- for scenario in "${scenario_list[@]}"; do
- run_scenario "$scenario" ""
- if [[ "$WARM" -eq 1 ]]; then
- for eligible in "${WARM_ELIGIBLE[@]}"; do
- if [[ "$scenario" == "$eligible" ]]; then
- run_scenario "$scenario" "warm"
- fi
- done
- fi
- done
-
- # Build one *.scenario.json per label for the summary step.
- for scenario_dir in "$OUT_DIR"/*/; do
- [[ -d "$scenario_dir" ]] || continue
- local_label="$(basename "$scenario_dir")"
- aggregate_scenario "$local_label" >"$OUT_DIR/${local_label}.scenario.json"
- done
-
- export LIBRARY_BENCH_BUILD
- LIBRARY_BENCH_BUILD=$([[ "$SLIM" -eq 1 ]] && echo "slim" || echo "default")
- export LIBRARY_BENCH_REPEAT="$REPEAT"
-
- write_summary
-
- log "results: $OUT_DIR"
- cat "$OUT_DIR/summary.md"
-}
-
-main "$@"
diff --git a/scripts/profile/library-cpu.sh b/scripts/profile/library-cpu.sh
deleted file mode 100755
index 4f1b492bf3..0000000000
--- a/scripts/profile/library-cpu.sh
+++ /dev/null
@@ -1,104 +0,0 @@
-#!/usr/bin/env bash
-# library-cpu.sh — samply wrapper for a CPU profile of one library-profile
-# scenario, following the cold-path CPU profiling recipe.
-#
-# Usage:
-# ./scripts/profile/library-cpu.sh <scenario> [-- <extra env VAR=value>...]
-# ./scripts/profile/library-cpu.sh --no-isolate <scenario>
-#
-# Options:
-# --no-isolate Do not force OPENHUMAN_PROFILE_DISABLE_MEMORY_WRITES=1 /
-# OPENHUMAN_PROFILE_FORCE_UTC=1 (default: isolated, matching
-# the documented cold-path CPU recipe)
-# --skip-build Reuse the existing target/release/library-profile binary
-# -h, --help Show this help
-#
-# Extra environment variables can be passed after `--`, e.g.:
-# ./scripts/profile/library-cpu.sh long-agent -- OPENHUMAN_PROFILE_TURNS=50
-#
-# Output: target/profile/rust-library/<scenario>-cpu.json.gz
-# View it with: samply load target/profile/rust-library/<scenario>-cpu.json.gz
-
-set -euo pipefail
-
-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
-
-ISOLATE=1
-SKIP_BUILD=0
-SCENARIO=""
-EXTRA_ENV=()
-
-usage() {
- sed -n '2,20p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
- exit "${1:-0}"
-}
-
-while [[ $# -gt 0 ]]; do
- case "$1" in
- --no-isolate) ISOLATE=0; shift ;;
- --skip-build) SKIP_BUILD=1; shift ;;
- -h|--help) usage 0 ;;
- --)
- shift
- EXTRA_ENV=("$@")
- break
- ;;
- *)
- if [[ -z "$SCENARIO" ]]; then
- SCENARIO="$1"
- shift
- else
- echo "ERROR: unexpected argument: $1" >&2
- usage 1
- fi
- ;;
- esac
-done
-
-if [[ -z "$SCENARIO" ]]; then
- echo "ERROR: scenario is required" >&2
- usage 1
-fi
-
-if ! command -v samply >/dev/null 2>&1; then
- echo "ERROR: samply is required. Install it with 'cargo install samply'." >&2
- exit 1
-fi
-
-BIN="$REPO_ROOT/target/release/library-profile"
-
-if [[ "$SKIP_BUILD" -eq 0 ]]; then
- echo "[library-cpu] building library-profile (GGML_NATIVE=OFF)" >&2
- (
- cd "$REPO_ROOT"
- GGML_NATIVE=OFF cargo build --release --features rss-bench --bin library-profile
- )
-fi
-
-if [[ ! -x "$BIN" ]]; then
- echo "ERROR: $BIN not found or not executable. Build it or drop --skip-build." >&2
- exit 1
-fi
-
-OUT_DIR="$REPO_ROOT/target/profile/rust-library"
-mkdir -p "$OUT_DIR"
-OUT_FILE="$OUT_DIR/${SCENARIO}-cpu.json.gz"
-
-ENV_ARGS=()
-if [[ "$ISOLATE" -eq 1 ]]; then
- ENV_ARGS+=(OPENHUMAN_PROFILE_DISABLE_MEMORY_WRITES=1 OPENHUMAN_PROFILE_FORCE_UTC=1)
-fi
-ENV_ARGS+=("${EXTRA_ENV[@]+"${EXTRA_ENV[@]}"}")
-
-echo "[library-cpu] recording scenario '$SCENARIO' -> $OUT_FILE" >&2
-env "${ENV_ARGS[@]+"${ENV_ARGS[@]}"}" samply record \
- --save-only \
- --unstable-presymbolicate \
- --rate 1000 \
- --iteration-count 5 \
- --output "$OUT_FILE" \
- -- "$BIN" "$SCENARIO"
-
-echo "[library-cpu] done: $OUT_FILE" >&2
-echo "[library-cpu] view it with: samply load $OUT_FILE" >&2
diff --git a/scripts/profile/library-fleet.sh b/scripts/profile/library-fleet.sh
deleted file mode 100755
index 4f8221f15a..0000000000
--- a/scripts/profile/library-fleet.sh
+++ /dev/null
@@ -1,371 +0,0 @@
-#!/usr/bin/env bash
-# library-fleet.sh — sweep the `fleet` scenario of library-profile across
-# agent counts and gate the result against the 2 GB RAM / 2 vCPU server
-# budget (100-1000 live agents). Companion scripts: library-bench.sh
-# (per-scenario RSS/duration), library-cpu.sh (samply), library-heap.sh
-# (dhat).
-#
-# Usage:
-# ./scripts/profile/library-fleet.sh [options]
-#
-# Options:
-# --agents "50,100,500" Comma-separated agent-count sweep (default: "50,100,500")
-# --turns N OPENHUMAN_PROFILE_TURNS per agent (default: 3)
-# --latency-ms N OPENHUMAN_PROFILE_MOCK_LATENCY_MS (default: 200)
-# --workers N OPENHUMAN_PROFILE_WORKER_THREADS, simulates the
-# 2 vCPU box (default: 2)
-# --repeat N Fresh-process repeats per agent count (default: 3)
-# --target N OPENHUMAN_PROFILE_TARGET_AGENTS (default: 1000)
-# --budget-mib N OPENHUMAN_PROFILE_RAM_BUDGET_MIB (default: 2048)
-# --skip-build Reuse the existing target/release binaries
-# --slim Build with --no-default-features (slim library recipe)
-# --out DIR Output directory (default: target/profile/rust-library/fleet-<timestamp>)
-# --no-gate Do not fail the exit code on fits==false (report only)
-# -h, --help Show this help
-#
-# Examples:
-# ./scripts/profile/library-fleet.sh
-# ./scripts/profile/library-fleet.sh --agents 100 --latency-ms 200
-# ./scripts/profile/library-fleet.sh --agents "100,1000" --target 1000 --budget-mib 2048
-
-set -euo pipefail
-
-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
-
-AGENTS="50,100,500"
-TURNS=3
-LATENCY_MS=200
-WORKERS=2
-REPEAT=3
-TARGET=1000
-BUDGET_MIB=2048
-SKIP_BUILD=0
-SLIM=0
-OUT_DIR=""
-GATE=1
-
-# Idle CPU is measured over a 10s parked window and should be ~flat
-# regardless of agent count (idle agents cost ~zero CPU). 500ms of CPU
-# across that window (5% of one core) is the "low" threshold used in the
-# PASS/FAIL verdict line.
-IDLE_CPU_MS_MAX=500
-
-usage() {
- sed -n '2,27p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
- exit "${1:-0}"
-}
-
-while [[ $# -gt 0 ]]; do
- case "$1" in
- --agents)
- AGENTS="${2:?--agents requires a value}"; shift 2 ;;
- --turns)
- TURNS="${2:?--turns requires a value}"; shift 2 ;;
- --latency-ms)
- LATENCY_MS="${2:?--latency-ms requires a value}"; shift 2 ;;
- --workers)
- WORKERS="${2:?--workers requires a value}"; shift 2 ;;
- --repeat)
- REPEAT="${2:?--repeat requires a value}"; shift 2 ;;
- --target)
- TARGET="${2:?--target requires a value}"; shift 2 ;;
- --budget-mib)
- BUDGET_MIB="${2:?--budget-mib requires a value}"; shift 2 ;;
- --skip-build) SKIP_BUILD=1; shift ;;
- --slim) SLIM=1; shift ;;
- --out)
- OUT_DIR="${2:?--out requires a value}"; shift 2 ;;
- --no-gate) GATE=0; shift ;;
- -h|--help) usage 0 ;;
- *)
- echo "ERROR: unknown argument: $1" >&2
- usage 1 ;;
- esac
-done
-
-if ! command -v jq >/dev/null 2>&1; then
- echo "ERROR: jq is required (aggregation over run JSON). Install it (e.g. 'brew install jq')." >&2
- exit 1
-fi
-
-if [[ -z "$OUT_DIR" ]]; then
- OUT_DIR="$REPO_ROOT/target/profile/rust-library/fleet-$(date +%Y%m%d-%H%M%S)"
-fi
-mkdir -p "$OUT_DIR"
-
-BIN="$REPO_ROOT/target/release/library-profile"
-
-log() { echo "[library-fleet] $*" >&2; }
-
-build_binaries() {
- if [[ "$SKIP_BUILD" -eq 1 ]]; then
- log "skipping build (--skip-build)"
- return
- fi
- local feature_args=(--features rss-bench)
- if [[ "$SLIM" -eq 1 ]]; then
- feature_args=(--no-default-features --features rss-bench)
- log "building slim library-profile + rss-bench (GGML_NATIVE=OFF)"
- else
- log "building default-feature library-profile + rss-bench (GGML_NATIVE=OFF)"
- fi
- (
- cd "$REPO_ROOT"
- GGML_NATIVE=OFF cargo build --release \
- "${feature_args[@]}" \
- --bin library-profile --bin rss-bench
- )
-}
-
-run_sweep_point() {
- local n="$1"
- local point_dir="$OUT_DIR/fleet-$n"
- mkdir -p "$point_dir"
-
- log "running fleet scenario with $n agents x$REPEAT (fresh process each run)"
-
- local i
- for ((i = 1; i <= REPEAT; i++)); do
- local run_file="$point_dir/run-$i.json"
-
- env \
- "OPENHUMAN_PROFILE_AGENTS=$n" \
- "OPENHUMAN_PROFILE_TURNS=$TURNS" \
- "OPENHUMAN_PROFILE_MOCK_LATENCY_MS=$LATENCY_MS" \
- "OPENHUMAN_PROFILE_WORKER_THREADS=$WORKERS" \
- "OPENHUMAN_PROFILE_TARGET_AGENTS=$TARGET" \
- "OPENHUMAN_PROFILE_RAM_BUDGET_MIB=$BUDGET_MIB" \
- "$BIN" fleet >"$run_file"
-
- if ! jq empty "$run_file" >/dev/null 2>&1; then
- echo "ERROR: run $i for agents=$n did not produce valid JSON: $run_file" >&2
- exit 1
- fi
-
- # library-heap.sh clobbers target/release/library-profile with the
- # rss-bench-dhat build, whose allocator perturbs RSS/timing. The dhat
- # binary marks its output, so refuse to benchmark it.
- if [[ "$(jq -r '.dhat // false' "$run_file")" == "true" ]]; then
- echo "ERROR: $BIN was built with rss-bench-dhat (library-heap.sh clobbered it)." >&2
- echo " Re-run without --skip-build to rebuild the plain rss-bench binary." >&2
- exit 1
- fi
- done
-}
-
-# Emit the median (lower-middle for even N), min, and max of a jq numeric
-# field across the run files for one sweep point, as a JSON object on stdout.
-aggregate_field() {
- local point_dir="$1"
- local jq_path="$2"
- jq -s "
- [ .[] | $jq_path | select(. != null) ] as \$vals |
- (\$vals | sort) as \$sorted |
- (\$sorted | length) as \$n |
- {
- median: (if \$n == 0 then null else \$sorted[(( \$n - 1) / 2 | floor)] end),
- min: (\$sorted[0] // null),
- max: (\$sorted[-1] // null),
- n: \$n
- }
- " "$point_dir"/run-*.json
-}
-
-# fits is a boolean per run; report it as "fits" only when every repeat
-# agreed it fits (a single unlucky repeat should not hide a marginal case).
-aggregate_fits() {
- local point_dir="$1"
- jq -s '
- [ .[] | .budget.fits // false ] as $vals |
- ($vals | length) as $n |
- ($vals | map(select(. == true)) | length) as $true_n |
- { all_fit: ($n > 0 and $true_n == $n), true_n: $true_n, n: $n }
- ' "$point_dir"/run-*.json
-}
-
-aggregate_point() {
- local n="$1"
- local point_dir="$OUT_DIR/fleet-$n"
-
- local marginal settled_rss idle_cpu threads open_fds p50 p95 p99 projected fits
- marginal=$(aggregate_field "$point_dir" ".marginal_rss_kib_per_agent")
- settled_rss=$(aggregate_field "$point_dir" ".settled.rss_kib")
- idle_cpu=$(aggregate_field "$point_dir" ".idle_cpu_ms")
- threads=$(aggregate_field "$point_dir" ".settled.threads")
- open_fds=$(aggregate_field "$point_dir" ".settled.open_fds")
- p50=$(aggregate_field "$point_dir" ".turn_latency_ms.p50")
- p95=$(aggregate_field "$point_dir" ".turn_latency_ms.p95")
- p99=$(aggregate_field "$point_dir" ".turn_latency_ms.p99")
- projected=$(aggregate_field "$point_dir" ".budget.projected_rss_mib_at_target")
- fits=$(aggregate_fits "$point_dir")
-
- jq -n \
- --argjson agents "$n" \
- --argjson marginal_rss_kib_per_agent "$marginal" \
- --argjson settled_rss_kib "$settled_rss" \
- --argjson idle_cpu_ms "$idle_cpu" \
- --argjson threads "$threads" \
- --argjson open_fds "$open_fds" \
- --argjson p50 "$p50" \
- --argjson p95 "$p95" \
- --argjson p99 "$p99" \
- --argjson projected_rss_mib_at_target "$projected" \
- --argjson fits "$fits" \
- '{
- agents: $agents,
- marginal_rss_kib_per_agent: $marginal_rss_kib_per_agent,
- settled_rss_kib: $settled_rss_kib,
- idle_cpu_ms: $idle_cpu_ms,
- threads: $threads,
- open_fds: $open_fds,
- turn_latency_ms: { p50: $p50, p95: $p95, p99: $p99 },
- projected_rss_mib_at_target: $projected_rss_mib_at_target,
- fits: $fits
- }'
-}
-
-kib_to_mib() {
- # $1: kib value (may be null/"null"). Prints "n/a" for null.
- local kib="$1"
- if [[ "$kib" == "null" || -z "$kib" ]]; then
- echo "n/a"
- return
- fi
- jq -n --argjson kib "$kib" '($kib / 1024 * 100 | round) / 100'
-}
-
-num_or_na() {
- local v="$1"
- [[ "$v" == "null" || -z "$v" ]] && echo "n/a" || echo "$v"
-}
-
-write_summary() {
- local summary_json="$OUT_DIR/summary.json"
- local summary_md="$OUT_DIR/summary.md"
-
- jq -s \
- --argjson turns "$TURNS" \
- --argjson latency_ms "$LATENCY_MS" \
- --argjson workers "$WORKERS" \
- --argjson repeat "$REPEAT" \
- --argjson target "$TARGET" \
- --argjson budget_mib "$BUDGET_MIB" \
- --arg build "$([[ "$SLIM" -eq 1 ]] && echo "slim" || echo "default")" \
- '{
- generated_at: (now | todate),
- build: $build,
- config: {
- turns: $turns,
- mock_latency_ms: $latency_ms,
- worker_threads: $workers,
- repeat: $repeat,
- target_agents: $target,
- ram_budget_mib: $budget_mib
- },
- sweep: .
- }' \
- "$OUT_DIR"/*.point.json >"$summary_json"
-
- local any_fail=0
-
- {
- echo "# Fleet benchmark summary"
- echo
- echo "Build: \`$([[ "$SLIM" -eq 1 ]] && echo "slim" || echo "default")\` "
- echo "Repeats per agent count: ${REPEAT} "
- echo "Turns/agent: ${TURNS}, mock latency: ${LATENCY_MS}ms, worker threads: ${WORKERS} "
- echo "Target: ${TARGET} agents, budget: ${BUDGET_MIB} MiB "
- echo "Generated: $(date)"
- echo
- echo "| N | marginal KiB/agent | settled MiB | idle CPU ms/10s | threads | fds | p95 ms | projected MiB @ target | fits |"
- echo "| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | :---: |"
-
- local f
- for f in "$OUT_DIR"/*.point.json; do
- local n marginal settled idle threads fds p95 projected fits_all
- n=$(jq -r '.agents' "$f")
- marginal=$(num_or_na "$(jq -r '.marginal_rss_kib_per_agent.median' "$f")")
- settled=$(kib_to_mib "$(jq -r '.settled_rss_kib.median' "$f")")
- idle=$(num_or_na "$(jq -r '.idle_cpu_ms.median' "$f")")
- threads=$(num_or_na "$(jq -r '.threads.median' "$f")")
- fds=$(num_or_na "$(jq -r '.open_fds.median' "$f")")
- p95=$(num_or_na "$(jq -r '.turn_latency_ms.p95.median' "$f")")
- projected=$(num_or_na "$(jq -r '.projected_rss_mib_at_target.median' "$f")")
- fits_all=$(jq -r '.fits.all_fit' "$f")
- echo "| $n | $marginal | $settled | $idle | $threads | $fds | $p95 | $projected | $fits_all |"
- done
-
- echo
- echo "## Verdict"
- echo
-
- for f in "$OUT_DIR"/*.point.json; do
- local n fits_all idle_median verdict reasons
- n=$(jq -r '.agents' "$f")
- fits_all=$(jq -r '.fits.all_fit' "$f")
- idle_median=$(jq -r '.idle_cpu_ms.median // "null"' "$f")
-
- reasons=""
- verdict="PASS"
- if [[ "$fits_all" != "true" ]]; then
- verdict="FAIL"
- reasons="${reasons}projected RSS at target does not fit ${BUDGET_MIB} MiB budget; "
- any_fail=1
- fi
- local idle_over
- idle_over=0
- if [[ "$idle_median" != "null" ]]; then
- idle_over=$(jq -n --argjson v "$idle_median" --argjson max "$IDLE_CPU_MS_MAX" 'if $v > $max then 1 else 0 end')
- fi
- if [[ "$idle_over" -eq 1 ]]; then
- verdict="FAIL"
- reasons="${reasons}idle CPU ${idle_median}ms/10s exceeds ${IDLE_CPU_MS_MAX}ms threshold; "
- fi
-
- if [[ "$verdict" == "PASS" ]]; then
- echo "- **N=$n: PASS** — fits budget, idle CPU low."
- else
- echo "- **N=$n: FAIL** — ${reasons}"
- fi
- done
- } >"$summary_md"
-
- if [[ "$any_fail" -eq 1 ]]; then
- return 1
- fi
- return 0
-}
-
-main() {
- build_binaries
-
- if [[ ! -x "$BIN" ]]; then
- echo "ERROR: $BIN not found or not executable. Build it or drop --skip-build." >&2
- exit 1
- fi
-
- IFS=',' read -r -a agent_list <<<"$AGENTS"
-
- local n
- for n in "${agent_list[@]}"; do
- run_sweep_point "$n"
- done
-
- for n in "${agent_list[@]}"; do
- aggregate_point "$n" >"$OUT_DIR/fleet-$n.point.json"
- done
-
- local gate_status=0
- write_summary || gate_status=1
-
- log "results: $OUT_DIR"
- cat "$OUT_DIR/summary.md"
-
- if [[ "$GATE" -eq 1 && "$gate_status" -ne 0 ]]; then
- log "GATE FAILED: at least one swept N does not fit the ${BUDGET_MIB} MiB / ${TARGET}-agent budget"
- exit 1
- fi
-}
-
-main "$@"
diff --git a/scripts/profile/library-heap.sh b/scripts/profile/library-heap.sh
deleted file mode 100755
index a62b7de035..0000000000
--- a/scripts/profile/library-heap.sh
+++ /dev/null
@@ -1,93 +0,0 @@
-#!/usr/bin/env bash
-# library-heap.sh — builds the rss-bench-dhat variant of library-profile and
-# runs one scenario under dhat heap profiling.
-#
-# Note: dhat instrumentation perturbs RSS/timing measurements. Use
-# library-bench.sh / library-cpu.sh for RSS and CPU numbers; use this script
-# only for live-heap attribution (allocation sites, retained bytes).
-#
-# This build REPLACES target/release/library-profile with the dhat variant.
-# A later `library-bench.sh --skip-build` would pick it up; the bench script
-# detects the dhat marker in the output JSON and refuses, but the clean fix
-# is to rerun library-bench.sh without --skip-build afterwards.
-#
-# Usage:
-# ./scripts/profile/library-heap.sh <scenario> [-- <extra env VAR=value>...]
-#
-# Options:
-# --skip-build Reuse the existing target/release/library-profile binary
-# -h, --help Show this help
-#
-# Output: target/profile/rust-library/dhat-<scenario>.json
-# View it at: https://nnethercote.github.io/dh_view/dh_view.html
-
-set -euo pipefail
-
-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
-
-SKIP_BUILD=0
-SCENARIO=""
-EXTRA_ENV=()
-
-usage() {
- sed -n '2,17p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
- exit "${1:-0}"
-}
-
-while [[ $# -gt 0 ]]; do
- case "$1" in
- --skip-build) SKIP_BUILD=1; shift ;;
- -h|--help) usage 0 ;;
- --)
- shift
- EXTRA_ENV=("$@")
- break
- ;;
- *)
- if [[ -z "$SCENARIO" ]]; then
- SCENARIO="$1"
- shift
- else
- echo "ERROR: unexpected argument: $1" >&2
- usage 1
- fi
- ;;
- esac
-done
-
-if [[ -z "$SCENARIO" ]]; then
- echo "ERROR: scenario is required" >&2
- usage 1
-fi
-
-BIN="$REPO_ROOT/target/release/library-profile"
-OUT_DIR="$REPO_ROOT/target/profile/rust-library"
-mkdir -p "$OUT_DIR"
-OUT_FILE="$OUT_DIR/dhat-${SCENARIO}.json"
-
-if [[ "$SKIP_BUILD" -eq 0 ]]; then
- echo "[library-heap] building library-profile with rss-bench-dhat (GGML_NATIVE=OFF)" >&2
- (
- cd "$REPO_ROOT"
- GGML_NATIVE=OFF cargo build --release --features rss-bench-dhat --bin library-profile
- )
-fi
-
-if [[ ! -x "$BIN" ]]; then
- echo "ERROR: $BIN not found or not executable. Build it or drop --skip-build." >&2
- exit 1
-fi
-
-echo "[library-heap] running scenario '$SCENARIO' under dhat" >&2
-echo "[library-heap] WARNING: dhat instrumentation perturbs RSS and timing; do not compare these numbers against library-bench.sh output" >&2
-
-env OPENHUMAN_PROFILE_DHAT_OUT="$OUT_FILE" "${EXTRA_ENV[@]+"${EXTRA_ENV[@]}"}" "$BIN" "$SCENARIO" >/dev/null
-
-if [[ ! -f "$OUT_FILE" ]]; then
- echo "ERROR: expected dhat output was not written: $OUT_FILE" >&2
- exit 1
-fi
-
-echo "[library-heap] done: $OUT_FILE" >&2
-echo "[library-heap] view it at https://nnethercote.github.io/dh_view/dh_view.html (load the JSON file)" >&2
diff --git a/scripts/profile/library-instances.sh b/scripts/profile/library-instances.sh
deleted file mode 100755
index 1c28e03a90..0000000000
--- a/scripts/profile/library-instances.sh
+++ /dev/null
@@ -1,548 +0,0 @@
-#!/usr/bin/env bash
-# library-instances.sh — multi-instance fuzz driver: spawn N independent
-# `library-profile` processes (one live instance each, held alive at settled
-# state via OPENHUMAN_PROFILE_HOLD_SECS) and measure per-INSTANCE cost and
-# box survivability under the "N processes" deployment model, as opposed to
-# the "N agents in one process" model that `library-fleet.sh` measures.
-#
-# Where library-fleet.sh answers "how many agents fit in one process", this
-# answers "how many independent processes/containers fit on one box" — the
-# opencompany per-tenant-instance question. Companion scripts: library-bench.sh
-# (per-scenario RSS/duration), library-fleet.sh (one-process fleet sweep).
-#
-# Usage:
-# ./scripts/profile/library-instances.sh [options]
-#
-# Options:
-# --instances "10,25,50" Comma-separated instance-count sweep (default: "10,25,50")
-# --hold-secs N Seconds each instance holds alive at settled state
-# after finishing its workload (default: 30)
-# --scenario NAME library-profile scenario to run per instance
-# (default: agent-turn)
-# --stagger-ms N Delay between spawning consecutive instances, in
-# milliseconds (default: 100)
-# --skip-build Reuse the existing target/release binary
-# --slim Build with --no-default-features (slim library recipe)
-# --max-instances N Hard safety cap on any swept N (default: 200).
-# Each held instance settles ~47 MiB RSS on a
-# default build, so sum-RSS scales roughly
-# linearly: 1000 instances (at default settings)
-# is on the order of 1000 x 47 MiB ~= 47 GB
-# aggregate RSS. Raising this cap is an explicit
-# "yes, I mean to spawn that many processes" — it
-# will not happen implicitly.
-# --out DIR Output directory (default:
-# target/profile/rust-library/instances-<timestamp>)
-# --gate Exit nonzero if any instance failed (nonzero exit
-# or missing/invalid JSON). Default: report only,
-# always exit 0 unless argument/build errors occur.
-# -h, --help Show this help
-#
-# Examples:
-# ./scripts/profile/library-instances.sh
-# ./scripts/profile/library-instances.sh --instances "10,50" --hold-secs 30
-# ./scripts/profile/library-instances.sh --instances "500" --max-instances 500 --gate
-
-set -euo pipefail
-
-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
-
-INSTANCES="10,25,50"
-HOLD_SECS=30
-SCENARIO="agent-turn"
-STAGGER_MS=100
-SKIP_BUILD=0
-SLIM=0
-MAX_INSTANCES=200
-OUT_DIR=""
-GATE=0
-
-# Default-build settled RSS per held instance, used only for the safety-cap
-# explanation message and the summary.md extrapolation fallback when PSS is
-# unavailable (macOS). This is a rule-of-thumb constant, not a measurement —
-# the script's own measured settled RSS supersedes it once real data exists.
-ASSUMED_PER_INSTANCE_RSS_MIB=47
-BUDGET_MIB=2048
-
-usage() {
- sed -n '2,38p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
- exit "${1:-0}"
-}
-
-while [[ $# -gt 0 ]]; do
- case "$1" in
- --instances)
- INSTANCES="${2:?--instances requires a value}"; shift 2 ;;
- --hold-secs)
- HOLD_SECS="${2:?--hold-secs requires a value}"; shift 2 ;;
- --scenario)
- SCENARIO="${2:?--scenario requires a value}"; shift 2 ;;
- --stagger-ms)
- STAGGER_MS="${2:?--stagger-ms requires a value}"; shift 2 ;;
- --skip-build) SKIP_BUILD=1; shift ;;
- --slim) SLIM=1; shift ;;
- --max-instances)
- MAX_INSTANCES="${2:?--max-instances requires a value}"; shift 2 ;;
- --out)
- OUT_DIR="${2:?--out requires a value}"; shift 2 ;;
- --gate) GATE=1; shift ;;
- -h|--help) usage 0 ;;
- *)
- echo "ERROR: unknown argument: $1" >&2
- usage 1 ;;
- esac
-done
-
-if ! command -v jq >/dev/null 2>&1; then
- echo "ERROR: jq is required (aggregation over run JSON). Install it (e.g. 'brew install jq')." >&2
- exit 1
-fi
-
-if [[ -z "$OUT_DIR" ]]; then
- OUT_DIR="$REPO_ROOT/target/profile/rust-library/instances-$(date +%Y%m%d-%H%M%S)"
-fi
-mkdir -p "$OUT_DIR"
-
-BIN="$REPO_ROOT/target/release/library-profile"
-
-log() { echo "[library-instances] $*" >&2; }
-
-# --- safety cap -------------------------------------------------------------
-
-check_cap() {
- local n="$1"
- if [[ "$n" -gt "$MAX_INSTANCES" ]]; then
- local naive_gib
- naive_gib=$(jq -n --argjson n "$n" --argjson mib "$ASSUMED_PER_INSTANCE_RSS_MIB" '(($n * $mib) / 1024 * 100 | round) / 100')
- echo "ERROR: requested $n instances exceeds --max-instances cap ($MAX_INSTANCES)." >&2
- echo " RAM math: each held instance settles ~${ASSUMED_PER_INSTANCE_RSS_MIB} MiB RSS on a" >&2
- echo " default build (many-processes model pays that base N times, unlike the" >&2
- echo " one-process fleet model, which amortizes it once). $n instances is roughly" >&2
- echo " $n x ${ASSUMED_PER_INSTANCE_RSS_MIB} MiB ~= ${naive_gib} GiB of aggregate sum-RSS — likely more" >&2
- echo " than this machine has. Pass --max-instances $n (or higher) to confirm you" >&2
- echo " intend to spawn that many processes." >&2
- exit 1
- fi
-}
-
-# --- build -------------------------------------------------------------------
-
-build_binaries() {
- if [[ "$SKIP_BUILD" -eq 1 ]]; then
- log "skipping build (--skip-build)"
- return
- fi
- local feature_args=(--features rss-bench)
- if [[ "$SLIM" -eq 1 ]]; then
- feature_args=(--no-default-features --features rss-bench)
- log "building slim library-profile + rss-bench (GGML_NATIVE=OFF)"
- else
- log "building default-feature library-profile + rss-bench (GGML_NATIVE=OFF)"
- fi
- (
- cd "$REPO_ROOT"
- GGML_NATIVE=OFF cargo build --release \
- "${feature_args[@]}" \
- --bin library-profile --bin rss-bench
- )
-}
-
-# One quick, short-lived run before the sweep: confirms the binary emits
-# valid schema JSON and is not the dhat-instrumented build (library-heap.sh
-# clobbers target/release/library-profile with rss-bench-dhat, whose
-# allocator perturbs RSS in a way that would corrupt every number below).
-probe_binary() {
- log "probe run: validating '$BIN $SCENARIO' before the sweep"
- local probe_file="$OUT_DIR/probe.json"
- local probe_log="$OUT_DIR/probe.log"
-
- OPENHUMAN_PROFILE_HOLD_SECS=0 "$BIN" "$SCENARIO" >"$probe_file" 2>"$probe_log"
-
- if ! jq empty "$probe_file" >/dev/null 2>&1; then
- echo "ERROR: probe run did not produce valid JSON: $probe_file" >&2
- exit 1
- fi
- if [[ "$(jq -r '.dhat // false' "$probe_file")" == "true" ]]; then
- echo "ERROR: $BIN was built with rss-bench-dhat (library-heap.sh clobbered it)." >&2
- echo " Re-run without --skip-build to rebuild the plain rss-bench binary." >&2
- exit 1
- fi
- log "probe OK: settled rss_kib=$(jq -r '.settled.rss_kib' "$probe_file")"
-}
-
-# --- spawn + sample ----------------------------------------------------------
-
-sleep_ms() {
- local ms="$1"
- [[ "$ms" -le 0 ]] && return 0
- local secs
- secs=$(awk -v ms="$ms" 'BEGIN { printf "%.3f", ms / 1000 }')
- sleep "$secs"
-}
-
-# Best-effort per-process attribution via the macOS `footprint` tool, run
-# against a handful of pids for one sweep point only (it is slow and
-# invasive; ignore any failure — this is a bonus artifact, not load-bearing).
-capture_footprint_sample() {
- local point_dir="$1"; shift
- local pids=("$@")
-
- if ! command -v footprint >/dev/null 2>&1; then
- log "footprint tool not present, skipping footprint sample"
- return 0
- fi
-
- local sampled=0
- local pid
- for pid in "${pids[@]}"; do
- [[ "$sampled" -ge 3 ]] && break
- footprint "$pid" >"$point_dir/footprint-pid$pid.txt" 2>&1 || true
- sampled=$((sampled + 1))
- done
- log "footprint: sampled $sampled pid(s) (best-effort, see footprint-pid*.txt)"
-}
-
-# Samples aggregate sum-RSS + live count every 2s via `ps -o pid=,rss=` until
-# every pid in the list has exited, appending to samples.csv. Records the
-# peak sum-RSS observed and takes one `vm_stat` system-memory snapshot at
-# that peak.
-sample_while_holding() {
- local point_dir="$1"; shift
- local -a pids=("$@")
-
- local samples_csv="$point_dir/samples.csv"
- echo "elapsed_s,sum_rss_kib,live_count" >"$samples_csv"
-
- local pid_csv
- pid_csv=$(IFS=,; echo "${pids[*]}")
-
- local start_ts
- start_ts=$(date +%s)
- local peak_sum=0
-
- while true; do
- local ps_out
- ps_out=$(ps -o pid=,rss= -p "$pid_csv" 2>/dev/null || true)
-
- local live_count sum_rss
- if [[ -z "$ps_out" ]]; then
- live_count=0
- sum_rss=0
- else
- read -r live_count sum_rss <<<"$(echo "$ps_out" | awk '{s += $2; c += 1} END { print c + 0, s + 0 }')"
- fi
-
- local elapsed=$(( $(date +%s) - start_ts ))
- echo "$elapsed,$sum_rss,$live_count" >>"$samples_csv"
-
- if [[ "$sum_rss" -gt "$peak_sum" ]]; then
- peak_sum="$sum_rss"
- vm_stat >"$point_dir/vm_stat-peak.txt" 2>/dev/null || true
- fi
-
- if [[ "$live_count" -eq 0 ]]; then
- break
- fi
- sleep 2
- done
-
- echo "$peak_sum" >"$point_dir/.peak_sum_rss_kib"
-}
-
-run_sweep_point() {
- local n="$1"
- local do_footprint="$2"
- local point_dir="$OUT_DIR/n$n"
- mkdir -p "$point_dir"
-
- log "spawning $n instance(s) of scenario '$SCENARIO' (hold=${HOLD_SECS}s, stagger=${STAGGER_MS}ms)"
-
- local -a pids=()
- local i
- for ((i = 1; i <= n; i++)); do
- local out_file="$point_dir/proc-$i.json"
- local log_file="$point_dir/proc-$i.log"
-
- env "OPENHUMAN_PROFILE_HOLD_SECS=$HOLD_SECS" "$BIN" "$SCENARIO" \
- >"$out_file" 2>"$log_file" &
- pids+=("$!")
-
- if [[ "$i" -lt "$n" ]]; then
- sleep_ms "$STAGGER_MS"
- fi
- done
-
- if [[ "$do_footprint" -eq 1 ]]; then
- capture_footprint_sample "$point_dir" "${pids[@]}"
- fi
-
- sample_while_holding "$point_dir" "${pids[@]}"
-
- local ok=0 failed=0
- local pid_index=0
- for pid in "${pids[@]}"; do
- pid_index=$((pid_index + 1))
- local out_file="$point_dir/proc-$pid_index.json"
- local status=0
- wait "$pid" || status=$?
-
- if [[ "$status" -eq 0 && -s "$out_file" ]] && jq empty "$out_file" >/dev/null 2>&1; then
- ok=$((ok + 1))
- else
- failed=$((failed + 1))
- log "WARN: instance $pid_index (pid $pid, n=$n) failed (exit=$status)"
- fi
- done
-
- echo "$ok" >"$point_dir/.ok_count"
- echo "$failed" >"$point_dir/.failed_count"
- log "n=$n done: ok=$ok failed=$failed"
-}
-
-# --- aggregate ----------------------------------------------------------------
-
-kib_to_mib() {
- local kib="$1"
- if [[ "$kib" == "null" || -z "$kib" ]]; then
- echo "n/a"
- return
- fi
- jq -n --argjson kib "$kib" '($kib / 1024 * 100 | round) / 100'
-}
-
-num_or_na() {
- local v="$1"
- [[ "$v" == "null" || -z "$v" ]] && echo "n/a" || echo "$v"
-}
-
-aggregate_point() {
- local n="$1"
- local point_dir="$OUT_DIR/n$n"
-
- local ok failed peak_sum_rss_kib
- ok=$(cat "$point_dir/.ok_count" 2>/dev/null || echo 0)
- failed=$(cat "$point_dir/.failed_count" 2>/dev/null || echo 0)
- peak_sum_rss_kib=$(cat "$point_dir/.peak_sum_rss_kib" 2>/dev/null || echo 0)
-
- local -a valid_files=()
- local f
- for f in "$point_dir"/proc-*.json; do
- [[ -e "$f" ]] || continue
- if jq empty "$f" >/dev/null 2>&1; then
- valid_files+=("$f")
- fi
- done
-
- local settled_rss_median pss_max pss_sum_kib
- if [[ "${#valid_files[@]}" -gt 0 ]]; then
- settled_rss_median=$(jq -s '
- [ .[] | .settled.rss_kib | select(. != null) ] as $vals |
- ($vals | sort) as $sorted |
- ($sorted | length) as $n |
- (if $n == 0 then null else $sorted[(($n - 1) / 2 | floor)] end)
- ' "${valid_files[@]}")
- pss_max=$(jq -s '[ .[] | .settled.pss_kib // 0 ] | max' "${valid_files[@]}")
- pss_sum_kib=$(jq -s '[ .[] | .settled.pss_kib // 0 ] | add' "${valid_files[@]}")
- else
- settled_rss_median=null
- pss_max=0
- pss_sum_kib=0
- fi
-
- local mean_sum_rss_kib_per_instance
- if [[ "$ok" -gt 0 ]]; then
- mean_sum_rss_kib_per_instance=$(jq -n --argjson total "$peak_sum_rss_kib" --argjson ok "$ok" '$total / $ok')
- else
- mean_sum_rss_kib_per_instance=null
- fi
-
- local pss_available
- pss_available=$(jq -n --argjson v "$pss_max" 'if $v > 0 then true else false end')
-
- jq -n \
- --argjson instances "$n" \
- --argjson launched "$n" \
- --argjson ok "$ok" \
- --argjson failed "$failed" \
- --argjson peak_sum_rss_kib "$peak_sum_rss_kib" \
- --argjson mean_sum_rss_kib_per_instance "$mean_sum_rss_kib_per_instance" \
- --argjson settled_rss_kib_median "$settled_rss_median" \
- --argjson pss_available "$pss_available" \
- --argjson pss_sum_kib "$pss_sum_kib" \
- '{
- instances: $instances,
- launched: $launched,
- ok: $ok,
- failed: $failed,
- peak_sum_rss_kib: $peak_sum_rss_kib,
- mean_sum_rss_kib_per_instance: $mean_sum_rss_kib_per_instance,
- settled_rss_kib_median: $settled_rss_kib_median,
- pss_available: $pss_available,
- pss_sum_kib: (if $pss_available then $pss_sum_kib else null end)
- }'
-}
-
-write_summary() {
- local summary_json="$OUT_DIR/summary.json"
- local summary_md="$OUT_DIR/summary.md"
-
- jq -s \
- --argjson hold_secs "$HOLD_SECS" \
- --arg scenario "$SCENARIO" \
- --argjson stagger_ms "$STAGGER_MS" \
- --arg build "$([[ "$SLIM" -eq 1 ]] && echo "slim" || echo "default")" \
- '{
- generated_at: (now | todate),
- build: $build,
- config: { scenario: $scenario, hold_secs: $hold_secs, stagger_ms: $stagger_ms },
- sweep: .
- }' \
- "$OUT_DIR"/*.point.json >"$summary_json"
-
- local any_fail=0
- local last_point_file=""
-
- {
- echo "# Multi-instance (many-processes) benchmark summary"
- echo
- echo "Build: \`$([[ "$SLIM" -eq 1 ]] && echo "slim" || echo "default")\` "
- echo "Scenario: \`${SCENARIO}\`, hold: ${HOLD_SECS}s, stagger: ${STAGGER_MS}ms "
- echo "Generated: $(date)"
- echo
- echo "This measures the **many-processes** deployment model: N independent"
- echo "\`library-profile\` processes, each a live held instance, as opposed to"
- echo "\`library-fleet.sh\`'s **one-process** model (N agents inside a single"
- echo "process). **Correctness note:** summed RSS below double-counts shared"
- echo "clean pages — all instances share one binary's resident executable text"
- echo "and any shared library mappings — so sum-RSS is an **upper bound** on"
- echo "real physical memory use, not the true cost. On Linux, summed PSS"
- echo "(proportional set size, from each instance's \`settled.pss_kib\`) divides"
- echo "shared pages across the processes that share them and is the honest"
- echo "number; it is surfaced below whenever the field is nonzero. On macOS"
- echo "there is no PSS equivalent, so only sum-RSS is available and the table"
- echo "says so explicitly."
- echo
- echo "| N | ok/launched | median settled RSS/instance (MiB) | mean sum-RSS/instance (MiB) | peak aggregate sum-RSS (MiB) | summed PSS (MiB) |"
- echo "| ---: | :---: | ---: | ---: | ---: | ---: |"
-
- local pf
- for pf in "$OUT_DIR"/*.point.json; do
- [[ -e "$pf" ]] || continue
- last_point_file="$pf"
- local n ok launched settled_rss mean_sum peak_sum pss_available pss_sum pss_cell
- n=$(jq -r '.instances' "$pf")
- ok=$(jq -r '.ok' "$pf")
- launched=$(jq -r '.launched' "$pf")
- settled_rss=$(kib_to_mib "$(jq -r '.settled_rss_kib_median' "$pf")")
- mean_sum=$(kib_to_mib "$(jq -r '.mean_sum_rss_kib_per_instance' "$pf")")
- peak_sum=$(kib_to_mib "$(jq -r '.peak_sum_rss_kib' "$pf")")
- pss_available=$(jq -r '.pss_available' "$pf")
- if [[ "$pss_available" == "true" ]]; then
- pss_sum=$(kib_to_mib "$(jq -r '.pss_sum_kib' "$pf")")
- pss_cell="$pss_sum"
- else
- pss_cell="n/a (macOS)"
- fi
-
- if [[ "$ok" != "$launched" ]]; then
- any_fail=1
- fi
-
- echo "| $n | $ok/$launched | $settled_rss | $mean_sum | $peak_sum | $pss_cell |"
- done
-
- echo
- echo "## Verdict (2 GB box extrapolation, estimate)"
- echo
-
- if [[ -n "$last_point_file" ]]; then
- local pss_available per_instance_mib per_instance_label fits_estimate
- pss_available=$(jq -r '.pss_available' "$last_point_file")
- if [[ "$pss_available" == "true" ]]; then
- per_instance_mib=$(kib_to_mib "$(jq -r '(.pss_sum_kib / .ok)' "$last_point_file")")
- per_instance_label="summed PSS/instance (honest, shared pages divided across sharers)"
- else
- per_instance_mib=$(kib_to_mib "$(jq -r '.mean_sum_rss_kib_per_instance' "$last_point_file")")
- per_instance_label="mean sum-RSS/instance (macOS, no PSS — this OVERSTATES true cost by double-counting shared pages)"
- fi
-
- if [[ "$per_instance_mib" != "n/a" ]]; then
- fits_estimate=$(jq -n --argjson budget "$BUDGET_MIB" --argjson per "$per_instance_mib" '($budget / $per) | floor')
- echo "Using the largest swept N's ${per_instance_label}: **${per_instance_mib} MiB/instance**."
- echo
- echo "\`instances_that_fit ~= ${BUDGET_MIB} / ${per_instance_mib} ~= ${fits_estimate}\` — a rough"
- echo "**estimate**, not a measured limit. It assumes every additional instance"
- echo "costs the same as the ones already measured (no host-level contention,"
- echo "no cgroup memory limit enforced here)."
- if [[ "$pss_available" == "true" ]]; then
- echo "PSS was available (Linux), so this divides shared pages across the"
- echo "processes that share them rather than double-counting them — still an"
- echo "estimate, but not skewed in a known direction the way the macOS"
- echo "sum-RSS fallback is."
- else
- echo "No PSS was available (macOS), so this uses sum-RSS as a stand-in,"
- echo "which double-counts shared pages (executable text, shared library"
- echo "mappings) across instances — treat this estimate as"
- echo "conservative-in-the-wrong-direction (fewer instances would actually fit"
- echo "than the sum-RSS math implies is safe, since real physical use is lower"
- echo "than sum-RSS thanks to shared pages, but this is also unverified against"
- echo "an actual memory-limited box)."
- fi
- else
- echo "No successful instances at the largest swept N — cannot extrapolate."
- any_fail=1
- fi
- else
- echo "No sweep points completed — nothing to extrapolate."
- any_fail=1
- fi
- } >"$summary_md"
-
- if [[ "$any_fail" -eq 1 ]]; then
- return 1
- fi
- return 0
-}
-
-main() {
- IFS=',' read -r -a instance_list <<<"$INSTANCES"
-
- local n
- for n in "${instance_list[@]}"; do
- check_cap "$n"
- done
-
- build_binaries
-
- if [[ ! -x "$BIN" ]]; then
- echo "ERROR: $BIN not found or not executable. Build it or drop --skip-build." >&2
- exit 1
- fi
-
- probe_binary
-
- local first_n="${instance_list[0]}"
- for n in "${instance_list[@]}"; do
- local do_footprint=0
- [[ "$n" == "$first_n" ]] && do_footprint=1
- run_sweep_point "$n" "$do_footprint"
- done
-
- for n in "${instance_list[@]}"; do
- aggregate_point "$n" >"$OUT_DIR/n$n.point.json"
- done
-
- local gate_status=0
- write_summary || gate_status=1
-
- log "results: $OUT_DIR"
- cat "$OUT_DIR/summary.md"
-
- if [[ "$GATE" -eq 1 && "$gate_status" -ne 0 ]]; then
- log "GATE FAILED: at least one instance failed to complete cleanly"
- exit 1
- fi
-}
-
-main "$@"
diff --git a/scripts/profile/library-pool-gate.sh b/scripts/profile/library-pool-gate.sh
deleted file mode 100755
index c86f648e2d..0000000000
--- a/scripts/profile/library-pool-gate.sh
+++ /dev/null
@@ -1,133 +0,0 @@
-#!/usr/bin/env bash
-# library-pool-gate.sh — regression gate for the shared runtime pool (#5106).
-#
-# Runs the `skill-run` scenario with K parallel skill runs and asserts the DoD:
-# with the pool ON, the process tree grows by ~one pooled worker, NOT K
-# interpreters. The scenario itself hard-asserts `tree.child_count <= max_workers`
-# for K > 1 (nonzero exit on failure); this script drives it in the profiling
-# suite and adds a pooled-vs-unpooled comparison for the report.
-#
-# A regression that reintroduces per-run interpreter forking makes the pooled
-# run's child_count scale with K → the scenario exits nonzero → this gate fails.
-#
-# Usage:
-# ./scripts/profile/library-pool-gate.sh [--concurrency N] [--workers W] [--skip-build] [--out DIR]
-#
-# Exits 0 = pass, 1 = regression/failure, 0 (with SKIP notice) = no system node.
-
-set -euo pipefail
-
-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
-
-CONCURRENCY=8
-POOL_WORKERS=1
-SKIP_BUILD=0
-OUT_DIR=""
-
-# Reject non-positive-integer values up front so a bad --concurrency/--workers
-# fails loudly instead of silently changing the workload.
-require_pos_int() {
- case "$2" in
- ''|*[!0-9]*) echo "ERROR: $1 must be a positive integer, got: $2" >&2; exit 1 ;;
- esac
- [ "$2" -ge 1 ] || { echo "ERROR: $1 must be >= 1, got: $2" >&2; exit 1; }
-}
-
-while [[ $# -gt 0 ]]; do
- case "$1" in
- --concurrency) CONCURRENCY="${2:?--concurrency requires a value}"; require_pos_int --concurrency "$CONCURRENCY"; shift 2 ;;
- --workers) POOL_WORKERS="${2:?--workers requires a value}"; require_pos_int --workers "$POOL_WORKERS"; shift 2 ;;
- --skip-build) SKIP_BUILD=1; shift ;;
- --out) OUT_DIR="${2:?--out requires a value}"; shift 2 ;;
- -h|--help) sed -n '2,18p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0 ;;
- *) echo "ERROR: unknown argument: $1" >&2; exit 1 ;;
- esac
-done
-require_pos_int --concurrency "$CONCURRENCY"
-require_pos_int --workers "$POOL_WORKERS"
-
-log() { echo "[pool-gate] $*" >&2; }
-
-if ! command -v jq >/dev/null 2>&1; then
- echo "ERROR: jq is required. Install it (e.g. 'brew install jq')." >&2
- exit 1
-fi
-
-# The scenario requires a real system node (it must never download one). No node
-# ⇒ SKIP (exit 0) so node-less CI runners don't false-fail; a node-equipped
-# runner is where this gate is meaningful.
-if ! command -v node >/dev/null 2>&1; then
- log "SKIP: no system 'node' on PATH — pool gate needs a real interpreter."
- exit 0
-fi
-
-[[ -z "$OUT_DIR" ]] && OUT_DIR="$REPO_ROOT/target/profile/rust-library/pool-gate-$(date +%Y%m%d-%H%M%S)"
-mkdir -p "$OUT_DIR"
-BIN="$REPO_ROOT/target/release/library-profile"
-
-if [[ "$SKIP_BUILD" -eq 0 ]]; then
- log "building library-profile (rss-bench, GGML_NATIVE=OFF)"
- ( cd "$REPO_ROOT" && GGML_NATIVE=OFF cargo build --release --features rss-bench --bin library-profile )
-fi
-[[ -x "$BIN" ]] || { echo "ERROR: $BIN not found (drop --skip-build to build it)." >&2; exit 1; }
-
-pooled_json="$OUT_DIR/pooled-k$CONCURRENCY.json"
-unpooled_json="$OUT_DIR/unpooled-k$CONCURRENCY.json"
-
-# --- Pooled run (the gate) ------------------------------------------------
-# The scenario hard-asserts child_count <= POOL_WORKERS; a nonzero exit here
-# (via set -e) fails the gate.
-log "pooled run: K=$CONCURRENCY, max_workers=$POOL_WORKERS (asserts child_count <= $POOL_WORKERS)"
-# Force the pool ON explicitly: an inherited OPENHUMAN_PROFILE_SKILL_RUN_POOL=off
-# would run the legacy path and make the scenario skip its pool assertion.
-OPENHUMAN_PROFILE_SKILL_RUN_POOL=on \
-OPENHUMAN_PROFILE_SKILL_RUN_CONCURRENCY="$CONCURRENCY" \
-OPENHUMAN_PROFILE_SKILL_RUN_POOL_WORKERS="$POOL_WORKERS" \
- "$BIN" skill-run >"$pooled_json"
-
-# --- Unpooled baseline (report only) --------------------------------------
-log "unpooled baseline: K=$CONCURRENCY, pool OFF (expect ~$CONCURRENCY interpreters)"
-OPENHUMAN_PROFILE_SKILL_RUN_CONCURRENCY="$CONCURRENCY" \
-OPENHUMAN_PROFILE_SKILL_RUN_POOL=off \
- "$BIN" skill-run >"$unpooled_json"
-
-# Pooled run: a missing/null tree means nothing was measured — that must FAIL,
-# not silently coerce to 0 (which would let the gate pass without observing an
-# interpreter). Unpooled is report-only, so its tree may default to 0.
-pooled_cc="$(jq -r '.tree.child_count // "null"' "$pooled_json")"
-unpooled_cc="$(jq -r '.tree.child_count // 0' "$unpooled_json")"
-pooled_rss="$(jq -r '.tree.tree_rss_kib // "null"' "$pooled_json")"
-unpooled_rss="$(jq -r '.tree.tree_rss_kib // 0' "$unpooled_json")"
-
-echo
-echo "=== runtime pool gate (#5106) — K=$CONCURRENCY ==="
-echo " pooled (max_workers=$POOL_WORKERS): child_count=$pooled_cc tree_rss_kib=$pooled_rss"
-echo " unpooled (legacy spawn) : child_count=$unpooled_cc tree_rss_kib=$unpooled_rss"
-
-if [[ "$pooled_cc" == "null" ]]; then
- echo "FAIL: pooled run captured no process-tree sample — cannot verify the pooled worker." >&2
- exit 1
-fi
-# The pooled worker must actually be observed (>= 1) and must not exceed the
-# pool size.
-if [[ "$pooled_cc" -lt 1 ]]; then
- echo "FAIL: pooled run observed zero interpreter children — the pooled worker was not sampled." >&2
- exit 1
-fi
-if [[ "$pooled_cc" -gt "$POOL_WORKERS" ]]; then
- echo "FAIL: pooled child_count=$pooled_cc exceeds max_workers=$POOL_WORKERS — pool is forking per run." >&2
- exit 1
-fi
-
-# Sanity: the unpooled baseline should fork more than the pool. If it didn't,
-# the comparison is inconclusive (likely a sampling miss on a fast machine) —
-# warn rather than hard-fail, since the pooled assertion above is the real gate.
-if [[ "$unpooled_cc" -le "$pooled_cc" ]]; then
- echo "WARN: unpooled baseline child_count=$unpooled_cc did not exceed pooled=$pooled_cc" >&2
- echo " (baseline sampling inconclusive; the pooled assertion still passed)." >&2
-else
- echo "PASS: pool bounded interpreters to $pooled_cc for K=$CONCURRENCY concurrent skill runs (unpooled forked $unpooled_cc)."
-fi
-echo " artifacts: $OUT_DIR"
-exit 0
diff --git a/scripts/profile/rss-bench.sh b/scripts/profile/rss-bench.sh
deleted file mode 100755
index 841f8c0c20..0000000000
--- a/scripts/profile/rss-bench.sh
+++ /dev/null
@@ -1,37 +0,0 @@
-#!/usr/bin/env bash
-# rss-bench.sh — steady-state RSS of an embedded openhuman_core agent roster
-# (#5046): 5 fresh processes x {1, 8} agents, reported against the 20 MiB
-# target and 30 MiB hard cap.
-#
-# Formerly the report-only `rust-rss-bench` CI job; benchmarks run from
-# scripts, not CI. The build is a stripped release (thin LTO, one codegen
-# unit), so expect a long first compile.
-#
-# Usage: ./scripts/profile/rss-bench.sh [--out FILE] [--skip-build]
-# --out FILE raw samples as JSON (default target/profile/rss-bench.json)
-# --skip-build reuse target/release/rss-bench
-set -euo pipefail
-
-cd "$(dirname "$0")/../.."
-
-out="target/profile/rss-bench.json"
-build=1
-while (($#)); do
- case "$1" in
- --out) out="$2"; shift 2 ;;
- --skip-build) build=0; shift ;;
- -h | --help) sed -n '2,13p' "$0"; exit 0 ;;
- *) echo "unknown argument: $1" >&2; exit 64 ;;
- esac
-done
-
-if ((build)); then
- echo "[rss-bench] building stripped-release rss-bench" >&2
- cargo build --release --features rss-bench --bin rss-bench
- echo "[rss-bench] running fixture tests" >&2
- cargo test --features rss-bench --bin rss-bench
-fi
-
-mkdir -p "$(dirname "${out}")"
-./target/release/rss-bench --out "${out}"
-echo "[rss-bench] raw samples: ${out}" >&2
diff --git a/scripts/test-onboarding-stress.mjs b/scripts/test-onboarding-stress.mjs
deleted file mode 100755
index d6aae95d9c..0000000000
--- a/scripts/test-onboarding-stress.mjs
+++ /dev/null
@@ -1,624 +0,0 @@
-#!/usr/bin/env node
-// ──────────────────────────────────────────────────────────────────────
-// test-onboarding-stress.mjs
-//
-// Runs 25 diverse onboarding scenarios, judges each one, and writes
-// a full report to docs/ONBOARDING-TEST-RESULTS.md
-// ──────────────────────────────────────────────────────────────────────
-
-import { existsSync, readFileSync, writeFileSync, readdirSync } from 'fs';
-import { homedir } from 'os';
-import path from 'path';
-import { fileURLToPath } from 'url';
-import { randomUUID } from 'crypto';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const ROOT = path.resolve(__dirname, '..');
-
-const CORE_PORT = process.env.OPENHUMAN_CORE_PORT || '7788';
-const CORE_HOST = process.env.OPENHUMAN_CORE_HOST || '127.0.0.1';
-const CORE_URL = `http://${CORE_HOST}:${CORE_PORT}`;
-
-const OPENHUMAN_HOME = process.env.OPENHUMAN_WORKSPACE
- ? path.join(process.env.OPENHUMAN_WORKSPACE)
- : path.join(homedir(), '.openhuman');
-
-// Set OPENHUMAN_USER_ID to pin to a specific user directory deterministically.
-function findConfigPath() {
- const usersDir = path.join(OPENHUMAN_HOME, 'users');
- const pinnedId = process.env.OPENHUMAN_USER_ID;
- if (pinnedId) {
- const candidate = path.join(usersDir, pinnedId, 'config.toml');
- if (existsSync(candidate)) return candidate;
- }
- if (existsSync(usersDir)) {
- try {
- const entries = readdirSync(usersDir).filter(e => e !== 'local').sort();
- for (const entry of entries) {
- const candidate = path.join(usersDir, entry, 'config.toml');
- if (existsSync(candidate)) return candidate;
- }
- } catch {}
- }
- return path.join(OPENHUMAN_HOME, 'config.toml');
-}
-
-const CONFIG_PATH = findConfigPath();
-const TRIGGER = 'the user just finished the desktop onboarding wizard. welcome the user.';
-const TURN_TIMEOUT_MS = 120_000;
-
-// ── 25 diverse test scenarios ──────────────────────────────────────
-const SCENARIOS = [
- {
- name: 'PM in Slack/Gmail',
- messages: [
- "hey! i'm a product manager, mostly in slack and gmail all day",
- "yeah sure, how do i connect slack?",
- "done, connected it. what else can this do?",
- "cool, i think that's enough for now. thanks!",
- ],
- },
- {
- name: 'Developer, minimal talker',
- messages: [
- "i'm a dev. mostly github and vscode",
- "ok",
- "sure connected github",
- "done",
- ],
- },
- {
- name: 'Curious user, lots of questions',
- messages: [
- "what exactly is this app? like what can it actually do for me?",
- "interesting. can it read my emails?",
- "how is that different from just using gmail?",
- "ok makes sense. i connected gmail. what about privacy, is my data safe?",
- "alright cool, i'm good",
- ],
- },
- {
- name: 'Impatient user wants to skip',
- messages: [
- "can we skip all this setup stuff? i just want to use the app",
- "fine, what do i need to do?",
- "ok connected whatsapp. now can i use it?",
- ],
- },
- {
- name: 'Non-technical user',
- messages: [
- "hi! i'm not very techy but my friend told me to try this. i mostly use whatsapp and email",
- "what does connecting my apps mean? is it safe?",
- "ok i trust you. i connected my gmail",
- "what can you help me with now?",
- "that sounds great, thanks!",
- ],
- },
- {
- name: 'Enterprise user, security focused',
- messages: [
- "i'm an IT manager at a mid-size company. we're evaluating this for our team",
- "what data do you store? where does it go?",
- "ok connected gmail via oauth. what integrations do you support?",
- "can multiple team members use this?",
- "alright, i've seen enough for now",
- ],
- },
- {
- name: 'Student on a budget',
- messages: [
- "hey i'm a college student, just trying to stay organized with classes and stuff",
- "i use google calendar and gmail mostly. sometimes discord for study groups",
- "connected gmail! does this cost money?",
- "ok cool, thanks!",
- ],
- },
- {
- name: 'Freelancer juggling clients',
- messages: [
- "i'm a freelance designer. i have like 5 different clients all using different tools. slack for some, email for others, whatsapp for a couple",
- "that sounds perfect. let me connect slack first",
- "done. can it help me track which client said what across all these channels?",
- "amazing. i'm sold. thanks!",
- ],
- },
- {
- name: 'User who just says hi',
- messages: [
- "hi",
- "what should i do?",
- "ok connected gmail",
- "cool thanks bye",
- ],
- },
- {
- name: 'User reports a bug',
- messages: [
- "hey the connect button isn't working for me",
- "i clicked on connect apps but nothing happens",
- "ok i'll try again later. i managed to connect gmail through the settings though",
- "alright we're good",
- ],
- },
- {
- name: 'WhatsApp-heavy user',
- messages: [
- "i basically live on whatsapp. all my work chats, family groups, everything",
- "yeah let me connect it. done!",
- "can you read my whatsapp messages and summarize them?",
- "perfect, that's all i need. thanks!",
- ],
- },
- {
- name: 'User wants morning briefing immediately',
- messages: [
- "i heard this can do morning briefings? that's why i downloaded it",
- "yeah i connected gmail already during the setup wizard",
- "how do i set up the morning briefing?",
- "awesome, can't wait to try it tomorrow. that's all for now!",
- ],
- },
- {
- name: 'Skeptical user',
- messages: [
- "another ai app huh. what makes this different from chatgpt?",
- "ok but how do i know you won't spam my contacts or something?",
- "fine i'll try connecting gmail. done",
- "we'll see. bye",
- ],
- },
- {
- name: 'Power user wants everything',
- messages: [
- "i want to connect everything. gmail, slack, whatsapp, telegram, discord, notion, github, calendar",
- "done, connected gmail and slack so far. how do i add the rest?",
- "connected telegram and whatsapp too. can you now monitor all of them at once?",
- "set up morning briefings and auto-triage my inbox please",
- "this is sick. thanks!",
- ],
- },
- {
- name: 'User in a hurry',
- messages: [
- "i have 2 minutes. what do i absolutely need to do?",
- "done, connected gmail",
- "great, gotta go. bye!",
- ],
- },
- {
- name: 'Telegram-first user',
- messages: [
- "i want to use this mainly through telegram. is that possible?",
- "cool. i connected telegram already",
- "can you reach me there when something important happens?",
- "perfect. that's it for now",
- ],
- },
- {
- name: 'User asks about pricing',
- messages: [
- "how much does this cost?",
- "ok. what do i get for free?",
- "alright let me connect gmail and try it out",
- "connected. thanks!",
- ],
- },
- {
- name: 'User speaks broken English',
- messages: [
- "hello i am new here. my english not so good. i use whatsapp and email for work",
- "ok i connect the gmail now. done",
- "what can you do help me?",
- "ok thank you very much!",
- ],
- },
- {
- name: 'User wants automation',
- messages: [
- "i want to automate as much of my workflow as possible. i'm drowning in notifications",
- "i use slack, gmail, and notion. can you auto-sort my notifications?",
- "connected all three. what automation can you set up?",
- "set up whatever you think makes sense. i trust you",
- "thanks, this is exactly what i needed",
- ],
- },
- {
- name: 'User only wants one thing',
- messages: [
- "i only care about email. can you help me manage my inbox?",
- "connected gmail. now what?",
- "can you triage my unread right now?",
- "ok sure, let me finish setup first then. we're done?",
- ],
- },
- {
- name: 'User compares to competitors',
- messages: [
- "i've tried notion ai and copilot. how is this different?",
- "interesting. the cross-app thing is unique. let me try connecting slack",
- "done. can you show me something slack-specific?",
- "ok cool, i get it now. thanks",
- ],
- },
- {
- name: 'Verbose storyteller',
- messages: [
- "so basically my problem is that i have way too many apps open at once. like right now i have gmail, slack, whatsapp web, telegram, notion, and google calendar all in different tabs and i'm constantly switching between them and losing track of conversations. my boss messages me on slack but then my client follows up on whatsapp about the same project and i forget to connect the dots",
- "yeah that's exactly it. let me connect slack and gmail",
- "done! this is promising",
- "i'm good for now, thanks for listening to my rant haha",
- ],
- },
- {
- name: 'User wants voice features',
- messages: [
- "can i talk to this thing with my voice?",
- "cool. for now let me just connect gmail",
- "done. when will voice be fully ready?",
- "alright, thanks!",
- ],
- },
- {
- name: 'Team lead evaluating for team',
- messages: [
- "i'm a team lead looking at this for my team of 12. we all use slack and google workspace",
- "how does the team feature work?",
- "interesting. i connected gmail for now to test it myself first",
- "can each team member have their own setup?",
- "makes sense. i'll report back to the team. thanks!",
- ],
- },
- {
- name: 'User who immediately connects app',
- messages: [
- "i already connected whatsapp and gmail during the wizard",
- "what can you do for me now?",
- "cool can you check my unread emails?",
- "ok let's finish the setup first. we done?",
- ],
- },
-];
-
-// ── Helpers ────────────────────────────────────────────────────────
-function log(msg) {
- process.stdout.write(`\x1b[36m[stress]\x1b[0m ${msg}\n`);
-}
-
-function resetOnboarding() {
- if (!existsSync(CONFIG_PATH)) return;
- let content = readFileSync(CONFIG_PATH, 'utf-8');
- if (content.includes('chat_onboarding_completed')) {
- content = content.replace(
- /chat_onboarding_completed\s*=\s*true/,
- 'chat_onboarding_completed = false'
- );
- } else {
- content = `chat_onboarding_completed = false\n${content}`;
- }
- writeFileSync(CONFIG_PATH, content, 'utf-8');
-}
-
-async function loadSocketIo() {
- const { createRequire } = await import('module');
- for (const dir of [path.join(ROOT, 'app'), ROOT]) {
- try {
- const require = createRequire(path.join(dir, 'package.json'));
- const mod = require('socket.io-client');
- return mod.io || mod.default || mod;
- } catch {}
- }
- process.exit(1);
-}
-
-// ── Run one scenario ───────────────────────────────────────────────
-async function runScenario(io, scenario, index) {
- resetOnboarding();
- await new Promise((r) => setTimeout(r, 800));
-
- const threadId = `stress-${index}-${randomUUID().slice(0, 6)}`;
- const conversation = [];
-
- const socket = io(CORE_URL, {
- transports: ['websocket'],
- reconnection: false,
- timeout: 10_000,
- });
-
- // Wait for ready
- const clientId = await new Promise((resolve, reject) => {
- const timer = setTimeout(() => reject(new Error('ready timeout')), 10_000);
- socket.on('ready', (d) => { clearTimeout(timer); resolve(d.sid); });
- socket.on('connect_error', (e) => { clearTimeout(timer); reject(e); });
- });
-
- function collectTurn() {
- return new Promise((resolve, reject) => {
- let text = '';
- let tools = [];
- const timer = setTimeout(() => {
- cleanup();
- resolve({ text: text.trim() || '(timeout - no response)', tools });
- }, TURN_TIMEOUT_MS);
-
- function onDelta(d) { if (d.delta) text += d.delta; }
- function onSeg(d) { if (d.message) text += d.message; }
- function onTool(d) { tools.push(d.tool_name || 'unknown'); }
- function onDone(d) {
- clearTimeout(timer); cleanup();
- if (!text && d.full_response) text = d.full_response;
- resolve({ text: text.trim(), tools });
- }
- function onErr(d) {
- clearTimeout(timer); cleanup();
- resolve({ text: `(error: ${d.message || d.error_type || 'unknown'})`, tools });
- }
- function cleanup() {
- socket.off('text_delta', onDelta);
- socket.off('chat_segment', onSeg);
- socket.off('tool_call', onTool);
- socket.off('chat_done', onDone);
- socket.off('chat_error', onErr);
- }
-
- socket.on('text_delta', onDelta);
- socket.on('chat_segment', onSeg);
- socket.on('tool_call', onTool);
- socket.on('chat_done', onDone);
- socket.on('chat_error', onErr);
- });
- }
-
- async function send(message) {
- const p = collectTurn();
- socket.emit('chat:start', { thread_id: threadId, message });
- return await p;
- }
-
- // Trigger
- const triggerResp = await send(TRIGGER);
- conversation.push({ role: 'trigger', content: TRIGGER });
- conversation.push({ role: 'assistant', content: triggerResp.text, tools: triggerResp.tools });
-
- // User turns
- for (const msg of scenario.messages) {
- await new Promise((r) => setTimeout(r, 500));
- const resp = await send(msg);
- conversation.push({ role: 'user', content: msg });
- conversation.push({ role: 'assistant', content: resp.text, tools: resp.tools });
- if (resp.tools.includes('complete_onboarding')) break;
- }
-
- socket.disconnect();
- return { conversation, clientId };
-}
-
-// ── Judge a conversation ───────────────────────────────────────────
-function judge(conversation) {
- const assistantTurns = conversation.filter((t) => t.role === 'assistant');
- const allTools = assistantTurns.flatMap((t) => t.tools || []);
- const allText = assistantTurns.map((t) => t.content).join('\n');
- const lower = allText.toLowerCase();
- const firstA = assistantTurns[0];
- const opener = firstA?.content || '';
-
- // Context flags for conditional checks
- const userText = conversation
- .filter((t) => t.role === 'user')
- .map((t) => t.content)
- .join('\n')
- .toLowerCase();
- const agentGuidedConnection = assistantTurns.some((t) =>
- /\bconnect\b/.test(t.content) || t.content.includes('accounts/setup')
- );
- const userAskedPricing = /\b(price|pricing|cost|billing|subscription|how much)\b/i.test(userText);
-
- const checks = {};
-
- checks['check_onboarding_status_first_turn'] = firstA?.tools?.includes('check_onboarding_status') || false;
- checks['opener_invites_response'] = opener.includes('?') || /what would you|what do you|what.?s on|tell me|how can i/i.test(opener);
- checks['no_checklist_dump'] = !/\d\.\s|step\s*\d|checklist|first.*second.*third/i.test(opener);
- checks['mentions_connecting_apps'] = lower.includes('connect') && (lower.includes('app') || lower.includes('gmail') || lower.includes('slack') || lower.includes('whatsapp'));
- // Only check pill usage when the agent actually guided a connection
- checks['uses_openhuman_link'] = !agentGuidedConnection || (allText.includes('openhuman-link') && allText.includes('accounts/setup'));
- checks['no_robotic_self_id'] = !['as an ai', "i'm openhuman", 'i am openhuman'].some((p) => lower.includes(p));
- // Allow billing mentions when the user explicitly asked about pricing
- checks['no_billing_pitch'] = userAskedPricing || !(lower.includes('billing') || lower.includes('subscription') || (lower.includes('credit') && lower.includes('trial')));
- checks['no_em_dashes'] = !allText.includes('\u2014');
- checks['references_user_apps'] = lower.includes('slack') || lower.includes('gmail') || lower.includes('whatsapp') || lower.includes('telegram') || lower.includes('notion') || lower.includes('github') || lower.includes('discord');
- checks['educates_capabilities'] = lower.includes('morning') || lower.includes('briefing') || lower.includes('action item') || lower.includes('summary') || lower.includes('summariz') || lower.includes('monitor') || lower.includes('triage') || lower.includes('automat');
- checks['discord_not_forced'] = !(lower.includes('must join') || lower.includes('need to join discord'));
- checks['no_json_or_code'] = !(allText.includes('```') || allText.includes('{"'));
- checks['messages_concise'] = assistantTurns.length > 0 ? (assistantTurns.reduce((s, t) => s + t.content.length, 0) / assistantTurns.length < 350) : true;
- checks['calls_complete_onboarding'] = allTools.includes('complete_onboarding');
- checks['no_markdown_formatting'] = !(allText.includes('**') || allText.includes('## ') || /^- /m.test(allText) || /^\d+\. /m.test(allText));
-
- const passed = Object.values(checks).filter(Boolean).length;
- const total = Object.keys(checks).length;
-
- return { checks, passed, total };
-}
-
-// ── Main ───────────────────────────────────────────────────────────
-async function main() {
- console.log('');
- console.log('\x1b[1m Welcome Agent Stress Test — 25 Scenarios\x1b[0m');
- console.log(' ════════════════════════════════════════════');
- console.log('');
-
- // Health check
- try {
- const r = await fetch(`${CORE_URL}/health`, { signal: AbortSignal.timeout(3000) });
- if (!r.ok) throw new Error();
- } catch {
- console.error('Core not reachable. Start it first.');
- process.exit(1);
- }
- log(`Core up at ${CORE_URL}`);
- log(`Config at ${CONFIG_PATH}`);
- console.log('');
-
- const io = await loadSocketIo();
- const results = [];
-
- for (let i = 0; i < SCENARIOS.length; i++) {
- const s = SCENARIOS[i];
- const label = `[${i + 1}/${SCENARIOS.length}] ${s.name}`;
- process.stdout.write(`\x1b[36m[stress]\x1b[0m ${label}...`);
-
- try {
- const { conversation } = await runScenario(io, s, i);
- const judgment = judge(conversation);
- results.push({ scenario: s, conversation, judgment });
-
- const color = judgment.passed === judgment.total ? '\x1b[32m' : judgment.passed >= judgment.total - 2 ? '\x1b[33m' : '\x1b[31m';
- process.stdout.write(` ${color}${judgment.passed}/${judgment.total}\x1b[0m\n`);
- } catch (e) {
- process.stdout.write(` \x1b[31mERROR: ${e.message}\x1b[0m\n`);
- results.push({ scenario: s, conversation: [], judgment: { checks: {}, passed: 0, total: 15, error: e.message } });
- }
-
- // Cool down between scenarios
- await new Promise((r) => setTimeout(r, 2000));
- }
-
- // ── Generate report ────────────────────────────────────────────
- const report = generateReport(results);
- const outPath = path.join(ROOT, 'docs', 'ONBOARDING-TEST-RESULTS.md');
- writeFileSync(outPath, report, 'utf-8');
- log(`Report written to ${outPath}`);
-
- // Summary
- console.log('');
- console.log('\x1b[1m SUMMARY\x1b[0m');
- console.log(' ─────────────────────────────');
- const totalPassed = results.reduce((s, r) => s + r.judgment.passed, 0);
- const totalChecks = results.reduce((s, r) => s + r.judgment.total, 0);
- const perfect = results.filter((r) => r.judgment.passed === r.judgment.total).length;
- const avgScore = (totalPassed / totalChecks * 100).toFixed(1);
- console.log(` Scenarios: ${results.length}`);
- console.log(` Perfect scores: ${perfect}/${results.length}`);
- console.log(` Overall: ${totalPassed}/${totalChecks} checks passed (${avgScore}%)`);
- console.log('');
-
- // Per-check stats
- const checkStats = {};
- for (const r of results) {
- for (const [k, v] of Object.entries(r.judgment.checks)) {
- if (!checkStats[k]) checkStats[k] = { pass: 0, fail: 0 };
- if (v) checkStats[k].pass++; else checkStats[k].fail++;
- }
- }
- console.log(' \x1b[1mPer-check pass rate:\x1b[0m');
- for (const [k, v] of Object.entries(checkStats).sort((a, b) => a[1].pass - b[1].pass)) {
- const pct = ((v.pass / (v.pass + v.fail)) * 100).toFixed(0);
- const color = pct === '100' ? '\x1b[32m' : parseInt(pct) >= 80 ? '\x1b[33m' : '\x1b[31m';
- console.log(` ${color}${pct.padStart(4)}%\x1b[0m ${k} (${v.pass}/${v.pass + v.fail})`);
- }
- console.log('');
-}
-
-function generateReport(results) {
- const lines = [];
- const now = new Date().toISOString().slice(0, 19).replace('T', ' ');
-
- lines.push('# Onboarding Agent Test Results');
- lines.push('');
- lines.push(`Generated: ${now}`);
- lines.push('');
-
- // Summary table
- const totalPassed = results.reduce((s, r) => s + r.judgment.passed, 0);
- const totalChecks = results.reduce((s, r) => s + r.judgment.total, 0);
- const perfect = results.filter((r) => r.judgment.passed === r.judgment.total).length;
-
- lines.push('## Summary');
- lines.push('');
- lines.push(`- **Scenarios run:** ${results.length}`);
- lines.push(`- **Perfect scores:** ${perfect}/${results.length}`);
- lines.push(`- **Overall pass rate:** ${totalPassed}/${totalChecks} (${(totalPassed / totalChecks * 100).toFixed(1)}%)`);
- lines.push('');
-
- // Scorecard table
- lines.push('## Scorecard');
- lines.push('');
- lines.push('| # | Scenario | Score | Status |');
- lines.push('|---|----------|-------|--------|');
- for (let i = 0; i < results.length; i++) {
- const r = results[i];
- const status = r.judgment.error ? 'ERROR' : r.judgment.passed === r.judgment.total ? 'PASS' : r.judgment.passed >= r.judgment.total - 2 ? 'WARN' : 'FAIL';
- lines.push(`| ${i + 1} | ${r.scenario.name} | ${r.judgment.passed}/${r.judgment.total} | ${status} |`);
- }
- lines.push('');
-
- // Per-check pass rate
- const checkStats = {};
- for (const r of results) {
- for (const [k, v] of Object.entries(r.judgment.checks)) {
- if (!checkStats[k]) checkStats[k] = { pass: 0, fail: 0 };
- if (v) checkStats[k].pass++; else checkStats[k].fail++;
- }
- }
- lines.push('## Per-Check Pass Rate');
- lines.push('');
- lines.push('| Check | Pass Rate | Passed | Failed |');
- lines.push('|-------|-----------|--------|--------|');
- for (const [k, v] of Object.entries(checkStats).sort((a, b) => (a[1].pass / (a[1].pass + a[1].fail)) - (b[1].pass / (b[1].pass + b[1].fail)))) {
- const pct = ((v.pass / (v.pass + v.fail)) * 100).toFixed(0);
- lines.push(`| ${k} | ${pct}% | ${v.pass} | ${v.fail} |`);
- }
- lines.push('');
-
- // Redact sensitive URLs from report output
- function sanitize(text) {
- return text
- .replace(/https?:\/\/backend\.composio\.dev\/api\/[^\s)]+/g, '[REDACTED_COMPOSIO_URL]')
- .replace(/https?:\/\/[^\s)]*composio[^\s)]*\/connect[^\s)]*/gi, '[REDACTED_COMPOSIO_URL]')
- .replace(/Bearer\s+[A-Za-z0-9._-]+/g, 'Bearer [REDACTED]');
- }
-
- // Full conversations
- lines.push('## Full Conversations');
- lines.push('');
- for (let i = 0; i < results.length; i++) {
- const r = results[i];
- lines.push(`### ${i + 1}. ${r.scenario.name} (${r.judgment.passed}/${r.judgment.total})`);
- lines.push('');
-
- if (r.judgment.error) {
- lines.push(`**ERROR:** ${r.judgment.error}`);
- lines.push('');
- continue;
- }
-
- // Failed checks
- const failed = Object.entries(r.judgment.checks).filter(([, v]) => !v).map(([k]) => k);
- if (failed.length > 0) {
- lines.push(`**Failed checks:** ${failed.join(', ')}`);
- lines.push('');
- }
-
- // Conversation
- lines.push('```');
- for (const turn of r.conversation) {
- if (turn.role === 'trigger') {
- lines.push(`[trigger] ${sanitize(turn.content)}`);
- } else if (turn.role === 'user') {
- lines.push('');
- lines.push(`you> ${sanitize(turn.content)}`);
- } else {
- const tools = turn.tools?.length ? ` [tools: ${turn.tools.join(', ')}]` : '';
- lines.push(`agent> ${sanitize(turn.content)}${tools}`);
- }
- }
- lines.push('```');
- lines.push('');
- }
-
- return lines.join('\n');
-}
-
-main().catch((e) => {
- console.error(e);
- process.exit(1);
-});