: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): let scouts produce structured outputs (#78106)
Andrew Maguire7b77670f7c31
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 57b096a78254..3ff3adca66d8 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -287,6 +287,7 @@ rules:|SignalScoutRun|SignalScoutEmission|SignalScoutNote+ |SignalScoutStructuredOutput|SignalScratchpad|SignalProjectProfile|SingleSessionSummary@@ -625,6 +626,7 @@ rules:|SignalScoutRun|SignalScoutEmission|SignalScoutNote+ |SignalScoutStructuredOutput|SignalScratchpad|SignalProjectProfile|SingleSessionSummarydiff --git a/frontend/src/scenes/inbox/components/config/scouts/ScoutConfigControls.test.tsx b/frontend/src/scenes/inbox/components/config/scouts/ScoutConfigControls.test.tsxindex 2f8bde386086..53b3867c3b83 100644--- a/frontend/src/scenes/inbox/components/config/scouts/ScoutConfigControls.test.tsx+++ b/frontend/src/scenes/inbox/components/config/scouts/ScoutConfigControls.test.tsx@@ -19,6 +19,7 @@ const config: SignalScoutConfigApi = {run_interval_minutes: 1440,run_cron_schedule: '0 9 * * *',output_destinations: {},+ structured_output_schema: null,last_run_at: null,consecutive_failure_count: 0,status_changed_at: null,diff --git a/frontend/src/scenes/inbox/logics/scoutCreateModalLogic.test.ts b/frontend/src/scenes/inbox/logics/scoutCreateModalLogic.test.tsindex 86f1bef95614..5bbd0cd16d5e 100644--- a/frontend/src/scenes/inbox/logics/scoutCreateModalLogic.test.ts+++ b/frontend/src/scenes/inbox/logics/scoutCreateModalLogic.test.ts@@ -39,6 +39,7 @@ const CREATED_SCOUT: SignalScoutCreateResponseApi = {run_interval_minutes: 60,run_cron_schedule: null,output_destinations: {},+ structured_output_schema: null,last_run_at: null,consecutive_failure_count: 0,status_changed_at: null,diff --git a/frontend/src/scenes/inbox/logics/scoutFleetLogic.test.ts b/frontend/src/scenes/inbox/logics/scoutFleetLogic.test.tsindex b82bc191d2e5..c4a734389594 100644--- a/frontend/src/scenes/inbox/logics/scoutFleetLogic.test.ts+++ b/frontend/src/scenes/inbox/logics/scoutFleetLogic.test.ts@@ -44,6 +44,7 @@ const BASE_CONFIG: SignalScoutConfigApi = {run_interval_minutes: 1440,run_cron_schedule: null,output_destinations: {},+ structured_output_schema: null,last_run_at: null,consecutive_failure_count: 0,status_changed_at: null,diff --git a/products/signals/backend/migrations/0086_signalscoutconfig_structured_output_schema.py b/products/signals/backend/migrations/0086_signalscoutconfig_structured_output_schema.pynew file mode 100644index 000000000000..830531a23dd0--- /dev/null+++ b/products/signals/backend/migrations/0086_signalscoutconfig_structured_output_schema.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-08-05 11:03++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("signals", "0085_signalscoutnote_feedback_origin"),+ ]++ operations = [+ migrations.AddField(+ model_name="signalscoutconfig",+ name="structured_output_schema",+ field=models.JSONField(blank=True, null=True),+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex be0e4d6c2087..5c6ce8ba1544 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0085_signalscoutnote_feedback_origin+0086_signalscoutconfig_structured_output_schemadiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex f1918276daa3..a754cbcc72c7 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -1269,6 +1269,15 @@ class SignalScoutConfig(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):# config columns. A Slack destination is active only when both its integration and channel# are present; the UI may persist the integration first while the user chooses a channel.output_destinations = models.JSONField(default=dict, db_default={})+ # Optional JSON Schema (draft 2020-12, object-rooted) describing one structured record this+ # scout produces via `scout-record-output`. Null = the channel is off: the record endpoint+ # fails closed and the run prompt renders no structured-output section. Records land solely+ # as `$scout_structured_output` events in the project, so the channel also requires `emit`+ # (a dry-run scout has nowhere to record to). Serializer-validated (must compile as a+ # schema, bounded size) — this field is only written through the config API. The schema+ # describes ONE record; cardinality is the scout's call (one record per run, one per judged+ # entity, ...), so no separate mode enum is stored.+ structured_output_schema = models.JSONField(null=True, blank=True)# Optional five-field cron expression anchoring runs to wall-clock slots (e.g. "30 9 * * *",# "0 9,17 * * *", "0 9 * * 1-5"). Takes precedence over the rolling `run_interval_minutes`# when set. The coordinator evaluates it in `team.timezone`, so scheduled times followdiff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex 55ffac4b9d51..7a734f6e534d 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -30,6 +30,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e- `emit.py` — `emit_signal_*` tools that push findings as `cross_source_issue` signals into the standard ingestion pipeline.- `scratchpad.py` — `remember`, `forget`, and `search_scratchpad` tools backed by the `SignalScratchpad` model.- `notes.py` — `list_notes` / `leave_note` / `delete_note` backed by the `SignalScoutNote` model: steering notes humans (or other agents) leave for the fleet over the public MCP surface (`scout-notes-*` tools), the inbound counterpart to the scratchpad. A note targets one scout by `skill_name` or the whole fleet (blank), optionally expiring via `expires_at`; the run prompt's _Notes left for you_ section directs every scout to `scout-notes-list` its own notes in step 1 and treat them as advisory steering. Unlike the scratchpad there is no sandbox-only write gate, but writes still demand skill-authoring-level authorization (keys need `llm_skill:write` on top of `signal_scout:write`, and every writer must clear the `llm_skill` RBAC editor bar) — so a note-writer could already steer the fleet by editing its skills, and notes add no new steering power. Three more writers derive rows from inbox activity. `../dismissal_notes.py`: judging an inbox report with a note (dismiss, snooze, or restore) also leaves it here as an `origin=report_dismissal` note, targeted at the scout that authored the report, so a reviewer's verdict reaches the scout without it having to re-find the report. Resolving does not, since that says the report did its job rather than that filing it was wrong. `../discussion_notes.py`: opening a discussion on a report (the inbox "Discuss" action, which kicks off a Q&A task) also leaves the user's question here as an `origin=report_discussion` note, targeted at the authoring scout — framed as context to weigh or ignore, not a verdict, so the scout can fold a durable preference/correction into its scratchpad or dismiss it as noise. `../feedback_notes.py`: the thumbs rating at the end of a report body ("Was this report useful?") carries its optional note here as an `origin=report_feedback` note, targeted at the authoring scout. Unlike a dismissal it never falls back to a fleet-wide note — feedback is a verdict on one scout's own report, so with no resolvable authoring scout nothing is forwarded and the call is a no-op — and it never changes the report's state; the analytics event the client fires stays the durable record of the rating. All three paths re-check the same steering gate (token `scoped_teams`, canonical-project access, and the `llm_skill` editor bar) since the dismiss, discuss, and feedback actions need only `task:write`, and all forward only on the canonical team. The discuss and feedback paths additionally demand the `signal_scout:write` / `llm_skill:write` key scopes: a dismissal's text reaches runs anyway through the reports API, whereas the note is the only path a discussion question or feedback note takes to a scout, so a `task:write` credential must not open it alone. The discuss path is triggered from the tasks viewset (which holds the request the gate reads) through `facade/api.py:forward_report_discussion_note`, never from the tasks facade. On the read side, all three derived origins quote report content (report id, title, the note text), so `SignalScoutNoteViewSet.list` withholds them from any caller failing the reports read gate (`_may_read_reports`). The derived rows are context with a TTL; the `dismissal` artefact / discussion task / feedback analytics event stays the record of truth.+ - `structured_output.py` — `record_structured_output` (+ `_sync`): the structured-output channel, next to signals and reports. Opt-in via `SignalScoutConfig.structured_output_schema` (a JSON Schema describing ONE record, validated at config-write time by `validate_structured_output_schema` — which also rejects non-local `$ref`/`$dynamicRef`, and every validator here uses a no-retrieval registry, so a user-controlled schema can never make the worker fetch a URL; null = channel off, and the record endpoint fails closed). Setting the schema is skill-authoring-level steering (schema `description` fields are free prose rendered verbatim into a privileged prompt), so the config viewset gates it behind `llm_skill:write` + the `llm_skill` editor bar, like scout notes; clearing it stays on the base config scope. Records validate against the dispatch-time schema snapshot the runner stamps on the run row (`metadata["structured_output_schema"]`), so a mid-run schema edit can't reject records matching what the run was shown — while clearing the config schema mid-run still fails the channel closed (re-checked inside the capacity-reservation transaction with the config row locked, so a clear racing a submit serializes cleanly). Each submitted record is validated against the schema (all-or-nothing per call — an invalid record fails the batch with nothing written) and written into the team's own project as a `$scout_structured_output` event via one `capture_batch_internal` call (person processing off, deterministic uuid over `(run, batch index, subject, payload)` so a resubmitted batch collapses at ingestion while in-batch duplicates stay distinct). The events ARE the record — there is no Postgres row store, so past records are read like any events (insights, HogQL) and retention follows event retention — which is also why a delivery failure fails the call (`StructuredOutputDeliveryError` → 503) with an instruction to retry — the events carry a stable timestamp (the run's `created_at`) alongside the deterministic uuid, so the dedupe sorting key (`toDate(timestamp)` is part of it) stays identical across retries even past UTC midnight — and why the channel fails loudly for a dry-run `emit=False` scout, an org without AI-processing consent (mirroring `emit._preflight_emit_gates`), or a disabled `signals_scout` source instead of suppressing quietly (the runner also withholds the prompt section and schema snapshot when `emit` is off). Cardinality is the scout's call — the schema describes one record; a run may submit one, one per judged entity, or a batch (caps: `MAX_RECORDS_PER_CALL` per call, `MAX_RECORDS_PER_RUN` per run via the `structured_output_count` counter on `run.metadata`, reserved under the run-row lock before the forward — it counts accepted batches, so failed or retried forwards still spend cap). The prompt renders the exact configured schema in a per-run `# Structured output` section only when the channel is live, so the prompt and the validator can never describe two different contracts.- `profile.py` — `project_profile_*` tools that read the deterministic `SignalProjectProfile` snapshot.- `runs.py` — `runs_*` tools that read past `SignalScoutRun` rows for dedupe and cross-skill awareness.- `profile/`@@ -92,7 +93,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick eNew 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.+ Both regions surface on the run serializers / `scout-runs-*` MCP tools, with one exception: the dispatch-time `structured_output_schema` snapshot is stripped on the way out (`RunMetadataField.to_representation`) — it exists for record validation, and repeating up to 20 KB of schema per row would bloat every run listing.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 + emit count), and `signals_scout_run_reaped` (a stranded orphan was reaped by `_self_heal_stale_runs`). They join on `run_id`/`task_run_id` and are the event-derived (no-warehouse-lag) basis for throughput, stall, and worker-death alerting — a `started` with no `finished` is a run that died before finalize; a reaped run emits no `finished`.diff --git a/products/signals/backend/scout_harness/derived_metadata.py b/products/signals/backend/scout_harness/derived_metadata.pyindex 8c2918d39ac7..5bcfbdfaac70 100644--- a/products/signals/backend/scout_harness/derived_metadata.py+++ b/products/signals/backend/scout_harness/derived_metadata.py@@ -27,6 +27,7 @@ from django.db import transactionfrom products.signals.backend.models import SignalReport, SignalScoutRun, SignalScratchpadfrom products.signals.backend.scout_harness.prompt import FOLLOWUP_KEY_PREFIXfrom products.signals.backend.scout_harness.tools.report import is_self_improvement_title+from products.signals.backend.scout_harness.tools.structured_output import STRUCTURED_OUTPUT_COUNT_KEYlogger = logging.getLogger(__name__)@@ -41,6 +42,7 @@ DERIVED_FLAG_KEYS = ("has_self_improvement","has_chart","has_self_validation",+ "has_structured_output",)@@ -68,6 +70,11 @@ def build_derived_flags(*, run: SignalScoutRun, team_id: int) -> dict[str, bool]"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),+ # The record endpoint bumps this counter on the run row under lock, so it's a+ # server-side observation, not a scout self-report. It counts accepted batches —+ # a batch whose event delivery then failed still registers here, which the+ # flood-breaker semantics of the counter accept (see STRUCTURED_OUTPUT_COUNT_KEY).+ "has_structured_output": bool((run.metadata or {}).get(STRUCTURED_OUTPUT_COUNT_KEY)),}diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.pyindex cda2f6ec7267..b73f06dae1bc 100644--- a/products/signals/backend/scout_harness/prompt.py+++ b/products/signals/backend/scout_harness/prompt.py@@ -605,6 +605,36 @@ Your skill is a canonical PostHog-authored skill that runs on many projects, and- Routing: this channel is only for the content of your canonical skill body. A problem with the tools, the harness, or these shared instructions goes through *Report operational friction* above, like any other run, under the same bar and etiquette: a concrete failure or waste observed this run, at most one submission per run, near close-out, mentioned in your summary."""+def _structured_output_section(schema: dict | None) -> str:+ """Compose the structured-output section, or empty when the config carries no schema.++ Per-run composed (like the follow-ups section) because the schema is per-team config data,+ not a template: the section renders the exact schema the record endpoint will enforce, so+ the prompt and the validator can never describe two different contracts. The section only+ exists when the channel is on — naming `scout-record-output` on a scout whose channel is+ off (no schema, or dry-run: the runner passes None for both) would steer it at a tool+ that fails closed.+ """+ if not schema:+ return ""+ schema_text = json.dumps(schema, indent=2, sort_keys=True)+ return f"""# Structured output++This scout's config carries a structured output schema, so producing records is part of this run's job, alongside everything above. Each record is one measurement (a judgment, a score, a classification) matching the schema below. How many records a run produces is your skill's call – one per run, one per entity you judged, or none when the skill's bar isn't met.++<jsonschema>+{schema_text}+</jsonschema>++- Record via `scout-record-output`, passing your `run_id` and a `records` list; each entry is `{{"payload": <object matching the schema>, "subject": "<optional key naming what the record is about, e.g. a report id>"}}`.+- Set `subject` whenever a record is about one specific entity, so that entity's records can be followed across runs without parsing payloads.+- Batch: submit many records per call (up to 100) rather than one call per record.+- Validation is all-or-nothing per call: if any record fails the schema, nothing is recorded and the error names the failing records – fix them and resubmit the whole batch.+- Each record lands in this project as a `$scout_structured_output` event – past records are queryable like any event (your payload's scalar keys are flattened to `output_<key>` properties, `subject` and `run_id` ride alongside).+- Recording is idempotent: resubmitting an identical batch cannot double-count, so if a call fails with a delivery error, retry the same call.+- Records complement your other outputs, they don't replace them: still write your scratchpad entries and close-out summary, and mention how many records you produced."""++_OPERATIONAL_FRICTION = """# Report operational frictionYou run this tooling end to end on a schedule, so your experience is how PostHog makes the scout system better over time. If something gets in your way as you work (a tool you needed was missing, a tool returned wrong, confusing, or unusable data, an error you couldn't recover from, the project profile lacked something you expected, or these instructions sent you down the wrong path), report it via the `agent-feedback` MCP tool when it's available to you this run.@@ -632,9 +662,10 @@ Respond at end_turn with a single JSON object matching this schema:</jsonschema>"""-def _signal_tail_sections(*, followup_section: str) -> list[str]:+def _signal_tail_sections(*, followup_section: str, structured_output_section: str = "") -> list[str]:"""Signal-channel tail. `followup_section` is the per-run composed self-validation section —- channel-matched, so it can't live in a static list."""+ channel-matched, so it can't live in a static list; `structured_output_section` is likewise+ per-run composed (empty when the config carries no schema)."""return [_HOW_A_RUN_WORKS_SIGNAL,# Ground rules lead the tail: the untrusted-input rule is stated once there, and the sections@@ -645,6 +676,7 @@ def _signal_tail_sections(*, followup_section: str) -> list[str]:_FLEET_SEAMS,followup_section,_RECENCY_LENS,+ *([structured_output_section] if structured_output_section else []),_FINDING_SCHEMA,_TAGGING,_WRITING_DESCRIPTION_SIGNAL,@@ -658,7 +690,12 @@ def _signal_tail_sections(*, followup_section: str) -> list[str]:def _report_tail_sections(- *, can_emit: bool, can_edit: bool, followup_section: str, github_read_access: bool = False+ *,+ can_emit: bool,+ can_edit: bool,+ followup_section: str,+ github_read_access: bool = False,+ structured_output_section: str = "",) -> list[str]:"""Report-channel tail, tailored to the report tools the scout actually opted into.@@ -709,6 +746,7 @@ def _report_tail_sections(_FLEET_SEAMS,followup_section,_RECENCY_LENS,+ *([structured_output_section] if structured_output_section else []),*channel_sections,_WRITING_STYLE,_WRITING_SUMMARY,@@ -772,6 +810,7 @@ def build_run_prompt(team_id: int,started_at: datetime,github_read_access: bool = False,+ structured_output_schema: dict | None = None,) -> str:"""Render the opening prompt for one scout run.@@ -824,6 +863,7 @@ def build_run_prompt(followup_section = _self_validation_followups_section(report_channel=report_channel, can_emit_report=can_emit_report, can_edit_report=can_edit_report)+ structured_output_section = _structured_output_section(structured_output_schema)if report_channel:intro = _report_intro(can_emit=can_emit_report, can_edit=can_edit_report)sections = _report_tail_sections(@@ -831,13 +871,16 @@ def build_run_prompt(can_edit=can_edit_report,followup_section=followup_section,github_read_access=github_read_access,+ structured_output_section=structured_output_section,)# Point the run-identity line at a report tool the scout can actually call — prefer authoring,# fall back to editing for an edit-only scout. Never name a tool that would fail closed.emit_tool = "scout-emit-report" if can_emit_report else "scout-edit-report"else:intro = _BASE_PROMPT_INTRO- sections = _signal_tail_sections(followup_section=followup_section)+ sections = _signal_tail_sections(+ followup_section=followup_section, structured_output_section=structured_output_section+ )emit_tool = "scout-emit-signal"# Slot the origin-matched improvement channel between friction reporting and the output format# (the last element of every tail): a custom scout suggests changes to its team-owned body viadiff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.pyindex e128eba4ade6..b001c65e916e 100644--- a/products/signals/backend/scout_harness/runner.py+++ b/products/signals/backend/scout_harness/runner.py@@ -523,7 +523,15 @@ 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_guidance+ skill,+ run_id=str(run_id),+ team_id=team.id,+ started_at=started_at,+ github_read_access=github_guidance,+ # 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),)logger.info("signals_scout: spawning sandbox",@@ -776,6 +784,14 @@ def _create_run_row(# 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+ # 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_schemareturn SignalScoutRun.objects.unscoped().create(id=run_id,task_run=task_run,diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex bdde385eeb29..13c75af2c97d 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -10,6 +10,7 @@ shape and Python shape stay in lockstep.from __future__ import annotationsfrom datetime import UTC, datetime+from typing import Anyfrom django.utils import timezone@@ -39,6 +40,12 @@ from products.signals.backend.scout_harness.tools.notes import MAX_NOTE_CONTENT_from products.signals.backend.scout_harness.tools.report import MAX_REPORT_TITLE_LENGTH, MAX_SUGGESTED_REVIEWERSfrom products.signals.backend.scout_harness.tools.runs import DEFAULT_FINDINGS_WINDOW_HOURS, MAX_FINDINGS_WINDOW_HOURSfrom products.signals.backend.scout_harness.tools.scratchpad import MAX_SCRATCHPAD_CONTENT_LENGTH+from products.signals.backend.scout_harness.tools.structured_output import (+ MAX_RECORDS_PER_CALL,+ MAX_SUBJECT_LENGTH,+ StructuredOutputSchemaError,+ validate_structured_output_schema,+)from products.signals.backend.serializers import ReportChartSerializerfrom products.skills.backend.api.skill_serializers import (MAX_SKILL_FILE_COUNT,@@ -89,8 +96,19 @@ class RunMetadataField(serializers.DictField):and it coerced the nested `derived` map to its string repr on the way out, turning a queryableobject 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.++ The dispatch-time `structured_output_schema` snapshot is stripped on the way out: it exists+ for record validation (`_resolve_schema` reads the row directly), can be 20 KB, and would+ otherwise repeat on every row of a run listing — megabytes of schema text no run consumer+ needs, in responses scouts read inside their own prompts."""+ def to_representation(self, value: Any) -> Any:+ data = super().to_representation(value)+ if isinstance(data, dict):+ data.pop("structured_output_schema", None)+ return data+class SignalScoutRunSummarySerializer(serializers.Serializer):"""Lightweight projection of a `SignalScoutRun` row used by `search-recent-runs`.@@ -367,6 +385,71 @@ class RecentEmissionsQuerySerializer(serializers.Serializer):)+# --- Structured outputs ----------------------------------------------------+++@extend_schema_field(OpenApiTypes.OBJECT)+class StructuredOutputPayloadField(serializers.JSONField):+ """One structured record as a JSON object. Its real shape is the scout config's+ `structured_output_schema`, which is per-team data — so the OpenAPI type stays a+ generic object rather than a fixed schema."""+++class StructuredOutputRecordSerializer(serializers.Serializer):+ """One record submitted through `scout-record-output`."""++ payload = StructuredOutputPayloadField(+ help_text=(+ "The record itself, as a JSON object. Must validate against the scout config's "+ "`structured_output_schema` (shown in the run prompt); any invalid record fails the whole "+ "call with nothing written."+ ),+ )+ subject = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ max_length=MAX_SUBJECT_LENGTH,+ help_text=(+ "Optional key naming what this record is about — a report id, URL, account key — so "+ "per-entity lookups don't need to parse `payload`. Omit for a run-level record."+ ),+ )+++class RecordStructuredOutputRequestSerializer(serializers.Serializer):+ """Request body for `scout-record-output`: a batch of schema-validated records."""++ records = serializers.ListField(+ child=StructuredOutputRecordSerializer(),+ allow_empty=False,+ # `allow_empty` alone doesn't reach the OpenAPI schema; `min_length` emits `minItems: 1`+ # so generated MCP/Zod clients can't construct an empty batch the API would 400.+ min_length=1,+ max_length=MAX_RECORDS_PER_CALL,+ help_text=(+ "Records to record, each validated against the scout config's `structured_output_schema`. "+ "All-or-nothing: if any record fails validation, nothing is written and the error names the "+ f"failing records. Capped at {MAX_RECORDS_PER_CALL} per call; batch per-entity judgments "+ "rather than calling once per record."+ ),+ )+++class RecordStructuredOutputResponseSerializer(serializers.Serializer):+ """Outcome of an accepted `scout-record-output` call."""++ recorded_count = serializers.IntegerField(help_text="How many records were recorded (all of them, or none).")+ record_ids = serializers.ListField(+ child=serializers.UUIDField(),+ help_text=(+ "Deterministic event ids of the recorded `$scout_structured_output` events, in submission "+ "order. Stable across a resubmission of the identical batch, which is what makes retrying "+ "a failed delivery safe."+ ),+ )++class FleetFindingsSummarySerializer(serializers.Serializer):"""Fleet-wide tally of recent scout output — legacy `emit_signal` findings plus reportsauthored/edited via the report channel. Backs the "Scout findings" callout so it renders@@ -1876,6 +1959,37 @@ def _validate_output_destinations(value: dict, context: dict) -> dict:return {"slack": slack}+@extend_schema_field(OpenApiTypes.OBJECT)+class StructuredOutputSchemaField(serializers.JSONField):+ """A JSON Schema (draft 2020-12) as a JSON object. Free-form at the OpenAPI layer —+ it's a schema-about-data, so its own shape is only bounded by JSON Schema itself."""+++_STRUCTURED_OUTPUT_SCHEMA_HELP = (+ "Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces "+ "via `scout-record-output` — e.g. a per-report quality judgment "+ '(`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, '+ '"reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). '+ 'The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: '+ "the run prompt renders the schema and every submitted record is validated against it and recorded "+ "in the project as a `$scout_structured_output` event, queryable like any event. The channel also "+ "requires emit — a dry-run scout has nowhere to record to. "+ "Cardinality is the scout's call (one record per run, one per judged entity, ...). "+ "Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` "+ "scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs "+ "only the config write. Records validate against the schema in force when the run was dispatched."+)+++def _validate_structured_output_schema(value: dict | None) -> dict | None:+ if value is None:+ return None+ try:+ return validate_structured_output_schema(value)+ except StructuredOutputSchemaError as exc:+ raise serializers.ValidationError(str(exc))++class SignalScoutConfigSerializer(serializers.ModelSerializer):"""Read shape for a per-(team, skill) scout config.@@ -1953,6 +2067,11 @@ class SignalScoutConfigSerializer(serializers.ModelSerializer):read_only=True,help_text="Destinations that receive each finding or report this scout emits. Empty when none is configured.",)+ structured_output_schema = StructuredOutputSchemaField(+ read_only=True,+ allow_null=True,+ help_text=_STRUCTURED_OUTPUT_SCHEMA_HELP,+ )network_access = serializers.ChoiceField(choices=SignalScoutConfig.NetworkAccess.choices,read_only=True,@@ -2025,6 +2144,7 @@ class SignalScoutConfigSerializer(serializers.ModelSerializer):"run_interval_minutes","run_cron_schedule","output_destinations",+ "structured_output_schema","network_access","last_run_at","consecutive_failure_count",@@ -2154,6 +2274,11 @@ class SignalScoutConfigUpdateSerializer(serializers.ModelSerializer):"`no_output` quiet warning. Set it on watchdog scouts whose value is staying quiet."),)+ structured_output_schema = StructuredOutputSchemaField(+ required=False,+ allow_null=True,+ help_text=_STRUCTURED_OUTPUT_SCHEMA_HELP,+ )def validate_run_cron_schedule(self, value: str | None) -> str | None:return _validate_run_cron_schedule(value) if value is not None else None@@ -2161,6 +2286,9 @@ class SignalScoutConfigUpdateSerializer(serializers.ModelSerializer):def validate_output_destinations(self, value: dict) -> dict:return _validate_output_destinations(value, self.context)+ def validate_structured_output_schema(self, value: dict | None) -> dict | None:+ return _validate_structured_output_schema(value)+def update(self, instance: SignalScoutConfig, validated_data: dict) -> SignalScoutConfig:# Re-anchor the coordinator's cron due-check only when the schedule actually changes —# an emit/enabled-only save must not defer an already-overdue scheduled run.@@ -2234,6 +2362,7 @@ class SignalScoutConfigUpdateSerializer(serializers.ModelSerializer):"run_interval_minutes","run_cron_schedule","output_destinations",+ "structured_output_schema","network_access","auto_pause_exempt",]@@ -2291,6 +2420,11 @@ class SignalScoutConfigOptionsSerializer(serializers.Serializer):"Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart."),)+ structured_output_schema = StructuredOutputSchemaField(+ required=False,+ allow_null=True,+ help_text=_STRUCTURED_OUTPUT_SCHEMA_HELP,+ )def validate_run_cron_schedule(self, value: str | None) -> str | None:return _validate_run_cron_schedule(value) if value is not None else None@@ -2302,6 +2436,9 @@ class SignalScoutConfigOptionsSerializer(serializers.Serializer):context = {**context, "project_id": getattr(team, "project_id", None)}return _validate_output_destinations(value, context)+ def validate_structured_output_schema(self, value: dict | None) -> dict | None:+ return _validate_structured_output_schema(value)+class SignalScoutConfigCreateSerializer(SignalScoutConfigOptionsSerializer):"""Request body for registering a scout config without waiting for the coordinator tick.diff --git a/products/signals/backend/scout_harness/tools/__init__.py b/products/signals/backend/scout_harness/tools/__init__.pyindex 7a0058e4b151..0ecde30ca769 100644--- a/products/signals/backend/scout_harness/tools/__init__.py+++ b/products/signals/backend/scout_harness/tools/__init__.py@@ -52,6 +52,18 @@ from products.signals.backend.scout_harness.tools.scratchpad import (remember,search_scratchpad,)+from products.signals.backend.scout_harness.tools.structured_output import (+ MAX_RECORDS_PER_CALL,+ MAX_RECORDS_PER_RUN,+ InvalidStructuredOutputError,+ RecordStructuredOutputResult,+ StructuredOutputDeliveryError,+ StructuredOutputRecord,+ StructuredOutputSchemaError,+ record_structured_output,+ record_structured_output_sync,+ validate_structured_output_schema,+)__all__ = ["DEFAULT_RUN_SEARCH_LIMIT",@@ -62,15 +74,22 @@ __all__ = ["InvalidEmitError","InvalidNoteError","InvalidScratchpadError",+ "InvalidStructuredOutputError","MAX_EVIDENCE_ENTRIES",+ "MAX_RECORDS_PER_CALL",+ "MAX_RECORDS_PER_RUN","MAX_RUN_SEARCH_LIMIT","MAX_TAG_LENGTH","MAX_TAGS_PER_FINDING","PROFILE_TTL","ProjectProfile",+ "RecordStructuredOutputResult","ReportEvidence","ScoutNote","ScratchpadEntry",+ "StructuredOutputDeliveryError",+ "StructuredOutputRecord",+ "StructuredOutputSchemaError","RunDetail","RunSummary","compute_project_profile",@@ -86,7 +105,10 @@ __all__ = ["leave_note","list_notes","normalize_tags",+ "record_structured_output",+ "record_structured_output_sync","remember","search_scratchpad","search_recent_runs",+ "validate_structured_output_schema",]diff --git a/products/signals/backend/scout_harness/tools/structured_output.py b/products/signals/backend/scout_harness/tools/structured_output.pynew file mode 100644index 000000000000..f4c396455c9a--- /dev/null+++ b/products/signals/backend/scout_harness/tools/structured_output.py@@ -0,0 +1,531 @@+"""Structured-output adapter: schema-validated records a scout submits during a run.++The third output channel, next to signals (`emit.py`) and reports (`report.py`). A scout+whose job is a recurring *measurement* — judging, scoring, classifying entities on a+schedule — produces data, not prose: its output only becomes useful when it can be+filtered and charted per record. This channel gives that shape a contract: the scout's+`SignalScoutConfig.structured_output_schema` (a JSON Schema describing ONE record) is the+opt-in, every submitted record is validated against it, and each accepted record becomes a+customer-facing `$scout_structured_output` event in the team's own project, so the records+are chartable in PostHog — trend a `verdict` breakdown, alert on a rate — with no export+step. The events ARE the record: there is no parallel Postgres copy, so past records are+read back the way any event is (insights, HogQL over `events`), and retention follows the+project's event retention.++Validation is all-or-nothing per call: if any record fails the schema, nothing is written+and the error names the failing records, so the agent can fix and resubmit the batch+without deduping a partial write. Each event carries a deterministic uuid derived from+`(run, batch index, subject, payload)`, so resubmitting an identical batch collapses at+ingestion instead of double-firing downstream automation, while in-batch duplicate records+still count separately — which is what makes "retry on delivery failure" safe to instruct.+Events for a batch go out as ONE `capture_batch_internal` POST, never one HTTP call per+record, and a failed POST fails the call: the events are the only write, so a swallowed+delivery failure would silently lose the run's output.++Cardinality is deliberately the scout's call, not a config mode: the schema describes one+record, and the scout may submit one per run, one per judged entity, or a batch per call+(`MAX_RECORDS_PER_CALL`), bounded per run by `MAX_RECORDS_PER_RUN` via a counter on the+run row.+"""++from __future__ import annotations++import json+import uuid+import asyncio+import logging+from dataclasses import dataclass+from typing import Any++from django.db import transaction++import posthoganalytics+from jsonschema import Draft202012Validator+from referencing import Registry+from referencing.exceptions import NoSuchResource++from posthog.api.capture import capture_batch_internal+from posthog.event_usage import groups+from posthog.models import Team++from products.signals.backend.models import SignalScoutConfig, SignalScoutRun, SignalSourceConfig+from products.signals.backend.scout_harness.tools.emit import SOURCE_PRODUCT, SOURCE_TYPE++logger = logging.getLogger(__name__)++# Per-call batch bound: large enough for "judge 100 sampled entities" in one call, small+# enough that a single request body stays well-bounded.+MAX_RECORDS_PER_CALL = 100+# Per-run ceiling across calls — a circuit breaker against a looping agent flooding the+# project's event stream, far above any sane per-run record count.+MAX_RECORDS_PER_RUN = 1000+# Serialized size cap per record. Records are data points, not documents; a judgment with+# a reason fits in a fraction of this.+MAX_RECORD_BYTES = 16_384+# Cap on the scout-chosen `subject` key, sized like a name column, not a document.+MAX_SUBJECT_LENGTH = 200+# Serialized size cap on the configured schema, enforced by the config serializers. Kept+# here so the schema validator and the write path agree on one constant.+MAX_SCHEMA_BYTES = 20_000++# Customer-facing per-record event (see `tools/report.py` for the `$`-prefix convention:+# a PostHog-generated event kept out of the customer's own custom-event namespace).+CUSTOMER_STRUCTURED_OUTPUT_EVENT = "$scout_structured_output"+_STRUCTURED_OUTPUT_EVENT_SOURCE = "signals_scout_structured_output"++# `SignalScoutRun.metadata` key holding how many records this run has had accepted, bumped+# under the run-row lock so concurrent calls can't overshoot `MAX_RECORDS_PER_RUN`. Counts+# accepted batches, not delivered events: it's the flood breaker (and the source of the+# `derived.has_structured_output` flag), not an accounting ledger, so a batch whose forward+# then fails — or is retried — still spends cap.+STRUCTURED_OUTPUT_COUNT_KEY = "structured_output_count"+++def _refuse_retrieval(uri: str) -> Any:+ """Registry retrieval callback that always fails. The schema is user-controlled, so+ resolving a non-local reference must never turn into the worker fetching an arbitrary+ (possibly internal) URL — an SSRF vector. Local `#/...` refs resolve in-document and+ never reach this; anything else fails closed here as defense-in-depth behind the+ write-time local-refs-only rule."""+ raise NoSuchResource(ref=uri) # type: ignore[call-arg]+++# Explicit no-network resolution for every validator this module builds. `retrieve` is the+# documented keyword; the type stubs don't model the attrs alias, hence the ignore.+_NO_RETRIEVAL_REGISTRY: Registry = Registry(retrieve=_refuse_retrieval) # type: ignore[call-arg]++# Keys whose value is a reference the validator would try to resolve.+_REFERENCE_KEYS = ("$ref", "$dynamicRef", "$recursiveRef")+# Regex-bearing keywords. Python's `re` backtracks, so a pathological pattern (`^(a+)+$`)+# against a near-matching payload can pin a worker for minutes, and nothing can interrupt a+# match in flight — the size caps bound bytes, not regex time. Measurement records don't+# need regex (enums, types, ranges, required cover the channel), so these fail closed.+_REGEX_KEYWORDS = ("pattern", "patternProperties")+# Keys whose immediate child keys are user-chosen names (e.g. property names), not JSON+# Schema keywords — a property legitimately named `pattern` must not read as the keyword.+_NAME_MAP_KEYS = ("properties", "$defs", "definitions", "dependentSchemas")+# Keys whose value is data, not schema — an example payload may contain a `pattern` key.+_DATA_KEYS = ("default", "const", "enum", "examples")+++class InvalidStructuredOutputError(ValueError):+ """The submission is malformed: no schema configured, the channel is off for this scout+ (dry-run, or the signals_scout source disabled), batch/record caps exceeded, or a record+ failed validation against the configured schema."""+++class StructuredOutputSchemaError(ValueError):+ """The supplied JSON Schema itself is invalid (raised at config-write time)."""+++class StructuredOutputDeliveryError(RuntimeError):+ """The records validated but the event forward failed, so nothing was recorded.++ Transient by nature (the capture endpoint was unreachable or rejected the batch), and+ safe to retry: event uuids are deterministic per `(run, batch index, subject, payload)`,+ so resubmitting the same batch cannot double-count."""+++@dataclass(frozen=True, kw_only=True)+class StructuredOutputRecord:+ """One record the agent submits: the schema-validated `payload` plus an optional+ `subject` naming what the record is about (a report id, URL, account key, ...)."""++ payload: dict[str, Any]+ subject: str | None = None+++@dataclass(frozen=True, kw_only=True)+class RecordStructuredOutputResult:+ """Outcome of an accepted `record_structured_output` call — validation failures raise+ `InvalidStructuredOutputError` and delivery failures raise `StructuredOutputDeliveryError`+ instead, so an instance always means the batch's events were accepted by capture.+ `record_ids` are the deterministic event uuids, in submission order."""++ recorded_count: int+ record_ids: list[str]+++def validate_structured_output_schema(schema: Any) -> dict[str, Any]:+ """Validate a user-supplied JSON Schema for the config field and return it.++ Called by the config serializers at write time so a broken schema is rejected at the+ boundary rather than failing every run's record call. Requires a JSON object rooted at+ `"type": "object"` — the record endpoint stores dict payloads, and an object root is+ what keeps each record breakdown-friendly downstream — and bounds serialized size so+ the schema stays a cheap per-record validation, not a document."""+ if not isinstance(schema, dict) or not schema:+ raise StructuredOutputSchemaError("structured_output_schema must be a non-empty JSON object")+ if schema.get("type") != "object":+ raise StructuredOutputSchemaError('structured_output_schema must declare "type": "object" at its root')+ encoded = json.dumps(schema)+ if len(encoded.encode("utf-8")) > MAX_SCHEMA_BYTES:+ raise StructuredOutputSchemaError(f"structured_output_schema exceeds {MAX_SCHEMA_BYTES} bytes serialized")+ _assert_supported_constructs(schema)+ try:+ Draft202012Validator.check_schema(schema)+ except Exception as exc:+ raise StructuredOutputSchemaError(f"structured_output_schema is not a valid JSON Schema: {exc}") from exc+ return schema+++def _assert_supported_constructs(node: Any) -> None:+ """Reject schema constructs that would let a schema author attack the validating worker.++ Two families, both walked recursively. Non-fragment `$ref` / `$dynamicRef` /+ `$recursiveRef` would ask the validator to fetch an arbitrary URL at record time+ (SSRF) — only in-document `#...` references are supported, with the no-retrieval+ registry as the fail-closed backstop for schemas that predate this rule. Regex keywords+ (`pattern`, `patternProperties`) are rejected outright: a catastrophic expression pins+ the worker during `iter_errors` and cannot be interrupted (see `_REGEX_KEYWORDS`).+ Name-map containers (`properties`, `$defs`, ...) and data positions (`default`,+ `enum`, ...) are walked without reading their user-chosen keys as keywords."""+ if isinstance(node, dict):+ for key, value in node.items():+ if key in _DATA_KEYS:+ continue+ if key in _NAME_MAP_KEYS and isinstance(value, dict):+ for subschema in value.values():+ _assert_supported_constructs(subschema)+ continue+ if key in _REFERENCE_KEYS and isinstance(value, str) and not value.startswith("#"):+ raise StructuredOutputSchemaError(+ f"structured_output_schema must not use remote references ({key}: {value!r}); "+ "only in-document '#/...' references are supported"+ )+ if key in _REGEX_KEYWORDS:+ raise StructuredOutputSchemaError(+ f"structured_output_schema must not use regex keywords ({key}): a pathological "+ "pattern can stall validation indefinitely. Express the constraint with enum, "+ "type, length, or numeric bounds instead."+ )+ _assert_supported_constructs(value)+ elif isinstance(node, list):+ for item in node:+ _assert_supported_constructs(item)+++def record_structured_output_sync(+ *,+ team: Team,+ run: SignalScoutRun,+ records: list[StructuredOutputRecord],+) -> RecordStructuredOutputResult:+ """Validate `records` against the run's configured schema and forward them as events.++ All-or-nothing: any invalid record fails the whole call with nothing written, so the+ agent never has to dedupe a partial batch. The event forward is the write — capacity is+ reserved on the run row first (under lock, re-checking the channel gates), then the+ batch POSTs to capture, and a delivery failure fails the call so the agent retries+ (deterministic event uuids make the retry collapse at ingestion). Only the internal+ telemetry event is best-effort.+ """+ _assert_team_owns_run(team, run)+ schema = _resolve_schema(team, run)+ _validate_records(records, schema)+ _reserve_capacity(team=team, run=run, count=len(records))+ forwards = _build_forwards(run=run, records=records)+ _forward_structured_output_events(team=team, run=run, forwards=forwards)+ _capture_recorded(team=team, run=run, recorded_count=len(records))+ return RecordStructuredOutputResult(+ recorded_count=len(records),+ record_ids=[forward.event_uuid for forward in forwards],+ )+++async def record_structured_output(+ *,+ team: Team,+ run: SignalScoutRun,+ records: list[StructuredOutputRecord],+) -> RecordStructuredOutputResult:+ """Async entry mirroring `record_structured_output_sync`, offloading DB work to the+ sync thread pool and the blocking event forward to a worker thread."""+ from posthog.sync import database_sync_to_async++ _assert_team_owns_run(team, run)+ schema = await database_sync_to_async(_resolve_schema, thread_sensitive=False)(team, run)+ _validate_records(records, schema)+ await database_sync_to_async(_reserve_capacity, thread_sensitive=False)(team=team, run=run, count=len(records))+ forwards = _build_forwards(run=run, records=records)+ # One blocking batch HTTP POST; `to_thread` keeps it off the event loop without+ # occupying the DB-thread pool for the HTTP leg.+ await asyncio.to_thread(_forward_structured_output_events, team=team, run=run, forwards=forwards)+ await database_sync_to_async(_capture_recorded, thread_sensitive=False)(+ team=team, run=run, recorded_count=len(records)+ )+ return RecordStructuredOutputResult(+ recorded_count=len(records),+ record_ids=[forward.event_uuid for forward in forwards],+ )+++def _assert_team_owns_run(team: Team, run: SignalScoutRun) -> None:+ """Defense-in-depth mirroring `emit._assert_team_owns_run`: the view path already+ filters the run lookup by team, so a mismatch here is a server-side wiring bug (500,+ not 400)."""+ if team.id != run.team_id:+ raise RuntimeError(f"record_structured_output: team {team.id} does not own run {run.id} (team {run.team_id})")+++def _resolve_schema(team: Team, run: SignalScoutRun) -> dict[str, Any]:+ """The schema governing this run's records.++ Two reads, each load-bearing. The run's dispatch-time config is re-read live (by pk,+ mirroring `emit._preflight_emit_gates`): a deleted config or a null schema fails closed —+ the channel is opt-in via the schema's presence, and a schema *cleared* mid-run is the+ kill switch that must stop further writes. But the schema records validate against is+ the dispatch-time snapshot the runner stamped on the run row (when present): the prompt+ rendered that exact schema, so a mid-run schema *edit* must not reject records that+ match what the run was shown, nor silently persist records under a contract the scout+ never saw. Runs predating the stamp fall back to the live value."""+ row = SignalScoutRun.all_teams.filter(pk=run.pk, team_id=team.id).values_list("scout_config_id", "metadata").first()+ config_id, metadata = row if row else (None, None)+ config = SignalScoutConfig.all_teams.filter(pk=config_id).first() if config_id else None+ live_schema = config.structured_output_schema if config else None+ if not live_schema:+ raise _no_schema_error()+ snapshot = (metadata or {}).get("structured_output_schema")+ return snapshot if isinstance(snapshot, dict) and snapshot else live_schema+++def _no_schema_error() -> InvalidStructuredOutputError:+ return InvalidStructuredOutputError(+ "This scout has no structured_output_schema configured, so structured output cannot be "+ "recorded. Set a schema on the scout's config (scout-config-update) to enable this channel."+ )+++def _validate_records(records: list[StructuredOutputRecord], schema: dict[str, Any]) -> None:+ if not records:+ raise InvalidStructuredOutputError("records must not be empty")+ if len(records) > MAX_RECORDS_PER_CALL:+ raise InvalidStructuredOutputError(+ f"records has {len(records)} entries, max is {MAX_RECORDS_PER_CALL} per call"+ )+ try:+ validator = Draft202012Validator(schema, registry=_NO_RETRIEVAL_REGISTRY)+ except Exception as exc:+ # The serializer validates schemas at write time, so this only fires for rows that+ # predate the guard or were written outside the API. The agent can't fix it; the+ # config owner can.+ raise InvalidStructuredOutputError(+ f"The configured structured_output_schema is not a valid JSON Schema ({exc}). "+ "Ask the scout's owner to fix it via scout-config-update."+ ) from exc+ problems: list[str] = []+ for index, record in enumerate(records):+ if record.subject is not None and len(record.subject) > MAX_SUBJECT_LENGTH:+ problems.append(f"records[{index}].subject exceeds {MAX_SUBJECT_LENGTH} chars")+ continue+ encoded = json.dumps(record.payload)+ if len(encoded.encode("utf-8")) > MAX_RECORD_BYTES:+ problems.append(f"records[{index}].payload exceeds {MAX_RECORD_BYTES} bytes serialized")+ continue+ try:+ error = next(iter(validator.iter_errors(record.payload)), None)+ except Exception as exc:+ # A reference the no-retrieval registry refused (or any other resolution failure)+ # is a config problem, not a record problem — fail the call closed with the reason.+ raise InvalidStructuredOutputError(+ f"The configured structured_output_schema could not be evaluated ({exc}). "+ "Ask the scout's owner to fix it via scout-config-update."+ ) from exc+ if error is not None:+ path = "".join(f"[{part!r}]" for part in error.absolute_path)+ problems.append(f"records[{index}].payload{path}: {error.message}")+ if problems:+ shown = problems[:5]+ suffix = f" (+{len(problems) - len(shown)} more)" if len(problems) > len(shown) else ""+ raise InvalidStructuredOutputError(+ f"{len(problems)} of {len(records)} records failed schema validation; nothing was recorded. "+ + "; ".join(shown)+ + suffix+ )+++def _reserve_capacity(*, team: Team, run: SignalScoutRun, count: int) -> None:+ """Reserve `count` records against the per-run ceiling and re-check the channel gates,+ in one transaction on the locked run row. Uses the unscoped manager because ownership+ was already validated by the caller.++ The kill switch is re-checked here with the config row locked: `_resolve_schema`'s+ earlier read and this reservation are separate operations, so without this a clear+ committing between them would let events fire after the channel was switched off. The+ lock serializes a concurrent clear against the reservation — whichever commits first+ wins cleanly. The gates that make forwarding permissible at all are checked under the+ same lock, mirroring `emit._preflight_emit_gates`: a dry-run scout (`emit=False`) has+ no row store to fall back on anymore, so the call fails loudly rather than silently+ dropping the batch; an organization that has not approved AI data processing must not+ receive AI-generated records into its project; and a project that disabled the+ signals_scout source has opted out of scout output entirely (the same inactive-skip+ rule as the emit/report channels).++ The counter lives on `run.metadata` (`STRUCTURED_OUTPUT_COUNT_KEY`) and is bumped+ before the forward: it's a flood breaker counting accepted batches, so a forward that+ then fails (or is retried) still spends cap — see the key's comment."""+ with transaction.atomic():+ locked_run = SignalScoutRun.all_teams.select_for_update(of=("self",)).filter(pk=run.pk).first()+ if locked_run is None:+ raise InvalidStructuredOutputError("The run row is gone; nothing was recorded.")+ config = (+ SignalScoutConfig.all_teams.select_for_update()+ .filter(pk=locked_run.scout_config_id)+ .only("structured_output_schema", "emit")+ .first()+ if locked_run.scout_config_id+ else None+ )+ if config is None or not config.structured_output_schema:+ raise _no_schema_error()+ if not config.emit:+ raise InvalidStructuredOutputError(+ "This scout is in dry-run (emit off), so structured-output records — which land as "+ "events in the project — cannot be recorded. Enable emit on the scout's config "+ "(scout-config-update) to turn the channel on."+ )+ if not team.organization.is_ai_data_processing_approved:+ raise InvalidStructuredOutputError(+ "This organization has not approved AI data processing, so structured-output records "+ "cannot be recorded. An org admin must turn on the 'Enable PostHog features that use "+ "third-party AI services' toggle in Organization settings → AI service providers."+ )+ if not SignalSourceConfig.is_source_enabled(run.team_id, SOURCE_PRODUCT, SOURCE_TYPE):+ raise InvalidStructuredOutputError(+ "This project has disabled the signals_scout source, so scout output — including "+ "structured-output records — cannot be recorded."+ )+ metadata = dict(locked_run.metadata or {})+ existing = metadata.get(STRUCTURED_OUTPUT_COUNT_KEY)+ existing = existing if isinstance(existing, int) else 0+ if existing + count > MAX_RECORDS_PER_RUN:+ raise InvalidStructuredOutputError(+ f"Recording {count} more records would exceed the per-run cap of "+ f"{MAX_RECORDS_PER_RUN} (already recorded: {existing})."+ )+ metadata[STRUCTURED_OUTPUT_COUNT_KEY] = existing + count+ locked_run.metadata = metadata+ locked_run.save(update_fields=["metadata"])+++def _capture_recorded(*, team: Team, run: SignalScoutRun, recorded_count: int) -> None:+ """Internal (PostHog-side) telemetry: one event per accepted call, mirroring the+ other scout lifecycle events' shape so it joins on `run_id`. Best-effort."""+ try:+ posthoganalytics.capture(+ event="signals_scout_structured_output_recorded",+ distinct_id=str(team.uuid),+ properties={+ "skill_name": run.skill_name,+ "skill_version": run.skill_version,+ "scout_config_id": str(run.scout_config_id) if run.scout_config_id else None,+ "run_id": str(run.id),+ "task_run_id": str(run.task_run_id) if run.task_run_id else None,+ "recorded_count": recorded_count,+ },+ groups=groups(team.organization, team),+ )+ except Exception:+ logger.warning(+ "signals_scout: failed to capture structured-output analytics event",+ extra={"team_id": team.id, "run_id": str(run.id), "skill_name": run.skill_name},+ )+++@dataclass(frozen=True, kw_only=True)+class _StructuredOutputForward:+ distinct_id: str+ event_uuid: str+ timestamp: str+ properties: dict[str, Any]+++def _build_forwards(*, run: SignalScoutRun, records: list[StructuredOutputRecord]) -> list[_StructuredOutputForward]:+ """One customer-facing event per record, into the team's own project. Scalar top-level+ payload keys are flattened to `output_<key>` properties so trends can break down on+ them directly (nested access works too; the flat copy is the ergonomic path), and the+ full record rides under `output`. Pure assembly — the channel gates (dry-run, AI+ consent, source disabled) were already enforced under lock in `_reserve_capacity`,+ which keeps this callable from the event loop in the async path.++ The event timestamp is the run's `created_at`, not now(): the events table dedupes on+ a sorting key that includes `toDate(timestamp)`, so a retried batch stamped at capture+ time would stop collapsing if the retry crossed UTC midnight. A stable timestamp makes+ the deterministic uuid's retry story exact instead of same-day."""+ stable_timestamp = run.created_at.isoformat()+ forwards: list[_StructuredOutputForward] = []+ base = {+ "skill_name": run.skill_name,+ "skill_version": run.skill_version,+ "run_id": str(run.id),+ "task_run_id": str(run.task_run_id) if run.task_run_id else None,+ }+ for index, record in enumerate(records):+ flattened = {+ f"output_{key}": value+ for key, value in record.payload.items()+ if isinstance(value, (str, int, float, bool)) or value is None+ }+ payload_key = json.dumps(record.payload, sort_keys=True, separators=(",", ":"))+ forwards.append(+ _StructuredOutputForward(+ distinct_id=f"signals_scout:{run.skill_name}",+ # `index` keeps in-batch duplicates (two records with identical subject ++ # payload that are meant to count separately) as distinct events, while a+ # resubmitted identical batch — same records at the same positions — still+ # collapses at ingestion instead of double-firing downstream automation.+ event_uuid=str(+ uuid.uuid5(+ uuid.NAMESPACE_URL,+ "signals_scout_structured_output:"+ + json.dumps(+ [str(run.id), str(index), record.subject or "", payload_key], separators=(",", ":")+ ),+ )+ ),+ timestamp=stable_timestamp,+ properties={**base, "subject": record.subject, "output": record.payload, **flattened},+ )+ )+ return forwards+++def _forward_structured_output_events(+ *, team: Team, run: SignalScoutRun, forwards: list[_StructuredOutputForward]+) -> None:+ """Write the accepted batch into the team's own event stream through the sanctioned+ `capture_batch_internal` path — one batch POST (auto-chunked with bounded concurrency+ above 200 events), never one HTTP call per record, so a slow capture endpoint costs one+ bounded round-trip instead of a timeout per record. Person processing is OFF with a+ synthetic per-scout `distinct_id` — a record is the scout's output, not an end-user+ action. This is the primary (and only) write: a failure raises+ `StructuredOutputDeliveryError` so the caller retries, which the deterministic event+ uuids make safe."""+ try:+ # `raise_for_status` matters: capture can accept the POST yet drop or exhaust+ # retries on individual events, returning a result instead of raising — without it+ # a partial forward failure would be silent.+ capture_batch_internal(+ events=[+ {+ "event": CUSTOMER_STRUCTURED_OUTPUT_EVENT,+ "distinct_id": forward.distinct_id,+ "properties": forward.properties,+ "event_uuid": forward.event_uuid,+ "timestamp": forward.timestamp,+ }+ for forward in forwards+ ],+ token=team.api_token,+ event_source=_STRUCTURED_OUTPUT_EVENT_SOURCE,+ process_person_profile=False,+ ).raise_for_status()+ except Exception as exc:+ logger.warning(+ "signals_scout: failed to forward structured-output events to team project",+ extra={"team_id": team.id, "run_id": str(run.id), "event_count": len(forwards)},+ )+ raise StructuredOutputDeliveryError(+ f"Delivering the batch of {len(forwards)} records failed; nothing was recorded. "+ "Retry the same call — delivery is idempotent, so a retry cannot double-count."+ ) from excdiff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 03a509bfb687..d36437c862c6 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -86,6 +86,8 @@ from products.signals.backend.scout_harness.serializers import (ProjectProfileQuerySerializer,ProjectProfileSerializer,RecentEmissionsQuerySerializer,+ RecordStructuredOutputRequestSerializer,+ RecordStructuredOutputResponseSerializer,RememberRequestSerializer,ScoutEmissionReportLinkSerializer,ScoutMemberSerializer,@@ -155,6 +157,12 @@ from products.signals.backend.scout_harness.tools.scratchpad import (remember,search_scratchpad,)+from products.signals.backend.scout_harness.tools.structured_output import (+ InvalidStructuredOutputError,+ StructuredOutputDeliveryError,+ StructuredOutputRecord,+ record_structured_output_sync,+)from products.signals.backend.scout_report import InvalidScoutReportErrorfrom products.skills.backend.api.skill_services import LLMSkillDuplicateNameConflictError, create_skillfrom products.skills.backend.models.skills import LLMSkill, LLMSkillFile@@ -178,6 +186,15 @@ MAX_EMISSIONS_PER_BATCH = 5000DEFAULT_RECENT_EMISSIONS_LIMIT = 50MAX_RECENT_EMISSIONS_LIMIT = 200++class _StructuredOutputDeliveryFailed(exceptions.APIException):+ """503 for a failed structured-output event forward: transient and safe to retry+ (deterministic event ids), unlike a 400 the agent would read as "fix the batch"."""++ status_code = status.HTTP_503_SERVICE_UNAVAILABLE+ default_code = "structured_output_delivery_failed"++# `SignalScoutRunViewSet.lookup_field` is `run_id`, but the model's PK field is `id`, so# drf-spectacular can't derive the path-param type from the model and warns (fatal under# `--fail-on-warn`). Declare the param explicitly on every detail action instead.@@ -1021,6 +1038,86 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):status=status.HTTP_200_OK,)+ @validated_request(+ request_serializer=RecordStructuredOutputRequestSerializer,+ parameters=[_RUN_ID_PATH_PARAMETER],+ responses={+ 200: OpenApiResponse(+ response=RecordStructuredOutputResponseSerializer,+ description="All records validated against the configured schema and recorded as events.",+ ),+ 400: OpenApiResponse(+ description=(+ "No structured_output_schema configured for this scout, the channel is off (dry-run "+ "scout, org AI-processing consent missing, or the signals_scout source disabled), a "+ "record failed schema validation (nothing written), or a batch/size cap was exceeded."+ )+ ),+ 404: OpenApiResponse(description="Run not found for this project."),+ 503: OpenApiResponse(+ description=(+ "The records validated but event delivery failed; nothing was recorded. Retry the "+ "same call — delivery is idempotent, so a retry cannot double-count."+ )+ ),+ },+ summary="Record structured output for a run",+ description=(+ "The structured-output channel: record schema-validated records this run produced. Opt-in via "+ "the scout config's `structured_output_schema` (a JSON Schema describing one record) — without "+ "it the call fails closed, as it does for a dry-run scout (emit off). All-or-nothing: any "+ "invalid record fails the whole call with nothing written, so fix and resubmit the batch. Each "+ "accepted record lands in the project's event stream as a `$scout_structured_output` event — "+ "query them like any event (insights, SQL over `events`). Recording is idempotent: event ids "+ "are deterministic, so resubmitting an identical batch (e.g. retrying after a 503) cannot "+ "double-count."+ ),+ operation_id="signals_scout_record_output",+ )+ @action(+ detail=True,+ methods=["post"],+ url_path="record-output",+ required_scopes=["signal_scout_internal:write"],+ pagination_class=None,+ )+ def record_output(self, request: Request, **kwargs) -> Response:+ run_id = _parse_run_id_or_404(kwargs)+ from products.tasks.backend.facade import api as tasks_facade++ run = (+ SignalScoutRun.objects.select_related("scout_config", "task_run", "team")+ .filter(team_id=_canonical_team_id(self), id=run_id)+ .first()+ )+ if run is None:+ raise exceptions.NotFound()+ if run.task_run.status != tasks_facade.TaskRunStatus.IN_PROGRESS:+ raise exceptions.ValidationError(+ {+ "status": (+ f"Structured output can only be recorded on in-progress runs (current: {run.task_run.status})."+ )+ }+ )+ records = [+ StructuredOutputRecord(payload=entry["payload"], subject=entry.get("subject") or None)+ for entry in request.validated_data["records"]+ ]+ try:+ # `run.team` is the canonical team the run was resolved on, as in `emit_report`.+ result = record_structured_output_sync(team=run.team, run=run, records=records)+ except InvalidStructuredOutputError as exc:+ raise exceptions.ValidationError({"detail": str(exc)})+ except StructuredOutputDeliveryError as exc:+ raise _StructuredOutputDeliveryFailed(detail=str(exc))+ return Response(+ RecordStructuredOutputResponseSerializer(+ {"recorded_count": result.recorded_count, "record_ids": result.record_ids}+ ).data,+ status=status.HTTP_200_OK,+ )+# `EvidenceEntrySerializer` is referenced for OpenAPI nested-schema discovery; keep# the import live so drf-spectacular registers it even if the runtime never imports# it directly inside this module.@@ -1801,6 +1898,35 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):lookup_field = "id"pagination_class = None+ def dangerously_get_required_scopes(self, request: Request, view) -> list[str] | None:+ # Setting a `structured_output_schema` injects text a privileged agent reads verbatim in+ # its run prompt (schema `description` fields are free prose), so it is skill-authoring-level+ # steering: keys need `llm_skill:write` on top of the config write — the same two-leg gate as+ # scout notes. Only the *setting* write escalates; reads, other config edits, and clearing+ # the schema (privilege-reducing) stay on the base config scopes.+ if getattr(view, "action", None) in ("create", "partial_update") and self._sets_structured_output_schema(+ request+ ):+ return ["signal_scout:write", "llm_skill:write"]+ return None++ @staticmethod+ def _sets_structured_output_schema(request: Request) -> bool:+ data = request.data+ return isinstance(data, dict) and data.get("structured_output_schema") is not None++ def _assert_can_author_structured_output_schema(self) -> None:+ # RBAC leg of the schema-write gate, mirroring the scout-notes steering gate: session+ # callers (and key holders) must clear the same `llm_skill` editor bar that editing a+ # scout's skill body requires, bound to the canonical team whose scouts read the prompt.+ canonical_team = self.team.parent_team or self.team+ access = UserAccessControl(user=cast(User, self.request.user), team=canonical_team)+ if not access.check_access_level_for_resource("llm_skill", "editor"):+ raise exceptions.PermissionDenied(+ "Setting structured_output_schema requires editor access to skills, since the schema "+ "is read verbatim by the scout agent."+ )+@extend_schema(responses={200: OpenApiResponse(@@ -1862,6 +1988,8 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)def create(self, request: Request, *args, **kwargs) -> Response:team_id = _canonical_team_id(self)+ if self._sets_structured_output_schema(request):+ self._assert_can_author_structured_output_schema()serializer = SignalScoutConfigCreateSerializer(data=request.data,context={**self.get_serializer_context(), "project_id": self.team.project_id},@@ -1910,6 +2038,8 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)def partial_update(self, request: Request, *args, **kwargs) -> Response:team_id = _canonical_team_id(self)+ if self._sets_structured_output_schema(request):+ self._assert_can_author_structured_output_schema()config_id = _parse_run_id_or_404(kwargs)config = SignalScoutConfig.objects.unscoped().filter(team_id=team_id, id=config_id).first()if config is None:diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex e9652e35dd09..68a098fa57af 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -349,6 +349,55 @@ class TestPromptCrossReferences(SimpleTestCase):assert referenced <= headings, f"dangling cross-references: {sorted(referenced - headings)}"+class TestStructuredOutputPromptSection(SimpleTestCase):+ _SCHEMA = {+ "type": "object",+ "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}},+ "required": ["verdict", "reason"],+ }++ @parameterized.expand(+ [+ ("signal_channel", []),+ ("report_channel", ["emit_report", "edit_report"]),+ ("edit_only", ["edit_report"]),+ ]+ )+ def test_section_renders_only_when_config_carries_a_schema(self, _name: str, allowed_tools: list[str]) -> None:+ # Two failure modes, both silent in production: dropping the section leaves a+ # schema-configured scout never told to record (the channel exists but nothing uses it),+ # and rendering it unconditionally steers schema-less scouts at a tool that fails closed.+ def _prompt(schema: dict | None) -> str:+ return build_run_prompt(+ LoadedSkill(+ name="signals-scout-judge",+ version=1,+ body="judge",+ description="d",+ allowed_tools=allowed_tools,+ files=[],+ skill_id="skill-1",+ origin="custom",+ authors=[],+ ),+ run_id="00000000-0000-0000-0000-000000000abc",+ team_id=1,+ started_at=datetime(2026, 5, 1, 12, 34, 56, tzinfo=UTC),+ structured_output_schema=schema,+ )++ with_schema = _prompt(self._SCHEMA)+ assert "# Structured output" in with_schema+ assert "scout-record-output" in with_schema+ # The exact schema the endpoint enforces is rendered, so the prompt and the+ # validator can never describe two different contracts.+ assert '"verdict"' in with_schema++ without_schema = _prompt(None)+ assert "# Structured output" not in without_schema+ assert "scout-record-output" not in without_schema++class TestPromptBuilder(BaseTest):def test_renders_identity_bootstrap_and_universal_sections(self) -> None:skill = LLMSkill.objects.create(diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 4aef2949dfb5..ca78e3260565 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -43,6 +43,7 @@ from products.signals.backend.scout_harness.limits import STALE_RUN_CUTOFF_Sfrom 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_TICK+from products.signals.backend.scout_harness.tools import structured_output as structured_output_toolfrom products.signals.backend.scout_harness.tools.profile import compute_project_profilefrom products.signals.backend.temporal.signal_queries import fetch_report_ids_for_source_idsfrom products.skills.backend.models.skills import LLMSkill@@ -710,6 +711,410 @@ class TestScoutHarnessEmitFindingAPI(APIBaseTest):)+_STRUCTURED_OUTPUT_SCHEMA: dict = {+ "type": "object",+ "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}},+ "required": ["verdict", "reason"],+ "additionalProperties": False,+}+++class TestScoutHarnessStructuredOutputAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ # record-output requires `signal_scout_internal:write` — session auth is rejected.+ _authenticate_as_scout(self)++ def _record_url(self, run_id: str) -> str:+ return f"/api/projects/{self.team.id}/signals/scout/runs/{run_id}/record-output/"++ def _make_run_with_schema(self, team: Team | None = None, **config_overrides) -> SignalScoutRun:+ run = _make_run(team or self.team)+ assert run.scout_config is not None+ run.scout_config.structured_output_schema = _STRUCTURED_OUTPUT_SCHEMA+ for field, value in config_overrides.items():+ setattr(run.scout_config, field, value)+ run.scout_config.save()+ return run++ def test_record_output_forwards_events_and_counts_on_the_run(self) -> None:+ run = self._make_run_with_schema()+ records = [+ {"payload": {"verdict": "good", "reason": "coherent grouping"}, "subject": "report-1"},+ {"payload": {"verdict": "bad", "reason": "two unrelated issues merged"}, "subject": "report-2"},+ {"payload": {"verdict": "unsure", "reason": "not enough signals"}},+ ]+ with patch(+ "products.signals.backend.scout_harness.tools.structured_output.capture_batch_internal"+ ) as mock_capture:+ response = self.client.post(self._record_url(str(run.id)), data={"records": records}, format="json")+ assert response.status_code == status.HTTP_200_OK, response.json()+ body = response.json()+ assert body["recorded_count"] == 3+ # One batch POST carrying one event per record, person processing off, scalar payload+ # keys flattened for breakdowns, and distinct deterministic uuids per record. The+ # response's record_ids ARE those event uuids — the events are the record.+ assert mock_capture.call_count == 1+ kwargs = mock_capture.call_args.kwargs+ events = kwargs["events"]+ assert len(events) == 3+ assert kwargs["process_person_profile"] is False+ assert events[0]["event"] == "$scout_structured_output"+ assert events[0]["properties"]["output_verdict"] == "good"+ assert events[0]["properties"]["subject"] == "report-1"+ assert events[0]["properties"]["run_id"] == str(run.id)+ assert len({event["event_uuid"] for event in events}) == 3+ assert body["record_ids"] == [event["event_uuid"] for event in events]+ # A stable timestamp (the run's created_at) keeps the dedupe sorting key — which+ # includes toDate(timestamp) — identical across retries, even past UTC midnight.+ assert {event["timestamp"] for event in events} == {run.created_at.isoformat()}+ # The per-run cap counter is the only Postgres trace, on the run row itself.+ run.refresh_from_db()+ assert (run.metadata or {}).get("structured_output_count") == 3++ def test_record_output_is_all_or_nothing_on_invalid_record(self) -> None:+ run = self._make_run_with_schema()+ records = [+ {"payload": {"verdict": "good", "reason": "fine"}},+ {"payload": {"verdict": "terrible", "reason": "not in the enum"}},+ ]+ with patch(+ "products.signals.backend.scout_harness.tools.structured_output.capture_batch_internal"+ ) as mock_capture:+ response = self.client.post(self._record_url(str(run.id)), data={"records": records}, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "records[1]" in str(response.json())+ mock_capture.assert_not_called()+ run.refresh_from_db()+ assert (run.metadata or {}).get("structured_output_count") is None++ def test_record_output_fails_closed_without_configured_schema(self) -> None:+ run = _make_run(self.team)+ response = self.client.post(+ self._record_url(str(run.id)),+ data={"records": [{"payload": {"verdict": "good", "reason": "x"}}]},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "structured_output_schema" in str(response.json())++ def test_record_output_rejects_non_in_progress_run(self) -> None:+ TaskRun = apps.get_model("tasks", "TaskRun")+ run = self._make_run_with_schema()+ TaskRun.objects.filter(id=run.task_run_id).update(status=TaskRun.Status.COMPLETED)+ response = self.client.post(+ self._record_url(str(run.id)),+ data={"records": [{"payload": {"verdict": "good", "reason": "x"}}]},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_record_output_other_teams_run_returns_404(self) -> None:+ other = Team.objects.create(organization=self.organization, name="Other")+ run = self._make_run_with_schema(team=other)+ response = self.client.post(+ self._record_url(str(run.id)),+ data={"records": [{"payload": {"verdict": "good", "reason": "x"}}]},+ format="json",+ )+ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_record_output_fails_closed_for_disabled_source(self) -> None:+ # Same inactive-skip rule as the emit/report channels — but with events as the only+ # record, suppressing them quietly would silently lose the batch, so the call fails+ # loudly instead.+ from products.signals.backend.models import SignalSourceConfig++ run = self._make_run_with_schema()+ SignalSourceConfig.objects.get_or_create(+ team=self.team,+ source_product="signals_scout",+ source_type="cross_source_issue",+ defaults={"enabled": False},+ )+ with patch(+ "products.signals.backend.scout_harness.tools.structured_output.capture_batch_internal"+ ) as mock_capture:+ response = self.client.post(+ self._record_url(str(run.id)),+ data={"records": [{"payload": {"verdict": "good", "reason": "x"}}]},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "disabled" in str(response.json())+ mock_capture.assert_not_called()++ def test_record_output_fails_closed_for_dry_run_scout(self) -> None:+ # The runner also withholds the prompt section for a dry-run scout; this guards the+ # backstop for a mid-run emit flip.+ run = self._make_run_with_schema(emit=False)+ with patch(+ "products.signals.backend.scout_harness.tools.structured_output.capture_batch_internal"+ ) as mock_capture:+ response = self.client.post(+ self._record_url(str(run.id)),+ data={"records": [{"payload": {"verdict": "good", "reason": "x"}}]},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "dry-run" in str(response.json())+ mock_capture.assert_not_called()++ def test_record_output_fails_closed_without_ai_processing_consent(self) -> None:+ # Mirrors the emit channel's org-level gate: an org that has not approved AI data+ # processing must not receive AI-generated records into its project.+ run = self._make_run_with_schema()+ self.organization.is_ai_data_processing_approved = False+ self.organization.save(update_fields=["is_ai_data_processing_approved"])+ with patch(+ "products.signals.backend.scout_harness.tools.structured_output.capture_batch_internal"+ ) as mock_capture:+ response = self.client.post(+ self._record_url(str(run.id)),+ data={"records": [{"payload": {"verdict": "good", "reason": "x"}}]},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "AI data processing" in str(response.json())+ mock_capture.assert_not_called()++ def test_record_output_delivery_failure_is_retryable_with_stable_event_ids(self) -> None:+ # The forward is the only write, so a failed batch POST must fail the call (a+ # swallowed failure silently loses the run's output — the regression this guards),+ # and a retry of the same batch must produce identical event uuids so it collapses+ # at ingestion instead of double-counting.+ run = self._make_run_with_schema()+ records = [{"payload": {"verdict": "good", "reason": "x"}, "subject": "report-1"}]+ with patch(+ "products.signals.backend.scout_harness.tools.structured_output.capture_batch_internal",+ side_effect=RuntimeError("capture down"),+ ) as failing_capture:+ failed = self.client.post(self._record_url(str(run.id)), data={"records": records}, format="json")+ assert failed.status_code == status.HTTP_503_SERVICE_UNAVAILABLE+ assert "etry" in str(failed.json())+ failed_uuids = [event["event_uuid"] for event in failing_capture.call_args.kwargs["events"]]++ with patch(+ "products.signals.backend.scout_harness.tools.structured_output.capture_batch_internal"+ ) as mock_capture:+ retried = self.client.post(self._record_url(str(run.id)), data={"records": records}, format="json")+ assert retried.status_code == status.HTTP_200_OK+ assert retried.json()["record_ids"] == failed_uuids+ assert [event["event_uuid"] for event in mock_capture.call_args.kwargs["events"]] == failed_uuids++ def test_record_output_validates_against_dispatch_time_schema_snapshot(self) -> None:+ # The prompt renders the dispatch-time schema, so a mid-run config edit must not+ # reject records matching what the run was shown — but clearing the schema entirely+ # stays a kill switch.+ run = self._make_run_with_schema()+ SignalScoutRun.objects.filter(pk=run.pk).update(+ metadata={"structured_output_schema": _STRUCTURED_OUTPUT_SCHEMA}+ )+ assert run.scout_config is not None+ run.scout_config.structured_output_schema = {+ "type": "object",+ "properties": {"grade": {"type": "integer"}},+ "required": ["grade"],+ "additionalProperties": False,+ }+ run.scout_config.save()+ with patch("products.signals.backend.scout_harness.tools.structured_output.capture_batch_internal"):+ response = self.client.post(+ self._record_url(str(run.id)),+ data={"records": [{"payload": {"verdict": "good", "reason": "matches the shown schema"}}]},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK, response.json()++ run.scout_config.structured_output_schema = None+ run.scout_config.save()+ cleared = self.client.post(+ self._record_url(str(run.id)),+ data={"records": [{"payload": {"verdict": "good", "reason": "x"}}]},+ format="json",+ )+ assert cleared.status_code == status.HTTP_400_BAD_REQUEST++ def test_run_read_strips_schema_snapshot_from_metadata(self) -> None:+ # The snapshot exists for record validation; leaking it into run reads repeats up to+ # 20 KB of schema per row on listings scouts read inside their own prompts.+ run = self._make_run_with_schema()+ SignalScoutRun.objects.filter(pk=run.pk).update(+ metadata={"structured_output_schema": _STRUCTURED_OUTPUT_SCHEMA, "report_channel": "none"}+ )+ 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 "structured_output_schema" not in metadata+ assert metadata["report_channel"] == "none"++ def test_record_output_fails_closed_when_schema_cleared_mid_request(self) -> None:+ # Simulates a clear committing between the schema read and the capacity reservation —+ # the in-transaction recheck must fail the call closed with nothing forwarded.+ run = self._make_run_with_schema()+ assert run.scout_config_id is not None+ config_id = run.scout_config_id+ original_validate = structured_output_tool._validate_records++ def clear_then_validate(records: list, schema: dict) -> None:+ SignalScoutConfig.objects.filter(pk=config_id).update(structured_output_schema=None)+ original_validate(records, schema)++ with (+ patch.object(structured_output_tool, "_validate_records", side_effect=clear_then_validate),+ patch.object(structured_output_tool, "capture_batch_internal") as mock_capture,+ ):+ response = self.client.post(+ self._record_url(str(run.id)),+ data={"records": [{"payload": {"verdict": "good", "reason": "x"}}]},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ mock_capture.assert_not_called()++ def test_record_output_enforces_per_run_cap_across_calls(self) -> None:+ # The cap counter lives on the run row, so it must accumulate across calls — a+ # reservation that doesn't persist would let a looping agent flood events.+ run = self._make_run_with_schema()+ with (+ patch("products.signals.backend.scout_harness.tools.structured_output.MAX_RECORDS_PER_RUN", 2),+ patch("products.signals.backend.scout_harness.tools.structured_output.capture_batch_internal"),+ ):+ first = self.client.post(+ self._record_url(str(run.id)),+ data={"records": [{"payload": {"verdict": "good", "reason": f"r{i}"}} for i in range(2)]},+ format="json",+ )+ second = self.client.post(+ self._record_url(str(run.id)),+ data={"records": [{"payload": {"verdict": "good", "reason": "one too many"}}]},+ format="json",+ )+ assert first.status_code == status.HTTP_200_OK, first.json()+ assert second.status_code == status.HTTP_400_BAD_REQUEST+ assert "per-run cap" in str(second.json())+++class TestStructuredOutputSchemaValidation(SimpleTestCase):+ @parameterized.expand(+ [+ ("valid_schema", _STRUCTURED_OUTPUT_SCHEMA, True),+ ("null_clears", None, True),+ ("non_object_root", {"type": "array", "items": {"type": "string"}}, False),+ ("empty_object", {}, False),+ ("not_a_valid_json_schema", {"type": "object", "properties": {"x": {"type": 42}}}, False),+ # A remote reference would have the worker fetch an arbitrary URL at record time (SSRF).+ (+ "remote_ref_rejected",+ {"type": "object", "properties": {"x": {"$ref": "https://169.254.169.254/schema.json"}}},+ False,+ ),+ (+ "local_ref_allowed",+ {+ "type": "object",+ "$defs": {"verdict": {"enum": ["good", "bad"]}},+ "properties": {"verdict": {"$ref": "#/$defs/verdict"}},+ },+ True,+ ),+ # A catastrophic regex (`^(a+)+$`) pins the validating worker with no way to+ # interrupt it, so regex keywords fail closed at the boundary.+ (+ "regex_pattern_rejected",+ {"type": "object", "properties": {"x": {"type": "string", "pattern": "^(a+)+$"}}},+ False,+ ),+ (+ "property_named_pattern_allowed",+ {"type": "object", "properties": {"pattern": {"type": "string"}}},+ True,+ ),+ ]+ )+ def test_config_schema_validation(self, _name: str, schema: dict | None, valid: bool) -> None:+ serializer = SignalScoutConfigUpdateSerializer(data={"structured_output_schema": schema}, partial=True)+ assert serializer.is_valid() is valid, serializer.errors+ if not valid:+ assert "structured_output_schema" in serializer.errors+++class TestScoutHarnessConfigStructuredOutputSchemaAPI(APIBaseTest):+ def _detail_url(self, config_id: str) -> str:+ return f"/api/projects/{self.team.id}/signals/scout/configs/{config_id}/"++ def test_patch_persists_schema_and_read_surfaces_it(self) -> None:+ # Wiring guard for the SimpleTestCase matrix above: the viewset actually routes+ # `structured_output_schema` through the update serializer and the read shape returns it.+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-judge")+ response = self.client.patch(+ self._detail_url(str(config.id)),+ data={"structured_output_schema": _STRUCTURED_OUTPUT_SCHEMA},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["structured_output_schema"] == _STRUCTURED_OUTPUT_SCHEMA+ config.refresh_from_db()+ assert config.structured_output_schema == _STRUCTURED_OUTPUT_SCHEMA++ def test_patch_rejects_invalid_schema(self) -> None:+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-judge")+ response = self.client.patch(+ self._detail_url(str(config.id)),+ data={"structured_output_schema": {"type": "array"}},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ config.refresh_from_db()+ assert config.structured_output_schema is None++ @parameterized.expand(+ [+ # The schema is rendered verbatim into a privileged run prompt, so setting it is+ # skill-authoring-level steering: a config-only key must not open the channel.+ ("config_scope_only", ["signal_scout:write"], status.HTTP_403_FORBIDDEN),+ ("with_skill_authoring_scope", ["signal_scout:write", "llm_skill:write"], status.HTTP_200_OK),+ ]+ )+ def test_setting_schema_requires_skill_authoring_scope(self, _name: str, scopes: list[str], expected: int) -> None:+ from posthog.models.personal_api_key import PersonalAPIKey+ from posthog.models.utils import generate_random_token_personal, hash_key_value++ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-judge")+ raw = generate_random_token_personal()+ PersonalAPIKey.objects.create(label="k", user=self.user, secure_value=hash_key_value(raw), scopes=scopes)+ self.client.logout()+ response = self.client.patch(+ self._detail_url(str(config.id)),+ data={"structured_output_schema": _STRUCTURED_OUTPUT_SCHEMA},+ format="json",+ HTTP_AUTHORIZATION=f"Bearer {raw}",+ )+ assert response.status_code == expected, response.json()++ def test_clearing_schema_needs_only_config_scope(self) -> None:+ from posthog.models.personal_api_key import PersonalAPIKey+ from posthog.models.utils import generate_random_token_personal, hash_key_value++ config = SignalScoutConfig.objects.create(+ team=self.team, skill_name="signals-scout-judge", structured_output_schema=_STRUCTURED_OUTPUT_SCHEMA+ )+ raw = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="k", user=self.user, secure_value=hash_key_value(raw), scopes=["signal_scout:write"]+ )+ self.client.logout()+ response = self.client.patch(+ self._detail_url(str(config.id)),+ data={"structured_output_schema": None},+ format="json",+ HTTP_AUTHORIZATION=f"Bearer {raw}",+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ config.refresh_from_db()+ assert config.structured_output_schema is None++class TestScoutHarnessScratchpadAPI(APIBaseTest):def setUp(self) -> None:super().setUp()@@ -2438,6 +2843,7 @@ class TestScoutRunDerivedMetadata(APIBaseTest):"has_self_improvement","has_chart","has_self_validation",+ "has_structured_output",}@parameterized.expand(diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex ba0863673c64..06f58fe199bc 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -1853,6 +1853,12 @@ export const ScoutConfigNetworkAccessEnumApi = {Full: 'full',} as const+/**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+export type SignalScoutConfigOptionsApiStructuredOutputSchema = { [key: string]: unknown } | null+/*** Schedule, enablement, and delivery options accepted while creating a scout.*/@@ -1882,6 +1888,11 @@ export interface SignalScoutConfigOptionsApi {* @nullable*/run_cron_schedule?: string | null+ /**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+ structured_output_schema?: SignalScoutConfigOptionsApiStructuredOutputSchema}/**@@ -1951,6 +1962,12 @@ export const ScoutConfigPauseReasonEnumApi = {RepeatedFailures: 'repeated_failures',} as const+/**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+export type SignalScoutConfigApiStructuredOutputSchema = { [key: string]: unknown } | null+/*** Read shape for a per-(team, skill) scout config.*@@ -1995,6 +2012,11 @@ export interface SignalScoutConfigApi {readonly run_cron_schedule: string | null/** Destinations that receive each finding or report this scout emits. Empty when none is configured. */readonly output_destinations: SignalScoutOutputDestinationsApi+ /**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+ readonly structured_output_schema: SignalScoutConfigApiStructuredOutputSchema/** What the scout's sandbox can reach over the network while it runs. `trusted` (the default) restricts runs to the platform's trusted-domain allowlist (PostHog, GitHub, common package registries). `full` lets the scout reach any site, for skills that read external sources such as documentation or papers.** * `trusted` - Trusted domains only@@ -2024,6 +2046,12 @@ export interface SignalScoutCreateResponseApi {config: SignalScoutConfigApi}+/**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+export type SignalScoutConfigCreateApiStructuredOutputSchema = { [key: string]: unknown } | null+/*** Request body for registering a scout config without waiting for the coordinator tick.*@@ -2056,6 +2084,11 @@ export interface SignalScoutConfigCreateApi {* @nullable*/run_cron_schedule?: string | null+ /**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+ structured_output_schema?: SignalScoutConfigCreateApiStructuredOutputSchema/*** The `signals-scout-*` skill to register a config for. The skill must already exist on this project — author it via the skills store first.* @maxLength 200@@ -2063,6 +2096,12 @@ export interface SignalScoutConfigCreateApi {skill_name: string}+/**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+export type PatchedSignalScoutConfigUpdateApiStructuredOutputSchema = { [key: string]: unknown } | null+/*** Editable schedule, enablement, and emit posture for one scout config.*/@@ -2085,6 +2124,11 @@ export interface PatchedSignalScoutConfigUpdateApi {run_cron_schedule?: string | null/** Destinations that receive each finding or report this scout emits. Pass an empty object to disable delivery. */output_destinations?: SignalScoutOutputDestinationsApi+ /**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+ structured_output_schema?: PatchedSignalScoutConfigUpdateApiStructuredOutputSchema/** What the scout's sandbox can reach over the network while it runs. `trusted` (the default) restricts runs to the platform's trusted-domain allowlist (PostHog, GitHub, common package registries). Set `full` to let this scout reach any site, for skills that read external sources such as documentation or papers. Applies from the scout's next run.** * `trusted` - Trusted domains only@@ -2891,6 +2935,7 @@ export type SignalScoutRunSummaryApiMetadataDerived = {has_self_improvement: booleanhas_chart: booleanhas_self_validation: boolean+ has_structured_output: boolean}/**@@ -3003,6 +3048,7 @@ export type SignalScoutRunDetailApiMetadataDerived = {has_self_improvement: booleanhas_chart: booleanhas_self_validation: boolean+ has_structured_output: boolean}/**@@ -3465,6 +3511,47 @@ export interface EmitFindingResponseApi {remediation: string | null}+/**+ * The record itself, as a JSON object. Must validate against the scout config's `structured_output_schema` (shown in the run prompt); any invalid record fails the whole call with nothing written.+ */+export type StructuredOutputRecordApiPayload = { [key: string]: unknown }++/**+ * One record submitted through `scout-record-output`.+ */+export interface StructuredOutputRecordApi {+ /** The record itself, as a JSON object. Must validate against the scout config's `structured_output_schema` (shown in the run prompt); any invalid record fails the whole call with nothing written. */+ payload: StructuredOutputRecordApiPayload+ /**+ * Optional key naming what this record is about — a report id, URL, account key — so per-entity lookups don't need to parse `payload`. Omit for a run-level record.+ * @maxLength 200+ * @nullable+ */+ subject?: string | null+}++/**+ * Request body for `scout-record-output`: a batch of schema-validated records.+ */+export interface RecordStructuredOutputRequestApi {+ /**+ * Records to record, each validated against the scout config's `structured_output_schema`. All-or-nothing: if any record fails validation, nothing is written and the error names the failing records. Capped at 100 per call; batch per-entity judgments rather than calling once per record.+ * @minItems 1+ * @maxItems 100+ */+ records: StructuredOutputRecordApi[]+}++/**+ * Outcome of an accepted `scout-record-output` call.+ */+export interface RecordStructuredOutputResponseApi {+ /** How many records were recorded (all of them, or none). */+ recorded_count: number+ /** Deterministic event ids of the recorded `$scout_structured_output` events, in submission order. Stable across a resubmission of the identical batch, which is what makes retrying a failed delivery safe. */+ record_ids: string[]+}+/*** Request body for the batched emissions / emission-reports lookups: the set of run UUIDs to* resolve in one call. Collapses the findings UI's old per-run fan-out (one request — and for thediff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex a1e074c10270..33fae935ef4b 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -37,6 +37,8 @@ import type {PullRequestReviewCommentCreateResponseApi,PullRequestReviewCommentReactionCreateApi,PullRequestReviewCommentReactionCreateResponseApi,+ RecordStructuredOutputRequestApi,+ RecordStructuredOutputResponseApi,RememberRequestApi,ReportSignalsResponseApi,ScoutEmissionReportLinkApi,@@ -1114,6 +1116,28 @@ export const signalsScoutEmitSignal = async (})}+export const getSignalsScoutRecordOutputUrl = (projectId: string, runId: string) => {+ return `/api/projects/${projectId}/signals/scout/runs/${runId}/record-output/`+}++/**+ * The structured-output channel: record schema-validated records this run produced. Opt-in via the scout config's `structured_output_schema` (a JSON Schema describing one record) — without it the call fails closed, as it does for a dry-run scout (emit off). All-or-nothing: any invalid record fails the whole call with nothing written, so fix and resubmit the batch. Each accepted record lands in the project's event stream as a `$scout_structured_output` event — query them like any event (insights, SQL over `events`). Recording is idempotent: event ids are deterministic, so resubmitting an identical batch (e.g. retrying after a 503) cannot double-count.+ * @summary Record structured output for a run+ */+export const signalsScoutRecordOutput = async (+ projectId: string,+ runId: string,+ recordStructuredOutputRequestApi: RecordStructuredOutputRequestApi,+ options?: RequestInit+): Promise<RecordStructuredOutputResponseApi> => {+ return apiMutator<RecordStructuredOutputResponseApi>(getSignalsScoutRecordOutputUrl(projectId, runId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(recordStructuredOutputRequestApi),+ })+}+export const getSignalsScoutRunsEmissionsBatchUrl = (projectId: string) => {return `/api/projects/${projectId}/signals/scout/runs/emissions/batch/`}diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 2ce60ba011fb..ead0de3323fb 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -438,6 +438,12 @@ export const SignalsScoutCreateBody = /* @__PURE__ */ zod.describe("Optional five-field cron expression, e.g. '30 9 \* \* \*' (daily at 09:30), '0 9,17 \* \* \*' (twice daily), or '0 9 \* \* 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart."),+ structured_output_schema: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe(+ 'Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{\"type\": \"object\", \"properties\": {\"verdict\": {\"enum\": [\"good\", \"bad\", \"unsure\"]}, \"reason\": {\"type\": \"string\"}}, \"required\": [\"verdict\", \"reason\"]}`). The root must be `\"type\": \"object\"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout\'s call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.'+ ),}).describe('Schedule, enablement, and delivery options accepted while creating a scout.').optional()@@ -523,6 +529,12 @@ export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod.describe("Optional five-field cron expression, e.g. '30 9 \* \* \*' (daily at 09:30), '0 9,17 \* \* \*' (twice daily), or '0 9 \* \* 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart."),+ structured_output_schema: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe(+ 'Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{\"type\": \"object\", \"properties\": {\"verdict\": {\"enum\": [\"good\", \"bad\", \"unsure\"]}, \"reason\": {\"type\": \"string\"}}, \"required\": [\"verdict\", \"reason\"]}`). The root must be `\"type\": \"object\"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout\'s call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.'+ ),skill_name: zod.string().max(signalsScoutConfigCreateBodySkillNameMax)@@ -602,6 +614,12 @@ export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod.describe('Destinations that receive each finding or report this scout emits. Pass an empty object to disable delivery.'),+ structured_output_schema: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe(+ 'Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{\"type\": \"object\", \"properties\": {\"verdict\": {\"enum\": [\"good\", \"bad\", \"unsure\"]}, \"reason\": {\"type\": \"string\"}}, \"required\": [\"verdict\", \"reason\"]}`). The root must be `\"type\": \"object\"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout\'s call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.'+ ),network_access: zod.enum(['trusted', 'full']).describe('\* `trusted` - Trusted domains only\n\* `full` - Full')@@ -1047,6 +1065,43 @@ export const SignalsScoutEmitSignalBody = /* @__PURE__ */ zod}).describe('Request body for `emit-finding`. Run attribution is taken from the URL path.')+/**+ * The structured-output channel: record schema-validated records this run produced. Opt-in via the scout config's `structured_output_schema` (a JSON Schema describing one record) — without it the call fails closed, as it does for a dry-run scout (emit off). All-or-nothing: any invalid record fails the whole call with nothing written, so fix and resubmit the batch. Each accepted record lands in the project's event stream as a `$scout_structured_output` event — query them like any event (insights, SQL over `events`). Recording is idempotent: event ids are deterministic, so resubmitting an identical batch (e.g. retrying after a 503) cannot double-count.+ * @summary Record structured output for a run+ */+export const signalsScoutRecordOutputBodyRecordsItemSubjectMax = 200++export const signalsScoutRecordOutputBodyRecordsMax = 100++export const SignalsScoutRecordOutputBody = /* @__PURE__ */ zod+ .object({+ records: zod+ .array(+ zod+ .object({+ payload: zod+ .record(zod.string(), zod.unknown())+ .describe(+ "The record itself, as a JSON object. Must validate against the scout config's `structured_output_schema` (shown in the run prompt); any invalid record fails the whole call with nothing written."+ ),+ subject: zod+ .string()+ .max(signalsScoutRecordOutputBodyRecordsItemSubjectMax)+ .nullish()+ .describe(+ "Optional key naming what this record is about — a report id, URL, account key — so per-entity lookups don't need to parse `payload`. Omit for a run-level record."+ ),+ })+ .describe('One record submitted through `scout-record-output`.')+ )+ .min(1)+ .max(signalsScoutRecordOutputBodyRecordsMax)+ .describe(+ "Records to record, each validated against the scout config's `structured_output_schema`. All-or-nothing: if any record fails validation, nothing is written and the error names the failing records. Capped at 100 per call; batch per-entity judgments rather than calling once per record."+ ),+ })+ .describe('Request body for `scout-record-output`: a batch of schema-validated records.')+/*** Batched form of the per-run emissions endpoint: return the findings every requested `SignalScoutRun` emitted, flattened newest-first, in a single request. Each row carries its `run_id`, so the caller can regroup by run. The findings UI uses this to load the whole recent window in one round-trip instead of one request per run. Strictly team-scoped — run ids belonging to another team contribute no rows (no per-run 404; one stale id never fails the batch).* @summary List emitted findings for many runs at oncediff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex 54c9261eb365..3c225ed60d37 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -644,6 +644,24 @@ tools:`inbox-source-configs-list` / `inbox-reports-list` / `read-data-schema` / `advanced-activity-logs-list`.Distinct from `scout-scratchpad-search`: profile is ground truth from authoritative tables; scratchpad isthe scout's inferred learnings.+ scout-record-output:+ operation: signals_scout_record_output+ enabled: true+ scopes:+ - signal_scout_internal:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Record structured output for a run+ description: >+ Record schema-validated structured records for a `SignalScoutRun` — the structured-output channel next to+ findings and reports. Opt-in via the scout config's `structured_output_schema` (a JSON Schema describing one+ record); without it the call fails closed, as it does for a dry-run scout (emit off). Pass the `run_id` and+ a `records` list of `{payload, subject}` entries. All-or-nothing: any record failing the schema fails the+ whole call with nothing written — fix and resubmit the batch. Each accepted record lands in the project's+ event stream as a `$scout_structured_output` event, queryable like any event. Idempotent — event ids are+ deterministic, so retrying a call that failed with a delivery error (503) cannot double-count.scout-run-now:operation: signals_scout_config_runenabled: truediff --git a/products/signals/skills/authoring-scouts/SKILL.md b/products/signals/skills/authoring-scouts/SKILL.mdindex cc3ab5b892ea..a3c997871e82 100644--- a/products/signals/skills/authoring-scouts/SKILL.md+++ b/products/signals/skills/authoring-scouts/SKILL.md@@ -119,6 +119,12 @@ For an **existing scout**, tune with `posthog:scout-config-update` (find the `idA scout whose reports nobody acts on is warned and then paused automatically (`pause_reason=ignored`) — every run costs a sandbox agent, so a scout producing output no human consumes shouldn't keep running forever. A scout that is merely quiet is only flagged (`pause_reason=no_output`, a warning that never advances to a pause), since a watch scout's silence can be its job.`-config-list` shows the warning as `status=pending_pause` and the pause as `status=paused_by_system`; setting `enabled=true` again resumes the scout, and marks it exempt so the sweep never overrules a person twice.Set `auto_pause_exempt=true` up front for a watchdog scout whose whole job is to stay quiet, so it never even picks up the quiet flag.+- `structured_output_schema` — defaults to null (channel off).+ Set a JSON Schema (draft 2020-12, root `"type": "object"`) describing **one** structured record and the scout gains a third output channel next to reports: each run is shown the schema and told to submit conforming records via `scout-record-output` (one per run, or one per judged entity — the skill body decides the cardinality and when to record).+ Records are validated server-side against the schema (all-or-nothing per call) and recorded in the project as `$scout_structured_output` events with scalar payload keys flattened to `output_<key>` properties — so a judging/scoring scout's series is chartable in insights directly, and past records are queryable like any events (filter on `subject` or `run_id`, break down on `output_<key>`).+ The channel also requires `emit`: a dry-run scout has nowhere to record to, so `scout-record-output` fails closed for it.+ Reach for this when the scout's job is a recurring **measurement** (judge each sampled report good/bad/unsure with a reason, score accounts, classify sessions) rather than surfacing anomalies; keep enums small and add a free-text reason field so the series is breakdown-friendly _and_ auditable.+ The skill body should say what to sample, how to judge, and what `subject` to stamp on each record; the schema owns the record shape.## Steering with notes (no authoring needed)diff --git a/products/signals/skills/exploring-scouts/references/scout-data-model.md b/products/signals/skills/exploring-scouts/references/scout-data-model.mdindex 71ffbf82db78..1b0b6a3a60f2 100644--- a/products/signals/skills/exploring-scouts/references/scout-data-model.md+++ b/products/signals/skills/exploring-scouts/references/scout-data-model.md@@ -9,17 +9,18 @@ One row per `(team, skill_name)`.Returned by `scout-config-list`.This is the scout's control surface, separate from its instruction body (the `LLMSkill`).-| Field | Meaning |-| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `id` | Config id — the handle `scout-config-update` takes to tune it. |-| `skill_name` | The `signals-scout-*` skill this config controls. Fixed; one config per skill per team. |-| `enabled` | `false` = paused. The coordinator skips disabled scouts entirely. Derived from `status`. |-| `status` | Who owns the pause: `active`, `pending_pause` (still runs, flagged to pause soon; any config edit clears it), `paused_by_system` (automatic — resumable with `enabled: true`), `paused_by_user` (a person switched it off; the system never overrides it). |-| `pause_reason` | Why the system paused or warned: `no_output`, `ignored`, or `repeated_failures`. Null outside `pending_pause` / `paused_by_system`. |-| `emit` | `false` = **dry-run**: the scout runs and reasons every tick but writes nothing to the inbox. |-| `run_interval_minutes` | Cadence, 30–43200. Default 1440 (daily). The coordinator dispatches when due. |-| `network_access` | What the run's sandbox can reach: `trusted` (default — the platform's trusted-domain allowlist: PostHog, GitHub, package registries) or `full` (any site, for skills that read external docs/papers). |-| `last_run_at` | When it last fired. `null` = never run. Drives the due-check. |+| Field | Meaning |+| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `id` | Config id — the handle `scout-config-update` takes to tune it. |+| `skill_name` | The `signals-scout-*` skill this config controls. Fixed; one config per skill per team. |+| `enabled` | `false` = paused. The coordinator skips disabled scouts entirely. Derived from `status`. |+| `status` | Who owns the pause: `active`, `pending_pause` (still runs, flagged to pause soon; any config edit clears it), `paused_by_system` (automatic — resumable with `enabled: true`), `paused_by_user` (a person switched it off; the system never overrides it). |+| `pause_reason` | Why the system paused or warned: `no_output`, `ignored`, or `repeated_failures`. Null outside `pending_pause` / `paused_by_system`. |+| `emit` | `false` = **dry-run**: the scout runs and reasons every tick but writes nothing to the inbox. |+| `run_interval_minutes` | Cadence, 30–43200. Default 1440 (daily). The coordinator dispatches when due. |+| `network_access` | What the run's sandbox can reach: `trusted` (default — the platform's trusted-domain allowlist: PostHog, GitHub, package registries) or `full` (any site, for skills that read external docs/papers). |+| `structured_output_schema` | Optional JSON Schema (object-rooted) describing one structured record the scout produces via `scout-record-output`. Null = the structured-output channel is off (it also needs `emit` on). When set, each run is shown the schema and its records are validated against it and recorded as `$scout_structured_output` events. |+| `last_run_at` | When it last fired. `null` = never run. Drives the due-check. |A scout that is `enabled: true, emit: false` is alive and working — it just can't post reports.This is the intended posture for a new or freshly-edited scout, and the most common cause of "my scout does nothing" reports.@@ -33,22 +34,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. |-| `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. |+| 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`, `has_structured_output`) — 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 values@@ -82,6 +83,22 @@ Grouping generated its own `document_id` and deduped on that — never on `sourcFor these runs only, `scout-runs-emission-reports` maps each emitted finding to the inbox report its signal grouped into (or `null`).On report-channel scouts both fields are always `0` / empty.+## `$scout_structured_output` events — schema-validated records (structured-output channel)++One event per record a run submitted via `scout-record-output`, recorded only when the scout's config carries a `structured_output_schema` (and `emit` is on — a dry-run scout has no channel).+The queryable view of a _measuring_ scout's output (judgments, scores, classifications), read like any events — trend them in insights or query the `events` table, filtering on the properties below.++| Property | Meaning |+| -------------- | -------------------------------------------------------------------------------------------------------------- |+| `run_id` | The run that recorded it. |+| `skill_name` | Which scout produced it. |+| `subject` | Optional scout-chosen key naming what the record is about (a report id, URL, account key). Null for run-level. |+| `output` | The full record, validated against the config's schema at submission time. |+| `output_<key>` | Each scalar top-level payload key, flattened for direct breakdowns (e.g. `output_verdict`). |++Event uuids are deterministic per `(run, batch index, subject, payload)`, so a retried batch collapses at ingestion rather than double-counting.+A run's `metadata.derived.has_structured_output` flag says whether the run recorded anything, without querying events.+## SignalScratchpad — durable fleet memoryReturned by `scout-scratchpad-search`.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 75a71b25adf7..3fb2ba1be88a 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -8118,6 +8118,20 @@"readOnlyHint": true}},+ "scout-record-output": {+ "description": "Record schema-validated structured records for a `SignalScoutRun` — the structured-output channel next to findings and reports. Opt-in via the scout config's `structured_output_schema` (a JSON Schema describing one record); without it the call fails closed, as it does for a dry-run scout (emit off). Pass the `run_id` and a `records` list of `{payload, subject}` entries. All-or-nothing: any record failing the schema fails the whole call with nothing written — fix and resubmit the batch. Each accepted record lands in the project's event stream as a `$scout_structured_output` event, queryable like any event. Idempotent — event ids are deterministic, so retrying a call that failed with a delivery error (503) cannot double-count.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Record structured output for a run",+ "title": "Record structured output for a run",+ "required_scopes": ["signal_scout_internal:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"scout-run-now": {"description": "Dispatch one on-demand run of a scout by its config `id`, regardless of its schedule — useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously and inherits the scheduled path's guards: it returns 429 if the project is over its Signals credits quota or its daily scout-run budget, and 409 if a run for this scout is already in progress. A manual run counts against the same daily run budget the scheduled runs draw from, so avoid triggering repeated runs of the same scout in a short window — each one consumes the project's scout-run allowance for the day. A manual run does not change the scout's schedule, and a disabled scout can still be run this way (to test before enabling). Returns the workflow id immediately — poll `scout-runs-list` for the resulting run and its findings.","category": "Signals",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex df649341b5f3..fc8255ac5b1a 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -8714,6 +8714,20 @@"readOnlyHint": true}},+ "scout-record-output": {+ "description": "Record schema-validated structured records for a `SignalScoutRun` — the structured-output channel next to findings and reports. Opt-in via the scout config's `structured_output_schema` (a JSON Schema describing one record); without it the call fails closed, as it does for a dry-run scout (emit off). Pass the `run_id` and a `records` list of `{payload, subject}` entries. All-or-nothing: any record failing the schema fails the whole call with nothing written — fix and resubmit the batch. Each accepted record lands in the project's event stream as a `$scout_structured_output` event, queryable like any event. Idempotent — event ids are deterministic, so retrying a call that failed with a delivery error (503) cannot double-count.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Record structured output for a run",+ "title": "Record structured output for a run",+ "required_scopes": ["signal_scout_internal:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"scout-run-now": {"description": "Dispatch one on-demand run of a scout by its config `id`, regardless of its schedule — useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously and inherits the scheduled path's guards: it returns 429 if the project is over its Signals credits quota or its daily scout-run budget, and 409 if a run for this scout is already in progress. A manual run counts against the same daily run budget the scheduled runs draw from, so avoid triggering repeated runs of the same scout in a short window — each one consumes the project's scout-run allowance for the day. A manual run does not change the scout's schedule, and a disabled scout can still be run this way (to test before enabling). Returns the workflow id immediately — poll `scout-runs-list` for the resulting run and its findings.","category": "Signals",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7c36214be1e7..e3bd738ed90b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -56280,6 +56280,12 @@ export namespace Schemas {summary?: string;}+ /**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+ export type PatchedSignalScoutConfigUpdateStructuredOutputSchema = { [key: string]: unknown } | null;+export interface SignalScoutSlackDestination {/*** ID of the Slack integration whose bot posts this scout's findings and reports.@@ -56333,6 +56339,11 @@ export namespace Schemas {run_cron_schedule?: string | null;/** Destinations that receive each finding or report this scout emits. Pass an empty object to disable delivery. */output_destinations?: SignalScoutOutputDestinations;+ /**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+ structured_output_schema?: PatchedSignalScoutConfigUpdateStructuredOutputSchema;/** What the scout's sandbox can reach over the network while it runs. `trusted` (the default) restricts runs to the platform's trusted-domain allowlist (PostHog, GitHub, common package registries). Set `full` to let this scout reach any site, for skills that read external sources such as documentation or papers. Applies from the scout's next run.** * `trusted` - Trusted domains only@@ -63741,6 +63752,47 @@ export namespace Schemas {recorded: boolean;}+ /**+ * The record itself, as a JSON object. Must validate against the scout config's `structured_output_schema` (shown in the run prompt); any invalid record fails the whole call with nothing written.+ */+ export type StructuredOutputRecordPayload = { [key: string]: unknown };++ /**+ * One record submitted through `scout-record-output`.+ */+ export interface StructuredOutputRecord {+ /** The record itself, as a JSON object. Must validate against the scout config's `structured_output_schema` (shown in the run prompt); any invalid record fails the whole call with nothing written. */+ payload: StructuredOutputRecordPayload;+ /**+ * Optional key naming what this record is about — a report id, URL, account key — so per-entity lookups don't need to parse `payload`. Omit for a run-level record.+ * @maxLength 200+ * @nullable+ */+ subject?: string | null;+ }++ /**+ * Request body for `scout-record-output`: a batch of schema-validated records.+ */+ export interface RecordStructuredOutputRequest {+ /**+ * Records to record, each validated against the scout config's `structured_output_schema`. All-or-nothing: if any record fails validation, nothing is written and the error names the failing records. Capped at 100 per call; batch per-entity judgments rather than calling once per record.+ * @minItems 1+ * @maxItems 100+ */+ records: StructuredOutputRecord[];+ }++ /**+ * Outcome of an accepted `scout-record-output` call.+ */+ export interface RecordStructuredOutputResponse {+ /** How many records were recorded (all of them, or none). */+ recorded_count: number;+ /** Deterministic event ids of the recorded `$scout_structured_output` events, in submission order. Stable across a resubmission of the identical batch, which is what makes retrying a failed delivery safe. */+ record_ids: string[];+ }+export interface RecordVisitResponse {/** True once today's visit row exists for the user. */recorded: boolean;@@ -66243,6 +66295,12 @@ export namespace Schemas {snooze_for?: number;}+ /**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+ export type SignalScoutConfigStructuredOutputSchema = { [key: string]: unknown } | null;+/*** Read shape for a per-(team, skill) scout config.*@@ -66287,6 +66345,11 @@ export namespace Schemas {readonly run_cron_schedule: string | null;/** Destinations that receive each finding or report this scout emits. Empty when none is configured. */readonly output_destinations: SignalScoutOutputDestinations;+ /**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+ readonly structured_output_schema: SignalScoutConfigStructuredOutputSchema;/** What the scout's sandbox can reach over the network while it runs. `trusted` (the default) restricts runs to the platform's trusted-domain allowlist (PostHog, GitHub, common package registries). `full` lets the scout reach any site, for skills that read external sources such as documentation or papers.** * `trusted` - Trusted domains only@@ -66309,6 +66372,12 @@ export namespace Schemas {readonly created_at: string;}+ /**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+ export type SignalScoutConfigCreateStructuredOutputSchema = { [key: string]: unknown } | null;+/*** Request body for registering a scout config without waiting for the coordinator tick.*@@ -66341,6 +66410,11 @@ export namespace Schemas {* @nullable*/run_cron_schedule?: string | null;+ /**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+ structured_output_schema?: SignalScoutConfigCreateStructuredOutputSchema;/*** The `signals-scout-*` skill to register a config for. The skill must already exist on this project — author it via the skills store first.* @maxLength 200@@ -66348,6 +66422,12 @@ export namespace Schemas {skill_name: string;}+ /**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+ export type SignalScoutConfigOptionsStructuredOutputSchema = { [key: string]: unknown } | null;+/*** Schedule, enablement, and delivery options accepted while creating a scout.*/@@ -66377,6 +66457,11 @@ export namespace Schemas {* @nullable*/run_cron_schedule?: string | null;+ /**+ * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.+ * @nullable+ */+ structured_output_schema?: SignalScoutConfigOptionsStructuredOutputSchema;}/**@@ -66481,6 +66566,7 @@ export namespace Schemas {has_self_improvement: boolean;has_chart: boolean;has_self_validation: boolean;+ has_structured_output: boolean;};/**@@ -66574,6 +66660,7 @@ export namespace Schemas {has_self_improvement: boolean;has_chart: boolean;has_self_validation: boolean;+ has_structured_output: boolean;};/**diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex 4398392eb906..846a26024df1 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 39 enabled ops+ * PostHog API - MCP 40 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -528,6 +528,12 @@ export const SignalsScoutCreateBody = /* @__PURE__ */ zod.describe("Optional five-field cron expression, e.g. '30 9 \* \* \*' (daily at 09:30), '0 9,17 \* \* \*' (twice daily), or '0 9 \* \* 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart."),+ structured_output_schema: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe(+ 'Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{\"type\": \"object\", \"properties\": {\"verdict\": {\"enum\": [\"good\", \"bad\", \"unsure\"]}, \"reason\": {\"type\": \"string\"}}, \"required\": [\"verdict\", \"reason\"]}`). The root must be `\"type\": \"object\"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout\'s call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.'+ ),}).describe('Schedule, enablement, and delivery options accepted while creating a scout.').optional()@@ -633,6 +639,12 @@ export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod.describe("Optional five-field cron expression, e.g. '30 9 \* \* \*' (daily at 09:30), '0 9,17 \* \* \*' (twice daily), or '0 9 \* \* 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart."),+ structured_output_schema: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe(+ 'Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{\"type\": \"object\", \"properties\": {\"verdict\": {\"enum\": [\"good\", \"bad\", \"unsure\"]}, \"reason\": {\"type\": \"string\"}}, \"required\": [\"verdict\", \"reason\"]}`). The root must be `\"type\": \"object\"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout\'s call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.'+ ),skill_name: zod.string().max(signalsScoutConfigCreateBodySkillNameMax)@@ -721,6 +733,12 @@ export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod.describe('Destinations that receive each finding or report this scout emits. Pass an empty object to disable delivery.'),+ structured_output_schema: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe(+ 'Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{\"type\": \"object\", \"properties\": {\"verdict\": {\"enum\": [\"good\", \"bad\", \"unsure\"]}, \"reason\": {\"type\": \"string\"}}, \"required\": [\"verdict\", \"reason\"]}`). The root must be `\"type\": \"object\"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout\'s call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.'+ ),network_access: zod.enum(['trusted', 'full']).describe('\* `trusted` - Trusted domains only\n\* `full` - Full')@@ -1465,6 +1483,52 @@ export const SignalsScoutEmitSignalBody = /* @__PURE__ */ zod}).describe('Request body for `emit-finding`. Run attribution is taken from the URL path.')+/**+ * The structured-output channel: record schema-validated records this run produced. Opt-in via the scout config's `structured_output_schema` (a JSON Schema describing one record) — without it the call fails closed, as it does for a dry-run scout (emit off). All-or-nothing: any invalid record fails the whole call with nothing written, so fix and resubmit the batch. Each accepted record lands in the project's event stream as a `$scout_structured_output` event — query them like any event (insights, SQL over `events`). Recording is idempotent: event ids are deterministic, so resubmitting an identical batch (e.g. retrying after a 503) cannot double-count.+ * @summary Record structured output for a run+ */+export const SignalsScoutRecordOutputParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+ run_id: zod.string().describe('UUID of the `SignalScoutRun` bridge row.'),+})++export const signalsScoutRecordOutputBodyRecordsItemSubjectMax = 200++export const signalsScoutRecordOutputBodyRecordsMax = 100++export const SignalsScoutRecordOutputBody = /* @__PURE__ */ zod+ .object({+ records: zod+ .array(+ zod+ .object({+ payload: zod+ .record(zod.string(), zod.unknown())+ .describe(+ "The record itself, as a JSON object. Must validate against the scout config's `structured_output_schema` (shown in the run prompt); any invalid record fails the whole call with nothing written."+ ),+ subject: zod+ .string()+ .max(signalsScoutRecordOutputBodyRecordsItemSubjectMax)+ .nullish()+ .describe(+ "Optional key naming what this record is about — a report id, URL, account key — so per-entity lookups don't need to parse `payload`. Omit for a run-level record."+ ),+ })+ .describe('One record submitted through `scout-record-output`.')+ )+ .min(1)+ .max(signalsScoutRecordOutputBodyRecordsMax)+ .describe(+ "Records to record, each validated against the scout config's `structured_output_schema`. All-or-nothing: if any record fails validation, nothing is written and the error names the failing records. Capped at 100 per call; batch per-entity judgments rather than calling once per record."+ ),+ })+ .describe('Request body for `scout-record-output`: a batch of schema-validated records.')+/*** Return the team's recently emitted scout findings across *every* run, newest first — the cross-run counterpart to the per-run `emissions` action. Each row carries its `run_id`, so you can regroup by run without first listing runs and fanning out one `emissions` call each. Pass `skill_name` to scope to a single scout, and `date_from` / `date_to` (a half-open window on `emitted_at`) to bound or paginate — set `date_to` to the oldest emission's `emitted_at` to walk back past the limit. Pure Postgres, no ClickHouse round-trip. Capped at 200 rows (default 50).* @summary List recent emitted findings across all runsdiff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex f2dc42d7b69d..128c87785f5c 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -35,6 +35,8 @@ import {SignalsScoutNotesDestroyParams,SignalsScoutNotesListQueryParams,SignalsScoutProjectProfileGetQueryParams,+ SignalsScoutRecordOutputBody,+ SignalsScoutRecordOutputParams,SignalsScoutRunsEmissionReportsParams,SignalsScoutRunsEmissionsParams,SignalsScoutRunsListQueryParams,@@ -536,6 +538,9 @@ const scoutConfigCreate = (): ToolBase<typeof ScoutConfigCreateSchema, Schemas.Sif (params.run_cron_schedule !== undefined) {body['run_cron_schedule'] = params.run_cron_schedule}+ if (params.structured_output_schema !== undefined) {+ body['structured_output_schema'] = params.structured_output_schema+ }if (params.skill_name !== undefined) {body['skill_name'] = params.skill_name}@@ -620,6 +625,9 @@ const scoutConfigUpdate = (): ToolBase<typeof ScoutConfigUpdateSchema, WithPostHif (params.output_destinations !== undefined) {body['output_destinations'] = params.output_destinations}+ if (params.structured_output_schema !== undefined) {+ body['structured_output_schema'] = params.structured_output_schema+ }if (params.network_access !== undefined) {body['network_access'] = params.network_access}@@ -969,6 +977,28 @@ const scoutProjectProfileGet = (): ToolBase<typeof ScoutProjectProfileGetSchema,},})+const ScoutRecordOutputSchema = SignalsScoutRecordOutputParams.omit({ project_id: true }).extend(+ SignalsScoutRecordOutputBody.shape+)++const scoutRecordOutput = (): ToolBase<typeof ScoutRecordOutputSchema, Schemas.RecordStructuredOutputResponse> => ({+ name: 'scout-record-output',+ schema: ScoutRecordOutputSchema,+ handler: async (context: Context, params: z.infer<typeof ScoutRecordOutputSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.records !== undefined) {+ body['records'] = params.records+ }+ const result = await context.api.request<Schemas.RecordStructuredOutputResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/runs/${encodeURIComponent(String(params.run_id))}/record-output/`,+ body,+ })+ return result+ },+})+const ScoutRunNowSchema = SignalsScoutConfigRunParams.omit({ project_id: true })const scoutRunNow = (): ToolBase<typeof ScoutRunNowSchema, unknown> => ({@@ -1185,6 +1215,9 @@ const signalsScoutConfigCreate = (): ToolBase<typeof SignalsScoutConfigCreateSchif (params.run_cron_schedule !== undefined) {body['run_cron_schedule'] = params.run_cron_schedule}+ if (params.structured_output_schema !== undefined) {+ body['structured_output_schema'] = params.structured_output_schema+ }if (params.skill_name !== undefined) {body['skill_name'] = params.skill_name}@@ -1278,6 +1311,9 @@ const signalsScoutConfigUpdate = (): ToolBase<if (params.output_destinations !== undefined) {body['output_destinations'] = params.output_destinations}+ if (params.structured_output_schema !== undefined) {+ body['structured_output_schema'] = params.structured_output_schema+ }if (params.network_access !== undefined) {body['network_access'] = params.network_access}@@ -1701,6 +1737,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'scout-notes-delete': scoutNotesDelete,'scout-notes-list': scoutNotesList,'scout-project-profile-get': scoutProjectProfileGet,+ 'scout-record-output': scoutRecordOutput,'scout-run-now': scoutRunNow,'scout-runs-emission-reports': scoutRunsEmissionReports,'scout-runs-emissions-list': scoutRunsEmissionsList,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.jsonindex b596bf3d332c..aa47d525e1f7 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json@@ -78,6 +78,21 @@"description": "The `signals-scout-*` skill to register a config for. The skill must already exist on this project — author it via the skills store first.","maxLength": 200,"type": "string"+ },+ "structured_output_schema": {+ "anyOf": [+ {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{\"type\": \"object\", \"properties\": {\"verdict\": {\"enum\": [\"good\", \"bad\", \"unsure\"]}, \"reason\": {\"type\": \"string\"}}, \"required\": [\"verdict\", \"reason\"]}`). The root must be `\"type\": \"object\"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched."}},"required": ["skill_name"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.jsonindex bb6a5572f520..8036e26580f6 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json@@ -76,6 +76,21 @@"maximum": 43200,"minimum": 30,"type": "number"+ },+ "structured_output_schema": {+ "anyOf": [+ {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{\"type\": \"object\", \"properties\": {\"verdict\": {\"enum\": [\"good\", \"bad\", \"unsure\"]}, \"reason\": {\"type\": \"string\"}}, \"required\": [\"verdict\", \"reason\"]}`). The root must be `\"type\": \"object\"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched."}},"required": ["id"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-prepare.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-prepare.jsonindex bf78a18896e0..a83b9ef3e54e 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-prepare.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-prepare.json@@ -80,6 +80,21 @@"maximum": 43200,"minimum": 30,"type": "number"+ },+ "structured_output_schema": {+ "anyOf": [+ {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{\"type\": \"object\", \"properties\": {\"verdict\": {\"enum\": [\"good\", \"bad\", \"unsure\"]}, \"reason\": {\"type\": \"string\"}}, \"required\": [\"verdict\", \"reason\"]}`). The root must be `\"type\": \"object\"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched."}},"type": "object"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-record-output.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-record-output.jsonnew file mode 100644index 000000000000..bcebde317bac--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-record-output.json@@ -0,0 +1,44 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "records": {+ "description": "Records to record, each validated against the scout config's `structured_output_schema`. All-or-nothing: if any record fails validation, nothing is written and the error names the failing records. Capped at 100 per call; batch per-entity judgments rather than calling once per record.",+ "items": {+ "description": "One record submitted through `scout-record-output`.",+ "properties": {+ "payload": {+ "additionalProperties": {},+ "description": "The record itself, as a JSON object. Must validate against the scout config's `structured_output_schema` (shown in the run prompt); any invalid record fails the whole call with nothing written.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "subject": {+ "anyOf": [+ {+ "maxLength": 200,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional key naming what this record is about — a report id, URL, account key — so per-entity lookups don't need to parse `payload`. Omit for a run-level record."+ }+ },+ "required": ["payload"],+ "type": "object"+ },+ "maxItems": 100,+ "minItems": 1,+ "type": "array"+ },+ "run_id": {+ "description": "UUID of the `SignalScoutRun` bridge row.",+ "type": "string"+ }+ },+ "required": ["run_id", "records"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.jsonindex b596bf3d332c..aa47d525e1f7 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json@@ -78,6 +78,21 @@"description": "The `signals-scout-*` skill to register a config for. The skill must already exist on this project — author it via the skills store first.","maxLength": 200,"type": "string"+ },+ "structured_output_schema": {+ "anyOf": [+ {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{\"type\": \"object\", \"properties\": {\"verdict\": {\"enum\": [\"good\", \"bad\", \"unsure\"]}, \"reason\": {\"type\": \"string\"}}, \"required\": [\"verdict\", \"reason\"]}`). The root must be `\"type\": \"object\"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched."}},"required": ["skill_name"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.jsonindex bb6a5572f520..8036e26580f6 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json@@ -76,6 +76,21 @@"maximum": 43200,"minimum": 30,"type": "number"+ },+ "structured_output_schema": {+ "anyOf": [+ {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{\"type\": \"object\", \"properties\": {\"verdict\": {\"enum\": [\"good\", \"bad\", \"unsure\"]}, \"reason\": {\"type\": \"string\"}}, \"required\": [\"verdict\", \"reason\"]}`). The root must be `\"type\": \"object\"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched."}},"required": ["id"],