Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

106 KB
Raw Blame
from __future__ import annotations

import time
import asyncio
import logging
from collections import deque
from contextlib import nullcontext
from dataclasses import dataclass, replace
from datetime import UTC, datetime, timedelta
from functools import lru_cache, partial
from typing import Any
from uuid import UUID

from django.db import transaction
from django.db.models import F, Func, JSONField, Q, Value
from django.db.models.functions import Coalesce
from django.utils import timezone

import posthoganalytics
from croniter import CroniterError, croniter

from posthog.clickhouse.query_tagging import private_capture_context
from posthog.dataclasses import frozen
from posthog.event_usage import groups
from posthog.exceptions_capture import capture_exception
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.models.utils import uuid7
from posthog.sync import database_sync_to_async
from posthog.temporal.oauth import SCOUT_DEFAULT_WRITE_SCOPES, scout_mcp_scopes, scout_scope_posture

from products.business_knowledge.backend.logic import is_maintained_for_team
from products.data_catalog.backend.facade.api import approved_metric_names_for_team
from products.mcp_store.backend.facade.api import get_sandbox_mcp_server_names
from products.signals.backend.activity_summary.search import searchable_config
from products.signals.backend.agent_runtime import STEP_SCOUT, AgentRuntime, resolve_agent_runtime
from products.signals.backend.constants import FIRST_REPORT_SCOUT, FIRST_REPORT_SCOUT_TIMEOUT_SECONDS
from products.signals.backend.facade.source_scouts import refresh_source_scout
from products.signals.backend.first_report_completion import complete_first_report_investigation
from products.signals.backend.first_report_experiment import FirstReportExperiment, resolve_first_report_experiment
from products.signals.backend.first_report_scout import set_first_report_state
from products.signals.backend.first_report_scout_types import FirstReportScoutResult
from products.signals.backend.github_optional import ResearchAccessPolicy
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
from products.signals.backend.report_content_gates import team_research_reviewer_selection_enabled
from products.signals.backend.scout_harness.acting_user import resolve_scout_run_acting_user
from products.signals.backend.scout_harness.derived_metadata import stamp_derived_metadata
from products.signals.backend.scout_harness.lazy_seed import canonical_skill_names, sync_canonical_skills
from products.signals.backend.scout_harness.limits import (
    DEFAULT_MAX_RUNTIME_S,
    FAILURE_STREAK_MAX_RUNS,
    FAILURE_STREAK_MIN_SPAN_MINUTES,
    ORPHAN_RECENT_RUNS,
    SCOUT_RUN_REAPED_METADATA_KEY,
    STALE_RUN_CUTOFF_S,
    TRIAL_ACTIVITY_TIMEOUT_S,
    TRIAL_MAX_RUNTIME_S,
    TRIGGERED_BY_ONBOARDING,
    TRIGGERED_BY_SCHEDULE,
    failure_streak_pause_threshold,
    interval_runs_in_tolerance_window,
)
from products.signals.backend.scout_harness.model_selection import RUNTIME_ADAPTER_CODEX, resolve_scout_model
from products.signals.backend.scout_harness.prompt import (
    HARNESS_PROMPT_VERSION,
    FirstReportScoutRunSummary,
    SignalScoutRunSummary,
    build_run_prompt,
)
from products.signals.backend.scout_harness.run_gates import lane_has_live_run
from products.signals.backend.scout_harness.skill_loader import (
    SIGNALS_SCOUT_SKILL_PREFIX,
    LoadedSkill,
    load_skill_for_run,
    resolve_report_channel_variant,
    skill_uses_report_channel,
)
from products.signals.backend.scout_harness.team_limits import (
    BackgroundBackoff,
    github_read_access_for_team,
    resolve_background_backoff,
    withheld_skills_for_team,
)
from products.signals.backend.scout_harness.tool_catalogue import scout_held_mcp_tools, scout_tool_access_enabled
from products.signals.backend.scout_harness.trial_launch import (
    TrialLaunch,
    assert_trial_model_access,
    load_trial_launch,
)
from products.signals.backend.scout_harness.trial_result import export_trial_result, validate_trial_runtime
from products.signals.backend.scout_harness.trial_state import SCOUT_TRIAL_METADATA_KEY, initial_trial_state
from products.signals.backend.scout_report import scout_report_tags_in_use
from products.signals.backend.spend import record_task_spend
from products.signals.backend.temporal.agentic import (
    SIGNALS_REPORT_RESEARCH_ENV_NAME,
    get_or_create_signals_sandbox_env,
)
from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.facade.agents import (
    AgentTurnFailed,
    CustomPromptSandboxContext,
    MultiTurnSession,
    TurnPollTimeout,
)

logger = logging.getLogger(__name__)

# Reuse the report-research sandbox env. Same posture: full repo on disk, restricted
# network, MCP read scopes injected. Split out later if the agent needs different policy.
SIGNALS_SCOUT_SANDBOX_ENV_NAME = SIGNALS_REPORT_RESEARCH_ENV_NAME

# Dedicated env for scouts whose config opts into full network access. Sandbox envs are
# per-team rows shared by name, and `upsert_internal_sandbox_env` reasserts policy on every
# call — so a full-network run must NOT reuse the shared research env above, or it would
# flip the network policy for report research and every trusted-mode scout on the team.
SIGNALS_SCOUT_FULL_NETWORK_ENV_NAME = "SIGNALS_SCOUT_FULL_NETWORK"

# Every scout `ai_stage` starts with this, so `ai_stage LIKE 'scout:%'` rolls the whole fleet
# up as one stage even though the tag names the individual scout.
SCOUT_AI_STAGE_PREFIX = "scout:"

# `_cron_runs_in_window` samples a cron schedule from a fixed reference (not `now`) so a lane's
# breaker threshold is a property of its schedule rather than of when it happened to fail. The
# horizon is one full pass of the month and day-of-month fields, which keeps cross-month
# adjacencies in the sample: "first of the month or Sunday" packs its fullest window where a
# matching Sunday touches a first, and a shorter occurrence-count sample never reaches one.
# Day-of-week alignments unique to other calendar years can still be missed, which only ever
# undercounts, so an exotic lane trips a little earlier instead of earning extra lease budget.
# The sample cap covers the horizon at the 30-minute schedule floor with room to spare; denser
# out-of-band schedules hit the `FAILURE_STREAK_MAX_RUNS` early exit long before it.
_CRON_WINDOW_REFERENCE = datetime(2026, 1, 1, tzinfo=UTC)
_CRON_WINDOW_HORIZON = timedelta(days=366)
_CRON_WINDOW_MAX_SAMPLES = 20_000

# Cron lanes hold wall-clock time in the project's timezone (see the coordinator's due-check),
# so on the spring-forward night more wall-clock schedule fits inside the same absolute outage
# than this transition-free sample sees. Sized to the largest jump among selectable project
# timezones (Antarctica/Troll advances two hours; every other zone is an hour or less), which
# keeps the tolerance honest on that night in every zone at the cost of at most a couple of
# extra tolerated failures the rest of the year. That is far cheaper than sizing per project
# timezone, which would put DST fold/gap arithmetic and a per-team cache key on the failure path.
_CRON_WINDOW_DST_SLACK_MINUTES = 120

# The report channel (emit_report/edit_report) is opt-in per skill. A scout's sandbox token
# carries the report-write scope ONLY when its skill listed one of these in `allowed_tools` (see
# the posture selection where the sandbox context is built). A baseline scout never carries that
# scope, so the MCP server strips the report tools from its toolset — they can't bleed into a run
# that didn't opt in. `views._assert_report_tool_opted_in` is the matching fail-closed gate on the
# write itself. `REPORT_CHANNEL_TOOLS` / `skill_uses_report_channel` live in `skill_loader` so the
# runner, prompt builder, and viewset all resolve the same opt-in set.


@dataclass(frozen=True)
class RunResult:
    """Outcome of a run-trigger.

    `run_id` / `task_run_id` are None when the trigger was skipped without
    persisting a row (e.g. another run for the same team/skill is still in
    flight). `status` mirrors `TaskRun.Status` values as strings so callers
    don't need to import the tasks model.
    """

    run_id: str | None
    task_run_id: str | None
    status: str | None
    last_message: str | None
    runtime_s: float
    skill_name: str
    skill_version: int
    skip_reason: str | None = None


class _TrialTaskCancelled(Exception):
    def __init__(self, *, task_run_id: str) -> None:
        super().__init__("The scout task was cancelled.")
        self.task_run_id = task_run_id


def _get_trial_config(trial: TrialLaunch) -> SignalScoutConfig:
    return SignalScoutConfig.objects.for_team(trial.team_id).get(id=trial.config_id, skill_name=trial.skill_name)


def _existing_trial_result(team_id: int, trial: TrialLaunch) -> RunResult | None:
    task_id = tasks_facade.get_task_id_by_idempotency_key(team_id, f"scout-trial:{trial.id}")
    if task_id is None:
        return None
    run = SignalScoutRun.objects.for_team(team_id).select_related("task_run").filter(task_run__task_id=task_id).first()
    if run is None:
        return None
    return RunResult(
        run_id=str(run.id),
        task_run_id=str(run.task_run_id),
        status=run.task_run.status,
        last_message=run.summary,
        runtime_s=0.0,
        skill_name=run.skill_name,
        skill_version=run.skill_version,
    )


def _trial_invalid_reason(*, team_id: int, run_id: UUID, trial: TrialLaunch) -> str | None:
    run = SignalScoutRun.objects.for_team(team_id).select_related("task_run").get(id=run_id)
    invalid_reason = validate_trial_runtime(run, trial)
    if run.task_run.status == tasks_facade.TaskRunStatus.CANCELLED.value:
        raise _TrialTaskCancelled(task_run_id=str(run.task_run_id))
    return invalid_reason


def _cancelled_trial_task_run_id(*, team_id: int, run_id: UUID) -> str | None:
    task_run_id = (
        SignalScoutRun.objects.for_team(team_id)
        .filter(id=run_id, task_run__status=tasks_facade.TaskRunStatus.CANCELLED.value)
        .values_list("task_run_id", flat=True)
        .first()
    )
    return str(task_run_id) if task_run_id is not None else None


def _export_trial_result_safely(*, team_id: int, run_id: UUID, status: str) -> None:
    try:
        run = SignalScoutRun.objects.for_team(team_id).select_related("task_run").filter(id=run_id).first()
        if run is not None:
            export_trial_result(run, status=status)
    except Exception:
        logger.warning("signals_scout: trial result export failed", extra={"run_id": str(run_id)}, exc_info=True)


def run_signals_scout(
    *,
    team_id: int,
    skill_name: str,
    skill_version: int | None = None,
    repository: str | None = None,
    verbose: bool = False,
    triggered_by: str = TRIGGERED_BY_SCHEDULE,
    run_note: str | None = None,
    agent_runtime: AgentRuntime | None = None,
    trial_launch_id: str | None = None,
    check_id: str | None = None,
) -> RunResult:
    """Synchronous entrypoint: resolves config, spawns sandbox, persists the run row.

    Wraps the async core for callers that aren't inside an event loop (management
    command, direct script). Temporal activities call `arun_signals_scout` directly.
    """
    return asyncio.run(
        arun_signals_scout(
            team_id=team_id,
            skill_name=skill_name,
            skill_version=skill_version,
            repository=repository,
            verbose=verbose,
            triggered_by=triggered_by,
            run_note=run_note,
            agent_runtime=agent_runtime,
            trial_launch_id=trial_launch_id,
            check_id=check_id,
        )
    )


