Skip to content

: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.

chore(hogli): steer cloud task agents to scoped, quiet test runs (#90878)

Alessandro Pogliaghi6ea5262c33bb
diff --git a/AGENTS.md b/AGENTS.md
index 44e5f125ff2e..a5118924dee2 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -31,6 +31,7 @@
- Cloud task VMs (prebaked dev-stack image): run `bootstrap-dev-stack` first (restores compose host aliases, starts dockerd), then `uv sync`, `source .venv/bin/activate`, `hogli start -y -d`, and `hogli wait` (the detached start returns while the stack is still booting; `hogli wait` blocks until every process is ready) — always detached: the sandbox has no TTY, and phrocs under a pseudo-TTY balloons in memory until OOM-killed
- Cloud task VMs: on user-created runs the backend usually starts the stack itself. While it does, `hogli start` exits without starting anything. Poll `/tmp/posthog-preview/status.json` until `state` is `ready` or `failed`. On `ready`, run `hogli wait`; it reports `not reachable` until the backend reaches the phrocs step, so retry it rather than forcing a second start. On `failed` (the backend does not retry), start the stack yourself with `hogli start -y -d`
- Cloud task VMs, frontend work: `pnpm install --frozen-lockfile --prefer-offline` links from the prebaked pnpm store, and Playwright Chromium is preinstalled; product/Storybook builds still run from source
+ - Cloud task VMs, tests: scope every run to what you changed, with `hogli test --changed` or the test files that cover the touched code. Run a whole module, package, or repo-wide suite at most once, right before you push, and only for a cross-cutting change. CI runs the full matrix; repeating it in the sandbox costs minutes per run and floods the context with output. In a sandbox `hogli test` runs pytest with `-q` (set `HOGLI_TEST_VERBOSE=1` to stream prints)
- OpenAPI/types: `hogli build:openapi` (regenerate after changing serializers/viewsets)
- LSP: Pyright is configured against the flox venv. Prefer LSP (`goToDefinition`, `findReferences`, `hover`) over grep when navigating or refactoring Python code.
- Dev experience feedback: `hogli devex:feedback "<message>"` sends feedback about repo tooling — hogli, the dev stack, tests, CI, migrations, this setup — straight to the devex team as a `hogli_feedback` event (add `-c bug|idea|praise|question`).
diff --git a/tools/hogli-commands/hogli_commands/test_runner.py b/tools/hogli-commands/hogli_commands/test_runner.py
index c7048d1a6b92..7f9e595f35fb 100644
--- a/tools/hogli-commands/hogli_commands/test_runner.py
+++ b/tools/hogli-commands/hogli_commands/test_runner.py
@@ -6,6 +6,7 @@ Detects the test type from a file path and dispatches to the correct runner
from __future__ import annotations
+import os
import json
import shlex
import tomllib
@@ -135,6 +136,37 @@ class TestRunConfig:
return self.env or None
+_DIRECTORY_HINT_MIN_FILES = 10
+_PYTEST_VERBOSITY_ARGS = {"-q", "--quiet", "-v", "-vv", "-vvv", "--verbose", "-s", "--capture"}
+
+
+def _in_cloud_task_sandbox() -> bool:
+ return bool(os.environ.get("POSTHOG_TASK_RUN_ID")) and not os.environ.get("HOGLI_TEST_VERBOSE")
+
+
+def _quiet_pytest_in_cloud_sandbox(command: list[str], extra_args: list[str]) -> list[str]:
+ """A cloud task agent reads pytest output as tokens, so in a sandbox the default swaps
+ ``-s`` (stream every print) for ``-q`` unless the agent chose a verbosity."""
+ if command[:1] != ["pytest"] or not _in_cloud_task_sandbox():
+ return command
+ if any(arg.split("=", 1)[0] in _PYTEST_VERBOSITY_ARGS for arg in extra_args):
+ return command
+ return ["-q" if arg == "-s" else arg for arg in command]
+
+
+def _hint_scoped_run(dir_path: str) -> None:
+ if not _in_cloud_task_sandbox():
+ return
+ file_count = len(_find_test_files(dir_path))
+ if file_count < _DIRECTORY_HINT_MIN_FILES:
+ return
+ click.secho(
+ f"Running every test under {dir_path} ({file_count} files). For changes on this branch, "
+ "`hogli test --changed` or a single test file is faster and quieter.",
+ fg="yellow",
+ )
+
+
def _python_env() -> dict[str, str]:
"""Environment variables needed for Python test runs."""
env: dict[str, str] = {"REDIS_URL": "redis:///"}
@@ -640,7 +672,7 @@ def _run_grouped(detected: list[tuple[str, TestRunConfig]], extra_args: list[str
cfg = entries[0][1]
command = cfg.command[:-1] + [f for f, _ in entries]
click.secho(f"Running {len(entries)} Python test file(s)...", fg="cyan")
- _run(command + extra_args, env=cfg.env_or_none, cwd=cfg.cwd)
+ _run(_quiet_pytest_in_cloud_sandbox(command, extra_args) + extra_args, env=cfg.env_or_none, cwd=cfg.cwd)
elif test_type == "jest":
# Sub-group by package so each pnpm --filter is correct
by_package: dict[str, tuple[TestRunConfig, list[str]]] = {}
@@ -787,6 +819,7 @@ def test_command(ctx: click.Context, file_path: str | None, changed: bool, watch
# For directories, check if multiple test types are present and run each group.
if abs_path.is_dir():
+ _hint_scoped_run(resolved)
multi_type = _check_multi_type(resolved)
if multi_type is not None:
detected, types = multi_type
@@ -799,4 +832,7 @@ def test_command(ctx: click.Context, file_path: str | None, changed: bool, watch
config = detect_test_type(resolved)
click.secho(f"Detected: {config.description}", fg="cyan")
- _run(config.command + list(ctx.args), env=config.env_or_none, cwd=config.cwd)
+ extra_args = list(ctx.args)
+ _run(
+ _quiet_pytest_in_cloud_sandbox(config.command, extra_args) + extra_args, env=config.env_or_none, cwd=config.cwd
+ )
diff --git a/tools/hogli-commands/hogli_commands/tests/test_test_runner.py b/tools/hogli-commands/hogli_commands/tests/test_test_runner.py
index 53db6d20acd9..321a0cd7956f 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_test_runner.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_test_runner.py
@@ -15,7 +15,9 @@ from hogli_commands.test_runner import (
_detect_all,
_find_test_files_for_source,
_get_changed_files,
+ _hint_scoped_run,
_is_test_file,
+ _quiet_pytest_in_cloud_sandbox,
_resolve_to_repo_relative,
_run_changed,
_run_grouped,
@@ -571,3 +573,54 @@ def _get_repo_root():
from hogli.manifest import REPO_ROOT
return REPO_ROOT
+
+
+class TestScopedRunHints:
+ @pytest.mark.parametrize(
+ "command, extra_args, env, expected",
+ [
+ (["pytest", "-s", "a.py"], [], {"POSTHOG_TASK_RUN_ID": "run-1"}, ["pytest", "-q", "a.py"]),
+ (["pytest", "-s", "a.py"], [], {}, ["pytest", "-s", "a.py"]),
+ (
+ ["pytest", "-s", "a.py"],
+ [],
+ {"POSTHOG_TASK_RUN_ID": "run-1", "HOGLI_TEST_VERBOSE": "1"},
+ ["pytest", "-s", "a.py"],
+ ),
+ (["pytest", "-s", "a.py"], ["-vv"], {"POSTHOG_TASK_RUN_ID": "run-1"}, ["pytest", "-s", "a.py"]),
+ (["pytest", "-s", "a.py"], ["--capture=no"], {"POSTHOG_TASK_RUN_ID": "run-1"}, ["pytest", "-s", "a.py"]),
+ (
+ ["pnpm", "exec", "jest", "a.test.ts"],
+ [],
+ {"POSTHOG_TASK_RUN_ID": "run-1"},
+ ["pnpm", "exec", "jest", "a.test.ts"],
+ ),
+ ],
+ )
+ def test_pytest_is_quiet_only_in_a_cloud_sandbox(self, monkeypatch, command, extra_args, env, expected):
+ monkeypatch.delenv("POSTHOG_TASK_RUN_ID", raising=False)
+ monkeypatch.delenv("HOGLI_TEST_VERBOSE", raising=False)
+ for key, value in env.items():
+ monkeypatch.setenv(key, value)
+
+ assert _quiet_pytest_in_cloud_sandbox(command, extra_args) == expected
+
+ @pytest.mark.parametrize(
+ "file_count, in_sandbox, hinted",
+ [(3, True, False), (10, True, True), (10, False, False)],
+ )
+ def test_directory_runs_in_a_sandbox_suggest_a_scoped_run(
+ self, monkeypatch, capsys, file_count, in_sandbox, hinted
+ ):
+ monkeypatch.delenv("HOGLI_TEST_VERBOSE", raising=False)
+ if in_sandbox:
+ monkeypatch.setenv("POSTHOG_TASK_RUN_ID", "run-1")
+ else:
+ monkeypatch.delenv("POSTHOG_TASK_RUN_ID", raising=False)
+ monkeypatch.setattr(
+ "hogli_commands.test_runner._find_test_files", lambda _path: [f"t{i}.py" for i in range(file_count)]
+ )
+
+ _hint_scoped_run("posthog/api/test")
+
+ assert ("hogli test --changed" in capsys.readouterr().out) is hinted