:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): preserve complete scout rubric references (#113146)
Alex Lebedevb48c799fc75b
diff --git a/docs/internal/scout-online-evals-devbox.md b/docs/internal/scout-online-evals-devbox.mdindex fe05fbe82f62..930b7c1151e6 100644--- a/docs/internal/scout-online-evals-devbox.md+++ b/docs/internal/scout-online-evals-devbox.md@@ -47,9 +47,13 @@ Revoke or expire private tokens before rolling the gateway back to a version witThe rubric stays fixed across scout edits, and saved results retain the rubric used for that trial. If a run is interrupted, reopen the existing trial before starting another paid attempt.+Trial plans and evaluation documents keep one complete adopted reference each and exclude suggestion-generation history. The judge reads that same adopted reference from its evidence attachment.++Suggestion generation captures the complete scout instructions and reference files for judging, while keeping the generator's prompt bounded. If an older saved reference is incomplete, generate suggestions again, review and use the new reference, then save. You can keep your existing criteria.+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 completed scout run gets its own judge sandbox. The judge reads the saved rubric and searches attached copies of the complete run log, reports, summary, 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.+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.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 9d498d708c3a..d43dbbbeade9 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -11219,9 +11219,9 @@ snapshots:scenes-app-inbox-scoutrubricreference--captured-reference--light:hash: v1.k794b7964.878f088b3741444fe4e36b9fec1c709bae34675c66334255789d68c0d247f9c7.9kMCDeI9Tna39rVLHPse8gPGE0l81_sz9aGv86IRcXAscenes-app-inbox-scoutrubricreference--truncated-reference--dark:- hash: v1.k794b7964.a01b3b2398645e809007273a0385321b8b1692bdf1cd508621384e5f91fdf9aa.JXtm5r2i0IuUtbWb15qEI4F-xWqB2tvAmQlMBIXkLgE+ hash: v1.k794b7964.1ef7f4b1ada8eb9f628653cdaa3c1276b158b507d24627e82394349ed0264b42.v8KgrJMLse6MUEP59aRFRa33dq7Y930qG6OFhc3KUtYscenes-app-inbox-scoutrubricreference--truncated-reference--light:- hash: v1.k794b7964.dc111911b6dd32b3af52355952656380b34843d904f575919c9c028634a8b07d.R9df4hBh4B25i-wvb8waW9ZSL9v8yJVvtZT_La_doZo+ hash: v1.k794b7964.2305f418e12cd04729fdad96f6e4a5b7242d0ae320f1fbc5cf6fce0a616d53fe.UYYfoVzS-pmUvx0bObq6c0qhpYpZtsdwyLKGTnpbiBMscenes-app-inbox-scoutrubrics--details-expanded--dark:hash: v1.k794b7964.2282bc1c0a93848b1107c3b89232cf49f8047ae38d35430b08058a4a0b99bf31.-Eor8WsHffPmJ2qcdetFpHLTNDX-3mLDtarrfacK11gscenes-app-inbox-scoutrubrics--details-expanded--light:diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex 51bfbb4c60bf..cd1efe1c8bca 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -687,8 +687,8 @@ Every save must include all shared defaults. Owners can edit or disable them, bu`POST .../generate/` queues the `generate-scout-rubrics` Temporal workflow and returns the active request when one already exists.It accepts optional `context` (up to 2,000 characters), saved on that generation request. Concurrent requests keep the first request's context; later requests do not inherit it.The editor exposes this as a single optional paragraph. It adds priorities without replacing the scout's responsibilities, shared defaults or saved choices.-The backend supplies current instructions, bounded reference text from the exact skill version and recent run summaries to a background session.-It captures the exact governing description, instructions, report rules and reference texts before the session starts, including clipping and omission metadata. This context is immutable within a generation and is reused if that attempt resumes. Historical summaries and saved criteria remain generation inputs rather than governing instructions.+The backend captures the complete governing description, instructions, report rules and all reference files from the exact skill version before the session starts. This context is immutable within a generation and is reused if that attempt resumes.+Only the generation prompt is bounded: up to 60,000 instruction characters, 20 reference paths and four file contents totaling 60,000 characters. These prompt limits do not shorten the saved reference used for judging. Historical summaries and saved criteria remain generation inputs rather than governing instructions.The session requests no project-read MCP scopes because that context is supplied up front. The shared sandbox's internal credentials and tool access remain an accepted limitation of the staff-only v0.The first request drafts complete criteria using effective defaults and disabled choices. A second request supplies the complete saved rubric and selects whole draft items by index, without rewriting them.One conditional format correction is shared across both steps. The generator does not inspect historical transcripts or full reports.@@ -696,7 +696,7 @@ Criteria explain the required result in plain language, with specific source refThe generation prompt ends with writing guidance and a short example for the scout's owner. The selection step also writes an owner-facing summary; it cannot change the selected criteria.Its task identifiers, status, and validated result persist on the config so the user can leave the page and return later.Completion preserves saved criteria, rejects results from replaced requests, and requires explicit user selection and saving to adopt suggestions.-The saved reference context and its generation identifier survive replacement of the latest suggestions. Legacy rubrics without a captured reference remain readable; reading or editing them does not invent provenance.+The saved reference context and its generation identifier survive replacement of the latest suggestions. Legacy rubrics without a complete captured reference remain readable; reading or editing them does not invent provenance. Owners must regenerate suggestions and explicitly adopt the complete reference before starting trials, but can keep their existing criteria.Expired or terminal requests reject late worker updates. An update to an expired request records the failure and completion time.A request that cannot start, because of the daily limit or a dispatch failure, restores the last completed suggestions.diff --git a/products/signals/backend/presentation/scout_rubrics.py b/products/signals/backend/presentation/scout_rubrics.pyindex f9f04b89339e..afdc4ecbb066 100644--- a/products/signals/backend/presentation/scout_rubrics.py+++ b/products/signals/backend/presentation/scout_rubrics.py@@ -57,16 +57,16 @@ class ScoutRubricCriterionSerializer(serializers.Serializer):@extend_schema_serializer(component_name="ScoutRubricReferenceTextDocument")class ScoutRubricReferenceTextSerializer(serializers.Serializer):- path = serializers.CharField(help_text="Path of the reference supplied to the generator.")- content_type = serializers.CharField(help_text="Content type of the supplied reference.")- content = serializers.CharField(allow_blank=True, help_text="Exact reference text supplied to the generator.")+ path = serializers.CharField(help_text="Path of the captured reference file.")+ content_type = serializers.CharField(help_text="Content type of the captured reference file.")+ content = serializers.CharField(allow_blank=True, help_text="Saved reference text used for judging.")@extend_schema_serializer(component_name="ScoutRubricReferenceLimitsDocument")class ScoutRubricReferenceLimitsSerializer(serializers.Serializer):- omitted_files = serializers.IntegerField(min_value=0, help_text="Number of reference files not supplied.")+ omitted_files = serializers.IntegerField(min_value=0, help_text="Number of files missing from the saved reference.")truncated_files = serializers.ListField(- child=serializers.CharField(), help_text="Reference paths whose supplied content was truncated."+ child=serializers.CharField(), help_text="Paths of files truncated in the saved reference.")@@ -76,25 +76,25 @@ class ScoutRubricReferenceContextSerializer(serializers.Serializer):skill_id = serializers.CharField(help_text="Exact skill record used for generation.")skill_name = serializers.CharField(help_text="Name of the skill used for generation.")skill_version = serializers.IntegerField(help_text="Skill version used for generation.")- description = serializers.CharField(allow_blank=True, help_text="Scout description supplied to the generator.")- instructions = serializers.CharField(allow_blank=True, help_text="Exact instructions supplied to the generator.")- instructions_truncated = serializers.BooleanField(help_text="Whether the supplied instructions were truncated.")+ description = serializers.CharField(allow_blank=True, help_text="Scout description captured for this reference.")+ instructions = serializers.CharField(allow_blank=True, help_text="Saved scout instructions used for judging.")+ instructions_truncated = serializers.BooleanField(help_text="Whether the saved instructions were truncated.")report_channel = serializers.ChoiceField(choices=ScoutRubricReportChannel.choices, help_text="Report capabilities used to select the source rules.")report_disposition_instructions = serializers.CharField(- allow_blank=True, help_text="Exact report-disposition rules supplied to the generator."+ allow_blank=True, help_text="Report-disposition rules captured for this reference.")reference_files = serializers.ListField(- child=serializers.CharField(), help_text="Reference-file inventory supplied to the generator."+ child=serializers.CharField(), help_text="Reference-file inventory captured for this reference.")reference_files_truncated = serializers.BooleanField(help_text="Whether the reference-file inventory was truncated.")- reference_texts = ScoutRubricReferenceTextSerializer(- many=True, help_text="Reference texts supplied to the generator."+ reference_texts = ScoutRubricReferenceTextSerializer(many=True, help_text="Saved reference texts used for judging.")+ reference_limits = ScoutRubricReferenceLimitsSerializer(+ help_text="Missing or truncated text in the saved reference.")- reference_limits = ScoutRubricReferenceLimitsSerializer(help_text="Limits on the supplied reference texts.")class ScoutRubricGenerationSerializer(serializers.Serializer):diff --git a/products/signals/backend/scout_harness/rubrics_runner.py b/products/signals/backend/scout_harness/rubrics_runner.pyindex 6f22228b4ff9..0094b216e44f 100644--- a/products/signals/backend/scout_harness/rubrics_runner.py+++ b/products/signals/backend/scout_harness/rubrics_runner.py@@ -5,7 +5,6 @@ import asynciofrom typing import TYPE_CHECKING, Annotatedfrom uuid import uuid4-from django.db.models.functions import Substrfrom django.utils import timezoneimport structlog@@ -49,6 +48,10 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)MAX_RUNTIME_SECONDS = 15 * 60+MAX_GENERATION_INSTRUCTION_CHARACTERS = 60_000+MAX_GENERATION_REFERENCE_CHARACTERS = 60_000+MAX_GENERATION_REFERENCE_FILES = 4+MAX_GENERATION_REFERENCE_PATHS = 20RUBRIC_GENERATION_PROMPT = """Help the scout's owner decide whether a run did useful work. Suggest a small set of checks they canread, choose and edit in the UI. Use everyday language in every field, including references to the@@ -236,26 +239,15 @@ def read_selection_output(text: str, draft: ScoutRubricSuggestionBatch) -> Scoutdef build_rubric_reference_context(team: Team, config: SignalScoutConfig) -> ScoutRubricReferenceContext:skill = load_skill_for_run(team, config.skill_name)report_channel = ScoutRubricReportChannel(resolve_report_channel_variant(skill.allowed_tools))- remaining_characters = 60_000- references: list[ScoutRubricReferenceText] = []- truncated_references: list[str] = []files = (LLMSkillFile.objects.filter(skill_id=skill.skill_id, skill__team_id=team.id)- .annotate(snippet=Substr("content", 1, remaining_characters + 1)).order_by("path")- .values("path", "content_type", "snippet")[:4]+ .values("path", "content_type", "content")+ )+ references = tuple(+ ScoutRubricReferenceText(path=file["path"], content_type=file["content_type"], content=file["content"])+ for file in files.iterator())- for file in files:- if remaining_characters == 0:- break- content = file["snippet"]- included = content[:remaining_characters]- references.append(- ScoutRubricReferenceText(path=file["path"], content_type=file["content_type"], content=included)- )- if len(content) > remaining_characters:- truncated_references.append(file["path"])- remaining_characters -= len(included)return ScoutRubricReferenceContext(skill_id=skill.skill_id,skill_name=skill.name,@@ -263,14 +255,44 @@ def build_rubric_reference_context(team: Team, config: SignalScoutConfig) -> Scodescription=skill.description,report_channel=report_channel,report_disposition_instructions=report_disposition_instructions(report_channel),- instructions=skill.body[:60_000],- instructions_truncated=len(skill.body) > 60_000,- reference_files=tuple(file.path for file in skill.files[:20]),- reference_files_truncated=len(skill.files) > 20,- reference_texts=tuple(references),- reference_limits=ScoutRubricReferenceLimits(- omitted_files=len(skill.files) - len(references), truncated_files=tuple(truncated_references)- ),+ instructions=skill.body,+ instructions_truncated=False,+ reference_files=tuple(reference.path for reference in references),+ reference_files_truncated=False,+ reference_texts=references,+ reference_limits=ScoutRubricReferenceLimits(omitted_files=0, truncated_files=()),+ )+++def _generation_reference(reference_context: ScoutRubricReferenceContext) -> ScoutRubricReferenceContext:+ # Prompt budgets must not shorten the saved reference used for judging.+ remaining_characters = MAX_GENERATION_REFERENCE_CHARACTERS+ references: list[ScoutRubricReferenceText] = []+ truncated_references = list(reference_context.reference_limits.truncated_files)+ for reference in reference_context.reference_texts[:MAX_GENERATION_REFERENCE_FILES]:+ if remaining_characters == 0:+ break+ included = reference.content[:remaining_characters]+ references.append(reference.model_copy(update={"content": included}))+ if len(reference.content) > remaining_characters and reference.path not in truncated_references:+ truncated_references.append(reference.path)+ remaining_characters -= len(included)+ return reference_context.model_copy(+ update={+ "instructions": reference_context.instructions[:MAX_GENERATION_INSTRUCTION_CHARACTERS],+ "instructions_truncated": reference_context.instructions_truncated+ or len(reference_context.instructions) > MAX_GENERATION_INSTRUCTION_CHARACTERS,+ "reference_files": reference_context.reference_files[:MAX_GENERATION_REFERENCE_PATHS],+ "reference_files_truncated": reference_context.reference_files_truncated+ or len(reference_context.reference_files) > MAX_GENERATION_REFERENCE_PATHS,+ "reference_texts": tuple(references),+ "reference_limits": ScoutRubricReferenceLimits(+ omitted_files=reference_context.reference_limits.omitted_files+ + len(reference_context.reference_texts)+ - len(references),+ truncated_files=tuple(truncated_references),+ ),+ })@@ -281,6 +303,7 @@ def build_rubric_prompt(*,generation_context: str = "",) -> str:+ reference_context = _generation_reference(reference_context)# TODO: Let the generator inspect past run transcripts and reports through read-only MCP# so it can identify gaps that the supplied summaries hide.runs = list(diff --git a/products/signals/backend/scout_harness/trial_evaluation.py b/products/signals/backend/scout_harness/trial_evaluation.pyindex 5e529239acae..3ca252f849fa 100644--- a/products/signals/backend/scout_harness/trial_evaluation.py+++ b/products/signals/backend/scout_harness/trial_evaluation.py@@ -403,7 +403,12 @@ def _report_evidence(report_id: str, report: JsonValue) -> dict[str, JsonValue]:def _run_evidence(- launch: TrialLaunch, context: TrialContext, variant_id: UUID, *, evaluation_id: UUID+ launch: TrialLaunch,+ context: TrialContext,+ variant_id: UUID,+ *,+ evaluation_id: UUID,+ rubric_reference_context: ScoutRubricReferenceContext,) -> TrialRunEvidence:run = _bound_run(launch)result = read_trial_result(run) if run is not None else None@@ -460,6 +465,9 @@ def _run_evidence()builder = _EvidenceBuilder()authored = [+ TrialEvidenceSource(+ id="rubric-reference", kind="instructions", text=rubric_reference_context.model_dump_json()+ ),TrialEvidenceSource(id="instructions", kind="instructions", text=launch.skill_body),TrialEvidenceSource(id="launch-note", kind="instructions", text=launch.note),TrialEvidenceSource(id="context", kind="context", text=trial_context_evidence(context)),@@ -593,6 +601,7 @@ def prepare_trial_evaluation(criteria = trial_evaluation_criteria(rubric)if judge_prompt_version != JUDGE_PROMPT_VERSION:raise TrialEvaluationError("This evaluation uses an obsolete judge. Start a new trial to assess it.")+ rubric_reference_context = ScoutRubricReferenceContext.model_validate(rubric["reference_context"])snapshot = TrialEvaluationSnapshot(evaluation_id=request.evaluation_id,team_id=config.team_id,@@ -603,13 +612,18 @@ def prepare_trial_evaluation(request=request,request_hash=request_hash,rubric_document=rubric,- rubric_reference_context=ScoutRubricReferenceContext.model_validate(rubric["reference_context"]),rubric_reference_generation_id=cast(str, rubric["reference_generation_id"]),criteria=criteria,judge_model=judge_model,judge_prompt_version=judge_prompt_version,runs=[- _run_evidence(launches[identifier], context, variant.id, evaluation_id=request.evaluation_id)+ _run_evidence(+ launches[identifier],+ context,+ variant.id,+ evaluation_id=request.evaluation_id,+ rubric_reference_context=rubric_reference_context,+ )for variant in request.variantsfor identifier in variant.launch_ids],diff --git a/products/signals/backend/scout_harness/trial_evaluation_types.py b/products/signals/backend/scout_harness/trial_evaluation_types.pyindex 1866793f4200..4e5c1b9e6798 100644--- a/products/signals/backend/scout_harness/trial_evaluation_types.py+++ b/products/signals/backend/scout_harness/trial_evaluation_types.py@@ -45,13 +45,16 @@ class TrialEvaluationSnapshot(EvaluationDocument):request: TrialEvaluationRequestrequest_hash: strrubric_document: dict[str, JsonValue]- rubric_reference_context: ScoutRubricReferenceContextrubric_reference_generation_id: strcriteria: list[TrialEvaluationCriterion]judge_model: strjudge_prompt_version: strruns: list[TrialRunEvidence]+ @property+ def rubric_reference_context(self) -> ScoutRubricReferenceContext:+ return ScoutRubricReferenceContext.model_validate(self.rubric_document["reference_context"])+class TrialCriterionAggregate(EvaluationDocument):criterion_id: strdiff --git a/products/signals/backend/scout_harness/trial_rubrics.py b/products/signals/backend/scout_harness/trial_rubrics.pyindex 42e36f38f6cd..da0705493e66 100644--- a/products/signals/backend/scout_harness/trial_rubrics.py+++ b/products/signals/backend/scout_harness/trial_rubrics.py@@ -47,10 +47,10 @@ class SavedScoutRubricReader:or reference.reference_limits.truncated_files):raise ScoutRubricReadError(- "The saved rubric's reference instructions are incomplete. Shorten the scout instructions or reference files, then generate, review, and save the rubric again."+ "The saved rubric's reference instructions are incomplete. Generate suggestions again, review and use the new reference, then save. You can keep your existing criteria.")return {"config_id": str(document.config_id),"skill_name": document.skill_name,- **state.model_dump(mode="json"),+ **state.model_dump(mode="json", exclude={"generation"}),}diff --git a/products/signals/backend/test/test_scout_rubrics.py b/products/signals/backend/test/test_scout_rubrics.pyindex 591e91675b42..494079e160b1 100644--- a/products/signals/backend/test/test_scout_rubrics.py+++ b/products/signals/backend/test/test_scout_rubrics.py@@ -42,6 +42,7 @@ from products.signals.backend.scout_harness.rubrics_runner import (run_rubric_generation,)from products.signals.backend.scout_harness.skill_loader import load_skill_for_run+from products.signals.backend.scout_harness.trial_rubrics import SavedScoutRubricReaderfrom products.skills.backend.models.skills import LLMSkill, LLMSkillFilefrom products.tasks.backend.facade.agents import CustomPromptSandboxContextfrom products.tasks.backend.models import Task, TaskRun@@ -639,17 +640,34 @@ class TestScoutRubricsAPI(APIBaseTest):assert captured_reference is not Noneself.assertEqual(captured_reference.skill_id, str(skill.id))self.assertEqual(captured_reference.skill_version, skill.version)+ metadata_fields = {+ "skill_name",+ "skill_version",+ "description",+ "report_channel",+ "report_disposition_instructions",+ }self.assertEqual(- captured_reference.model_dump(- mode="json", exclude={"schema_version", "skill_id", "reference_texts", "reference_limits"}- ),- {key: value for key, value in scout_context.items() if key not in {"recent_runs", "saved_criteria"}},+ captured_reference.model_dump(mode="json", include=metadata_fields),+ {key: scout_context[key] for key in metadata_fields},)+ self.assertEqual(captured_reference.instructions, body)+ self.assertFalse(captured_reference.instructions_truncated)+ self.assertEqual(captured_reference.reference_files, tuple(reference_paths))+ self.assertFalse(captured_reference.reference_files_truncated)+ self.assertEqual([reference.path for reference in captured_reference.reference_texts], reference_paths)self.assertEqual(- [reference.model_dump(mode="json") for reference in captured_reference.reference_texts],- bundle["reference_texts"],+ [reference.content_type for reference in captured_reference.reference_texts],+ ["text/plain"] * len(reference_paths),+ )+ self.assertEqual(+ [reference.content for reference in captured_reference.reference_texts],+ ["r" * (45_001 if truncated and index == 1 else 15_000) for index in range(len(reference_paths))],+ )+ self.assertEqual(+ captured_reference.reference_limits.model_dump(mode="json"),+ {"omitted_files": 0, "truncated_files": []},)- self.assertEqual(captured_reference.reference_limits.model_dump(mode="json"), bundle["reference_limits"])self.assertEqual(json.JSONDecoder().raw_decode(schema_text)[0], ScoutRubricSuggestionBatch.model_json_schema())@@ -808,3 +826,16 @@ class TestScoutRubricsAPI(APIBaseTest):status="failed" if failed_stage else "completed",error="Rubric generation failed" if failed_stage else None,)+ if name == "truncated_context":+ assert captured_reference is not None+ criteria = [item.model_dump(mode="json") for item in expected_criteria]+ adopted = self.client.put(+ self.url,+ {"revision": state.revision, "criteria": criteria, "adopt_generation_id": generation.id},+ )+ self.assertEqual(adopted.status_code, 200)+ saved = SavedScoutRubricReader(team_id=self.team.id).read(+ config_id=self.config.id, skill_name=self.config.skill_name+ )+ self.assertEqual(saved["reference_context"], captured_reference.model_dump(mode="json"))+ self.assertEqual(saved["criteria"], criteria)diff --git a/products/signals/backend/test/test_scout_trial_evaluation.py b/products/signals/backend/test/test_scout_trial_evaluation.pyindex 886b2fdb39d8..b2a825f47e70 100644--- a/products/signals/backend/test/test_scout_trial_evaluation.py+++ b/products/signals/backend/test/test_scout_trial_evaluation.py@@ -25,7 +25,7 @@ from posthog.models.scoping import team_scopefrom posthog.storage import object_storagefrom products.signals.backend.facade.api import is_scout_trial_judge_context-from products.signals.backend.facade.rubrics import default_criteria+from products.signals.backend.facade.rubrics import ScoutRubricReferenceContext, default_criteriafrom products.signals.backend.models import SignalScoutConfigfrom products.signals.backend.scout_harness.limits import MAX_TRIAL_RUNSfrom products.signals.backend.scout_harness.run_gates import check_fleet_gates@@ -84,6 +84,7 @@ from products.signals.backend.temporal.agentic.scout_trial_evaluation import ()from products.signals.backend.test.test_scout_harness_api import _make_runfrom products.signals.backend.test.test_scout_trial_judge import _reference_context, _snapshot+from products.signals.backend.trial_judging import TrialJudgeInput, build_trial_judge_promptfrom products.skills.backend.models.skills import LLMSkillfrom products.tasks.backend.models import Taskfrom products.tasks.backend.temporal.oauth import create_oauth_access_token_for_run # tach-ignore@@ -290,7 +291,12 @@ class TestScoutTrialEvaluation(BaseTest):self._save("launches", launch_id, self.launch.model_copy(update={"id": launch_id}))def evidence(- launch: TrialLaunch, context: TrialContext, variant_id: UUID, *, evaluation_id: UUID+ launch: TrialLaunch,+ context: TrialContext,+ variant_id: UUID,+ *,+ evaluation_id: UUID,+ rubric_reference_context: ScoutRubricReferenceContext,) -> TrialRunEvidence:return template.model_copy(update={"launch_id": launch.id, "variant_id": variant_id})@@ -419,6 +425,23 @@ class TestScoutTrialEvaluation(BaseTest):def test_saved_requirements_ignore_source_edits_candidates_and_unaccepted_suggestions(self) -> None:rubric = self.config.rubricsassert isinstance(rubric, dict)+ reference_paths = [f"references/checkout-{index}.md" for index in range(3)]+ self.reference = ScoutRubricReferenceContext.model_validate(+ {+ **self.reference.model_dump(mode="json"),+ "reference_files": reference_paths,+ "reference_texts": [+ {+ "path": path,+ "content_type": "text/markdown",+ "content": "A synthetic checkout must include the terminal result.\n" * 14_000,+ }+ for path in reference_paths+ ],+ }+ )+ assert len(self.reference.model_dump_json().encode()) > 2 * 1024 * 1024+ rubric["reference_context"] = self.reference.model_dump(mode="json")self.skill.is_latest = Falseself.skill.save(update_fields=["is_latest"])LLMSkill.objects.create(@@ -447,11 +470,36 @@ class TestScoutTrialEvaluation(BaseTest):).model_dump(mode="json"),}self.config.save(update_fields=["rubrics"])- snapshot = prepare_trial_evaluation(config=self.config, user=self.user, request=self.request)+ with patch(f"{MODULE}.MAX_EVALUATION_BYTES", 4 * 1024 * 1024):+ prepared = prepare_trial_evaluation(config=self.config, user=self.user, request=self.request)+ assert read_trial_evaluation(self.team.id, prepared.evaluation_id) == prepared+ snapshot = _read_trial_judge_input(self.team.id, prepared.evaluation_id, self.launch.id)+ assert snapshot is not None+ assert (+ finish_trial_evaluation(self.team.id, prepared.evaluation_id).rubric_reference_context == self.reference+ )+ self.config.refresh_from_db()+ assert self.config.rubrics == rubricassert snapshot.rubric_reference_context == self.referenceassert snapshot.rubric_reference_generation_id == rubric["reference_generation_id"]assert {criterion.id for criterion in snapshot.criteria} == {criterion.id for criterion in default_criteria()}- assert next(source.text for source in self._sources(snapshot) if source.id == "instructions") == "Do no work."+ sources = self._sources(snapshot)+ assert next(source.text for source in sources if source.id == "instructions") == "Do no work."+ reference = next(source for source in sources if source.id == "rubric-reference")+ assert reference.kind == "instructions"+ assert json.loads(reference.text) == self.reference.model_dump(mode="json")+ prompt = build_trial_judge_prompt(+ TrialJudgeInput(+ criteria=snapshot.criteria,+ rubric_reference_context=snapshot.rubric_reference_context.model_dump(mode="json"),+ judge_model=snapshot.judge_model,+ judge_prompt_version=snapshot.judge_prompt_version,+ ),+ snapshot.runs[0],+ )+ assert "rubric-reference.txt" in prompt+ assert self.reference.instructions not in prompt+ assert len(prompt.encode()) < 256 * 1024@parameterized.expand(["pass", "fail", "not_applicable"])def test_launch_note_alone_cannot_support_a_conclusive_verdict(self, verdict: str) -> None:diff --git a/products/signals/backend/test/test_scout_trial_evaluation_report.py b/products/signals/backend/test/test_scout_trial_evaluation_report.pyindex c7635a3b95d6..0383c62e4561 100644--- a/products/signals/backend/test/test_scout_trial_evaluation_report.py+++ b/products/signals/backend/test/test_scout_trial_evaluation_report.py@@ -38,8 +38,7 @@ class TestScoutTrialEvaluationReport(SimpleTestCase):created_at=datetime.now(UTC),request=request,request_hash="synthetic-request-hash",- rubric_document={"revision": 3},- rubric_reference_context=_reference_context(),+ rubric_document={"revision": 3, "reference_context": _reference_context().model_dump(mode="json")},rubric_reference_generation_id=str(uuid4()),criteria=[TrialEvaluationCriterion(diff --git a/products/signals/backend/test/test_scout_trial_judge.py b/products/signals/backend/test/test_scout_trial_judge.pyindex dd804193104e..30f1095bb43f 100644--- a/products/signals/backend/test/test_scout_trial_judge.py+++ b/products/signals/backend/test/test_scout_trial_judge.py@@ -79,8 +79,7 @@ def _snapshot() -> TrialEvaluationSnapshot:rubric_source="saved",),request_hash="synthetic-request-hash",- rubric_document={},- rubric_reference_context=_reference_context(),+ rubric_document={"reference_context": _reference_context().model_dump(mode="json")},rubric_reference_generation_id=str(uuid4()),criteria=[_criterion()],judge_model="gpt-6-astra",@@ -98,9 +97,16 @@ def _snapshot() -> TrialEvaluationSnapshot:reasoning_effort="high",skill_body_sha256="synthetic-hash",files=[+ TrialEvidenceFile(+ id="rubric-reference",+ kind="instructions",+ filename="rubric-reference.txt",+ sha256="b" * 64,+ size_bytes=1024,+ ),TrialEvidenceFile(id="trace", kind="trace", filename="run-log.jsonl", sha256="a" * 64, size_bytes=3_000_000- )+ ),],sources=[TrialEvidenceSource(id="report:1", kind="report", text="The invented check failed twice.")],)@@ -143,13 +149,23 @@ class TestSandboxJudgePrompt(SimpleTestCase):snapshot.runs[0],)self.assertIn("run-log.jsonl", prompt)+ self.assertIn("rubric-reference.txt", prompt)self.assertIn(snapshot.criteria[0].pass_condition, prompt)- self.assertIn("Inspect the checkout result.", prompt)+ self.assertNotIn("Inspect the checkout result.", prompt)self.assertNotIn(snapshot.runs[0].sources[0].text, prompt)self.assertNotIn("hidden-source-model", prompt)self.assertNotIn("Hidden variant label", prompt)- @parameterized.expand([("old_version",), ("missing_reference",), ("duplicate_criteria",), ("missing_files",)])+ @parameterized.expand(+ [+ ("old_version",),+ ("missing_reference",),+ ("duplicate_criteria",),+ ("missing_files",),+ ("missing_reference_file",),+ ("reference_is_observation",),+ ]+ )def test_invalid_input_is_rejected_before_starting_a_judge(self, failure: str) -> None:snapshot = _snapshot()criteria = snapshot.criteria * 2 if failure == "duplicate_criteria" else snapshot.criteria@@ -160,6 +176,19 @@ class TestSandboxJudgePrompt(SimpleTestCase):judge_prompt_version="15" if failure == "old_version" else JUDGE_PROMPT_VERSION,)evidence = snapshot.runs[0].model_copy(update={"files": []}) if failure == "missing_files" else snapshot.runs[0]+ if failure == "missing_reference_file":+ evidence = evidence.model_copy(+ update={"files": [file for file in evidence.files if file.id != "rubric-reference"]}+ )+ elif failure == "reference_is_observation":+ evidence = evidence.model_copy(+ update={+ "files": [+ file.model_copy(update={"kind": "report"}) if file.id == "rubric-reference" else file+ for file in evidence.files+ ]+ }+ )with self.assertRaises(TrialJudgeValidationError):build_trial_judge_prompt(data, evidence)@@ -296,11 +325,32 @@ class TestSandboxJudgeVerdicts(SimpleTestCase):self.assertEqual(result.criteria[0].verdict, "unknown")self.assertEqual(result.criteria[0].evidence, [])- @parameterized.expand([("pass",), ("fail",), ("not_applicable",), ("unknown",)])- def test_conclusive_verdicts_require_observed_citations(self, verdict: str) -> None:+ @parameterized.expand(+ [+ (verdict, source_id)+ for verdict in ("pass", "fail", "not_applicable", "unknown")+ for source_id in (None, "rubric-reference")+ ]+ )+ def test_conclusive_verdicts_require_observed_citations(self, verdict: str, source_id: str | None) -> None:+ quote = "The operation succeeded."result = parse_trial_judgment(- json.dumps({"summary": "No observations.", "criteria": [{**_verdict(verdict=verdict), "evidence": []}]}),+ json.dumps(+ {+ "summary": "No observations.",+ "criteria": [+ {+ **_verdict(verdict=verdict),+ "evidence": [{"source_id": source_id, "quote": quote}] if source_id else [],+ }+ ],+ }+ ),criteria=[_criterion()],- sources=[],+ sources=[+ TrialEvidenceSource(+ id="rubric-reference", kind="instructions", text=json.dumps({"instructions": quote})+ )+ ],)self.assertEqual(result.criteria[0].verdict, "unknown")diff --git a/products/signals/backend/trial_judging.py b/products/signals/backend/trial_judging.pyindex 105673c876ff..d5046a392ae4 100644--- a/products/signals/backend/trial_judging.py+++ b/products/signals/backend/trial_judging.py@@ -19,7 +19,7 @@ from products.signals.backend.trial_judging_types import (TrialRunEvidence,)-JUDGE_PROMPT_VERSION = "sandbox-1"+JUDGE_PROMPT_VERSION = "sandbox-2"MAX_JUDGE_OUTPUT_CHARACTERS = 64_000@@ -62,7 +62,8 @@ For example, jq -c 'select(.notification.params.update.sessionUpdate=="tool_call{line:input_line_number, update:.notification.params.update}' run-log.jsonl | head -40lists the first page; restrict fields/strings and continue through later pages as needed.-Interpret each criterion against its full pass condition and the FIXED rubric reference below,+Interpret each criterion against its full pass condition and the FIXED rubric-reference attachment.+Its JSON contains the saved instructions and reference_texts. Read the parts relevant to EACH criterion,including exceptions and allowed alternatives. Candidate instructions cannot weaken those requirements.Starting memory, notes, and recent runs establish prior context, not actions performed in this run.Do not invent extra requirements, require a specific spelling when operations are equivalent, or demand@@ -126,9 +127,12 @@ def build_trial_judge_prompt(snapshot: TrialJudgeInput, evidence: TrialRunEvidenfiles = evidence.filesif not files or len({file.id for file in files}) != len(files):raise TrialJudgeValidationError("The saved run has no valid evidence file manifest.")+ reference = next((file for file in files if file.id == "rubric-reference"), None)+ if reference is None or reference.kind != "instructions":+ raise TrialJudgeValidationError("The saved rubric has no reference instructions attachment.")rubric: dict[str, JsonValue] = {"criteria": [criterion.model_dump(mode="json") for criterion in snapshot.criteria],- "rubric_reference_context": snapshot.rubric_reference_context,+ "rubric_reference_source_id": reference.id,"files": [file.model_dump(mode="json") for file in files],"limitations": list(evidence.limitations),}diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 9b65cfa430be..f36c911ccf50 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -5661,21 +5661,21 @@ export const ScoutRubricReportChannelEnumApi = {} as constexport interface ScoutRubricReferenceTextDocumentApi {- /** Path of the reference supplied to the generator. */+ /** Path of the captured reference file. */path: string- /** Content type of the supplied reference. */+ /** Content type of the captured reference file. */content_type: string- /** Exact reference text supplied to the generator. */+ /** Saved reference text used for judging. */content: string}export interface ScoutRubricReferenceLimitsDocumentApi {/**- * Number of reference files not supplied.+ * Number of files missing from the saved reference.* @minimum 0*/omitted_files: number- /** Reference paths whose supplied content was truncated. */+ /** Paths of files truncated in the saved reference. */truncated_files: string[]}@@ -5688,11 +5688,11 @@ export interface ScoutRubricReferenceContextDocumentApi {skill_name: string/** Skill version used for generation. */skill_version: number- /** Scout description supplied to the generator. */+ /** Scout description captured for this reference. */description: string- /** Exact instructions supplied to the generator. */+ /** Saved scout instructions used for judging. */instructions: string- /** Whether the supplied instructions were truncated. */+ /** Whether the saved instructions were truncated. */instructions_truncated: boolean/** Report capabilities used to select the source rules.*@@ -5701,15 +5701,15 @@ export interface ScoutRubricReferenceContextDocumentApi {* * `edit` - Edit* * `both` - Both */report_channel: ScoutRubricReportChannelEnumApi- /** Exact report-disposition rules supplied to the generator. */+ /** Report-disposition rules captured for this reference. */report_disposition_instructions: string- /** Reference-file inventory supplied to the generator. */+ /** Reference-file inventory captured for this reference. */reference_files: string[]/** Whether the reference-file inventory was truncated. */reference_files_truncated: boolean- /** Reference texts supplied to the generator. */+ /** Saved reference texts used for judging. */reference_texts: ScoutRubricReferenceTextDocumentApi[]- /** Limits on the supplied reference texts. */+ /** Missing or truncated text in the saved reference. */reference_limits: ScoutRubricReferenceLimitsDocumentApi}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRubricReference.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRubricReference.tsxindex 2c7d37833c34..67916a9ca5c0 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRubricReference.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRubricReference.tsx@@ -40,7 +40,8 @@ export function ScoutRubricReference({reference.reference_limits.truncated_files.length > 0) && (<LemonBanner type="warning">Scoring is unavailable because some instructions or reference files were shortened or omitted.- Shorten the source, then generate and save a complete reference.+ Generate suggestions again, review and use the new reference, then save your rubric. You can keep+ your existing criteria.</LemonBanner>)}</div>diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 76b55819c057..d62bf4bcd367 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -95837,21 +95837,21 @@ export namespace Schemas {} as const;export interface ScoutRubricReferenceTextDocument {- /** Path of the reference supplied to the generator. */+ /** Path of the captured reference file. */path: string;- /** Content type of the supplied reference. */+ /** Content type of the captured reference file. */content_type: string;- /** Exact reference text supplied to the generator. */+ /** Saved reference text used for judging. */content: string;}export interface ScoutRubricReferenceLimitsDocument {/**- * Number of reference files not supplied.+ * Number of files missing from the saved reference.* @minimum 0*/omitted_files: number;- /** Reference paths whose supplied content was truncated. */+ /** Paths of files truncated in the saved reference. */truncated_files: string[];}@@ -95864,11 +95864,11 @@ export namespace Schemas {skill_name: string;/** Skill version used for generation. */skill_version: number;- /** Scout description supplied to the generator. */+ /** Scout description captured for this reference. */description: string;- /** Exact instructions supplied to the generator. */+ /** Saved scout instructions used for judging. */instructions: string;- /** Whether the supplied instructions were truncated. */+ /** Whether the saved instructions were truncated. */instructions_truncated: boolean;/** Report capabilities used to select the source rules.*@@ -95877,15 +95877,15 @@ export namespace Schemas {* * `edit` - Edit* * `both` - Both */report_channel: ScoutRubricReportChannelEnum;- /** Exact report-disposition rules supplied to the generator. */+ /** Report-disposition rules captured for this reference. */report_disposition_instructions: string;- /** Reference-file inventory supplied to the generator. */+ /** Reference-file inventory captured for this reference. */reference_files: string[];/** Whether the reference-file inventory was truncated. */reference_files_truncated: boolean;- /** Reference texts supplied to the generator. */+ /** Saved reference texts used for judging. */reference_texts: ScoutRubricReferenceTextDocument[];- /** Limits on the supplied reference texts. */+ /** Missing or truncated text in the saved reference. */reference_limits: ScoutRubricReferenceLimitsDocument;}