async def _arun_signals_scout(
    *,
    team_id: int,
    skill_name: str,
    skill_version: int | None = None,
    repository: str | None = None,
    verbose: bool = False,
    triggered_by: str = TRIGGERED_BY_SCHEDULE,
    run_note: str | None = None,
    trigger_workflow_id: str | None = None,
    agent_runtime: AgentRuntime | None = None,
    trial_launch_id: str | None = None,
    check_id: str | None = None,
    precheck_rows: str | None = None,
    precheck_query_source: str | None = None,
) -> RunResult:
    """Async core. Safe to call from inside a running event loop (Temporal activity).

    `triggered_by` is `"schedule"` for coordinator-dispatched runs (including breaker probes),
    `"manual"` for on-demand triggers (the `run` endpoint, the management command) and
    `"workflow"` for a workflow step that runs a scout. Only scheduled failures feed the
    failure-streak breaker; see the failure path below. Anything but `"schedule"` is also stamped
    onto the run row's `metadata`, which is what the workflow path's cooldown reads.

    `run_note` is the one-off steering a person typed when triggering the run by hand. It renders
    its own prompt section and is stamped on the run row, so the run it steered says so in its own
    history; it is never carried into a later run.

    `trigger_workflow_id` is the workflow whose "Run scout" step started a `"workflow"` run. It
    renders in the run's identity and is stamped on the run row.

    `precheck_rows` are the rows the pre-check of a scheduled run found (`scout_harness/precheck.py`).
    They render in their own prompt section as untrusted data. `precheck_query_source` says which
    pre-check started the run, and is stamped on the run row.
    """
    if skill_name == FIRST_REPORT_SCOUT and triggered_by != TRIGGERED_BY_ONBOARDING:
        raise ValueError("The first-report scout only accepts onboarding dispatches.")
    team = await database_sync_to_async(_get_team, thread_sensitive=False)(team_id)
    trial = (
        await database_sync_to_async(load_trial_launch, thread_sensitive=False)(
            team.parent_team_id or team.id, trial_launch_id
        )
        if trial_launch_id is not None
        else None
    )
    if trial is not None:
        skill_name = trial.skill_name
        skill_version = trial.skill_version
        run_note = trial.note
        triggered_by = "experiment"
        agent_runtime = AgentRuntime(
            runtime_adapter=trial.runtime_adapter,
            model=trial.model,
            reasoning_effort=trial.reasoning_effort,
            service_tier=trial.service_tier,
        )
        prior = await database_sync_to_async(_existing_trial_result, thread_sensitive=False)(
            team.parent_team_id or team.id, trial
        )
        if prior is not None:
            return prior
        await database_sync_to_async(assert_trial_model_access, thread_sensitive=False)(trial)

    # Honor the per-scout holdback denylist, resolved against the canonical project. Two effects:
    # (1) a direct run of a held-back scout is refused up front (so this manual path can't seed or
    # run a scout the flag withholds), and (2) the canonical sync below is passed the denylist so
    # running *any* scout on a held-back team can't seed the other withheld scouts' rows as a side
    # effect. In local dev there's no flag payload, so this resolves empty and nothing is blocked.
    withheld = await database_sync_to_async(withheld_skills_for_team, thread_sensitive=False)(
        team.parent_team_id or team.id
    )
    if skill_name in withheld:
        logger.info(
            "signals_scout: skipping run, scout is withheld from this team",
            extra={"team_id": team_id, "skill_name": skill_name},
        )
        return RunResult(
            run_id=None,
            task_run_id=None,
            status=None,
            last_message=None,
            runtime_s=0.0,
            skill_name=skill_name,
            skill_version=skill_version or 0,
            skip_reason="scout is withheld from this team",
        )

    # Sync canonical signals-scout-* skills before we resolve the skill the run asked for.
    # Creates rows for newly-shipped specialists, updates harness-seeded rows the team
    # hasn't edited, and leaves forked / tombstoned rows alone. Failures here should not
    # crash the run — we log and continue with whatever skills the team already has.
    if trial is None:
        try:
            await database_sync_to_async(sync_canonical_skills, thread_sensitive=False)(
                team, withheld_skill_names=withheld
            )
        except Exception:
            logger.exception(
                "signals_scout: canonical skill sync failed; continuing with existing team skills",
                extra={"team_id": team_id},
            )
        # A product that created this scout for one of its objects may bring its text up to date first.
        try:
            await database_sync_to_async(refresh_source_scout, thread_sensitive=False)(
                team.parent_team_id or team.id, skill_name
            )
        except Exception:
            logger.exception(
                "signals_scout: source scout refresh failed; continuing with the stored skill",
                extra={"team_id": team_id, "skill_name": skill_name},
            )
    skill = await database_sync_to_async(load_skill_for_run, thread_sensitive=False)(
        team, skill_name, version=skill_version, include_authors=True
    )
    if trial is None:
        config = await database_sync_to_async(_resolve_config, thread_sensitive=False)(team, skill.name)
    else:
        config = await database_sync_to_async(_get_trial_config, thread_sensitive=False)(trial)
        config.write_scopes = []
        skill = replace(skill, body=trial.skill_body)

    # Stale-run recovery, before the skip-if-running guard below. A scout run writes its own
    # terminal `task_run.status` from inside the activity; if the worker/sandbox dies hard
    # mid-run that write never lands, leaving the TaskRun stuck `IN_PROGRESS` — which would
    # otherwise block every future dispatch for this `(team, skill)` forever via
    # `_has_running_run`. Reap such orphans here so the lane self-heals. Keyed on the same
    # canonical `(team, skill_name)` the guard uses so it reaps exactly the rows the guard sees.
    if trial is None:
        await database_sync_to_async(_self_heal_stale_runs, thread_sensitive=False)(
            team.parent_team_id or team.id, skill.name
        )

    # Skip-if-running guard, keyed on (team, skill_name). Different skills for the same
    # team are allowed to run concurrently — the coordinator can dispatch several due
    # scouts for one team in a single tick. Best-effort — there is a race window between
    # this check and the bridge-row insert inside _spawn_and_run (a second trigger could
    # land in between), which we accept until a claim/lease primitive lands.
    if trial is None and await database_sync_to_async(_has_running_run, thread_sensitive=False)(
        team_id=team.parent_team_id or team.id, skill_name=skill.name
    ):
        logger.info(
            "signals_scout: skipping trigger, prior run still in progress",
            extra={"team_id": team_id, "skill_name": skill.name},
        )
        return RunResult(
            run_id=None,
            task_run_id=None,
            status=None,
            last_message=None,
            runtime_s=0.0,
            skill_name=skill.name,
            skill_version=skill.version,
            skip_reason="prior run still in progress",
        )

    # Resolve the acting user up front: the skill's creator (else the config's enabler/creator)
    # when one resolves, so a scout's runs, and the AI spend attributed off the task row, land on
    # the human who authored or enabled the scout instead of pooling on one team-level default
    # user. A scout clones with the team's read-only mint rather than the acting user's own
    # credential, so it needs no personal GitHub link even when it pins repositories
    # — the `resolve_acting_user_id_for_team` fallback prefers the GitHub creator when present but
    # falls back to any other member with access to this project, so a team that never connected
    # GitHub still runs (these dominated the fleet failure rate when the run instead crashed ~5s
    # into `_spawn_and_run` and booked a bogus `failed`). The only remaining short-circuit is the
    # genuine "no member can act" case; like the withheld / in-flight skips it leaves no row, no
    # lifecycle event, and a `skip_reason` the coordinator can surface — not a failure.
    acting_user = await database_sync_to_async(resolve_scout_run_acting_user, thread_sensitive=False)(
        team, skill.name, config, trial_user_id=trial.user_id if trial is not None else None
    )
    if acting_user is None:
        logger.info(
            "signals_scout: skipping run, no active user to act as for team",
            extra={"team_id": team_id, "skill_name": skill.name},
        )
        return RunResult(
            run_id=None,
            task_run_id=None,
            status=None,
            last_message=None,
            runtime_s=0.0,
            skill_name=skill.name,
            skill_version=skill.version,
            skip_reason="no active user to act as for team",
        )
    granted_write_scopes = _granted_write_scopes(config)
    if acting_user.is_team_fallback and set(granted_write_scopes) - SCOUT_DEFAULT_WRITE_SCOPES:
        # The grant was approved for the person the runs act as. The team fallback is a member
        # who never approved it, so this run holds only the fleet posture and the default scopes
        # the scout still holds. The fleet granted those, not a person, so the fallback bypasses
        # no approval by keeping them. Cleared in memory only: the runner never saves the config
        # row, so the grant is back the moment the author's identity resolves again.
        logger.info(
            "signals_scout: withholding write access, acting user is the team fallback",
            extra={"team_id": team_id, "skill_name": skill.name, "user_id": acting_user.user_id},
        )
        config.write_scopes = sorted(set(granted_write_scopes) & SCOUT_DEFAULT_WRITE_SCOPES)
    user_id = acting_user.user_id

    started = time.monotonic()
    # Pre-mint the bridge row's UUID so the prompt can reference it before the row
    # exists. The TaskRun is created inside `MultiTurnSession.start`; the bridge row is
    # inserted in the task creation transaction so first-turn tools resolve its private state.
    run_id = uuid7()
    started_at = timezone.now()

    # Resolve the scout's agent model. A `None` model keeps the agent-server default; an override
    # routes this run on that model, paired with the runtime adapter that can serve it (the agent
    # server can't route a model without one). Two flag-gated layers, resolved in one call: the
    # scout's own `config.model` pin (honored while the `scouts-model-config` dogfood flag is on
    # for the team, deterministic per scout), then the `scouts-model-selection` payload — a
    # per-team, per-scout model distribution, bucketed per run on `run_id`, so a scout can A/B/n
    # across models against itself across runs. Resolved once here so the whole run is consistent.
    # Off the event loop — the flag reads do blocking network I/O.
    # The scout-model resolution (config pin, then experiment gate) sits above the
    # `signals-pipeline-models` runtime pin, the default layer beneath it. When it resolves a model
    # for this run it wins (the gate's unallocated remainder resolves None and falls through to the
    # pin), so a fleet-wide pin can't silently swallow a configured model. Either way the whole
    # runtime/model/effort triple is taken from one source — a Codex runtime never pairs with a
    # model it can't serve. Model-only pin entries are still ignored for scout: a pin supplies
    # model+runtime as a pair, and overriding one without the other would mis-route.
    experiment = None
    if skill.name == FIRST_REPORT_SCOUT and agent_runtime is None and trial is None:
        experiment = await database_sync_to_async(resolve_first_report_experiment, thread_sensitive=False)(team)
        if experiment is None or experiment.agent_runtime is None:
            await database_sync_to_async(set_first_report_state, thread_sensitive=False)(team.id, "incomplete")
            return RunResult(
                run_id=None,
                task_run_id=None,
                status=None,
                last_message=None,
                runtime_s=0.0,
                skill_name=skill.name,
                skill_version=skill.version,
                skip_reason="first-report experiment disabled" if experiment is None else "first-report control arm",
            )
        agent_runtime = experiment.agent_runtime
    runtime = agent_runtime.runtime if agent_runtime is not None else "acp"
    if agent_runtime is not None:
        runtime_adapter: str | None = agent_runtime.runtime_adapter
        model: str | None = agent_runtime.model
        reasoning_effort: str | None = agent_runtime.reasoning_effort
        service_tier: str | None = agent_runtime.service_tier
    else:
        scout_model = await database_sync_to_async(resolve_scout_model, thread_sensitive=False)(
            team, skill.name, str(run_id), configured_model=config.model
        )
        pipeline_runtime = await database_sync_to_async(resolve_agent_runtime, thread_sensitive=False)(
            team_id, STEP_SCOUT
        )
        if scout_model.model:
            runtime_adapter = scout_model.runtime_adapter
            model = scout_model.model
            reasoning_effort = scout_model.reasoning_effort
            service_tier = scout_model.service_tier
        elif pipeline_runtime.runtime_adapter:
            runtime_adapter = pipeline_runtime.runtime_adapter
            model = pipeline_runtime.model
            reasoning_effort = pipeline_runtime.reasoning_effort
            service_tier = pipeline_runtime.service_tier
        else:
            runtime_adapter = None
            model = None
            reasoning_effort = None
            service_tier = None
    # The OpenAI queue travels with the model it was configured beside, like the rest of the
    # triple: a slice's own tier, or the pipeline pin's when the pin's model runs. It never crosses
    # to a model the operator did not pair it with (some reject the field outright), which is what
    # lets one slice trial `flex` against the remainder's standard queue on the same model. Only a
    # Codex turn joins an OpenAI queue, so a claude runtime drops it rather than stamping a tier the
    # run never asked for onto the A/B readout.
    if runtime_adapter != RUNTIME_ADAPTER_CODEX:
        service_tier = None
    # Resolved here rather than inside `_spawn_and_run` so the failure and cancellation paths below
    # can report the same prompt shape the run actually got: a spawn that raises never returns, so a
    # value resolved in there would be unavailable to exactly the runs whose shape matters most.
    github = await _resolve_github_posture(team=team, config=config, skill=skill, repository_override=repository)
    github_guidance = github.prompt_names_gh
    # Resolved here alongside `github_guidance`, and for the same reason: it forks the prompt, so
    # the failure and cancellation paths below must report the same shape the run got, and a value
    # resolved inside `_spawn_and_run` would be missing on exactly the runs that raised before
    # reaching it. The helper never raises (it swallows read errors to off), so it is safe outside
    # the try. Whether the business-knowledge section rendered rides on this boolean.
    business_knowledge_maintained = await database_sync_to_async(
        _business_knowledge_maintained_for_team, thread_sensitive=False
    )(team)
    # Resolved here for the same reason: it picks the reviewer-routing sections of the prompt. Teams in
    # the `signals-research-reviewer-selection` trial get the evidence-only guidance, the rest the
    # legacy routing text, so the trial measures the prompt change too. Fails closed to legacy.
    strict_reviewer_selection = await database_sync_to_async(
        team_research_reviewer_selection_enabled, thread_sensitive=False
    )(team.id)
    # Resolved here for the same reason, so every lifecycle event reports the same cadence. The
    # backoff comes from the lane that runs this config's skill.
    backoff = (
        await asyncio.to_thread(resolve_background_backoff, config.skill_name)
        if config.managed_by == SignalScoutConfig.ManagedBy.BACKGROUND
        else None
    )
    trial_status = tasks_facade.TaskRunStatus.FAILED.value
    try:
        last_message, task_run_id = await _spawn_and_run(
            team=team,
            config=config,
            run_id=run_id,
            started_at=started_at,
            skill=skill,
            repositories=github.repositories,
            verbose=verbose,
            user_id=user_id,
            github_guidance=github_guidance,
            business_knowledge_maintained=business_knowledge_maintained,
            strict_reviewer_selection=strict_reviewer_selection,
            background_backoff=backoff,
            model=model,
            runtime_adapter=runtime_adapter,
            reasoning_effort=reasoning_effort,
            service_tier=service_tier,
            runtime=runtime,
            experiment=experiment,
            triggered_by=triggered_by,
            run_note=run_note,
            trigger_workflow_id=trigger_workflow_id,
            trial=trial,
            check_id=check_id,
            precheck_rows=precheck_rows,
            precheck_query_source=precheck_query_source,
        )
        trial_status = tasks_facade.TaskRunStatus.COMPLETED.value
        runtime_s = time.monotonic() - started
        emitted_count, _ = await database_sync_to_async(_read_run_metrics, thread_sensitive=False)(
            run_id, team.parent_team_id or team.id
        )
        # A run that got all the way through closes the breaker: the lane works, so any streak
        # it had accumulated is stale and a standing auto-pause is lifted (this is also how the
        # half-open probe recovers a paused lane once its underlying cause is fixed). Any
        # trigger counts, since a manual success is the natural way to revive a lane right
        # after fixing its skill.
        if trial is None:
            await database_sync_to_async(_clear_failure_streak, thread_sensitive=False)(config.pk)
        outcome_properties = (
            await database_sync_to_async(complete_first_report_investigation, thread_sensitive=False)(
                team.id, str(run_id)
            )
            if experiment is not None
            else {}
        )
        _capture_run_finished(
            team=team,
            config=config,
            skill=skill,
            github_guidance=github_guidance,
            business_knowledge_maintained=business_knowledge_maintained,
            strict_reviewer_selection=strict_reviewer_selection,
            background_backoff=backoff,
            run_id=run_id,
            task_run_id=task_run_id,
            status=tasks_facade.TaskRunStatus.COMPLETED.value,
            runtime_s=runtime_s,
            emitted_count=emitted_count,
            triggered_by=triggered_by,
            model=model,
            runtime_adapter=runtime_adapter,
            service_tier=service_tier,
            runtime=runtime,
            experiment=experiment,
            extra_properties=outcome_properties,
        )
        return RunResult(
            run_id=str(run_id),
            task_run_id=task_run_id,
            status=tasks_facade.TaskRunStatus.COMPLETED.value,
            last_message=last_message,
            runtime_s=runtime_s,
            skill_name=skill.name,
            skill_version=skill.version,
        )
    except Exception as exc:
        trial_status = tasks_facade.TaskRunStatus.FAILED.value
        runtime_s = time.monotonic() - started
        if trial is not None:
            cancelled_task_run_id = (
                exc.task_run_id
                if isinstance(exc, _TrialTaskCancelled)
                else await database_sync_to_async(_cancelled_trial_task_run_id, thread_sensitive=False)(
                    team_id=team.parent_team_id or team.id, run_id=run_id
                )
            )
            if cancelled_task_run_id is not None:
                trial_status = tasks_facade.TaskRunStatus.CANCELLED.value
                return RunResult(
                    run_id=str(run_id),
                    task_run_id=cancelled_task_run_id,
                    status=trial_status,
                    last_message=None,
                    runtime_s=runtime_s,
                    skill_name=skill.name,
                    skill_version=skill.version,
                )
        # A failure before the dispatch initializer fires means no row was persisted —
        # don't hand callers a run_id that resolves to nothing.
        row_persisted = await database_sync_to_async(_run_row_exists, thread_sensitive=False)(
            run_id, team.parent_team_id or team.id
        )
        # Fail safe and silent: the TaskRun MultiTurnSession spans carries the error
        # context (status=FAILED, error_message, full chat log via LLMA). Nothing
        # additional to persist on the bridge row.
        logger.exception(
            "signals_scout: run failed",
            extra={
                "team_id": team_id,
                "run_id": str(run_id),
                "skill_name": skill.name,
                "row_persisted": row_persisted,
            },
        )
        # A partial run can still have emitted (and have a linked TaskRun) before failing,
        # so read both from the bridge row when it exists; otherwise it never ran far
        # enough to persist either.
        emitted_count, failed_task_run_id = (
            await database_sync_to_async(_read_run_metrics, thread_sensitive=False)(
                run_id, team.parent_team_id or team.id
            )
            if row_persisted
            else (0, None)
        )
        # Advance the breaker before the event so the failure that trips it is the one whose
        # `error_message` explains the pause. Scheduled failures only: the threshold is sized
        # on the schedule's cadence, so counting off-schedule "run now" retries would let a
        # burst of them reach a slow lane's threshold in minutes and impose the probe cooldown
        # on a lane whose schedule never failed.
        streak = (
            await database_sync_to_async(_record_failure_streak, thread_sensitive=False)(config.pk)
            if triggered_by == TRIGGERED_BY_SCHEDULE
            else None
        )
        outcome_properties = (
            await database_sync_to_async(complete_first_report_investigation, thread_sensitive=False)(
                team.id, str(run_id)
            )
            if experiment is not None
            else {}
        )
        _capture_run_finished(
            team=team,
            config=config,
            skill=skill,
            github_guidance=github_guidance,
            business_knowledge_maintained=business_knowledge_maintained,
            strict_reviewer_selection=strict_reviewer_selection,
            background_backoff=backoff,
            run_id=run_id,
            task_run_id=failed_task_run_id,
            status=tasks_facade.TaskRunStatus.FAILED.value,
            runtime_s=runtime_s,
            emitted_count=emitted_count,
            triggered_by=triggered_by,
            model=model,
            runtime_adapter=runtime_adapter,
            service_tier=service_tier,
            runtime=runtime,
            experiment=experiment,
            error_type=type(exc).__name__,
            error_message=str(exc)[:300],
            extra_properties={**outcome_properties, **(_failure_properties(exc) or {})},
        )
        if streak is not None and streak.tripped:
            _capture_config_auto_paused(
                team=team,
                config=config,
                skill_name=skill.name,
                run_id=run_id,
                failure_count=streak.count,
                failure_streak_threshold=streak.threshold,
                reason=str(exc)[:300],
            )
        return RunResult(
            run_id=str(run_id) if row_persisted else None,
            task_run_id=None,
            status=tasks_facade.TaskRunStatus.FAILED.value,
            last_message=None,
            runtime_s=runtime_s,
            skill_name=skill.name,
            skill_version=skill.version,
        )
    except BaseException as exc:
        trial_status = tasks_facade.TaskRunStatus.CANCELLED.value
        # Cancellation / worker-shutdown / system-exit: re-raise so Temporal sees the
        # activity as failed. Post-collapse the bridge row's status flows from its
        # linked TaskRun (managed by MultiTurnSession), so we don't update anything
        # here directly. A TaskRun stranded in IN_PROGRESS (e.g. SIGKILL before
        # MultiTurnSession finalizes) blocks new runs for this (team, skill) via
        # `_has_running_run` until `_self_heal_stale_runs` reaps it past the stale cutoff.
        runtime_s = time.monotonic() - started
        logger.warning(
            "signals_scout: run cancelled mid-flight",
            extra={
                "team_id": team_id,
                "run_id": str(run_id),
                "skill_name": skill.name,
                "exception_type": type(exc).__name__,
                "runtime_s": runtime_s,
            },
        )
        # The failure-streak breaker is deliberately untouched: a cancelled run says nothing
        # about whether this lane can succeed, and counting worker shutdowns toward the streak
        # would pause healthy scouts after a few deploys.
        outcome_properties = (
            await database_sync_to_async(complete_first_report_investigation, thread_sensitive=False)(
                team.id, str(run_id)
            )
            if experiment is not None
            else {}
        )
        _capture_run_finished(
            team=team,
            config=config,
            skill=skill,
            github_guidance=github_guidance,
            business_knowledge_maintained=business_knowledge_maintained,
            strict_reviewer_selection=strict_reviewer_selection,
            background_backoff=backoff,
            run_id=run_id,
            task_run_id=None,
            status=tasks_facade.TaskRunStatus.CANCELLED.value,
            runtime_s=runtime_s,
            emitted_count=None,
            triggered_by=triggered_by,
            model=model,
            runtime_adapter=runtime_adapter,
            service_tier=service_tier,
            runtime=runtime,
            experiment=experiment,
            extra_properties=outcome_properties,
        )
        raise
    finally:
        if trial is not None:
            await asyncio.shield(
                database_sync_to_async(_export_trial_result_safely, thread_sensitive=False)(
                    team_id=team.parent_team_id or team.id, run_id=run_id, status=trial_status
                )
            )


