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.

fix(signals): move trial state and checks out of tasks (#114001)

Alex Lebedev3c683bf2c0e9
diff --git a/docs/internal/scout-online-evals-devbox.md b/docs/internal/scout-online-evals-devbox.md
index 210d9dfa7884..8e005acc48d8 100644
--- a/docs/internal/scout-online-evals-devbox.md
+++ b/docs/internal/scout-online-evals-devbox.md
@@ -34,7 +34,7 @@ The backend and scout orchestration worker use their existing `AI_GATEWAY_URL` a
API-side token calls bypass environment proxies, matching the other service gateway clients. Sandbox token calls keep their existing proxy behavior.
Enable `SCOUT_LIVE_TRIALS_PRIVATE_CAPTURE` only after confirming query/task telemetry and warehouse replicas do not expose trial content to the inspected project. The gateway must acknowledge capture suppression when minting tokens.
This setting also installs the private-trial analytics filter when backend and worker processes start. Leave it enabled while saved trial data remains accessible, even after disabling new launches or the `scout-trials` flag. Deployments without this setting keep their existing analytics callbacks.
-Keep the worker and backend on the same code revision; use `TEMPORAL_DISABLE_HOT_RELOAD=1` during paid runs.
+Deploy the backend, scout orchestration worker and Tasks worker from the same code revision before enabling trials; use `TEMPORAL_DISABLE_HOT_RELOAD=1` during paid runs. The scout worker uses the video-export queue. The Tasks worker provisions the sandboxes. Removing the old Tasks validation does not change the ordinary judge path, but new scout launches require the updated Tasks worker.
Revoke or expire private tokens before rolling the gateway back to a version without private capture support.
## Run one trial
@@ -53,12 +53,16 @@ Suggestion generation captures the complete scout instructions and reference fil
Variants and retries share a saved copy of the project's scout memory, notes and recent scout runs. This starting context lives in private object storage and can exceed the 16 MiB limit on launch settings without being shortened.
+Each trial scout stores its own memory changes and reports in a separate `trial_state` field on its Signals scout-run record. The small trial marker stays in metadata so ordinary history queries can exclude trials without reading their documents. Tasks run state contains execution settings and token bindings, not trial documents. Signals verifies the sandbox token belongs to that exact run before serving private context. Tasks grants the restricted scout credential only the necessary log, summary and lifecycle writes for its own run; it cannot change another task or steer a trial. Ordinary scout responses omit the private state.
+
Each completed scout run gets its own judge sandbox. The judge reads the saved rubric and searches attached copies of the complete rubric reference, run log, reports, summary, candidate instructions and starting context. These files live in private object storage; Temporal receives only their identifiers. Evidence larger than 128 MiB is refused explicitly instead of being silently shortened.
Signals checks the operator's access, source run and saved evidence before attaching files and dispatching the judge through the existing internal Tasks path used by rubric generation. Queued judges do not repeat Signals-specific staff, skill or source-run checks at sandbox startup. Ordinary account and project permissions still apply when downloading evidence, and Signals checks operator access again before publishing the report.
Judges use ordinary Tasks permissions and logging rather than the scout runs' private credentials and capture suppression. Other sandboxes acting as the same operator in the same project can read judge prompts and attached evidence through the Tasks API.
+Scout sandboxes keep private gateway capture and exclude shared context-layer inputs. Tasks no longer calls Signals to interpret trial documents or judge credentials. Shared dispatch preparation, file attachments and budget-stop handling remain unchanged.
+
The judge has no live project tools, external MCP connections or repository credentials. Its run disables live context, so the Tasks worker neither mounts the current wiki nor adds Store skill descriptions. Internal Tasks also exclude project and personal instructions. A retry to correct its JSON response uses the same sandbox and keeps these inputs disabled. Deploy the Tasks worker's support for this run setting before starting new judges.
It returns one verdict per rubric check, with quotes checked against the original saved files. Missing evidence gives an unknown verdict. A judge failure is shown separately from a failed rubric check, and incomplete results cannot win. Judging has a 15-minute runtime limit per run; saved results never rerun the judge when viewed.
diff --git a/posthog/api/test/test_comments.py b/posthog/api/test/test_comments.py
index 0afd65370fee..6ab05f5eea38 100644
--- a/posthog/api/test/test_comments.py
+++ b/posthog/api/test/test_comments.py
@@ -707,11 +707,11 @@ class TestComments(APIBaseTest, QueryMatchingTest):
("unbound_trial", "scout-trial:", "unbound", False, False),
("sibling_judge", "scout-trial-judge:", "other", False, False),
("ordinary_task", "", "other", False, True),
- ("judge_token", "scout-trial-judge:", "own", True, False),
+ ("internal_only_token", "scout-trial-judge:", "own", True, False),
]
)
def test_generic_task_comment_reads_respect_trial_task_binding(
- self, _name: str, origin_prefix: str, binding: str, judge_token: bool, visible: bool
+ self, _name: str, origin_prefix: str, binding: str, internal_only_token: bool, visible: bool
) -> None:
task = self._task_artifact_target(public=False)
if origin_prefix:
@@ -748,7 +748,9 @@ class TestComments(APIBaseTest, QueryMatchingTest):
bound_task_id = task.id if binding == "own" else other_task.id if binding == "other" else None
client = self._sandbox_task_comment_client(
task_id=bound_task_id,
- scopes=" ".join(resolve_scopes("signals_scout_judge" if judge_token else "signals_scout_experiment")),
+ scopes="scout_experiment_internal:read"
+ if internal_only_token
+ else " ".join(resolve_scopes("signals_scout_experiment")),
)
listed = client.get(url, query)
@@ -756,7 +758,7 @@ class TestComments(APIBaseTest, QueryMatchingTest):
retrieved = client.get(f"{url}/{root.id}")
thread = client.get(f"{url}/{root.id}/thread")
- if judge_token:
+ if internal_only_token:
assert [response.status_code for response in (listed, counted, retrieved, thread)] == [
status.HTTP_403_FORBIDDEN
] * 4
diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.py
index 950577d3b9b6..d874b1ce7592 100644
--- a/posthog/temporal/oauth.py
+++ b/posthog/temporal/oauth.py
@@ -116,7 +116,6 @@ McpScopePreset = Literal[
"signals_scout",
"signals_scout_reports",
"signals_scout_experiment",
- "signals_scout_judge",
"signals_research",
"signals_implementation",
]
@@ -341,7 +340,6 @@ MCP_SCOPE_PRESETS = (
"signals_scout",
"signals_scout_reports",
"signals_scout_experiment",
- "signals_scout_judge",
"signals_research",
"signals_implementation",
)
@@ -446,8 +444,6 @@ def resolve_scopes(
# `RESEARCH_WITHHELD_SCOPES` for why `task:write` comes back out.
reads = [scope for scope in (*MCP_READ_SCOPES, *internal) if scope not in RESEARCH_WITHHELD_SCOPES]
resolved = [*reads, *scratchpad]
- elif scopes == "signals_scout_judge":
- resolved = ["scout_experiment_internal:read"] if include_internal_scopes else []
elif scopes == "signals_scout_experiment":
# Trials use a separate private Go token; their tool credential must not reach the legacy gateway.
reads = [
diff --git a/posthog/temporal/tests/test_oauth.py b/posthog/temporal/tests/test_oauth.py
index f26ce570b478..43f9fdfd95f4 100644
--- a/posthog/temporal/tests/test_oauth.py
+++ b/posthog/temporal/tests/test_oauth.py
@@ -54,10 +54,6 @@ class TestResolveScopes(SimpleTestCase):
def test_read_only_is_default(self) -> None:
assert resolve_scopes() == resolve_scopes("read_only")
- def test_scout_judge_has_no_live_project_or_shared_internal_scopes(self) -> None:
- assert resolve_scopes("signals_scout_judge") == ["scout_experiment_internal:read"]
- assert resolve_scopes("signals_scout_judge", include_internal_scopes=False) == []
-
def test_full_preset(self) -> None:
result = resolve_scopes("full")
assert set(result) == set(MCP_READ_SCOPES + MCP_WRITE_SCOPES + INTERNAL_SCOPES + [CONTEXT_LAYER_INTERNAL_SCOPE])
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index ea12672361ea..229465a738e3 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -88,6 +88,7 @@ from products.signals.backend.signal_metadata import SourceSliceSignalStats, fet
# Re-exported for external products (tasks presentation catches it around facade create_task).
from products.signals.backend.task_run_artefacts import ReportTaskCapExceeded as ReportTaskCapExceeded
+from products.tasks.backend.facade.access import is_sandbox_run_request
if TYPE_CHECKING:
from products.tasks.backend.facade.repo_selection import RepoSelectionResult
@@ -98,100 +99,6 @@ MAX_SIGNAL_DESCRIPTION_TOKENS = 8000
MAX_SIGNAL_REMEDIATION_TOKENS = 16000
-def is_scout_trial_task(*, team_id: int, task_id: uuid.UUID) -> bool:
- return (
- SignalScoutRun.objects.for_team(team_id)
- .filter(task_run__task_id=task_id, metadata__scout_trial__version=1)
- .exists()
- )
-
-
-def is_scout_trial_task_run(*, team_id: int, task_id: uuid.UUID, task_run_id: uuid.UUID) -> bool:
- run = (
- SignalScoutRun.objects.for_team(team_id)
- .select_related("task_run__task")
- .filter(task_run_id=task_run_id, task_run__task_id=task_id, metadata__scout_trial__version=1)
- .first()
- )
- if run is None:
- return False
- marker = (run.metadata or {})["scout_trial"]
- launch_id = marker.get("launch_id")
- return (
- isinstance(launch_id, str)
- and run.task_run.task.origin_product == "signals_scout"
- and run.task_run.task.origin_key == f"scout-trial:{launch_id}"
- and (run.task_run.state or {}).get("scout_trial") == marker
- )
-
-
-def is_scout_trial_judge_context(*, team_id: int, user_id: int, marker: object) -> bool:
- from products.signals.backend.scout_harness.trial_evaluation import ( # noqa: PLC0415 -- avoids loading evaluation storage for ordinary tasks
- _assert_worker_access,
- _read_trial_judge_input,
- )
-
- if not isinstance(marker, dict) or type(marker.get("version")) is not int or marker["version"] != 1:
- return False
- if type(marker.get("user_id")) is not int or marker["user_id"] != user_id:
- return False
- identifiers: dict[str, uuid.UUID] = {}
- for key in (
- "evaluation_id",
- "launch_id",
- "context_id",
- "source_task_id",
- "source_task_run_id",
- "source_scout_run_id",
- ):
- value = marker.get(key)
- if not isinstance(value, str):
- return False
- try:
- identifiers[key] = uuid.UUID(value)
- except ValueError:
- return False
- if str(identifiers[key]) != value:
- return False
- snapshot = _read_trial_judge_input(team_id, identifiers["evaluation_id"], identifiers["launch_id"])
- if snapshot is None or snapshot.user_id != user_id or snapshot.context_id != identifiers["context_id"]:
- return False
- _assert_worker_access(snapshot)
- evidence = next((run for run in snapshot.runs if run.launch_id == identifiers["launch_id"]), None)
- if evidence is None or (
- evidence.task_id != identifiers["source_task_id"]
- or evidence.task_run_id != identifiers["source_task_run_id"]
- or evidence.run_id != identifiers["source_scout_run_id"]
- or evidence.execution_status != "completed"
- or evidence.exclusion_reason is not None
- ):
- return False
- source = (
- SignalScoutRun.objects.for_team(team_id)
- .select_related("task_run__task")
- .filter(
- id=identifiers["source_scout_run_id"],
- task_run_id=identifiers["source_task_run_id"],
- task_run__task_id=identifiers["source_task_id"],
- task_run__team_id=team_id,
- task_run__task__team_id=team_id,
- task_run__task__created_by_id=user_id,
- task_run__task__deleted=False,
- task_run__task__origin_product="signals_scout",
- task_run__task__origin_key=f"scout-trial:{marker['launch_id']}",
- task_run__status="completed",
- metadata__scout_trial__version=1,
- metadata__scout_trial__launch_id=marker["launch_id"],
- metadata__scout_trial__context_id=marker["context_id"],
- )
- .first()
- )
- if source is None or (source.task_run.state or {}).get("scout_trial") != (source.metadata or {}).get("scout_trial"):
- return False
- private_state = (source.task_run.state or {}).get("scout_trial_private")
- return not isinstance(private_state, dict) or not private_state.get("invalid_reason")
-
-
@frozen
class ScoutTrialSkill:
name: str
@@ -199,29 +106,22 @@ class ScoutTrialSkill:
body: str = dataclasses.field(repr=False)
-def get_scout_trial_skill_override(*, team_id: int, task_id: uuid.UUID) -> ScoutTrialSkill | None:
- from products.signals.backend.scout_harness.trial_launch import (
- read_trial_launch, # noqa: PLC0415 -- trial tools import the shared Signals facade
+def get_scout_trial_skill_override(*, team_id: int, task_id: uuid.UUID, token_id: uuid.UUID) -> ScoutTrialSkill | None:
+ from products.signals.backend.scout_harness.trial_launch import ( # noqa: PLC0415 -- trial tools import the shared Signals facade
+ bound_trial_run,
+ read_trial_launch,
)
- run = (
- SignalScoutRun.objects.for_team(team_id)
- .select_related("task_run__task")
- .filter(task_run__task_id=task_id, metadata__scout_trial__version=1)
- .first()
- )
- if run is None:
- return None
- marker = (run.metadata or {})["scout_trial"]
- launch_id = marker.get("launch_id")
+ run = bound_trial_run(team_id, task_id)
if (
- not isinstance(launch_id, str)
- or run.task_run.task.origin_product != "signals_scout"
- or run.task_run.task.origin_key != f"scout-trial:{launch_id}"
- or (run.task_run.state or {}).get("scout_trial") != marker
+ run is None
+ or run.metadata is None
+ or not is_sandbox_run_request(
+ team_id=team_id, task_id=str(task_id), run_id=str(run.task_run_id), token_id=token_id
+ )
):
return None
- launch = read_trial_launch(team_id, launch_id)
+ launch = read_trial_launch(team_id, run.metadata["scout_trial"]["launch_id"])
if launch.skill_name != run.skill_name or launch.skill_version != run.skill_version:
return None
return ScoutTrialSkill(name=launch.skill_name, version=launch.skill_version, body=launch.skill_body)
diff --git a/products/signals/backend/migrations/0163_signalscoutrun_trial_state.py b/products/signals/backend/migrations/0163_signalscoutrun_trial_state.py
new file mode 100644
index 000000000000..9e454ff5e8aa
--- /dev/null
+++ b/products/signals/backend/migrations/0163_signalscoutrun_trial_state.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.18 on 2026-10-09 10:30
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0162_delete_impact_measurement_plans"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalscoutrun",
+ name="trial_state",
+ field=models.JSONField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 5f25594ce629..bca2cd14ca12 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0162_delete_impact_measurement_plans
+0163_signalscoutrun_trial_state
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index cc6821e495a7..80adbbfe6e75 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -3070,6 +3070,8 @@ class SignalScoutRun(TeamScopedRootMixin, UUIDModel):
# the note a person typed when triggering the run by hand, so read it as prose, not a dimension.
# Nullable with a `{}` db_default so the AddField stays non-blocking on the populated table.
metadata = models.JSONField(null=True, blank=True, default=dict, db_default={})
+ # Keep private trial documents separate from metadata inspected by ordinary scout history queries.
+ trial_state = models.JSONField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
# Last touch on the row. The `summary`, the emit and edit tallies, and `metadata` all land after
# the row is created, so a reader keyed on `created_at` alone never sees a settled run. Nullable
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 007173352138..4fac53fb428f 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -18,7 +18,6 @@ from django.utils import timezone
import posthoganalytics
from croniter import CroniterError, croniter
-from pydantic import JsonValue
from posthog.clickhouse.query_tagging import private_capture_context
from posthog.dataclasses import frozen
@@ -69,11 +68,7 @@ from products.signals.backend.scout_harness.trial_launch import (
load_trial_launch,
)
from products.signals.backend.scout_harness.trial_result import export_trial_result, validate_trial_runtime
-from products.signals.backend.scout_harness.trial_state import (
- SCOUT_TRIAL_METADATA_KEY,
- SCOUT_TRIAL_STATE_KEY,
- initial_trial_state,
-)
+from products.signals.backend.scout_harness.trial_state import SCOUT_TRIAL_METADATA_KEY, initial_trial_state
from products.signals.backend.temporal.agentic import (
SIGNALS_REPORT_RESEARCH_ENV_NAME,
get_or_create_signals_sandbox_env,
@@ -1009,8 +1004,8 @@ async def _spawn_and_run(
},
)
- def _create_bridge_row(task_run_id: UUID) -> dict[str, JsonValue] | None:
- scout_run = _create_run_row(
+ def _create_bridge_row(task_run_id: UUID) -> None:
+ _create_run_row(
run_id=run_id,
task_run_id=task_run_id,
team=team,
@@ -1048,12 +1043,6 @@ async def _spawn_and_run(
service_tier=service_tier,
)
)
- if trial is not None:
- return {
- SCOUT_TRIAL_METADATA_KEY: (scout_run.metadata or {})[SCOUT_TRIAL_METADATA_KEY],
- SCOUT_TRIAL_STATE_KEY: initial_trial_state(),
- }
- return None
session, result = await MultiTurnSession.start(
prompt=prompt,
@@ -1405,6 +1394,7 @@ def _create_run_row(
skill_name=skill.name,
skill_version=skill.version,
metadata=metadata,
+ trial_state=initial_trial_state() if trial is not None else None,
)
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index d0f33445274b..a8da9f40e3a3 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -150,7 +150,7 @@ logger = structlog.get_logger(__name__)
}
)
class RunMetadataField(serializers.DictField):
- """The run row's whole `metadata` column: runner-stamped keys at the top level plus the nested
+ """The run row's public `metadata`: runner-stamped keys at the top level plus the nested
`derived` map of harness-computed booleans.
The known keys are spelled out so generated TypeScript and MCP consumers get real types
diff --git a/products/signals/backend/scout_harness/trial_access.py b/products/signals/backend/scout_harness/trial_access.py
index 91bc0093edb3..14b1ada78694 100644
--- a/products/signals/backend/scout_harness/trial_access.py
+++ b/products/signals/backend/scout_harness/trial_access.py
@@ -16,6 +16,7 @@ from products.signals.backend.scout_harness.trial_launch import (
)
from products.signals.backend.scout_harness.trial_reads import SavedScoutReads
from products.signals.backend.scout_harness.trial_state import ScoutTrialStateError, ScoutTrialStore
+from products.tasks.backend.facade.access import is_sandbox_run_request
def trial_run_for_request(request: Request, team_id: int) -> SignalScoutRun | None:
@@ -27,6 +28,13 @@ def trial_run_for_request(request: Request, team_id: int) -> SignalScoutRun | No
carries_scope = "scout_experiment_internal:read" in (token.scope or "").split()
if carries_scope != (run is not None):
raise exceptions.PermissionDenied("The scout credential does not match its run.")
+ if run is not None and not is_sandbox_run_request(
+ team_id=team_id,
+ task_id=str(token.sandbox_task_id),
+ run_id=str(run.task_run_id),
+ token_id=token.pk,
+ ):
+ raise exceptions.PermissionDenied("The scout credential does not match its run.")
return run
diff --git a/products/signals/backend/scout_harness/trial_evaluation.py b/products/signals/backend/scout_harness/trial_evaluation.py
index 3ca252f849fa..2c776d73d0a9 100644
--- a/products/signals/backend/scout_harness/trial_evaluation.py
+++ b/products/signals/backend/scout_harness/trial_evaluation.py
@@ -332,7 +332,6 @@ def _bound_run(launch: TrialLaunch) -> SignalScoutRun | None:
or not isinstance(marker, dict)
or marker.get("version") != 1
or marker.get("context_id") != str(launch.context_id)
- or (task_run.state or {}).get("scout_trial") != marker
):
raise TrialEvaluationError("The trial does not match its private task and operator.")
return run
diff --git a/products/signals/backend/scout_harness/trial_gateway.py b/products/signals/backend/scout_harness/trial_gateway.py
index b90e7a4e65cf..a7b528fd56ae 100644
--- a/products/signals/backend/scout_harness/trial_gateway.py
+++ b/products/signals/backend/scout_harness/trial_gateway.py
@@ -9,18 +9,21 @@ from products.tasks.backend.facade.api import mint_private_gateway_token, revoke
def create_trial_gateway_token(run: SignalScoutRun) -> str:
- from products.signals.backend.facade.api import ( # noqa: PLC0415 -- the facade imports report tools
- is_scout_trial_task_run,
+ from products.signals.backend.scout_harness.trial_launch import ( # noqa: PLC0415 -- launch serialization imports report tools
+ bound_trial_run,
)
ensure_scout_trial_capture_ready()
current = SignalScoutRun.objects.for_team(run.team_id).select_related("task_run__task__team").get(id=run.id)
task_run = current.task_run
task = task_run.task
+ bound = bound_trial_run(run.team_id, task.id)
if (
task.team_id != run.team_id
or task_run.team_id != run.team_id
- or not is_scout_trial_task_run(team_id=run.team_id, task_id=task.id, task_run_id=task_run.id)
+ or bound is None
+ or bound.id != current.id
+ or bound.task_run_id != task_run.id
):
raise GatewayNotConfiguredError("Report safety requires a validated scout trial")
actor = User.objects.filter(
diff --git a/products/signals/backend/scout_harness/trial_inspection.py b/products/signals/backend/scout_harness/trial_inspection.py
index c7ff311f3fdc..9c84ef5e009b 100644
--- a/products/signals/backend/scout_harness/trial_inspection.py
+++ b/products/signals/backend/scout_harness/trial_inspection.py
@@ -177,7 +177,6 @@ class ScoutTrialInspection:
not isinstance(marker.get("launch_id"), str)
or run.task_run.task.origin_product != "signals_scout"
or run.task_run.task.origin_key != f"scout-trial:{marker['launch_id']}"
- or (run.task_run.state or {}).get("scout_trial") != marker
):
continue
try:
diff --git a/products/signals/backend/scout_harness/trial_judge.py b/products/signals/backend/scout_harness/trial_judge.py
index 565cbe18f3c5..6d34d8af3a51 100644
--- a/products/signals/backend/scout_harness/trial_judge.py
+++ b/products/signals/backend/scout_harness/trial_judge.py
@@ -86,7 +86,6 @@ def _assert_scout_available(snapshot: TrialEvaluationSnapshot, evidence: TrialRu
or marker.get("launch_id") != str(evidence.launch_id)
or marker.get("context_id") != str(snapshot.context_id)
or run.task_run.status != "completed"
- or (run.task_run.state or {}).get("scout_trial") != marker
):
raise TrialJudgeValidationError("The saved scout run is no longer available for this evaluation.")
if ScoutTrialStore(run).invalid_reason() is not None:
diff --git a/products/signals/backend/scout_harness/trial_launch.py b/products/signals/backend/scout_harness/trial_launch.py
index f7172b44e5f2..06b5638f1872 100644
--- a/products/signals/backend/scout_harness/trial_launch.py
+++ b/products/signals/backend/scout_harness/trial_launch.py
@@ -40,7 +40,6 @@ from products.tasks.backend.facade.run_config import (
MAX_TRIAL_LAUNCH_BYTES = 16 * 1024 * 1024
MAX_EVIDENCE_BYTES = 128 * 1024 * 1024
-SCOUT_TRIAL_TASK_STATE_KEY = "scout_trial"
class ScoutTrialLaunchError(ValueError):
@@ -461,9 +460,22 @@ def create_trial_launch(
def bound_trial_run(team_id: int, task_id: UUID | str | None) -> SignalScoutRun | None:
if task_id is None:
return None
- return (
+ run = (
SignalScoutRun.objects.for_team(team_id)
- .filter(task_run__task_id=task_id, metadata__scout_trial__version=1)
- .select_related("task_run")
+ .filter(
+ task_run__task_id=task_id,
+ task_run__team_id=team_id,
+ task_run__task__team_id=team_id,
+ task_run__task__deleted=False,
+ task_run__task__origin_product="signals_scout",
+ metadata__scout_trial__version=1,
+ )
+ .select_related("task_run__task")
.first()
)
+ if run is None or run.metadata is None:
+ return None
+ launch_id = run.metadata["scout_trial"].get("launch_id")
+ if not isinstance(launch_id, str) or run.task_run.task.origin_key != f"scout-trial:{launch_id}":
+ return None
+ return run
diff --git a/products/signals/backend/scout_harness/trial_state.py b/products/signals/backend/scout_harness/trial_state.py
index ede7ea15c908..bc21141cb0f0 100644
--- a/products/signals/backend/scout_harness/trial_state.py
+++ b/products/signals/backend/scout_harness/trial_state.py
@@ -27,7 +27,6 @@ from products.signals.backend.scout_harness.tools.scratchpad import (
if TYPE_CHECKING:
from uuid import UUID
-SCOUT_TRIAL_STATE_KEY = "scout_trial_private"
MAX_SCOUT_TRIAL_STATE_BYTES = 2 * 1024 * 1024
_MEMORY_ADAPTER = TypeAdapter(list[ScratchpadEntry])
@@ -106,16 +105,16 @@ class ScoutTrialStore:
row = (
SignalScoutRun.objects.for_team(self.run.team_id)
.filter(pk=self.run.pk, task_run_id=self.run.task_run_id)
- .values("metadata", "task_run__state")
+ .values("metadata", "trial_state")
.first()
)
if row is None:
raise ScoutTrialStateError("The scout run has no private state.")
marker = (row["metadata"] or {}).get(SCOUT_TRIAL_METADATA_KEY)
- if not isinstance(marker, dict) or marker.get("version") != 1:
+ state = row["trial_state"]
+ if not isinstance(marker, dict) or marker.get("version") != 1 or not isinstance(state, dict):
raise ScoutTrialStateError("The scout run has no private state.")
- state = row["task_run__state"] or {}
- return _TrialState.model_validate(state.get(SCOUT_TRIAL_STATE_KEY, {}))
+ return _TrialState.model_validate(state)
def _mutate(
self, change: Callable[[_TrialState], _Result], *, allow_terminal: bool = False, allow_invalid: bool = False
@@ -125,15 +124,17 @@ class ScoutTrialStore:
locked = (
SignalScoutRun.objects.for_team(self.run.team_id)
.select_related("task_run")
- .select_for_update(of=("task_run",))
+ .select_for_update(of=("self", "task_run"))
.get(pk=self.run.pk, task_run_id=self.run.task_run_id)
)
if not is_scout_trial(locked) or locked.task_run.team_id != self.run.team_id:
raise ScoutTrialStateError("The scout run has no private state.")
if not allow_terminal and locked.task_run.status != "in_progress":
raise ScoutTrialStateError("The scout run is no longer in progress.")
- state = dict(locked.task_run.state or {})
- private = _TrialState.model_validate(state.get(SCOUT_TRIAL_STATE_KEY, {}))
+ state = locked.trial_state
+ if not isinstance(state, dict):
+ raise ScoutTrialStateError("The scout run has no private state.")
+ private = _TrialState.model_validate(state)
if private.invalid_reason and not allow_invalid:
raise ScoutTrialStateError(private.invalid_reason)
updated = private.model_copy(deep=True)
@@ -147,9 +148,8 @@ class ScoutTrialStore:
invalid_reason = "The scout run exceeded its private state limit and cannot be compared."
private.invalid_reason = invalid_reason
payload = private.model_dump(mode="json")
- state[SCOUT_TRIAL_STATE_KEY] = payload
- locked.task_run.state = state
- locked.task_run.save(update_fields=["state", "updated_at"])
+ locked.trial_state = payload
+ locked.save(update_fields=["trial_state"])
if invalid_reason:
raise ScoutTrialStateError(invalid_reason)
return result
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index 6bf5cc058471..a09687b6be94 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -1654,6 +1654,7 @@ async def test_successful_run_creates_bridge_row_pointing_at_task_run(
assert bridge.skill_name == "signals-scout-errors"
assert bridge.skill_version == 1
assert (bridge.metadata or {}).get("check_id") == check_id
+ assert bridge.trial_state is None
# Agent close-out is persisted on the bridge row so future runs can dedupe
# against non-emitting runs via the runs-list ILIKE filter.
assert bridge.summary == "I would investigate /checkout 500s next."
@@ -1765,13 +1766,11 @@ async def test_trial_runs_keep_runtime_and_state_separate_from_the_production_sc
session.task_run.status = "in_progress"
await database_sync_to_async(session.task_run.save)(update_fields=["state", "status"])
initial_state = await database_sync_to_async(before_task_dispatch)(session.task_run.id)
- assert initial_state is not None
- session.task_run.state = {**session.task_run.state, **initial_state}
- await database_sync_to_async(session.task_run.save)(update_fields=["state"])
+ assert initial_state is None
persisted = await database_sync_to_async(type(session.task_run).objects.get)(pk=session.task_run.pk)
assert persisted.state is not None
- assert persisted.state["scout_trial"]["launch_id"] == str(launch.id)
- assert "scout_trial_private" in persisted.state
+ assert "scout_trial" not in persisted.state
+ assert "scout_trial_private" not in persisted.state
if task_cancelled or outcome_case == "task_failed_no_message":
await database_sync_to_async(type(session.task_run).objects.filter(pk=session.task_run.pk).update)(
status="cancelled" if task_cancelled else "failed"
@@ -1870,6 +1869,7 @@ async def test_trial_runs_keep_runtime_and_state_separate_from_the_production_sc
assert outcome.task_run_id == replay.task_run_id == str(session.task_run.id)
assert bridge.metadata is not None
assert bridge.metadata["scout_trial"]["context_id"] == str(context.id)
+ assert bridge.trial_state is not None
assert bridge.metadata["reasoning_effort"] == "high"
export.assert_called_once()
assert export.call_args.args[0] == f"signals/scout-trials/{ateam.id}/results/{bridge.id}.json"
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index 604bc6a47a62..544607782dd3 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -25,6 +25,7 @@ from posthog.mcp_tool_definitions import get_mcp_tool_definitions
from posthog.models import OAuthApplication
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.integration import Integration
+from posthog.models.oauth import find_oauth_access_token
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -77,6 +78,7 @@ from products.signals.backend.scout_harness.team_limits import MAX_RUNS_PER_TEAM
from products.signals.backend.scout_harness.tools import structured_output as structured_output_tool
from products.signals.backend.scout_harness.tools.lighthouse import MAX_AUDITS_PER_RUN, RUN_AUDIT_COUNT_KEY
from products.signals.backend.scout_harness.tools.profile import compute_project_profile
+from products.signals.backend.scout_harness.trial_state import initial_trial_state
from products.signals.backend.temporal.signal_queries import fetch_report_ids_for_source_ids
from products.skills.backend.models.skills import LLMSkill, LLMSkillOwner
@@ -130,6 +132,25 @@ def _authenticate_as_scout(
include_internal_scopes=True,
sandbox_task_id=sandbox_task_id,
)
+ if sandbox_task_id is not None:
+ access_token = find_oauth_access_token(token)
+ assert access_token is not None
+ TaskRun = apps.get_model("tasks", "TaskRun")
+ run = (
+ TaskRun.objects.filter(task_id=sandbox_task_id, team_id=team_id if team_id is not None else test.team.id)
+ .order_by("-created_at", "-id")
+ .first()
+ )
+ if run is not None:
+ TaskRun.update_state_atomic(
+ run.id,
+ updates={
+ "sandbox_oauth_token_ids": [
+ *(run.state or {}).get("sandbox_oauth_token_ids", []),
+ str(access_token.pk),
+ ]
+ },
+ )
test.client.logout()
test.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
@@ -166,6 +187,15 @@ def _make_run(team: Team, *, task_run_status: str | None = None, **overrides) ->
"skill_version": 1,
}
defaults.update(overrides)
+ if metadata := defaults.get("metadata"):
+ marker = metadata.get("scout_trial")
+ if isinstance(marker, dict) and marker.get("version") == 1:
+ marker = {"launch_id": str(uuid4()), **marker}
+ defaults["metadata"] = {**metadata, "scout_trial": marker}
+ defaults.setdefault("trial_state", initial_trial_state())
+ task = defaults["task_run"].task
+ task.origin_key = f"scout-trial:{marker['launch_id']}"
+ task.save(update_fields=["origin_key"])
return SignalScoutRun.objects.create(team=team, **defaults)
diff --git a/products/signals/backend/test/test_scout_trial_evaluation.py b/products/signals/backend/test/test_scout_trial_evaluation.py
index 425d057956ba..2722d6235971 100644
--- a/products/signals/backend/test/test_scout_trial_evaluation.py
+++ b/products/signals/backend/test/test_scout_trial_evaluation.py
@@ -24,7 +24,6 @@ from posthog.models import Team, User
from posthog.models.scoping import team_scope
from posthog.storage import object_storage
-from products.signals.backend.facade.api import is_scout_trial_judge_context
from products.signals.backend.facade.rubrics import ScoutRubricReferenceContext, default_criteria
from products.signals.backend.models import SignalScoutConfig
from products.signals.backend.scout_harness.limits import MAX_TRIAL_RUNS
@@ -90,8 +89,6 @@ from products.signals.backend.test.test_scout_harness_api import _make_run
from products.signals.backend.test.test_scout_trial_judge import _reference_context, _snapshot
from products.signals.backend.trial_judging import TrialJudgeInput, build_trial_judge_prompt
from products.skills.backend.models.skills import LLMSkill
-from products.tasks.backend.models import Task
-from products.tasks.backend.temporal.oauth import create_oauth_access_token_for_run # tach-ignore
if TYPE_CHECKING:
pass
@@ -586,91 +583,6 @@ class TestScoutTrialEvaluation(BaseTest):
with self.assertRaisesMessage(TrialEvaluationError, "private task and operator"):
prepare_trial_evaluation(config=self.config, user=self.user, request=self.request)
- @parameterized.expand(
- [
- "valid",
- "evaluation_id",
- "launch_id",
- "context_id",
- "source_task_id",
- "source_task_run_id",
- "source_scout_run_id",
- "user_id",
- "caller_user",
- "caller_team",
- "source_origin",
- "source_state",
- "source_status",
- "source_deleted",
- "source_invalidated",
- "operator_revoked",
- ]
- )
- def test_judge_credentials_require_the_exact_saved_evaluation_and_private_source(self, mismatch: str) -> None:
- snapshot = prepare_trial_evaluation(config=self.config, user=self.user, request=self.request)
- evidence = snapshot.runs[0]
- marker: dict[str, str | int] = {
- "version": 1,
- "evaluation_id": str(snapshot.evaluation_id),
- "launch_id": str(evidence.launch_id),
- "context_id": str(snapshot.context_id),
- "user_id": snapshot.user_id,
- "source_task_id": str(evidence.task_id),
- "source_task_run_id": str(evidence.task_run_id),
- "source_scout_run_id": str(evidence.run_id),
- }
- team_id, user_id = self.team.id, self.user.id
- if mismatch == "user_id":
- marker["user_id"] = user_id + 1
- elif mismatch in marker:
- marker[mismatch] = str(uuid4())
- elif mismatch == "caller_team":
- team_id += 1
- elif mismatch == "caller_user":
- user_id += 1
- elif mismatch == "source_origin":
- task = self.scout_run.task_run.task
- task.origin_key = "ordinary-task"
- task.save(update_fields=["origin_key"])
- elif mismatch == "source_state":
- self.scout_run.task_run.state["scout_trial"] = {}
- self.scout_run.task_run.save(update_fields=["state"])
- elif mismatch == "source_status":
- self.scout_run.task_run.status = "failed"
- self.scout_run.task_run.save(update_fields=["status"])
- elif mismatch == "source_deleted":
- task = self.scout_run.task_run.task
- task.deleted = True
- task.save(update_fields=["deleted"])
- elif mismatch == "source_invalidated":
- ScoutTrialStore(self.scout_run).invalidate("Synthetic invalidation", allow_terminal=True)
- elif mismatch == "operator_revoked":
- self.user.is_staff = False
- self.user.save(update_fields=["is_staff"])
- with self.assertRaises(TrialEvaluationError):
- is_scout_trial_judge_context(team_id=team_id, user_id=user_id, marker=marker)
- return
- assert is_scout_trial_judge_context(team_id=team_id, user_id=user_id, marker=marker) is (mismatch == "valid")
- if mismatch == "valid":
- judge_task = Task.objects.create(
- team=self.team,
- created_by=self.user,
- title="Synthetic trial judge",
- origin_product=Task.OriginProduct.SIGNALS_SCOUT,
- origin_key=f"scout-trial-judge:{snapshot.evaluation_id}:{evidence.launch_id}",
- )
- judge_run = judge_task.create_run(extra_state={"scout_trial_judge": marker, "use_dedicated_stream": False})
- with patch(
- "products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user",
- return_value="synthetic-judge-token",
- ) as mint:
- assert (
- create_oauth_access_token_for_run(judge_task, judge_run.state, scopes="full")
- == "synthetic-judge-token"
- )
- assert mint.call_args.kwargs["scopes"] == "signals_scout_judge"
- assert mint.call_args.kwargs["sandbox_task_id"] == judge_task.id
-
@parameterized.expand(
["source_origin", "source_state", "excluded_evidence", "unfinished_evidence", "foreign_evidence"]
)
@@ -682,8 +594,9 @@ class TestScoutTrialEvaluation(BaseTest):
task.origin_key = "ordinary-task"
task.save(update_fields=["origin_key"])
elif invalid == "source_state":
- self.scout_run.task_run.state["scout_trial"] = {}
- self.scout_run.task_run.save(update_fields=["state"])
+ assert self.scout_run.metadata is not None
+ self.scout_run.metadata["scout_trial"] = {}
+ self.scout_run.save(update_fields=["metadata"])
elif invalid == "excluded_evidence":
evidence = evidence.model_copy(update={"exclusion_reason": "Synthetic excluded run."})
snapshot = snapshot.model_copy(update={"runs": [evidence]})
@@ -796,10 +709,8 @@ class TestScoutTrialEvaluation(BaseTest):
TrialReport(id=f"synthetic-report-{index}", document={"summary": f"Finding {index}. " * 3000})
for index in range(4)
]
- self.scout_run.task_run.state["scout_trial_private"] = {
- "reports": {report.id: report.model_dump(mode="json") for report in reports}
- }
- self.scout_run.task_run.save(update_fields=["state"])
+ self.scout_run.trial_state = {"reports": {report.id: report.model_dump(mode="json") for report in reports}}
+ self.scout_run.save(update_fields=["trial_state"])
log = json.dumps(
{
"notification": {
@@ -859,10 +770,8 @@ class TestScoutTrialEvaluation(BaseTest):
operator_metadata={"skipped_automatic_repository_selection": False},
artefacts=[{"type": "note", "content": "Synthetic diagnostic detail. " * 250}],
)
- self.scout_run.task_run.state["scout_trial_private"] = {
- "reports": {captured_report.id: captured_report.model_dump(mode="json")}
- }
- self.scout_run.task_run.save(update_fields=["state"])
+ self.scout_run.trial_state = {"reports": {captured_report.id: captured_report.model_dump(mode="json")}}
+ self.scout_run.save(update_fields=["trial_state"])
log = (
"\n".join(
json.dumps(
diff --git a/products/signals/backend/test/test_scout_trial_state.py b/products/signals/backend/test/test_scout_trial_state.py
index 542599cf06d3..323fab9f25b7 100644
--- a/products/signals/backend/test/test_scout_trial_state.py
+++ b/products/signals/backend/test/test_scout_trial_state.py
@@ -25,6 +25,7 @@ from products.signals.backend.models import (
ArtefactAttribution,
SignalReport,
SignalReportArtefact,
+ SignalScoutRun,
SignalScratchpad,
)
from products.signals.backend.repo_corrections import SCOUT_REPOSITORY_REASON
@@ -42,7 +43,6 @@ from products.signals.backend.scout_harness.tools.report_author import ScoutRunR
from products.signals.backend.scout_harness.tools.scratchpad import ScratchpadEntry
from products.signals.backend.scout_harness.trial_gateway import create_trial_gateway_token, revoke_trial_gateway_token
from products.signals.backend.scout_harness.trial_state import (
- SCOUT_TRIAL_STATE_KEY,
ScoutTrialStateError,
ScoutTrialStore,
TrialReport,
@@ -83,6 +83,8 @@ class TestScoutTrialState(APIBaseTest):
assert own.search_memory(key=original.key)[0].content == "First candidate"
assert sibling.search_memory(key=original.key)[0].content == "Second candidate"
+ self.scout_run.task_run.refresh_from_db()
+ assert "scout_trial_private" not in (self.scout_run.task_run.state or {})
assert sibling.search_memory(key="finding:new") == []
original.refresh_from_db()
assert original.content == "Production changed after capture"
@@ -96,12 +98,19 @@ class TestScoutTrialState(APIBaseTest):
first = ScoutTrialStore(self.scout_run, initial_memory=[])
second = ScoutTrialStore(self.scout_run, initial_memory=[])
first.remember(key="first", content="First value")
+ latest = SignalScoutRun.objects.for_team(self.team.id).get(pk=self.scout_run.pk)
+ assert latest.metadata is not None
+ latest.metadata["derived"] = {"has_emit_report": False}
+ latest.save(update_fields=["metadata"])
TaskRun.update_state_atomic(self.scout_run.task_run_id, updates={"sandbox_id": "existing-sandbox"})
second.remember(key="second", content="Second value")
assert {entry.key for entry in first.search_memory()} == {"first", "second"}
self.scout_run.task_run.refresh_from_db()
assert self.scout_run.task_run.state["sandbox_id"] == "existing-sandbox"
+ self.scout_run.refresh_from_db()
+ assert self.scout_run.metadata is not None
+ assert self.scout_run.metadata["derived"] == {"has_emit_report": False}
@parameterized.expand(["completed", "cancelled", "failed"])
def test_terminal_runs_reject_mutation(self, status: str) -> None:
@@ -110,18 +119,28 @@ class TestScoutTrialState(APIBaseTest):
with self.assertRaisesMessage(ScoutTrialStateError, "no longer in progress"):
store.remember(key="key", content="value")
- self.scout_run.task_run.refresh_from_db()
- assert SCOUT_TRIAL_STATE_KEY not in self.scout_run.task_run.state
store.invalidate("The runner observed different settings.", allow_terminal=True)
store.invalidate("Do not replace the first failure.", allow_terminal=True)
assert store.invalid_reason() == "The runner observed different settings."
def test_private_state_does_not_enable_trial_permissions(self) -> None:
ordinary = _make_run(self.team)
- TaskRun.update_state_atomic(ordinary.task_run_id, updates={SCOUT_TRIAL_STATE_KEY: {}})
+ assert ordinary.trial_state is None
+ ordinary.trial_state = {}
+ ordinary.save(update_fields=["trial_state"])
with self.assertRaisesMessage(ScoutTrialStateError, "does not have a private context"):
ScoutTrialStore(ordinary, initial_memory=[])
+ def test_missing_trial_state_rejects_reads_and_writes(self) -> None:
+ self.scout_run.trial_state = None
+ self.scout_run.save(update_fields=["trial_state"])
+ store = ScoutTrialStore(self.scout_run, initial_memory=[])
+
+ with self.assertRaisesMessage(ScoutTrialStateError, "no private state"):
+ store.export()
+ with self.assertRaisesMessage(ScoutTrialStateError, "no private state"):
+ store.remember(key="key", content="value")
+
def test_limit_invalidates_trial_without_losing_accepted_content(self) -> None:
store = ScoutTrialStore(self.scout_run, initial_memory=[])
store.remember(key="accepted", content="Keep this")
@@ -182,8 +201,6 @@ class TestScoutTrialReportCapture(APIBaseTest):
task.created_by = self.user
task.origin_key = f"scout-trial:{marker['launch_id']}"
task.save(update_fields=["created_by", "origin_key"])
- self.scout_run.task_run.state = {**(self.scout_run.task_run.state or {}), "scout_trial": marker}
- self.scout_run.task_run.save(update_fields=["state"])
self.gateway_mint = self.enterContext(
patch(
"products.signals.backend.scout_harness.trial_gateway.mint_private_gateway_token",
@@ -254,8 +271,9 @@ class TestScoutTrialReportCapture(APIBaseTest):
@parameterized.expand(["untrusted_run", "revoked_actor", "revoked_membership"])
def test_gateway_credential_rejects_invalid_trial_identity(self, condition: str) -> None:
if condition == "untrusted_run":
- self.scout_run.task_run.state = {}
- self.scout_run.task_run.save(update_fields=["state"])
+ assert self.scout_run.metadata is not None
+ self.scout_run.metadata["scout_trial"] = {}
+ self.scout_run.save(update_fields=["metadata"])
elif condition == "revoked_actor":
self.user.is_active = False
self.user.save(update_fields=["is_active"])
diff --git a/products/signals/backend/test/test_scout_trials_api.py b/products/signals/backend/test/test_scout_trials_api.py
index 59af23add957..f4fe179fdb0d 100644
--- a/products/signals/backend/test/test_scout_trials_api.py
+++ b/products/signals/backend/test/test_scout_trials_api.py
@@ -50,6 +50,7 @@ from products.signals.backend.test.test_scout_harness_api import _authenticate_a
from products.signals.backend.test.test_scout_trial_judge import _reference_context
from products.skills.backend.models.skills import LLMSkill
from products.tasks.backend.facade.run_config import get_default_model_for_runtime_adapter
+from products.tasks.backend.models import TaskRun
class TestScoutTrialAPI(APIBaseTest):
@@ -73,12 +74,14 @@ class TestScoutTrialAPI(APIBaseTest):
_authenticate_as_scout(self, scopes="signals_scout_experiment", sandbox_task_id=self.trial_run.task_run.task_id)
def test_operator_run_reads_mark_only_trial_content(self) -> None:
+ ScoutTrialStore(self.trial_run, initial_memory=[]).remember(key="private", content="Trial-only memory")
for run, private in ((self.trial_run, True), (self.production, False)):
run.task_run.task.created_by = self.user
run.task_run.task.save(update_fields=["created_by"])
response = self.client.get(f"{self.trial_runs_url}{run.id}/")
assert response.status_code == 200, response.data
assert (response.get("X-PostHog-Suppress-Analytics") == "true") == private
+ assert "trial_state" not in response.json()
def test_memory_routes_from_credential_and_cannot_write_production_or_sibling(self) -> None:
original = SignalScratchpad.objects.create(team=self.team, key="finding:shared", content="Production value")
@@ -118,6 +121,7 @@ class TestScoutTrialAPI(APIBaseTest):
assert response.json() == []
def test_ordinary_scout_cannot_read_trial_runs_and_own_detail_hides_labels(self) -> None:
+ ScoutTrialStore(self.trial_run, initial_memory=[]).remember(key="private", content="Trial-only memory")
config = SignalScoutConfig.objects.for_team(self.team.id).get(skill_name=self.trial_run.skill_name)
config.emit = False
config.save(update_fields=["emit"])
@@ -125,11 +129,13 @@ class TestScoutTrialAPI(APIBaseTest):
response = self.client.get(self.trial_runs_url)
assert response.status_code == 200, response.data
assert [row["run_id"] for row in response.json()] == [str(self.production.id)]
+ assert all("trial_state" not in row for row in response.json())
assert self.client.get(f"{self.trial_runs_url}{self.trial_run.id}/").status_code == 404
self._as_trial()
response = self.client.get(f"{self.trial_runs_url}{self.trial_run.id}/")
assert response.status_code == 200, response.data
assert "scout_trial" not in response.json()["metadata"]
+ assert "trial_state" not in response.json()
assert self.client.get(f"{self.trial_runs_url}{self.other.id}/").status_code == 404
configs = self.client.get(f"/api/projects/{self.team.id}/signals/scout/configs/")
assert configs.status_code == 200, configs.data
@@ -223,13 +229,32 @@ class TestScoutTrialAPI(APIBaseTest):
assert response.status_code == 400, response.data
assert response.json()["detail"] == f"report {own_id} not found"
- def test_trial_scope_without_bound_run_fails_closed(self) -> None:
- _authenticate_as_scout(
- self, scopes="signals_scout_experiment", sandbox_task_id=self.production.task_run.task_id
- )
+ @parameterized.expand(["ordinary_run", "unregistered_token", "wrong_token", "sibling_run"])
+ def test_trial_scope_without_bound_run_fails_closed(self, binding: str) -> None:
+ if binding == "ordinary_run":
+ _authenticate_as_scout(
+ self, scopes="signals_scout_experiment", sandbox_task_id=self.production.task_run.task_id
+ )
+ else:
+ self._as_trial()
+ run = self.trial_run.task_run
+ run.refresh_from_db()
+ if binding == "sibling_run":
+ TaskRun.objects.create(
+ task=run.task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ state={"sandbox_oauth_token_ids": run.state["sandbox_oauth_token_ids"]},
+ )
+ TaskRun.update_state_atomic(
+ run.id, updates={"sandbox_oauth_token_ids": [str(uuid4())] if binding == "wrong_token" else []}
+ )
+ response = self.client.get(self.memory_url)
+ assert response.status_code == 403, response.data
response = self.client.post(self.memory_url, {"key": "untrusted", "content": "Must not persist"})
assert response.status_code == 403, response.data
assert not SignalScratchpad.objects.filter(team=self.team, key="untrusted").exists()
+ assert ScoutTrialStore(self.trial_run).search_memory(key="untrusted") == []
@override_settings(
@@ -427,14 +452,23 @@ class TestScoutTrialLaunch(APIBaseTest):
valid.task_run.task.created_by = self.user
valid.task_run.task.origin_key = f"scout-trial:{launch.id}"
valid.task_run.task.save(update_fields=["created_by", "origin_key"])
- valid.task_run.state = {"scout_trial": marker, "model": "Changed during execution"}
+ valid.task_run.state = {"model": "Changed during execution"}
valid.task_run.save(update_fields=["state"])
- other_operator = _make_run(self.team, scout_config=self.config, metadata={"scout_trial": marker})
+ other_operator = _make_run(
+ self.team,
+ scout_config=self.config,
+ metadata={"scout_trial": {**marker, "launch_id": str(uuid4())}},
+ )
other_operator.task_run.task.created_by = self._create_user("[email protected]")
other_operator.task_run.task.save(update_fields=["created_by"])
- invalid = _make_run(self.team, scout_config=self.config, metadata={"scout_trial": marker})
+ invalid = _make_run(
+ self.team,
+ scout_config=self.config,
+ metadata={"scout_trial": {**marker, "launch_id": str(uuid4())}},
+ )
invalid.task_run.task.created_by = self.user
- invalid.task_run.task.save(update_fields=["created_by"])
+ invalid.task_run.task.origin_key = "ordinary-task"
+ invalid.task_run.task.save(update_fields=["created_by", "origin_key"])
_make_run(self.team, scout_config=self.config)
self.trials_flag.return_value = False
response = self.client.get(f"{base}trial_history/")
@@ -765,7 +799,6 @@ class TestScoutTrialLaunch(APIBaseTest):
run.task_run.task.origin_key = f"scout-trial:{launch.id}"
run.task_run.task.save(update_fields=["created_by", "origin_product", "origin_key"])
run.task_run.state = {
- "scout_trial": marker,
"runtime_adapter": launch.runtime_adapter,
"model": launch.model,
"reasoning_effort": launch.reasoning_effort,
diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.py
index 4dafee799614..c78b3ea03f82 100644
--- a/products/skills/backend/api/skills.py
+++ b/products/skills/backend/api/skills.py
@@ -706,7 +706,9 @@ class LLMSkillViewSet(
return None
if token.sandbox_task_id is None:
raise PermissionDenied()
- trial_skill = get_scout_trial_skill_override(team_id=self.team.id, task_id=token.sandbox_task_id)
+ trial_skill = get_scout_trial_skill_override(
+ team_id=self.team.id, task_id=token.sandbox_task_id, token_id=token.pk
+ )
if trial_skill is None:
raise PermissionDenied()
return trial_skill
diff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.py
index 80112c793dd3..7b621af79539 100644
--- a/products/skills/backend/api/test/test_skills.py
+++ b/products/skills/backend/api/test/test_skills.py
@@ -2758,9 +2758,7 @@ class TestScoutTrialSkillAPI(APIBaseTest):
origin_key=f"scout-trial:{self.launch.id}",
created_by=self.operator,
)
- self.task_run = TaskRun.objects.create(
- task=self.task, team=self.team, status=TaskRun.Status.IN_PROGRESS, state={"scout_trial": marker}
- )
+ self.task_run = TaskRun.objects.create(task=self.task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
SignalScoutRun.objects.for_team(self.team.id).create(
team=self.team,
task_run=self.task_run,
@@ -2786,6 +2784,8 @@ class TestScoutTrialSkillAPI(APIBaseTest):
scoped_teams=[self.team.id],
sandbox_task_id=self.task.id,
)
+ self.task_run.state = {"sandbox_oauth_token_ids": [str(self.token.pk)]}
+ self.task_run.save(update_fields=["state"])
self.client.logout()
self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {self.token.token}")
@@ -2872,13 +2872,23 @@ class TestScoutTrialSkillAPI(APIBaseTest):
response = self.client.get(self._url())
assert response.status_code == status.HTTP_403_FORBIDDEN
- @parameterized.expand([("different_task",), ("untrusted_state",)])
+ @parameterized.expand([("different_task",), ("unregistered_token",), ("different_run",), ("wrong_origin",)])
def test_private_prompt_rejects_unbound_identity(self, mismatch: str) -> None:
if mismatch == "different_task":
self.token.sandbox_task_id = uuid.uuid4()
self.token.save(update_fields=["sandbox_task_id"])
+ elif mismatch == "wrong_origin":
+ self.task.origin_key = "ordinary-task"
+ self.task.save(update_fields=["origin_key"])
else:
- self.task_run.state = {"scout_trial": {"version": 1}}
+ if mismatch == "different_run":
+ TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ state={"sandbox_oauth_token_ids": [str(self.token.pk)]},
+ )
+ self.task_run.state = {}
self.task_run.save(update_fields=["state"])
with patch("posthog.storage.object_storage.read") as storage_read:
response = self.client.get(self._url())
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index f06049374ec6..82800a8580da 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -2652,6 +2652,7 @@ def delete_sandbox_custom_image(image_id: str | UUID, team_id: int, user_id: int
# These keys are reserved for server-owned run state, never PATCH input.
_PROTECTED_RUN_STATE_KEYS = frozenset(
{
+ # Worker-interpreted trial markers must never be caller-writable.
"scout_trial",
"scout_trial_judge",
"scout_trial_private",
@@ -6597,27 +6598,6 @@ def is_scout_trial_task(task_id: str | UUID, team_id: int) -> bool:
return Task.objects.filter(Task.scout_experiment_q(), id=task_id, team_id=team_id).exists()
-def is_scout_trial_judge_task_run(*, team_id: int, task_id: UUID, run_id: UUID | None = None) -> bool:
- runs = TaskRun.objects.filter(task_id=task_id, team_id=team_id, task__team_id=team_id)
- if run_id is not None:
- runs = runs.filter(id=run_id)
- row = (
- runs.filter(task__origin_product=Task.OriginProduct.SIGNALS_SCOUT, task__deleted=False)
- .values("state", "task__origin_key", "task__created_by_id")
- .first()
- )
- marker = (row["state"] or {}).get("scout_trial_judge") if row else None
- return bool(
- row
- and isinstance(marker, dict)
- and type(marker.get("version")) is int
- and marker["version"] == 1
- and type(marker.get("user_id")) is int
- and marker.get("user_id") == row["task__created_by_id"]
- and row["task__origin_key"] == f"scout-trial-judge:{marker.get('evaluation_id')}:{marker.get('launch_id')}"
- )
-
-
def list_pinned_task_ids(team_id: int, user_id: int, *, exclude_task_ids: Iterable[UUID] = ()) -> list[UUID]:
visible_tasks = _visible_task_qs(team_id, user_id).exclude(id__in=exclude_task_ids).values("id")
return list(
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 4b172e84a1ba..db2d6d67dc80 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -661,17 +661,9 @@ class Task(Taggable, DeletedMetaFields, models.Model):
(SCOUT_TRIAL_ORIGIN_KEY_PREFIX, SCOUT_TRIAL_JUDGE_ORIGIN_KEY_PREFIX)
)
- @property
- def is_scout_trial_judge(self) -> bool:
- return self.origin_product == self.OriginProduct.SIGNALS_SCOUT and (self.origin_key or "").startswith(
- SCOUT_TRIAL_JUDGE_ORIGIN_KEY_PREFIX
- )
-
def capture_event(
self, event: str, properties: dict | None = None, capture_fn: Callable[..., None] | None = None
) -> None:
- if self.is_scout_experiment:
- return
# capture_fn lets Celery callers pass a ph_scoped_capture client — the module-level
# posthoganalytics.capture silently drops events in workers (see posthog.ph_client).
try:
@@ -3194,8 +3186,6 @@ class TaskRun(models.Model):
work — but the outcome is reported so callers tracking event loss can count it.
"""
try:
- if self.task.is_scout_experiment:
- return False
# The override lets the PR webhook attribute pr_merged to the GitHub user who
# actually merged, rather than the task's assigned user.
distinct_id = distinct_id_override or (
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index fab6cd60ae17..940f412be18b 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -475,19 +475,6 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# request/response schema via @validated_request / @extend_schema.
serializer_class = TaskSerializer
- def dangerously_get_required_scopes(self, request: Request, view: object) -> list[str] | None:
- if self.action == "retrieve":
- scopes = get_authenticator_scopes(request.successful_authenticator) or []
- task_id = _sandbox_bound_task_id(request)
- if (
- "scout_experiment_internal:read" in scopes
- and task_id is not None
- and str(task_id) == self.kwargs.get("pk")
- and tasks_facade.is_scout_trial_judge_task_run(team_id=self.team_id, task_id=task_id)
- ):
- return ["scout_experiment_internal:read"]
- return None
-
def initial(self, request: Request, *args: object, **kwargs: object) -> None:
super().initial(request, *args, **kwargs)
task_id = self.kwargs.get("pk")
@@ -1808,27 +1795,6 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return False
return True
- @staticmethod
- def _is_judge_pending_prompt_cleanup(payload: object) -> bool:
- if not isinstance(payload, dict) or set(payload) != {"state_remove_keys"}:
- return False
- keys = payload["state_remove_keys"]
- return (
- isinstance(keys, list)
- and bool(keys)
- and all(
- isinstance(key, str)
- and key
- in {
- "pending_user_message",
- "pending_user_artifact_ids",
- "pending_user_message_id",
- "pending_user_message_ts",
- }
- for key in keys
- )
- )
-
def dangerously_get_required_scopes(self, request: Request, view: object) -> list[str] | None:
if self.action not in {
"append_log",
@@ -1840,34 +1806,22 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
}:
return None
scopes = get_authenticator_scopes(request.successful_authenticator) or []
- judge_cleanup = self.action in {"update", "partial_update"} and self._is_judge_pending_prompt_cleanup(
- request.data
- )
- if "scout_experiment_internal:read" in scopes and (
- self.action in {"append_log", "set_summary", "artifacts_download", "retrieve"}
- or self._is_trial_lifecycle_update(request.data)
- or judge_cleanup
+ if (
+ "task:read" in scopes
+ and "scout_experiment_internal:read" in scopes
+ and (
+ self.action in {"append_log", "set_summary"}
+ or self.action in {"update", "partial_update"}
+ and self._is_trial_lifecycle_update(request.data)
+ )
+ and run_context.is_sandbox_run_request(
+ request=request,
+ team_id=self.team_id,
+ task_id=self._task_id(),
+ run_id=self.kwargs.get("pk"),
+ )
):
- task_id = self._task_id()
- if _sandbox_bound_task_id(request) == UUID(task_id):
- try:
- run_id = UUID(self.kwargs["pk"])
- except (ValueError, TypeError, KeyError):
- raise NotFound("Task run not found")
- if tasks_facade.is_scout_trial_judge_task_run(
- team_id=self.team_id, task_id=UUID(task_id), run_id=run_id
- ):
- return ["scout_experiment_internal:read"]
- if judge_cleanup:
- return ["task:write"]
- from products.signals.backend.facade.api import (
- is_scout_trial_task_run, # noqa: PLC0415 -- keeps the scout workflow graph off ordinary API startup
- )
-
- if "task:read" in scopes and is_scout_trial_task_run(
- team_id=self.team_id, task_id=UUID(task_id), task_run_id=run_id
- ):
- return ["task:read", "scout_experiment_internal:read"]
+ return ["task:read", "scout_experiment_internal:read"]
if self.action == "artifacts_download":
return ["task:read"]
if self.action == "retrieve":
diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.py
index 3896e98459e8..3a7f25917dc4 100644
--- a/products/tasks/backend/temporal/oauth.py
+++ b/products/tasks/backend/temporal/oauth.py
@@ -166,8 +166,6 @@ def dispatched_run_scopes(task: Task, state: dict[str, Any] | None) -> PosthogMc
MCP session, or a shell fallback runs with less than the run was given. A recorded value
that does not parse fails closed to ``read_only``.
"""
- if task.is_scout_trial_judge:
- return "signals_scout_judge"
pending = (state or {}).get("pending_dispatch")
raw = pending.get("posthog_mcp_scopes") if isinstance(pending, dict) else None
if raw is None:
@@ -276,25 +274,6 @@ def create_oauth_access_token_for_run(
# `start_agent_server` mints its token with explicit scopes.
if scopes == "signals_research":
scopes = [*resolve_scopes(scopes), *RESEARCH_WITHHELD_SCOPES]
- judge_marker = (state or {}).get("scout_trial_judge")
- if task.is_scout_trial_judge or judge_marker is not None:
- from products.signals.backend.facade.api import ( # noqa: PLC0415 -- private judge validation loads evaluation storage
- is_scout_trial_judge_context,
- )
-
- if (
- not task.is_scout_trial_judge
- or task.created_by_id is None
- or not isinstance(judge_marker, dict)
- or task.origin_key
- != f"scout-trial-judge:{judge_marker.get('evaluation_id')}:{judge_marker.get('launch_id')}"
- or not is_scout_trial_judge_context(team_id=task.team_id, user_id=task.created_by_id, marker=judge_marker)
- ):
- raise TaskInvalidStateError(
- "The scout trial judge has no trusted evaluation context.",
- {"task_id": task.id},
- cause=RuntimeError("missing scout trial judge context"),
- )
with transaction.atomic():
locked_task = (
Task.objects.select_for_update(of=("self",))
@@ -313,25 +292,8 @@ def create_oauth_access_token_for_run(
loop_id = (state or {}).get("loop_id")
effective_scopes = scopes
trial_origin = locked_task.is_scout_experiment
- if locked_task.is_scout_trial_judge or judge_marker is not None:
- if (
- not locked_task.is_scout_trial_judge
- or not isinstance(judge_marker, dict)
- or locked_task.created_by_id != judge_marker.get("user_id")
- or locked_task.origin_key
- != f"scout-trial-judge:{judge_marker.get('evaluation_id')}:{judge_marker.get('launch_id')}"
- ):
- raise TaskInvalidStateError(
- "The scout trial judge has no trusted evaluation context.",
- {"task_id": task.id},
- cause=RuntimeError("missing scout trial judge context"),
- )
- effective_scopes = "signals_scout_judge"
- elif trial_origin or "scout_experiment_internal:read" in resolve_scopes(scopes):
- # The Signals facade imports its workflow graph, so load it only for trial credentials.
- from products.signals.backend.facade.api import is_scout_trial_task # noqa: PLC0415
-
- if not trial_origin or not is_scout_trial_task(team_id=task.team_id, task_id=task.id):
+ if trial_origin or "scout_experiment_internal:read" in resolve_scopes(scopes):
+ if not trial_origin:
raise TaskInvalidStateError(
"The scout trial has no trusted execution context.",
{"task_id": task.id},
diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
index 5d2d29929ce9..9cb3db4cb30f 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
@@ -226,7 +226,7 @@ class TaskProcessingContext:
Independent of ``repositories``: a run that pins repos still clones them, with a token
that carries ``contents: read`` and nothing else.
"""
- return not (self.state or {}).get("scout_trial_judge") and (self.state or {}).get("github_read_access") is True
+ return (self.state or {}).get("github_read_access") is True
@property
def sandbox_environment_id(self) -> str | None:
@@ -1245,41 +1245,6 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
state = task_run.state or {}
trial_origin = task.is_scout_experiment
- trial_marker = state.get("scout_trial")
- judge_marker = state.get("scout_trial_judge")
- if task.is_scout_trial_judge or judge_marker is not None:
- from products.signals.backend.facade.api import ( # noqa: PLC0415 -- private judges validate frozen evaluation membership
- is_scout_trial_judge_context,
- )
-
- if (
- not task.is_scout_trial_judge
- or not isinstance(judge_marker, dict)
- or task.origin_key
- != f"scout-trial-judge:{judge_marker.get('evaluation_id')}:{judge_marker.get('launch_id')}"
- or not is_scout_trial_judge_context(team_id=team.id, user_id=task.created_by.pk, marker=judge_marker)
- ):
- raise TaskInvalidStateError(
- "The scout trial judge has inconsistent private context",
- {"task_id": str(task.id), "run_id": run_id},
- cause=RuntimeError("The task identity and saved evaluation do not match"),
- )
- elif trial_origin or trial_marker is not None:
- from products.signals.backend.facade.api import (
- is_scout_trial_task, # noqa: PLC0415 -- avoids loading the scout worker graph for ordinary tasks
- )
-
- if (
- not trial_origin
- or not isinstance(trial_marker, dict)
- or trial_marker.get("version") != 1
- or not is_scout_trial_task(team_id=team.id, task_id=task.id)
- ):
- raise TaskInvalidStateError(
- "The scout run has inconsistent private context",
- {"task_id": str(task.id), "run_id": run_id},
- cause=RuntimeError("The task identity and private scout context do not match"),
- )
actor_user = get_task_run_credential_user(task, state)
if is_slack_interaction_state(state) and actor_user is None:
raise TaskInvalidStateError(
@@ -1399,11 +1364,7 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
store_skills: list[dict[str, Any]] | None = []
state[STORE_SKILLS_STATE_KEY] = []
else:
- store_skills = (
- None
- if task.is_scout_trial_judge
- else resolve_store_skills(team, actor_user or task.created_by, run_id=run_id)
- )
+ store_skills = resolve_store_skills(team, actor_user or task.created_by, run_id=run_id)
except Exception as e:
log_with_activity_context("store_skills_resolve_failed", run_id=run_id, error=str(e))
store_skills = None
@@ -1413,9 +1374,8 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
# Best-effort for the same reason as store skills.
state_remove_keys: list[str] = []
try:
- if not task.is_scout_trial_judge:
- instruction_updates, state_remove_keys = agent_instructions_state_update(task, actor_user)
- state_updates.update(instruction_updates)
+ instruction_updates, state_remove_keys = agent_instructions_state_update(task, actor_user)
+ state_updates.update(instruction_updates)
except Exception as e:
log_with_activity_context("agent_instructions_resolve_failed", run_id=run_id, error=str(e))
try:
@@ -1701,9 +1661,9 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
)
pr_authorship_mode = get_pr_authorship_mode(task, state)
user_github_integration_id = None
- if not task.is_scout_trial_judge and not (is_slack_interaction_state(state) and pr_authorship_mode.value == "user"):
+ if not (is_slack_interaction_state(state) and pr_authorship_mode.value == "user"):
user_github_integration_id = str(task.github_user_integration_id) if task.github_user_integration_id else None
- if not task.is_scout_trial_judge and user_github_integration_id is None and pr_authorship_mode.value == "user":
+ if user_github_integration_id is None and pr_authorship_mode.value == "user":
user_github_integration = resolve_user_github_integration_for_task(
task,
actor_user=actor_user,
@@ -1718,7 +1678,7 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
team_id=task.team_id,
team_uuid=str(task.team.uuid),
organization_id=str(task.team.organization_id),
- github_integration_id=None if task.is_scout_trial_judge else task.github_integration_id,
+ github_integration_id=task.github_integration_id,
github_user_integration_id=user_github_integration_id,
repository=run_repository,
distinct_id=distinct_id,
@@ -1730,7 +1690,7 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
pr_loop_enabled=pr_loop_enabled,
pr_babysit_enabled=pr_babysit_enabled,
context_layer_enabled=context_layer_enabled,
- state={key: value for key, value in state.items() if key != "scout_trial_private"},
+ state=state,
_branch=task_run.branch,
sandbox_environment_name=sandbox_environment_name,
allowed_domains=allowed_domains,
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index 70ba50da8eb3..beba13ec3d8e 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -419,8 +419,6 @@ def _resolve_sandbox_github_token(
one only after the create-time Desktop gate passed. So a repo-less run with no integration
stays credential-less, and an entitled discussion can clone a private repository and push.
"""
- if task.is_scout_trial_judge is True:
- return ""
if ctx.github_read_access:
github_token = get_readonly_github_token(ctx.team_id) or ""
emit_agent_log(
@@ -583,7 +581,7 @@ def _build_environment_variables(
environment_variables.update(run_gateway_env_vars(ctx, task))
environment_variables.update(mcp_exec_skills_env_vars(ctx))
- if settings.DEBUG or (ctx.state or {}).get("scout_trial") or (ctx.state or {}).get("scout_trial_judge"):
+ if settings.DEBUG or task.is_scout_experiment is True:
# Pinned eval runs must not switch models after an overload.
environment_variables["POSTHOG_DISABLE_MODEL_FALLBACK"] = "1"
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index 6b3f51f942a7..d910b854d0aa 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -504,54 +504,38 @@ def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes, sandbo
if ctx.model_access.adapter == "codex":
codex_run_token = create_codex_subscription_run_token(task_run, sandbox_id=sandbox_id)
- mcp_configs = (
- []
- if task.is_scout_trial_judge is True
- else get_sandbox_ph_mcp_configs(
- token=access_token,
- project_id=ctx.team_id,
- scopes=scopes,
- interaction_origin=ctx.interaction_origin,
- slack_reply_context=ctx.slack_reply_context,
- task_id=str(ctx.task_id),
- origin_product=task.origin_product,
- exclude_tools=mcp_exclude_tools_from_state(ctx.state),
- )
+ mcp_configs = get_sandbox_ph_mcp_configs(
+ token=access_token,
+ project_id=ctx.team_id,
+ scopes=scopes,
+ interaction_origin=ctx.interaction_origin,
+ slack_reply_context=ctx.slack_reply_context,
+ task_id=str(ctx.task_id),
+ origin_product=task.origin_product,
+ exclude_tools=mcp_exclude_tools_from_state(ctx.state),
)
include_personal = _include_personal_mcp_for_task(task)
- user_mcp_configs = (
- []
- if task.is_scout_trial_judge is True
- else get_user_mcp_server_configs(
- token=access_token,
- team_id=ctx.team_id,
- user_id=actor_user.id if actor_user else None,
- include_personal=include_personal,
- interaction_origin=ctx.interaction_origin,
- slack_reply_context=ctx.slack_reply_context,
- allowed_installation_ids=loop_mcp_installation_allowlist(ctx.state),
- origin_product=task.origin_product,
- task_agent_key=task.mcp_builtin_agent_key,
- credential_owner_id=task.mcp_credential_owner_id,
- allowed_gateway_server_ids=task.mcp_gateway_server_allowlist,
- )
+ user_mcp_configs = get_user_mcp_server_configs(
+ token=access_token,
+ team_id=ctx.team_id,
+ user_id=actor_user.id if actor_user else None,
+ include_personal=include_personal,
+ interaction_origin=ctx.interaction_origin,
+ slack_reply_context=ctx.slack_reply_context,
+ allowed_installation_ids=loop_mcp_installation_allowlist(ctx.state),
+ origin_product=task.origin_product,
+ task_agent_key=task.mcp_builtin_agent_key,
+ credential_owner_id=task.mcp_credential_owner_id,
+ allowed_gateway_server_ids=task.mcp_gateway_server_allowlist,
)
if user_mcp_configs:
mcp_configs = mcp_configs + user_mcp_configs
- imported_mcp_configs = (
- []
- if task.is_scout_trial_judge is True
- else get_imported_mcp_server_configs(task_run, {config.name for config in mcp_configs})
- )
+ imported_mcp_configs = get_imported_mcp_server_configs(task_run, {config.name for config in mcp_configs})
if imported_mcp_configs:
mcp_configs = mcp_configs + imported_mcp_configs
- relayed_names = (
- []
- if task.is_scout_trial_judge is True
- else get_relayed_mcp_server_names(task_run, {config.name for config in mcp_configs})
- )
+ relayed_names = get_relayed_mcp_server_names(task_run, {config.name for config in mcp_configs})
if relayed_names:
emit_agent_log(
ctx.run_id,
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
index a5721bd4e107..a764a0b4ccbb 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
@@ -12,7 +12,6 @@ from temporalio.testing import ActivityEnvironment
from posthog.models import OrganizationMembership, User
from posthog.models.user_integration import UserIntegration
-from products.signals.backend.models import SignalScoutRun
from products.skills.backend.models.skills import LLMSkill
from products.tasks.backend.constants import (
AGENT_PROXY_KEEP_STREAM_OPEN_FEATURE_FLAG,
@@ -248,22 +247,12 @@ class TestGetTaskProcessingContextActivity:
email="[email protected]", password=None, first_name="Owner", distinct_id="subscription-owner"
)
OrganizationMembership.objects.create(organization=test_task.team.organization, user=owner)
- private_payload = {"reports": {"synthetic-report": {"summary": "Private observation. " * 20_000}}}
extra_state: dict[str, object] = {"claude_model_access": "own-subscription"} if subscription else {}
if is_trial:
test_task.origin_product = Task.OriginProduct.SIGNALS_SCOUT
test_task.origin_key = "scout-trial:11111111-1111-1111-1111-111111111111"
test_task.save(update_fields=["origin_product", "origin_key"])
- extra_state.update({"scout_trial": {"version": 1}, "scout_trial_private": private_payload})
task_run = test_task.create_run(acting_user_id=owner.id, extra_state=extra_state)
- if is_trial:
- SignalScoutRun.objects.for_team(test_task.team_id).create(
- team_id=test_task.team_id,
- task_run=task_run,
- skill_name="signals-scout-fixture",
- skill_version=1,
- metadata={"scout_trial": {"version": 1}},
- )
input_data = GetTaskProcessingContextInput(run_id=str(task_run.id))
with (
@@ -296,39 +285,6 @@ class TestGetTaskProcessingContextActivity:
assert result.agent_otel_telemetry_enabled is (not is_trial)
assert result.context_layer_enabled is (not is_trial)
assert result.state is not None
- assert "scout_trial_private" not in result.state
- if is_trial:
- assert result.state["scout_trial"] == {"version": 1}
- task_run.refresh_from_db()
- assert task_run.state["scout_trial_private"] == private_payload
-
- @pytest.mark.django_db(transaction=True)
- @pytest.mark.parametrize("missing", ["origin", "marker", "version", "bridge"])
- def test_private_context_requires_matching_server_provenance(
- self, activity_environment: ActivityEnvironment, test_task: Task, missing: str
- ) -> None:
- if missing != "origin":
- test_task.origin_product = Task.OriginProduct.SIGNALS_SCOUT
- test_task.origin_key = "scout-trial:11111111-1111-1111-1111-111111111111"
- test_task.save(update_fields=["origin_product", "origin_key"])
- extra_state = {} if missing == "marker" else {"scout_trial": {"version": 2 if missing == "version" else 1}}
- task_run = test_task.create_run(extra_state=extra_state)
- if missing != "bridge":
- SignalScoutRun.objects.for_team(test_task.team_id).create(
- team_id=test_task.team_id,
- task_run=task_run,
- skill_name="signals-scout-fixture",
- skill_version=1,
- metadata={"scout_trial": {"version": 1}},
- )
-
- async def execute_context() -> TaskProcessingContext:
- return await activity_environment.run(
- get_task_processing_context, GetTaskProcessingContextInput(run_id=str(task_run.id))
- )
-
- with pytest.raises(TaskInvalidStateError, match="inconsistent private context"):
- async_to_sync(execute_context)()
@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize(
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
index d864a217d814..9744f4362a0e 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
@@ -66,43 +66,24 @@ def _context_for_desktop_bootstrap(
)
[email protected]("marker", [None, "scout_trial", "scout_trial_judge"])
[email protected]("is_trial", [False, True])
@override_settings(
DEBUG=False,
SANDBOX_AGENT_OTEL_LOGS_URL="https://telemetry.example/logs",
SANDBOX_AGENT_OTEL_LOGS_TOKEN="synthetic-token",
)
-def test_private_trial_keeps_the_pinned_model_after_overload(mocker, marker: str | None) -> None:
+def test_private_trial_keeps_the_pinned_model_without_agent_telemetry(mocker, is_trial: bool) -> None:
context = _context_for_desktop_bootstrap()
- context.state = {marker: {"version": 1}} if marker else {}
context.agent_otel_telemetry_enabled = True
for name in ("run_gateway_env_vars", "mcp_exec_skills_env_vars", "get_git_identity_env_vars"):
mocker.patch.object(provision_sandbox_module, name, return_value={})
mocker.patch.object(provision_sandbox_module, "get_sandbox_jwt_public_key", return_value="public-key")
- task = mocker.Mock(is_scout_experiment=marker is not None)
+ task = mocker.Mock(is_scout_experiment=is_trial)
environment = provision_sandbox_module._build_environment_variables(context, task, "", "fake-token")
- assert environment.get("POSTHOG_DISABLE_MODEL_FALLBACK") == ("1" if marker else None)
- assert environment.get("POSTHOG_AGENT_OTEL_LOGS_TOKEN") == (None if marker else "synthetic-token")
-
-
-def test_judge_does_not_inherit_github_credentials(mocker) -> None:
- context = _context_for_desktop_bootstrap()
- context.state = {"github_read_access": True, "scout_trial_judge": {"version": 1}}
- task = Task(origin_product="signals_scout", origin_key="scout-trial-judge:synthetic-evaluation:synthetic-launch")
- token = mocker.patch.object(provision_sandbox_module, "get_sandbox_github_token")
- readonly_token = mocker.patch.object(provision_sandbox_module, "get_readonly_github_token")
-
- assert (
- provision_sandbox_module._resolve_sandbox_github_token(
- context, task=task, actor_user=None, repository=None, has_repo=False
- )
- == ""
- )
- assert context.github_read_access is False
- token.assert_not_called()
- readonly_token.assert_not_called()
+ assert environment.get("POSTHOG_DISABLE_MODEL_FALLBACK") == ("1" if is_trial else None)
+ assert environment.get("POSTHOG_AGENT_OTEL_LOGS_TOKEN") == (None if is_trial else "synthetic-token")
class _ShellSandbox:
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
index f77140690fe8..9fc0c854c1b6 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
@@ -18,7 +18,6 @@ from products.tasks.backend.exceptions import (
from products.tasks.backend.logic.services.launch_preparation_metrics import record_launch_preparation_ms
from products.tasks.backend.logic.services.modal_sandbox import ModalSandbox
from products.tasks.backend.logic.services.sandbox import ExecutionResult, sandbox_repo_path
-from products.tasks.backend.models import Task
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
from products.tasks.backend.temporal.process_task.activities.start_agent_server import (
CollectAgentShadowResultInput,
@@ -755,34 +754,6 @@ def test_prepare_launch_releases_boot_milestone_claims(mocker) -> None:
release.assert_called_once_with("run-id", True)
-def test_prepare_judge_has_no_live_or_inherited_mcp_connections(mocker) -> None:
- prefix = "products.tasks.backend.temporal.process_task.activities.start_agent_server"
- _mock_prepare_launch_dependencies(mocker)
- task = Task(
- team_id=1,
- internal=True,
- origin_product=Task.OriginProduct.SIGNALS_SCOUT,
- origin_key="scout-trial-judge:00000000-0000-0000-0000-000000000001:00000000-0000-0000-0000-000000000002",
- )
- mocker.patch(f"{prefix}.Task.objects.select_related").return_value.get.return_value = task
- resolvers = [
- mocker.patch(f"{prefix}.{name}", side_effect=AssertionError("Judge must not resolve MCP connections"))
- for name in (
- "get_sandbox_ph_mcp_configs",
- "get_user_mcp_server_configs",
- "get_imported_mcp_server_configs",
- "get_relayed_mcp_server_names",
- )
- ]
-
- params = _prepare_launch(_context(), "signals_scout_judge", "sandbox-id")
-
- assert params.mcp_configs == []
- assert params.relayed_mcp_servers == []
- for resolver in resolvers:
- resolver.assert_not_called()
-
-
@pytest.mark.parametrize(
"pr_base,lookup_error,lookup_hangs,expected",
[
diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
index f6c1b4c519eb..7d9442c7508e 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -136,25 +136,6 @@ def _build_context(
)
[email protected]("marker", [None, "scout_trial", "scout_trial_judge"])
-async def test_private_trial_workflow_keeps_metrics_without_analytics(
- monkeypatch: pytest.MonkeyPatch, marker: str | None
-) -> None:
- workflow_instance = ProcessTaskWorkflow()
- workflow_instance._context = _build_context(
- github_integration_id=None, state={marker: {"version": 1}} if marker else {}
- )
- execute = AsyncMock()
- monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", execute)
-
- await workflow_instance._track_workflow_event("sandbox_started", {"task_id": "task-id"})
-
- execute.assert_awaited_once()
- assert execute.call_args.args[0] == track_workflow_event
- assert execute.call_args.args[1].capture_analytics is (marker is None)
-
-
def test_activity_error_properties_includes_failed_activity_context():
error = ActivityError(
"Activity task timed out",
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 7b20d2be8c60..dc25610c9d2d 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -2751,10 +2751,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
"organization": self.context.organization_id,
"project": self.context.team_uuid,
},
- capture_analytics=capture_analytics
- and not bool(
- (self.context.state or {}).get("scout_trial") or (self.context.state or {}).get("scout_trial_judge")
- ),
+ capture_analytics=capture_analytics,
)
await workflow.execute_activity(
track_workflow_event,
diff --git a/products/tasks/backend/temporal/tests/test_oauth.py b/products/tasks/backend/temporal/tests/test_oauth.py
index 66e56b2bab71..8f4366452d99 100644
--- a/products/tasks/backend/temporal/tests/test_oauth.py
+++ b/products/tasks/backend/temporal/tests/test_oauth.py
@@ -10,7 +10,6 @@ from posthog.models.organization import OrganizationMembership
from posthog.models.user import User
from posthog.temporal.oauth import PosthogMcpScopes, resolve_scopes
-from products.signals.backend.models import SignalScoutRun
from products.tasks.backend.exceptions import TaskInvalidStateError
from products.tasks.backend.models import (
INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGIN,
@@ -374,12 +373,11 @@ def test_run_token_rejects_previous_task_owner(mock_create: MagicMock) -> None:
@pytest.mark.django_db
@pytest.mark.parametrize(
- "trial_origin,bridge,requested,allowed",
+ "trial_origin,requested,allowed",
[
- (False, True, "signals_scout_experiment", False),
- (False, False, ["scout_experiment_internal:read"], False),
- (True, False, "full", False),
- (True, True, "full", True),
+ (False, "signals_scout_experiment", False),
+ (False, ["scout_experiment_internal:read"], False),
+ (True, "full", True),
],
)
@patch("products.tasks.backend.temporal.oauth.is_builtin_agent_enforcement_enabled", return_value=False)
@@ -389,7 +387,6 @@ def test_private_scout_token_requires_trusted_task_and_cannot_be_widened(
mock_enforcement: MagicMock,
test_task: Task,
trial_origin: bool,
- bridge: bool,
requested: PosthogMcpScopes,
allowed: bool,
) -> None:
@@ -397,15 +394,7 @@ def test_private_scout_token_requires_trusted_task_and_cannot_be_widened(
test_task.origin_product = Task.OriginProduct.SIGNALS_SCOUT
test_task.origin_key = "scout-trial:11111111-1111-1111-1111-111111111111"
test_task.save(update_fields=["origin_product", "origin_key"])
- task_run = test_task.create_run(extra_state={"scout_trial": {"version": 1}})
- if bridge:
- SignalScoutRun.objects.for_team(test_task.team_id).create(
- team_id=test_task.team_id,
- task_run=task_run,
- skill_name="signals-scout-fixture",
- skill_version=1,
- metadata={"scout_trial": {"version": 1}},
- )
+ task_run = test_task.create_run()
if not allowed:
with pytest.raises(TaskInvalidStateError, match="no trusted execution context"):
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index ee3347d2565d..b16b54ac9ec3 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -45,7 +45,6 @@ from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV, ARRAY_APP_CLIENT_ID_
from posthog.utils import absolute_uri
from products.posthog_ai.backend.models.assistant import Conversation
-from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
from products.slack_app.backend.models import SlackThreadTaskMapping
from products.tasks.backend.access import DesktopAccessResolutionError
from products.tasks.backend.constants import DEV_STACK_PREVIEW_PORT
@@ -405,14 +404,7 @@ class TestScoutTrialTaskVisibility(BaseTaskAPITest):
)
for index in range(2)
]
- self.trial_runs = [
- TaskRun.objects.create(
- team=self.team,
- task=task,
- state={"scout_trial": {"id": "private"}, "scout_trial_private": {"reports": []}},
- )
- for task in self.trial_tasks
- ]
+ self.trial_runs = [TaskRun.objects.create(team=self.team, task=task) for task in self.trial_tasks]
for task in self.trial_tasks:
TaskPin.objects.create(user=self.user, task=task)
TaskSearchDocument.objects.for_team(self.team.id).create(
@@ -460,22 +452,7 @@ class TestScoutTrialTaskVisibility(BaseTaskAPITest):
client_id: str = ARRAY_APP_CLIENT_ID_DEV,
scopes: str = "task:read internal_run:read scout_experiment_internal:read",
) -> APIClient:
- task, run = self.trial_tasks[0], self.trial_runs[0]
- assert task.origin_key is not None
- marker = {"version": 1, "launch_id": task.origin_key.removeprefix("scout-trial:")}
- run.state = {"scout_trial": marker, "scout_trial_private": {"reports": []}}
- run.save(update_fields=["state"])
- config = SignalScoutConfig.objects.for_team(self.team.id).create(
- team=self.team, skill_name="signals-scout-synthetic-log"
- )
- SignalScoutRun.objects.for_team(self.team.id).create(
- team=self.team,
- task_run=run,
- scout_config=config,
- skill_name=config.skill_name,
- skill_version=1,
- metadata={"scout_trial": marker},
- )
+ task = self.trial_tasks[0]
return self._sandbox_oauth_client(
task.id,
bound=bound,
@@ -483,122 +460,6 @@ class TestScoutTrialTaskVisibility(BaseTaskAPITest):
scopes=scopes,
)
- def test_judge_token_can_only_read_inputs_and_record_its_own_run(self) -> None:
- task, run = self.trial_tasks[0], self.trial_runs[0]
- marker = {
- "version": 1,
- "user_id": self.user.id,
- **{
- key: str(uuid.uuid4())
- for key in (
- "evaluation_id",
- "launch_id",
- "context_id",
- "source_task_id",
- "source_task_run_id",
- "source_scout_run_id",
- )
- },
- }
- task.origin_key = f"scout-trial-judge:{marker['evaluation_id']}:{marker['launch_id']}"
- task.save(update_fields=["origin_key"])
- run.state = {
- "scout_trial_judge": marker,
- "pending_user_message": "Use the attached synthetic run log",
- "pending_user_artifact_ids": [],
- "pending_user_message_id": str(uuid.uuid4()),
- "pending_user_message_ts": "123456789.000000",
- }
- storage_path = f"tasks/{task.id}/runs/{run.id}/artifacts/run-log.jsonl"
- run.artifacts = [
- build_task_artifact_entry(
- artifact_id=str(uuid.uuid4()),
- name="run-log.jsonl",
- storage_path=storage_path,
- artifact_type="file",
- source="internal",
- size=21,
- content_type="application/x-ndjson",
- )
- ]
- run.save(update_fields=["state", "artifacts"])
- client = self._sandbox_oauth_client(task.id, scopes="scout_experiment_internal:read")
- base = f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/"
-
- assert client.get(f"/api/projects/@current/tasks/{task.id}/").status_code == status.HTTP_200_OK
- assert client.get(base).status_code == status.HTTP_200_OK
- with patch.object(object_storage, "read_bytes", return_value=b'{"tool":"synthetic"}\n'):
- response = client.post(f"{base}artifacts/download/", {"storage_path": storage_path}, format="json")
- assert response.status_code == status.HTTP_200_OK, response.content
- assert (
- client.post(
- f"{base}artifacts/download/", {"storage_path": "other-run/private-log.jsonl"}, format="json"
- ).status_code
- == status.HTTP_404_NOT_FOUND
- )
- with patch("products.tasks.backend.models.TaskRun.heartbeat_workflow"):
- response = client.patch(
- base, {"status": "in_progress", "state": {"agent_version": "test-judge"}}, format="json"
- )
- assert response.status_code == status.HTTP_200_OK, response.json()
- pending_keys = [
- "pending_user_message",
- "pending_user_artifact_ids",
- "pending_user_message_id",
- "pending_user_message_ts",
- ]
- assert client.patch(base, {"state_remove_keys": pending_keys}, format="json").status_code == status.HTTP_200_OK
- assert (
- client.patch(base, {"state_remove_keys": [*pending_keys, "scout_trial_judge"]}, format="json").status_code
- == status.HTTP_403_FORBIDDEN
- )
- assert (
- client.patch(
- base, {"state": {"pending_user_message": "Replace the trusted prompt"}}, format="json"
- ).status_code
- == status.HTTP_403_FORBIDDEN
- )
- assert (
- client.patch(f"{base}set_summary/", {"summary": "Saved a rubric assessment"}, format="json").status_code
- == status.HTTP_200_OK
- )
- response = client.patch(
- f"{base}set_output/",
- {"output": {"summary": "Synthetic rubric assessment", "criteria": []}},
- format="json",
- )
- assert response.status_code == status.HTTP_403_FORBIDDEN
- for path in (
- "/api/projects/@current/tasks/",
- f"/api/projects/@current/tasks/{self.ordinary_task.id}/",
- f"/api/projects/@current/tasks/{self.trial_tasks[1].id}/runs/{self.trial_runs[1].id}/",
- "/api/projects/@current/insights/",
- ):
- assert client.get(path).status_code == status.HTTP_403_FORBIDDEN, path
- assert (
- client.patch(base, {"state": {"scout_trial_judge": {}}}, format="json").status_code
- == status.HTTP_403_FORBIDDEN
- )
- assert client.post(f"{base}cancel/", {}, format="json").status_code == status.HTTP_403_FORBIDDEN
- assert (
- client.patch(
- f"/api/projects/@current/tasks/{self.trial_tasks[1].id}/runs/{self.trial_runs[1].id}/set_output/",
- {"output": {"summary": "Cannot change another run"}},
- format="json",
- ).status_code
- == status.HTTP_403_FORBIDDEN
- )
- with patch.object(tasks_facade, "resume_task_run_in_cloud") as resume:
- assert (
- self.client.post(f"{base}resume_in_cloud/", {}, format="json").status_code
- == status.HTTP_400_BAD_REQUEST
- )
- resume.assert_not_called()
- run.refresh_from_db()
- assert run.state["scout_trial_judge"] == marker
- assert all(key not in run.state for key in pending_keys)
- assert not SignalScoutRun.objects.for_team(self.team.id).filter(task_run=run).exists()
-
def test_trial_can_append_own_log_without_general_task_write_access(self) -> None:
task, run = self.trial_tasks[0], self.trial_runs[0]
client = self._trial_log_client()
@@ -615,7 +476,6 @@ class TestScoutTrialTaskVisibility(BaseTaskAPITest):
response = client.post(f"{base}append_log/", {"entries": [entry]}, format="json")
logs = client.get(f"{base}session_logs/")
assert response.status_code == status.HTTP_200_OK, response.json()
- assert "scout_trial_private" not in response.json()["state"]
assert logs.status_code == status.HTTP_200_OK
assert logs.json()[0]["message"] == entry["message"]
usage = {"input_tokens": 12, "output_tokens": 4}
@@ -637,8 +497,6 @@ class TestScoutTrialTaskVisibility(BaseTaskAPITest):
assert run.state is not None
assert run.state["token_usage"] == usage
assert run.state["agent_version"] == "test-agent"
- marker = run.state["scout_trial"]
- assert run.state["scout_trial_private"] == {"reports": []}
response = client.patch(
f"{base}set_summary/",
{"summary": "Reviewed recent exports", "tags": ["synthetic-trial-tag"]},
@@ -646,8 +504,6 @@ class TestScoutTrialTaskVisibility(BaseTaskAPITest):
)
assert response.status_code == status.HTTP_200_OK, response.json()
assert response.json()["task_summary"] == "Reviewed recent exports"
- assert "scout_trial" not in response.json()["state"]
- assert "scout_trial_private" not in response.json()["state"]
run.refresh_from_db()
assert run.state is not None and run.state["task_summary"] == "Reviewed recent exports"
assert run.state["task_tags"] == ["synthetic-trial-tag"]
@@ -672,20 +528,16 @@ class TestScoutTrialTaskVisibility(BaseTaskAPITest):
assert run.state is not None
assert run.state["agent_version"] == "test-agent"
assert run.state["token_usage"] == usage
- assert run.state["scout_trial"] == marker
- assert run.state["scout_trial_private"] == {"reports": []}
@parameterized.expand(
[
("model", {"state": {"model": "other"}}),
("effort", {"state": {"reasoning_effort": "low"}}),
- ("marker", {"state": {"scout_trial": {}}}),
- ("private", {"state": {"scout_trial_private": {}}}),
("other_state", {"state": {"custom_key": "value"}}),
("mixed_state", {"status": "failed", "state": {"agent_version": "test-agent", "model": "other"}}),
("state_type", {"status": "failed", "state": ["agent_version"]}),
("state_null", {"status": "failed", "state": None}),
- ("remove", {"state_remove_keys": ["scout_trial"]}),
+ ("remove", {"state_remove_keys": ["model"]}),
("branch", {"branch": "other"}),
("output", {"output": {"url": "https://example.com"}}),
("status_type", {"status": {"value": "failed"}}),
@@ -708,9 +560,7 @@ class TestScoutTrialTaskVisibility(BaseTaskAPITest):
("unbound",),
("sibling_task",),
("other_run",),
- ("missing_bridge",),
- ("wrong_origin",),
- ("wrong_marker",),
+ ("unregistered_token",),
("foreign_client",),
("gateway_only",),
]
@@ -730,13 +580,8 @@ class TestScoutTrialTaskVisibility(BaseTaskAPITest):
task, run = self.trial_tasks[1], self.trial_runs[1]
elif case == "other_run":
run = TaskRun.objects.create(task=task, team=self.team)
- elif case == "missing_bridge":
- SignalScoutRun.objects.for_team(self.team.id).filter(task_run=run).delete()
- elif case == "wrong_origin":
- task.origin_key = f"scout-trial:{uuid.uuid4()}"
- task.save(update_fields=["origin_key"])
- elif case == "wrong_marker":
- run.state = {"scout_trial": {"version": 1, "launch_id": str(uuid.uuid4())}}
+ elif case == "unregistered_token":
+ run.state = {"sandbox_oauth_token_ids": [str(uuid.uuid4())]}
run.save(update_fields=["state"])
run.refresh_from_db()
@@ -10177,7 +10022,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
("session", None, status.HTTP_200_OK),
("read_scope", "task:read", status.HTTP_200_OK),
("unrelated_scope", "query:read", status.HTTP_403_FORBIDDEN),
- ("judge_scope", "scout_experiment_internal:read", status.HTTP_403_FORBIDDEN),
+ ("internal_scope_only", "scout_experiment_internal:read", status.HTTP_403_FORBIDDEN),
]
)
@patch("posthog.storage.object_storage.read_bytes")
diff --git a/products/tasks/backend/tests/test_channels_api.py b/products/tasks/backend/tests/test_channels_api.py
index cc1e88098c4f..64d252317dec 100644
--- a/products/tasks/backend/tests/test_channels_api.py
+++ b/products/tasks/backend/tests/test_channels_api.py
@@ -1011,11 +1011,11 @@ class ThreadMessagesAPITestCase(ChannelTaskAPITestCase):
("unbound_trial", "scout-trial:", "unbound", False, status.HTTP_404_NOT_FOUND),
("sibling_judge", "scout-trial-judge:", "other", False, status.HTTP_404_NOT_FOUND),
("ordinary_task", "", "other", False, status.HTTP_200_OK),
- ("judge_token", "scout-trial-judge:", "own", True, status.HTTP_403_FORBIDDEN),
+ ("internal_scope_only", "scout-trial:", "own", True, status.HTTP_403_FORBIDDEN),
]
)
def test_sandbox_thread_reads_respect_trial_task_binding(
- self, _name: str, origin_prefix: str, binding: str, judge_token: bool, expected_status: int
+ self, _name: str, origin_prefix: str, binding: str, internal_scope_only: bool, expected_status: int
) -> None:
task = Task.objects.create(
team=self.team,
@@ -1046,7 +1046,9 @@ class ThreadMessagesAPITestCase(ChannelTaskAPITestCase):
user=self.author,
application=application,
token=f"pha_thread_{uuid4().hex}",
- scope=" ".join(resolve_scopes("signals_scout_judge" if judge_token else "signals_scout_experiment")),
+ scope="scout_experiment_internal:read"
+ if internal_scope_only
+ else " ".join(resolve_scopes("signals_scout_experiment")),
expires=django_timezone.now() + timedelta(hours=1),
scoped_teams=[self.team.id],
sandbox_task_id=task.id if binding == "own" else self.task.id if binding == "other" else None,
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index 9701c1a589e1..c15d42cccb93 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -286,9 +286,8 @@ class TestFacadeReadsAndMappers(TestCase):
"store_skills": [{"name": "my-skill", "description": "Mine.", "version": 1}],
"systemPrompt": {"type": "preset", "preset": "claude_code", "append": "PostHog AI"},
"sandbox_jwt_kid": "secret",
- "scout_trial": {"id": "private-trial"},
- "scout_trial_private": {"reports": [{"title": "Saved candidate"}]},
- "posthog_mcp_scopes": "signals_scout_experiment",
+ "unknown_server_context": {"title": "Saved context"},
+ "posthog_mcp_scopes": "read_only",
"task_summary": "Private workflow context",
"token_cost": {"model": {"provider": {"cost_microusd": 4, "request_ids": ["request-1"]}}},
"compute_cost": 2,
@@ -310,8 +309,7 @@ class TestFacadeReadsAndMappers(TestCase):
assert ("store_skills" in detail.state) is include_agent_state
assert ("systemPrompt" in detail.state) is include_agent_state
assert "sandbox_jwt_kid" not in detail.state
- assert "scout_trial" not in detail.state
- assert "scout_trial_private" not in detail.state
+ assert "unknown_server_context" not in detail.state
assert "posthog_mcp_scopes" not in detail.state
assert {"token_cost", "compute_cost", "token_cost_incomplete", "unprocessed_request_ids"}.isdisjoint(
detail.state
diff --git a/products/tasks/backend/tests/test_task_capture.py b/products/tasks/backend/tests/test_task_capture.py
index 7206b3a8539c..57a58a5eafe7 100644
--- a/products/tasks/backend/tests/test_task_capture.py
+++ b/products/tasks/backend/tests/test_task_capture.py
@@ -55,15 +55,11 @@ class TestTaskCaptureEvent(TestCase):
@parameterized.expand(
[
- (Task.OriginProduct.SIGNALS_SCOUT, "scout-trial:00000000-0000-4000-8000-000000000001", True),
- (Task.OriginProduct.SIGNALS_SCOUT, "scheduled-scout", False),
- (Task.OriginProduct.SIGNALS_SCOUT, None, False),
- (Task.OriginProduct.USER_CREATED, "scout-trial:00000000-0000-4000-8000-000000000001", False),
+ (Task.OriginProduct.SIGNALS_SCOUT, "scout-trial:00000000-0000-4000-8000-000000000001"),
+ (Task.OriginProduct.USER_CREATED, None),
]
)
- def test_trial_task_and_run_captures_stay_private(
- self, origin_product: str, origin_key: str | None, suppressed: bool
- ) -> None:
+ def test_task_and_run_lifecycle_events_are_captured(self, origin_product: str, origin_key: str | None) -> None:
with (
patch("products.tasks.backend.models.posthoganalytics.capture") as capture,
self.captureOnCommitCallbacks(execute=True),
@@ -80,10 +76,9 @@ class TestTaskCaptureEvent(TestCase):
task.capture_event("task_updated")
captured = run.capture_event("task_run_completed")
- self.assertEqual(captured, not suppressed)
+ self.assertTrue(captured)
events = {call.kwargs["event"] for call in capture.call_args_list}
- expected = set() if suppressed else {"task_created", "task_run_created", "task_updated", "task_run_completed"}
- self.assertEqual(events, expected)
+ self.assertEqual(events, {"task_created", "task_run_created", "task_updated", "task_run_completed"})
@parameterized.expand(
[