:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): parallel harness for sandboxed agent evals (#70072)
Georgiy Tarasov4f4333482fc6
diff --git a/.agents/skills/writing-evals/SKILL.md b/.agents/skills/writing-evals/SKILL.mdnew file mode 100644index 000000000000..ddbaed3f9cd8--- /dev/null+++ b/.agents/skills/writing-evals/SKILL.md@@ -0,0 +1,176 @@+---+name: writing-evals+description: >+ Teaches how to write and run evals on the `products/posthog_ai/eval_harness/` harness — sandboxed agent suites that execute the real coding agent in a Docker or Modal sandbox against a seeded Hedgebox project, and one-shot suites that score a single in-process model invocation per case.+ Use when adding or changing eval suites, cases, scorers, seeders, or synthesizers under `products/posthog_ai/evals/` or `products/*/evals/`, when touching the harness under `products/posthog_ai/eval_harness/`, or when running or debugging those evals (`hogli evals`).+ Covers suite kinds and discovery, case anatomy, the seeder/synthesizer split, the one-branch scorer patterns, and how to read results.+ Not for `ee/hogai/eval/ci/` pytest evals, and not for the LLM Analytics product's evaluation features.+---++# Writing and running evals++The harness under `products/posthog_ai/eval_harness/` runs two kinds of suites: **sandboxed** suites execute the real coding agent inside a real sandbox against a seeded Hedgebox project and score what it did, and **one-shot** suites score a single in-process model invocation per case.+Neither runs under pytest — the standalone harness boots the shared infrastructure the selected suites need (for sandboxed suites: test DB, Django live server, LLM gateway, MCP server, Temporal, personhog; for one-shot suites: just the test DB, personhog, and demo data) and runs every selected suite concurrently, with Braintrust as the eval engine.++Read before writing anything:++- [products/posthog_ai/eval_harness/README.md](../../../products/posthog_ai/eval_harness/README.md) — usage, CLI flags, providers.+- [products/posthog_ai/evals/AGENTS.md](../../../products/posthog_ai/evals/AGENTS.md) — the Hedgebox dataset reference. Your prompts, `expected` values, and scorers must match that taxonomy exactly (`signed_up`, not `sign_up`).+- [products/posthog_ai/eval_harness/harness/AGENTS.md](../../../products/posthog_ai/eval_harness/harness/AGENTS.md) — invariants when touching the harness itself.++Field-level API detail (case fields, the `output` dict, `LogParser`, seeder inventory) lives in [references/authoring-reference.md](references/authoring-reference.md).++## Writing a suite++Suites are discovered by convention, not registered: any coroutine named `eval_*` in a file named `eval_*.py`, taking a single `ctx: EvalContext` and returning `None`.+The harness discovers suites from two root sets:++- `products/posthog_ai/evals/<domain>/` — the built-in tree, reserved for Max and other agent suites. The directory is the domain; the suite id is `<domain>/<module>::<fn>` (import path `products.posthog_ai.evals.<domain>.<module>`).+- `products/<product>/evals/` — where a product ships eval suites next to its own code. Note the **plural** `evals/`: the singular `products/signals/eval/` is an existing pytest tree and is not collected by the harness. The product is the domain; the suite id is `<product>/<module>::<fn>` (import path `products.<product>.evals.<module>`).++New product-owned evals belong under `products/<product>/evals/`. Both root sets use the same conventions (the `eval_*`-coroutine-in-`eval_*.py` rule, the `SUITE_KIND` marker, and substring selectors).+No `evals/` tree needs a pytest-collection exclusion: pytest's default `python_files` matches `test_*.py`, so `eval_*.py` files there are never collected as tests. Do not add a `conftest.py` under an `evals/` tree.++```python+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+++async def eval_my_thing(ctx: EvalContext) -> None:+ await SandboxedPrivateEval(+ experiment_name="sandboxed-my-thing-cli",+ cases=[SandboxedEvalCase(name="my_case", prompt="...")],+ scorers=[],+ ctx=ctx,+ )+```++- One suite = one Braintrust experiment. Bundle related cases into one suite; split only when the scorecard would be heterogeneous (self-skipping scorers stretch a shared scorer list across mildly different cases, but a scorecard where half the scorers skip half the cases is a sign to split).+- `experiment_name` is the Braintrust history key — renaming it resets cross-run comparison. Existing sandboxed suites end in `-cli` because the MCP server serves the `cli` surface.+- `SandboxedPublicEval` sends logs to Braintrust (summary gets an experiment URL); `SandboxedPrivateEval` runs with `no_send_logs`, so the local log dir is the only record. Use private for cases whose prompts or seeds shouldn't leave the machine.++## One-shot suites++A module-level `SUITE_KIND` declares how a module's suites execute; absent means sandboxed, so existing suites need nothing.+`SuiteKind.ONE_SHOT` suites skip the sandbox entirely: the harness boots only the test DB, personhog, and demo data for them, and preflight requires only `BRAINTRUST_API_KEY` + `LLM_GATEWAY_ANTHROPIC_API_KEY`.++```python+from products.posthog_ai.eval_harness.config import BaseEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.harness.requirements import SuiteKind+from products.posthog_ai.eval_harness.one_shot import OneShotPrivateEval++SUITE_KIND = SuiteKind.ONE_SHOT+++async def eval_my_generation(ctx: EvalContext) -> None:+ async def task(case: BaseEvalCase, task_ctx: EvalContext) -> dict:+ return {"answer": ...} # one model invocation, JSON-serializable++ await OneShotPrivateEval(+ experiment_name="my-generation",+ cases=[BaseEvalCase(name="my_case", prompt="...")],+ scorers=[...],+ task=task,+ ctx=ctx,+ )+```++- The task function runs once per case under the global one-shot limiter with the standard per-case timeout, and its returned dict **is** the scorer `output` — each one-shot suite defines its own output shape, and its scorers read the keys they know about. The runner backfills `prompt`; an optional `last_message` feeds the local `.summary.txt`.+- Cases are `BaseEvalCase` (no `repo_fixture`/`setup`); the shared master Hedgebox team is available as `ctx.demo_data.master_team_id` for read-only queries. A task that needs writes should copy a team via `products.posthog_ai.eval_harness.data_setup.copy_demo_data_to_new_team` under `ctx.demo_slots`.+- The sandbox-log scorer helpers (`LogParser`, `ExitCodeZero`, tool-call scorers) don't apply to one-shot outputs — write deterministic scorers against your own output dict, and reuse `JudgedScorer` for LLM judges.++## Case anatomy++`SandboxedEvalCase` (`products/posthog_ai/eval_harness/config.py`) has five author-facing fields: `name`, `prompt`, `expected`, `metadata`, `setup`.++- `name` doubles as the `--eval <substr>` filter target and the per-case log filename — keep it unique within the suite.+- `expected` is keyed by each scorer's `_name()`. A scorer reads only its own sub-dict and self-skips (or falls back to default behavior) when its key is absent — that is what lets one scorer list span a suite's cases. Judges take payloads like `{"warehouse_answer_correctness": {"expected_answer": "..."}}`.+- Every sandboxed case runs in a fresh isolated org/team/user copied from the master Hedgebox team, so cases never see each other's state. One-shot cases share the master team read-only.++## Seeding data: seeders and synthesizers++When a case needs data Hedgebox doesn't have (a running experiment, error-tracking issues, a warehouse catalog), declare a **seeder** as the case's `setup=`.++The contract:++- Synchronous: `def seed_x(context: CustomPromptSandboxContext) -> dict[str, Any]`. The harness calls it via `asyncio.to_thread` — never make it async.+- Runs once per case, after the per-case team is provisioned and before the agent prompt is dispatched.+- The returned dict lands in scorer `output["seed"]` — this is how scorers learn seeded IDs, flag keys, and expected values. Return everything a scorer will need.+- It receives only the context (`team_id`, `user_id`, ...) — there are no per-case parameters. Case-specific configuration means a dedicated seeder function; adding knobs to a shared seeder silently couples every suite that uses it.+- A seeder exception marks the case as an infra error (excluded from score averages), not a 0 — so a broken seeder never masquerades as an agent regression.++Shared building blocks live in `products/posthog_ai/eval_harness/seeders/` (`common.py` seeded-name providers and the `[lookup]` prefix, `insight.py` noise insights, `survey.py` flags); domain seeders live next to their suites (`data_warehouse/seeder.py`, `error_tracking/seeders.py`, `experiments/seeders.py`).++**Synthesizers** are the generation half of a two-part split, used when the seeded catalog is large or synthetic. A synthesizer is a pure, Django-free, deterministic generator that emits frozen dataclasses — no ORM, no I/O — and the seeder translates that catalog into ORM/ClickHouse/S3 rows inside the case's team.+The split exists so generation stays unit-testable and byte-for-byte reproducible (see `ee/hogai/test/eval/test_warehouse_synthesizer.py`) while installation stays an integration concern.+The reference implementation is `data_warehouse/synthesizer.py`: ~250 realistic noise tables plus seven planted "needles", each targeting one discovery skill, with needle name constants that prompts, `expected` values, and scorers all import verbatim so they can never drift apart.+Follow this split (and the constants-shared-by-all-three pattern) when seeding any new synthetic catalog.++## Writing scorers++Two patterns, each with exactly **one** implemented branch — never both `_run_eval_sync` and `_run_eval_async` (see the Scorers section of `harness/AGENTS.md`):++**Deterministic** — subclass `Scorer`, implement `_run_eval_sync` only. The base class supplies the async path the engine uses.++```python+from products.posthog_ai.eval_harness.log_parser import LogParser+from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer+++class MyCheck(Scorer):+ def _name(self) -> str:+ return "my_check"++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:+ if not output or not output.get("raw_log"):+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})+ parser = LogParser.cached(output["raw_log"], initial_prompt=output.get("prompt", "") or "")+ ...+```++**LLM judge** — subclass `JudgedScorer` from `products.posthog_ai.eval_harness.scorers`, implement `_prepare` only (plus `__init__` with the prompt template). `_prepare` returns either a `Score` to short-circuit without an LLM call, or `{"output": ..., "expected": ...}` template variables (omit `"expected"` for judges that don't need it). The shared base owns the async branch and maps judge errors to `score=0.0`.++Rules that apply to both:++- The harness adds `ExitCodeZero` to every experiment. Do not include it in a suite's `scorers`; an explicit duplicate is rejected.+- Reuse the other generic scorers first: `NoToolCall`, `RequiredToolCall`, and `LastToolCallNot` (all in `products.posthog_ai.eval_harness.scorers`).+- Always parse logs via `LogParser.cached(...)` so a case's log is parsed once, not once per scorer.+- Count only successful tool calls (`is_error=False`) — the agent is free to attempt and fail.+- `score=None` means "skipped": Braintrust omits it from the aggregate entirely. `0.0` means "failed". Pick deliberately — `None` for "this check doesn't apply to this case", `0.0` for "the agent got it wrong" _and_ for broken-judge/missing-input paths that must not silently vanish from the average.++## Running++Read [references/running-evals.md](references/running-evals.md) when setting up the local Docker provider or the remote Modal provider for the first time.+It covers shared credentials, provider authentication, first-run commands, concurrency limits, and common setup failures.+Prefer remote Modal for sandboxed suites when its prerequisites are available.+It runs agent sandboxes in parallel without the local Docker memory ceiling, so multi-case evals finish faster; keep Docker for small smoke tests or when remote access is unavailable.++```bash+hogli evals --list # suite ids, no infra+hogli evals eval_my_thing --eval my_case # one case, docker+hogli evals cli_mcp --provider modal # a domain, remote, fully parallel+```++`hogli evals:sandboxed` is a back-compat alias of `hogli evals`.++- Run from a flox shell (or wrap in `flox activate -- bash -c "..."`): the personhog build needs flox's Rust toolchain, and outside it the preflight `cargo build` dies on a missing `pkg-config`/OpenSSL.+- Env is loaded automatically (`.env` by the harness, `.env.local`/`.env.development`/`.env.services` by hogli) and a preflight validates the required variables before any infrastructure boots.+- `--provider docker` (default) caps at 4 concurrent sandboxes (16 GB each); `--provider modal` is unbounded — every case runs at once, `--max-sandboxes` is the cost knob.+- Team cloning and case seeding use one setup slot on ordinary local machines and four when `CODER` or `CI` is set.+- `--trials N` repeats every case for variance on stochastic behavior; `--fail-under <fraction>` gates the run's mean score.+- `--agent-runtime codex` runs the OpenAI Codex harness (default model `gpt-5.5`) instead of Claude; it requires `LLM_GATEWAY_OPENAI_API_KEY`. The runtime/model land in the Braintrust experiment metadata, so compare scores within one runtime.+- Every real eval invocation mirrors its complete stdout and stderr to `products/posthog_ai/eval_harness/logs/harness/<timestamp>_<id>.log`. The ending label identifies it as the full run transcript, the last terminal line is its absolute path, and `logs/harness/latest.log` points to the newest transcript. `--list` and argument errors do not create one.+- The plain-text summary is stable for people and agents: only the overall run says `PASS` or `FAIL`; completed suites, experiments, and cases say `DONE`; experiment blocks label scores, URLs, and agent-log directories.+- `EXPORT_EVAL_RESULTS=1` additionally appends one structured Braintrust summary per experiment to `eval_results.jsonl`. It does not replace the always-on transcript.+- Start debugging with the transcript path on the last line. Then open the experiment's `Agent logs` directory for `<case>.jsonl` (raw agent log), `<case>.artifacts.json`, and `<case>.summary.txt`. `logs/runs.jsonl` indexes historical case runs.++## Verification checklist++Before opening a PR:++1. `hogli evals --list` shows your suite (this also import-checks every eval module).+2. Run your new case alone: `hogli evals <suite> --eval <case>`. Read the transcript named on the final line, then the case summary and scorer metadata, not just the score.+3. Unit-test scorer and synthesizer logic where it's cheap — but not inside an `evals/` tree: keep suite dirs free of `conftest.py` and `pytest` imports. Existing homes: `products/posthog_ai/eval_harness/test/` and product test dirs.+4. Prompts and `expected` values use exact Hedgebox taxonomy names, relative date ranges (`-30d`, `-8w`), and shape-based assertions — never absolute counts.diff --git a/.agents/skills/writing-evals/references/authoring-reference.md b/.agents/skills/writing-evals/references/authoring-reference.mdnew file mode 100644index 000000000000..d5d849b7988c--- /dev/null+++ b/.agents/skills/writing-evals/references/authoring-reference.md@@ -0,0 +1,100 @@+# Sandboxed eval authoring reference++Field-level contracts for eval authors. Paths are relative to `products/posthog_ai/eval_harness/` unless noted.+When anything here disagrees with the code, the code wins — the sources of truth are `config.py`, `base.py`, and `log_parser.py`.++## `SandboxedEvalCase` (`config.py`)++| Field | Type | Meaning |+| -------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `name` | `str` | Case name. Also the `--eval <substr>` filter target and the per-case log filename. Unique within the suite. |+| `prompt` | `str` | The natural-language task given to the agent. |+| `repo_fixture` | `str = ""` | Informational only (tracking). |+| `expected` | `dict = {}` | Per-scorer expected values, keyed by each scorer's `_name()`. A scorer reads only its own sub-dict; a missing key means default behavior or self-skip. |+| `metadata` | `dict = {}` | Arbitrary tracking/filtering metadata. |+| `setup` | `Callable[[CustomPromptSandboxContext], dict] \| None` | The seed hook. Excluded from serialization (callables don't survive Braintrust's JSON round-trip); the runner re-binds it from the original case by name. |++There is no per-case `skills` field (skills are built once per run and available globally in every sandbox — assert skill _outcomes_, not attachment) and no per-case timeout (`--case-timeout` is run-level, counted from sandbox acquisition).++## Seeder contract++```python+def seed_my_domain(context: CustomPromptSandboxContext) -> dict[str, Any]: ...+```++- Synchronous, plain Django ORM / `sync_execute`; the harness runs it in `asyncio.to_thread`.+- Runs once per case: after the isolated team/user is minted, before the prompt is dispatched.+- `context` is a frozen dataclass; seeders in practice use `context.team_id` and `context.user_id`.+- The return dict becomes `output["seed"]` for every scorer of that case.+- Raising marks the case as an infra error (excluded from averages) rather than scoring 0.++Existing seeders and what they return:++| Seeder | Returns |+| ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |+| `seeders/insight.py::seed_insight_noise` | `{"noise_count", "lookup_insights": [{id, short_id, name}]}` |+| `seeders/survey.py::seed_survey_feature_flags` | `{"feature_flags_by_key": {...}}` |+| `data_warehouse/seeder.py::seed_warehouse_schema` | per-needle metadata incl. `queryable` (False when object storage creds are absent — dependent scorers self-skip) |+| `error_tracking/seeders.py::seed_error_tracking_issues` | `{"lookup_issues": [{id, name}]}` |+| `experiments/seeders.py::seed_*` | seeded experiment ids, flag keys, split signatures |++`seeders/common.py` provides `make_name_providers(seed)` (seeded mimesis bundle, `DEFAULT_NAME_SEED = 42`) and `LOOKUP_PREFIX = "[lookup]"` — a substring guaranteed absent from generated noise, so a prompt can name a lookup entity unambiguously.++## The `output` dict scorers receive++`AgentArtifacts.model_dump()` (`config.py`) merged with runner extras (`base.py`):++- From `AgentArtifacts`: `exit_code`, `stdout`, `stderr`, `git_diff`, `files_changed`, `test_exit_code`, `test_output`, `lint_exit_code`, `lint_output`, `duration_seconds`, `pr_url`.+- Added by the runner: `last_message` (final assistant text), `messages` (parsed message list), `raw_log` (the raw JSONL — what `LogParser` consumes), `seed` (the setup hook's return dict), `prompt`.++Error semantics: a per-case timeout produces a scored-0 agent failure (`exit_code=1`, stderr says timeout); any other exception (demo copy, seeder, provisioning) re-raises as an errored case excluded from score averages.++## `LogParser` (`log_parser.py`)++- `LogParser.cached(raw_log, initial_prompt="")` — memoized; always use this over the constructor so one case's log is parsed once across scorers.+- `get_tool_calls(name=None) -> list[ToolCall]` — chronological tool calls (excludes the `Skill` tool), optionally filtered by normalized name.+- `get_skill_calls(name=None)` / `was_skill_called(name)` — `Skill` tool invocations (`SkillCall(name, args, call_id, output, is_error, position)`).+- `get_user_prompt()` — first user text, falling back to `initial_prompt`.+- `get_final_agent_message()` — last assistant text block, or `None`.+- `normalize_tool_name(name)` — strips `mcp__<server>__<tool>` down to `<tool>`.+- `INFO_SYNTHETIC_PREFIX = "__info__:"` — synthetic call name unifying `exec {command: "info <tool>"}` and Claude Code's `ToolSearch(select:...)` as "tool schema loaded".++`ToolCall` fields: `name` (normalized; `exec` unwrapped to the inner tool), `input: dict`, `output: str`, `is_error` (also `True` when unpaired), `call_id`, `position` (chronological index), `raw_name`, `is_exec_unwrapped`, `requested_output_format` (`"json"` / `"optimized"` / `None`).++## Judge scorer shape++```python+from typing import Any++from braintrust import Score++from products.posthog_ai.eval_harness.scorers import BINARY_CHOICE_SCORES, JUDGE_MODEL, JudgedScorer+++class SaysHello(JudgedScorer):+ def __init__(self, **kwargs):+ super().__init__(+ name="says_hello",+ prompt_template="...did the agent greet the user?...\n<msg>{{output.last_message}}</msg>\nAnswer `yes` or `no`.",+ choice_scores=BINARY_CHOICE_SCORES,+ model=JUDGE_MODEL,+ max_completion_tokens=128,+ **kwargs,+ )++ def _prepare(self, output, expected) -> dict[str, Any] | Score:+ if not output or not output.get("last_message"):+ return Score(name=self._name(), score=0.0, metadata={"reason": "No final message"})+ return {"output": {"last_message": output["last_message"]}}+```++`_prepare` returns template variables — `{{output.*}}` / `{{expected.*}}` in `prompt_template` resolve against the returned `"output"` / `"expected"` values, not the raw case output. Shared constants: `BINARY_CHOICE_SCORES` (yes/no), `GRADED_ALIGNMENT_CHOICE_SCORES` (six-bucket scale), `JUDGE_MODEL`.++## Determinism discipline++The dataset is byte-for-byte reproducible under the fixed `EVAL_SEED` (`products/posthog_ai/eval_harness/data_setup.py`), and noise generators use fixed seeds.++- Reference events, properties, flags, and insight names **exactly** as listed in the Hedgebox dataset reference (`products/posthog_ai/evals/AGENTS.md`).+- Prefer relative date ranges (`-30d`, `-8w`, `-6m`) and shape-based assertions; never hard-code absolute counts — they drift when the simulation changes.+- Mirror seeded insights with `filterTestAccounts=True`; use the `account` group type (index 0) for group math.+- Share constants between synthesizer/seeder, prompts, and scorers by importing them (the warehouse needle pattern) instead of restating strings.diff --git a/.agents/skills/writing-evals/references/running-evals.md b/.agents/skills/writing-evals/references/running-evals.mdnew file mode 100644index 000000000000..02909827d9f8--- /dev/null+++ b/.agents/skills/writing-evals/references/running-evals.md@@ -0,0 +1,152 @@+# Running evals locally and remotely++Use this reference to prepare a machine for the standalone eval harness and choose between local Docker sandboxes and remote Modal sandboxes.+Both providers keep the eval database, Django server, LLM gateway, MCP server, Temporal, personhog, case setup, and scoring on the machine running `hogli evals`.+The provider changes only where the coding-agent sandbox runs.+Prefer remote Modal for multi-case sandboxed evals when its prerequisites are available.+Remote sandboxes run in parallel without consuming local Docker memory, which usually shortens the run substantially.+Use local Docker for a single-case smoke test, offline work, or when Modal and ngrok credentials are unavailable.++## Shared setup++Run evals from the repository root in a flox shell.+The personhog build needs flox's Rust toolchain, `pkg-config`, and OpenSSL.+When a flox shell is not already active, wrap the whole command instead of starting an interactive activation:++```bash+flox activate -- bash -c "hogli evals --list"+```++Use `hogli evals` for normal runs.+It loads the repository's `.env`, `.env.local`, `.env.development`, and `.env.services` files, with existing shell variables taking precedence.+Keep personal credentials in the gitignored `.env.local` or in the shell.+The direct `python -m products.posthog_ai.eval_harness.harness` entry point loads only `.env`, so export any other credentials before using it.++The required variables depend on the selected suite and runtime:++| Selection | Required variables |+| ------------------- | --------------------------------------------------------------- |+| Every suite | `BRAINTRUST_API_KEY`, `LLM_GATEWAY_ANTHROPIC_API_KEY` |+| Any sandboxed suite | `SANDBOX_JWT_PRIVATE_KEY` in addition to the variables above |+| Codex runtime | `LLM_GATEWAY_OPENAI_API_KEY` in addition to the variables above |++The local-development sandbox JWT key ships in `.env.example` and is normally copied into `.env` as part of repository setup.+Use that key only for local development, never for production.+Preflight reports every missing variable before it starts the database or any services.++List discovered suite IDs before the first real run:++```bash+hogli evals --list+```++Product-owned suites have IDs in the form `<product>/<module>::<function>`.+Start with one suite and one case so setup errors are cheap to diagnose:++```bash+hogli evals '<product>/eval_example::eval_my_thing' --eval '<case-name>'+```++One-shot-only selections do not use a sandbox provider.+Do not pass `--provider`, `--max-sandboxes`, or other sandbox-only flags for them; preflight rejects those flags rather than ignoring them.++The harness also limits the team-cloning and case-seeding phase separately from sandbox concurrency.+That setup limit is one on an ordinary local machine and automatically increases to four when either `CODER` or `CI` is set.+The higher limit lets managed development and CI environments prepare cases in parallel while keeping local ClickHouse memory use conservative.++## Local setup with Docker++Local sandboxed evals use Docker by default.+Install Docker, start the daemon, and confirm the CLI can reach it:++```bash+docker info+```++No manual sandbox-image build is required.+Before a run, the harness checks whether `posthog-sandbox-base` is current and rebuilds it when the Dockerfile or published agent version changed.+The first personhog build and any required image build can take several minutes; later runs reuse their outputs.++Run one case with one live sandbox first:++```bash+hogli evals '<suite-selector>' \+ --eval '<case-name>' \+ --provider docker \+ --max-sandboxes 1+```++`--provider docker` is optional because Docker is the default.+The default local cap is four concurrent sandboxes, and each sandbox is configured for up to 16 GB of memory.+Keep `--max-sandboxes` low unless the host has enough memory for the requested concurrency.++Normal teardown removes each case's container and sweeps leftovers from the current run.+For a failed case that needs container inspection, rerun it with `--keep-sandbox-containers`; remove the retained container after debugging.+Use `--rebuild-sandbox-image` only when a forced image rebuild is part of the diagnosis.++## Remote setup with Modal (preferred)++Remote sandboxed evals use the dedicated `posthog-sandbox-evals` Modal app.+Install the `modal` and `ngrok` CLIs and make sure both are on `PATH` inside the flox environment.++Authenticate Modal once:++```bash+modal token new+```++This normally writes `~/.modal.toml`.+For non-interactive environments, set both `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET` instead.++Authenticate ngrok once:++```bash+ngrok config add-authtoken '<token>'+```++Setting `NGROK_AUTHTOKEN` is the non-interactive alternative.+The harness generates a temporary ngrok configuration and starts HTTPS tunnels for the local Django API, LLM gateway, and MCP server.+Do not manually set `SANDBOX_API_URL`, `SANDBOX_LLM_GATEWAY_URL`, or `SANDBOX_MCP_URL` for an eval run.++The automated Modal provider currently requires three simultaneous ngrok tunnels.+That needs an authenticated paid ngrok plan.+Cloudflare Tunnel can expose the same services in other development workflows, but it is not wired into `hogli evals --provider modal` and does not satisfy the provider's current ngrok preflight.++Start with one remote sandbox to verify credentials, tunnels, and the remote image build:++```bash+hogli evals '<suite-selector>' \+ --eval '<case-name>' \+ --provider modal \+ --max-sandboxes 1+```++The first Modal run builds the eval image remotely.+Later runs reuse that image until its Dockerfile, build context, or bundled local skills change.+Keep the local process and network connection alive because the remote sandbox calls back into the services running on the local machine.++Modal concurrency is unbounded by default, so always choose an intentional `--max-sandboxes` value before running a product or domain with many cases:++```bash+hogli evals '<product-or-domain>' --provider modal --max-sandboxes 4+```++The harness stops its temporary tunnels during teardown.+It also terminates each case's task-tagged sandbox and sweeps leftovers belonging to the current run.+The generated tunnel URLs are publicly reachable while the run is active, so do not share them or leave a run unattended after an interruption.++## Diagnosing setup failures++Read the preflight error first; it names the missing executable, credential, or environment variable and gives the expected fix.+Frequent causes are:++- Running outside flox, which makes the personhog Rust build fail on its toolchain or OpenSSL dependencies.+- A stopped Docker daemon in local mode.+- Missing `~/.modal.toml` or incomplete `MODAL_TOKEN_ID` / `MODAL_TOKEN_SECRET` credentials in remote mode.+- An ngrok free plan or missing authtoken, which prevents all three remote tunnels from starting.+- Passing provider flags to a one-shot-only selection.+- Omitting `LLM_GATEWAY_OPENAI_API_KEY` when selecting `--agent-runtime codex`.++Every real invocation mirrors stdout and stderr to `products/posthog_ai/eval_harness/logs/harness/<timestamp>_<id>.log`.+The final terminal line is that transcript's absolute path, and `logs/harness/latest.log` points to the newest run.+After a case starts, its agent log directory contains `<case>.jsonl`, `<case>.artifacts.json`, and `<case>.summary.txt` for deeper debugging.diff --git a/AGENTS.md b/AGENTS.mdindex 1a76511fd0a8..bcccfd5a99ce 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -203,5 +203,6 @@ ALWAYS invoke the matching skill **before** writing or reviewing code in these a- `/modifying-taxonomic-filter` — any TaxonomicFilter change- `/sending-notifications` — adding notification support- `/writing-skills` — creating or updating skills in `.agents/skills/`+- `/writing-evals` — adding or changing eval suites, cases, scorers, or seeders under `products/posthog_ai/evals/` or `products/*/evals/`, touching the harness in `products/posthog_ai/eval_harness/`, or running those evals- `/authoring-ci-workflows` — adding or editing any `.github/workflows` workflow, composite action, or reusable workflow- `/gating-production-deploys` — any workflow that builds and pushes a production image or dispatches a deploydiff --git a/ee/hogai/eval/README.md b/ee/hogai/eval/README.mdindex d8b0514eebf6..d2541a16428f 100644--- a/ee/hogai/eval/README.md+++ b/ee/hogai/eval/README.md@@ -23,6 +23,24 @@ We currently use [Braintrust](https://braintrust.dev) as our evaluation platformFor historical eval runs, see the [full Experiments list in Braintrust](https://www.braintrust.dev/app/PostHog/p/Max%20AI/experiments).+## Sandboxed evals++The sandboxed coding-agent evals (`products/posthog_ai/eval_harness/`) run on a standalone harness rather than pytest:++```bash+flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness [SELECTOR ...]"+```++Selectors are substrings matched against `<domain>/<module>::<fn>` (for example `experiments`, `sql`, or `eval_lifecycle_skills`); omit them to run every suite, or pass `--list` to see the ids.+`--eval <substr>` filters cases by name.+Sandboxes run locally under Docker by default; `--provider modal` runs them remotely on Modal.++Every suite runs concurrently, with one global semaphore bounding live sandboxes, so selecting more suites raises throughput without raising peak load.++- [`products/posthog_ai/eval_harness/README.md`](../../../products/posthog_ai/eval_harness/README.md) covers the flags, the provider prerequisites, and how to add a suite.+- [`products/posthog_ai/evals/AGENTS.md`](../../../products/posthog_ai/evals/AGENTS.md) is the Hedgebox dataset reference every eval case is written against.+- [`products/posthog_ai/eval_harness/harness/README.md`](../../../products/posthog_ai/eval_harness/harness/README.md) explains how the harness itself works.+## Offline evals### Datasetsdiff --git a/ee/hogai/eval/ci/conftest.py b/ee/hogai/eval/ci/conftest.pyindex 0c75e053e62e..4b8661573c4b 100644--- a/ee/hogai/eval/ci/conftest.py+++ b/ee/hogai/eval/ci/conftest.py@@ -11,6 +11,13 @@ from posthog.schema import FailureMessage, HumanMessagefrom posthog.models import Organization, Team, Userfrom products.posthog_ai.backend.models.assistant import Conversation, CoreMemory+from products.posthog_ai.eval_harness.data_setup import (+ EVAL_USER_FULL_NAME, # noqa: F401 — re-exported for eval_root_style.py+ DashboardWithInsightsFixture,+ create_core_memory,+ create_dashboard_with_insights,+ create_demo_org_team_user,+)from ee.hogai.artifacts.manager import ArtifactManagerfrom ee.hogai.artifacts.utils import unwrap_visualization_artifact_content@@ -19,13 +26,6 @@ from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer# We want the PostHog set_up_evals fixture herefrom ee.hogai.eval.conftest import set_up_evals # noqa: F401-from ee.hogai.eval.data_setup import (- EVAL_USER_FULL_NAME, # noqa: F401 — re-exported for eval_root_style.py- DashboardWithInsightsFixture,- create_core_memory,- create_dashboard_with_insights,- create_demo_org_team_user,-)from ee.hogai.eval.scorers import PlanAndQueryOutputfrom ee.hogai.utils.types import AssistantNodeName, AssistantStatefrom ee.hogai.utils.types.base import ArtifactRefMessagediff --git a/ee/hogai/eval/conftest.py b/ee/hogai/eval/conftest.pyindex 5f65f812164e..909ae68b9542 100644--- a/ee/hogai/eval/conftest.py+++ b/ee/hogai/eval/conftest.py@@ -12,32 +12,6 @@ from posthog.conftest import _django_db_setup # noqa: F401def pytest_addoption(parser):# Example: pytest ee/hogai/eval/ci/eval_sql.py --eval churn - to only run cases containing "churn" in inputparser.addoption("--eval", action="store")- parser.addoption(- "--keep-sandbox-containers",- action="store_true",- default=False,- help="Skip the sandboxed eval harness Docker container cleanup at session end (for debugging).",- )- parser.addoption(- "--mcp-mode",- action="store",- default="both",- choices=("tools", "cli", "both"),- help=(- "Which PostHog MCP execution mode to exercise in sandboxed evals. "- "'tools' registers each tool individually; 'cli' wraps them in a single "- "`exec` tool; 'both' (default) parametrizes each test across both modes."- ),- )- parser.addoption(- "--agent-model",- action="store",- default="anthropic/claude-opus-4-8",- help=(- "Model the sandboxed agent runs against. Pinned for stable cross-run "- "comparisons. Defaults to anthropic/claude-opus-4-8."- ),- )_nodeid_to_results_url_map: dict[str, str] = {}diff --git a/ee/hogai/eval/sandboxed/base.py b/ee/hogai/eval/sandboxed/base.pydeleted file mode 100644index 96488ea02f14..000000000000--- a/ee/hogai/eval/sandboxed/base.py+++ /dev/null@@ -1,336 +0,0 @@-from __future__ import annotations--import os-import uuid-import asyncio-import logging-from collections.abc import Sequence-from functools import partial-from pathlib import Path-from typing import TYPE_CHECKING, Any--import pytest--from braintrust import EvalAsync, EvalCase, EvalHooks-from posthoganalytics import Posthog--from .config import AgentArtifacts, SandboxedEvalCase-from .log_sink import append_case_scores, build_case_dir, write_case_logs-from .runner import run_eval_case--if TYPE_CHECKING:- from .conftest import SandboxedDemoData-from .acp_log import ParsedLog, parse_log-from .scorers import wrap_scorers-from .trace_events import emit_evaluation_events, emit_trace_events, emit_trace_root--logger = logging.getLogger(__name__)---def _get_last_assistant_text(parsed: ParsedLog) -> str:- """Extract the last assistant message text from the final generation."""- for gen in reversed(parsed.generations):- if not gen.output_content:- continue- texts = [b.get("text", "") for b in gen.output_content if isinstance(b, dict) and b.get("type") == "text"]- text = "\n".join(t for t in texts if t)- if text:- return text- return ""---def _log_conversation_spans(hooks: EvalHooks, parsed: ParsedLog) -> None:- """Log each conversation message as a child span so Braintrust renders a trace tree.-- Uses the same Anthropic-format messages as PostHog trace capture.- """- for msg in parsed.messages:- role = msg.get("role", "system")- content = msg.get("content", "")-- # Anthropic format: content can be a string or list of content blocks- if isinstance(content, list):- # Render content blocks for display- parts: list[str] = []- for block in content:- if not isinstance(block, dict):- continue- block_type = block.get("type", "")- if block_type == "text":- parts.append(block.get("text", ""))- elif block_type == "tool_use":- parts.append(f"[tool_use: {block.get('name', '?')}]")- elif block_type == "tool_result":- result_text = str(block.get("content", ""))[:500]- is_error = block.get("is_error", False)- prefix = "[tool_result error]" if is_error else "[tool_result]"- parts.append(f"{prefix} {result_text}")- display_content = "\n".join(parts)- else:- display_content = str(content)-- if role == "assistant":- # Check if this message contains tool_use blocks- has_tool_use = isinstance(content, list) and any(- isinstance(b, dict) and b.get("type") == "tool_use" for b in content- )- span_type = "function" if has_tool_use else "llm"- name = "tool_call" if has_tool_use else "agent"- elif role == "user":- has_tool_result = isinstance(content, list) and any(- isinstance(b, dict) and b.get("type") == "tool_result" for b in content- )- span_type = "function"- name = "tool_result" if has_tool_result else "user"- else:- span_type = "function"- name = role-- with hooks.span.start_span(name=name, span_attributes={"type": span_type}) as span:- if role == "user":- span.log(input=display_content)- elif role == "assistant":- span.log(output=display_content)- else:- span.log(metadata={"message": display_content})-- # Also log non-AI spans (console, errors)- for span_desc in parsed.spans:- with hooks.span.start_span(name=span_desc.span_name, span_attributes={"type": "function"}) as span:- span.log(metadata={"message": span_desc.content})---async def SandboxedEval(- experiment_name: str,- cases: Sequence[SandboxedEvalCase],- scorers: Sequence[Any],- pytestconfig: pytest.Config,- sandboxed_demo_data: SandboxedDemoData,- is_public: bool = False,- no_send_logs: bool = True,- posthog_client: Posthog | None = None,-):- """Run a sandboxed agent evaluation suite via Braintrust.-- For each ``SandboxedEvalCase``, creates a Task, triggers the temporal workflow- (sandbox provisioning, agent-server, prompt delivery, cleanup), polls S3 logs- for results, and feeds parsed artifacts to the scorers.-- ``sandboxed_demo_data.make_context(case_name)`` is invoked once per case and- returns a freshly isolated ``CustomPromptSandboxContext`` (own org/team/user)- so cases can't pollute each other's state.- """- # Generate a unique experiment ID per eval run- experiment_id = str(uuid.uuid4())-- # Shared lookups populated by task(), read after EvalAsync completes.- agent_trace_id_lookup: dict[str, str] = {}- # Per-case metadata for emitting $ai_trace root events after scoring.- case_trace_meta: dict[str, dict[str, Any]] = {}-- # Local disk sink for raw agent logs — lets an agent iterating on the- # harness read back what happened without round-tripping through Braintrust.- run_log_dir = build_case_dir(experiment_name, experiment_id)- log_dirs: set[Path] = getattr(pytestconfig, "_sandboxed_eval_log_dirs", set())- log_dirs.add(run_log_dir)- pytestconfig._sandboxed_eval_log_dirs = log_dirs # type: ignore[attr-defined]-- # Wrap scorers with tracing if PostHog client is available- scorer_traces: dict[tuple[str, str], str] = {}- if posthog_client:- active_scorers, scorer_traces = wrap_scorers(- scorers, posthog_client, experiment_id, experiment_name, agent_trace_id_lookup- )- else:- active_scorers = list(scorers)-- # Filter cases by --eval flag if provided- case_filter = pytestconfig.option.eval if hasattr(pytestconfig.option, "eval") else None-- # Closure-scoped lookup so callable hooks on SandboxedEvalCase (e.g. `setup`)- # can be re-bound inside `task()` — they don't survive Braintrust's JSON- # round-trip, but the original case objects do.- cases_by_name: dict[str, SandboxedEvalCase] = {c.name: c for c in cases}-- eval_cases: list[EvalCase] = []- for case in cases:- if case_filter and case_filter not in case.name:- continue- eval_cases.append(- EvalCase(- input={- "name": case.name,- "prompt": case.prompt,- "repo_fixture": case.repo_fixture,- },- expected=case.expected,- metadata=case.metadata,- )- )-- async def task(input: dict[str, Any], hooks: EvalHooks) -> dict[str, Any] | None:- eval_case = SandboxedEvalCase(- name=input["name"],- prompt=input["prompt"],- repo_fixture=input.get("repo_fixture", ""),- )- original_case = cases_by_name.get(input["name"])-- try:- # The factory does Django ORM work. Django's async-safety guard- # rejects sync ORM calls from async contexts, so run it in a worker- # thread.- sandbox_context = await asyncio.to_thread(- sandboxed_demo_data.make_context,- eval_case.name,- )- seed_result: dict[str, Any] = {}- if original_case is not None and original_case.setup is not None:- try:- seed_result = await asyncio.to_thread(original_case.setup, sandbox_context)- except Exception:- logger.exception("Setup hook failed for '%s'", eval_case.name)- raise-- result = await run_eval_case(eval_case, sandbox_context)-- # Store trace_id in metadata so evaluation events can link to the trace- if result.trace_id:- hooks.metadata["trace_id"] = result.trace_id- agent_trace_id_lookup[eval_case.name] = result.trace_id- hooks.metadata["artifacts"] = result.artifacts.model_dump()-- # Parse the log once, use for both Braintrust spans and PostHog trace capture- last_message = ""- messages: list[dict[str, Any]] = []- if result.raw_log:- parsed = parse_log(result.raw_log, initial_prompt=eval_case.prompt)- _log_conversation_spans(hooks, parsed)- last_message = _get_last_assistant_text(parsed)- messages = parsed.messages-- if posthog_client:- try:- emit_trace_events(- posthog_client,- trace_id=result.trace_id,- experiment_id=experiment_id,- experiment_name=experiment_name,- case_name=eval_case.name,- parsed=parsed,- )- # Store metadata for emit_trace_root (called after scoring)- case_trace_meta[eval_case.name] = {- "prompt": eval_case.prompt,- "duration": result.artifacts.duration_seconds,- "first_timestamp": parsed.first_timestamp,- "last_message": last_message,- "artifacts_summary": result.artifacts.model_dump(),- "token_usage": parsed.total_token_usage,- }- except Exception:- logger.exception("Failed to emit trace events for '%s'", eval_case.name)-- try:- paths = write_case_logs(- case_dir=run_log_dir,- case_name=eval_case.name,- raw_log=result.raw_log or "",- artifacts=result.artifacts.model_dump(),- prompt=eval_case.prompt,- duration=result.artifacts.duration_seconds,- last_message=last_message,- token_usage=case_trace_meta.get(eval_case.name, {}).get("token_usage"),- )- print(f"[eval-logs] {eval_case.name}: {paths.case_dir}") # noqa: T201- except Exception:- logger.exception("Failed to write local eval logs for '%s'", eval_case.name)-- return result.artifacts.model_dump() | {- "last_message": last_message,- "messages": messages,- "raw_log": result.raw_log,- "seed": seed_result,- "prompt": eval_case.prompt,- }- except Exception as e:- logger.exception("Eval task failed for '%s'", input.get("name", "?"))- return AgentArtifacts(- exit_code=-1,- stderr=f"Eval runner error: {e}",- ).model_dump()-- project_name = f"sandboxed-agent-{experiment_name}" if is_public else experiment_name-- timeout = 60 * 15 # 15 minutes per case- if os.getenv("EVAL_MODE") == "offline":- timeout = 60 * 60-- result = await EvalAsync(- project_name,- data=eval_cases,- task=task,- scores=active_scorers,- timeout=timeout,- max_concurrency=2,- update=True,- is_public=is_public,- no_send_logs=no_send_logs,- )-- # Append final scores to local summary files for every case we wrote.- if result.results:- for eval_result in result.results:- case_name = eval_result.input.get("name", "") if isinstance(eval_result.input, dict) else ""- if not case_name:- continue- try:- append_case_scores(run_log_dir, case_name, dict(eval_result.scores or {}))- except Exception:- logger.exception("Failed to append scores to local log summary for '%s'", case_name)-- # Emit evaluation events and trace roots to PostHog (after scoring)- if posthog_client and result.results:- try:- emit_evaluation_events(posthog_client, experiment_id, experiment_name, result.results, scorer_traces)- # Emit $ai_trace root events now that scores are available- for eval_result in result.results:- case_name = eval_result.input.get("name", "") if isinstance(eval_result.input, dict) else ""- trace_id = agent_trace_id_lookup.get(case_name)- meta = case_trace_meta.get(case_name)- if trace_id and meta:- emit_trace_root(- posthog_client,- trace_id=trace_id,- experiment_id=experiment_id,- experiment_name=experiment_name,- case_name=case_name,- prompt=meta["prompt"],- duration=meta["duration"],- first_timestamp=meta["first_timestamp"],- last_message=meta.get("last_message", ""),- artifacts_summary=meta.get("artifacts_summary"),- scores=eval_result.scores,- token_usage=meta.get("token_usage"),- )- posthog_client.flush()- print( # noqa: T201- f"\nPostHog evaluations: "- f"https://us.posthog.com/project/2/ai-evals/evaluations/offline/experiments/"- f"{experiment_id}?offline_date_from=-1d\n"- )- except Exception:- logger.exception("Failed to emit evaluation events for '%s'", experiment_name)-- if os.getenv("EXPORT_EVAL_RESULTS"):- with open("eval_results.jsonl", "a") as f:- f.write(result.summary.as_json() + "\n")-- return result---SandboxedPublicEval = partial(SandboxedEval, is_public=True, no_send_logs=False)-"""Sandboxed evaluation case that is publicly accessible."""--SandboxedPrivateEval = partial(SandboxedEval, is_public=False, no_send_logs=True)-"""Sandboxed evaluation case that is not accessible publicly."""diff --git a/ee/hogai/eval/sandboxed/conftest.py b/ee/hogai/eval/sandboxed/conftest.pydeleted file mode 100644index 9578f063f827..000000000000--- a/ee/hogai/eval/sandboxed/conftest.py+++ /dev/null@@ -1,698 +0,0 @@-from __future__ import annotations--import os-import json-import atexit-import asyncio-import logging-import threading-import subprocess-from collections.abc import Generator-from datetime import timedelta-from pathlib import Path--import pytest--from django.conf import settings--from temporalio.testing import WorkflowEnvironment--from posthog.temporal.common.worker import create_worker--from products.tasks.backend.facade.agents import (- ENV_LOCAL_SKILLS_HOST_PATH,- CustomPromptSandboxContext,- LocalSkillsCache,-)-from products.tasks.backend.facade.temporal import (- ACTIVITIES as TASKS_ACTIVITIES,- WORKFLOWS as TASKS_WORKFLOWS,-)--# We want the PostHog set_up_evals fixture here-from ee.hogai.eval.conftest import set_up_evals # noqa: F401-from ee.hogai.eval.data_setup import copy_demo_data_to_new_team, create_core_memory, ensure_master_demo_team-from ee.hogai.eval.sandboxed.long_lived_subprocess import LongLivedSubprocessManager--logger = logging.getLogger(__name__)--MCP_PORT = 18787 # Non-default port to avoid conflicts with dev MCP-DJANGO_LIVE_PORT = 18000 # Non-default port for in-process Django server-LLM_GATEWAY_PORT = 13308 # Non-default port to avoid conflicts with dev LLM gateway--# pytest-django normally derives this from ``@pytest.mark.django_db`` markers.-# Sandboxed evals intentionally strip those markers to avoid per-test DB-# transactions/flushes, so the local ``django_db_setup`` override below forces-# setup of the base Django DB explicitly. Person DB setup is handled by-# PostHog's eval setup after the default test DB name is known.-SANDBOXED_EVAL_SETUP_DATABASES: dict[str, None] = {"default": None}---def pytest_collection_modifyitems(config, items): # noqa: ARG001- """Keep sandboxed evals out of pytest-django's per-test DB wrappers.-- The sandbox harness starts a live Django server and Temporal worker that- use separate DB connections. They must see committed rows immediately, so- normal pytest-django test transactions do not work. ``transaction=True``- makes the rows visible, but also puts every eval on the transactional test- path, which flushes/re-initializes state between tests and defeats the- long-lived eval database.-- Instead, ``_sandboxed_eval_database_access`` below creates the DB once and- leaves access unblocked for the whole eval session. Strip accidental- ``django_db`` markers so pytest-django does not add transactional fixtures- back in.- """- base_dir = Path(__file__).parent- for item in items:- try:- test_path = Path(str(item.fspath))- test_path.relative_to(base_dir)- except (TypeError, ValueError):- continue- node = item- while node is not None:- own_markers = getattr(node, "own_markers", None)- if own_markers is not None:- node.own_markers = [marker for marker in own_markers if marker.name != "django_db"]- node = node.parent- # NodeKeywords forbids __delitem__ in newer pytest — the own_markers- # mutation above is what actually strips the marker; this pop is a- # legacy belt-and-braces that's a no-op when not supported.- try:- item.keywords.pop("django_db", None)- except (ValueError, TypeError):- pass--[email protected](scope="session")-def django_db_setup(- request: pytest.FixtureRequest,- django_test_environment: None,- django_db_blocker,- django_db_use_migrations: bool,- django_db_keepdb: bool,- django_db_createdb: bool,- django_db_modify_db_settings: None,-) -> Generator[None]:- """Create the eval test DB even though eval items have no django_db marker."""- from django.test.utils import setup_databases, teardown_databases-- from pytest_django.fixtures import _disable_migrations-- if not django_db_use_migrations:- _disable_migrations()-- with django_db_blocker.unblock():- db_cfg = setup_databases(- verbosity=request.config.option.verbose,- interactive=False,- keepdb=django_db_keepdb and not django_db_createdb,- aliases=SANDBOXED_EVAL_SETUP_DATABASES,- serialized_aliases=set(),- )-- yield-- if not django_db_keepdb:- with django_db_blocker.unblock():- teardown_databases(db_cfg, verbosity=request.config.option.verbose)--[email protected](scope="session", autouse=True)-def _sandboxed_eval_database_access(set_up_evals, django_db_blocker) -> Generator[None]: # noqa: F811- """Use one committed eval database instead of per-test transactions."""- django_db_blocker.unblock()- yield- django_db_blocker.restore()---# Sandbox container name prefix used by the eval harness (set in SandboxConfig.name)-_EVAL_CONTAINER_PREFIX = "task-sandbox-"-_LONG_LIVED_SUBPROCESSES = LongLivedSubprocessManager()---def pytest_keyboard_interrupt(excinfo: object) -> None: # noqa: ARG001- _LONG_LIVED_SUBPROCESSES.stop_all()---def pytest_sessionfinish(session: pytest.Session, exitstatus: int) -> None: # noqa: ARG001- _LONG_LIVED_SUBPROCESSES.stop_all()---def _temporal_client_target(env: WorkflowEnvironment) -> tuple[str, str]:- config = env.client.config()- service_client = config["service_client"]- target_host = service_client.config.target_host- host, port = target_host.rsplit(":", maxsplit=1)- return host, port---def _cleanup_eval_containers():- """Remove any leftover eval Docker containers.-- Registered via ``atexit`` so it runs even on Ctrl+C / SIGINT where- pytest session teardown may be skipped.- """- try:- result = subprocess.run(- ["docker", "ps", "-a", "--filter", f"name={_EVAL_CONTAINER_PREFIX}", "--format", "{{.ID}}"],- capture_output=True,- text=True,- timeout=10,- )- for container_id in result.stdout.strip().splitlines():- if container_id:- logger.info("Cleaning up eval container %s", container_id)- subprocess.run(["docker", "rm", "-f", container_id], capture_output=True, timeout=10)- except Exception:- pass # Best effort — don't crash the exit path--[email protected](scope="session", autouse=True)-def _cleanup_sandbox_containers(pytestconfig):- """Stop and remove any eval sandbox containers at session end. Sandboxes are kept alive, but evals should not keep them.-- Registers an ``atexit`` hook as a belt-and-braces safety net for SIGINT /- SIGTERM paths where pytest's session teardown is skipped. Pass- ``--keep-sandbox-containers`` to opt out (useful when debugging a- leftover container).- """- keep = pytestconfig.option.keep_sandbox_containers- if not keep:- atexit.register(_cleanup_eval_containers)- yield- if keep:- logger.info("--keep-sandbox-containers set, skipping container cleanup")- return- _cleanup_eval_containers()--[email protected](scope="session", autouse=True)-def _django_live_server(_sandboxed_eval_database_access):- """Start an in-process Django HTTP server on the test database.-- Uses Django's ``LiveServerThread`` (same mechanism as pytest-django's- ``live_server`` fixture, but session-scoped). The sandbox Docker container- calls this server via ``host.docker.internal`` for API requests,- log persistence, and the LLM gateway.-- Depends on ``_sandboxed_eval_database_access`` so the PostHog eval database- setup has completed before any subprocess (LLM gateway, MCP) connects.- """- from pytest_django.live_server_helper import LiveServer-- # Bind on all interfaces so the sandbox Docker container can reach the server- # via ``host.docker.internal`` (the docker bridge gateway). The socket binds- # at thread start using this host; we then re-point ``thread.host`` at- # localhost purely so ``server.url`` advertises a loopback address to- # host-side clients (MCP server, LLM gateway) — the already-bound 0.0.0.0- # socket still accepts both loopback and bridge connections.- server = LiveServer(f"0.0.0.0:{DJANGO_LIVE_PORT}")- server.thread.host = "127.0.0.1"- logger.info("Django live server started at %s (bound on 0.0.0.0)", server.url)-- yield server-- server.stop()- logger.info("Django live server stopped")--[email protected](scope="session", autouse=True)-def _sandboxed_local_skills(_sandbox_settings) -> Generator[Path]:- """Build local skills once per session; bind-mount into every sandbox.-- Uses a content-hash cache so repeat runs skip the build when nothing has- changed. Sets ``SANDBOX_LOCAL_SKILLS_HOST_PATH`` so ``DockerSandbox`` can- pick it up when provisioning containers — keeping the base image stable- while letting eval authors iterate on skills without rebuilding it.-- Depends on ``_sandbox_settings`` so the ``DEBUG=True`` override is active- when the skill renderer runs — some template helpers (e.g. HogQL example- rendering) guard on that setting.- """- cache = LocalSkillsCache()- dist_dir = cache.ensure_built()- previous = os.environ.get(ENV_LOCAL_SKILLS_HOST_PATH)- os.environ[ENV_LOCAL_SKILLS_HOST_PATH] = str(dist_dir)- try:- yield dist_dir- finally:- if previous is None:- os.environ.pop(ENV_LOCAL_SKILLS_HOST_PATH, None)- else:- os.environ[ENV_LOCAL_SKILLS_HOST_PATH] = previous--[email protected](scope="session", autouse=True)-def _temporal_test_server() -> Generator[tuple[str, str, str]]:- """Start an isolated Temporal dev server for sandboxed eval workflows."""- loop = asyncio.new_event_loop()- temporal_namespace = settings.TEMPORAL_NAMESPACE- env: WorkflowEnvironment | None = None-- try:- env = loop.run_until_complete(- WorkflowEnvironment.start_local(- namespace=temporal_namespace,- ip="127.0.0.1",- port=None,- dev_server_log_level="warn",- )- )- host, port = _temporal_client_target(env)- logger.info("Sandboxed eval Temporal server ready at %s:%s namespace=%s", host, port, temporal_namespace)-- yield host, port, temporal_namespace- finally:- if env is not None:- logger.info("Shutting down sandboxed eval Temporal server")- loop.run_until_complete(env.shutdown())- loop.close()--[email protected](scope="session", autouse=True)-def _sandbox_settings(- _django_live_server: object,- _llm_gateway: object,- _temporal_test_server: tuple[str, str, str],-) -> Generator[None]:- """Configure Django settings required by the sandbox/temporal activities.-- All URLs use ``host.docker.internal`` so they're reachable from inside- Docker sandbox containers. Points at the in-process Django live server- which shares the test database.-- Temporal is pointed at a per-session local dev server and task queue. That- keeps eval workflows away from any dev worker already polling the normal- tasks queue in the developer's environment.-- Also patches ``posthoganalytics.feature_enabled`` to return True for all- flags so workflow guards pass.- """- from unittest.mock import patch-- from django.test import override_settings-- # Docker containers reach the host via host.docker.internal- docker_api_url = f"http://host.docker.internal:{DJANGO_LIVE_PORT}"- docker_llm_gateway_url = f"http://host.docker.internal:{LLM_GATEWAY_PORT}"- temporal_host, temporal_port, temporal_namespace = _temporal_test_server- temporal_task_queue = f"sandboxed-evals-tasks-{os.getpid()}"-- import posthoganalytics-- with (- override_settings(- DEBUG=True, # Required for sandbox URL validation to allow http://localhost- # The sandbox container reaches the Django live server with a- # ``Host: host.docker.internal`` header; allow it (test-only) so the- # agent's event-ingest stream isn't rejected with an invalid-host 400.- ALLOWED_HOSTS=["*"],- SANDBOX_PROVIDER="docker",- SANDBOX_API_URL=docker_api_url,- SANDBOX_LLM_GATEWAY_URL=docker_llm_gateway_url,- SANDBOX_MCP_URL=f"http://host.docker.internal:{MCP_PORT}/mcp",- TEMPORAL_HOST=temporal_host,- TEMPORAL_PORT=temporal_port,- TEMPORAL_NAMESPACE=temporal_namespace,- TEMPORAL_CLIENT_CERT=None,- TEMPORAL_CLIENT_KEY=None,- TASKS_TASK_QUEUE=temporal_task_queue,- ),- patch.object(posthoganalytics, "feature_enabled", return_value=True),- ):- yield---# MCP mode selection — see `--mcp-mode` option in ee/hogai/eval/conftest.py.-# The PostHog MCP server can register tools individually ("tools" mode) or-# wrap them all behind a single `exec` tool ("cli" mode). Each sandboxed-# eval is parametrized across both modes by default so we can compare-# agent behavior across the two surfaces in a single run.---def pytest_generate_tests(metafunc):- """Parametrize sandboxed tests across the requested MCP execution modes.-- Triggered for any test whose dependency graph touches ``mcp_mode`` —- which covers every test under ``ee/hogai/eval/sandboxed/`` because the- autouse ``_apply_mcp_mode`` fixture depends on it.- """- if "mcp_mode" not in metafunc.fixturenames:- return- option = metafunc.config.getoption("--mcp-mode")- if option == "both":- modes = ["tools", "cli"]- else:- modes = [option]- metafunc.parametrize("mcp_mode", modes)--[email protected](autouse=True)-def _apply_mcp_mode(mcp_mode, _sandbox_settings):- """Per-test override that pins the MCP execution mode.-- Appends ``?mode=<mcp_mode>`` to ``SANDBOX_MCP_URL`` so the MCP server- registers either every tool individually (``tools``) or wraps them all- in a single ``posthog`` exec tool (``cli``). The explicit query- parameter wins over the feature-flag + client-profile heuristic in- ``services/mcp/src/mcp.ts``, and the MCP service runs in a Cloudflare- Worker outside this Python process — so a Python-side- ``posthoganalytics.feature_enabled`` patch wouldn't reach it anyway.- """- from django.test import override_settings-- base = settings.SANDBOX_MCP_URL or ""- sep = "&" if "?" in base else "?"- moded_url = f"{base}{sep}mode={mcp_mode}"-- with override_settings(SANDBOX_MCP_URL=moded_url):- yield mcp_mode--[email protected](scope="session", autouse=True)-def _terminate_stale_workflows(_sandbox_settings):- """Terminate any stale temporal workflows left over from previous test runs.-- Without this, the in-process worker wastes time processing old workflows- (creating sandboxes for runs that no longer exist in the test database),- delaying the actual eval workflow by 30-60 seconds.- """- import asyncio as _asyncio-- from posthog.temporal.common.client import async_connect-- async def _terminate():- client = await async_connect()- terminated = 0- async for wf in client.list_workflows(f'TaskQueue="{settings.TASKS_TASK_QUEUE}"'):- try:- handle = client.get_workflow_handle(wf.id, run_id=wf.run_id)- await handle.terminate(reason="eval harness cleanup")- terminated += 1- except Exception:- pass- if terminated:- logger.info("Terminated %d stale temporal workflows", terminated)-- _asyncio.run(_terminate())- yield--[email protected](scope="session", autouse=True)-def _temporal_worker(_sandbox_settings, _terminate_stale_workflows, _sandboxed_eval_database_access):- """Start an in-process temporal worker for the tasks queue.-- Mirrors the dev worker (``manage.py start_temporal_worker``) using- ``create_worker``. Runs in a daemon thread. DB access is unblocked so- temporal activities can use the Django ORM against the test database.- """- loop = asyncio.new_event_loop()- stop_event = asyncio.Event()- ready_event = threading.Event()-- async def _run():- logger.info(- "Starting eval temporal worker (%s:%s queue=%s)",- settings.TEMPORAL_HOST,- settings.TEMPORAL_PORT,- settings.TASKS_TASK_QUEUE,- )- managed = await create_worker(- host=settings.TEMPORAL_HOST,- port=int(settings.TEMPORAL_PORT),- metrics_port=0,- namespace=settings.TEMPORAL_NAMESPACE,- task_queue=settings.TASKS_TASK_QUEUE,- workflows=TASKS_WORKFLOWS,- activities=TASKS_ACTIVITIES, # type: ignore[arg-type]- max_concurrent_workflow_tasks=100,- max_concurrent_activities=100,- enable_combined_metrics_server=False,- )- logger.info("Eval temporal worker created")- ready_event.set()- worker_task = asyncio.ensure_future(managed.run())- await stop_event.wait()- logger.info("Shutting down eval temporal worker")- await managed.shutdown()- worker_task.cancel()-- thread = threading.Thread(target=loop.run_until_complete, args=(_run(),), daemon=True)- thread.start()-- if not ready_event.wait(timeout=30):- pytest.fail(- f"Temporal worker failed to start within 30s. "- f"Is temporal running at {settings.TEMPORAL_HOST}:{settings.TEMPORAL_PORT}?"- )-- logger.info("Eval temporal worker ready")- yield-- loop.call_soon_threadsafe(stop_event.set)- thread.join(timeout=10)--[email protected](scope="session", autouse=True)-def _llm_gateway(_django_live_server, sandboxed_demo_data):- """Start the LLM gateway as a subprocess.-- Mirrors ``bin/start-llm-gateway``: runs uvicorn on a non-default port.- The sandbox's agent-server uses this to proxy LLM calls to Anthropic.- """- gateway_dir = Path(settings.BASE_DIR) / "services" / "llm-gateway"- venv_dir = gateway_dir / ".venv"- uvicorn_bin = venv_dir / "bin" / "uvicorn"-- if not uvicorn_bin.exists():- pytest.fail(- f"LLM gateway venv not found at {venv_dir}. "- "Run `bin/start-llm-gateway` once or `cd services/llm-gateway && uv venv .venv && uv pip install -e .`"- )- # The LLM gateway uses pydantic BaseSettings with env_prefix="LLM_GATEWAY_".- # DATABASE_URL and LLM_GATEWAY_ANTHROPIC_API_KEY come from the parent env- # (e.g. .env.local / op run). We need to point it at the test database.- from django.db import connections-- conn = connections["default"]- # After django_db_setup runs, settings_dict["NAME"] is already rewritten to- # the test DB name (pytest-django does this in-place), so don't re-prefix it.- db_name = conn.settings_dict["NAME"]- db_user = conn.settings_dict.get("USER", "posthog")- db_password = conn.settings_dict.get("PASSWORD", "posthog")- db_host = conn.settings_dict.get("HOST", "localhost")- db_port = conn.settings_dict.get("PORT", "5432")- test_db_url = f"postgres://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}"-- env = {- **os.environ,- "UV_PROJECT_ENVIRONMENT": str(venv_dir),- "LLM_GATEWAY_DATABASE_URL": test_db_url,- "LLM_GATEWAY_DEBUG": "true",- "LLM_GATEWAY_TEAM_RATE_LIMIT_MULTIPLIERS": '{"1": 10}',- "LLM_GATEWAY_POSTHOG_HOST": str(_django_live_server),- }-- logger.info("Starting LLM gateway on port %d", LLM_GATEWAY_PORT)- _, stop = _LONG_LIVED_SUBPROCESSES.start(- name="LLM gateway",- port=LLM_GATEWAY_PORT,- cmd=[- str(uvicorn_bin),- "llm_gateway.main:app",- "--host",- "0.0.0.0",- "--port",- str(LLM_GATEWAY_PORT),- ],- cwd=gateway_dir,- env=env,- log_prefix="llm-gateway",- )-- logger.info("LLM gateway ready on port %d", LLM_GATEWAY_PORT)- yield-- stop()- logger.info("LLM gateway stopped")--[email protected](scope="session", autouse=True)-def _mcp_server(_django_live_server, _sandbox_settings):- """Start the MCP server as a subprocess for the eval session.-- Pointed at the in-process Django live server (which uses the test DB).- Uses a non-default port to avoid conflicts with a running dev MCP server.-- Runs the Node-native Hono server via ``pnpm dev:hono``. In production the- Cloudflare Worker is now a proxy that forwards to a regional Hono- deployment, so Hono is what real users hit.- """- mcp_dir = Path(settings.BASE_DIR) / "services" / "mcp"- if not (mcp_dir / "node_modules").exists():- logger.info("Installing MCP server dependencies")- subprocess.run(["pnpm", "install", "--frozen-lockfile"], cwd=mcp_dir, check=True, capture_output=True)-- api_url = str(_django_live_server)-- # The Hono server reads config directly from process env — no wrangler- # --var wiring needed. PORT picks the listen port; the dev:hono script- # bundles via esbuild then spawns Node on the bundle.- env = {- **os.environ,- "POSTHOG_API_BASE_URL": api_url,- "MCP_APPS_BASE_URL": f"http://localhost:{MCP_PORT}",- "POSTHOG_MCP_APPS_ANALYTICS_BASE_URL": api_url,- "NODE_ENV": "development",- "PORT": str(MCP_PORT),- "HOST": "0.0.0.0",- # The MCP server evaluates feature flags via posthog-node, which is disabled- # here (no POSTHOG_ANALYTICS_* config), so every flag would resolve false.- # Force flag-gated behavior on for evals via the dev/test-only override seam- # (honored only when NODE_ENV is explicitly development/test — set above).- # No flags currently need forcing on.- "FEATURE_FLAG_OVERRIDES": json.dumps({}),- }-- logger.info("Starting MCP server (Hono runtime) on port %d (API: %s)", MCP_PORT, api_url)- _, stop = _LONG_LIVED_SUBPROCESSES.start(- name="MCP server",- port=MCP_PORT,- cmd=["pnpm", "dev:hono"],- cwd=mcp_dir,- env=env,- log_prefix="mcp",- )-- logger.info("MCP server ready on port %d", MCP_PORT)- yield-- stop()- logger.info("MCP server stopped")---class SandboxedDemoData:- """Session-scoped holder for master demo seed + per-case team factory.-- One instance per pytest session: seeds the master Hedgebox team (or reuses- a healthy one), then produces a fresh isolated ``CustomPromptSandboxContext``- for every eval case via ``make_context(label)``. Each call copies the master- into a brand-new org/team/user with its own core memory and tasks-API- access, so concurrent eval cases can't pollute each other's state.- """-- def __init__(self, master_team_id: int, django_db_blocker, agent_model: str | None = None):- self.master_team_id = master_team_id- self._django_db_blocker = django_db_blocker- self.agent_model = agent_model-- def make_context(self, case_label: str) -> CustomPromptSandboxContext:- from django.apps import apps-- CodeInvite = apps.get_model("tasks", "CodeInvite")- CodeInviteRedemption = apps.get_model("tasks", "CodeInviteRedemption")-- org, team, user = copy_demo_data_to_new_team(self.master_team_id, self._django_db_blocker, label=case_label)- create_core_memory(team, self._django_db_blocker)- with self._django_db_blocker.unblock():- invite, _ = CodeInvite.objects.get_or_create(code="eval-harness", max_redemptions=0, is_active=True)- CodeInviteRedemption.objects.get_or_create(invite_code=invite, user=user, organization=org)- logger.info("Case %r assigned team_id=%d user_id=%d", case_label, team.id, user.id)- return CustomPromptSandboxContext(- team_id=team.id,- user_id=user.id,- repository="posthog/hedgebox",- model=self.agent_model,- )---# Event-level properties the error-tracking ``searchQuery`` test cases match on-# (see ``products/error_tracking/backend/hogql_queries/error_tracking_query_runner_utils.py``).-# These are stored as JSON arrays (``["TypeError"]``); without materialized-# columns the bare ``properties.$exception_types`` lookup goes through-# ``JSONExtractString`` which returns ``""`` for non-string JSON values, so-# ``searchQuery`` filtering on these properties silently never matches anything.-# Materializing and backfilling once per session makes the sandbox behave like-# prod for error-tracking searchQuery, including reused local ClickHouse state-# where the columns already exist but older demo rows still need values.-_EVAL_MATERIALIZED_EVENT_PROPERTIES: tuple[str, ...] = (- "$exception_types",- "$exception_values",-)---def _ensure_event_search_columns_materialized(django_db_blocker) -> None:- from ee.clickhouse.materialized_columns.columns import (- backfill_materialized_columns,- get_materialized_columns,- materialize,- )-- with django_db_blocker.unblock():- existing_columns = get_materialized_columns("events")- columns = []- for property_name in _EVAL_MATERIALIZED_EVENT_PROPERTIES:- column = existing_columns.get((property_name, "properties"))- if column is None:- column = materialize("events", property_name)- columns.append(column)- backfill_materialized_columns("events", columns, timedelta(days=180))--[email protected](scope="session", autouse=True)-def sandboxed_demo_data(- set_up_evals, # noqa: F811- django_db_blocker,- pytestconfig,-) -> SandboxedDemoData:- """Seed the master Hedgebox team (once) and expose a per-case context factory."""- from posthog.clickhouse.client import sync_execute-- master_team_id = ensure_master_demo_team(django_db_blocker)- _ensure_event_search_columns_materialized(django_db_blocker)- with django_db_blocker.unblock():- rows = sync_execute(- "SELECT event, count() FROM events WHERE team_id = %(team_id)s GROUP BY event ORDER BY 2 DESC LIMIT 20",- {"team_id": master_team_id},- )- logger.info("Master demo ready: team_id=%d event_counts=%s", master_team_id, rows)-- agent_model = pytestconfig.getoption("--agent-model")- logger.info("Sandboxed eval agent model pinned to %r", agent_model)- return SandboxedDemoData(- master_team_id=master_team_id,- django_db_blocker=django_db_blocker,- agent_model=agent_model,- )--[email protected](scope="session")-def posthog_client() -> Generator:- """PostHog analytics client for capturing eval traces and evaluation events to US production."""- from posthog.ph_client import get_client-- client = get_client("US")- yield client- if client:- client.shutdown()---def pytest_terminal_summary(terminalreporter, exitstatus, config): # noqa: ARG001- """Surface the local eval log directories at the end of a test session.-- Mirrors the Braintrust URL reporter pattern in ``ee/hogai/eval/conftest.py`` —- gives an agent iterating on failing eval cases a single, obvious place to- look for raw agent output without digging through per-test stdout capture.- """- log_dirs = getattr(config, "_sandboxed_eval_log_dirs", None)- if not log_dirs:- return-- writer = terminalreporter- writer.write_sep("=", "sandboxed eval logs")- writer.write_line("Raw agent logs written to:")- for path in sorted(log_dirs):- writer.write_line(f" {path}")- writer.write_line("Files per case: <case>.jsonl (raw), <case>.artifacts.json, <case>.summary.txt")diff --git a/ee/hogai/eval/sandboxed/scorers/__init__.py b/ee/hogai/eval/sandboxed/scorers/__init__.pydeleted file mode 100644index 86d6d90f3dda..000000000000--- a/ee/hogai/eval/sandboxed/scorers/__init__.py+++ /dev/null@@ -1,15 +0,0 @@-from ee.hogai.eval.sandboxed.log_parser import LogParser, normalize_tool_name--from .deterministic import ExitCodeZero, LastToolCallNot, NoToolCall, RequiredToolCall-from .tracing import TracedScorer, wrap_scorers--__all__ = [- "ExitCodeZero",- "LastToolCallNot",- "LogParser",- "NoToolCall",- "RequiredToolCall",- "TracedScorer",- "normalize_tool_name",- "wrap_scorers",-]diff --git a/ee/hogai/eval/sandboxed/sql/__init__.py b/ee/hogai/eval/sandboxed/sql/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/ee/hogai/test/eval/test_acp_log_model.py b/ee/hogai/test/eval/test_acp_log_model.pydeleted file mode 100644index cf2a70b4dd44..000000000000--- a/ee/hogai/test/eval/test_acp_log_model.py+++ /dev/null@@ -1,91 +0,0 @@-from __future__ import annotations--import json--import pytest--from ee.hogai.eval.sandboxed.acp_log import parse_log---def _line(payload: dict) -> str:- return json.dumps({"type": "notification", "timestamp": "2026-04-29T08:42:29.620Z", "notification": payload})--- "lines, expected_model",- [- pytest.param(- [- _line(- {- "jsonrpc": "2.0",- "id": 1,- "method": "session/new",- "params": {"model": "anthropic/claude-opus-4-7"},- }- ),- ],- "anthropic/claude-opus-4-7",- id="captures_from_session_new_params",- ),- pytest.param(- [- _line({"jsonrpc": "2.0", "id": 1, "method": "session/new", "params": {"cwd": "/tmp"}}),- _line(- {- "jsonrpc": "2.0",- "id": 1,- "result": {"sessionId": "s1", "models": {"currentModelId": "claude-sonnet-4-6"}},- }- ),- ],- "claude-sonnet-4-6",- id="falls_back_to_result_currentModelId",- ),- pytest.param(- [- _line(- {- "jsonrpc": "2.0",- "id": 1,- "method": "session/new",- "params": {"model": "anthropic/claude-opus-4-7"},- }- ),- _line(- {- "jsonrpc": "2.0",- "id": 1,- "result": {"sessionId": "s1", "models": {"currentModelId": "claude-sonnet-4-6"}},- }- ),- ],- "anthropic/claude-opus-4-7",- id="prefers_params_over_result_when_both_present",- ),- pytest.param(- [- _line({"jsonrpc": "2.0", "id": 1, "method": "session/prompt", "params": {}}),- ],- "",- id="empty_when_no_session_new",- ),- pytest.param(- [- _line({"jsonrpc": "2.0", "id": 1, "method": "session/new", "params": {"model": ""}}),- _line(- {- "jsonrpc": "2.0",- "id": 1,- "result": {"sessionId": "s1", "models": {"currentModelId": "claude-haiku-4-5"}},- }- ),- ],- "claude-haiku-4-5",- id="ignores_empty_string_model_and_falls_back",- ),- ],-)-def test_parse_log_extracts_agent_model(lines: list[str], expected_model: str) -> None:- parsed = parse_log("\n".join(lines))- assert parsed.model == expected_modeldiff --git a/hogli.yaml b/hogli.yamlindex 17bbce02f937..82c4896be41e 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -776,6 +776,14 @@ tests:test:quarantine:click: hogli_commands.quarantine.cli:quarantinedescription: Manage .test_quarantine.json — quarantine flaky tests so they stop blocking CI+ evals:+ cmd: python -m products.posthog_ai.eval_harness.harness+ description: Run evals — sandboxed agent and one-shot suites (extra args pass through, e.g. `sql` or `cli_mcp --provider modal`)+ needs_secrets: true+ evals:sandboxed:+ cmd: python -m products.posthog_ai.eval_harness.harness+ description: Alias of `evals` (kept for back-compat)+ needs_secrets: truequality:lint:cmd: ./bin/ruff.sh check . && pnpm --filter=@posthog/frontend run lintdiff --git a/products/posthog_ai/eval_harness/README.md b/products/posthog_ai/eval_harness/README.mdnew file mode 100644index 000000000000..c5760dcac59f--- /dev/null+++ b/products/posthog_ai/eval_harness/README.md@@ -0,0 +1,240 @@+# Sandboxed agent evals++These evals run the real coding agent inside a real sandbox against a seeded Hedgebox project, then score what it did.+Each eval case gets its own isolated org/team/user, so cases never see each other's state.++Unlike `ee/hogai/eval/ci/`, this tree does **not** run under pytest.+It runs on a standalone harness that boots the shared infrastructure once (test database, Django live server, LLM gateway, MCP server, Temporal) and then runs every selected suite concurrently.+See [`harness/README.md`](harness/README.md) for how that works internally.++The harness also hosts non-sandboxed suite kinds — see [Suite kinds](#suite-kinds).+A run boots only the infrastructure its selected suites need, so a one-shot-only run starts no sandbox provider, Temporal, live server, LLM gateway, or MCP server.++Two other docs sit next to this one:++- [`../evals/AGENTS.md`](../evals/AGENTS.md) is the Hedgebox dataset reference. Read it before writing eval cases: your `expected` values and scorers must match that taxonomy exactly.+- [`harness/AGENTS.md`](harness/AGENTS.md) lists the invariants to preserve when changing the harness itself.++## Running++```bash+hogli evals [SELECTOR ...] [flags]+```++`hogli evals:sandboxed` is a back-compat alias of `hogli evals`; both run the same harness.++Run it from a flox shell — the personhog build needs flox's Rust toolchain (`cargo`, `pkg-config`, OpenSSL), and outside it the preflight build fails.++Or invoke the harness module directly:++```bash+python -m products.posthog_ai.eval_harness.harness [SELECTOR ...] [flags]+```++No manual env sourcing is needed on either path.+The harness loads the repo-root `.env` itself (shell values win), and `hogli evals` additionally layers in `.env.local` / `.env.development` / `.env.services` through hogli's standard env loading — including 1Password resolution when `.env.local` holds `op://` references.+Before any infrastructure boots, a preflight validates that the required variables are set and fails with a one-line fix per missing variable.+Which variables are required depends on the eval engine and the selected suites' kinds: the braintrust engine (the default, and only one today) requires `BRAINTRUST_API_KEY` on every run — it is the engine's own `required_env()`, not a core harness variable; sandboxed suites add `SANDBOX_JWT_PRIVATE_KEY` and `LLM_GATEWAY_ANTHROPIC_API_KEY`; one-shot suites add `LLM_GATEWAY_ANTHROPIC_API_KEY` (used directly, no gateway).++Selectors are substrings matched against a suite id of the form `<domain>/<module>::<fn>`, for example `experiments`, `sql`, or `eval_lifecycle_skills`.+Omit them to run every suite.+An unmatched selector fails immediately, before anything is provisioned.++The harness needs the Rust toolchain (`cargo`, provided by the flox shell): person and group reads go through personhog with no ORM fallback, so it builds and runs `personhog-replica` + `personhog-router` from `rust/` against the test persons DB.+The first build compiles the crates and can take several minutes; later builds are incremental no-ops.++```bash+# every suite, docker sandboxes, 4 at a time+python -m products.posthog_ai.eval_harness.harness++# two domains+python -m products.posthog_ai.eval_harness.harness experiments sql++# one suite, one case+python -m products.posthog_ai.eval_harness.harness eval_sql --eval churn++# remote sandboxes, every case at once+python -m products.posthog_ai.eval_harness.harness --provider modal++# print the suite ids and exit+python -m products.posthog_ai.eval_harness.harness --list+```++| Flag | Meaning |+| -------------------------------- | -------------------------------------------------------------------------------- |+| `--eval <substr>` | Only run cases whose name contains the substring. |+| `--provider {docker,modal}` | Where sandboxes run. Default `docker`. |+| `--max-sandboxes N` | Cap concurrently live sandboxes across all suites. |+| `--agent-model <model>` | Model the sandboxed agent runs against, pinned for stable cross-run comparison. |+| `--agent-runtime {claude,codex}` | Agent runtime serving the model. Default `claude`. |+| `--reasoning-effort <effort>` | Agent reasoning effort; valid values depend on runtime+model. |+| `--keep-sandbox-containers` | Skip the end-of-run Docker sweep, to inspect a leftover container. Docker only. |+| `--rebuild-sandbox-image` | Force a rebuild of the `posthog-sandbox-base` image before the run. Docker only. |+| `--create-db` | Rebuild the eval test database instead of reusing it. |+| `--case-timeout <seconds>` | Agent-run budget (minimum 1 second), started after the case's team setup. |+| `--trials N` | Run every case N times (Braintrust trials), for variance on stochastic agents. |+| `--fail-under <fraction>` | Exit nonzero when the mean score across all experiments falls below this (0-1). |+| `--list` | Print the discovered suite ids (with their kinds) and exit. |++Sandbox-only flags (`--provider`, `--max-sandboxes`, `--agent-runtime`, `--reasoning-effort`, `--keep-sandbox-containers`, `--rebuild-sandbox-image`) are rejected in preflight when no selected suite is sandboxed, instead of being silently ignored.++`EXPORT_EVAL_RESULTS=1` additionally appends one structured JSON summary per experiment to `eval_results.jsonl`.+The full plain-text run transcript is always written without this setting.++### Codex runtime++`--agent-runtime codex` runs the same agent-server with OpenAI's Codex harness instead of Claude, defaulting the model to `gpt-5.5`.+It requires `LLM_GATEWAY_OPENAI_API_KEY` in the environment (checked by preflight), which the harness's LLM gateway uses to proxy the agent's OpenAI calls.+Experiment names don't change with the runtime — each Braintrust experiment records `agent_runtime` and `agent_model` in its metadata instead — so compare cross-run scores within one runtime.++## Providers++Prefer Modal for multi-case sandboxed evals when its prerequisites are available.+Remote sandboxes can run in parallel without consuming local Docker memory, so they usually finish faster.+Use Docker for small smoke tests or when remote access is unavailable.++**docker** (default) runs sandboxes as local containers, so a Docker daemon must be reachable.+Each container defaults to 16 GB, so host RAM is what bounds concurrency: the default cap is 4, and raising `--max-sandboxes` needs a big host.++Every docker run verifies the `posthog-sandbox-base` image is fresh before any case starts: it rebuilds when `@posthog/agent` has published a newer version than the one baked into the image, or when the Dockerfile changed since the image was built.+An unchanged image passes the check in under a second, and even a rebuild is mostly layer-cached — only the npm install layer onward re-runs when the agent version moved.+When npm is unreachable the check warns and reuses the existing image instead of failing the run.+`--rebuild-sandbox-image` forces the rebuild regardless.+(The modal DEBUG image is rebuilt by Modal whenever the Dockerfile or build context changes, but a new `@posthog/agent` publish alone does not invalidate it — a known limitation.)++**modal** runs sandboxes remotely.+Modal's network cannot reach `localhost`, so the harness starts ngrok tunnels itself and points the sandbox at the public URLs.+Eval sandboxes run in the dedicated `posthog-sandbox-evals` Modal app, separate from production and local development sandboxes.+The manual tunnel setup in [`docs/internal/sandboxes-setup-guide.md`](../../../../docs/internal/sandboxes-setup-guide.md) is therefore not needed for evals.+The first modal run pays a one-time remote image build; later runs reuse the cached image until the skills or build context change.++Modal prerequisites, all checked by preflight before anything boots:++- `ngrok` on `PATH`, plus an authtoken (`NGROK_AUTHTOKEN`, or `ngrok config add-authtoken <token>`). Three simultaneous tunnels need a paid ngrok plan; Cloudflare Tunnel is the free alternative.+- Modal credentials: `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET`, or a `~/.modal.toml` from `modal token new`.+- `SANDBOX_JWT_PRIVATE_KEY` in the environment. The dev key ships in `.env.example`; the harness auto-loads it from `.env`.++Sandboxes are unbounded by default on modal, meaning every case can hold one at once.+`--max-sandboxes N` is the cost knob.++Each case waits for its workflow to terminate the sandbox, then runs a tag-scoped Modal sweep as a safety net.+When the whole run ends, the harness sweeps the Modal app again for its own leftover sandboxes, so a crashed or interrupted run doesn't leave sandboxes billing until their TTL.+The sweep is scoped to this run's own tasks (matched by the `task_id` sandbox tag), so a second eval run sharing the same Modal app keeps its sandboxes.++## Concurrency++Every selected suite runs concurrently on one event loop, and a global semaphore bounds the number of live sandboxes across all of them.+Selecting more suites therefore increases throughput without increasing peak load.++A separate semaphore covers the full per-case team setup, including the demo-data clone and optional setup hook.+It allows one setup at a time on ordinary local machines and four when either `CODER` or `CI` is set.+These phases can issue large ClickHouse copies or direct inserts, so the independent limit protects ClickHouse from RAM exhaustion even when Modal sandbox capacity is unbounded while letting managed environments prepare cases faster.+When object storage is enabled, setup also validates the master warehouse and clones team-scoped warehouse metadata for each case while reusing the master's immutable CSV files.+When a setup completes, its slot becomes available to the next case while the prepared case runs its agent.++A case holds a sandbox slot only for the window it actually needs one: team setup and the agent run.+Log parsing, Braintrust span building, trace emission, and scoring all happen after the slot is released.+The per-case timeout starts after team setup, so neither sandbox nor setup queueing consumes the agent's budget.++## Suite kinds++Each eval module declares how its suites execute with a module-level `SUITE_KIND` (from `products.posthog_ai.eval_harness.harness.requirements`); a module without one is sandboxed.++| Kind | Marker | What runs per case | Infrastructure booted |+| ------------------- | --------------------------------- | --------------------------------------- | ----------------------------------- |+| sandboxed (default) | none, or `SuiteKind.SANDBOXED` | the real coding agent in a real sandbox | everything |+| one-shot | `SUITE_KIND = SuiteKind.ONE_SHOT` | one in-process model invocation | test database, personhog, demo data |++The harness boots the union of what the selected suites require, and a suite that under-declares its kind fails loudly when its runner finds the infrastructure it needed was never booted.++## Adding an eval suite++The `/writing-evals` skill ([.agents/skills/writing-evals](../../../../.agents/skills/writing-evals/SKILL.md)) covers the full authoring workflow — cases, seeders, synthesizers, scorer patterns, and verification.+The short version:++There is no registry. Suites are discovered by convention from two root sets:++- `products/posthog_ai/evals/<domain>/` — the built-in tree, reserved for Max and other agent suites.+- `products/<product>/evals/` — where a product owns its eval suites (plural `evals/`; the singular `products/signals/eval/` is an unrelated pytest tree the harness ignores). Suite id is `<product>/<module>::<fn>`, import path `products.<product>.evals.<module>`.++New product-owned evals belong under `products/<product>/evals/`; that directory needs no pytest-collection exclusion, since pytest's default `python_files` matches `test_*.py` and never collects `eval_*.py` there.++1. Create `products/posthog_ai/evals/<domain>/eval_<name>.py` (or `products/<product>/evals/eval_<name>.py`). The directory becomes the suite's domain.+2. Write one or more coroutines named `eval_*` taking a single `ctx: EvalContext`.+3. Build a list of `SandboxedEvalCase` and hand it to `SandboxedPrivateEval` or `SandboxedPublicEval` along with your scorers and `ctx=ctx`.++```python+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+++async def eval_my_thing(ctx: EvalContext) -> None:+ await SandboxedPrivateEval(+ experiment_name="sandboxed-my-thing-cli",+ cases=[SandboxedEvalCase(name="my_case", prompt="...")],+ scorers=[],+ ctx=ctx,+ )+```++The harness automatically adds the `ExitCodeZero` scorer to every sandboxed experiment.+Do not add it to a suite's `scorers` list; the harness rejects duplicates.++For a one-shot suite, declare the kind, build `BaseEvalCase`s, and pass a task function to `OneShotPrivateEval` / `OneShotPublicEval` — the task runs once per case under the global one-shot limiter and returns the scorer `output` dict directly:++```python+from products.posthog_ai.eval_harness.config import BaseEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.harness.requirements import SuiteKind+from products.posthog_ai.eval_harness.one_shot import OneShotPrivateEval++SUITE_KIND = SuiteKind.ONE_SHOT+++async def eval_my_generation(ctx: EvalContext) -> None:+ async def task(case: BaseEvalCase, task_ctx: EvalContext) -> dict:+ return {"answer": ...} # one model invocation; JSON-serializable++ await OneShotPrivateEval(+ experiment_name="my-generation",+ cases=[BaseEvalCase(name="my_case", prompt="...")],+ scorers=[...],+ task=task,+ ctx=ctx,+ )+```++Bundle related cases into one suite function rather than splitting them across many.+One suite is one Braintrust experiment, which is what makes cross-case comparison and `--eval` filtering useful.++`experiment_name` is the Braintrust experiment key, so changing it starts a fresh history.+Existing suites end in `-cli` because the MCP server serves the `cli` surface; that suffix is kept so history lines up with earlier runs.++Confirm discovery picked your suite up:++```bash+python -m products.posthog_ai.eval_harness.harness --list | grep my_thing+```++## Output++Progress lines use stable labels as cases and suites start or finish: `SUITE START`, `EXPERIMENT START`, `CASE DONE`, `EXPERIMENT DONE`, and `SUITE DONE`.+Only the overall run uses `PASS` or `FAIL`, so a suite with a low behavioral score still reads as completed rather than passed.+The final summary gives labeled suite and case totals, the score gate, total duration, and one block per experiment with scorer averages, PostHog and Braintrust URLs, and the agent-log directory.+A crashed suite is labeled `CRASH`, includes its traceback in the summary, and makes the run exit nonzero without taking down the other suites.++Every real eval invocation mirrors its complete stdout and stderr to:++```text+products/posthog_ai/eval_harness/logs/harness/<timestamp>_<id>.log+```++The line before the path identifies it as the full stdout/stderr run transcript.+The final terminal line is the unlabeled absolute path, with no output after it, so a person or agent can reliably open it.+The transcript itself ends with the same path, and `logs/harness/latest.log` points to the newest transcript.+Suite listing (`--list`) and argument errors do not create transcripts.++Raw per-case agent logs land on local disk (`<case>.jsonl`, `<case>.artifacts.json`, `<case>.summary.txt`), which is usually the fastest way to see what the agent actually did.++`SandboxedPrivateEval` runs with `no_send_logs`, so its summary has no Braintrust URL; the local logs are the record.diff --git a/products/posthog_ai/eval_harness/__init__.py b/products/posthog_ai/eval_harness/__init__.pynew file mode 100644index 000000000000..89aef1fdb4db--- /dev/null+++ b/products/posthog_ai/eval_harness/__init__.py@@ -0,0 +1,6 @@+"""Standalone eval harness for PostHog AI agents.++Run via ``python -m products.posthog_ai.eval_harness.harness`` (``hogli evals``).+Built-in suites live in ``products/posthog_ai/evals/``; product-owned suites in+``products/<product>/evals/``.+"""diff --git a/ee/hogai/eval/sandboxed/acp_log.py b/products/posthog_ai/eval_harness/acp_log.pysimilarity index 76%rename from ee/hogai/eval/sandboxed/acp_log.pyrename to products/posthog_ai/eval_harness/acp_log.pyindex ab8bb1b71ebf..8115a2de149f 100644--- a/ee/hogai/eval/sandboxed/acp_log.py+++ b/products/posthog_ai/eval_harness/acp_log.py@@ -46,8 +46,10 @@ class ParsedLog:first_timestamp: str = ""last_timestamp: str = ""model: str = ""- """Agent model resolved from the ACP ``session/new`` exchange — either the- request's ``params.model`` or the response's ``result.models.currentModelId``.+ """Agent model resolved from the ACP ``session/new`` exchange — the request's+ ``params.model``, the response's ``result.models.currentModelId``, or the+ response's ``configOptions`` entry with ``id == "model"`` (the only channel+ the posthog claude/codex adapters actually populate).Empty when the log predates this capture (callers should fall back)."""@property@@ -106,6 +108,7 @@ class AcpLogParser:self._gen_start_ts: str = "" # When the model call was invokedself._gen_last_output_ts: str = "" # Timestamp of most recent output blockself._last_tool_result_ts: str = "" # Drives next gen's start_ts+ self._pending_gen_usage: dict[str, int] = {} # Latest _posthog/usage_update, consumed on flushdef parse(self, raw_log: str) -> ParsedLog:for line in raw_log.strip().split("\n"):@@ -153,6 +156,9 @@ class AcpLogParser:if self._handle_result(entry_result):return # end_turn consumed this entry+ if method == "_posthog/usage_update":+ self._on_usage_update(notification)+ returnif method == "_posthog/console":self._on_console(notification, ts)return@@ -175,6 +181,15 @@ class AcpLogParser:current = models_block.get("currentModelId")if isinstance(current, str) and current:self._result.model = current+ if not self._result.model:+ # The posthog adapters don't fill result.models; the model lives in the+ # session/new result's configOptions picker instead.+ for option in entry_result.get("configOptions") or []:+ if isinstance(option, dict) and option.get("id") == "model":+ current_value = option.get("currentValue")+ if isinstance(current_value, str) and current_value:+ self._result.model = current_value+ breakusage = entry_result.get("usage")if isinstance(usage, dict):self._last_token_usage = {@@ -190,6 +205,29 @@ class AcpLogParser:return Truereturn False+ def _on_usage_update(self, notification: dict) -> None:+ """Record per-model-call token usage for the generation currently being built.++ The codex adapter reports each call's tokens in ``params.usage`` here — its+ end_turn result carries no usage. The claude adapter's variant of this+ notification has no ``usage`` key (usage arrives on the prompt result), so+ it falls through untouched.+ """+ params = notification.get("params")+ usage = params.get("usage") if isinstance(params, dict) else None+ if not isinstance(usage, dict):+ return+ normalized = {+ "inputTokens": usage.get("inputTokens", 0),+ "outputTokens": usage.get("outputTokens", 0),+ "cachedReadTokens": usage.get("cachedReadTokens", 0),+ "cachedWriteTokens": usage.get("cachedWriteTokens", 0),+ "totalTokens": usage.get("totalTokens", 0),+ }+ if "reasoningTokens" in usage:+ normalized["reasoningTokens"] = usage.get("reasoningTokens", 0)+ self._pending_gen_usage = normalized+def _on_console(self, notification: dict, ts: str) -> None:params = notification.get("params", {}) or {}level = params.get("level", "info")@@ -252,9 +290,20 @@ class AcpLogParser:if not self._gen_timestamp:self._gen_timestamp = ts- meta = update.get("_meta", {})- cc = meta.get("claudeCode", {}) if isinstance(meta, dict) else {}- tool_name = cc.get("toolName", update.get("title", "unknown_tool"))+ # The runtime adapters stamp the real tool name in different _meta keys+ # (claude → _meta.claudeCode, codex → _meta.posthog); the title is only a+ # display string (e.g. "posthog/exec"), so it's the last resort.+ meta = update.get("_meta") or {}+ if not isinstance(meta, dict):+ meta = {}+ tool_name = next(+ (+ adapter_meta["toolName"]+ for adapter_meta in (meta.get("claudeCode"), meta.get("posthog"))+ if isinstance(adapter_meta, dict) and adapter_meta.get("toolName")+ ),+ update.get("title", "unknown_tool"),+ )tool_call_id = update.get("toolCallId", str(uuid.uuid4()))raw_input = update.get("rawInput", {})@@ -285,7 +334,7 @@ class AcpLogParser:returnraw_output = update.get("rawOutput", "")- content = self._extract_text(update)+ content = self._extract_tool_content(update)output_text = raw_output if raw_output else (content or "")if isinstance(output_text, dict):output_text = json.dumps(output_text)@@ -328,11 +377,15 @@ class AcpLogParser:"""Flush accumulated output into a GenerationDescriptor with full history as input."""if not self._current_output:return+ # An explicit usage (claude's end_turn result) wins; otherwise attach the+ # latest _posthog/usage_update, which codex emits once per model call.+ effective_usage = token_usage or self._pending_gen_usage+ self._pending_gen_usage = {}self._result.generations.append(GenerationDescriptor(input_messages=list(self._history),output_content=list(self._current_output),- token_usage=token_usage or {},+ token_usage=effective_usage or {},timestamp=self._gen_timestamp,start_ts=self._gen_start_ts,end_ts=self._gen_last_output_ts or self._gen_timestamp,@@ -345,6 +398,33 @@ class AcpLogParser:self._gen_start_ts = ""self._gen_last_output_ts = ""+ @staticmethod+ def _extract_tool_content(update: dict) -> str:+ """Extract a tool result's text from the ACP ``ToolCallContent`` list.++ Both adapters send tool results as a list of ``{"type": "content",+ "content": {"type": "text", ...}}`` blocks — for codex it's the only output+ channel (``rawOutput`` is never set, so this is what reaches the parsed+ log). File-change results carry ``diff`` blocks instead of text.+ Non-list content falls back to the plain-text extraction.+ """+ content = update.get("content")+ if not isinstance(content, list):+ return AcpLogParser._extract_text(update)+ parts: list[str] = []+ for block in content:+ if not isinstance(block, dict):+ continue+ if block.get("type") == "diff":+ parts.append(f"[diff] {block.get('path', '')}")+ continue+ inner = block.get("content")+ if isinstance(inner, dict) and inner.get("type") == "text":+ text = inner.get("text", "").strip()+ if text:+ parts.append(text)+ return "\n".join(parts)+@staticmethoddef _extract_text(update: dict) -> str:content = update.get("content")diff --git a/products/posthog_ai/eval_harness/base.py b/products/posthog_ai/eval_harness/base.pynew file mode 100644index 000000000000..bc0d133abbb3--- /dev/null+++ b/products/posthog_ai/eval_harness/base.py@@ -0,0 +1,513 @@+from __future__ import annotations++import time+import uuid+import asyncio+import logging+from collections.abc import Sequence+from functools import partial+from typing import TYPE_CHECKING, Any, Literal++from .acp_log import ParsedLog, parse_log+from .config import AgentArtifacts, BaseEvalCase, SandboxedEvalCase+from .engines.base import EvalEngine+from .engines.types import CaseHooks, CaseSpec, ExperimentResult, ExperimentSpec, SpanKind+from .log_sink import append_case_scores, build_case_dir, write_case_logs+from .runner import EvalCaseResult, run_eval_case+from .scorers import ExitCodeZero, wrap_scorers+from .trace_events import emit_evaluation_events, emit_trace_events, emit_trace_root++if TYPE_CHECKING:+ from .harness.context import EvalContext++logger = logging.getLogger(__name__)+++def _get_last_assistant_text(parsed: ParsedLog) -> str:+ """Extract the last assistant message text from the final generation."""+ for gen in reversed(parsed.generations):+ if not gen.output_content:+ continue+ texts = [b.get("text", "") for b in gen.output_content if isinstance(b, dict) and b.get("type") == "text"]+ text = "\n".join(t for t in texts if t)+ if text:+ return text+ return ""+++def _log_conversation_spans(hooks: CaseHooks, parsed: ParsedLog) -> None:+ """Log each conversation message as a child span so Braintrust renders a trace tree.++ Uses the same Anthropic-format messages as PostHog trace capture.+ """+ for msg in parsed.messages:+ role = msg.get("role", "system")+ content = msg.get("content", "")++ # Anthropic format: content can be a string or list of content blocks+ if isinstance(content, list):+ # Render content blocks for display+ parts: list[str] = []+ for block in content:+ if not isinstance(block, dict):+ continue+ block_type = block.get("type", "")+ if block_type == "text":+ parts.append(block.get("text", ""))+ elif block_type == "tool_use":+ parts.append(f"[tool_use: {block.get('name', '?')}]")+ elif block_type == "tool_result":+ result_text = str(block.get("content", ""))[:500]+ is_error = block.get("is_error", False)+ prefix = "[tool_result error]" if is_error else "[tool_result]"+ parts.append(f"{prefix} {result_text}")+ display_content = "\n".join(parts)+ else:+ display_content = str(content)++ span_type: SpanKind+ if role == "assistant":+ # Check if this message contains tool_use blocks+ has_tool_use = isinstance(content, list) and any(+ isinstance(b, dict) and b.get("type") == "tool_use" for b in content+ )+ span_type = "function" if has_tool_use else "llm"+ name = "tool_call" if has_tool_use else "agent"+ elif role == "user":+ has_tool_result = isinstance(content, list) and any(+ isinstance(b, dict) and b.get("type") == "tool_result" for b in content+ )+ span_type = "function"+ name = "tool_result" if has_tool_result else "user"+ else:+ span_type = "function"+ name = role++ with hooks.start_span(name, span_type) as span:+ if role == "user":+ span.log(input=display_content)+ elif role == "assistant":+ span.log(output=display_content)+ else:+ span.log(metadata={"message": display_content})++ # Also log non-AI spans (console, errors)+ for span_desc in parsed.spans:+ with hooks.start_span(span_desc.span_name, "function") as span:+ span.log(metadata={"message": span_desc.content})+++class _BaseEvalRun:+ """One evaluation suite run — the per-experiment state and the generic+ Braintrust orchestration, independent of how a case's task executes.++ Holds the experiment id, the case lookups, the local log dir, and the scorer+ wiring so the Braintrust ``_task`` and the post-scoring ``_finalize`` share+ them without a giant closure. Subclasses implement ``_execute_case`` (the+ per-case work) and ``_timeout_output`` (the scored-0 shape for a case that+ outran its budget); ``_SandboxedEvalRun`` is the sandbox-agent incarnation.+ """++ trace_namespace = "evals"+ """Prefix for the experiment name in scorer trace metadata."""++ def __init__(+ self,+ experiment_name: str,+ cases: Sequence[BaseEvalCase],+ scorers: Sequence[Any],+ ctx: EvalContext,+ is_public: bool,+ no_send_logs: bool,+ engine: EvalEngine | None = None,+ ) -> None:+ self.experiment_name = experiment_name+ self.cases = cases+ self.ctx = ctx+ self.is_public = is_public+ self.no_send_logs = no_send_logs+ # The execution/reporting backend, resolved once per run and shared via+ # ctx.engine; an explicit engine (in tests) overrides it.+ self.engine = engine or ctx.engine++ # Generate a unique experiment ID per eval run+ self.experiment_id = str(uuid.uuid4())++ self.posthog_client = ctx.posthog_client++ # Shared lookups populated by _task(), read after the experiment run completes.+ self.agent_trace_id_lookup: dict[str, str] = {}+ # Per-case metadata for emitting $ai_trace root events after scoring.+ self.case_trace_meta: dict[str, dict[str, Any]] = {}++ # Local disk sink for raw agent logs — lets an agent iterating on the+ # harness read back what happened without round-tripping through Braintrust.+ self.run_log_dir = build_case_dir(experiment_name, self.experiment_id)++ # Wrap scorers with tracing if PostHog client is available+ self.scorer_traces: dict[tuple[str, str], str] = {}+ if self.posthog_client:+ self.active_scorers, self.scorer_traces = wrap_scorers(+ scorers,+ self.posthog_client,+ self.experiment_id,+ experiment_name,+ self.agent_trace_id_lookup,+ trace_namespace=self.trace_namespace,+ )+ else:+ self.active_scorers = list(scorers)++ self.case_filter = ctx.case_filter++ # Instance-scoped lookup so callable hooks on a case (e.g. a sandboxed+ # case's `setup`) can be re-bound inside `_task()` — they don't survive+ # Braintrust's JSON round-trip, but the original case objects do.+ self.cases_by_name: dict[str, BaseEvalCase] = {c.name: c for c in cases}++ def _case_input(self, case: BaseEvalCase) -> dict[str, Any]:+ """The JSON-safe ``input`` dict a case round-trips through Braintrust as."""+ return {"name": case.name, "prompt": case.prompt}++ def _build_eval_cases(self) -> list[CaseSpec]:+ eval_cases: list[CaseSpec] = []+ for case in self.cases:+ if self.case_filter and self.case_filter not in case.name:+ continue+ eval_cases.append(CaseSpec(input=self._case_input(case), expected=case.expected, metadata=case.metadata))+ return eval_cases++ async def _execute_case(self, input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:+ """Run one case and return the scorer ``output`` dict.++ Owns the case's concurrency slot and its ``asyncio.wait_for`` budget;+ a ``TimeoutError`` escaping here is scored 0 by ``_task`` rather than+ marked as an infra error.+ """+ raise NotImplementedError++ def _timeout_output(self) -> dict[str, Any]:+ """The scorer ``output`` dict for a case that outran its budget."""+ raise NotImplementedError++ def _project_name(self) -> str:+ return self.experiment_name++ def _experiment_metadata(self) -> dict[str, Any]:+ return {"agent_model": self.ctx.agent_model}++ async def _task(self, input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any] | None:+ case_started = time.monotonic()+ case_name = input.get("name", "?")+ status: Literal["ok", "timeout", "error"] = "ok"+ try:+ return await self._execute_case(input, hooks)+ except TimeoutError:+ # A case that outran its budget is a task result (too slow), not an+ # infra error: score it 0 rather than letting Braintrust mark it errored.+ status = "timeout"+ logger.warning("Eval case '%s' timed out after %ds", case_name, self.ctx.per_case_timeout_seconds)+ return self._timeout_output()+ except Exception:+ # Infra failure (provisioning, demo copy, setup hook, poll). Re-raise so+ # Braintrust records the case as errored and excludes it from score+ # averages, instead of scoring the task 0 for the harness's fault.+ status = "error"+ logger.exception("Eval task errored for '%s'", case_name)+ raise+ finally:+ # Report on every path so the reporter's live case counter never stalls.+ await self.ctx.reporter.case_done(+ self.experiment_name,+ case_name,+ duration_seconds=time.monotonic() - case_started,+ status=status,+ )++ async def _finalize(self, result: ExperimentResult) -> None:+ """Append scores to local summaries, emit PostHog evaluation/trace-root+ events, and hand the summary to the reporter — after scoring completes."""+ # Append final scores to local summary files for every case we wrote.+ if result.results:+ for eval_result in result.results:+ case_name = eval_result.input.get("name", "") if isinstance(eval_result.input, dict) else ""+ if not case_name:+ continue+ try:+ append_case_scores(self.run_log_dir, case_name, dict(eval_result.scores or {}))+ except Exception:+ logger.exception("Failed to append scores to local log summary for '%s'", case_name)++ # Emit evaluation events and trace roots to PostHog (after scoring)+ if self.posthog_client and result.results:+ try:+ emit_evaluation_events(+ self.posthog_client, self.experiment_id, self.experiment_name, result.results, self.scorer_traces+ )+ # Emit $ai_trace root events now that scores are available+ for eval_result in result.results:+ case_name = eval_result.input.get("name", "") if isinstance(eval_result.input, dict) else ""+ trace_id = self.agent_trace_id_lookup.get(case_name)+ meta = self.case_trace_meta.get(case_name)+ if trace_id and meta:+ emit_trace_root(+ self.posthog_client,+ trace_id=trace_id,+ experiment_id=self.experiment_id,+ experiment_name=self.experiment_name,+ case_name=case_name,+ prompt=meta["prompt"],+ duration=meta["duration"],+ first_timestamp=meta["first_timestamp"],+ last_message=meta.get("last_message", ""),+ artifacts_summary=meta.get("artifacts_summary"),+ scores=eval_result.scores,+ token_usage=meta.get("token_usage"),+ )+ self.posthog_client.flush()+ await self.ctx.reporter.record_posthog_evaluations_url(self.experiment_name, self.experiment_id)+ except Exception:+ logger.exception("Failed to emit evaluation events for '%s'", self.experiment_name)++ # Hand the summary to the reporter: suites don't return their Braintrust+ # result up to the orchestrator, so this is the only place the final table+ # and the EXPORT_EVAL_RESULTS jsonl can read per-scorer scores from.+ # Errored cases (infra failures) are surfaced separately so they read as noise,+ # not as agent 0s dragging the averages.+ error_count = sum(1 for r in result.results if r.error is not None)+ await self.ctx.reporter.record_summary(self.experiment_name, result.summary, error_count=error_count)++ async def run(self) -> ExperimentResult:+ eval_cases = self._build_eval_cases()++ # Register the case total (post-filter, times trials) so the reporter can+ # append a per-experiment progress counter to each case line.+ planned_cases = len(eval_cases) * self.ctx.trials+ await self.ctx.reporter.experiment_started(self.experiment_name, planned_cases, self.run_log_dir)++ result = await self.engine.run_experiment(+ ExperimentSpec(+ project_name=self._project_name(),+ cases=eval_cases,+ task=self._task,+ scorers=self.active_scorers,+ trial_count=self.ctx.trials,+ is_public=self.is_public,+ no_send_logs=self.no_send_logs,+ # Experiment names stay runtime/model-agnostic so history lines up across+ # runs; the metadata is what lets an engine filter or compare by them.+ metadata=self._experiment_metadata(),+ )+ )++ await self._finalize(result)+ return result+++class _SandboxedEvalRun(_BaseEvalRun):+ """The sandbox-agent incarnation of ``_BaseEvalRun``: per-case team+ provisioning, the sandbox-owning window, and ACP log post-processing.+ ``SandboxedEval`` is the thin public entry point."""++ trace_namespace = "sandboxed-agent"++ def __init__(+ self,+ experiment_name: str,+ cases: Sequence[SandboxedEvalCase],+ scorers: Sequence[Any],+ ctx: EvalContext,+ is_public: bool,+ no_send_logs: bool,+ ) -> None:+ if any(isinstance(scorer, ExitCodeZero) for scorer in scorers):+ raise ValueError("ExitCodeZero is added by the sandboxed eval harness; remove it from scorers")+ super().__init__(+ experiment_name=experiment_name,+ cases=cases,+ scorers=[ExitCodeZero(), *scorers],+ ctx=ctx,+ is_public=is_public,+ no_send_logs=no_send_logs,+ )+ # Narrow the infra-backed optionals once: they are None only when the+ # harness didn't boot sandbox infrastructure for this run.+ if ctx.provider_strategy is None or ctx.demo_data is None or ctx.sandbox_slots is None:+ raise RuntimeError(+ f"Suite '{experiment_name}' needs sandbox infrastructure that this run didn't boot; "+ "is its module missing the sandboxed SUITE_KIND?"+ )+ self._provider_strategy = ctx.provider_strategy+ self._demo_data = ctx.demo_data+ self._sandbox_slots = ctx.sandbox_slots++ def _case_input(self, case: BaseEvalCase) -> dict[str, Any]:+ assert isinstance(case, SandboxedEvalCase)+ return super()._case_input(case) | {"repo_fixture": case.repo_fixture}++ async def _run_sandbox_window(+ self, eval_case: SandboxedEvalCase, original_case: SandboxedEvalCase | None+ ) -> tuple[EvalCaseResult, dict[str, Any]]:+ """Run the sandbox-owning window and return its result plus the seed data.++ Holds a global sandbox slot for only this window: demo-data copy, setup+ hook, and the agent run. Everything after — log parsing, span building,+ trace emission, scoring — runs once the slot is freed, so a live sandbox+ never waits on post-processing.+ """+ ctx = self.ctx+ seed_result: dict[str, Any] = {}+ async with self._sandbox_slots:+ # Team cloning and some case seeders both write to ClickHouse. Bound+ # the full setup phase separately even when Modal makes sandbox+ # capacity effectively unbounded.+ async with ctx.team_setup_slots:+ # The factory does Django ORM work. Django's async-safety+ # guard rejects sync ORM calls from async contexts, so run it+ # in a worker thread.+ sandbox_context = await asyncio.to_thread(self._demo_data.make_context, eval_case.name)+ if original_case is not None and original_case.setup is not None:+ try:+ seed_result = await asyncio.to_thread(original_case.setup, sandbox_context)+ except Exception:+ logger.exception("Setup hook failed for '%s'", eval_case.name)+ raise+ # Start the agent budget after team setup, so neither semaphore wait+ # nor the ClickHouse copy can consume it.+ result = await asyncio.wait_for(+ run_eval_case(eval_case, sandbox_context, provider=self._provider_strategy),+ timeout=ctx.per_case_timeout_seconds,+ )+ return result, seed_result++ async def _post_process(+ self,+ eval_case: SandboxedEvalCase,+ hooks: CaseHooks,+ result: EvalCaseResult,+ seed_result: dict[str, Any],+ ) -> dict[str, Any]:+ """Build Braintrust spans, write local logs, emit trace events, and shape+ the scorer input dict — all off the sandbox slot."""+ # Store trace_id in metadata so evaluation events can link to the trace+ if result.trace_id:+ hooks.metadata["trace_id"] = result.trace_id+ self.agent_trace_id_lookup[eval_case.name] = result.trace_id+ hooks.metadata["artifacts"] = result.artifacts.model_dump()++ # Parse the log once, use for both Braintrust spans and PostHog trace capture+ last_message = ""+ messages: list[dict[str, Any]] = []+ if result.raw_log:+ parsed = parse_log(result.raw_log, initial_prompt=eval_case.prompt)+ _log_conversation_spans(hooks, parsed)+ last_message = _get_last_assistant_text(parsed)+ messages = parsed.messages++ if self.posthog_client:+ try:+ emit_trace_events(+ self.posthog_client,+ trace_id=result.trace_id,+ experiment_id=self.experiment_id,+ experiment_name=self.experiment_name,+ case_name=eval_case.name,+ parsed=parsed,+ )+ # Store metadata for emit_trace_root (called after scoring)+ self.case_trace_meta[eval_case.name] = {+ "prompt": eval_case.prompt,+ "duration": result.artifacts.duration_seconds,+ "first_timestamp": parsed.first_timestamp,+ "last_message": last_message,+ "artifacts_summary": result.artifacts.model_dump(),+ "token_usage": parsed.total_token_usage,+ }+ except Exception:+ logger.exception("Failed to emit trace events for '%s'", eval_case.name)++ try:+ write_case_logs(+ case_dir=self.run_log_dir,+ case_name=eval_case.name,+ raw_log=result.raw_log or "",+ artifacts=result.artifacts.model_dump(),+ prompt=eval_case.prompt,+ duration=result.artifacts.duration_seconds,+ last_message=last_message,+ token_usage=self.case_trace_meta.get(eval_case.name, {}).get("token_usage"),+ )+ except Exception:+ logger.exception("Failed to write local eval logs for '%s'", eval_case.name)++ return result.artifacts.model_dump() | {+ "last_message": last_message,+ "messages": messages,+ "raw_log": result.raw_log,+ "seed": seed_result,+ "prompt": eval_case.prompt,+ }++ async def _execute_case(self, input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:+ eval_case = SandboxedEvalCase(+ name=input["name"],+ prompt=input["prompt"],+ repo_fixture=input.get("repo_fixture", ""),+ )+ original_case = self.cases_by_name.get(input["name"])+ sandbox_case = original_case if isinstance(original_case, SandboxedEvalCase) else None+ result, seed_result = await self._run_sandbox_window(eval_case, sandbox_case)+ return await self._post_process(eval_case, hooks, result, seed_result)++ def _timeout_output(self) -> dict[str, Any]:+ return AgentArtifacts(+ exit_code=1,+ stderr=f"case timeout after {self.ctx.per_case_timeout_seconds}s",+ ).model_dump()++ def _project_name(self) -> str:+ return f"sandboxed-agent-{self.experiment_name}" if self.is_public else self.experiment_name++ def _experiment_metadata(self) -> dict[str, Any]:+ return {"agent_model": self.ctx.agent_model, "agent_runtime": self.ctx.agent_runtime}+++async def SandboxedEval(+ experiment_name: str,+ cases: Sequence[SandboxedEvalCase],+ scorers: Sequence[Any],+ ctx: EvalContext,+ is_public: bool = False,+ no_send_logs: bool = True,+) -> ExperimentResult:+ """Run a sandboxed agent evaluation suite via Braintrust.++ For each ``SandboxedEvalCase``, creates a Task, triggers the temporal workflow+ (sandbox provisioning, agent-server, prompt delivery, cleanup), polls S3 logs+ for results, and feeds parsed artifacts to the scorers.++ ``ctx.demo_data.make_context(case_name)`` is invoked once per case and+ returns a freshly isolated ``CustomPromptSandboxContext`` (own org/team/user)+ so cases can't pollute each other's state.++ Everything the suite needs (demo data, analytics client, case filter,+ concurrency limits, reporter) comes off ``ctx``; suites run concurrently on+ one event loop, with sandbox load bounded by ``ctx.sandbox_slots`` and team+ setup serialized by ``ctx.team_setup_slots``.+ """+ run = _SandboxedEvalRun(+ experiment_name=experiment_name,+ cases=cases,+ scorers=scorers,+ ctx=ctx,+ is_public=is_public,+ no_send_logs=no_send_logs,+ )+ return await run.run()+++SandboxedPublicEval = partial(SandboxedEval, is_public=True, no_send_logs=False)+"""Sandboxed evaluation case that is publicly accessible."""++SandboxedPrivateEval = partial(SandboxedEval, is_public=False, no_send_logs=True)+"""Sandboxed evaluation case that is not accessible publicly."""diff --git a/ee/hogai/eval/sandboxed/config.py b/products/posthog_ai/eval_harness/config.pysimilarity index 88%rename from ee/hogai/eval/sandboxed/config.pyrename to products/posthog_ai/eval_harness/config.pyindex 73807a6b7660..7398eb9c1839 100644--- a/ee/hogai/eval/sandboxed/config.py+++ b/products/posthog_ai/eval_harness/config.py@@ -8,8 +8,12 @@ from pydantic import BaseModel, ConfigDict, Fieldfrom products.tasks.backend.facade.agents import CustomPromptSandboxContext-class SandboxedEvalCase(BaseModel):- """A single eval case for the sandboxed coding agent."""+class BaseEvalCase(BaseModel):+ """A single eval case, independent of how its task executes.++ Named ``BaseEvalCase`` (not ``EvalCase``) to avoid shadowing Braintrust's+ ``EvalCase``, which the runners import alongside it.+ """model_config = ConfigDict(arbitrary_types_allowed=True)@@ -17,10 +21,7 @@ class SandboxedEvalCase(BaseModel):"""Human-readable name for this eval case."""prompt: str- """Natural language task description for the agent."""-- repo_fixture: str = ""- """Name of the repo fixture (informational, for tracking)."""+ """Natural language task description for the agent or model."""expected: dict[str, Any] = Field(default_factory=dict)"""Expected values for scoring, keyed by scorer ``_name()``.@@ -32,6 +33,13 @@ class SandboxedEvalCase(BaseModel):metadata: dict[str, Any] = Field(default_factory=dict)"""Arbitrary metadata for tracking and filtering."""++class SandboxedEvalCase(BaseEvalCase):+ """A single eval case for the sandboxed coding agent."""++ repo_fixture: str = ""+ """Name of the repo fixture (informational, for tracking)."""+setup: Callable[[CustomPromptSandboxContext], dict[str, Any]] | None = Field(default=None,exclude=True,diff --git a/ee/hogai/eval/data_setup.py b/products/posthog_ai/eval_harness/data_setup.pysimilarity index 86%rename from ee/hogai/eval/data_setup.pyrename to products/posthog_ai/eval_harness/data_setup.pyindex c6cc2d543f98..07828d56e66e 100644--- a/ee/hogai/eval/data_setup.py+++ b/products/posthog_ai/eval_harness/data_setup.py@@ -10,6 +10,7 @@ import uuidimport loggingimport datetime+from django.conf import settingsfrom django.db import transactionfrom django.test import override_settings@@ -44,6 +45,32 @@ def _build_hedgebox_matrix() -> HedgeboxMatrix:)+def _validate_sandboxed_eval_warehouse_config() -> None:+ if not settings.OBJECT_STORAGE_ENABLED:+ return++ required_settings = (+ "OBJECT_STORAGE_ENDPOINT",+ "OBJECT_STORAGE_ACCESS_KEY_ID",+ "OBJECT_STORAGE_SECRET_ACCESS_KEY",+ "OBJECT_STORAGE_BUCKET",+ )+ missing_settings = [setting_name for setting_name in required_settings if not getattr(settings, setting_name, None)]+ if missing_settings:+ raise RuntimeError("Sandboxed eval warehouse setup requires these settings: " + ", ".join(missing_settings))+++def _master_warehouse_ready(team: Team) -> bool:+ """True when the master team's demo warehouse CSVs are already in object storage.++ Per-case teams register their own warehouse tables against the master team's stored+ CSVs, so the presence of those files is what makes the master team reusable. Checked+ under ``TEST=False`` because warehouse storage is intentionally disabled in test mode.+ """+ with override_settings(TEST=False):+ return not _build_hedgebox_matrix().demo_data_warehouse_tables_need_saving(team.id)++def create_isolated_demo_data(django_db_blocker,*,@@ -103,6 +130,7 @@ def ensure_master_demo_team(django_db_blocker) -> int:"""with django_db_blocker.unblock():+ _validate_sandboxed_eval_warehouse_config()existing_org = Organization.objects.filter(name=MASTER_ORG_NAME).order_by("-created_at").first()if existing_org is not None:team = existing_org.teams.first()@@ -112,9 +140,12 @@ def ensure_master_demo_team(django_db_blocker) -> int:{"team_id": team.id},)[0][0]if ch_event_count > 0:- logger.info("Reusing master demo team id=%d (events=%d)", team.id, ch_event_count)- return team.id- logger.warning("Master demo team id=%d has no CH events — regenerating", team.id)+ if not settings.OBJECT_STORAGE_ENABLED or _master_warehouse_ready(team):+ logger.info("Reusing master demo team id=%d (events=%d)", team.id, ch_event_count)+ return team.id+ logger.warning("Master demo team id=%d has an incomplete warehouse; regenerating", team.id)+ else:+ logger.warning("Master demo team id=%d has no CH events; regenerating", team.id)User.objects.filter(organization_membership__organization=existing_org).delete()existing_org.delete()User.objects.filter(email=MASTER_USER_EMAIL).delete()@@ -130,6 +161,12 @@ def ensure_master_demo_team(django_db_blocker) -> int:_org, team, _user = matrix_manager.ensure_account_and_save(MASTER_USER_EMAIL, EVAL_USER_FULL_NAME, MASTER_ORG_NAME)++ if settings.OBJECT_STORAGE_ENABLED and not _master_warehouse_ready(team):+ raise RuntimeError(+ "The Hedgebox master team warehouse is incomplete after generation. "+ "Check object storage connectivity and the captured setup errors."+ )return team.id@@ -199,8 +236,12 @@ def copy_demo_data_to_new_team(# per-case teams instead of returning "does not exist in the taxonomy".infer_taxonomy_for_team(team.id)+ matrix = _build_hedgebox_matrix()with override_settings(TEST=False):- _build_hedgebox_matrix().set_project_up(team, user)+ matrix.set_project_up(team, user)+ # Point this team's warehouse tables at the master team's already-saved CSVs+ # (keyed by the master team id) — the same pre-save path the demo signup uses.+ matrix.register_demo_data_warehouse_tables(team, user, master_team_id)team.save()team.project.save()diff --git a/products/posthog_ai/eval_harness/engines/base.py b/products/posthog_ai/eval_harness/engines/base.pynew file mode 100644index 000000000000..ddd66620ebcb--- /dev/null+++ b/products/posthog_ai/eval_harness/engines/base.py@@ -0,0 +1,52 @@+"""The engine seam: how a built suite's cases actually get run and scored.++``_BaseEvalRun`` owns everything about a run *except* the experiment execution+itself — case building, the per-case task skeleton, local logging, and the+reporting/finalization path. The one thing it delegates is running the+experiment, so the execution/reporting backend can be swapped without touching+the run base or any suite.+"""++from __future__ import annotations++from typing import ClassVar, Protocol++from .types import EnvVarSpec, EvalTaskFn, ExperimentResult, ExperimentSpec++# Re-exported for callers that import ``EvalTaskFn`` from the engine seam; it now+# lives in ``types`` (retargeted at the neutral ``CaseHooks``).+__all__ = ["EvalEngine", "EvalTaskFn"]+++class EvalEngine(Protocol):+ """Runs one experiment over a suite's cases and returns the scored, summarized+ result the reporting path (``_BaseEvalRun._finalize``) consumes.++ ``BraintrustEngine`` is the only implementation today. The seam exists so a+ future ``PostHogEvalsEngine`` — recording datasets, experiments, and scores+ into PostHog's own LLM analytics as the system of record — can slot in behind+ the same interface, without changing the run base or any suite.++ Obligations (documented on the implementation and pinned by the conformance+ suite): never throttle or budget the task; persist ``hooks.metadata`` onto+ ``CaseResult.metadata``; a task exception becomes ``CaseResult.error`` and is+ excluded from aggregates; ``None`` scores are preserved per-case and excluded+ from the means.+ """++ name: ClassVar[str]+ """Stable engine identifier; ``reporting`` renders ``name.title()`` as the label."""++ supports_public_experiments: ClassVar[bool]+ """Whether the engine has a notion of a public experiment (``is_public``)."""++ @classmethod+ def required_env(cls) -> tuple[EnvVarSpec, ...]:+ """The environment variables this engine needs, validated in preflight."""+ ...++ async def run_experiment(self, spec: ExperimentSpec) -> ExperimentResult:+ """Run every case in ``spec`` (``trial_count`` times each) through the task+ and scorers, and return the engine-neutral result plus its per-scorer+ summary."""+ ...diff --git a/products/posthog_ai/eval_harness/engines/braintrust.py b/products/posthog_ai/eval_harness/engines/braintrust.pynew file mode 100644index 000000000000..dfd6dd5986e1--- /dev/null+++ b/products/posthog_ai/eval_harness/engines/braintrust.py@@ -0,0 +1,146 @@+"""The Braintrust engine — the default (and currently only) ``EvalEngine``."""++from __future__ import annotations++from collections.abc import Iterator+from contextlib import contextmanager+from typing import Any, ClassVar++from braintrust import EvalAsync, EvalCase, EvalHooks+from braintrust.framework import EvalResultWithSummary, Evaluator, ReporterDef++from .types import AggregateScore, CaseResult, EnvVarSpec, EvalSummary, ExperimentResult, ExperimentSpec, SpanKind+++def _quiet_report_eval(evaluator: Evaluator, result: EvalResultWithSummary, verbose: bool, jsonl: bool) -> bool:+ return True+++def _quiet_report_run(results: list[bool], verbose: bool, jsonl: bool) -> bool:+ return True+++QUIET_REPORTER: ReporterDef = ReporterDef(+ name="quiet",+ report_eval=_quiet_report_eval,+ report_run=_quiet_report_run,+)+"""Reporter that keeps Braintrust's per-experiment tables out of the shared stream.++Its callbacks are called synchronously by ``EvalAsync`` and must not be coroutines."""+++class _BraintrustCaseHooks:+ """Adapts braintrust's ``EvalHooks`` to the neutral ``CaseHooks``.++ ``metadata`` is a write-through onto the braintrust hooks (so mutations land+ on the eventual ``CaseResult.metadata``); ``start_span`` maps the neutral+ ``(name, kind)`` onto braintrust's ``start_span(name=, span_attributes=)`` and+ yields the braintrust ``Span``, whose ``.log`` already matches ``SpanHandle``.+ """++ def __init__(self, hooks: EvalHooks) -> None:+ self._hooks = hooks++ @property+ def metadata(self) -> dict[str, Any]:+ return self._hooks.metadata++ @contextmanager+ def start_span(self, name: str, kind: SpanKind) -> Iterator[Any]:+ with self._hooks.span.start_span(name=name, span_attributes={"type": kind}) as span:+ yield span+++class BraintrustEngine:+ """Runs experiments on Braintrust and reports through it.++ These knobs are load-bearing invariants (they used to live in+ ``harness/AGENTS.md``); breaking one produces a hang or a silently wrong+ result rather than an exception:++ - **Never pass a ``timeout``.** ``EvalAsync``'s timeout wraps the whole task+ invocation, including time a case spends queued on the harness's own+ concurrency semaphores, so it would kill cases that never started. The+ per-case budget belongs in the ``asyncio.wait_for`` inside the run's+ ``_execute_case``, which starts only after slot acquisition.+ - **Never let ``max_concurrency`` bind.** It is set to the total case count+ (cases × trials) so the harness's semaphores are the only limiters.+ - **``QUIET_REPORTER``.** Suites share one stdout; the quiet reporter stops+ each experiment from dumping its own score table into the interleaved+ stream. Its callbacks are called synchronously by ``EvalAsync`` and must+ not be coroutines.+ - **``update=True``.** Experiment names stay runtime/model-agnostic so history+ lines up across runs; updating keeps that history rather than forking it.+ """++ name: ClassVar[str] = "braintrust"+ supports_public_experiments: ClassVar[bool] = True++ @classmethod+ def required_env(cls) -> tuple[EnvVarSpec, ...]:+ return (EnvVarSpec("BRAINTRUST_API_KEY", "records experiments and scores to Braintrust"),)++ async def run_experiment(self, spec: ExperimentSpec) -> ExperimentResult:+ async def bridged_task(input: dict[str, Any], hooks: EvalHooks) -> dict[str, Any] | None:+ # Wrap braintrust's hooks so the suite task only ever sees neutral CaseHooks.+ return await spec.task(input, _BraintrustCaseHooks(hooks))++ cases = [EvalCase(input=case.input, expected=case.expected, metadata=case.metadata) for case in spec.cases]+ result = await EvalAsync(+ spec.project_name,+ data=cases,+ task=bridged_task,+ scores=list(spec.scorers),+ trial_count=spec.trial_count,+ # Our global concurrency semaphores are the only limiters that should+ # bind. Braintrust's own per-suite limiter must never gate, so let it+ # admit every case at once — across all trials.+ max_concurrency=max(len(cases) * spec.trial_count, 1),+ # Braintrust's timeout wraps the whole task invocation, including any+ # time a case spends queued on our concurrency semaphores — so a queued+ # case would be killed before it ever started. The real budget is the+ # ``asyncio.wait_for`` inside ``_execute_case``.+ timeout=None,+ # Suites share one stdout; the quiet reporter stops each experiment+ # from dumping its own score table into the interleaved stream.+ reporter=QUIET_REPORTER,+ update=True,+ is_public=spec.is_public,+ no_send_logs=spec.no_send_logs,+ # Experiment names stay runtime/model-agnostic so history lines up+ # across runs; the metadata is what lets Braintrust filter or compare.+ metadata=spec.metadata,+ )+ return self._translate(result)++ def _translate(self, result: EvalResultWithSummary) -> ExperimentResult:+ """Map braintrust's ``EvalResultWithSummary`` onto the neutral model.++ ``score=None`` is preserved per-case (braintrust drops it from the+ aggregate); a task exception becomes ``CaseResult.error`` as a string so+ callers never re-handle a live ``Exception``; ``summary.raw`` is the+ braintrust summary's ``as_dict()`` so the jsonl export round-trips+ byte-for-byte through ``EvalSummary.as_json()``.+ """+ summary = result.summary+ return ExperimentResult(+ summary=EvalSummary(+ engine_name=self.name,+ experiment_name=summary.experiment_name,+ scores={name: AggregateScore(name=s.name, score=s.score) for name, s in summary.scores.items()},+ experiment_url=summary.experiment_url,+ raw=summary.as_dict(),+ ),+ results=[+ CaseResult(+ input=case.input,+ output=case.output,+ scores=dict(case.scores or {}),+ expected=case.expected,+ metadata=dict(case.metadata or {}),+ error=None if case.error is None else str(case.error),+ )+ for case in result.results+ ],+ )diff --git a/products/posthog_ai/eval_harness/engines/registry.py b/products/posthog_ai/eval_harness/engines/registry.pynew file mode 100644index 000000000000..a5dd1e495236--- /dev/null+++ b/products/posthog_ai/eval_harness/engines/registry.py@@ -0,0 +1,27 @@+"""Engine registry: resolve an ``EvalEngine`` by name.++There is no ``--engine`` CLI flag yet — the default is the only entry until a+second engine exists — but ``EvalContext.engine`` and preflight both resolve+through here, so adding one is a one-line change.+"""++from __future__ import annotations++from .base import EvalEngine+from .braintrust import BraintrustEngine++_ENGINES: dict[str, type[EvalEngine]] = {+ BraintrustEngine.name: BraintrustEngine,+}++DEFAULT_ENGINE = BraintrustEngine.name+++def resolve_engine(name: str = DEFAULT_ENGINE) -> EvalEngine:+ """Return a fresh engine instance for ``name`` (the Braintrust engine by default)."""+ try:+ engine_cls = _ENGINES[name]+ except KeyError:+ known = ", ".join(sorted(_ENGINES))+ raise ValueError(f"Unknown eval engine '{name}'; known engines: {known}") from None+ return engine_cls()diff --git a/products/posthog_ai/eval_harness/engines/types.py b/products/posthog_ai/eval_harness/engines/types.pynew file mode 100644index 000000000000..552e2e767120--- /dev/null+++ b/products/posthog_ai/eval_harness/engines/types.py@@ -0,0 +1,160 @@+"""Engine-neutral types at the harness/engine boundary.++Stdlib-only on purpose: no Braintrust, no Django, no pydantic. ``env_preflight``+imports ``EnvVarSpec`` from here, and it sits on the Django-free ``__main__``+import chain (see ``harness/AGENTS.md``), so nothing here may pull in a heavier+dependency.++Each ``EvalEngine`` translates its native result shapes into these so the run+base, reporting, and trace emission never see an engine-specific type.+"""++from __future__ import annotations++import json+from collections.abc import Awaitable, Callable, Iterator, Sequence+from contextlib import AbstractContextManager, contextmanager+from dataclasses import dataclass, field+from typing import Any, Literal, Protocol+++@dataclass(frozen=True)+class CaseSpec:+ """An engine-neutral eval case: JSON-safe ``input`` plus ``expected`` and+ ``metadata``. Each engine translates this to its native case type; the+ harness keeps callable rebinding (a case's ``setup`` hook) in ``cases_by_name``."""++ input: dict[str, Any]+ expected: dict[str, Any] = field(default_factory=dict)+ metadata: dict[str, Any] = field(default_factory=dict)+++SpanKind = Literal["llm", "function", "task", "score"]+++class SpanHandle(Protocol):+ """A single span the task logs onto; the engine renders it into its own trace."""++ def log(self, *, input: Any = None, output: Any = None, metadata: dict[str, Any] | None = None) -> None: ...+++class CaseHooks(Protocol):+ """The per-case handle the engine passes to the task.++ ``metadata`` is a mutable dict the engine must persist onto+ ``CaseResult.metadata``; ``start_span`` opens a child span the task logs onto.+ """++ @property+ def metadata(self) -> dict[str, Any]: ...++ def start_span(self, name: str, kind: SpanKind) -> AbstractContextManager[SpanHandle]: ...+++EvalTaskFn = Callable[[dict[str, Any], CaseHooks], Awaitable[dict[str, Any] | None]]+"""The per-case task the engine drives: it takes the JSON-safe case input and the+neutral ``CaseHooks`` and returns the scorer ``output`` dict (or ``None``)."""+++class _NullSpanHandle:+ def log(self, *, input: Any = None, output: Any = None, metadata: dict[str, Any] | None = None) -> None:+ return None+++class NullCaseHooks:+ """A concrete no-op ``CaseHooks`` for tests and span-less engines.++ Replaces the old ``hooks=None`` sentinel: ``metadata`` is a real (discarded)+ dict and ``start_span`` yields a span that swallows every ``log``.+ """++ def __init__(self) -> None:+ self._metadata: dict[str, Any] = {}++ @property+ def metadata(self) -> dict[str, Any]:+ return self._metadata++ @contextmanager+ def start_span(self, name: str, kind: SpanKind) -> Iterator[SpanHandle]:+ yield _NullSpanHandle()+++@dataclass(frozen=True)+class ExperimentSpec:+ """The single argument to ``run_experiment``. Bundling the knobs in one frozen+ spec means a new field (e.g. a baseline experiment id) breaks no engine or stub."""++ project_name: str+ cases: Sequence[CaseSpec]+ task: EvalTaskFn+ scorers: Sequence[Any] # duck-typed: eval_async(output, expected, **kwargs) + _name()+ trial_count: int+ is_public: bool+ no_send_logs: bool+ metadata: dict[str, Any]+++@dataclass+class CaseResult:+ """One scored case (or case × trial): the engine-neutral ``EvalResult``.++ ``scores`` maps scorer name to its per-case score; ``None`` means the scorer+ skipped this case (excluded from aggregates). ``error`` is non-``None`` when+ the task itself raised — an infra failure the engine excludes from score+ averages rather than scoring 0.+ """++ input: dict[str, Any]+ output: Any+ scores: dict[str, float | None]+ expected: Any = None+ metadata: dict[str, Any] = field(default_factory=dict)+ error: str | None = None+++@dataclass(frozen=True)+class AggregateScore:+ """A scorer's mean over the cases where it produced a non-``None`` score."""++ name: str+ score: float | None+++@dataclass+class EvalSummary:+ """The per-experiment summary the reporting path consumes.++ ``raw`` is the engine-native summary payload; ``as_json`` passes it straight+ through so the ``eval_results.jsonl`` export stays byte-identical to what the+ engine would have written itself.+ """++ engine_name: str+ experiment_name: str+ scores: dict[str, AggregateScore]+ experiment_url: str | None = None+ raw: dict[str, Any] = field(default_factory=dict)++ def as_json(self) -> str:+ return json.dumps(self.raw)+++@dataclass+class ExperimentResult:+ """What ``EvalEngine.run_experiment`` returns: the summary plus every case."""++ summary: EvalSummary+ results: list[CaseResult]+++@dataclass(frozen=True)+class EnvVarSpec:+ """One environment variable an engine requires, surfaced in the preflight error.++ ``name`` is the literal variable name; ``description`` says what it is for so a+ missing variable reads as a one-line fix.+ """++ name: str+ description: strdiff --git a/products/posthog_ai/eval_harness/harness/AGENTS.md b/products/posthog_ai/eval_harness/harness/AGENTS.mdnew file mode 100644index 000000000000..01191be5b9f9--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/AGENTS.md@@ -0,0 +1,135 @@+# Working on the sandboxed eval harness++Read [`README.md`](README.md) first for the module map and boot sequence.+This file is only the set of invariants that are easy to break and expensive to debug, because breaking most of them produces a hang or a silently wrong result rather than an exception.++Verify a change with `python -m products.posthog_ai.eval_harness.harness --list` (imports every eval module, so it catches most breakage in seconds) before spending a real eval run on it.++## Import ordering++`__main__.py` calls `setup_django()` **before** importing `lifecycle`, and `lifecycle` is what pulls in everything that touches Django settings, the ORM, or the `products.tasks` facade.+Anything reachable from `__main__`'s top-level imports must therefore stay Django-free: today that is `cli.py`, `providers.py`, `tunnels.py`, `ports.py`, `env_preflight.py`, `requirements.py`, `transcript.py`, `log_sink.py`, and `django_env.py` itself, plus [`../engines/types.py`](../engines/types.py) — the stdlib-only neutral types `env_preflight` imports `EnvVarSpec` from. Keep `types.py` free of braintrust, Django, and pydantic for that reason.++This is why the port constants live in `ports.py` rather than in `services.py`, which imports Django.+If you add an import to one of those modules, check that `--list` still runs.++## Concurrency++The Braintrust-specific knobs below (`timeout`, `max_concurrency`, `QUIET_REPORTER`, `update`) are applied in one place — `BraintrustEngine.run_experiment` in [`../engines/braintrust.py`](../engines/braintrust.py), the sole `EvalEngine` implementation — and documented as obligations in its docstring. `_BaseEvalRun.run()` only hands the engine the cases, task, scorers, and metadata. A future engine (e.g. a PostHog-native one) owns its own equivalents.++- **Never give Braintrust a `timeout`.** `EvalAsync`'s timeout wraps the whole task invocation, including time queued on our concurrency semaphores, so it would kill cases that never started. The budget belongs in the `asyncio.wait_for` inside the slot.+- **Never let Braintrust's `max_concurrency` bind.** It is set to the case count so that the harness's own semaphores are the only limiters.+- **Acquire `ctx.sandbox_slots` exactly once per case**, around only the sandbox-owning window. It is not reentrant; a second acquisition inside the first deadlocks. `ctx.one_shot_slots` follows the same rules for one-shot cases: acquired once, `wait_for` budget inside, never both semaphores in one case.+- Hold `ctx.team_setup_slots` across both the demo-data clone and optional case setup hook. Some setup hooks write directly to ClickHouse, so releasing it between those phases defeats the RAM guard.+- Resolve the team-setup limit once through `HarnessOptions`: one permit normally and four when `CODER` or `CI` is set. Do not read those environment variables inside a case or make setup concurrency follow the sandbox limit.+- Keep scoring, log parsing, and span building _outside_ the slot. A sandbox that is being scored is a sandbox that someone else could be using.+- Every sync Django ORM call reached from async code goes through `asyncio.to_thread`. Do not set `DJANGO_ALLOW_ASYNC_UNSAFE` to make an error go away.++## Engines++`_BaseEvalRun.run()` builds an `ExperimentSpec` (cases, task, scorers, flags, metadata) and hands it to `ctx.engine.run_experiment`, which returns an engine-neutral `ExperimentResult` ([`../engines/types.py`](../engines/types.py)).+The engine is resolved once per run by `engines/registry.resolve_engine()` and shared via `EvalContext.engine`; there is no `--engine` flag until a second engine exists.+`BraintrustEngine` ([`../engines/braintrust.py`](../engines/braintrust.py)) is the only implementation and the sole runtime module that knows braintrust exists, alongside the deferred autoevals judge substrate in `../scorers/`.++Every engine owes the run base these obligations, pinned by the conformance suite ([`../test/test_engine_conformance.py`](../test/test_engine_conformance.py)):++- Never throttle or budget the task — the harness's own semaphores and `asyncio.wait_for` are the only limiters. The braintrust `timeout`/`max_concurrency` knobs above are how `BraintrustEngine` honors this.+- Persist `hooks.metadata` mutations onto `CaseResult.metadata`.+- Turn a task exception into `CaseResult.error` (a string) and exclude that case from aggregates.+- Preserve `score=None` per-case and exclude it from the means — `None` is "skipped", `0.0` is "failed".+- Print nothing to the shared stdout (braintrust's `QUIET_REPORTER` is how it stays quiet), and accumulate history under a stable `project_name`.++A new engine implements the `EvalEngine` protocol ([`../engines/base.py`](../engines/base.py)) — `name`, `supports_public_experiments`, `required_env()`, `run_experiment(spec)` — registers in `engines/registry.py`, joins the conformance fixture list, and must pass it unchanged.++## Terminal output++`ProgressReporter` owns formatted harness messages and holds a lock, because suites run concurrently and would otherwise interleave.+Do not add bare `print` calls to `base.py` or the run lifecycle; route them through the reporter.+The same lock guards the `eval_results.jsonl` append, where concurrent writes would tear a line in half.++`QUIET_REPORTER` exists so each Braintrust experiment does not dump its own score table into the shared stream.+Its callbacks are called synchronously by `EvalAsync` and must not be coroutines.++`RunTranscript` owns the outer stdout/stderr tee for every real run.+It must contain the complete plain-text terminal stream, and both the terminal and transcript must end with the same unlabeled absolute transcript path.+The preceding line must identify that path as the full stdout/stderr run transcript.+Keep final summary rendering after suite teardown and call `logging.shutdown()` before `RunTranscript.finish()`, so cleanup or buffered logging cannot write after the path.+`--list` and argparse errors intentionally bypass transcript creation.++Only the final overall status may say `PASS` or `FAIL`.+Successful cases, experiments, and suites say `DONE`; `TIMEOUT`, `ERROR`, and `CRASH` keep outcome and infrastructure failures distinct.++## Suites++Suites are discovered by convention, not registered: any coroutine named `eval_*` defined in a file named `eval_*.py` under `products/posthog_ai/evals/` or a `products/<product>/evals/` tree.+A suite takes one argument, `ctx: EvalContext`, and returns `None`.++A module declares how its suites execute with a module-level `SUITE_KIND` (`requirements.SuiteKind`); absent means sandboxed.+The kind decides which infrastructure the harness boots (`requirements.INFRA_BY_KIND`) and which env models preflight validates (`env_preflight.ENV_MODELS_BY_KIND`) — an under-declared kind fails loudly when the runner narrows the `EvalContext` fields its infra never populated.++Because suites do not return their Braintrust result, `base.py` hands the summary to the reporter via `record_summary`.+That is the only path by which the final table and the JSONL export see per-scorer scores — for every suite kind.++A crashing suite must never take down the others: `lifecycle._run_suite` catches `Exception` per suite and the run exits non-zero at the end.+Do not widen that to `BaseException`, which would swallow `CancelledError` and `KeyboardInterrupt`.++## Scorers++`base.py` adds `ExitCodeZero` to every experiment before optional tracing wraps the scorers.+Suites must not declare it themselves, and the constructor rejects an explicit duplicate.++Every scorer implements exactly one branch — never both `_run_eval_sync` and `_run_eval_async`.+Braintrust's `EvalAsync` always dispatches through `eval_async`, and the base `Scorer`'s default `_run_eval_async` already delegates to `_run_eval_sync`, so a second branch is either dead code or a silently divergent copy.++- Deterministic scorers subclass `Scorer` and implement `_run_eval_sync` only; the base class supplies the async path (and the sync path is what the pytest scorer tests call).+- LLM judges subclass `scorers.JudgedScorer` and implement `_prepare` only; the shared base owns the short-circuit/error-mapping async branch, and `AsyncOnlyScorerMixin` makes the unused sync branch raise instead of running without `_prepare`.+- Async-only classes that subclass `Scorer` directly (`TracedScorer`, hybrids like `DuplicateUniqueFlagKey`) need `AsyncOnlyScorerMixin` first in their bases — `_run_eval_sync` is abstract on `Scorer`, and the mixin is what satisfies it.++## Teardown++Bootstrap registers teardown on an `ExitStack` as each resource comes up, so a failure halfway through still unwinds what already started.+`atexit` hooks plus the subprocess manager's signal handlers cover Ctrl-C, where neither stack unwinds.++After any change, a Ctrl-C mid-run must leave no listeners on 18000 / 13308 / 18787 / 14040 / 15051 / 15052, no `task-sandbox-*` containers, and no Temporal dev server.++Three layers tear a case's sandbox down, outermost last:++- Every case signals its `ProcessTaskWorkflow` with a terminal status and waits for the workflow result, which includes the workflow's own `cleanup_sandbox` call.+- If the workflow does not finish within the completion grace period, the runner cancels it and waits once more. An otherwise successful case becomes an infrastructure error when neither wait confirms a terminal state; existing failures and timeouts keep their original outcome.+- `provider.cleanup_case(task_id)` then runs as a per-case safety net. Docker reclaims the case's container by name, while Modal terminates sandboxes carrying that exact `task_id` tag.++`provider.cleanup()` runs through the normal `ExitStack` and through `atexit` as an interruption fallback, sweeping anything the above missed: leftover Docker containers by name and leftover Modal sandboxes under the eval app.+Both sweeps are scoped to this run's own tasks: the runner registers each task id via `provider.register_task`, and cleanup filters on that set — by container name on Docker, by the `task_id` sandbox tag on Modal.+So a dev-stack task sandbox or a second concurrent eval run sharing the provider is never reaped, and a run that started nothing sweeps nothing.++## Providers++Provider differences belong in `providers.py`, not in `if provider == "docker"` branches scattered through `lifecycle.py`.+Add a `SandboxProviderStrategy` method rather than a conditional.+Per-case teardown is one such method (`cleanup_case`): the runner calls it after every case, so a docker-only concern like reclaiming a leftover container never leaks into `runner.py` or fires on a Modal run.++`preflight()` must catch a missing prerequisite before any infrastructure boots, and its message must say how to fix it.+A missing ngrok authtoken, for instance, otherwise surfaces only as a 60-second tunnel timeout.++The chosen provider must reach `settings.SANDBOX_PROVIDER` **before `django.setup()`**, which is why `__main__` sets it in the environment (from `SANDBOX_PROVIDER_SETTING`) rather than relying only on the async-phase `override_settings`.+`products.tasks` resolves the sandbox class from that setting exactly once and caches it in module globals, so the first `Sandbox` access wins for the whole process.+`.env` ships `SANDBOX_PROVIDER=docker`, so setting it late let a `--provider modal` run cache `DockerSandbox` and execute the agent in a local container while still pointing it at the ngrok URLs.+Docker mode hid this because the cached value already matched.+Modal evals use the `MODAL_EVALS` backend, whose sandbox class is pinned to the `posthog-sandbox-evals` Modal app.++`PERSONHOG_ADDR` follows the same rule for the same reason: the personhog client is a cached singleton keyed off settings at its first call, and bootstrap-phase reads run before the async-phase `override_settings`.+`__main__` therefore sets it in the environment before `django.setup()`, pointing at the harness's own router on 15052 — which also shields the run from a `PERSONHOG_ADDR` leaked out of a sourced dev `.env`, where reads would silently hit the dev persons DB.++Env loading follows the same before-`django.setup()` rule: `__main__` loads the repo-root `.env` via `env_preflight.load_env_file()` (a stdlib parser that decodes `.env`'s quoted/escaped PEM keys, which hogli's line-based parser cannot represent), never overriding variables the shell or hogli's env loading already exported.+`products/signals/eval/conftest.py` reuses the same loader, so it is the repo's one `.env` parser — keep it dependency-free.+The explicit `SANDBOX_PROVIDER` / `PERSONHOG_ADDR` assignments come after the load, so they trump any env file on every path.++`setup_django()` also forces `SELF_CAPTURE=0` before `django.setup()`. The ASGI app must not re-enable the global SDK with the local development personal API key during evals; eval trace emission uses the harness's explicit regional client instead.+Required variables are then validated by `env_preflight.validate_eval_env()` at the top of `lifecycle.run()`, before any infrastructure boots — add new hard env requirements to the per-kind env models there (`SandboxEvalEnv`, `OneShotEvalEnv`), or, for engine-specific keys, to the engine's `required_env()` (`BRAINTRUST_API_KEY` lives on `BraintrustEngine`), which `lifecycle` threads in via the `engine_env` argument — not as ad-hoc checks scattered through bootstrap.++## pytest++This tree is not pytest: do not add a `conftest.py` here and do not import `pytest` in harness or eval modules.+The harness's own unit tests live in [`../test/`](../test/), which is ordinary pytest.+Suite files under the `evals/` trees are never collected by pytest either — its default `python_files` only matches `test_*.py`.+`ee/hogai/eval/ci/` and `ee/hogai/eval/offline/` are still pytest and still import `data_setup` from this package, so keep that module's pytest-independence intact.diff --git a/ee/hogai/eval/sandboxed/CLAUDE.md b/products/posthog_ai/eval_harness/harness/CLAUDE.mdsimilarity index 100%rename from ee/hogai/eval/sandboxed/CLAUDE.mdrename to products/posthog_ai/eval_harness/harness/CLAUDE.mddiff --git a/products/posthog_ai/eval_harness/harness/README.md b/products/posthog_ai/eval_harness/harness/README.mdnew file mode 100644index 000000000000..dcceac4bef96--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/README.md@@ -0,0 +1,108 @@+# The sandboxed eval harness++This package is the runner for `products/posthog_ai/eval_harness/`.+For how to _use_ it, read [`../README.md`](../README.md).+For the rules to preserve when _changing_ it, read [`AGENTS.md`](AGENTS.md).+This file explains how it fits together.++## Why it exists++The sandboxed evals need heavy shared infrastructure: a committed test database, an in-process Django server the sandbox can call back into, an LLM gateway, an MCP server, and a Temporal server plus worker.+Under pytest that infrastructure lived in session fixtures, and suites ran strictly one at a time, with Braintrust parallelizing only _within_ a suite.+Wall-clock was dominated by suites queueing behind each other while sandbox capacity sat idle.++The harness boots the same infrastructure once, then runs every suite concurrently on a single event loop and bounds sandbox and team-setup load with shared semaphores.+Braintrust remains the eval engine and reporting backend; it just no longer controls scheduling.+The `EvalAsync` call itself lives behind an `EvalEngine` seam (`../engines/`): `_BaseEvalRun.run()` hands a neutral `ExperimentSpec` to the engine resolved by `engines/registry.resolve_engine()` (shared via `EvalContext.engine`) and gets back a neutral `ExperimentResult` (`engines/types.py`), so a future PostHog-native engine can slot in behind the same interface — implementing the `EvalEngine` protocol and passing the conformance suite — without touching the run base or any suite.++Not every suite is sandboxed anymore: each suite declares a `SUITE_KIND` (`requirements.py`), the kind maps to a set of `Infra` requirements, and the harness boots only the union of what the selected suites need.+A run of one-shot suites never pays for — or fails preflight on — the sandbox provider, Temporal, the live server, the LLM gateway, or the MCP server.++## Modules++| Module | Role |+| ------------------ | --------------------------------------------------------------------------------------------------------------------------------- |+| `__main__.py` | Entry point. Parses args, starts the transcript, configures Django, then hands off to `lifecycle`. |+| `cli.py` | `HarnessOptions` and the argparse builder. Resolves per-provider defaults. |+| `env_preflight.py` | Loads the repo-root `.env` (stdlib parser, shell wins) and validates per-kind env vars via pydantic models. |+| `ports.py` | The six port constants. Deliberately free of Django imports. |+| `providers.py` | `SandboxProviderStrategy` and its docker/modal implementations: preflight, settings overrides, sandbox TTL, cleanup. |+| `tunnels.py` | `NgrokTunnels`. Modal only: generates an ngrok config, starts the agent, waits for public URLs. |+| `requirements.py` | `SuiteKind`, `Infra`, and the kind → infrastructure mapping (with implication closure). |+| `django_env.py` | `setup_django()`, the `NullDbBlocker` shim, and `EvalDatabase` (test database lifecycle). |+| `live_server.py` | `EvalLiveServer`, a session-lifetime Uvicorn server for PostHog's full ASGI application. |+| `services.py` | Starts the LLM gateway, MCP server, and personhog subprocesses; builds local skills. |+| `temporal_env.py` | Local Temporal dev server, stale-workflow cleanup, and the worker thread. |+| `demo_data.py` | `SandboxedDemoData`: seeds the master Hedgebox team once, then mints an isolated team per case. |+| `discovery.py` | Walks the tree for `eval_*.py` and collects `eval_*` coroutines into `EvalSuite` objects. |+| `context.py` | `EvalContext`, the single object every suite receives. |+| `reporting.py` | `ProgressReporter` and the final summary table. The quiet Braintrust reporter lives with the engine (`../engines/braintrust.py`). |+| `transcript.py` | Mirrors stdout and stderr to one run log, then publishes its absolute path as the final line. |+| `lifecycle.py` | `SandboxedEvalHarness`: orchestrates bootstrap, the run, and teardown. |++## Boot sequence++Discovery happens first, before anything is provisioned, so a typo'd selector costs a module import rather than a database build.+Every step below is gated on the selected suites' infrastructure union — a step whose `Infra` member no run requires is skipped, and skipped steps register no teardown.+The sequence as written is the sandboxed (full) path; a one-shot-only run performs just steps 1–3 and 8.++The bootstrap is deliberately synchronous and runs before any event loop exists, because it is ORM-heavy and Django's async-safety guard rejects sync ORM calls from an async context:++1. `__main__` creates the run transcript, then loads the repo-root `.env` (never overriding what the shell — or hogli's own env loading, under `hogli evals` — already exported), then `setup_django()` sets `DEBUG` / `TEST` / `IN_EVAL_TESTING`, forces `SELF_CAPTURE=0`, and runs `django.setup()` and `setup_test_environment()`. Eval telemetry still uses the explicit regional client configured by the harness.+ The env preflight (required variables, one-line fix per missing one) and provider preflight then run, followed by the personhog binary build (`cargo build`, incremental after the first run) — a missing key or toolchain fails here, before any database work.+2. `EvalDatabase.setup()` creates the `default` test database and drives PostHog's own eval database setup (persons database, ClickHouse).+3. `personhog-replica` (`:15051`) and `personhog-router` (`:15052`) start against the test persons database — before anything can query, so a dead router never poisons the negative group-types cache.+4. `EvalLiveServer` serves PostHog's ASGI application on `0.0.0.0:18000`, including the sandbox event-ingest route.+5. The LLM gateway (`:13308`) and MCP server (`:18787`) start as subprocesses.+6. Docker only: the `posthog-sandbox-base` image freshness check runs (rebuilding on a new `@posthog/agent` version or Dockerfile change). Modal only: ngrok tunnels come up, exposing the callback services publicly.+7. Local skills are built. Docker bind-mounts them; Modal bakes them into the image it builds.+8. The master Hedgebox team is seeded.++The async phase then starts the Temporal dev server on the main loop, applies the provider's settings overrides, terminates stale workflows, starts the Temporal worker on its own thread and loop, and fans the suites out with `asyncio.gather`.++Teardown unwinds an `ExitStack` and an `AsyncExitStack` in reverse.+`atexit` hooks and the subprocess manager's signal handlers cover the Ctrl-C path, where neither stack unwinds.+The final summary renders after teardown, logging is flushed, and the transcript path is emitted last.++## Output model++The reporter emits plain-text records with stable labels so terminals and agents can scan the same output.+`START` marks work entering flight, `DONE` marks successful completion, and `TIMEOUT`, `ERROR`, or `CRASH` name exceptional outcomes.+Only the final overall run status uses `PASS` or `FAIL`.++Every invocation that attempts an eval writes the combined stdout/stderr stream to `logs/harness/<timestamp>_<id>.log`.+An explanatory line identifies the full run transcript, followed by the log's unlabeled absolute path as the final line in both the transcript and terminal.+`logs/harness/latest.log` points to it.+Discovery-only `--list` invocations and argument errors do not write transcripts.++## Concurrency model++One `asyncio.Semaphore` on `EvalContext` bounds live sandboxes across every suite.+`base.py::task()` acquires it around exactly the sandbox-owning window and releases it before post-processing.++Two consequences worth internalizing:++- The per-case timeout is an `asyncio.wait_for` **inside** the slot. Braintrust's own `timeout` would have wrapped the whole task invocation, including time queued on the semaphore, killing cases that never got a sandbox.+- A second `team_setup_slots` semaphore covers the full demo-data clone plus optional case seeder. It has one permit on ordinary local machines and four when `CODER` or `CI` is set, so managed environments prepare cases faster without making setup concurrency follow Modal's unbounded sandbox capacity.+- The agent timeout begins after team setup. Waiting for either semaphore never consumes it.+- One-shot suites never touch the sandbox semaphore; a separate global `one_shot_slots` semaphore bounds their concurrently running cases under the same acquire-once, budget-inside rules.++There are two event loops. The main loop owns the Temporal dev server, the suites, and the reporter.+The Temporal worker keeps its own loop on a daemon thread, and the two communicate only through `loop.call_soon_threadsafe`.++## Provider differences++| | docker | modal |+| ------------------- | ----------------------------- | ------------------------- |+| `SANDBOX_PROVIDER` | `docker` | `MODAL_EVALS` |+| Service URLs | `host.docker.internal:<port>` | ngrok public URLs |+| `start()` | base-image freshness check | ngrok tunnels |+| Local skills | bind-mounted | baked into the image |+| Default sandbox cap | 4 | unbounded |+| Sandbox TTL | default | case timeout plus margin |+| Per-case safety net | container sweep | task-tagged sandbox sweep |+| End-of-run cleanup | container sweep | task-tagged sandbox sweep |++`MODAL_EVALS` is the same `ModalSandbox` class under the dedicated `posthog-sandbox-evals` app, so eval image builds do not share an image cache with production or local development sandboxes.++The modal TTL override exists because under `TEST=1` the sandbox TTL equals the default per-case timeout, which would let Modal reap a slow case's sandbox exactly as it was finishing.diff --git a/products/posthog_ai/eval_harness/harness/__init__.py b/products/posthog_ai/eval_harness/harness/__init__.pynew file mode 100644index 000000000000..85e1721612a9--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/__init__.py@@ -0,0 +1,9 @@+"""Standalone runner for the sandboxed agent evals.++Replaces pytest as the driver: boots the shared session infrastructure once+(test DB, Django live server, LLM gateway, MCP server, Temporal), then runs+every selected eval suite concurrently on one event loop with a single global+sandbox semaphore bounding total load. Braintrust stays as the eval engine.++ python -m products.posthog_ai.eval_harness.harness --help+"""diff --git a/products/posthog_ai/eval_harness/harness/__main__.py b/products/posthog_ai/eval_harness/harness/__main__.pynew file mode 100644index 000000000000..06f9d73cbbd8--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/__main__.py@@ -0,0 +1,91 @@+from __future__ import annotations++import os+import sys+import logging++from .cli import HarnessOptions, parse_args+from .django_env import setup_django+from .env_preflight import load_env_file+from .ports import PERSONHOG_ROUTER_PORT+from .providers import SANDBOX_PROVIDER_SETTING, PreflightError+from .transcript import RunTranscript++USAGE_ERROR_EXIT_CODE = 2+++def _run(options: HarnessOptions) -> int:+ # Load the repo-root .env before Django reads the environment, so the harness+ # works without a manual `set -a; source .env`. Shell values win, and the+ # explicit overrides below still trump anything an env file provided.+ load_env_file()++ # Select the sandbox class before Django loads settings. products.tasks resolves+ # settings.SANDBOX_PROVIDER once and caches the class in module globals, so the+ # async-phase override_settings runs too late to change it. .env ships+ # SANDBOX_PROVIDER=docker, so without this a modal run would cache DockerSandbox+ # and execute locally. See SANDBOX_PROVIDER_SETTING. Set unconditionally — on a+ # run without sandboxed suites it only selects a class nothing instantiates.+ os.environ["SANDBOX_PROVIDER"] = SANDBOX_PROVIDER_SETTING[options.provider]++ # Point person/group reads at the harness's own personhog router before Django+ # loads settings. PERSONHOG_ADDR is read from env once at django.setup(), and the+ # personhog client is a cached singleton keyed off that setting at its first call.+ # Bootstrap-phase reads (demo seeding, taxonomy inference) run before the+ # async-phase override_settings, so setting it there would be too late — the+ # singleton is already built. A PERSONHOG_ADDR leaked from a sourced dev .env+ # would otherwise silently point eval reads at the dev persons DB.+ os.environ["PERSONHOG_ADDR"] = f"127.0.0.1:{PERSONHOG_ROUTER_PORT}"++ setup_django()++ # Deferred so Django is configured first: everything below reaches settings,+ # the ORM, or the products.tasks facade at import time.+ from .discovery import SuiteDiscoveryError # noqa: PLC0415 — must import after django.setup()+ from .lifecycle import SandboxedEvalHarness # noqa: PLC0415 — must import after django.setup()++ try:+ return SandboxedEvalHarness(options).run()+ except (PreflightError, SuiteDiscoveryError) as e:+ # A missing prerequisite or a typo'd selector is user error, not a harness+ # bug: say what's wrong without a traceback.+ print(f"error: {e}", file=sys.stderr) # noqa: T201+ return USAGE_ERROR_EXIT_CODE+++def _configure_logging() -> None:+ logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)-7s %(name)s: %(message)s",+ force=True,+ )+++def main(argv: list[str] | None = None) -> int:+ options = parse_args(argv)+ if options.list_only:+ _configure_logging()+ return _run(options)++ transcript = RunTranscript.create()+ exit_code = 1+ try:+ with transcript.capture():+ _configure_logging()+ try:+ exit_code = _run(options)+ except KeyboardInterrupt:+ logging.getLogger(__name__).warning("Interrupted")+ exit_code = 130+ except Exception:+ logging.getLogger(__name__).exception("Sandboxed eval harness failed")+ exit_code = 1+ finally:+ logging.shutdown()+ finally:+ transcript.finish()+ return exit_code+++if __name__ == "__main__":+ sys.exit(main())diff --git a/products/posthog_ai/eval_harness/harness/cli.py b/products/posthog_ai/eval_harness/harness/cli.pynew file mode 100644index 000000000000..7f929856c1a6--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/cli.py@@ -0,0 +1,225 @@+from __future__ import annotations++import os+import argparse+from dataclasses import dataclass+from typing import cast, get_args++from .providers import DockerProviderStrategy, ModalProviderStrategy, SandboxProvider++# Bare model ids, no "anthropic/"/"openai/" prefix: the LLM gateway checks the model+# against a bare-id allowlist with startswith, so the prefixed form is rejected with a+# 403 and the agent finishes without doing anything — while still scoring exit_code_zero=1.+DEFAULT_AGENT_MODEL = "claude-opus-4-8"+DEFAULT_CODEX_AGENT_MODEL = "gpt-5.5"++# Literal mirror of products.tasks' RuntimeAdapter values: this module must stay+# Django-free (see harness/AGENTS.md), so it cannot import the enum.+AGENT_RUNTIMES = ("claude", "codex")+DEFAULT_AGENT_MODEL_BY_RUNTIME = {"claude": DEFAULT_AGENT_MODEL, "codex": DEFAULT_CODEX_AGENT_MODEL}+DEFAULT_CASE_TIMEOUT_SECONDS = 60 * 15+OFFLINE_CASE_TIMEOUT_SECONDS = 60 * 60++DEFAULT_TEAM_SETUP_CONCURRENCY = 1+MANAGED_TEAM_SETUP_CONCURRENCY = 4+"""Per-case team setups allowed at once. Managed Coder and CI environments can+absorb parallel ClickHouse copies; ordinary local machines stay conservative."""++DEFAULT_ONE_SHOT_CONCURRENCY = 8+"""Concurrently running one-shot cases across all suites — bounds LLM API and+local query load the same way sandbox slots bound sandboxes."""++UNBOUNDED_SANDBOXES = 1 << 20+"""Semaphore value standing in for "no limit" — larger than any case count."""+++@dataclass(frozen=True)+class HarnessOptions:+ selectors: tuple[str, ...]+ provider: SandboxProvider+ case_filter: str | None+ agent_model: str+ agent_runtime: str+ reasoning_effort: str | None+ max_sandboxes: int+ team_setup_concurrency: int+ """Concurrent team-cloning and case-seeding phases for this run."""++ keep_sandbox_containers: bool+ rebuild_sandbox_image: bool+ create_db: bool+ list_only: bool+ per_case_timeout_seconds: int+ trials: int+ fail_under: float | None+ sandbox_flags_set: tuple[str, ...]+ """Sandbox-only flags the user passed explicitly, so a run without sandboxed+ suites can reject them instead of silently ignoring them."""+++def _default_case_timeout() -> int:+ if os.getenv("EVAL_MODE") == "offline":+ return OFFLINE_CASE_TIMEOUT_SECONDS+ return DEFAULT_CASE_TIMEOUT_SECONDS+++def _default_team_setup_concurrency() -> int:+ if os.getenv("CODER") is not None or os.getenv("CI") is not None:+ return MANAGED_TEAM_SETUP_CONCURRENCY+ return DEFAULT_TEAM_SETUP_CONCURRENCY+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ prog="python -m products.posthog_ai.eval_harness.harness",+ description=(+ "Run the sandboxed agent evals. Boots the shared session infrastructure once, "+ "then runs every selected suite concurrently under a single global sandbox limit."+ ),+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,+ )+ parser.add_argument(+ "selectors",+ nargs="*",+ help="Substring selectors matched against '<domain>/<module>::<fn>'. Omit to run everything.",+ )+ parser.add_argument(+ "--provider",+ choices=get_args(SandboxProvider),+ default=None,+ help="Where sandboxes run (default: docker). 'modal' starts ngrok tunnels so remote sandboxes can reach this host.",+ )+ parser.add_argument("--eval", dest="case_filter", default=None, help="Only run cases whose name contains this.")+ parser.add_argument(+ "--agent-model",+ default=None,+ help=(+ f"Model the sandboxed agent runs against "+ f"(default: {DEFAULT_AGENT_MODEL} for claude, {DEFAULT_CODEX_AGENT_MODEL} for codex)."+ ),+ )+ parser.add_argument(+ "--agent-runtime",+ choices=AGENT_RUNTIMES,+ default=None,+ help="Agent runtime serving the model (default: claude). 'codex' additionally requires LLM_GATEWAY_OPENAI_API_KEY.",+ )+ parser.add_argument(+ "--reasoning-effort",+ default=None,+ help="Agent reasoning effort (e.g. 'low'…'xhigh'); valid values depend on runtime+model.",+ )+ parser.add_argument(+ "--max-sandboxes",+ type=int,+ default=None,+ help=(+ f"Concurrently live sandboxes across all suites "+ f"(default: {DockerProviderStrategy.default_max_sandboxes} for docker, unbounded for modal)."+ ),+ )+ parser.add_argument(+ "--keep-sandbox-containers",+ action="store_true",+ help="Skip the end-of-run Docker container sweep, for debugging a leftover container.",+ )+ parser.add_argument(+ "--rebuild-sandbox-image",+ action="store_true",+ help="Force a rebuild of the posthog-sandbox-base image before the run (docker only).",+ )+ parser.add_argument(+ "--create-db", action="store_true", help="Rebuild the eval test database instead of reusing it."+ )+ parser.add_argument(+ "--list", dest="list_only", action="store_true", help="Print the discovered suite ids and exit."+ )+ parser.add_argument(+ "--case-timeout",+ type=int,+ default=None,+ help=f"Agent-run budget in seconds, started after team setup; must be at least 1 (default: {_default_case_timeout()}).",+ )+ parser.add_argument(+ "--trials",+ type=int,+ default=1,+ help="Run every case this many times (Braintrust trials), to measure variance on stochastic agents.",+ )+ parser.add_argument(+ "--fail-under",+ type=float,+ default=None,+ help="Exit nonzero when the mean score across all experiments falls below this fraction (0-1).",+ )+ return parser+++def parse_args(argv: list[str] | None = None) -> HarnessOptions:+ parser = build_parser()+ args = parser.parse_args(argv)++ # Sandbox-only flags keep None/False defaults so an explicit use is+ # detectable: a run without sandboxed suites rejects them in preflight+ # instead of silently ignoring them.+ sandbox_flags_set = tuple(+ flag+ for flag, is_set in (+ ("--provider", args.provider is not None),+ ("--agent-runtime", args.agent_runtime is not None),+ ("--reasoning-effort", args.reasoning_effort is not None),+ ("--max-sandboxes", args.max_sandboxes is not None),+ ("--keep-sandbox-containers", args.keep_sandbox_containers),+ ("--rebuild-sandbox-image", args.rebuild_sandbox_image),+ )+ if is_set+ )+ provider = cast(SandboxProvider, args.provider or "docker")+ agent_runtime = args.agent_runtime or "claude"++ if args.max_sandboxes is not None and args.max_sandboxes < 1:+ parser.error("--max-sandboxes must be at least 1")+ if args.keep_sandbox_containers and provider != "docker":+ parser.error("--keep-sandbox-containers only applies to --provider docker")+ if args.rebuild_sandbox_image and provider != "docker":+ parser.error("--rebuild-sandbox-image only applies to --provider docker")+ if args.trials < 1:+ parser.error("--trials must be at least 1")+ if args.case_timeout is not None and args.case_timeout < 1:+ parser.error("--case-timeout must be at least 1")++ # A runtime/model mismatch otherwise surfaces minutes into the run as an opaque+ # gateway 403, with the agent finishing without doing anything.+ agent_model = args.agent_model or DEFAULT_AGENT_MODEL_BY_RUNTIME[agent_runtime]+ if agent_runtime == "codex" and agent_model.startswith("claude"):+ parser.error(f"--agent-model {agent_model} is a Claude model; the codex runtime serves gpt-* models")+ if agent_runtime == "claude" and agent_model.startswith("gpt"):+ parser.error(f"--agent-model {agent_model} is an OpenAI model; pass --agent-runtime codex to serve it")+ if args.fail_under is not None and not (0 < args.fail_under <= 1):+ parser.error("--fail-under must be greater than 0 and at most 1")++ default_slots = (+ DockerProviderStrategy.default_max_sandboxes+ if provider == "docker"+ else ModalProviderStrategy.default_max_sandboxes+ )+ max_sandboxes = args.max_sandboxes or default_slots or UNBOUNDED_SANDBOXES++ return HarnessOptions(+ selectors=tuple(args.selectors),+ provider=provider,+ case_filter=args.case_filter,+ agent_model=agent_model,+ agent_runtime=agent_runtime,+ reasoning_effort=args.reasoning_effort,+ max_sandboxes=max_sandboxes,+ team_setup_concurrency=_default_team_setup_concurrency(),+ keep_sandbox_containers=args.keep_sandbox_containers,+ rebuild_sandbox_image=args.rebuild_sandbox_image,+ create_db=args.create_db,+ list_only=args.list_only,+ per_case_timeout_seconds=args.case_timeout if args.case_timeout is not None else _default_case_timeout(),+ trials=args.trials,+ fail_under=args.fail_under,+ sandbox_flags_set=sandbox_flags_set,+ )diff --git a/products/posthog_ai/eval_harness/harness/context.py b/products/posthog_ai/eval_harness/harness/context.pynew file mode 100644index 000000000000..1cf6bdc03a98--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/context.py@@ -0,0 +1,76 @@+from __future__ import annotations++import asyncio+from dataclasses import dataclass++from posthoganalytics import Posthog++from ..engines.base import EvalEngine+from .demo_data import SandboxedDemoData+from .providers import SandboxProvider, SandboxProviderStrategy+from .reporting import ProgressReporter+++@dataclass+class EvalContext:+ """Everything a suite function needs, assembled once per harness run.++ Replaces the pytest fixtures (``sandboxed_demo_data``, ``pytestconfig``,+ ``posthog_client``) that suites used to take individually. Passed unchanged+ down into ``SandboxedEval`` / ``OneShotEval``.++ Infra-backed fields are ``None`` when the run's suite kinds didn't require+ that infrastructure to boot; the runners narrow them and fail loudly if a+ suite's ``SUITE_KIND`` under-declares what it uses.+ """++ provider: SandboxProvider+ """Provider label, kept for display and metadata only."""++ provider_strategy: SandboxProviderStrategy | None+ """The live provider strategy — the behavior hook for per-case teardown.+ ``None`` when no selected suite is sandboxed."""++ agent_model: str+ """Model every agent or one-shot generation runs against. Pinned for stable+ comparisons."""++ agent_runtime: str+ """Runtime adapter serving the sandboxed agent's model (``"claude"`` | ``"codex"``)."""++ reasoning_effort: str | None+ """Agent reasoning effort override; ``None`` keeps the agent server's default."""++ case_filter: str | None+ """Substring filter on case names, from ``--eval``."""++ demo_data: SandboxedDemoData | None+ """Master Hedgebox seed plus the per-case isolated team factory. ``None``+ when no selected suite requires demo data."""++ posthog_client: Posthog | None+ """Analytics client for eval trace + evaluation event capture."""++ sandbox_slots: asyncio.Semaphore | None+ """The one global limiter on concurrently live sandboxes, shared by every+ suite. ``None`` when no selected suite is sandboxed."""++ team_setup_slots: asyncio.Semaphore+ """Bounds concurrent team cloning and case seeders to protect ClickHouse RAM."""++ one_shot_slots: asyncio.Semaphore+ """The one global limiter on concurrently running one-shot cases, shared by+ every suite — the one-shot analog of ``sandbox_slots``."""++ reporter: ProgressReporter+ """Owns all terminal output and the ``eval_results.jsonl`` export."""++ engine: EvalEngine+ """The execution/reporting backend every suite runs on, resolved once per run."""++ per_case_timeout_seconds: int+ """Budget for the agent run, started after team setup so queueing cannot consume it."""++ trials: int+ """Times each case runs. Agents are stochastic, so N runs per case measure+ the variance a single run can't reveal."""diff --git a/products/posthog_ai/eval_harness/harness/demo_data.py b/products/posthog_ai/eval_harness/harness/demo_data.pynew file mode 100644index 000000000000..1f8de0e3ec80--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/demo_data.py@@ -0,0 +1,131 @@+from __future__ import annotations++import logging+from datetime import timedelta++from django.apps import apps++from posthog.clickhouse.client import sync_execute++from products.posthog_ai.eval_harness.data_setup import (+ copy_demo_data_to_new_team,+ create_core_memory,+ ensure_master_demo_team,+)+from products.tasks.backend.facade.agents import CustomPromptSandboxContext++from ee.clickhouse.materialized_columns.columns import (+ backfill_materialized_columns,+ get_materialized_columns,+ materialize,+)++from .django_env import NullDbBlocker++logger = logging.getLogger(__name__)+++class SandboxedDemoData:+ """Run-scoped holder for master demo seed + per-case team factory.++ One instance per harness run: seeds the master Hedgebox team (or reuses+ a healthy one), then produces a fresh isolated ``CustomPromptSandboxContext``+ for every eval case via ``make_context(label)``. Each call copies the master+ into a brand-new org/team/user with its own core memory and tasks-API+ access, so concurrent eval cases can't pollute each other's state.+ """++ def __init__(+ self,+ master_team_id: int,+ django_db_blocker: NullDbBlocker,+ agent_model: str | None = None,+ agent_runtime: str | None = None,+ reasoning_effort: str | None = None,+ sandbox_timeout_seconds: int | None = None,+ ):+ self.master_team_id = master_team_id+ self._django_db_blocker = django_db_blocker+ self.agent_model = agent_model+ self.agent_runtime = agent_runtime+ self.reasoning_effort = reasoning_effort+ self.sandbox_timeout_seconds = sandbox_timeout_seconds++ def make_context(self, case_label: str) -> CustomPromptSandboxContext:+ CodeInvite = apps.get_model("tasks", "CodeInvite")+ CodeInviteRedemption = apps.get_model("tasks", "CodeInviteRedemption")++ org, team, user = copy_demo_data_to_new_team(self.master_team_id, self._django_db_blocker, label=case_label)+ create_core_memory(team, self._django_db_blocker)+ with self._django_db_blocker.unblock():+ invite, _ = CodeInvite.objects.get_or_create(code="eval-harness", max_redemptions=0, is_active=True)+ CodeInviteRedemption.objects.get_or_create(invite_code=invite, user=user, organization=org)+ logger.info("Case %r assigned team_id=%d user_id=%d", case_label, team.id, user.id)+ return CustomPromptSandboxContext(+ team_id=team.id,+ user_id=user.id,+ repository="posthog/hedgebox",+ model=self.agent_model,+ runtime_adapter=self.agent_runtime,+ reasoning_effort=self.reasoning_effort,+ # Under TEST=1, SANDBOX_TTL_SECONDS is 15 minutes — equal to the default+ # per-case timeout — so a slow Modal case would have its sandbox reaped+ # exactly as it was finishing. The modal provider passes a larger TTL here.+ sandbox_timeout_seconds=self.sandbox_timeout_seconds,+ )+++# Event-level properties the error-tracking ``searchQuery`` test cases match on+# (see ``products/error_tracking/backend/hogql_queries/error_tracking_query_runner_utils.py``).+# These are stored as JSON arrays (``["TypeError"]``); without materialized+# columns the bare ``properties.$exception_types`` lookup goes through+# ``JSONExtractString`` which returns ``""`` for non-string JSON values, so+# ``searchQuery`` filtering on these properties silently never matches anything.+# Materializing and backfilling once per session makes the sandbox behave like+# prod for error-tracking searchQuery, including reused local ClickHouse state+# where the columns already exist but older demo rows still need values.+_EVAL_MATERIALIZED_EVENT_PROPERTIES: tuple[str, ...] = (+ "$exception_types",+ "$exception_values",+)+++def _ensure_event_search_columns_materialized(django_db_blocker: NullDbBlocker) -> None:+ with django_db_blocker.unblock():+ existing_columns = get_materialized_columns("events")+ columns = []+ for property_name in _EVAL_MATERIALIZED_EVENT_PROPERTIES:+ column = existing_columns.get((property_name, "properties"))+ if column is None:+ column = materialize("events", property_name)+ columns.append(column)+ backfill_materialized_columns("events", columns, timedelta(days=180))+++def ensure_demo_ready(+ *,+ blocker: NullDbBlocker,+ agent_model: str,+ agent_runtime: str,+ reasoning_effort: str | None,+ sandbox_timeout_seconds: int | None,+) -> SandboxedDemoData:+ """Seed the master Hedgebox team (once) and expose a per-case context factory."""+ master_team_id = ensure_master_demo_team(blocker)+ _ensure_event_search_columns_materialized(blocker)+ with blocker.unblock():+ rows = sync_execute(+ "SELECT event, count() FROM events WHERE team_id = %(team_id)s GROUP BY event ORDER BY 2 DESC LIMIT 20",+ {"team_id": master_team_id},+ )+ logger.info("Master demo ready: team_id=%d event_counts=%s", master_team_id, rows)+ logger.info("Sandboxed eval agent pinned to model=%r runtime=%r", agent_model, agent_runtime)++ return SandboxedDemoData(+ master_team_id=master_team_id,+ django_db_blocker=blocker,+ agent_model=agent_model,+ agent_runtime=agent_runtime,+ reasoning_effort=reasoning_effort,+ sandbox_timeout_seconds=sandbox_timeout_seconds,+ )diff --git a/products/posthog_ai/eval_harness/harness/discovery.py b/products/posthog_ai/eval_harness/harness/discovery.pynew file mode 100644index 000000000000..458fde1952c0--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/discovery.py@@ -0,0 +1,151 @@+from __future__ import annotations++import inspect+import logging+import importlib+from collections.abc import Callable, Coroutine, Iterator, Sequence+from dataclasses import dataclass+from pathlib import Path+from types import ModuleType+from typing import TYPE_CHECKING, Any++from .requirements import SuiteKind++if TYPE_CHECKING:+ from .context import EvalContext++logger = logging.getLogger(__name__)++BUILTIN_EVALS_PACKAGE = "products.posthog_ai.evals"+REPO_ROOT = Path(__file__).resolve().parents[4]+BUILTIN_EVALS_ROOT = REPO_ROOT / "products" / "posthog_ai" / "evals"+PRODUCTS_ROOT = REPO_ROOT / "products"++EvalSuiteFn = Callable[["EvalContext"], Coroutine[Any, Any, None]]+++class SuiteDiscoveryError(RuntimeError):+ pass+++@dataclass(frozen=True)+class EvalSuite:+ domain: str+ """Directory the suite lives in, e.g. ``experiments`` for a sandboxed suite or+ ``<product>`` for a product-owned suite. ``root`` for top-level sandboxed files."""++ module_name: str+ fn_name: str+ fn: EvalSuiteFn++ kind: SuiteKind = SuiteKind.SANDBOXED+ """How the suite's cases execute, from the module-level ``SUITE_KIND``."""++ @property+ def id(self) -> str:+ return f"{self.domain}/{self.module_name}::{self.fn_name}"+++def _builtin_modules(root: Path) -> Iterator[tuple[str, str, str]]:+ """Yield ``(domain, module_name, dotted)`` for every ``eval_*.py`` in the+ built-in evals tree. The domain falls out of the directory the file lives in."""+ for path in sorted(root.rglob("eval_*.py")):+ relative = path.relative_to(root)+ domain = relative.parent.as_posix().replace("/", ".") if relative.parent != Path(".") else "root"+ dotted_parent = "" if domain == "root" else f".{domain}"+ yield domain, path.stem, f"{BUILTIN_EVALS_PACKAGE}{dotted_parent}.{path.stem}"+++def _product_modules(root: Path, *, exclude_root: Path) -> Iterator[tuple[str, str, str]]:+ """Yield ``(domain, module_name, dotted)`` for every ``eval_*.py`` under a+ ``products/<product>/evals/`` tree (plural ``evals`` — the singular+ ``products/signals/eval/`` pytest tree is deliberately not matched).++ The built-in tree (``exclude_root``) also matches the glob, but its suites keep+ their per-directory domains, so ``_builtin_modules`` owns it and it is skipped here.++ The import anchor is ``root.parent`` (the repo root for the real+ ``products/`` dir), so the dotted path is ``<root name>.<product>.evals.…`` —+ ``products.<product>.evals.<module>`` in production."""+ for path in sorted(root.glob("*/evals/**/eval_*.py")):+ if path.resolve().is_relative_to(exclude_root.resolve()):+ continue+ relative = path.relative_to(root)+ product = relative.parts[0]+ dotted = ".".join([root.name, *relative.with_suffix("").parts])+ yield product, path.stem, dotted+++def _import_suite_module(dotted: str, module_target: str, selectors: Sequence[str]) -> ModuleType | None:+ """Import a discovered module, applying the shared import-failure policy.++ A selected run only cares about the modules its selectors target, so a broken+ *unrelated* module is skipped. A no-selector run (full run or ``--list``) is+ the repo's import smoke check, so there a failure stays fatal.++ Selectors are matched against ``<domain>/<module>`` (not the full+ ``<domain>/<module>::<fn>`` suite id): a module that failed to import has no+ function names to build ids from, so a ``::fn``-style selector can't match here+ and the module is treated as unrelated — acceptable, since such a selector+ still fails the run loudly via the "No eval suites matched" check.+ """+ try:+ return importlib.import_module(dotted)+ except Exception as e:+ if selectors and not any(selector in module_target for selector in selectors):+ logger.warning("Skipping unselected eval module %s that failed to import: %s", dotted, e)+ return None+ raise SuiteDiscoveryError(f"Failed to import eval module {dotted}: {e}") from e+++def _collect_suites(module: ModuleType, domain: str, module_name: str, dotted: str) -> list[EvalSuite]:+ kind = getattr(module, "SUITE_KIND", SuiteKind.SANDBOXED)+ if not isinstance(kind, SuiteKind):+ raise SuiteDiscoveryError(f"{dotted}.SUITE_KIND must be a SuiteKind member, got {kind!r}")+ collected: list[EvalSuite] = []+ for fn_name, fn in vars(module).items():+ if not fn_name.startswith("eval_") or not inspect.iscoroutinefunction(fn):+ continue+ # Only functions defined here — an `eval_*` imported from a sibling+ # module would otherwise be collected twice.+ if fn.__module__ != dotted:+ continue+ collected.append(EvalSuite(domain=domain, module_name=module_name, fn_name=fn_name, fn=fn, kind=kind))+ return collected+++def discover_suites(+ selectors: Sequence[str] = (),+ *,+ builtin_root: Path = BUILTIN_EVALS_ROOT,+ products_root: Path = PRODUCTS_ROOT,+) -> list[EvalSuite]:+ """Import every ``eval_*.py`` under the built-in evals tree and the+ ``products/*/evals/`` trees, and collect their ``eval_*`` coroutines.++ Convention over registry: a new eval file is picked up with no boilerplate,+ and its domain falls out of the directory it lives in. Roots are injectable so+ discovery can be exercised against a fixture tree in tests.+ """+ modules: list[tuple[str, str, str]] = [+ *_builtin_modules(builtin_root),+ *_product_modules(products_root, exclude_root=builtin_root),+ ]++ suites: list[EvalSuite] = []+ for domain, module_name, dotted in modules:+ module_target = f"{domain}/{module_name}"+ module = _import_suite_module(dotted, module_target, selectors)+ if module is None:+ continue+ suites.extend(_collect_suites(module, domain, module_name, dotted))++ if not selectors:+ return suites++ selected = [suite for suite in suites if any(selector in suite.id for selector in selectors)]+ if not selected:+ raise SuiteDiscoveryError(+ f"No eval suites matched {list(selectors)}. Run with --list to see the available suite ids."+ )+ return selecteddiff --git a/products/posthog_ai/eval_harness/harness/django_env.py b/products/posthog_ai/eval_harness/harness/django_env.pynew file mode 100644index 000000000000..0fb124ec318c--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/django_env.py@@ -0,0 +1,111 @@+from __future__ import annotations++import os+import logging+import contextlib+from collections.abc import Generator, Iterator+from typing import Any++import django++logger = logging.getLogger(__name__)++_DJANGO_INITIALIZED = False+++def setup_django(*, debug: bool = True) -> None:+ """Configure the environment and initialize Django for a harness run.++ Sets the eval env flags (``DEBUG``/``TEST``/``IN_EVAL_TESTING``) and disables+ local self-capture before Django reads them, then runs ``django.setup()`` and+ Django's test-environment setup. Safe to call more than once — subsequent+ calls are a no-op.+ """+ global _DJANGO_INITIALIZED+ if _DJANGO_INITIALIZED:+ return++ os.environ["DJANGO_SETTINGS_MODULE"] = "posthog.settings"+ os.environ["DEBUG"] = "1" if debug else "0"+ os.environ["TEST"] = "1"+ os.environ["IN_EVAL_TESTING"] = "1"+ # Eval traces use an explicit regional client; local self-capture would poll flags with the development API key.+ os.environ["SELF_CAPTURE"] = "0"++ django.setup()++ from django.test.utils import setup_test_environment # noqa: PLC0415 — must import only after django.setup()++ setup_test_environment()+ _DJANGO_INITIALIZED = True+++class NullDbBlocker:+ """Inert stand-in for pytest-django's ``django_db_blocker``.++ Outside pytest nothing blocks ORM access in the first place, so this only+ needs to satisfy the shared setup helpers' interface: an ``unblock()``+ context manager (the sole thing callers use, as ``with blocker.unblock():``)+ plus no-op ``block()``/``restore()``.+ """++ @contextlib.contextmanager+ def unblock(self) -> Iterator[None]:+ yield++ def block(self) -> None:+ pass++ def restore(self) -> None:+ pass+++class EvalDatabase:+ """Owns the eval test database lifecycle for a harness run.++ Mirrors what pytest-django's ``django_db_setup`` did for sandboxed evals:+ create the base Django test DB once, then drive PostHog's own eval DB setup+ (persons DB, ClickHouse) and leave it committed for the whole run. Sandboxed+ evals intentionally strip per-test DB markers to avoid transactions/flushes,+ so the base Django DB is set up explicitly here.+ """++ def __init__(self, *, keepdb: bool) -> None:+ self.keepdb = keepdb+ self.blocker = NullDbBlocker()+ self._db_cfg: Any = None+ self._eval_setup: Generator[None] | None = None++ def setup(self) -> None:+ from django.test.utils import setup_databases # noqa: PLC0415 — must import only after django.setup()++ from posthog.conftest import (+ _django_db_setup, # noqa: PLC0415 — pulls in Django models; keep off the pre-setup import path+ )++ # Only the base Django ("default") DB is created here. Person DB setup is+ # handled by PostHog's eval setup below, after the default test DB name is+ # known (see SANDBOXED_EVAL_SETUP_DATABASES in the original conftest).+ self._db_cfg = setup_databases(+ verbosity=1,+ interactive=False,+ keepdb=self.keepdb,+ aliases={"default": None},+ serialized_aliases=set(),+ )+ self._eval_setup = _django_db_setup(self.keepdb, self.blocker)+ next(self._eval_setup)++ def teardown(self) -> None:+ from django.test.utils import teardown_databases # noqa: PLC0415 — must import only after django.setup()++ if self._eval_setup is not None:+ # Run the generator's post-``yield`` cleanup (ClickHouse reset / drop).+ try:+ next(self._eval_setup)+ except StopIteration:+ pass+ self._eval_setup = None++ if not self.keepdb and self._db_cfg is not None:+ teardown_databases(self._db_cfg, verbosity=1)diff --git a/products/posthog_ai/eval_harness/harness/env_preflight.py b/products/posthog_ai/eval_harness/harness/env_preflight.pynew file mode 100644index 000000000000..cc7a81148a1e--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/env_preflight.py@@ -0,0 +1,187 @@+"""Environment loading and validation for the eval harness.++Django-free on purpose: ``__main__`` loads the env file before ``django.setup()``,+so nothing here may touch Django settings or the ORM.+"""++from __future__ import annotations++import os+import re+from collections.abc import Collection+from pathlib import Path++from pydantic import BaseModel, ConfigDict, Field, ValidationError++from ..engines.types import EnvVarSpec+from .providers import PreflightError+from .requirements import SuiteKind++REPO_ROOT = Path(__file__).parents[4]++_ASSIGNMENT_RE = re.compile(r"^\s*(?:export\s+)?(?P<key>[A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?P<value>.*)$")+_ESCAPES = {"n": "\n", "r": "\r", "t": "\t", '"': '"', "'": "'", "\\": "\\"}+++class SandboxEvalEnv(BaseModel):+ """Additional variables sandboxed suites need."""++ model_config = ConfigDict(extra="ignore")++ SANDBOX_JWT_PRIVATE_KEY: str = Field(+ min_length=1,+ description="signs the sandboxed agent's API tokens; the dev key ships in .env.example",+ )+ LLM_GATEWAY_ANTHROPIC_API_KEY: str = Field(+ min_length=1,+ description="Anthropic API key the LLM gateway proxies the agent's model calls with",+ )+++class OneShotEvalEnv(BaseModel):+ """Additional variables one-shot suites need."""++ model_config = ConfigDict(extra="ignore")++ LLM_GATEWAY_ANTHROPIC_API_KEY: str = Field(+ min_length=1,+ description="Anthropic API key one-shot generation tasks call the model with directly",+ )+++class CodexEvalEnv(BaseModel):+ """Additional variables required when sandboxed suites use the codex runtime."""++ model_config = ConfigDict(extra="ignore")++ LLM_GATEWAY_OPENAI_API_KEY: str = Field(+ min_length=1,+ description="OpenAI API key the LLM gateway proxies the codex agent's model calls with",+ )+++ENV_MODELS_BY_KIND: dict[SuiteKind, tuple[type[BaseModel], ...]] = {+ SuiteKind.SANDBOXED: (SandboxEvalEnv,),+ SuiteKind.ONE_SHOT: (OneShotEvalEnv,),+}+++def _read_quoted(text: str, quote: str) -> tuple[str, bool]:+ """Consume ``text`` up to an unescaped closing ``quote``; returns (body, closed)."""+ escaped = False+ for idx, char in enumerate(text):+ if quote == '"' and char == "\\" and not escaped:+ escaped = True+ continue+ if char == quote and not escaped:+ return text[:idx], True+ escaped = False+ return text, False+++def _decode_escapes(value: str) -> str:+ return re.sub(r"\\(.)", lambda m: _ESCAPES.get(m.group(1), f"\\{m.group(1)}"), value)+++def parse_env_file(path: Path) -> dict[str, str]:+ """Parse a ``.env`` file with the stdlib (no python-dotenv dependency).++ Handles what PostHog's env files actually use: blank lines, ``#`` comments,+ optional ``export`` prefixes, unquoted values with trailing inline comments,+ single-quoted literals, and double-quoted values with escape decoding+ (``"...\\n..."`` PEM keys) and multiline continuation.+ """+ values: dict[str, str] = {}+ lines = path.read_text().splitlines()+ index = 0+ while index < len(lines):+ line = lines[index]+ index += 1+ stripped = line.strip()+ if not stripped or stripped.startswith("#"):+ continue+ match = _ASSIGNMENT_RE.match(line)+ if not match:+ continue+ key, raw = match.group("key"), match.group("value").strip()+ if raw[:1] in ('"', "'"):+ quote = raw[0]+ body, closed = _read_quoted(raw[1:], quote)+ while not closed and index < len(lines):+ more, closed = _read_quoted(lines[index], quote)+ index += 1+ body = f"{body}\n{more}"+ values[key] = _decode_escapes(body) if quote == '"' else body+ else:+ values[key] = re.split(r"\s+#", raw, maxsplit=1)[0].rstrip()+ return values+++def load_env_file() -> None:+ """Load the repo-root ``.env`` into the environment, shell values winning.++ Replaces the manual ``set -a; source .env; set +a`` incantation. Only ``.env``+ is loaded here: hogli already loads ``.env.local`` / ``.env.development`` /+ ``.env.services`` before `hogli evals:sandboxed` reaches this process, and its+ line-based parser cannot represent ``.env``'s quoted/escaped PEM keys — so+ this file is the harness's job, via ``parse_env_file``, which decodes them+ correctly. ``setdefault`` keeps hogli's precedence: anything already exported+ (by the shell or by hogli's env loading) wins over ``.env``.+ """+ env_file = REPO_ROOT / ".env"+ if not env_file.exists():+ return+ for key, value in parse_env_file(env_file).items():+ os.environ.setdefault(key, value)+++def validate_eval_env(+ agent_runtime: str = "claude",+ *,+ kinds: Collection[SuiteKind] = (SuiteKind.SANDBOXED,),+ engine_env: Collection[EnvVarSpec] = (),+) -> None:+ """Fail fast, before any infrastructure boots, if a required variable is unset.++ ``engine_env`` is the selected engine's ``required_env()`` (e.g. the Braintrust+ engine's ``BRAINTRUST_API_KEY``). Only the env models for the selected suites'+ kinds are checked, so a run without sandboxed suites doesn't demand sandbox+ credentials. Without this a missing key surfaces minutes into a run as an+ opaque mid-case failure (gateway 401s, engine login errors) instead of a+ one-line fix.+ """+ models: list[type[BaseModel]] = []+ for kind, kind_models in ENV_MODELS_BY_KIND.items():+ if kind in kinds:+ models.extend(kind_models)+ if SuiteKind.SANDBOXED in kinds and agent_runtime == "codex":+ models.append(CodexEvalEnv)++ lines = []+ seen: set[str] = set()+ # Engine env first, so its line (e.g. BRAINTRUST_API_KEY) leads the report as+ # the core CoreEvalEnv field used to.+ for spec in engine_env:+ if spec.name in seen or os.environ.get(spec.name):+ continue+ seen.add(spec.name)+ lines.append(f" - {spec.name}: {spec.description}")+ for model in models:+ try:+ model.model_validate(dict(os.environ))+ except ValidationError as e:+ fields = model.model_fields+ for error in e.errors():+ name = str(error["loc"][0]) if error["loc"] else "?"+ if name in seen:+ continue+ seen.add(name)+ description = fields[name].description if name in fields else ""+ lines.append(f" - {name}: {description}")+ if lines:+ raise PreflightError(+ "Missing required environment variables:\n"+ + "\n".join(lines)+ + f"\nExport them in your shell, add them to {REPO_ROOT / '.env'} (loaded automatically), "+ "or keep them in .env.local and run via `hogli evals:sandboxed`."+ )diff --git a/products/posthog_ai/eval_harness/harness/lifecycle.py b/products/posthog_ai/eval_harness/harness/lifecycle.pynew file mode 100644index 000000000000..868e445f5bb8--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/lifecycle.py@@ -0,0 +1,329 @@+from __future__ import annotations++import time+import atexit+import asyncio+import logging+from collections.abc import Sequence+from contextlib import AsyncExitStack, ExitStack++from unittest.mock import patch++from django.conf import settings+from django.test import override_settings++import posthoganalytics+from posthoganalytics import Posthog++from posthog.ph_client import get_client++from products.tasks.backend.temporal.process_task.utils import get_reasoning_effort_error++from ..engines.base import EvalEngine+from ..engines.registry import resolve_engine+from .cli import DEFAULT_ONE_SHOT_CONCURRENCY, HarnessOptions+from .context import EvalContext+from .demo_data import SandboxedDemoData, ensure_demo_ready+from .discovery import EvalSuite, discover_suites+from .django_env import EvalDatabase+from .env_preflight import validate_eval_env+from .live_server import EvalLiveServer+from .ports import DJANGO_LIVE_PORT+from .providers import PreflightError, SandboxProviderStrategy, build_provider+from .reporting import ProgressReporter, SuiteRunResult+from .requirements import Infra, infra_union+from .services import (+ build_local_skills,+ ensure_personhog_binaries,+ start_llm_gateway,+ start_mcp_server,+ start_personhog,+ stop_all_subprocesses,+)+from .temporal_env import (+ TemporalWorkerThread,+ start_temporal_env,+ temporal_client_target,+ temporal_task_queue,+ terminate_stale_workflows,+)++logger = logging.getLogger(__name__)+++class SandboxedEvalHarness:+ """Boots the shared eval infrastructure once, then runs every selected suite concurrently.++ Two phases. The sync bootstrap runs before any event loop exists, because+ Django's async-safety guard rejects sync ORM calls from an async context and+ most of the setup is ORM-heavy. The async phase owns Temporal, the suites,+ and the shared semaphores that bound sandbox load and serialize team setup.+ """++ def __init__(self, options: HarnessOptions) -> None:+ self.options = options+ self.provider: SandboxProviderStrategy | None = None+ # The execution/reporting backend for this run. No --engine flag yet, so+ # this is the registry default; it feeds preflight and every suite's run.+ self._engine: EvalEngine = resolve_engine()+ self._stack = ExitStack()+ self._database: EvalDatabase | None = None+ self._live_server: EvalLiveServer | None = None+ self._posthog_client: Posthog | None = None+ self._demo_data: SandboxedDemoData | None = None++ def run(self) -> int:+ # Discover before anything is provisioned: a typo'd selector should cost a+ # module import, not a database build and a Hedgebox seed.+ suites = discover_suites(self.options.selectors)++ if self.options.list_only:+ for suite in suites:+ print(f"{suite.id} [{suite.kind.value}]") # noqa: T201+ return 0++ # Boot only what the selected suites' kinds require: a one-shot-only run+ # never pays for (or fails on) sandbox infrastructure.+ kinds = {suite.kind for suite in suites}+ required = infra_union(kinds)++ if Infra.SANDBOX not in required and self.options.sandbox_flags_set:+ flags = ", ".join(self.options.sandbox_flags_set)+ raise PreflightError(f"{flags}: no selected suite is sandboxed, so sandbox flags have no effect")++ reporter = ProgressReporter(total_suites=len(suites))+ reporter.print_run_header(+ provider=self.options.provider,+ agent_runtime=self.options.agent_runtime,+ agent_model=self.options.agent_model,+ max_sandboxes=self.options.max_sandboxes,+ trials=self.options.trials,+ )++ started = time.monotonic()+ results: list[SuiteRunResult] | None = None+ interrupted = False+ try:+ validate_eval_env(self.options.agent_runtime, kinds=kinds, engine_env=self._engine.required_env())+ if Infra.SANDBOX in required:+ self.provider = build_provider(+ self.options.provider,+ keep_containers=self.options.keep_sandbox_containers,+ rebuild_image=self.options.rebuild_sandbox_image,+ )+ self._validate_agent_options()+ self.provider.preflight()+ if Infra.PERSONHOG in required:+ ensure_personhog_binaries()+ self._bootstrap(required)+ results = asyncio.run(self._run_suites(suites, required, reporter))+ except KeyboardInterrupt:+ logger.warning("Interrupted, tearing down")+ interrupted = True+ finally:+ try:+ self._stack.close()+ finally:+ atexit.unregister(stop_all_subprocesses)+ if self.provider is not None:+ atexit.unregister(self.provider.cleanup)++ duration_seconds = time.monotonic() - started+ if interrupted:+ reporter.print_incomplete_summary(status="INTERRUPTED", duration_seconds=duration_seconds)+ return 130+ if results is None:+ raise RuntimeError("Sandboxed eval run finished without suite results")++ exit_code = self._exit_code(results, reporter)+ reporter.print_final_summary(+ results,+ exit_code=exit_code,+ fail_under=self.options.fail_under,+ duration_seconds=duration_seconds,+ )+ return exit_code++ def _exit_code(self, results: Sequence[SuiteRunResult], reporter: ProgressReporter) -> int:+ if any(result.status == "crashed" for result in results):+ return 1+ if self.options.fail_under is None:+ return 0+ mean = reporter.mean_score()+ if mean is None or mean < self.options.fail_under:+ return 1+ return 0++ def _validate_agent_options(self) -> None:+ """Validate runtime/model/effort with the tasks helpers, which need Django loaded.++ ``cli.py`` is Django-free by invariant, so this is the earliest point the real+ validation can run — still before any infrastructure boots.+ """+ error = get_reasoning_effort_error(+ self.options.agent_runtime, self.options.agent_model, self.options.reasoning_effort+ )+ if error:+ raise PreflightError(error)++ def _bootstrap(self, required: frozenset[Infra]) -> None:+ """Stand up everything the selected suites share. Teardown is registered in+ reverse on the stack, so what wasn't started is never torn down."""+ # Belt and braces for the SIGINT / SIGTERM paths, where the ExitStack never unwinds.+ atexit.register(stop_all_subprocesses)+ if self.provider is not None:+ atexit.register(self.provider.cleanup)+ self._stack.callback(self.provider.cleanup)++ if Infra.DATABASE in required:+ database = EvalDatabase(keepdb=not self.options.create_db)+ database.setup()+ self._stack.callback(database.teardown)+ self._database = database++ if Infra.PERSONHOG in required:+ # Bring personhog up before the live server and demo seeding: those bootstrap+ # reads go through the router, and a dead router would poison personhog's 30s+ # negative group-types cache for the rest of the run.+ self._stack.callback(start_personhog())++ if Infra.LIVE_SERVER in required:+ live_server = EvalLiveServer(DJANGO_LIVE_PORT)+ self._stack.callback(live_server.stop)+ self._live_server = live_server++ if Infra.LLM_GATEWAY in required:+ assert self._live_server is not None+ self._stack.callback(start_llm_gateway(self._live_server.url))+ if Infra.MCP_SERVER in required:+ assert self._live_server is not None+ self._stack.callback(start_mcp_server(self._live_server.url))++ if Infra.SANDBOX in required:+ assert self.provider is not None+ # Modal sandboxes live off-host, so the three services above have to be+ # publicly reachable before any settings pointing at them are computed.+ self.provider.start(self._stack)++ # DockerSandbox bind-mounts the built skills; ModalSandbox bakes them into+ # the image it builds from the local context, so it wants no host path.+ build_local_skills(set_bind_mount_env=self.options.provider == "docker")++ self._posthog_client = get_client("US")+ if self._posthog_client is not None:+ self._stack.callback(self._posthog_client.shutdown)++ if Infra.DEMO_DATA in required:+ assert self._database is not None+ self._demo_data = ensure_demo_ready(+ blocker=self._database.blocker,+ agent_model=self.options.agent_model,+ agent_runtime=self.options.agent_runtime,+ reasoning_effort=self.options.reasoning_effort,+ sandbox_timeout_seconds=(+ self.provider.sandbox_timeout_seconds(self.options.per_case_timeout_seconds)+ if self.provider is not None+ else None+ ),+ )++ async def _run_suites(+ self, suites: Sequence[EvalSuite], required: frozenset[Infra], reporter: ProgressReporter+ ) -> list[SuiteRunResult]:+ async with AsyncExitStack() as stack:+ overrides: dict[str, object] = {}+ if Infra.LIVE_SERVER in required:+ overrides.update(+ DEBUG=True, # Required for sandbox URL validation to allow http://localhost+ # The sandbox reaches the Django live server with a non-loopback+ # Host header (host.docker.internal, or the ngrok domain); allow it+ # (test-only) so the agent's event-ingest stream isn't rejected with+ # an invalid-host 400.+ ALLOWED_HOSTS=["*"],+ )+ if Infra.SANDBOX in required:+ assert self.provider is not None+ temporal_env = await start_temporal_env()+ stack.push_async_callback(temporal_env.shutdown)+ temporal_host, temporal_port = temporal_client_target(temporal_env)+ overrides.update(+ TEMPORAL_HOST=temporal_host,+ TEMPORAL_PORT=temporal_port,+ TEMPORAL_NAMESPACE=settings.TEMPORAL_NAMESPACE,+ TEMPORAL_CLIENT_CERT=None,+ TEMPORAL_CLIENT_KEY=None,+ # Keep eval workflows off any dev worker already polling the normal tasks queue.+ TASKS_TASK_QUEUE=temporal_task_queue(),+ **self.provider.settings_overrides(),+ )++ if overrides:+ stack.enter_context(override_settings(**overrides))+ stack.enter_context(patch.object(posthoganalytics, "feature_enabled", return_value=True))++ if Infra.SANDBOX in required:+ # Stale workflows from a prior run make the worker provision sandboxes for+ # runs that no longer exist, delaying the real eval workflows by 30-60s.+ await terminate_stale_workflows()++ worker = TemporalWorkerThread()+ worker.start()+ stack.callback(worker.stop)++ ctx = self._build_context(required, reporter)++ if Infra.SANDBOX in required:+ logger.info(+ "Running %d suite(s) on provider=%s with %d sandbox slot(s)",+ len(suites),+ self.options.provider,+ self.options.max_sandboxes,+ )+ else:+ logger.info("Running %d suite(s) without sandbox infrastructure", len(suites))+ results = await asyncio.gather(*(self._run_suite(suite, ctx) for suite in suites))+ return results++ def _build_context(self, required: frozenset[Infra], reporter: ProgressReporter) -> EvalContext:+ if Infra.DEMO_DATA in required and self._demo_data is None:+ raise RuntimeError("_bootstrap() must run before the eval context is built")+ return EvalContext(+ provider=self.options.provider,+ provider_strategy=self.provider,+ agent_model=self.options.agent_model,+ agent_runtime=self.options.agent_runtime,+ reasoning_effort=self.options.reasoning_effort,+ case_filter=self.options.case_filter,+ demo_data=self._demo_data,+ posthog_client=self._posthog_client,+ sandbox_slots=asyncio.Semaphore(self.options.max_sandboxes) if Infra.SANDBOX in required else None,+ team_setup_slots=asyncio.Semaphore(self.options.team_setup_concurrency),+ one_shot_slots=asyncio.Semaphore(DEFAULT_ONE_SHOT_CONCURRENCY),+ reporter=reporter,+ engine=self._engine,+ per_case_timeout_seconds=self.options.per_case_timeout_seconds,+ trials=self.options.trials,+ )++ async def _run_suite(self, suite: EvalSuite, ctx: EvalContext) -> SuiteRunResult:+ """Run one suite, absorbing its failures so a crash never takes the others down."""+ await ctx.reporter.suite_started(suite.id)+ started = time.monotonic()+ try:+ await suite.fn(ctx)+ except Exception as e:+ logger.exception("Eval suite %s crashed", suite.id)+ result = SuiteRunResult(+ suite_id=suite.id,+ status="crashed",+ error=e,+ duration_seconds=time.monotonic() - started,+ )+ else:+ result = SuiteRunResult(+ suite_id=suite.id,+ status="passed",+ duration_seconds=time.monotonic() - started,+ )+ await ctx.reporter.suite_finished(result)+ return resultdiff --git a/products/posthog_ai/eval_harness/harness/live_server.py b/products/posthog_ai/eval_harness/harness/live_server.pynew file mode 100644index 000000000000..8991c24c07f7--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/live_server.py@@ -0,0 +1,141 @@+from __future__ import annotations++import socket+import logging+import threading++from django.conf import settings+from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler+from django.db import connections+from django.db.backends.base.base import BaseDatabaseWrapper+from django.db.backends.sqlite3.creation import DatabaseCreation as SQLiteDatabaseCreation++import uvicorn++from posthog.asgi import application++from .ports import DJANGO_LIVE_PORT++logger = logging.getLogger(__name__)+++class _EvalUvicornServer(uvicorn.Server):+ def __init__(self, config: uvicorn.Config, ready: threading.Event) -> None:+ super().__init__(config)+ self.ready = ready+ self.startup_error: BaseException | None = None++ async def startup(self, sockets: list[socket.socket] | None = None) -> None:+ try:+ await super().startup(sockets=sockets)+ except BaseException as error:+ self.startup_error = error+ raise+ finally:+ self.ready.set()+++class EvalLiveServer:+ """Session-lifetime ASGI server backed by the eval test database.++ Serving PostHog's full ASGI application keeps the sandbox event-ingest route+ available alongside normal Django URLs. Docker sandboxes reach the listener+ through ``host.docker.internal``.+ """++ def __init__(self, port: int = DJANGO_LIVE_PORT) -> None:+ # If using in-memory SQLite, share the main thread's connection with the+ # server thread. Postgres needs no override.+ connections_override: dict[str, BaseDatabaseWrapper] = {}+ for connection in connections.all():+ if isinstance(connection.creation, SQLiteDatabaseCreation) and connection.creation.is_in_memory_db(+ connection.settings_dict["NAME"]+ ):+ connections_override[connection.alias] = connection++ asgi_application = (+ ASGIStaticFilesHandler(application)+ if "django.contrib.staticfiles" in settings.INSTALLED_APPS+ else application+ )+ self._connections_override = connections_override+ self._ready = threading.Event()+ self._thread_error: BaseException | None = None+ self._stopped = False++ # Bind before starting the thread so port=0 is race-free and ``url`` can+ # immediately advertise the actual OS-assigned port.+ # Docker sandboxes connect through host.docker.internal, which cannot reach a loopback-only listener.+ self._socket = socket.socket( # nosemgrep: python.lang.security.audit.network.bind.avoid-bind-to-all-interfaces+ socket.AF_INET, socket.SOCK_STREAM+ )+ self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ self._socket.bind(("0.0.0.0", port))+ self._socket.listen(2048)+ self.port = self._socket.getsockname()[1]++ config = uvicorn.Config(+ asgi_application,+ host="0.0.0.0",+ port=self.port,+ loop="asyncio",+ lifespan="on",+ log_level="warning",+ access_log=False,+ timeout_graceful_shutdown=10,+ )+ self.server = _EvalUvicornServer(config, self._ready)+ self.thread = threading.Thread(target=self._serve, name="sandboxed-eval-asgi", daemon=True)++ for connection in connections_override.values():+ connection.inc_thread_sharing()++ self.thread.start()+ if not self._ready.wait(timeout=30):+ self.stop()+ raise RuntimeError("Django ASGI server did not start within 30 seconds")+ if self.server.startup_error is not None:+ error = self.server.startup_error+ self.stop()+ raise error+ if not self.server.started:+ self.stop()+ raise RuntimeError("Django ASGI server stopped during startup")++ logger.info("Django live server started at %s (bound on 0.0.0.0)", self.url)++ def _serve(self) -> None:+ for alias, connection in self._connections_override.items():+ connections[alias] = connection+ try:+ self.server.run(sockets=[self._socket])+ except BaseException as error:+ self._thread_error = error+ self._ready.set()+ if self.server.startup_error is None:+ logger.exception("Django ASGI server crashed")+ finally:+ connections.close_all()++ @property+ def url(self) -> str:+ return f"http://127.0.0.1:{self.port}"++ def __str__(self) -> str:+ return self.url++ def stop(self) -> None:+ if self._stopped:+ return+ self._stopped = True+ self.server.should_exit = True+ self.thread.join(timeout=15)+ if self.thread.is_alive():+ self.server.force_exit = True+ self.thread.join(timeout=5)+ if self.thread.is_alive():+ logger.warning("Django ASGI server thread did not stop within 20 seconds")+ self._socket.close()+ for connection in self._connections_override.values():+ connection.dec_thread_sharing()+ logger.info("Django live server stopped")diff --git a/products/posthog_ai/eval_harness/harness/ports.py b/products/posthog_ai/eval_harness/harness/ports.pynew file mode 100644index 000000000000..4bab2053b998--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/ports.py@@ -0,0 +1,20 @@+from __future__ import annotations++MCP_PORT = 18787+"""Non-default port to avoid conflicts with a running dev MCP server."""++DJANGO_LIVE_PORT = 18000+"""Non-default port for the in-process Django server."""++LLM_GATEWAY_PORT = 13308+"""Non-default port to avoid conflicts with a running dev LLM gateway."""++NGROK_WEB_PORT = 14040+"""Dedicated ngrok agent API port, so the harness never adopts or collides with+a developer's already-running ngrok agent on the default 4040."""++PERSONHOG_REPLICA_PORT = 15051+"""Non-default port so a dev-stack personhog-replica on 50051 never collides."""++PERSONHOG_ROUTER_PORT = 15052+"""Non-default port; the harness points PERSONHOG_ADDR at this router."""diff --git a/products/posthog_ai/eval_harness/harness/providers.py b/products/posthog_ai/eval_harness/harness/providers.pynew file mode 100644index 000000000000..2b67e7073aa2--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/providers.py@@ -0,0 +1,327 @@+from __future__ import annotations++import os+import shutil+import logging+import subprocess+from abc import ABC, abstractmethod+from contextlib import ExitStack+from pathlib import Path+from typing import Any, ClassVar, Literal++from .ports import DJANGO_LIVE_PORT, LLM_GATEWAY_PORT, MCP_PORT+from .tunnels import NgrokTunnels, resolve_authtoken++logger = logging.getLogger(__name__)++SandboxProvider = Literal["docker", "modal"]++SANDBOX_PROVIDER_SETTING: dict[SandboxProvider, str] = {+ "docker": "docker",+ "modal": "MODAL_EVALS",+}+"""Value each provider writes to ``settings.SANDBOX_PROVIDER``, which selects the+sandbox class in ``products.tasks``. ``modal`` maps to ``MODAL_EVALS``: a+``ModalSandbox`` subclass pinned to the ``posthog-sandbox-evals`` Modal app.++``__main__`` sets this in the environment before ``django.setup()``. It must be+correct before the *first* ``Sandbox`` access, because ``products.tasks`` resolves+that class once and caches it in module globals; a later ``override_settings`` can+no longer change it. ``.env`` ships ``SANDBOX_PROVIDER=docker``, so without the+early set a modal run would cache ``DockerSandbox`` and silently execute locally."""++EVAL_CONTAINER_PREFIX = "task-sandbox-"+"""Container name prefix the sandbox harness stamps on every eval container+(see ``SandboxConfig.name`` / ``get_sandbox_name_for_task``)."""++SETUP_GUIDE = "docs/internal/sandboxes-setup-guide.md"+++class PreflightError(RuntimeError):+ """A provider prerequisite is missing. Raised before any infrastructure boots."""+++def cleanup_case_containers(task_id: str) -> None:+ """Force-remove any sandbox container created for this case's task.++ Eval cases return as soon as ``poll_for_turn`` sees ``end_turn``, but the+ ``ProcessTaskWorkflow`` finally block that calls ``cleanup_sandbox`` runs+ asynchronously and can lag — or get cancelled when the temporal worker is+ shut down at session end. With 16GB-per-sandbox defaults and a handful of+ concurrent cases, accumulated containers exhaust host memory.++ Match by name prefix ``task-sandbox-{task_id}-`` (see ``get_sandbox_name_for_task``+ and ``DockerSandbox.create``) so we never touch a concurrently-running case's+ container.+ """+ name_prefix = f"{EVAL_CONTAINER_PREFIX}{task_id}-"+ try:+ result = subprocess.run(+ ["docker", "ps", "-a", "--filter", f"name={name_prefix}", "--format", "{{.ID}}"],+ capture_output=True,+ text=True,+ timeout=15,+ )+ except Exception:+ logger.warning("Failed to list sandbox containers for task %s", task_id, exc_info=True)+ return++ for container_id in result.stdout.strip().splitlines():+ if not container_id:+ continue+ logger.info("Cleaning up eval container %s for task %s", container_id, task_id)+ try:+ subprocess.run(["docker", "rm", "-f", container_id], capture_output=True, timeout=30)+ except Exception:+ logger.warning("Failed to remove sandbox container %s", container_id, exc_info=True)+++def _modal_eval_app_name() -> str:+ """Name of the dedicated Modal app the eval sandboxes run under (the+ ``MODAL_EVALS`` provider), read from its source of truth in ``products.tasks``."""+ from products.tasks.backend.logic.services.sandbox import ( # noqa: PLC0415 — Django import, kept off the harness import path+ get_sandbox_class_for_backend,+ )++ app_name = getattr(get_sandbox_class_for_backend("MODAL_EVALS"), "DEFAULT_APP_NAME", "")+ return app_name if isinstance(app_name, str) else ""+++def cleanup_modal_eval_sandboxes(app_name: str, task_ids: set[str]) -> None:+ """Terminate this run's leftover Modal sandboxes under the eval app.++ The Modal analog of the Docker container sweep: best effort, and also reached+ from an ``atexit`` hook. A case that finishes cleanly has its own workflow+ terminate its sandbox; this catches the ones a per-case timeout, a crash, or a+ Ctrl-C left running, so they don't idle (and bill) until their TTL.++ Scoped to this run's own tasks so two concurrent runs sharing the eval app+ don't reap each other. Each sandbox carries a ``task_id`` tag (see+ ``_build_sandbox_tags`` / ``ModalSandbox`` ``set_tags``), so we list per+ registered id and terminate only those. We filter on the tag rather than the+ ``task-sandbox-<id>-<hex>`` name because the installed Modal SDK does not+ expose a listed sandbox's name. Empty registry (nothing ran) sweeps nothing.+ """+ if not task_ids:+ return+ try:+ import modal # noqa: PLC0415 — heavy, optional dep kept off the harness import path+ except Exception:+ return+ try:+ app = modal.App.lookup(app_name, create_if_missing=False)+ except Exception:+ # Nothing ever ran under this app, so there is nothing to sweep.+ return+ for task_id in task_ids:+ try:+ sandboxes = list(modal.Sandbox.list(app_id=app.app_id, tags={"task_id": task_id}))+ except Exception:+ logger.warning("Could not list Modal sandboxes for task %s during cleanup", task_id)+ continue+ for sandbox in sandboxes:+ try:+ logger.info("Terminating leftover Modal sandbox %s for task %s", sandbox.object_id, task_id)+ sandbox.terminate()+ except Exception:+ pass+++class SandboxProviderStrategy(ABC):+ """Per-provider bootstrap, settings, and teardown for a harness run."""++ name: ClassVar[SandboxProvider]++ default_max_sandboxes: ClassVar[int | None]+ """``None`` means unbounded — every case may hold a sandbox at once."""++ def __init__(self) -> None:+ self._task_ids: set[str] = set()+ """Task ids whose sandboxes this run created. The end-of-run sweep filters+ on these so it only reaps this run's own sandboxes — never a dev-stack task+ sandbox or a concurrent run sharing the same provider."""++ def register_task(self, task_id: str) -> None:+ """Record a task whose sandbox this run created, so ``cleanup()`` can scope+ its sweep to this run. The runner calls it once per case, right after the+ task's workflow is triggered."""+ self._task_ids.add(task_id)++ @abstractmethod+ def preflight(self) -> None:+ """Fail fast when a prerequisite is missing, before anything is started."""++ def start(self, stack: ExitStack) -> None: # noqa: B027 — optional hook; docker brings up nothing of its own+ """Bring up provider-owned infrastructure, registering teardown on ``stack``."""++ @abstractmethod+ def settings_overrides(self) -> dict[str, Any]:+ """Django settings the sandbox and its temporal activities read."""++ def sandbox_timeout_seconds(self, per_case_timeout_seconds: int) -> int | None:+ """Per-sandbox max lifetime, or ``None`` to keep ``SANDBOX_TTL_SECONDS``."""+ return None++ def cleanup_case(self, task_id: str) -> None: # noqa: B027 — optional hook; only providers whose per-case teardown can lag override it+ """Per-case teardown run after each case settles, on top of the workflow's own cleanup."""++ def cleanup(self) -> None: # noqa: B027 — optional hook; providers that own teardown override it+ """End-of-run sweep for anything per-case teardown may have missed."""+++class DockerProviderStrategy(SandboxProviderStrategy):+ """Local Docker sandboxes. Each container defaults to 16 GB, so host RAM,+ not the sandbox API, is what bounds concurrency."""++ name: ClassVar[SandboxProvider] = "docker"+ default_max_sandboxes: ClassVar[int | None] = 4++ def __init__(self, *, keep_containers: bool = False, rebuild_image: bool = False) -> None:+ super().__init__()+ self.keep_containers = keep_containers+ self.rebuild_image = rebuild_image++ def preflight(self) -> None:+ if shutil.which("docker") is None:+ raise PreflightError("`docker` not found on PATH. The docker provider needs a local Docker daemon.")+ try:+ result = subprocess.run(["docker", "info"], capture_output=True, timeout=20)+ except Exception as e:+ raise PreflightError(f"Could not reach the Docker daemon: {e}") from e+ if result.returncode != 0:+ raise PreflightError("The Docker daemon is not reachable. Start Docker and retry.")++ def start(self, stack: ExitStack) -> None:+ # Verify posthog-sandbox-base is fresh (rebuilding when @posthog/agent published a+ # newer version or the Dockerfile changed) before any case grabs a sandbox, so a+ # stale image can't break the whole run. Imported here because it pulls in Django.+ from products.tasks.backend.logic.services.docker_sandbox import ( # noqa: PLC0415 — Django import, kept off the harness import path+ ensure_fresh_base_image,+ )++ ensure_fresh_base_image(force=self.rebuild_image)++ def settings_overrides(self) -> dict[str, Any]:+ # Docker containers reach the host via host.docker.internal.+ return {+ "SANDBOX_PROVIDER": SANDBOX_PROVIDER_SETTING[self.name],+ "SANDBOX_API_URL": f"http://host.docker.internal:{DJANGO_LIVE_PORT}",+ "SANDBOX_LLM_GATEWAY_URL": f"http://host.docker.internal:{LLM_GATEWAY_PORT}",+ "SANDBOX_MCP_URL": f"http://host.docker.internal:{MCP_PORT}/mcp",+ }++ def cleanup_case(self, task_id: str) -> None:+ # Belt-and-braces on top of the workflow's own shutdown: its cleanup_sandbox+ # can lag or be cancelled at worker shutdown, so reclaim this case's container+ # by name before the next case grabs a slot. --keep-sandbox-containers skips+ # this too — the flag exists to inspect a failed case's container, and the+ # per-case reclaim would otherwise remove it before anyone could look.+ if self.keep_containers:+ return+ cleanup_case_containers(task_id)++ def cleanup(self) -> None:+ if self.keep_containers:+ logger.info("--keep-sandbox-containers set, skipping container cleanup")+ return+ # Scope the sweep to this run's own tasks so we never reap a dev-stack task+ # sandbox that happens to share the `task-sandbox-` prefix. Empty registry+ # (nothing ran) sweeps nothing.+ for task_id in self._task_ids:+ cleanup_case_containers(task_id)+++class ModalProviderStrategy(SandboxProviderStrategy):+ """Remote Modal sandboxes, reached from Modal's network through ngrok tunnels.++ Runs under the ``MODAL_EVALS`` provider — the same ``ModalSandbox`` class+ against the ``posthog-sandbox-evals`` app, so DEBUG-mode eval image builds+ don't share an image cache with production or local development sandboxes.+ """++ name: ClassVar[SandboxProvider] = "modal"+ default_max_sandboxes: ClassVar[int | None] = None++ def __init__(self) -> None:+ super().__init__()+ self._tunnels: NgrokTunnels | None = None+ self._sandbox_app_name: str | None = None++ def preflight(self) -> None:+ if shutil.which("ngrok") is None:+ raise PreflightError(+ "`ngrok` not found on PATH. Modal sandboxes run outside this host, so the "+ f"Django API, LLM gateway, and MCP server must be publicly reachable. See {SETUP_GUIDE}."+ )+ if resolve_authtoken() is None:+ # Three simultaneous tunnels need a paid, authenticated agent. Without a+ # token ngrok starts and then fails per-tunnel, which would otherwise+ # surface only as a 60s startup timeout.+ raise PreflightError(+ "No ngrok authtoken found. Set NGROK_AUTHTOKEN, or run `ngrok config add-authtoken <token>` "+ f"with a token from https://dashboard.ngrok.com/get-started/your-authtoken. See {SETUP_GUIDE}."+ )+ has_env_tokens = bool(os.environ.get("MODAL_TOKEN_ID") and os.environ.get("MODAL_TOKEN_SECRET"))+ if not has_env_tokens and not (Path.home() / ".modal.toml").exists():+ raise PreflightError(+ "No Modal credentials found. Set MODAL_TOKEN_ID and MODAL_TOKEN_SECRET, "+ f"or run `modal token new`. See {SETUP_GUIDE}."+ )+ # SANDBOX_JWT_PRIVATE_KEY and the other env-only prerequisites are validated+ # earlier by env_preflight.validate_eval_env(); only checks with non-env+ # fallbacks (ngrok config file, ~/.modal.toml) live here.++ def start(self, stack: ExitStack) -> None:+ # Resolve the eval sandbox app now, while Django is configured, so cleanup()+ # can sweep leftover sandboxes later — including from the atexit path, where+ # importing products.tasks is unsafe. A failure here must not fail the run.+ try:+ self._sandbox_app_name = _modal_eval_app_name()+ except Exception:+ logger.warning("Could not resolve the Modal eval app; end-of-run sandbox sweep is disabled")++ tunnels = NgrokTunnels(+ {+ "django": DJANGO_LIVE_PORT,+ "gateway": LLM_GATEWAY_PORT,+ "mcp": MCP_PORT,+ }+ )+ tunnels.start()+ stack.callback(tunnels.stop)+ self._tunnels = tunnels++ def settings_overrides(self) -> dict[str, Any]:+ if self._tunnels is None:+ raise RuntimeError("ModalProviderStrategy.start() must run before settings_overrides()")+ return {+ "SANDBOX_PROVIDER": SANDBOX_PROVIDER_SETTING[self.name],+ "SANDBOX_API_URL": self._tunnels.url_for("django"),+ "SANDBOX_LLM_GATEWAY_URL": self._tunnels.url_for("gateway"),+ "SANDBOX_MCP_URL": f"{self._tunnels.url_for('mcp')}/mcp",+ }++ def sandbox_timeout_seconds(self, per_case_timeout_seconds: int) -> int | None:+ # Under TEST=1, SANDBOX_TTL_SECONDS equals the per-case timeout, so Modal+ # would reap a slow case's sandbox exactly as it was about to finish.+ return per_case_timeout_seconds + 10 * 60++ def cleanup_case(self, task_id: str) -> None:+ if self._sandbox_app_name:+ cleanup_modal_eval_sandboxes(self._sandbox_app_name, {task_id})++ def cleanup(self) -> None:+ # A finished case terminates its own sandbox; sweep the app for any that a+ # timeout, crash, or Ctrl-C left running so they don't idle until their TTL.+ # Scoped to this run's own tasks so a concurrent run sharing the eval app+ # keeps its sandboxes.+ if self._sandbox_app_name:+ cleanup_modal_eval_sandboxes(self._sandbox_app_name, self._task_ids)+++def build_provider(+ provider: SandboxProvider, *, keep_containers: bool, rebuild_image: bool = False+) -> SandboxProviderStrategy:+ if provider == "docker":+ return DockerProviderStrategy(keep_containers=keep_containers, rebuild_image=rebuild_image)+ return ModalProviderStrategy()diff --git a/products/posthog_ai/eval_harness/harness/reporting.py b/products/posthog_ai/eval_harness/harness/reporting.pynew file mode 100644index 000000000000..5751414d5c18--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/reporting.py@@ -0,0 +1,259 @@+from __future__ import annotations++import os+import asyncio+import traceback+from collections import Counter, defaultdict+from collections.abc import Sequence+from dataclasses import dataclass+from pathlib import Path+from typing import Literal++from ..engines.types import EvalSummary++EVAL_RESULTS_JSONL = "eval_results.jsonl"+"""Machine-readable per-experiment summary export, opt-in via ``EXPORT_EVAL_RESULTS``."""++POSTHOG_EVALUATIONS_URL = (+ "https://us.posthog.com/project/2/ai-evals/evaluations/offline/experiments/{experiment_id}?offline_date_from=-1d"+)++CaseStatus = Literal["ok", "timeout", "error"]+++def _emit(text: str) -> None:+ print(text) # noqa: T201 — this module is the single owner of harness terminal output+++@dataclass+class SuiteRunResult:+ """Outcome of one suite function, assembled by the orchestrator."""++ suite_id: str+ status: Literal["passed", "crashed"]+ error: BaseException | None = None+ duration_seconds: float = 0.0+++class ProgressReporter:+ """Serializes harness output and renders the stable final summary."""++ def __init__(self, total_suites: int) -> None:+ self._total_suites = total_suites+ self._lock = asyncio.Lock()+ self._finished_suites = 0+ self._summaries: dict[str, EvalSummary] = {}+ self._case_counts: dict[str, int] = defaultdict(int)+ self._case_durations: dict[str, float] = defaultdict(float)+ self._case_statuses: dict[str, Counter[str]] = defaultdict(Counter)+ self._summary_error_counts: dict[str, int] = defaultdict(int)+ self._experiment_totals: dict[str, int] = {}+ self._posthog_urls: dict[str, str] = {}+ self._log_dirs: dict[str, Path] = {}++ def print_run_header(+ self,+ *,+ provider: str,+ agent_runtime: str,+ agent_model: str,+ max_sandboxes: int,+ trials: int,+ ) -> None:+ lines = [+ "Sandboxed eval run",+ f"Suites: {self._total_suites}",+ f"Provider: {provider}",+ f"Agent: {agent_runtime} / {agent_model}",+ f"Sandbox concurrency: {max_sandboxes}",+ f"Trials per case: {trials}",+ "",+ ]+ _emit("\n".join(lines))++ async def suite_started(self, suite_id: str) -> None:+ async with self._lock:+ _emit(f"SUITE START {suite_id}")++ async def experiment_started(self, experiment_name: str, planned_cases: int, log_dir: Path) -> None:+ async with self._lock:+ self._experiment_totals[experiment_name] = planned_cases+ self._log_dirs[experiment_name] = log_dir+ _emit(f"EXPERIMENT START {experiment_name} [{planned_cases} cases]")++ async def case_done(+ self,+ experiment_name: str,+ case_name: str,+ *,+ duration_seconds: float,+ status: CaseStatus = "ok",+ ) -> None:+ async with self._lock:+ self._case_counts[experiment_name] += 1+ self._case_durations[experiment_name] += duration_seconds+ self._case_statuses[experiment_name][status] += 1+ marker = {"ok": "DONE", "timeout": "TIMEOUT", "error": "ERROR"}[status]+ total = self._experiment_totals.get(experiment_name)+ progress = f"[{self._case_counts[experiment_name]}/{total}]" if total is not None else ""+ _emit(+ f"CASE {marker:<7} {experiment_name} :: {case_name} {progress} {_format_duration(duration_seconds)}"+ )++ async def suite_finished(self, result: SuiteRunResult) -> None:+ async with self._lock:+ self._finished_suites += 1+ marker = "DONE" if result.status == "passed" else "CRASH"+ _emit(+ f"SUITE {marker:<5} {result.suite_id} "+ f"[{self._finished_suites}/{self._total_suites} suites] "+ f"{_format_duration(result.duration_seconds)}"+ )++ async def record_summary(self, experiment_name: str, summary: EvalSummary, *, error_count: int = 0) -> None:+ async with self._lock:+ self._summaries[experiment_name] = summary+ self._summary_error_counts[experiment_name] = error_count+ if os.getenv("EXPORT_EVAL_RESULTS"):+ with open(EVAL_RESULTS_JSONL, "a", encoding="utf-8") as f:+ f.write(summary.as_json() + "\n")+ total = self._experiment_totals.get(experiment_name)+ progress = f"[{self._case_counts[experiment_name]}/{total} cases]" if total is not None else ""+ _emit(f"EXPERIMENT DONE {experiment_name} {progress}")++ async def record_posthog_evaluations_url(self, experiment_name: str, experiment_id: str) -> None:+ async with self._lock:+ self._posthog_urls[experiment_name] = POSTHOG_EVALUATIONS_URL.format(experiment_id=experiment_id)++ def print_final_summary(+ self,+ results: Sequence[SuiteRunResult],+ *,+ exit_code: int,+ fail_under: float | None,+ duration_seconds: float,+ ) -> None:+ crashed = sorted(+ (result for result in results if result.status == "crashed"), key=lambda result: result.suite_id+ )+ case_statuses = self._combined_case_statuses()+ lines = [+ "",+ "Sandboxed eval summary",+ "----------------------",+ f"Status: {'PASS' if exit_code == 0 else 'FAIL'}",+ f"Suites: {len(results) - len(crashed)} done, {len(crashed)} crashed",+ (+ f"Cases: {case_statuses['ok']} done, {case_statuses['timeout']} timed out, "+ f"{case_statuses['error']} errors"+ ),+ f"Mean score: {self._mean_score_text()}",+ f"Score gate: {self._score_gate_text(fail_under)}",+ f"Duration: {_format_duration(duration_seconds)}",+ ]++ for experiment_name in sorted(self._summaries):+ lines.extend(self._experiment_block(experiment_name, self._summaries[experiment_name]))++ if not self._summaries and not crashed:+ lines.extend(["", "No experiments ran."])++ lines.extend(self._crash_block(crashed))+ _emit("\n".join(lines))++ def print_incomplete_summary(self, *, status: str, duration_seconds: float) -> None:+ _emit(+ "\n".join(+ [+ "",+ "Sandboxed eval summary",+ "----------------------",+ f"Status: {status}",+ f"Duration: {_format_duration(duration_seconds)}",+ ]+ )+ )++ def mean_score(self) -> float | None:+ scores = [+ score.score+ for summary in self._summaries.values()+ for score in summary.scores.values()+ if score.score is not None+ ]+ if not scores:+ return None+ return sum(scores) / len(scores)++ def _combined_case_statuses(self) -> Counter[str]:+ combined: Counter[str] = Counter()+ experiment_names = self._case_statuses.keys() | self._summary_error_counts.keys()+ for experiment_name in experiment_names:+ statuses = self._case_statuses[experiment_name]+ combined["ok"] += statuses["ok"]+ combined["timeout"] += statuses["timeout"]+ combined["error"] += max(statuses["error"], self._summary_error_counts[experiment_name])+ return combined++ def _experiment_block(self, experiment_name: str, summary: EvalSummary) -> list[str]:+ statuses = self._case_statuses[experiment_name]+ error_count = max(statuses["error"], self._summary_error_counts[experiment_name])+ lines = [+ "",+ f"Experiment: {experiment_name}",+ (f" Cases: {statuses['ok']} done, {statuses['timeout']} timed out, {error_count} errors"),+ f" Case time: {_format_duration(self._case_durations[experiment_name])}",+ ]+ scores = [(score.name, score.score) for score in summary.scores.values() if score.score is not None]+ if scores:+ lines.append(" Scores:")+ lines.extend(f" {name}: {score * 100:.1f}%" for name, score in scores)+ else:+ lines.append(" Scores: none")++ posthog_url = self._posthog_urls.get(experiment_name)+ if posthog_url:+ lines.append(f" PostHog: {posthog_url}")+ lines.append(f" {summary.engine_name.title()}: {summary.experiment_url or '(local run, not uploaded)'}")+ log_dir = self._log_dirs.get(experiment_name)+ if log_dir:+ lines.append(f" Agent logs: {log_dir}")+ return lines++ def _mean_score_text(self) -> str:+ mean = self.mean_score()+ return f"{mean * 100:.1f}%" if mean is not None else "n/a"++ def _score_gate_text(self, fail_under: float | None) -> str:+ if fail_under is None:+ return "not configured"+ mean = self.mean_score()+ target = fail_under * 100+ if mean is None:+ return f"not met (no scores; required {target:.1f}%)"+ comparison = ">=" if mean >= fail_under else "<"+ status = "met" if mean >= fail_under else "not met"+ return f"{status} ({mean * 100:.1f}% {comparison} {target:.1f}%)"++ def _crash_block(self, crashed: Sequence[SuiteRunResult]) -> list[str]:+ if not crashed:+ return []+ lines = ["", "Crashed suites", "---------------"]+ for result in crashed:+ lines.append(f"Suite: {result.suite_id}")+ lines.append(f"Duration: {_format_duration(result.duration_seconds)}")+ if result.error is not None:+ lines.append("".join(traceback.format_exception(result.error)).rstrip())+ else:+ lines.append("(no traceback captured)")+ return lines+++def _format_duration(seconds: float) -> str:+ if seconds < 60:+ return f"{seconds:.1f}s"+ minutes, remaining = divmod(seconds, 60)+ if minutes < 60:+ return f"{int(minutes)}m {remaining:.1f}s"+ hours, minutes = divmod(int(minutes), 60)+ return f"{hours}h {minutes}m {remaining:.1f}s"diff --git a/products/posthog_ai/eval_harness/harness/requirements.py b/products/posthog_ai/eval_harness/harness/requirements.pynew file mode 100644index 000000000000..08b4447b52b8--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/requirements.py@@ -0,0 +1,83 @@+"""Suite kinds and the shared infrastructure each one requires.++Django-free on purpose: ``env_preflight`` (on ``__main__``'s top-level import+chain) reads the kind → env-model mapping before ``django.setup()`` runs.+"""++from __future__ import annotations++import enum+from collections.abc import Iterable+++class Infra(enum.Enum):+ """One bootable piece of shared eval infrastructure."""++ DATABASE = "database"+ """The eval test database (Postgres + persons DB + ClickHouse)."""++ PERSONHOG = "personhog"+ """The personhog replica/router pair person reads route through."""++ LIVE_SERVER = "live_server"+ """The Django live server sandboxes and the MCP server call back into."""++ LLM_GATEWAY = "llm_gateway"+ """The gateway proxying the sandboxed agent's model calls."""++ MCP_SERVER = "mcp_server"+ """The MCP server the sandboxed agent's tools talk to."""++ DEMO_DATA = "demo_data"+ """The master Hedgebox seed team and per-case team factory."""++ SANDBOX = "sandbox"+ """The sandbox provider, local skills build, and the Temporal environment."""+++class SuiteKind(enum.Enum):+ """How a suite's cases execute; declared per module via ``SUITE_KIND``."""++ SANDBOXED = "sandboxed"+ """The coding agent runs in a real sandbox; the default when unset."""++ ONE_SHOT = "one-shot"+ """One in-process model invocation per case — no sandbox, no servers."""+++_IMPLIES: dict[Infra, frozenset[Infra]] = {+ Infra.LIVE_SERVER: frozenset({Infra.DATABASE}),+ # Both services take the live server URL as their upstream.+ Infra.LLM_GATEWAY: frozenset({Infra.LIVE_SERVER}),+ Infra.MCP_SERVER: frozenset({Infra.LIVE_SERVER}),+ # Demo seeding's person/group reads go through the personhog router; a dead+ # router would poison its 30s negative group-types cache for the whole run.+ Infra.DEMO_DATA: frozenset({Infra.DATABASE, Infra.PERSONHOG}),+ Infra.SANDBOX: frozenset({Infra.LLM_GATEWAY, Infra.MCP_SERVER, Infra.DEMO_DATA}),+}++INFRA_BY_KIND: dict[SuiteKind, frozenset[Infra]] = {+ SuiteKind.SANDBOXED: frozenset(Infra),+ SuiteKind.ONE_SHOT: frozenset({Infra.DATABASE, Infra.PERSONHOG, Infra.DEMO_DATA}),+}+++def expand(infra: Iterable[Infra]) -> frozenset[Infra]:+ """Close a requirement set over implications, so a kind can never request+ a service without the things that service needs to come up."""+ result = set(infra)+ pending = list(result)+ while pending:+ for implied in _IMPLIES.get(pending.pop(), ()):+ if implied not in result:+ result.add(implied)+ pending.append(implied)+ return frozenset(result)+++def infra_union(kinds: Iterable[SuiteKind]) -> frozenset[Infra]:+ """The infrastructure the harness must boot for a run over these suite kinds."""+ required: set[Infra] = set()+ for kind in kinds:+ required |= INFRA_BY_KIND[kind]+ return expand(required)diff --git a/products/posthog_ai/eval_harness/harness/services.py b/products/posthog_ai/eval_harness/harness/services.pynew file mode 100644index 000000000000..5045657f6b16--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/services.py@@ -0,0 +1,273 @@+from __future__ import annotations++import os+import json+import shutil+import logging+import subprocess+from collections.abc import Callable+from pathlib import Path++from django.conf import settings+from django.db import connections++from products.posthog_ai.eval_harness.long_lived_subprocess import LongLivedSubprocessManager, SubprocessStartupError+from products.tasks.backend.facade.agents import ENV_LOCAL_SKILLS_HOST_PATH, LocalSkillsCache++from .ports import LLM_GATEWAY_PORT, MCP_PORT, PERSONHOG_REPLICA_PORT, PERSONHOG_ROUTER_PORT+from .providers import PreflightError++logger = logging.getLogger(__name__)++LONG_LIVED_SUBPROCESSES = LongLivedSubprocessManager()+++def start_llm_gateway(live_server_url: str) -> Callable[[], None]:+ """Start the LLM gateway as a subprocess.++ Mirrors ``bin/start-llm-gateway``: runs uvicorn on a non-default port.+ The sandbox's agent-server uses this to proxy LLM calls to Anthropic.+ """+ gateway_dir = Path(settings.BASE_DIR) / "services" / "llm-gateway"+ venv_dir = gateway_dir / ".venv"+ uvicorn_bin = venv_dir / "bin" / "uvicorn"++ if not uvicorn_bin.exists():+ raise SubprocessStartupError(+ f"LLM gateway venv not found at {venv_dir}. "+ "Run `bin/start-llm-gateway` once or `cd services/llm-gateway && uv venv .venv && uv pip install -e .`"+ )+ # The LLM gateway uses pydantic BaseSettings with env_prefix="LLM_GATEWAY_".+ # DATABASE_URL and LLM_GATEWAY_ANTHROPIC_API_KEY come from the parent env+ # (e.g. .env.local / op run). We need to point it at the test database.+ conn = connections["default"]+ # The test DB setup rewrites settings_dict["NAME"] to the test DB name in+ # place, so don't re-prefix it.+ db_name = conn.settings_dict["NAME"]+ db_user = conn.settings_dict.get("USER", "posthog")+ db_password = conn.settings_dict.get("PASSWORD", "posthog")+ db_host = conn.settings_dict.get("HOST", "localhost")+ db_port = conn.settings_dict.get("PORT", "5432")+ test_db_url = f"postgres://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}"++ # No team rate-limit multiplier: the gateway keys multipliers by team id, but+ # each eval case runs as its own freshly minted team, so a mapping like {"1": 10}+ # never matches. Rate limits are per team, so every case gets the full base+ # budget (hundreds of requests/minute), which is already ample for eval traffic.+ env = {+ **os.environ,+ "UV_PROJECT_ENVIRONMENT": str(venv_dir),+ "LLM_GATEWAY_DATABASE_URL": test_db_url,+ "LLM_GATEWAY_DEBUG": "true",+ "LLM_GATEWAY_POSTHOG_HOST": live_server_url,+ }++ logger.info("Starting LLM gateway on port %d", LLM_GATEWAY_PORT)+ _, stop = LONG_LIVED_SUBPROCESSES.start(+ name="LLM gateway",+ port=LLM_GATEWAY_PORT,+ cmd=[+ str(uvicorn_bin),+ "llm_gateway.main:app",+ "--host",+ "0.0.0.0",+ "--port",+ str(LLM_GATEWAY_PORT),+ ],+ cwd=gateway_dir,+ env=env,+ log_prefix="llm-gateway",+ )++ logger.info("LLM gateway ready on port %d", LLM_GATEWAY_PORT)+ return stop+++def start_mcp_server(live_server_url: str) -> Callable[[], None]:+ """Start the MCP server as a subprocess for the eval session.++ Pointed at the in-process Django live server (which uses the test DB).+ Uses a non-default port to avoid conflicts with a running dev MCP server.++ Runs the Node-native Hono server via ``pnpm dev:hono``. In production the+ Cloudflare Worker is now a proxy that forwards to a regional Hono+ deployment, so Hono is what real users hit.+ """+ mcp_dir = Path(settings.BASE_DIR) / "services" / "mcp"+ if not (mcp_dir / "node_modules").exists():+ logger.info("Installing MCP server dependencies")+ subprocess.run(["pnpm", "install", "--frozen-lockfile"], cwd=mcp_dir, check=True, capture_output=True)++ api_url = live_server_url++ # The Hono server reads config directly from process env — no wrangler+ # --var wiring needed. PORT picks the listen port; the dev:hono script+ # bundles via esbuild then spawns Node on the bundle.+ env = {+ **os.environ,+ "POSTHOG_API_BASE_URL": api_url,+ "MCP_APPS_BASE_URL": f"http://localhost:{MCP_PORT}",+ "POSTHOG_MCP_APPS_ANALYTICS_BASE_URL": api_url,+ "NODE_ENV": "development",+ "PORT": str(MCP_PORT),+ "HOST": "0.0.0.0",+ # The MCP server evaluates feature flags via posthog-node, which is disabled+ # here (no POSTHOG_ANALYTICS_* config), so every flag would resolve false.+ # Force flag-gated behavior on for evals via the dev/test-only override seam+ # (honored only when NODE_ENV is explicitly development/test — set above).+ # No flags currently need forcing on.+ "FEATURE_FLAG_OVERRIDES": json.dumps({}),+ }++ logger.info("Starting MCP server (Hono runtime) on port %d (API: %s)", MCP_PORT, api_url)+ _, stop = LONG_LIVED_SUBPROCESSES.start(+ name="MCP server",+ port=MCP_PORT,+ cmd=["pnpm", "dev:hono"],+ cwd=mcp_dir,+ env=env,+ log_prefix="mcp",+ )++ logger.info("MCP server ready on port %d", MCP_PORT)+ return stop+++def _personhog_target_dir(rust_dir: Path) -> Path:+ """Resolve where cargo drops the debug binaries.++ Defaults to ``rust/target``, but the flox dev shell exports+ ``CARGO_TARGET_DIR`` to a shared out-of-tree location, so honor it — otherwise+ the build lands there while we look under ``rust/target`` and never find it.+ """+ override = os.environ.get("CARGO_TARGET_DIR")+ return Path(override) if override else rust_dir / "target"+++def ensure_personhog_binaries() -> None:+ """Build the personhog binaries the harness runs for person/group reads.++ The query API reads persons and groups exclusively through personhog (there is+ no ORM fallback), so the harness stands up ``personhog-replica`` ++ ``personhog-router`` from ``rust/`` against the test persons DB. Building here,+ during preflight, keeps the slow first compile off the async run path.+ """+ if shutil.which("cargo") is None:+ raise PreflightError(+ "`cargo` not found on PATH. The query API reads persons/groups through personhog, "+ "which the harness builds from rust/. Enter the flox dev shell or install the Rust toolchain."+ )++ rust_dir = Path(settings.BASE_DIR) / "rust"+ logger.info(+ "Building personhog binaries (first build can take several minutes; later builds are incremental no-ops)"+ )+ result = subprocess.run(+ ["cargo", "build", "-p", "personhog-replica", "-p", "personhog-router"],+ cwd=rust_dir,+ capture_output=True,+ text=True,+ # The first build compiles the whole dependency tree; only later builds are+ # incremental no-ops. Keep the ceiling well clear of a cold compile.+ timeout=20 * 60,+ )+ if result.returncode != 0:+ output = (result.stdout or "") + (result.stderr or "")+ tail = "\n".join(output.splitlines()[-30:])+ raise PreflightError(f"Failed to build personhog binaries (cargo exit {result.returncode}):\n{tail}")+++def start_personhog() -> Callable[[], None]:+ """Start personhog-replica + personhog-router against the test persons DB.++ Django reads persons/groups only through personhog (no ORM fallback), so+ ``/query`` scorers read 0 unless the router is up and ``PERSONHOG_ADDR`` points+ at it. Both run as raw debug binaries — the read path needs no etcd, config+ server, or leader election (the router defaults to ``router_mode=replica``).+ """+ persons_url = os.environ.get("PERSONS_DB_WRITER_URL")+ if not persons_url:+ raise SubprocessStartupError(+ "PERSONS_DB_WRITER_URL is unset. personhog reads the seeded persons DB from it; "+ "start_personhog() must run after EvalDatabase.setup() has provisioned the test persons DB."+ )++ rust_dir = Path(settings.BASE_DIR) / "rust"+ target_dir = _personhog_target_dir(rust_dir)+ replica_bin = target_dir / "debug" / "personhog-replica"+ router_bin = target_dir / "debug" / "personhog-router"++ # METRICS_PORT=0 binds the Prometheus listener to an OS-assigned ephemeral port,+ # so the harness never collides with a dev stack's 9100/9101.+ logger.info("Starting personhog-replica on port %d", PERSONHOG_REPLICA_PORT)+ _, stop_replica = LONG_LIVED_SUBPROCESSES.start(+ name="personhog-replica",+ port=PERSONHOG_REPLICA_PORT,+ cmd=[str(replica_bin)],+ cwd=rust_dir,+ env={+ **os.environ,+ "PRIMARY_DATABASE_URL": persons_url,+ "GRPC_ADDRESS": f"127.0.0.1:{PERSONHOG_REPLICA_PORT}",+ "METRICS_PORT": "0",+ "RUST_LOG": "info",+ },+ log_prefix="personhog-replica",+ )++ logger.info("Starting personhog-router on port %d", PERSONHOG_ROUTER_PORT)+ try:+ _, stop_router = LONG_LIVED_SUBPROCESSES.start(+ name="personhog-router",+ port=PERSONHOG_ROUTER_PORT,+ cmd=[str(router_bin)],+ cwd=rust_dir,+ env={+ **os.environ,+ "REPLICA_URL": f"http://127.0.0.1:{PERSONHOG_REPLICA_PORT}",+ "GRPC_ADDRESS": f"127.0.0.1:{PERSONHOG_ROUTER_PORT}",+ "METRICS_PORT": "0",+ "RUST_LOG": "info",+ },+ log_prefix="personhog-router",+ )+ except Exception:+ stop_replica()+ raise++ logger.info("personhog ready (router on port %d)", PERSONHOG_ROUTER_PORT)++ def stop() -> None:+ try:+ stop_router()+ finally:+ stop_replica()++ return stop+++def build_local_skills(*, set_bind_mount_env: bool) -> Path:+ """Build local skills once per run and return the built dist dir.++ Uses a content-hash cache so repeat runs skip the build when nothing has+ changed, keeping the base image stable while letting eval authors iterate on+ skills without rebuilding it.++ Depends on ``DEBUG=True`` being active while the skill renderer runs — some+ template helpers (e.g. HogQL example rendering) guard on that setting. The+ harness sets ``DEBUG=1`` in the environment before ``django.setup()``, so+ that ordering holds by the time this runs.+ """+ cache = LocalSkillsCache()+ dist_dir = cache.ensure_built()+ if set_bind_mount_env:+ # Only ``DockerSandbox.create`` reads this to bind-mount the built skills.+ # Under the modal provider the locally built skills are instead baked into+ # the Modal image by the DEBUG ``from_dockerfile`` build, so setting it+ # there would be inert.+ os.environ[ENV_LOCAL_SKILLS_HOST_PATH] = str(dist_dir)+ return dist_dir+++def stop_all_subprocesses() -> None:+ LONG_LIVED_SUBPROCESSES.stop_all()diff --git a/products/posthog_ai/eval_harness/harness/temporal_env.py b/products/posthog_ai/eval_harness/harness/temporal_env.pynew file mode 100644index 000000000000..653f3b303380--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/temporal_env.py@@ -0,0 +1,150 @@+from __future__ import annotations++import os+import asyncio+import logging+import threading++from django.conf import settings++from temporalio.testing import WorkflowEnvironment++from posthog.temporal.common.client import async_connect+from posthog.temporal.common.worker import create_worker++from products.tasks.backend.facade.temporal import (+ ACTIVITIES as TASKS_ACTIVITIES,+ WORKFLOWS as TASKS_WORKFLOWS,+)++logger = logging.getLogger(__name__)+++def temporal_client_target(env: WorkflowEnvironment) -> tuple[str, str]:+ config = env.client.config()+ service_client = config["service_client"]+ target_host = service_client.config.target_host+ host, port = target_host.rsplit(":", maxsplit=1)+ return host, port+++async def start_temporal_env() -> WorkflowEnvironment:+ """Start an isolated Temporal dev server for sandboxed eval workflows.++ Awaited on the harness's main event loop, so eval workflows and the local+ dev server share one loop instead of the fixture's private throwaway loop.+ """+ # Hogli loads the dev OTLP exporter config, but the eval harness does not+ # start a collector. Disable trace export only while the Temporal child is+ # spawned, then restore the parent process environment immediately.+ previous_traces_exporter = os.environ.get("OTEL_TRACES_EXPORTER")+ os.environ["OTEL_TRACES_EXPORTER"] = "none"+ try:+ env = await WorkflowEnvironment.start_local(+ namespace=settings.TEMPORAL_NAMESPACE,+ ip="127.0.0.1",+ port=None,+ dev_server_log_level="warn",+ )+ finally:+ if previous_traces_exporter is None:+ os.environ.pop("OTEL_TRACES_EXPORTER", None)+ else:+ os.environ["OTEL_TRACES_EXPORTER"] = previous_traces_exporter+ host, port = temporal_client_target(env)+ logger.info("Sandboxed eval Temporal server ready at %s:%s namespace=%s", host, port, settings.TEMPORAL_NAMESPACE)+ return env+++def temporal_task_queue() -> str:+ """Per-process task queue so eval workflows stay off any dev worker's queue."""+ return f"sandboxed-evals-tasks-{os.getpid()}"+++async def terminate_stale_workflows() -> None:+ """Terminate any stale temporal workflows left over from previous runs.++ Without this, the in-process worker wastes time processing old workflows+ (creating sandboxes for runs that no longer exist in the test database),+ delaying the actual eval workflow by 30-60 seconds.+ """+ client = await async_connect()+ terminated = 0+ async for wf in client.list_workflows(f'TaskQueue="{settings.TASKS_TASK_QUEUE}"'):+ try:+ handle = client.get_workflow_handle(wf.id, run_id=wf.run_id)+ await handle.terminate(reason="eval harness cleanup")+ terminated += 1+ except Exception:+ pass+ if terminated:+ logger.info("Terminated %d stale temporal workflows", terminated)+++class TemporalWorkerThread:+ """In-process temporal worker for the tasks queue, on its own thread + loop.++ Mirrors the dev worker (``manage.py start_temporal_worker``) using+ ``create_worker``. The worker runs on a private ``asyncio`` loop inside a+ daemon thread so it can poll Temporal without competing with the harness's+ main loop; DB access is unblocked (nothing blocks it in the harness) so+ temporal activities can use the Django ORM against the test database.+ """++ def __init__(self, *, max_concurrent_workflow_tasks: int = 100, max_concurrent_activities: int = 100) -> None:+ self._max_concurrent_workflow_tasks = max_concurrent_workflow_tasks+ self._max_concurrent_activities = max_concurrent_activities+ self._loop = asyncio.new_event_loop()+ self._stop_event = asyncio.Event()+ self._ready_event = threading.Event()+ self._thread: threading.Thread | None = None++ def start(self) -> None:+ self._thread = threading.Thread(target=self._loop.run_until_complete, args=(self._run(),), daemon=True)+ self._thread.start()++ if not self._ready_event.wait(timeout=30):+ raise RuntimeError(+ f"Temporal worker failed to start within 30s. "+ f"Is temporal running at {settings.TEMPORAL_HOST}:{settings.TEMPORAL_PORT}?"+ )++ logger.info("Eval temporal worker ready")++ async def _run(self) -> None:+ logger.info(+ "Starting eval temporal worker (%s:%s queue=%s)",+ settings.TEMPORAL_HOST,+ settings.TEMPORAL_PORT,+ settings.TASKS_TASK_QUEUE,+ )+ managed = await create_worker(+ host=settings.TEMPORAL_HOST,+ port=int(settings.TEMPORAL_PORT),+ metrics_port=0,+ namespace=settings.TEMPORAL_NAMESPACE,+ task_queue=settings.TASKS_TASK_QUEUE,+ workflows=TASKS_WORKFLOWS,+ activities=TASKS_ACTIVITIES, # type: ignore[arg-type]+ max_concurrent_workflow_tasks=self._max_concurrent_workflow_tasks,+ max_concurrent_activities=self._max_concurrent_activities,+ enable_combined_metrics_server=False,+ )+ logger.info("Eval temporal worker created")+ self._ready_event.set()+ worker_task = asyncio.ensure_future(managed.run())+ await self._stop_event.wait()+ logger.info("Shutting down eval temporal worker")+ await managed.shutdown()+ worker_task.cancel()++ def stop(self) -> None:+ self._loop.call_soon_threadsafe(self._stop_event.set)+ if self._thread is not None:+ self._thread.join(timeout=10)+ if self._thread.is_alive():+ # The loop is still running the worker; closing it now would raise.+ # Leak it rather than risk a RuntimeError masking the real teardown.+ logger.warning("Eval temporal worker thread did not join in 10s; leaving its loop open")+ return+ self._loop.close()diff --git a/products/posthog_ai/eval_harness/harness/transcript.py b/products/posthog_ai/eval_harness/harness/transcript.pynew file mode 100644index 000000000000..4a61627e4dac--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/transcript.py@@ -0,0 +1,126 @@+from __future__ import annotations++import sys+import uuid+import threading+from collections.abc import Iterator+from contextlib import contextmanager, redirect_stderr, redirect_stdout+from datetime import UTC, datetime+from pathlib import Path+from typing import IO, TextIO++from ..log_sink import LOGS_ROOT++HARNESS_LOGS_ROOT = LOGS_ROOT / "harness"+++class _TranscriptSink:+ def __init__(self, path: Path, stdout: TextIO) -> None:+ self.path = path+ self.stdout = stdout+ self.file: IO[str] = path.open("w", encoding="utf-8", buffering=1)+ self.lock = threading.Lock()+ self.finished = False+ self.ends_with_newline = True++ def write(self, terminal: TextIO, text: str) -> int:+ with self.lock:+ if self.finished:+ return len(text)+ self.file.write(text)+ self.file.flush()+ terminal.write(text)+ terminal.flush()+ if text:+ self.ends_with_newline = text.endswith("\n")+ return len(text)++ def flush(self, terminal: TextIO) -> None:+ with self.lock:+ if self.finished:+ return+ self.file.flush()+ terminal.flush()++ def finish(self) -> None:+ with self.lock:+ if self.finished:+ return+ prefix = "" if self.ends_with_newline else "\n"+ line = f"{prefix}Full run transcript (stdout and stderr):\n{self.path}\n"+ self.file.write(line)+ self.file.flush()+ self.stdout.write(line)+ self.stdout.flush()+ self.finished = True+ self.file.close()+++class _TeeStream:+ """Plain-text stream that mirrors writes to a terminal and one shared file."""++ def __init__(self, terminal: TextIO, sink: _TranscriptSink) -> None:+ self._terminal = terminal+ self._sink = sink++ @property+ def encoding(self) -> str:+ return self._terminal.encoding or "utf-8"++ @property+ def errors(self) -> str | None:+ return self._terminal.errors++ def write(self, text: str) -> int:+ return self._sink.write(self._terminal, text)++ def flush(self) -> None:+ self._sink.flush(self._terminal)++ def fileno(self) -> int:+ return self._terminal.fileno()++ def isatty(self) -> bool:+ # Static output is readable in terminals, redirected logs, and agent tools.+ return False++ def writable(self) -> bool:+ return True+++class RunTranscript:+ """Tee one harness invocation to disk and publish its path last."""++ def __init__(self, path: Path, stdout: TextIO, stderr: TextIO) -> None:+ self.path = path.resolve()+ self._sink = _TranscriptSink(self.path, stdout)+ self._stdout = _TeeStream(stdout, self._sink)+ self._stderr = _TeeStream(stderr, self._sink)++ @classmethod+ def create(cls, root: Path = HARNESS_LOGS_ROOT) -> RunTranscript:+ root = root.resolve()+ root.mkdir(parents=True, exist_ok=True)+ timestamp = datetime.now(UTC).strftime("%Y%m%d-%H%M%S")+ path = root / f"{timestamp}_{uuid.uuid4().hex[:8]}.log"+ transcript = cls(path, sys.stdout, sys.stderr)+ transcript._update_latest_symlink(root)+ return transcript++ @contextmanager+ def capture(self) -> Iterator[None]:+ with redirect_stdout(self._stdout), redirect_stderr(self._stderr):+ yield++ def finish(self) -> None:+ self._sink.finish()++ def _update_latest_symlink(self, root: Path) -> None:+ latest = root / "latest.log"+ try:+ if latest.is_symlink() or latest.exists():+ latest.unlink()+ latest.symlink_to(self.path.name)+ except OSError:+ # The real transcript remains usable on filesystems without symlink support.+ passdiff --git a/products/posthog_ai/eval_harness/harness/tunnels.py b/products/posthog_ai/eval_harness/harness/tunnels.pynew file mode 100644index 000000000000..8915fe4055c3--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/tunnels.py@@ -0,0 +1,197 @@+from __future__ import annotations++import os+import json+import time+import shutil+import signal+import logging+import tempfile+import subprocess+from pathlib import Path+from typing import Any+from urllib.error import URLError+from urllib.request import urlopen++import yaml++from .ports import NGROK_WEB_PORT++logger = logging.getLogger(__name__)++SETUP_GUIDE = "docs/internal/sandboxes-setup-guide.md"++NGROK_DEFAULT_CONFIG_PATHS: tuple[Path, ...] = (+ Path.home() / ".config" / "ngrok" / "ngrok.yml",+ Path.home() / "Library" / "Application Support" / "ngrok" / "ngrok.yml",+ Path.home() / ".ngrok2" / "ngrok.yml",+)+"""Where the ngrok agent keeps the token written by ``ngrok config add-authtoken``,+on Linux, macOS, and the legacy v2 location respectively."""+++class NgrokError(RuntimeError):+ """ngrok tunnels could not be established for the eval run."""+++def resolve_authtoken() -> str | None:+ """Find the user's ngrok authtoken without inheriting the rest of their config.++ The harness generates its own config (its tunnels point at eval ports, not the+ dev-stack ports the setup guide documents), so it cannot just hand ngrok the+ user's file. The token is the one thing worth lifting out of it.+ """+ from_env = os.environ.get("NGROK_AUTHTOKEN")+ if from_env:+ return from_env++ for path in NGROK_DEFAULT_CONFIG_PATHS:+ if not path.is_file():+ continue+ try:+ config = yaml.safe_load(path.read_text(encoding="utf-8"))+ except (OSError, yaml.YAMLError):+ continue+ if not isinstance(config, dict):+ continue+ # Config version 3 nests it under ``agent``; version 2 keeps it top-level.+ agent = config.get("agent")+ token = agent.get("authtoken") if isinstance(agent, dict) else None+ token = token or config.get("authtoken")+ if isinstance(token, str) and token:+ return token+ return None+++class NgrokTunnels:+ """Modal-only ngrok lifecycle: publicly exposes the host services a remote+ Modal sandbox must reach (Django API, LLM gateway, MCP server).++ While a run is live the tunnel URLs are reachable by anyone on the internet+ who learns them, so they exist only for the duration of the run.+ """++ def __init__(self, ports: dict[str, int]) -> None:+ self._ports: dict[str, int] = dict(ports)+ self._proc: subprocess.Popen[bytes] | None = None+ self._config_dir: Path | None = None+ self._log_path: Path | None = None+ self._public_urls: dict[str, str] = {}++ def start(self) -> None:+ self._config_dir = Path(tempfile.mkdtemp(prefix="posthog-eval-ngrok-"))+ config_path = self._config_dir / "ngrok.yml"+ self._log_path = self._config_dir / "ngrok.log"+ config_path.write_text(yaml.safe_dump(self._build_config(), sort_keys=False), encoding="utf-8")++ # ngrok's own log goes to a file, never to a pipe: nothing drains a pipe+ # for the length of a run, and a full 64 KB buffer would block the agent+ # and stall every tunnel mid-eval.+ self._proc = subprocess.Popen(+ ["ngrok", "start", "--all", "--config", str(config_path)],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ start_new_session=True,+ )++ deadline = time.monotonic() + 60+ while time.monotonic() < deadline:+ if self._proc.poll() is not None:+ detail = f"ngrok exited early with code {self._proc.returncode}.\n{self._read_log_tail()}"+ self.stop()+ raise NgrokError(self._failure_message(detail))++ urls = self._read_tunnel_urls()+ if all(name in urls for name in self._ports):+ self._public_urls = {name: urls[name] for name in self._ports}+ logger.info("ngrok tunnels ready: %s", self._public_urls)+ return++ time.sleep(0.5)++ detail = f"Timed out waiting for all tunnels to report a public URL.\n{self._read_log_tail()}"+ self.stop()+ raise NgrokError(self._failure_message(detail))++ def url_for(self, name: str) -> str:+ return self._public_urls[name].rstrip("/")++ def stop(self) -> None:+ proc = self._proc+ if proc is not None:+ self._proc = None+ self._terminate_process_group(proc)++ config_dir = self._config_dir+ if config_dir is not None:+ self._config_dir = None+ self._log_path = None+ shutil.rmtree(config_dir, ignore_errors=True)++ def _build_config(self) -> dict[str, Any]:+ # Config version 3: agent-level options live under ``agent``, tunnels stay+ # top-level. Same shape as the config in the setup guide.+ agent: dict[str, Any] = {+ # A dedicated web_addr so the harness never adopts, or collides with,+ # a developer's already-running ngrok agent on the default 4040.+ "web_addr": f"127.0.0.1:{NGROK_WEB_PORT}",+ "log": str(self._log_path),+ "log_level": "info",+ }+ authtoken = resolve_authtoken()+ if authtoken:+ agent["authtoken"] = authtoken++ tunnels = {name: {"proto": "http", "addr": port, "schemes": ["https"]} for name, port in self._ports.items()}+ return {"version": "3", "agent": agent, "tunnels": tunnels}++ def _read_tunnel_urls(self) -> dict[str, str]:+ try:+ # The fixed loopback HTTP origin prevents callers from selecting another urllib scheme.+ # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected+ with urlopen(f"http://127.0.0.1:{NGROK_WEB_PORT}/api/tunnels", timeout=2) as resp:+ payload = json.loads(resp.read().decode("utf-8"))+ except (URLError, OSError, json.JSONDecodeError):+ return {}++ urls: dict[str, str] = {}+ for tunnel in payload.get("tunnels", []):+ # A tunnel restricted to ``schemes: [https]`` is reported under its+ # config name; strip any ``" (https)"``-style suffix defensively.+ name = str(tunnel.get("name", "")).split(" ", 1)[0]+ public_url = tunnel.get("public_url")+ if name and public_url:+ urls[name] = public_url+ return urls++ def _terminate_process_group(self, proc: subprocess.Popen[bytes]) -> None:+ if proc.poll() is not None:+ return+ try:+ os.killpg(os.getpgid(proc.pid), signal.SIGTERM)+ except (ProcessLookupError, PermissionError):+ return+ try:+ proc.wait(timeout=5)+ except subprocess.TimeoutExpired:+ try:+ os.killpg(os.getpgid(proc.pid), signal.SIGKILL)+ except (ProcessLookupError, PermissionError):+ pass++ def _read_log_tail(self, lines: int = 20) -> str:+ if self._log_path is None or not self._log_path.is_file():+ return ""+ try:+ return "\n".join(self._log_path.read_text(encoding="utf-8", errors="replace").splitlines()[-lines:])+ except OSError:+ return ""++ def _failure_message(self, detail: str) -> str:+ return (+ f"{detail}\n"+ "ngrok could not serve the Django, LLM gateway, and MCP tunnels simultaneously. "+ "The free ngrok plan covers a single tunnel, so multi-tunnel eval runs need an "+ "authtoken on a paid plan (ngrok Hobbyist or above), or Cloudflare Tunnel instead. "+ f"See {SETUP_GUIDE}."+ )diff --git a/ee/hogai/eval/sandboxed/log_parser.py b/products/posthog_ai/eval_harness/log_parser.pysimilarity index 94%rename from ee/hogai/eval/sandboxed/log_parser.pyrename to products/posthog_ai/eval_harness/log_parser.pyindex 9e5c6287b326..b427d61213b9 100644--- a/ee/hogai/eval/sandboxed/log_parser.py+++ b/products/posthog_ai/eval_harness/log_parser.py@@ -13,6 +13,7 @@ test config.from __future__ import annotationsimport json+import functoolsfrom typing import Anyfrom pydantic import BaseModel, ConfigDict@@ -114,6 +115,17 @@ class LogParser:self._tool_results = _index_tool_results(self._messages)self._tool_use_positions = _index_tool_use_positions(self._messages)+ @classmethod+ def cached(cls, raw_log: str, initial_prompt: str = "") -> LogParser:+ """Return a shared parser for ``(raw_log, initial_prompt)``, parsed once.++ Every deterministic scorer runs against the same per-case log, so+ without memoization one case gets parsed ~10 times. The public getters+ are read-only, so scorers can safely share a single instance. The+ cache key hashes the raw log once, which is far cheaper than reparsing.+ """+ return _cached_parser(raw_log, initial_prompt)+def was_skill_called(self, name: str) -> bool:return any(call.name == name for call in self._iter_skill_calls())@@ -259,6 +271,11 @@ class LogParser:return (output, bool(result.get("is_error", False)))[email protected]_cache(maxsize=32)+def _cached_parser(raw_log: str, initial_prompt: str) -> LogParser:+ return LogParser(raw_log, initial_prompt=initial_prompt)++def _index_tool_results(messages: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:by_id: dict[str, dict[str, Any]] = {}for msg in messages:diff --git a/ee/hogai/eval/sandboxed/log_sink.py b/products/posthog_ai/eval_harness/log_sink.pysimilarity index 100%rename from ee/hogai/eval/sandboxed/log_sink.pyrename to products/posthog_ai/eval_harness/log_sink.pydiff --git a/ee/hogai/eval/sandboxed/logs/.gitignore b/products/posthog_ai/eval_harness/logs/.gitignoresimilarity index 100%rename from ee/hogai/eval/sandboxed/logs/.gitignorerename to products/posthog_ai/eval_harness/logs/.gitignorediff --git a/ee/hogai/eval/sandboxed/long_lived_subprocess.py b/products/posthog_ai/eval_harness/long_lived_subprocess.pysimilarity index 96%rename from ee/hogai/eval/sandboxed/long_lived_subprocess.pyrename to products/posthog_ai/eval_harness/long_lived_subprocess.pyindex 47196a4d2f70..bd03fd3c8de2 100644--- a/ee/hogai/eval/sandboxed/long_lived_subprocess.py+++ b/products/posthog_ai/eval_harness/long_lived_subprocess.py@@ -15,13 +15,15 @@ from pathlib import Pathfrom types import FrameTypefrom typing import TypedDict, cast-import pytest-logger = logging.getLogger(__name__)StopCallback = Callable[[], None]+class SubprocessStartupError(RuntimeError):+ """A managed support subprocess failed to come up (crashed, timed out, or port already bound)."""++class ProcessMetadata(TypedDict):name: strport: int@@ -93,7 +95,7 @@ class LongLivedSubprocessManager:while time.monotonic() < deadline:if proc.poll() is not None:stop()- pytest.fail(+ raise SubprocessStartupError(f"{name} subprocess exited with code {proc.returncode} during startup. "f"Check the [{log_prefix}] WARNING lines above.")@@ -105,7 +107,7 @@ class LongLivedSubprocessManager:time.sleep(0.5)stop()- pytest.fail(f"{name} failed to start on port {port} within {readiness_timeout:.0f}s.")+ raise SubprocessStartupError(f"{name} failed to start on port {port} within {readiness_timeout:.0f}s.")def stop_all(self) -> None:with self._stops_lock:@@ -121,7 +123,7 @@ class LongLivedSubprocessManager:try:pre_sock = socket.create_connection(("localhost", port), timeout=0.5)pre_sock.close()- pytest.fail(+ raise SubprocessStartupError(f"Port {port} is already in use — likely a stale {name} from a prior eval session. "f"Find and kill it:\n lsof -iTCP:{port} -sTCP:LISTEN")@@ -316,6 +318,7 @@ class LongLivedSubprocessManager:self._stops.append(stop)def _unregister(self, stop: StopCallback) -> None:+ atexit.unregister(stop)with self._stops_lock:try:self._stops.remove(stop)diff --git a/products/posthog_ai/eval_harness/one_shot.py b/products/posthog_ai/eval_harness/one_shot.pynew file mode 100644index 000000000000..78a43bd161c3--- /dev/null+++ b/products/posthog_ai/eval_harness/one_shot.py@@ -0,0 +1,131 @@+"""One-shot eval runner: one in-process model invocation per case, no sandbox.++``OneShotEval`` mirrors ``SandboxedEval`` but the per-case work is a+suite-supplied task function instead of a sandboxed agent run. The task+returns the scorer ``output`` dict directly, so each suite defines its own+output shape and its scorers read the keys they know about.+"""++from __future__ import annotations++import json+import time+import asyncio+import logging+from collections.abc import Awaitable, Callable, Sequence+from functools import partial+from typing import TYPE_CHECKING, Any++from .base import _BaseEvalRun+from .config import BaseEvalCase+from .engines.types import CaseHooks, ExperimentResult+from .log_sink import write_case_logs++if TYPE_CHECKING:+ from .harness.context import EvalContext++logger = logging.getLogger(__name__)++OneShotTaskFn = Callable[[BaseEvalCase, "EvalContext"], Awaitable[dict[str, Any]]]+"""The per-case task: one model invocation returning the scorer ``output`` dict.++The returned dict must be JSON-serializable (it round-trips through Braintrust).+``prompt`` is backfilled by the runner; an optional ``last_message`` feeds the+local ``.summary.txt``.+"""+++class _OneShotEvalRun(_BaseEvalRun):+ """The one-shot incarnation of ``_BaseEvalRun``: a concurrency slot, a+ timeout budget, and local log writing around the suite's task function."""++ trace_namespace = "one-shot"++ def __init__(+ self,+ experiment_name: str,+ cases: Sequence[BaseEvalCase],+ scorers: Sequence[Any],+ ctx: EvalContext,+ is_public: bool,+ no_send_logs: bool,+ task_fn: OneShotTaskFn,+ ) -> None:+ super().__init__(+ experiment_name=experiment_name,+ cases=cases,+ scorers=scorers,+ ctx=ctx,+ is_public=is_public,+ no_send_logs=no_send_logs,+ )+ self._task_fn = task_fn++ async def _execute_case(self, input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:+ # Re-bind the original case object: it carries what Braintrust's JSON+ # round-trip drops, and the task fn may want `expected`/`metadata`.+ case = self.cases_by_name.get(input["name"]) or BaseEvalCase(name=input["name"], prompt=input.get("prompt", ""))+ started = time.monotonic()+ async with self.ctx.one_shot_slots:+ # Budget the task from slot acquisition, so time spent queued on the+ # semaphore can never eat into a case's timeout.+ output = await asyncio.wait_for(+ self._task_fn(case, self.ctx),+ timeout=self.ctx.per_case_timeout_seconds,+ )+ output.setdefault("prompt", case.prompt)+ await self._write_local_logs(case, output, duration=time.monotonic() - started)+ return output++ async def _write_local_logs(self, case: BaseEvalCase, output: dict[str, Any], duration: float) -> None:+ try:+ write_case_logs(+ case_dir=self.run_log_dir,+ case_name=case.name,+ raw_log=json.dumps(output, indent=2, default=str),+ artifacts={},+ prompt=case.prompt,+ duration=duration,+ last_message=str(output.get("last_message", "")),+ )+ except Exception:+ logger.exception("Failed to write local eval logs for '%s'", case.name)++ def _timeout_output(self) -> dict[str, Any]:+ return {"timeout": True, "error": f"case timeout after {self.ctx.per_case_timeout_seconds}s"}+++async def OneShotEval(+ experiment_name: str,+ cases: Sequence[BaseEvalCase],+ scorers: Sequence[Any],+ task: OneShotTaskFn,+ ctx: EvalContext,+ is_public: bool = False,+ no_send_logs: bool = True,+) -> ExperimentResult:+ """Run a one-shot evaluation suite via Braintrust.++ For each ``BaseEvalCase``, invokes ``task(case, ctx)`` once under the global+ ``ctx.one_shot_slots`` limiter with the per-case timeout, then feeds the+ returned dict to the scorers. The suite's module must declare+ ``SUITE_KIND = SuiteKind.ONE_SHOT`` so the harness skips sandbox+ infrastructure for it.+ """+ run = _OneShotEvalRun(+ experiment_name=experiment_name,+ cases=cases,+ scorers=scorers,+ ctx=ctx,+ is_public=is_public,+ no_send_logs=no_send_logs,+ task_fn=task,+ )+ return await run.run()+++OneShotPublicEval = partial(OneShotEval, is_public=True, no_send_logs=False)+"""One-shot evaluation whose Braintrust experiment is publicly accessible."""++OneShotPrivateEval = partial(OneShotEval, is_public=False, no_send_logs=True)+"""One-shot evaluation that is not accessible publicly; local logs are the record."""diff --git a/ee/hogai/eval/sandboxed/runner.py b/products/posthog_ai/eval_harness/runner.pysimilarity index 52%rename from ee/hogai/eval/sandboxed/runner.pyrename to products/posthog_ai/eval_harness/runner.pyindex 0b7dcbdbaf29..cb6a8952463e 100644--- a/ee/hogai/eval/sandboxed/runner.py+++ b/products/posthog_ai/eval_harness/runner.py@@ -1,55 +1,78 @@from __future__ import annotations+import reimport jsonimport timeimport uuidimport asyncioimport logging-import subprocessfrom dataclasses import dataclass+from typing import TYPE_CHECKING++from temporalio.client import WorkflowFailureError++from posthog.temporal.common.client import async_connectfrom products.tasks.backend.facade.agents import CustomPromptSandboxContext, create_task_and_trigger, poll_for_turn+from products.tasks.backend.facade.temporal import ProcessTaskWorkflowfrom .config import AgentArtifacts, SandboxedEvalCase+from .harness.providers import SandboxProviderStrategy++if TYPE_CHECKING:+ from temporalio.client import WorkflowHandlelogger = logging.getLogger(__name__)__all__ = ["run_eval_case"]+# Word-boundary matches so a tool title like "latest release" doesn't read as a+# test run, and "blueprint" doesn't read as a lint run. These artifacts feed the+# tests-pass / lint-pass scorers, so a false match is a scoring bug.+TEST_TITLE_RE = re.compile(r"\b(pytest|tests?)\b")+LINT_TITLE_RE = re.compile(r"\b(ruff|lint)\b")-def _cleanup_case_containers(task_id: str) -> None:- """Force-remove any sandbox container created for this case's task.+WORKFLOW_COMPLETION_GRACE_SECONDS = 60+WORKFLOW_CANCELLATION_GRACE_SECONDS = 30- Eval cases return as soon as ``poll_for_turn`` sees ``end_turn``, but the- ``ProcessTaskWorkflow`` finally block that calls ``cleanup_sandbox`` runs- asynchronously and can lag — or get cancelled when the temporal worker is- shut down at session end. With 16GB-per-sandbox defaults and- ``max_concurrency=2`` cases, accumulated containers exhaust host memory.- Match by name prefix ``task-sandbox-{task_id}-`` (see- ``get_sandbox_name_for_task`` and ``DockerSandbox.create``) so we never- touch a concurrently-running case's container.- """- name_prefix = f"task-sandbox-{task_id}-"+class WorkflowCleanupError(RuntimeError):+ pass+++async def _wait_for_workflow_terminal(handle: WorkflowHandle, timeout_seconds: int) -> bool:try:- result = subprocess.run(- ["docker", "ps", "-a", "--filter", f"name={name_prefix}", "--format", "{{.ID}}"],- capture_output=True,- text=True,- timeout=15,- )+ await asyncio.wait_for(handle.result(), timeout=timeout_seconds)+ except TimeoutError:+ return False+ except WorkflowFailureError:+ # Cancellation and workflow failure are terminal states. The workflow's+ # finally block has run before Temporal publishes either result.+ return Trueexcept Exception:- logger.warning("Failed to list sandbox containers for task %s", task_id, exc_info=True)- return+ logger.warning("Could not confirm eval workflow completion", exc_info=True)+ return False+ return True- for container_id in result.stdout.strip().splitlines():- if not container_id:- continue- logger.info("Cleaning up eval container %s for task %s", container_id, task_id)- try:- subprocess.run(["docker", "rm", "-f", container_id], capture_output=True, timeout=30)- except Exception:- logger.warning("Failed to remove sandbox container %s", container_id, exc_info=True)++async def _finish_workflow(handle: WorkflowHandle, *, status: str, reason: str | None) -> bool:+ """Request a terminal state and wait for the workflow's sandbox cleanup."""+ signaled = False+ try:+ await handle.signal(ProcessTaskWorkflow.complete_task, args=[status, reason])+ signaled = True+ except Exception:+ logger.warning("Could not signal eval workflow status=%s", status, exc_info=True)++ if signaled and await _wait_for_workflow_terminal(handle, WORKFLOW_COMPLETION_GRACE_SECONDS):+ return True++ try:+ await handle.cancel()+ except Exception:+ logger.warning("Could not cancel eval workflow after status=%s", status, exc_info=True)++ return await _wait_for_workflow_terminal(handle, WORKFLOW_CANCELLATION_GRACE_SECONDS)@dataclass@@ -62,16 +85,32 @@ class EvalCaseResult:async def run_eval_case(case: SandboxedEvalCase,context: CustomPromptSandboxContext,+ *,+ provider: SandboxProviderStrategy,) -> EvalCaseResult:- """Run an eval case using the full Task -> temporal workflow -> log polling pipeline."""+ """Run an eval case using the full Task -> temporal workflow -> log polling pipeline.++ The function returns only after the workflow has reached a terminal state, so+ its sandbox cleanup cannot lag behind a successful case. Failures and caller+ cancellation preserve their original outcome even when cleanup cannot be+ confirmed.+ """trace_id = str(uuid.uuid4())logger.info("Starting eval case '%s' (trace=%s) with prompt: %.100s...", case.name, trace_id, case.prompt)start = time.monotonic()task = None+ handle: WorkflowHandle | None = None+ completion_task: asyncio.Task[bool] | None = Nonetry:# Eval is a test harness — direct use of internals (instead of MTS) is intentional:# the agent isn't asked for structured JSON, and we need full_log for artifact parsing.task, task_run = await create_task_and_trigger(case.prompt, context, step_name=case.name)+ # Register the task so the end-of-run sweep stays scoped to this run's sandboxes.+ provider.register_task(str(task.id))+ # Handle to the case's workflow so a timeout/error can shut the agent down.+ workflow_id = task_run.get_workflow_id(task.id, task_run.id)+ client = await async_connect()+ handle = client.get_workflow_handle(workflow_id)last_message, full_log_opt, _, _ = await poll_for_turn(task_run, verbose=True, output_fn=lambda msg: logger.info("agent: %s", msg))@@ -86,17 +125,37 @@ async def run_eval_case(last_message or "(none)",)artifacts = _parse_artifacts_from_log(full_log, duration, agent_finished=True)+ completion_task = asyncio.create_task(_finish_workflow(handle, status="completed", reason=None))+ cleanup_confirmed = await asyncio.shield(completion_task)+ if not cleanup_confirmed:+ raise WorkflowCleanupError(+ f"Eval case '{case.name}' finished, but its workflow cleanup could not be confirmed"+ )return EvalCaseResult(artifacts=artifacts, trace_id=trace_id, raw_log=full_log)- except Exception as e:+ except (Exception, asyncio.CancelledError) as e:+ # CancelledError is how the caller's asyncio.wait_for timeout reaches this+ # coroutine; catch it explicitly so we can stop the workflow, then re-raise.duration = time.monotonic() - startlogger.exception("Eval case '%s' failed after %.1fs: %s", case.name, duration, e)- return EvalCaseResult(- artifacts=AgentArtifacts(exit_code=1, stderr=str(e), duration_seconds=duration),- trace_id=trace_id,- )+ cleanup_confirmed = False+ if completion_task is not None:+ # A case timeout can arrive while successful workflow cleanup is+ # already running. Let that bounded task settle instead of sending a+ # conflicting failed completion signal.+ cleanup_confirmed = await asyncio.shield(completion_task)+ elif handle is not None and not isinstance(e, WorkflowCleanupError):+ cleanup_confirmed = await asyncio.shield(+ _finish_workflow(handle, status="failed", reason=f"eval case '{case.name}' failed: {e}")+ )+ if handle is not None and not cleanup_confirmed:+ logger.warning("Eval workflow cleanup could not be confirmed for case '%s'", case.name)+ raisefinally:if task is not None:- await asyncio.to_thread(_cleanup_case_containers, str(task.id))+ try:+ await asyncio.to_thread(provider.cleanup_case, str(task.id))+ except Exception:+ logger.warning("Provider cleanup failed for eval task %s", task.id, exc_info=True)def _parse_artifacts_from_log(log_content: str, duration_seconds: float, agent_finished: bool) -> AgentArtifacts:@@ -160,7 +219,7 @@ def _parse_artifacts_from_log(log_content: str, duration_seconds: float, agent_ffiles_changed.extend(f.strip() for f in text.splitlines() if f.strip())# Detect test runs- if ("pytest" in title or "test" in title) and text:+ if TEST_TITLE_RE.search(title) and text:test_output = text# Infer exit code from pytest output patternsif "passed" in text and "failed" not in text and "error" not in text.lower():@@ -169,7 +228,7 @@ def _parse_artifacts_from_log(log_content: str, duration_seconds: float, agent_ftest_exit_code = 1# Detect lint runs- if ("ruff" in title or "lint" in title) and text:+ if LINT_TITLE_RE.search(title) and text:lint_output = textif "All checks passed" in text or not text.strip():lint_exit_code = 0diff --git a/products/posthog_ai/eval_harness/scorers/__init__.py b/products/posthog_ai/eval_harness/scorers/__init__.pynew file mode 100644index 000000000000..6e3f4efa7b3c--- /dev/null+++ b/products/posthog_ai/eval_harness/scorers/__init__.py@@ -0,0 +1,27 @@+from products.posthog_ai.eval_harness.log_parser import LogParser, normalize_tool_name++from .deterministic import ExitCodeZero, LastToolCallNot, NoToolCall, RequiredToolCall+from .judged import (+ BINARY_CHOICE_SCORES,+ GRADED_ALIGNMENT_CHOICE_SCORES,+ JUDGE_MODEL,+ AsyncOnlyScorerMixin,+ JudgedScorer,+)+from .tracing import TracedScorer, wrap_scorers++__all__ = [+ "BINARY_CHOICE_SCORES",+ "GRADED_ALIGNMENT_CHOICE_SCORES",+ "JUDGE_MODEL",+ "AsyncOnlyScorerMixin",+ "ExitCodeZero",+ "JudgedScorer",+ "LastToolCallNot",+ "LogParser",+ "NoToolCall",+ "RequiredToolCall",+ "TracedScorer",+ "normalize_tool_name",+ "wrap_scorers",+]diff --git a/products/posthog_ai/eval_harness/scorers/contract.py b/products/posthog_ai/eval_harness/scorers/contract.pynew file mode 100644index 000000000000..eeeaf79c7d92--- /dev/null+++ b/products/posthog_ai/eval_harness/scorers/contract.py@@ -0,0 +1,35 @@+"""The PostHog-owned scorer contract.++Ships as a shim today: ``Score`` re-exports braintrust's and ``Scorer`` is an+empty subclass of braintrust's base — zero behavior change. Both still satisfy+braintrust's duck-typed dispatch (``hasattr(scorer, "eval_async")``) and score+check (``name``/``score``/``metadata``/``as_dict``), so scorers written against+this module stay directly consumable by ``BraintrustEngine`` with no adapter.++A later flip replaces these with pure PostHog classes carrying the same surface+(``eval_async(output, expected, **kwargs)``, ``_name()``, ``Score.name/score/+metadata/as_dict``) — a single-file change that no scorer has to follow.+"""++from __future__ import annotations++from typing import Any++from braintrust import Score as Score+from braintrust_core.score import Scorer as _UpstreamScorer+++class Scorer(_UpstreamScorer):+ """PostHog's scorer base. An empty subclass of braintrust's base for now."""+++class AsyncOnlyScorerMixin:+ """Marks a scorer as async-only; the sync branch is unreachable in the harness.++ The harness runs every scorer through the engine, which dispatches via+ ``eval_async``, so async-only scorers turn the never-used sync branch into an+ explicit error instead of a silently divergent code path.+ """++ def _run_eval_sync(self, output: Any, expected: Any = None, **kwargs: Any) -> Score:+ raise NotImplementedError(f"{type(self).__name__} is async-only; call eval_async()")diff --git a/ee/hogai/eval/sandboxed/scorers/deterministic.py b/products/posthog_ai/eval_harness/scorers/deterministic.pysimilarity index 79%rename from ee/hogai/eval/sandboxed/scorers/deterministic.pyrename to products/posthog_ai/eval_harness/scorers/deterministic.pyindex cc94c939f682..841fbf5f5eb4 100644--- a/ee/hogai/eval/sandboxed/scorers/deterministic.py+++ b/products/posthog_ai/eval_harness/scorers/deterministic.py@@ -2,10 +2,9 @@ from __future__ import annotationsfrom collections.abc import Iterable-from braintrust import Score-from braintrust_core.score import Scorer+from products.posthog_ai.eval_harness.log_parser import LogParser-from ee.hogai.eval.sandboxed.log_parser import LogParser+from .contract import Score, Scorerclass ExitCodeZero(Scorer):@@ -14,13 +13,7 @@ class ExitCodeZero(Scorer):def _name(self) -> str:return "exit_code_zero"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _evaluate(self, output: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=0.0, metadata={"reason": "No output"})exit_code = output.get("exit_code", -1)@@ -54,20 +47,14 @@ class NoToolCall(Scorer):def _name(self) -> str:return self._label- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _evaluate(self, output: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})raw_log = output.get("raw_log")if not raw_log:return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})- parser = LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")+ parser = LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")successful_calls: list[str] = [call.name for call in parser.get_tool_calls() if not call.is_error and call.name in self.forbidden]@@ -108,20 +95,14 @@ class LastToolCallNot(Scorer):def _name(self) -> str:return self._label- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _evaluate(self, output: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})raw_log = output.get("raw_log")if not raw_log:return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})- parser = LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")+ parser = LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")successful = [call for call in parser.get_tool_calls() if not call.is_error]if not successful:return Score(name=self._name(), score=None, metadata={"reason": "No successful tool calls"})@@ -158,20 +139,14 @@ class RequiredToolCall(Scorer):def _name(self) -> str:return self._label- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _evaluate(self, output: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})raw_log = output.get("raw_log")if not raw_log:return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})- parser = LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")+ parser = LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")seen: list[str] = [call.name for call in parser.get_tool_calls() if not call.is_error and call.name in self.required]diff --git a/products/posthog_ai/eval_harness/scorers/judged.py b/products/posthog_ai/eval_harness/scorers/judged.pynew file mode 100644index 000000000000..e95b113ddca0--- /dev/null+++ b/products/posthog_ai/eval_harness/scorers/judged.py@@ -0,0 +1,66 @@+"""Shared wiring for sandboxed LLM-judge scorers.++The harness runs every scorer through Braintrust's ``EvalAsync``, which always+dispatches via ``eval_async`` — so judges implement only the async branch, and+``AsyncOnlyScorerMixin`` turns the never-used sync branch into an explicit error+instead of a silently divergent code path.+"""++from __future__ import annotations++from typing import Any++from autoevals.llm import LLMClassifier++from .contract import AsyncOnlyScorerMixin, Score++# Re-exported for back-compat: AsyncOnlyScorerMixin now lives in the scorer contract.+__all__ = [+ "BINARY_CHOICE_SCORES",+ "GRADED_ALIGNMENT_CHOICE_SCORES",+ "JUDGE_MODEL",+ "AsyncOnlyScorerMixin",+ "JudgedScorer",+]++BINARY_CHOICE_SCORES = {"yes": 1.0, "no": 0.0}++GRADED_ALIGNMENT_CHOICE_SCORES = {+ "perfect": 1.0,+ "near_perfect": 0.9,+ "slightly_off": 0.75,+ "somewhat_misaligned": 0.5,+ "strongly_misaligned": 0.25,+ "useless": 0.0,+}++JUDGE_MODEL = "gpt-5.4"+++class JudgedScorer(AsyncOnlyScorerMixin, LLMClassifier):+ """Base class for sandboxed LLM judges.++ Subclasses implement ``_prepare(output, expected)`` returning either a+ ``Score`` to short-circuit (no LLM call), or a dict with ``output`` — and+ optionally ``expected`` — to forward to the LLM judge as template variables.++ Both the short-circuit paths and judge-call exceptions map to+ ``score=0.0`` rather than ``score=None`` — Braintrust treats ``None`` as+ "skipped" and drops it from the aggregate, which silently hides broken+ judges and missing query inputs. We want those to surface as failing+ scores instead. Judges that should genuinely self-skip (e.g. the graded+ tool never ran and another scorer covers that) return ``Score(score=None)``+ from ``_prepare`` deliberately.+ """++ async def _run_eval_async(self, output: Any, expected: Any = None, **kwargs: Any) -> Score:+ prepared = self._prepare(output, expected)+ if isinstance(prepared, Score):+ return prepared+ try:+ return await super()._run_eval_async(prepared["output"], prepared.get("expected"), **kwargs)+ except Exception as exc:+ return Score(name=self._name(), score=0.0, metadata={"reason": f"judge error: {exc}"})++ def _prepare(self, output: Any, expected: Any) -> dict[str, Any] | Score:+ raise NotImplementedErrordiff --git a/ee/hogai/eval/sandboxed/scorers/tracing.py b/products/posthog_ai/eval_harness/scorers/tracing.pysimilarity index 93%rename from ee/hogai/eval/sandboxed/scorers/tracing.pyrename to products/posthog_ai/eval_harness/scorers/tracing.pyindex eca1c79f24ee..a00fa80c38bb 100644--- a/ee/hogai/eval/sandboxed/scorers/tracing.py+++ b/products/posthog_ai/eval_harness/scorers/tracing.py@@ -16,10 +16,10 @@ from contextvars import ContextVarfrom dataclasses import dataclassfrom typing import Any-from braintrust_core.score import Scorerfrom posthoganalytics import Posthogfrom ..trace_events import DISTINCT_ID+from .contract import AsyncOnlyScorerMixin, Scorer# Context var for injecting per-scorer-invocation trace properties# into the traced OpenAI client's ``create()`` calls.@@ -111,7 +111,7 @@ def create_traced_scorer_clients(posthog_client: Posthog) -> TracedClients:)-class TracedScorer(Scorer):+class TracedScorer(AsyncOnlyScorerMixin, Scorer):"""Wraps a Scorer to trace LLM calls and collect per-invocation trace IDs.For LLM-based scorers (those with a ``client`` attribute), injects a@@ -176,15 +176,9 @@ class TracedScorer(Scorer):async def _run_eval_async(self, output, expected=None, **kwargs):case_name = _case_name_from_kwargs(kwargs)with self._invocation_context(case_name) as is_llm_scorer:- result = await self._inner._run_eval_async(output, expected, **kwargs)- if not is_llm_scorer and self._posthog_client:- self._emit_scorer_span(case_name, result)- return result-- def _run_eval_sync(self, output, expected=None, **kwargs):- case_name = _case_name_from_kwargs(kwargs)- with self._invocation_context(case_name) as is_llm_scorer:- result = self._inner._run_eval_sync(output, expected, **kwargs)+ # eval_async, not _run_eval_async: sync-only inner scorers rely on+ # the base class's async-to-sync delegation.+ result = await self._inner.eval_async(output, expected, **kwargs)if not is_llm_scorer and self._posthog_client:self._emit_scorer_span(case_name, result)return result@@ -223,6 +217,7 @@ def wrap_scorers(experiment_id: str,experiment_name: str,agent_trace_id_lookup: dict[str, str],+ trace_namespace: str = "sandboxed-agent",) -> tuple[list[Any], dict[tuple[str, str], str]]:"""Wrap scorers with tracing.@@ -230,13 +225,14 @@ def wrap_scorers(``agent_trace_id_lookup`` maps case_name → agent trace_id. It's populatedby the ``task()`` function and read by deterministic scorers to attach- their spans to the agent trace.+ their spans to the agent trace. ``trace_namespace`` prefixes the experiment+ name in trace metadata so eval kinds stay distinguishable in PostHog."""traced_clients = create_traced_scorer_clients(posthog_client)scorer_traces: dict[tuple[str, str], str] = {}eval_metadata = {"experiment_id": experiment_id,- "experiment_name": f"sandboxed-agent/{experiment_name}",+ "experiment_name": f"{trace_namespace}/{experiment_name}",}wrapped = [TracedScorer(diff --git a/ee/hogai/eval/sandboxed/seeders/common.py b/products/posthog_ai/eval_harness/seeders/common.pysimilarity index 95%rename from ee/hogai/eval/sandboxed/seeders/common.pyrename to products/posthog_ai/eval_harness/seeders/common.pyindex ae76b362edc7..cdee675a25fd 100644--- a/ee/hogai/eval/sandboxed/seeders/common.py+++ b/products/posthog_ai/eval_harness/seeders/common.py@@ -3,7 +3,7 @@Seeders are plain callables that receive the per-case``CustomPromptSandboxContext`` and return a dict that gets merged into thetask output under ``seed`` so scorers can read seeded entity IDs. The-wiring lives in ``ee/hogai/eval/sandboxed/base.py:task()``; the per-entity+wiring lives in ``products/posthog_ai/eval_harness/base.py:task()``; the per-entityseeders live in sibling modules (``insight.py`` etc.).This module collects pieces every seeder is likely to want:diff --git a/ee/hogai/eval/sandboxed/seeders/insight.py b/products/posthog_ai/eval_harness/seeders/insight.pysimilarity index 97%rename from ee/hogai/eval/sandboxed/seeders/insight.pyrename to products/posthog_ai/eval_harness/seeders/insight.pyindex 84ea09d0f917..fc7aecc00e91 100644--- a/ee/hogai/eval/sandboxed/seeders/insight.py+++ b/products/posthog_ai/eval_harness/seeders/insight.py@@ -11,10 +11,9 @@ from __future__ import annotationsimport loggingfrom typing import Any+from products.posthog_ai.eval_harness.seeders.common import LOOKUP_PREFIX, NameProviders, make_name_providersfrom products.tasks.backend.facade.agents import CustomPromptSandboxContext-from ee.hogai.eval.sandboxed.seeders.common import LOOKUP_PREFIX, NameProviders, make_name_providers-logger = logging.getLogger(__name__)diff --git a/ee/hogai/eval/sandboxed/seeders/survey.py b/products/posthog_ai/eval_harness/seeders/survey.pysimilarity index 100%rename from ee/hogai/eval/sandboxed/seeders/survey.pyrename to products/posthog_ai/eval_harness/seeders/survey.pydiff --git a/products/posthog_ai/eval_harness/test/__init__.py b/products/posthog_ai/eval_harness/test/__init__.pynew file mode 100644index 000000000000..4221e4e543b7--- /dev/null+++ b/products/posthog_ai/eval_harness/test/__init__.py@@ -0,0 +1 @@+"""Unit tests for the eval harness (pytest — unlike the harness itself, which runs standalone)."""diff --git a/ee/hogai/test/test_acp_log.py b/products/posthog_ai/eval_harness/test/test_acp_log.pysimilarity index 99%rename from ee/hogai/test/test_acp_log.pyrename to products/posthog_ai/eval_harness/test/test_acp_log.pyindex c261eb52826f..9fd418beffd9 100644--- a/ee/hogai/test/test_acp_log.py+++ b/products/posthog_ai/eval_harness/test/test_acp_log.py@@ -12,7 +12,7 @@ import jsonfrom posthog.test.base import BaseTest-from ee.hogai.eval.sandboxed.acp_log import parse_log+from products.posthog_ai.eval_harness.acp_log import parse_logdef _notification(**params) -> dict:diff --git a/products/posthog_ai/eval_harness/test/test_acp_log_model.py b/products/posthog_ai/eval_harness/test/test_acp_log_model.pynew file mode 100644index 000000000000..24e484dc22dd--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_acp_log_model.py@@ -0,0 +1,345 @@+from __future__ import annotations++import json++import pytest++from products.posthog_ai.eval_harness.acp_log import parse_log+++def _line(payload: dict) -> str:+ return json.dumps({"type": "notification", "timestamp": "2026-04-29T08:42:29.620Z", "notification": payload})+++ "lines, expected_model",+ [+ pytest.param(+ [+ _line(+ {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "session/new",+ "params": {"model": "anthropic/claude-opus-4-7"},+ }+ ),+ ],+ "anthropic/claude-opus-4-7",+ id="captures_from_session_new_params",+ ),+ pytest.param(+ [+ _line({"jsonrpc": "2.0", "id": 1, "method": "session/new", "params": {"cwd": "/tmp"}}),+ _line(+ {+ "jsonrpc": "2.0",+ "id": 1,+ "result": {"sessionId": "s1", "models": {"currentModelId": "claude-sonnet-4-6"}},+ }+ ),+ ],+ "claude-sonnet-4-6",+ id="falls_back_to_result_currentModelId",+ ),+ pytest.param(+ [+ _line(+ {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "session/new",+ "params": {"model": "anthropic/claude-opus-4-7"},+ }+ ),+ _line(+ {+ "jsonrpc": "2.0",+ "id": 1,+ "result": {"sessionId": "s1", "models": {"currentModelId": "claude-sonnet-4-6"}},+ }+ ),+ ],+ "anthropic/claude-opus-4-7",+ id="prefers_params_over_result_when_both_present",+ ),+ pytest.param(+ [+ _line({"jsonrpc": "2.0", "id": 1, "method": "session/prompt", "params": {}}),+ ],+ "",+ id="empty_when_no_session_new",+ ),+ pytest.param(+ [+ _line({"jsonrpc": "2.0", "id": 1, "method": "session/new", "params": {"model": ""}}),+ _line(+ {+ "jsonrpc": "2.0",+ "id": 1,+ "result": {"sessionId": "s1", "models": {"currentModelId": "claude-haiku-4-5"}},+ }+ ),+ ],+ "claude-haiku-4-5",+ id="ignores_empty_string_model_and_falls_back",+ ),+ pytest.param(+ [+ _line({"jsonrpc": "2.0", "id": 1, "method": "session/new", "params": {"cwd": "/tmp"}}),+ _line(+ {+ "jsonrpc": "2.0",+ "id": 1,+ "result": {+ "sessionId": "s1",+ "configOptions": [+ {"type": "select", "id": "mode", "category": "mode", "currentValue": "auto"},+ {"type": "select", "id": "model", "category": "model", "currentValue": "gpt-5.5"},+ {"type": "select", "id": "effort", "category": "thought_level", "currentValue": "low"},+ ],+ },+ }+ ),+ ],+ "gpt-5.5",+ id="falls_back_to_config_options_model_entry",+ ),+ pytest.param(+ [+ _line({"jsonrpc": "2.0", "id": 1, "method": "session/new", "params": {"cwd": "/tmp"}}),+ _line(+ {+ "jsonrpc": "2.0",+ "id": 1,+ "result": {+ "sessionId": "s1",+ "models": {"currentModelId": "claude-sonnet-4-6"},+ "configOptions": [{"type": "select", "id": "model", "currentValue": "gpt-5.5"}],+ },+ }+ ),+ ],+ "claude-sonnet-4-6",+ id="prefers_current_model_id_over_config_options",+ ),+ ],+)+def test_parse_log_extracts_agent_model(lines: list[str], expected_model: str) -> None:+ parsed = parse_log("\n".join(lines))+ assert parsed.model == expected_model+++def _tool_call_line(meta: dict | None, title: str) -> str:+ return _line(+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "update": {+ "sessionUpdate": "tool_call",+ "toolCallId": "t1",+ "title": title,+ "_meta": meta,+ "rawInput": {},+ }+ },+ }+ )+++ "meta, title, expected_name",+ [+ pytest.param(+ {"claudeCode": {"toolName": "mcp__posthog__execute_sql"}},+ "execute sql",+ "mcp__posthog__execute_sql",+ id="claude_runtime_meta",+ ),+ pytest.param(+ {"posthog": {"toolName": "mcp__posthog__exec", "mcp": {"server": "posthog", "tool": "exec"}}},+ "posthog/exec",+ "mcp__posthog__exec",+ id="codex_runtime_meta",+ ),+ pytest.param(None, "/bin/bash -lc ls", "/bin/bash -lc ls", id="null_meta_falls_back_to_title"),+ pytest.param({"posthog": {}}, "posthog/exec", "posthog/exec", id="empty_adapter_meta_falls_back_to_title"),+ ],+)+def test_parse_log_resolves_tool_name_from_runtime_meta(meta: dict | None, title: str, expected_name: str) -> None:+ parsed = parse_log(_tool_call_line(meta, title))+ tool_uses = [+ block+ for message in parsed.messages+ if isinstance(message.get("content"), list)+ for block in message["content"]+ if block.get("type") == "tool_use"+ ]+ assert [block["name"] for block in tool_uses] == [expected_name]+++def _tool_call_update_line(status: str, extra: dict) -> str:+ return _line(+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {"update": {"sessionUpdate": "tool_call_update", "toolCallId": "t1", "status": status, **extra}},+ }+ )+++def _text_block(text: str) -> dict:+ return {"type": "content", "content": {"type": "text", "text": text}}+++ "status, extra, expected_content, expected_is_error",+ [+ pytest.param(+ "completed",+ {"content": [_text_block("42 rows")]},+ "42 rows",+ False,+ id="codex_content_list",+ ),+ pytest.param(+ "completed",+ {"content": [_text_block("first"), _text_block("second")]},+ "first\nsecond",+ False,+ id="joins_multiple_content_blocks",+ ),+ pytest.param(+ "completed",+ {"content": [_text_block("ignored")], "rawOutput": {"success": True}},+ json.dumps({"success": True}),+ False,+ id="raw_output_wins_over_content_list",+ ),+ pytest.param(+ "failed",+ {"content": [_text_block("boom")]},+ "boom",+ True,+ id="failed_status_extracts_error_text",+ ),+ pytest.param(+ "completed",+ {"content": [{"type": "diff", "path": "a.txt", "oldText": "old", "newText": "new"}]},+ "[diff] a.txt",+ False,+ id="diff_blocks_render_as_path_marker",+ ),+ pytest.param("completed", {}, "(no output)", False, id="missing_output_keeps_placeholder"),+ ],+)+def test_parse_log_extracts_tool_result_from_content_list(+ status: str, extra: dict, expected_content: str, expected_is_error: bool+) -> None:+ lines = [_tool_call_line(None, "posthog/exec"), _tool_call_update_line(status, extra)]+ parsed = parse_log("\n".join(lines))+ tool_results = [+ block+ for message in parsed.messages+ if isinstance(message.get("content"), list)+ for block in message["content"]+ if block.get("type") == "tool_result"+ ]+ assert len(tool_results) == 1+ assert tool_results[0]["content"] == expected_content+ assert tool_results[0].get("is_error", False) is expected_is_error+++def _agent_message_line(text: str) -> str:+ return _line(+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {"update": {"sessionUpdate": "agent_message", "content": {"type": "text", "text": text}}},+ }+ )+++ "lines, expected_usages",+ [+ pytest.param(+ [+ _agent_message_line("checking"),+ _tool_call_line({"posthog": {"toolName": "mcp__posthog__exec"}}, "posthog/exec"),+ _tool_call_update_line("completed", {"content": [_text_block("42 rows")]}),+ _line(+ {+ "jsonrpc": "2.0",+ "method": "_posthog/usage_update",+ "params": {+ "sessionId": "s1",+ "usage": {+ "inputTokens": 100,+ "outputTokens": 20,+ "cachedReadTokens": 5,+ "reasoningTokens": 3,+ "totalTokens": 120,+ },+ },+ }+ ),+ _agent_message_line("done"),+ _line({"jsonrpc": "2.0", "id": 2, "result": {"stopReason": "end_turn"}}),+ ],+ [+ {+ "inputTokens": 100,+ "outputTokens": 20,+ "cachedReadTokens": 5,+ "cachedWriteTokens": 0,+ "totalTokens": 120,+ "reasoningTokens": 3,+ },+ {},+ ],+ id="codex_usage_update_attaches_to_flushed_generation",+ ),+ pytest.param(+ [+ _agent_message_line("done"),+ _line(+ {+ "jsonrpc": "2.0",+ "id": 2,+ "result": {"stopReason": "end_turn", "usage": {"inputTokens": 50, "outputTokens": 10}},+ }+ ),+ ],+ [+ {+ "inputTokens": 50,+ "outputTokens": 10,+ "cachedReadTokens": 0,+ "cachedWriteTokens": 0,+ "totalTokens": 0,+ }+ ],+ id="claude_result_usage_still_wins",+ ),+ pytest.param(+ [+ _agent_message_line("done"),+ _line(+ {+ "jsonrpc": "2.0",+ "method": "_posthog/usage_update",+ "params": {"sessionId": "s1", "used": {"inputTokens": 50}, "cost": 0.75},+ }+ ),+ _line({"jsonrpc": "2.0", "id": 2, "result": {"stopReason": "end_turn"}}),+ ],+ [{}],+ id="claude_usage_update_without_usage_key_is_ignored",+ ),+ ],+)+def test_parse_log_attaches_token_usage_per_generation(lines: list[str], expected_usages: list[dict]) -> None:+ parsed = parse_log("\n".join(lines))+ assert [gen.token_usage for gen in parsed.generations] == expected_usagesdiff --git a/products/posthog_ai/eval_harness/test/test_braintrust_engine.py b/products/posthog_ai/eval_harness/test/test_braintrust_engine.pynew file mode 100644index 000000000000..d33abc170a5f--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_braintrust_engine.py@@ -0,0 +1,101 @@+from __future__ import annotations++from typing import Any++from braintrust.framework import EvalResult, EvalResultWithSummary+from braintrust.logger import ExperimentSummary, ScoreSummary++from products.posthog_ai.eval_harness.engines.braintrust import BraintrustEngine, _BraintrustCaseHooks+++def _summary(**overrides: Any) -> ExperimentSummary:+ defaults: dict[str, Any] = {+ "project_name": "p",+ "project_id": None,+ "experiment_id": None,+ "experiment_name": "exp",+ "project_url": None,+ "experiment_url": None,+ "comparison_experiment_name": None,+ "scores": {"acc": ScoreSummary("acc", 3, 0.5, None, None)},+ "metrics": {},+ }+ defaults.update(overrides)+ return ExperimentSummary(**defaults)+++def test_translate_preserves_none_scores_and_stringifies_errors() -> None:+ result: EvalResultWithSummary = EvalResultWithSummary(+ summary=_summary(experiment_url="https://bt.example/e"),+ results=[+ EvalResult(input={"name": "a"}, output={"v": 1}, scores={"acc": 1.0}, expected={"e": 1}, metadata={"m": 1}),+ EvalResult(input={"name": "skip"}, output={}, scores={"acc": None}, metadata={}),+ EvalResult(input={"name": "boom"}, output=None, scores={}, error=ValueError("infra boom")),+ ],+ )++ translated = BraintrustEngine()._translate(result)++ assert [r.scores for r in translated.results] == [{"acc": 1.0}, {"acc": None}, {}]+ assert translated.results[2].error == "infra boom"+ assert translated.results[0].error is None+ assert translated.results[0].input == {"name": "a"}+ assert translated.results[0].expected == {"e": 1}+ assert translated.results[0].metadata == {"m": 1}+ assert translated.summary.engine_name == "braintrust"+ assert translated.summary.experiment_url == "https://bt.example/e"+ assert translated.summary.scores["acc"].score == 0.5+++def test_translate_summary_raw_round_trips_as_json() -> None:+ summary = _summary()+ translated = BraintrustEngine()._translate(EvalResultWithSummary(summary=summary, results=[]))++ # The jsonl export must stay byte-identical to what braintrust would write.+ assert translated.summary.as_json() == summary.as_json()+++class _FakeSpan:+ def __init__(self) -> None:+ self.logs: list[dict[str, Any]] = []++ def log(self, **kwargs: Any) -> None:+ self.logs.append(kwargs)++ def __enter__(self) -> _FakeSpan:+ return self++ def __exit__(self, *exc: Any) -> None:+ return None+++class _FakeSpanFactory:+ def __init__(self) -> None:+ self.started: list[tuple[str, dict[str, Any], _FakeSpan]] = []++ def start_span(self, *, name: str, span_attributes: dict[str, Any]) -> _FakeSpan:+ span = _FakeSpan()+ self.started.append((name, span_attributes, span))+ return span+++class _FakeEvalHooks:+ def __init__(self) -> None:+ self.metadata: dict[str, Any] = {}+ self.span = _FakeSpanFactory()+++def test_case_hooks_adapter_writes_through_metadata_and_translates_spans() -> None:+ hooks = _FakeEvalHooks()+ adapter = _BraintrustCaseHooks(hooks) # type: ignore[arg-type]++ adapter.metadata["trace_id"] = "t1"+ # Write-through: mutations must land on the underlying braintrust hooks.+ assert hooks.metadata == {"trace_id": "t1"}++ with adapter.start_span("agent", "llm") as span:+ span.log(output="hi")++ name, attrs, started_span = hooks.span.started[0]+ assert (name, attrs) == ("agent", {"type": "llm"})+ assert started_span.logs == [{"output": "hi"}]diff --git a/products/posthog_ai/eval_harness/test/test_discovery.py b/products/posthog_ai/eval_harness/test/test_discovery.pynew file mode 100644index 000000000000..afcf74e55e1f--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_discovery.py@@ -0,0 +1,94 @@+from __future__ import annotations++from pathlib import Path++import pytest++from products.posthog_ai.eval_harness.harness.discovery import SuiteDiscoveryError, discover_suites+from products.posthog_ai.eval_harness.harness.requirements import SuiteKind++_ONE_SHOT_MODULE = """+from products.posthog_ai.eval_harness.harness.requirements import SuiteKind++SUITE_KIND = SuiteKind.ONE_SHOT+++async def eval_alpha(ctx) -> None:+ return None+"""++_DEFAULT_MODULE = """+async def eval_beta(ctx) -> None:+ return None+"""++_SINGULAR_MODULE = """+async def eval_should_be_ignored(ctx) -> None:+ return None+"""+++def product_roots(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, Path]:+ products_root = tmp_path / "fakeproducts"+ empty_builtin_root = tmp_path / "builtin"+ empty_builtin_root.mkdir()++ one_shot = products_root / "analytics" / "evals"+ one_shot.mkdir(parents=True)+ (one_shot / "eval_one.py").write_text(_ONE_SHOT_MODULE)++ default = products_root / "core" / "evals"+ default.mkdir(parents=True)+ (default / "eval_two.py").write_text(_DEFAULT_MODULE)++ # Singular ``eval/`` (the existing pytest tree convention) must never be+ # picked up by the harness.+ singular = products_root / "signals" / "eval"+ singular.mkdir(parents=True)+ (singular / "eval_ignored.py").write_text(_SINGULAR_MODULE)++ # The import anchor is the parent of the products root.+ monkeypatch.syspath_prepend(str(tmp_path))+ return products_root, empty_builtin_root+++def _discover(product_roots: tuple[Path, Path]) -> dict[str, SuiteKind]:+ products_root, builtin_root = product_roots+ suites = discover_suites(builtin_root=builtin_root, products_root=products_root)+ return {suite.id: suite.kind for suite in suites}+++def test_product_suites_discovered_with_product_scoped_ids(product_roots: tuple[Path, Path]) -> None:+ ids = _discover(product_roots)+ assert set(ids) == {"analytics/eval_one::eval_alpha", "core/eval_two::eval_beta"}+++def test_singular_eval_dir_is_ignored(product_roots: tuple[Path, Path]) -> None:+ ids = _discover(product_roots)+ assert not any("eval_ignored" in suite_id for suite_id in ids)+++ "suite_id, expected_kind",+ [+ pytest.param("analytics/eval_one::eval_alpha", SuiteKind.ONE_SHOT, id="marker_respected"),+ pytest.param("core/eval_two::eval_beta", SuiteKind.SANDBOXED, id="absent_marker_defaults_sandboxed"),+ ],+)+def test_suite_kind_resolved_from_product_module(+ product_roots: tuple[Path, Path], suite_id: str, expected_kind: SuiteKind+) -> None:+ assert _discover(product_roots)[suite_id] == expected_kind+++def test_selector_matches_product_suite_ids(product_roots: tuple[Path, Path]) -> None:+ products_root, builtin_root = product_roots+ suites = discover_suites(["analytics"], builtin_root=builtin_root, products_root=products_root)+ assert [suite.id for suite in suites] == ["analytics/eval_one::eval_alpha"]+++def test_unmatched_selector_raises(product_roots: tuple[Path, Path]) -> None:+ products_root, builtin_root = product_roots+ with pytest.raises(SuiteDiscoveryError):+ discover_suites(["nonexistent"], builtin_root=builtin_root, products_root=products_root)diff --git a/products/posthog_ai/eval_harness/test/test_engine_conformance.py b/products/posthog_ai/eval_harness/test/test_engine_conformance.pynew file mode 100644index 000000000000..7ebcc1f3f906--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_engine_conformance.py@@ -0,0 +1,188 @@+from __future__ import annotations++import asyncio+from collections import defaultdict+from collections.abc import Sequence+from typing import Any++import pytest++import braintrust.framework as bt_framework+from braintrust import Score+from braintrust.framework import EvalResult, Evaluator+from braintrust.logger import ExperimentSummary, ScoreSummary+from braintrust_core.score import Scorer++from products.posthog_ai.eval_harness.engines.braintrust import BraintrustEngine+from products.posthog_ai.eval_harness.engines.types import CaseHooks, CaseSpec, ExperimentResult, ExperimentSpec++# Every ``EvalEngine`` must satisfy these obligations; a future ``PostHogEvalsEngine``+# joins this parameter list and must pass the same suite unchanged.+pytestmark = pytest.mark.parametrize("engine", ["braintrust"], indirect=True)+++def _none_safe_local_summary(+ evaluator: Evaluator[Any, Any], results: Sequence[EvalResult[Any, Any]]+) -> ExperimentSummary:+ """A None-aware replacement for braintrust's offline ``build_local_summary``.++ The stock offline path sums ``None`` scores and crashes (a local-mode bug the+ authenticated path doesn't have — the real harness always runs authenticated).+ This shim excludes ``None`` from the mean, matching authenticated behavior, so+ the offline fixture can exercise the None-exclusion the engine contract promises.+ """+ by_name: dict[str, tuple[float, int]] = defaultdict(lambda: (0.0, 0))+ for result in results:+ for name, score in result.scores.items():+ if score is None:+ continue+ total, count = by_name[name]+ by_name[name] = (total + score, count + 1)+ longest = max((len(name) for name in by_name), default=0)+ scores = {+ name: ScoreSummary(+ name=name,+ _longest_score_name=longest,+ score=(total / count if count else 0.0),+ improvements=0,+ regressions=0,+ )+ for name, (total, count) in by_name.items()+ }+ return ExperimentSummary(+ project_name=evaluator.project_name,+ project_id=None,+ experiment_id=None,+ experiment_name=evaluator.experiment_name or evaluator.project_name,+ project_url=None,+ experiment_url=None,+ comparison_experiment_name=None,+ scores=scores,+ metrics={},+ )+++def engine(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> BraintrustEngine:+ if request.param == "braintrust":+ # Keep the run fully offline: no API key means no login and no network.+ monkeypatch.delenv("BRAINTRUST_API_KEY", raising=False)+ monkeypatch.setattr(bt_framework, "build_local_summary", _none_safe_local_summary)+ return BraintrustEngine()+ raise AssertionError(f"unknown engine fixture: {request.param}")+++class _MaybeNoneScorer(Scorer):+ """Scores 1.0/0.0 by the ``good`` flag, but skips (``None``) when ``skip`` is set."""++ def _name(self) -> str:+ return "maybe"++ def _run_eval_sync(self, output: dict[str, Any] | None, expected: Any = None, **kwargs: Any) -> Score:+ if output and output.get("skip"):+ return Score(name="maybe", score=None)+ return Score(name="maybe", score=1.0 if (output and output.get("good")) else 0.0)+++def _spec(+ task: Any,+ cases: list[CaseSpec],+ *,+ scorers: list[Any] | None = None,+ trial_count: int = 1,+) -> ExperimentSpec:+ return ExperimentSpec(+ project_name="conformance",+ cases=cases,+ task=task,+ scorers=scorers if scorers is not None else [_MaybeNoneScorer()],+ trial_count=trial_count,+ is_public=False,+ no_send_logs=True,+ metadata={},+ )+++def _run(engine: BraintrustEngine, spec: ExperimentSpec) -> ExperimentResult:+ return asyncio.run(engine.run_experiment(spec))+++def test_one_result_per_case_and_trial(engine: BraintrustEngine) -> None:+ async def task(input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:+ return {"good": True}++ cases = [CaseSpec(input={"name": name}) for name in ("a", "b", "c")]+ result = _run(engine, _spec(task, cases, trial_count=2))++ assert len(result.results) == 6+++def test_input_round_trips(engine: BraintrustEngine) -> None:+ async def task(input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:+ return {"good": True}++ cases = [CaseSpec(input={"name": name}) for name in ("a", "b")]+ result = _run(engine, _spec(task, cases))++ assert sorted(r.input["name"] for r in result.results) == ["a", "b"]+++def test_hooks_metadata_persisted(engine: BraintrustEngine) -> None:+ async def task(input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:+ hooks.metadata["seen"] = input["name"]+ return {"good": True}++ result = _run(engine, _spec(task, [CaseSpec(input={"name": "a"})]))++ assert result.results[0].metadata.get("seen") == "a"+++def test_task_exception_becomes_error_and_is_excluded_from_aggregate(engine: BraintrustEngine) -> None:+ async def task(input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:+ if input["name"] == "boom":+ raise ValueError("infra boom")+ return {"good": True}++ cases = [CaseSpec(input={"name": name}) for name in ("a", "boom", "b")]+ result = _run(engine, _spec(task, cases))++ by_name = {r.input["name"]: r for r in result.results}+ assert by_name["boom"].error is not None+ assert by_name["boom"].scores == {}+ assert by_name["a"].error is None+ # boom is excluded: the mean is over the two successful 1.0 scores.+ assert result.summary.scores["maybe"].score == 1.0+++def test_none_score_preserved_per_case_and_excluded_from_aggregate(engine: BraintrustEngine) -> None:+ async def task(input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:+ if input["name"] == "skip":+ return {"skip": True}+ return {"good": input["name"] == "hit"}++ cases = [CaseSpec(input={"name": name}) for name in ("hit", "skip", "miss")]+ result = _run(engine, _spec(task, cases))++ by_name = {r.input["name"]: r for r in result.results}+ assert by_name["skip"].scores == {"maybe": None}+ # None is excluded, so the mean is over hit (1.0) and miss (0.0).+ assert result.summary.scores["maybe"].score == 0.5+++def test_engine_does_not_throttle_concurrency(engine: BraintrustEngine) -> None:+ active = 0+ peak = 0++ async def task(input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:+ nonlocal active, peak+ active += 1+ peak = max(peak, active)+ await asyncio.sleep(0.05)+ active -= 1+ return {"good": True}++ cases = [CaseSpec(input={"name": str(i)}) for i in range(5)]+ _run(engine, _spec(task, cases))++ # The engine must admit every case at once; only the harness's own semaphores gate.+ assert peak == 5diff --git a/products/posthog_ai/eval_harness/test/test_env_file_parser.py b/products/posthog_ai/eval_harness/test/test_env_file_parser.pynew file mode 100644index 000000000000..5f9c39eeff6d--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_env_file_parser.py@@ -0,0 +1,35 @@+from __future__ import annotations++from pathlib import Path++import pytest++from products.posthog_ai.eval_harness.harness.env_preflight import parse_env_file++PEM_ESCAPED = 'KEY="-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBg\\n-----END PRIVATE KEY-----\\n"'+PEM_MULTILINE = 'KEY="-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBg\n-----END PRIVATE KEY-----\n"'+PEM_DECODED = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBg\n-----END PRIVATE KEY-----\n"+++ "content, expected",+ [+ pytest.param("KEY=value", {"KEY": "value"}, id="bare_assignment"),+ pytest.param("export KEY=value", {"KEY": "value"}, id="export_prefix"),+ pytest.param("KEY = spaced ", {"KEY": "spaced"}, id="whitespace_stripped"),+ pytest.param("# comment\n\nKEY=value\n", {"KEY": "value"}, id="comments_and_blank_lines_skipped"),+ pytest.param("KEY=value # trailing comment", {"KEY": "value"}, id="unquoted_inline_comment_stripped"),+ pytest.param("KEY='single # quoted'", {"KEY": "single # quoted"}, id="single_quotes_keep_hashes"),+ pytest.param("KEY='literal\\nvalue'", {"KEY": "literal\\nvalue"}, id="single_quotes_skip_escape_decoding"),+ pytest.param('KEY="a\\tb\\"c\\\\d"', {"KEY": 'a\tb"c\\d'}, id="double_quotes_decode_escapes"),+ pytest.param(PEM_ESCAPED, {"KEY": PEM_DECODED}, id="escaped_pem_becomes_multiline"),+ pytest.param(PEM_MULTILINE, {"KEY": PEM_DECODED}, id="quoted_multiline_pem"),+ pytest.param("KEY=first\nKEY=second", {"KEY": "second"}, id="later_assignment_wins"),+ pytest.param("not an assignment\nKEY=value", {"KEY": "value"}, id="malformed_lines_skipped"),+ pytest.param("KEY=", {"KEY": ""}, id="empty_value"),+ ],+)+def test_parse_env_file(tmp_path: Path, content: str, expected: dict[str, str]) -> None:+ env_file = tmp_path / ".env"+ env_file.write_text(content)+ assert parse_env_file(env_file) == expecteddiff --git a/products/error_tracking/backend/hogql_queries/test/test_eval_scorers.py b/products/posthog_ai/eval_harness/test/test_eval_scorers.pysimilarity index 98%rename from products/error_tracking/backend/hogql_queries/test/test_eval_scorers.pyrename to products/posthog_ai/eval_harness/test/test_eval_scorers.pyindex e567f86526ff..b893c2299256 100644--- a/products/error_tracking/backend/hogql_queries/test/test_eval_scorers.py+++ b/products/posthog_ai/eval_harness/test/test_eval_scorers.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport jsonfrom typing import Any-from ee.hogai.eval.sandboxed.error_tracking.scorers import (+from products.posthog_ai.evals.error_tracking.scorers import (ERROR_TRACKING_WRITE_TOOLS,QUERY_ISSUE_EVENTS_TOOL,QUERY_ISSUES_LIST_TOOL,diff --git a/products/error_tracking/backend/hogql_queries/test/test_eval_seeders.py b/products/posthog_ai/eval_harness/test/test_eval_seeders.pysimilarity index 96%rename from products/error_tracking/backend/hogql_queries/test/test_eval_seeders.pyrename to products/posthog_ai/eval_harness/test/test_eval_seeders.pyindex cdfbac8cba91..361613c623f1 100644--- a/products/error_tracking/backend/hogql_queries/test/test_eval_seeders.py+++ b/products/posthog_ai/eval_harness/test/test_eval_seeders.py@@ -11,8 +11,7 @@ from posthog.clickhouse.client import sync_executefrom products.cohorts.backend.models.cohort import get_or_create_internal_test_users_cohortfrom products.error_tracking.backend.hogql_queries.error_tracking_query_runner import ErrorTrackingQueryRunner--from ee.hogai.eval.sandboxed.error_tracking.seeders import _EVAL_DISTINCT_IDS, seed_error_tracking_issues+from products.posthog_ai.evals.error_tracking.seeders import _EVAL_DISTINCT_IDS, seed_error_tracking_issues@dataclass(frozen=True)diff --git a/ee/hogai/test/test_log_parser.py b/products/posthog_ai/eval_harness/test/test_log_parser.pysimilarity index 99%rename from ee/hogai/test/test_log_parser.pyrename to products/posthog_ai/eval_harness/test/test_log_parser.pyindex 0b93bb112fab..c3445caab0ba 100644--- a/ee/hogai/test/test_log_parser.py+++ b/products/posthog_ai/eval_harness/test/test_log_parser.py@@ -6,7 +6,7 @@ import jsonimport unittest-from ee.hogai.eval.sandboxed.log_parser import (+from products.posthog_ai.eval_harness.log_parser import (EXEC_TOOL_NAME,INFO_SYNTHETIC_PREFIX,SKILL_TOOL_NAME,diff --git a/products/posthog_ai/eval_harness/test/test_one_shot_runner.py b/products/posthog_ai/eval_harness/test/test_one_shot_runner.pynew file mode 100644index 000000000000..62abad424e7f--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_one_shot_runner.py@@ -0,0 +1,181 @@+from __future__ import annotations++import asyncio+from pathlib import Path+from typing import Any, ClassVar++import pytest++from products.posthog_ai.eval_harness.config import BaseEvalCase+from products.posthog_ai.eval_harness.engines.registry import resolve_engine+from products.posthog_ai.eval_harness.engines.types import (+ EnvVarSpec,+ EvalSummary,+ ExperimentResult,+ ExperimentSpec,+ NullCaseHooks,+)+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.one_shot import _OneShotEvalRun+++class _StubReporter:+ def __init__(self) -> None:+ self.done: list[tuple[str, str]] = []+ self.started: list[tuple[str, int]] = []+ self.summaries: list[tuple[str, Any, int]] = []++ async def case_done(self, experiment_name: str, case_name: str, duration_seconds: float, status: str) -> None:+ self.done.append((case_name, status))++ async def experiment_started(self, experiment_name: str, planned_cases: int, log_dir: Path) -> None:+ self.started.append((experiment_name, planned_cases))++ async def record_summary(self, experiment_name: str, summary: Any, error_count: int) -> None:+ self.summaries.append((experiment_name, summary, error_count))+++class _StubEngine:+ name: ClassVar[str] = "stub"+ supports_public_experiments: ClassVar[bool] = False++ def __init__(self, result: ExperimentResult) -> None:+ self.result = result+ self.calls: list[ExperimentSpec] = []++ @classmethod+ def required_env(cls) -> tuple[EnvVarSpec, ...]:+ return ()++ async def run_experiment(self, spec: ExperimentSpec) -> ExperimentResult:+ self.calls.append(spec)+ return self.result+++def _build_ctx(timeout_seconds: int = 30, one_shot_slots: int = 2, case_filter: str | None = None) -> EvalContext:+ return EvalContext(+ provider="docker",+ provider_strategy=None,+ agent_model="claude-test",+ agent_runtime="claude",+ reasoning_effort=None,+ case_filter=case_filter,+ demo_data=None,+ posthog_client=None,+ sandbox_slots=None,+ team_setup_slots=asyncio.Semaphore(1),+ one_shot_slots=asyncio.Semaphore(one_shot_slots),+ reporter=_StubReporter(), # type: ignore[arg-type]+ engine=resolve_engine(),+ per_case_timeout_seconds=timeout_seconds,+ trials=1,+ )+++def _build_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ctx: EvalContext, task_fn: Any) -> _OneShotEvalRun:+ monkeypatch.setattr("products.posthog_ai.eval_harness.base.build_case_dir", lambda *_: tmp_path)+ return _OneShotEvalRun(+ experiment_name="one-shot-test",+ cases=[BaseEvalCase(name="c1", prompt="the prompt"), BaseEvalCase(name="c2", prompt="other")],+ scorers=[],+ ctx=ctx,+ is_public=False,+ no_send_logs=True,+ task_fn=task_fn,+ )+++def test_execute_case_backfills_prompt_and_writes_logs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ async def task(case: BaseEvalCase, ctx: EvalContext) -> dict[str, Any]:+ return {"answer": 42, "last_message": "done"}++ ctx = _build_ctx()+ run = _build_run(tmp_path, monkeypatch, ctx, task)+ output = asyncio.run(run._execute_case({"name": "c1", "prompt": "the prompt"}, hooks=NullCaseHooks()))++ assert output["answer"] == 42+ assert output["prompt"] == "the prompt"+ assert (tmp_path / "c1.summary.txt").exists()+++def test_task_scores_timeout_as_output_not_error(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ async def task(case: BaseEvalCase, ctx: EvalContext) -> dict[str, Any]:+ await asyncio.sleep(30)+ return {}++ ctx = _build_ctx(timeout_seconds=1)+ run = _build_run(tmp_path, monkeypatch, ctx, task)+ output = asyncio.run(run._task({"name": "c1", "prompt": "the prompt"}, hooks=NullCaseHooks()))++ assert output == {"timeout": True, "error": "case timeout after 1s"}+ assert ctx.reporter.done == [("c1", "timeout")] # type: ignore[attr-defined]+++def test_task_reraises_infra_errors(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ async def task(case: BaseEvalCase, ctx: EvalContext) -> dict[str, Any]:+ raise ValueError("boom")++ ctx = _build_ctx()+ run = _build_run(tmp_path, monkeypatch, ctx, task)+ with pytest.raises(ValueError):+ asyncio.run(run._task({"name": "c1", "prompt": "the prompt"}, hooks=NullCaseHooks()))+ assert ctx.reporter.done == [("c1", "error")] # type: ignore[attr-defined]+++def test_one_shot_slots_bound_concurrency(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ active = 0+ max_active = 0++ async def task(case: BaseEvalCase, ctx: EvalContext) -> dict[str, Any]:+ nonlocal active, max_active+ active += 1+ max_active = max(max_active, active)+ await asyncio.sleep(0.01)+ active -= 1+ return {}++ ctx = _build_ctx(one_shot_slots=1)+ run = _build_run(tmp_path, monkeypatch, ctx, task)++ async def run_both() -> None:+ await asyncio.gather(+ run._execute_case({"name": "c1", "prompt": "the prompt"}, hooks=NullCaseHooks()),+ run._execute_case({"name": "c2", "prompt": "other"}, hooks=NullCaseHooks()),+ )++ asyncio.run(run_both())+ assert max_active == 1+++def test_case_filter_narrows_eval_cases(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ async def task(case: BaseEvalCase, ctx: EvalContext) -> dict[str, Any]:+ return {}++ run = _build_run(tmp_path, monkeypatch, _build_ctx(case_filter="c2"), task)+ assert [case.input["name"] for case in run._build_eval_cases()] == ["c2"]+++def test_run_routes_through_the_engine(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ async def task(case: BaseEvalCase, ctx: EvalContext) -> dict[str, Any]:+ raise AssertionError("the engine is stubbed, so the task must not run")++ canned = ExperimentResult(+ summary=EvalSummary(engine_name="stub", experiment_name="one-shot-test", scores={}),+ results=[],+ )+ engine = _StubEngine(canned)+ ctx = _build_ctx()+ run = _build_run(tmp_path, monkeypatch, ctx, task)+ run.engine = engine++ returned = asyncio.run(run.run())++ assert returned is canned+ assert len(engine.calls) == 1+ call = engine.calls[0]+ assert call.project_name == "one-shot-test"+ assert [case.input["name"] for case in call.cases] == ["c1", "c2"]+ assert call.metadata == {"agent_model": "claude-test"}+ reporter = ctx.reporter+ assert reporter.started == [("one-shot-test", 2)] # type: ignore[attr-defined]+ assert reporter.summaries == [("one-shot-test", canned.summary, 0)] # type: ignore[attr-defined]diff --git a/ee/hogai/eval/test_sandboxed_experiment_scorers.py b/products/posthog_ai/eval_harness/test/test_sandboxed_experiment_scorers.pysimilarity index 93%rename from ee/hogai/eval/test_sandboxed_experiment_scorers.pyrename to products/posthog_ai/eval_harness/test/test_sandboxed_experiment_scorers.pyindex d2ede71ee4ed..093193e27708 100644--- a/ee/hogai/eval/test_sandboxed_experiment_scorers.py+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_experiment_scorers.py@@ -1,12 +1,8 @@"""Unit tests for the grading logic the metric-schema-discovery eval uses.Exercises ``FirstUpdateMetricShape`` and the metric-shape validators from-``sandboxed/experiments/scorers.py`` directly, lightweight as it's given-hand-built metric dicts and synthetic ACP log lines, no sandboxed stack.--Lives one level above ``sandboxed/`` on purpose: a test under that package-inherits its ``conftest.py``, whose autouse fixtures boot the full eval harness-(Temporal, MCP, gateway, Django). Up here it stays a fast unit test.+``products/posthog_ai/evals/experiments/scorers.py`` directly, lightweight as it's+given hand-built metric dicts and synthetic ACP log lines, no sandboxed stack."""from __future__ import annotations@@ -15,9 +11,8 @@ import jsonimport pytest-from braintrust import Score--from ee.hogai.eval.sandboxed.experiments.scorers import (+from products.posthog_ai.eval_harness.scorers.contract import Score+from products.posthog_ai.evals.experiments.scorers import (FirstUpdateMetricShape,validate_ratio_revenue_metric,validate_retention_metric,diff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness.pynew file mode 100644index 000000000000..4e94244513ed--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py@@ -0,0 +1,256 @@+from __future__ import annotations++import os+import sys+import asyncio+import subprocess+from pathlib import Path+from types import SimpleNamespace++import pytest+from unittest.mock import AsyncMock, MagicMock, patch++import requests+from parameterized import parameterized++from products.posthog_ai.eval_harness import runner+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.cli import parse_args+from products.posthog_ai.eval_harness.harness.live_server import EvalLiveServer+from products.posthog_ai.eval_harness.harness.providers import ModalProviderStrategy, SandboxProviderStrategy+++class _FakeWorkflowHandle:+ def __init__(self, *, complete_on_signal: bool, complete_on_cancel: bool = False) -> None:+ self.complete_on_signal = complete_on_signal+ self.complete_on_cancel = complete_on_cancel+ self.signal_received = asyncio.Event()+ self.terminal = asyncio.Event()+ self.signals: list[list[str | None]] = []+ self.cancelled = False++ async def signal(self, _signal: object, *, args: list[str | None]) -> None:+ self.signals.append(args)+ self.signal_received.set()+ if self.complete_on_signal:+ self.terminal.set()++ async def result(self) -> None:+ await self.terminal.wait()++ async def cancel(self) -> None:+ self.cancelled = True+ if self.complete_on_cancel:+ self.terminal.set()+++class _Provider(SandboxProviderStrategy):+ name = "docker"+ default_max_sandboxes = 1++ def __init__(self) -> None:+ super().__init__()+ self.cleaned_task_ids: list[str] = []++ def preflight(self) -> None:+ return None++ def settings_overrides(self) -> dict[str, object]:+ return {}++ def cleanup_case(self, task_id: str) -> None:+ self.cleaned_task_ids.append(task_id)+++class _TaskRun:+ id = "run-id"++ def get_workflow_id(self, task_id: str, run_id: str) -> str:+ return f"{task_id}-{run_id}"+++def _patch_runner_boundaries(monkeypatch: pytest.MonkeyPatch, handle: _FakeWorkflowHandle, poll: AsyncMock) -> None:+ task = SimpleNamespace(id="task-id")+ task_run = _TaskRun()+ client = SimpleNamespace(get_workflow_handle=lambda _workflow_id: handle)+ monkeypatch.setattr(runner, "create_task_and_trigger", AsyncMock(return_value=(task, task_run)))+ monkeypatch.setattr(runner, "async_connect", AsyncMock(return_value=client))+ monkeypatch.setattr(runner, "poll_for_turn", poll)+++def test_eval_live_server_routes_event_ingest_through_asgi() -> None:+ with (+ patch("posthog.asgi._ensure_post_fork_init"),+ patch("posthog.utils.initialize_self_capture_api_token", new=AsyncMock()),+ ):+ server = EvalLiveServer(port=0)+ try:+ response = requests.post(+ f"{server.url}/api/projects/25/tasks/task-id/runs/run-id/event_stream/",+ timeout=5,+ )+ finally:+ server.stop()++ assert response.status_code == 401+ assert response.json() == {"error": "Missing authorization bearer token"}+++def test_setup_django_disables_self_capture_before_settings_load() -> None:+ result = subprocess.run(+ [+ sys.executable,+ "-c",+ (+ "from products.posthog_ai.eval_harness.harness.django_env import setup_django\n"+ "setup_django()\n"+ "from django.conf import settings\n"+ "assert settings.SELF_CAPTURE is False\n"+ ),+ ],+ cwd=Path(__file__).resolve().parents[4],+ env={**os.environ, "SELF_CAPTURE": "1"},+ capture_output=True,+ text=True,+ timeout=30,+ )++ assert result.returncode == 0, result.stderr++[email protected]([(0,), (-1,)])+def test_parse_args_rejects_non_positive_case_timeout(case_timeout: int) -> None:+ with pytest.raises(SystemExit) as error:+ parse_args(["--case-timeout", str(case_timeout)])++ assert error.value.code == 2+++ [+ ("local", {}, 1),+ ("coder", {"CODER": "true"}, 4),+ ("ci", {"CI": ""}, 4),+ ]+)+def test_parse_args_resolves_team_setup_concurrency(+ _environment_name: str, environment: dict[str, str], expected_concurrency: int+) -> None:+ with patch.dict(os.environ, environment, clear=True):+ options = parse_args([])++ assert options.team_setup_concurrency == expected_concurrency+++async def test_success_waits_for_workflow_cleanup_before_returning(monkeypatch: pytest.MonkeyPatch) -> None:+ handle = _FakeWorkflowHandle(complete_on_signal=False)+ provider = _Provider()+ _patch_runner_boundaries(+ monkeypatch,+ handle,+ AsyncMock(return_value=("done", '{"notification": {}}', None, None)),+ )++ case_task = asyncio.create_task(+ runner.run_eval_case(+ SandboxedEvalCase(name="case", prompt="prompt"),+ MagicMock(),+ provider=provider,+ )+ )+ await asyncio.wait_for(handle.signal_received.wait(), timeout=1)++ assert not case_task.done()+ handle.terminal.set()+ result = await asyncio.wait_for(case_task, timeout=1)++ assert result.artifacts.exit_code == 0+ assert handle.signals == [["completed", None]]+ assert provider.cleaned_task_ids == ["task-id"]+++async def test_poll_failure_is_preserved_after_workflow_cleanup(monkeypatch: pytest.MonkeyPatch) -> None:+ handle = _FakeWorkflowHandle(complete_on_signal=True)+ provider = _Provider()+ _patch_runner_boundaries(monkeypatch, handle, AsyncMock(side_effect=RuntimeError("poll failed")))++ with pytest.raises(RuntimeError, match="poll failed"):+ await runner.run_eval_case(+ SandboxedEvalCase(name="case", prompt="prompt"),+ MagicMock(),+ provider=provider,+ )++ assert handle.signals[0][0] == "failed"+ assert provider.cleaned_task_ids == ["task-id"]+++async def test_cancellation_finishes_workflow_before_propagating(monkeypatch: pytest.MonkeyPatch) -> None:+ poll_started = asyncio.Event()+ never_finishes = asyncio.Event()++ async def poll_for_turn(*_args: object, **_kwargs: object) -> None:+ poll_started.set()+ await never_finishes.wait()++ handle = _FakeWorkflowHandle(complete_on_signal=True)+ provider = _Provider()+ _patch_runner_boundaries(monkeypatch, handle, AsyncMock(side_effect=poll_for_turn))+ case_task = asyncio.create_task(+ runner.run_eval_case(+ SandboxedEvalCase(name="case", prompt="prompt"),+ MagicMock(),+ provider=provider,+ )+ )+ await asyncio.wait_for(poll_started.wait(), timeout=1)++ case_task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await case_task++ assert handle.signals[0][0] == "failed"+ assert provider.cleaned_task_ids == ["task-id"]+++async def test_unconfirmed_success_is_an_infrastructure_error(monkeypatch: pytest.MonkeyPatch) -> None:+ handle = _FakeWorkflowHandle(complete_on_signal=False)+ provider = _Provider()+ _patch_runner_boundaries(+ monkeypatch,+ handle,+ AsyncMock(return_value=("done", '{"notification": {}}', None, None)),+ )+ monkeypatch.setattr(runner, "WORKFLOW_COMPLETION_GRACE_SECONDS", 0.01)+ monkeypatch.setattr(runner, "WORKFLOW_CANCELLATION_GRACE_SECONDS", 0.01)++ with pytest.raises(runner.WorkflowCleanupError, match="cleanup could not be confirmed"):+ await runner.run_eval_case(+ SandboxedEvalCase(name="case", prompt="prompt"),+ MagicMock(),+ provider=provider,+ )++ assert handle.cancelled+ assert provider.cleaned_task_ids == ["task-id"]+++def test_modal_cleanup_case_terminates_only_the_task_sandboxes(monkeypatch: pytest.MonkeyPatch) -> None:+ sandbox = SimpleNamespace(object_id="sandbox-id", terminate=MagicMock())+ sandbox_list = MagicMock(return_value=[sandbox])+ modal = SimpleNamespace(+ App=SimpleNamespace(lookup=MagicMock(return_value=SimpleNamespace(app_id="app-id"))),+ Sandbox=SimpleNamespace(list=sandbox_list),+ )+ monkeypatch.setitem(sys.modules, "modal", modal)+ provider = ModalProviderStrategy()+ provider._sandbox_app_name = "eval-app"++ provider.cleanup_case("task-id")++ sandbox_list.assert_called_once_with(app_id="app-id", tags={"task_id": "task-id"})+ sandbox.terminate.assert_called_once_with()diff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.pynew file mode 100644index 000000000000..5261821a0d5a--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py@@ -0,0 +1,141 @@+from __future__ import annotations++import sys+from pathlib import Path++import pytest+from unittest.mock import MagicMock++from products.posthog_ai.eval_harness import base+from products.posthog_ai.eval_harness.engines.types import AggregateScore, EvalSummary+from products.posthog_ai.eval_harness.harness.reporting import ProgressReporter, SuiteRunResult+from products.posthog_ai.eval_harness.harness.transcript import RunTranscript+from products.posthog_ai.eval_harness.scorers import ExitCodeZero+++def test_run_transcript_captures_both_streams_and_prints_its_path_last(+ tmp_path: Path, capsys: pytest.CaptureFixture[str]+) -> None:+ transcript = RunTranscript.create(tmp_path)++ with transcript.capture():+ sys.stderr.write("stderr line\n")+ sys.stdout.write("stdout line")+ transcript.finish()++ captured = capsys.readouterr()+ transcript_lines = transcript.path.read_text(encoding="utf-8").splitlines()++ assert captured.out.splitlines() == [+ "stdout line",+ "Full run transcript (stdout and stderr):",+ str(transcript.path),+ ]+ assert captured.err.splitlines() == ["stderr line"]+ assert transcript_lines == [+ "stderr line",+ "stdout line",+ "Full run transcript (stdout and stderr):",+ str(transcript.path),+ ]+ assert (tmp_path / "latest.log").resolve() == transcript.path+++async def test_reporter_output_is_labeled_and_reserves_pass_for_the_run(+ tmp_path: Path, capsys: pytest.CaptureFixture[str]+) -> None:+ reporter = ProgressReporter(total_suites=1)+ reporter.print_run_header(+ provider="docker",+ agent_runtime="codex",+ agent_model="gpt-5",+ max_sandboxes=4,+ trials=1,+ )+ await reporter.suite_started("cli_mcp/eval_workflow::eval_verify_event_before_query")+ await reporter.experiment_started("sandboxed-cli-mcp-verify-event-cli", 1, tmp_path)+ await reporter.case_done(+ "sandboxed-cli-mcp-verify-event-cli",+ "trends_pageview_verifies_first",+ duration_seconds=396.4,+ )+ await reporter.record_summary(+ "sandboxed-cli-mcp-verify-event-cli",+ EvalSummary(+ engine_name="Braintrust",+ experiment_name="sandboxed-cli-mcp-verify-event-cli",+ scores={+ "exit_code_zero": AggregateScore("exit_code_zero", 1.0),+ "called_target_tool": AggregateScore("called_target_tool", 0.0),+ },+ experiment_url="https://experiments.example/e",+ ),+ )+ await reporter.record_posthog_evaluations_url(+ "sandboxed-cli-mcp-verify-event-cli", "bd8b7f0d-7cc3-4ea3-a3a6-53be0d9e6eb4"+ )+ await reporter.suite_finished(+ SuiteRunResult(+ suite_id="cli_mcp/eval_workflow::eval_verify_event_before_query",+ status="passed",+ duration_seconds=404.6,+ )+ )+ reporter.print_final_summary(+ [+ SuiteRunResult(+ suite_id="cli_mcp/eval_workflow::eval_verify_event_before_query",+ status="passed",+ duration_seconds=404.6,+ )+ ],+ exit_code=0,+ fail_under=0.4,+ duration_seconds=404.6,+ )++ output = capsys.readouterr().out++ assert "CASE DONE" in output+ assert "EXPERIMENT DONE" in output+ assert "SUITE DONE" in output+ assert "Status: PASS" in output+ assert "Score gate: met (50.0% >= 40.0%)" in output+ assert "Suites: 1 done, 0 crashed" in output+ assert "Cases: 1 done, 0 timed out, 0 errors" in output+ assert "Experiment: sandboxed-cli-mcp-verify-event-cli" in output+ assert "exit_code_zero: 100.0%" in output+ assert "called_target_tool: 0.0%" in output+ assert "PostHog: https://us.posthog.com/" in output+ assert "Braintrust: https://experiments.example/e" in output+ assert f"Agent logs: {tmp_path}" in output+ assert output.count("PASS") == 1+++def test_sandboxed_eval_run_adds_exit_code_scorer(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ monkeypatch.setattr(base, "build_case_dir", MagicMock(return_value=tmp_path))+ ctx = MagicMock(posthog_client=None, case_filter=None)+ custom_scorer = MagicMock()++ run = base._SandboxedEvalRun(+ experiment_name="experiment",+ cases=[],+ scorers=[custom_scorer],+ ctx=ctx,+ is_public=False,+ no_send_logs=True,+ )++ assert isinstance(run.active_scorers[0], ExitCodeZero)+ assert run.active_scorers[1] is custom_scorer++ with pytest.raises(ValueError, match="ExitCodeZero is added by the sandboxed eval harness"):+ base._SandboxedEvalRun(+ experiment_name="experiment",+ cases=[],+ scorers=[ExitCodeZero()],+ ctx=ctx,+ is_public=False,+ no_send_logs=True,+ )diff --git a/products/posthog_ai/eval_harness/test/test_scorer_contract.py b/products/posthog_ai/eval_harness/test/test_scorer_contract.pynew file mode 100644index 000000000000..3e3308ca815b--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_scorer_contract.py@@ -0,0 +1,26 @@+from __future__ import annotations++from typing import Any++from braintrust.score import is_score++from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer+++def test_contract_scorer_is_dispatchable_by_braintrust() -> None:+ class _S(Scorer):+ def _name(self) -> str:+ return "s"++ def _run_eval_sync(self, output: Any, expected: Any = None, **kwargs: Any) -> Score:+ return Score(name="s", score=1.0)++ # braintrust's EvalAsync only runs a scorer if it exposes eval_async; the+ # later pure-class flip must keep that surface, or every scorer stops firing.+ assert hasattr(_S(), "eval_async")+++def test_contract_score_passes_braintrust_is_score() -> None:+ # is_score is braintrust's duck check (name/score/metadata/as_dict); a Score+ # that fails it is silently dropped from every experiment's results.+ assert is_score(Score(name="s", score=1.0))diff --git a/products/posthog_ai/eval_harness/test/test_suite_requirements.py b/products/posthog_ai/eval_harness/test/test_suite_requirements.pynew file mode 100644index 000000000000..eed3b1ea5348--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_suite_requirements.py@@ -0,0 +1,143 @@+from __future__ import annotations++import pytest++from products.posthog_ai.eval_harness.engines.registry import resolve_engine+from products.posthog_ai.eval_harness.harness.env_preflight import validate_eval_env+from products.posthog_ai.eval_harness.harness.providers import PreflightError+from products.posthog_ai.eval_harness.harness.requirements import INFRA_BY_KIND, Infra, SuiteKind, expand, infra_union++ALL_ENV_VARS = (+ "BRAINTRUST_API_KEY",+ "SANDBOX_JWT_PRIVATE_KEY",+ "LLM_GATEWAY_ANTHROPIC_API_KEY",+ "LLM_GATEWAY_OPENAI_API_KEY",+)+++ "requested, expected",+ [+ pytest.param({Infra.DATABASE}, {Infra.DATABASE}, id="database_implies_nothing"),+ pytest.param(+ {Infra.MCP_SERVER},+ {Infra.MCP_SERVER, Infra.LIVE_SERVER, Infra.DATABASE},+ id="mcp_server_pulls_live_server_and_database",+ ),+ pytest.param(+ {Infra.DEMO_DATA},+ {Infra.DEMO_DATA, Infra.DATABASE, Infra.PERSONHOG},+ id="demo_data_pulls_database_and_personhog",+ ),+ pytest.param({Infra.SANDBOX}, set(Infra), id="sandbox_pulls_everything"),+ ],+)+def test_expand_closes_over_implications(requested: set[Infra], expected: set[Infra]) -> None:+ assert expand(requested) == frozenset(expected)+++ "kinds, expected",+ [+ pytest.param([SuiteKind.SANDBOXED], set(Infra), id="sandboxed_needs_everything"),+ pytest.param(+ [SuiteKind.ONE_SHOT],+ {Infra.DATABASE, Infra.PERSONHOG, Infra.DEMO_DATA},+ id="one_shot_skips_servers_and_sandbox",+ ),+ pytest.param([SuiteKind.SANDBOXED, SuiteKind.ONE_SHOT], set(Infra), id="mixed_run_is_the_union"),+ pytest.param([], set(), id="no_kinds_no_infra"),+ ],+)+def test_infra_union(kinds: list[SuiteKind], expected: set[Infra]) -> None:+ assert infra_union(kinds) == frozenset(expected)+++def test_every_kind_declares_a_closed_infra_set() -> None:+ for kind, infra in INFRA_BY_KIND.items():+ assert expand(infra) == infra, f"{kind} declares an infra set that is not implication-closed"+++ "kinds, agent_runtime, env, expect_missing",+ [+ pytest.param(+ {SuiteKind.ONE_SHOT},+ "claude",+ {"BRAINTRUST_API_KEY": "x", "LLM_GATEWAY_ANTHROPIC_API_KEY": "x"},+ (),+ id="one_shot_run_needs_no_sandbox_credentials",+ ),+ pytest.param(+ {SuiteKind.ONE_SHOT},+ "claude",+ {"BRAINTRUST_API_KEY": "x"},+ ("LLM_GATEWAY_ANTHROPIC_API_KEY",),+ id="one_shot_run_still_needs_the_generation_key",+ ),+ pytest.param(+ {SuiteKind.SANDBOXED},+ "claude",+ {"BRAINTRUST_API_KEY": "x", "LLM_GATEWAY_ANTHROPIC_API_KEY": "x"},+ ("SANDBOX_JWT_PRIVATE_KEY",),+ id="sandboxed_run_needs_the_jwt_key",+ ),+ pytest.param(+ {SuiteKind.SANDBOXED, SuiteKind.ONE_SHOT},+ "claude",+ {"BRAINTRUST_API_KEY": "x"},+ ("SANDBOX_JWT_PRIVATE_KEY", "LLM_GATEWAY_ANTHROPIC_API_KEY"),+ id="mixed_run_reports_each_missing_variable_once",+ ),+ pytest.param(+ {SuiteKind.ONE_SHOT},+ "codex",+ {"BRAINTRUST_API_KEY": "x", "LLM_GATEWAY_ANTHROPIC_API_KEY": "x"},+ (),+ id="codex_requirement_only_applies_to_sandboxed_runs",+ ),+ pytest.param(+ {SuiteKind.SANDBOXED},+ "codex",+ {"BRAINTRUST_API_KEY": "x", "LLM_GATEWAY_ANTHROPIC_API_KEY": "x", "SANDBOX_JWT_PRIVATE_KEY": "x"},+ ("LLM_GATEWAY_OPENAI_API_KEY",),+ id="sandboxed_codex_run_needs_the_openai_key",+ ),+ ],+)+def test_validate_eval_env_by_kind(+ monkeypatch: pytest.MonkeyPatch,+ kinds: set[SuiteKind],+ agent_runtime: str,+ env: dict[str, str],+ expect_missing: tuple[str, ...],+) -> None:+ for name in ALL_ENV_VARS:+ monkeypatch.delenv(name, raising=False)+ for name, value in env.items():+ monkeypatch.setenv(name, value)++ if not expect_missing:+ validate_eval_env(agent_runtime, kinds=kinds)+ return++ with pytest.raises(PreflightError) as exc_info:+ validate_eval_env(agent_runtime, kinds=kinds)+ message = str(exc_info.value)+ for name in expect_missing:+ assert message.count(name) == 1+ for name in set(ALL_ENV_VARS) - set(expect_missing) - set(env):+ assert name not in message+++def test_validate_eval_env_reports_missing_engine_env(monkeypatch: pytest.MonkeyPatch) -> None:+ for name in ALL_ENV_VARS:+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setenv("LLM_GATEWAY_ANTHROPIC_API_KEY", "x")++ with pytest.raises(PreflightError) as exc_info:+ validate_eval_env("claude", kinds={SuiteKind.ONE_SHOT}, engine_env=resolve_engine().required_env())++ # The Braintrust engine's requirement is reported with the same line the core+ # env model used to emit, so a missing key reads identically to before.+ assert " - BRAINTRUST_API_KEY: records experiments and scores to Braintrust" in str(exc_info.value)diff --git a/ee/hogai/test/eval/test_warehouse_scorers.py b/products/posthog_ai/eval_harness/test/test_warehouse_scorers.pysimilarity index 82%rename from ee/hogai/test/eval/test_warehouse_scorers.pyrename to products/posthog_ai/eval_harness/test/test_warehouse_scorers.pyindex f04b3472b7aa..51bd9aa14b87 100644--- a/ee/hogai/test/eval/test_warehouse_scorers.py+++ b/products/posthog_ai/eval_harness/test/test_warehouse_scorers.py@@ -2,17 +2,15 @@Builds minimal ACP session logs (the same shape ``LogParser`` consumes inproduction) plus synthetic ``seed`` dicts, then asserts each scorer's verdict —-no sandboxed stack. Lives above ``sandboxed/`` so it stays a fast unit test-instead of booting the eval harness via that package's conftest.+no sandboxed stack — it stays a fast unit test instead of booting the eval harness."""from __future__ import annotationsimport json-from braintrust import Score--from ee.hogai.eval.sandboxed.data_warehouse.scorers import (+from products.posthog_ai.eval_harness.scorers.contract import Score+from products.posthog_ai.evals.data_warehouse.scorers import (AgenticSearchUsed,AnswerQueryRanWhenExpected,InformationSchemaBeforeAnswer,@@ -132,19 +130,19 @@ def _make_output(def test_information_schema_queried_passes_when_info_schema_hit():out = _make_output(sql_calls=[("SELECT table_name FROM system.information_schema.tables", "rows")])- score = InformationSchemaQueried()._evaluate(out, {"information_schema_queried": {}})+ score = InformationSchemaQueried()._run_eval_sync(out, {"information_schema_queried": {}})assert score.score == 1.0def test_information_schema_queried_fails_without_info_schema():out = _make_output(sql_calls=[("SELECT 1 FROM stripe_charges", "rows")])- score = InformationSchemaQueried()._evaluate(out, {"information_schema_queried": {}})+ score = InformationSchemaQueried()._run_eval_sync(out, {"information_schema_queried": {}})assert score.score == 0.0def test_information_schema_queried_skips_when_not_requested():out = _make_output(sql_calls=[("SELECT 1 FROM system.information_schema.tables", "rows")])- score = InformationSchemaQueried()._evaluate(out, {})+ score = InformationSchemaQueried()._run_eval_sync(out, {})assert score.score is None@@ -158,7 +156,7 @@ def test_before_answer_passes_when_discovery_precedes_answer():("SELECT * FROM pg_orders LIMIT 5", "rows"),])- score = InformationSchemaBeforeAnswer()._evaluate(out, {"information_schema_before_answer": {}})+ score = InformationSchemaBeforeAnswer()._run_eval_sync(out, {"information_schema_before_answer": {}})assert score.score == 1.0@@ -169,13 +167,13 @@ def test_before_answer_fails_when_answer_precedes_discovery():("SELECT column_name FROM system.information_schema.columns", "rows"),])- score = InformationSchemaBeforeAnswer()._evaluate(out, {"information_schema_before_answer": {}})+ score = InformationSchemaBeforeAnswer()._run_eval_sync(out, {"information_schema_before_answer": {}})assert score.score == 0.0def test_before_answer_skips_when_no_answer_query():out = _make_output(sql_calls=[("SELECT table_name FROM system.information_schema.tables", "rows")])- score = InformationSchemaBeforeAnswer()._evaluate(out, {"information_schema_before_answer": {}})+ score = InformationSchemaBeforeAnswer()._run_eval_sync(out, {"information_schema_before_answer": {}})assert score.score is None@@ -186,13 +184,13 @@ def test_agentic_search_passes_for_filtered_query():out = _make_output(sql_calls=[("SELECT table_name FROM system.information_schema.tables WHERE table_name = 'pg_orders'", "rows")])- score = AgenticSearchUsed()._evaluate(out, {"agentic_search_used": {}})+ score = AgenticSearchUsed()._run_eval_sync(out, {"agentic_search_used": {}})assert score.score == 1.0def test_agentic_search_fails_for_unfiltered_dump():out = _make_output(sql_calls=[("SELECT table_name FROM system.information_schema.tables", "rows")])- score = AgenticSearchUsed()._evaluate(out, {"agentic_search_used": {}})+ score = AgenticSearchUsed()._run_eval_sync(out, {"agentic_search_used": {}})assert score.score == 0.0@@ -204,8 +202,8 @@ def test_agentic_search_require_pattern_needs_like():sql_calls=[("SELECT table_name FROM system.information_schema.tables WHERE description ILIKE '%mrr%'", "rows")])spec = {"agentic_search_used": {"require_pattern": True}}- assert AgenticSearchUsed()._evaluate(where_eq, spec).score == 0.0- assert AgenticSearchUsed()._evaluate(where_like, spec).score == 1.0+ assert AgenticSearchUsed()._run_eval_sync(where_eq, spec).score == 0.0+ assert AgenticSearchUsed()._run_eval_sync(where_like, spec).score == 1.0# -- NeedleTableIdentified ----------------------------------------------------@@ -213,7 +211,7 @@ def test_agentic_search_require_pattern_needs_like():def test_needle_table_identified_via_final_message():out = _make_output(final_text="The canonical MRR table is pg_ext_4471.")- score = NeedleTableIdentified()._evaluate(out, {"needle_table_identified": {"table": "pg_ext_4471"}})+ score = NeedleTableIdentified()._run_eval_sync(out, {"needle_table_identified": {"table": "pg_ext_4471"}})assert score.score == 1.0@@ -221,13 +219,13 @@ def test_needle_table_identified_resolves_seed_key():out = _make_output(final_text="It's hubspot_sync_meta.", seed={"column_type_needle": {"table": "hubspot_sync_meta"}})- score = NeedleTableIdentified()._evaluate(out, {"needle_table_identified": {"seed_key": "column_type_needle"}})+ score = NeedleTableIdentified()._run_eval_sync(out, {"needle_table_identified": {"seed_key": "column_type_needle"}})assert score.score == 1.0def test_needle_table_identified_fails_when_absent():out = _make_output(final_text="I could not find it.")- score = NeedleTableIdentified()._evaluate(out, {"needle_table_identified": {"table": "pg_ext_4471"}})+ score = NeedleTableIdentified()._run_eval_sync(out, {"needle_table_identified": {"table": "pg_ext_4471"}})assert score.score == 0.0@@ -240,13 +238,13 @@ def test_needle_value_retrieved_from_sql_result():final_text="The secret_code is HEDGE-7731.",seed={"retrieval_needle": {"queryable": True, "answer": "HEDGE-7731"}},)- score = NeedleValueRetrieved()._evaluate(out, {"needle_value_retrieved": {}})+ score = NeedleValueRetrieved()._run_eval_sync(out, {"needle_value_retrieved": {}})assert score.score == 1.0def test_needle_value_retrieved_skips_when_not_queryable():out = _make_output(seed={"retrieval_needle": {"queryable": False, "answer": "HEDGE-7731"}})- score = NeedleValueRetrieved()._evaluate(out, {"needle_value_retrieved": {}})+ score = NeedleValueRetrieved()._run_eval_sync(out, {"needle_value_retrieved": {}})assert score.score is None@@ -256,7 +254,7 @@ def test_needle_value_retrieved_honors_value_override():final_text="Largest is 24990.",seed={"retrieval_needle": {"queryable": True, "answer": "HEDGE-7731"}},)- score = NeedleValueRetrieved()._evaluate(out, {"needle_value_retrieved": {"value": "24990"}})+ score = NeedleValueRetrieved()._run_eval_sync(out, {"needle_value_retrieved": {"value": "24990"}})assert score.score == 1.0@@ -271,7 +269,7 @@ def test_relationship_discovery_passes_with_relationships_query_and_named_pair()final_text="pg_orders_2023 joins salesforce_acct_xref on account_ref.",seed={"relationship_needle": {"source": "pg_orders_2023", "target": "salesforce_acct_xref"}},)- score = RelationshipDiscovery()._evaluate(out, {"relationship_discovery": {}})+ score = RelationshipDiscovery()._run_eval_sync(out, {"relationship_discovery": {}})assert score.score == 1.0@@ -280,7 +278,7 @@ def test_relationship_discovery_fails_without_discovery():final_text="They are probably related somehow.",seed={"relationship_needle": {"source": "pg_orders_2023", "target": "salesforce_acct_xref"}},)- score = RelationshipDiscovery()._evaluate(out, {"relationship_discovery": {}})+ score = RelationshipDiscovery()._run_eval_sync(out, {"relationship_discovery": {}})assert score.score == 0.0@@ -297,19 +295,19 @@ def test_stale_table_avoided_passes_when_current_recommended_and_stale_flagged()),seed=_RELEVANCY_SEED,)- score = StaleTableAvoided()._evaluate(out, {"stale_table_avoided": {}})+ score = StaleTableAvoided()._run_eval_sync(out, {"stale_table_avoided": {}})assert score.score == 1.0def test_stale_table_avoided_passes_when_only_current_named():out = _make_output(final_text="You should use dim_accounts_snapshot for current reporting.", seed=_RELEVANCY_SEED)- score = StaleTableAvoided()._evaluate(out, {"stale_table_avoided": {}})+ score = StaleTableAvoided()._run_eval_sync(out, {"stale_table_avoided": {}})assert score.score == 1.0def test_stale_table_avoided_fails_when_stale_recommended():out = _make_output(final_text="Use dim_accounts_snapshot_2023 for your accounts reporting.", seed=_RELEVANCY_SEED)- score = StaleTableAvoided()._evaluate(out, {"stale_table_avoided": {}})+ score = StaleTableAvoided()._run_eval_sync(out, {"stale_table_avoided": {}})assert score.score == 0.0@@ -319,13 +317,13 @@ def test_stale_table_avoided_fails_when_stale_named_without_deprecation_cue():final_text="There's dim_accounts_snapshot and dim_accounts_snapshot_2023; either has accounts.",seed=_RELEVANCY_SEED,)- score = StaleTableAvoided()._evaluate(out, {"stale_table_avoided": {}})+ score = StaleTableAvoided()._run_eval_sync(out, {"stale_table_avoided": {}})assert score.score == 0.0def test_stale_table_avoided_skips_when_not_requested():out = _make_output(final_text="anything", seed=_RELEVANCY_SEED)- score = StaleTableAvoided()._evaluate(out, {})+ score = StaleTableAvoided()._run_eval_sync(out, {})assert score.score is None@@ -351,7 +349,7 @@ def test_join_path_traversed_passes_with_relationships_query_and_all_tables_name),seed=_CHAIN_SEED,)- score = JoinPathTraversed()._evaluate(out, {"join_path_traversed": {}})+ score = JoinPathTraversed()._run_eval_sync(out, {"join_path_traversed": {}})assert score.score == 1.0assert score.metadata["keys_named"] == ["account_ref", "owner_id"]@@ -364,7 +362,7 @@ def test_join_path_traversed_fails_when_only_first_hop_found():final_text="pg_orders_2023 joins salesforce_acct_xref on account_ref.",seed=_CHAIN_SEED,)- score = JoinPathTraversed()._evaluate(out, {"join_path_traversed": {}})+ score = JoinPathTraversed()._run_eval_sync(out, {"join_path_traversed": {}})assert score.score == 0.0@@ -373,13 +371,13 @@ def test_join_path_traversed_fails_without_relationships_query():final_text="pg_orders_2023, salesforce_acct_xref and salesforce_acct_owners are probably related.",seed=_CHAIN_SEED,)- score = JoinPathTraversed()._evaluate(out, {"join_path_traversed": {}})+ score = JoinPathTraversed()._run_eval_sync(out, {"join_path_traversed": {}})assert score.score == 0.0def test_join_path_traversed_skips_when_not_requested():out = _make_output(final_text="anything", seed=_CHAIN_SEED)- score = JoinPathTraversed()._evaluate(out, {})+ score = JoinPathTraversed()._run_eval_sync(out, {})assert score.score is None@@ -388,19 +386,19 @@ def test_join_path_traversed_skips_when_not_requested():def test_answer_query_ran_true_for_real_answer():out = _make_output(sql_calls=[("SELECT * FROM pg_orders LIMIT 5", "rows")])- score = AnswerQueryRanWhenExpected()._evaluate(out, {"answer_query_ran": {}})+ score = AnswerQueryRanWhenExpected()._run_eval_sync(out, {"answer_query_ran": {}})assert score.score == 1.0def test_answer_query_ran_false_for_discovery_only():out = _make_output(sql_calls=[("SELECT table_name FROM system.information_schema.tables", "rows")])- score = AnswerQueryRanWhenExpected()._evaluate(out, {"answer_query_ran": {}})+ score = AnswerQueryRanWhenExpected()._run_eval_sync(out, {"answer_query_ran": {}})assert score.score == 0.0def test_answer_query_ran_skips_when_not_requested():out = _make_output(sql_calls=[("SELECT * FROM pg_orders", "rows")])- score = AnswerQueryRanWhenExpected()._evaluate(out, {})+ score = AnswerQueryRanWhenExpected()._run_eval_sync(out, {})assert score.score is Nonediff --git a/ee/hogai/test/eval/test_warehouse_seeder.py b/products/posthog_ai/eval_harness/test/test_warehouse_seeder.pysimilarity index 96%rename from ee/hogai/test/eval/test_warehouse_seeder.pyrename to products/posthog_ai/eval_harness/test/test_warehouse_seeder.pyindex 5f1277df3ddc..698667476c3c 100644--- a/ee/hogai/test/eval/test_warehouse_seeder.py+++ b/products/posthog_ai/eval_harness/test/test_warehouse_seeder.py@@ -15,11 +15,11 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom posthog.hogql.query import execute_hogql_query-from ee.hogai.eval.sandboxed.data_warehouse.seeder import seed_warehouse_schema+from products.posthog_ai.evals.data_warehouse.seeder import seed_warehouse_schemaif TYPE_CHECKING:from products.tasks.backend.facade.agents import CustomPromptSandboxContext-from ee.hogai.eval.sandboxed.data_warehouse.synthesizer import (+from products.posthog_ai.evals.data_warehouse.synthesizer import (DESC_NEEDLE_PHRASE,DESC_NEEDLE_TABLE,REL_NEEDLE_SOURCE,diff --git a/ee/hogai/test/eval/test_warehouse_synthesizer.py b/products/posthog_ai/eval_harness/test/test_warehouse_synthesizer.pysimilarity index 98%rename from ee/hogai/test/eval/test_warehouse_synthesizer.pyrename to products/posthog_ai/eval_harness/test/test_warehouse_synthesizer.pyindex 399c42a0fa17..65332cfb7c3b 100644--- a/ee/hogai/test/eval/test_warehouse_synthesizer.py+++ b/products/posthog_ai/eval_harness/test/test_warehouse_synthesizer.py@@ -4,7 +4,7 @@ from __future__ import annotationsfrom dataclasses import astuple-from ee.hogai.eval.sandboxed.data_warehouse.synthesizer import (+from products.posthog_ai.evals.data_warehouse.synthesizer import (CHAIN_NEEDLE_HOP3,DESC_NEEDLE_PHRASE,DESC_NEEDLE_TABLE,diff --git a/ee/hogai/eval/sandboxed/trace_events.py b/products/posthog_ai/eval_harness/trace_events.pysimilarity index 99%rename from ee/hogai/eval/sandboxed/trace_events.pyrename to products/posthog_ai/eval_harness/trace_events.pyindex e267205b596f..d3165ec5d6e5 100644--- a/ee/hogai/eval/sandboxed/trace_events.py+++ b/products/posthog_ai/eval_harness/trace_events.py@@ -16,6 +16,7 @@ from typing import Anyfrom posthoganalytics import Posthogfrom .acp_log import GenerationDescriptor, ParsedLog, SpanDescriptor+from .engines.types import CaseResultlogger = logging.getLogger(__name__)@@ -276,7 +277,7 @@ def emit_evaluation_events(client: Posthog,experiment_id: str,experiment_name: str,- eval_results: list,+ eval_results: list[CaseResult],scorer_traces: dict[tuple[str, str], str] | None = None,) -> None:"""Emit ``$ai_evaluation`` events for each scorer result in each eval case.diff --git a/ee/hogai/eval/sandboxed/AGENTS.md b/products/posthog_ai/evals/AGENTS.mdsimilarity index 91%rename from ee/hogai/eval/sandboxed/AGENTS.mdrename to products/posthog_ai/evals/AGENTS.mdindex 6bac4d960645..d75061bcdfd4 100644--- a/ee/hogai/eval/sandboxed/AGENTS.md+++ b/products/posthog_ai/evals/AGENTS.md@@ -7,11 +7,14 @@ Source of truth (read these if anything below looks stale):- Simulation logic: `products/demo/backend/logic/products/hedgebox/models.py` (per-person session state machine + events)- Project setup (actions/cohorts/dashboards/insights/flags/experiments): `products/demo/backend/logic/products/hedgebox/matrix.py` → `HedgeboxMatrix.set_project_up`- Taxonomy constants (event/flag/group names): `products/demo/backend/logic/products/hedgebox/taxonomy.py`-- How evals seed it: `ee/hogai/eval/data_setup.py`+- How evals seed it: `products/posthog_ai/eval_harness/data_setup.py`++Running these evals, writing a new suite, and the provider prerequisites are covered in [`../eval_harness/README.md`](../eval_harness/README.md).+The harness internals live in [`../eval_harness/harness/README.md`](../eval_harness/harness/README.md).## How the data is seeded for evals-`ee/hogai/eval/data_setup.py` builds the matrix with fixed parameters — **do not assume the library defaults** (180 days / `DEMO_MATRIX_N_CLUSTERS`):+`products/posthog_ai/eval_harness/data_setup.py` builds the matrix with fixed parameters — **do not assume the library defaults** (180 days / `DEMO_MATRIX_N_CLUSTERS`):```pythonHedgeboxMatrix(@@ -24,7 +27,7 @@ HedgeboxMatrix(```- The seed is fixed, so the dataset is **byte-for-byte reproducible** — assertions on relative shapes (e.g. "signups trend over -8w") are stable, but **do not hard-code absolute counts**; they can drift if the simulation code changes.-- **Sandboxed evals** (`SandboxedDemoData` in `conftest.py`): a master Hedgebox team is generated once via `ensure_master_demo_team`, then each eval case gets its own org/team via `copy_demo_data_to_new_team` (ClickHouse `INSERT ... SELECT` copy + `set_project_up` re-run + taxonomy re-inference). Each case is isolated; the seeded user is **"Karen Smith"**.+- **Sandboxed evals** (`SandboxedDemoData` in `harness/demo_data.py`): a master Hedgebox team is generated once via `ensure_master_demo_team`, then each eval case gets its own org/team via `copy_demo_data_to_new_team` (ClickHouse `INSERT ... SELECT` copy + `set_project_up` re-run + taxonomy re-inference). When object storage is enabled, the master must also have all five warehouse CSVs and metadata rows. Case teams share those immutable master CSVs but receive isolated credentials, table metadata, annotations, and the persons join. Each case is isolated; the seeded user is **"Karen Smith"**.- **CI evals** reuse one org/team via `create_demo_org_team_user`.- Events span both past (`days_past`) and future (`days_future` — `paid_bill` events are scheduled forward). When choosing date ranges in expected queries, prefer relative ranges like `-30d`, `-8w`, `-6m`.- Most insights/dashboards are built with `filterTestAccounts=True`. The team has `test_account_filters` configured, and a "Signed-up users" cohort exists.diff --git a/products/posthog_ai/evals/CLAUDE.md b/products/posthog_ai/evals/CLAUDE.mdnew file mode 120000index 000000000000..47dc3e3d863c--- /dev/null+++ b/products/posthog_ai/evals/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/products/posthog_ai/evals/__init__.py b/products/posthog_ai/evals/__init__.pynew file mode 100644index 000000000000..82e396ba8f9c--- /dev/null+++ b/products/posthog_ai/evals/__init__.py@@ -0,0 +1,5 @@+"""Built-in eval suites for the PostHog AI eval harness (`products.posthog_ai.eval_harness`).++One directory per domain; suites are discovered by convention (`eval_*` coroutines in `eval_*.py`).+Product-owned suites live in `products/<product>/evals/` and follow the same conventions.+"""diff --git a/ee/hogai/eval/sandboxed/__init__.py b/products/posthog_ai/evals/ci/__init__.pysimilarity index 100%rename from ee/hogai/eval/sandboxed/__init__.pyrename to products/posthog_ai/evals/ci/__init__.pydiff --git a/ee/hogai/eval/sandboxed/ci/eval_basic.py b/products/posthog_ai/evals/ci/eval_basic.pysimilarity index 75%rename from ee/hogai/eval/sandboxed/ci/eval_basic.pyrename to products/posthog_ai/evals/ci/eval_basic.pyindex ce9a58efc968..fad97bc84cb5 100644--- a/ee/hogai/eval/sandboxed/ci/eval_basic.py+++ b/products/posthog_ai/evals/ci/eval_basic.py@@ -1,7 +1,7 @@"""Placeholder eval cases for the sandboxed coding agent.To run:- pytest ee/hogai/eval/sandboxed/ci/eval_basic.py+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_basic"Example eval case pattern:@@ -11,13 +11,13 @@ Example eval case pattern:from __future__ import annotations-from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.cli_mcp.scorers import CalledTargetTool, SurfacedGeneratedAppUrl-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.evals.cli_mcp.scorers import CalledTargetTool, SurfacedGeneratedAppUrl-async def eval_bugfix(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_bugfix(ctx: EvalContext) -> None:cases = [SandboxedEvalCase(name="fix_divide_bug",@@ -36,18 +36,14 @@ async def eval_bugfix(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mod]await SandboxedPublicEval(- experiment_name=f"sandboxed-bugfix-{mcp_mode}",+ experiment_name="sandboxed-bugfix-cli",cases=cases,- scorers=[- ExitCodeZero(),- ],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ scorers=[],+ ctx=ctx,)-async def eval_app_link_generation(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_app_link_generation(ctx: EvalContext) -> None:"""Entity links must be resolved via ``generate-app-url``, not hand-built.Reproduces the reported failure where the MCP confidently returned 404 links — a person@@ -89,10 +85,8 @@ async def eval_app_link_generation(sandboxed_demo_data, pytestconfig, posthog_cl]await SandboxedPublicEval(- experiment_name=f"sandboxed-app-link-generation-{mcp_mode}",+ experiment_name="sandboxed-app-link-generation-cli",cases=cases,- scorers=[ExitCodeZero(), CalledTargetTool(), SurfacedGeneratedAppUrl()],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ scorers=[CalledTargetTool(), SurfacedGeneratedAppUrl()],+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/ci/__init__.py b/products/posthog_ai/evals/cli_mcp/__init__.pysimilarity index 100%rename from ee/hogai/eval/sandboxed/ci/__init__.pyrename to products/posthog_ai/evals/cli_mcp/__init__.pydiff --git a/ee/hogai/eval/sandboxed/cli_mcp/eval_render_ui.py b/products/posthog_ai/evals/cli_mcp/eval_render_ui.pysimilarity index 74%rename from ee/hogai/eval/sandboxed/cli_mcp/eval_render_ui.pyrename to products/posthog_ai/evals/cli_mcp/eval_render_ui.pyindex ab4b2ff541b1..62b083ced9cf 100644--- a/ee/hogai/eval/sandboxed/cli_mcp/eval_render_ui.py+++ b/products/posthog_ai/evals/cli_mcp/eval_render_ui.py@@ -33,22 +33,25 @@ Not exercised here (sandbox/scope limits, not prompt gaps):side effects against the shared demo project.* **Surveys** — the hedgebox demo seeds none.-``render-ui`` is registered only in ``cli`` mode and for MCP Apps hosts (the-sandboxed eval client presents as one), so the only remaining gate here is the-mode: all cases skip under ``--mcp-mode=tools`` (see ``conftest.py:_apply_mcp_mode``).+``render-ui`` is registered only for MCP Apps hosts, which the sandboxed eval+client presents as, and the MCP server now serves the ``cli`` surface it lives+on by default.To run a single eval:- pytest ee/hogai/eval/sandboxed/cli_mcp/eval_render_ui.py::eval_renders_entity_ui --mcp-mode=cli+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_renders_entity_ui""""from __future__ import annotations-import pytest--from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.cli_mcp.scorers import CalledTargetTool, DidNotRenderUi, ExecBeforeRender, RenderedEntityUi-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.evals.cli_mcp.scorers import (+ CalledTargetTool,+ DidNotRenderUi,+ ExecBeforeRender,+ RenderedEntityUi,+)# Renderable experiment tools (detail + results). The agent may render the detail# view (``experiment-get``) or a results view for a status/results question. Two@@ -57,10 +60,8 @@ from ee.hogai.eval.sandboxed.scorers import ExitCodeZeroEXPERIMENT_RENDER_TOOLS = ["experiment-results-get", "experiment-get", "experiment-timeseries-results"]-async def eval_renders_entity_ui(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_renders_entity_ui(ctx: EvalContext) -> None:"""Entity-centric answers must render the entity (in addition to summarizing it)."""- if mcp_mode == "tools":- pytest.skip("render-ui only exists in cli mode")cases: list[SandboxedEvalCase] = [# Status / health → render the experiment ("File engagement boost" runs in the demo).@@ -93,16 +94,14 @@ async def eval_renders_entity_ui(sandboxed_demo_data, pytestconfig, posthog_clie]await SandboxedPublicEval(- experiment_name=f"sandboxed-cli-mcp-renders-entity-ui-{mcp_mode}",+ experiment_name="sandboxed-cli-mcp-renders-entity-ui-cli",cases=cases,- scorers=[ExitCodeZero(), RenderedEntityUi(), ExecBeforeRender()],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ scorers=[RenderedEntityUi(), ExecBeforeRender()],+ ctx=ctx,)-async def eval_no_render_for_query_results(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_no_render_for_query_results(ctx: EvalContext) -> None:"""Insight/trends answers must NOT be routed through ``render-ui``.``query-trends`` (and the other insight ``query-*`` tools) carry the custom@@ -110,8 +109,6 @@ async def eval_no_render_for_query_results(sandboxed_demo_data, pytestconfig, po``render-ui``'s enum. The agent should answer with the query tool and nevercall ``render-ui``."""- if mcp_mode == "tools":- pytest.skip("render-ui only exists in cli mode")cases: list[SandboxedEvalCase] = [SandboxedEvalCase(@@ -125,10 +122,8 @@ async def eval_no_render_for_query_results(sandboxed_demo_data, pytestconfig, po]await SandboxedPublicEval(- experiment_name=f"sandboxed-cli-mcp-no-render-for-query-{mcp_mode}",+ experiment_name="sandboxed-cli-mcp-no-render-for-query-cli",cases=cases,- scorers=[ExitCodeZero(), CalledTargetTool(), DidNotRenderUi()],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ scorers=[CalledTargetTool(), DidNotRenderUi()],+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.py b/products/posthog_ai/evals/cli_mcp/eval_workflow.pysimilarity index 68%rename from ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.pyrename to products/posthog_ai/evals/cli_mcp/eval_workflow.pyindex 51676a3b2141..8f02a6ff7a34 100644--- a/ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.py+++ b/products/posthog_ai/evals/cli_mcp/eval_workflow.py@@ -17,19 +17,19 @@ in ``services/mcp/src/templates/cli-proxy-tool.md`` and* ``eval_verify_event_before_query`` — for ``query-*`` calls, the agentverifies the event/property exists via ``read-data-schema`` first.-All five skip when ``--mcp-mode=tools`` because the ``exec`` tool is only-registered in ``cli`` mode (see ``conftest.py:_apply_mcp_mode``).+Every case exercises the ``posthog:exec`` tool, which the MCP server now+registers by default.To run a single eval:- pytest ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.py::eval_typo_recovery --mcp-mode=cli+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_typo_recovery""""from __future__ import annotations-import pytest--from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.cli_mcp.scorers import (+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.evals.cli_mcp.scorers import (CalledTargetTool,DrilledIntoSchema,InfoBeforeCall,@@ -39,14 +39,10 @@ from ee.hogai.eval.sandboxed.cli_mcp.scorers import (UsedJsonOutputFormat,VerifiedEventBeforeQuery,)-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero-async def eval_typo_recovery(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_typo_recovery(ctx: EvalContext) -> None:"""Prompted with a deprecated or typo'd tool name, the agent must recover."""- if mcp_mode == "tools":- pytest.skip("posthog:exec only exists in cli mode")cases: list[SandboxedEvalCase] = [SandboxedEvalCase(@@ -72,19 +68,15 @@ async def eval_typo_recovery(sandboxed_demo_data, pytestconfig, posthog_client,]await SandboxedPublicEval(- experiment_name=f"sandboxed-cli-mcp-typo-recovery-{mcp_mode}",+ experiment_name="sandboxed-cli-mcp-typo-recovery-cli",cases=cases,- scorers=[ExitCodeZero(), RecoveredToCorrectTool()],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ scorers=[RecoveredToCorrectTool()],+ ctx=ctx,)-async def eval_schema_drilldown(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_schema_drilldown(ctx: EvalContext) -> None:"""Trends question with breakdown — the agent must drill into nested schema fields."""- if mcp_mode == "tools":- pytest.skip("posthog:exec only exists in cli mode")cases: list[SandboxedEvalCase] = [SandboxedEvalCase(@@ -109,19 +101,15 @@ async def eval_schema_drilldown(sandboxed_demo_data, pytestconfig, posthog_clien]await SandboxedPublicEval(- experiment_name=f"sandboxed-cli-mcp-schema-drilldown-{mcp_mode}",+ experiment_name="sandboxed-cli-mcp-schema-drilldown-cli",cases=cases,- scorers=[ExitCodeZero(), CalledTargetTool(), DrilledIntoSchema()],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ scorers=[CalledTargetTool(), DrilledIntoSchema()],+ ctx=ctx,)-async def eval_search_first(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_search_first(ctx: EvalContext) -> None:"""Open-ended discovery — the agent must prefer ``search`` over bare ``tools``."""- if mcp_mode == "tools":- pytest.skip("posthog:exec only exists in cli mode")cases: list[SandboxedEvalCase] = [SandboxedEvalCase(@@ -135,19 +123,15 @@ async def eval_search_first(sandboxed_demo_data, pytestconfig, posthog_client, m]await SandboxedPublicEval(- experiment_name=f"sandboxed-cli-mcp-search-first-{mcp_mode}",+ experiment_name="sandboxed-cli-mcp-search-first-cli",cases=cases,- scorers=[ExitCodeZero(), CalledTargetTool(), PreferredSearchOverTools()],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ scorers=[CalledTargetTool(), PreferredSearchOverTools()],+ ctx=ctx,)-async def eval_info_before_call(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_info_before_call(ctx: EvalContext) -> None:"""Every successful ``call <tool>`` must be preceded by ``info <tool>``."""- if mcp_mode == "tools":- pytest.skip("posthog:exec only exists in cli mode")cases: list[SandboxedEvalCase] = [SandboxedEvalCase(@@ -169,16 +153,14 @@ async def eval_info_before_call(sandboxed_demo_data, pytestconfig, posthog_clien]await SandboxedPublicEval(- experiment_name=f"sandboxed-cli-mcp-info-before-call-{mcp_mode}",+ experiment_name="sandboxed-cli-mcp-info-before-call-cli",cases=cases,- scorers=[ExitCodeZero(), CalledTargetTool(), InfoBeforeCall()],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ scorers=[CalledTargetTool(), InfoBeforeCall()],+ ctx=ctx,)-async def eval_json_for_post_processing(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_json_for_post_processing(ctx: EvalContext) -> None:"""Post-processing scenario — agent must request raw JSON and run Python on it.The default ``output_format: "optimized"`` is token-efficient but lossy@@ -187,8 +169,6 @@ async def eval_json_for_post_processing(sandboxed_demo_data, pytestconfig, posthit should opt into ``output_format: "json"`` so the result is a parseableJSON document, then drive Python via ``Bash`` to compute the answer."""- if mcp_mode == "tools":- pytest.skip("posthog:exec only exists in cli mode")cases: list[SandboxedEvalCase] = [SandboxedEvalCase(@@ -209,24 +189,19 @@ async def eval_json_for_post_processing(sandboxed_demo_data, pytestconfig, posth]await SandboxedPublicEval(- experiment_name=f"sandboxed-cli-mcp-json-postprocess-{mcp_mode}",+ experiment_name="sandboxed-cli-mcp-json-postprocess-cli",cases=cases,scorers=[- ExitCodeZero(),CalledTargetTool(),UsedJsonOutputFormat(),RanPythonPostProcessing(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)-async def eval_verify_event_before_query(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_verify_event_before_query(ctx: EvalContext) -> None:"""``query-*`` calls must be preceded by a successful ``read-data-schema`` call."""- if mcp_mode == "tools":- pytest.skip("posthog:exec only exists in cli mode")cases: list[SandboxedEvalCase] = [SandboxedEvalCase(@@ -240,10 +215,8 @@ async def eval_verify_event_before_query(sandboxed_demo_data, pytestconfig, post]await SandboxedPublicEval(- experiment_name=f"sandboxed-cli-mcp-verify-event-{mcp_mode}",+ experiment_name="sandboxed-cli-mcp-verify-event-cli",cases=cases,- scorers=[ExitCodeZero(), CalledTargetTool(), VerifiedEventBeforeQuery()],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ scorers=[CalledTargetTool(), VerifiedEventBeforeQuery()],+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/cli_mcp/scorers.py b/products/posthog_ai/evals/cli_mcp/scorers.pysimilarity index 88%rename from ee/hogai/eval/sandboxed/cli_mcp/scorers.pyrename to products/posthog_ai/evals/cli_mcp/scorers.pyindex 1ca8bd308666..cc1899cc8873 100644--- a/ee/hogai/eval/sandboxed/cli_mcp/scorers.py+++ b/products/posthog_ai/evals/cli_mcp/scorers.py@@ -32,10 +32,8 @@ from __future__ import annotationsimport re-from braintrust import Score-from braintrust_core.score import Scorer--from ee.hogai.eval.sandboxed.log_parser import EXEC_TOOL_NAME, INFO_SYNTHETIC_PREFIX, LogParser, ToolCall+from products.posthog_ai.eval_harness.log_parser import EXEC_TOOL_NAME, INFO_SYNTHETIC_PREFIX, LogParser, ToolCall+from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer__all__ = ["CalledTargetTool",@@ -108,7 +106,7 @@ def _build_parser(output: dict | None) -> LogParser | None:raw_log = output.get("raw_log")if not raw_log:return None- return LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")+ return LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")class CalledTargetTool(Scorer):@@ -117,13 +115,7 @@ class CalledTargetTool(Scorer):def _name(self) -> str:return "called_target_tool"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})target = _read_tool(expected, self._name())@@ -137,7 +129,7 @@ class CalledTargetTool(Scorer):if not raw_log:return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})- parser = LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")+ parser = LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")for call in parser.get_tool_calls(target):if not call.is_error:return Score(name=self._name(), score=1.0, metadata={"tool": target, "call_id": call.call_id})@@ -184,13 +176,7 @@ class RecoveredToCorrectTool(Scorer):def _name(self) -> str:return "recovered_to_correct_tool"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:spec = _read_spec(expected, self._name())if not spec:return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} spec on case"})@@ -250,13 +236,7 @@ class DrilledIntoSchema(Scorer):def _name(self) -> str:return "drilled_into_schema"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:spec = _read_spec(expected, self._name())if not spec:return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} spec on case"})@@ -322,13 +302,7 @@ class RetrievedSchemaPath(Scorer):def _name(self) -> str:return "retrieved_schema_path"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:spec = _read_spec(expected, self._name())if not spec:return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} spec on case"})@@ -404,13 +378,7 @@ class PreferredSearchOverTools(Scorer):def _name(self) -> str:return "preferred_search_over_tools"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if _read_spec(expected, self._name()) is None:return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} key on case"})@@ -473,13 +441,7 @@ class InfoBeforeCall(Scorer):def _name(self) -> str:return "info_before_call"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:target = _read_tool(expected, self._name())if not target:return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()}.tool on case"})@@ -542,13 +504,7 @@ class VerifiedEventBeforeQuery(Scorer):def _name(self) -> str:return "verified_event_before_query"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:spec = _read_spec(expected, self._name())if not spec:return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} spec on case"})@@ -618,13 +574,7 @@ class UsedJsonOutputFormat(Scorer):def _name(self) -> str:return "used_json_output_format"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:target = _read_tool(expected, self._name())if not target:return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()}.tool on case"})@@ -682,13 +632,7 @@ class SurfacedGeneratedAppUrl(Scorer):def _name(self) -> str:return "surfaced_generated_app_url"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if _read_spec(expected, self._name()) is None:return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} key on case"})@@ -742,13 +686,7 @@ class RanPythonPostProcessing(Scorer):def _name(self) -> str:return "ran_python_post_processing"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if _read_spec(expected, self._name()) is None:return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} key on case"})@@ -810,13 +748,7 @@ class RenderedEntityUi(Scorer):def _name(self) -> str:return "rendered_entity_ui"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:spec = _read_spec(expected, self._name())if spec is None:return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} spec on case"})@@ -875,19 +807,13 @@ class ExecBeforeRender(Scorer):def _name(self) -> str:return "exec_before_render"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-@staticmethoddef _is_exec_action(call: ToolCall) -> bool:if call.is_error:return Falsereturn call.is_exec_unwrapped or call.name == EXEC_TOOL_NAME or call.name.startswith(INFO_SYNTHETIC_PREFIX)- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if _read_spec(expected, self._name()) is None:return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} key on case"})@@ -935,13 +861,7 @@ class DidNotRenderUi(Scorer):def _name(self) -> str:return "did_not_render_ui"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:spec = _read_spec(expected, self._name())if spec is None:return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} key on case"})diff --git a/ee/hogai/eval/sandboxed/cohorts/eval_cohort_from_query.py b/products/posthog_ai/evals/cohorts/eval_cohort_from_query.pysimilarity index 78%rename from ee/hogai/eval/sandboxed/cohorts/eval_cohort_from_query.pyrename to products/posthog_ai/evals/cohorts/eval_cohort_from_query.pyindex 8c95c5f4827a..a525ff96d299 100644--- a/ee/hogai/eval/sandboxed/cohorts/eval_cohort_from_query.py+++ b/products/posthog_ai/evals/cohorts/eval_cohort_from_query.py@@ -13,22 +13,23 @@ resulting cohort size.To run::- pytest ee/hogai/eval/sandboxed/cohorts/eval_cohort_from_query.py+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_cohort_from_query""""from __future__ import annotations-from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.cohorts.scorers import (+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import NoToolCall+from products.posthog_ai.evals.cohorts.scorers import (COHORTS_ADD_PERSONS_TOOL,CohortFromQueryUsed,QueryTargetsActorColumn,)-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, NoToolCall-async def eval_cohort_from_query(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_cohort_from_query(ctx: EvalContext) -> None:cases = [SandboxedEvalCase(name="cohort_from_sql_query",@@ -57,15 +58,12 @@ async def eval_cohort_from_query(sandboxed_demo_data, pytestconfig, posthog_clie]await SandboxedPublicEval(- experiment_name=f"sandboxed-cohorts-from-query-{mcp_mode}",+ experiment_name="sandboxed-cohorts-from-query-cli",cases=cases,scorers=[- ExitCodeZero(),CohortFromQueryUsed(),QueryTargetsActorColumn(),NoToolCall(forbidden={COHORTS_ADD_PERSONS_TOOL}, name="no_uuid_batching"),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/cohorts/scorers.py b/products/posthog_ai/evals/cohorts/scorers.pysimilarity index 86%rename from ee/hogai/eval/sandboxed/cohorts/scorers.pyrename to products/posthog_ai/evals/cohorts/scorers.pyindex ef4e8b972c27..e534b099fc17 100644--- a/ee/hogai/eval/sandboxed/cohorts/scorers.py+++ b/products/posthog_ai/evals/cohorts/scorers.py@@ -8,9 +8,8 @@ itself and looping ``cohorts-add-persons-to-static-cohort-partial-update`` overthe UUIDs. The query path runs server-side with no row limit; the batching pathcaps out and is the failure mode this eval guards against.-All scorers build a single ``LogParser`` from ``output["raw_log"]`` so they work-identically in ``mcp_mode=tools`` (per-tool MCP) and ``mcp_mode=cli`` (single-``exec`` wrapper) — the parser handles exec-unwrapping.+All scorers build a single ``LogParser`` from ``output["raw_log"]``; the parser+handles unwrapping the ``posthog:exec`` cli wrapper the MCP server serves."""from __future__ import annotations@@ -18,10 +17,8 @@ from __future__ import annotationsimport refrom typing import Any-from braintrust import Score-from braintrust_core.score import Scorer--from ee.hogai.eval.sandboxed.log_parser import LogParser+from products.posthog_ai.eval_harness.log_parser import LogParser+from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer__all__ = ["COHORTS_ADD_PERSONS_TOOL",@@ -46,7 +43,7 @@ def _parser_for(output: dict[str, Any] | None) -> LogParser | None:raw_log = output.get("raw_log")if not raw_log:return None- return LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")+ return LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")def _is_truthy(value: Any) -> bool:@@ -93,13 +90,7 @@ class CohortFromQueryUsed(Scorer):def _name(self) -> str:return self._label- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _evaluate(self, output: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:parser = _parser_for(output)if parser is None:return Score(name=self._name(), score=None, metadata={"reason": "No raw log to parse"})@@ -132,13 +123,7 @@ class QueryTargetsActorColumn(Scorer):def _name(self) -> str:return self._label- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _evaluate(self, output: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:parser = _parser_for(output)calls = _query_population_calls(parser)if not calls:diff --git a/ee/hogai/eval/sandboxed/cli_mcp/__init__.py b/products/posthog_ai/evals/data_warehouse/__init__.pysimilarity index 100%rename from ee/hogai/eval/sandboxed/cli_mcp/__init__.pyrename to products/posthog_ai/evals/data_warehouse/__init__.pydiff --git a/ee/hogai/eval/sandboxed/data_warehouse/eval_information_schema.py b/products/posthog_ai/evals/data_warehouse/eval_information_schema.pysimilarity index 86%rename from ee/hogai/eval/sandboxed/data_warehouse/eval_information_schema.pyrename to products/posthog_ai/evals/data_warehouse/eval_information_schema.pyindex c2dff7451e45..262a3f131759 100644--- a/ee/hogai/eval/sandboxed/data_warehouse/eval_information_schema.py+++ b/products/posthog_ai/evals/data_warehouse/eval_information_schema.py@@ -24,14 +24,15 @@ Prompts read like real user questions and never mention ``information_schema``.To run a single eval::- pytest ee/hogai/eval/sandboxed/data_warehouse/eval_information_schema.py::eval_dw_discovery+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_dw_discovery""""from __future__ import annotations-from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.data_warehouse.scorers import (+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.evals.data_warehouse.scorers import (AgenticSearchUsed,AnswerQueryRanWhenExpected,InformationSchemaBeforeAnswer,@@ -43,8 +44,8 @@ from ee.hogai.eval.sandboxed.data_warehouse.scorers import (StaleTableAvoided,WarehouseAnswerCorrectness,)-from ee.hogai.eval.sandboxed.data_warehouse.seeder import seed_warehouse_schema-from ee.hogai.eval.sandboxed.data_warehouse.synthesizer import (+from products.posthog_ai.evals.data_warehouse.seeder import seed_warehouse_schema+from products.posthog_ai.evals.data_warehouse.synthesizer import (CHAIN_NEEDLE_HOP3,DESC_NEEDLE_TABLE,REL_NEEDLE_SOURCE,@@ -57,10 +58,9 @@ from ee.hogai.eval.sandboxed.data_warehouse.synthesizer import (TYPE_NEEDLE_TABLE,VIEW_NEEDLE_NAME,)-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero-async def eval_dw_discovery(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_dw_discovery(ctx: EvalContext) -> None:"""Find the right table/model among hundreds via agentic search over the catalog."""cases: list[SandboxedEvalCase] = [# Discover a specific data model (view) among hundreds of tables. Graded on@@ -109,21 +109,18 @@ async def eval_dw_discovery(sandboxed_demo_data, pytestconfig, posthog_client, m]await SandboxedPublicEval(- experiment_name=f"sandboxed-warehouse-discovery-{mcp_mode}",+ experiment_name="sandboxed-warehouse-discovery-cli",cases=cases,scorers=[- ExitCodeZero(),InformationSchemaQueried(),AgenticSearchUsed(),NeedleTableIdentified(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)-async def eval_dw_value_retrieval(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_dw_value_retrieval(ctx: EvalContext) -> None:"""Retrieve a lookup needle with a real SQL query, including duck-typed columns."""cases: list[SandboxedEvalCase] = [# Value lookup against the queryable needle: discover via information_schema,@@ -174,23 +171,20 @@ async def eval_dw_value_retrieval(sandboxed_demo_data, pytestconfig, posthog_cli]await SandboxedPublicEval(- experiment_name=f"sandboxed-warehouse-retrieval-{mcp_mode}",+ experiment_name="sandboxed-warehouse-retrieval-cli",cases=cases,scorers=[- ExitCodeZero(),InformationSchemaQueried(),InformationSchemaBeforeAnswer(),NeedleValueRetrieved(),AnswerQueryRanWhenExpected(name="answer_query_ran"),WarehouseAnswerCorrectness(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)-async def eval_dw_relationships(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_dw_relationships(ctx: EvalContext) -> None:"""Follow joins surfaced in information_schema.relationships, single- and multi-hop."""cases: list[SandboxedEvalCase] = [# Single-hop relationship traversal. Graded deterministically by@@ -233,22 +227,19 @@ async def eval_dw_relationships(sandboxed_demo_data, pytestconfig, posthog_clien]await SandboxedPublicEval(- experiment_name=f"sandboxed-warehouse-relationships-{mcp_mode}",+ experiment_name="sandboxed-warehouse-relationships-cli",cases=cases,scorers=[- ExitCodeZero(),InformationSchemaQueried(),RelationshipDiscovery(),JoinPathTraversed(),WarehouseAnswerCorrectness(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)-async def eval_dw_table_relevancy(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_dw_table_relevancy(ctx: EvalContext) -> None:"""Pick the live table over a near-identical frozen/superseded decoy."""cases: list[SandboxedEvalCase] = [# Two near-identical accounts dimensions, one live and one frozen/superseded.@@ -279,17 +270,14 @@ async def eval_dw_table_relevancy(sandboxed_demo_data, pytestconfig, posthog_cli]await SandboxedPublicEval(- experiment_name=f"sandboxed-warehouse-relevancy-{mcp_mode}",+ experiment_name="sandboxed-warehouse-relevancy-cli",cases=cases,scorers=[- ExitCodeZero(),InformationSchemaQueried(),AgenticSearchUsed(),NeedleTableIdentified(),StaleTableAvoided(),WarehouseAnswerCorrectness(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/data_warehouse/scorers.py b/products/posthog_ai/evals/data_warehouse/scorers.pysimilarity index 87%rename from ee/hogai/eval/sandboxed/data_warehouse/scorers.pyrename to products/posthog_ai/evals/data_warehouse/scorers.pyindex a832ab7ef6cc..11849a0f8d71 100644--- a/ee/hogai/eval/sandboxed/data_warehouse/scorers.py+++ b/products/posthog_ai/evals/data_warehouse/scorers.py@@ -16,18 +16,11 @@ from __future__ import annotationsfrom typing import Any-from braintrust import Score-from braintrust_core.score import Scorer--from ee.hogai.eval.sandboxed.log_parser import LogParser, ToolCall-from ee.hogai.eval.sandboxed.product_analytics.scorers import (- GRADED_ALIGNMENT_CHOICE_SCORES,- JUDGE_MODEL,- JudgedScorer,- parser_for,- user_prompt,-)-from ee.hogai.eval.sandboxed.sql.scorers import _truncate_result_for_judge, extract_last_execute_sql_call+from products.posthog_ai.eval_harness.log_parser import LogParser, ToolCall+from products.posthog_ai.eval_harness.scorers import GRADED_ALIGNMENT_CHOICE_SCORES, JUDGE_MODEL, JudgedScorer+from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer+from products.posthog_ai.evals.product_analytics.scorers import parser_for, user_prompt+from products.posthog_ai.evals.sql.scorers import _truncate_result_for_judge, extract_last_execute_sql_call__all__ = ["InformationSchemaQueried",@@ -83,13 +76,7 @@ class InformationSchemaQueried(Scorer):def _name(self) -> str:return "information_schema_queried"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})if not _requested(expected, self._name()):@@ -112,13 +99,7 @@ class InformationSchemaBeforeAnswer(Scorer):def _name(self) -> str:return "information_schema_before_answer"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})if not _requested(expected, self._name()):@@ -175,13 +156,7 @@ class AgenticSearchUsed(Scorer):def _name(self) -> str:return "agentic_search_used"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})if not _requested(expected, self._name()):@@ -225,12 +200,6 @@ class NeedleTableIdentified(Scorer):def _name(self) -> str:return "needle_table_identified"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-def _resolve_table(self, output: dict | None, expected: dict | None) -> str | None:spec = expected.get(self._name()) if isinstance(expected, dict) else Noneif not isinstance(spec, dict):@@ -244,7 +213,7 @@ class NeedleTableIdentified(Scorer):return entry["table"]return None- def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})if not _requested(expected, self._name()):@@ -279,13 +248,7 @@ class NeedleValueRetrieved(Scorer):def _name(self) -> str:return "needle_value_retrieved"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})if not _requested(expected, self._name()):@@ -330,13 +293,7 @@ class RelationshipDiscovery(Scorer):def _name(self) -> str:return "relationship_discovery"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})if not _requested(expected, self._name()):@@ -399,13 +356,7 @@ class StaleTableAvoided(Scorer):def _name(self) -> str:return "stale_table_avoided"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})if not _requested(expected, self._name()):@@ -448,13 +399,7 @@ class JoinPathTraversed(Scorer):def _name(self) -> str:return "join_path_traversed"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})if not _requested(expected, self._name()):@@ -506,13 +451,7 @@ class AnswerQueryRanWhenExpected(Scorer):def _name(self) -> str:return self._label- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})if not _requested(expected, self._name()):diff --git a/ee/hogai/eval/sandboxed/data_warehouse/seeder.py b/products/posthog_ai/evals/data_warehouse/seeder.pysimilarity index 99%rename from ee/hogai/eval/sandboxed/data_warehouse/seeder.pyrename to products/posthog_ai/evals/data_warehouse/seeder.pyindex fcefdded780f..0bcef0e7e7cf 100644--- a/ee/hogai/eval/sandboxed/data_warehouse/seeder.py+++ b/products/posthog_ai/evals/data_warehouse/seeder.py@@ -18,7 +18,7 @@ import csvimport loggingfrom typing import TYPE_CHECKING, Any-from ee.hogai.eval.sandboxed.data_warehouse.synthesizer import (+from products.posthog_ai.evals.data_warehouse.synthesizer import (CHAIN_NEEDLE_HOP3,CHAIN_NEEDLE_KEY,DESC_NEEDLE_PHRASE,diff --git a/ee/hogai/eval/sandboxed/data_warehouse/synthesizer.py b/products/posthog_ai/evals/data_warehouse/synthesizer.pysimilarity index 99%rename from ee/hogai/eval/sandboxed/data_warehouse/synthesizer.pyrename to products/posthog_ai/evals/data_warehouse/synthesizer.pyindex ce9856377924..150999c066b4 100644--- a/ee/hogai/eval/sandboxed/data_warehouse/synthesizer.py+++ b/products/posthog_ai/evals/data_warehouse/synthesizer.py@@ -33,7 +33,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Any, Literal-from ee.hogai.eval.sandboxed.seeders.common import DEFAULT_NAME_SEED, NameProviders, make_name_providers+from products.posthog_ai.eval_harness.seeders.common import DEFAULT_NAME_SEED, NameProviders, make_name_providers__all__ = ["HogqlType",diff --git a/ee/hogai/eval/sandboxed/error_tracking/eval_events_sampling.py b/products/posthog_ai/evals/error_tracking/eval_events_sampling.pysimilarity index 83%rename from ee/hogai/eval/sandboxed/error_tracking/eval_events_sampling.pyrename to products/posthog_ai/evals/error_tracking/eval_events_sampling.pyindex 22a895e7d1ad..e5f7fc38c973 100644--- a/ee/hogai/eval/sandboxed/error_tracking/eval_events_sampling.py+++ b/products/posthog_ai/evals/error_tracking/eval_events_sampling.py@@ -15,25 +15,24 @@ case's expected shape.To run::- pytest ee/hogai/eval/sandboxed/error_tracking/eval_events_sampling.py+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_events_sampling""""from __future__ import annotationsfrom typing import Any-import pytest--from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.error_tracking.scorers import (+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import NoToolCall+from products.posthog_ai.evals.error_tracking.scorers import (ERROR_TRACKING_WRITE_TOOLS,EventsArgsAlignment,EventsToolUsed,IssueIdMatchesTarget,)-from ee.hogai.eval.sandboxed.error_tracking.seeders import seed_error_tracking_issues-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, NoToolCall+from products.posthog_ai.evals.error_tracking.seeders import seed_error_tracking_issuesdef _events_case(@@ -54,8 +53,7 @@ def _events_case()-async def eval_events_sampling(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_events_sampling(ctx: EvalContext) -> None:cases = [# One example, modest verbosity — the prompt only asks for "an example",# so cranking limit > 3 or asking for raw is wasteful. Issue described@@ -108,16 +106,13 @@ async def eval_events_sampling(sandboxed_demo_data, pytestconfig, posthog_client]await SandboxedPublicEval(- experiment_name=f"sandboxed-error-tracking-events-sampling-{mcp_mode}",+ experiment_name="sandboxed-error-tracking-events-sampling-cli",cases=cases,scorers=[- ExitCodeZero(),NoToolCall(forbidden=ERROR_TRACKING_WRITE_TOOLS, name="no_error_tracking_write"),EventsToolUsed(),EventsArgsAlignment(),IssueIdMatchesTarget(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/error_tracking/eval_issue_drilldown.py b/products/posthog_ai/evals/error_tracking/eval_issue_drilldown.pysimilarity index 85%rename from ee/hogai/eval/sandboxed/error_tracking/eval_issue_drilldown.pyrename to products/posthog_ai/evals/error_tracking/eval_issue_drilldown.pyindex ed5c8546057d..a9dceb789cbe 100644--- a/ee/hogai/eval/sandboxed/error_tracking/eval_issue_drilldown.py+++ b/products/posthog_ai/evals/error_tracking/eval_issue_drilldown.py@@ -22,25 +22,24 @@ when they didn't need them, and agents drilling into the wrong issue.To run::- pytest ee/hogai/eval/sandboxed/error_tracking/eval_issue_drilldown.py+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_issue_drilldown""""from __future__ import annotationsfrom typing import Any-import pytest--from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.error_tracking.scorers import (+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import NoToolCall+from products.posthog_ai.evals.error_tracking.scorers import (ERROR_TRACKING_WRITE_TOOLS,IssueDrilldownOrder,IssueIdMatchesTarget,IssueInputAlignment,)-from ee.hogai.eval.sandboxed.error_tracking.seeders import seed_error_tracking_issues-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, NoToolCall+from products.posthog_ai.evals.error_tracking.seeders import seed_error_tracking_issuesdef _drilldown_case(@@ -75,8 +74,7 @@ def _drilldown_case()-async def eval_issue_drilldown(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_issue_drilldown(ctx: EvalContext) -> None:cases = [# Detail-only — impact numbers + a glance at the issue. Should not# trigger the heavier events tool or fan out to session recordings.@@ -122,16 +120,13 @@ async def eval_issue_drilldown(sandboxed_demo_data, pytestconfig, posthog_client]await SandboxedPublicEval(- experiment_name=f"sandboxed-error-tracking-issue-drilldown-{mcp_mode}",+ experiment_name="sandboxed-error-tracking-issue-drilldown-cli",cases=cases,scorers=[- ExitCodeZero(),NoToolCall(forbidden=ERROR_TRACKING_WRITE_TOOLS, name="no_error_tracking_write"),IssueDrilldownOrder(),IssueIdMatchesTarget(),IssueInputAlignment(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/error_tracking/eval_issues_list.py b/products/posthog_ai/evals/error_tracking/eval_issues_list.pysimilarity index 79%rename from ee/hogai/eval/sandboxed/error_tracking/eval_issues_list.pyrename to products/posthog_ai/evals/error_tracking/eval_issues_list.pyindex 84a3b9dea737..b133a2e24c32 100644--- a/ee/hogai/eval/sandboxed/error_tracking/eval_issues_list.py+++ b/products/posthog_ai/evals/error_tracking/eval_issues_list.py@@ -22,24 +22,23 @@ final message references the per-case UUID.To run::- pytest ee/hogai/eval/sandboxed/error_tracking/eval_issues_list.py+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_issues_list""""from __future__ import annotationsfrom typing import Any-import pytest--from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.error_tracking.scorers import (+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import NoToolCall+from products.posthog_ai.evals.error_tracking.scorers import (ERROR_TRACKING_WRITE_TOOLS,IssuesListInputAlignment,IssuesListToolUsed,)-from ee.hogai.eval.sandboxed.error_tracking.seeders import seed_error_tracking_issues-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, NoToolCall+from products.posthog_ai.evals.error_tracking.seeders import seed_error_tracking_issuesdef _list_case(@@ -56,8 +55,7 @@ def _list_case()-async def eval_issues_list(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_issues_list(ctx: EvalContext) -> None:cases = [_list_case(name="issues_list_active_default",@@ -87,15 +85,12 @@ async def eval_issues_list(sandboxed_demo_data, pytestconfig, posthog_client, mc]await SandboxedPublicEval(- experiment_name=f"sandboxed-error-tracking-issues-list-{mcp_mode}",+ experiment_name="sandboxed-error-tracking-issues-list-cli",cases=cases,scorers=[- ExitCodeZero(),NoToolCall(forbidden=ERROR_TRACKING_WRITE_TOOLS, name="no_error_tracking_write"),IssuesListToolUsed(),IssuesListInputAlignment(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/error_tracking/scorers.py b/products/posthog_ai/evals/error_tracking/scorers.pysimilarity index 93%rename from ee/hogai/eval/sandboxed/error_tracking/scorers.pyrename to products/posthog_ai/evals/error_tracking/scorers.pyindex dc3276b3ab95..76c2db96d080 100644--- a/ee/hogai/eval/sandboxed/error_tracking/scorers.py+++ b/products/posthog_ai/evals/error_tracking/scorers.py@@ -10,9 +10,8 @@ Three families of scorer:go list → issue (→ optional events → optional recordings), and did itpass the correct per-case ``issueId`` for the named seeded issue?-All scorers build a single ``LogParser`` from ``output["raw_log"]`` so they-work identically in ``mcp_mode=tools`` (per-tool MCP) and ``mcp_mode=cli``-(single-``exec`` wrapper) — the parser handles exec-unwrapping.+All scorers build a single ``LogParser`` from ``output["raw_log"]``; the parser+handles unwrapping the ``posthog:exec`` cli wrapper the MCP server serves."""from __future__ import annotations@@ -21,11 +20,9 @@ import reimport jsonfrom typing import Any-from autoevals.llm import LLMClassifier-from braintrust import Score-from braintrust_core.score import Scorer--from ee.hogai.eval.sandboxed.log_parser import LogParser, ToolCall+from products.posthog_ai.eval_harness.log_parser import LogParser, ToolCall+from products.posthog_ai.eval_harness.scorers import BINARY_CHOICE_SCORES, JUDGE_MODEL, JudgedScorer+from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer__all__ = ["BINARY_CHOICE_SCORES",@@ -67,9 +64,6 @@ QUERY_ISSUE_TOOL = "query-error-tracking-issue"QUERY_ISSUE_EVENTS_TOOL = "query-error-tracking-issue-events"SESSION_RECORDINGS_LIST_TOOL = "query-session-recordings-list"-BINARY_CHOICE_SCORES = {"yes": 1.0, "no": 0.0}--_JUDGE_MODEL = "gpt-5.4"_SESSION_ID_TEXT_RE = re.compile(r"""["']?\$?session_id["']?\s*[:=]\s*["']?([^"',\s}\]]+)""")_TOON_NON_EMPTY_RESULTS_RE = re.compile(r"""(?m)^\s*results\[[1-9]\d*\](?:\{[^}]*\})?:""")@@ -85,7 +79,7 @@ def _parser_for(output: dict[str, Any] | None) -> LogParser | None:raw_log = output.get("raw_log")if not raw_log:return None- return LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")+ return LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")def _last_successful_input(parser: LogParser | None, tool_name: str) -> dict[str, Any] | None:@@ -250,13 +244,7 @@ class _ToolUsedScorer(Scorer):def _name(self) -> str:return self._label- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _evaluate(self, output: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:parser = _parser_for(output)if parser is None:return Score(name=self._name(), score=None, metadata={"reason": "No raw log to parse"})@@ -322,11 +310,11 @@ class EventsToolUsed(_ToolUsedScorer):# ----------------------------------------------------------------------------class _AlignmentClassifier(LLMClassifier):+class _AlignmentClassifier(JudgedScorer):"""Shared boilerplate for binary alignment classifiers.Subclasses provide the prompt template, the per-tool input extractor,- and the expected-payload key on ``case.expected``. The base class+ and the expected-payload key on ``case.expected``. This basehandles the "agent never ran the tool" / "no expected provided"short-circuits by returning ``Score(score=None, ...)`` beforedelegating to the LLM judge — scoring uncalled tools as 0 would@@ -339,24 +327,6 @@ class _AlignmentClassifier(LLMClassifier):def _extract_actual(self, output: dict[str, Any] | None) -> dict[str, Any] | None:raise NotImplementedError- async def _run_eval_async(self, output, expected=None, **kwargs):- prepared = self._prepare(output, expected)- if isinstance(prepared, Score):- return prepared- try:- return await super()._run_eval_async(prepared["output"], prepared["expected"], **kwargs)- except Exception as exc:- return Score(name=self._name(), score=0.0, metadata={"reason": f"judge error: {exc}"})-- def _run_eval_sync(self, output, expected=None, **kwargs):- prepared = self._prepare(output, expected)- if isinstance(prepared, Score):- return prepared- try:- return super()._run_eval_sync(prepared["output"], prepared["expected"], **kwargs)- except Exception as exc:- return Score(name=self._name(), score=0.0, metadata={"reason": f"judge error: {exc}"})-def _prepare(self, output: dict[str, Any] | None, expected: dict[str, Any] | None) -> dict[str, Any] | Score:actual = self._extract_actual(output)if actual is None:@@ -430,7 +400,7 @@ Ignore `filterTestAccounts`, `volumeResolution`, `limit`, `offset` unless EXPECTDoes the actual input match the expected one on the material fields above? Answer `yes` or `no`.""".strip(),choice_scores=BINARY_CHOICE_SCORES,- model=_JUDGE_MODEL,+ model=JUDGE_MODEL,max_completion_tokens=512,**kwargs,)@@ -470,7 +440,7 @@ Ignore `issueId` for this check (covered by a separate scorer). Ignore `filterTeDoes the actual issue input match the expected one on the material fields above? Answer `yes` or `no`.""".strip(),choice_scores=BINARY_CHOICE_SCORES,- model=_JUDGE_MODEL,+ model=JUDGE_MODEL,max_completion_tokens=512,**kwargs,)@@ -579,7 +549,7 @@ Ignore `issueId` for this check (covered by a separate scorer). Ignore `filterTeAre all actual events arguments consistent with the expected ones? Answer `yes` or `no`.""".strip(),choice_scores=BINARY_CHOICE_SCORES,- model=_JUDGE_MODEL,+ model=JUDGE_MODEL,max_completion_tokens=512,**kwargs,)@@ -646,13 +616,7 @@ class IssueIdMatchesTarget(Scorer):def _name(self) -> str:return self._label- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})target = _resolve_target_issue(output.get("seed"), expected)@@ -748,13 +712,7 @@ class IssueDrilldownOrder(Scorer):def _name(self) -> str:return self._label- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})parser = _parser_for(output)diff --git a/ee/hogai/eval/sandboxed/error_tracking/seeders.py b/products/posthog_ai/evals/error_tracking/seeders.pysimilarity index 100%rename from ee/hogai/eval/sandboxed/error_tracking/seeders.pyrename to products/posthog_ai/evals/error_tracking/seeders.pydiff --git a/ee/hogai/eval/sandboxed/data_warehouse/__init__.py b/products/posthog_ai/evals/experiments/__init__.pysimilarity index 100%rename from ee/hogai/eval/sandboxed/data_warehouse/__init__.pyrename to products/posthog_ai/evals/experiments/__init__.pydiff --git a/ee/hogai/eval/sandboxed/experiments/eval_bias_uneven_split.py b/products/posthog_ai/evals/experiments/eval_bias_uneven_split.pysimilarity index 85%rename from ee/hogai/eval/sandboxed/experiments/eval_bias_uneven_split.pyrename to products/posthog_ai/evals/experiments/eval_bias_uneven_split.pyindex 602e4b637d44..7c1ed6e1b84c 100644--- a/ee/hogai/eval/sandboxed/experiments/eval_bias_uneven_split.py+++ b/products/posthog_ai/evals/experiments/eval_bias_uneven_split.py@@ -24,30 +24,24 @@ Two cases:To run:- flox activate -- bash -c "set -a; source .env; set +a; \\- pytest -c ee/hogai/eval/pytest.ini \\- ee/hogai/eval/sandboxed/experiments/eval_bias_uneven_split.py \\- -v --mcp-mode tools"+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_bias_uneven_split""""from __future__ import annotations-import pytest--from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.experiments.scorers import CitesDiagnosticGroup, SurfacesAllFindings-from ee.hogai.eval.sandboxed.experiments.seeders import (+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.evals.experiments.scorers import CitesDiagnosticGroup, SurfacesAllFindings+from products.posthog_ai.evals.experiments.seeders import (ROLLOUT_EXPERIMENT_NAME,UNEVEN_SPLIT_EXPERIMENT_NAME,seed_running_experiment,seed_uneven_split_experiment,)-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero-async def eval_bias_uneven_split(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_bias_uneven_split(ctx: EvalContext) -> None:cases: list[SandboxedEvalCase] = [SandboxedEvalCase(name="uneven_split_alone",@@ -112,14 +106,11 @@ async def eval_bias_uneven_split(sandboxed_demo_data, pytestconfig, posthog_clie]await SandboxedPrivateEval(- experiment_name=f"sandboxed-experiments-diagnose-bias-{mcp_mode}",+ experiment_name="sandboxed-experiments-diagnose-bias-cli",cases=cases,scorers=[- ExitCodeZero(),CitesDiagnosticGroup(),SurfacesAllFindings(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/experiments/eval_create_control_variant.py b/products/posthog_ai/evals/experiments/eval_create_control_variant.pysimilarity index 78%rename from ee/hogai/eval/sandboxed/experiments/eval_create_control_variant.pyrename to products/posthog_ai/evals/experiments/eval_create_control_variant.pyindex 8428f19c662e..493d53c8e9e6 100644--- a/ee/hogai/eval/sandboxed/experiments/eval_create_control_variant.py+++ b/products/posthog_ai/evals/experiments/eval_create_control_variant.py@@ -25,20 +25,18 @@ in any layer that prevents the agent from ever producing a successfulcreate call will flip this scorer to 0.0.To run:- flox activate -- bash -c "set -a; source .env; set +a; \\- pytest -c ee/hogai/eval/pytest.ini \\- ee/hogai/eval/sandboxed/experiments/eval_create_control_variant.py \\- -v --mcp-mode tools"+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_create_control_variant""""from __future__ import annotations-from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, RequiredToolCall+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import RequiredToolCall-async def eval_create_control_variant(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_create_control_variant(ctx: EvalContext) -> None:cases: list[SandboxedEvalCase] = [# Single high-coverage case. The "A (existing) vs B (new)" framing# is the highest-yield trigger of the production "Feature flag@@ -57,10 +55,9 @@ async def eval_create_control_variant(sandboxed_demo_data, pytestconfig, posthog]await SandboxedPrivateEval(- experiment_name=f"sandboxed-experiments-create-control-{mcp_mode}",+ experiment_name="sandboxed-experiments-create-control-cli",cases=cases,scorers=[- ExitCodeZero(),# The single outcome scorer: did experiment-create return without error?# `RequiredToolCall` matches on `is_error=False`, so any of the three# paths in the docstring (clean call / silent normalization / retry@@ -70,7 +67,5 @@ async def eval_create_control_variant(sandboxed_demo_data, pytestconfig, posthogname="experiment_created_successfully",),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/experiments/eval_empty_experiment.py b/products/posthog_ai/evals/experiments/eval_empty_experiment.pysimilarity index 89%rename from ee/hogai/eval/sandboxed/experiments/eval_empty_experiment.pyrename to products/posthog_ai/evals/experiments/eval_empty_experiment.pyindex 82d2f449ede6..f56f785a7128 100644--- a/ee/hogai/eval/sandboxed/experiments/eval_empty_experiment.py+++ b/products/posthog_ai/evals/experiments/eval_empty_experiment.py@@ -36,30 +36,24 @@ snapshot, or checking ``experiment-stats``).To run:- flox activate -- bash -c "set -a; source .env; set +a; \\- pytest -c ee/hogai/eval/pytest.ini \\- ee/hogai/eval/sandboxed/experiments/eval_empty_experiment.py \\- -v --mcp-mode tools"+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_empty_experiment""""from __future__ import annotations-import pytest--from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.experiments.scorers import CitesDiagnosticGroup-from ee.hogai.eval.sandboxed.experiments.seeders import (+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.evals.experiments.scorers import CitesDiagnosticGroup+from products.posthog_ai.evals.experiments.seeders import (INACTIVE_FLAG_EXPERIMENT_NAME,ROLLOUT_EXPERIMENT_NAME,seed_inactive_flag_experiment,seed_running_experiment,)-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero-async def eval_empty_experiment(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_empty_experiment(ctx: EvalContext) -> None:cases: list[SandboxedEvalCase] = [SandboxedEvalCase(name="empty_experiment_inactive_flag",@@ -142,13 +136,10 @@ async def eval_empty_experiment(sandboxed_demo_data, pytestconfig, posthog_clien]await SandboxedPrivateEval(- experiment_name=f"sandboxed-experiments-diagnose-empty-{mcp_mode}",+ experiment_name="sandboxed-experiments-diagnose-empty-cli",cases=cases,scorers=[- ExitCodeZero(),CitesDiagnosticGroup(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/experiments/eval_interpretation_traps.py b/products/posthog_ai/evals/experiments/eval_interpretation_traps.pysimilarity index 84%rename from ee/hogai/eval/sandboxed/experiments/eval_interpretation_traps.pyrename to products/posthog_ai/evals/experiments/eval_interpretation_traps.pyindex c93dab649b5e..a7a4f0b3d552 100644--- a/ee/hogai/eval/sandboxed/experiments/eval_interpretation_traps.py+++ b/products/posthog_ai/evals/experiments/eval_interpretation_traps.py@@ -25,25 +25,19 @@ Two cases:To run:- flox activate -- bash -c "set -a; source .env; set +a; \\- pytest -c ee/hogai/eval/pytest.ini \\- ee/hogai/eval/sandboxed/experiments/eval_interpretation_traps.py \\- -v --mcp-mode tools"+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_interpretation_traps""""from __future__ import annotations-import pytest+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.evals.experiments.scorers import AdvisesAgainstShipping, CitesDiagnosticGroup+from products.posthog_ai.evals.experiments.seeders import ROLLOUT_EXPERIMENT_NAME, seed_running_experiment-from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.experiments.scorers import AdvisesAgainstShipping, CitesDiagnosticGroup-from ee.hogai.eval.sandboxed.experiments.seeders import ROLLOUT_EXPERIMENT_NAME, seed_running_experiment-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero--async def eval_interpretation_traps(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_interpretation_traps(ctx: EvalContext) -> None:cases: list[SandboxedEvalCase] = [SandboxedEvalCase(name="low_volume_30_16_split",@@ -106,14 +100,11 @@ async def eval_interpretation_traps(sandboxed_demo_data, pytestconfig, posthog_c]await SandboxedPrivateEval(- experiment_name=f"sandboxed-experiments-diagnose-interpretation-{mcp_mode}",+ experiment_name="sandboxed-experiments-diagnose-interpretation-cli",cases=cases,scorers=[- ExitCodeZero(),CitesDiagnosticGroup(),AdvisesAgainstShipping(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/experiments/eval_lifecycle_skills.py b/products/posthog_ai/evals/experiments/eval_lifecycle_skills.pysimilarity index 72%rename from ee/hogai/eval/sandboxed/experiments/eval_lifecycle_skills.pyrename to products/posthog_ai/evals/experiments/eval_lifecycle_skills.pyindex 03903cdd47c0..b8045cf03d3c 100644--- a/ee/hogai/eval/sandboxed/experiments/eval_lifecycle_skills.py+++ b/products/posthog_ai/evals/experiments/eval_lifecycle_skills.py@@ -25,34 +25,32 @@ metric becomes a noisy signal for it. We measure outcomes instead.Skill-load coverage belongs in a focused, single-purpose eval.To run:- flox activate -- bash -c "set -a; source .env; set +a; \\- pytest -c ee/hogai/eval/pytest.ini \\- ee/hogai/eval/sandboxed/experiments/eval_lifecycle_skills.py \\- -v --mcp-mode tools"+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_lifecycle_skills""""from __future__ import annotations-from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.experiments.scorers import (+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import NoToolCall, RequiredToolCall+from products.posthog_ai.evals.experiments.scorers import (AskedForConfirmation,DuplicateUniqueFlagKey,RecommendsShipVariant,)-from ee.hogai.eval.sandboxed.experiments.seeders import ROLLOUT_EXPERIMENT_NAME, seed_running_experiment-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, NoToolCall, RequiredToolCall+from products.posthog_ai.evals.experiments.seeders import ROLLOUT_EXPERIMENT_NAME, seed_running_experiment-# Cases are bundled into one test function rather than @pytest.mark.parametrize-# because the sandboxed harness wraps a list of cases in a single-# SandboxedPrivateEval call: one Braintrust experiment, parallel execution via-# max_concurrency=2, per-case filtering via --eval at the runner level. Pytest--# level parametrize would create N separate Braintrust experiments, lose the-# parallelism, and break cross-case comparison. Every existing sandboxed eval-# (eval_funnel, eval_retention, eval_insight_retrieval, eval_rollout_skill)-# follows this same single-function-multiple-cases shape.-async def eval_lifecycle_skills(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+# Cases are bundled into one suite function rather than one function per case+# because the harness wraps a list of cases in a single SandboxedPrivateEval+# call: one Braintrust experiment, with concurrency bounded by the harness's+# global sandbox semaphore and per-case filtering via --eval. Splitting into+# one function per case would create N separate Braintrust experiments and break+# cross-case comparison. Every existing sandboxed eval (eval_funnel,+# eval_retention, eval_insight_retrieval, eval_rollout_skill) follows this same+# single-function-multiple-cases shape.+async def eval_lifecycle_skills(ctx: EvalContext) -> None:cases: list[SandboxedEvalCase] = [# Case 1: Ship variant must require confirmation.# Tests name resolution + the "Always confirm before shipping"@@ -92,10 +90,9 @@ async def eval_lifecycle_skills(sandboxed_demo_data, pytestconfig, posthog_clien]await SandboxedPrivateEval(- experiment_name=f"sandboxed-experiments-lifecycle-{mcp_mode}",+ experiment_name="sandboxed-experiments-lifecycle-cli",cases=cases,scorers=[- ExitCodeZero(),# Agent must look up the named experiment (either tool counts).RequiredToolCall(required={"experiment-list", "experiment-get-all"},@@ -109,7 +106,5 @@ async def eval_lifecycle_skills(sandboxed_demo_data, pytestconfig, posthog_clienDuplicateUniqueFlagKey(),RecommendsShipVariant(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/experiments/eval_metric_schema_discovery.py b/products/posthog_ai/evals/experiments/eval_metric_schema_discovery.pysimilarity index 75%rename from ee/hogai/eval/sandboxed/experiments/eval_metric_schema_discovery.pyrename to products/posthog_ai/evals/experiments/eval_metric_schema_discovery.pyindex 6fb0bf879ef6..5a3d26b5003b 100644--- a/ee/hogai/eval/sandboxed/experiments/eval_metric_schema_discovery.py+++ b/products/posthog_ai/evals/experiments/eval_metric_schema_discovery.py@@ -15,18 +15,19 @@ recovering on a later call does not flip the score.from __future__ import annotations-from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.experiments.scorers import (+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import RequiredToolCall+from products.posthog_ai.evals.experiments.scorers import (FirstUpdateMetricShape,validate_ratio_revenue_metric,validate_retention_metric,)-from ee.hogai.eval.sandboxed.experiments.seeders import ROLLOUT_EXPERIMENT_NAME, seed_running_experiment-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, RequiredToolCall+from products.posthog_ai.evals.experiments.seeders import ROLLOUT_EXPERIMENT_NAME, seed_running_experiment-async def eval_metric_schema_discovery(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_metric_schema_discovery(ctx: EvalContext) -> None:cases: list[SandboxedEvalCase] = [SandboxedEvalCase(name="ratio_metric_uses_math_sum",@@ -51,14 +52,11 @@ async def eval_metric_schema_discovery(sandboxed_demo_data, pytestconfig, postho]await SandboxedPrivateEval(- experiment_name=f"sandboxed-experiments-metric-schema-discovery-{mcp_mode}",+ experiment_name="sandboxed-experiments-metric-schema-discovery-cli",cases=cases,scorers=[- ExitCodeZero(),RequiredToolCall(required={"experiment-update"}, name="called_experiment_update"),FirstUpdateMetricShape(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/experiments/eval_midrun_changes.py b/products/posthog_ai/evals/experiments/eval_midrun_changes.pysimilarity index 87%rename from ee/hogai/eval/sandboxed/experiments/eval_midrun_changes.pyrename to products/posthog_ai/evals/experiments/eval_midrun_changes.pyindex 2f68a4fee078..e9030fe95230 100644--- a/ee/hogai/eval/sandboxed/experiments/eval_midrun_changes.py+++ b/products/posthog_ai/evals/experiments/eval_midrun_changes.py@@ -34,34 +34,28 @@ final diagnosis and the no-edit recommendation are.To run:- flox activate -- bash -c "set -a; source .env; set +a; \\- pytest -c ee/hogai/eval/pytest.ini \\- ee/hogai/eval/sandboxed/experiments/eval_midrun_changes.py \\- -v --mcp-mode tools"+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_midrun_changes""""from __future__ import annotations-import pytest--from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.experiments.scorers import (+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.evals.experiments.scorers import (AdvisesAgainstShipping,CitesDiagnosticGroup,DoesNotRecommendEdit,)-from ee.hogai.eval.sandboxed.experiments.seeders import (+from products.posthog_ai.evals.experiments.seeders import (ENDED_EXPERIMENT_NAME,ROLLOUT_EXPERIMENT_NAME,seed_ended_experiment_with_flag_flip,seed_running_experiment,)-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero-async def eval_midrun_changes(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_midrun_changes(ctx: EvalContext) -> None:cases: list[SandboxedEvalCase] = [SandboxedEvalCase(name="ship_variant_flag_flip_on_stopped_experiment",@@ -125,15 +119,12 @@ async def eval_midrun_changes(sandboxed_demo_data, pytestconfig, posthog_client,]await SandboxedPrivateEval(- experiment_name=f"sandboxed-experiments-diagnose-midrun-changes-{mcp_mode}",+ experiment_name="sandboxed-experiments-diagnose-midrun-changes-cli",cases=cases,scorers=[- ExitCodeZero(),CitesDiagnosticGroup(),DoesNotRecommendEdit(),AdvisesAgainstShipping(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/experiments/eval_numbers_vs_sql.py b/products/posthog_ai/evals/experiments/eval_numbers_vs_sql.pysimilarity index 88%rename from ee/hogai/eval/sandboxed/experiments/eval_numbers_vs_sql.pyrename to products/posthog_ai/evals/experiments/eval_numbers_vs_sql.pyindex 9e7c2b583b74..88daccb7dfa3 100644--- a/ee/hogai/eval/sandboxed/experiments/eval_numbers_vs_sql.py+++ b/products/posthog_ai/evals/experiments/eval_numbers_vs_sql.py@@ -26,25 +26,19 @@ Two cases:To run:- flox activate -- bash -c "set -a; source .env; set +a; \\- pytest -c ee/hogai/eval/pytest.ini \\- ee/hogai/eval/sandboxed/experiments/eval_numbers_vs_sql.py \\- -v --mcp-mode tools"+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_numbers_vs_sql""""from __future__ import annotations-import pytest+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.evals.experiments.scorers import CitesDiagnosticGroup+from products.posthog_ai.evals.experiments.seeders import ROLLOUT_EXPERIMENT_NAME, seed_running_experiment-from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.experiments.scorers import CitesDiagnosticGroup-from ee.hogai.eval.sandboxed.experiments.seeders import ROLLOUT_EXPERIMENT_NAME, seed_running_experiment-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero--async def eval_numbers_vs_sql(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_numbers_vs_sql(ctx: EvalContext) -> None:cases: list[SandboxedEvalCase] = [SandboxedEvalCase(name="posthog_count_below_raw_sql",@@ -126,13 +120,10 @@ async def eval_numbers_vs_sql(sandboxed_demo_data, pytestconfig, posthog_client,]await SandboxedPrivateEval(- experiment_name=f"sandboxed-experiments-diagnose-numbers-vs-sql-{mcp_mode}",+ experiment_name="sandboxed-experiments-diagnose-numbers-vs-sql-cli",cases=cases,scorers=[- ExitCodeZero(),CitesDiagnosticGroup(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/experiments/eval_rollout_skill.py b/products/posthog_ai/evals/experiments/eval_rollout_skill.pysimilarity index 58%rename from ee/hogai/eval/sandboxed/experiments/eval_rollout_skill.pyrename to products/posthog_ai/evals/experiments/eval_rollout_skill.pyindex a05c9a079159..fc646a7b4c51 100644--- a/ee/hogai/eval/sandboxed/experiments/eval_rollout_skill.py+++ b/products/posthog_ai/evals/experiments/eval_rollout_skill.py@@ -12,24 +12,21 @@ the variant-split rows (2.5, 5.3, 5.4, 5.5) in STEP_1_HARNESS.md. Useslocal logs and PostHog ``$ai_trace`` events still emit.To run:- flox activate -- bash -c "set -a; source .env; set +a; \\- pytest -c ee/hogai/eval/pytest.ini \\- ee/hogai/eval/sandboxed/experiments/eval_rollout_skill.py \\- -v --mcp-mode tools --eval rollout"+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_rollout_skill""""from __future__ import annotations-from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.experiments.seeders import ROLLOUT_EXPERIMENT_NAME, seed_running_experiment-from ee.hogai.eval.sandboxed.retrieval.scorers import SkillLoaded-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.evals.experiments.seeders import ROLLOUT_EXPERIMENT_NAME, seed_running_experiment+from products.posthog_ai.evals.retrieval.scorers import SkillLoadedSKILL_NAME = "configuring-experiment-rollout"-async def eval_rollout_skill(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_rollout_skill(ctx: EvalContext) -> None:cases: list[SandboxedEvalCase] = [SandboxedEvalCase(name="rollout_change_split_70_30",@@ -41,13 +38,10 @@ async def eval_rollout_skill(sandboxed_demo_data, pytestconfig, posthog_client,]await SandboxedPrivateEval(- experiment_name=f"sandboxed-experiments-rollout-{mcp_mode}",+ experiment_name="sandboxed-experiments-rollout-cli",cases=cases,scorers=[- ExitCodeZero(),SkillLoaded(skill_name=SKILL_NAME),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/experiments/eval_shared_metric_validation.py b/products/posthog_ai/evals/experiments/eval_shared_metric_validation.pysimilarity index 78%rename from ee/hogai/eval/sandboxed/experiments/eval_shared_metric_validation.pyrename to products/posthog_ai/evals/experiments/eval_shared_metric_validation.pyindex 326e8bb89101..b1a8cc250afc 100644--- a/ee/hogai/eval/sandboxed/experiments/eval_shared_metric_validation.py+++ b/products/posthog_ai/evals/experiments/eval_shared_metric_validation.py@@ -7,14 +7,15 @@ and (2) reach the correct verdict citing grounded discrepancies.from __future__ import annotations-from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.experiments.scorers import SharedMetricValidationVerdict-from ee.hogai.eval.sandboxed.experiments.seeders import SHARED_METRIC_NAME, seed_shared_metric_purchase_count-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, RequiredToolCall+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import RequiredToolCall+from products.posthog_ai.evals.experiments.scorers import SharedMetricValidationVerdict+from products.posthog_ai.evals.experiments.seeders import SHARED_METRIC_NAME, seed_shared_metric_purchase_count-async def eval_shared_metric_validation(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_shared_metric_validation(ctx: EvalContext) -> None:cases: list[SandboxedEvalCase] = [# Case 1: criteria match the seeded metric exactly. Agent should# affirm the match and cite the event and math.@@ -48,10 +49,9 @@ async def eval_shared_metric_validation(sandboxed_demo_data, pytestconfig, posth]await SandboxedPrivateEval(- experiment_name=f"sandboxed-experiments-shared-metric-validation-{mcp_mode}",+ experiment_name="sandboxed-experiments-shared-metric-validation-cli",cases=cases,scorers=[- ExitCodeZero(),# Agent must actually read the seeded metric — either via list# (to resolve by name) or retrieve (by ID). Hallucinating a# verdict without reading the metric should fail this scorer.@@ -61,7 +61,5 @@ async def eval_shared_metric_validation(sandboxed_demo_data, pytestconfig, posth),SharedMetricValidationVerdict(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/experiments/eval_unknown_events_confirmation.py b/products/posthog_ai/evals/experiments/eval_unknown_events_confirmation.pysimilarity index 79%rename from ee/hogai/eval/sandboxed/experiments/eval_unknown_events_confirmation.pyrename to products/posthog_ai/evals/experiments/eval_unknown_events_confirmation.pyindex d10d954ffc1b..8d82cb859a2a 100644--- a/ee/hogai/eval/sandboxed/experiments/eval_unknown_events_confirmation.py+++ b/products/posthog_ai/evals/experiments/eval_unknown_events_confirmation.py@@ -29,26 +29,24 @@ Pass criteria for the case below:To run:- flox activate -- bash -c "set -a; source .env; set +a; \\- pytest -c ee/hogai/eval/pytest.ini \\- ee/hogai/eval/sandboxed/experiments/eval_unknown_events_confirmation.py \\- -v --mcp-mode tools"+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_unknown_events_confirmation""""from __future__ import annotations-from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.experiments.scorers import AskedForConfirmation-from ee.hogai.eval.sandboxed.experiments.seeders import ROLLOUT_EXPERIMENT_NAME, seed_running_experiment-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, NoToolCall, RequiredToolCall+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import NoToolCall, RequiredToolCall+from products.posthog_ai.evals.experiments.scorers import AskedForConfirmation+from products.posthog_ai.evals.experiments.seeders import ROLLOUT_EXPERIMENT_NAME, seed_running_experiment# Event name chosen to be obviously fictional so the agent can't plausibly# justify it as a typo of a real PostHog event in the seeded team.UNKNOWN_EVENT_NAME = "totally_made_up_event_qzx"-async def eval_unknown_events_confirmation(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_unknown_events_confirmation(ctx: EvalContext) -> None:cases: list[SandboxedEvalCase] = [# The agent is asked to wire up a metric on an event the project# has never ingested. The first experiment-update attempt will hit@@ -67,10 +65,9 @@ async def eval_unknown_events_confirmation(sandboxed_demo_data, pytestconfig, po]await SandboxedPrivateEval(- experiment_name=f"sandboxed-experiments-unknown-events-{mcp_mode}",+ experiment_name="sandboxed-experiments-unknown-events-cli",cases=cases,scorers=[- ExitCodeZero(),# Agent must look up the named experiment first.RequiredToolCall(required={"experiment-list", "experiment-get-all"},@@ -91,7 +88,5 @@ async def eval_unknown_events_confirmation(sandboxed_demo_data, pytestconfig, po),),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/experiments/scorers.py b/products/posthog_ai/evals/experiments/scorers.pysimilarity index 92%rename from ee/hogai/eval/sandboxed/experiments/scorers.pyrename to products/posthog_ai/evals/experiments/scorers.pyindex cbbe4aa1d320..5558d06f5482 100644--- a/ee/hogai/eval/sandboxed/experiments/scorers.py+++ b/products/posthog_ai/evals/experiments/scorers.py@@ -7,7 +7,7 @@ where they aren't applicable. We return ``score=1.0`` withaggregating ``None`` (``int + None``). The trade-off: per-scoreraggregates are mildly inflated (a 100% score with one case checked andtwo trivially skipped). Per-case detail is preserved in the local log-dir under ``ee/hogai/eval/sandboxed/logs/``.+dir under ``products/posthog_ai/eval_harness/logs/``.* ``DuplicateUniqueFlagKey`` — deterministic. Verifies that when the agentcalls ``experiment-duplicate``, it provides a ``feature_flag_key`` that@@ -58,12 +58,12 @@ from __future__ import annotationsfrom typing import Anyfrom autoevals.llm import LLMClassifier-from braintrust import Score-from braintrust_core.score import Scorer-from ee.hogai.eval.sandboxed.scorers import LogParser+from products.posthog_ai.eval_harness.scorers import BINARY_CHOICE_SCORES, AsyncOnlyScorerMixin, JudgedScorer, LogParser+from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer-BINARY_CHOICE_SCORES = {"yes": 1.0, "no": 0.0}+# Not the shared JUDGE_MODEL: these judges were baselined on gpt-4.1, and+# swapping the model resets their Braintrust history._JUDGE_MODEL = "gpt-4.1"@@ -73,7 +73,7 @@ def _parser_for(output: dict[str, Any] | None) -> LogParser | None:raw_log = output.get("raw_log")if not raw_log:return None- return LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")+ return LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")def _user_prompt(output: dict[str, Any] | None) -> str:@@ -92,7 +92,7 @@ def _is_applicable(expected: Any, key: str) -> bool:return isinstance(expected, dict) and bool(expected.get(key))-class DuplicateUniqueFlagKey(Scorer):+class DuplicateUniqueFlagKey(AsyncOnlyScorerMixin, Scorer):"""Hybrid (deterministic + LLM judge): agent must avoid the silent shared-flag-key default.The skill body (``managing-experiment-lifecycle/SKILL.md`` line 111)@@ -169,20 +169,7 @@ Answer `yes` or `no`.return deterministic# No experiment-duplicate call → fall through to LLM judge.try:- judge_score = await self._refusal_judge._run_eval_async(- {"prompt": _user_prompt(output), "last_message": output.get("last_message", "") or ""},- None,- )- except Exception as exc:- return Score(name=self._name(), score=0.0, metadata={"reason": f"judge error: {exc}"})- return self._wrap_judge(judge_score)-- def _run_eval_sync(self, output, expected=None, **kwargs):- deterministic = self._evaluate_deterministic(output, expected)- if deterministic is not None:- return deterministic- try:- judge_score = self._refusal_judge._run_eval_sync(+ judge_score = await self._refusal_judge.eval_async({"prompt": _user_prompt(output), "last_message": output.get("last_message", "") or ""},None,)@@ -272,38 +259,7 @@ Answer `yes` or `no`.)-class _BinaryJudge(LLMClassifier):- """Mirror of ``product_analytics._JudgedScorer`` for binary yes/no judges.-- Subclasses implement ``_prepare(output, expected)`` returning either a- ``Score`` (skip the judge call) or a dict with ``output`` to forward- as template variables. Judge-call errors map to ``score=0.0`` so a- broken judge surfaces instead of silently dropping out of the aggregate.- """-- async def _run_eval_async(self, output, expected=None, **kwargs):- prepared = self._prepare(output, expected)- if isinstance(prepared, Score):- return prepared- try:- return await super()._run_eval_async(prepared["output"], None, **kwargs)- except Exception as exc:- return Score(name=self._name(), score=0.0, metadata={"reason": f"judge error: {exc}"})-- def _run_eval_sync(self, output, expected=None, **kwargs):- prepared = self._prepare(output, expected)- if isinstance(prepared, Score):- return prepared- try:- return super()._run_eval_sync(prepared["output"], None, **kwargs)- except Exception as exc:- return Score(name=self._name(), score=0.0, metadata={"reason": f"judge error: {exc}"})-- def _prepare(self, output, expected) -> dict[str, Any] | Score:- raise NotImplementedError---class AskedForConfirmation(_BinaryJudge):+class AskedForConfirmation(JudgedScorer):"""Binary yes/no: did the agent ask for confirmation before the action the user requested?Pass ``scenario`` (a verb phrase describing what the user asked) to swap@@ -360,7 +316,7 @@ Did the agent ask the user to confirm before proceeding? Phrasings like "let me)-class SharedMetricValidationVerdict(_BinaryJudge):+class SharedMetricValidationVerdict(JudgedScorer):"""Binary yes/no: agent's verdict aligns with expected AND cites grounded reasons.Opts in via ``expected={"shared_metric_validation_verdict": "match" | "mismatch"}``.@@ -433,7 +389,7 @@ Answer `yes` or `no`.)-class CitesDiagnosticGroup(_BinaryJudge):+class CitesDiagnosticGroup(JudgedScorer):"""Binary yes/no: did the agent's final message correctly cite the expected diagnostic?Opt-in via ``expected={"diagnosis_group": "<one-line description of the expected diagnosis>"}``.@@ -493,7 +449,7 @@ Answer `no` if the agent listed a different diagnostic as the primary cause, if)-class SurfacesAllFindings(_BinaryJudge):+class SurfacesAllFindings(JudgedScorer):"""Binary yes/no: did the agent surface every listed co-occurring finding?Opt-in via ``expected={"surfaces_all_findings": ["finding 1", "finding 2", ...]}``.@@ -556,7 +512,7 @@ Answer `no` if the agent surfaced only some of the findings, bundled them into a)-class DoesNotRecommendEdit(_BinaryJudge):+class DoesNotRecommendEdit(JudgedScorer):"""Binary yes/no: agent led with explanation and didn't push reversal on a stopped experiment.Opt-in via ``expected={"does_not_recommend_edit": True}``. On a stopped@@ -630,7 +586,7 @@ Answer `no` if ANY of the following hold:)-class RecommendsShipVariant(_BinaryJudge):+class RecommendsShipVariant(JudgedScorer):"""Binary yes/no: in a 'clear winner' scenario, did the agent recommend ship-variant (not end)?"""def _prepare(self, output, expected) -> dict[str, Any] | Score:@@ -698,13 +654,7 @@ class FirstUpdateMetricShape(Scorer):def _name(self) -> str:return "first_update_metric_shape"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: Any) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: Any = None, **kwargs) -> Score:validator = expected.get(self._name()) if isinstance(expected, dict) else Noneif not callable(validator):return Score(@@ -791,7 +741,7 @@ def validate_retention_metric(metrics: list[dict]) -> tuple[bool, str]:return (True, "Retention metric carries retention_window_start and start_handling")-class AdvisesAgainstShipping(_BinaryJudge):+class AdvisesAgainstShipping(JudgedScorer):"""Binary yes/no: did the agent advise against shipping (or recommend waiting)?Opt-in via ``expected={"advises_against_shipping": True}``. Behavioraldiff --git a/ee/hogai/eval/sandboxed/experiments/seeders.py b/products/posthog_ai/evals/experiments/seeders.pysimilarity index 100%rename from ee/hogai/eval/sandboxed/experiments/seeders.pyrename to products/posthog_ai/evals/experiments/seeders.pydiff --git a/ee/hogai/eval/sandboxed/product_analytics/eval_funnel.py b/products/posthog_ai/evals/product_analytics/eval_funnel.pysimilarity index 97%rename from ee/hogai/eval/sandboxed/product_analytics/eval_funnel.pyrename to products/posthog_ai/evals/product_analytics/eval_funnel.pyindex 687995bf56ce..185c952812c4 100644--- a/ee/hogai/eval/sandboxed/product_analytics/eval_funnel.py+++ b/products/posthog_ai/evals/product_analytics/eval_funnel.py@@ -6,7 +6,7 @@ the same intents end-to-end through the sandboxed agent + PostHog MCP toolsand judges the funnel query the agent ran via the ``query-funnel`` MCP tool.To run:- pytest ee/hogai/eval/sandboxed/product_analytics/eval_funnel.py+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_funnel""""from __future__ import annotations@@ -20,14 +20,15 @@ from posthog.schema import (AssistantFunnelsQuery,)-from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.product_analytics.scorers import (+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import LastToolCallNot, NoToolCall, RequiredToolCall+from products.posthog_ai.evals.product_analytics.scorers import (INSIGHT_WRITE_TOOLS,FunnelSchemaAlignment,FunnelTimeRangeRelevancy,)-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, LastToolCallNot, NoToolCall, RequiredToolCalldef _funnel_case(@@ -45,7 +46,7 @@ def _funnel_case()-async def eval_funnel(sandboxed_demo_data, pytestconfig, posthog_client):+async def eval_funnel(ctx: EvalContext) -> None:now = datetime.now()this_year = now.yearthis_month_start = f"{now.year}-{now.month:02d}-01"@@ -597,14 +598,11 @@ async def eval_funnel(sandboxed_demo_data, pytestconfig, posthog_client):experiment_name="sandboxed-funnels",cases=cases,scorers=[- ExitCodeZero(),NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),LastToolCallNot(forbidden="execute-sql", name="last_call_not_execute_sql"),RequiredToolCall(required={"read-data-schema"}, name="verified_event_exists"),FunnelSchemaAlignment(),FunnelTimeRangeRelevancy(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/product_analytics/eval_retention.py b/products/posthog_ai/evals/product_analytics/eval_retention.pysimilarity index 88%rename from ee/hogai/eval/sandboxed/product_analytics/eval_retention.pyrename to products/posthog_ai/evals/product_analytics/eval_retention.pyindex 232214c60278..7da9879e2147 100644--- a/ee/hogai/eval/sandboxed/product_analytics/eval_retention.py+++ b/products/posthog_ai/evals/product_analytics/eval_retention.py@@ -7,21 +7,22 @@ and judges the retention query the agent ran via the ``query-retention`` MCPtool.To run:- pytest ee/hogai/eval/sandboxed/product_analytics/eval_retention.py+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_retention""""from __future__ import annotationsfrom posthog.schema import AssistantRetentionEventsNode, AssistantRetentionFilter, AssistantRetentionQuery-from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.product_analytics.scorers import (+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import LastToolCallNot, NoToolCall+from products.posthog_ai.evals.product_analytics.scorers import (INSIGHT_WRITE_TOOLS,RetentionSchemaAlignment,RetentionTimeRangeRelevancy,)-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, LastToolCallNot, NoToolCalldef _retention_case(@@ -39,7 +40,7 @@ def _retention_case()-async def eval_retention(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_retention(ctx: EvalContext) -> None:cases = [_retention_case(name="retention_pageview_default",@@ -124,16 +125,13 @@ async def eval_retention(sandboxed_demo_data, pytestconfig, posthog_client, mcp_]await SandboxedPublicEval(- experiment_name=f"sandboxed-retention-{mcp_mode}",+ experiment_name="sandboxed-retention-cli",cases=cases,scorers=[- ExitCodeZero(),NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),LastToolCallNot(forbidden="execute-sql", name="last_call_not_execute_sql"),RetentionSchemaAlignment(),RetentionTimeRangeRelevancy(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/product_analytics/eval_schema_discovery.py b/products/posthog_ai/evals/product_analytics/eval_schema_discovery.pysimilarity index 81%rename from ee/hogai/eval/sandboxed/product_analytics/eval_schema_discovery.pyrename to products/posthog_ai/evals/product_analytics/eval_schema_discovery.pyindex 996fff7026d6..8a0049aef075 100644--- a/ee/hogai/eval/sandboxed/product_analytics/eval_schema_discovery.py+++ b/products/posthog_ai/evals/product_analytics/eval_schema_discovery.py@@ -12,17 +12,18 @@ is ``ee/hogai/eval/ci/eval_trends.py``'s job. This eval grades orderingand discovery hygiene.To run:- pytest ee/hogai/eval/sandboxed/product_analytics/eval_schema_discovery.py+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_schema_discovery""""from __future__ import annotationsfrom typing import Any-from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.product_analytics.scorers import INSIGHT_WRITE_TOOLS, SchemaDiscoveryOrder-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, LastToolCallNot, NoToolCall+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import LastToolCallNot, NoToolCall+from products.posthog_ai.evals.product_analytics.scorers import INSIGHT_WRITE_TOOLS, SchemaDiscoveryOrderdef _discovery_case(@@ -43,7 +44,7 @@ def _discovery_case(return SandboxedEvalCase(name=name, prompt=prompt, expected=expected)-async def eval_schema_discovery(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_schema_discovery(ctx: EvalContext) -> None:cases = [_discovery_case(name="schema_discovery_pageview_7d",@@ -83,15 +84,12 @@ async def eval_schema_discovery(sandboxed_demo_data, pytestconfig, posthog_clien]await SandboxedPublicEval(- experiment_name=f"sandboxed-schema-discovery-{mcp_mode}",+ experiment_name="sandboxed-schema-discovery-cli",cases=cases,scorers=[- ExitCodeZero(),NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),LastToolCallNot(forbidden="execute-sql", name="last_call_not_execute_sql"),SchemaDiscoveryOrder(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/product_analytics/eval_trends.py b/products/posthog_ai/evals/product_analytics/eval_trends.pysimilarity index 94%rename from ee/hogai/eval/sandboxed/product_analytics/eval_trends.pyrename to products/posthog_ai/evals/product_analytics/eval_trends.pyindex 4903d4b11576..575e406bcfc6 100644--- a/ee/hogai/eval/sandboxed/product_analytics/eval_trends.py+++ b/products/posthog_ai/evals/product_analytics/eval_trends.py@@ -6,7 +6,7 @@ the same intents end-to-end through the sandboxed agent + PostHog MCP toolsand judges the trends query the agent ran via the ``query-trends`` MCP tool.To run:- pytest ee/hogai/eval/sandboxed/product_analytics/eval_trends.py+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_trends""""from __future__ import annotations@@ -23,15 +23,16 @@ from posthog.schema import (TrendsFormulaNode,)-from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.product_analytics.scorers import (+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import LastToolCallNot, NoToolCall+from products.posthog_ai.evals.product_analytics.scorers import (INSIGHT_WRITE_TOOLS,TrendsSchemaAlignment,TrendsTimeRangeRelevancy,)-from ee.hogai.eval.sandboxed.retrieval.scorers import SkillLoaded-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, LastToolCallNot, NoToolCall+from products.posthog_ai.evals.retrieval.scorers import SkillLoadeddef _trends_case(@@ -49,7 +50,7 @@ def _trends_case()-async def eval_trends(sandboxed_demo_data, pytestconfig, posthog_client):+async def eval_trends(ctx: EvalContext) -> None:cases = [_trends_case(name="trends_pageview_default",@@ -311,14 +312,11 @@ async def eval_trends(sandboxed_demo_data, pytestconfig, posthog_client):experiment_name="sandboxed-trends",cases=cases,scorers=[- ExitCodeZero(),NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),LastToolCallNot(forbidden="execute-sql", name="last_call_not_execute_sql"),SkillLoaded("providing-insights", name="providing_insights_skill_loaded"),TrendsSchemaAlignment(),TrendsTimeRangeRelevancy(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/product_analytics/scorers.py b/products/posthog_ai/evals/product_analytics/scorers.pysimilarity index 93%rename from ee/hogai/eval/sandboxed/product_analytics/scorers.pyrename to products/posthog_ai/evals/product_analytics/scorers.pyindex b92036a239fc..f20e94864b2d 100644--- a/ee/hogai/eval/sandboxed/product_analytics/scorers.py+++ b/products/posthog_ai/evals/product_analytics/scorers.py@@ -16,14 +16,18 @@ from __future__ import annotationsfrom collections.abc import Iterablefrom typing import Any-from autoevals.llm import LLMClassifier-from braintrust import Score-from braintrust_core.score import Scorerfrom pydantic import BaseModelfrom posthog.schema import AssistantFunnelsQuery, AssistantRetentionQuery, AssistantTrendsQuery-from ee.hogai.eval.sandboxed.log_parser import INFO_SYNTHETIC_PREFIX, LogParser, ToolCall+from products.posthog_ai.eval_harness.log_parser import INFO_SYNTHETIC_PREFIX, LogParser, ToolCall+from products.posthog_ai.eval_harness.scorers import (+ BINARY_CHOICE_SCORES,+ GRADED_ALIGNMENT_CHOICE_SCORES,+ JUDGE_MODEL,+ JudgedScorer,+)+from products.posthog_ai.eval_harness.scorers.contract import Score, ScorerQUERY_TRENDS_TOOL_NAME = "query-trends"QUERY_RETENTION_TOOL_NAME = "query-retention"@@ -31,17 +35,6 @@ QUERY_FUNNEL_TOOL_NAME = "query-funnel"READ_DATA_SCHEMA_TOOL_NAME = "read-data-schema"TOOL_SEARCH_TOOL_NAME = "ToolSearch"-BINARY_CHOICE_SCORES = {"yes": 1.0, "no": 0.0}--GRADED_ALIGNMENT_CHOICE_SCORES = {- "perfect": 1.0,- "near_perfect": 0.9,- "slightly_off": 0.75,- "somewhat_misaligned": 0.5,- "strongly_misaligned": 0.25,- "useless": 0.0,-}-GRADED_ALIGNMENT_RUBRIC = """How would you rate the alignment of the generated query with the expected query? Choose one:- perfect: The generated query fully matches the expected query on every material aspect.@@ -54,8 +47,6 @@ How would you rate the alignment of the generated query with the expected query?Details matter greatly here — including math types, property types, and filter direction — so be harsh.""".strip()-JUDGE_MODEL = "gpt-5.4"-# PostHog MCP tools that persist saved-insight state. The sandbox is disposable# but these tools still hit real rows, so any successful call is a bug in the# agent's behaviour for a "just run the query" prompt.@@ -69,49 +60,13 @@ INSIGHT_WRITE_TOOLS = frozenset()-class JudgedScorer(LLMClassifier):- """Shared wiring for sandboxed LLM judges.-- Subclasses implement ``_prepare(output, expected)`` returning either a- ``Score`` to short-circuit, or a dict with ``output``/``expected`` to- forward to the LLM judge.-- Both the short-circuit paths and judge-call exceptions map to- ``score=0.0`` rather than ``score=None`` — Braintrust treats ``None`` as- "skipped" and drops it from the aggregate, which silently hides broken- judges and missing query inputs. We want those to surface as failing- scores instead.- """-- async def _run_eval_async(self, output, expected=None, **kwargs):- prepared = self._prepare(output, expected)- if isinstance(prepared, Score):- return prepared- try:- return await super()._run_eval_async(prepared["output"], prepared["expected"], **kwargs)- except Exception as exc:- return Score(name=self._name(), score=0.0, metadata={"reason": f"judge error: {exc}"})-- def _run_eval_sync(self, output, expected=None, **kwargs):- prepared = self._prepare(output, expected)- if isinstance(prepared, Score):- return prepared- try:- return super()._run_eval_sync(prepared["output"], prepared["expected"], **kwargs)- except Exception as exc:- return Score(name=self._name(), score=0.0, metadata={"reason": f"judge error: {exc}"})-- def _prepare(self, output, expected) -> dict[str, Any] | Score:- raise NotImplementedError--def parser_for(output: dict[str, Any] | None) -> LogParser | None:if not output:return Noneraw_log = output.get("raw_log")if not raw_log:return None- return LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")+ return LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")def extract_last_successful_input(@@ -609,13 +564,7 @@ class SchemaDiscoveryOrder(Scorer):def _name(self) -> str:return self._label- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})parser = parser_for(output)diff --git a/ee/hogai/eval/sandboxed/retrieval/eval_insight_retrieval.py b/products/posthog_ai/evals/retrieval/eval_insight_retrieval.pysimilarity index 79%rename from ee/hogai/eval/sandboxed/retrieval/eval_insight_retrieval.pyrename to products/posthog_ai/evals/retrieval/eval_insight_retrieval.pyindex 0d18a1c95b0e..ef9a878e98c1 100644--- a/ee/hogai/eval/sandboxed/retrieval/eval_insight_retrieval.py+++ b/products/posthog_ai/evals/retrieval/eval_insight_retrieval.py@@ -14,21 +14,21 @@ Two metrics:hallucinating a plausible-looking ID.To run:- pytest ee/hogai/eval/sandboxed/retrieval/eval_insight_retrieval.py+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_insight_retrieval""""from __future__ import annotations-from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.retrieval.scorers import LookupIdInOutput, SkillLoaded-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero-from ee.hogai.eval.sandboxed.seeders.insight import seed_insight_noise+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.seeders.insight import seed_insight_noise+from products.posthog_ai.evals.retrieval.scorers import LookupIdInOutput, SkillLoadedSKILL_NAME = "querying-posthog-data"-async def eval_insight_retrieval(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_insight_retrieval(ctx: EvalContext) -> None:cases: list[SandboxedEvalCase] = [SandboxedEvalCase(name="retrieval_insight_northern_lights",@@ -71,14 +71,11 @@ async def eval_insight_retrieval(sandboxed_demo_data, pytestconfig, posthog_clie]await SandboxedPublicEval(- experiment_name=f"sandboxed-retrieval-{mcp_mode}",+ experiment_name="sandboxed-retrieval-cli",cases=cases,scorers=[- ExitCodeZero(),SkillLoaded(skill_name=SKILL_NAME),LookupIdInOutput(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/retrieval/eval_system_table_search.py b/products/posthog_ai/evals/retrieval/eval_system_table_search.pysimilarity index 80%rename from ee/hogai/eval/sandboxed/retrieval/eval_system_table_search.pyrename to products/posthog_ai/evals/retrieval/eval_system_table_search.pyindex 8e42b1f615df..fcb2dc80d646 100644--- a/ee/hogai/eval/sandboxed/retrieval/eval_system_table_search.py+++ b/products/posthog_ai/evals/retrieval/eval_system_table_search.py@@ -25,19 +25,19 @@ Metrics:To run::- pytest ee/hogai/eval/sandboxed/retrieval/eval_system_table_search.py+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_system_table_search""""from __future__ import annotations-from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.retrieval.scorers import InfoCalledBeforeTool, InformationSchemaBeforeSql-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero-from ee.hogai.eval.sandboxed.seeders.insight import seed_insight_noise+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.seeders.insight import seed_insight_noise+from products.posthog_ai.evals.retrieval.scorers import InfoCalledBeforeTool, InformationSchemaBeforeSql-async def eval_system_table_search(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_system_table_search(ctx: EvalContext) -> None:# ``seed_insight_noise`` adds ~1000 plausible-looking noise insights plus a# handful of deterministic lookup insights (incl. "Monthly Active Users# (Hedgebox)") to the per-case team. The noise volume makes `insights-list`@@ -72,14 +72,11 @@ async def eval_system_table_search(sandboxed_demo_data, pytestconfig, posthog_cl]await SandboxedPublicEval(- experiment_name=f"sandboxed-system-table-search-{mcp_mode}",+ experiment_name="sandboxed-system-table-search-cli",cases=cases,scorers=[- ExitCodeZero(),InformationSchemaBeforeSql(),InfoCalledBeforeTool("execute-sql"),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/retrieval/scorers.py b/products/posthog_ai/evals/retrieval/scorers.pysimilarity index 90%rename from ee/hogai/eval/sandboxed/retrieval/scorers.pyrename to products/posthog_ai/evals/retrieval/scorers.pyindex 2616cdb62859..68e5bbb70594 100644--- a/ee/hogai/eval/sandboxed/retrieval/scorers.py+++ b/products/posthog_ai/evals/retrieval/scorers.py@@ -31,24 +31,26 @@ nothing has to be threaded through ``expected``. The third opts in viafrom __future__ import annotationsimport re+import jsonfrom typing import Any-from braintrust import Score-from braintrust_core.score import Scorer--from ee.hogai.eval.sandboxed.log_parser import INFO_SYNTHETIC_PREFIX, LogParser+from products.posthog_ai.eval_harness.log_parser import INFO_SYNTHETIC_PREFIX, LogParser+from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer__all__ = ["InfoCalledBeforeTool", "InformationSchemaBeforeSql", "LookupIdInOutput", "SkillLoaded"]class SkillLoaded(Scorer):- """Binary: did the agent load a specific Claude Code skill?+ """Binary: did the agent load a specific skill?- Recognized as either:- * a successful ``Skill`` tool call (``input.skill == skill_name``), or+ Recognized as any of:+ * a successful ``Skill`` tool call (``input.skill == skill_name``),* a successful ``Read`` tool call whose ``file_path`` references theskill's ``SKILL.md`` (catches the fallback path where the agent- reads the skill file directly).+ reads the skill file directly), or+ * any other successful tool call that references the skill's ``SKILL.md``+ path in its name or input — the codex runtime has no ``Skill``/``Read``+ tools and reads skills through shell commands instead."""def __init__(self, skill_name: str, *, name: str | None = None):@@ -58,20 +60,14 @@ class SkillLoaded(Scorer):def _name(self) -> str:return self._label- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _evaluate(self, output: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})raw_log = output.get("raw_log")if not raw_log:return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})- parser = LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")+ parser = LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")for skill_call in parser.get_skill_calls(self.skill_name):if not skill_call.is_error:@@ -92,6 +88,17 @@ class SkillLoaded(Scorer):metadata={"matched_via": "read_skill_md", "file_path": file_path},)+ skill_file_ref = f"{self.skill_name}/SKILL.md"+ for call in parser.get_tool_calls():+ if call.is_error:+ continue+ if skill_file_ref in call.name or skill_file_ref in json.dumps(call.input, default=str):+ return Score(+ name=self._name(),+ score=1.0,+ metadata={"matched_via": "tool_reference", "tool": call.name[:120]},+ )+return Score(name=self._name(),score=0.0,@@ -140,13 +147,7 @@ class LookupIdInOutput(Scorer):def _name(self) -> str:return self._label- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})@@ -294,12 +295,6 @@ class InformationSchemaBeforeSql(Scorer):def _name(self) -> str:return "information_schema_before_sql"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-@staticmethoddef _query_text(call) -> str:query = call.input.get("query") if isinstance(call.input, dict) else None@@ -314,7 +309,7 @@ class InformationSchemaBeforeSql(Scorer):query = cls._query_text(call)return "system." in query and "information_schema" not in query- def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})if not isinstance(expected, dict) or self._name() not in expected:@@ -324,7 +319,7 @@ class InformationSchemaBeforeSql(Scorer):if not raw_log:return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})- parser = LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")+ parser = LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")calls = sorted(parser.get_tool_calls(), key=lambda c: c.position)seen_discovery = False@@ -389,20 +384,14 @@ class InfoCalledBeforeTool(Scorer):def _name(self) -> str:return self._label- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _evaluate(self, output: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})raw_log = output.get("raw_log")if not raw_log:return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})- parser = LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")+ parser = LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")calls = sorted(parser.get_tool_calls(), key=lambda c: c.position)if not any(call.is_exec_unwrapped for call in calls):diff --git a/ee/hogai/eval/sandboxed/experiments/__init__.py b/products/posthog_ai/evals/sql/__init__.pysimilarity index 100%rename from ee/hogai/eval/sandboxed/experiments/__init__.pyrename to products/posthog_ai/evals/sql/__init__.pydiff --git a/ee/hogai/eval/sandboxed/sql/eval_sql.py b/products/posthog_ai/evals/sql/eval_sql.pysimilarity index 94%rename from ee/hogai/eval/sandboxed/sql/eval_sql.pyrename to products/posthog_ai/evals/sql/eval_sql.pyindex 3e76c692406f..b23bcd13495a 100644--- a/ee/hogai/eval/sandboxed/sql/eval_sql.py+++ b/products/posthog_ai/evals/sql/eval_sql.py@@ -15,17 +15,18 @@ typed query tool — perfectly valid for the user, but not what this evalis testing. The framing is the forcing function in lieu of an agent mode.To run:- pytest ee/hogai/eval/sandboxed/sql/eval_sql.py+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_sql""""from __future__ import annotations-from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.product_analytics.scorers import INSIGHT_WRITE_TOOLS-from ee.hogai.eval.sandboxed.retrieval.scorers import SkillLoaded-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, LastToolCallNot, NoToolCall-from ee.hogai.eval.sandboxed.sql.scorers import AnswerQueryRan, SQLResultMessageAlignment, SQLSchemaAlignment+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import LastToolCallNot, NoToolCall+from products.posthog_ai.evals.product_analytics.scorers import INSIGHT_WRITE_TOOLS+from products.posthog_ai.evals.retrieval.scorers import SkillLoaded+from products.posthog_ai.evals.sql.scorers import AnswerQueryRan, SQLResultMessageAlignment, SQLSchemaAlignmentdef _sql_case(*, name: str, prompt: str, expected_sql: str) -> SandboxedEvalCase:@@ -36,7 +37,7 @@ def _sql_case(*, name: str, prompt: str, expected_sql: str) -> SandboxedEvalCase)-async def eval_sql(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+async def eval_sql(ctx: EvalContext) -> None:cases = [# Straightforward breakdowns_sql_case(@@ -380,10 +381,9 @@ WHERE properties.interests IS NOT NULL]await SandboxedPublicEval(- experiment_name=f"sandboxed-sql-{mcp_mode}",+ experiment_name="sandboxed-sql-cli",cases=cases,scorers=[- ExitCodeZero(),NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),AnswerQueryRan(name="execute_sql_called"),LastToolCallNot(@@ -394,7 +394,5 @@ WHERE properties.interests IS NOT NULLSQLSchemaAlignment(),SQLResultMessageAlignment(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/sql/scorers.py b/products/posthog_ai/evals/sql/scorers.pysimilarity index 92%rename from ee/hogai/eval/sandboxed/sql/scorers.pyrename to products/posthog_ai/evals/sql/scorers.pyindex 03db9f448732..aca83e08587b 100644--- a/ee/hogai/eval/sandboxed/sql/scorers.py+++ b/products/posthog_ai/evals/sql/scorers.py@@ -14,30 +14,19 @@ placeholder is dropped: the sandboxed run doesn't surface a schema dumpto scorers, and the judge has the user prompt + reference SQL to anchoron without it.-The shared judge plumbing (``JudgedScorer``, ``parser_for``,-``user_prompt``, alignment constants, ``JUDGE_MODEL``) is cross-imported-from ``product_analytics/scorers.py``.-That's a layering smell — they're general-purpose helpers tied to a-domain folder by accident — but with only this one new consumer, the-fix-up belongs in a follow-up refactor when a third general-purpose eval-(warehouse, system tables, persons CRUD) lands. Don't lift speculatively.+The shared judge plumbing (``JudgedScorer``, alignment constants,+``JUDGE_MODEL``) lives in ``products/posthog_ai/eval_harness/scorers/``; only the+log-extraction helpers (``parser_for``, ``user_prompt``) and the query+rubric are still cross-imported from ``product_analytics/scorers.py``."""from __future__ import annotationsfrom typing import Any-from braintrust import Score-from braintrust_core.score import Scorer--from ee.hogai.eval.sandboxed.product_analytics.scorers import (- GRADED_ALIGNMENT_CHOICE_SCORES,- GRADED_ALIGNMENT_RUBRIC,- JUDGE_MODEL,- JudgedScorer,- parser_for,- user_prompt,-)+from products.posthog_ai.eval_harness.scorers import GRADED_ALIGNMENT_CHOICE_SCORES, JUDGE_MODEL, JudgedScorer+from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer+from products.posthog_ai.evals.product_analytics.scorers import GRADED_ALIGNMENT_RUBRIC, parser_for, user_promptQUERY_SQL_TOOL_NAME = "execute-sql"_MAX_RESULT_CHARS_FOR_JUDGE = 12_000@@ -98,13 +87,7 @@ class AnswerQueryRan(Scorer):def _name(self) -> str:return self._label- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _evaluate(self, output: dict | None) -> Score:+ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})if extract_last_execute_sql_query(output) is None:diff --git a/ee/hogai/eval/sandboxed/surveys/eval_surveys.py b/products/posthog_ai/evals/surveys/eval_surveys.pysimilarity index 93%rename from ee/hogai/eval/sandboxed/surveys/eval_surveys.pyrename to products/posthog_ai/evals/surveys/eval_surveys.pyindex 7c5b07e0df61..39747e62a704 100644--- a/ee/hogai/eval/sandboxed/surveys/eval_surveys.py+++ b/products/posthog_ai/evals/surveys/eval_surveys.py@@ -6,7 +6,7 @@ asks the sandboxed agent to create surveys through the PostHog MCP``survey-create`` tool and scores the payload/result it produced.To run:- pytest ee/hogai/eval/sandboxed/surveys/eval_surveys.py+ flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_surveys""""from __future__ import annotations@@ -14,22 +14,20 @@ from __future__ import annotationsfrom collections.abc import Callablefrom typing import Any-import pytest--from products.tasks.backend.facade.agents import CustomPromptSandboxContext--from ee.hogai.eval.sandboxed.base import SandboxedPublicEval-from ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.product_analytics.scorers import INSIGHT_WRITE_TOOLS-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, NoToolCall-from ee.hogai.eval.sandboxed.seeders.survey import seed_survey_feature_flags-from ee.hogai.eval.sandboxed.surveys.scorers import (+from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import NoToolCall+from products.posthog_ai.eval_harness.seeders.survey import seed_survey_feature_flags+from products.posthog_ai.evals.product_analytics.scorers import INSIGHT_WRITE_TOOLS+from products.posthog_ai.evals.surveys.scorers import (SURVEY_FORBIDDEN_WRITE_TOOLS,SurveyCreateOutcome,SurveyCreateReturnedId,SurveyCreateSchemaAlignment,SurveyIdInFinalMessage,)+from products.tasks.backend.facade.agents import CustomPromptSandboxContextdef _survey_case(@@ -51,12 +49,7 @@ def _survey_case()-async def eval_surveys(- sandboxed_demo_data: Any,- pytestconfig: pytest.Config,- posthog_client: Any,- mcp_mode: str,-) -> None:+async def eval_surveys(ctx: EvalContext) -> None:cases: list[SandboxedEvalCase] = [_survey_case(name="survey_nps_draft",@@ -285,10 +278,9 @@ async def eval_surveys(]await SandboxedPublicEval(- experiment_name=f"sandboxed-surveys-{mcp_mode}",+ experiment_name="sandboxed-surveys-cli",cases=cases,scorers=[- ExitCodeZero(),NoToolCall(forbidden=SURVEY_FORBIDDEN_WRITE_TOOLS | INSIGHT_WRITE_TOOLS,name="no_forbidden_survey_side_effects",@@ -298,7 +290,5 @@ async def eval_surveys(SurveyCreateSchemaAlignment(),SurveyIdInFinalMessage(),],- pytestconfig=pytestconfig,- sandboxed_demo_data=sandboxed_demo_data,- posthog_client=posthog_client,+ ctx=ctx,)diff --git a/ee/hogai/eval/sandboxed/surveys/scorers.py b/products/posthog_ai/evals/surveys/scorers.pysimilarity index 86%rename from ee/hogai/eval/sandboxed/surveys/scorers.pyrename to products/posthog_ai/evals/surveys/scorers.pyindex 557fe2e4bd3c..939a50831889 100644--- a/ee/hogai/eval/sandboxed/surveys/scorers.py+++ b/products/posthog_ai/evals/surveys/scorers.py@@ -6,11 +6,9 @@ import reimport jsonfrom typing import Any-from autoevals.llm import LLMClassifier-from braintrust import Score-from braintrust_core.score import Scorer--from ee.hogai.eval.sandboxed.log_parser import LogParser, ToolCall+from products.posthog_ai.eval_harness.log_parser import LogParser, ToolCall+from products.posthog_ai.eval_harness.scorers import GRADED_ALIGNMENT_CHOICE_SCORES, JUDGE_MODEL, JudgedScorer+from products.posthog_ai.eval_harness.scorers.contract import Score, ScorerSURVEY_CREATE_TOOL_NAME = "survey-create"SURVEY_FORBIDDEN_WRITE_TOOLS = frozenset(@@ -30,15 +28,6 @@ SURVEY_FORBIDDEN_WRITE_TOOLS = frozenset(})-GRADED_ALIGNMENT_CHOICE_SCORES = {- "perfect": 1.0,- "near_perfect": 0.9,- "slightly_off": 0.75,- "somewhat_misaligned": 0.5,- "strongly_misaligned": 0.25,- "useless": 0.0,-}-GRADED_ALIGNMENT_RUBRIC = """How would you rate the alignment of the generated survey-create payload with the expected survey? Choose one:- perfect: The payload fully matches the expected survey on every material aspect.@@ -51,41 +40,17 @@ How would you rate the alignment of the generated survey-create payload with theDetails matter greatly here, especially question type, launch state, targeting, and feature-flag variant conditions.""".strip()-_JUDGE_MODEL = "gpt-5.4"_UUID_RE = re.compile(r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b")_ID_FIELD_RE = re.compile(r"\bid\s*[:=]\s*['\"]?([0-9a-fA-F-]{32,36})")-class _JudgedScorer(LLMClassifier):- async def _run_eval_async(self, output, expected=None, **kwargs):- prepared = self._prepare(output, expected)- if isinstance(prepared, Score):- return prepared- try:- return await super()._run_eval_async(prepared["output"], prepared["expected"], **kwargs)- except Exception as exc:- return Score(name=self._name(), score=0.0, metadata={"reason": f"judge error: {exc}"})-- def _run_eval_sync(self, output, expected=None, **kwargs):- prepared = self._prepare(output, expected)- if isinstance(prepared, Score):- return prepared- try:- return super()._run_eval_sync(prepared["output"], prepared["expected"], **kwargs)- except Exception as exc:- return Score(name=self._name(), score=0.0, metadata={"reason": f"judge error: {exc}"})-- def _prepare(self, output, expected) -> dict[str, Any] | Score:- raise NotImplementedError--def _parser_for(output: dict[str, Any] | None) -> LogParser | None:if not output:return Noneraw_log = output.get("raw_log")if not raw_log:return None- return LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")+ return LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")def _user_prompt(output: dict[str, Any] | None) -> str:@@ -287,13 +252,7 @@ class SurveyCreationSuccess(Scorer):def _name(self) -> str:return "survey_created"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict[str, Any] | None, expected: dict[str, Any] | None) -> Score:+ def _run_eval_sync(self, output: dict[str, Any] | None, expected: dict[str, Any] | None = None, **kwargs) -> Score:spec = _expected_spec(expected, self._name()) or {}should_create = spec.get("should_create", True)successful_call = _last_survey_create_call(output, successful=True)@@ -334,13 +293,7 @@ class SurveyCreateOutcome(Scorer):def _name(self) -> str:return "survey_create_outcome"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict[str, Any] | None, expected: dict[str, Any] | None) -> Score:+ def _run_eval_sync(self, output: dict[str, Any] | None, expected: dict[str, Any] | None = None, **kwargs) -> Score:spec = _expected_spec(expected, "survey_created") or {}should_create = spec.get("should_create", True)parser = _parser_for(output)@@ -411,13 +364,7 @@ class SurveyCreateReturnedId(Scorer):def _name(self) -> str:return "survey_create_returned_id"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict[str, Any] | None, expected: dict[str, Any] | None) -> Score:+ def _run_eval_sync(self, output: dict[str, Any] | None, expected: dict[str, Any] | None = None, **kwargs) -> Score:spec = _expected_spec(expected, "survey_created") or {}if spec.get("should_create", True) is not True:return Score(name=self._name(), score=None, metadata={"reason": "Survey ID not expected"})@@ -442,13 +389,7 @@ class SurveyIdInFinalMessage(Scorer):def _name(self) -> str:return "survey_id_in_final_message"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict[str, Any] | None, expected: dict[str, Any] | None) -> Score:+ def _run_eval_sync(self, output: dict[str, Any] | None, expected: dict[str, Any] | None = None, **kwargs) -> Score:spec = _expected_spec(expected, self._name())if spec is None:return Score(name=self._name(), score=None, metadata={"reason": "No ID-in-final-message expectation"})@@ -485,13 +426,7 @@ class SurveyCreateRejected(Scorer):def _name(self) -> str:return "survey_create_rejected"- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output, expected)-- def _evaluate(self, output: dict[str, Any] | None, expected: dict[str, Any] | None) -> Score:+ def _run_eval_sync(self, output: dict[str, Any] | None, expected: dict[str, Any] | None = None, **kwargs) -> Score:spec = _expected_spec(expected, self._name())if spec is None:return Score(name=self._name(), score=None, metadata={"reason": "No rejection expectation"})@@ -536,7 +471,7 @@ class SurveyCreateRejected(Scorer):)-class SurveyCreateSchemaAlignment(_JudgedScorer):+class SurveyCreateSchemaAlignment(JudgedScorer):"""Graded score: how well does the actual survey-create input match the expected survey?"""def _prepare(self, output, expected) -> dict[str, Any] | Score:@@ -606,7 +541,7 @@ Penalize:+ "\n\n"+ GRADED_ALIGNMENT_RUBRIC,choice_scores=GRADED_ALIGNMENT_CHOICE_SCORES,- model=_JUDGE_MODEL,+ model=JUDGE_MODEL,max_completion_tokens=512,**kwargs,)diff --git a/products/posthog_ai/package.json b/products/posthog_ai/package.jsonindex 58d80781288d..d46759ad89ec 100644--- a/products/posthog_ai/package.json+++ b/products/posthog_ai/package.json@@ -1,7 +1,7 @@{"name": "@posthog/products-posthog-ai","scripts": {- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ scripts/ -v --tb=short"+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ scripts/ eval_harness/test/ -v --tb=short"},"dependencies": {"@posthog/quill-primitives": "workspace:*",diff --git a/products/ruff.toml b/products/ruff.tomlindex 6f55978e592b..19eb765d3d0c 100644--- a/products/ruff.toml+++ b/products/ruff.toml@@ -11,6 +11,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]"**/management/**" = ["ANN"]"**/skills/**" = ["ANN"]"**/eval/**" = ["ANN"]+"**/evals/**" = ["ANN"]"**/dags/**" = ["ANN"]"**/scripts/**" = ["ANN"]"**/stats/**" = ["ANN"]@@ -44,6 +45,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]"marketing_analytics/backend/**" = ["ANN"]"messaging/backend/**" = ["ANN"]"notebooks/backend/**" = ["ANN"]+"posthog_ai/eval_harness/**" = ["ANN"]"product_analytics/backend/**" = ["ANN"]"product_tours/backend/**" = ["ANN"]"revenue_analytics/backend/**" = ["ANN"]diff --git a/products/signals/eval/conftest.py b/products/signals/eval/conftest.pyindex d2b9f09d50c2..96ebd77f077c 100644--- a/products/signals/eval/conftest.py+++ b/products/signals/eval/conftest.py@@ -14,6 +14,7 @@ from posthoganalytics.ai.openai import AsyncOpenAIfrom posthog.llm.gateway_client import get_async_anthropic_gateway_clientfrom posthog.models import Organization, Team+# This eval runs via bare pytest (no hogli), so the conftest owns loading repo-root .env.load_dotenv(Path(__file__).resolve().parents[3] / ".env")# Initialize posthoganalytics default_client so the LLM wrapper (which requires it) worksdiff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.pyindex 6cd771818d24..f616a1d19d8e 100644--- a/products/tasks/backend/logic/services/docker_sandbox.py+++ b/products/tasks/backend/logic/services/docker_sandbox.py@@ -2,11 +2,13 @@ from __future__ import annotationsimport osimport json+import timeimport uuidimport shleximport base64import shutilimport socket+import hashlibimport loggingimport tempfileimport subprocess@@ -64,6 +66,11 @@ DEFAULT_IMAGE_NAME = "posthog-sandbox-base"NOTEBOOK_IMAGE_NAME = "posthog-sandbox-notebook"PI_IMAGE_NAME = "posthog-sandbox-pi"STREAMLIT_IMAGE_NAME = "posthog-sandbox-streamlit"++# Stamped on the base image so a later run can tell whether it must rebuild: the sha of+# the Dockerfile that produced it, and the @posthog/agent version baked into the npm layer.+_DOCKERFILE_SHA_LABEL = "com.posthog.sandbox.dockerfile-sha"+_AGENT_VERSION_LABEL = "com.posthog.sandbox.agent-version"AGENT_SERVER_PORT = 47821 # Arbitrary high port unlikely to conflict with dev servers# Streamlit sandboxes expose their auth proxy (not the agent-server) on this port; the# host-published port maps to it so connect_info can reach the app across processes.@@ -196,11 +203,19 @@ class DockerSandbox(SandboxBase):image_name: str,dockerfile_path: str,build_args: dict[str, str] | None = None,+ *,+ labels: dict[str, str] | None = None,+ force: bool = False,) -> None:- """Build a sandbox image if it doesn't exist."""- result = DockerSandbox._run(["docker", "images", "-q", image_name])- if result.stdout.strip():- return+ """Build a sandbox image if it doesn't exist, or unconditionally when ``force``.++ The image is always stamped with the sha256 of the Dockerfile bytes (plus any+ caller-supplied ``labels``) so a later run can detect a stale image and rebuild.+ """+ if not force:+ result = DockerSandbox._run(["docker", "images", "-q", image_name])+ if result.stdout.strip():+ returnlogger.info(f"Building {image_name} image (this may take a few minutes)...")@@ -211,6 +226,10 @@ class DockerSandbox(SandboxBase):# hogli build:skills.LocalSkillsCache().ensure_built()+ with open(dockerfile_path, "rb") as dockerfile:+ dockerfile_sha = hashlib.sha256(dockerfile.read()).hexdigest()+ all_labels = {_DOCKERFILE_SHA_LABEL: dockerfile_sha, **(labels or {})}+argv = ["docker","build",@@ -221,6 +240,8 @@ class DockerSandbox(SandboxBase):]for key, value in (build_args or {}).items():argv.extend(["--build-arg", f"{key}={value}"])+ for key, value in all_labels.items():+ argv.extend(["--label", f"{key}={value}"])argv.append(str(settings.BASE_DIR))DockerSandbox._run(argv, check=True)@@ -287,9 +308,7 @@ class DockerSandbox(SandboxBase):DockerSandbox._build_image_if_needed(STREAMLIT_IMAGE_NAME, dockerfile_path)return STREAMLIT_IMAGE_NAME- dockerfile_path = os.path.join(- settings.BASE_DIR, "products/tasks/backend/sandbox/images/Dockerfile.sandbox-base"- )+ dockerfile_path = _base_dockerfile_path()DockerSandbox._build_image_if_needed(DEFAULT_IMAGE_NAME, dockerfile_path)if template == SandboxTemplate.PI_BASE:@@ -1110,3 +1129,110 @@ class DockerSandbox(SandboxBase):@propertydef name(self) -> str:return self.config.name+++def _base_dockerfile_path() -> str:+ return os.path.join(settings.BASE_DIR, "products/tasks/backend/sandbox/images/Dockerfile.sandbox-base")+++def _none_if_blank(value: str) -> str | None:+ """Normalize a docker inspect label value: a missing label prints as ``<no value>``."""+ value = value.strip()+ if not value or value == "<no value>":+ return None+ return value+++def _resolve_latest_agent_version() -> str | None:+ """Latest published @posthog/agent version, or ``None`` if npm is unavailable.++ Any failure (npm missing, nonzero exit, timeout) resolves to ``None`` so the caller+ can fall back to reusing the existing image rather than failing the whole run.+ """+ try:+ result = subprocess.run(+ ["npm", "view", "@posthog/agent", "version"],+ capture_output=True,+ text=True,+ timeout=15,+ )+ except Exception:+ return None+ if result.returncode != 0:+ return None+ return result.stdout.strip() or None+++def ensure_fresh_base_image(*, force: bool = False) -> None:+ """Rebuild ``posthog-sandbox-base`` when it is stale, otherwise reuse it.++ Stale means any of: ``force``; the image is missing; the Dockerfile changed since the+ image was built; or @posthog/agent published a newer version than the one baked in.+ This is the only place that reaches out to npm.+ """+ dockerfile_path = _base_dockerfile_path()+ with open(dockerfile_path, "rb") as dockerfile:+ current_dockerfile_sha = hashlib.sha256(dockerfile.read()).hexdigest()++ latest = _resolve_latest_agent_version()++ # A nonzero exit means the image is missing; otherwise the two labels come back+ # tab-separated (or "<no value>" for a label the image predates).+ inspect = DockerSandbox._run(+ [+ "docker",+ "image",+ "inspect",+ DEFAULT_IMAGE_NAME,+ "-f",+ f'{{{{index .Config.Labels "{_DOCKERFILE_SHA_LABEL}"}}}}\t'+ f'{{{{index .Config.Labels "{_AGENT_VERSION_LABEL}"}}}}',+ ]+ )+ image_exists = inspect.returncode == 0+ image_dockerfile_sha: str | None = None+ image_agent_version: str | None = None+ if image_exists:+ parts = inspect.stdout.strip().split("\t")+ image_dockerfile_sha = _none_if_blank(parts[0]) if len(parts) > 0 else None+ image_agent_version = _none_if_blank(parts[1]) if len(parts) > 1 else None++ dockerfile_changed = image_dockerfile_sha is None or image_dockerfile_sha != current_dockerfile_sha+ agent_stale = latest is not None and (+ image_agent_version is None or image_agent_version == "unknown" or image_agent_version != latest+ )++ if force:+ reason = "forced"+ elif not image_exists:+ reason = "image missing"+ elif dockerfile_changed:+ reason = "dockerfile changed"+ elif agent_stale:+ reason = f"stale agent version (have {image_agent_version!r}, latest {latest!r})"+ else:+ reason = None++ if reason is None:+ if latest is None:+ # npm unreachable but the on-disk image still matches the Dockerfile — the best+ # we can do offline is trust it rather than fail or force a needless rebuild.+ logger.warning(+ "could not check @posthog/agent freshness (npm unreachable); reusing existing posthog-sandbox-base"+ )+ else:+ logger.info("posthog-sandbox-base is up to date (agent %s); reusing existing image", latest)+ return++ # Passing the agent version as COMMIT_HASH lets docker's layer cache no-op the npm+ # install layer when the version is unchanged, and re-run exactly that layer onward+ # when it changed. When we can't resolve a version, fall back to a unique cache-bust.+ cache_bust = latest or f"force-{int(time.time())}"+ logger.info("Rebuilding posthog-sandbox-base: %s", reason)+ DockerSandbox._build_image_if_needed(+ DEFAULT_IMAGE_NAME,+ dockerfile_path,+ build_args={"COMMIT_HASH": cache_bust},+ labels={_AGENT_VERSION_LABEL: latest or "unknown"},+ force=True,+ )diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex 5d0aff13623e..8a647577432e 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -479,6 +479,19 @@ def _get_modal_docker_sandbox_class() -> SandboxClass:return ModalDockerSandbox+def _get_modal_evals_sandbox_class() -> SandboxClass:+ """Modal sandbox isolated from both production and local development apps."""+ if not (settings.DEBUG or settings.TEST):+ raise RuntimeError("MODAL_EVALS sandbox is for evals only and requires DEBUG=1 or TEST=1.")+ from .modal_sandbox import ModalSandbox++ class ModalEvalsSandbox(ModalSandbox):+ DEFAULT_APP_NAME = "posthog-sandbox-evals"+ NOTEBOOK_APP_NAME = "posthog-sandbox-evals"++ return ModalEvalsSandbox++def get_sandbox_class() -> SandboxClass:provider = getattr(settings, "SANDBOX_PROVIDER", None)@@ -488,6 +501,9 @@ def get_sandbox_class() -> SandboxClass:if provider and provider.upper() == "MODAL_DOCKER":return _get_modal_docker_sandbox_class()+ if provider and provider.upper() == "MODAL_EVALS":+ return _get_modal_evals_sandbox_class()+# Default to Modal everywherefrom .modal_sandbox import ModalSandbox@@ -501,6 +517,8 @@ def get_sandbox_class_for_backend(backend: str) -> SandboxClass:return ModalSandboxif backend in ("modal_docker", "MODAL_DOCKER"):return _get_modal_docker_sandbox_class()+ if backend in ("modal_evals", "MODAL_EVALS"):+ return _get_modal_evals_sandbox_class()if backend == "docker":return _get_docker_sandbox_class()raise RuntimeError(f"Unsupported sandbox backend: {backend}")@@ -513,7 +531,7 @@ else:def __getattr__(name: str) -> object:# Resolve `Sandbox` lazily. Computing it at import time calls get_sandbox_class(),- # which for the docker / modal_docker providers imports a sibling module+ # which for the docker / local Modal providers imports a sibling module# (docker_sandbox / modal_sandbox). When that sibling is the first of the pair to be# imported (e.g. test_docker_sandbox.py imports docker_sandbox, which imports this# module), the eager call reaches back into the still-initializing sibling and failsdiff --git a/products/tasks/backend/logic/services/test_docker_sandbox.py b/products/tasks/backend/logic/services/test_docker_sandbox.pyindex 16b76c25edb4..bda25d8240de 100644--- a/products/tasks/backend/logic/services/test_docker_sandbox.py+++ b/products/tasks/backend/logic/services/test_docker_sandbox.py@@ -71,6 +71,16 @@ class TestSandboxProviderGuard:else:assert get_sandbox_class() is DockerSandbox+ @patch("products.tasks.backend.logic.services.sandbox.settings")+ def test_modal_evals_provider_uses_dedicated_app(self, mock_settings):+ mock_settings.SANDBOX_PROVIDER = "MODAL_EVALS"+ mock_settings.DEBUG = False+ mock_settings.TEST = True++ sandbox_class = get_sandbox_class()++ assert getattr(sandbox_class, "DEFAULT_APP_NAME", None) == "posthog-sandbox-evals"+@pytest.mark.skipif(is_ci() or not docker_available(), reason="Docker sandbox tests only run locally, not in CI")class TestSandboxFactory:diff --git a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-baseindex 8bab6e2d85ee..52d03d66355a 100644--- a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base+++ b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base@@ -26,6 +26,8 @@ RUN apt-get update && \# Build toolsbuild-essential \pkg-config \+ # Loader for the musl-linked @openai/codex binary bundled with @posthog/agent+ musl \# Languages and runtimespython3 \python3-pip \diff --git a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.pyindex d96080410651..55c943aff3e8 100644--- a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py+++ b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py@@ -57,7 +57,7 @@ def _get_image_source_label(if provider == "docker":return "local Docker sandbox image"- if provider and provider.upper() == "MODAL_DOCKER":+ if provider and provider.upper() in ("MODAL_DOCKER", "MODAL_EVALS"):return "local Modal Dockerfile build"if settings.DEBUG and not has_repo:diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 5ed5ce16f6d0..a3f3b678c1a9 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -199,7 +199,7 @@ def _get_image_source_label(if provider == "docker":return "docker_base_image", "local Docker sandbox image"- if provider and provider.upper() == "MODAL_DOCKER":+ if provider and provider.upper() in ("MODAL_DOCKER", "MODAL_EVALS"):return "modal_local_build", "local Modal Dockerfile build"if settings.DEBUG and not has_repo:diff --git a/tach.toml b/tach.tomlindex 328b0cfa16e1..90b95e91156a 100644--- a/tach.toml+++ b/tach.toml@@ -6,6 +6,11 @@ exclude = ["**/*egg-info","docs","tests",+ # Eval trees are dev/CI-only tooling (same class as `tests`): the harness orchestrates+ # many products by design, and product-owned suites under products/*/evals import the+ # harness contracts, so neither fits the production dependency graph.+ "products/posthog_ai/eval_harness",+ "products/*/evals",]source_roots = [".",diff --git a/uv.lock b/uv.lockindex ec0780981194..fc8aaa5e3b31 100644--- a/uv.lock+++ b/uv.lock@@ -4644,7 +4644,7 @@ name = "nvidia-cudnn-cu12"version = "9.10.2.21"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "nvidia-cublas-cu12", marker = "platform_machine != 's390x' and sys_platform != 'emscripten'" },+ { name = "nvidia-cublas-cu12" },]wheels = [{ url = "https://files.pythonhosted.org/packages/ba/51/e123d997aa098c61d029f76663dedbfb9bc8dcf8c60cbd6adbe42f76d049/nvidia_cudnn_cu12-9.10.2.21-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:949452be657fa16687d0930933f032835951ef0892b37d2d53824d1a84dc97a8", size = 706758467, upload-time = "2025-06-06T21:54:08.597Z" },@@ -4655,7 +4655,7 @@ name = "nvidia-cufft-cu12"version = "11.3.3.83"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "nvidia-nvjitlink-cu12", marker = "platform_machine != 's390x' and sys_platform != 'emscripten'" },+ { name = "nvidia-nvjitlink-cu12" },]wheels = [{ url = "https://files.pythonhosted.org/packages/1f/13/ee4e00f30e676b66ae65b4f08cb5bcbb8392c03f54f2d5413ea99a5d1c80/nvidia_cufft_cu12-11.3.3.83-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4d2dd21ec0b88cf61b62e6b43564355e5222e4a3fb394cac0db101f2dd0d4f74", size = 193118695, upload-time = "2025-03-07T01:45:27.821Z" },@@ -4682,9 +4682,9 @@ name = "nvidia-cusolver-cu12"version = "11.7.3.90"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "nvidia-cublas-cu12", marker = "platform_machine != 's390x' and sys_platform != 'emscripten'" },- { name = "nvidia-cusparse-cu12", marker = "platform_machine != 's390x' and sys_platform != 'emscripten'" },- { name = "nvidia-nvjitlink-cu12", marker = "platform_machine != 's390x' and sys_platform != 'emscripten'" },+ { name = "nvidia-cublas-cu12" },+ { name = "nvidia-cusparse-cu12" },+ { name = "nvidia-nvjitlink-cu12" },]wheels = [{ url = "https://files.pythonhosted.org/packages/85/48/9a13d2975803e8cf2777d5ed57b87a0b6ca2cc795f9a4f59796a910bfb80/nvidia_cusolver_cu12-11.7.3.90-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:4376c11ad263152bd50ea295c05370360776f8c3427b30991df774f9fb26c450", size = 267506905, upload-time = "2025-03-07T01:47:16.273Z" },@@ -4695,7 +4695,7 @@ name = "nvidia-cusparse-cu12"version = "12.5.8.93"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "nvidia-nvjitlink-cu12", marker = "platform_machine != 's390x' and sys_platform != 'emscripten'" },+ { name = "nvidia-nvjitlink-cu12" },]wheels = [{ url = "https://files.pythonhosted.org/packages/c2/f5/e1854cb2f2bcd4280c44736c93550cc300ff4b8c95ebe370d0aa7d2b473d/nvidia_cusparse_cu12-12.5.8.93-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1ec05d76bbbd8b61b06a80e1eaf8cf4959c3d4ce8e711b65ebd0443bb0ebb13b", size = 288216466, upload-time = "2025-03-07T01:48:13.779Z" },@@ -5354,7 +5354,7 @@ name = "pexpect"version = "4.9.0"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "ptyprocess", marker = "sys_platform != 'emscripten'" },+ { name = "ptyprocess" },]sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" }wheels = [@@ -7599,7 +7599,7 @@ name = "shadowcopy"version = "0.0.4"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "wmi", marker = "sys_platform != 'emscripten'" },+ { name = "wmi" },]sdist = { url = "https://files.pythonhosted.org/packages/12/44/c00420a3b7bcdf830529b933392b566c876a4944a24f31e126eb6fd28647/shadowcopy-0.0.4.tar.gz", hash = "sha256:ed89817dda065f893607a04c0b7d6b3b34c3507a4711f441111a4bcb1b1826c0", size = 4138, upload-time = "2023-07-08T00:01:35.266Z" }wheels = [@@ -8033,7 +8033,7 @@ name = "tbb"version = "2022.3.1"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "tcmlib", marker = "platform_machine != 's390x' and sys_platform != 'emscripten'" },+ { name = "tcmlib" },]wheels = [{ url = "https://files.pythonhosted.org/packages/08/59/8d381a2cfe8d36c4f4ff9f94769ff2809bfc16014d888360b0e24c7e5c6b/tbb-2022.3.1-py2.py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:534c089eca6bcf148408684c156229d5f09c01d323b685b15739f41985b529d7", size = 4178630, upload-time = "2026-01-22T05:30:20.589Z" },@@ -8415,7 +8415,7 @@ name = "triton"version = "3.4.0"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "setuptools", marker = "platform_machine != 's390x' and sys_platform != 'emscripten'" },+ { name = "setuptools" },]wheels = [{ url = "https://files.pythonhosted.org/packages/30/7b/0a685684ed5322d2af0bddefed7906674f67974aa88b0fae6e82e3b766f6/triton-3.4.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00be2964616f4c619193cb0d1b29a99bd4b001d7dc333816073f92cf2a8ccdeb", size = 155569223, upload-time = "2025-07-30T19:58:44.017Z" },@@ -9122,7 +9122,7 @@ name = "wmi"version = "1.5.1"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "pywin32", marker = "sys_platform != 'emscripten'" },+ { name = "pywin32" },]sdist = { url = "https://files.pythonhosted.org/packages/d4/66/6364deb0a03415f96c66803d8c4379f808f2401da3bdb183348487b10510/WMI-1.5.1.tar.gz", hash = "sha256:b6a6be5711b1b6c8d55bda7a8befd75c48c12b770b9d227d31c1737dbf0d40a6", size = 26254, upload-time = "2020-04-28T08:22:58.096Z" }wheels = [