async def arun_signals_scout(
    *,
    team_id: int,
    skill_name: str,
    skill_version: int | None = None,
    repository: str | None = None,
    verbose: bool = False,
    triggered_by: str = TRIGGERED_BY_SCHEDULE,
    run_note: str | None = None,
    trigger_workflow_id: str | None = None,
    agent_runtime: AgentRuntime | None = None,
    trial_launch_id: str | None = None,
    check_id: str | None = None,
    precheck_rows: str | None = None,
    precheck_query_source: str | None = None,
) -> RunResult:
    with private_capture_context() if trial_launch_id is not None else nullcontext():
        return await _arun_signals_scout(
            team_id=team_id,
            skill_name=skill_name,
            skill_version=skill_version,
            repository=repository,
            verbose=verbose,
            triggered_by=triggered_by,
            run_note=run_note,
            trigger_workflow_id=trigger_workflow_id,
            agent_runtime=agent_runtime,
            trial_launch_id=trial_launch_id,
            check_id=check_id,
            precheck_rows=precheck_rows,
            precheck_query_source=precheck_query_source,
        )


def _business_knowledge_maintained_for_team(team: Team) -> bool:
    """Whether this team's scouts get the business-knowledge section.

    `is_maintained_for_team`, not `is_available_for_team`: the section rides on every run, so a
    knowledge base a team tried once and abandoned would tax the whole lane forever. Resolved
    fresh per run so a flag flip, a first finished ingest, or a team returning to curate lands on
    the next run. Falls back to off on a read error rather than propagating: the resolved value
    forks the prompt and is stamped on the run row + both lifecycle events, so a raise would book a
    failed run and advance the streak over a section the run does not need. Swallowing here also
    keeps it safe to resolve in `arun_signals_scout` (outside the run's try/except), where the
    failure and cancellation paths read it back to report the shape the run got.
    """
    try:
        return is_maintained_for_team(team)
    except Exception as error:
        capture_exception(error)
        return False


