:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): record derived and provenance metadata on scout runs (#74626)
Andrew Maguire545172f1c6af
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex 6dc2b6a30c71..cb4a05457942 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -553,17 +553,22 @@ Per-scout binding for the headless **Signals agent**: one row per `(team, skill_Thin bridge from a Tasks `TaskRun` to the scout skill that ran inside it: one scout-domain row per scheduled agent run that links its `TaskRun` to the skill it executed. Status, timing, error context, and the full chat log live on the `TaskRun`; emitted findings are `Signal` / `SignalReport` rows written by `emit_signal()`. This row carries only the scout-specific fields that need to be queryable as real columns.-| Field | Type | Description |-| --------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `team` | FK → Team | Owning team (`related_name="signal_scout_runs"`). Denormalised tenant boundary; canonical value is `task_run.task.team`. |-| `task_run` | OneToOne → tasks.TaskRun | The `TaskRun` the scout span ran inside (`related_name="signal_scout_run"`, CASCADE — bridge row goes when the `TaskRun` is purged). |-| `scout_config` | FK → SignalScoutConfig (SET_NULL) | Audit pointer; `SET_NULL` so deleting and recreating a config doesn't destroy run history. |-| `skill_name` | CharField(200) | The `signals-scout-*` skill the run executed. |-| `skill_version` | Int | The `LLMSkill.version` snapshot at run start. |-| `summary` | TextField | One-paragraph close-out the agent writes at end-of-run. Searchable via ILIKE on the list endpoint so future runs can dedupe even when no `Signal` row was emitted. |-| `created_at` | DateTime | Auto-set on creation. |--**Status, timing, and chat log live on the linked `TaskRun`.** The bridge row carries no `status` / `started_at` / `completed_at` / `findings` / `run_metrics` / `metadata` of its own — those moved to `tasks.TaskRun` so the LLM-analytics token / cost roll-up, the Tasks UI, and the harness all see one canonical record. `MultiTurnSession` owns the `TaskRun` lifecycle; the `on_task_run_created` hook attaches the `TaskRun` to the bridge row before the agent's first turn.+| Field | Type | Description |+| --------------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `team` | FK → Team | Owning team (`related_name="signal_scout_runs"`). Denormalised tenant boundary; canonical value is `task_run.task.team`. |+| `task_run` | OneToOne → tasks.TaskRun | The `TaskRun` the scout span ran inside (`related_name="signal_scout_run"`, CASCADE — bridge row goes when the `TaskRun` is purged). |+| `scout_config` | FK → SignalScoutConfig (SET_NULL) | Audit pointer; `SET_NULL` so deleting and recreating a config doesn't destroy run history. |+| `skill_name` | CharField(200) | The `signals-scout-*` skill the run executed. |+| `skill_version` | Int | The `LLMSkill.version` snapshot at run start. |+| `summary` | TextField | One-paragraph close-out the agent writes at end-of-run. Searchable via ILIKE on the list endpoint so future runs can dedupe even when no `Signal` row was emitted. |+| `metadata` | JSONField | Server-written run context in two regions: runner-stamped top-level keys (always `harness_prompt_version` / `report_channel` / `skill_origin`; plus `model` / `runtime_adapter` / `reasoning_effort` when routing overrode the default) and the nested `derived` map of harness-computed booleans written at finalize. See below. |+| `created_at` | DateTime | Auto-set on creation. |++**Status, timing, and chat log live on the linked `TaskRun`.** The bridge row carries no `status` / `started_at` / `completed_at` / `findings` / `run_metrics` of its own — those moved to `tasks.TaskRun` so the LLM-analytics token / cost roll-up, the Tasks UI, and the harness all see one canonical record.++**Run provenance is stamped, not re-derived.** `harness_prompt_version` (a hash of `scout_harness/prompt.py` plus the imported constants its templates render, identifying the prompt build), `report_channel` (`none`/`emit`/`edit`/`both`, since the prompt branches on the two report capabilities separately), `skill_origin`, and `github_guidance` are written at run creation because none can be reconstructed later: the harness prompt carries no version history, `allowed_tools` is editable, and a seeded canonical skill row becomes `custom` as soon as a team edits it. Together they let a model or prompt A/B compare only runs that were given the same prompt shape. All four ride the `signals_scout_run_started` / `_finished` events too, which is where that readout happens.++**Run metadata is derived, never self-reported.** `metadata.derived` answers "what kind of run was this?" (`has_emit_report`, `has_edit_report`, `has_self_improvement`, `has_chart`, `has_self_validation`) and is computed server-side at finalize by `scout_harness/derived_metadata.py` from the run's own settled output. Asking the scout to declare these instead would make each flag only as reliable as the model remembering to write it, so the column stays queryable precisely because nothing in it is agent-authored. An absent `derived` region is unknown rather than all-false: the run predates the field, never reached finalize, or its stamp failed (best-effort, logged). `MultiTurnSession` owns the `TaskRun` lifecycle; the `on_task_run_created` hook attaches the `TaskRun` to the bridge row before the agent's first turn.**Tasks UI cross-link.** Run serializers expose a computed `task_url` field on `scout-runs-list` and `scout-runs-retrieve` MCP responses — `/project/{team_id}/tasks/{task_run.task_id}?runId={task_run_id}`. `task_url` is `null` for rows whose `task_run` link is missing (rows aborted before `MultiTurnSession.start()` returned).diff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 6292369f1fe9..c4fd1c12033e 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -1267,12 +1267,21 @@ class SignalScoutRun(TeamScopedRootMixin, UUIDModel):# report (pipeline-authored included), so an edited id is generally NOT one the run authored. Nullable# with a `[]` db_default so the AddField stays non-blocking on the populated table.edited_report_ids = models.JSONField(null=True, blank=True, default=list, db_default=[])- # Scout-owned per-run context stamped once at run creation — the native home for run- # dimensions that matter operationally but don't each warrant a dedicated column. Known keys- # today: `model` / `runtime_adapter` / `reasoning_effort`, the triple the run was routed on- # when the `scouts-model-selection` gate (or a runtime pin) overrode the agent-server default;- # empty for default-model runs. Write-once at creation, not a mutable grab-bag — new keys- # (e.g. a future config-level model) should also be stamped by the runner at run start.+ # Scout-owned per-run context — the native home for run dimensions that matter operationally+ # but don't each warrant a dedicated column. Two regions, distinguished by who writes them.+ # Top-level keys are stamped write-once by the runner at run creation, and split by whether+ # they are always present. `harness_prompt_version` / `report_channel` / `skill_origin` always+ # are: they pin down which instructions the run was given, and each is unrecoverable later+ # (the prompt has no version history, `allowed_tools` can be edited, and a seeded row flips to+ # `custom` the moment a team edits it), which is what makes them worth stamping rather than+ # resolving at read time. `model` / `runtime_adapter` / `reasoning_effort` appear only when the+ # `scouts-model-selection` gate or a runtime pin overrode the agent-server default, so their+ # absence is meaningful. New runner-known dimensions belong there, stamped by `_create_run_row`.+ # The nested `derived` object is written once at finalize by+ # `scout_harness/derived_metadata.py` and holds booleans the harness computes from the run's+ # own output, so "what kind of run was this?" is a field lookup rather than prose parsing.+ # Both regions are server-written: nothing here is scout-authored, which is what makes the+ # column safe to query directly.# Nullable with a `{}` db_default so the AddField stays non-blocking on the populated table.metadata = models.JSONField(null=True, blank=True, default=dict, db_default={})created_at = models.DateTimeField(auto_now_add=True)diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex 3774a968ec2a..4965c3bdd5d2 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -197,6 +197,17 @@ ACTIVITY_SLACK_S`, the activity-level ceiling that gates the workflow'scoordinator and the metadata endpoint import from here so the reported caps never drift from whatdispatch allows. `resolve_team_metadata()` backs the metadata viewset;`seed_config_layers_for_team()` lets the on-demand `sync` endpoint seed the same launch posture.+- `derived_metadata.py`+ Computes the `metadata["derived"]` region on the run row at finalize: booleans the harness+ reads back off the run's own settled output (`has_emit_report`, `has_edit_report`,+ `has_self_improvement`, `has_chart`, `has_self_validation`). Deliberately server-derived+ rather than scout-reported, so a flag can't be omitted or contradicted by the model, and+ computed in one place at finalize rather than stamped incrementally at each emit/edit site.+ `has_self_improvement` classifies authored report titles through+ `tools/report.is_self_improvement_title`, the same predicate the lifecycle events use, so the+ run row and the event stream can never disagree. `has_self_validation` reads the run window+ against the skill-namespaced `followup:` scratchpad keys, since working that queue means+ writing to it.- `serializers.py`DRF serializers for the harness HTTP surface (runs, scratchpad, project profile).Annotated for drf-spectacular so the generated MCP tools have informative schemas.@@ -267,13 +278,38 @@ one sandbox session → zero or more emitted signals.(`/project/{team_id}/tasks/{task_id}?runId={task_run_id}`) and is the join key for theLLM-analytics token / cost roll-up. Failure context (status, error, full chat log viaLLMA) lives on the `TaskRun`; the harness persists no run state on the bridge row.- The bridge row does carry a write-once `metadata` JSON column stamped at creation — the- API-native record of run context that isn't worth a dedicated column. Known keys today:- `model` / `runtime_adapter` / `reasoning_effort`, the triple the run was routed on when the- `scouts-model-selection` gate (or a runtime pin) overrode the agent-server default (`{}` on the- default path). Surfaced verbatim on the run serializers / `scout-runs-*` MCP tools; new- operationally-relevant run dimensions should be stamped there by `_create_run_row`, not grown- as ad-hoc columns.+ The bridge row does carry a `metadata` JSON column — the API-native record of run context that+ isn't worth a dedicated column — in two server-written regions.+ Top-level keys are stamped write-once at creation by `_create_run_row`, and split by whether they+ are always present.+ `harness_prompt_version` / `report_channel` (`none`/`emit`/`edit`/`both`) / `skill_origin` /+ `github_guidance` always are:+ together they pin down which instructions the run was given, which is the thing an eval or A/B+ has to hold constant. The last three are composition forks the build alone doesn't capture, since+ the same prompt build renders different sections depending on channel, skill origin, and whether+ a read-only GitHub token could be minted.+ Each is unrecoverable after the fact (the prompt has no version history, a skill's+ `allowed_tools` can be edited, and a seeded canonical row flips to `custom` the moment a team+ edits it, taking every past run's origin with it), which is why they are stamped rather than+ resolved at read time.+ `model` / `runtime_adapter` / `reasoning_effort` appear only when the `scouts-model-selection`+ gate (or a runtime pin) overrode the agent-server default, so their absence is meaningful.+ All four are attached to both lifecycle events via `_attach_run_shape_props`, since that is where+ the A/B readout happens, and `github_guidance` is resolved in `arun_signals_scout` rather than+ inside `_spawn_and_run` so the failure and cancellation paths can report it too.+ New runner-known run dimensions belong here, not grown as ad-hoc columns.+ The nested `derived` object is written once at finalize by `derived_metadata.py` and holds+ booleans the harness computes from the run's own settled output (`has_emit_report`,+ `has_edit_report`, `has_self_improvement`, `has_chart`, `has_self_validation`), so+ "what kind of run was this?" is a field lookup rather than a parse of the prose `summary`.+ Nothing in the column is scout-authored: a self-reported flag would only be as reliable as the+ model remembering to write it, which is what makes this column safe to query directly.+ Both regions surface verbatim on the run serializers / `scout-runs-*` MCP tools.+ A missing `derived` region is unknown rather than all-false: the run predates the field, died+ before finalize, or its stamp failed (best-effort and logged, since observability must not fail a+ run that already committed its output). The flags read the authored reports' current state at+ finalize rather than an emit-time snapshot, so a title or chart changed after the emit is what+ lands; the emit-time record stays on the report lifecycle events.- Each run emits scout-owned lifecycle analytics events (best-effort, keyed on the team):`signals_scout_run_started` (the run cleared the guards and a TaskRun exists),`signals_scout_run_finished` (terminal: `completed`/`failed`/`cancelled` + runtime + emitdiff --git a/products/signals/backend/scout_harness/derived_metadata.py b/products/signals/backend/scout_harness/derived_metadata.pynew file mode 100644index 000000000000..8c2918d39ac7--- /dev/null+++ b/products/signals/backend/scout_harness/derived_metadata.py@@ -0,0 +1,144 @@+"""Harness-observed run dimensions, stamped onto the run row at finalize.++`SignalScoutRun.metadata` holds regions distinguished by who writes them. The top-level+keys are stamped write-once by the runner at run creation (the routed model triple). This+module owns a second region, the nested `derived` object: a flat map of booleans answering+"what kind of run was this?" for the fleet tooling and the `exploring-scouts` reader.++Everything here is computed server-side from what the run already left behind, rather than+self-reported by the scout, because a scout-authored flag is only as reliable as the model+remembering to write it. A derived flag cannot be omitted, misremembered, or contradicted+by the prose close-out, which is what makes `metadata.derived` safe to query directly+instead of parsing `summary`.++The whole map is written at once, so within the region every key is always present. An+absent region is genuinely unknown rather than all-false: the run predates this field, or it+never reached finalize (it failed or was reaped), or its stamp failed and was logged. Consumers+that need to tell those apart have to check the run's status and `created_at`.+"""++from __future__ import annotations++import logging+from typing import Any++from django.db import transaction++from products.signals.backend.models import SignalReport, SignalScoutRun, SignalScratchpad+from products.signals.backend.scout_harness.prompt import FOLLOWUP_KEY_PREFIX+from products.signals.backend.scout_harness.tools.report import is_self_improvement_title++logger = logging.getLogger(__name__)++# The sub-object inside `SignalScoutRun.metadata` that harness-derived flags live under.+DERIVED_METADATA_KEY = "derived"++# Every flag `build_derived_flags` writes. The run serializer's schema is built from this, so a+# new flag reaches the generated frontend and MCP types without a second edit that could drift.+DERIVED_FLAG_KEYS = (+ "has_emit_report",+ "has_edit_report",+ "has_self_improvement",+ "has_chart",+ "has_self_validation",+)+++def build_derived_flags(*, run: SignalScoutRun, team_id: int) -> dict[str, bool]:+ """Compute the derived flag map for a finalized run.++ Split out from the write so the classification is testable without a transaction, and so+ a caller that already holds the row can reuse it. `team_id` is passed rather than read off+ the row so every query here is anchored to the canonical team the caller resolved.+ """+ emitted_ids = run.emitted_report_ids or []+ authored_titles, authored_charts = _authored_report_facts(team_id=team_id, report_ids=emitted_ids)+ return {+ "has_emit_report": bool(emitted_ids),+ "has_edit_report": bool(run.edited_report_ids),+ # Both are scoped to reports this run *authored*. A run that edits someone else's+ # self-improvement report, or appends a note to a report whose charts a previous run+ # set, did not itself produce that artefact, so attributing it here would overcount.+ # The trade is that both read the report's state at finalize rather than an immutable+ # emit-time snapshot, so a title or chart set changed after the emit (by this run or a+ # concurrent one) is what gets recorded. The emit-time record lives on the report+ # lifecycle events; these describe the reports the run left behind. The same scoping+ # means charts a run attached to someone else's report through `edit_report` are not+ # counted, which needs run-attributed chart provenance rather than a wider query here.+ "has_self_improvement": any(is_self_improvement_title(title) for title in authored_titles),+ "has_chart": any(charts for charts in authored_charts),+ "has_self_validation": _touched_followup_queue(run=run, team_id=team_id),+ }+++def _authored_report_facts(*, team_id: int, report_ids: list[str]) -> tuple[list[str | None], list[Any]]:+ """Titles and chart lists for the reports a run authored, in one query.++ Returns empty lists when the run authored nothing, which keeps the caller free of a+ special case and avoids a query for the common non-emitting run.+ """+ if not report_ids:+ return [], []+ rows = SignalReport.objects.filter(team_id=team_id, id__in=report_ids).values_list("title", "charts")+ titles = [row[0] for row in rows]+ charts = [row[1] for row in rows]+ return titles, charts+++def _touched_followup_queue(*, run: SignalScoutRun, team_id: int) -> bool:+ """Whether this run wrote to its own self-validation follow-up queue.++ Working the queue *is* writing to it: the follow-up discipline tells a scout to record the+ validation outcome in each entry it touches, so a `followup:` entry whose `updated_at` falls+ inside the run window is a direct observation of the work rather than a proxy for it.++ The entry must predate the run: an ordinary investigation is told to *create* a follow-up when+ it surfaces something measurable, and a newly created row would otherwise satisfy the window+ and label every such run a validation pass. Requiring `created_at` before the run start keeps+ only writes to a queue that already existed, which is what working the queue means. The+ inverse case stays uncounted: a validation that confirms a fix and then `forget`s the entry+ leaves nothing to observe. That direction under-reports rather than inventing validation runs,+ and the follow-up discipline keeps validated entries around with a `validated` state header+ rather than deleting them, so it should be rare.++ The key prefix is skill-namespaced, and the coordinator's single-flight guard keeps two runs+ of the same `(team, skill)` from overlapping, so the window cannot pick up a sibling's work.+ That guard is best-effort at the app layer, which means a rare overlapping pair could each+ claim the other's queue write. The flag is fleet observability, not an audit trail, so+ tolerating that beats threading run attribution through every scratchpad upsert.++ `for_team` rather than a bare `objects.filter(team_id=...)`: `SignalScratchpad` is fail-closed,+ and finalize runs from a Temporal activity with no request-level team scope installed, so the+ plain manager raises `TeamScopeError` there.+ """+ return (+ SignalScratchpad.objects.for_team(team_id)+ .filter(+ key__startswith=f"{FOLLOWUP_KEY_PREFIX}{run.skill_name}:",+ created_at__lt=run.created_at,+ updated_at__gte=run.created_at,+ )+ .exists()+ )+++def stamp_derived_metadata(*, run_id: Any, team_id: int) -> None:+ """Merge the derived flag map into the run's `metadata` under `derived`.++ Best-effort and observability-only: the run's real output has already committed by the time+ this runs, so a failure here is logged rather than surfaced as a run failure. Runs under+ `select_for_update` because the read-modify-write on the JSON column would otherwise race the+ report tally writers, which touch the same row on the same commit path.+ """+ try:+ with transaction.atomic():+ run = SignalScoutRun.objects.for_team(team_id).select_for_update().filter(pk=run_id).first()+ if run is None:+ logger.warning("signals_scout.derived_metadata: run %s gone, skipping stamp", run_id)+ return+ metadata = dict(run.metadata or {})+ metadata[DERIVED_METADATA_KEY] = build_derived_flags(run=run, team_id=team_id)+ run.metadata = metadata+ run.save(update_fields=["metadata"])+ except Exception:+ logger.exception("signals_scout.derived_metadata: failed to stamp derived metadata for run %s", run_id)diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.pyindex cdc9ad40e2b8..c3145dc926f0 100644--- a/products/signals/backend/scout_harness/prompt.py+++ b/products/signals/backend/scout_harness/prompt.py@@ -1,7 +1,9 @@from __future__ import annotationsimport json+import hashlibfrom datetime import datetime+from pathlib import Pathfrom pydantic import BaseModel, Field@@ -9,6 +11,45 @@ from products.signals.backend.report_charts import MAX_REPORT_CHARTSfrom products.signals.backend.scout_harness.skill_loader import LoadedSkill, SkillAuthor, skill_uses_report_channel+def _compute_harness_prompt_version() -> str:+ """Identify the harness prompt build, so runs can be grouped by the instructions they got.++ Hashes this module's own source rather than a hand-maintained constant or a list of the+ section templates. A bumped constant drifts the first time someone edits a section and+ forgets, and hashing a named subset of templates silently misses a newly added section:+ both failure modes merge two genuinely different prompt builds under one id, which corrupts+ any A/B run across the change. Hashing the source can only fail the other way, splitting one+ build into two ids after a comment or whitespace edit, which costs sample size rather than+ correctness.++ Deliberately NOT a hash of the assembled prompt: `build_run_prompt` interpolates the skill+ body, scratchpad entries, project profile, and recent run summaries, so that hash would be+ unique per run and could not group anything. This identifies the build; `report_channel`,+ `skill_origin`, and `github_guidance` on the run row identify which sections that build+ composed.++ Imported values that get rendered into a section have to be hashed alongside the source,+ because changing one changes the instructions while leaving this file's bytes untouched —+ the false-merge direction the source hash otherwise rules out. Add to `_RENDERED_IMPORTS`+ whenever a template starts interpolating something from another module.+ """+ try:+ source = Path(__file__).read_bytes()+ except OSError:+ # Falls back rather than failing the import: an unreadable source file must not take the+ # whole harness down for a field that only feeds analytics.+ return "unknown"+ rendered_imports = "\n".join(f"{name}={value}" for name, value in sorted(_RENDERED_IMPORTS.items()))+ return hashlib.sha256(source + rendered_imports.encode()).hexdigest()[:12]+++# Values imported from other modules that templates in this file render into the prompt.+_RENDERED_IMPORTS: dict[str, object] = {"MAX_REPORT_CHARTS": MAX_REPORT_CHARTS}+++HARNESS_PROMPT_VERSION = _compute_harness_prompt_version()++class SignalScoutRunSummary(BaseModel):"""Structured close-out the scout returns at end_turn.diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.pyindex 178a55d03baf..445e04c83f74 100644--- a/products/signals/backend/scout_harness/runner.py+++ b/products/signals/backend/scout_harness/runner.py@@ -18,13 +18,19 @@ from posthog.sync import database_sync_to_asyncfrom products.signals.backend.agent_runtime import STEP_SCOUT, resolve_agent_runtimefrom products.signals.backend.models import SignalScoutConfig, SignalScoutRun+from products.signals.backend.scout_harness.derived_metadata import stamp_derived_metadatafrom products.signals.backend.scout_harness.lazy_seed import sync_canonical_skillsfrom products.signals.backend.scout_harness.limits import DEFAULT_MAX_RUNTIME_S, STALE_RUN_CUTOFF_Sfrom products.signals.backend.scout_harness.model_selection import resolve_scout_model-from products.signals.backend.scout_harness.prompt import SignalScoutRunSummary, build_run_prompt+from products.signals.backend.scout_harness.prompt import (+ HARNESS_PROMPT_VERSION,+ SignalScoutRunSummary,+ build_run_prompt,+)from products.signals.backend.scout_harness.skill_loader import (LoadedSkill,load_skill_for_run,+ resolve_report_channel_variant,skill_uses_report_channel,)from products.signals.backend.scout_harness.team_limits import github_read_access_for_team, withheld_skills_for_team@@ -244,6 +250,27 @@ async def arun_signals_scout(runtime_adapter = Nonemodel = Nonereasoning_effort = 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.+ # The `gh` guidance is gated 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). Repo-backed runs (the management command's `--repository`+ # escape hatch) are excluded too: they take the full-credential provisioning path, and the+ # section's read-only framing would misdescribe the token they actually hold.+ github_guidance = (+ skill_uses_report_channel(skill.allowed_tools)+ and repository is None+ and await database_sync_to_async(github_read_access_for_team, thread_sensitive=False)(+ team.parent_team_id or team.id+ )+ )+ if github_guidance:+ github_guidance = await database_sync_to_async(+ tasks_facade.can_mint_readonly_github_token, thread_sensitive=False+ )(team.id)try:last_message, task_run_id = await _spawn_and_run(team=team,@@ -254,6 +281,7 @@ async def arun_signals_scout(repository=repository,verbose=verbose,user_id=user_id,+ github_guidance=github_guidance,model=model,runtime_adapter=runtime_adapter,reasoning_effort=reasoning_effort,@@ -266,6 +294,7 @@ async def arun_signals_scout(team=team,config=config,skill=skill,+ github_guidance=github_guidance,run_id=run_id,task_run_id=task_run_id,status=tasks_facade.TaskRunStatus.COMPLETED.value,@@ -316,6 +345,7 @@ async def arun_signals_scout(team=team,config=config,skill=skill,+ github_guidance=github_guidance,run_id=run_id,task_run_id=failed_task_run_id,status=tasks_facade.TaskRunStatus.FAILED.value,@@ -360,6 +390,7 @@ async def arun_signals_scout(team=team,config=config,skill=skill,+ github_guidance=github_guidance,run_id=run_id,task_run_id=None,status=tasks_facade.TaskRunStatus.CANCELLED.value,@@ -381,6 +412,7 @@ async def _spawn_and_run(repository: str | None,verbose: bool,user_id: int,+ github_guidance: bool,model: str | None,runtime_adapter: str | None = None,reasoning_effort: str | None = None,@@ -412,17 +444,6 @@ async def _spawn_and_run(# falling back). Repo-backed runs (the management command's `--repository` escape hatch) are# excluded too: they take the full-credential provisioning path, and the section's read-only# framing would misdescribe the token they actually hold.- github_prompt_guidance = (- report_channel- and repository is None- and await database_sync_to_async(github_read_access_for_team, thread_sensitive=False)(- team.parent_team_id or team.id- )- )- if github_prompt_guidance:- github_prompt_guidance = await database_sync_to_async(- tasks_facade.can_mint_readonly_github_token, thread_sensitive=False- )(team.id)# `repository` is None on the cadence path — v1 doesn't clone a repo into the# sandbox. The kwarg stays wired so the management command can still pass# `--repository` for ad-hoc local investigations; productionised repo access@@ -457,7 +478,7 @@ async def _spawn_and_run(reasoning_effort=reasoning_effort,)prompt = build_run_prompt(- skill, run_id=str(run_id), team_id=team.id, started_at=started_at, github_read_access=github_prompt_guidance+ skill, run_id=str(run_id), team_id=team.id, started_at=started_at, github_read_access=github_guidance)logger.info("signals_scout: spawning sandbox",@@ -486,6 +507,7 @@ async def _spawn_and_run(model=model,runtime_adapter=runtime_adapter,reasoning_effort=reasoning_effort,+ github_guidance=github_guidance,)# 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 —@@ -496,6 +518,7 @@ async def _spawn_and_run(team=team,config=config,skill=skill,+ github_guidance=github_guidance,run_id=run_id,task_run_id=str(task_run.id),model=model,@@ -531,7 +554,7 @@ async def _spawn_and_run(# 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_summary, thread_sensitive=False)(+ 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,@@ -671,11 +694,12 @@ def _create_run_row(model: str | None = None,runtime_adapter: str | None = None,reasoning_effort: str | None = None,+ github_guidance: bool = False,) -> SignalScoutRun:# Stamp the routed model triple 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 an empty dict means the agent-server default served the run.- metadata = {+ # on the default path, so their absence means the agent-server default served the run.+ metadata: dict[str, Any] = {key: valuefor key, value in (("model", model),@@ -684,6 +708,21 @@ def _create_run_row()if value is not None}+ # 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_guidancereturn SignalScoutRun.objects.unscoped().create(id=run_id,task_run=task_run,@@ -722,6 +761,7 @@ def _capture_run_started(team: Team,config: SignalScoutConfig,skill: LoadedSkill,+ github_guidance: bool,run_id: Any,task_run_id: str,model: str | None = None,@@ -743,7 +783,9 @@ def _capture_run_started("run_id": str(run_id),"task_run_id": task_run_id,}- _attach_model_props(properties, model=model, runtime_adapter=runtime_adapter)+ _attach_run_shape_props(+ properties, skill=skill, github_guidance=github_guidance, model=model, runtime_adapter=runtime_adapter+ )try:posthoganalytics.capture(event="signals_scout_run_started",@@ -797,10 +839,28 @@ def _capture_run_reaped()-def _attach_model_props(properties: dict[str, Any], *, model: str | None, runtime_adapter: str | None) -> None:- # Only attached when the `scouts-model-selection` gate (or a runtime pin) routed the run —- # absence means the agent-server default served it. Makes run outcomes (timeout rate, runtime,- # emit volume) sliceable by model without joining through $ai_generation.+def _attach_run_shape_props(+ properties: dict[str, Any],+ *,+ skill: LoadedSkill,+ github_guidance: bool,+ model: str | None,+ runtime_adapter: str | 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. All three 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_guidanceif model is not None:properties["model"] = modelif runtime_adapter is not None:@@ -812,6 +872,7 @@ def _capture_run_finished(team: Team,config: SignalScoutConfig,skill: LoadedSkill,+ github_guidance: bool,run_id: Any,task_run_id: str | None,status: str,@@ -846,7 +907,9 @@ def _capture_run_finished("runtime_seconds": round(runtime_s, 1),"emitted_count": emitted_count,}- _attach_model_props(properties, model=model, runtime_adapter=runtime_adapter)+ _attach_run_shape_props(+ properties, skill=skill, github_guidance=github_guidance, model=model, runtime_adapter=runtime_adapter+ )# 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:@@ -866,10 +929,14 @@ def _capture_run_finished()-def _finalize_run_summary(*, run_id: Any, team_id: int, summary: str) -> None:+def _finalize_run_row(*, run_id: Any, team_id: int, summary: str) -> 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.SignalScoutRun.objects.unscoped().filter(team_id=team_id, id=run_id).update(summary=summary)+ # 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.+ stamp_derived_metadata(run_id=run_id, team_id=team_id)def _step_name(skill: LoadedSkill) -> str:diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 79c2a0b4fdc0..c9d091a3239d 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -25,6 +25,7 @@ from posthog.permissions import get_authenticator_scopesfrom products.signals.backend.artefact_schemas import ActionabilityChoice, Priorityfrom products.signals.backend.models import SignalScoutConfig, SignalScoutEmissionfrom products.signals.backend.report_charts import MAX_REPORT_CHARTS+from products.signals.backend.scout_harness.derived_metadata import DERIVED_FLAG_KEYS, DERIVED_METADATA_KEYfrom products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIXfrom products.signals.backend.scout_harness.tools.emit import (MAX_FINDING_ID_LENGTH,@@ -47,6 +48,44 @@ from products.skills.backend.models.skills import LLMSkill# --- Run history -----------------------------------------------------------+@extend_schema_field(+ {+ "type": "object",+ "properties": {+ "harness_prompt_version": {"type": "string"},+ "report_channel": {"type": "string"},+ "skill_origin": {"type": "string"},+ "github_guidance": {"type": "boolean"},+ "model": {"type": "string"},+ "runtime_adapter": {"type": "string"},+ "reasoning_effort": {"type": "string"},+ # Closed and fully required, unlike the parent: the region is written whole or not at+ # all, so every flag is present whenever the object is. Leaving it open would generate+ # a `[key: string]: boolean` index signature that the optional named flags cannot+ # satisfy, which fails frontend typechecking.+ DERIVED_METADATA_KEY: {+ "type": "object",+ "properties": {key: {"type": "boolean"} for key in DERIVED_FLAG_KEYS},+ "required": list(DERIVED_FLAG_KEYS),+ },+ },+ # Older rows predate these keys and future runner-stamped dimensions land here before the+ # schema catches up, so the object stays open rather than closed.+ "additionalProperties": True,+ }+)+class RunMetadataField(serializers.DictField):+ """The run row's whole `metadata` column: runner-stamped keys at the top level plus the nested+ `derived` map of harness-computed booleans.++ The known keys are spelled out so generated TypeScript and MCP consumers get real types+ instead of `unknown` on every value. `DictField(child=CharField())` is what this replaced,+ and it coerced the nested `derived` map to its string repr on the way out, turning a queryable+ object into unparseable prose. Output-only: writes come from the runner at creation and from+ `derived_metadata.stamp_derived_metadata` at finalize, never through this field.+ """++class SignalScoutRunSummarySerializer(serializers.Serializer):"""Lightweight projection of a `SignalScoutRun` row used by `search-recent-runs`.@@ -148,13 +187,24 @@ class SignalScoutRunSummarySerializer(serializers.Serializer):"edited no report."),)- metadata = serializers.DictField(- child=serializers.CharField(),- help_text=(- "Scout-owned per-run context stamped at run start. Known keys today: `model`, "- "`runtime_adapter`, and `reasoning_effort` — the triple the run was routed on when the "- "`scouts-model-selection` gate (or a runtime pin) overrode the agent-server default. "- "Empty object when the run rode the default model, or for runs predating the field."+ metadata = RunMetadataField(+ help_text=(+ "Scout-owned per-run context, in two regions. Top-level keys are stamped by the runner "+ "at run start. Always present: `harness_prompt_version` (id of the harness prompt build "+ "the run was given), `report_channel` (which report tools the run held: `none`, `emit`, "+ "`edit`, or `both`), "+ "`skill_origin` (`canonical` or `custom`), and `github_guidance` (whether the run got "+ "the GitHub evidence section) — the provenance set that says which instructions the run "+ "actually got, so runs are only compared against runs of the same shape. Present only "+ "when routing overrode the agent-server default: `model`, "+ "`runtime_adapter`, and `reasoning_effort`. The nested `derived` object is the harness's "+ "own map of boolean run dimensions, computed server-side at finalize: `has_emit_report`, "+ "`has_edit_report`, `has_self_improvement`, `has_chart`, and `has_self_validation`. Use "+ "`derived` to answer 'what kind of run was this?' instead of parsing the `summary` prose. "+ "Note the flags describe the reports the run authored as they stand now, so charts "+ "attached to someone else's report via an edit are not counted. A missing `derived` "+ "object is unknown, not all-false: the run predates the field, never finalized, or its "+ "stamp failed."),)diff --git a/products/signals/backend/scout_harness/skill_loader.py b/products/signals/backend/scout_harness/skill_loader.pyindex 9c6cb1cf9860..6333e2945d8d 100644--- a/products/signals/backend/scout_harness/skill_loader.py+++ b/products/signals/backend/scout_harness/skill_loader.py@@ -26,6 +26,27 @@ def skill_uses_report_channel(allowed_tools: list[str] | None) -> bool:return bool(REPORT_CHANNEL_TOOLS & set(allowed_tools or []))+def resolve_report_channel_variant(allowed_tools: list[str] | None) -> str:+ """Which report tools a run held: `none`, `emit`, `edit`, or `both`.++ Finer-grained than `skill_uses_report_channel` because the prompt builder branches on the two+ capabilities separately (the follow-up re-surface clause, the self-improvement escalation path,+ and the channel sections all differ between emit-only and edit-only), so a single boolean would+ pool runs that were given materially different instructions. Stamped on the run row, where+ `allowed_tools` being editable means the variant cannot be recovered afterwards.+ """+ tools = set(allowed_tools or [])+ can_emit = "emit_report" in tools+ can_edit = "edit_report" in tools+ if can_emit and can_edit:+ return "both"+ if can_emit:+ return "emit"+ if can_edit:+ return "edit"+ return "none"++class SkillNotFoundError(LookupError):"""The team has no skill matching the requested name."""diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.pyindex bf4091a784e9..c95324268bf7 100644--- a/products/signals/backend/scout_harness/tools/report.py+++ b/products/signals/backend/scout_harness/tools/report.py@@ -583,6 +583,15 @@ _SELF_IMPROVEMENT_TITLE_RE = re.compile(r"^\s*scout\s+self[\s-]?improvement\s*:"assert _SELF_IMPROVEMENT_TITLE_RE.match(SELF_IMPROVEMENT_REPORT_TITLE_PREFIX)+def is_self_improvement_title(title: str | None) -> bool:+ """Whether a report title marks it as a scout self-improvement report.++ Public because the run row's derived metadata classifies authored reports the same way the+ lifecycle events do (see `derived_metadata.build_derived_flags`), and the two must agree.+ """+ return _SELF_IMPROVEMENT_TITLE_RE.match(title or "") is not None++def _report_classification_props(effective_title: str | None) -> dict[str, Any]:"""Derived classification dimensions stamped on both report-channel lifecycle events (and theircustomer-facing copies): `report_kind` (enum, breakdown-friendly) + `is_self_improvement_report`@@ -591,7 +600,7 @@ def _report_classification_props(effective_title: str | None) -> dict[str, Any]:than scout-declared, so the flag can't be omitted by the model and needs no tool-schema change.This helper is the single extension point for future derived telemetry dimensions — add them hereso the emit and edit events never drift apart."""- is_self_improvement = _SELF_IMPROVEMENT_TITLE_RE.match(effective_title or "") is not None+ is_self_improvement = is_self_improvement_title(effective_title)return {"report_kind": REPORT_KIND_SELF_IMPROVEMENT if is_self_improvement else REPORT_KIND_FINDING,"is_self_improvement_report": is_self_improvement,diff --git a/products/signals/backend/scout_harness/tools/runs.py b/products/signals/backend/scout_harness/tools/runs.pyindex d6c6a1ab66ac..4e4608f3a1cc 100644--- a/products/signals/backend/scout_harness/tools/runs.py+++ b/products/signals/backend/scout_harness/tools/runs.py@@ -81,9 +81,10 @@ class RunSummary:# one-liner. Both are surfaced only for failed/cancelled runs — null otherwise (incl. success).error: str | None = Nonefailure_reason: str | None = None- # Scout-owned per-run context stamped at run creation (today: the routed model triple —- # `model` / `runtime_adapter` / `reasoning_effort`). Empty for default-model runs and rows- # predating the column.+ # Scout-owned per-run context: runner-stamped keys from run creation (today: the routed model+ # triple `model` / `runtime_adapter` / `reasoning_effort`) plus the nested `derived` map of+ # harness-computed run flags written at finalize. Empty for default-model runs that never+ # finalized, and for rows predating the column.metadata: dict[str, Any] = field(default_factory=dict)def as_dict(self) -> dict[str, Any]:@@ -124,9 +125,10 @@ class RunDetail:# one-liner. Both are surfaced only for failed/cancelled runs — null otherwise (incl. success).error: str | None = Nonefailure_reason: str | None = None- # Scout-owned per-run context stamped at run creation (today: the routed model triple —- # `model` / `runtime_adapter` / `reasoning_effort`). Empty for default-model runs and rows- # predating the column.+ # Scout-owned per-run context: runner-stamped keys from run creation (today: the routed model+ # triple `model` / `runtime_adapter` / `reasoning_effort`) plus the nested `derived` map of+ # harness-computed run flags written at finalize. Empty for default-model runs that never+ # finalized, and for rows predating the column.metadata: dict[str, Any] = field(default_factory=dict)def as_dict(self) -> dict[str, Any]:diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex 4643f05fb81d..a336c3b39027 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -23,17 +23,20 @@ from temporalio.testing import ActivityEnvironmentfrom posthog.models import Organization, OrganizationMembership, Team, Userfrom posthog.models.scoping import team_scope+from posthog.models.utils import uuid7from posthog.sync import database_sync_to_asyncfrom products.signals.backend.agent_runtime import AgentRuntimefrom products.signals.backend.models import SignalScoutConfig, SignalScoutRunfrom products.signals.backend.report_charts import ReportChart+from products.signals.backend.scout_harness.derived_metadata import DERIVED_METADATA_KEYfrom products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, _compute_row_hashfrom products.signals.backend.scout_harness.limits import STALE_RUN_CUTOFF_Sfrom products.signals.backend.scout_harness.model_selection import ScoutModel-from products.signals.backend.scout_harness.prompt import _REPORT_CHARTS, build_run_prompt-from products.signals.backend.scout_harness.runner import RunResult, arun_signals_scout+from products.signals.backend.scout_harness.prompt import _REPORT_CHARTS, HARNESS_PROMPT_VERSION, build_run_prompt+from products.signals.backend.scout_harness.runner import RunResult, _create_run_row, arun_signals_scoutfrom products.signals.backend.scout_harness.skill_loader import (+ LoadedSkill,SkillNotFoundError,is_signals_scout_skill,load_skill_for_run,@@ -920,7 +923,8 @@ async def test_run_pins_sandbox_to_resolved_scout_model(assert captured["context"].runtime_adapter == expected_runtime_adapterassert captured["context"].reasoning_effort == expected_reasoning_effort# The routed triple is also stamped on the bridge row's `metadata` (keys omitted when unset,- # `{}` on the default path) — the native API-side record of which model served the run.+ # nothing at the top level on the default path) — the native API-side record of which model+ # served the run.bridge = await database_sync_to_async(SignalScoutRun.objects.get)(team=ateam)expected_metadata = {key: value@@ -931,7 +935,14 @@ async def test_run_pins_sandbox_to_resolved_scout_model()if value is not None}- assert bridge.metadata == expected_metadata+ stamped = bridge.metadata or {}+ routed = {key: value for key, value in stamped.items() if key in _ROUTED_MODEL_KEYS}+ assert routed == expected_metadata+ # Wiring guards for the two regions written outside `_create_run_row`'s routing triple:+ # the prompt build the run was given, and the finalize-time derived map. Neither can be+ # proven by a direct unit test of the function that computes it.+ assert stamped["harness_prompt_version"] == HARNESS_PROMPT_VERSION+ assert DERIVED_METADATA_KEY in stampedevents = {c.kwargs["event"] for c in capture.call_args_list}assert events == {"signals_scout_run_started", "signals_scout_run_finished"}for call in capture.call_args_list:@@ -1605,3 +1616,59 @@ def test_to_summary_and_detail_surface_task_url_from_bridge():assert detail.task_id == summary.task_idassert detail.task_run_id == summary.task_run_idassert detail.task_url == summary.task_url+++_ROUTED_MODEL_KEYS = ("model", "runtime_adapter", "reasoning_effort")+++class TestRunRowProvenanceStamps(BaseTest):+ # The three dimensions an eval or A/B has to hold constant. Each is unrecoverable after the+ # fact, so a regression that hardcodes one (rather than reading it off the loaded skill)+ # silently mislabels every run from then on instead of failing loudly.+ def _skill(self, *, allowed_tools: list[str], origin: str) -> LoadedSkill:+ return LoadedSkill(+ name="signals-scout-general",+ version=3,+ body="scout",+ description="",+ allowed_tools=allowed_tools,+ files=[],+ skill_id="skill-1",+ origin=origin, # type: ignore[arg-type]+ authors=[],+ )++ @parameterized.expand(+ [+ # emit-only and edit-only are separate prompt builds, not one "report channel" —+ # `build_run_prompt` renders different follow-up, escalation, and action guidance for+ # each, so collapsing them to a boolean would pool runs given different instructions.+ ("emit_only_custom", ["emit_report"], "custom", "emit", "custom"),+ ("edit_only_custom", ["edit_report"], "custom", "edit", "custom"),+ ("both_tools_canonical", ["emit_report", "edit_report"], "canonical", "both", "canonical"),+ ("legacy_channel_canonical", ["emit_finding"], "canonical", "none", "canonical"),+ ]+ )+ def test_stamps_prompt_build_channel_and_origin(+ self,+ _name: str,+ allowed_tools: list[str],+ origin: str,+ expected_channel: str,+ expected_origin: str,+ ) -> None:+ config, _ = SignalScoutConfig.objects.get_or_create(team=self.team, skill_name="signals-scout-general")+ run = _create_run_row(+ run_id=uuid7(),+ task_run=_make_task_run(self.team),+ team=self.team,+ config=config,+ skill=self._skill(allowed_tools=allowed_tools, origin=origin),+ )+ stamped = run.metadata or {}+ assert stamped["harness_prompt_version"] == HARNESS_PROMPT_VERSION+ assert stamped["report_channel"] == expected_channel+ assert stamped["skill_origin"] == expected_origin+ # The routing triple stays absent on the default-model path, so its keys can't be+ # confused with the always-present provenance keys.+ assert not any(key in stamped for key in _ROUTED_MODEL_KEYS)diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 75c77d5b68a8..9a2a380f8ff3 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -37,8 +37,10 @@ from products.signals.backend.models import (SignalScoutRun,SignalScratchpad,)+from products.signals.backend.scout_harness.derived_metadata import DERIVED_METADATA_KEY, stamp_derived_metadatafrom products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, discover_canonical_skillsfrom products.signals.backend.scout_harness.limits import STALE_RUN_CUTOFF_S+from products.signals.backend.scout_harness.prompt import FOLLOWUP_KEY_PREFIXfrom products.signals.backend.scout_harness.serializers import SignalScoutConfigUpdateSerializerfrom products.signals.backend.scout_harness.team_limits import MAX_RUNS_PER_TEAM_PER_TICKfrom products.signals.backend.scout_harness.tools.profile import compute_project_profile@@ -2139,3 +2141,101 @@ class TestScoutHarnessMembersAPI(APIBaseTest):_authenticate_as_scout(self, scopes=scopes)response = self.client.get(self._url())assert response.status_code == status.HTTP_403_FORBIDDEN+++class TestScoutRunDerivedMetadata(APIBaseTest):+ def _stamp(self, run: SignalScoutRun) -> dict:+ stamp_derived_metadata(run_id=run.id, team_id=self.team.id)+ run.refresh_from_db()+ return (run.metadata or {})[DERIVED_METADATA_KEY]++ def _make_report(self, *, title: str = "A finding", charts: list | None = None) -> SignalReport:+ return SignalReport.objects.create(team=self.team, title=title, charts=charts or [])++ def test_stamp_preserves_runner_stamped_keys(self) -> None:+ run = _make_run(self.team, metadata={"model": "some-model", "runtime_adapter": "some-adapter"})+ self._stamp(run)+ stamped = run.metadata or {}+ assert stamped["model"] == "some-model"+ assert stamped["runtime_adapter"] == "some-adapter"++ def test_stamp_writes_every_flag_so_absent_means_never_finalized(self) -> None:+ run = _make_run(self.team)+ assert set(self._stamp(run)) == {+ "has_emit_report",+ "has_edit_report",+ "has_self_improvement",+ "has_chart",+ "has_self_validation",+ }++ @parameterized.expand(+ [+ ("authored", True, True),+ ("only_edited", False, False),+ ]+ )+ def test_report_derived_flags_only_count_authored_reports(self, _name: str, authored: bool, expected: bool) -> None:+ report = self._make_report(+ title="Scout self-improvement: signals-scout-general – noisy rule",+ charts=[{"chart_id": "c1", "title": "Trend", "query": "select 1"}],+ )+ ids = [str(report.id)]+ run = _make_run(+ self.team,+ emitted_report_ids=ids if authored else [],+ edited_report_ids=[] if authored else ids,+ )+ flags = self._stamp(run)+ assert flags["has_self_improvement"] is expected+ assert flags["has_chart"] is expected+ assert flags["has_emit_report"] is authored+ assert flags["has_edit_report"] is not authored++ @parameterized.expand(+ [+ # An entry that predates the run and was written during it: the queue was worked.+ ("worked_existing_entry", timedelta(hours=-2), timedelta(minutes=1), True),+ ("existing_entry_untouched", timedelta(hours=-2), timedelta(hours=-1), False),+ # An entry this run created is an ordinary investigation recording a future probe,+ # not a validation pass. Both timestamps land inside the window, so only the+ # created-before-the-run guard separates the two.+ ("created_this_run", timedelta(minutes=1), timedelta(minutes=1), False),+ ]+ )+ def test_self_validation_counts_only_writes_to_a_queue_that_already_existed(+ self, _name: str, created_offset: timedelta, updated_offset: timedelta, expected: bool+ ) -> None:+ run = _make_run(self.team)+ entry = SignalScratchpad.objects.create(+ team=self.team,+ key=f"{FOLLOWUP_KEY_PREFIX}{run.skill_name}:checkout-errors",+ content="pending",+ )+ # Both columns are auto-managed, so a queryset update is the only way to place the row+ # relative to the run window.+ SignalScratchpad.all_teams.filter(pk=entry.pk).update(+ created_at=run.created_at + created_offset, updated_at=run.created_at + updated_offset+ )+ assert self._stamp(run)["has_self_validation"] is expected++ def test_sibling_skills_queue_does_not_count(self) -> None:+ run = _make_run(self.team)+ entry = SignalScratchpad.objects.create(+ team=self.team,+ key=f"{FOLLOWUP_KEY_PREFIX}signals-scout-experiments:checkout-errors",+ content="pending",+ )+ SignalScratchpad.all_teams.filter(pk=entry.pk).update(created_at=run.created_at - timedelta(hours=2))+ assert self._stamp(run)["has_self_validation"] is False++ def test_derived_map_round_trips_as_an_object_not_a_string(self) -> None:+ # Guards the serializer field: a `DictField(child=CharField())` coerces the nested map to+ # its Python repr, which turns a queryable object into unparseable prose.+ run = _make_run(self.team, metadata={"model": "some-model"})+ self._stamp(run)+ response = self.client.get(f"/api/projects/{self.team.id}/signals/scout/runs/{run.id}/")+ assert response.status_code == status.HTTP_200_OK+ metadata = response.json()["metadata"]+ assert metadata["model"] == "some-model"+ assert metadata[DERIVED_METADATA_KEY]["has_emit_report"] is Falsediff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex bdb9fa94e1c9..e90ca1b89c42 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -2625,10 +2625,28 @@ export interface ProjectProfileApi {payload: ProjectProfilePayloadApi}+export type SignalScoutRunSummaryApiMetadataDerived = {+ has_emit_report: boolean+ has_edit_report: boolean+ has_self_improvement: boolean+ has_chart: boolean+ has_self_validation: boolean+}+/**- * Scout-owned per-run context stamped at run start. Known keys today: `model`, `runtime_adapter`, and `reasoning_effort` — the triple the run was routed on when the `scouts-model-selection` gate (or a runtime pin) overrode the agent-server default. Empty object when the run rode the default model, or for runs predating the field.+ * Scout-owned per-run context, in two regions. Top-level keys are stamped by the runner at run start. Always present: `harness_prompt_version` (id of the harness prompt build the run was given), `report_channel` (which report tools the run held: `none`, `emit`, `edit`, or `both`), `skill_origin` (`canonical` or `custom`), and `github_guidance` (whether the run got the GitHub evidence section) — the provenance set that says which instructions the run actually got, so runs are only compared against runs of the same shape. Present only when routing overrode the agent-server default: `model`, `runtime_adapter`, and `reasoning_effort`. The nested `derived` object is the harness's own map of boolean run dimensions, computed server-side at finalize: `has_emit_report`, `has_edit_report`, `has_self_improvement`, `has_chart`, and `has_self_validation`. Use `derived` to answer 'what kind of run was this?' instead of parsing the `summary` prose. Note the flags describe the reports the run authored as they stand now, so charts attached to someone else's report via an edit are not counted. A missing `derived` object is unknown, not all-false: the run predates the field, never finalized, or its stamp failed.*/-export type SignalScoutRunSummaryApiMetadata = { [key: string]: string }+export type SignalScoutRunSummaryApiMetadata = {+ harness_prompt_version?: string+ report_channel?: string+ skill_origin?: string+ github_guidance?: boolean+ model?: string+ runtime_adapter?: string+ reasoning_effort?: string+ derived?: SignalScoutRunSummaryApiMetadataDerived+ [key: string]: unknown+}/*** * `not_started` - not_started@@ -2714,14 +2732,32 @@ export interface SignalScoutRunSummaryApi {emitted_report_ids: string[]/** The `SignalReport` ids this run mutated via the `edit_report` channel (rewrote title/summary and/or appended a note), deduped. Distinct from `emitted_report_ids`: edit can target any inbox report, so these are generally not reports the run authored. Empty for runs that edited no report. */edited_report_ids: string[]- /** Scout-owned per-run context stamped at run start. Known keys today: `model`, `runtime_adapter`, and `reasoning_effort` — the triple the run was routed on when the `scouts-model-selection` gate (or a runtime pin) overrode the agent-server default. Empty object when the run rode the default model, or for runs predating the field. */+ /** Scout-owned per-run context, in two regions. Top-level keys are stamped by the runner at run start. Always present: `harness_prompt_version` (id of the harness prompt build the run was given), `report_channel` (which report tools the run held: `none`, `emit`, `edit`, or `both`), `skill_origin` (`canonical` or `custom`), and `github_guidance` (whether the run got the GitHub evidence section) — the provenance set that says which instructions the run actually got, so runs are only compared against runs of the same shape. Present only when routing overrode the agent-server default: `model`, `runtime_adapter`, and `reasoning_effort`. The nested `derived` object is the harness's own map of boolean run dimensions, computed server-side at finalize: `has_emit_report`, `has_edit_report`, `has_self_improvement`, `has_chart`, and `has_self_validation`. Use `derived` to answer 'what kind of run was this?' instead of parsing the `summary` prose. Note the flags describe the reports the run authored as they stand now, so charts attached to someone else's report via an edit are not counted. A missing `derived` object is unknown, not all-false: the run predates the field, never finalized, or its stamp failed. */metadata: SignalScoutRunSummaryApiMetadata}+export type SignalScoutRunDetailApiMetadataDerived = {+ has_emit_report: boolean+ has_edit_report: boolean+ has_self_improvement: boolean+ has_chart: boolean+ has_self_validation: boolean+}+/**- * Scout-owned per-run context stamped at run start. Known keys today: `model`, `runtime_adapter`, and `reasoning_effort` — the triple the run was routed on when the `scouts-model-selection` gate (or a runtime pin) overrode the agent-server default. Empty object when the run rode the default model, or for runs predating the field.+ * Scout-owned per-run context, in two regions. Top-level keys are stamped by the runner at run start. Always present: `harness_prompt_version` (id of the harness prompt build the run was given), `report_channel` (which report tools the run held: `none`, `emit`, `edit`, or `both`), `skill_origin` (`canonical` or `custom`), and `github_guidance` (whether the run got the GitHub evidence section) — the provenance set that says which instructions the run actually got, so runs are only compared against runs of the same shape. Present only when routing overrode the agent-server default: `model`, `runtime_adapter`, and `reasoning_effort`. The nested `derived` object is the harness's own map of boolean run dimensions, computed server-side at finalize: `has_emit_report`, `has_edit_report`, `has_self_improvement`, `has_chart`, and `has_self_validation`. Use `derived` to answer 'what kind of run was this?' instead of parsing the `summary` prose. Note the flags describe the reports the run authored as they stand now, so charts attached to someone else's report via an edit are not counted. A missing `derived` object is unknown, not all-false: the run predates the field, never finalized, or its stamp failed.*/-export type SignalScoutRunDetailApiMetadata = { [key: string]: string }+export type SignalScoutRunDetailApiMetadata = {+ harness_prompt_version?: string+ report_channel?: string+ skill_origin?: string+ github_guidance?: boolean+ model?: string+ runtime_adapter?: string+ reasoning_effort?: string+ derived?: SignalScoutRunDetailApiMetadataDerived+ [key: string]: unknown+}/*** Full `SignalScoutRun` projection used by `get-run`. Same shape as the summary@@ -2788,7 +2824,7 @@ export interface SignalScoutRunDetailApi {emitted_report_ids: string[]/** The `SignalReport` ids this run mutated via the `edit_report` channel (rewrote title/summary and/or appended a note), deduped. Distinct from `emitted_report_ids`: edit can target any inbox report, so these are generally not reports the run authored. Empty for runs that edited no report. */edited_report_ids: string[]- /** Scout-owned per-run context stamped at run start. Known keys today: `model`, `runtime_adapter`, and `reasoning_effort` — the triple the run was routed on when the `scouts-model-selection` gate (or a runtime pin) overrode the agent-server default. Empty object when the run rode the default model, or for runs predating the field. */+ /** Scout-owned per-run context, in two regions. Top-level keys are stamped by the runner at run start. Always present: `harness_prompt_version` (id of the harness prompt build the run was given), `report_channel` (which report tools the run held: `none`, `emit`, `edit`, or `both`), `skill_origin` (`canonical` or `custom`), and `github_guidance` (whether the run got the GitHub evidence section) — the provenance set that says which instructions the run actually got, so runs are only compared against runs of the same shape. Present only when routing overrode the agent-server default: `model`, `runtime_adapter`, and `reasoning_effort`. The nested `derived` object is the harness's own map of boolean run dimensions, computed server-side at finalize: `has_emit_report`, `has_edit_report`, `has_self_improvement`, `has_chart`, and `has_self_validation`. Use `derived` to answer 'what kind of run was this?' instead of parsing the `summary` prose. Note the flags describe the reports the run authored as they stand now, so charts attached to someone else's report via an edit are not counted. A missing `derived` object is unknown, not all-false: the run predates the field, never finalized, or its stamp failed. */metadata: SignalScoutRunDetailApiMetadata}diff --git a/products/signals/skills/exploring-scouts/SKILL.md b/products/signals/skills/exploring-scouts/SKILL.mdindex 79abf3d15285..ebf038d82fe3 100644--- a/products/signals/skills/exploring-scouts/SKILL.md+++ b/products/signals/skills/exploring-scouts/SKILL.md@@ -29,6 +29,9 @@ It is the observability counterpart to the `authoring-scouts` skill (which teach**A scout's output is inbox reports, written 1:1.** Scouts list `emit_report` / `edit_report` in their `allowed_tools` and **author or edit inbox reports directly**; a run's output shows up as **`emitted_report_ids`** (reports it authored) and **`edited_report_ids`** (reports it updated).The run rows also carry `emitted_count` / `emitted_finding_ids` — **legacy fields from the deprecated signal-emitting channel** (weak `emit_signal` findings a pipeline consolidated). On a report-channel scout they stay `0` / empty even on a productive run; a non-zero tally means the run came from a scout still on the legacy channel (an old custom scout, or a canonical scout not yet ported) — real output for that run, not noise. When unsure of a scout's channel, check its `allowed_tools` via `skill-get`.**Never read `emitted_count: 0` as "did nothing"** — check the report columns and the run summary first.+Each run also carries a `metadata` map. Top-level: the provenance set `harness_prompt_version` / `report_channel` (`none`, `emit`, `edit`, or `both`) / `skill_origin` / `github_guidance`, saying which instructions the run was given; plus routing keys (`model` / `runtime_adapter` / `reasoning_effort`) only when a gate or pin overrode the default. Nested under `metadata.derived`: booleans the harness computes at the end of the run (`has_emit_report`, `has_edit_report`, `has_self_improvement`, `has_chart`, `has_self_validation`).+When comparing runs (before/after a prompt change, one model against another), segment on all four provenance values first: runs differing on any of `harness_prompt_version`, `report_channel`, `skill_origin`, or `github_guidance` were given different instructions and aren't a like-for-like population. Runs predating this field have none of them, so treat missing provenance as unknown and exclude those runs from a comparison rather than pooling them.+For "what kind of run was this?" questions — did it author a self-improvement report, did it validate its follow-up queue — read `derived` rather than parsing the prose summary. It's computed server-side from what the run actually did, so it can't disagree with the run's own output. No `derived` map at all means unknown, not "all false" — the run predates the field, failed before finishing, or its stamp failed. Most runs from before this shipped have no map, so don't read their absence as a finding.There are six things you can observe about the fleet, each with its own tool:diff --git a/products/signals/skills/exploring-scouts/references/scout-data-model.md b/products/signals/skills/exploring-scouts/references/scout-data-model.mdindex b62751cff750..dc31d4e80a5b 100644--- a/products/signals/skills/exploring-scouts/references/scout-data-model.md+++ b/products/signals/skills/exploring-scouts/references/scout-data-model.md@@ -30,21 +30,22 @@ The run is a thin bridge to a `tasks.TaskRun` — status, timing, and the full t`runs-retrieve` takes the run id as `id`, **not** `run_id` — even though the list and the detail payload both name the field `run_id`.Pass the list's `run_id` value through as `id`.-| Field | Meaning |-| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `run_id` | UUID of the run. Pass it to `runs-retrieve` as `id`. Strictly team-scoped (404 across teams). |-| `skill_name` | Which scout ran. |-| `skill_version` | The body version that ran. If a scout was edited, older runs ran an older version — useful when comparing behavior before/after a change. |-| `status` | Run outcome, from the linked `TaskRun` (see below). |-| `started_at` | ISO-8601 — when the `TaskRun` was created. |-| `completed_at` | ISO-8601 — when it finished. `null` while in flight. Duration = `completed_at - started_at`. |-| `emitted_report_ids` | The reports the run **authored** via `emit_report`, in order. This (with `edited_report_ids`) is the run's output — resolve each id via `inbox-reports-retrieve`. Empty = the run authored nothing. |-| `edited_report_ids` | The reports the run **edited** via `edit_report` (title/summary rewrite, appended note, or reviewers set), deduped. Edits can target any inbox report, not just scout-authored ones. |-| `emitted_count` | **Legacy** — how many weak findings the run emitted on the deprecated signal channel. Always `0` on report-channel scouts; populated only on runs from scouts still on the legacy channel. Don't infer "did nothing" from `0` — check the report id columns. |-| `emitted_finding_ids` | **Legacy** — the `finding_id`s behind `emitted_count`, in emit order. Each maps to a `Signal` with `source_id = run:<run_id>:finding:<finding_id>`. Empty on report-channel scouts. |-| `task_id`, `task_run_id` | Identifiers on the Tasks side. |-| `task_url` | Relative deep-link to the Tasks UI for this run — **the full transcript** (every tool call and reasoning step) lives here, not in the run payload. |-| `summary` | The scout's own one-paragraph end-of-run close-out. The primary thing to read and relay. Empty for runs that errored before close-out. |+| Field | Meaning |+| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `run_id` | UUID of the run. Pass it to `runs-retrieve` as `id`. Strictly team-scoped (404 across teams). |+| `skill_name` | Which scout ran. |+| `skill_version` | The body version that ran. If a scout was edited, older runs ran an older version — useful when comparing behavior before/after a change. |+| `status` | Run outcome, from the linked `TaskRun` (see below). |+| `started_at` | ISO-8601 — when the `TaskRun` was created. |+| `completed_at` | ISO-8601 — when it finished. `null` while in flight. Duration = `completed_at - started_at`. |+| `emitted_report_ids` | The reports the run **authored** via `emit_report`, in order. This (with `edited_report_ids`) is the run's output — resolve each id via `inbox-reports-retrieve`. Empty = the run authored nothing. |+| `edited_report_ids` | The reports the run **edited** via `edit_report` (title/summary rewrite, appended note, or reviewers set), deduped. Edits can target any inbox report, not just scout-authored ones. |+| `emitted_count` | **Legacy** — how many weak findings the run emitted on the deprecated signal channel. Always `0` on report-channel scouts; populated only on runs from scouts still on the legacy channel. Don't infer "did nothing" from `0` — check the report id columns. |+| `emitted_finding_ids` | **Legacy** — the `finding_id`s behind `emitted_count`, in emit order. Each maps to a `Signal` with `source_id = run:<run_id>:finding:<finding_id>`. Empty on report-channel scouts. |+| `metadata` | Two server-written regions. Top-level keys are runner-stamped at run start: `harness_prompt_version` / `report_channel` (`none`/`emit`/`edit`/`both`) / `skill_origin` / `github_guidance` (the provenance set — which prompt build, which report tools, canonical or custom skill, and whether the GitHub evidence section was rendered; segment on all four before comparing runs, and treat runs missing them as unknown rather than pooling them), plus `model` / `runtime_adapter` / `reasoning_effort` only when routing overrode the default. `metadata.derived` is the harness's own map of booleans computed at finalize (`has_emit_report`, `has_edit_report`, `has_self_improvement`, `has_chart`, `has_self_validation`) — the structured answer to "what kind of run was this?", so read it before parsing `summary`. Nothing here is scout-declared, so it can't contradict the run's actual output. No `derived` map at all means unknown — the run predates the field (most historical runs), never reached finalize, or its stamp failed — never that every flag was false. |+| `task_id`, `task_run_id` | Identifiers on the Tasks side. |+| `task_url` | Relative deep-link to the Tasks UI for this run — **the full transcript** (every tool call and reasoning step) lives here, not in the run payload. |+| `summary` | The scout's own one-paragraph end-of-run close-out. The primary thing to read and relay. Empty for runs that errored before close-out. |### Run status valuesdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a1c1cd12da69..72b692d8fe8d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -62344,10 +62344,28 @@ export namespace Schemas {started: boolean;}+ export type SignalScoutRunDetailMetadataDerived = {+ has_emit_report: boolean;+ has_edit_report: boolean;+ has_self_improvement: boolean;+ has_chart: boolean;+ has_self_validation: boolean;+ };+/**- * Scout-owned per-run context stamped at run start. Known keys today: `model`, `runtime_adapter`, and `reasoning_effort` — the triple the run was routed on when the `scouts-model-selection` gate (or a runtime pin) overrode the agent-server default. Empty object when the run rode the default model, or for runs predating the field.+ * Scout-owned per-run context, in two regions. Top-level keys are stamped by the runner at run start. Always present: `harness_prompt_version` (id of the harness prompt build the run was given), `report_channel` (which report tools the run held: `none`, `emit`, `edit`, or `both`), `skill_origin` (`canonical` or `custom`), and `github_guidance` (whether the run got the GitHub evidence section) — the provenance set that says which instructions the run actually got, so runs are only compared against runs of the same shape. Present only when routing overrode the agent-server default: `model`, `runtime_adapter`, and `reasoning_effort`. The nested `derived` object is the harness's own map of boolean run dimensions, computed server-side at finalize: `has_emit_report`, `has_edit_report`, `has_self_improvement`, `has_chart`, and `has_self_validation`. Use `derived` to answer 'what kind of run was this?' instead of parsing the `summary` prose. Note the flags describe the reports the run authored as they stand now, so charts attached to someone else's report via an edit are not counted. A missing `derived` object is unknown, not all-false: the run predates the field, never finalized, or its stamp failed.*/- export type SignalScoutRunDetailMetadata = {[key: string]: string};+ export type SignalScoutRunDetailMetadata = {+ harness_prompt_version?: string;+ report_channel?: string;+ skill_origin?: string;+ github_guidance?: boolean;+ model?: string;+ runtime_adapter?: string;+ reasoning_effort?: string;+ derived?: SignalScoutRunDetailMetadataDerived;+ [key: string]: unknown;+ };/*** Full `SignalScoutRun` projection used by `get-run`. Same shape as the summary@@ -62414,14 +62432,32 @@ export namespace Schemas {emitted_report_ids: string[];/** The `SignalReport` ids this run mutated via the `edit_report` channel (rewrote title/summary and/or appended a note), deduped. Distinct from `emitted_report_ids`: edit can target any inbox report, so these are generally not reports the run authored. Empty for runs that edited no report. */edited_report_ids: string[];- /** Scout-owned per-run context stamped at run start. Known keys today: `model`, `runtime_adapter`, and `reasoning_effort` — the triple the run was routed on when the `scouts-model-selection` gate (or a runtime pin) overrode the agent-server default. Empty object when the run rode the default model, or for runs predating the field. */+ /** Scout-owned per-run context, in two regions. Top-level keys are stamped by the runner at run start. Always present: `harness_prompt_version` (id of the harness prompt build the run was given), `report_channel` (which report tools the run held: `none`, `emit`, `edit`, or `both`), `skill_origin` (`canonical` or `custom`), and `github_guidance` (whether the run got the GitHub evidence section) — the provenance set that says which instructions the run actually got, so runs are only compared against runs of the same shape. Present only when routing overrode the agent-server default: `model`, `runtime_adapter`, and `reasoning_effort`. The nested `derived` object is the harness's own map of boolean run dimensions, computed server-side at finalize: `has_emit_report`, `has_edit_report`, `has_self_improvement`, `has_chart`, and `has_self_validation`. Use `derived` to answer 'what kind of run was this?' instead of parsing the `summary` prose. Note the flags describe the reports the run authored as they stand now, so charts attached to someone else's report via an edit are not counted. A missing `derived` object is unknown, not all-false: the run predates the field, never finalized, or its stamp failed. */metadata: SignalScoutRunDetailMetadata;}+ export type SignalScoutRunSummaryMetadataDerived = {+ has_emit_report: boolean;+ has_edit_report: boolean;+ has_self_improvement: boolean;+ has_chart: boolean;+ has_self_validation: boolean;+ };+/**- * Scout-owned per-run context stamped at run start. Known keys today: `model`, `runtime_adapter`, and `reasoning_effort` — the triple the run was routed on when the `scouts-model-selection` gate (or a runtime pin) overrode the agent-server default. Empty object when the run rode the default model, or for runs predating the field.+ * Scout-owned per-run context, in two regions. Top-level keys are stamped by the runner at run start. Always present: `harness_prompt_version` (id of the harness prompt build the run was given), `report_channel` (which report tools the run held: `none`, `emit`, `edit`, or `both`), `skill_origin` (`canonical` or `custom`), and `github_guidance` (whether the run got the GitHub evidence section) — the provenance set that says which instructions the run actually got, so runs are only compared against runs of the same shape. Present only when routing overrode the agent-server default: `model`, `runtime_adapter`, and `reasoning_effort`. The nested `derived` object is the harness's own map of boolean run dimensions, computed server-side at finalize: `has_emit_report`, `has_edit_report`, `has_self_improvement`, `has_chart`, and `has_self_validation`. Use `derived` to answer 'what kind of run was this?' instead of parsing the `summary` prose. Note the flags describe the reports the run authored as they stand now, so charts attached to someone else's report via an edit are not counted. A missing `derived` object is unknown, not all-false: the run predates the field, never finalized, or its stamp failed.*/- export type SignalScoutRunSummaryMetadata = {[key: string]: string};+ export type SignalScoutRunSummaryMetadata = {+ harness_prompt_version?: string;+ report_channel?: string;+ skill_origin?: string;+ github_guidance?: boolean;+ model?: string;+ runtime_adapter?: string;+ reasoning_effort?: string;+ derived?: SignalScoutRunSummaryMetadataDerived;+ [key: string]: unknown;+ };/*** Lightweight projection of a `SignalScoutRun` row used by `search-recent-runs`.@@ -62488,7 +62524,7 @@ export namespace Schemas {emitted_report_ids: string[];/** The `SignalReport` ids this run mutated via the `edit_report` channel (rewrote title/summary and/or appended a note), deduped. Distinct from `emitted_report_ids`: edit can target any inbox report, so these are generally not reports the run authored. Empty for runs that edited no report. */edited_report_ids: string[];- /** Scout-owned per-run context stamped at run start. Known keys today: `model`, `runtime_adapter`, and `reasoning_effort` — the triple the run was routed on when the `scouts-model-selection` gate (or a runtime pin) overrode the agent-server default. Empty object when the run rode the default model, or for runs predating the field. */+ /** Scout-owned per-run context, in two regions. Top-level keys are stamped by the runner at run start. Always present: `harness_prompt_version` (id of the harness prompt build the run was given), `report_channel` (which report tools the run held: `none`, `emit`, `edit`, or `both`), `skill_origin` (`canonical` or `custom`), and `github_guidance` (whether the run got the GitHub evidence section) — the provenance set that says which instructions the run actually got, so runs are only compared against runs of the same shape. Present only when routing overrode the agent-server default: `model`, `runtime_adapter`, and `reasoning_effort`. The nested `derived` object is the harness's own map of boolean run dimensions, computed server-side at finalize: `has_emit_report`, `has_edit_report`, `has_self_improvement`, `has_chart`, and `has_self_validation`. Use `derived` to answer 'what kind of run was this?' instead of parsing the `summary` prose. Note the flags describe the reports the run authored as they stand now, so charts attached to someone else's report via an edit are not counted. A missing `derived` object is unknown, not all-false: the run predates the field, never finalized, or its stamp failed. */metadata: SignalScoutRunSummaryMetadata;}