Skip to content

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.

feat: add max score drop feature to scenario gates

Wuthrich Julien2962e1bf5dbf
diff --git a/.github/actions/tracely-gate/action.yml b/.github/actions/tracely-gate/action.yml
index cfcacbf..d990b14 100644
--- a/.github/actions/tracely-gate/action.yml
+++ b/.github/actions/tracely-gate/action.yml
@@ -30,6 +30,13 @@ inputs:
suites, which land some probes by design.
required: false
default: ""
+ max-score-drop:
+ description: >
+ simulate only. Fail when any evaluator's mean score falls at least this much (0-1, e.g. 0.1)
+ vs the last green gate on the same scenarios, even if every conversation passed. Empty =
+ a drop is only a warning.
+ required: false
+ default: ""
timeout:
description: "simulate only. Seconds to wait for the run. Timing out fails the job, never passes it."
required: false
@@ -78,6 +85,7 @@ runs:
AGENT: ${{ inputs.agent }}
GATE_ENV: ${{ inputs.env }}
MIN_PASS_RATE: ${{ inputs.min-pass-rate }}
+ MAX_SCORE_DROP: ${{ inputs.max-score-drop }}
TIMEOUT: ${{ inputs.timeout }}
# The identity of THIS workflow attempt. `mode=gate` pairs candidates to traces stamped
# with it, so an older trace with the same input can never satisfy this run. Export the
@@ -105,6 +113,9 @@ runs:
if [ -n "$MIN_PASS_RATE" ]; then
args+=(--min-pass-rate "$MIN_PASS_RATE")
fi
+ if [ -n "$MAX_SCORE_DROP" ]; then
+ args+=(--max-score-drop "$MAX_SCORE_DROP")
+ fi
tracely simulate "${args[@]}"
elif [ "$MODE" = "gate" ]; then
if [ -z "$AGENT" ]; then
diff --git a/backend/tests/test_cluster_versions.py b/backend/tests/test_cluster_versions.py
new file mode 100644
index 0000000..cadbf74
--- /dev/null
+++ b/backend/tests/test_cluster_versions.py
@@ -0,0 +1,44 @@
+"""Version attribution for a failure cluster (`domain.failure.versions.introduced_in`)."""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+
+from tracely.api.routers.clusters import _versions
+from tracely.domain.failure.versions import VersionRow, introduced_in
+
+T0 = datetime(2026, 9, 1)
+
+
+def _row(v: str, runs: int, members: int, day: int) -> VersionRow:
+ return VersionRow(v, runs, members, T0 + timedelta(days=day))
+
+
+def test_first_failing_version_after_clean_traffic_is_blamed():
+ rows = [_row("v3", 280, 41, 10), _row("v2", 340, 0, 0)] # input order must not matter
+ assert introduced_in(rows) == "v3"
+
+
+def test_present_since_the_first_version_is_not_attributed():
+ assert introduced_in([_row("v1", 300, 5, 0), _row("v2", 300, 9, 5)]) is None
+
+
+def test_too_little_clean_traffic_is_not_attributed():
+ assert introduced_in([_row("v1", 3, 0, 0), _row("v2", 300, 9, 5)]) is None
+
+
+def test_unversioned_runs_are_ignored():
+ assert introduced_in([_row("", 500, 0, 0), _row("v1", 10, 2, 1)]) is None
+
+
+def test_router_block_uses_labels_and_orders_oldest_first():
+ out = _versions(
+ [
+ {"version_id": "id3", "runs": 280, "members": 41, "first_seen": T0 + timedelta(days=9)},
+ {"version_id": "id2", "runs": 340, "members": 0, "first_seen": T0},
+ {"version_id": "", "runs": 4, "members": 0, "first_seen": T0},
+ ],
+ {"id2": "v2", "id3": "v3"},
+ )
+ assert out["introduced_in"] == "v3"
+ assert [r["version"] for r in out["rows"]] == ["v2", None, "v3"]
diff --git a/backend/tests/test_gate_score_drop.py b/backend/tests/test_gate_score_drop.py
new file mode 100644
index 0000000..b347d5a
--- /dev/null
+++ b/backend/tests/test_gate_score_drop.py
@@ -0,0 +1,79 @@
+"""Score drops between scenario gates: a run that passes can still be worse than the last one.
+
+Pure-function cases for `domain.gate.score_drop`, plus the service path through
+`GateService.grade_scenarios` on the same in-memory harness as `test_scenario_hardening`.
+"""
+
+from __future__ import annotations
+
+from tracely.config import settings
+from tracely.domain.gate.score_drop import score_drops
+from tracely.infrastructure.db import models
+
+from tests.test_scenario_hardening import PROJECT, _Reader, _svc, db # noqa: F401 (fixture)
+
+
+def test_drop_past_threshold_is_reported():
+ (d,) = score_drops({"s1": {"goal": [0.5]}}, {"s1": {"goal": [0.9]}}, 0.1)
+ assert d.name == "goal" and round(d.delta, 2) == -0.4 and d.scenarios == 1
+ assert "goal -0.40 vs last green gate (0.90→0.50, 1 scenario)" == d.message()
+
+
+def test_small_drop_and_improvement_are_not():
+ assert score_drops({"s1": {"g": [0.85]}}, {"s1": {"g": [0.9]}}, 0.1) == []
+ assert score_drops({"s1": {"g": [1.0]}}, {"s1": {"g": [0.2]}}, 0.1) == []
+
+
+def test_only_shared_scenarios_are_compared():
+ # s2 only ran this time with a low score: a different subset is not a regression.
+ cur = {"s1": {"g": [0.9]}, "s2": {"g": [0.1]}}
+ assert score_drops(cur, {"s1": {"g": [0.9]}}, 0.1) == []
+
+
+def test_non_unit_scale_and_excluded_names_are_skipped():
+ cur = {"s1": {"latency": [900.0], "adv": [0.0]}}
+ base = {"s1": {"latency": [100.0], "adv": [1.0]}}
+ assert score_drops(cur, base, 0.1, exclude=["adv"]) == []
+
+
+def _gate(db, gid, status, trace_ids, created): # noqa: F811
+ db.add(models.GateRun(
+ id=gid, project_id=PROJECT, agent_id="a1", env="ci", status=status,
+ passed=0, failed=0, skipped=0, total=1, created_at=created,
+ ))
+ db.add(models.GateCase(
+ id=f"gc-{gid}", gate_run_id=gid, scenario_id="sc1", candidate_trace_id=f"c-{gid}",
+ verdict="PASS" if status == "PASS" else "PENDING", detail={"trace_ids": trace_ids},
+ ))
+ db.commit()
+
+
+def _run(db, monkeypatch, max_score_drop): # noqa: F811
+ from datetime import datetime, timedelta, timezone
+
+ monkeypatch.setattr(settings, "gate_scenario_span_grace_s", 0)
+ db.add(models.Scenario(id="sc1", project_id=PROJECT, agent_id="a1", title="s", kind="SCRIPTED", turns=[]))
+ now = datetime.now(timezone.utc)
+ _gate(db, "old", "PASS", ["t-old"], now - timedelta(days=1))
+ _gate(db, "new", "RUNNING", ["t-new"], now)
+ reader = _Reader(scores={
+ "t-old": [{"name": "goal", "verdict": "PASS", "value": 0.9}],
+ "t-new": [{"name": "goal", "verdict": "PASS", "value": 0.6}],
+ })
+ return _svc(db, reader=reader).grade_scenarios("new", max_score_drop=max_score_drop)
+
+
+def test_passing_gate_with_a_score_drop_warns(db, monkeypatch): # noqa: F811
+ gate = _run(db, monkeypatch, None)
+ assert gate.status == "PASS"
+ assert any(w.startswith("score drop: goal -0.30") for w in gate.warnings)
+
+
+def test_max_score_drop_makes_it_block(db, monkeypatch): # noqa: F811
+ gate = _run(db, monkeypatch, 0.2)
+ assert gate.status == "FAIL"
+
+
+def test_drop_below_max_score_drop_still_passes(db, monkeypatch): # noqa: F811
+ gate = _run(db, monkeypatch, 0.5)
+ assert gate.status == "PASS" and gate.warnings
diff --git a/backend/tracely/api/routers/clusters.py b/backend/tracely/api/routers/clusters.py
index a37a0a8..4b89e63 100644
--- a/backend/tracely/api/routers/clusters.py
+++ b/backend/tracely/api/routers/clusters.py
@@ -20,6 +20,7 @@ from tracely.api.auth import get_project_id, require_user
from tracely.config import settings
from tracely.domain.evaluation.evaluator_suggestion import suggest_evaluator
from tracely.domain.failure.histogram import histogram
+from tracely.domain.failure.versions import VersionRow, introduced_in
from tracely.infrastructure.clickhouse.trace_reader import TraceReader
from tracely.infrastructure.db import repositories as repo
from tracely.infrastructure.db.engine import SyncSessionLocal
@@ -104,6 +105,25 @@ async def list_clusters(
return await run_in_threadpool(work)
+def _versions(rows: list[dict], labels: dict[str, str]) -> dict[str, Any]:
+ """The cluster's "by agent version" block: runs vs failures per release, oldest first, and
+ the version that introduced it when the evidence supports naming one."""
+ vrows = [VersionRow(**r) for r in rows]
+ blamed = introduced_in(vrows)
+ return {
+ "introduced_in": labels.get(blamed, blamed) if blamed else None,
+ "rows": [
+ {
+ "version": labels.get(r.version_id, r.version_id) if r.version_id else None,
+ "runs": r.runs,
+ "members": r.members,
+ "first_seen": r.first_seen.isoformat() if r.first_seen else None,
+ }
+ for r in sorted(vrows, key=lambda r: r.first_seen)
+ ],
+ }
+
+
@router.get("/clusters/{cluster_id}")
async def get_cluster(
cluster_id: str, project_id: str = Depends(get_project_id), members: int = 25
@@ -161,6 +181,10 @@ async def get_cluster(
d["member_total"] = len(all_ids)
d["histogram"] = histogram(reader.member_timestamps(project_id, all_ids))
d["suggested_evaluator"] = suggest_evaluator(cl.label, cl.taxonomy)
+ d["versions"] = _versions(
+ reader.version_breakdown(project_id, cl.agent_id, all_ids),
+ repo.agent_version_labels(s, cl.agent_id),
+ )
return d
res = await run_in_threadpool(work)
diff --git a/backend/tracely/api/routers/gate.py b/backend/tracely/api/routers/gate.py
index 1a09f4a..7b2b7c8 100644
--- a/backend/tracely/api/routers/gate.py
+++ b/backend/tracely/api/routers/gate.py
@@ -77,6 +77,20 @@ def _ids(body: dict, key: str) -> list[str] | None:
return [str(x) for x in v]
+def _unit_float(body: dict, key: str) -> float | None:
+ """An optional 0..1 knob (`min_pass_rate`, `max_score_drop`); 400 on anything else."""
+ v = body.get(key)
+ if v is None:
+ return None
+ try:
+ v = float(v)
+ except (TypeError, ValueError):
+ raise HTTPException(status_code=400, detail=f"{key} must be a number") from None
+ if not 0.0 <= v <= 1.0:
+ raise HTTPException(status_code=400, detail=f"{key} must be between 0 and 1")
+ return v
+
+
@router.post("/gate")
async def run_gate(
project_id: str = Depends(get_project_id), body: dict = Body(default={})
@@ -131,14 +145,8 @@ async def run_simulated_gate(
raise HTTPException(status_code=400, detail="agent required")
case_ids = _ids(body, "case_ids")
scenario_ids = _ids(body, "scenario_ids")
- min_pass_rate = body.get("min_pass_rate")
- if min_pass_rate is not None:
- try:
- min_pass_rate = float(min_pass_rate)
- except (TypeError, ValueError):
- raise HTTPException(status_code=400, detail="min_pass_rate must be a number") from None
- if not 0.0 <= min_pass_rate <= 1.0:
- raise HTTPException(status_code=400, detail="min_pass_rate must be between 0 and 1")
+ min_pass_rate = _unit_float(body, "min_pass_rate")
+ max_score_drop = _unit_float(body, "max_score_drop")
def work():
with SyncSessionLocal() as s:
@@ -161,7 +169,7 @@ async def run_simulated_gate(
gate_id, aid, env, git_ref, pr_number = payload
run_scenario_gate_task.delay(
project_id, aid, gate_id, env, git_ref, pr_number, min_pass_rate,
- case_ids, scenario_ids,
+ case_ids, scenario_ids, max_score_drop,
)
return {"id": gate_id, "status": "RUNNING", "agent": agent_ref, "env": env}
diff --git a/backend/tracely/config.py b/backend/tracely/config.py
index 2b87aca..bb5b437 100644
--- a/backend/tracely/config.py
+++ b/backend/tracely/config.py
@@ -244,6 +244,10 @@ class Settings(BaseSettings):
gate_latency_warn_pct: float = 25.0
gate_tokens_warn_pct: float = 25.0
gate_block_on_warnings: bool = False
+ # Scenario gates: an evaluator whose mean score fell at least this much (absolute, 0..1 scale)
+ # vs the last green gate's conversations raises a soft warning. CI makes it blocking per run
+ # with `tracely simulate --max-score-drop` — a per-pipeline choice, not a server-wide one.
+ gate_score_drop_warn: float = 0.1
# Coverage policy. A gate that exercised NONE of its promoted cases (every case SKIPped
# because CI emitted no matching trace) is ALWAYS treated as a non-PASS `NO_COVERAGE` —
# a green gate that tested nothing is the worst failure mode for a merge-blocker. When this
diff --git a/backend/tracely/domain/failure/versions.py b/backend/tracely/domain/failure/versions.py
new file mode 100644
index 0000000..d6fcc37
--- /dev/null
+++ b/backend/tracely/domain/failure/versions.py
@@ -0,0 +1,35 @@
+"""Which agent version introduced a failure mode — pure, no I/O.
+
+Input is, per agent version, how many production runs it served and how many of those landed in
+the cluster. A version is blamed only when the versions BEFORE it served real traffic and never
+failed this way: "0 of 340 runs on v2, 41 of 280 on v3" says v3 introduced it. A failure that is
+present from the first version we ever saw — or whose earlier versions barely ran — has no
+attributable version, and saying one would send someone bisecting the wrong change.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import datetime
+
+# Clean runs on earlier versions needed before the first failing version gets the blame.
+MIN_CLEAN_RUNS = 20
+
+
+@dataclass(frozen=True)
+class VersionRow:
+ version_id: str # "" = runs that carried no `tracely.agent.version`
+ runs: int
+ members: int
+ first_seen: datetime
+
+
+def introduced_in(rows: Sequence[VersionRow], min_clean_runs: int = MIN_CLEAN_RUNS) -> str | None:
+ """The version id that introduced this failure, or None when it can't be attributed."""
+ clean = 0
+ for r in sorted((r for r in rows if r.version_id), key=lambda r: r.first_seen):
+ if r.members:
+ return r.version_id if clean >= min_clean_runs else None
+ clean += r.runs
+ return None
diff --git a/backend/tracely/domain/gate/score_drop.py b/backend/tracely/domain/gate/score_drop.py
new file mode 100644
index 0000000..897ff60
--- /dev/null
+++ b/backend/tracely/domain/gate/score_drop.py
@@ -0,0 +1,76 @@
+"""Evaluator score drops between two gate runs — pure, no I/O.
+
+A scenario gate that passes can still be worse than the last one: every conversation clears its
+bar while the goal-completion judge slides from 0.9 to 0.6. Verdicts can't see that; means can.
+
+Compared PER SCENARIO, then averaged over the scenarios both runs drove. Pooling all scores per
+run instead would turn "this PR ran a different subset" into a fake regression (or hide a real
+one). Only evaluators whose every value sits in [0, 1] are compared — a latency check scored in
+milliseconds has no meaningful absolute "drop" on the same scale as a judge's 0.8.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+
+# Per scenario id → per score name → raw values (one per graded turn / conversation).
+ScoreTable = Mapping[str, Mapping[str, Sequence[float]]]
+
+_EPS = 1e-9
+
+
+@dataclass(frozen=True)
+class ScoreDrop:
+ name: str
+ baseline: float
+ current: float
+ scenarios: int
+
+ @property
+ def delta(self) -> float:
+ return self.current - self.baseline
+
+ def message(self) -> str:
+ n = self.scenarios
+ return (
+ f"{self.name} {self.delta:+.2f} vs last green gate "
+ f"({self.baseline:.2f}→{self.current:.2f}, {n} scenario{'s' if n != 1 else ''})"
+ )
+
+
+def _mean(xs: Sequence[float]) -> float:
+ return sum(xs) / len(xs)
+
+
+def score_drops(
+ current: ScoreTable,
+ baseline: ScoreTable,
+ threshold: float,
+ exclude: Sequence[str] = (),
+) -> list[ScoreDrop]:
+ """Evaluators whose mean fell by at least `threshold` (absolute) vs `baseline`, worst first."""
+ skip = set(exclude)
+ per_name: dict[str, list[tuple[float, float]]] = {}
+ unit_scale: dict[str, bool] = {}
+ for sid, cur_scores in current.items():
+ base_scores = baseline.get(sid)
+ if not base_scores:
+ continue
+ for name, cur_vals in cur_scores.items():
+ base_vals = base_scores.get(name)
+ if name in skip or not cur_vals or not base_vals:
+ continue
+ in_unit = all(0.0 <= v <= 1.0 for v in (*cur_vals, *base_vals))
+ unit_scale[name] = unit_scale.get(name, True) and in_unit
+ per_name.setdefault(name, []).append((_mean(base_vals), _mean(cur_vals)))
+
+ drops = []
+ for name, pairs in per_name.items():
+ if not unit_scale[name]:
+ continue
+ base = _mean([b for b, _ in pairs])
+ cur = _mean([c for _, c in pairs])
+ if base - cur >= threshold - _EPS:
+ drops.append(ScoreDrop(name, base, cur, len(pairs)))
+ return sorted(drops, key=lambda d: d.delta)
diff --git a/backend/tracely/infrastructure/clickhouse/trace_reader.py b/backend/tracely/infrastructure/clickhouse/trace_reader.py
index 20d6514..ff94902 100644
--- a/backend/tracely/infrastructure/clickhouse/trace_reader.py
+++ b/backend/tracely/infrastructure/clickhouse/trace_reader.py
@@ -271,6 +271,33 @@ class TraceReader:
).result_rows
return [r[0] for r in rows]
+ def version_breakdown(
+ self, project_id: str, agent_id: str, member_ids: Iterable[str]
+ ) -> list[dict[str, Any]]:
+ """Per agent version: production runs it served, how many of those are `member_ids`, and
+ when the version was first seen — what attributes a failure cluster to a release.
+
+ One row per trace first (a version is stamped on the agent span only, so `anyIf` picks it
+ from whichever span carries it), then per version. `ci` and Tracely's own internal runs are
+ left out: a replay of an old case on a new version is not that version's traffic.
+ ponytail: scans the agent's whole retained history per call; cache or pre-aggregate if
+ cluster detail ever shows up in the query log."""
+ members = sorted({t for t in member_ids if t})
+ rows = self.client.query(
+ "SELECT v, count() AS runs, countIf(trace_id IN {m:Array(String)}) AS hits, "
+ "min(ts) AS first_seen "
+ "FROM (SELECT trace_id, anyIf(agent_version_id, agent_version_id != '') AS v, "
+ " min(start_time) AS ts FROM events FINAL "
+ " WHERE project_id = {p:String} AND agent_id = {ag:String} AND env != 'ci' "
+ " AND internal_kind = '' AND is_deleted = 0 GROUP BY trace_id) "
+ "GROUP BY v",
+ parameters={"p": project_id, "ag": agent_id, "m": members},
+ ).result_rows
+ return [
+ {"version_id": v, "runs": int(runs), "members": int(hits), "first_seen": first}
+ for v, runs, hits, first in rows
+ ]
+
def member_meta(
self, project_id: str, trace_ids: Iterable[str]
) -> dict[str, dict[str, Any]]:
diff --git a/backend/tracely/infrastructure/db/repositories.py b/backend/tracely/infrastructure/db/repositories.py
index fc51043..a396ca2 100644
--- a/backend/tracely/infrastructure/db/repositories.py
+++ b/backend/tracely/infrastructure/db/repositories.py
@@ -715,6 +715,13 @@ def clusters_count(
return int(s.execute(q).scalar_one())
+def agent_version_labels(s: Session, agent_id: str) -> dict[str, str]:
+ """`{version_id: label}` for one agent — the label the SDK sent (`version="v3"`, stored as
+ `config_hash`) unless a friendlier `label` was set."""
+ rows = s.execute(select(AgentVersion).where(AgentVersion.agent_id == agent_id)).scalars()
+ return {v.id: v.label or v.config_hash for v in rows}
+
+
def cluster_get(s: Session, project_id: str, cluster_id: str) -> FailureCluster | None:
cl = s.get(FailureCluster, cluster_id)
return cl if cl and cl.project_id == project_id else None
diff --git a/backend/tracely/services/gate_service.py b/backend/tracely/services/gate_service.py
index 8e84303..242795b 100644
--- a/backend/tracely/services/gate_service.py
+++ b/backend/tracely/services/gate_service.py
@@ -19,6 +19,7 @@ from sqlalchemy import delete, or_, select
from sqlalchemy.orm import Session
from tracely.config import settings
+from tracely.domain.gate.score_drop import ScoreDrop, score_drops
from tracely.domain.gate.warnings import delta_warnings
from tracely.domain.regression.outcome import gate_status, worst_gate_status
from tracely.domain.regression.fixtures import FixtureBundle
@@ -324,9 +325,14 @@ class GateService:
min_pass_rate: float | None = None,
project_id: str | None = None,
scenario_ids: Sequence[str] | None = None,
+ max_score_drop: float | None = None,
) -> GateRun | None:
"""Phase 2: grade the conversations phase 1 drove, then finalize the run.
+ `max_score_drop` (0..1, from `tracely simulate --max-score-drop`): an evaluator whose mean
+ fell at least that much vs the last green gate FAILs the run, even when every conversation
+ passed. Without it a drop past `gate_score_drop_warn` is only a warning.
+
Separate task on purpose. The agent's own spans reach Tracely as ordinary OTLP, so their
ingest is a Celery task — and under the default `--pool=solo --concurrency=1` those tasks
cannot run while the gate holds the worker's only slot. Grading inline meant every tool
@@ -411,12 +417,86 @@ class GateService:
gate.skipped += sum(o.verdict == "SKIP" for o in outcomes) + len(orphaned)
# A gate is only as good as its worst half.
gate.status = _worst(case_status, scenario_status)
+ drops = self._score_drops(gate, outcomes, max_score_drop)
+ if drops:
+ gate.warnings = list(dict.fromkeys([
+ *(gate.warnings or []), *(f"score drop: {d.message()}" for d in drops),
+ ]))
+ blocking = max_score_drop is not None and any(
+ -d.delta >= max_score_drop - 1e-9 for d in drops
+ )
+ if blocking or settings.gate_block_on_warnings:
+ gate.status = _worst(gate.status, "FAIL")
gate.finished_at = datetime.now(timezone.utc)
self.session.commit()
log.info("scenario_gate", gate_id=gate.id, status=gate.status, **summary)
self._notify_gate(gate)
return gate
+ def _score_drops(
+ self, gate: GateRun, outcomes: list[ScenarioOutcome], max_score_drop: float | None
+ ) -> list[ScoreDrop]:
+ """Evaluators whose mean fell vs the last green scenario gate, per shared scenario.
+
+ Read from ClickHouse for BOTH runs rather than stored on the row: the baseline's
+ conversations are still there (`detail["trace_ids"]`), and re-reading them means a judge
+ re-run since then is compared as it scores today. Advisory evaluators and the authored
+ `tracely.scenario.*` expectations are left out — the first never blocks anything, the
+ second is already a verdict on the conversation.
+ """
+ threshold = settings.gate_score_drop_warn
+ if max_score_drop is not None:
+ threshold = min(threshold, max_score_drop)
+ current = {o.scenario_id: o.trace_ids for o in outcomes if o.scenario_id and o.trace_ids}
+ if not current:
+ return []
+ baseline = self.session.execute(
+ select(GateRun)
+ .join(GateCase, GateCase.gate_run_id == GateRun.id)
+ .where(
+ GateRun.project_id == gate.project_id,
+ GateRun.agent_id == gate.agent_id,
+ GateRun.status == "PASS",
+ GateRun.id != gate.id,
+ GateCase.scenario_id.is_not(None),
+ )
+ .order_by(GateRun.created_at.desc())
+ .limit(1)
+ ).scalar_one_or_none()
+ if baseline is None:
+ return []
+ previous = {
+ gc.scenario_id: list((gc.detail or {}).get("trace_ids") or [])
+ for gc in self.session.execute(
+ select(GateCase).where(
+ GateCase.gate_run_id == baseline.id, GateCase.scenario_id.is_not(None)
+ )
+ ).scalars()
+ if gc.scenario_id in current
+ }
+ if not previous:
+ return []
+ scores = self.trace_reader.scores_by_trace(
+ gate.project_id, [t for tids in (*current.values(), *previous.values()) for t in tids]
+ )
+
+ def table(by_scenario: dict[str, list[str]]) -> dict[str, dict[str, list[float]]]:
+ out: dict[str, dict[str, list[float]]] = {}
+ for sid, tids in by_scenario.items():
+ for tid in tids:
+ for s in scores.get(tid, []):
+ name, value = s.get("name") or "", s.get("value")
+ # SKIP means "not graded" — its value says nothing about quality.
+ if value is None or s.get("verdict") == "SKIP":
+ continue
+ if name.startswith("tracely.scenario."):
+ continue
+ out.setdefault(sid, {}).setdefault(name, []).append(float(value))
+ return out
+
+ advisory = repositories.advisory_score_names(self.session, gate.project_id)
+ return score_drops(table(current), table(previous), threshold, exclude=advisory)
+
def _milestone_ci(self, gate: GateRun, candidate_spans: list[list]) -> None:
"""`ci_check_completed` — a REAL CI run graded the suite against a specific revision: it
must be run-scoped, have cases in it, and end PASS or FAIL. An empty gate, NO_COVERAGE
diff --git a/backend/tracely/workers/tasks.py b/backend/tracely/workers/tasks.py
index 16dc697..c89b500 100644
--- a/backend/tracely/workers/tasks.py
+++ b/backend/tracely/workers/tasks.py
@@ -152,6 +152,7 @@ def run_scenario_gate_task(
min_pass_rate: float | None = None,
case_ids: list[str] | None = None,
scenario_ids: list[str] | None = None,
+ max_score_drop: float | None = None,
) -> dict:
"""Phase 1 of a simulated gate: replay the regression cases, then drive the conversations.
@@ -197,7 +198,7 @@ def run_scenario_gate_task(
try:
grade_scenario_gate_task.apply_async(
- (project_id, gate_run_id, min_pass_rate, scenario_ids),
+ (project_id, gate_run_id, min_pass_rate, scenario_ids, max_score_drop),
countdown=settings.gate_scenario_span_grace_s,
)
except Exception:
@@ -216,6 +217,7 @@ def grade_scenario_gate_task(
gate_run_id: str,
min_pass_rate: float | None = None,
scenario_ids: list[str] | None = None,
+ max_score_drop: float | None = None,
) -> dict:
"""Phase 2: grade the driven conversations and finalize the run.
@@ -228,7 +230,8 @@ def grade_scenario_gate_task(
with SyncSessionLocal() as s:
try:
gate = GateService(s).grade_scenarios(
- gate_run_id, min_pass_rate, project_id=project_id, scenario_ids=scenario_ids
+ gate_run_id, min_pass_rate, project_id=project_id, scenario_ids=scenario_ids,
+ max_score_drop=max_score_drop,
)
except Exception:
s.rollback()
diff --git a/docker-compose.yml b/docker-compose.yml
index a291689..8ff8e7b 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -134,6 +134,8 @@ x-app-env: &app-env
ALLOW_PUBLIC_SIGNUP: ${ALLOW_PUBLIC_SIGNUP:-false}
# Agent endpoints / monitor webhooks on private addresses. Unset = allowed outside prod.
ALLOW_PRIVATE_URLS: ${ALLOW_PRIVATE_URLS:-}
+ # Scenario gates warn when an evaluator's mean falls this much vs the last green gate.
+ GATE_SCORE_DROP_WARN: ${GATE_SCORE_DROP_WARN:-0.1}
REQUIRE_PROJECT_LLM_KEY: ${REQUIRE_PROJECT_LLM_KEY:-false}
STRIPE_SECRET_KEY: ${STRIPE_SECRET_KEY:-}
STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-}
diff --git a/docs/pages/api-reference.mdx b/docs/pages/api-reference.mdx
index 6317478..c8d6874 100644
--- a/docs/pages/api-reference.mdx
+++ b/docs/pages/api-reference.mdx
@@ -207,7 +207,7 @@ This is what makes replay deterministic, offline, and free (no API keys, no cost
## 3. The CI gate CLI
```bash
-tracely simulate [<agent> | --agent a,b | --all] [--min-pass-rate 0.9] [--timeout 900] [--github]
+tracely simulate [<agent> | --agent a,b | --all] [--min-pass-rate 0.9] [--max-score-drop 0.1] [--timeout 900] [--github]
tracely gate <agent> [--env ci] [--api …] [--key …] [--pr N] [--sha …] [--github]
tracely replay <agent> (--entrypoint module:func | --cmd "…") [--live] [--github]
```
diff --git a/docs/pages/cli.mdx b/docs/pages/cli.mdx
index c0b6cc2..8b9d0df 100644
--- a/docs/pages/cli.mdx
+++ b/docs/pages/cli.mdx
@@ -10,7 +10,7 @@ The `tracely` CLI (shipped with the SDK) turns an agent's behaviour into a pull-
exit `0` (PASS) / `1` (the gate said no: FAIL, NO_COVERAGE) / `2` (no verdict was reached: INCOMPLETE, ERROR, unreachable), plus a GitHub commit status + PR comment. All non-zero codes block the merge; the split says whose fault it was.
```bash
-tracely simulate [<agent> | --agent a,b | --all] [--min-pass-rate 0.9] [--timeout 900] [--github]
+tracely simulate [<agent> | --agent a,b | --all] [--min-pass-rate 0.9] [--max-score-drop 0.1] [--timeout 900] [--github]
tracely gate <agent> [--env ci] [--api …] [--key …] [--pr N] [--sha …] [--github]
tracely replay <agent> (--entrypoint module:func | --cmd "…") [--live] [--github]
tracely export [--out dump.ndjson] [--limit N] [--from-ts …] [--to-ts …] [--evals]
@@ -128,6 +128,11 @@ reproduce the failure (no error step, and any tool the model required must actua
**soft warnings** flag latency / token regressions versus the last green gate (non-blocking by
default; set `gate_block_on_warnings` to make them block).
+`tracely simulate` adds **score drops**: each evaluator's mean score is compared, scenario by
+scenario, with the last green gate's conversations. A drop of 0.1 or more (`GATE_SCORE_DROP_WARN`)
+is a warning; `--max-score-drop 0.1` makes it fail the gate even when every conversation passed.
+Only evaluators scored 0–1 are compared, and advisory evaluators never are.
+
## GitHub Actions
Inside Actions (or with `--github`), the CLI posts a **commit status** (`tracely/regression-gate`)
diff --git a/docs/pages/product/_meta.js b/docs/pages/product/_meta.js
index 5e8120a..4935354 100644
--- a/docs/pages/product/_meta.js
+++ b/docs/pages/product/_meta.js
@@ -2,6 +2,7 @@ export default {
index: "Overview",
dashboard: "Dashboard",
traces: "Traces & conversations",
+ evaluators: "Evaluators",
trends: "Trends & cross-metric analysis",
clusters: "Failure clusters",
cases: "Regression cases",
diff --git a/docs/pages/product/alerts.mdx b/docs/pages/product/alerts.mdx
index 66228c4..5b429ea 100644
--- a/docs/pages/product/alerts.mdx
+++ b/docs/pages/product/alerts.mdx
@@ -6,7 +6,7 @@ import { Callout } from "nextra/components";
# Alerts
-**Settings → Alerts.** An alert rule has two halves: **when** it fires, and **what happens** —
+**Runs → Alerts** (or **Alert on fail** on any [evaluator](/product/evaluators#alert-on-fail)). An alert rule has two halves: **when** it fires, and **what happens** —
drawn as a flow.
<img className="screenshot" src="/screenshots/alerts-flow.png" alt="The alert flow builder: a When node wired through a condition, an LLM step and Slack, with the inspector below" />
diff --git a/docs/pages/product/clusters.mdx b/docs/pages/product/clusters.mdx
index df0a8fc..7c49bb7 100644
--- a/docs/pages/product/clusters.mdx
+++ b/docs/pages/product/clusters.mdx
@@ -26,6 +26,7 @@ Stage 2 needs the workspace's OpenRouter key; without one the button is disabled
<img className="screenshot" src="/screenshots/cluster-detail.png" alt="An issue: occurrences over time, analysis, proposed fix, suggested evaluator, signature, member traces" />
- **Occurrences** — when it happened, per day. A spike says *a deploy did this*; a flat line says *it has always done this*.
+- **By agent version** — production runs per version and how many of them fail this way. When earlier versions served at least 20 runs without a single one landing here, the first version that does is named: *introduced in v3*. A failure present since the first version Tracely saw is never pinned on one. Needs `version=` on `tracely.agent(…)` — a git sha is fine.
- **Analysis / Proposed fix** — the written-up mechanism and what to change.
- **Suggested evaluator** — a draft column that would catch this class of failure going forward. *Add it* opens the [Add Column](/product/traces#add-column) form pre-filled so you can review, edit, and save it.
- **Signature** — the masked structural key.
diff --git a/docs/pages/product/evaluators.mdx b/docs/pages/product/evaluators.mdx
new file mode 100644
index 0000000..a9fab00
--- /dev/null
+++ b/docs/pages/product/evaluators.mdx
@@ -0,0 +1,65 @@
+---
+description: "Tracely evaluators: the structural checks and LLM-judge rubrics that grade every new run. Create, edit, switch off and delete them in one list, and turn any of them into an alert in one click."
+---
+
+import { Callout } from "nextra/components";
+
+# Evaluators
+
+**Failures → Evaluators.** Every check that grades your agent, in one list.
+
+<img className="screenshot" src="/screenshots/evaluators.png" alt="The Evaluators list: each evaluator with its kind, level, on/off toggle, Alert on fail, Edit and delete" />
+
+An evaluator is a **column** on the [Traces table](/product/traces#evaluator-columns--the-grades): every
+new trace is scored by every enabled evaluator a few seconds after ingest. This page is the same set
+of columns, managed without opening a grid first.
+
+## What a verdict does
+
+A run **fails** iff some **non-advisory** evaluator scored it `FAIL`. That one rule drives everything
+downstream:
+
+- the red/green badge on the Traces table and the dashboard,
+- [failure clustering](/product/clusters) — only failed runs are clustered into issues,
+- [regression cases](/product/cases), which are promoted from those failures and replayed by the
+ [CI gate](/product/gates),
+- the *Conversation failed* and *FAIL rate* triggers in [Alerts](/product/alerts).
+
+Mark an evaluator **advisory** to keep its score visible without letting it fail a run.
+
+## Kinds and levels
+
+| Kind | How it grades | Cost |
+|---|---|---|
+| **Check** (structural) | Deterministic, computed from the spans: run outcome, tool success, tool consistency, latency budget, required tools. | Free |
+| **LLM judge** | A rubric graded by a model on the workspace's own OpenRouter key ([Settings → API keys](/product/settings#api-keys)). | Your tokens; capped by **sampling** |
+
+The level says what one score is about: **Conversation** (the whole thread), **Message** (one
+request/answer) or **Step** (each tool call, generation or hand-off inside a message).
+
+## Managing evaluators
+
+- **+ New evaluator** opens the editor: start from the template library, write the rubric yourself, or
+ describe the metric and let the model draft it. Every field is documented under
+ [Add Column](/product/traces#add-column) — it is the same editor.
+- **Edit** (or click the name) reopens it with the current configuration.
+- The **toggle** stops an evaluator from grading new runs without deleting it or its past scores.
+- **✕** deletes it; its column disappears from the Traces table. Deleting needs a signed-in account —
+ an ingest key can send and read traces but never remove what people built.
+
+<Callout type="info">
+ Changing an evaluator grades **new** runs only. To re-score history, re-run the column from its
+ header on the Traces table.
+</Callout>
+
+## Alert on fail
+
+**Alert on fail** opens a new [alert](/product/alerts) already wired up: trigger *Conversation failed*,
+scoped to this evaluator, with a Slack step. Paste a Slack webhook URL (or swap the step for email or a
+webhook) and save. Use it for the evaluators you would want to hear about at 3 a.m. — a PII or policy
+judge, a tool-choice check — and leave the rest to the dashboard.
+
+## Trusting a judge
+
+Before an LLM judge blocks merges, check it against yourself on [Judge calibration](/product/calibration):
+grade a sample blind and see how often the judge agrees, and whether it misses failures or over-flags.
diff --git a/docs/pages/product/gates.mdx b/docs/pages/product/gates.mdx
index 3a0a4b8..a0c8429 100644
--- a/docs/pages/product/gates.mdx
+++ b/docs/pages/product/gates.mdx
@@ -41,6 +41,7 @@ Pick the **agent to gate** (the picker is ranked by how many promoted cases each
Every case verdict is built from named **checks** — `tools`, `no_error`, and one `quality:<judge>` per judge the case was promoted from — each *required* or *advisory*, each `PASS` / `FAIL` / `UNAVAILABLE`, plus the execution evidence (mode, completed, divergence). A case is `PASS` only when every required check ran and passed under a completed execution; a required check that is unavailable makes it `INCOMPLETE`; a required `FAIL` is `FAIL`. Advisory checks stay visible and never decide. The same contract grades the manual **Replay** on a case page, so the UI, the CLI and CI cannot disagree about one candidate.
- **Warnings** — the candidate's latency and token usage are compared with the last green gate for the same agent; a regression beyond 25 % is a warning. Warnings are **non-blocking** unless the gate is configured to block on them. Fail-to-pass is the only hard rule.
+- **Score drops** (scenario gates) — each [evaluator](/product/evaluators)'s mean score is compared, scenario by scenario, with the conversations of the last green gate. A drop of 0.1 or more is a warning (`score drop: goal_success -0.22 vs last green gate …`); run `tracely simulate --max-score-drop 0.1` and it fails the gate, even when every conversation passed.
- **Cases** — one row per case: verdict, the candidate trace it was checked against (click through to the trace), and the assertion that failed.
## In CI
diff --git a/docs/pages/product/index.mdx b/docs/pages/product/index.mdx
index c1eacfe..6c55b32 100644
--- a/docs/pages/product/index.mdx
+++ b/docs/pages/product/index.mdx
@@ -31,6 +31,7 @@ Each page — and each panel that does something non-obvious — carries a small
|---|---|---|
| Dashboard | "Is the loop closed?" — the activation checklist and headline counts | [Dashboard](/product/dashboard) |
| Traces | "What did the agent do?" — conversation → message → step, with a grade per level | [Traces & conversations](/product/traces) |
+| Evaluators | "What counts as a failure?" — the checks and LLM judges that grade every run | [Evaluators](/product/evaluators) |
| Trends | "Is it getting better?" — failure rate, gate pass-rate, latency/cost, and how metrics move *together* | [Trends & cross-metric analysis](/product/trends) |
| Failure clusters | "What *kinds* of failure do we have?" | [Failure clusters](/product/clusters) |
| Regression cases | "Which production failures must never recur?" | [Regression cases](/product/cases) |
diff --git a/docs/pages/scenarios.mdx b/docs/pages/scenarios.mdx
index dd11704..8a84470 100644
--- a/docs/pages/scenarios.mdx
+++ b/docs/pages/scenarios.mdx
@@ -113,6 +113,7 @@ to `expect`. Without an LLM key configured the scenario is skipped, never silent
api: ${{ secrets.TRACELY_API }}
key: ${{ secrets.TRACELY_KEY }}
min-pass-rate: "0.9" # adversarial suites land some probes by design
+ max-score-drop: "0.1" # also fail if a judge's mean score slides vs the last green gate
# agent: support-agent,planner ← a subset; omit it to gate EVERY agent with scenarios
```
diff --git a/docs/public/screenshots/evaluators.png b/docs/public/screenshots/evaluators.png
new file mode 100644
index 0000000..dc74e1f
Binary files /dev/null and b/docs/public/screenshots/evaluators.png differ
diff --git a/frontend/app/(app)/clusters/[clusterId]/page.tsx b/frontend/app/(app)/clusters/[clusterId]/page.tsx
index 8daae81..7add7c9 100644
--- a/frontend/app/(app)/clusters/[clusterId]/page.tsx
+++ b/frontend/app/(app)/clusters/[clusterId]/page.tsx
@@ -32,6 +32,9 @@ export default async function ClusterPage({ params }: { params: Promise<{ cluste
const hist = c.histogram ?? [];
const histMax = Math.max(1, ...hist.map((b) => b.count));
const ev = c.suggested_evaluator;
+ const versions = c.versions?.rows ?? [];
+ const versioned = versions.some((v) => v.version);
+ const introduced = c.versions?.introduced_in ?? null;
return (
<div className="space-y-6">
@@ -90,6 +93,42 @@ export default async function ClusterPage({ params }: { params: Promise<{ cluste
</section>
)}
+ {versions.length > 0 && (
+ <section className="reveal card overflow-hidden" style={{ animationDelay: "80ms" }}>
+ <div className="flex items-center justify-between border-b border-line px-4 py-3">
+ <h2 className="text-[13px] font-semibold text-fg">By agent version</h2>
+ {introduced ? (
+ <Badge variant="fail">introduced in {introduced}</Badge>
+ ) : (
+ <span className="font-mono text-[10px] uppercase tracking-wider text-fg-faint">production runs</span>
+ )}
+ </div>
+ {versioned ? (
+ <div className="divide-y divide-line">
+ {versions.map((v) => (
+ <div key={v.version ?? "—"} className="flex items-center gap-3 px-4 py-2.5 text-[12.5px]">
+ <span className={`w-28 truncate font-mono ${v.version === introduced ? "text-fail" : "text-fg"}`}>
+ {v.version ?? "unversioned"}
+ </span>
+ <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-ink-700">
+ <div className="h-full bg-fail/70" style={{ width: `${v.runs ? (v.members / v.runs) * 100 : 0}%` }} />
+ </div>
+ <span className="w-40 text-right font-mono text-[11.5px] tabular-nums text-fg-muted">
+ {v.members} of {v.runs} run{v.runs === 1 ? "" : "s"}
+ </span>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <p className="px-4 py-3.5 text-[12.5px] text-fg-muted">
+ These runs carry no agent version, so the failure can't be tied to a release. Pass{" "}
+ <code className="font-mono text-fg">version=</code> to <code className="font-mono text-fg">tracely.agent(…)</code>{" "}
+ (a git sha works) and this shows which release introduced it.
+ </p>
+ )}
+ </section>
+ )}
+
{c.description && (
<section className="reveal card overflow-hidden" style={{ animationDelay: "90ms" }}>
<div className="border-b border-line px-4 py-3 text-[13px] font-semibold text-fg">Analysis</div>
diff --git a/frontend/app/(app)/evaluators/page.tsx b/frontend/app/(app)/evaluators/page.tsx
index 15636c7..dd94fea 100644
--- a/frontend/app/(app)/evaluators/page.tsx
+++ b/frontend/app/(app)/evaluators/page.tsx
@@ -11,7 +11,7 @@ export default function EvaluatorsPage() {
<header className="reveal">
<div className="flex items-center gap-3">
<h1 className="font-display text-[26px] font-extrabold tracking-tight">Evaluators</h1>
- <DocLink path="/product/traces" />
+ <DocLink path="/product/evaluators" />
</div>
<p className="mt-1.5 max-w-3xl text-[14px] text-fg-muted">
The checks that grade every new run — deterministic structural checks and LLM-judge rubrics. Each one is a
diff --git a/frontend/app/lib/api.ts b/frontend/app/lib/api.ts
index cf86f38..6af7ddb 100644
--- a/frontend/app/lib/api.ts
+++ b/frontend/app/lib/api.ts
@@ -542,6 +542,12 @@ export type FailureCluster = {
member_total?: number;
histogram?: { t: string; count: number }[];
suggested_evaluator?: SuggestedEvaluator;
+ // Production runs vs failures per agent version, oldest first; `version: null` = runs that sent
+ // no `tracely.agent.version`. `introduced_in` is set only when earlier versions ran clean.
+ versions?: {
+ introduced_in: string | null;
+ rows: { version: string | null; runs: number; members: number; first_seen: string | null }[];
+ };
};
/** `minSize` hides clusters with fewer members (>= 2); omitted = the backend default. */
diff --git a/sdk/README.md b/sdk/README.md
index 0d4a9c3..657a946 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -243,7 +243,7 @@ This is what makes replay deterministic, offline, and free (no API keys, no cost
## 3. The CI gate CLI
```bash
-tracely simulate [<agent> | --agent a,b | --all] [--min-pass-rate 0.9] [--timeout 900] [--github]
+tracely simulate [<agent> | --agent a,b | --all] [--min-pass-rate 0.9] [--max-score-drop 0.1] [--timeout 900] [--github]
tracely gate <agent> [--env ci] [--api …] [--key …] [--pr N] [--sha …] [--github]
tracely replay <agent> (--entrypoint module:func | --cmd "…") [--live | --lenient] [--github]
```
@@ -254,6 +254,8 @@ tracely replay <agent> (--entrypoint module:func | --cmd "…") [--live | --le
Scenarios belong to an agent, so `simulate` gates one agent, a comma-separated subset, or — with `--all` — every agent that has at least one **enabled** scenario (an agent whose suite is switched off is skipped, not reported untested). Each agent gets its own gate run but they share one commit status and one PR comment, and the job fails if any agent does. `--timeout` budgets the whole command.
+**Score drops.** Passing isn't the same as not getting worse: `simulate` also compares every evaluator's mean score, scenario by scenario, against the last green gate's conversations. A drop of `GATE_SCORE_DROP_WARN` (default 0.1) or more is a soft warning; pass `--max-score-drop 0.1` to make it fail the gate. Only evaluators scored on a 0–1 scale are compared, advisory ones never.
+
All three **exit 0 (PASS) / 1 (FAIL) / 2 (no answer — timeout, unreachable API, or a server-side ERROR run)** and, inside GitHub Actions (or with `--github`), post a **commit status + PR comment** with per-case results and soft warnings (latency/token deltas vs the last green gate). `--dry-run` prints the GitHub calls instead of sending; `--no-github` never touches GitHub. Config via flags or env (`TRACELY_API`, `TRACELY_KEY`, `TRACELY_AGENT`, `TRACELY_GATE_ENV`, `TRACELY_WEB_URL`, `GITHUB_TOKEN`; the git ref falls back to `GIT_REF` outside Actions). A `--cmd` subprocess inherits `TRACELY_INPUT` plus `TRACELY_API`/`TRACELY_KEY`/`TRACELY_ENV`, so it can emit traces without hardcoding the endpoint. A reusable composite action lives at `.github/actions/tracely-gate/`.
---
diff --git a/sdk/tests/test_cli_simulate.py b/sdk/tests/test_cli_simulate.py
index d83c718..3fe5f35 100644
--- a/sdk/tests/test_cli_simulate.py
+++ b/sdk/tests/test_cli_simulate.py
@@ -103,7 +103,7 @@ def _args(**over):
base = dict(
agent="planner", agents=None, all_agents=False, env="ci", api="http://api.test", key="k",
web_url="", pr=None, sha="deadbeef", github=False, no_github=True, token="",
- dry_run=True, min_pass_rate=None, timeout=30,
+ dry_run=True, min_pass_rate=None, max_score_drop=None, timeout=30,
)
base.update(over)
return argparse.Namespace(**base)
@@ -285,13 +285,14 @@ def test_min_pass_rate_is_forwarded(monkeypatch):
sent = {}
monkeypatch.setattr(
cli, "start_simulation",
- lambda api, key, agent, env, ref, pr, mpr=None: sent.update(rate=mpr) or {"id": "g1"},
+ lambda api, key, agent, env, ref, pr, mpr=None, msd=None: sent.update(rate=mpr, drop=msd)
+ or {"id": "g1"},
)
monkeypatch.setattr(cli, "poll_gate", lambda *a, **k: _data(status="PASS"))
monkeypatch.setattr(cli, "gh_context", lambda: ("", "", None))
- cli.cmd_simulate(_args(min_pass_rate=0.9))
- assert sent["rate"] == 0.9
+ cli.cmd_simulate(_args(min_pass_rate=0.9, max_score_drop=0.1))
+ assert sent == {"rate": 0.9, "drop": 0.1}
def test_conn_treats_empty_env_as_unset(monkeypatch):
diff --git a/sdk/tracely_sdk/cli.py b/sdk/tracely_sdk/cli.py
index e1a1bef..6fc5001 100644
--- a/sdk/tracely_sdk/cli.py
+++ b/sdk/tracely_sdk/cli.py
@@ -592,11 +592,14 @@ def cmd_gate(args: argparse.Namespace) -> int:
def start_simulation(
- api: str, key: str, agent: str, env: str, git_ref: str, pr: int | None, min_pass_rate=None
+ api: str, key: str, agent: str, env: str, git_ref: str, pr: int | None, min_pass_rate=None,
+ max_score_drop=None,
) -> dict:
body: dict = {"agent": agent, "env": env, "git_ref": git_ref, "pr_number": pr}
if min_pass_rate is not None:
body["min_pass_rate"] = min_pass_rate
+ if max_score_drop is not None:
+ body["max_score_drop"] = max_score_drop
return _post_json(f"{api.rstrip('/')}/api/gate/simulate", key, body)
@@ -700,7 +703,9 @@ def cmd_simulate(args: argparse.Namespace) -> int:
results: list[dict] = []
for agent in agents:
try:
- gate = start_simulation(api, key, agent, args.env, sha or "", pr, args.min_pass_rate)
+ gate = start_simulation(
+ api, key, agent, args.env, sha or "", pr, args.min_pass_rate, args.max_score_drop
+ )
print(f"driving scenarios for {agent} (gate {gate['id'][:8]}…)")
started.append((agent, gate["id"]))
except urllib.error.HTTPError as e:
@@ -1071,6 +1076,13 @@ def main(argv: list[str] | None = None) -> int:
help="fraction of conversations that must PASS (default: the server's setting, 1.0). "
"Lower it for adversarial suites, which land some probes by design.",
)
+ s.add_argument(
+ "--max-score-drop",
+ type=float,
+ help="fail when any evaluator's mean score falls at least this much (0..1, e.g. 0.1) vs "
+ "the last green gate on the same scenarios — even if every conversation passed. Without "
+ "it, a drop is reported as a soft warning only.",
+ )
s.add_argument(
"--timeout",
type=int,