def _project_has_governed_metrics(team: Team, user_id: int) -> bool:
    """Whether the run's prompt should mention the data catalog.

    Resolved as the run's acting user, the same identity the sandbox's MCP token carries, so the
    prompt never points a run at metrics it could not read for itself. A failed read is False:
    the mention is optional steering, so an outage must not fail the run or mis-steer it.
    """
    try:
        return bool(approved_metric_names_for_team(team, User.objects.get(id=user_id)))
    except Exception as error:
        capture_exception(error)
        return False


ACTIVITY_SUMMARY_SEARCH_TOOL = "activity-summary-search"


def _activity_summary_search_available(team: Team, mcp_tool_allowlist: list[str] | None) -> bool:
    """Whether the run's prompt should name `activity-summary-search` for reviewer routing.

    True only when the team can search and the run holds the tool, so the prompt never names a tool
    the run cannot call. A failed check is False: the mention is optional steering.
    """
    try:
        if mcp_tool_allowlist is not None and ACTIVITY_SUMMARY_SEARCH_TOOL not in scout_held_mcp_tools(
            mcp_tool_allowlist
        ):
            return False
        return searchable_config(team) is not None
    except Exception as error:
        capture_exception(error)
        return False


def _report_tags_in_use(team: Team, *, report_channel: bool) -> list[str]:
    """The team's report tags for the prompt, or none for a signal-channel scout.

    A failed read is an empty list: the listing is optional steering, so an outage must not fail the run.
    """
    if not report_channel:
        return []
    try:
        return scout_report_tags_in_use(team_id=team.id)
    except Exception as error:
        capture_exception(error)
        return []


def _granted_write_scopes(config: SignalScoutConfig) -> list[str]:
    """The extra write scopes this scout's next run actually holds.

    Read through `scout_scope_posture` rather than off the column, so the prompt, the run row, and
    the analytics events can never name a scope the token drops — a grant made before the allowlist
    narrowed stops reaching all four at once. A dry run (`emit=False`) holds no grant at all: dry
    run exists so a person can watch what a scout would do before it reaches the inbox, and a
    dry run that edits dashboards has already done the thing they wanted to preview.
    """
    return scout_scope_posture("signals_scout", _write_scopes_for_run(config))["extra_write_scopes"]


def _write_scopes_for_run(config: SignalScoutConfig) -> object:
    """The stored grant as the posture builder should see it, or nothing for a dry run.

    Returns the column value unshaped so that the posture builder's own type check is what decides
    what a malformed value grants. Coercing here would turn a stray JSON object into its keys.
    """
    return config.write_scopes if config.emit else []


def _mcp_tool_allowlist_for_run(team: Team, config: SignalScoutConfig) -> list[str] | None:
    """The tool list this run is narrowed to, or None to leave it on its token scopes alone.

    Gated on the same flag that gates writing the list, so a list saved while a team had the flag
    stops applying when the flag goes off. Read once per run: a config edit applies from the next run.
    """
    if config.allowed_mcp_tools is None or not scout_tool_access_enabled(team):
        return None
    if not isinstance(config.allowed_mcp_tools, list):
        return []
    return [tool for tool in config.allowed_mcp_tools if isinstance(tool, str)]


def _mcp_server_names_for_run(team: Team, user_id: int, config: SignalScoutConfig) -> list[str]:
    """Names of the external MCP servers this run's sandbox will mount, for prompt steering.

    Mirrors the launch path's resolution parameter for parameter (`start_agent_server` →
    `get_installations_for_sandbox`): same origin and agent key, no credential owner, the
    per-scout server selection, and the personal-inclusion posture of a non-internal task —
    so the prompt names exactly the servers the sandbox mounts. A resolution error degrades
    to an empty list rather than propagating, for the same reason as the flag fallback above:
    the servers still mount (or not) at launch regardless, so the fallback only costs steering.
    """
    try:
        return get_sandbox_mcp_server_names(
            team.id,
            user_id=user_id,
            include_personal=True,
            task_origin=tasks_facade.TaskOriginProduct.SIGNALS_SCOUT,
            task_agent_key="scout",
            credential_owner_id=None,
            allowed_gateway_server_ids=[str(server_id) for server_id in (config.mcp_gateway_server_ids or [])],
        )
    except Exception as error:
        capture_exception(error)
        return []


@frozen
class _GithubPosture:
    """What one scout run gets from GitHub: the repositories its sandbox clones, and whether the
    prompt may name `gh`."""

    repositories: list[str]
    prompt_names_gh: bool


async def _resolve_github_posture(
    *,
    team: Team,
    config: SignalScoutConfig,
    skill: LoadedSkill,
    repository_override: str | None,
) -> _GithubPosture:
    """Decide what this run can read on GitHub, before the sandbox is spawned.

    `repositories` are cloned into the sandbox, so the agent works on a tree instead of reading
    code one `gh api` call at a time. The scout's own pin is the cadence path; the management
    command's `--repository` override wins, so an ad-hoc investigation can aim a scout at one repo
    without editing its config.

    `prompt_names_gh` gates the `gh` evidence section on report-channel scouts whose team passes
    the `github_read_access` posture in the `signals-scout` flag payload (default on; per-team or
    fleet-wide `false` is the kill switch, resolved against the canonical project id) AND a mint
    preflight, since the prompt must not name `gh` when the team has no usable installation to
    mint from (the scout would burn budget on 401s before falling back).

    That same preflight decides whether a pin can be honored: a scout clones with the read-only
    mint, so without a mintable installation the clone would fail on every run. The pin is dropped
    in that case and the run goes ahead repo-less rather than wedging the lane on clone failures.
    The prompt reads this same list, so the agent is never told about a checkout it does not have.
    """
    repositories = [repository_override] if repository_override else list(config.repositories or [])
    names_gh = skill_uses_report_channel(skill.allowed_tools) and await database_sync_to_async(
        github_read_access_for_team, thread_sensitive=False
    )(team.parent_team_id or team.id)
    if not names_gh and not repositories:
        return _GithubPosture(repositories=[], prompt_names_gh=False)
    can_mint = await database_sync_to_async(tasks_facade.can_mint_readonly_github_token, thread_sensitive=False)(
        team.id
    )
    if repositories and not can_mint:
        # The public allowlist clones without a token, so `--repository posthog/.github` still
        # works on a team that never connected GitHub.
        public = [repository for repository in repositories if tasks_facade.is_public_sandbox_repo(repository)]
        if len(public) != len(repositories):
            logger.info(
                "signals_scout: dropping pinned repositories, no mintable GitHub installation",
                extra={"team_id": team.id, "skill_name": skill.name, "repositories": repositories},
            )
        repositories = public
    return _GithubPosture(repositories=repositories, prompt_names_gh=names_gh and can_mint)


