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): run trial judges through ordinary internal tasks (#113595)

Alex Lebedevf5cb79cad1c4
diff --git a/docs/internal/scout-online-evals-devbox.md b/docs/internal/scout-online-evals-devbox.md
index 0ca7727a8b06..210d9dfa7884 100644
--- a/docs/internal/scout-online-evals-devbox.md
+++ b/docs/internal/scout-online-evals-devbox.md
@@ -27,7 +27,7 @@ SCOUT_LIVE_TRIALS_PRIVATE_CAPTURE=true
Enable the `scout-trials` feature flag for the `project` group with `id = 2`. A missing or unreadable flag blocks new work. Trials also require private capture and the gateway configuration above. The team-2 and staff restrictions still apply even if the flag targets another project. Production MCP also hides trial tools until the flag is enabled.
-Switching the flag off blocks new trials, resumes, and queued scout or judge work. Already-running scouts and judge jobs can finish, and saved results remain readable. After re-enabling the flag, resume interrupted trials to recover saved work.
+Switching the flag off blocks new trials, resumes, queued scout work and new judge dispatch. Judges already dispatched to Tasks can finish, even if their sandbox has not started yet. Saved results remain readable.
Verify the ports and Docker host mapping. Sandbox URLs and MCP's `POSTHOG_API_BASE_URL` must reach services directly, without the Coder login proxy. Keep `POSTHOG_PUBLIC_URL` and `SITE_URL` on the browser URL.
The backend and scout orchestration worker use their existing `AI_GATEWAY_URL` and `AI_GATEWAY_API_KEY`. Private report checks mint and revoke temporary tokens with that service credential. Only the Tasks worker that provisions sandboxes needs `SANDBOX_AI_GATEWAY_URL` and `SANDBOX_AI_GATEWAY_MINT_KEY`. Both credentials must allow private token creation and team attribution in the intended paying project. The `signals_scout` product must not bill customer credits.
@@ -55,6 +55,12 @@ Variants and retries share a saved copy of the project's scout memory, notes and
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.
-The judge has no live project tools, external MCP connections or repository credentials. 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.
+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.
+
+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.
Before dispatch, the full batch must fit the project's existing daily scout budget. Resuming counts only runs that have not already started. This is a capacity check, not a reservation: simultaneous submissions can still race, and the budget remains shared with ordinary scouts.
diff --git a/products/signals/backend/scout_harness/trial_judge.py b/products/signals/backend/scout_harness/trial_judge.py
index 3166e3f3225d..565cbe18f3c5 100644
--- a/products/signals/backend/scout_harness/trial_judge.py
+++ b/products/signals/backend/scout_harness/trial_judge.py
@@ -58,18 +58,23 @@ def _assert_scout_available(snapshot: TrialEvaluationSnapshot, evidence: TrialRu
raise TrialJudgeValidationError("The saved evidence is not bound to a scout task run.")
if evidence not in snapshot.runs:
raise TrialJudgeValidationError("The evidence does not belong to this evaluation.")
+ if evidence.execution_status != "completed" or evidence.exclusion_reason is not None:
+ raise TrialJudgeValidationError("The saved scout run is not eligible for judging.")
run = (
SignalScoutRun.objects.for_team(snapshot.team_id)
.select_related("task_run__task")
.filter(
id=evidence.run_id,
scout_config_id=snapshot.config_id,
+ skill_name=snapshot.rubric_reference_context.skill_name,
task_run_id=evidence.task_run_id,
task_run__team_id=snapshot.team_id,
task_run__task_id=evidence.task_id,
task_run__task__team_id=snapshot.team_id,
task_run__task__created_by_id=snapshot.user_id,
task_run__task__deleted=False,
+ task_run__task__origin_product="signals_scout",
+ task_run__task__origin_key=f"scout-trial:{evidence.launch_id}",
)
.first()
)
@@ -81,6 +86,7 @@ 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:
@@ -114,21 +120,12 @@ class _JudgeRun:
]
tasks_facade.attach_task_run_input_files(team_id=self.snapshot.team_id, run_id=run_id, files=files)
return {
- "scout_trial_judge": {
- "version": 1,
- "evaluation_id": str(self.snapshot.evaluation_id),
- "launch_id": str(self.evidence.launch_id),
- "context_id": str(self.snapshot.context_id),
- "user_id": self.snapshot.user_id,
- "source_task_id": str(self.evidence.task_id),
- "source_task_run_id": str(self.evidence.task_run_id),
- "source_scout_run_id": str(self.evidence.run_id),
- },
"pending_user_message": self.prompt,
# Startup and Temporal forwarding must recognize the same initial message.
"pending_user_message_id": str(run_id),
"pending_user_artifact_ids": [file.id for file in files],
"mcp_gateway_server_ids": [],
+ "include_live_context": False,
}
def fail_unfinished(self, error: str) -> None:
@@ -183,7 +180,7 @@ async def judge_trial_run(snapshot: TrialEvaluationSnapshot, evidence: TrialRunE
team_id=snapshot.team_id,
user_id=snapshot.user_id,
sandbox_environment_id=environment_id,
- posthog_mcp_scopes="signals_scout_judge",
+ posthog_mcp_scopes=[],
model=snapshot.judge_model,
runtime_adapter="codex",
reasoning_effort="high",
@@ -199,9 +196,11 @@ async def judge_trial_run(snapshot: TrialEvaluationSnapshot, evidence: TrialRunE
model=TrialJudgeVerdicts,
step_name="scout_trial_judge",
ai_stage="scout:trial_judge",
- origin_product=tasks_facade.TaskOriginProduct.SIGNALS_SCOUT,
+ # Reuse rubric generation's repo-less internal sandbox policy.
+ origin_product=tasks_facade.TaskOriginProduct.SIGNALS_SCOUT_SUGGESTIONS,
origin_key=origin_key,
internal=True,
+ mcp_builtin_agent_key="scout",
mcp_gateway_server_ids=[],
before_task_dispatch=judge_run.bind_before_dispatch,
max_poll_seconds=JUDGE_MAX_RUNTIME_SECONDS,
diff --git a/products/signals/backend/test/test_scout_trial_evaluation.py b/products/signals/backend/test/test_scout_trial_evaluation.py
index b2a825f47e70..425d057956ba 100644
--- a/products/signals/backend/test/test_scout_trial_evaluation.py
+++ b/products/signals/backend/test/test_scout_trial_evaluation.py
@@ -9,7 +9,7 @@ from typing import TYPE_CHECKING, Literal
from uuid import UUID, uuid4
from posthog.test.base import BaseTest
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch
from django.test import SimpleTestCase, override_settings
from django.utils import timezone
@@ -64,7 +64,11 @@ from products.signals.backend.scout_harness.trial_evaluation_types import (
TrialRunEvidence,
TrialRunJudgment,
)
-from products.signals.backend.scout_harness.trial_judge import TrialJudgeExecutionError, parse_trial_judgment
+from products.signals.backend.scout_harness.trial_judge import (
+ TrialJudgeExecutionError,
+ judge_trial_run,
+ parse_trial_judgment,
+)
from products.signals.backend.scout_harness.trial_launch import (
ScoutTrialLaunchError,
ScoutTrialsDisabled,
@@ -667,6 +671,33 @@ class TestScoutTrialEvaluation(BaseTest):
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"]
+ )
+ def test_changed_source_or_ineligible_evidence_cannot_dispatch_a_judge(self, invalid: str) -> None:
+ snapshot = prepare_trial_evaluation(config=self.config, user=self.user, request=self.request)
+ evidence = snapshot.runs[0]
+ if invalid == "source_origin":
+ task = self.scout_run.task_run.task
+ 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"])
+ elif invalid == "excluded_evidence":
+ evidence = evidence.model_copy(update={"exclusion_reason": "Synthetic excluded run."})
+ snapshot = snapshot.model_copy(update={"runs": [evidence]})
+ elif invalid == "unfinished_evidence":
+ evidence = evidence.model_copy(update={"execution_status": "failed"})
+ snapshot = snapshot.model_copy(update={"runs": [evidence]})
+ else:
+ evidence = evidence.model_copy(update={"launch_id": uuid4()})
+
+ with patch(f"{JUDGE_MODULE}.MultiTurnSession.start", new_callable=AsyncMock) as start:
+ with self.assertRaises(TrialJudgeExecutionError):
+ async_to_sync(judge_trial_run)(snapshot, evidence)
+ start.assert_not_awaited()
+
@parameterized.expand(
[(bound, status, None) for bound in (False, True) for status in ("pending", "unknown", "not_started")]
+ [
@@ -947,17 +978,66 @@ class TestScoutTrialEvaluation(BaseTest):
report.runs[0].error or ""
)
- def test_worker_rechecks_operator_access_before_judging(self) -> None:
+ @parameterized.expand(
+ [
+ "staff_revoked",
+ "inactive",
+ "membership_revoked",
+ "project_revoked",
+ "historical_skill_removed",
+ "source_skill",
+ "source_config_team",
+ "source_invalidated",
+ ]
+ )
+ def test_worker_rechecks_source_and_operator_access_before_judging(self, revoked: str) -> None:
snapshot = prepare_trial_evaluation(config=self.config, user=self.user, request=self.request)
- self.user.is_staff = False
- self.user.save(update_fields=["is_staff"])
- judge = AsyncMock()
- with patch(f"{JUDGE_MODULE}.judge_trial_run", judge):
+ if revoked == "staff_revoked":
+ self.user.is_staff = False
+ self.user.save(update_fields=["is_staff"])
+ elif revoked == "inactive":
+ self.user.is_active = False
+ self.user.save(update_fields=["is_active"])
+ elif revoked == "membership_revoked":
+ self.user.organization_memberships.filter(organization_id=self.organization.id).delete()
+ elif revoked == "project_revoked":
+ self.enterContext(
+ patch(
+ "products.access_control.backend.facade.user_access_control.UserAccessControl.has_project_access",
+ new_callable=PropertyMock,
+ return_value=False,
+ )
+ )
+ elif revoked == "historical_skill_removed":
+ self.skill.delete()
+ LLMSkill.objects.create(
+ team=self.team,
+ name=self.skill.name,
+ version=2,
+ body="Updated synthetic instructions.",
+ allowed_tools=["emit_report"],
+ )
+ elif revoked == "source_skill":
+ self.scout_run.skill_name = "signals-scout-other"
+ self.scout_run.save(update_fields=["skill_name"])
+ elif revoked == "source_config_team":
+ self.config.team = Team.objects.create(organization=self.organization, name="Other synthetic project")
+ self.config.save(update_fields=["team"])
+ else:
+ ScoutTrialStore(self.scout_run).invalidate("Synthetic invalidation", allow_terminal=True)
+
+ with (
+ patch(f"{JUDGE_MODULE}.get_or_create_signals_sandbox_env", return_value=None),
+ patch(f"{JUDGE_MODULE}.MultiTurnSession.start", new_callable=AsyncMock) as start,
+ ):
async_to_sync(run_evaluation_run)(self.team.id, snapshot.evaluation_id, self.launch.id)
- judge.assert_not_called()
- self.user.is_staff = True
- self.user.save(update_fields=["is_staff"])
- assert finish_trial_evaluation(self.team.id, snapshot.evaluation_id).runs[0].status == "judge_error"
+ start.assert_not_awaited()
+ judgment = TrialRunJudgment.model_validate_json(
+ self.documents[
+ f"signals/scout-trials/{self.team.id}/evaluations/{snapshot.evaluation_id}/runs/{self.launch.id}.json"
+ ]
+ )
+ assert judgment.status == "judge_error"
@parameterized.expand(["before_start", "during_judging"])
def test_flag_disable_preserves_unstarted_attempts_and_active_results(self, timing: str) -> None:
diff --git a/products/signals/backend/test/test_scout_trial_judge_sandbox.py b/products/signals/backend/test/test_scout_trial_judge_sandbox.py
index 674cdc15feba..27d98b4e767f 100644
--- a/products/signals/backend/test/test_scout_trial_judge_sandbox.py
+++ b/products/signals/backend/test/test_scout_trial_judge_sandbox.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import json
import asyncio
from types import SimpleNamespace
from uuid import uuid4
@@ -7,7 +8,7 @@ from uuid import uuid4
from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, MagicMock, patch
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, override_settings
from asgiref.sync import async_to_sync
from parameterized import parameterized
@@ -17,7 +18,6 @@ from posthog.models.scoping import team_scope
from products.signals.backend.scout_harness.trial_judge import TrialJudgeExecutionError, judge_trial_run
from products.signals.backend.test.test_scout_trial_judge import _snapshot, _verdict
from products.signals.backend.trial_judging_types import TrialJudgeVerdicts
-from products.tasks.backend.facade.agents import TurnPollResult
from products.tasks.backend.models import Task, TaskRun
MODULE = "products.signals.backend.scout_harness.trial_judge"
@@ -95,19 +95,54 @@ class TestSandboxJudgeLifecycle(SimpleTestCase):
class TestSandboxJudgeDispatch(BaseTest):
- def test_private_inputs_are_attached_before_dispatch_and_retry_cannot_create_another_run(self) -> None:
+ @parameterized.expand([("valid_json", False), ("invalid_json", True)])
+ @override_settings(DEBUG=False)
+ def test_ordinary_task_attaches_evidence_and_retries_json_in_same_run(self, _name: str, retry_json: bool) -> None:
snapshot = _snapshot().model_copy(update={"team_id": self.team.id, "user_id": self.user.id})
evidence = snapshot.runs[0]
output = TrialJudgeVerdicts.model_validate({"summary": "Synthetic assessment.", "criteria": [_verdict()]})
- workflow_handle = MagicMock(signal=AsyncMock())
+ dispatched: list[TaskRun] = []
+ log_lines: list[str] = []
+ followup_messages: list[str] = []
+
+ def append_response(text: str) -> None:
+ log_lines.extend(
+ [
+ json.dumps(
+ {
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {"type": "text", "text": text},
+ }
+ },
+ }
+ }
+ ),
+ json.dumps({"notification": {"result": {"stopReason": "end_turn"}}}),
+ ]
+ )
+
+ append_response("The synthetic check passed." if retry_json else output.model_dump_json())
+
+ async def signal(signal: object, message: str | None = None, **_kwargs: object) -> None:
+ if message is not None:
+ followup_messages.append(message)
+ self.assertIn("Return the complete JSON object", message)
+ append_response(output.model_dump_json())
+
+ workflow_handle = MagicMock(signal=AsyncMock(side_effect=signal))
client = MagicMock()
client.get_workflow_handle.return_value = workflow_handle
- dispatched: list[TaskRun] = []
def dispatch(run: TaskRun, **_kwargs: object) -> None:
run.refresh_from_db()
- self.assertEqual(run.state["scout_trial_judge"]["source_task_run_id"], str(evidence.task_run_id))
- self.assertEqual(run.state["pending_dispatch"]["posthog_mcp_scopes"], "signals_scout_judge")
+ self.assertEqual(run.task.origin_product, Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS)
+ self.assertFalse(run.task.is_scout_experiment)
+ self.assertNotIn("scout_trial_judge", run.state)
+ self.assertEqual(run.state["pending_dispatch"]["posthog_mcp_scopes"], [])
self.assertEqual(run.state["pending_user_message_id"], str(run.id))
self.assertEqual(run.state["pending_user_artifact_ids"], [item["id"] for item in run.artifacts])
self.assertEqual([item["name"] for item in run.artifacts], [file.filename for file in evidence.files])
@@ -115,31 +150,29 @@ class TestSandboxJudgeDispatch(BaseTest):
self.assertEqual(run.state["model"], snapshot.judge_model)
self.assertEqual(run.state["reasoning_effort"], "high")
self.assertEqual(run.state["mcp_gateway_server_ids"], [])
+ self.assertFalse(run.state["include_live_context"])
+ self.assertEqual(run.task.mcp_builtin_agent_key, "scout")
+ self.assertEqual(run.task.mcp_gateway_server_allowlist, [])
self.assertIsNone(run.task.repository)
self.assertTrue(run.task.internal)
for artifact in run.artifacts:
self.assertIn(f"/{snapshot.team_id}/evaluations/{snapshot.evaluation_id}/", artifact["storage_path"])
self.assertIn(str(evidence.launch_id), artifact["storage_path"])
+
dispatched.append(run)
with (
team_scope(self.team.id, canonical=True),
patch(f"{MODULE}._assert_scout_available"),
patch(f"{MODULE}.read_trial_evidence_sources", return_value=evidence.sources),
- patch(f"{MODULE}.get_or_create_signals_sandbox_env", return_value=None),
+ patch("posthoganalytics.feature_enabled", return_value=False),
patch(
"products.tasks.backend.logic.services.workflow_dispatch.enqueue_or_start_workflow",
side_effect=dispatch,
),
patch(f"{SESSION_MODULE}.async_connect", new=AsyncMock(return_value=client)),
- patch(
- f"{SESSION_MODULE}.poll_for_turn",
- new=AsyncMock(
- return_value=TurnPollResult(
- last_message=output.model_dump_json(), full_log=None, total_lines=2, printed_lines=0
- )
- ),
- ),
+ patch("asyncio.sleep", new_callable=AsyncMock),
+ patch("posthog.storage.object_storage.read", side_effect=lambda *_args, **_kwargs: "\n".join(log_lines)),
):
result = async_to_sync(judge_trial_run)(snapshot, evidence)
self.assertEqual(result.status, "judged")
@@ -150,4 +183,8 @@ class TestSandboxJudgeDispatch(BaseTest):
Task.objects.filter(team_id=self.team.id, origin_key__startswith="scout-trial-judge:").count(), 1
)
self.assertEqual(TaskRun.objects.filter(team_id=self.team.id, task=dispatched[0].task).count(), 1)
+ dispatched[0].refresh_from_db()
+ self.assertFalse(dispatched[0].state["include_live_context"])
self.assertEqual(workflow_handle.signal.call_args.kwargs["args"], ["completed", None])
+ self.assertEqual(result.criteria[0].verdict, "pass")
+ self.assertEqual(len(followup_messages), int(retry_json))
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index a170dac6c026..f06049374ec6 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -2655,6 +2655,7 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(
"scout_trial",
"scout_trial_judge",
"scout_trial_private",
+ "include_live_context",
"analytics_query_context",
"sandbox_oauth_token_ids",
"resume_from_run_id",
diff --git a/products/tasks/backend/logic/services/store_skills.py b/products/tasks/backend/logic/services/store_skills.py
index b2d5ec3d582d..dff665b5b17e 100644
--- a/products/tasks/backend/logic/services/store_skills.py
+++ b/products/tasks/backend/logic/services/store_skills.py
@@ -85,7 +85,11 @@ def refresh_store_skills_state(task_run: TaskRun, user: User, *, reason: str) ->
"""
run_id = str(task_run.id)
try:
- store_skills = resolve_store_skills(task_run.task.team, user, run_id=run_id)
+ store_skills = (
+ []
+ if (task_run.state or {}).get("include_live_context") is False
+ else resolve_store_skills(task_run.task.team, user, run_id=run_id)
+ )
if store_skills is None:
return
TaskRun.update_state_atomic(task_run.id, updates={STORE_SKILLS_STATE_KEY: store_skills})
diff --git a/products/tasks/backend/logic/services/test_store_skills.py b/products/tasks/backend/logic/services/test_store_skills.py
new file mode 100644
index 000000000000..7fddebb5b3e4
--- /dev/null
+++ b/products/tasks/backend/logic/services/test_store_skills.py
@@ -0,0 +1,52 @@
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from products.skills.backend.models.skills import LLMSkill
+from products.tasks.backend.constants import STORE_SKILLS_STATE_KEY
+from products.tasks.backend.logic.services.store_skills import refresh_store_skills_state
+from products.tasks.backend.models import Task, TaskRun
+
+
+class TestRefreshStoreSkillsState(BaseTest):
+ @parameterized.expand(
+ [
+ (None, True, "resolved"),
+ (None, None, "unchanged"),
+ (False, True, "empty"),
+ (False, None, "empty"),
+ ]
+ )
+ def test_refresh_respects_live_context_setting(
+ self, include_live_context: bool | None, flag_value: bool | None, expected: str
+ ) -> None:
+ LLMSkill.objects.create(
+ team=self.team,
+ name="invoice-review",
+ description="Check invoice failures.",
+ body="# Invoice review\n",
+ version=1,
+ is_latest=True,
+ created_by=self.user,
+ )
+ task = Task.objects.create(team=self.team, title="Review evidence", created_by=self.user)
+ state: dict[str, object] = {STORE_SKILLS_STATE_KEY: [{"name": "stale-live-skill"}]}
+ if include_live_context is not None:
+ state["include_live_context"] = include_live_context
+ run = TaskRun.objects.create(task=task, team=self.team, state=state)
+
+ with patch(
+ "products.tasks.backend.logic.services.store_skills.posthog_feature_flag_value", return_value=flag_value
+ ):
+ refresh_store_skills_state(run, self.user, reason="actor_switch")
+
+ run.refresh_from_db()
+ if expected == "resolved":
+ assert run.state[STORE_SKILLS_STATE_KEY] == [
+ {"name": "invoice-review", "description": "Check invoice failures.", "version": 1}
+ ]
+ elif expected == "unchanged":
+ assert run.state[STORE_SKILLS_STATE_KEY] == [{"name": "stale-live-skill"}]
+ else:
+ assert run.state[STORE_SKILLS_STATE_KEY] == []
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 323c8a0742e8..5d2d29929ce9 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
@@ -1390,15 +1390,20 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
) # Ensure we get a boolean value even if the flag is missing
emit_agent_log(run_id, "debug", f"pr_loop_enabled: {pr_loop_enabled} for this task run")
state_updates: dict[str, Any] = {PR_LOOP_ENABLED_STATE_KEY: pr_loop_enabled}
+ include_live_context = state.get("include_live_context") is not False
# The sandbox agent renders these into its skill roots at session start. Resolved here so the
# sandbox needs no extra request on its boot path, and best-effort: a store failure must not
# stop the run, it only leaves the sandbox without store skills for this session.
try:
- store_skills = (
- None
- if task.is_scout_trial_judge
- else resolve_store_skills(team, actor_user or task.created_by, run_id=run_id)
- )
+ if not include_live_context:
+ 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)
+ )
except Exception as e:
log_with_activity_context("store_skills_resolve_failed", run_id=run_id, error=str(e))
store_skills = None
@@ -1458,8 +1463,10 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
run_id=run_id,
state=state,
)
- context_layer_enabled = not trial_origin and context_layer_facade.is_context_layer_enabled(
- organization_id=organization_id, distinct_id=distinct_id
+ context_layer_enabled = (
+ include_live_context
+ and not trial_origin
+ and context_layer_facade.is_context_layer_enabled(organization_id=organization_id, distinct_id=distinct_id)
)
use_modal_network_allowlist = _is_modal_network_allowlist_enabled(
distinct_id=distinct_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 723de6b11f93..a5721bd4e107 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
@@ -36,6 +36,7 @@ from products.tasks.backend.constants import (
)
from products.tasks.backend.exceptions import ProcessTaskFatalError, TaskInvalidStateError, TaskRunNotReadyError
from products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, SandboxEnvironment, Task, TaskRun
+from products.tasks.backend.temporal.process_task.activities import provision_sandbox
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import (
GetTaskProcessingContextInput,
TaskProcessingContext,
@@ -762,15 +763,17 @@ class TestGetTaskProcessingContextActivity:
@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize(
- "flag_value,expected_state",
+ "flag_value,include_live_context,expected_state",
[
- (True, "resolved"),
- (False, []),
- (None, "untouched"), # a flag-service outage must not clear stubs a resumed sandbox still has
+ (True, None, "resolved"),
+ (False, None, []),
+ (None, None, "untouched"), # a flag-service outage must not clear stubs a resumed sandbox still has
+ (True, False, []),
+ (None, False, []),
],
)
def test_store_skills_state_follows_the_sandbox_flag(
- self, activity_environment, test_task, user, flag_value, expected_state
+ self, activity_environment, test_task, user, mocker, flag_value, include_live_context, expected_state
):
LLMSkill.objects.create(
team=test_task.team,
@@ -781,16 +784,40 @@ class TestGetTaskProcessingContextActivity:
is_latest=True,
created_by=user,
)
- task_run = test_task.create_run()
+ task_run = test_task.create_run(
+ extra_state={"include_live_context": include_live_context} if include_live_context is not None else {}
+ )
TaskRun.update_state_atomic(task_run.id, updates={STORE_SKILLS_STATE_KEY: [{"name": "from-last-session"}]})
input_data = GetTaskProcessingContextInput(run_id=str(task_run.id))
- with patch(
- "products.tasks.backend.logic.services.store_skills.posthog_feature_flag_value",
- return_value=flag_value,
+ with (
+ patch(
+ "products.tasks.backend.logic.services.store_skills.posthog_feature_flag_value",
+ return_value=flag_value,
+ ),
+ patch(
+ "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.context_layer_facade.is_context_layer_enabled",
+ return_value=True,
+ ),
):
- async_to_sync(activity_environment.run)(get_task_processing_context, input_data)
+ result = async_to_sync(activity_environment.run)(get_task_processing_context, input_data)
+ assert result.context_layer_enabled is (include_live_context is not False)
+ if include_live_context is False:
+ assert result.state is not None
+ assert result.state[STORE_SKILLS_STATE_KEY] == []
+ for name in ("run_gateway_env_vars", "mcp_exec_skills_env_vars", "get_git_identity_env_vars"):
+ mocker.patch.object(provision_sandbox, name, return_value={})
+ mocker.patch.object(provision_sandbox, "get_sandbox_jwt_public_key", return_value="public-key")
+ mocker.patch.object(
+ provision_sandbox.context_layer_facade,
+ "sandbox_environment_variables",
+ return_value={"POSTHOG_CONTEXT_LAYER_PATH": "/tmp/workspace/context"},
+ )
+ environment = provision_sandbox._build_environment_variables(result, test_task, "", "fake-token")
+ assert environment.get("POSTHOG_CONTEXT_LAYER_PATH") == (
+ "/tmp/workspace/context" if include_live_context is not False else None
+ )
stored = TaskRun.objects.get(id=task_run.id).state[STORE_SKILLS_STATE_KEY]
if expected_state == "untouched":
assert stored == [{"name": "from-last-session"}]
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 492b691ffdcd..ee3347d2565d 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -7504,6 +7504,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
"scout_trial": trial_context,
"scout_trial_private": trial_private,
"github_credential_source": "caller_token",
+ "include_live_context": False,
"analytics_query_context": [],
"sandbox_oauth_token_ids": ["server-token-id"],
"resume_from_run_id": "server-resume-id",
@@ -7584,6 +7585,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
"scout_trial": {"version": 2},
"scout_trial_private": {"reports": {}},
"github_credential_source": "server_integration",
+ "include_live_context": True,
"analytics_query_context": [{"kind": "private"}],
"sandbox_oauth_token_ids": ["forged-token-id"],
"resume_from_run_id": "caller-resume-id",
@@ -7673,6 +7675,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
assert run.state["resume_from_run_id"] == "server-resume-id"
assert run.state["sandbox_oauth_token_ids"] == ["server-token-id"]
assert run.state["github_credential_source"] == "caller_token"
+ assert run.state["include_live_context"] is False
assert run.state["pr_authorship_mode"] == "user"
assert "dev_stack_preview" not in run.state
assert run.state["sandbox_id"] == "sb-real"
@@ -7746,6 +7749,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
"state_remove_keys": [
"scout_trial",
"scout_trial_private",
+ "include_live_context",
"analytics_query_context",
"sandbox_oauth_token_ids",
"resume_from_run_id",
@@ -7807,6 +7811,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
assert run.state["claude_model_access"] == "own-subscription"
assert run.state["claude_subscription_user_id"] == self.user.id
assert run.state["github_credential_source"] == "caller_token" # protected key survives removal
+ assert run.state["include_live_context"] is False
assert run.state["agent_otel_telemetry_enabled"] is False # protected key survives removal
assert run.state["agent_proxy_keep_stream_open"] is False
assert run.state["overlap_clone_boot_enabled"] is False
@@ -7864,6 +7869,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",
{
"state_append": {
+ "include_live_context": True,
"analytics_query_context": [{"kind": "private"}],
"sandbox_oauth_token_ids": ["forged-token-id"],
"systemPrompt": "Caller-controlled instructions",
@@ -7886,6 +7892,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
assert run.state["resume_from_run_id"] == "server-resume-id"
assert run.state["sandbox_oauth_token_ids"] == ["server-token-id"]
assert run.state["scratch"] == ["ok"]
+ assert run.state["include_live_context"] is False
assert run.state["task_management_ci_idle_skips"] == 1
assert run.state["task_management_ci_wait_checks"] == 10
assert run.state["pending_external_followups_checkpoint"] == {"generation": 8}