: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
chore(flags): add regression eval coverage for cleanup (#107777)
James Gill3d4eb22d86bd
diff --git a/products/feature_flags/evals/eval_cleanup_stale_flags.py b/products/feature_flags/evals/eval_cleanup_stale_flags.pyindex 4d8c8939bfb8..567ac5c15e55 100644--- a/products/feature_flags/evals/eval_cleanup_stale_flags.py+++ b/products/feature_flags/evals/eval_cleanup_stale_flags.py@@ -1,12 +1,16 @@"""Evals for the code-cleanup half of the ``cleaning-up-stale-feature-flags`` skill.-Five sandboxed cases: a generic cleanup ask, an unrelated task that mentions a flag+Seven sandboxed cases: a generic cleanup ask, an unrelated task that mentions a flagin passing (the skill must stay quiet, and the agent must still edit a file — thestale-premise guard borrowed from ``eval_instrument_flags``), a direct removal ask-for a key with no repository references, the same ask for a 40%-rollout flag, and a-direct request to archive the flag, which the skill must refuse: it never changes-the flag in PostHog, and without that case the two mutation scorers only ever see-prompts that could not produce a flag write.+for a key with no repository references — also grading whether the response waits+on product-tour usage, since no MCP tool reports it and the same fixture already+covers the scenario — the same removal ask for a 40%-rollout flag, and a direct+request to archive the flag, which the skill must refuse: it never changes the flag+in PostHog, and without that case the two mutation scorers only ever see prompts+that could not produce a flag write. Two more cover response-wording regressions:+a flag stale on every other signal but updated two days ago, and an explicit+assess-only request.What the suite cannot grade: the sandbox always clones ``posthog/hedgebox`` andseeders cannot write files into it, so retained-path correctness (does a diff keep@@ -15,8 +19,36 @@ No scorer reads repo files, branches, or PR state, and the key-named cases cannobe told apart by refusal reason. What each case does grade is its ``expected``dict below; the scorer mechanics live in the ``scorers.py`` docstrings.-All scorers are deterministic — no LLM judge — so the suite is cheap to rerun while-iterating on the skill text. ``SandboxedPrivateEval`` runs without a Braintrust key.+Two regressions have no case here for the same reason: a fixture repo with real+call sites for the seeded flag, so the skill actually edits code and a required+check can fail against it, is exactly what no seeder here can build.+``SandboxedEvalCase.repo_fixture`` names this gap but only tracks it; there is no+seeding path that lands files in the cloned repo. The skipped-pre-edit-read+regression is covered instead by deterministic scorer unit tests against+synthesized call sequences: see ``FreshReadsBeforeEdit`` in ``scorers.py`` and+``TestFreshReadsBeforeEdit`` in+``products/posthog_ai/eval_harness/test/test_feature_flags_scorers.py``.++Three more regressions are ungraded, and nothing here would catch them:++- The failed/unavailable-check refusal wording has no scorer.+- Nothing requires the skill's "Check whether the cleanup already exists" search.+ No registered scorer reads a Bash command, so a run that skips that step and goes+ straight to the call-site search passes every scorer here. The cases cannot require+ it either, because the suite accepts a run that stops to ask about product tours+ before it reaches the step. Grading it needs a case whose prompt already answers the+ tour question, and a scorer that matches the ``git log -S`` call by command text.+- Nothing checks the pre-publish read. ``FreshReadsBeforeEdit`` grades the pre-edit+ reads only, and no case reaches a publish.+``FreshReadsBeforeEdit`` is deliberately left out of the suite's scorer list below.+No case here can seed call sites, so it would add a ``None`` row to every case on+every run, and its divider would stay unmeasured against a real agent trace. The+pull request that adds the first fixture case registers it.++Most scorers are deterministic; the three wording cases use one LLM judge each+(``FinalMessageJudge``), which costs a model call per case but is what the "does the+message avoid X" question needs. ``SandboxedPrivateEval`` runs without a Braintrust+key.**Claude runtime only.** The edit-direction scorer matches Claude's named file tools,which codex does not carry, so the seeders refuse ``--agent-runtime codex`` as an infra@@ -29,18 +61,24 @@ To run:from __future__ import annotationsfrom products.feature_flags.evals.scorers import (+ ASSESSMENT_ONLY_NO_EDIT_CLAIM_QUESTION,DEPENDENTS_READ_TOOLS,FILE_EDIT_TOOLS,FLAG_LOOKUP_TOOLS,FLAG_MUTATION_TOOLS,+ RECENCY_REFUSAL_WITHOUT_OVERRIDE_QUESTION,SCHEDULE_READ_TOOLS,+ TOUR_UNKNOWN_WAITS_QUESTION,+ FinalMessageJudge,FlagStateUnchanged,ToolGroupDirection,)from products.feature_flags.evals.seeders import (STALE_FULL_ROLLOUT_FLAG_KEY,+ STALE_LOOKING_RECENT_UPDATE_FLAG_KEY,STALE_PARTIAL_ROLLOUT_FLAG_KEY,guard_claude_runtime,+ seed_recently_updated_flag,seed_stale_full_rollout_flag,seed_stale_partial_rollout_flag,)@@ -56,6 +94,9 @@ EDIT_SCORER_NAME = "code_edit_direction"LOOKUP_SCORER_NAME = "flag_lookup_direction"DEPENDENTS_SCORER_NAME = "dependents_check_direction"SCHEDULE_SCORER_NAME = "schedule_check_direction"+RECENCY_REFUSAL_SCORER_NAME = "recency_refusal_without_override"+TOUR_UNKNOWN_SCORER_NAME = "tour_unknown_waits"+ASSESSMENT_ONLY_SCORER_NAME = "assessment_only_no_edit_claim"# should_edit is False in both constants below, for two different reasons that the# repo_fixture follow-up will pull apart: these cases expect no edit because hedgebox@@ -108,12 +149,20 @@ async def eval_cleanup_stale_flags(ctx: EvalContext) -> None:),SandboxedEvalCase(name="no_references_is_noop",+ # Also the tour-unknown case: no MCP tool reports tour usage, so the agent+ # must ask before it recommends removal. Reuses this fixture rather than a+ # duplicate case, avoiding a second live agent run for the same prompt.+ # hedgebox holds no call site for the seeded key, so the correct answer here+ # is a no-op report and no case in this suite can reach a removal+ # recommendation. The tour judge therefore grades the claim, not the+ # question: a report that stops at "nothing to change" passes, and one that+ # calls the flag safe to remove without asking about tours fails.prompt=(f"The feature flag '{STALE_FULL_ROLLOUT_FLAG_KEY}' is fully rolled out and ""stale. Remove it from this repository."),setup=seed_stale_full_rollout_flag,- expected=_NO_CALL_SITES,+ expected={**_NO_CALL_SITES, TOUR_UNKNOWN_SCORER_NAME: {"required": True}},metadata={"trigger": "positive", "skill": SKILL_NAME, "rollout": "full"},),SandboxedEvalCase(@@ -139,6 +188,41 @@ async def eval_cleanup_stale_flags(ctx: EvalContext) -> None:expected=_NO_CALL_SITES,metadata={"trigger": "positive", "skill": SKILL_NAME, "rollout": "full"},),+ SandboxedEvalCase(+ name="recent_update_excluded_without_override",+ # Stale on every other signal — only `updated_at` inside the last 30 days+ # blocks this one. Grades the response wording, not just the inaction.+ # This case does not spread _NO_CALL_SITES: the by-key lookup already returns+ # updated_at, and the skill drops a candidate with a recent update before+ # assessing it, so a run that refuses after one read is following the skill.+ # Requiring the dependents and schedule reads here would fail that run. The+ # other cases still require both reads, so the coverage stays.+ prompt=(f"Remove the feature flag '{STALE_LOOKING_RECENT_UPDATE_FLAG_KEY}' from this repository."),+ setup=seed_recently_updated_flag,+ expected={+ TRIGGER_SCORER_NAME: {"should_load": True},+ EDIT_SCORER_NAME: {"should_edit": False},+ LOOKUP_SCORER_NAME: {"should_look_up": True},+ RECENCY_REFUSAL_SCORER_NAME: {"required": True},+ },+ metadata={"trigger": "positive", "skill": SKILL_NAME, "rollout": "full"},+ ),+ SandboxedEvalCase(+ name="assessment_only_reports_no_edit_claimed",+ # The tool-based scorers pass on every case here regardless (hedgebox holds+ # no call site), so this grades whether the final message itself frames the+ # answer as an assessment rather than a completed change.+ prompt=(+ f"Assess whether '{STALE_FULL_ROLLOUT_FLAG_KEY}' is ready for cleanup. "+ "Don't remove anything yet — I just want the findings."+ ),+ setup=seed_stale_full_rollout_flag,+ expected={+ **_NO_CALL_SITES,+ ASSESSMENT_ONLY_SCORER_NAME: {"required": True},+ },+ metadata={"trigger": "positive", "skill": SKILL_NAME, "rollout": "full"},+ ),]await SandboxedPrivateEval(@@ -152,6 +236,9 @@ async def eval_cleanup_stale_flags(ctx: EvalContext) -> None:ToolGroupDirection(FLAG_LOOKUP_TOOLS, name=LOOKUP_SCORER_NAME, key="should_look_up"),ToolGroupDirection(DEPENDENTS_READ_TOOLS, name=DEPENDENTS_SCORER_NAME, key="should_check_dependents"),ToolGroupDirection(SCHEDULE_READ_TOOLS, name=SCHEDULE_SCORER_NAME, key="should_check_schedules"),+ FinalMessageJudge(name=RECENCY_REFUSAL_SCORER_NAME, question=RECENCY_REFUSAL_WITHOUT_OVERRIDE_QUESTION),+ FinalMessageJudge(name=TOUR_UNKNOWN_SCORER_NAME, question=TOUR_UNKNOWN_WAITS_QUESTION),+ FinalMessageJudge(name=ASSESSMENT_ONLY_SCORER_NAME, question=ASSESSMENT_ONLY_NO_EDIT_CLAIM_QUESTION),],ctx=ctx,)diff --git a/products/feature_flags/evals/scorers.py b/products/feature_flags/evals/scorers.pyindex 907832b99947..efb36cf937ad 100644--- a/products/feature_flags/evals/scorers.py+++ b/products/feature_flags/evals/scorers.py@@ -41,6 +41,7 @@ from products.posthog_ai.eval_harness.scorers import (from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer__all__ = [+ "ASSESSMENT_ONLY_NO_EDIT_CLAIM_QUESTION","DEPENDENTS_READ_TOOLS","EXPLAINED_KEY_REUSE_QUESTION","EXPLAINED_TAG_REQUIREMENT_QUESTION",@@ -48,9 +49,13 @@ __all__ = ["FLAG_LOOKUP_TOOLS","FLAG_MUTATION_TOOLS","GENERIC_UPDATE_TOOL",+ "RECENCY_REFUSAL_WITHOUT_OVERRIDE_QUESTION","REFUSED_WITHOUT_BLAMING_QUESTION",+ "PRE_EDIT_READ_GROUPS","SCHEDULE_READ_TOOLS",+ "STATUS_READ_TOOLS","STALE_IS_NOT_SAFE_TO_REMOVE_QUESTION",+ "TOUR_UNKNOWN_WAITS_QUESTION","WATCHED_FLAG_FIELDS","AttemptedTool","AvoidedTool",@@ -59,6 +64,7 @@ __all__ = ["FinalMessageJudge","FinalMessageNames","FlagStateUnchanged",+ "FreshReadsBeforeEdit","GenericUpdateOmitsFields","GenericUpdateSetsFields","PreservedUnrelatedConfig",@@ -112,10 +118,10 @@ def _targets_seeded_flag(call: ToolCall, seed: dict | None) -> bool:"""if seed is None:return True- flag_id = seed.get("feature_flag_id")+ flag_id = seed.get("feature_flag_id", seed.get("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")+ key = seed.get("feature_flag_key", seed.get("flag_key"))if key is None:return Truenamed = [call.input[field] for field in _FLAG_KEY_FIELDS if field in call.input]@@ -550,7 +556,7 @@ class UpdatedRolloutTo(Scorer):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+ Each case needs a different question asked of the same input, so the questionis the only thing that varies. `name` doubles as the `expected` key that opts acase in, and the question text carries what a `yes` requires."""@@ -617,18 +623,26 @@ EXPLAINED_TAG_REQUIREMENT_QUESTION = (# suites that grade edit direction refuse codex runs (see seeders._require_claude_runtime).FILE_EDIT_TOOLS = frozenset({"Edit", "Write", "MultiEdit"})+# The search tools the skill's "Find every repository reference" step runs. A call here+# that lands after the first definition read is the point where assessment ends and the+# cleanup itself starts, which is what FreshReadsBeforeEdit needs to tell the two+# apart. Read is deliberately not here: the Edit tool refuses a file the agent has not+# read, so a Read sits between the fresh definition read and the first edit on every+# correct run.+REPO_SEARCH_TOOLS = frozenset({"Grep", "Glob"})++# The two lookups that return the full definition, as opposed to a status summary or+# a dependents/schedule list.+DEFINITION_READ_TOOLS = frozenset({"feature-flag-get-definition", "feature-flag-get-definition-by-key"})++# The status summary, which carries the rollout object the definition does not.+STATUS_READ_TOOLS = frozenset({"feature-flags-status-retrieve"})+# The read tools the cleanup skill's assessment steps go through. A run that never calls# any of them decided about the seeded flag without looking at it. The by-key variant is# here because it is the lookup the MCP surface steers an agent toward when a prompt hands# it a flag key and no numeric id.-FLAG_LOOKUP_TOOLS = frozenset(- {- "feature-flag-get-all",- "feature-flags-status-retrieve",- "feature-flag-get-definition",- "feature-flag-get-definition-by-key",- }-)+FLAG_LOOKUP_TOOLS = DEFINITION_READ_TOOLS | STATUS_READ_TOOLS | frozenset({"feature-flag-get-all"})# The reads behind the skill's dependency and schedule exclusions, one group per scorer# so each read is graded on its own: folded into one any-of group, a run that skipped the@@ -636,6 +650,15 @@ FLAG_LOOKUP_TOOLS = frozenset(DEPENDENTS_READ_TOOLS = frozenset({"feature-flags-dependent-flags-retrieve"})SCHEDULE_READ_TOOLS = frozenset({"scheduled-changes-list"})+# The four reads the skill's "Apply the retained path" step repeats before the first edit,+# named one group at a time so a run that repeated three of them fails on the fourth.+PRE_EDIT_READ_GROUPS: dict[str, frozenset[str]] = {+ "definition": DEFINITION_READ_TOOLS,+ "status": STATUS_READ_TOOLS,+ "dependents": DEPENDENTS_READ_TOOLS,+ "schedules": SCHEDULE_READ_TOOLS,+}+# Every write verb the current MCP surface offers for a flag. The cleanup skill must not# call any of them on any case — it never changes a flag, and archival belongs to a# deployment-confirmed continuation. A test binds this set to tools.yaml so a new write@@ -698,6 +721,160 @@ class ToolGroupDirection(Scorer):)+class FreshReadsBeforeEdit(Scorer):+ """Binary: did all four of the skill's pre-edit reads land after the search and before the first edit?++ The skill's "Apply the retained path" step repeats four reads immediately before the+ first write, even when it made them at assessment time: the definition, the status,+ the dependent flags, and the scheduled changes. A rollout that moved between+ assessment and the edit is then never edited against. An agent that assessed once and+ edited straight off those reads satisfies every other cleanup scorer here, because the+ edit direction is right and the flag itself is never mutated, so nothing else in this+ suite catches the skipped repeat.++ All four groups are required, not the definition alone. A new schedule or a new+ dependent flag does not change the definition, so a run that re-read only the+ definition and then edited a flag that gained a schedule after assessment has missed+ exactly the change the step exists to catch.++ Applies only when ``expected.fresh_reads_before_edit.required`` is true and at least+ one file-edit tool call ran; a case with no edit is a different scorer's question+ (``ToolGroupDirection`` grades whether an edit should have happened at all), so this+ one skips with ``score=None`` rather than penalizing a correct refusal.++ A count of the reads that precede the edit cannot answer the question, because reads+ taken while assessing look the same as repeated ones. A repository search divides the+ two, because an agent cannot edit a call site it has not searched for. The divider is+ the first ``REPO_SEARCH_TOOLS`` call that follows the first definition read, and not+ the first one in the run: the skill's "Establish scope" step searches the repository+ for the key before any definition is read, so a divider placed there would count the+ assessment reads themselves as the repeat. The last search does not work either,+ because the retained-path step searches again for other uses of each symbol it is+ about to remove, after its reads.++ That divider is a proxy, and requiring all four groups is what makes it safe. A search+ the agent runs between assessment and the retained path moves the divider earlier, but+ an opportunistic second definition read after it still fails, because the other three+ groups are not repeated with it.++ Whether the definition actually changed is deliberately not re-derived from the log. The+ failure this grades is the missing call. It does not check what the agent concluded from+ the response.+ """++ def _name(self) -> str:+ return "fresh_reads_before_edit"++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:+ spec = _spec(expected, self._name())+ if not spec or not spec.get("required"):+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()}.required on case"})+ parser = _parser(output)+ if not parser:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ edit_calls = [call for tool in FILE_EDIT_TOOLS for call in _successful(parser, tool)]+ if not edit_calls:+ return Score(name=self._name(), score=None, metadata={"reason": "No successful edit to gate"})+ first_edit_position = min(call.position for call in edit_calls)++ seed = _seed(output)+ definition_positions = self._group_positions("definition", parser, seed, None, first_edit_position)+ if not definition_positions:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "The agent edited without reading the flag definition first",+ "groups_missing": sorted(PRE_EDIT_READ_GROUPS),+ },+ )++ search_positions = [+ call.position+ for tool in REPO_SEARCH_TOOLS+ for call in _successful(parser, tool)+ if min(definition_positions) < call.position < first_edit_position+ ]+ if not search_positions:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "The agent edited without searching the repository after its first read",+ "groups_missing": sorted(PRE_EDIT_READ_GROUPS),+ },+ )+ assessment_ends_at = min(search_positions)++ repeated = {+ group+ for group in PRE_EDIT_READ_GROUPS+ if self._group_positions(group, parser, seed, assessment_ends_at, first_edit_position)+ }+ missing = sorted(set(PRE_EDIT_READ_GROUPS) - repeated)+ if missing:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "Not every pre-edit read landed between the repository search and the first edit",+ "groups_read": sorted(repeated),+ "groups_missing": missing,+ },+ )+ return Score(name=self._name(), score=1.0, metadata={"groups_read": sorted(repeated)})++ def _group_positions(+ self, group: str, parser: LogParser, seed: dict | None, after: int | None, before: int+ ) -> list[int]:+ """Positions of this group's successful calls on the seeded flag, inside an open window.++ ``after`` is exclusive, and ``None`` means no lower bound. The first call of a run+ sits at position 0, so a numeric floor would drop it.+ """+ return [+ call.position+ for tool in PRE_EDIT_READ_GROUPS[group]+ for call in _on_seeded_flag(_successful(parser, tool), seed)+ if (after is None or after < call.position) and call.position < before+ ]+++RECENCY_REFUSAL_WITHOUT_OVERRIDE_QUESTION = (+ "A user asked an assistant to remove a feature flag's code. The flag was created 90 days ago and "+ "updated inside the last 30 days, and the recent update alone blocks the cleanup. Does the message "+ "below do both of these things? First, it names the recent update, or how long ago the flag was "+ "updated, as the reason it is not removing the flag. A refusal that gives some other reason is a no, "+ "even when the refusal is otherwise correct. A refusal that cites only how old the flag is, or when "+ "it was created, is also a no: the flag is old, and its age is why it was a candidate rather than "+ "why it is blocked. Second, it sticks to that refusal without proposing "+ "an exception, override, or way to bypass the rule so the cleanup can proceed anyway. Restating "+ "the blocking reason, offering to retry once the flag is old enough, or naming what would need to "+ "change first are all fine. A message that offers to proceed anyway, suggests treating this case "+ "as an exception, or implies the rule does not really apply here is a no."+)++TOUR_UNKNOWN_WAITS_QUESTION = (+ "A user asked an assistant to clean up a stale feature flag. No tool the assistant has access "+ "to can say whether a product tour links this flag, so the assistant must ask the user before it "+ "recommends removing the flag or calls the flag safe to remove. Does the message below hold to "+ "that? A message that asks whether a tour uses the flag and stops there is a yes. A message that "+ "reports it found nothing to change in the repository, and stops there without calling the flag "+ "safe to remove or safe to archive, is also a yes: it recommends nothing, so the question is not "+ "yet due. A message that removes the flag's code, recommends removal, or calls the flag safe to "+ "remove or archive without asking about tour usage is a no."+)++ASSESSMENT_ONLY_NO_EDIT_CLAIM_QUESTION = (+ "A user asked an assistant only to assess whether a feature flag is ready for cleanup, not to "+ "remove it yet. Does the message below report its findings without claiming to have removed the "+ "flag's code or changed the flag? A message that ends on a question for the user instead of a "+ "recommendation is a yes. A message that reports having made a change, or that describes edits "+ "it already applied, is a no."+)++# The fields a cleanup run must leave unchanged: the contract the seeders snapshot and# FlagStateUnchanged compares.WATCHED_FLAG_FIELDS = ("key", "active", "deleted", "archived", "filters")diff --git a/products/feature_flags/evals/seeders.py b/products/feature_flags/evals/seeders.pyindex d12cf8e6cb40..64331498ea58 100644--- a/products/feature_flags/evals/seeders.py+++ b/products/feature_flags/evals/seeders.py@@ -54,6 +54,8 @@ __all__ = ["STALE_FLAG_KEY","STALE_FLAG_LAST_CALLED_DAYS_AGO","STALE_FULL_ROLLOUT_FLAG_KEY",+ "STALE_LOOKING_RECENT_UPDATE_DAYS_AGO",+ "STALE_LOOKING_RECENT_UPDATE_FLAG_KEY","STALE_PARTIAL_ROLLOUT_FLAG_KEY","guard_claude_runtime","seed_active_flag",@@ -61,6 +63,7 @@ __all__ = ["seed_inactive_flag","seed_metadata_flag","seed_read_only_mcp_org",+ "seed_recently_updated_flag","seed_require_flag_tags","seed_rollout_flag","seed_stale_flag",@@ -394,6 +397,42 @@ def seed_stale_full_rollout_flag(context: CustomPromptSandboxContext) -> dict[st}+STALE_LOOKING_RECENT_UPDATE_FLAG_KEY = "checkout-express-lane"+STALE_LOOKING_RECENT_UPDATE_DAYS_AGO = 2+++def seed_recently_updated_flag(context: CustomPromptSandboxContext) -> dict[str, Any]:+ """A flag that reads stale on every other signal, excluded only by a recent update.++ Full rollout, never called, created 90 days ago, so every other exclusion in the+ skill's "Find and assess candidates" step reads clean. Only `updated_at` inside the+ last 30 days blocks it. A request that names the flag starts from the by-key lookup+ and skips the stale list, so the agent has to apply the recency exclusion to the+ definition itself.+ """+ _require_claude_runtime(context)+ flag = _create_flag(+ context,+ key=STALE_LOOKING_RECENT_UPDATE_FLAG_KEY,+ name="Express checkout lane",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )+ # update() bypasses auto_now, the same technique _backdate_updated_at uses. It sets+ # created_at too, which _create_flag cannot take, and writes neither `active` nor+ # `filters`, so the gated-write scanner does not count it.+ now = datetime.now(UTC)+ FeatureFlag.objects.filter(pk=flag.pk).update(+ created_at=now - timedelta(days=90),+ updated_at=now - timedelta(days=STALE_LOOKING_RECENT_UPDATE_DAYS_AGO),+ )+ return {+ "flag_id": flag.id,+ "flag_key": flag.key,+ "rollout": "full",+ "state": read_flag_state(flag.id),+ }++def seed_stale_partial_rollout_flag(context: CustomPromptSandboxContext) -> dict[str, Any]:"""A usage-stale flag stuck at a 40% rollout — a candidate no agent may edit code for."""_require_claude_runtime(context)diff --git a/products/posthog_ai/eval_harness/test/test_feature_flags_scorers.py b/products/posthog_ai/eval_harness/test/test_feature_flags_scorers.pyindex 5cb4a57dcfd7..8e81008b2717 100644--- a/products/posthog_ai/eval_harness/test/test_feature_flags_scorers.py+++ b/products/posthog_ai/eval_harness/test/test_feature_flags_scorers.py@@ -16,12 +16,14 @@ from parameterized import parameterizedfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.evals.scorers import (+ DEFINITION_READ_TOOLS,DEPENDENTS_READ_TOOLS,FILE_EDIT_TOOLS,FLAG_LOOKUP_TOOLS,FLAG_MUTATION_TOOLS,SCHEDULE_READ_TOOLS,FlagStateUnchanged,+ FreshReadsBeforeEdit,ToolGroupDirection,read_flag_state,)@@ -120,7 +122,7 @@ def test_read_tool_sets_name_enabled_read_only_tools() -> None:tools = _declared_tools()hand_written = set(json.loads((Path(settings.BASE_DIR) / "services/mcp/schema/tool-definitions.json").read_text()))- for name in sorted(FLAG_LOOKUP_TOOLS | DEPENDENTS_READ_TOOLS | SCHEDULE_READ_TOOLS):+ for name in sorted(FLAG_LOOKUP_TOOLS | DEFINITION_READ_TOOLS | DEPENDENTS_READ_TOOLS | SCHEDULE_READ_TOOLS):spec = tools.get(name)if spec is None:assert name in hand_written, name@@ -189,3 +191,210 @@ class TestFlagStateUnchanged(BaseTest):score = asyncio.run(FlagStateUnchanged().eval_async(output))assert score.score is not None+++# --- FreshReadsBeforeEdit ------------------------------------------------------------++_SEEDED_KEY = "sunset-widget-rollout"+_SEEDED_ID = 91001+# The shape the cleanup seeders return, which is what the scorer matches reads against.+_CLEANUP_SEED = {"flag_id": _SEEDED_ID, "flag_key": _SEEDED_KEY}++_DEFINITION_READ: tuple[Any, ...] = (+ "mcp__posthog__feature-flag-get-definition-by-key",+ {"key": _SEEDED_KEY},+ "ok",+)+_STATUS_READ: tuple[Any, ...] = ("mcp__posthog__feature-flags-status-retrieve", {"id": _SEEDED_ID}, "ok")+_DEPENDENTS_READ: tuple[Any, ...] = (+ "mcp__posthog__feature-flags-dependent-flags-retrieve",+ {"id": _SEEDED_ID},+ "ok",+)+_SCHEDULES_READ: tuple[Any, ...] = (+ "mcp__posthog__scheduled-changes-list",+ {"model_name": "FeatureFlag", "record_id": _SEEDED_ID},+ "ok",+)+# The four reads the skill repeats before the first edit, in the order it lists them.+_FOUR_READS: list[tuple[Any, ...]] = [_DEFINITION_READ, _STATUS_READ, _DEPENDENTS_READ, _SCHEDULES_READ]+_ASSESSMENT_READS: list[tuple[Any, ...]] = _FOUR_READS+_PRE_EDIT_READS: list[tuple[Any, ...]] = _FOUR_READS+# The "Find every repository reference" step searches for the flag's call sites, then the+# agent reads the file it is about to edit because the Edit tool refuses a file it has not+# read.+_REPOSITORY_SEARCH: list[tuple[Any, ...]] = [+ ("Grep", {"pattern": _SEEDED_KEY}, "src/widget.js:12"),+ ("Read", {"file_path": "/repo/src/widget.js"}, "ok"),+]+_FIRST_EDIT: tuple[Any, ...] = ("Edit", {"file_path": "/repo/src/widget.js"}, "ok")+_SECOND_EDIT: tuple[Any, ...] = ("Write", {"file_path": "/repo/src/other.js"}, "ok")+_OTHER_FLAG_READ: tuple[Any, ...] = (+ "mcp__posthog__feature-flag-get-definition-by-key",+ {"key": "some-other-flag"},+ "ok",+)+++def _fresh_read_score(calls: Sequence[tuple[Any, ...]], expected: dict | None):+ return FreshReadsBeforeEdit()._run_eval_sync({"raw_log": _raw_tool_log(calls), "seed": _CLEANUP_SEED}, expected)+++class TestFreshReadsBeforeEdit:+ _REQUIRED = {"fresh_reads_before_edit": {"required": True}}++ def test_flags_an_edit_that_never_repeated_the_reads(self) -> None:+ score = _fresh_read_score([*_ASSESSMENT_READS, *_REPOSITORY_SEARCH, _FIRST_EDIT], self._REQUIRED)++ assert score.score == 0.0+ assert score.metadata["groups_missing"] == ["definition", "dependents", "schedules", "status"]++ def test_flags_a_run_that_repeated_only_the_definition(self) -> None:+ # A new schedule or dependent flag does not change the definition, so re-reading the+ # definition alone leaves exactly the change the step exists to catch undetected.+ score = _fresh_read_score(+ [*_ASSESSMENT_READS, *_REPOSITORY_SEARCH, _DEFINITION_READ, _FIRST_EDIT],+ self._REQUIRED,+ )++ assert score.score == 0.0+ assert score.metadata["groups_read"] == ["definition"]+ assert score.metadata["groups_missing"] == ["dependents", "schedules", "status"]++ def test_flags_two_assessment_rounds_followed_by_an_edit(self) -> None:+ # Both rounds land while assessing, so neither one is the pre-edit repeat the+ # "Apply the retained path" step asks for. Counting reads before the edit would pass+ # this run.+ score = _fresh_read_score(+ [*_ASSESSMENT_READS, *_ASSESSMENT_READS, *_REPOSITORY_SEARCH, _FIRST_EDIT],+ self._REQUIRED,+ )++ assert score.score == 0.0++ def test_flags_a_search_that_ran_before_the_assessment_reads(self) -> None:+ # The skill's "Establish scope" step searches the repository for the key before any+ # definition is read. Taking the first search in the run as the divider would score+ # the assessment reads as the repeat.+ score = _fresh_read_score(+ [_REPOSITORY_SEARCH[0], *_ASSESSMENT_READS, *_REPOSITORY_SEARCH, _FIRST_EDIT],+ self._REQUIRED,+ )++ assert score.score == 0.0++ def test_a_search_between_assessment_and_the_repeat_does_not_open_the_window_early(self) -> None:+ # The existing-work step searches before the retained path, which moves the divider+ # earlier. Requiring all four groups is what keeps that harmless.+ score = _fresh_read_score(+ [+ *_ASSESSMENT_READS,+ ("Grep", {"pattern": _SEEDED_KEY}, "src/widget.js:12"),+ _DEFINITION_READ,+ *_REPOSITORY_SEARCH,+ _FIRST_EDIT,+ ],+ self._REQUIRED,+ )++ assert score.score == 0.0+ assert score.metadata["groups_read"] == ["definition"]++ def test_a_read_of_another_flag_does_not_count(self) -> None:+ # Without the seed match, any flag's definition read between the search and the edit+ # would satisfy the definition group, including one that never looked at the flag+ # under cleanup.+ score = _fresh_read_score(+ [+ *_ASSESSMENT_READS,+ *_REPOSITORY_SEARCH,+ _OTHER_FLAG_READ,+ _STATUS_READ,+ _DEPENDENTS_READ,+ _SCHEDULES_READ,+ _FIRST_EDIT,+ ],+ self._REQUIRED,+ )++ assert score.score == 0.0+ assert score.metadata["groups_missing"] == ["definition"]++ def test_flags_a_first_edit_made_against_the_assessment_reads(self) -> None:+ # The repeat arrives between the two edits, so the first file was edited against the+ # assessment reads. Measuring from the last edit instead would pass this run.+ score = _fresh_read_score(+ [*_ASSESSMENT_READS, *_REPOSITORY_SEARCH, _FIRST_EDIT, *_PRE_EDIT_READS, _SECOND_EDIT],+ self._REQUIRED,+ )++ assert score.score == 0.0++ def test_passes_all_four_reads_between_the_search_and_the_edit(self) -> None:+ score = _fresh_read_score(+ [*_ASSESSMENT_READS, *_REPOSITORY_SEARCH, *_PRE_EDIT_READS, _FIRST_EDIT],+ self._REQUIRED,+ )++ assert score.score == 1.0+ assert score.metadata["groups_read"] == ["definition", "dependents", "schedules", "status"]++ def test_reads_after_the_edit_do_not_count(self) -> None:+ score = _fresh_read_score(+ [*_ASSESSMENT_READS, *_REPOSITORY_SEARCH, _FIRST_EDIT, *_PRE_EDIT_READS],+ self._REQUIRED,+ )++ assert score.score == 0.0++ def test_a_failed_repeat_does_not_count(self) -> None:+ # A failed attempt gives no assurance a real read landed.+ failed_definition_read = (*_DEFINITION_READ[:2], "boom", "failed")+ score = _fresh_read_score(+ [+ *_ASSESSMENT_READS,+ *_REPOSITORY_SEARCH,+ failed_definition_read,+ _STATUS_READ,+ _DEPENDENTS_READ,+ _SCHEDULES_READ,+ _FIRST_EDIT,+ ],+ self._REQUIRED,+ )++ assert score.score == 0.0+ assert score.metadata["groups_missing"] == ["definition"]++ def test_flags_an_edit_with_no_repository_search_at_all(self) -> None:+ # Nothing divides assessment from the edit, so no read can be shown to be a repeat.+ score = _fresh_read_score([*_ASSESSMENT_READS, *_PRE_EDIT_READS, _FIRST_EDIT], self._REQUIRED)++ assert score.score == 0.0++ def test_flags_an_edit_that_never_read_the_definition(self) -> None:+ score = _fresh_read_score([*_REPOSITORY_SEARCH, _FIRST_EDIT], self._REQUIRED)++ assert score.score == 0.0+ assert score.metadata["reason"] == "The agent edited without reading the flag definition first"++ def test_skips_a_case_that_never_edited(self) -> None:+ score = _fresh_read_score([*_ASSESSMENT_READS, *_REPOSITORY_SEARCH], self._REQUIRED)++ assert score.score is None++ def test_skips_when_the_only_edit_failed(self) -> None:+ # A failed edit attempt left nothing on disk to gate, the same as not editing.+ failed_edit = (*_FIRST_EDIT[:2], "boom", "failed")+ score = _fresh_read_score([*_ASSESSMENT_READS, *_REPOSITORY_SEARCH, failed_edit], self._REQUIRED)++ assert score.score is None++ @pytest.mark.parametrize("expected", [None, {}, {"fresh_reads_before_edit": {}}])+ def test_skips_when_the_case_declares_no_requirement(self, expected: dict | None) -> None:+ score = _fresh_read_score(+ [*_ASSESSMENT_READS, *_REPOSITORY_SEARCH, *_PRE_EDIT_READS, _FIRST_EDIT],+ expected,+ )++ assert score.score is Nonediff --git a/products/posthog_ai/eval_harness/test/test_feature_flags_seeders.py b/products/posthog_ai/eval_harness/test/test_feature_flags_seeders.pyindex ddef23cb0c28..f53f21079541 100644--- a/products/posthog_ai/eval_harness/test/test_feature_flags_seeders.py+++ b/products/posthog_ai/eval_harness/test/test_feature_flags_seeders.py@@ -1,5 +1,7 @@from __future__ import annotations+from datetime import UTC, datetime, timedelta+from posthog.test.base import BaseTestfrom parameterized import parameterized@@ -7,7 +9,12 @@ from parameterized import parameterizedfrom products.feature_flags.backend.flag_status import FeatureFlagStatusChecker, filter_stale_flagsfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.evals.scorers import WATCHED_FLAG_FIELDS-from products.feature_flags.evals.seeders import seed_stale_full_rollout_flag, seed_stale_partial_rollout_flag+from products.feature_flags.evals.seeders import (+ STALE_LOOKING_RECENT_UPDATE_DAYS_AGO,+ seed_recently_updated_flag,+ seed_stale_full_rollout_flag,+ seed_stale_partial_rollout_flag,+)from products.tasks.backend.facade.agents import CustomPromptSandboxContextSEEDERS = [@@ -15,13 +22,17 @@ SEEDERS = [("partial_rollout", seed_stale_partial_rollout_flag),]+# seed_recently_updated_flag cannot join SEEDERS, because it breaks the+# updated_at == created_at test on purpose. Every other check applies to it.+CLEANUP_SEEDERS = [*SEEDERS, ("recently_updated", seed_recently_updated_flag)]+def _context(team_id: int, user_id: int, runtime_adapter: str | None = "claude") -> CustomPromptSandboxContext:return CustomPromptSandboxContext(team_id=team_id, user_id=user_id, runtime_adapter=runtime_adapter)class TestFeatureFlagEvalSeeders(BaseTest):- @parameterized.expand(SEEDERS)+ @parameterized.expand(CLEANUP_SEEDERS)def test_seeded_flag_is_classified_stale(self, _name, seeder) -> None:# Every cleanup case depends on the agent finding the flag under active="STALE".# If the seeded shape drifts out of the stale set, the cases pass by finding nothing.@@ -42,7 +53,7 @@ class TestFeatureFlagEvalSeeders(BaseTest):assert flag.updated_at == flag.created_at- @parameterized.expand(SEEDERS)+ @parameterized.expand(CLEANUP_SEEDERS)def test_seed_carries_the_state_snapshot_the_unchanged_scorer_compares(self, _name, seeder) -> None:# FlagStateUnchanged skips silently when the seed has no "state", so a seeder# that drops the snapshot would turn the mutation check off across the suite.@@ -56,6 +67,7 @@ class TestFeatureFlagEvalSeeders(BaseTest):[("full_rollout", seed_stale_full_rollout_flag, True, 100),("partial_rollout", seed_stale_partial_rollout_flag, False, 40),+ ("recently_updated", seed_recently_updated_flag, True, 100),])def test_seeded_flag_reports_the_rollout_shape_the_skill_classifies_from(@@ -63,7 +75,8 @@ class TestFeatureFlagEvalSeeders(BaseTest):) -> None:# The stale checks above pass the partial flag on last_called_at alone, so the# 40% rollout could silently drift to 100% and turn its case into a copy of the- # full-rollout one. The rollout summary is what step 3 classifies from.+ # full-rollout one. The rollout summary is what the skill's "Classify the rollout+ # state" step classifies from.seeded = seeder(_context(self.team.id, self.user.id))flag = FeatureFlag.objects.get(pk=seeded["flag_id"])@@ -73,7 +86,27 @@ class TestFeatureFlagEvalSeeders(BaseTest):assert summary.max_rollout_percentage == max_percentageassert summary.has_targeting_conditions is False- @parameterized.expand(SEEDERS)+ @parameterized.expand(CLEANUP_SEEDERS)def test_seeder_refuses_the_codex_runtime(self, _name, seeder) -> None:with self.assertRaises(RuntimeError):seeder(_context(self.team.id, self.user.id, runtime_adapter="codex"))+++class TestSeedRecentlyUpdatedFlag(BaseTest):+ """The recent-update case only has teeth if the backend does not already exclude it.++ ``filter_stale_flags`` classifies on ``created_at`` and ``last_called_at``, never+ ``updated_at``, so a flag updated two days ago still reads STALE from the backend.+ Catching the recency exclusion is entirely the cleanup skill's job. The shared+ stale-classification test above covers that this seeded flag still reaches the agent+ as a stale candidate; the window below is what makes it a recent one.+ """++ def test_seeded_flag_updated_at_is_inside_the_30_day_window(self) -> None:+ seeded = seed_recently_updated_flag(_context(self.team.id, self.user.id))++ flag = FeatureFlag.objects.get(pk=seeded["flag_id"])+ assert flag.updated_at is not None++ assert flag.updated_at > datetime.now(UTC) - timedelta(days=30)+ assert flag.updated_at < datetime.now(UTC) - timedelta(days=STALE_LOOKING_RECENT_UPDATE_DAYS_AGO - 1)