async def _spawn_and_run(
    *,
    team: Team,
    config: SignalScoutConfig,
    run_id: Any,
    started_at: Any,
    skill: LoadedSkill,
    repositories: list[str],
    verbose: bool,
    user_id: int,
    github_guidance: bool,
    business_knowledge_maintained: bool,
    strict_reviewer_selection: bool,
    model: str | None,
    background_backoff: BackgroundBackoff | None = None,
    runtime_adapter: str | None = None,
    reasoning_effort: str | None = None,
    service_tier: str | None = None,
    runtime: str = "acp",
    experiment: FirstReportExperiment | None = None,
    triggered_by: str = TRIGGERED_BY_SCHEDULE,
    run_note: str | None = None,
    trigger_workflow_id: str | None = None,
    trial: TrialLaunch | None = None,
    check_id: str | None = None,
    precheck_rows: str | None = None,
    precheck_query_source: str | None = None,
) -> tuple[str, str]:
    """Spawn the sandbox, create the bridge row before the first turn, run the agent.

    `user_id` is the acting user resolved (and validated non-None) by the caller. `model`,
    `runtime_adapter`, and `reasoning_effort` are the agent runtime overrides (`model` paired with the
    `runtime_adapter` that serves it — the agent server derives the provider from it; all `None` keeps
    the agent-server default Claude runtime). Returns `(last_message, task_run_id)`.
    """
    # The config's `network_access` picks the sandbox env — and with it the egress policy the
    # provisioning layer enforces. Trusted (default) shares the research env; full gets its own
    # env name so its unrestricted policy can't be reasserted onto the shared one.
    github_optional = await database_sync_to_async(ResearchAccessPolicy.enabled, thread_sensitive=False)(team.id)
    if config.network_access == SignalScoutConfig.NetworkAccess.FULL:
        sandbox_env_name = SIGNALS_SCOUT_FULL_NETWORK_ENV_NAME
        network_access_level = tasks_facade.SandboxNetworkAccessLevel.FULL
    else:
        sandbox_env_name = SIGNALS_SCOUT_SANDBOX_ENV_NAME
        network_access_level = tasks_facade.SandboxNetworkAccessLevel.TRUSTED
    sandbox_env_id = await database_sync_to_async(get_or_create_signals_sandbox_env, thread_sensitive=False)(
        team.id,
        sandbox_env_name,
        network_access_level,
    )
    report_channel = skill_uses_report_channel(skill.allowed_tools)
    # `write_scopes` adds the user-facing writes this ONE scout was granted from its settings, so a
    # scout asked to maintain dashboards can change them. Everything else about the posture is
    # identical across the fleet. Composed once here, because the token, the prompt, and the run row
    # all have to read the same grant — `scout_scope_posture` drops anything the allowlist no longer
    # holds, and mint time intersects it again. A dry run gets no grant (see `_write_scopes_for_run`).
    scope_posture = scout_scope_posture(
        "signals_scout_reports" if report_channel else "signals_scout",
        _write_scopes_for_run(config),
    )
    # Resolved once, because the task stamp, the run row, and the prompt must all read the same list.
    mcp_tool_allowlist = (
        None
        if trial is not None
        else await database_sync_to_async(_mcp_tool_allowlist_for_run, thread_sensitive=False)(team, config)
    )
    # Scout sandboxes never get the write-capable installation token: task creation attaches the
    # team's GitHub integration to every task, so without this request a scout run on a
    # GitHub-connected team is silently provisioned with the FULL token. Requesting read access on
    # every scout run downscopes that to a read-only mint (or nothing when the mint fails) —
    # a strict privilege reduction, independent of the prompt-guidance flag below.
    #
    # `repositories` does not weaken that. Provisioning keys the downscope on the request alone,
    # so a scout that pins repos clones them with a `contents: read` token: it gets a working tree
    # it can read, build, and test, and still cannot push, comment, or open a pull request. Write
    # capability for a scout stays a separate opt-in nobody has yet.
    #
    # The `gh` guidance in the prompt is gated separately: report-channel scouts only, the
    # `github_read_access` posture in the `signals-scout` flag payload (default on; per-team or
    # fleet-wide `false` is the kill switch — resolved against the canonical project id, like
    # every flag-payload lookup), AND a mint preflight — the prompt must not name `gh` when the
    # team has no usable installation to mint from (the scout would burn budget on 401s before
    # falling back).
    context = CustomPromptSandboxContext(
        team_id=team.id,
        user_id=user_id,
        repositories=tuple(repositories),
        sandbox_environment_id=sandbox_env_id,
        # `signals_scout` is the harness's own scope posture: project reads +
        # INTERNAL_SCOPES + the scout's `signal_scout_internal:write`. User-facing writes,
        # notebooks included, come only from the per-scout grant in `scope_posture`. It reports
        # `has_write_scopes=True` so the MCP server doesn't enable read-only-mode tool
        # filtering. Without that opt-out, the MCP layer would categorically strip every
        # tool annotated `readOnlyHint: false` — including the agent's own `remember`,
        # `forget`, and `emit_finding` tools — even though the OAuth token does carry the
        # right scope to call them.
        #
        # A scout that opted into the report channel gets `signals_scout_reports` instead —
        # the same posture plus `signal_scout_report:write` — so the MCP server exposes the
        # emit_report/edit_report tools. Every other scout gets plain `signals_scout` and never
        # sees them. Dispatched as the preset string unless this scout holds a grant, so a scout
        # without one never depends on the sandbox worker reading the posture dict.
        posthog_mcp_scopes="signals_scout_experiment" if trial is not None else scout_mcp_scopes(scope_posture),
        github_read_access=True,
        # `None` keeps the agent-server default; an override pins the whole run on one model
        # (the `scouts-model-selection` gate routes it here). The model the gateway actually serves
        # is tagged on each $ai_generation, so per-run model is queryable in LLM analytics.
        model=model,
        # Paired with `model`: the agent server derives the LLM provider from the runtime.
        runtime_adapter=runtime_adapter,
        reasoning_effort=reasoning_effort,
        # Codex-only, and independent of the model pin: which OpenAI queue the run's turns join.
        service_tier=service_tier,
        runtime=runtime,
        sandbox_timeout_seconds=TRIAL_ACTIVITY_TIMEOUT_S + 60 if trial is not None else None,
    )
    project_has_governed_metrics = await database_sync_to_async(_project_has_governed_metrics, thread_sensitive=False)(
        team, user_id
    )
    mcp_server_names = await database_sync_to_async(_mcp_server_names_for_run, thread_sensitive=False)(
        team, user_id, config
    )
    report_tags_in_use = await database_sync_to_async(_report_tags_in_use, thread_sensitive=False)(
        team, report_channel=report_channel
    )
    activity_summary_search = report_channel and await database_sync_to_async(
        _activity_summary_search_available, thread_sensitive=False
    )(team, mcp_tool_allowlist)
    prompt = build_run_prompt(
        skill,
        run_id=str(run_id),
        team_id=team.id,
        started_at=started_at,
        project_timezone=team.timezone,
        github_read_access=github_guidance,
        project_has_governed_metrics=project_has_governed_metrics,
        activity_summary_search_available=activity_summary_search,
        # Names the external MCP servers the sandbox will mount, so *How to call tools* can carve
        # them out of the exec-interface rule; empty renders nothing.
        mcp_server_names=mcp_server_names,
        business_knowledge_maintained=business_knowledge_maintained,
        strict_reviewer_selection=strict_reviewer_selection,
        # Renders the structured-output section (schema + `scout-record-output` contract) only
        # when the config carries a schema AND emit is on — records land solely as project
        # events, so a dry-run scout must not be steered at a tool that fails closed.
        structured_output_schema=(config.structured_output_schema if config.emit else None),
        # Names the objects this scout may change, so it acts on them and reports what it changed.
        # Resolved through the same allowlist the token is, so the prompt can never promise write
        # access the token does not carry.
        write_scopes=scope_posture["extra_write_scopes"],
        tool_allowlist_narrowed=mcp_tool_allowlist is not None,
        run_note=run_note,
        trigger_workflow_id=trigger_workflow_id,
        # The repositories the sandbox clones, so the prompt can point the agent at the checkout
        # instead of leaving it to discover the tree. Same list the sandbox context carries, so
        # the prompt can never describe a tree the run does not have.
        repositories=repositories,
        # Frames the note: a check dispatch carries an assignment the run has to answer, where a
        # manual trigger carries a nudge a person typed alongside the scout's usual work.
        triggered_by=triggered_by,
        is_private_trial=trial is not None,
        precheck_rows=precheck_rows,
        report_tags_in_use=report_tags_in_use,
    )
    logger.info(
        "signals_scout: spawning sandbox",
        extra={
            "team_id": team.id,
            "skill_name": skill.name,
            "skill_version": skill.version,
            "skill_id": skill.skill_id,
            "allowed_tools": skill.allowed_tools,
        },
    )

    def _create_bridge_row(task_run_id: UUID) -> None:
        _create_run_row(
            run_id=run_id,
            task_run_id=task_run_id,
            team=team,
            config=config,
            skill=skill,
            model=model,
            runtime_adapter=runtime_adapter,
            reasoning_effort=reasoning_effort,
            service_tier=service_tier,
            runtime=runtime,
            experiment=experiment,
            github_guidance=github_guidance,
            github_optional=github_optional,
            business_knowledge_maintained=business_knowledge_maintained,
            strict_reviewer_selection=strict_reviewer_selection,
            background_backoff=background_backoff,
            repositories=repositories,
            triggered_by=triggered_by,
            run_note=run_note,
            trigger_workflow_id=trigger_workflow_id,
            trial=trial,
            check_id=check_id,
            precheck_query_source=precheck_query_source,
            mcp_tool_allowlist=mcp_tool_allowlist,
        )
        # Lifecycle start marker. The row + TaskRun now exist and the run has cleared the
        # reap + single-flight guards, so this counts exactly the runs that actually start —
        # a skipped dispatch emits nothing. Pairs with `signals_scout_run_finished` for
        # event-derived throughput and stall detection (started with no finished = a run
        # that died before finalize), with no warehouse-sync lag.
        transaction.on_commit(
            lambda: _capture_run_started(
                team=team,
                config=config,
                skill=skill,
                github_guidance=github_guidance,
                business_knowledge_maintained=business_knowledge_maintained,
                strict_reviewer_selection=strict_reviewer_selection,
                background_backoff=background_backoff,
                run_id=run_id,
                task_run_id=str(task_run_id),
                triggered_by=triggered_by,
                model=model,
                runtime_adapter=runtime_adapter,
                service_tier=service_tier,
                runtime=runtime,
                experiment=experiment,
            )
        )

    summary_model = FirstReportScoutRunSummary if skill.name == FIRST_REPORT_SCOUT else SignalScoutRunSummary
    session, result = await MultiTurnSession.start(
        prompt=prompt,
        context=context,
        model=summary_model,
        step_name=_step_name(skill),
        verbose=verbose,
        origin_product=tasks_facade.TaskOriginProduct.SIGNALS_SCOUT,
        internal=skill.name == FIRST_REPORT_SCOUT,
        mcp_builtin_agent_key="scout",
        # No credential owner on purpose: a scout is a team resource, so its runs mount only
        # connections members shared to the whole team, never anyone's personal grants. That
        # keeps runs identical no matter who created or edits the scout, and covers ownerless
        # coordinator-discovered scouts. The per-scout selection below picks which of those
        # team-shared servers this scout's runs mount. Empty selects none.
        mcp_gateway_server_ids=[str(server_id) for server_id in (config.mcp_gateway_server_ids or [])],
        mcp_tool_allowlist=mcp_tool_allowlist,
        # Tag every scout $ai_generation with its stage AND its scout, so scout spend is both
        # splittable out of the ai_product='signals' bucket (scouts carry no signal_report_id)
        # and attributable to one scout. Team attribution rides along as `team_id`.
        ai_stage=_ai_stage(skill),
        # `ai_stage` collapses team-authored scouts to `scout:custom` to bound a fleet-wide tag's
        # cardinality, so it cannot name one. `ai_agent_name` is read per team and carries the
        # full skill name for canonical and custom scouts alike.
        ai_agent_name=skill.name,
        before_task_dispatch=_create_bridge_row,
        origin_key=(
            "first-report"
            if skill.name == FIRST_REPORT_SCOUT
            else f"scout-trial:{trial.id}"
            if trial is not None
            else None
        ),
        # Leave the activity's cleanup allowance after the scout's own timeout.
        max_poll_seconds=(
            FIRST_REPORT_SCOUT_TIMEOUT_SECONDS
            if skill.name == FIRST_REPORT_SCOUT
            else TRIAL_MAX_RUNTIME_S
            if trial is not None
            else DEFAULT_MAX_RUNTIME_S
        ),
        # The close-out is free-text markdown — if the agent ends with prose or malformed JSON
        # instead of a SignalScoutRunSummary object, keep the raw text as the summary rather than
        # failing the whole run. A failed run never finalizes, so its scan-position close-out is
        # lost and the next run inherits a doubled scan delta.
        fallback_from_text=lambda text: (
            FirstReportScoutRunSummary(summary=text, first_report_result=FirstReportScoutResult(outcome="incomplete"))
            if skill.name == FIRST_REPORT_SCOUT
            else SignalScoutRunSummary(summary=text)
        ),
    )
    end_status = "completed"
    end_error: str | None = None
    try:
        if trial is not None:
            invalid_reason = await database_sync_to_async(_trial_invalid_reason, thread_sensitive=False)(
                team_id=team.parent_team_id or team.id, run_id=run_id, trial=trial
            )
            if invalid_reason:
                raise ValueError(invalid_reason)
        # Persist the agent's end-of-turn close-out so non-emitting runs leave a
        # discoverable trace for future-run dedupe. Failure paths skip this on
        # purpose — the bridge row keeps its empty default and the linked TaskRun
        # carries the error context.
        await database_sync_to_async(_finalize_run_row, thread_sensitive=False)(
            run_id=run_id,
            team_id=team.parent_team_id or team.id,
            summary=result.summary,
            trial=trial is not None,
            first_report_result=result.first_report_result if isinstance(result, FirstReportScoutRunSummary) else None,
        )
        return result.summary, str(session.task_run.id)
    except BaseException as error:
        end_status = (
            "failed" if isinstance(error, Exception) and not isinstance(error, _TrialTaskCancelled) else "cancelled"
        )
        end_error = str(error)
        raise
    finally:
        if end_status == "completed":
            await session.end()
        else:
            await asyncio.shield(session.end(status=end_status, error=end_error))


def _get_team(team_id: int) -> Team:
    return Team.objects.select_related("organization").get(id=team_id)


def _resolve_config(team: Team, skill_name: str) -> SignalScoutConfig:
    """Get-or-create the (team, skill) config row, keyed on the canonical (parent) team.

    `get_or_create`'s lookup half isn't canonicalized by the TeamScopedRootMixin `save()`,
    so resolve to the parent id ourselves — else a child-team lookup misses the stored row
    and tries to create a duplicate, raising IntegrityError on the unique constraint.
    """
    config, _ = SignalScoutConfig.objects.unscoped().get_or_create(
        team_id=team.parent_team_id or team.id, skill_name=skill_name
    )
    return config


def _has_running_run(*, team_id: int, skill_name: str) -> bool:
    # Locked on (canonical team, skill_name) — different skills for the same team are
    # allowed to fan out (the coordinator can dispatch several due scouts per tick). Status flows
    # from the linked TaskRun now that SignalScoutRun is just a bridge; treat both QUEUED
    # and IN_PROGRESS as active, since a TaskRun sits in QUEUED before transitioning and a
    # second trigger landing in that window would otherwise slip past the guard. Not keyed
    # on `scout_config_id`: configs are `on_delete=SET_NULL`, so a config delete/recreate
    # mid-run would orphan the FK and silently defeat the dedupe in exactly the
    # config-churn case it should still cover.
    # A run older than `STALE_RUN_CUTOFF_S` is an orphan that `_self_heal_stale_runs` reaps just
    # before this check, so it does not count.
    lane_runs = (
        SignalScoutRun.objects.unscoped()
        .filter(team_id=team_id, skill_name=skill_name)
        .exclude(metadata__has_key=SCOUT_TRIAL_METADATA_KEY)
    )
    return lane_has_live_run(lane_runs)


