Skip to content

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

test(agent): tier-1 prompt routing cases and tier-2 scored prompt evals

M3gA-Mind33c05335c684
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index dfca9c5c84..4ff9957cd0 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -154,6 +154,10 @@ path = "../../tests/agent_builder_public.rs"
name = "agent_harness_e2e"
path = "../../tests/agent_harness_e2e.rs"
+[[test]]
+name = "agent_prompt_comprehension_e2e"
+path = "../../tests/agent_prompt_comprehension_e2e.rs"
+
[[test]]
name = "agent_harness_public"
path = "../../tests/agent_harness_public.rs"
diff --git a/docs/prompt-evals.md b/docs/prompt-evals.md
new file mode 100644
index 0000000000..d4f15668d7
--- /dev/null
+++ b/docs/prompt-evals.md
@@ -0,0 +1,90 @@
+# Prompt evals
+
+Two tiers answer two different questions. Do not cite one as evidence for the
+other.
+
+| | Tier 1 — routing | Tier 2 — comprehension |
+|---|---|---|
+| Question | Is the agent wired so a model *could* follow its prompt? | Does a real model actually follow it? |
+| Where | `tests/agent_prompt_comprehension_e2e.rs` | `scripts/prompt-eval.sh` + `scripts/prompt-eval/cases.json` |
+| Model | Scripted completions (no model) | The real backend model |
+| Cost | Free, deterministic | Money per run, non-deterministic |
+| CI | Runs with the Rust integration tests | **Never.** Refuses to run when `CI=true` |
+
+## Tier 1 pins the script, not a model's judgment
+
+Every tier-1 completion is scripted. When the `workflow_builder` case scripts
+two `search_tool_catalog` calls and then `propose_workflow`, the test proves
+the builder's belt carries both tools, that both calls resolve (no
+`unknown tool`), that `flows_build` extracts the proposal, and that nothing in
+the runtime turns two searches into three. It proves **nothing** about whether
+a model, given that prompt, would propose instead of searching 27 times. That
+was the 2026-09-17 incident: the right guidance was in the prompt, and the
+model never reached it.
+
+A green tier 1 is therefore not evidence of comprehension. Only tier 2 is.
+
+The six cases cover the agents where mis-routing has cost something:
+`workflow_builder` (must reach `propose_workflow`, never three consecutive
+catalog searches), `orchestrator` (hands integration work off, never holds the
+raw Composio or cron tools), `integrations_agent`, `scheduler_agent`, and the
+two zero-belt agents `summarizer` and `trigger_triage` (advertise nothing).
+Fleet-wide static coverage of all agents lives in the prompt tests under
+`crates/openhuman-core/src/agent/registry/agents/`, not here.
+
+```sh
+cargo test -p openhuman --test agent_prompt_comprehension_e2e
+```
+
+## Tier 2
+
+```sh
+cargo build --bin openhuman-core
+OPENHUMAN_BACKEND_SESSION_TOKEN=... scripts/prompt-eval.sh --case workflow-builder-news
+# or OPENHUMAN_BACKEND_API_KEY=...; BACKEND_URL selects the backend
+```
+
+Each case gets a fresh `mktemp -d` workspace (`OPENHUMAN_WORKSPACE`) and its own
+`openhuman-core call` subprocesses: one to install the credential, one to run
+the agent (`openhuman.flows_build` or `openhuman.agent_chat`), and one for the
+judge. A process per case sidesteps the process-global model override and
+`AlreadyRunning`, and needs no feature gate.
+
+Scoring reads only artifacts the run already writes, in this order:
+
+1. **Hard failure signals.** A breaker halt (the repeat/failure middlewares'
+ halt log line), `[SUBAGENT_INCOMPLETE]` in a transcript, or `trail_off` /
+ `capped` / `error` on the `flows_build` result. Any of these scores the run
+ 0: it was unproductive. The motivating incident would have tripped these.
+2. **Did it do the thing.** Expected calls, forbidden calls and repeat caps,
+ from the assistant `tool_calls` in `<ws>/**/session_raw/*.jsonl`.
+3. **Cost.** Summed from each transcript's `_meta` (`input_tokens`,
+ `output_tokens`, `cached_input_tokens`, `charged_amount_usd`), plus an
+ `max_input_tokens` ceiling per case. The judge call is not included.
+4. **Judge** (cases with `"judge": true`). The production close-verification
+ rubric from `close_verification_prompt` in
+ `agent/harness/session/turn_checkpoint.rs`, copied into `cases.json` rather
+ than widening that `pub(super)` function for an on-demand script. The
+ verdict is read as `parse_close_verdict` reads it: the last standalone
+ `ACCEPT`/`REJECT` token wins, so `UNACCEPTABLE` is not `ACCEPT`.
+
+One row per case is appended to `target/prompt-eval-runs.jsonl`
+(gitignored with `target/`), and the run prints the total USD.
+
+**Every row records the model id beside its cost.** A provider-side model
+update silently rebaselines every score. Compare rows only when the model
+ids match.
+
+Tier 2 reads the on-disk transcripts, never Langfuse: Langfuse push is
+disabled outside staging/dev by design, and only the web progress bridge
+installs a collector at all. The run journal under
+`<ws>/tinyagents_store/journal` is the natural enrichment if transcript
+scoring proves too coarse.
+
+### Adding a case
+
+Add an object to `cases` in `scripts/prompt-eval/cases.json`: `id`, `entry`
+(`flows_build` or `agent_chat`), `message`, `expect_calls`, `forbid_calls`,
+`max_consecutive` (`{tool: cap}`), `max_input_tokens`, `judge`, and a `_why`
+naming the failure it guards against. Keep the set small; every case costs
+money on every run.
diff --git a/scripts/prompt-eval.sh b/scripts/prompt-eval.sh
new file mode 100755
index 0000000000..01fbce9ea4
--- /dev/null
+++ b/scripts/prompt-eval.sh
@@ -0,0 +1,97 @@
+#!/usr/bin/env bash
+# Tier-2 prompt evals: does a real model follow the agent prompts? Scored,
+# costs money, non-deterministic. NEVER gates CI (refuses to run when CI=true).
+# Tier 1 (`tests/agent_prompt_comprehension_e2e.rs`) pins the script; only this
+# answers whether a model follows it. See docs/prompt-evals.md.
+#
+# Usage: scripts/prompt-eval.sh [--case <id>] [--bin <openhuman-core>]
+#
+# Needs a backend credential in OPENHUMAN_BACKEND_SESSION_TOKEN or
+# OPENHUMAN_BACKEND_API_KEY (BACKEND_URL optional). Each case runs in its own
+# fresh workspace and its own `openhuman-core call` subprocesses, so the
+# process-global model override and `AlreadyRunning` never come into it.
+#
+# Scoring reads artifacts the run already writes:
+# 1. hard failure signals — breaker halt (log), [SUBAGENT_INCOMPLETE]
+# (transcripts), trail_off / capped (flows_build result). Any ⇒ unproductive.
+# 2. tool calls from <ws>/**/session_raw/*.jsonl: expected, forbidden, repeat caps.
+# 3. cost from each transcript's `_meta` line, with the model id beside it.
+# 4. optional judge: the production close-verification rubric (cases.json).
+# One row per case is appended to target/prompt-eval-runs.jsonl (gitignored).
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+CASES="$ROOT/scripts/prompt-eval/cases.json"
+BIN="$ROOT/target/debug/openhuman-core"
+OUT="$ROOT/target/prompt-eval-runs.jsonl"
+ONLY=""
+
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --case) ONLY="$2"; shift 2 ;;
+ --bin) BIN="$2"; shift 2 ;;
+ -h|--help) sed -n '2,20p' "$0"; exit 0 ;;
+ *) echo "unknown arg: $1" >&2; exit 2 ;;
+ esac
+done
+
+if [ "${CI:-}" = "true" ]; then
+ echo "prompt-eval: refusing to run in CI — tier 2 costs money and is non-deterministic" >&2
+ exit 1
+fi
+if [ -z "${OPENHUMAN_BACKEND_SESSION_TOKEN:-}${OPENHUMAN_BACKEND_API_KEY:-}" ]; then
+ echo "prompt-eval: set OPENHUMAN_BACKEND_SESSION_TOKEN or OPENHUMAN_BACKEND_API_KEY" >&2
+ exit 2
+fi
+[ -x "$BIN" ] || { echo "prompt-eval: no binary at $BIN (cargo build --bin openhuman-core)" >&2; exit 2; }
+mkdir -p "$(dirname "$OUT")"
+
+ids=$(python3 -c 'import json,sys; print("\n".join(c["id"] for c in json.load(open(sys.argv[1]))["cases"]))' "$CASES")
+[ -n "$ONLY" ] && { echo "$ids" | grep -qx "$ONLY" || { echo "no case $ONLY" >&2; exit 2; }; ids="$ONLY"; }
+
+total_usd=0
+for id in $ids; do
+ ws="$(mktemp -d -t prompt-eval)"
+ printf 'chat_onboarding_completed = true\n\n[secrets]\nencrypt = false\n' > "$ws/config.toml"
+ export OPENHUMAN_WORKSPACE="$ws" OPENHUMAN_KEYRING_BACKEND=file RUST_LOG="${RUST_LOG:-info}"
+
+ core() { "$BIN" call --method "$1" --params "$2" 2>>"$ws/core.log"; }
+
+ # `call` does not run the server's boot-env credential seeding, so install it.
+ # ponytail: the credential rides argv (visible in `ps`) — `call` takes params
+ # no other way; fine on a dev machine, add a --params-file before a shared host.
+ if [ -n "${OPENHUMAN_BACKEND_API_KEY:-}" ]; then
+ cred=$(python3 -c 'import json,os; print(json.dumps({"token": os.environ["OPENHUMAN_BACKEND_API_KEY"], "kind": "api-key"}))')
+ else
+ cred=$(python3 -c 'import json,os; print(json.dumps({"token": os.environ["OPENHUMAN_BACKEND_SESSION_TOKEN"], "kind": "session"}))')
+ fi
+ core openhuman.auth_set_credential "$cred" >/dev/null
+
+ entry=$(python3 -c 'import json,sys; c=[c for c in json.load(open(sys.argv[1]))["cases"] if c["id"]==sys.argv[2]][0]; print(c["entry"]); print(c["message"])' "$CASES" "$id")
+ kind=$(echo "$entry" | head -1); message=$(echo "$entry" | tail -n +2)
+ case "$kind" in
+ flows_build) method=openhuman.flows_build
+ params=$(python3 -c 'import json,sys; print(json.dumps({"mode": "create", "instruction": sys.argv[1]}))' "$message") ;;
+ agent_chat) method=openhuman.agent_chat
+ params=$(python3 -c 'import json,sys; print(json.dumps({"message": sys.argv[1]}))' "$message") ;;
+ *) echo "case $id: unknown entry $kind" >&2; exit 2 ;;
+ esac
+
+ echo "── $id ($method) workspace=$ws" >&2
+ started=$(date +%s)
+ core "$method" "$params" > "$ws/result.json" || echo "case $id: $method exited non-zero (scored anyway)" >&2
+ elapsed=$(( $(date +%s) - started ))
+
+ # Judge in the same workspace (same credential), as a tool-less chat call.
+ judge_prompt=$(python3 "$ROOT/scripts/prompt-eval/score.py" judge-prompt "$CASES" "$id" "$ws")
+ if [ -n "$judge_prompt" ]; then
+ jp=$(python3 -c 'import json,sys; print(json.dumps({"message": sys.stdin.read()}))' <<<"$judge_prompt")
+ core openhuman.agent_chat_simple "$jp" > "$ws/judge.json" || true
+ fi
+
+ row=$(python3 "$ROOT/scripts/prompt-eval/score.py" score "$CASES" "$id" "$ws" "$elapsed")
+ echo "$row" >> "$OUT"
+ echo "$row" | python3 -c 'import json,sys; r=json.load(sys.stdin); print("%s: %s score=%s usd=%.4f models=%s failures=%s" % (r["case"], "PASS" if r["pass"] else "FAIL", r["score"], r["usd"], r["models"], r["failures"]))'
+ total_usd=$(python3 -c 'import json,sys; print(float(sys.argv[1]) + json.loads(sys.argv[2])["usd"])' "$total_usd" "$row")
+done
+echo "total USD: $total_usd (rows appended to $OUT)"
diff --git a/scripts/prompt-eval/cases.json b/scripts/prompt-eval/cases.json
new file mode 100644
index 0000000000..5ef702e5e3
--- /dev/null
+++ b/scripts/prompt-eval/cases.json
@@ -0,0 +1,47 @@
+{
+ "_comment": "Tier-2 prompt evals: real model, scored, on demand only. Never wired into CI. See docs/prompt-evals.md.",
+ "judge": {
+ "_source": "Copied from close_verification_prompt in crates/openhuman-core/src/agent/harness/session/turn_checkpoint.rs (pub(super), deliberately not widened for this script). The Rust copy has a drift guard; if you edit the rules there, mirror them here.",
+ "preamble": "You are checking a reply before it is shown to a user. Below are the user's request, the records of the tool calls made while handling it, and the reply.",
+ "rules": [
+ "The reply only says what the assistant will do or is about to do, instead of reporting what happened.",
+ "The reply states something the tool records contradict, for example that something does not exist or did not work when a record shows it succeeded, or that something succeeded when its record shows it failed.",
+ "The request was not completed, a failed record gives the reason, and the reply does not pass that reason on."
+ ]
+ },
+ "cases": [
+ {
+ "id": "workflow-builder-news",
+ "_why": "The 2026-09-17 incident: 512,775 input tokens and 27 catalog searches in one turn, no propose_workflow.",
+ "entry": "flows_build",
+ "message": "Every morning at 8am, send me a digest of the latest sports news.",
+ "expect_calls": ["propose_workflow"],
+ "forbid_calls": [],
+ "max_consecutive": { "search_tool_catalog": 2 },
+ "max_input_tokens": 150000,
+ "judge": true
+ },
+ {
+ "id": "orchestrator-reminder",
+ "_why": "A scheduling request must reach scheduler_agent through schedule_task, not be answered in prose.",
+ "entry": "agent_chat",
+ "message": "Remind me to stretch every weekday at 3pm.",
+ "expect_calls": ["schedule_task"],
+ "forbid_calls": ["shell"],
+ "max_consecutive": {},
+ "max_input_tokens": 100000,
+ "judge": true
+ },
+ {
+ "id": "orchestrator-direct-answer",
+ "_why": "Direct-first: a trivial question must be answered without spawning a sub-agent.",
+ "entry": "agent_chat",
+ "message": "What is 17 times 23?",
+ "expect_calls": [],
+ "forbid_calls": ["research", "spawn_async_subagent", "schedule_task"],
+ "max_consecutive": {},
+ "max_input_tokens": 60000,
+ "judge": false
+ }
+ ]
+}
diff --git a/scripts/prompt-eval/score.py b/scripts/prompt-eval/score.py
new file mode 100755
index 0000000000..993bec5703
--- /dev/null
+++ b/scripts/prompt-eval/score.py
@@ -0,0 +1,219 @@
+#!/usr/bin/env python3
+"""Scorer for scripts/prompt-eval.sh. Reads only artifacts a run already wrote.
+
+ score.py judge-prompt <cases.json> <case-id> <workspace> -> judge prompt, or nothing
+ score.py score <cases.json> <case-id> <workspace> <secs> -> one JSON row
+ score.py selftest
+"""
+import glob
+import json
+import os
+import re
+import subprocess
+import sys
+import time
+
+# Log lines the breaker middlewares emit when they halt a run
+# (agent/tinyagents/middleware/{repeat_progress,repeated_failure}.rs).
+HALT_LOG = re.compile(r"halted the run|halting run so the root cause|halting on first occurrence")
+
+
+def load_case(cases_path, case_id):
+ doc = json.load(open(cases_path))
+ return doc, next(c for c in doc["cases"] if c["id"] == case_id)
+
+
+def rpc_value(path):
+ """The value an `openhuman-core call` printed, unwrapped from {result, logs}."""
+ try:
+ text = open(path).read()
+ except OSError:
+ return None
+ start = text.find("{")
+ if start < 0:
+ return text.strip() or None
+ try:
+ v = json.loads(text[start:])
+ except ValueError:
+ return text.strip()
+ while isinstance(v, dict) and "result" in v and len(v) <= 2:
+ v = v["result"]
+ return v
+
+
+def transcripts(ws):
+ """[(meta, [message lines])] for every session_raw transcript in the workspace."""
+ out = []
+ for path in sorted(glob.glob(os.path.join(ws, "**", "session_raw", "*.jsonl"), recursive=True)):
+ meta, lines = {}, []
+ for raw in open(path, errors="replace"):
+ raw = raw.strip()
+ if not raw:
+ continue
+ try:
+ obj = json.loads(raw)
+ except ValueError:
+ continue
+ if "_meta" in obj:
+ meta = obj["_meta"] # last one wins: the header is rewritten as the run advances
+ else:
+ lines.append(obj)
+ out.append((meta, lines))
+ return out
+
+
+def tool_calls(lines):
+ return [tc.get("name", "") for m in lines if m.get("role") == "assistant" for tc in (m.get("tool_calls") or [])]
+
+
+def max_consecutive(calls, tool):
+ best = run = 0
+ for name in calls:
+ run = run + 1 if name == tool else 0
+ best = max(best, run)
+ return best
+
+
+def verdict(text):
+ """parse_close_verdict: the LAST standalone ACCEPT/REJECT token wins."""
+ tokens = [t.upper() for t in re.split(r"[^A-Za-z]+", text or "")]
+ found = [t for t in tokens if t in ("ACCEPT", "REJECT")]
+ return found[-1] if found else "UNCLEAR"
+
+
+def reply_text(value):
+ if isinstance(value, dict):
+ for key in ("assistant_text", "response", "text", "reply"):
+ if isinstance(value.get(key), str):
+ return value[key]
+ return json.dumps(value)[:4000]
+ return value or ""
+
+
+def records(ts):
+ out = []
+ for _, lines in ts:
+ for m in lines:
+ if m.get("role") == "tool":
+ status = "failed" if m.get("failure") else "ok"
+ out.append(f"- [{status}] {str(m.get('content', ''))[:400]}")
+ return "\n".join(out[-40:])
+
+
+def judge_prompt(doc, case, ws):
+ if not case.get("judge"):
+ return ""
+ j = doc["judge"]
+ rules = "\n".join(f"{i}. {r}" for i, r in enumerate(j["rules"], 1))
+ recs = records(transcripts(ws)).strip() or "(no tool calls completed)"
+ return (
+ f"{j['preamble']}\n\nAnswer REJECT if any of these is true:\n{rules}\n\n"
+ "Otherwise answer ACCEPT. Reply with the single word ACCEPT or REJECT.\n\n"
+ f"<user_request>\n{case['message']}\n</user_request>\n\n<tool_records>\n{recs}\n</tool_records>\n\n"
+ f"<reply>\n{reply_text(rpc_value(os.path.join(ws, 'result.json'))).strip()}\n</reply>"
+ )
+
+
+def score(doc, case, ws, secs):
+ ts = transcripts(ws)
+ result = rpc_value(os.path.join(ws, "result.json"))
+ failures = []
+
+ # 1. Hard failure signals — cheap, no judge needed.
+ signals = []
+ log = ""
+ for path in [os.path.join(ws, "core.log")] + glob.glob(os.path.join(ws, "**", "*.log"), recursive=True):
+ try:
+ log += open(path, errors="replace").read()
+ except OSError:
+ pass
+ if HALT_LOG.search(log):
+ signals.append("breaker_halt")
+ blob = json.dumps([lines for _, lines in ts]) + json.dumps(result)
+ if "[SUBAGENT_INCOMPLETE]" in blob:
+ signals.append("SUBAGENT_INCOMPLETE")
+ if isinstance(result, dict):
+ for flag in ("trail_off", "capped"):
+ if result.get(flag):
+ signals.append(flag)
+ if result.get("error"):
+ signals.append("run_error")
+ if result is None:
+ signals.append("no_result")
+ failures += [f"signal:{s}" for s in signals]
+
+ # 2. Did it do the thing.
+ all_calls = [c for _, lines in ts for c in tool_calls(lines)]
+ checks = 0
+ for tool in case.get("expect_calls", []):
+ checks += 1
+ if tool not in all_calls:
+ failures.append(f"missing_call:{tool}")
+ for tool in case.get("forbid_calls", []):
+ checks += 1
+ if tool in all_calls:
+ failures.append(f"forbidden_call:{tool}")
+ for tool, cap in case.get("max_consecutive", {}).items():
+ checks += 1
+ worst = max([max_consecutive(tool_calls(lines), tool) for _, lines in ts] or [0])
+ if worst > cap:
+ failures.append(f"repeat:{tool}x{worst}>{cap}")
+
+ # 3. Cost. ponytail: sums every transcript's _meta; if a parent's totals ever
+ # include its children's, this double-counts — switch to root-only then.
+ metas = [m for m, _ in ts if m]
+ tok = {k: sum(int(m.get(k) or 0) for m in metas) for k in ("input_tokens", "output_tokens", "cached_input_tokens")}
+ usd = sum(float(m.get("charged_amount_usd") or 0) for m in metas)
+ models = sorted({m.get("model") for m in metas if m.get("model")} |
+ {l.get("model") for _, lines in ts for l in lines if l.get("model")})
+ checks += 1
+ if tok["input_tokens"] > case.get("max_input_tokens", 10**12):
+ failures.append(f"input_tokens:{tok['input_tokens']}>{case['max_input_tokens']}")
+
+ # 4. Judge.
+ judged = None
+ if case.get("judge"):
+ checks += 1
+ judged = verdict(reply_text(rpc_value(os.path.join(ws, "judge.json"))))
+ if judged != "ACCEPT":
+ failures.append(f"judge:{judged}")
+
+ passed_checks = checks - len([f for f in failures if not f.startswith("signal:")])
+ return {
+ "ts": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
+ "case": case["id"],
+ "git_sha": subprocess.run(["git", "rev-parse", "--short", "HEAD"], capture_output=True, text=True).stdout.strip(),
+ "models": models,
+ "pass": not failures,
+ "score": 0.0 if signals else round(max(passed_checks, 0) / max(checks, 1), 3),
+ "signals": signals,
+ "failures": failures,
+ "judge": judged,
+ "calls": all_calls,
+ "transcripts": len(ts),
+ **tok,
+ "usd": usd,
+ "seconds": secs,
+ "workspace": ws,
+ }
+
+
+def selftest():
+ assert verdict("I think... ACCEPT") == "ACCEPT"
+ assert verdict("ACCEPT? no. REJECT") == "REJECT"
+ assert verdict("UNACCEPTABLE") == "UNCLEAR"
+ assert max_consecutive(["a", "b", "b", "a", "b", "b", "b"], "b") == 3
+ assert HALT_LOG.search("[tinyagents::mw] crate successful-repeat tracker halted the run")
+ print("score.py selftest ok")
+
+
+if __name__ == "__main__":
+ cmd = sys.argv[1]
+ if cmd == "selftest":
+ selftest()
+ elif cmd == "judge-prompt":
+ doc, case = load_case(sys.argv[2], sys.argv[3])
+ print(judge_prompt(doc, case, sys.argv[4]))
+ elif cmd == "score":
+ doc, case = load_case(sys.argv[2], sys.argv[3])
+ print(json.dumps(score(doc, case, sys.argv[4], int(sys.argv[5]))))
diff --git a/tests/agent_prompt_comprehension_e2e.rs b/tests/agent_prompt_comprehension_e2e.rs
new file mode 100644
index 0000000000..4d6d20d9a7
--- /dev/null
+++ b/tests/agent_prompt_comprehension_e2e.rs
@@ -0,0 +1,920 @@
+//! Tier-1 prompt-comprehension routing cases (see `docs/prompt-evals.md`).
+//!
+//! Each case drives one agent through the real core JSON-RPC stack against a
+//! scripted upstream and asserts on the captured wire: which tools the agent's
+//! own model request advertised, which scripted calls actually resolved to a
+//! tool the agent could reach, and how many times in a row it repeated one.
+//!
+//! **This pins the script, not a model's judgment.** The completions are
+//! scripted, so a green run proves the belt, the routing and the hand-offs are
+//! wired so a model *could* follow the prompt — never that one does. Whether a
+//! real model follows it is tier 2 (`scripts/prompt-eval.sh`).
+//!
+//! Infrastructure is copied from `tests/agent_harness_e2e.rs` (scripted HTTP
+//! stack, not `test_provider_override`, which compiles out of an integration
+//! test without a default-off feature). Every test holds the process-global
+//! `env_lock()` across `.await` on purpose, as there.
+#![allow(clippy::await_holding_lock)]
+
+use std::net::SocketAddr;
+use std::path::Path;
+use std::sync::{Mutex, OnceLock};
+use std::time::Duration;
+
+use axum::http::{header::AUTHORIZATION, HeaderMap};
+use axum::routing::{get, post};
+use axum::{Json, Router};
+use futures_util::StreamExt;
+use serde_json::{json, Value};
+use tempfile::tempdir;
+
+use openhuman_core::agent::harness::AgentDefinitionRegistry;
+use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
+use openhuman_core::core::jsonrpc::build_core_http_router;
+
+const TEST_RPC_TOKEN: &str = "json-rpc-e2e-local-token";
+
+// ─── Env serialization ──────────────────────────────────────────────────────
+
+static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
+static KEYRING_INIT: OnceLock<()> = OnceLock::new();
+static AGENT_DEF_REGISTRY_INIT: OnceLock<()> = OnceLock::new();
+
+fn env_lock() -> std::sync::MutexGuard<'static, ()> {
+ KEYRING_INIT.get_or_init(|| unsafe {
+ std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "file");
+ });
+ match ENV_LOCK.get_or_init(|| Mutex::new(())).lock() {
+ Ok(guard) => guard,
+ Err(poisoned) => poisoned.into_inner(),
+ }
+}
+
+struct EnvVarGuard {
+ key: &'static str,
+ old: Option<String>,
+}
+
+impl EnvVarGuard {
+ fn set_to_path(key: &'static str, path: &Path) -> Self {
+ let old = std::env::var(key).ok();
+ std::env::set_var(key, path.as_os_str());
+ Self { key, old }
+ }
+
+ fn unset(key: &'static str) -> Self {
+ let old = std::env::var(key).ok();
+ std::env::remove_var(key);
+ Self { key, old }
+ }
+}
+
+impl Drop for EnvVarGuard {
+ fn drop(&mut self) {
+ match &self.old {
+ Some(v) => std::env::set_var(self.key, v),
+ None => std::env::remove_var(self.key),
+ }
+ }
+}
+
+// ─── Scripted upstream ──────────────────────────────────────────────────────
+
+static SCRIPTED: OnceLock<Mutex<std::collections::VecDeque<Value>>> = OnceLock::new();
+static CAPTURED: OnceLock<Mutex<Vec<Value>>> = OnceLock::new();
+
+fn lock_or_recover<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
+ match m.lock() {
+ Ok(g) => g,
+ Err(p) => p.into_inner(),
+ }
+}
+
+fn scripted() -> std::sync::MutexGuard<'static, std::collections::VecDeque<Value>> {
+ lock_or_recover(SCRIPTED.get_or_init(Default::default))
+}
+
+fn captured() -> std::sync::MutexGuard<'static, Vec<Value>> {
+ lock_or_recover(CAPTURED.get_or_init(Default::default))
+}
+
+fn reset_script(responses: Vec<Value>) {
+ let mut q = scripted();
+ q.clear();
+ q.extend(responses);
+ captured().clear();
+}
+
+fn text_completion(content: &str) -> Value {
+ json!({ "content": content })
+}
+
+/// One tool call, id'd `call_<name>_<arglen>` so repeats of the same tool with
+/// different arguments stay distinguishable (from `agent_harness_e2e.rs`).
+fn tool_calls_completion(calls: &[(&str, Value)]) -> Value {
+ json!({ "content": "", "toolCalls": calls.iter().map(|(name, arguments)| json!({
+ "id": format!("call_{name}_{}", arguments.to_string().len()),
+ "name": name,
+ "arguments": arguments.to_string(),
+ })).collect::<Vec<_>>() })
+}
+
+fn call(name: &str, arguments: Value) -> Value {
+ tool_calls_completion(&[(name, arguments)])
+}
+
+/// True when any captured request carries the engine's unknown-tool result.
+fn captured_requests_mention_unknown_tool(requests: &[Value]) -> bool {
+ serde_json::to_string(requests)
+ .unwrap_or_default()
+ .to_ascii_lowercase()
+ .contains("unknown tool")
+}
+
+/// The tool message answering the first scripted call to `tool_name`.
+/// Panics on an `unknown tool` result: that error echoes the arguments, so a
+/// canary passed as an argument would otherwise read as a pass.
+fn tool_result_text(requests: &[Value], tool_name: &str) -> Option<String> {
+ let prefix = format!("call_{tool_name}_");
+ requests
+ .iter()
+ .filter_map(|request| request.pointer("/body/messages").and_then(Value::as_array))
+ .flatten()
+ .find(|message| {
+ message.get("role").and_then(Value::as_str) == Some("tool")
+ && message
+ .get("tool_call_id")
+ .and_then(Value::as_str)
+ .is_some_and(|id| id.starts_with(&prefix))
+ })
+ .and_then(|message| message.get("content"))
+ .map(|content| {
+ let text = content
+ .as_str()
+ .map(str::to_string)
+ .unwrap_or_else(|| content.to_string());
+ assert!(
+ !text.trim_start().starts_with("unknown tool"),
+ "`{tool_name}` was not a tool the calling agent could reach: {text}"
+ );
+ text
+ })
+}
+
+/// Tool names a captured model request advertised to the provider.
+fn advertised_tool_names(request: &Value) -> Vec<String> {
+ request
+ .pointer("/body/tools")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter_map(|tool| {
+ tool.pointer("/function/name")
+ .or_else(|| tool.get("name"))
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ })
+ .collect()
+}
+
+async fn scripted_chat_completions(Json(body): Json<Value>) -> axum::response::Response {
+ let streaming = body.get("stream").and_then(Value::as_bool).unwrap_or(false);
+ captured().push(json!({ "body": body.clone() }));
+
+ let entry = scripted().pop_front();
+ let Some(entry) = entry else {
+ let message = json!({ "role": "assistant", "content": "default scripted completion" });
+ return completion_response(streaming, message);
+ };
+ let content = entry.get("content").and_then(Value::as_str).unwrap_or("");
+ let mut message = json!({ "role": "assistant", "content": content });
+ if let Some(tool_calls) = entry.get("toolCalls").and_then(Value::as_array) {
+ let calls: Vec<Value> = tool_calls
+ .iter()
+ .map(|tc| {
+ json!({
+ "id": tc.get("id").and_then(Value::as_str).unwrap_or("call_scripted"),
+ "type": "function",
+ "function": {
+ "name": tc.get("name").and_then(Value::as_str).unwrap_or(""),
+ "arguments": tc.get("arguments").and_then(Value::as_str).unwrap_or("{}"),
+ }
+ })
+ })
+ .collect();
+ message["tool_calls"] = json!(calls);
+ }
+ completion_response(streaming, message)
+}
+
+/// Non-streaming JSON body or the SSE stream both model clients parse.
+fn completion_response(streaming: bool, message: Value) -> axum::response::Response {
+ use axum::response::IntoResponse;
+
+ if !streaming {
+ return Json(json!({ "choices": [{ "message": message }] })).into_response();
+ }
+ let mut delta = json!({ "role": "assistant" });
+ if let Some(content) = message.get("content").and_then(Value::as_str) {
+ if !content.is_empty() {
+ delta["content"] = json!(content);
+ }
+ }
+ if let Some(tool_calls) = message.get("tool_calls").and_then(Value::as_array) {
+ let indexed: Vec<Value> = tool_calls
+ .iter()
+ .enumerate()
+ .map(|(i, tc)| {
+ let mut c = tc.clone();
+ c["index"] = json!(i);
+ c
+ })
+ .collect();
+ delta["tool_calls"] = json!(indexed);
+ }
+ let body = format!(
+ "data: {}\n\ndata: {}\n\ndata: [DONE]\n\n",
+ json!({ "choices": [{ "index": 0, "delta": delta }] }),
+ json!({ "choices": [{ "index": 0, "delta": {}, "finish_reason": "stop" }] })
+ );
+ (
+ [(axum::http::header::CONTENT_TYPE, "text/event-stream")],
+ body,
+ )
+ .into_response()
+}
+
+async fn current_user(_headers: HeaderMap) -> Json<Value> {
+ Json(json!({ "success": true, "data": { "_id": "e2e-user-1", "username": "e2e" } }))
+}
+
+/// One connected Gmail toolkit, so the orchestrator is offered
+/// `delegate_to_integrations_agent` and the integrations agent has a toolkit to
+/// bind to. Shapes from `tools_approval_channels_raw_coverage_e2e.rs`.
+async fn composio_toolkits() -> Json<Value> {
+ Json(json!({ "success": true, "data": { "toolkits": ["gmail"] } }))
+}
+
+async fn composio_connections() -> Json<Value> {
+ Json(json!({ "success": true, "data": { "connections": [{
+ "id": "conn-gmail-1", "toolkit": "gmail", "status": "ACTIVE",
+ "createdAt": "2026-05-29T12:00:00Z"
+ }] } }))
+}
+
+async fn composio_tools() -> Json<Value> {
+ Json(json!({ "success": true, "data": { "tools": [{
+ "type": "function",
+ "function": {
+ "name": "GMAIL_FETCH_EMAILS",
+ "description": "Fetch matching Gmail messages for the user.",
+ "parameters": { "type": "object", "properties": { "query": { "type": "string" } } }
+ }
+ }] } }))
+}
+
+fn scripted_upstream_router() -> Router {
+ Router::new()
+ .route("/settings", get(current_user))
+ .route("/auth/me", get(current_user))
+ .route(
+ "/agent-integrations/composio/toolkits",
+ get(composio_toolkits),
+ )
+ .route(
+ "/agent-integrations/composio/connections",
+ get(composio_connections),
+ )
+ .route("/agent-integrations/composio/tools", get(composio_tools))
+ .route(
+ "/openai/v1/chat/completions",
+ post(scripted_chat_completions),
+ )
+ .route("/v1/chat/completions", post(scripted_chat_completions))
+ .route("/chat/completions", post(scripted_chat_completions))
+}
+
+// ─── Server + RPC helpers ───────────────────────────────────────────────────
+
+async fn serve_on_ephemeral(
+ app: Router,
+) -> (
+ SocketAddr,
+ tokio::task::JoinHandle<Result<(), std::io::Error>>,
+) {
+ static AUTH_INIT: OnceLock<()> = OnceLock::new();
+ AUTH_INIT.get_or_init(|| {
+ // SAFETY: runs exactly once via OnceLock before concurrent env reads occur.
+ unsafe { std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN) };
+ let token_dir = std::env::temp_dir().join("openhuman-prompt-comprehension-e2e-auth");
+ init_rpc_token(&token_dir).expect("init rpc auth token");
+ });
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind");
+ let addr = listener.local_addr().expect("addr");
+ let handle = tokio::spawn(async move { axum::serve(listener, app).await });
+ (addr, handle)
+}
+
+async fn post_json_rpc(rpc_base: &str, id: i64, method: &str, params: Value) -> Value {
+ let client = reqwest::Client::builder()
+ .timeout(Duration::from_secs(180))
+ .build()
+ .expect("client");
+ let body = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });
+ let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));
+ let resp = client
+ .post(&url)
+ .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))
+ .json(&body)
+ .send()
+ .await
+ .unwrap_or_else(|e| panic!("POST {url}: {e}"));
+ assert!(
+ resp.status().is_success(),
+ "HTTP {} for {method}",
+ resp.status()
+ );
+ resp.json::<Value>()
+ .await
+ .unwrap_or_else(|e| panic!("json for {method}: {e}"))
+}
+
+fn assert_no_jsonrpc_error<'a>(v: &'a Value, context: &str) -> &'a Value {
+ if let Some(err) = v.get("error") {
+ panic!("{context}: JSON-RPC error: {err}");
+ }
+ v.get("result")
+ .unwrap_or_else(|| panic!("{context}: missing result: {v}"))
+}
+
+/// `extra` is appended verbatim, for per-case `[context]` knobs.
+fn write_min_config(openhuman_dir: &Path, api_origin: &str, extra: &str) {
+ // `compaction_enabled = false`: the builder's `propose_workflow` result is
+ // otherwise CCR-compressed and `flows_build` cannot extract the proposal
+ // (see `write_flows_tier_config` in `json_rpc_e2e.rs`).
+ let cfg = format!(
+ r#"api_url = "{api_origin}"
+default_model = "e2e-mock-model"
+default_temperature = 0.7
+chat_onboarding_completed = true
+
+[secrets]
+encrypt = false
+
+[context]
+compaction_enabled = false
+{extra}
+"#
+ );
+ for dir in [
+ openhuman_dir.to_path_buf(),
+ openhuman_dir.join("users").join("local"),
+ ] {
+ std::fs::create_dir_all(&dir).expect("mkdir openhuman");
+ std::fs::write(dir.join("config.toml"), &cfg).expect("write config");
+ }
+ let _: openhuman_core::config::Config =
+ toml::from_str(&cfg).expect("config toml must match Config schema");
+}
+
+fn spawn_sse_collector(events_url: String) -> tokio::sync::mpsc::UnboundedReceiver<Value> {
+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
+ tokio::spawn(async move {
+ let client = reqwest::Client::builder()
+ .timeout(Duration::from_secs(300))
+ .build()
+ .expect("client");
+ let resp = client
+ .get(&events_url)
+ .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))
+ .send()
+ .await
+ .unwrap_or_else(|e| panic!("GET {events_url}: {e}"));
+ let mut stream = resp.bytes_stream();
+ let mut buffer: Vec<u8> = Vec::new();
+ while let Some(Ok(chunk)) = stream.next().await {
+ buffer.extend_from_slice(&chunk);
+ while let Some(idx) = buffer.windows(2).position(|w| w == b"\n\n") {
+ let frame: Vec<u8> = buffer.drain(..idx + 2).take(idx).collect();
+ let data: Vec<String> = String::from_utf8_lossy(&frame)
+ .lines()
+ .filter_map(|l| l.strip_prefix("data:"))
+ .map(|l| l.trim_start().to_string())
+ .collect();
+ if let Ok(value) = serde_json::from_str::<Value>(&data.join("\n")) {
+ if tx.send(value).is_err() {
+ return;
+ }
+ }
+ }
+ }
+ });
+ rx
+}
+
+async fn wait_for_terminal(rx: &mut tokio::sync::mpsc::UnboundedReceiver<Value>) -> Value {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(180);
+ loop {
+ let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
+ match tokio::time::timeout(remaining, rx.recv()).await {
+ Ok(Some(v)) => match v.get("event").and_then(Value::as_str) {
+ Some("chat_done") | Some("chat_error") => return v,
+ _ => {}
+ },
+ Ok(None) => panic!("SSE channel closed waiting for terminal event"),
+ Err(_) => panic!("timed out waiting for terminal web-chat event"),
+ }
+ }
+}
+
+struct Stack {
+ rpc_base: String,
+ _guards: Vec<EnvVarGuard>,
+ _tmp: tempfile::TempDir,
+ joins: Vec<tokio::task::JoinHandle<Result<(), std::io::Error>>>,
+}
+
+impl Drop for Stack {
+ fn drop(&mut self) {
+ self.joins.iter().for_each(|j| j.abort());
+ }
+}
+
+async fn boot_stack(extra_config: &str) -> Stack {
+ AGENT_DEF_REGISTRY_INIT.get_or_init(|| {
+ AgentDefinitionRegistry::init_global_builtins()
+ .expect("AgentDefinitionRegistry::init_global_builtins must not fail");
+ });
+
+ let tmp = tempdir().expect("tempdir");
+ let home = tmp.path().to_path_buf();
+ let openhuman_home = home.join(".openhuman");
+ let guards = vec![
+ EnvVarGuard::set_to_path("HOME", &home),
+ EnvVarGuard::unset("OPENHUMAN_WORKSPACE"),
+ EnvVarGuard::unset("BACKEND_URL"),
+ EnvVarGuard::unset("VITE_BACKEND_URL"),
+ ];
+
+ let (mock_addr, mock_join) = serve_on_ephemeral(scripted_upstream_router()).await;
+ let mock_origin = format!("http://{mock_addr}");
+ write_min_config(&openhuman_home, &mock_origin, extra_config);
+ write_min_config(
+ &openhuman_home.join("users").join("e2e-user"),
+ &mock_origin,
+ extra_config,
+ );
+
+ let (rpc_addr, rpc_join) = serve_on_ephemeral(build_core_http_router(false)).await;
+ let rpc_base = format!("http://{rpc_addr}");
+ tokio::time::sleep(Duration::from_millis(100)).await;
+
+ let store = post_json_rpc(
+ &rpc_base,
+ 1,
+ "openhuman.auth_store_session",
+ json!({ "token": "e2e-test-jwt", "user_id": "e2e-user" }),
+ )
+ .await;
+ assert_no_jsonrpc_error(&store, "auth_store_session");
+
+ Stack {
+ rpc_base,
+ _guards: guards,
+ _tmp: tmp,
+ joins: vec![mock_join, rpc_join],
+ }
+}
+
+fn run_on_agent_stack<F, Fut>(name: &str, future_factory: F)
+where
+ F: FnOnce() -> Fut + Send + 'static,
+ Fut: std::future::Future<Output = ()> + 'static,
+{
+ std::thread::Builder::new()
+ .name(name.to_string())
+ .stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .spawn(move || {
+ tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .enable_all()
+ .build()
+ .expect("build runtime")
+ .block_on(future_factory());
+ })
+ .expect("spawn agent stack thread")
+ .join()
+ .expect("prompt comprehension case should not panic");
+}
+
+// ─── The case table ─────────────────────────────────────────────────────────
+
+/// How the case reaches its agent.
+enum Entry {
+ /// A web-chat turn (the orchestrator, and specialists it hands off to).
+ WebChat,
+ /// `openhuman.flows_build` — the workflow_builder directly.
+ FlowsBuild,
+ /// `openhuman.agent_triage_evaluate` with `dry_run` — trigger_triage directly.
+ TriageEvaluate,
+}
+
+struct Case {
+ /// Agent under test.
+ agent: &'static str,
+ /// Substring of that agent's system prompt (its `prompt.md` heading), used
+ /// to pick its requests out of everything the stack sent upstream.
+ agent_marker: &'static str,
+ entry: Entry,
+ user_message: &'static str,
+ /// Every upstream reply, in request order across all agents in the run.
+ scripted_completions: Vec<Value>,
+ /// Tools the agent called that must have resolved (a tool result exists
+ /// and is not `unknown tool`).
+ must_call: &'static [&'static str],
+ /// Tools the agent must never have called.
+ must_not_call: &'static [&'static str],
+ must_advertise: &'static [&'static str],
+ must_not_advertise: &'static [&'static str],
+ /// Zero-belt agents: the agent's requests carry no tools at all.
+ advertises_nothing: bool,
+ /// `(tool, n)`: never more than `n` consecutive calls of `tool`.
+ max_consecutive_calls_of: Option<(&'static str, usize)>,
+ /// Extra `config.toml` lines (appended after `[context]`).
+ extra_config: &'static str,
+}
+
+fn system_text(request: &Value) -> String {
+ request
+ .pointer("/body/messages")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter(|m| m.get("role").and_then(Value::as_str) == Some("system"))
+ .map(|m| {
+ m.get("content")
+ .map(|c| {
+ c.as_str()
+ .map(str::to_string)
+ .unwrap_or_else(|| c.to_string())
+ })
+ .unwrap_or_default()
+ })
+ .collect()
+}
+
+/// Tool names the agent called, in order, read from its last request (which
+/// carries its whole history).
+fn called_tools(request: &Value) -> Vec<String> {
+ request
+ .pointer("/body/messages")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter(|m| m.get("role").and_then(Value::as_str) == Some("assistant"))
+ .filter_map(|m| m.get("tool_calls").and_then(Value::as_array))
+ .flatten()
+ .filter_map(|tc| tc.pointer("/function/name").and_then(Value::as_str))
+ .map(str::to_string)
+ .collect()
+}
+
+fn max_consecutive(calls: &[String], tool: &str) -> usize {
+ let (mut best, mut run) = (0, 0);
+ for name in calls {
+ run = if name == tool { run + 1 } else { 0 };
+ best = best.max(run);
+ }
+ best
+}
+
+fn run_case(case: Case) {
+ run_on_agent_stack(case.agent, move || run_case_inner(case));
+}
+
+async fn run_case_inner(case: Case) {
+ let _lock = env_lock();
+ reset_script(case.scripted_completions);
+ let stack = boot_stack(case.extra_config).await;
+
+ match case.entry {
+ Entry::WebChat => {
+ let client_id = format!("prompt-{}", case.agent);
+ let mut events =
+ spawn_sse_collector(format!("{}/events?client_id={client_id}", stack.rpc_base));
+ let resp = post_json_rpc(
+ &stack.rpc_base,
+ 10,
+ "openhuman.channel_web_chat",
+ json!({
+ "client_id": client_id,
+ "thread_id": format!("thread-{}", case.agent),
+ "message": case.user_message,
+ "model_override": "e2e-mock-model",
+ }),
+ )
+ .await;
+ assert_no_jsonrpc_error(&resp, "channel_web_chat");
+ let done = wait_for_terminal(&mut events).await;
+ assert_eq!(
+ done.get("event").and_then(Value::as_str),
+ Some("chat_done"),
+ "[{}] turn must finish: {done}",
+ case.agent
+ );
+ }
+ Entry::FlowsBuild => {
+ let resp = post_json_rpc(
+ &stack.rpc_base,
+ 10,
+ "openhuman.flows_build",
+ json!({ "mode": "create", "instruction": case.user_message }),
+ )
+ .await;
+ let out = assert_no_jsonrpc_error(&resp, "flows_build");
+ let out = out.get("result").unwrap_or(out);
+ assert!(
+ out.get("proposal").is_some_and(|p| !p.is_null()),
+ "[{}] flows_build returned no proposal: {out}",
+ case.agent
+ );
+ }
+ Entry::TriageEvaluate => {
+ let resp = post_json_rpc(
+ &stack.rpc_base,
+ 10,
+ "openhuman.agent_triage_evaluate",
+ json!({
+ "source": "composio",
+ "toolkit": "gmail",
+ "trigger": "GMAIL_NEW_GMAIL_MESSAGE",
+ "display_label": "New Gmail message",
+ "payload": { "subject": case.user_message },
+ "dry_run": true,
+ }),
+ )
+ .await;
+ assert_no_jsonrpc_error(&resp, "agent_triage_evaluate");
+ }
+ }
+
+ let requests = captured().clone();
+ let dump = || serde_json::to_string_pretty(&requests).unwrap_or_default();
+ let agent = case.agent;
+ assert!(
+ !captured_requests_mention_unknown_tool(&requests),
+ "[{agent}] a scripted call hit `unknown tool`: {}",
+ dump()
+ );
+
+ let own: Vec<&Value> = requests
+ .iter()
+ .filter(|r| system_text(r).contains(case.agent_marker))
+ .collect();
+ let belts: Vec<Vec<String>> = requests.iter().map(advertised_tool_names).collect();
+ assert!(
+ !own.is_empty(),
+ "[{agent}] no upstream request carried the agent's prompt ({:?}); belts seen: {belts:?}",
+ case.agent_marker
+ );
+
+ for request in &own {
+ let belt = advertised_tool_names(request);
+ if case.advertises_nothing {
+ assert!(
+ belt.is_empty(),
+ "[{agent}] zero-belt agent advertised {belt:?}"
+ );
+ }
+ for tool in case.must_advertise {
+ assert!(
+ belt.iter().any(|b| b == tool),
+ "[{agent}] must advertise `{tool}`; advertised {belt:?}"
+ );
+ }
+ for tool in case.must_not_advertise {
+ assert!(
+ !belt.iter().any(|b| b == tool),
+ "[{agent}] must not advertise `{tool}`; advertised {belt:?}"
+ );
+ }
+ }
+
+ let calls = called_tools(own.last().expect("non-empty"));
+ for tool in case.must_call {
+ assert!(
+ calls.iter().any(|c| c == tool),
+ "[{agent}] must call `{tool}`; called {calls:?}"
+ );
+ tool_result_text(&requests, tool)
+ .unwrap_or_else(|| panic!("[{agent}] no tool result for `{tool}`: {}", dump()));
+ }
+ for tool in case.must_not_call {
+ assert!(
+ !calls.iter().any(|c| c == tool),
+ "[{agent}] must not call `{tool}`; called {calls:?}"
+ );
+ }
+ if let Some((tool, cap)) = case.max_consecutive_calls_of {
+ let run = max_consecutive(&calls, tool);
+ assert!(
+ run <= cap,
+ "[{agent}] {run} consecutive `{tool}` calls (cap {cap}); called {calls:?}"
+ );
+ }
+}
+
+// ─── Cases ──────────────────────────────────────────────────────────────────
+
+/// A minimal graph `propose_workflow` accepts: manual trigger → agent node.
+fn news_digest_graph() -> Value {
+ json!({
+ "schema_version": 1,
+ "name": "Daily sports news digest",
+ "nodes": [
+ { "id": "trigger", "kind": "trigger", "name": "Run manually",
+ "config": { "trigger_kind": "manual" } },
+ { "id": "digest", "kind": "agent", "name": "Summarise today's sports news",
+ "config": { "model": "chat-v1",
+ "prompt": "Summarise today's top sports news in five bullets." } }
+ ],
+ "edges": [
+ { "from_node": "trigger", "from_port": "main", "to_node": "digest", "to_port": "main" }
+ ]
+ })
+}
+
+/// The motivating incident: the builder searched the catalog 27 times and never
+/// proposed. Pinned here: the builder's belt carries both tools, two searches
+/// then a proposal resolves end to end, and a third consecutive search is a
+/// failure — so a loop in the runtime (a re-issued call, a retry that repeats
+/// the search) cannot pass as progress.
+#[test]
+fn workflow_builder_reaches_propose_workflow() {
+ run_case(Case {
+ agent: "workflow_builder",
+ agent_marker: "# Workflow Builder",
+ entry: Entry::FlowsBuild,
+ user_message: "Every morning, send me a digest of the latest sports news.",
+ scripted_completions: vec![
+ call("search_tool_catalog", json!({ "query": "news" })),
+ call(
+ "search_tool_catalog",
+ json!({ "query": "sports headlines" }),
+ ),
+ call(
+ "propose_workflow",
+ json!({ "name": "Daily sports news digest", "graph": news_digest_graph() }),
+ ),
+ text_completion("Here is a daily sports news digest workflow."),
+ ],
+ must_call: &["search_tool_catalog", "propose_workflow"],
+ must_not_call: &[],
+ must_advertise: &["search_tool_catalog", "propose_workflow"],
+ must_not_advertise: &["shell", "file_write"],
+ advertises_nothing: false,
+ max_consecutive_calls_of: Some(("search_tool_catalog", 2)),
+ extra_config: "",
+ });
+}
+
+/// The orchestrator routes integration work through the hand-off, and never
+/// holds the raw Composio or cron tools its specialists own.
+#[test]
+fn orchestrator_hands_integration_work_to_the_specialist() {
+ run_case(Case {
+ agent: "orchestrator",
+ agent_marker: "## Delegation (direct-first)",
+ entry: Entry::WebChat,
+ user_message: "Check my Gmail for anything from my landlord.",
+ scripted_completions: vec![
+ call(
+ "delegate_to_integrations_agent",
+ json!({ "toolkit": "gmail", "prompt": "Find emails from my landlord." }),
+ ),
+ text_completion("No emails from your landlord."),
+ text_completion("You have no emails from your landlord."),
+ ],
+ must_call: &["delegate_to_integrations_agent"],
+ must_not_call: &["composio_execute"],
+ must_advertise: &["delegate_to_integrations_agent", "schedule_task"],
+ must_not_advertise: &["composio_execute", "composio_list_tools", "cron_add"],
+ advertises_nothing: false,
+ max_consecutive_calls_of: None,
+ extra_config: "",
+ });
+}
+
+/// The integrations specialist, reached through that hand-off, holds the
+/// Composio execution surface and none of the orchestrator's hand-offs.
+#[test]
+fn integrations_agent_holds_the_composio_surface() {
+ run_case(Case {
+ agent: "integrations_agent",
+ agent_marker: "# Integrations Agent",
+ entry: Entry::WebChat,
+ user_message: "Check my Gmail for anything from my landlord.",
+ scripted_completions: vec![
+ call(
+ "delegate_to_integrations_agent",
+ json!({ "toolkit": "gmail", "prompt": "Find emails from my landlord." }),
+ ),
+ call("composio_list_tools", json!({ "toolkit": "gmail" })),
+ text_completion("No emails from your landlord."),
+ text_completion("You have no emails from your landlord."),
+ ],
+ must_call: &["composio_list_tools"],
+ must_not_call: &[],
+ must_advertise: &["composio_execute", "composio_list_tools"],
+ must_not_advertise: &["delegate_to_integrations_agent", "schedule_task", "shell"],
+ advertises_nothing: false,
+ max_consecutive_calls_of: None,
+ extra_config: "",
+ });
+}
+
+/// `schedule_task` lands in scheduler_agent, which owns cron and nothing else.
+#[test]
+fn scheduler_agent_owns_the_cron_surface() {
+ run_case(Case {
+ agent: "scheduler_agent",
+ agent_marker: "# Scheduler Agent",
+ entry: Entry::WebChat,
+ user_message: "What reminders do I have scheduled?",
+ scripted_completions: vec![
+ call(
+ "schedule_task",
+ json!({ "prompt": "List my scheduled reminders.", "blocking": true }),
+ ),
+ call("cron_list", json!({})),
+ text_completion("You have no scheduled reminders."),
+ text_completion("You have no scheduled reminders."),
+ ],
+ must_call: &["cron_list"],
+ must_not_call: &[],
+ must_advertise: &["cron_add", "cron_list", "cron_remove"],
+ must_not_advertise: &["composio_execute", "shell", "schedule_task"],
+ advertises_nothing: false,
+ max_consecutive_calls_of: None,
+ extra_config: "",
+ });
+}
+
+/// With the summarizer threshold at one token, any orchestrator tool result is
+/// runtime-dispatched to the summarizer, which must run with no tools at all.
+#[test]
+fn summarizer_advertises_no_tools() {
+ run_case(Case {
+ agent: "summarizer",
+ agent_marker: "# Summarizer Agent",
+ entry: Entry::WebChat,
+ user_message: "What is the state of my workspace?",
+ scripted_completions: vec![
+ call("read_workspace_state", json!({})),
+ text_completion("Workspace summary: nothing notable."),
+ text_completion("Your workspace has nothing notable."),
+ ],
+ must_call: &[],
+ must_not_call: &[],
+ must_advertise: &[],
+ must_not_advertise: &[],
+ advertises_nothing: true,
+ max_consecutive_calls_of: None,
+ extra_config: "summarizer_payload_threshold_tokens = 1",
+ });
+}
+
+/// trigger_triage classifies with a flat JSON decision and no tools.
+#[test]
+fn trigger_triage_advertises_no_tools() {
+ run_case(Case {
+ agent: "trigger_triage",
+ agent_marker: "# Trigger Triage",
+ entry: Entry::TriageEvaluate,
+ user_message: "Weekly newsletter: 10 productivity tips",
+ scripted_completions: vec![text_completion(
+ r#"{"action":"drop","target_agent":null,"prompt":null,"reason":"Routine newsletter."}"#,
+ )],
+ must_call: &[],
+ must_not_call: &[],
+ must_advertise: &[],
+ must_not_advertise: &[],
+ advertises_nothing: true,
+ max_consecutive_calls_of: None,
+ extra_config: "",
+ });
+}
+
+#[test]
+fn max_consecutive_counts_the_longest_run() {
+ let calls: Vec<String> = ["a", "b", "b", "a", "b", "b", "b"]
+ .iter()
+ .map(|s| s.to_string())
+ .collect();
+ assert_eq!(max_consecutive(&calls, "b"), 3);
+ assert_eq!(max_consecutive(&calls, "a"), 1);
+ assert_eq!(max_consecutive(&calls, "c"), 0);
+}