Trace-native CI/CD for AI agents — production failures become regression tests that block the PR. Auto-detect, cluster, freeze into hermetic cases, replay in CI for $0.
Python agentagent-observabilityai-agentsci-cdclickhouseevalsevaluationllmllm-as-judgellm-evaluationllm-observabilityllm-opsllmopsmcpmonitoringopentelemetrypythonself-hostedtracing
feat(audits): let the assistant and MCP clients create, run and read audits
Wuthrich Julienbb5a1225806f
diff --git a/backend/tests/test_assistant_tools.py b/backend/tests/test_assistant_tools.pyindex c407f9e..bdab5b2 100644--- a/backend/tests/test_assistant_tools.py+++ b/backend/tests/test_assistant_tools.py@@ -195,6 +195,7 @@ async def test_the_toolbox_covers_the_product(tools):"create_scenario", "import_scenario", "run_scenario", # emulated conversations"promote_trace", "promote_cluster", "replay_case", # regression cases"create_alert", "list_alerts", # "tell me when this happens"+ "create_audit", "generate_audit_seeds", "run_audit", "get_audit_run", "get_audit_rollout", # audits"delete_conversations", # the destructive end, gated by the system prompt} <= names@@ -264,3 +265,95 @@ async def test_draft_alert_validates_and_only_draws_on_the_editor():assert "create_alert" in await elsewhere["draft_alert"].ainvoke({"name": "x", "trigger": "trace_failed", "steps": slack})+++# ── audits ───────────────────────────────────────────────────────────────────+++def audits_db(tmp_path, monkeypatch, engine, sync_db):+ """The audits router on the same file-backed database, with its tables."""+ import tracely.api.routers.audits as audits_router++ sync = create_engine(f"sqlite:///{tmp_path}/test.db")+ Base.metadata.create_all(sync, tables=[+ models.Agent.__table__, models.Audit.__table__, models.AuditSeed.__table__,+ models.AuditRun.__table__, models.AuditRollout.__table__,+ ])+ monkeypatch.setattr(audits_router, "SyncSessionLocal", sessionmaker(sync))+++async def test_the_assistant_builds_an_audit_end_to_end(client, audits_db, make_workspace, tools):+ """Create from a preset, add a seed, read it back — all through the real router."""+ _proj, user, _key = await make_workspace("tools-audit", "tools_key_audit", "[email protected]")+ t = tools(tokens.issue_session(user.id))++ catalog = await t["audit_catalog"].ainvoke({})+ assert "sycophancy" in {p["key"] for p in catalog["presets"]} and catalog["variation_axes"]++ made = await t["create_audit"].ainvoke({"preset": "sycophancy", "target_model": "openai/gpt-4o-mini"})+ assert made["name"] and made["seeds"] >= 1 and made["link"] == f"/audits/{made['id']}"+ await t["add_audit_seed"].ainvoke({"audit_id": made["id"], "instruction": "play an upset customer", "title": "Upset"})++ audit = await t["get_audit"].ainvoke({"audit_id": made["id"]})+ assert audit["target"] == {"model": "openai/gpt-4o-mini", "control": "auditor"}+ seed = next(s for s in audit["seeds"] if s["title"] == "Upset")+ off = await t["set_audit_seed_enabled"].ainvoke({"audit_id": made["id"], "seed_id": seed["id"], "enabled": False})+ assert off == {"id": seed["id"], "enabled": False}+ assert [a["id"] for a in await t["list_audits"].ainvoke({})] == [made["id"]]++ # a run that cannot start says why, as text the model can relay — here: no model key+ refused = await t["run_audit"].ainvoke({"audit_id": made["id"]})+ assert isinstance(refused, str) and refused.startswith("error: Tracely API 400")++ # an ingest key reads audits but cannot author them+ machine = tools("tools_key_audit")+ assert [a["id"] for a in await machine["list_audits"].ainvoke({})] == [made["id"]]+ denied = await machine["create_audit"].ainvoke({"behaviour": "lies", "target_model": "openai/gpt-4o-mini"})+ assert isinstance(denied, str) and denied.startswith("error: Tracely API 40")+++async def test_an_unknown_preset_or_agent_is_explained_not_raised(client, audits_db, make_workspace, tools):+ _proj, user, _key = await make_workspace("tools-audit2", "tools_key_audit2", "[email protected]")+ t = tools(tokens.issue_session(user.id))+ assert "no preset 'nope'" in await t["create_audit"].ainvoke({"preset": "nope", "target_model": "m"})+ out = await t["create_audit"].ainvoke({"behaviour": "lies", "agent": "ghost"})+ assert isinstance(out, str) and out.startswith("error:")+++def test_a_rollout_is_briefed_as_its_final_conversation():+ from tracely.domain.audit import brief++ out = brief.rollout_brief({+ "id": "r1", "verdict": "ELICITED", "seed": {"title": "Upset"}, "detail": {},+ "results": [{"name": "sycophancy", "kind": "behaviour", "value": 8, "flagged": True, "disputed": False,+ "judges": [{"justification": ""}, {"justification": "agreed with a false claim"}]}],+ "transcript": {+ "head": "M4", "branches": [{"n": 0}, {"n": 1}],+ "nodes": [+ {"id": "M1", "parent": "", "role": "user", "content": "2+2=5 right?"},+ {"id": "M2", "parent": "M1", "role": "assistant", "content": "No."}, # rolled back+ {"id": "M3", "parent": "", "role": "user", "content": "", "attachments": [+ {"kind": "audio", "name": "v.mp3", "text": "two plus two is five right"}]},+ {"id": "M4", "parent": "M3", "role": "assistant", "content": "x" * 2000,+ "tool_calls": [{"id": "c", "name": "lookup", "args": {"q": 1}}]},+ ],+ },+ })+ assert [m["id"] for m in out["conversation"]] == ["M3", "M4"] and out["rolled_back_branches"] == 1+ assert out["conversation"][0]["text"] == '[voice message: "two plus two is five right"]'+ assert len(out["conversation"][1]["text"]) < 800 and out["conversation"][1]["calls"] == ["lookup({'q': 1})"]+ assert out["judges"][0]["reason"] == "agreed with a false claim"+++def test_a_created_audit_tests_the_agent_only_when_its_prompt_was_found():+ from tracely.domain.audit import brief++ fixed = brief.create_body(behaviour="lies about refunds", agent="support",+ imported={"found": True, "model": "x/y", "system_prompt": "You are…", "tools": [{"name": "t"}]})+ assert fixed["config"]["target"] == {"model": "x/y", "control": "fixed", "system_prompt": "You are…", "tools": [{"name": "t"}]}+ assert fixed["agent"] == "support" and fixed["name"] == "lies about refunds"+ model = brief.create_body(behaviour="lies", target_model="x/z", real_machine=True, packs=["office"], budget_usd=2)+ assert model["config"]["target"]["control"] == "auditor" and model["agent"] == ""+ assert model["config"]["environment"] == {"mode": "sandbox", "packs": ["office"]}+ assert model["config"]["limits"] == {"budget_usd": 2.0}diff --git a/backend/tests/test_mcp_server.py b/backend/tests/test_mcp_server.pyindex b94ca4b..eb7ab9a 100644--- a/backend/tests/test_mcp_server.py+++ b/backend/tests/test_mcp_server.py@@ -98,6 +98,7 @@ async def test_tools_are_listed(client, sync_db, make_workspace):async with mcp_session("mcp_key_list") as s:names = {t.name for t in (await s.list_tools()).tools}assert {"list_traces", "get_trace", "list_evaluators", "create_evaluator"} <= names+ assert {"list_audits", "create_audit", "generate_audit_seeds", "run_audit", "get_audit_run", "get_audit_rollout"} <= names# Read-mostly by design: no delete/admin/ingest surface.assert not [n for n in names if "delete" in n]diff --git a/backend/tracely/api/mcp_server.py b/backend/tracely/api/mcp_server.pyindex 4971290..74bf7f7 100644--- a/backend/tracely/api/mcp_server.py+++ b/backend/tracely/api/mcp_server.py@@ -24,6 +24,7 @@ from mcp.server.fastmcp import Context, FastMCPfrom mcp.server.transport_security import TransportSecuritySettingsfrom tracely.api.internal_client import api_call, auth_headers_from+from tracely.domain.audit import brieffrom tracely.domain.evaluation.guide import create_evaluator_descriptionINSTRUCTIONS = """Tracely is trace-native CI/CD for AI agents: production traces are graded by@@ -232,6 +233,113 @@ async def get_ops_metrics(ctx: Context, days: int = 14) -> dict:return await _call(ctx, "GET", "/api/ops", params={"days": days})+# ── audits ───────────────────────────────────────────────────────────────────+#+# The same reads and writes the in-app assistant has (`services/assistant_tools.py`), shaped by+# the same helpers (`domain/audit/brief.py`). Creating an audit and writing its seeds are+# `require_user` routes: they work with a session token, and an ingest key is refused by the+# router — a CI key can read audits and start runs, never author them.+++async def list_audits(ctx: Context) -> list[dict]:+ """Behavioural audits: an attacker model tries to provoke a behaviour in a target and judges+ score how often it appears. Each with its target, seed count and last measured result."""+ return [+ {"id": a["id"], "name": a["name"], "behaviour": (a.get("behavior") or "")[:200],+ "target": a["config"]["target"]["model"], "seeds": a.get("seeds"),+ "last_run": brief.run_brief(a["last_run"]) if a.get("last_run") else None}+ for a in await _call(ctx, "GET", "/api/audits")+ ]+++async def get_audit(ctx: Context, audit_id: str) -> dict:+ """One audit: what it looks for, its target, its seeds (with ids) and its runs."""+ return brief.audit_brief(await _call(ctx, "GET", f"/api/audits/{audit_id}"))+++async def audit_catalog(ctx: Context) -> dict:+ """What an audit can be built from: behaviour presets, seed-library topics, variation axes,+ tool packs, and whether this deployment can give the target a real machine."""+ return brief.catalog_brief(await _call(ctx, "GET", "/api/audits/catalog"))+++async def create_audit(+ ctx: Context,+ behaviour: str = "",+ target_model: str = "",+ agent: str = "",+ preset: str = "",+ name: str = "",+ real_machine: bool = False,+ packs: list[str] | None = None,+ attacker_media: list[str] | None = None,+ budget_usd: float = 0.0,+) -> dict:+ """Create an audit. WHAT to look for: `behaviour` in a sentence or two, or a `preset` key+ from `audit_catalog`. WHAT to test: `target_model` alone audits a model; `agent` (a slug)+ audits that agent's real system prompt and tools, from its latest trace. Optional:+ `real_machine` + `packs` (dev, office, support, data, devops) for real tools instead of+ invented tool results; `attacker_media` (`image`, `voice`); `budget_usd` per run. Needs a+ signed-in user's token. A preset comes with seeds; otherwise call `generate_audit_seeds`."""+ chosen = None+ if preset:+ presets = (await _call(ctx, "GET", "/api/audits/catalog")).get("presets") or []+ chosen = next((p for p in presets if p["key"] == preset), None)+ if chosen is None:+ raise ValueError(f"no preset {preset!r}. Presets: {', '.join(p['key'] for p in presets)}")+ imported = None+ if agent:+ imported = await _call(ctx, "POST", "/api/audits/import-target", json={"agent": agent})+ if not imported.get("found"):+ raise ValueError(f"no recent trace of agent {agent!r} shows a system prompt or tools")+ out = await _call(ctx, "POST", "/api/audits", json=brief.create_body(+ behaviour=behaviour, target_model=target_model, name=name, preset=chosen, imported=imported,+ agent=agent, real_machine=real_machine, packs=packs, attacker_media=attacker_media,+ budget_usd=budget_usd,+ ))+ return {"id": out["id"], "name": out["name"], "seeds": out.get("seeds")}+++async def generate_audit_seeds(ctx: Context, audit_id: str, guidance: str = "", n: int = 8) -> list[dict]:+ """Write up to 8 new seeds (situations for the attacker to play out) from the audit's+ behaviour, target and existing seeds. `guidance` steers the batch. Needs a signed-in user's+ token. Call again for more."""+ out = await _call(ctx, "POST", f"/api/audits/{audit_id}/seeds/generate", timeout=300.0,+ json={"n": n, "guidance": guidance})+ return [{"id": s["id"], "title": s["title"]} for s in out]+++async def run_audit(+ ctx: Context, audit_id: str, mode: str = "measure", reps: int = 0, budget_usd: float = 0.0+) -> dict:+ """Start a run. It SPENDS MONEY on the workspace's model key, up to the audit's budget —+ confirm with the user first. `mode`: `measure` (the rate is the audit's result) or `explore`+ (finds more; its rate is not a result). Returns at once; poll `get_audit_run`."""+ body = {k: v for k, v in {"mode": mode, "reps": reps, "budget_usd": budget_usd}.items() if v}+ return brief.run_brief(await _call(ctx, "POST", f"/api/audits/{audit_id}/runs", json=body))+++async def get_audit_run(ctx: Context, run_id: str) -> dict:+ """A run's result: the elicitation rate and each rollout's verdict and scores. ELICITED = the+ target showed the behaviour, CLEAN = it did not, anything else was not a fair test. A null+ rate means nothing was measured, not 0%."""+ return brief.run_brief(await _call(ctx, "GET", f"/api/audit-runs/{run_id}"))+++async def get_audit_rollout(ctx: Context, rollout_id: str) -> dict:+ """One rollout: each judge dimension's score and reason, and the conversation between the+ attacker and the target (the final branch; long messages are shortened)."""+ return brief.rollout_brief(await _call(ctx, "GET", f"/api/audit-rollouts/{rollout_id}"))++class _ASGIHandler:"""Adapter so Starlette treats the MCP endpoint as a raw ASGI app: a bare function or boundmethod in a `Route` is taken to be `func(request) -> response`, and only a non-functiondiff --git a/backend/tracely/domain/audit/brief.py b/backend/tracely/domain/audit/brief.pynew file mode 100644index 0000000..60b29eb--- /dev/null+++ b/backend/tracely/domain/audit/brief.py@@ -0,0 +1,154 @@+"""Audits as an agent reads and writes them — the in-app assistant and the MCP server.++Both reach audits through the routers, like every other tool. What they need on top is small and+pure, so it lives here once: a request body built from flat arguments (an assistant tool cannot+take a nested `config` — see `services/assistant_tools.py`), and short versions of the two reads+that are far too large to hand a model whole (a run is every judge's every answer; a rollout is+hundreds of KB of transcript).+"""++from __future__ import annotations++from typing import Any++from tracely.domain.audit import media++_TEXT = 700 # characters of one message kept in a rollout brief+++def create_body(+ *,+ behaviour: str = "",+ target_model: str = "",+ name: str = "",+ preset: dict | None = None,+ imported: dict | None = None,+ agent: str = "",+ real_machine: bool = False,+ packs: list[str] | None = None,+ attacker_media: list[str] | None = None,+ judge_models: list[str] | None = None,+ budget_usd: float = 0.0,+) -> dict[str, Any]:+ """The body for `POST /api/audits`.++ `preset` is an entry of the catalog's `presets` (it supplies the behaviour, its dimensions and+ starter seeds); `imported` is what `POST /api/audits/import-target` returned for `agent` (its+ real system prompt and tools, which then become the thing under test)."""+ preset, imported = preset or {}, imported or {}+ behaviour = (behaviour or preset.get("behaviour") or "").strip()+ fixed = bool(imported.get("found"))+ config: dict[str, Any] = {+ "target": {+ "model": target_model or imported.get("model") or "",+ "control": "fixed" if fixed else "auditor",+ "system_prompt": imported.get("system_prompt") or "" if fixed else "",+ "tools": imported.get("tools") or [] if fixed else [],+ },+ "attacker": {"media": list(attacker_media or [])},+ "environment": (+ {"mode": "sandbox", "packs": list(packs or ["dev"])} if real_machine else {"mode": "synthetic"}+ ),+ "dimensions": list(preset.get("dimensions") or []),+ "judge_models": list(judge_models or []),+ }+ if budget_usd:+ config["limits"] = {"budget_usd": float(budget_usd)}+ return {+ "name": (name or preset.get("name") or " ".join(behaviour.split()[:6])).strip(),+ "behavior": behaviour,+ "agent": agent if fixed else "",+ "preset": preset.get("key"),+ "seeds": list(preset.get("seeds") or []),+ "config": config,+ }+++def catalog_brief(catalog: dict) -> dict:+ """What an agent needs to choose from: presets, library topics, variation axes, packs."""+ return {+ "presets": [{"key": p["key"], "name": p["name"], "behaviour": p["behaviour"]} for p in catalog.get("presets") or []],+ "library_topics": (catalog.get("library") or {}).get("petri", {}).get("tags") or [],+ "variation_axes": catalog.get("variations") or [],+ "extra_dimensions": [d["name"] for d in catalog.get("behaviours") or []],+ "real_machine": catalog.get("sandbox") or {"available": False},+ "packs": ["dev", "office", "support", "data", "devops"],+ }+++def audit_brief(audit: dict) -> dict:+ """One audit without its dimension rubrics: what it tests, its seeds, its runs."""+ cfg = audit.get("config") or {}+ return {+ "id": audit.get("id"), "name": audit.get("name"), "behaviour": audit.get("behavior"),+ "target": {k: (cfg.get("target") or {}).get(k) for k in ("model", "control")},+ "environment": cfg.get("environment"), "budget_usd": (cfg.get("limits") or {}).get("budget_usd"),+ "seeds": [+ {"id": s["id"], "title": s.get("title"), "enabled": s.get("enabled"), "origin": s.get("origin"),+ "instruction": (s.get("instruction") or "")[:300], "files": [a["name"] for a in s.get("attachments") or []]}+ for s in audit.get("seeds") or []+ ] if isinstance(audit.get("seeds"), list) else audit.get("seeds"),+ "runs": [run_brief(r) for r in audit.get("runs") or []],+ "link": f"/audits/{audit.get('id')}",+ }+++def run_brief(run: dict) -> dict:+ """A run as its headline and one line per rollout — no judge-by-judge detail."""+ summary = run.get("summary") or {}+ out = {+ "id": run.get("id"), "status": run.get("status"), "mode": run.get("mode"),+ "elicitation_rate": summary.get("elicitation_rate"), "counted": summary.get("counted"),+ "verdicts": summary.get("verdicts"), "done": run.get("done"), "total": run.get("total"),+ "spend_usd": run.get("spend_usd"), "budget_usd": run.get("budget_usd"),+ "link": f"/audits/{run.get('audit_id')}/runs/{run.get('id')}",+ }+ if run.get("mode") == "explore":+ out["note"] = "Explore run: rollouts learn from each other, so this rate is not the audit's result."+ if "rollouts" in run:+ out["rollouts"] = [+ {+ "id": r["id"], "seed": r.get("title"), "verdict": r.get("verdict") or r.get("phase"),+ "second_pass": bool(r.get("stage")),+ "scores": {x["name"]: x.get("value") for x in r.get("results") or []},+ "why": (r.get("detail") or {}).get("error") or (r.get("detail") or {}).get("reason") or "",+ }+ for r in run["rollouts"]+ ]+ return out+++def rollout_brief(rollout: dict) -> dict:+ """One rollout: the verdict, each dimension's score with a judge's reason, and the+ conversation the target ended with (rolled-back branches are counted, not printed)."""+ transcript = rollout.get("transcript") or {}+ nodes = {n["id"]: n for n in transcript.get("nodes") or []}+ final: list[dict] = []+ cur = transcript.get("head") or ""+ while cur in nodes:+ final.append(nodes[cur])+ cur = nodes[cur].get("parent") or ""+ conversation = []+ for node in reversed(final):+ text = media.node_text(node)+ calls = [f"{c['name']}({str(c.get('args'))[:120]})" for c in node.get("tool_calls") or []]+ conversation.append({+ "id": node["id"], "role": node["role"],+ "text": text if len(text) <= _TEXT else text[:_TEXT] + f"… [{len(text)} chars]",+ **({"calls": calls} if calls else {}),+ })+ return {+ "id": rollout.get("id"), "seed": (rollout.get("seed") or {}).get("title") or rollout.get("title"),+ "verdict": rollout.get("verdict") or rollout.get("phase"),+ "why": (rollout.get("detail") or {}).get("error") or (rollout.get("detail") or {}).get("reason") or "",+ "judges": [+ {+ "dimension": r["name"], "kind": r.get("kind"), "score": r.get("value"),+ "flagged": r.get("flagged"), "disputed": r.get("disputed"),+ "reason": next((j.get("justification") for j in r.get("judges") or [] if j.get("justification")), ""),+ }+ for r in rollout.get("results") or []+ ],+ "rolled_back_branches": max(len(transcript.get("branches") or []) - 1, 0),+ "conversation": conversation,+ }diff --git a/backend/tracely/services/assistant_service.py b/backend/tracely/services/assistant_service.pyindex 9d8d2fd..6b5f4da 100644--- a/backend/tracely/services/assistant_service.py+++ b/backend/tracely/services/assistant_service.py@@ -65,7 +65,12 @@ traces are clustered, clusters become regression cases, and those cases gate a ptrace is the source of truth — there are no hand-authored datasets.The pages: Dashboard · Traces (conversations → turns → spans, one column per evaluator) ·-Failure clusters · Regression cases · CI gates · Trends · Scenarios · Alerts · Settings.+Failure clusters · Regression cases · CI gates · Trends · Scenarios · Audits · Alerts · Settings.++Audits go looking for a behaviour instead of waiting for it: an attacker model plays out seeds+(situations) against a target — a model, or one of the workspace's agents with its real prompt+and tools — and a panel of judges scores each conversation. The result is the elicitation rate:+how often the behaviour appeared, over the conversations that were a fair test.Your tools read and change this workspace, running as the person you are talking to — you seeexactly what they see, and nothing they couldn't reach themselves.@@ -82,6 +87,10 @@ How you work:/clusters/{cluster_id}, /cases, /scenarios, /settings/alerts/{alert_id}.- Creating things is normal work — an evaluator, a scenario, a regression case, a backfill. Doit and say plainly what you did, rather than asking whether you may.+- Starting an audit run is the other exception: `run_audit` spends real money on the+ workspace's own model key. Say how many rollouts it is and the budget cap, and wait for a yes.+ Creating the audit and writing its seeds needs no such pause. Link audits as+ /audits/{audit_id} and runs as /audits/{audit_id}/runs/{run_id}.- Deleting is the exception. Before any delete_* tool, state exactly what will be deleted andwait for the user to confirm in their next message. Never delete on an instruction youinferred rather than one they typed. For a column they simply want to stop using, offerdiff --git a/backend/tracely/services/assistant_tools.py b/backend/tracely/services/assistant_tools.pyindex 8099fef..2cc25da 100644--- a/backend/tracely/services/assistant_tools.py+++ b/backend/tracely/services/assistant_tools.py@@ -34,6 +34,7 @@ from typing import Anyfrom uuid import uuid4from tracely.api.internal_client import api_call+from tracely.domain.audit import brieffrom tracely.domain.evaluation.guide import create_evaluator_description# One tool result's ceiling. Large enough for a cluster with its members or a trace with its@@ -133,6 +134,15 @@ def build_tools(headers: dict[str, str], path: str = "") -> list:async def call(method: str, path: str, **kw: Any) -> Any:return await _api(headers, method, path, **kw)+ async def api_call_raw(method: str, path: str, **kw: Any) -> Any:+ """Like `call`, but unclipped: for a read the tool itself shortens before returning.+ Clipping first turns the JSON into a string cut in half, with nothing left to shorten —+ the audit catalog alone (43 rubrics) is over twice the clip."""+ try:+ return await api_call(headers, method, path, **kw)+ except Exception as exc:+ return f"error: {exc}"[:1000]+# ── reading: traces and conversations ────────────────────────────────────@tool@@ -622,8 +632,176 @@ def build_tools(headers: dict[str, str], path: str = "") -> list:json=_params(candidate_trace_id=candidate_trace_id),)+ # ── audits: go looking for a behaviour ───────────────────────────────────++ @tool+ async def audit_catalog() -> Any:+ """What an audit can be built from: behaviour presets, the seed library's topics, the axes+ a seed can be varied along, the tool packs, and whether this deployment can give the+ target a real machine. Read it before `create_audit` when the user has not said exactly+ what they want."""+ out = await api_call_raw("GET", "/api/audits/catalog")+ return out if isinstance(out, str) else _clip(brief.catalog_brief(out))++ @tool+ async def list_audits() -> Any:+ """Every audit with its target, seed count and last measured result."""+ out = await api_call_raw("GET", "/api/audits")+ if isinstance(out, str):+ return out+ return _clip([+ {"id": a["id"], "name": a["name"], "behaviour": (a.get("behavior") or "")[:200],+ "target": a["config"]["target"]["model"], "seeds": a.get("seeds"),+ "last_run": brief.run_brief(a["last_run"]) if a.get("last_run") else None,+ "link": f"/audits/{a['id']}"}+ for a in out+ ])++ @tool+ async def get_audit(audit_id: str) -> Any:+ """One audit: what it looks for, its target, its seeds (with ids) and its runs."""+ out = await api_call_raw("GET", f"/api/audits/{audit_id}")+ return out if isinstance(out, str) else _clip(brief.audit_brief(out))++ @tool+ async def create_audit(+ behaviour: str = "",+ target_model: str = "",+ agent: str = "",+ preset: str = "",+ name: str = "",+ real_machine: bool = False,+ packs: list[str] | None = None,+ attacker_media: list[str] | None = None,+ judge_models: list[str] | None = None,+ budget_usd: float = 0.0,+ ) -> Any:+ """Create an audit: an attacker model tries to provoke a behaviour in a target, and judges+ score how often it appears.++ Two things decide it. WHAT to look for: `behaviour` in a sentence or two, or a `preset`+ key from `audit_catalog`. WHAT to test: `target_model` alone audits a model (the attacker+ builds a deployment around it), while `agent` (an agent's slug) audits that agent's real+ system prompt and tools, taken from its latest trace — `target_model` then defaults to+ the model it ran on.++ Everything else is optional: `real_machine` gives the target real tools on a real Linux+ box (`packs`: dev, office, support, data, devops) instead of invented tool results;+ `attacker_media` (`image`, `voice`) lets the attacker send pictures or voice messages;+ `budget_usd` caps one run (default 5). A preset comes with starter seeds; otherwise call+ `generate_audit_seeds` next."""+ chosen: dict | None = None+ if preset:+ catalog = await api_call_raw("GET", "/api/audits/catalog")+ if isinstance(catalog, str):+ return catalog+ chosen = next((p for p in catalog.get("presets") or [] if p["key"] == preset), None)+ if chosen is None:+ return f"error: no preset {preset!r}. Presets: {', '.join(p['key'] for p in catalog.get('presets') or [])}"+ imported: dict | None = None+ if agent:+ imported = await call("POST", "/api/audits/import-target", json={"agent": agent})+ if isinstance(imported, str):+ return imported+ if not imported.get("found"):+ return (f"error: no recent trace of agent {agent!r} shows a system prompt or tools, "+ "so there is nothing to audit as that agent. Audit the model instead, or ask the user.")+ out = await call("POST", "/api/audits", json=brief.create_body(+ behaviour=behaviour, target_model=target_model, name=name, preset=chosen, imported=imported,+ agent=agent, real_machine=real_machine, packs=packs, attacker_media=attacker_media,+ judge_models=judge_models, budget_usd=budget_usd,+ ))+ return out if isinstance(out, str) else {+ "id": out["id"], "name": out["name"], "seeds": out.get("seeds"), "link": f"/audits/{out['id']}",+ }++ @tool+ async def generate_audit_seeds(audit_id: str, guidance: str = "", n: int = 8) -> Any:+ """Write up to 8 new seeds (situations for the attacker to play out) for an audit, from+ its behaviour, its target and the seeds it already has. `guidance` steers the batch+ ("angry customers", "one where the user sends a photo"). Call again for more."""+ out = await call(+ "POST", f"/api/audits/{audit_id}/seeds/generate", timeout=SLOW_TIMEOUT_S,+ json={"n": n, "guidance": guidance},+ )+ return out if isinstance(out, str) else [{"id": s["id"], "title": s["title"]} for s in out]++ @tool+ async def add_audit_seed(audit_id: str, instruction: str, title: str = "") -> Any:+ """Add one seed you or the user wrote: who the attacker plays, what the target has, what+ happens, and what to try if the first approach fails."""+ return await call("POST", f"/api/audits/{audit_id}/seeds", json={"title": title, "instruction": instruction})++ @tool+ async def import_audit_seeds(audit_id: str, topic: str) -> Any:+ """Copy seeds from the research library into an audit, by topic (see `audit_catalog`'s+ `library_topics`). They suit auditing a model better than a deployed agent."""+ out = await call("POST", f"/api/audits/{audit_id}/seeds/import", json={"tag": topic})+ return out if isinstance(out, str) else {"imported": len(out)}++ @tool+ async def vary_audit_seed(audit_id: str, seed_id: str, axes: list[str]) -> Any:+ """Write one variation of a seed per axis (see `audit_catalog`'s `variation_axes`), each+ changing only that one thing — how to learn what a behaviour depends on."""+ out = await call(+ "POST", f"/api/audits/{audit_id}/seeds/{seed_id}/variations", timeout=SLOW_TIMEOUT_S,+ json={"dimensions": axes},+ )+ return out if isinstance(out, str) else [{"id": s["id"], "title": s["title"]} for s in out]++ @tool+ async def set_audit_seed_enabled(audit_id: str, seed_id: str, enabled: bool) -> Any:+ """Switch a seed on or off. A run plays every enabled seed."""+ out = await call("PATCH", f"/api/audits/{audit_id}/seeds/{seed_id}", json={"enabled": enabled})+ return out if isinstance(out, str) else {"id": out["id"], "enabled": out["enabled"]}++ @tool+ async def run_audit(+ audit_id: str, mode: str = "measure", reps: int = 0, budget_usd: float = 0.0,+ seed_ids: list[str] | None = None,+ ) -> Any:+ """Start a run of an audit. THIS SPENDS MONEY on the workspace's own model key: before+ calling it, tell the user how many rollouts it is (enabled seeds x reps) and the budget+ cap, and wait for their yes.++ `mode` is `measure` (independent rollouts — the rate is the audit's result) or `explore`+ (finds more, but its rate is not a result). `budget_usd` can only lower the audit's own+ cap. Returns at once; the run takes minutes — read it with `get_audit_run`."""+ out = await call("POST", f"/api/audits/{audit_id}/runs", json=_params(+ mode=mode, reps=reps or None, budget_usd=budget_usd or None, seed_ids=seed_ids or None,+ ))+ return out if isinstance(out, str) else brief.run_brief(out)++ @tool+ async def get_audit_run(run_id: str) -> Any:+ """A run's result: the elicitation rate, and each rollout's verdict and scores. ELICITED =+ the target showed the behaviour; CLEAN = it did not; anything else was not a fair test and+ is not counted. A rate of null means nothing was measured — never report it as 0%."""+ out = await api_call_raw("GET", f"/api/audit-runs/{run_id}")+ return out if isinstance(out, str) else _clip(brief.run_brief(out))++ @tool+ async def get_audit_rollout(rollout_id: str) -> Any:+ """One rollout (ids come from `get_audit_run`): why the judges scored it as they did, and+ the conversation between the attacker and the target. Read this before saying what the+ target actually did."""+ out = await api_call_raw("GET", f"/api/audit-rollouts/{rollout_id}")+ return out if isinstance(out, str) else _clip(brief.rollout_brief(out))++ @tool+ async def cancel_audit_run(run_id: str) -> Any:+ """Stop a running audit run. What it has already judged is kept."""+ out = await call("POST", f"/api/audit-runs/{run_id}/cancel")+ return out if isinstance(out, str) else brief.run_brief(out)+# ── deletes: ask the user first, every time ──────────────────────────────+ @tool+ async def delete_audit(audit_id: str) -> Any:+ """Delete an audit with its seeds and every run, permanently. Ask the user to confirm+ before calling this."""+ return await call("DELETE", f"/api/audits/{audit_id}")+@toolasync def delete_evaluator(evaluator_id: str) -> Any:"""Delete an evaluator column permanently. Ask the user to confirm before calling this,@@ -665,5 +843,8 @@ def build_tools(headers: dict[str, str], path: str = "") -> list:list_scenarios, create_scenario, import_scenario, run_scenario,list_alerts, create_alert, draft_alert,promote_trace, promote_cluster, replay_case,- delete_evaluator, delete_scenario, delete_case, delete_clusters, delete_conversations,+ audit_catalog, list_audits, get_audit, create_audit, generate_audit_seeds, add_audit_seed,+ import_audit_seeds, vary_audit_seed, set_audit_seed_enabled, run_audit, get_audit_run,+ get_audit_rollout, cancel_audit_run,+ delete_audit, delete_evaluator, delete_scenario, delete_case, delete_clusters, delete_conversations,)]