def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:
    """Reap orphaned in-flight runs so a dead run can't block the lane forever.

    A scout run writes its own terminal `task_run.status` from inside the activity. If the
    worker / sandbox dies hard mid-run (SIGKILL, pod eviction, sandbox loss), that write
    never lands and the TaskRun is frozen at `QUEUED`/`IN_PROGRESS`. `_has_running_run`
    single-flights against that frozen row until `STALE_RUN_CUTOFF_S`, and the row stays
    unreported unless this reap closes it. Nothing else reconciles it:
    Temporal has already torn the workflow down (the activity is killed at
    `WORKFLOW_HARD_CEILING_S` with `maximum_attempts=1`), and the Tasks cleanup path does
    not cover a crashed worker.

    A run older than `STALE_RUN_CUTOFF_S` (a generous multiple of that ceiling) cannot
    still be legitimately executing, so it is an orphan and we mark it failed. The cutoff's
    slack means a run merely at the wall — about to fail or finish on its own — is never
    reaped out from under itself. Best-effort and silent: a failure to reap one row must
    never block the new run, so each is guarded independently.

    A worker death also strands runs that no longer block the lane. Once the agent goes idle,
    the Tasks inactivity timeout closes the TaskRun as `COMPLETED` or `FAILED`, often before
    the next dispatch. The scout never ends its own session through that timeout, because
    every path that survives signals completion, so that marker means the run lost its driver
    and never emitted `signals_scout_run_finished`. Those runs are reported too, once each.

    The reap reads only the lane's newest `ORPHAN_RECENT_RUNS` runs. This runs before every
    dispatch, so an orphan is one of the newest runs when the next dispatch comes.
    """
    now = timezone.now()
    cutoff = now - timedelta(seconds=STALE_RUN_CUTOFF_S)
    active_statuses = (tasks_facade.TaskRunStatus.QUEUED, tasks_facade.TaskRunStatus.IN_PROGRESS)
    # Read the IDs before the join, not as a subquery, so the join starts from these few runs and not
    # from `posthog_task_run`.
    recent_run_ids = list(
        SignalScoutRun.objects.unscoped()
        .filter(team_id=team_id, skill_name=skill_name)
        .exclude(metadata__has_key=SCOUT_TRIAL_METADATA_KEY)
        .order_by("-created_at")
        .values_list("id", flat=True)[:ORPHAN_RECENT_RUNS]
    )
    if not recent_run_ids:
        return
    closed_by_inactivity = Q(
        task_run__status__in=(tasks_facade.TaskRunStatus.COMPLETED, tasks_facade.TaskRunStatus.FAILED),
        **{f"task_run__state__{tasks_facade.TIMED_OUT_INACTIVITY_STATE_KEY}": True},
    )
    stale_runs = list(
        SignalScoutRun.objects.unscoped()
        .filter(team_id=team_id, id__in=recent_run_ids, task_run__created_at__lt=cutoff)
        .filter(Q(task_run__status__in=active_statuses) | closed_by_inactivity)
        .exclude(metadata__has_key=SCOUT_RUN_REAPED_METADATA_KEY)
        .select_related("task_run")
    )
    if not stale_runs:
        return
    from products.signals.backend.tasks import (
        settle_scout_spend,  # noqa: PLC0415 - avoids loading the Celery task registry when importing the runner
    )

    # Resolve the team once, only when there is actually something to reap, so the reaped
    # event carries the same team / groups shape as the other scout lifecycle events.
    team = _get_team(team_id)
    for run in stale_runs:
        try:
            task_run = run.task_run
            # Read the pre-reap status / age off the loaded bridge instance before the claim:
            # the conditional update below doesn't refresh it, so these stay the original values.
            status_before = task_run.status
            age_seconds = (now - task_run.created_at).total_seconds()
            # Compare-and-set claim, on the status transition for a live TaskRun and on the
            # bridge row for a closed one. Two triggers for the same `(team, skill)` can reach
            # this self-heal concurrently and load the same stale row; the conditional UPDATE
            # lets exactly one win — the other matches zero rows. Only the winner falls through
            # to emit, so a single stranded run can't double-count in the worker-death signal.
            if status_before in active_statuses:
                claimed = tasks_facade.claim_and_fail_stale_run(
                    task_run.id,
                    "Scout run abandoned: no terminal status past the runtime ceiling "
                    "(worker/sandbox lost before finalize).",
                    error_type="stale_run_reaped",
                )
            else:
                claimed = _claim_finished_orphan(run_id=run.id, team_id=team_id)
            if not claimed:
                continue
            logger.warning(
                "signals_scout: reaped stale in-progress run before dispatch",
                extra={
                    "team_id": team_id,
                    "skill_name": skill_name,
                    "run_id": str(run.id),
                    "task_run_id": str(run.task_run_id),
                },
            )
            # A reaped run never reaches the finalize path, so it emits no
            # `signals_scout_run_finished`. This event makes the strand observable with no
            # warehouse lag — a spike is the worker-death / mass-stall shape, caught within a
            # tick of the cutoff rather than days late.
            _capture_run_reaped(
                team=team,
                skill_name=skill_name,
                run_id=run.id,
                task_run_id=str(run.task_run_id),
                status_before=status_before,
                age_seconds=age_seconds,
            )
            transaction.on_commit(partial(settle_scout_spend.delay, team_id=team_id, run_id=str(task_run.id)))
        except Exception:
            logger.exception(
                "signals_scout: failed to reap stale in-progress run; continuing",
                extra={"team_id": team_id, "skill_name": skill_name, "run_id": str(run.id)},
            )


def _claim_finished_orphan(*, run_id: Any, team_id: int) -> bool:
    """Compare-and-set claim on a run whose TaskRun is already terminal. Returns whether this caller won.

    The TaskRun status cannot carry the claim here, so the bridge row does: the conditional
    update stamps `SCOUT_RUN_REAPED_METADATA_KEY` only while it is absent, and the loser of a
    concurrent reap matches zero rows.
    """
    stamp = Value({SCOUT_RUN_REAPED_METADATA_KEY: timezone.now().isoformat()}, output_field=JSONField())
    return bool(
        SignalScoutRun.objects.unscoped()
        .filter(team_id=team_id, id=run_id)
        .exclude(metadata__has_key=SCOUT_RUN_REAPED_METADATA_KEY)
        .update(
            metadata=Func(
                Coalesce(F("metadata"), Value({}, output_field=JSONField())),
                stamp,
                arg_joiner=" || ",
                template="(%(expressions)s)",
                output_field=JSONField(),
            ),
            updated_at=timezone.now(),
        )
    )


def _create_run_row(
    *,
    run_id: Any,
    task_run_id: UUID,
    team: Team,
    config: SignalScoutConfig,
    skill: LoadedSkill,
    model: str | None = None,
    runtime_adapter: str | None = None,
    reasoning_effort: str | None = None,
    service_tier: str | None = None,
    runtime: str = "acp",
    experiment: FirstReportExperiment | None = None,
    github_guidance: bool = False,
    github_optional: bool = False,
    business_knowledge_maintained: bool = False,
    strict_reviewer_selection: bool = False,
    background_backoff: BackgroundBackoff | None = None,
    repositories: list[str] | None = None,
    triggered_by: str = TRIGGERED_BY_SCHEDULE,
    run_note: str | None = None,
    trigger_workflow_id: str | None = None,
    trial: TrialLaunch | None = None,
    check_id: str | None = None,
    precheck_query_source: str | None = None,
    mcp_tool_allowlist: list[str] | None = None,
) -> SignalScoutRun:
    # Stamp the routed model triple (and the OpenAI queue it asked for) onto the row's `metadata`
    # so "which model ran this?" is a column read on the run API, not an analytics-event join. Keys
    # are omitted (not null-valued) on the default path, so their absence means the agent-server
    # default served the run.
    metadata: dict[str, Any] = {
        key: value
        for key, value in (
            ("model", model),
            ("runtime_adapter", runtime_adapter),
            ("reasoning_effort", reasoning_effort),
            ("service_tier", service_tier),
        )
        if value is not None
    }
    metadata["runtime"] = runtime
    if experiment is not None:
        metadata.update(experiment.properties())
    # Stamped only when non-default, like the model triple: absence means the run held the
    # trusted-domains posture. Stamped (rather than read off the config later) because the
    # config row can be edited after the fact, which would silently rewrite what past runs
    # could actually reach.
    if config.network_access == SignalScoutConfig.NetworkAccess.FULL:
        metadata["network_access"] = config.network_access
    # The three dimensions that pin down which instructions this run actually got. All are
    # point-in-time facts that become unrecoverable later, which is why they are stamped rather
    # than resolved at read time: the harness prompt has no version history, a skill's
    # `allowed_tools` can be edited (so an old run's channel can't be re-derived), and a seeded
    # canonical row flips to `custom` the moment a team edits it, taking every past run's origin
    # with it. Together they let runs be compared only against runs that got the same prompt
    # shape, which is what a model or prompt A/B needs to hold constant.
    metadata["harness_prompt_version"] = HARNESS_PROMPT_VERSION
    metadata["report_channel"] = resolve_report_channel_variant(skill.allowed_tools)
    metadata["skill_origin"] = skill.origin
    # Whether the run got the gh evidence section, which `_spawn_and_run` includes or omits from
    # the whole prompt based on the team's flag posture and whether a read-only token could be
    # minted. Both can change between runs, so this is a fourth composition fork rather than a
    # property of the build.
    metadata["github_guidance"] = github_guidance
    metadata["github_optional"] = github_optional
    # Whether the business-knowledge section rendered — a fifth composition fork, resolved per run
    # from the team's flag + a maintained knowledge base (`_business_knowledge_maintained_for_team`).
    # Both inputs can change between runs, so like `github_guidance` this is stamped rather than
    # re-derived at read time, letting an eval or A/B compare only runs that got the same prompt.
    metadata["business_knowledge_maintained"] = business_knowledge_maintained
    # Which reviewer-routing guidance the run got (evidence-only for the trial arm, legacy otherwise),
    # stamped because the flag can change between runs.
    metadata["strict_reviewer_selection"] = strict_reviewer_selection
    # Stamped only for background-managed scouts, because a person who edits the config takes it over
    # and deleting it nulls `scout_config`. Reports this run authors keep their background origin.
    if config.managed_by == SignalScoutConfig.ManagedBy.BACKGROUND:
        metadata["managed_by"] = config.managed_by
        # The band that sampled the project, so each band's pilot reads on its own. Absent for a
        # hand-picked `team_ids` project.
        if config.background_band is not None:
            metadata["background_band"] = config.background_band
        metadata.update(_background_backoff_props(config, background_backoff))
    # Dispatch-time snapshot of the structured-output contract. The prompt renders this exact
    # schema, so the record endpoint validates against the snapshot rather than the live config
    # value — a mid-run schema edit must not reject records that match what the run was shown.
    # Clearing the config's schema entirely still fails the channel closed mid-run (the kill
    # switch); see `tools/structured_output._resolve_schema`. Gated on `emit` like the prompt
    # section: records land solely as project events, so a dry-run scout has no channel.
    if config.structured_output_schema and config.emit:
        metadata["structured_output_schema"] = config.structured_output_schema
    # Dispatch-time snapshot of what this run could write, stamped like the network posture and for
    # the same reason: the config's grant can be widened or revoked afterwards, which would rewrite
    # what past runs are recorded as having been able to change. Omitted when the scout holds no
    # grant, so absence reads as "the fleet posture".
    if granted_write_scopes := _granted_write_scopes(config):
        metadata["write_scopes"] = granted_write_scopes
    # The tool list the run was narrowed to, stamped next to the write grant for the same reason.
    # Omitted when the run was not narrowed, so absence reads as "every tool the scopes allow".
    if mcp_tool_allowlist is not None:
        metadata["allowed_mcp_tools"] = sorted(set(mcp_tool_allowlist))
    # Which tree the run was looking at, so a reader of its report can tell. Stamped rather than
    # read off the config, for the same reason as the write grant: the pin can be edited or
    # dropped afterwards, and this is the only record of what a past run actually cloned. Omitted
    # when the run was repo-less, so absence reads as "no checkout".
    if repositories:
        metadata["repositories"] = list(repositories)
    # Omitted on the default path like the model triple, so absence reads as "the schedule".
    # Load-bearing for the workflow path specifically: its 30-minute cooldown counts prior
    # *workflow*-triggered runs of this (team, skill), and this is the only record of which those
    # were — a scheduled patrol or a human's "Run now" must not extend it.
    if triggered_by != TRIGGERED_BY_SCHEDULE:
        metadata["triggered_by"] = triggered_by
    # The only record of which workflow spent the run, so its author can find the runs it started.
    if trigger_workflow_id:
        metadata["trigger_workflow_id"] = trigger_workflow_id
    # The only record of why a manual run behaved differently from the scheduled ones around it,
    # because the note is deliberately never stored as a scout note.
    if run_note:
        metadata["run_note"] = run_note
    if trial is not None:
        metadata[SCOUT_TRIAL_METADATA_KEY] = {
            "version": 1,
            "launch_id": str(trial.id),
            "context_id": str(trial.context_id),
            "variant": trial.variant,
        }
    # The check a coordinator dispatch was started to answer. `scout-check-record-result` and
    # `scout-report-check-list` read it to tie the check to this run.
    if check_id:
        metadata["check_id"] = check_id
    # Which pre-check started this run (`config` or `skill_default`), so run outcomes can be split
    # by it. Absent when no pre-check ran.
    if precheck_query_source:
        metadata["precheck_query_source"] = precheck_query_source
    with transaction.atomic():
        run = SignalScoutRun.objects.for_team(team.id).create(
            id=run_id,
            task_run_id=task_run_id,
            team=team,
            scout_config=config,
            skill_name=skill.name,
            skill_version=skill.version,
            metadata=metadata,
            trial_state=initial_trial_state() if trial is not None else None,
        )
        record_task_spend(team_id=team.id, run_id=str(task_run_id), scout_run_id=str(run.id), stage="scout")
    return run


