:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): resume operational scouts on wildcard-enrolled teams (#106933)
posthog[bot]18b5b33f97c7
diff --git a/products/signals/backend/management/AGENTS.md b/products/signals/backend/management/AGENTS.mdindex 11db84720ebf..334fe629347b 100644--- a/products/signals/backend/management/AGENTS.md+++ b/products/signals/backend/management/AGENTS.md@@ -199,6 +199,23 @@ uv run manage.py backfill_report_actionability --team-id 1 --batch-size 100 --afIdempotent. It recomputes each report from its artefacts and writes only the rows that disagree.+## Resuming operational scouts the setup flow paused++An older self-driving setup flow switched off every scout the user did not pick, including operational scouts such as inbox validation.+Those rows look like a person's pause, so the coordinator's reconcile leaves them alone.+`resume_setup_paused_operational_scouts` resumes only operational rows paused without an attributed user within `--max-gap-seconds` (default 300) of creation.+It skips withheld scouts and does not go past the enabled-scout cap.++```bash+# Dry run (the default): counts per scout and the first team ids+uv run manage.py resume_setup_paused_operational_scouts++# Write, optionally for one team+uv run manage.py resume_setup_paused_operational_scouts --apply --team-id 1+```++Idempotent. A resumed row no longer matches.+## Tips- Compare runs by saving output: `list_signal_reports --json > run_baseline.json`diff --git a/products/signals/backend/management/commands/resume_setup_paused_operational_scouts.py b/products/signals/backend/management/commands/resume_setup_paused_operational_scouts.pynew file mode 100644index 000000000000..59fd4696dbaa--- /dev/null+++ b/products/signals/backend/management/commands/resume_setup_paused_operational_scouts.py@@ -0,0 +1,46 @@+from argparse import ArgumentParser+from datetime import timedelta+from typing import cast++from django.core.management.base import BaseCommand++from products.signals.backend.scout_harness.config_registry import resume_setup_paused_operational_scouts+++class Command(BaseCommand):+ help = (+ "Resume operational scouts (such as inbox validation) that the old self-driving setup flow "+ "switched off seconds after the seed. A pause a person made is left alone. Dry run unless "+ "--apply is passed. Safe to rerun: a resumed row no longer matches."+ )++ def add_arguments(self, parser: ArgumentParser) -> None:+ mode = parser.add_mutually_exclusive_group()+ mode.add_argument("--dry-run", action="store_true", help="Print what would change. The default.")+ mode.add_argument("--apply", action="store_true", help="Resume the selected scouts.")+ parser.add_argument("--team-id", type=int, help="Limit the run to one project.")+ parser.add_argument("--batch-size", type=int, default=500)+ parser.add_argument(+ "--max-gap-seconds",+ type=int,+ default=300,+ help="Longest time between the seed and the pause for the pause to count as the setup flow's.",+ )+ parser.add_argument("--show-team-ids", type=int, default=20, help="How many team ids to print.")++ def handle(self, *args: object, **options: object) -> None:+ apply = bool(options["apply"])+ summary = resume_setup_paused_operational_scouts(+ apply=apply,+ team_id=cast(int | None, options["team_id"]),+ batch_size=max(1, min(cast(int, options["batch_size"]), 5000)),+ max_gap=timedelta(seconds=max(0, cast(int, options["max_gap_seconds"]))),+ )+ self.stdout.write("Mode: apply" if apply else "Mode: dry run (pass --apply to write)")+ for skill_name, count in sorted(summary.selected.items()):+ line = f"{skill_name}: selected {count}, withheld {summary.skipped_withheld[skill_name]}"+ if apply:+ line += f", resumed {summary.resumed[skill_name]}, not resumed {summary.not_resumed[skill_name]}"+ self.stdout.write(line)+ shown = summary.team_ids[: cast(int, options["show_team_ids"])]+ self.stdout.write(f"Teams: {len(summary.team_ids)}. First team ids: {shown}")diff --git a/products/signals/backend/report_check_agent.py b/products/signals/backend/report_check_agent.pyindex d7501b6857be..5c1c51d0ae28 100644--- a/products/signals/backend/report_check_agent.py+++ b/products/signals/backend/report_check_agent.py@@ -338,7 +338,11 @@ def run_agent_check(check: SignalReportCheck, *, now: datetime | None = None) ->)return "deferred"record_check_verdict(- check, CheckVerdict(outcome="errored", explanation=f"{check.title}: {refusal.detail}"), now=now+ check,+ CheckVerdict(outcome="errored", explanation=f"{check.title}: {refusal.detail}"),+ now=now,+ skill_name=skill_name,+ refusal_reason=refusal.reason,)return "errored"diff --git a/products/signals/backend/report_check_execution.py b/products/signals/backend/report_check_execution.pyindex dfcfec47cc05..f27d2065e2cb 100644--- a/products/signals/backend/report_check_execution.py+++ b/products/signals/backend/report_check_execution.py@@ -267,6 +267,8 @@ def record_check_verdict(now: datetime | None = None,attribution: ArtefactAttribution | None = None,run_id: str | None = None,+ skill_name: str | None = None,+ refusal_reason: str | None = None,) -> None:"""The single persistence funnel: append the result artefact and advance or retire the check.@@ -274,7 +276,8 @@ def record_check_verdict(records nothing.`attribution` and `run_id` name the scout run that decided an `agent` check. A deterministic run- has neither, so it keeps the `system()` attribution the executor writes under.+ has neither, so it keeps the `system()` attribution the executor writes under. `skill_name` and+ `refusal_reason` name the scout and the gate when the fleet refused to run an `agent` check."""now = now or timezone.now()# The result's context is best-effort. A stored config can stop parsing part-way through a soak,@@ -345,7 +348,16 @@ def record_check_verdict(# the caller's row, where both call paths already select it with its organization; the# locked row selects neither, and widening the lock to reach them would take `FOR UPDATE`# on `Team`.- transaction.on_commit(partial(capture_report_check_evaluated, check.team, current, run_id=run_id))+ transaction.on_commit(+ partial(+ capture_report_check_evaluated,+ check.team,+ current,+ run_id=run_id,+ skill_name=skill_name,+ reason=refusal_reason,+ )+ )def _should_resurface(check: SignalReportCheck, verdict: CheckVerdict) -> bool:diff --git a/products/signals/backend/report_check_telemetry.py b/products/signals/backend/report_check_telemetry.pyindex 15935168182a..1cbbb5bf80f8 100644--- a/products/signals/backend/report_check_telemetry.py+++ b/products/signals/backend/report_check_telemetry.py@@ -86,7 +86,14 @@ def capture_report_check_created(team: Team, check: SignalReportCheck) -> None:logger.exception("signals.report_check.created_capture_failed", check_id=str(check.id), team_id=check.team_id)-def capture_report_check_evaluated(team: Team, check: SignalReportCheck, *, run_id: str | None = None) -> None:+def capture_report_check_evaluated(+ team: Team,+ check: SignalReportCheck,+ *,+ run_id: str | None = None,+ skill_name: str | None = None,+ reason: str | None = None,+) -> None:"""`signals_report_check_evaluated`: a run recorded a verdict on a check.Emitted per verdict rather than per check, so a recurring check that keeps holding reports one@@ -95,7 +102,9 @@ def capture_report_check_evaluated(team: Team, check: SignalReportCheck, *, run_(`active`).`run_id` names the scout run that decided an `agent` check. The deterministic lane has none,- which is what tells the two lanes apart in the data. Requires `team.organization` to be loaded.+ which is what tells the two lanes apart in the data. `reason` and `skill_name` are set when the+ fleet refused to run an `agent` check, so an errored verdict can be traced to the gate that+ refused it. Requires `team.organization` to be loaded."""try:posthoganalytics.capture(@@ -109,6 +118,8 @@ def capture_report_check_evaluated(team: Team, check: SignalReportCheck, *, run_"consecutive_errors": check.consecutive_errors,"hours_since_created": (timezone.now() - check.created_at).total_seconds() / 3600,"run_id": run_id,+ "skill_name": skill_name,+ "reason": reason,},groups=groups(team.organization, team),)diff --git a/products/signals/backend/scout_harness/config_registry.py b/products/signals/backend/scout_harness/config_registry.pyindex cd82dc85fb20..24cd92f66a52 100644--- a/products/signals/backend/scout_harness/config_registry.py+++ b/products/signals/backend/scout_harness/config_registry.py@@ -13,11 +13,13 @@ goes through the write-scoped config `create` endpoint.from __future__ import annotations+from collections import Counterfrom collections.abc import Mapping-from datetime import UTC, datetime+from dataclasses import dataclass, field+from datetime import UTC, datetime, timedeltafrom django.db import transaction-from django.db.models import Q+from django.db.models import Exists, F, OuterRef, Q, QuerySetfrom django.utils import timezoneimport structlog@@ -33,12 +35,20 @@ from products.signals.backend.scout_harness.lazy_seed import (canonical_config_tags_for,canonical_deprecation_for,canonical_display_name_for,+ canonical_operational_scout_names,canonical_skill_names,canonical_structured_output_schema_for,is_operational_scout,)from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX-from products.signals.backend.scout_harness.team_limits import resolve_max_enabled_scouts+from products.signals.backend.scout_harness.team_limits import (+ _canonicalize_team_config_keys,+ _default_team_config,+ _read_flag_payload,+ _resolve_withheld_skills,+ _team_configs,+ resolve_max_enabled_scouts,+)from products.skills.backend.models.skills import LLMSkilllogger = structlog.get_logger(__name__)@@ -60,6 +70,7 @@ CRON_SCHEDULE_MAX_LENGTH = 100_CRON_SAMPLE_OCCURRENCES = 100_OPERATIONAL_RECONCILE_JOB_TYPE = "signals_scout_operational_reconcile"+_SETUP_PAUSE_RESUME_JOB_TYPE = "signals_scout_setup_pause_resume"def cron_schedule_error(value: str) -> str | None:@@ -404,6 +415,60 @@ def _backfill_unset_column()+def _harness_seeded_skill_exists() -> Exists:+ """Whether the config's skill is the live, harness-seeded canonical row, not a team's own copy."""+ return Exists(+ LLMSkill.objects.filter(+ team_id=OuterRef("team_id"),+ name=OuterRef("skill_name"),+ is_latest=True,+ deleted=False,+ metadata__seeded_by=HARNESS_SEEDED_BY,+ )+ )+++def operational_configs_needing_reconcile() -> dict[int, set[str]]:+ """Operational scout names per team whose config `reconcile_operational_configs` would change.++ One fleet-wide query, so the coordinator can reconcile only the wildcard teams that need it+ instead of paying for a per-team reconcile on every tick. A row matches when it misses the+ sweep exemption, carries an inactivity pause, or still sits disabled as the seed created it.+ A human pause and a breaker pause match only while the exemption is missing, and the+ reconcile stamps it on the first pass, so they stop matching after one tick.+ """+ operational = canonical_operational_scout_names()+ if not operational:+ return {}+ rows = (+ SignalScoutConfig.all_teams.filter(skill_name__in=operational)+ .filter(+ Q(auto_pause_exempt=False)+ | Q(pause_reason__in=SignalScoutConfig.INACTIVITY_PAUSE_REASONS)+ | Q(status=SignalScoutConfig.Status.PAUSED_BY_USER, status_changed_at__isnull=True)+ )+ .filter(_harness_seeded_skill_exists())+ .values_list("team_id", "skill_name")+ )+ needing: dict[int, set[str]] = {}+ for team_id, skill_name in rows:+ needing.setdefault(team_id, set()).add(skill_name)+ return needing+++def canonical_operational_skill_names(team_id: int) -> set[str]:+ """The team's live, harness-seeded skills that declare the operational role."""+ return set(+ LLMSkill.objects.filter(+ team_id=team_id,+ name__in=canonical_operational_scout_names(),+ is_latest=True,+ deleted=False,+ metadata__seeded_by=HARNESS_SEEDED_BY,+ ).values_list("name", flat=True)+ )++@transaction.atomicdef reconcile_operational_configs(team_id: int,@@ -490,3 +555,128 @@ def _resume_operational_config(config: SignalScoutConfig, *, max_enabled_scouts:team_id=config.team_id,skill_name=config.skill_name,)+++def setup_paused_operational_configs(*, max_gap: timedelta, team_id: int | None = None) -> QuerySet[SignalScoutConfig]:+ """Operational scout configs that a setup flow switched off right after the seed.++ The setup flow wrote `enabled: false` through the config API without a user attribution,+ seconds after the seed created the row. That leaves a `paused_by_user` row with no+ `status_changed_by` and a `status_changed_at` close to `created_at`. A person's pause carries+ an attribution, or lands long after the seed, so it does not match.+ """+ configs = (+ SignalScoutConfig.all_teams.filter(+ skill_name__in=canonical_operational_scout_names(),+ status=SignalScoutConfig.Status.PAUSED_BY_USER,+ status_changed_by__isnull=True,+ status_changed_at__isnull=False,+ status_changed_at__lte=F("created_at") + max_gap,+ )+ .filter(_harness_seeded_skill_exists())+ .order_by("team_id", "skill_name")+ )+ if team_id is not None:+ configs = configs.filter(team_id=team_id)+ return configs+++def resume_setup_paused_operational_config(config: SignalScoutConfig, *, max_enabled_scouts: int) -> bool:+ """Put one setup-paused operational scout back to `active`, exempt from the inactivity sweep.++ Returns False without a write when the row moved since the caller read it, or when the team+ is at its enabled-scout cap. The row lock covers the whole team, as in+ `transition_status_by_system`, because the cap check counts sibling rows.+ """+ with transaction.atomic():+ team_rows = {+ row.pk: row for row in SignalScoutConfig.objects.for_team(config.team_id).select_for_update().order_by("pk")+ }+ locked = team_rows.get(config.pk)+ if (+ locked is None+ or locked.status != SignalScoutConfig.Status.PAUSED_BY_USER+ or locked.status_changed_by_id is not None+ or locked.status_changed_at != config.status_changed_at+ ):+ return False+ peers = sum(1 for row in team_rows.values() if row.enabled and row.pk != locked.pk)+ if peers >= max_enabled_scouts:+ return False+ trigger = Trigger(+ job_type=_SETUP_PAUSE_RESUME_JOB_TYPE,+ job_id=str(locked.id),+ payload={"skill_name": locked.skill_name},+ )+ with ActivityTriggerContext(trigger):+ locked.status = SignalScoutConfig.Status.ACTIVE+ locked.enabled = True+ locked.pause_reason = None+ locked.status_changed_at = timezone.now()+ locked.auto_pause_exempt = True+ locked.auto_pause_exempt_by_role = True+ locked.save(+ update_fields=[+ "status",+ "enabled",+ "pause_reason",+ "status_changed_at",+ "auto_pause_exempt",+ "auto_pause_exempt_by_role",+ "updated_at",+ ]+ )+ logger.info(+ "signals_scout: setup-paused operational scout resumed",+ team_id=locked.team_id,+ skill_name=locked.skill_name,+ )+ return True+++@dataclass(frozen=False)+class ResumeSummary:+ selected: Counter[str] = field(default_factory=Counter)+ resumed: Counter[str] = field(default_factory=Counter)+ skipped_withheld: Counter[str] = field(default_factory=Counter)+ not_resumed: Counter[str] = field(default_factory=Counter)+ team_ids: list[int] = field(default_factory=list)+++def resume_setup_paused_operational_scouts(+ *, apply: bool, team_id: int | None, batch_size: int, max_gap: timedelta+) -> ResumeSummary:+ # One flag read for the whole run, so every team resolves its holdback and cap from one payload.+ payload = _read_flag_payload()+ team_configs = _canonicalize_team_config_keys(_team_configs(payload))+ default_team_config = _default_team_config(payload)++ summary = ResumeSummary()+ seen_team_ids: set[int] = set()+ # A pk cursor rather than re-reading the first page: a row this run skips still matches.+ after_pk = None+ while True:+ configs = setup_paused_operational_configs(max_gap=max_gap, team_id=team_id).order_by("pk")+ if after_pk is not None:+ configs = configs.filter(pk__gt=after_pk)+ batch = list(configs[:batch_size])+ if not batch:+ return summary+ for config in batch:+ summary.selected[config.skill_name] += 1+ if config.team_id not in seen_team_ids:+ seen_team_ids.add(config.team_id)+ summary.team_ids.append(config.team_id)+ if config.skill_name in _resolve_withheld_skills(config.team_id, team_configs, default_team_config):+ summary.skipped_withheld[config.skill_name] += 1+ continue+ if not apply:+ continue+ max_enabled_scouts = resolve_max_enabled_scouts(+ [team_configs.get(config.team_id) or {}, default_team_config]+ )+ if resume_setup_paused_operational_config(config, max_enabled_scouts=max_enabled_scouts):+ summary.resumed[config.skill_name] += 1+ else:+ summary.not_resumed[config.skill_name] += 1+ after_pk = batch[-1].pkdiff --git a/products/signals/backend/scout_harness/lazy_seed.py b/products/signals/backend/scout_harness/lazy_seed.pyindex 1093ebff16cc..077b6db9cba2 100644--- a/products/signals/backend/scout_harness/lazy_seed.py+++ b/products/signals/backend/scout_harness/lazy_seed.py@@ -660,6 +660,11 @@ def _canonical_operational_scouts() -> frozenset[str]:return frozenset()+def canonical_operational_scout_names() -> frozenset[str]:+ """Names of every canonical scout that declares `scout-role: operational`."""+ return _canonical_operational_scouts()++def is_operational_scout(skill_name: str) -> bool:"""Whether the canonical scout of this name watches the self-driving system itself.diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.pyindex 400b366ea2da..9d82233f9dbc 100644--- a/products/signals/backend/temporal/agentic/scout_coordinator.py+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py@@ -23,7 +23,13 @@ from posthog.temporal.common.heartbeat import Heartbeaterfrom products.signals.backend.models import SignalScoutConfigfrom products.signals.backend.report_check_execution import run_due_report_checks-from products.signals.backend.scout_harness.config_registry import live_scout_skill_names, register_missing_configs+from products.signals.backend.scout_harness.config_registry import (+ canonical_operational_skill_names,+ live_scout_skill_names,+ operational_configs_needing_reconcile,+ reconcile_operational_configs,+ register_missing_configs,+)from products.signals.backend.scout_harness.lazy_seed import sync_canonical_skillsfrom products.signals.backend.scout_harness.limits import (AUTO_PAUSE_PROBE_INTERVAL_S,@@ -52,6 +58,7 @@ from products.signals.backend.scout_harness.team_limits import (_resolve_withheld_skills,_runs_today_by_team,_team_configs,+ resolve_max_enabled_scouts,)from products.signals.backend.temporal.agentic.scout_scheduler import RunSignalsScoutInput, RunSignalsScoutWorkflowfrom products.signals.backend.temporal.metrics import (@@ -341,7 +348,8 @@ def _collect_planned_runs(default_team_config = default_team_config or {}due: list[_DueRun] = []paused_by_team = _breaker_paused_configs_by_team()- for team, needs_seed in _participating_teams(enrollment):+ reconcile_by_team = operational_configs_needing_reconcile() if enrollment.wildcard else {}+ for team, needs_seed in _participating_teams(enrollment, reconcile_team_ids=set(reconcile_by_team)):# Scouts held back from this team via the `withheld_skills` denylist (resolved most-# specific-first from this team's `team_configs` entry, then the fleet `default_team_config`):# skip seeding the skill, skip seeding/enabling a config, and skip dispatch.@@ -381,6 +389,16 @@ def _collect_planned_runs(# brand-new canonical scouts as rows — both rare, and both catch up on the team's next# `sync` (follow-up if needed: a slow fleet-wide prune/seed sweep off the dispatch path).live_skills = live_scout_skill_names(team.id, withheld_skill_names=withheld_for_team)+ # The one part of the reconcile the wildcard path still runs: an operational scout+ # that stays off stops the checks and validation that run on it. Only teams with a+ # row that needs it pay for the call, and a withheld scout is never a reason to call.+ if reconcile_by_team.get(team.id, set()) - withheld_for_team:+ _reconcile_wildcard_operational_configs(+ team.id,+ live_skills,+ withheld_for_team,+ [team_configs.get(team.id) or {}, default_team_config],+ )# Skip enabled configs whose skill was deleted or is no longer the# latest version: dispatching them would spawn a child workflow that fails fast in# load_skill_for_run on every tick.@@ -516,7 +534,26 @@ def _canonicalize_team_ids(ids: set[int]) -> set[int]:}-def _participating_teams(enrollment: Enrollment) -> list[tuple[Team, bool]]:+def _reconcile_wildcard_operational_configs(+ team_id: int, live_skills: set[str], withheld_skill_names: frozenset[str] | set[str], seed_config_layers: list[dict]+) -> None:+ """Run `reconcile_operational_configs` for one wildcard team. A failure does not abort the tick."""+ try:+ reconcile_operational_configs(+ team_id,+ canonical_operational_skill_names(team_id) & live_skills,+ withheld_skill_names,+ # Resolved here, because the reconcile holds row locks and must not read the flag.+ max_enabled_scouts=resolve_max_enabled_scouts(seed_config_layers),+ )+ except Exception:+ logger.exception(+ "signals_scout coordinator: operational reconcile failed for team; continuing",+ team_id=team_id,+ )+++def _participating_teams(enrollment: Enrollment, reconcile_team_ids: set[int] | None = None) -> list[tuple[Team, bool]]:"""Resolve enrollment to canonical `Team`s to run scouts on, each tagged `needs_seed`.Two ways a team participates:@@ -528,6 +565,8 @@ def _participating_teams(enrollment: Enrollment) -> list[tuple[Team, bool]]:(`needs_seed=False`): it self-enrolled through the product-autonomy-gated UI, so it alreadyhas configs and the tick skips the expensive seed/reconcile for it. If a team is in both, theexplicit tag wins (it gets the seed pass).+ `reconcile_team_ids` joins the wildcard set too: a team whose only scouts are operational+ ones the harness left off has no enabled config, and it must still reach the reconcile.Child envs canonicalize to their parent project; `skip_team_ids` is removed from both sets.Skip is subtracted AFTER canonicalizing both sides, so listing a child env in `guaranteed_team_ids`and its parent project in `skip_team_ids` (or the reverse) still hard-excludes the project — the@@ -553,6 +592,7 @@ def _participating_teams(enrollment: Enrollment) -> list[tuple[Team, bool]]:.values_list("team_id", flat=True).distinct())+ wildcard_ids |= reconcile_team_ids or set()wildcard_ids -= skip_canonicalwildcard_ids -= explicit # explicit wins the tag — it gets the seed pass belowdiff --git a/products/signals/backend/test/test_report_checks.py b/products/signals/backend/test/test_report_checks.pyindex b17356602930..3c9e50268f68 100644--- a/products/signals/backend/test/test_report_checks.py+++ b/products/signals/backend/test/test_report_checks.py@@ -954,12 +954,17 @@ class TestAgentCheckDispatch(APIBaseTest):})- with patch(_CONNECT), patch(_DISPATCH) as dispatch:- summary = run_due_report_checks()+ with patch(_CONNECT), patch(_DISPATCH) as dispatch, patch(_CAPTURE) as capture:+ with self.captureOnCommitCallbacks(execute=True):+ summary = run_due_report_checks()assert summary.errored == 1dispatch.assert_not_called()assert "is paused" in self._results()[0].content+ properties = capture.call_args.kwargs["properties"]+ assert capture.call_args.kwargs["event"] == "signals_report_check_evaluated"+ assert properties["reason"] == "scout_paused"+ assert properties["skill_name"] == "signals-scout-health-checks"def test_an_unenrolled_project_records_an_errored_result(self) -> None:self._enrol({"guaranteed_team_ids": []})diff --git a/products/signals/backend/test/test_resume_setup_paused_operational_scouts.py b/products/signals/backend/test/test_resume_setup_paused_operational_scouts.pynew file mode 100644index 000000000000..d81946245f56--- /dev/null+++ b/products/signals/backend/test/test_resume_setup_paused_operational_scouts.py@@ -0,0 +1,75 @@+from datetime import timedelta+from typing import Any++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.management import call_command++from parameterized import parameterized++from products.signals.backend.models import SignalScoutConfig+from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY+from products.skills.backend.models.skills import LLMSkill++_OPERATIONAL_SCOUT = "signals-scout-inbox-validation"+_READ_PAYLOAD = "products.signals.backend.scout_harness.config_registry._read_flag_payload"+++class TestResumeSetupPausedOperationalScouts(BaseTest):+ def _paused_config(+ self, skill_name: str = _OPERATIONAL_SCOUT, *, gap: timedelta = timedelta(seconds=10), by_user: bool = False+ ) -> SignalScoutConfig:+ LLMSkill.objects.create(+ team=self.team, name=skill_name, description="d", body="b", metadata={"seeded_by": HARNESS_SEEDED_BY}+ )+ config = SignalScoutConfig.objects.create(team=self.team, skill_name=skill_name, enabled=True)+ SignalScoutConfig.all_teams.filter(pk=config.pk).update(+ enabled=False,+ status=SignalScoutConfig.Status.PAUSED_BY_USER,+ status_changed_at=config.created_at + gap,+ status_changed_by=self.user if by_user else None,+ )+ config.refresh_from_db()+ return config++ def _run(self, *args: str, payload: dict[str, Any] | None = None) -> None:+ with patch(_READ_PAYLOAD, return_value=payload):+ call_command("resume_setup_paused_operational_scouts", *args)++ def test_dry_run_changes_nothing_and_apply_resumes_the_setup_pause(self) -> None:+ config = self._paused_config()++ self._run()+ config.refresh_from_db()+ assert config.status == SignalScoutConfig.Status.PAUSED_BY_USER++ self._run("--apply", "--team-id", str(self.team.id))+ config.refresh_from_db()+ assert config.status == SignalScoutConfig.Status.ACTIVE+ assert config.enabled is True+ assert config.auto_pause_exempt is True++ @parameterized.expand(+ [+ ("attributed_pause", {"by_user": True}),+ ("late_pause", {"gap": timedelta(hours=1)}),+ ("specialist", {"skill_name": "signals-scout-general"}),+ ]+ )+ def test_apply_leaves_pauses_the_setup_flow_did_not_make(self, _name: str, kwargs: dict[str, Any]) -> None:+ config = self._paused_config(**kwargs)++ self._run("--apply")++ config.refresh_from_db()+ assert config.status == SignalScoutConfig.Status.PAUSED_BY_USER+ assert config.enabled is False++ def test_apply_leaves_a_withheld_scout_paused(self) -> None:+ config = self._paused_config()++ self._run("--apply", payload={"default_team_config": {"withheld_skills": [_OPERATIONAL_SCOUT]}})++ config.refresh_from_db()+ assert config.status == SignalScoutConfig.Status.PAUSED_BY_USERdiff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.pyindex 9b46cec66fe8..7f5f312d9a62 100644--- a/products/signals/backend/test/test_scout_coordinator.py+++ b/products/signals/backend/test/test_scout_coordinator.py@@ -1822,6 +1822,86 @@ def test_reconcile_leaves_a_failure_pause_alone():assert config.pause_reason == SignalScoutConfig.PauseReason.REPEATED_FAILURES+async def test_wildcard_tick_resumes_an_operational_scout_seeded_disabled(ateam):+ # The wildcard path skips the seed, and a team whose only scout sits disabled has no enabled+ # config, so without the targeted reconcile this row stays off for good.+ await database_sync_to_async(_create_skill)(ateam, _OPERATIONAL_SCOUT)+ await database_sync_to_async(_create_config)(ateam, _OPERATIONAL_SCOUT, enabled=False)++ with patch(_PAYLOAD_PATH, return_value={"guaranteed_team_ids": ["*"]}):+ planned = await _run_activity()++ config = await database_sync_to_async(+ lambda: SignalScoutConfig.all_teams.get(team_id=ateam.id, skill_name=_OPERATIONAL_SCOUT)+ )()+ assert config.status == SignalScoutConfig.Status.ACTIVE+ assert config.auto_pause_exempt is True+ assert any(p.team_id == ateam.id and p.skill_name == _OPERATIONAL_SCOUT for p in planned)+++ "config_kwargs,human_pause,withheld,expected_status",+ [+ ({"enabled": False}, True, False, SignalScoutConfig.Status.PAUSED_BY_USER),+ (+ {+ "status": SignalScoutConfig.Status.PAUSED_BY_SYSTEM,+ "pause_reason": SignalScoutConfig.PauseReason.REPEATED_FAILURES,+ },+ False,+ False,+ SignalScoutConfig.Status.PAUSED_BY_SYSTEM,+ ),+ ({"enabled": False}, False, True, SignalScoutConfig.Status.PAUSED_BY_USER),+ ],+ ids=["human_pause", "breaker_pause", "withheld"],+)+async def test_wildcard_tick_leaves_pauses_it_does_not_own(+ ateam, config_kwargs, human_pause, withheld, expected_status+):+ await database_sync_to_async(_create_skill)(ateam, _OPERATIONAL_SCOUT)+ config = await database_sync_to_async(_create_config)(ateam, _OPERATIONAL_SCOUT, **config_kwargs)+ if human_pause:+ await database_sync_to_async(SignalScoutConfig.all_teams.filter(pk=config.pk).update)(+ status_changed_at=timezone.now()+ )+ payload: dict[str, Any] = {"guaranteed_team_ids": ["*"]}+ if withheld:+ payload["default_team_config"] = {"withheld_skills": [_OPERATIONAL_SCOUT]}++ with patch(_PAYLOAD_PATH, return_value=payload):+ await _run_activity()++ await database_sync_to_async(config.refresh_from_db)()+ assert config.status == expected_status+ assert config.auto_pause_exempt is not withheld+++async def test_wildcard_tick_skips_the_reconcile_when_nothing_needs_it(ateam):+ await database_sync_to_async(_create_skill)(ateam, _OPERATIONAL_SCOUT)+ await database_sync_to_async(_create_config)(+ ateam, _OPERATIONAL_SCOUT, enabled=True, auto_pause_exempt=True, auto_pause_exempt_by_role=True+ )++ with (+ patch(_PAYLOAD_PATH, return_value={"guaranteed_team_ids": ["*"]}),+ patch("products.signals.backend.temporal.agentic.scout_coordinator.reconcile_operational_configs") as reconcile,+ ):+ planned = await _run_activity()++ assert all(call.args[0] != ateam.id for call in reconcile.call_args_list)+ assert any(p.team_id == ateam.id and p.skill_name == _OPERATIONAL_SCOUT for p in planned)++@pytest.mark.django_dbdef test_a_teams_own_scout_sharing_an_operational_name_gets_no_exemption():# A hand-authored skill must not inherit a posture that skips the harness's controls.