: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(flags): improve AI lifecycle tool selection (#96064)
James Gill768ed23a4290
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_require_tags.py b/products/feature_flags/backend/api/test/test_feature_flag_require_tags.pyindex 31a8579b21e2..c3fb6fdc9162 100644--- a/products/feature_flags/backend/api/test/test_feature_flag_require_tags.py+++ b/products/feature_flags/backend/api/test/test_feature_flag_require_tags.py@@ -38,7 +38,16 @@ class TestFeatureFlagRequireTags(APIBaseTest):response = self.client.post(self.url, {"key": "untagged-flag"}, format="json")assert response.status_code == status.HTTP_400_BAD_REQUEST- assert "Add at least one tag" in response.json()["detail"]+ # The whole envelope, not just the message. An agent creating a flag through MCP+ # cannot see this policy until the create is rejected, and the MCP server only+ # forwards the message when the body says `validation_error` — otherwise the+ # agent gets an opaque "HTTP 400" with no field and nothing to correct.+ assert response.json() == {+ "type": "validation_error",+ "code": "invalid_input",+ "detail": "Add at least one tag. This project requires new feature flags to be tagged.",+ "attr": "tags",+ }assert not FeatureFlag.objects.filter(key="untagged-flag", team=self.team).exists()def test_create_with_empty_tag_list_is_rejected_when_required(self) -> None:diff --git a/products/feature_flags/evals/eval_flag_answers.py b/products/feature_flags/evals/eval_flag_answers.pynew file mode 100644index 000000000000..4d958c995a12--- /dev/null+++ b/products/feature_flags/evals/eval_flag_answers.py@@ -0,0 +1,127 @@+"""What the agent tells the user when the obvious write is not the answer.++Three conversations where a flag question or a flag change cannot end in a plain+successful write, and the value of the turn is what the agent says instead:++* ``stale_flag_is_not_safe_to_remove`` — the flag has not been evaluated in months, and+ another active flag depends on it. Staleness is one signal, not a clearance.+* ``read_only_mcp_refuses_write`` — the organization caps MCP access to read-only, so+ the write is refused. The user must learn that from the reply, nothing must change,+ and the refusal has to be one the agent met rather than assumed.+* ``required_tags_create_recovers`` — the project requires a tag on every new flag, a+ policy the user did not mention and the agent cannot see until the create is rejected.++Each case pairs one judge on the final message with a deterministic row, so a message+that reads well while the tool calls tell a different story still fails.++To run:+ flox activate -- bash -c "hogli evals eval_flag_answers"+"""++from __future__ import annotations++import json+from pathlib import Path++from products.feature_flags.evals.scorers import (+ EXPLAINED_TAG_REQUIREMENT_QUESTION,+ REFUSED_WITHOUT_BLAMING_QUESTION,+ STALE_IS_NOT_SAFE_TO_REMOVE_QUESTION,+ AttemptedTool,+ AvoidedTool,+ CalledExpectedTool,+ CreatedFlagWithTags,+ FinalMessageJudge,+ FinalMessageNames,+)+from products.feature_flags.evals.seeders import (+ DEPENDENT_FLAG_KEY,+ READ_ONLY_FLAG_KEY,+ REQUIRED_TAGS_FLAG_KEY,+ STALE_FLAG_KEY,+ seed_read_only_mcp_org,+ seed_require_flag_tags,+ seed_stale_flag,+)+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext++_TOOL_DEFINITIONS = Path(__file__).parents[3] / "services/mcp/schema/generated-tool-definitions.json"+FLAG_TOOL_CATEGORY = "Feature flags"+++def flag_write_tools() -> list[str]:+ """Every flag write the MCP server exposes, read from the generated catalog.++ Derived rather than copied. The read-only case passes as soon as none of these+ landed, so a write tool added to the category later and missed here would be a+ write the case never looked for. Scheduling a change counts as a write, which is+ why `scheduled-changes-*` arrive with the rest.+ """+ definitions = json.loads(_TOOL_DEFINITIONS.read_text())+ return sorted(+ name+ for name, entry in definitions.items()+ if entry.get("category") == FLAG_TOOL_CATEGORY and entry.get("annotations", {}).get("readOnlyHint") is False+ )+++async def eval_flag_answers(ctx: EvalContext) -> None:+ write_tools = flag_write_tools()+ cases: list[SandboxedEvalCase] = [+ SandboxedEvalCase(+ name="stale_flag_is_not_safe_to_remove",+ prompt=f"Is the {STALE_FLAG_KEY} flag stale, and what evidence do we have?",+ setup=seed_stale_flag,+ expected={+ "called_expected_tool": {"tools": ["feature-flags-status-retrieve"]},+ "stale_is_not_safe_to_remove": {"required": True},+ # The judge grades how the answer reads. This grades whether the agent+ # found the blocker at all, which it can only do by looking past the+ # status endpoint to the flag's dependents.+ "final_message_names": {"text": [DEPENDENT_FLAG_KEY]},+ },+ ),+ SandboxedEvalCase(+ name="read_only_mcp_refuses_write",+ prompt=f"Turn the {READ_ONLY_FLAG_KEY} flag off.",+ setup=seed_read_only_mcp_org,+ expected={+ # The cap is enforced at the API, so the write tools are still offered and+ # the refusal arrives as a 403. An agent that never sent one is reporting a+ # restriction it assumed, which reads the same in the final message.+ "attempted_tool": {"tools": write_tools},+ "avoided_tool": {"tools": write_tools},+ "refused_without_blaming": {"required": True},+ },+ ),+ SandboxedEvalCase(+ name="required_tags_create_recovers",+ prompt=(+ f"Add a kill switch flag called {REQUIRED_TAGS_FLAG_KEY} so we can turn the billing "+ "sync off if it starts failing."+ ),+ setup=seed_require_flag_tags,+ expected={+ "created_flag_with_tags": {"required": True},+ "explained_tag_requirement": {"required": True},+ },+ ),+ ]++ await SandboxedPrivateEval(+ experiment_name="sandboxed-feature-flags-answers-cli",+ cases=cases,+ scorers=[+ CalledExpectedTool(),+ AttemptedTool(),+ AvoidedTool(),+ CreatedFlagWithTags(),+ FinalMessageNames(),+ FinalMessageJudge(name="stale_is_not_safe_to_remove", question=STALE_IS_NOT_SAFE_TO_REMOVE_QUESTION),+ FinalMessageJudge(name="refused_without_blaming", question=REFUSED_WITHOUT_BLAMING_QUESTION),+ FinalMessageJudge(name="explained_tag_requirement", question=EXPLAINED_TAG_REQUIREMENT_QUESTION),+ ],+ ctx=ctx,+ )diff --git a/products/feature_flags/evals/eval_flag_tool_selection.py b/products/feature_flags/evals/eval_flag_tool_selection.pynew file mode 100644index 000000000000..205c60aa07e9--- /dev/null+++ b/products/feature_flags/evals/eval_flag_tool_selection.py@@ -0,0 +1,162 @@+"""Which write the agent picks when a user asks to change a feature flag.++The flag lifecycle tools (`feature-flag-enable`, `-disable`, `-archive`, `-unarchive`)+each change one state field and send no body, so a targeting change someone else made+between the agent's read and its write survives. `update-feature-flag` is a PATCH whose+`filters` replaces the whole object. Both can leave a flag in the state the user asked+for; only one of them is safe. So these cases grade the tool and the payload, not the+final state, which cannot tell the two apart.++Five conversations, one per way the choice goes wrong:++* ``metadata_rename_and_description`` — a rename must land both edits and must not+ carry `filters`.+* ``existing_key_create_recovers`` — an already-taken key must resolve by key and+ continue, not create a second flag or dead-end.+* ``disable_uses_lifecycle_tool`` / ``enable_uses_lifecycle_tool`` — a state flip must+ not go through the generic update.+* ``rollout_10_to_25_preserves_config`` — a rollout change genuinely needs the generic+ update, and must merge rather than replace.++The rollout case runs against `update-feature-flag` on purpose. Dedicated rollout tools+are not built yet; when they land, this case retargets to them and the preservation+assertion moves to whatever payload they take.++To run:+ flox activate -- bash -c "hogli evals eval_flag_tool_selection"+"""++from __future__ import annotations++from products.feature_flags.evals.scorers import (+ EXPLAINED_KEY_REUSE_QUESTION,+ AvoidedTool,+ CalledExpectedTool,+ FinalMessageJudge,+ GenericUpdateOmitsFields,+ GenericUpdateSetsFields,+ PreservedUnrelatedConfig,+ UpdatedRolloutTo,+)+from products.feature_flags.evals.seeders import (+ DISABLE_FLAG_KEY,+ ENABLE_FLAG_KEY,+ EXISTING_FLAG_KEY,+ EXISTING_FLAG_TO_PERCENTAGE,+ METADATA_FLAG_KEY,+ ROLLOUT_FLAG_KEY,+ ROLLOUT_FROM_PERCENTAGE,+ ROLLOUT_TO_PERCENTAGE,+ seed_active_flag,+ seed_existing_key_flag,+ seed_inactive_flag,+ seed_metadata_flag,+ seed_rollout_flag,+)+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.scorers import RequiredToolCall++# The rename case asks for these two values, so the prompt and the scorer read the same+# constants: a prompt that changed without the expectation would grade the old request.+METADATA_RENAMED_KEY = "file-preview-tiles"+METADATA_NEW_DESCRIPTION = "Show grid thumbnails in the file browser"+++async def eval_flag_tool_selection(ctx: EvalContext) -> None:+ cases: list[SandboxedEvalCase] = [+ SandboxedEvalCase(+ name="metadata_rename_and_description",+ prompt=(+ f"Rename the {METADATA_FLAG_KEY} feature flag to {METADATA_RENAMED_KEY}, and change its "+ f"description to '{METADATA_NEW_DESCRIPTION}'."+ ),+ setup=seed_metadata_flag,+ expected={+ "called_expected_tool": {"tools": ["update-feature-flag"]},+ # A rename has no reason to send targeting. Sending it replaces the+ # seeded plan condition with whatever the agent last read.+ "generic_update_omits_fields": {"fields": ["filters"]},+ # `name` is the description on this model, so the two halves of the+ # request land in two different fields and an agent can write one into+ # the other.+ "generic_update_sets_fields": {+ "fields": {"key": METADATA_RENAMED_KEY, "name": METADATA_NEW_DESCRIPTION}+ },+ },+ ),+ SandboxedEvalCase(+ name="existing_key_create_recovers",+ prompt=(+ f"Create a feature flag called {EXISTING_FLAG_KEY} so we can gate the new multi-file "+ f"download behind it, at a {EXISTING_FLAG_TO_PERCENTAGE}% rollout."+ ),+ setup=seed_existing_key_flag,+ expected={+ # The prompt gives an exact key, which is what the by-key lookup is for.+ "called_expected_tool": {"tools": ["feature-flag-get-definition-by-key"]},+ "avoided_tool": {"tools": ["create-feature-flag"]},+ # The judge reads the final message, so "I reused the existing flag"+ # scores the same whether or not the write happened. This makes the+ # claim answerable from the tool calls.+ "updated_rollout_to": {"percentage": EXISTING_FLAG_TO_PERCENTAGE},+ # The seeded flag carries a 20% condition the update must not drop.+ "preserved_unrelated_config": {"required": True},+ "explained_key_reuse": {"required": True},+ },+ ),+ SandboxedEvalCase(+ name="disable_uses_lifecycle_tool",+ prompt=f"Turn the {DISABLE_FLAG_KEY} flag off, we're seeing complaints about it.",+ setup=seed_active_flag,+ expected={+ "called_expected_tool": {"tools": ["feature-flag-disable"]},+ "generic_update_omits_fields": {"fields": ["active", "archived", "filters"]},+ },+ ),+ SandboxedEvalCase(+ name="enable_uses_lifecycle_tool",+ prompt=f"Switch the {ENABLE_FLAG_KEY} flag on.",+ setup=seed_inactive_flag,+ expected={+ "called_expected_tool": {"tools": ["feature-flag-enable"]},+ "generic_update_omits_fields": {"fields": ["active", "archived", "filters"]},+ },+ ),+ SandboxedEvalCase(+ name="rollout_10_to_25_preserves_config",+ prompt=(+ f"Take the {ROLLOUT_FLAG_KEY} flag from a {ROLLOUT_FROM_PERCENTAGE}% rollout to "+ f"{ROLLOUT_TO_PERCENTAGE}%."+ ),+ setup=seed_rollout_flag,+ expected={+ "called_expected_tool": {"tools": ["update-feature-flag"]},+ "preserved_unrelated_config": {"required": True},+ },+ metadata={"retarget_when": "dedicated rollout tools land"},+ ),+ ]++ await SandboxedPrivateEval(+ experiment_name="sandboxed-feature-flags-tool-selection-cli",+ cases=cases,+ scorers=[+ # Every prompt names its flag by key, and the write tools take a numeric id.+ # An agent that resolved neither never reached the write, so this row keeps a+ # case that failed early from reading as a clean tool-selection result.+ RequiredToolCall(+ {"feature-flag-get-definition-by-key", "feature-flag-get-all", "feature-flag-get-definition"},+ name="resolved_flag_by_key",+ ),+ CalledExpectedTool(),+ AvoidedTool(),+ GenericUpdateOmitsFields(),+ GenericUpdateSetsFields(),+ PreservedUnrelatedConfig(),+ UpdatedRolloutTo(),+ FinalMessageJudge(name="explained_key_reuse", question=EXPLAINED_KEY_REUSE_QUESTION),+ ],+ ctx=ctx,+ )diff --git a/products/feature_flags/evals/scorers.py b/products/feature_flags/evals/scorers.pyindex a71349481533..88aeaa5d0af0 100644--- a/products/feature_flags/evals/scorers.py+++ b/products/feature_flags/evals/scorers.py@@ -1,15 +1,618 @@-"""Scorers and tool groups shared by the feature-flags eval suites."""+"""Scorers for the feature-flag eval suites.++Two sets live here. The lifecycle scorers grade which write an agent picked and what+it put in the payload. The cleanup scorers below them grade the stale-flag cleanup+skill, which must read a flag and change nothing.++Every scorer reads its per-case parameters from ``expected`` under its own+``_name()``, the convention ``products/posthog_ai/evals/cli_mcp/scorers.py`` uses,+and returns ``score=None`` when its key is absent so a case it does not apply to+does not drag the rollup down.++The deterministic ones read the agent's tool calls, not the database. What went+wrong in a bad run is which tool the agent picked and what it put in the payload, so+that is what these grade. A flag left in the right state by the wrong write — a+generic PATCH that replaced `filters` on its way to flipping `active` — is the exact+failure the lifecycle tools exist to prevent, and final state cannot see it.++Scoping: a scorer grades only the calls that name the case's seeded flag, through+``_on_seeded_flag``. The same lifecycle call on one of the demo project's own flags is+a mis-resolution, not a pass. ``AvoidedTool`` and ``GenericUpdateOmitsFields`` opt out+and read every call in the log, because both grade a write that must not happen at+all: a forbidden write is still forbidden when it lands on the wrong flag, and+widening them can only fail a run that a narrower reading would have passed.+"""from __future__ import annotations+import jsonimport asyncio+from collections import Counterfrom typing import Anyfrom products.feature_flags.backend.models.feature_flag import FeatureFlag-from products.posthog_ai.eval_harness.log_parser import LogParser-from products.posthog_ai.eval_harness.scorers import AsyncOnlyScorerMixin+from products.posthog_ai.eval_harness.log_parser import LogParser, ToolCall+from products.posthog_ai.eval_harness.scorers import (+ BINARY_CHOICE_SCORES,+ JUDGE_MODEL,+ AsyncOnlyScorerMixin,+ JudgedScorer,+)from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer+__all__ = [+ "DEPENDENTS_READ_TOOLS",+ "EXPLAINED_KEY_REUSE_QUESTION",+ "EXPLAINED_TAG_REQUIREMENT_QUESTION",+ "FILE_EDIT_TOOLS",+ "FLAG_LOOKUP_TOOLS",+ "FLAG_MUTATION_TOOLS",+ "GENERIC_UPDATE_TOOL",+ "REFUSED_WITHOUT_BLAMING_QUESTION",+ "SCHEDULE_READ_TOOLS",+ "STALE_IS_NOT_SAFE_TO_REMOVE_QUESTION",+ "WATCHED_FLAG_FIELDS",+ "AttemptedTool",+ "AvoidedTool",+ "CalledExpectedTool",+ "CreatedFlagWithTags",+ "FinalMessageJudge",+ "FinalMessageNames",+ "FlagStateUnchanged",+ "GenericUpdateOmitsFields",+ "GenericUpdateSetsFields",+ "PreservedUnrelatedConfig",+ "ToolGroupDirection",+ "UpdatedRolloutTo",+ "read_flag_state",+]++GENERIC_UPDATE_TOOL = "update-feature-flag"+CREATE_TOOL = "create-feature-flag"+++def _spec(expected: dict | None, scorer_name: str) -> dict | None:+ if not isinstance(expected, dict):+ return None+ spec = expected.get(scorer_name)+ return spec if isinstance(spec, dict) else None+++def _parser(output: dict | None) -> LogParser | None:+ if not output:+ return None+ raw_log = output.get("raw_log")+ if not raw_log:+ return None+ return LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")+++def _successful(parser: LogParser, name: str) -> list[ToolCall]:+ return [call for call in parser.get_tool_calls(name) if not call.is_error]+++def _seed(output: dict | None) -> dict | None:+ seed = (output or {}).get("seed")+ return seed if isinstance(seed, dict) else None+++# The by-key lookup accepts these aliases and normalizes them onto `key`, and the log+# records what the agent sent rather than what the tool normalized it to.+_FLAG_KEY_FIELDS = ("key", "flagKey", "flag_key", "feature_flag_key", "featureFlagKey")+++def _targets_seeded_flag(call: ToolCall, seed: dict | None) -> bool:+ """Did this call name the flag the case seeded?++ Each case runs in a team that already holds the demo project's own flags, and the+ prompts name a flag by key while the write tools take a numeric id. The same tool+ call on a different flag is a different answer, so the tool name alone cannot say+ the agent did what was asked. A call that names no flag this can check, such as a+ search, still counts: what that call contributes to a case is the tool itself.+ """+ if seed is None:+ return True+ flag_id = seed.get("feature_flag_id")+ if flag_id is not None and "id" in call.input:+ return str(call.input["id"]) == str(flag_id)+ key = seed.get("feature_flag_key")+ if key is None:+ return True+ named = [call.input[field] for field in _FLAG_KEY_FIELDS if field in call.input]+ return key in named if named else True+++def _on_seeded_flag(calls: list[ToolCall], seed: dict | None) -> list[ToolCall]:+ return [call for call in calls if _targets_seeded_flag(call, seed)]+++def _tools(spec: dict) -> list[str]:+ raw = spec.get("tools")+ return [tool for tool in raw if isinstance(tool, str)] if isinstance(raw, list) else []+++class CalledExpectedTool(Scorer):+ """Binary: did the agent successfully call one of ``expected.tools`` on the seeded flag?++ One instance serves every case, because what varies between cases is exactly the+ tool a competent agent should reach for. The flag has to match too: the same+ lifecycle call on one of the demo project's own flags is the mis-resolution these+ cases exist to catch, not a pass.+ """++ def _name(self) -> str:+ return "called_expected_tool"++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:+ spec = _spec(expected, self._name())+ tools = _tools(spec) if spec else []+ if not tools:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()}.tools on case"})+ parser = _parser(output)+ if not parser:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ seed = _seed(output)+ called = sorted({tool for tool in tools if _on_seeded_flag(_successful(parser, tool), seed)})+ if called:+ return Score(name=self._name(), score=1.0, metadata={"called": called})+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "expected_any_of": sorted(tools),+ "called_on_another_flag": sorted({tool for tool in tools if _successful(parser, tool)}),+ },+ )+++class AvoidedTool(Scorer):+ """Binary: did the agent avoid successfully calling any of ``expected.tools``?++ Failed attempts pass. The agent is free to try a tool and be refused; what this+ grades is whether the write landed.+ """++ def _name(self) -> str:+ return "avoided_tool"++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:+ spec = _spec(expected, self._name())+ tools = _tools(spec) if spec else []+ if not tools:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()}.tools on case"})+ parser = _parser(output)+ if not parser:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ called = sorted({tool for tool in tools if _successful(parser, tool)})+ if called:+ return Score(name=self._name(), score=0.0, metadata={"called": called})+ return Score(name=self._name(), score=1.0, metadata={"forbidden": sorted(tools)})+++class AttemptedTool(Scorer):+ """Binary: did the agent try one of ``expected.tools`` on the seeded flag?++ The mirror of ``AvoidedTool``, for the case whose answer is a refusal. Every other+ row on that case passes by inaction: no forbidden call succeeded, and a message can+ report a refusal the agent never met. Attempts that were refused are the point here,+ so an error counts; whether one landed is the other row's question.+ """++ def _name(self) -> str:+ return "attempted_tool"++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:+ spec = _spec(expected, self._name())+ tools = _tools(spec) if spec else []+ if not tools:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()}.tools on case"})+ parser = _parser(output)+ if not parser:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ seed = _seed(output)+ attempted = sorted({tool for tool in tools if _on_seeded_flag(parser.get_tool_calls(tool), seed)})+ if attempted:+ return Score(name=self._name(), score=1.0, metadata={"attempted": attempted})+ return Score(name=self._name(), score=0.0, metadata={"expected_an_attempt_at_any_of": sorted(tools)})+++class GenericUpdateOmitsFields(Scorer):+ """Binary: did every successful generic update leave ``expected.fields`` out?++ Two failures share this shape. A metadata edit that also sends `filters` replaces+ the whole targeting object, so a condition someone added between the read and the+ write is gone. A state change sent as `active` or `archived` here does the same+ thing on the way to a flip that `feature-flag-enable` / `-disable` would have made+ on its own, with no body at all.+ """++ def _name(self) -> str:+ return "generic_update_omits_fields"++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:+ spec = _spec(expected, self._name())+ raw = spec.get("fields") if spec else None+ fields = [field for field in raw if isinstance(field, str)] if isinstance(raw, list) else []+ if not fields:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()}.fields on case"})+ parser = _parser(output)+ if not parser:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ sent = sorted(+ {field for call in _successful(parser, GENERIC_UPDATE_TOOL) for field in fields if field in call.input}+ )+ if sent:+ return Score(name=self._name(), score=0.0, metadata={"sent_via_generic_update": sent})+ return Score(name=self._name(), score=1.0, metadata={"forbidden_fields": sorted(fields)})+++def _same_text(written: Any, asked: Any) -> bool:+ """Compare what the agent wrote against what the prompt asked for.++ Case and surrounding whitespace are the agent's to choose; the words are not.+ """+ if isinstance(written, str) and isinstance(asked, str):+ return written.strip().casefold() == asked.strip().casefold()+ return bool(written == asked)+++class GenericUpdateSetsFields(Scorer):+ """Binary: did the generic updates carry every ``expected.fields`` value?++ ``GenericUpdateOmitsFields`` passes by inaction, because an update carrying nothing+ omits every forbidden field too. This is the positive half: the edit the user asked for has to+ be in a body somewhere. `name` holds the description on this model, so an agent+ that hears "rename" and writes the new key into `name` fails here while looking+ right to every other row on the case.++ The fields may arrive across more than one update, because splitting the rename+ from the description is chatty rather than wrong.+ """++ def _name(self) -> str:+ return "generic_update_sets_fields"++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:+ spec = _spec(expected, self._name())+ raw = spec.get("fields") if spec else None+ fields = raw if isinstance(raw, dict) and raw else None+ if not fields:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()}.fields on case"})+ parser = _parser(output)+ if not parser:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ writes = _on_seeded_flag(_successful(parser, GENERIC_UPDATE_TOOL), _seed(output))+ written = {field: [call.input[field] for call in writes if field in call.input] for field in fields}+ missing = sorted(+ field for field, values in written.items() if not any(_same_text(value, fields[field]) for value in values)+ )+ return Score(+ name=self._name(),+ score=0.0 if missing else 1.0,+ metadata={+ "not_written_as_asked": missing,+ "written": {field: values for field, values in written.items() if values},+ },+ )+++class CreatedFlagWithTags(Scorer):+ """Binary: did the flag the case asked for land, carrying at least one tag?++ The project requires a tag, so a create with none is rejected. This passes only+ when the agent ends up with that flag created, whether it tagged the first attempt+ or recovered from the rejection. A tagged create under some other key is a+ different flag, so it does not count.+ """++ def _name(self) -> str:+ return "created_flag_with_tags"++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:+ spec = _spec(expected, self._name())+ if not spec:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} spec on case"})+ parser = _parser(output)+ if not parser:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ seed = _seed(output)+ attempts = parser.get_tool_calls(CREATE_TOOL)+ for call in attempts:+ if call.is_error or not _targets_seeded_flag(call, seed):+ continue+ tags = call.input.get("tags")+ if isinstance(tags, list) and any(isinstance(tag, str) and tag.strip() for tag in tags):+ return Score(name=self._name(), score=1.0, metadata={"tags": tags, "attempts": len(attempts)})+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "No successful create of the case's flag carried a tag", "attempts": len(attempts)},+ )+++def _groups(filters: Any) -> list[dict]:+ if not isinstance(filters, dict):+ return []+ groups = filters.get("groups")+ return [group for group in groups if isinstance(group, dict)] if isinstance(groups, list) else []+++def _variants(filters: Any) -> list[str]:+ """Every variant, whole and in order.++ Whole, because a variant compared by its percentage alone survives a rewrite that+ drops its name. In order, because the list decides which users land in which+ variant. Only the keys inside one variant are sorted, which an agent is free to+ reorder.+ """+ if not isinstance(filters, dict):+ return []+ multivariate = filters.get("multivariate")+ variants = multivariate.get("variants") if isinstance(multivariate, dict) else None+ if not isinstance(variants, list):+ return []+ return [json.dumps(variant, sort_keys=True) for variant in variants]+++def _canonical_group(group: dict) -> str:+ """One release condition as a comparable string.++ The whole condition, because a percentage read apart from the properties it serves+ cannot tell a rollout change from two conditions trading percentages, and a+ condition read as properties plus percentage hides a group-level variant override.+ The properties inside a condition are sorted because they AND together, and keys+ are sorted because an agent that rewrites the definition may emit them in any order.+ """+ properties = group.get("properties")+ canonical: dict[str, Any] = {key: value for key, value in group.items() if key != "properties"}+ canonical["properties"] = (+ sorted(json.dumps(prop, sort_keys=True) for prop in properties) if isinstance(properties, list) else properties+ )+ return json.dumps(canonical, sort_keys=True)+++def _rollout_checks(after: Any, seed: dict) -> tuple[dict[str, bool], list[str]]:+ """Grade one written `filters` object against the definition the seed declared."""+ before = seed["initial_filters"]+ source = seed.get("rollout_from_percentage")+ target = seed.get("rollout_to_percentage")++ before_groups = _groups(before)+ after_groups = _groups(after)+ moved = [+ {**group, "rollout_percentage": target} for group in before_groups if group.get("rollout_percentage") == source+ ]+ pinned = [group for group in before_groups if group.get("rollout_percentage") != source]+ # Counted over every condition at once, so two of them that traded percentages+ # cannot cover for each other.+ missing = Counter(_canonical_group(group) for group in [*moved, *pinned]) - Counter(+ _canonical_group(group) for group in after_groups+ )++ checks = {+ "moved_the_target_group": not any(_canonical_group(group) in missing for group in moved),+ "kept_the_other_conditions": not any(_canonical_group(group) in missing for group in pinned),+ "kept_every_condition": len(after_groups) == len(before_groups),+ "kept_the_variants": _variants(after) == _variants(before),+ "kept_the_payloads": (after.get("payloads") if isinstance(after, dict) else None) == before.get("payloads"),+ }+ return checks, sorted(missing.elements())+++class PreservedUnrelatedConfig(Scorer):+ """Binary: did the rollout edit move one number and keep everything else?++ Sending `filters` replaces the whole object, so an agent that writes the new+ percentage without merging the current definition silently drops the other release+ condition, the variants and the payloads. Compares whole release conditions against+ the ones the seed declared, so a write that moves the number onto the wrong+ condition fails, while a rewrite that only reorders what it read still passes.++ Every write to the seeded flag is graded, not the final one. A write that flattened+ the definition already lost whatever a teammate added since the agent's read, and+ the flag serves the wrong people until the next write lands, so an agent that+ repaired its own damage did not make a safe edit.+ """++ def _name(self) -> str:+ return "preserved_unrelated_config"++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:+ spec = _spec(expected, self._name())+ if not spec:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} spec on case"})+ seed = _seed(output)+ if seed is None or not isinstance(seed.get("initial_filters"), dict):+ return Score(name=self._name(), score=0.0, metadata={"reason": "Case seed carries no initial_filters"})+ # Without the percentages every seeded condition reads as pinned, so a correct+ # write fails on `kept_the_other_conditions` and the run looks like an agent+ # regression instead of a seed that is missing a field.+ absent = [field for field in ("rollout_from_percentage", "rollout_to_percentage") if seed.get(field) is None]+ if absent:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "Case seed carries no rollout percentages", "missing": absent},+ )+ parser = _parser(output)+ if not parser:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ writes = [+ call for call in _on_seeded_flag(_successful(parser, GENERIC_UPDATE_TOOL), seed) if "filters" in call.input+ ]+ if not writes:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No successful update sent filters"})++ failures = []+ for position, call in enumerate(writes, start=1):+ checks, not_written = _rollout_checks(call.input["filters"], seed)+ failed = sorted(name for name, ok in checks.items() if not ok)+ if failed:+ failures.append(+ {+ "write": position,+ "failed_checks": failed,+ "conditions_not_written": not_written,+ "written_filters": call.input["filters"],+ }+ )++ return Score(+ name=self._name(),+ score=0.0 if failures else 1.0,+ metadata={+ "failed_checks": sorted({name for failure in failures for name in failure["failed_checks"]}),+ "failed_writes": failures,+ "writes": len(writes),+ },+ )+++class FinalMessageNames(Scorer):+ """Binary: does the final message name every string in ``expected.text``?++ A judge grades whether an answer reads well, and a question that accepts any one of+ several caveats cannot tell which one the agent found. This grades whether the+ specific evidence reached the user. The comparison is case-insensitive because a+ flag key can be quoted, capitalized or wrapped in prose, and it reads the message+ rather than the tool calls because what the user learns is the thing being graded.+ """++ def _name(self) -> str:+ return "final_message_names"++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:+ spec = _spec(expected, self._name())+ raw = spec.get("text") if spec else None+ required = [text for text in raw if isinstance(text, str) and text] if isinstance(raw, list) else []+ if not required:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()}.text on case"})++ message = output.get("last_message") if output else None+ if not message:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No final message"})++ lowered = message.lower()+ missing = sorted(text for text in required if text.lower() not in lowered)+ if missing:+ return Score(name=self._name(), score=0.0, metadata={"missing": missing, "required": sorted(required)})+ return Score(name=self._name(), score=1.0, metadata={"required": sorted(required)})+++class UpdatedRolloutTo(Scorer):+ """Binary: did an update land on the seeded flag setting ``expected.percentage``?++ The judge that grades this case reads the final message, so a message claiming the+ existing flag was reused scores the same whether or not the write happened. This is+ the deterministic half of that pair: it reads the tool calls, so the claim has to be+ true. A release condition carries the percentage, so the check looks inside the+ written `filters` rather than at a top-level field.+ """++ def _name(self) -> str:+ return "updated_rollout_to"++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:+ spec = _spec(expected, self._name())+ target = spec.get("percentage") if spec else None+ if not isinstance(target, int):+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()}.percentage on case"})+ parser = _parser(output)+ if not parser:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ seed = _seed(output)+ writes = [+ call for call in _on_seeded_flag(_successful(parser, GENERIC_UPDATE_TOOL), seed) if "filters" in call.input+ ]+ written = [group.get("rollout_percentage") for call in writes for group in _groups(call.input["filters"])]+ if target in written:+ return Score(name=self._name(), score=1.0, metadata={"percentage": target, "writes": len(writes)})+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "No successful update of the case's flag set the requested rollout",+ "percentage": target,+ "rollouts_written": [value for value in written if value is not None],+ "writes": len(writes),+ },+ )+++class FinalMessageJudge(JudgedScorer):+ """Judge one yes/no question about the agent's final message.++ Four cases each need a different question asked of the same input, so the question+ is the only thing that varies. `name` doubles as the `expected` key that opts a+ case in, and the question text carries what a `yes` requires.+ """++ def __init__(self, *, name: str, question: str, **kwargs):+ super().__init__(+ name=name,+ prompt_template=f"{question}\n\n<message>{{{{output.last_message}}}}</message>\n\nAnswer `yes` or `no`.",+ choice_scores=BINARY_CHOICE_SCORES,+ model=JUDGE_MODEL,+ max_completion_tokens=256,+ **kwargs,+ )++ def _prepare(self, output, expected) -> dict[str, Any] | Score:+ if not _spec(expected, self._name()):+ return Score(name=self._name(), score=None, metadata={"reason": "Not applicable to this case"})+ if not output or not output.get("last_message"):+ return Score(name=self._name(), score=0.0, metadata={"reason": "No final message"})+ return {"output": {"last_message": output["last_message"]}}+++EXPLAINED_KEY_REUSE_QUESTION = (+ "A user asked an assistant to create a feature flag, and the key they named already belonged to "+ "an existing flag. Does the message below tell the user that a flag with that key already "+ "existed, and say that the assistant changed that existing flag rather than making a new one? A "+ "message that reports creating a new flag, or that stops at an error without naming the "+ "existing flag, is a no."+)++STALE_IS_NOT_SAFE_TO_REMOVE_QUESTION = (+ "A user asked an assistant whether a feature flag is stale and what evidence there is. The flag "+ "has not been evaluated for months, and another active flag depends on it. Does the message "+ "below report the staleness as one signal rather than proof, and say that another active flag "+ "depends on this one, so removing it would break that flag? Other caveats, such as a linked "+ "experiment or survey, code references, or the limits of evaluation data, are welcome but do "+ "not replace the dependent flag. A message that concludes the flag is safe to remove, or that "+ "it can be deleted, is a no, and so is one that offers only the other caveats."+)++REFUSED_WITHOUT_BLAMING_QUESTION = (+ "A user asked an assistant to change a feature flag. The organization allows the assistant to "+ "read data but not to change it, so the write was refused. Does the message below tell the user "+ "the change did not happen, and give the reason as a permission the assistant does not have "+ "rather than as a broken flag, a missing flag, or an unexplained failure? Naming who can lift "+ "the restriction, or what the user can do instead, also counts as yes. A message that claims the "+ "change was made is a no."+)++EXPLAINED_TAG_REQUIREMENT_QUESTION = (+ "A user asked an assistant to create a feature flag. The project requires every new flag to "+ "carry at least one tag, which the user did not mention. Does the message below tell the user "+ "that the project requires a tag on new flags, and say which tag the flag now carries? A message "+ "that reports the flag as created without mentioning the tag requirement is a no, and so is one "+ "that stops at the error."+)+++# --- Stale-flag cleanup suite -------------------------------------------------+# The scorers below grade `cleaning-up-stale-feature-flags`, whose contract is the+# opposite of the lifecycle suites': it reads a flag and must change nothing.+# Claude's named file tools. The codex runtime does not carry them, which is why the# suites that grade edit direction refuse codex runs (see seeders._require_claude_runtime).FILE_EDIT_TOOLS = frozenset({"Edit", "Write", "MultiEdit"})diff --git a/products/feature_flags/evals/seeders.py b/products/feature_flags/evals/seeders.pyindex 798e63843f1e..d12cf8e6cb40 100644--- a/products/feature_flags/evals/seeders.py+++ b/products/feature_flags/evals/seeders.py@@ -1,20 +1,344 @@-"""Seed helpers for the stale-flag cleanup evals.+"""Seeders for the feature-flag lifecycle eval cases.-Each seeder creates one invented flag in the case's isolated team, shaped to land in a-specific branch of ``cleaning-up-stale-feature-flags``. The keys are invented and must not-exist in the sandbox's ``posthog/hedgebox`` checkout — the cleanup cases assert a-no-references outcome, so a key that ever appears in that repo would flip the case.+Each seeder runs once, in the case's own team, after the team is provisioned and+before the prompt is dispatched. What it returns lands in ``output["seed"]``, so+scorers read the seeded key, id and filters from there rather than restating them.++Flag keys are module constants because the prompt, the seeder and the scorers all+have to mean the same flag. Keys are invented Hedgebox-flavored product names that+the seeded dataset does not already use (see ``products/posthog_ai/evals/AGENTS.md``+for the flags it does).++Two seeders here change a policy rather than create data, and both verify the policy+took effect before returning. A policy that silently failed to apply would turn its+case into a hollow pass: the agent would face no restriction and score for handling+one. Raising instead marks the case an infra error, which the harness excludes from+score averages."""from __future__ import annotations+from copy import deepcopyfrom datetime import UTC, datetime, timedeltafrom typing import Any+from django.utils import timezone++from posthog.constants import AvailableFeature+from posthog.models.organization import Organization++from products.access_control.backend.facade.mcp_access import mcp_access_denialfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.team_feature_flag_policy_config import (+ TeamFeatureFlagPolicyConfig,+ team_requires_flag_tags,+)from products.feature_flags.evals.scorers import read_flag_statefrom products.tasks.backend.facade.agents import CustomPromptSandboxContext+__all__ = [+ "DEPENDENT_FLAG_KEY",+ "DISABLE_FLAG_KEY",+ "ENABLE_FLAG_KEY",+ "EXISTING_FLAG_FROM_PERCENTAGE",+ "EXISTING_FLAG_KEY",+ "EXISTING_FLAG_TO_PERCENTAGE",+ "METADATA_FLAG_KEY",+ "READ_ONLY_FLAG_KEY",+ "REQUIRED_TAGS_FLAG_KEY",+ "ROLLOUT_FLAG_KEY",+ "ROLLOUT_FROM_PERCENTAGE",+ "ROLLOUT_INITIAL_FILTERS",+ "ROLLOUT_PINNED_PERCENTAGE",+ "ROLLOUT_TO_PERCENTAGE",+ "STALE_FLAG_KEY",+ "STALE_FLAG_LAST_CALLED_DAYS_AGO",+ "STALE_FULL_ROLLOUT_FLAG_KEY",+ "STALE_PARTIAL_ROLLOUT_FLAG_KEY",+ "guard_claude_runtime",+ "seed_active_flag",+ "seed_existing_key_flag",+ "seed_inactive_flag",+ "seed_metadata_flag",+ "seed_read_only_mcp_org",+ "seed_require_flag_tags",+ "seed_rollout_flag",+ "seed_stale_flag",+ "seed_stale_full_rollout_flag",+ "seed_stale_partial_rollout_flag",+]++METADATA_FLAG_KEY = "file-preview-thumbnails"+EXISTING_FLAG_KEY = "bulk-download-zip"+DISABLE_FLAG_KEY = "share-link-expiry"+ENABLE_FLAG_KEY = "folder-color-tags"+ROLLOUT_FLAG_KEY = "smart-upload-retry"+STALE_FLAG_KEY = "legacy-drag-drop-upload"+# The flag whose release condition points at the stale one. A scorer reads this key,+# so the answer has to name the blocker rather than any caveat it can think of.+DEPENDENT_FLAG_KEY = "upload-progress-toast"+READ_ONLY_FLAG_KEY = "team-audit-log"+# Nothing seeds this one: the case asks the agent to create it.+REQUIRED_TAGS_FLAG_KEY = "billing-sync-killswitch"++# The rollout the flag already holds, and the one the prompt asks for. The prompt and+# the scorer read the same constants, so a reworded prompt cannot leave the check+# grading the old request.+EXISTING_FLAG_FROM_PERCENTAGE = 20+EXISTING_FLAG_TO_PERCENTAGE = 30++ROLLOUT_FROM_PERCENTAGE = 10+ROLLOUT_TO_PERCENTAGE = 25+# The second release condition, which the rollout edit must leave alone.+ROLLOUT_PINNED_PERCENTAGE = 100++# Comfortably past the 30-day staleness threshold in `flag_status.py`, and relative to+# now so the case keeps meaning the same thing as time passes.+STALE_FLAG_LAST_CALLED_DAYS_AGO = 90++_BOOLEAN_FULL_ROLLOUT: dict[str, Any] = {"groups": [{"properties": [], "rollout_percentage": 100}]}++# The composite configuration a rollout edit can drop. Exported because+# `PreservedUnrelatedConfig`'s tests grade against this exact shape: a second copy would+# let them keep passing after the seeder changed.+ROLLOUT_INITIAL_FILTERS: dict[str, Any] = {+ "groups": [+ {+ "properties": [{"key": "plan", "type": "person", "value": ["business/enterprise"], "operator": "exact"}],+ "rollout_percentage": ROLLOUT_PINNED_PERCENTAGE,+ },+ {"properties": [], "rollout_percentage": ROLLOUT_FROM_PERCENTAGE},+ ],+ "multivariate": {+ "variants": [+ {"key": "control", "name": "Control", "rollout_percentage": 50},+ {"key": "retry", "name": "Retry", "rollout_percentage": 50},+ ]+ },+ "payloads": {"control": '{"attempts":0}', "retry": '{"attempts":3}'},+}+++def _create_flag(+ context: CustomPromptSandboxContext,+ *,+ key: str,+ name: str,+ filters: dict[str, Any],+ active: bool = True,+) -> FeatureFlag:+ return FeatureFlag.objects.create(+ team_id=context.team_id,+ created_by_id=context.user_id,+ key=key,+ name=name,+ filters=filters,+ active=active,+ )+++def _flag_payload(flag: FeatureFlag) -> dict[str, Any]:+ return {+ "feature_flag_id": flag.id,+ "feature_flag_key": flag.key,+ "feature_flag_name": flag.name,+ "initial_filters": flag.filters,+ "initial_active": flag.active,+ }+++def seed_metadata_flag(context: CustomPromptSandboxContext) -> dict[str, Any]:+ """One flag with real targeting, for the rename-and-redescribe case.++ The targeting exists so the case can tell a metadata-only edit from one that+ also replaced `filters`.+ """+ flag = _create_flag(+ context,+ key=METADATA_FLAG_KEY,+ name="Thumbnail previews in the file browser",+ filters={+ "groups": [+ {+ "properties": [+ {"key": "plan", "type": "person", "value": ["business/standard"], "operator": "exact"}+ ],+ "rollout_percentage": 50,+ }+ ]+ },+ )+ return _flag_payload(flag)+++def seed_existing_key_flag(context: CustomPromptSandboxContext) -> dict[str, Any]:+ """A flag already holding the key the prompt asks to create."""+ flag = _create_flag(+ context,+ key=EXISTING_FLAG_KEY,+ name="Download several files as one zip",+ filters={"groups": [{"properties": [], "rollout_percentage": EXISTING_FLAG_FROM_PERCENTAGE}]},+ )+ payload = _flag_payload(flag)+ # `PreservedUnrelatedConfig` reads these to tell the condition the prompt moves from+ # the ones it must leave alone. Without them every condition reads as pinned and a+ # correct write scores 0.+ payload["rollout_from_percentage"] = EXISTING_FLAG_FROM_PERCENTAGE+ payload["rollout_to_percentage"] = EXISTING_FLAG_TO_PERCENTAGE+ return payload+++def seed_active_flag(context: CustomPromptSandboxContext) -> dict[str, Any]:+ """An enabled flag, for the turn-it-off case."""+ flag = _create_flag(+ context,+ key=DISABLE_FLAG_KEY,+ name="Expiring share links",+ filters=_BOOLEAN_FULL_ROLLOUT,+ active=True,+ )+ return _flag_payload(flag)+++def seed_inactive_flag(context: CustomPromptSandboxContext) -> dict[str, Any]:+ """A disabled flag, for the turn-it-on case."""+ flag = _create_flag(+ context,+ key=ENABLE_FLAG_KEY,+ name="Color tags on folders",+ filters=_BOOLEAN_FULL_ROLLOUT,+ active=False,+ )+ return _flag_payload(flag)+++def seed_rollout_flag(context: CustomPromptSandboxContext) -> dict[str, Any]:+ """A flag whose composite configuration a rollout edit can drop.++ Two release conditions, two variants and two payloads. The prompt asks for one+ number to move, and `filters` replaces the whole object, so everything else here+ is what `PreservedUnrelatedConfig` checks survived.+ """+ flag = _create_flag(+ context,+ key=ROLLOUT_FLAG_KEY,+ name="Retry a failed upload automatically",+ # Copied so the ORM does not hold a reference to the shared constant.+ filters=deepcopy(ROLLOUT_INITIAL_FILTERS),+ )+ payload = _flag_payload(flag)+ payload["rollout_from_percentage"] = ROLLOUT_FROM_PERCENTAGE+ payload["rollout_to_percentage"] = ROLLOUT_TO_PERCENTAGE+ return payload+++def seed_stale_flag(context: CustomPromptSandboxContext) -> dict[str, Any]:+ """A flag that reads as stale, plus an active flag that depends on it.++ The staleness comes from usage: enabled, never archived, last evaluated well past+ the 30-day threshold in `flag_status.py`. The dependent flag is what makes the+ honest answer more than "stale, delete it" — removing this flag breaks another.+ """+ flag = _create_flag(+ context,+ key=STALE_FLAG_KEY,+ name="Drag and drop uploads (legacy path)",+ filters=_BOOLEAN_FULL_ROLLOUT,+ active=True,+ )+ FeatureFlag.objects.filter(pk=flag.pk).update(+ last_called_at=timezone.now() - timedelta(days=STALE_FLAG_LAST_CALLED_DAYS_AGO),+ created_at=timezone.now() - timedelta(days=STALE_FLAG_LAST_CALLED_DAYS_AGO * 2),+ )++ dependent = _create_flag(+ context,+ key=DEPENDENT_FLAG_KEY,+ name="Progress toast while a file uploads",+ filters={+ "groups": [+ {+ "properties": [+ {"key": str(flag.id), "type": "flag", "value": "true", "operator": "flag_evaluates_to"}+ ],+ "rollout_percentage": 100,+ }+ ]+ },+ active=True,+ )++ payload = _flag_payload(flag)+ payload["dependent_flag_key"] = dependent.key+ payload["last_called_days_ago"] = STALE_FLAG_LAST_CALLED_DAYS_AGO+ return payload+++def seed_read_only_mcp_org(context: CustomPromptSandboxContext) -> dict[str, Any]:+ """Cap the case's organization to read-only MCP access, then prove the cap holds.++ `read_only_mcp_access` denies every write that arrives through the MCP server,+ admins included, which is the pathway the sandboxed agent uses. The feature has+ to be available for the cap to apply, so grant that first.+ """+ flag = _create_flag(+ context,+ key=READ_ONLY_FLAG_KEY,+ name="Per-team audit log",+ filters=_BOOLEAN_FULL_ROLLOUT,+ active=True,+ )++ # `Team.organization` sets related_query_name="team", so a filter spells it `team`+ # even though the accessor is `organization.teams`.+ organization = Organization.objects.get(team__id=context.team_id)+ features = list(organization.available_product_features or [])+ if not organization.is_feature_available(AvailableFeature.ORGANIZATION_SECURITY_SETTINGS):+ features.append(+ {+ "key": AvailableFeature.ORGANIZATION_SECURITY_SETTINGS,+ "name": AvailableFeature.ORGANIZATION_SECURITY_SETTINGS,+ }+ )+ organization.available_product_features = features+ organization.read_only_mcp_access = True+ organization.save(update_fields=["available_product_features", "read_only_mcp_access"])++ denial = mcp_access_denial(organization, is_mcp=True, writes=True)+ if not denial:+ raise RuntimeError(+ "read_only_mcp_access did not deny an MCP write for this organization, so the case "+ "would score the agent for handling a restriction it never met. Check whether "+ "products/access_control/backend/facade/mcp_access.py still gates on "+ f"{AvailableFeature.ORGANIZATION_SECURITY_SETTINGS}."+ )++ payload = _flag_payload(flag)+ payload["expected_denial"] = denial+ return payload+++def seed_require_flag_tags(context: CustomPromptSandboxContext) -> dict[str, Any]:+ """Turn on the project's "require tags on new flags" policy, then prove it is on.++ Nothing else is seeded: the case asks the agent to create a flag, and the policy+ is what it has to notice.+ """+ TeamFeatureFlagPolicyConfig.objects.update_or_create(team_id=context.team_id, defaults={"require_tags": True})+ if not team_requires_flag_tags(context.team_id):+ raise RuntimeError(+ "the require-tags policy did not stick for this team, so the case would score the "+ "agent for recovering from an error the API never returns. Check "+ "products/feature_flags/backend/models/team_feature_flag_policy_config.py."+ )++ return {"feature_flag_key": REQUIRED_TAGS_FLAG_KEY, "requires_tags": True}+++# --- Stale-flag cleanup suite -------------------------------------------------+# These keys are invented and must not appear in the sandbox's `posthog/hedgebox`+# checkout, because the cleanup cases assert a no-references outcome.+STALE_FULL_ROLLOUT_FLAG_KEY = "sunset-widget-rollout"STALE_PARTIAL_ROLLOUT_FLAG_KEY = "beta-search-ranking"diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yamlindex 88b547154484..67dc2510b368 100644--- a/products/feature_flags/mcp/tools.yaml+++ b/products/feature_flags/mcp/tools.yaml@@ -40,7 +40,8 @@ tools:own flag. Release conditions, rollout percentages, multivariate variants, and payloads all go in thestructured `filters` param (`filters.groups` for release conditions, `filters.multivariate.variants` forvariants, `filters.payloads` for JSON-encoded payloads). Use `update-feature-flag` to change an existing- flag, and `feature-flag-get-all` first to check whether the key is already taken.+ flag. Check the key first: `feature-flag-get-definition-by-key` when you already have the exact key it will+ use, `feature-flag-get-all` when you only know part of the key or the name.include_params:- key- namediff --git a/products/posthog_ai/eval_harness/test/test_flag_lifecycle_scorers.py b/products/posthog_ai/eval_harness/test/test_flag_lifecycle_scorers.pynew file mode 100644index 000000000000..48905411711e--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_flag_lifecycle_scorers.py@@ -0,0 +1,641 @@+from __future__ import annotations++import json+from typing import Any++from parameterized import parameterized++from products.feature_flags.evals.eval_flag_answers import flag_write_tools+from products.feature_flags.evals.scorers import (+ AttemptedTool,+ AvoidedTool,+ CalledExpectedTool,+ CreatedFlagWithTags,+ FinalMessageJudge,+ FinalMessageNames,+ GenericUpdateOmitsFields,+ GenericUpdateSetsFields,+ PreservedUnrelatedConfig,+ UpdatedRolloutTo,+)+from products.feature_flags.evals.seeders import (+ DEPENDENT_FLAG_KEY,+ ROLLOUT_FROM_PERCENTAGE,+ ROLLOUT_INITIAL_FILTERS,+ ROLLOUT_PINNED_PERCENTAGE,+ ROLLOUT_TO_PERCENTAGE,+)+from products.posthog_ai.eval_harness.scorers.contract import Score++CREATE_TOOL = "create-feature-flag"+UPDATE_TOOL = "update-feature-flag"+BY_KEY_TOOL = "feature-flag-get-definition-by-key"+++def _session_update(sequence: int, update: dict) -> str:+ return json.dumps(+ {+ "type": "notification",+ "timestamp": f"2026-07-16T10:00:{sequence:02d}.000Z",+ "notification": {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {"sessionId": "session", "update": update},+ },+ }+ )+++def _tool_log(calls: list[tuple[str, dict[str, Any], str]]) -> str:+ updates: list[str] = []+ sequence = 0+ for index, (tool_name, raw_input, status) in enumerate(calls, start=1):+ call_id = f"call-{index}"+ sequence += 1+ updates.append(+ _session_update(+ sequence,+ {+ "sessionUpdate": "tool_call",+ "toolCallId": call_id,+ "status": "pending",+ "rawInput": raw_input,+ "title": tool_name,+ "_meta": {"claudeCode": {"toolName": tool_name}},+ },+ )+ )+ sequence += 1+ updates.append(+ _session_update(+ sequence,+ {+ "sessionUpdate": "tool_call_update",+ "toolCallId": call_id,+ "status": status,+ "rawOutput": "error" if status == "failed" else "ok",+ },+ )+ )+ return "\n".join(updates)+++SEEDED_FILTERS: dict[str, Any] = ROLLOUT_INITIAL_FILTERS++ROLLOUT_SEED = {+ "initial_filters": SEEDED_FILTERS,+ "rollout_from_percentage": ROLLOUT_FROM_PERCENTAGE,+ "rollout_to_percentage": ROLLOUT_TO_PERCENTAGE,+}++SEEDED_FLAG_ID = 7+SEEDED_FLAG_KEY = "smart-upload-retry"+FLAG_SEED = {"feature_flag_id": SEEDED_FLAG_ID, "feature_flag_key": SEEDED_FLAG_KEY}++RENAMED_KEY = "file-preview-tiles"+NEW_DESCRIPTION = "Show grid thumbnails in the file browser"++# What `seed_rollout_flag` really returns: the rollout percentages plus the flag's identity.+ROLLOUT_SEED_WITH_IDENTITY = {**ROLLOUT_SEED, **FLAG_SEED}+++def _merged_filters() -> dict[str, Any]:+ merged = json.loads(json.dumps(SEEDED_FILTERS))+ merged["groups"][1]["rollout_percentage"] = ROLLOUT_TO_PERCENTAGE+ return merged+++def _reordered_filters() -> dict[str, Any]:+ filters = _merged_filters()+ filters["groups"].reverse()+ for group in filters["groups"]:+ group["properties"] = [dict(reversed(list(prop.items()))) for prop in group["properties"]]+ return filters+++def _flattened_filters() -> dict[str, Any]:+ """The modal bad write: the new percentage, and nothing else the flag carried."""+ return {"groups": [{"properties": [], "rollout_percentage": ROLLOUT_TO_PERCENTAGE}]}+++def _without(key: str) -> dict[str, Any]:+ filters = _merged_filters()+ filters.pop(key)+ return filters+++def _swapped_filters() -> dict[str, Any]:+ """The two release conditions trade percentages, so the catch-all goes to 100%."""+ filters = _merged_filters()+ filters["groups"][0]["rollout_percentage"] = ROLLOUT_TO_PERCENTAGE+ filters["groups"][1]["rollout_percentage"] = ROLLOUT_PINNED_PERCENTAGE+ return filters+++def _unnamed_variants() -> dict[str, Any]:+ filters = _merged_filters()+ for variant in filters["multivariate"]["variants"]:+ variant.pop("name")+ return filters+++def _group_level_variant_override() -> dict[str, Any]:+ """The merged write, plus an override pinning the moved condition to one variant."""+ filters = _merged_filters()+ filters["groups"][1]["variant"] = "retry"+ return filters+++# A spec-driven scorer that returned 0.0 instead of None on a case it does not apply to+# would drag every unrelated case down, so the suite mean would stop meaning anything.+ [+ (CalledExpectedTool(), "called_expected_tool"),+ (AttemptedTool(), "attempted_tool"),+ (AvoidedTool(), "avoided_tool"),+ (GenericUpdateOmitsFields(), "generic_update_omits_fields"),+ (GenericUpdateSetsFields(), "generic_update_sets_fields"),+ (CreatedFlagWithTags(), "created_flag_with_tags"),+ (PreservedUnrelatedConfig(), "preserved_unrelated_config"),+ ]+)+def test_flag_scorers_self_skip_when_the_case_carries_no_spec(scorer: Any, scorer_name: str) -> None:+ score = scorer._run_eval_sync({"raw_log": _tool_log([])}, {})++ assert score.name == scorer_name+ assert score.score is None+++# The read-only case expects the agent to try the write and be refused, so a failed call+# has to pass. Counting a refused call as landed would fail every correct run of that case,+# and counting a completed one as avoided would pass a run where the write got through.+ [+ ("read_only_work_only", [("feature-flags-status-retrieve", {"id": "7"}, "completed")], 1.0),+ ("attempted_and_refused", [("feature-flag-disable", {"id": "7"}, "failed")], 1.0),+ ("write_landed", [("feature-flag-disable", {"id": "7"}, "completed")], 0.0),+ ("landed_a_different_forbidden_tool", [(UPDATE_TOOL, {"id": "7", "active": False}, "completed")], 0.0),+ ]+)+def test_avoided_tool(_name: str, calls: list[tuple[str, dict[str, Any], str]], expected_score: float) -> None:+ score = AvoidedTool()._run_eval_sync(+ {"raw_log": _tool_log(calls)},+ {"avoided_tool": {"tools": ["feature-flag-disable", UPDATE_TOOL]}},+ )++ assert score.score == expected_score+++# The refusal case turns the rule above around. Its other rows all pass on a run that made+# no calls at all, so a message claiming "I do not have permission" scores full marks+# without the agent ever meeting the restriction. A refused attempt is the evidence.+ [+ ("attempted_and_was_refused", [("feature-flag-disable", {"id": SEEDED_FLAG_ID}, "failed")], 1.0),+ # Whether the write landed is the avoided-tool row's question, not this one's.+ ("attempt_landed", [("feature-flag-disable", {"id": SEEDED_FLAG_ID}, "completed")], 1.0),+ ("read_the_flag_and_stopped", [(BY_KEY_TOOL, {"key": SEEDED_FLAG_KEY}, "completed")], 0.0),+ ("tried_on_another_flag", [("feature-flag-disable", {"id": 4242}, "failed")], 0.0),+ ]+)+def test_attempted_tool(_name: str, calls: list[tuple[str, dict[str, Any], str]], expected_score: float) -> None:+ score = AttemptedTool()._run_eval_sync(+ {"raw_log": _tool_log(calls), "seed": FLAG_SEED},+ {"attempted_tool": {"tools": ["feature-flag-disable", UPDATE_TOOL]}},+ )++ assert score.score == expected_score+++# The mirror of the rule above: only a successful call counts as having reached for the tool.+ [+ ("called_it", [("feature-flag-disable", {"id": "7"}, "completed")], 1.0),+ ("called_one_of_several", [(UPDATE_TOOL, {"id": "7"}, "completed")], 1.0),+ ("attempt_failed", [("feature-flag-disable", {"id": "7"}, "failed")], 0.0),+ ("reached_for_something_else", [("feature-flag-archive", {"id": "7"}, "completed")], 0.0),+ ]+)+def test_called_expected_tool(_name: str, calls: list[tuple[str, dict[str, Any], str]], expected_score: float) -> None:+ score = CalledExpectedTool()._run_eval_sync(+ {"raw_log": _tool_log(calls)},+ {"called_expected_tool": {"tools": ["feature-flag-disable", UPDATE_TOOL]}},+ )++ assert score.score == expected_score+++# Every case runs in a team that already holds the demo project's own flags, so the right+# tool on the wrong flag is the mis-resolution these cases exist to catch. The id arrives+# as a string or a number depending on how the agent wrote the call, and a rename carries+# the new key alongside the seeded id.+ [+ ("lifecycle_call_on_the_seeded_flag", [("feature-flag-disable", {"id": SEEDED_FLAG_ID}, "completed")], 1.0),+ ("id_written_as_a_string", [("feature-flag-disable", {"id": str(SEEDED_FLAG_ID)}, "completed")], 1.0),+ ("lifecycle_call_on_another_flag", [("feature-flag-disable", {"id": 4242}, "completed")], 0.0),+ (+ "rename_keeps_the_seeded_id_and_takes_a_new_key",+ [(UPDATE_TOOL, {"id": SEEDED_FLAG_ID, "key": "renamed"}, "completed")],+ 1.0,+ ),+ ("lookup_of_the_seeded_key", [(BY_KEY_TOOL, {"key": SEEDED_FLAG_KEY}, "completed")], 1.0),+ ("lookup_under_an_accepted_alias", [(BY_KEY_TOOL, {"flag_key": SEEDED_FLAG_KEY}, "completed")], 1.0),+ ("lookup_of_another_key", [(BY_KEY_TOOL, {"key": "file-previews"}, "completed")], 0.0),+ # A search names no single flag, so it is graded on the tool alone.+ ("search_names_no_flag", [("feature-flag-get-all", {"search": "upload"}, "completed")], 1.0),+ ]+)+def test_called_expected_tool_grades_the_seeded_flag(+ _name: str, calls: list[tuple[str, dict[str, Any], str]], expected_score: float+) -> None:+ score = CalledExpectedTool()._run_eval_sync(+ {"raw_log": _tool_log(calls), "seed": FLAG_SEED},+ {"called_expected_tool": {"tools": ["feature-flag-disable", UPDATE_TOOL, BY_KEY_TOOL, "feature-flag-get-all"]}},+ )++ assert score.score == expected_score+++# Four judges are registered across the two suites and each case opts in to some of them.+# If the spec check stopped short-circuiting, every case would be graded by questions+# written about a different case. `FinalMessageJudge` deliberately scores a missing final+# message 0.0 rather than None, because a run that said nothing did not answer the user.+ [+ ("case_did_not_opt_in", "anything", {}, None),+ ("run_left_no_final_message", "", {"refused_without_blaming": {"required": True}}, 0.0),+ ]+)+def test_final_message_judge_short_circuits(+ _name: str, last_message: str, expected: dict[str, Any], expected_score: float | None+) -> None:+ prepared = FinalMessageJudge(name="refused_without_blaming", question="q")._prepare(+ {"last_message": last_message}, expected+ )++ assert isinstance(prepared, Score)+ assert prepared.score == expected_score+++ [+ ("metadata_only_edit", [(UPDATE_TOOL, {"id": "7", "key": "renamed"}, "completed")], ["filters"], 1.0),+ (+ "edit_replaced_targeting",+ [(UPDATE_TOOL, {"id": "7", "key": "renamed", "filters": {"groups": []}}, "completed")],+ ["filters"],+ 0.0,+ ),+ # A rejected write changed nothing, so it is not the failure this grades.+ (+ "rejected_edit_sent_targeting",+ [(UPDATE_TOOL, {"id": "7", "filters": {"groups": []}}, "failed")],+ ["filters"],+ 1.0,+ ),+ (+ "state_flip_through_generic_update",+ [(UPDATE_TOOL, {"id": "7", "active": False}, "completed")],+ ["active", "archived"],+ 0.0,+ ),+ ("state_flip_through_lifecycle_tool", [("feature-flag-disable", {"id": "7"}, "completed")], ["active"], 1.0),+ ]+)+def test_generic_update_omits_fields(+ _name: str, calls: list[tuple[str, dict[str, Any], str]], fields: list[str], expected_score: float+) -> None:+ scorer = GenericUpdateOmitsFields()+ score = scorer._run_eval_sync({"raw_log": _tool_log(calls)}, {"generic_update_omits_fields": {"fields": fields}})++ assert score.score == expected_score+++# `name` holds the description on this model, so the rename and the redescribe land in two+# different fields. The neighbouring omits-fields check passes on a body carrying nothing at+# all, which is why the positive half exists.+ [+ (+ "wrote_both_halves",+ [(UPDATE_TOOL, {"id": SEEDED_FLAG_ID, "key": RENAMED_KEY, "name": NEW_DESCRIPTION}, "completed")],+ 1.0,+ ),+ ("update_carried_nothing", [(UPDATE_TOOL, {"id": SEEDED_FLAG_ID}, "completed")], 0.0),+ # The agent heard "rename" and wrote the new key into the description field.+ (+ "wrote_the_key_into_the_description",+ [(UPDATE_TOOL, {"id": SEEDED_FLAG_ID, "name": RENAMED_KEY}, "completed")],+ 0.0,+ ),+ (+ "renamed_but_left_the_description",+ [(UPDATE_TOOL, {"id": SEEDED_FLAG_ID, "key": RENAMED_KEY}, "completed")],+ 0.0,+ ),+ (+ "wrote_a_description_of_its_own",+ [(UPDATE_TOOL, {"id": SEEDED_FLAG_ID, "key": RENAMED_KEY, "name": "Thumbnails"}, "completed")],+ 0.0,+ ),+ # Two calls is chatty, not wrong, so the fields may arrive separately.+ (+ "split_the_edit_across_two_updates",+ [+ (UPDATE_TOOL, {"id": SEEDED_FLAG_ID, "key": RENAMED_KEY}, "completed"),+ (UPDATE_TOOL, {"id": SEEDED_FLAG_ID, "name": NEW_DESCRIPTION}, "completed"),+ ],+ 1.0,+ ),+ (+ "case_and_spacing_are_the_agents_to_choose",+ [+ (+ UPDATE_TOOL,+ {"id": SEEDED_FLAG_ID, "key": RENAMED_KEY, "name": f" {NEW_DESCRIPTION.upper()} "},+ "completed",+ )+ ],+ 1.0,+ ),+ (+ "rejected_update_changed_nothing",+ [(UPDATE_TOOL, {"id": SEEDED_FLAG_ID, "key": RENAMED_KEY, "name": NEW_DESCRIPTION}, "failed")],+ 0.0,+ ),+ (+ "edited_another_flag",+ [(UPDATE_TOOL, {"id": 4242, "key": RENAMED_KEY, "name": NEW_DESCRIPTION}, "completed")],+ 0.0,+ ),+ ]+)+def test_generic_update_sets_fields(+ _name: str, calls: list[tuple[str, dict[str, Any], str]], expected_score: float+) -> None:+ score = GenericUpdateSetsFields()._run_eval_sync(+ {"raw_log": _tool_log(calls), "seed": FLAG_SEED},+ {"generic_update_sets_fields": {"fields": {"key": RENAMED_KEY, "name": NEW_DESCRIPTION}}},+ )++ assert score.score == expected_score+++ [+ ("tagged_first_try", [(CREATE_TOOL, {"key": "k", "tags": ["billing"]}, "completed")], 1.0),+ ("no_tags", [(CREATE_TOOL, {"key": "k"}, "completed")], 0.0),+ ("blank_tag", [(CREATE_TOOL, {"key": "k", "tags": [" "]}, "completed")], 0.0),+ # The recovery path the required-tags case is built to measure: rejected without+ # a tag, then created with one.+ (+ "recovered_after_rejection",+ [+ (CREATE_TOOL, {"key": "k"}, "failed"),+ (CREATE_TOOL, {"key": "k", "tags": ["billing"]}, "completed"),+ ],+ 1.0,+ ),+ ("never_landed", [(CREATE_TOOL, {"key": "k", "tags": ["billing"]}, "failed")], 0.0),+ ]+)+def test_created_flag_with_tags(+ _name: str, calls: list[tuple[str, dict[str, Any], str]], expected_score: float+) -> None:+ scorer = CreatedFlagWithTags()+ score = scorer._run_eval_sync({"raw_log": _tool_log(calls)}, {"created_flag_with_tags": {"required": True}})++ assert score.score == expected_score+++# The case asks for one flag, so a tagged create under some other key is a different flag+# and leaves the asked-for one unmade.+ [+ ("created_the_flag_the_case_asked_for", "billing-sync-killswitch", 1.0),+ ("created_a_different_flag", "some-other-flag", 0.0),+ ]+)+def test_created_flag_with_tags_grades_the_asked_for_key(_name: str, created_key: str, expected_score: float) -> None:+ scorer = CreatedFlagWithTags()+ score = scorer._run_eval_sync(+ {+ "raw_log": _tool_log([(CREATE_TOOL, {"key": created_key, "tags": ["billing"]}, "completed")]),+ "seed": {"feature_flag_key": "billing-sync-killswitch", "requires_tags": True},+ },+ {"created_flag_with_tags": {"required": True}},+ )++ assert score.score == expected_score+++ [+ ("merged_the_current_definition", _merged_filters(), 1.0),+ # An agent that rewrites the definition may reorder keys and conditions without+ # changing who the flag serves. Failing that would fail every correct run.+ ("rewrote_the_definition_in_a_different_order", _reordered_filters(), 1.0),+ ("dropped_the_variants", _without("multivariate"), 0.0),+ ("dropped_the_payloads", _without("payloads"), 0.0),+ (+ "dropped_the_other_release_condition",+ {"groups": [{"properties": [], "rollout_percentage": ROLLOUT_TO_PERCENTAGE}]},+ 0.0,+ ),+ (+ "kept_the_condition_count_but_lost_its_properties",+ {+ "groups": [+ {"properties": [], "rollout_percentage": ROLLOUT_PINNED_PERCENTAGE},+ {"properties": [], "rollout_percentage": ROLLOUT_TO_PERCENTAGE},+ ],+ "multivariate": SEEDED_FILTERS["multivariate"],+ "payloads": SEEDED_FILTERS["payloads"],+ },+ 0.0,+ ),+ ("never_moved_the_target_group", SEEDED_FILTERS, 0.0),+ # The same two percentages come back, on the wrong conditions: everyone now gets+ # the flag and only paying customers are sampled. Comparing the percentages apart+ # from the conditions they serve cannot see it.+ ("swapped_the_targeting_between_the_conditions", _swapped_filters(), 0.0),+ # Both names are user-facing, and a variant checked by its percentage keeps them+ # only by accident.+ ("dropped_the_variant_names", _unnamed_variants(), 0.0),+ # Everything the seed declared is still there, plus a group-level override that+ # pins the whole condition to one variant.+ ("added_a_group_level_variant_override", _group_level_variant_override(), 0.0),+ ]+)+def test_preserved_unrelated_config(_name: str, written: dict[str, Any], expected_score: float) -> None:+ scorer = PreservedUnrelatedConfig()+ score = scorer._run_eval_sync(+ {+ "raw_log": _tool_log([(UPDATE_TOOL, {"id": "7", "filters": written}, "completed")]),+ "seed": ROLLOUT_SEED,+ },+ {"preserved_unrelated_config": {"required": True}},+ )++ assert score.score == expected_score+++# `filters` replaces the whole object, so a write that flattened it lost whatever a+# teammate added since the agent's read, and the flag serves the wrong people until the+# next write lands. Grading the last write only would call that run clean.+ [+ ("merged_on_the_first_attempt", [_merged_filters()], 1.0),+ ("flattened_then_repaired", [_flattened_filters(), _merged_filters()], 0.0),+ ("repeated_the_correct_write", [_merged_filters(), _merged_filters()], 1.0),+ ]+)+def test_preserved_unrelated_config_grades_every_write(+ _name: str, written: list[dict[str, Any]], expected_score: float+) -> None:+ scorer = PreservedUnrelatedConfig()+ score = scorer._run_eval_sync(+ {+ "raw_log": _tool_log(+ [(UPDATE_TOOL, {"id": SEEDED_FLAG_ID, "filters": filters}, "completed") for filters in written]+ ),+ "seed": ROLLOUT_SEED_WITH_IDENTITY,+ },+ {"preserved_unrelated_config": {"required": True}},+ )++ assert score.score == expected_score+++# Another flag's filters compared against this seed would fail nearly every check, so the+# write has to be attributed before it is graded — and a run that only ever wrote to+# another flag has not made the edit at all.+ [+ ("another_flags_write_is_not_graded", [(4242, _flattened_filters()), (SEEDED_FLAG_ID, _merged_filters())], 1.0),+ ("only_ever_wrote_to_another_flag", [(4242, _merged_filters())], 0.0),+ ]+)+def test_preserved_unrelated_config_grades_the_seeded_flag(+ _name: str, written: list[tuple[int, dict[str, Any]]], expected_score: float+) -> None:+ scorer = PreservedUnrelatedConfig()+ score = scorer._run_eval_sync(+ {+ "raw_log": _tool_log(+ [(UPDATE_TOOL, {"id": flag_id, "filters": filters}, "completed") for flag_id, filters in written]+ ),+ "seed": ROLLOUT_SEED_WITH_IDENTITY,+ },+ {"preserved_unrelated_config": {"required": True}},+ )++ assert score.score == expected_score+++def test_preserved_unrelated_config_fails_when_no_update_sent_filters() -> None:+ scorer = PreservedUnrelatedConfig()+ score = scorer._run_eval_sync(+ {+ "raw_log": _tool_log([("feature-flag-enable", {"id": "7"}, "completed")]),+ "seed": ROLLOUT_SEED,+ },+ {"preserved_unrelated_config": {"required": True}},+ )++ assert score.score == 0.0+++# The stale case's judge accepts several caveats, so it cannot say which one the agent+# found. This row is the one that requires the blocking dependent flag by name.+ [+ ("named_it", f"It is stale, but {DEPENDENT_FLAG_KEY} depends on it.", 1.0),+ ("named_it_in_other_case", f"Blocked by {DEPENDENT_FLAG_KEY.upper()}.", 1.0),+ ("offered_a_different_caveat", "It is stale. Check for code references first.", 0.0),+ ("said_nothing", "", 0.0),+ ]+)+def test_final_message_names(_name: str, last_message: str, expected_score: float) -> None:+ score = FinalMessageNames()._run_eval_sync(+ {"last_message": last_message},+ {"final_message_names": {"text": [DEPENDENT_FLAG_KEY]}},+ )++ assert score.score == expected_score+++# The key-reuse judge reads the final message, so "I reused the existing flag" scores the+# same whether or not the update happened. This is the row that reads the tool calls.+ [+ ("set_the_asked_for_rollout", [(SEEDED_FLAG_ID, 30)], 1.0),+ ("wrote_a_different_rollout", [(SEEDED_FLAG_ID, 50)], 0.0),+ ("claimed_it_without_writing", [], 0.0),+ ("wrote_it_on_another_flag", [(4242, 30)], 0.0),+ ("reached_it_on_a_later_write", [(SEEDED_FLAG_ID, 50), (SEEDED_FLAG_ID, 30)], 1.0),+ ]+)+def test_updated_rollout_to(_name: str, written: list[tuple[int, int]], expected_score: float) -> None:+ score = UpdatedRolloutTo()._run_eval_sync(+ {+ "raw_log": _tool_log(+ [+ (UPDATE_TOOL, {"id": flag_id, "filters": {"groups": [{"rollout_percentage": pct}]}}, "completed")+ for flag_id, pct in written+ ]+ or [("feature-flag-get-definition-by-key", {"key": SEEDED_FLAG_KEY}, "completed")]+ ),+ "seed": FLAG_SEED,+ },+ {"updated_rollout_to": {"percentage": 30}},+ )++ assert score.score == expected_score+++# A seed missing either percentage makes every condition read as pinned, so a correct+# write fails and the metadata blames the agent. The guard names the seed instead.+ [+ ("no_from_percentage", "rollout_from_percentage"),+ ("no_to_percentage", "rollout_to_percentage"),+ ]+)+def test_preserved_unrelated_config_names_a_seed_missing_its_percentages(_name: str, dropped: str) -> None:+ seed = {key: value for key, value in ROLLOUT_SEED_WITH_IDENTITY.items() if key != dropped}+ score = PreservedUnrelatedConfig()._run_eval_sync(+ {+ "raw_log": _tool_log([(UPDATE_TOOL, {"id": SEEDED_FLAG_ID, "filters": _merged_filters()}, "completed")]),+ "seed": seed,+ },+ {"preserved_unrelated_config": {"required": True}},+ )++ assert score.score == 0.0+ assert score.metadata["missing"] == [dropped]+++# `JudgedScorer._run_eval_async` reads `prepared["output"]` inside its own try block, so a+# shape that stops matching the prompt template is caught and scored 0.0 as a judge error+# on all four judges rather than raising.+def test_final_message_judge_hands_the_message_to_the_judge() -> None:+ prepared = FinalMessageJudge(name="refused_without_blaming", question="q")._prepare(+ {"last_message": "I could not change it."}, {"refused_without_blaming": {"required": True}}+ )++ assert not isinstance(prepared, Score)+ assert prepared["output"]["last_message"] == "I could not change it."+++# The read-only case passes as soon as none of these landed, so a derivation that returned+# nothing would pass every run. Reading the catalog is what keeps the list current; this+# checks the reading still finds it.+def test_flag_write_tools_reads_the_generated_catalog() -> None:+ tools = flag_write_tools()++ assert "update-feature-flag" in tools+ assert "scheduled-changes-create" in tools+ assert "feature-flag-get-all" not in tools+ assert len(tools) >= 13diff --git a/products/posthog_ai/eval_harness/test/test_flag_lifecycle_seeders.py b/products/posthog_ai/eval_harness/test/test_flag_lifecycle_seeders.pynew file mode 100644index 000000000000..fbc90e894b3c--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_flag_lifecycle_seeders.py@@ -0,0 +1,111 @@+from __future__ import annotations++from types import SimpleNamespace+from typing import TYPE_CHECKING, Any, cast++from posthog.test.base import APIBaseTest++from parameterized import parameterized++from products.access_control.backend.facade.mcp_access import mcp_access_denial+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.team_feature_flag_policy_config import team_requires_flag_tags+from products.feature_flags.evals.seeders import (+ DEPENDENT_FLAG_KEY,+ EXISTING_FLAG_FROM_PERCENTAGE,+ EXISTING_FLAG_KEY,+ EXISTING_FLAG_TO_PERCENTAGE,+ ROLLOUT_FLAG_KEY,+ ROLLOUT_FROM_PERCENTAGE,+ ROLLOUT_INITIAL_FILTERS,+ ROLLOUT_TO_PERCENTAGE,+ STALE_FLAG_KEY,+ STALE_FLAG_LAST_CALLED_DAYS_AGO,+ seed_active_flag,+ seed_existing_key_flag,+ seed_inactive_flag,+ seed_metadata_flag,+ seed_read_only_mcp_org,+ seed_require_flag_tags,+ seed_rollout_flag,+ seed_stale_flag,+)++if TYPE_CHECKING:+ from products.tasks.backend.facade.agents import CustomPromptSandboxContext+++class TestFlagLifecycleSeeders(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ # The seeders read team_id and user_id only, so a namespace stands in for the+ # real sandbox context.+ self.context = cast("CustomPromptSandboxContext", SimpleNamespace(team_id=self.team.id, user_id=self.user.id))++ # `PreservedUnrelatedConfig` and the tool scorers read these keys out of the payload,+ # and the scorer tests hand-build the dict rather than calling the seeder. A seeder+ # that stopped returning one of them would fail every case with "seed carries no+ # initial_filters", which reads as an agent regression rather than a broken fixture.+ @parameterized.expand(+ [+ ("metadata", seed_metadata_flag),+ ("existing_key", seed_existing_key_flag),+ ("active", seed_active_flag),+ ("inactive", seed_inactive_flag),+ ("rollout", seed_rollout_flag),+ ("stale", seed_stale_flag),+ ]+ )+ def test_seeder_payload_identifies_its_flag(self, _name: str, seeder: Any) -> None:+ payload = seeder(self.context)++ flag = FeatureFlag.objects.get(team_id=self.team.id, pk=payload["feature_flag_id"])+ assert payload["feature_flag_key"] == flag.key+ assert payload["initial_filters"] == flag.filters+ assert payload["initial_active"] == flag.active++ def test_rollout_seeder_carries_the_percentages_the_scorer_reads(self) -> None:+ payload = seed_rollout_flag(self.context)++ assert payload["initial_filters"] == ROLLOUT_INITIAL_FILTERS+ assert payload["rollout_from_percentage"] == ROLLOUT_FROM_PERCENTAGE+ assert payload["rollout_to_percentage"] == ROLLOUT_TO_PERCENTAGE+ assert payload["feature_flag_key"] == ROLLOUT_FLAG_KEY++ def test_existing_key_seeder_carries_the_percentages_the_scorer_reads(self) -> None:+ payload = seed_existing_key_flag(self.context)++ assert payload["feature_flag_key"] == EXISTING_FLAG_KEY+ assert payload["rollout_from_percentage"] == EXISTING_FLAG_FROM_PERCENTAGE+ assert payload["rollout_to_percentage"] == EXISTING_FLAG_TO_PERCENTAGE+ rollouts = [group["rollout_percentage"] for group in payload["initial_filters"]["groups"]]+ assert rollouts == [EXISTING_FLAG_FROM_PERCENTAGE]++ # The dependent flag is the case's whole point, and `FinalMessageNames` grades the+ # answer against this key. A seeder that stopped planting it would leave the case+ # asking for evidence that is not there.+ def test_stale_seeder_plants_a_dependent_flag_pointing_at_the_stale_one(self) -> None:+ payload = seed_stale_flag(self.context)++ assert payload["feature_flag_key"] == STALE_FLAG_KEY+ assert payload["dependent_flag_key"] == DEPENDENT_FLAG_KEY+ assert payload["last_called_days_ago"] == STALE_FLAG_LAST_CALLED_DAYS_AGO++ dependent = FeatureFlag.objects.get(team_id=self.team.id, key=DEPENDENT_FLAG_KEY)+ conditions = dependent.filters["groups"][0]["properties"]+ assert [condition["key"] for condition in conditions] == [str(payload["feature_flag_id"])]+ assert conditions[0]["operator"] == "flag_evaluates_to"++ # Both policy seeders raise instead of returning when the policy did not take, so a+ # case can never score an agent for handling a restriction it never met. These check+ # the happy path actually applies the policy the case is named after.+ def test_read_only_seeder_caps_the_organization(self) -> None:+ seed_read_only_mcp_org(self.context)++ self.organization.refresh_from_db()+ assert mcp_access_denial(self.organization, is_mcp=True, writes=True)++ def test_require_tags_seeder_binds_the_policy_to_the_team(self) -> None:+ seed_require_flag_tags(self.context)++ assert team_requires_flag_tags(self.team.id)diff --git a/services/mcp/evals/README.md b/services/mcp/evals/README.mdindex be8b72de198f..0d099b1ce082 100644--- a/services/mcp/evals/README.md+++ b/services/mcp/evals/README.md@@ -9,8 +9,9 @@ Two consumers:## Layout-- `benchmark/tasks.yaml` — the task set (v1). Each task is a realistic agent goal with the tools a competent agent should reach for.+- `benchmark/tasks.yaml` — the task set (v2). Each task is a realistic agent goal with the tools a competent agent should reach for, plus a `fixtures` block naming the entities a run needs in place.- `benchmark/schema.ts` — zod schema, loader, and types. `tests/evals/benchmark.test.ts` validates the fixtures against the schema and the live tool catalog, so a tool rename or removal fails CI here instead of silently invalidating the benchmark.+- `runner/seed.ts` — writes the `fixtures` block to the target project. See [Seeding](#seeding).## Task format@@ -35,6 +36,28 @@ Two consumers:Scores per run: task success rate, tool-selection accuracy, schema-validation failure count, tool error rate, retries per task, latency p50/p95, tokens per task.+## Seeding++Agent mode mutates state, so it needs state to mutate.+`fixtures` in `tasks.yaml` declares it, and `runner/seed.ts` writes it:++```bash+LIVE_POSTHOG_URL=http://localhost:8000 LIVE_MCP_TOKEN=phx_... \+ pnpm exec tsx evals/runner/seed.ts [--project 12345]+```++Run it before every agent-mode run.+It is idempotent over the keys it owns: it rewrites every flag in `fixtures.feature_flags` and clears the keys in `fixtures.absent_feature_flags`, so those tasks start a second run where they started the first.+`flag-create-routes-to-experiment` is the exception. The agent picks the key of the flag its experiment manages, so the seeder cannot name that key in `absent_feature_flags`, and the experiment and flag from an earlier run are still there on the next one. Delete them by hand when a rerun needs a clean project.+Probe mode needs no seeding — probes are read-only.++Two things to get right:++- **Seed the project the MCP session acts on.** Without `--project` the seeder uses the token's current project. Seeding one project while the run scores another looks exactly like a tool-selection regression.+- **Give each mutating task its own fixture.** Two tasks sharing one flag make the run order-dependent: whichever runs first decides what the next one starts from. `tests/evals/benchmark.test.ts` asserts every fixture key is named in exactly one intent, which catches both a shared fixture and an orphaned one.++The seeder talks to the REST API, not to the MCP server, so the tools under test are not also what builds the state they are measured against.+## Authoring rules- Sample intents from real usage (`$mcp_intent` clusters, `query-mcp-tool-sample-intents`) but **paraphrase — never paste customer text verbatim**, and never include PII.diff --git a/services/mcp/evals/benchmark/schema.ts b/services/mcp/evals/benchmark/schema.tsindex dc918aec9d98..b2d3a86bd3d1 100644--- a/services/mcp/evals/benchmark/schema.ts+++ b/services/mcp/evals/benchmark/schema.ts@@ -54,13 +54,58 @@ export const BenchmarkTaskSchema = z.object({probe: BenchmarkProbeSchema.optional(),})-export const BenchmarkFileSchema = z.object({- version: z.literal(1),- tasks: z.array(BenchmarkTaskSchema).min(1),-})+/** Prefix every seeded entity carries, so a fixture is never mistaken for real project data. */+export const FIXTURE_KEY_PREFIX = 'mcp-eval-'++/** Tag the seeder puts on every fixture flag, so a project's own flags stay distinguishable. */+export const FIXTURE_TAG = 'mcp-eval'++/** Both fixture lists name keys the same seeder owns, so they validate through one schema. */+const FixtureFlagKeySchema = z+ .string()+ .regex(new RegExp(`^${FIXTURE_KEY_PREFIX}[a-z0-9-]+$`), `flag fixture keys start with ${FIXTURE_KEY_PREFIX}`)+ .max(200)++export const BenchmarkFlagFixtureSchema = z+ .object({+ key: FixtureFlagKeySchema,+ name: z.string().min(1),+ active: z.boolean(),+ archived: z.boolean(),+ // Release conditions, variants and payloads, in the API's own shape. Tasks that assert+ // an edit preserved unrelated configuration need something here to preserve.+ filters: z.record(z.string(), z.unknown()).default({}),+ })+ .strict()+ // The API disables a flag on the way to archiving it, so a fixture asking for both would+ // describe a state the seeder cannot leave the flag in.+ .refine((fixture) => !(fixture.archived && fixture.active), 'an archived fixture flag cannot also be active')++// Strict all the way down, because every fixture container defaults to empty. A misspelled+// key would otherwise be stripped, leaving the seeder nothing to write and no error to say so.+export const BenchmarkFixturesSchema = z+ .object({+ feature_flags: z.array(BenchmarkFlagFixtureSchema).default([]),+ // Keys a task is asked to create. The seeder soft-deletes each one, so the create+ // path is exercised rather than a second run hitting an already-taken key.+ absent_feature_flags: z.array(FixtureFlagKeySchema).default([]),+ })+ .strict()++export const BenchmarkFileSchema = z+ .object({+ version: z.literal(2),+ // Entities `runner/seed.ts` creates and resets before an agent-mode run, so tasks that+ // mutate state start from a known place and score the same on a second run.+ fixtures: BenchmarkFixturesSchema.default({ feature_flags: [], absent_feature_flags: [] }),+ tasks: z.array(BenchmarkTaskSchema).min(1),+ })+ .strict()export type BenchmarkProbe = z.infer<typeof BenchmarkProbeSchema>export type BenchmarkTask = z.infer<typeof BenchmarkTaskSchema>+export type BenchmarkFlagFixture = z.infer<typeof BenchmarkFlagFixtureSchema>+export type BenchmarkFixtures = z.infer<typeof BenchmarkFixturesSchema>export type BenchmarkFile = z.infer<typeof BenchmarkFileSchema>export const DEFAULT_BENCHMARK_PATH = fileURLToPath(new URL('./tasks.yaml', import.meta.url))@@ -69,6 +114,20 @@ export function loadBenchmark(path: string = DEFAULT_BENCHMARK_PATH): BenchmarkFreturn BenchmarkFileSchema.parse(parseYaml(readFileSync(path, 'utf-8')))}+/**+ * Fixture flag keys a task's intent names. Task independence rides on this: two tasks that+ * mutate the same fixture flag make the run order-dependent and stop a second run from+ * starting where the first one did, so the fixture test asserts no key is named twice.+ */+export function fixtureFlagKeysInIntent(task: BenchmarkTask, fixtures: BenchmarkFixtures): string[] {+ return fixtureFlagKeys(fixtures).filter((key) => task.intent.includes(key))+}++/** Every flag key the seeder owns — the ones it writes and the ones it clears. */+export function fixtureFlagKeys(fixtures: BenchmarkFixtures): string[] {+ return [...fixtures.feature_flags.map((fixture) => fixture.key), ...fixtures.absent_feature_flags]+}+export function referencedTools(task: BenchmarkTask): string[] {return [...new Set([...task.expected_tools, ...task.acceptable_tools, ...(task.probe ? [task.probe.tool] : [])])]}diff --git a/services/mcp/evals/benchmark/tasks.yaml b/services/mcp/evals/benchmark/tasks.yamlindex 19042b948c7a..274d823eb989 100644--- a/services/mcp/evals/benchmark/tasks.yaml+++ b/services/mcp/evals/benchmark/tasks.yaml@@ -1,9 +1,105 @@-# MCP agent-experience benchmark v1.+# MCP agent-experience benchmark v2.## Task intents are paraphrased from real agent usage (top tool families by# production volume) — never verbatim copies of customer text. Keep probes# read-only; the runner refuses non-read-only probe tools.-version: 1+#+# v2 gave every feature-flag task its own fixture flag and added the fixtures+# below, so flag scores are no longer order-dependent. Scores are comparable+# within a version, not across one.+version: 2++# Entities `runner/seed.ts` writes to the target project before an agent-mode run.+# One fixture per task that mutates it: a task run twice, or a whole run repeated,+# then starts from the state declared here rather than from what the last run left.+fixtures:+ feature_flags:+ - key: mcp-eval-enable-me+ name: MCP eval — enable target+ active: false+ archived: false+ filters:+ groups:+ - properties: []+ rollout_percentage: 100++ - key: mcp-eval-disable-me+ name: MCP eval — disable target+ active: true+ archived: false+ filters:+ groups:+ - properties: []+ rollout_percentage: 100++ - key: mcp-eval-archive-me+ name: MCP eval — archive target+ # Enabled on purpose: archiving has to turn the flag off too, and the task+ # scores whether the agent says so.+ active: true+ archived: false+ filters:+ groups:+ - properties: []+ rollout_percentage: 100++ - key: mcp-eval-unarchive-me+ name: MCP eval — unarchive target+ active: false+ archived: true+ filters:+ groups:+ - properties: []+ rollout_percentage: 100++ - key: mcp-eval-retarget-me+ name: MCP eval — targeting-edit target+ active: true+ archived: false+ # Two groups, variants and a payload, so a targeting edit through the+ # generic update tool has unrelated configuration it can drop.+ filters:+ groups:+ - properties:+ - key: email+ type: person+ value: ['[email protected]']+ operator: exact+ rollout_percentage: 100+ - properties: []+ rollout_percentage: 10+ multivariate:+ variants:+ - key: control+ name: Control+ rollout_percentage: 50+ - key: test+ name: Test+ rollout_percentage: 50+ payloads:+ control: '{"layout":"list"}'+ test: '{"layout":"grid"}'++ - key: mcp-eval-rollout-conditions+ name: MCP eval — rollout-conditions read target+ active: true+ archived: false+ filters:+ groups:+ - properties:+ - key: '$geoip_country_code'+ type: person+ value: ['GB', 'IE']+ operator: exact+ rollout_percentage: 25++ # `flag-create-killswitch-no-experiment` creates this key, so the seeder clears it+ # first. `flag-create-routes-to-experiment` has no counterpart here: the agent picks+ # the key of the flag the experiment manages, so the seeder cannot name it. That+ # task's leftovers still accumulate across runs.+ absent_feature_flags:+ - mcp-eval-billing-killswitch+tasks:# --- sql ---------------------------------------------------------------- id: sql-daily-event-volume@@ -207,22 +303,21 @@ tasks:- id: flag-rollout-conditionscategory: feature-flags- intent: 'What are the rollout conditions for our mcp-analytics feature flag?'+ intent: 'What are the rollout conditions for our mcp-eval-rollout-conditions feature flag?'expected_tools: [feature-flag-get-definition-by-key]acceptable_tools: [feature-flag-get-all, feature-flag-get-definition]- success_criteria: "Resolves the flag by its key ('mcp-analytics') directly — does not guess a numeric id."-- # The lifecycle tasks below all act on one flag key, so an agent-mode run flips only that- # flag's state. They score tool selection whether or not `mcp-eval-lifecycle` exists,- # because a missing flag must produce a clear answer rather than a fallback to the generic- # update tool. Nothing seeds the key today; seed it to also exercise the state change.- # One shared key makes the run order-dependent. `flag-unarchive-stays-off` needs the flag- # archived, and only `flag-archive-completed` leaves it that way. A second full run also- # starts from the targeting the first one wrote. Give each task its own key before relying- # on the state-change half of these scores.+ success_criteria: >+ Resolves the flag by its key ('mcp-eval-rollout-conditions') directly — does not guess a numeric id — and+ reports the seeded country condition and its 25% rollout.++ # Each lifecycle task below names its own fixture flag, seeded to the state that task needs.+ # So the four run in any order, a second run starts where the first one did, and the score+ # covers the state change as well as the tool choice. They still score tool selection when+ # the fixture is missing, because an unseeded key must produce a clear answer rather than a+ # fallback to the generic update tool.- id: flag-enable-by-keycategory: feature-flags- intent: 'Turn on the mcp-eval-lifecycle feature flag.'+ intent: 'Turn on the mcp-eval-enable-me feature flag.'expected_tools: [feature-flag-enable]acceptable_tools: [feature-flag-get-definition-by-key, feature-flag-get-all, feature-flag-get-definition]success_criteria: >@@ -231,7 +326,7 @@ tasks:- id: flag-disable-reports-impactcategory: feature-flags- intent: "We're seeing errors from the mcp-eval-lifecycle flag. Switch it off."+ intent: "We're seeing errors from the mcp-eval-disable-me flag. Switch it off."expected_tools: [feature-flag-disable]acceptable_tools:[@@ -247,7 +342,7 @@ tasks:- id: flag-archive-completedcategory: feature-flags- intent: 'The mcp-eval-lifecycle rollout is finished. Archive the flag so it stops cluttering the list.'+ intent: 'The mcp-eval-archive-me rollout is finished. Archive the flag so it stops cluttering the list.'expected_tools: [feature-flag-archive]acceptable_tools: [feature-flag-get-definition-by-key, feature-flag-get-all, feature-flag-get-definition]success_criteria: >@@ -256,7 +351,7 @@ tasks:- id: flag-unarchive-stays-offcategory: feature-flags- intent: 'Bring the mcp-eval-lifecycle flag back into the flag list, I need to look at it again.'+ intent: 'Bring the mcp-eval-unarchive-me flag back into the flag list, I need to look at it again.'expected_tools: [feature-flag-unarchive]acceptable_tools: [feature-flag-get-all, feature-flag-get-definition-by-key, feature-flag-get-definition]success_criteria: >@@ -266,12 +361,14 @@ tasks:- id: flag-targeting-edit-uses-updatecategory: feature-flags- intent: 'Change the mcp-eval-lifecycle flag so it only applies to users on the @example.com domain.'+ intent: 'Take the mcp-eval-retarget-me flag from a 10% rollout to 25%.'expected_tools: [update-feature-flag]acceptable_tools: [feature-flag-get-definition-by-key, feature-flag-get-definition, feature-flag-get-all]success_criteria: >Reads the current definition first, then edits targeting through update-feature-flag. Does not reach for a- lifecycle tool, which cannot change targeting. If the flag does not exist, says so.+ lifecycle tool, which cannot change targeting. Sending `filters` replaces the whole object, so the written+ filters must keep the seeded email condition, both variants and both payloads, and change only the 10%+ group to 25%. If the flag does not exist, says so.# The description asks the agent to weigh an experiment before it creates a flag. The# pair below scores both directions: a user-visible change should route to an experiment,@@ -294,10 +391,11 @@ tasks:'Add a kill switch flag called mcp-eval-billing-killswitch so we can turn off the billing sync if it startsfailing.'expected_tools: [create-feature-flag]- acceptable_tools: [feature-flag-get-all]+ acceptable_tools: [feature-flag-get-definition-by-key, feature-flag-get-all]success_criteria: >Creates the flag and does not raise an experiment. An operational kill switch has no user-visible change- to measure.+ to measure. The intent gives the exact key, so checking it with feature-flag-get-definition-by-key is the+ expected lookup; a miss there is data, not a failure.# --- session-replay ----------------------------------------------------------- id: replay-rage-clicksdiff --git a/services/mcp/evals/runner/seed.ts b/services/mcp/evals/runner/seed.tsnew file mode 100644index 000000000000..7a1a9692ca3f--- /dev/null+++ b/services/mcp/evals/runner/seed.ts@@ -0,0 +1,235 @@+/**+ * Fixture seeder — no LLM, no MCP. Writes the benchmark's `fixtures` block straight+ * to the PostHog API so an agent-mode run starts from the state its tasks describe.+ *+ * Run it before every agent-mode run. Without it the feature-flag tasks score tool+ * selection only: the flags they name do not exist, so the state change half of each+ * `success_criteria` cannot be judged. Run it again after a run to reset. It is+ * idempotent over the keys it owns: every flag in `fixtures.feature_flags` is rewritten+ * and every key in `fixtures.absent_feature_flags` is cleared, so those tasks start a+ * second run where they started the first.+ *+ * `flag-create-routes-to-experiment` is the exception. The agent picks the key of the+ * flag its experiment manages, so the seeder cannot name that key in+ * `absent_feature_flags`, and that task's experiment and flag accumulate across runs.+ *+ * It talks to the REST API rather than to the MCP server on purpose: the tools under+ * test must not also be the thing that builds the state they are measured against.+ *+ * Usage:+ * LIVE_POSTHOG_URL=https://us.posthog.com LIVE_MCP_TOKEN=phx_... \+ * pnpm exec tsx evals/runner/seed.ts [--project 12345]+ *+ * `LIVE_MCP_TOKEN` is the same personal API key the probe uses; it needs+ * `feature_flag:write`, plus `user:read` when `--project` is omitted, because the project+ * is then resolved through `/api/users/@me/`. Without `--project` the project comes from the token's current+ * project — pass it explicitly when the MCP session points somewhere else, because+ * seeding one project and scoring another looks exactly like a tool-selection+ * regression.+ *+ * Exit code is non-zero when any fixture could not be written, so CI can gate on it.+ */++import process from 'node:process'+import { parseArgs } from 'node:util'++import { type BenchmarkFlagFixture, FIXTURE_TAG, loadBenchmark } from '../benchmark/schema'++/** A flag as the list endpoint returns it, narrowed to what the seeder reads. */+interface ListedFlag {+ id: number+ key: string+}++interface SeedOutcome {+ key: string+ action: 'created' | 'updated' | 'cleared' | 'already-absent'+}++class SeedError extends Error {+ constructor(+ public readonly key: string,+ message: string+ ) {+ super(message)+ this.name = 'SeedError'+ }+}++class PostHogApi {+ constructor(+ private readonly baseUrl: string,+ private readonly token: string+ ) {}++ async request<T>(method: string, path: string, body?: unknown): Promise<T> {+ const response = await fetch(new URL(path, this.baseUrl), {+ method,+ headers: {+ Authorization: `Bearer ${this.token}`,+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),+ },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ })+ const text = await response.text()+ if (!response.ok) {+ throw new Error(`${method} ${path} → ${response.status} ${response.statusText}: ${text.slice(0, 400)}`)+ }+ return (text ? JSON.parse(text) : {}) as T+ }+}++/** The flag state a fixture declares, in the shape the feature-flags API accepts. */+function fixtureBody(fixture: BenchmarkFlagFixture): Record<string, unknown> {+ return {+ key: fixture.key,+ name: fixture.name,+ active: fixture.active,+ archived: fixture.archived,+ filters: fixture.filters,+ // A project can require a tag on every new flag, which would otherwise reject+ // the create. The tag also marks the flag as eval-owned in the flag list.+ tags: [FIXTURE_TAG],+ }+}++/**+ * The fixture flag with this key, whatever state it is in.+ *+ * Two calls because the list endpoint hides archived flags unless `archived` is passed,+ * and passing it narrows to archived flags only — neither call alone sees both.+ */+async function findFlag(api: PostHogApi, projectId: number, key: string): Promise<ListedFlag | undefined> {+ const search = `search=${encodeURIComponent(key)}`+ for (const query of [search, `${search}&archived=true`]) {+ const page = await api.request<{ results: ListedFlag[] }>(+ 'GET',+ `/api/projects/${projectId}/feature_flags/?${query}`+ )+ // `search` is a substring match, so pin the exact key rather than taking the first hit.+ const exact = page.results.find((flag) => flag.key === key)+ if (exact) {+ return exact+ }+ }+ return undefined+}++async function seedFlag(api: PostHogApi, projectId: number, fixture: BenchmarkFlagFixture): Promise<SeedOutcome> {+ const existing = await findFlag(api, projectId, fixture.key)+ const body = fixtureBody(fixture)+ if (existing) {+ await api.request('PATCH', `/api/projects/${projectId}/feature_flags/${existing.id}/`, body)+ return { key: fixture.key, action: 'updated' }+ }+ await api.request('POST', `/api/projects/${projectId}/feature_flags/`, body)+ return { key: fixture.key, action: 'created' }+}++async function clearFlag(api: PostHogApi, projectId: number, key: string): Promise<SeedOutcome> {+ const existing = await findFlag(api, projectId, key)+ if (!existing) {+ return { key, action: 'already-absent' }+ }+ // Soft delete, the same write the `delete-feature-flag` tool makes.+ await api.request('PATCH', `/api/projects/${projectId}/feature_flags/${existing.id}/`, { deleted: true })+ return { key, action: 'cleared' }+}++async function resolveProjectId(api: PostHogApi, override: number | null): Promise<number> {+ if (override !== null) {+ return override+ }+ const me = await api.request<{ team?: { id?: number } }>('GET', '/api/users/@me/')+ const id = me.team?.id+ if (typeof id !== 'number') {+ throw new Error('could not resolve a current project from /api/users/@me/ — pass --project <id>')+ }+ return id+}++const PROJECT_FLAG = '--project'++/** Reads `--project <id>` or `--project=<id>`, and rejects anything else.+ *+ * Strict because this command writes. An argument it did not understand would fall+ * through to the token's current project, so a typo would seed a project nobody named.+ */+function parseProjectFlag(args: string[]): number | null {+ // `strict` rejects an unknown argument, a stray positional and a missing value, so a+ // typo stops the run instead of falling through to the token's current project. The+ // seeder writes six flags and soft-deletes one, so the wrong project is not+ // recoverable by rerunning it.+ const { values } = parseArgs({+ args,+ options: { project: { type: 'string', multiple: true } },+ strict: true,+ allowPositionals: false,+ })+ const given = values.project ?? []+ if (given.length === 0) {+ return null+ }+ if (given.length > 1) {+ throw new Error(`${PROJECT_FLAG} was given ${given.length} times`)+ }+ const id = Number(given[0])+ if (!given[0] || !Number.isInteger(id) || id <= 0) {+ throw new Error(`${PROJECT_FLAG} requires a positive integer project id`)+ }+ return id+}++async function main(): Promise<void> {+ const token = process.env.LIVE_MCP_TOKEN+ if (!token) {+ console.error(+ 'LIVE_MCP_TOKEN is required (a personal API key with feature_flag:write, and user:read unless you pass --project)'+ )+ process.exit(2)+ }++ let projectOverride: number | null+ try {+ projectOverride = parseProjectFlag(process.argv.slice(2))+ } catch (error) {+ console.error(error instanceof Error ? error.message : String(error))+ process.exit(2)+ return+ }++ const api = new PostHogApi(process.env.LIVE_POSTHOG_URL ?? 'http://localhost:8000', token)+ const { fixtures } = loadBenchmark()+ const projectId = await resolveProjectId(api, projectOverride)++ const outcomes: SeedOutcome[] = []+ const failures: SeedError[] = []+ // Sequential: the fixture set is small, and one flag at a time keeps a failure+ // attributable to its own key instead of to whichever request lost a race.+ for (const fixture of fixtures.feature_flags) {+ try {+ outcomes.push(await seedFlag(api, projectId, fixture))+ } catch (error) {+ failures.push(new SeedError(fixture.key, error instanceof Error ? error.message : String(error)))+ }+ }+ for (const key of fixtures.absent_feature_flags) {+ try {+ outcomes.push(await clearFlag(api, projectId, key))+ } catch (error) {+ failures.push(new SeedError(key, error instanceof Error ? error.message : String(error)))+ }+ }++ // stdout directly: the summary IS the program output (oxlint strips console.log).+ process.stdout.write(`seeded project ${projectId}\n`)+ for (const outcome of outcomes) {+ process.stdout.write(` ${outcome.action} ${outcome.key}\n`)+ }+ for (const failure of failures) {+ process.stdout.write(` FAILED ${failure.key}: ${failure.message}\n`)+ }+ process.exit(failures.length > 0 ? 1 : 0)+}++void main()diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex bb32558142a5..44093879e45e 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -2280,7 +2280,7 @@}},"create-feature-flag": {- "description": "Create a feature flag in the current project. Call when the user asks to add a flag, gate a feature behind a flag, set up a percentage rollout, or deliver a remote config value. If this flag is for a new version of a page or flow, or for a pricing or onboarding change, an experiment may be in order. Ask the user if they want to run an experiment, and if so create the experiment with `experiment-create`, which will manage its own flag. Release conditions, rollout percentages, multivariate variants, and payloads all go in the structured `filters` param (`filters.groups` for release conditions, `filters.multivariate.variants` for variants, `filters.payloads` for JSON-encoded payloads). Use `update-feature-flag` to change an existing flag, and `feature-flag-get-all` first to check whether the key is already taken.",+ "description": "Create a feature flag in the current project. Call when the user asks to add a flag, gate a feature behind a flag, set up a percentage rollout, or deliver a remote config value. If this flag is for a new version of a page or flow, or for a pricing or onboarding change, an experiment may be in order. Ask the user if they want to run an experiment, and if so create the experiment with `experiment-create`, which will manage its own flag. Release conditions, rollout percentages, multivariate variants, and payloads all go in the structured `filters` param (`filters.groups` for release conditions, `filters.multivariate.variants` for variants, `filters.payloads` for JSON-encoded payloads). Use `update-feature-flag` to change an existing flag. Check the key first: `feature-flag-get-definition-by-key` when you already have the exact key it will use, `feature-flag-get-all` when you only know part of the key or the name.","category": "Feature flags","feature": "flags","summary": "Create feature flag",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex beb1cb41b3cb..2871028fec8f 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -2295,7 +2295,7 @@}},"create-feature-flag": {- "description": "Create a feature flag in the current project. Call when the user asks to add a flag, gate a feature behind a flag, set up a percentage rollout, or deliver a remote config value. If this flag is for a new version of a page or flow, or for a pricing or onboarding change, an experiment may be in order. Ask the user if they want to run an experiment, and if so create the experiment with `experiment-create`, which will manage its own flag. Release conditions, rollout percentages, multivariate variants, and payloads all go in the structured `filters` param (`filters.groups` for release conditions, `filters.multivariate.variants` for variants, `filters.payloads` for JSON-encoded payloads). Use `update-feature-flag` to change an existing flag, and `feature-flag-get-all` first to check whether the key is already taken.",+ "description": "Create a feature flag in the current project. Call when the user asks to add a flag, gate a feature behind a flag, set up a percentage rollout, or deliver a remote config value. If this flag is for a new version of a page or flow, or for a pricing or onboarding change, an experiment may be in order. Ask the user if they want to run an experiment, and if so create the experiment with `experiment-create`, which will manage its own flag. Release conditions, rollout percentages, multivariate variants, and payloads all go in the structured `filters` param (`filters.groups` for release conditions, `filters.multivariate.variants` for variants, `filters.payloads` for JSON-encoded payloads). Use `update-feature-flag` to change an existing flag. Check the key first: `feature-flag-get-definition-by-key` when you already have the exact key it will use, `feature-flag-get-all` when you only know part of the key or the name.","category": "Feature flags","feature": "flags","summary": "Create feature flag",diff --git a/services/mcp/tests/evals/benchmark.test.ts b/services/mcp/tests/evals/benchmark.test.tsindex 8e732f9ff3a6..fa28b04b5c75 100644--- a/services/mcp/tests/evals/benchmark.test.ts+++ b/services/mcp/tests/evals/benchmark.test.ts@@ -2,7 +2,31 @@ import { describe, expect, it } from 'vitest'import { getToolDefinitions } from '@/tools/toolDefinitions'-import { TASK_CATEGORIES, loadBenchmark, referencedTools } from '../../evals/benchmark/schema'+import {+ BenchmarkFileSchema,+ TASK_CATEGORIES,+ fixtureFlagKeys,+ fixtureFlagKeysInIntent,+ loadBenchmark,+ referencedTools,+} from '../../evals/benchmark/schema'++const FLAG_FIXTURE = {+ key: 'mcp-eval-enable-me',+ name: 'Enable target',+ active: false,+ archived: false,+}++const FIXTURES_BLOCK = { feature_flags: [FLAG_FIXTURE], absent_feature_flags: ['mcp-eval-create-me'] }++const TASK = {+ id: 'enable-a-flag',+ category: 'feature-flags',+ intent: 'Turn the mcp-eval-enable-me flag on.',+ expected_tools: ['feature-flag-enable'],+ success_criteria: 'The flag is enabled and the reply says so.',+}describe('MCP eval benchmark fixtures', () => {// Loaded inside each test (not at describe scope) so a broken fixture or@@ -39,6 +63,65 @@ describe('MCP eval benchmark fixtures', () => {expect(unsafe).toEqual([])})+ // Both halves of the seeded-fixture contract in one assertion. Zero tasks means the+ // seeder writes state nothing reads, which is how a renamed key silently stops being+ // exercised. Two or more means those tasks share a flag, which is the order-dependence+ // v2 removed: whichever ran first decides what the next one starts from.+ it('names every seeded flag fixture in exactly one task intent', () => {+ const benchmark = loadBenchmark()+ const tasksByKey = new Map(fixtureFlagKeys(benchmark.fixtures).map((key) => [key, [] as string[]]))+ for (const task of benchmark.tasks) {+ for (const key of fixtureFlagKeysInIntent(task, benchmark.fixtures)) {+ tasksByKey.get(key)!.push(task.id)+ }+ }+ const wrong = [...tasksByKey.entries()]+ .filter(([, taskIds]) => taskIds.length !== 1)+ .map(([key, taskIds]) => `${key} → ${taskIds.length ? taskIds.join(', ') : 'no task'}`)+ expect(wrong).toEqual([])+ })++ // Every fixture container defaults to empty, so a stripped key used to read as "no+ // fixtures" rather than as a typo: the seeder wrote nothing, exited 0, and the test+ // above passed over an empty map while the next run scored the lifecycle tasks+ // against flags that did not exist.+ it.each([+ { name: 'the fixtures block spelled correctly', fixtures: FIXTURES_BLOCK, parses: true },+ { name: 'a misspelled fixture list', fixtures: { feature_flag: [FLAG_FIXTURE] }, parses: false },+ {+ name: 'a misspelled field on a fixture flag',+ fixtures: { feature_flags: [{ ...FLAG_FIXTURE, activee: true }] },+ parses: false,+ },+ // `clearFlag` soft-deletes whatever key it is handed, so a fixture key without+ // the prefix would delete one of the project's real flags rather than a fixture.+ {+ name: 'a fixture key missing the mcp-eval- prefix',+ fixtures: { feature_flags: [{ ...FLAG_FIXTURE, key: 'billing-killswitch' }] },+ parses: false,+ },+ {+ name: 'an absent-flag key missing the mcp-eval- prefix',+ fixtures: { ...FIXTURES_BLOCK, absent_feature_flags: ['billing-killswitch'] },+ parses: false,+ },+ // The API disables a flag on the way to archiving it, so the seeder cannot leave+ // a flag in both states and a fixture asking for both describes nothing.+ {+ name: 'a fixture that is both archived and active',+ fixtures: { feature_flags: [{ ...FLAG_FIXTURE, active: true, archived: true }] },+ parses: false,+ },+ ])('the schema accepts $name: $parses', ({ fixtures, parses }) => {+ expect(BenchmarkFileSchema.safeParse({ version: 2, fixtures, tasks: [TASK] }).success).toBe(parses)+ })++ it('rejects a misspelled fixtures block', () => {+ const parsed = BenchmarkFileSchema.safeParse({ version: 2, fixtuers: FIXTURES_BLOCK, tasks: [TASK] })++ expect(parsed.success).toBe(false)+ })+it('probes exercise a tool the task expects', () => {const mismatched = loadBenchmark().tasks.filter((task) => task.probe)