@dataclass(frozen=True)
class _FailureStreak:
    """Breaker state after a failed run. `tripped` is the *transition* into paused, not the
    paused state itself — a re-failed probe leaves the status where it is without tripping
    again, so the alerting event fires once per wedge rather than once per doomed run."""

    count: int
    tripped: bool
    threshold: int


def _clear_failure_streak(config_id: Any) -> None:
    """Zero the breaker after a successful run and lift its pause. Best-effort: the run
    succeeded, so a bookkeeping failure here must not turn it into a failure. The streak reset
    is filtered so the common case (a healthy lane) does no write at all; the resume goes
    through the transition helper, whose reason scoping means only the breaker's own
    `repeated_failures` pause can be lifted here — never a human's, never another writer's."""
    try:
        SignalScoutConfig.all_teams.filter(pk=config_id).exclude(consecutive_failure_count=0).update(
            consecutive_failure_count=0
        )
        config = SignalScoutConfig.all_teams.filter(pk=config_id).first()
        if (
            config is not None
            and config.status == SignalScoutConfig.Status.PAUSED_BY_SYSTEM
            and config.pause_reason == SignalScoutConfig.PauseReason.REPEATED_FAILURES
        ):
            resumed = config.transition_status_by_system(
                SignalScoutConfig.Status.ACTIVE,
                pause_reason=SignalScoutConfig.PauseReason.REPEATED_FAILURES,
            )
            if not resumed:
                # Refused resumes are legitimate (team back at its enabled-scout cap, or the
                # pause changed hands since the read) — the lane stays paused, worth a trace.
                logger.info(
                    "signals_scout: probe succeeded but resume was refused",
                    extra={"scout_config_id": str(config_id)},
                )
    except Exception:
        logger.exception("signals_scout: failed to clear failure streak", extra={"scout_config_id": str(config_id)})


def _failure_streak_runs_in_window(config: SignalScoutConfig) -> int:
    """Runs this lane's schedule fits in the breaker's tolerance window — what it scales on.

    A cron schedule takes precedence over `run_interval_minutes` at dispatch, and the column
    keeps whatever value it held before the cron was set, so reading the column alone would
    size the breaker off a cadence the lane no longer runs at.

    Cron gaps are uneven, and no single gap answers the question the breaker asks: "0,30 0 * * *"
    has a 30-minute gap but runs twice a day, so its tightest gap would buy it the tolerance of a
    lane that runs all day. So count occurrences over a whole schedule cycle and take the fullest
    window — the most failures an outage of that length can actually leave behind.

    A malformed expression can only arrive via an out-of-band write (the API validates on save);
    fall back to the rolling interval rather than fail a run's breaker bookkeeping over it.
    """
    if config.run_cron_schedule:
        try:
            return _cron_runs_in_window(config.run_cron_schedule)
        except (CroniterError, ValueError):
            logger.warning(
                "signals_scout: invalid cron schedule while sizing failure breaker",
                extra={"scout_config_id": str(config.pk)},
            )
    return interval_runs_in_tolerance_window(config.run_interval_minutes)


@lru_cache(maxsize=256)
def _cron_runs_in_window(cron_schedule: str) -> int:
    """Fullest tolerance window of occurrences (`FAILURE_STREAK_MIN_SPAN_MINUTES` plus the DST
    slack) anywhere in the schedule's sampled cycle. Cached because it is a pure function of the
    schedule string given the fixed reference, and the densest schedules cost a few hundred
    milliseconds to walk.

    Each window's count is read at its last occurrence: the occurrences within `window` looking
    back from occurrence t are exactly the ones a window opened at its earliest member covers, so
    the running deque sees every half-open window's count without materializing the sample. That
    matches `interval_runs_in_tolerance_window`'s half-open count for a lane with no cron.
    """
    iterator = croniter(cron_schedule, _CRON_WINDOW_REFERENCE)
    window = timedelta(minutes=FAILURE_STREAK_MIN_SPAN_MINUTES + _CRON_WINDOW_DST_SLACK_MINUTES)
    horizon = _CRON_WINDOW_REFERENCE + _CRON_WINDOW_HORIZON + window
    in_window: deque[datetime] = deque()
    # A schedule with no occurrence inside the horizon (e.g. February 29th) still runs once.
    fullest = 1
    for _ in range(_CRON_WINDOW_MAX_SAMPLES):
        occurrence = iterator.get_next(datetime)
        if occurrence > horizon:
            break
        while in_window and in_window[0] <= occurrence - window:
            in_window.popleft()
        in_window.append(occurrence)
        fullest = max(fullest, len(in_window))
        if fullest >= FAILURE_STREAK_MAX_RUNS:
            break
    return fullest


def _record_failure_streak(config_id: Any) -> _FailureStreak | None:
    """Bump the failure streak and pause the lane at the threshold. Returns None when the row
    is gone or the write failed — the caller only uses the result to decide whether to emit the
    auto-paused event, and a failure here must never mask the run's own error.

    The bump is an atomic `F()` increment, not read-then-write: the runner's single-flight guard
    means one run per (team, skill) at a time, but a config edit's streak reset can land
    concurrently, and a stale absolute write would resurrect the streak the edit just cleared.
    The threshold is per-lane, derived from the runs the config's own schedule fits in the
    tolerance window (`failure_streak_pause_threshold`), so the same wall-clock tolerance holds
    whether the lane runs hourly or monthly.

    The pause goes through the transition helper: `tripped` is True only when the helper actually
    moved the status, so a re-failed probe (already paused, transition is a no-op) re-arms the
    cooldown via its own `last_run_at` stamp without firing the trip event again. The error text
    rides on the events, not the row — the row records only the reason taxonomy
    (`repeated_failures`).
    """
    try:
        updated = SignalScoutConfig.all_teams.filter(pk=config_id).update(
            consecutive_failure_count=F("consecutive_failure_count") + 1
        )
        if not updated:
            return None
        config = SignalScoutConfig.all_teams.filter(pk=config_id).first()
        if config is None:
            return None
        count = config.consecutive_failure_count
        threshold = failure_streak_pause_threshold(_failure_streak_runs_in_window(config))
        tripped = False
        if count >= threshold:
            tripped = config.transition_status_by_system(
                SignalScoutConfig.Status.PAUSED_BY_SYSTEM,
                pause_reason=SignalScoutConfig.PauseReason.REPEATED_FAILURES,
            )
        return _FailureStreak(count=count, tripped=tripped, threshold=threshold)
    except Exception:
        logger.exception("signals_scout: failed to record failure streak", extra={"scout_config_id": str(config_id)})
        return None


def _failure_properties(exc: BaseException) -> dict[str, Any] | None:
    """Cause-specific analytics properties for a failed run, or None when the exception's type and
    message already say everything.

    A run that died at the per-turn poll wall gets the turn-log diagnostics. Every wall failure
    raises the same error string, which is why the fleet's timeout rate reads as one cause; these
    properties split it into the populations that need different fixes — an agent that never
    emitted a single turn-relevant line (never started), one that worked and then went silent, and
    one still streaming when the budget ran out (the budget, not the agent, is the constraint).

    A run the agent itself failed gets the agent's own classification, because `error_type` is
    `AgentTurnFailed` for all of them. A provider outage, a spend limit and a broken scout body
    raise the same exception, so only `error_category` separates the upstream failures worth
    retrying from the defects that must keep feeding the failure breaker."""
    if isinstance(exc, TurnPollTimeout):
        return exc.diagnostics()
    if isinstance(exc, AgentTurnFailed) and exc.category is not None:
        return {"error_category": exc.category}
    return None


def _run_row_exists(run_id: Any, team_id: int) -> bool:
    return SignalScoutRun.objects.unscoped().filter(team_id=team_id, id=run_id).exists()


def _read_run_metrics(run_id: Any, team_id: int) -> tuple[int, str | None]:
    # The bridge row carries the authoritative emit tally (the emit tool bumps it in-run)
    # and the FK to the linked TaskRun — the join key into LLM analytics, where the
    # richer per-run metrics (tool calls, generations, tokens, cost) already live. Reading
    # both here keeps that linkage on failed runs too, not just clean completions. Returns
    # (0, None) when the row never persisted (failure before the first turn).
    row = (
        SignalScoutRun.objects.unscoped()
        .filter(team_id=team_id, id=run_id)
        .values_list("emitted_count", "task_run_id")
        .first()
    )
    if row is None:
        return 0, None
    emitted_count, task_run_id = row
    return emitted_count or 0, str(task_run_id) if task_run_id else None


def _capture_run_started(
    *,
    team: Team,
    config: SignalScoutConfig,
    skill: LoadedSkill,
    github_guidance: bool,
    business_knowledge_maintained: bool,
    strict_reviewer_selection: bool,
    run_id: Any,
    background_backoff: BackgroundBackoff | None = None,
    task_run_id: str,
    triggered_by: str,
    model: str | None = None,
    runtime_adapter: str | None = None,
    service_tier: str | None = None,
    runtime: str = "acp",
    experiment: FirstReportExperiment | None = None,
) -> None:
    """Emit the scout-owned run-started analytics event.

    The lifecycle counterpart to `signals_scout_run_finished`, fired once the TaskRun + bridge
    row exist and the run has cleared the reap + single-flight guards. Keyed on the team (same
    shape as the finished event) so the two join on `run_id`: `started` minus `finished` is the
    in-flight / stalled set, and a `started` with no `finished` is a run that died before
    finalize — an event-derived stall signal with no warehouse lag. Best-effort: a capture
    failure must never block the run.
    """
    if triggered_by == "experiment":
        return
    properties: dict[str, Any] = {
        "skill_name": skill.name,
        "skill_version": skill.version,
        "scout_config_id": str(config.id),
        "run_id": str(run_id),
        "task_run_id": task_run_id,
    }
    properties["runtime"] = runtime
    if experiment is not None:
        properties.update(experiment.properties())
    _attach_run_shape_props(
        properties,
        config=config,
        skill=skill,
        github_guidance=github_guidance,
        business_knowledge_maintained=business_knowledge_maintained,
        strict_reviewer_selection=strict_reviewer_selection,
        background_backoff=background_backoff,
        model=model,
        runtime_adapter=runtime_adapter,
        service_tier=service_tier,
        triggered_by=triggered_by,
    )
    try:
        posthoganalytics.capture(
            event="signals_scout_run_started",
            distinct_id=str(team.uuid),
            properties=properties,
            groups=groups(team.organization, team),
        )
    except Exception:
        logger.warning(
            "signals_scout: failed to capture run-started analytics event",
            extra={"team_id": team.id, "run_id": str(run_id), "skill_name": skill.name},
        )


def _capture_run_reaped(
    *,
    team: Team,
    skill_name: str,
    run_id: Any,
    task_run_id: str,
    status_before: str,
    age_seconds: float,
) -> None:
    """Emit a scout-owned event when a stranded run is reaped (see `_self_heal_stale_runs`).

    A run orphaned by a hard worker death never reaches the finalize path, so it emits no
    `signals_scout_run_finished` — the reap is otherwise visible only in the logs. This event
    surfaces the strand directly: a rising count is the worker-death / mass-stall shape, and
    `status_before` + `age_seconds` distinguish a routine one-off from a fleet event. Keyed on
    the team to match the other scout lifecycle events. Best-effort: a capture failure must
    never block the reap or the new run.
    """
    try:
        posthoganalytics.capture(
            event="signals_scout_run_reaped",
            distinct_id=str(team.uuid),
            properties={
                "skill_name": skill_name,
                "run_id": str(run_id),
                "task_run_id": task_run_id,
                "status_before": status_before,
                "age_seconds": round(age_seconds, 1),
                "stale_cutoff_seconds": STALE_RUN_CUTOFF_S,
            },
            groups=groups(team.organization, team),
        )
    except Exception:
        logger.warning(
            "signals_scout: failed to capture run-reaped analytics event",
            extra={"team_id": team.id, "run_id": str(run_id), "skill_name": skill_name},
        )


def _capture_config_auto_paused(
    *,
    team: Team,
    config: SignalScoutConfig,
    skill_name: str,
    run_id: Any,
    failure_count: int,
    failure_streak_threshold: int,
    reason: str,
) -> None:
    """Emit a scout-owned event when a lane's failure-streak breaker trips.

    The state is also readable on the config row (and its API surface), but a wedge needs to be
    *noticed*, not looked up: a lane that has never once succeeded is otherwise indistinguishable
    from healthy traffic in the `signals_scout_run_finished` stream, which is why one tenant could
    fail every run for days with an empty inbox and nobody see it. Fires only on the transition, so
    a count here is a count of wedges. Best-effort: a capture failure must never affect the run.
    """
    try:
        posthoganalytics.capture(
            event="signals_scout_config_auto_paused",
            distinct_id=str(team.uuid),
            properties={
                "skill_name": skill_name,
                "scout_config_id": str(config.id),
                "run_id": str(run_id),
                "consecutive_failure_count": failure_count,
                # A wedge count is only readable next to the threshold the lane was actually
                # held to, and the threshold only next to the schedule it was derived from
                # (the cron when set, else the interval).
                "failure_streak_threshold": failure_streak_threshold,
                "run_interval_minutes": config.run_interval_minutes,
                "run_cron_schedule": config.run_cron_schedule,
                "auto_pause_reason": reason,
            },
            groups=groups(team.organization, team),
        )
    except Exception:
        logger.warning(
            "signals_scout: failed to capture config auto-paused analytics event",
            extra={"team_id": team.id, "skill_name": skill_name},
        )


def _background_backoff_props(config: SignalScoutConfig, backoff: BackgroundBackoff | None) -> dict[str, int]:
    """The backoff level of a background config and the interval it sets to the next run.

    Empty when the backoff is off or the config is not background-managed. The stamp before this
    run already moved the level, so the values describe the cadence after this run.
    """
    if backoff is None or config.managed_by != SignalScoutConfig.ManagedBy.BACKGROUND or config.run_cron_schedule:
        return {}
    level = config.background_backoff_level or 0
    return {
        "background_backoff_level": level,
        "background_effective_interval_minutes": backoff.effective_interval_minutes(config.run_interval_minutes, level),
    }


def _attach_run_shape_props(
    properties: dict[str, Any],
    *,
    config: SignalScoutConfig,
    skill: LoadedSkill,
    github_guidance: bool,
    business_knowledge_maintained: bool,
    strict_reviewer_selection: bool,
    model: str | None,
    runtime_adapter: str | None,
    service_tier: str | None,
    triggered_by: str,
    background_backoff: BackgroundBackoff | None = None,
) -> None:
    """Attach the dimensions that describe what this run was configured with, to both lifecycle
    events from one place so the started and finished streams can never drift apart.

    `harness_prompt_version` is always present: it identifies the prompt build the run was given,
    which is the dimension a prompt A/B has to hold constant, and until it existed nothing recorded
    which build a run used. Model and runtime adapter are attached only when the
    `scouts-model-selection` gate (or a runtime pin) routed the run, so their absence means the
    agent-server default served it; `service_tier` likewise only when a slice or pipeline pin asked
    for an OpenAI queue, so a flex arm and its standard control split without joining through
    `$ai_generation`. `network_access` follows the same absent-means-default
    convention (attached only for `full`), so an event-based readout never pools runs with
    different egress capabilities under one model or prompt. `write_scopes` is attached only for a scout
    granted extra write access, so a readout can separate runs that could change project objects from
    runs that could not. `triggered_by` follows the run row's
    own absent-means-schedule convention (`_create_run_row`), so the started/finished streams can
    separate workflow-triggered volume, failure, and latency from scheduled and manual traffic
    without a database join. All of these make run outcomes (timeout rate, runtime, emit volume)
    sliceable without joining through $ai_generation.
    """
    properties["harness_prompt_version"] = HARNESS_PROMPT_VERSION
    properties["report_channel"] = resolve_report_channel_variant(skill.allowed_tools)
    properties["skill_origin"] = skill.origin
    properties["github_guidance"] = github_guidance
    properties["business_knowledge_maintained"] = business_knowledge_maintained
    properties["strict_reviewer_selection"] = strict_reviewer_selection
    properties["managed_by"] = config.managed_by
    if config.managed_by == SignalScoutConfig.ManagedBy.BACKGROUND and config.background_band is not None:
        properties["background_band"] = config.background_band
    properties.update(_background_backoff_props(config, background_backoff))
    if config.network_access == SignalScoutConfig.NetworkAccess.FULL:
        properties["network_access"] = config.network_access
    if granted_write_scopes := _granted_write_scopes(config):
        properties["write_scopes"] = granted_write_scopes
    if model is not None:
        properties["model"] = model
    if runtime_adapter is not None:
        properties["runtime_adapter"] = runtime_adapter
    if service_tier is not None:
        properties["service_tier"] = service_tier
    if triggered_by != TRIGGERED_BY_SCHEDULE:
        properties["triggered_by"] = triggered_by


def _capture_run_finished(
    *,
    team: Team,
    config: SignalScoutConfig,
    skill: LoadedSkill,
    github_guidance: bool,
    business_knowledge_maintained: bool,
    strict_reviewer_selection: bool,
    run_id: Any,
    background_backoff: BackgroundBackoff | None = None,
    task_run_id: str | None,
    status: str,
    runtime_s: float,
    emitted_count: int | None,
    triggered_by: str,
    model: str | None = None,
    runtime_adapter: str | None = None,
    service_tier: str | None = None,
    runtime: str = "acp",
    experiment: FirstReportExperiment | None = None,
    error_type: str | None = None,
    error_message: str | None = None,
    extra_properties: dict[str, Any] | None = None,
) -> None:
    """Emit the scout-owned per-run analytics event.

    Complements the generic `task_run_completed` / `task_run_failed` events (which only
    differentiate scout runs by `origin_product="signals_scout"`) with the dimensions a
    scout experiment segments on: skill identity, body version, outcome, duration, and
    emit volume — keyed on the team so it joins both to the emit-side `signal_emitted`
    events and to the team-level experiment exposure. Best-effort: a capture failure must
    never fail or mask the run outcome.

    On `status='failed'`, `error_type` (the exception class) and a truncated `error_message`
    are attached so the failure rate is breakable down by cause without digging into worker
    logs — the bulk of scout failures fail in this layer before the `process-task` workflow's
    own `task_run_failed` event ever fires, so this is the only event that carries their reason.
    `extra_properties` carries cause-specific detail the error string can't: the turn-log
    diagnostics behind a per-turn poll timeout, which is a single string covering several
    distinct failures, and the agent's own `error_category` for a failure it classified.
    """
    if triggered_by == "experiment":
        return
    properties: dict[str, Any] = {
        "skill_name": skill.name,
        "skill_version": skill.version,
        "scout_config_id": str(config.id),
        "run_id": str(run_id),
        "task_run_id": task_run_id,
        "status": status,
        "runtime_seconds": round(runtime_s, 1),
        "emitted_count": emitted_count,
    }
    properties["runtime"] = runtime
    if experiment is not None:
        properties.update(experiment.properties())
    _attach_run_shape_props(
        properties,
        config=config,
        skill=skill,
        github_guidance=github_guidance,
        business_knowledge_maintained=business_knowledge_maintained,
        strict_reviewer_selection=strict_reviewer_selection,
        background_backoff=background_backoff,
        model=model,
        runtime_adapter=runtime_adapter,
        service_tier=service_tier,
        triggered_by=triggered_by,
    )
    # Only attach failure context on failed runs — keeps successful / cancelled events clean
    # rather than carrying explicit-null error fields on every event.
    if error_type is not None:
        properties["error_type"] = error_type
        properties["error_message"] = error_message
    if extra_properties:
        properties.update(extra_properties)
    try:
        posthoganalytics.capture(
            event="signals_scout_run_finished",
            distinct_id=str(team.uuid),
            properties=properties,
            groups=groups(team.organization, team),
        )
    except Exception:
        logger.warning(
            "signals_scout: failed to capture run-finished analytics event",
            extra={"team_id": team.id, "run_id": str(run_id), "skill_name": skill.name},
        )


def _finalize_run_row(
    *,
    run_id: Any,
    team_id: int,
    summary: str,
    trial: bool = False,
    first_report_result: FirstReportScoutResult | None = None,
) -> None:
    # Targeted UPDATE rather than `.save()` — the row's other fields are untouched
    # by the agent's close-out, and `update()` skips the full model refresh. `updated_at` is stamped
    # by hand because `auto_now` runs in `save()`, which this path deliberately skips.
    SignalScoutRun.objects.unscoped().filter(team_id=team_id, id=run_id).update(
        summary=summary, updated_at=timezone.now()
    )
    if first_report_result is not None:
        with transaction.atomic():
            run = SignalScoutRun.objects.for_team(team_id).select_for_update().get(id=run_id)
            run.metadata = {**(run.metadata or {}), "first_report_result": first_report_result.model_dump(mode="json")}
            run.save(update_fields=["metadata", "updated_at"])
    # Stamped here rather than at each emit/edit site so the flags are computed once, from the
    # run's settled output, in the same hop that persists the close-out. Best-effort inside, so
    # a stamp failure never costs the summary write that already landed above.
    if not trial:
        stamp_derived_metadata(run_id=run_id, team_id=team_id)


def _step_name(skill: LoadedSkill) -> str:
    # Surfaces in the Task title and S3 log prefix. Keep terse — the sandbox truncates.
    safe = skill.name.replace(" ", "_")[:40]
    return f"signals_scout:{safe}"


def _ai_stage(skill: LoadedSkill) -> str:
    """The `ai_stage` tag every $ai_generation of this run carries.

    `scout:<skill>` so LLM-analytics cost is breakdown-able per scout while the whole fleet
    stays selectable by the `scout:` prefix. Only canonical skill *names* go in the tag — a
    custom scout's name is team-authored, so admitting it would grow the cardinality of a
    stage tag with the fleet's teams. The gate is the name, not `skill.origin`: a canonical
    scout a team has edited in place is still one named scout across the fleet.
    """
    if skill.name not in canonical_skill_names():
        return f"{SCOUT_AI_STAGE_PREFIX}custom"
    short = skill.name.removeprefix(SIGNALS_SCOUT_SKILL_PREFIX)
    return f"{SCOUT_AI_STAGE_PREFIX}{short}"