Skip to content

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

feat(signals): emit_report/edit_report channel — tools, API, MCP exposure + opt-in scope (2/3) (#66131)

Andrew Maguireb8f73d43bbe8
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 136c03645d9e..abfac981b6d3 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -93,6 +93,7 @@ APIScopeObject = Literal[
"sharing_configuration",
"signal_scout",
"signal_scout_internal",
+ "signal_scout_report",
"streamlit_app",
"subscription",
"survey",
@@ -138,6 +139,11 @@ INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset(
# finding emit). Read access for the same surface lives on the public
# `signal_scout` object so user-grantable PAKs can still inspect runs/memory.
"signal_scout_internal",
+ # Sandbox-only write for the scout report channel (emit_report / edit_report).
+ # Split out from `signal_scout_internal` so it can be granted ONLY to scouts that
+ # opted into the report tools (via the `signals_scout_reports` posture) — every
+ # other scout's token lacks it, so the MCP server strips those tools entirely.
+ "signal_scout_report",
}
)
diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.py
index b07902ea5f45..b7d106a655d1 100644
--- a/posthog/temporal/oauth.py
+++ b/posthog/temporal/oauth.py
@@ -15,7 +15,7 @@ POSTHOG_AI_APP_CLIENT_ID_US = "N6UgOECSl98ag1xajxPphGApQXYEVvJIwzCXotKu"
POSTHOG_AI_APP_CLIENT_ID_EU = "0Lizwa3mFSlBuEEQ8V8FMJlskUXpDuSmoEdhzxyi"
POSTHOG_AI_APP_CLIENT_ID_DEV = "DD2ZLG6a2YEUtpPANSzSiIBPuUryYmbndLnKKUy1"
-McpScopePreset = Literal["read_only", "full", "signals_scout"]
+McpScopePreset = Literal["read_only", "full", "signals_scout", "signals_scout_reports"]
SandboxOAuthApplication = Literal["array", "posthog_ai"]
@@ -35,6 +35,16 @@ SCOUT_INTERNAL_SCOPES: list[str] = [
]
+# The scout report channel (emit_report / edit_report). Held separate from
+# `SCOUT_INTERNAL_SCOPES` and added ONLY for the `signals_scout_reports` posture, so a scout
+# carries it only when its skill opted into the report tools via `allowed_tools`. A baseline
+# scout's token never carries this scope, so the MCP server strips the report tools from its
+# toolset entirely — they can't bleed into a run that didn't opt in.
+SCOUT_REPORT_SCOPES: list[str] = [
+ "signal_scout_report:write",
+]
+
+
# A deliberately narrow set of user-facing WRITE scopes granted to the Signals scout
# sandbox so scouts can produce durable artifacts as part of a finding — e.g. a notebook
# that documents and illustrates an emitted anomaly. Unlike `SCOUT_INTERNAL_SCOPES` these
@@ -77,7 +87,7 @@ TOKEN_EXPIRATION_SECONDS = 60 * 60 * 6 # 6 hours
PosthogMcpScopes = McpScopePreset | list[str]
-MCP_SCOPE_PRESETS = ("read_only", "full", "signals_scout")
+MCP_SCOPE_PRESETS = ("read_only", "full", "signals_scout", "signals_scout_reports")
def resolve_scopes(scopes: PosthogMcpScopes = "read_only", *, include_internal_scopes: bool = True) -> list[str]:
@@ -85,17 +95,23 @@ def resolve_scopes(scopes: PosthogMcpScopes = "read_only", *, include_internal_s
if isinstance(scopes, str):
if scopes == "full":
resolved = [*MCP_READ_SCOPES, *MCP_WRITE_SCOPES, *internal]
- elif scopes == "signals_scout":
+ elif scopes in ("signals_scout", "signals_scout_reports"):
# The scout sandbox: reads, the scout's own internal write scope, and a narrow
# allowlist of user-facing writes (`SCOUT_USER_WRITE_SCOPES`) for the durable
# artifacts a finding can produce (e.g. a notebook). Both extra sets are added
# ONLY here (not via the global `INTERNAL_SCOPES`), so unrelated `full`/`read_only`
- # task tokens never carry them. `has_write_scopes("signals_scout")` also reports
- # True so the MCP server doesn't enable read-only mode, which would otherwise strip
- # the agent's own internal-write tools (`signal_scout_internal:write` is annotated
- # as not-read-only).
+ # task tokens never carry them. `has_write_scopes(...)` also reports True so the MCP
+ # server doesn't enable read-only mode, which would otherwise strip the agent's own
+ # internal-write tools (`signal_scout_internal:write` is annotated as not-read-only).
+ #
+ # `signals_scout_reports` is the same posture plus the report-channel scope, granted
+ # only to a scout whose skill opted into emit_report/edit_report. A baseline scout
+ # gets `signals_scout` (no report scope), so the MCP server strips the report tools.
scout_internal = list(SCOUT_INTERNAL_SCOPES) if include_internal_scopes else []
- resolved = [*MCP_READ_SCOPES, *internal, *scout_internal, *SCOUT_USER_WRITE_SCOPES]
+ scout_report = (
+ list(SCOUT_REPORT_SCOPES) if (scopes == "signals_scout_reports" and include_internal_scopes) else []
+ )
+ resolved = [*MCP_READ_SCOPES, *internal, *scout_internal, *scout_report, *SCOUT_USER_WRITE_SCOPES]
else:
# "read_only": reads + shared internal scopes only — no scout write scope.
resolved = [*MCP_READ_SCOPES, *internal]
@@ -111,7 +127,7 @@ def has_write_scopes(scopes: PosthogMcpScopes) -> bool:
# (remember/forget/emit_finding + the narrow `SCOUT_USER_WRITE_SCOPES`). Read-only mode
# is a tool-annotation filter, not a scope filter, and would strip those tools
# categorically without this opt-out.
- return scopes in ("full", "signals_scout")
+ return scopes in ("full", "signals_scout", "signals_scout_reports")
return any(s in MCP_WRITE_SCOPES for s in scopes)
diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.ts
index b12795bd94d1..bb1116c2712f 100644
--- a/products/conversations/frontend/generated/api.schemas.ts
+++ b/products/conversations/frontend/generated/api.schemas.ts
@@ -614,9 +614,9 @@ export const TicketStatusEnumApi = {
* * `medium` - Medium
* * `high` - High
*/
-export type PriorityEnumApi = (typeof PriorityEnumApi)[keyof typeof PriorityEnumApi]
+export type TicketPriorityEnumApi = (typeof TicketPriorityEnumApi)[keyof typeof TicketPriorityEnumApi]
-export const PriorityEnumApi = {
+export const TicketPriorityEnumApi = {
Low: 'low',
Medium: 'medium',
High: 'high',
@@ -681,7 +681,7 @@ export interface TicketApi {
* * `low` - Low
* * `medium` - Medium
* * `high` - High */
- priority?: PriorityEnumApi | BlankEnumApi | null
+ priority?: TicketPriorityEnumApi | BlankEnumApi | null
readonly assignee: TicketAssignmentApi
/** Customer-provided traits such as name and email */
anonymous_traits?: unknown
@@ -766,7 +766,7 @@ export interface PatchedTicketApi {
* * `low` - Low
* * `medium` - Medium
* * `high` - High */
- priority?: PriorityEnumApi | BlankEnumApi | null
+ priority?: TicketPriorityEnumApi | BlankEnumApi | null
readonly assignee?: TicketAssignmentApi
/** Customer-provided traits such as name and email */
anonymous_traits?: unknown
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 91f22feeac46..dcbd085a0cc5 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -196,8 +196,14 @@ one sandbox session → zero or more emitted signals.
for that `(team, skill)` via `_has_running_run` — so `_self_heal_stale_runs` fails any such
run older than `STALE_RUN_CUTOFF_S` before the guard, letting the lane recover within a tick
or two instead of wedging until manual intervention.
-- Emit path goes through `emit_signal()` and only `emit_signal()`. Do not write to
- the embeddings pipeline or `SignalReport` directly from harness code.
+- Emit path goes through `emit_signal()` and only `emit_signal()` — **with one sanctioned
+ carve-out**: a scout that opts into the report-authoring channel (`emit_report` / `edit_report`
+ in its skill's `allowed_tools`) writes a full `SignalReport` directly. That write does NOT go
+ through harness code touching `SignalReport` or the embeddings pipeline itself — it goes through
+ the `scout_report/` service (`create_scout_report` / `update_scout_report`), which owns the report
+ row + the bound `document_embeddings` signal write (the grouping substrate, minus the matcher).
+ Harness/tool code calls that service; it still never touches `SignalReport` or the embeddings
+ pipeline directly. See `../scout_report/persistence.py` and the `scouts-emit-reports` spec.
- **If you add or rename a workflow/activity in `temporal/agentic/`, update
`posthog/temporal/tests/ai/test_module_integrity.py` (`TestSignalsProductModuleIntegrity`)
to match.**
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index c7581091d2b3..9a413a142a8b 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -40,6 +40,14 @@ logger = logging.getLogger(__name__)
# network, MCP read scopes injected. Split out later if the agent needs different policy.
SIGNALS_SCOUT_SANDBOX_ENV_NAME = SIGNALS_REPORT_RESEARCH_ENV_NAME
+# The report channel (emit_report/edit_report) is opt-in per skill. A scout's sandbox token
+# carries the report-write scope ONLY when its skill listed one of these in `allowed_tools` (see
+# the posture selection where the sandbox context is built). A baseline scout never carries that
+# scope, so the MCP server strips the report tools from its toolset — they can't bleed into a run
+# that didn't opt in. `views._assert_report_tool_opted_in` is the matching fail-closed gate on the
+# write itself.
+REPORT_CHANNEL_TOOLS: frozenset[str] = frozenset({"emit_report", "edit_report"})
+
@dataclass(frozen=True)
class RunResult:
@@ -367,7 +375,14 @@ async def _spawn_and_run(
# tool annotated `readOnlyHint: false` — including the agent's own `remember`,
# `forget`, and `emit_finding` tools — even though the OAuth token does carry the
# right scope to call them.
- posthog_mcp_scopes="signals_scout",
+ #
+ # A scout that opted into the report channel gets `signals_scout_reports` instead —
+ # the same posture plus `signal_scout_report:write` — so the MCP server exposes the
+ # emit_report/edit_report tools. Every other scout gets plain `signals_scout` and never
+ # sees them.
+ posthog_mcp_scopes=(
+ "signals_scout_reports" if REPORT_CHANNEL_TOOLS & set(skill.allowed_tools or []) else "signals_scout"
+ ),
# `None` keeps the agent-server default; an override pins the whole run on one model
# (the `scouts-model-selection` gate routes it here). The model the gateway actually serves
# is tagged on each $ai_generation, so per-run model is queryable in LLM analytics.
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index 3ef7ed18450e..7fd60b1e9290 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -14,6 +14,7 @@ from rest_framework import serializers
from posthog.schema import Severity
+from products.signals.backend.artefact_schemas import ActionabilityChoice, Priority
from products.signals.backend.models import SignalScoutConfig, SignalScoutEmission
from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX
from products.signals.backend.scout_harness.tools.emit import (
@@ -21,6 +22,7 @@ from products.signals.backend.scout_harness.tools.emit import (
MAX_TAG_LENGTH,
MAX_TAGS_PER_FINDING,
)
+from products.signals.backend.scout_harness.tools.report import MAX_REPORT_TITLE_LENGTH
from products.signals.backend.scout_harness.tools.scratchpad import MAX_SCRATCHPAD_CONTENT_LENGTH
# --- Run history -----------------------------------------------------------
@@ -460,6 +462,156 @@ class EmitFindingResponseSerializer(serializers.Serializer):
)
+# --- Report authoring (emit_report / edit_report) --------------------------
+
+
+class ReportEvidenceSerializer(serializers.Serializer):
+ """One observation backing an authored report — becomes a bound signal row on the report."""
+
+ description = serializers.CharField(
+ help_text="Prose for this observation. Embedded and rendered to the safety/research surfaces.",
+ )
+ source_id = serializers.CharField(
+ help_text="Stable id for this observation within the report (lets a later edit address it).",
+ )
+ weight = serializers.FloatField(
+ required=False,
+ min_value=0.0,
+ help_text="Optional per-signal weight (defaults to 1.0). Scouts rarely need to set this.",
+ )
+
+
+class EmitReportRequestSerializer(serializers.Serializer):
+ """Request body for `emit-report`. Run attribution is taken from the URL path."""
+
+ title = serializers.CharField(
+ max_length=MAX_REPORT_TITLE_LENGTH,
+ help_text=(
+ "One-line report title the inbox shows. Conventional-commit style "
+ "(`type(scope): description`, e.g. `fix(insights): missing series color`) renders with "
+ "type/scope styling."
+ ),
+ )
+ summary = serializers.CharField(
+ help_text=(
+ "The report body the inbox shows. Markdown is supported (headings, lists, code, links; "
+ "images are not rendered). Lead with one plain declarative sentence — the inbox card uses "
+ "your first line verbatim as the headline (~140 chars, emphasis stripped), then renders the "
+ "full markdown in the detail view."
+ ),
+ )
+ evidence = serializers.ListField(
+ child=ReportEvidenceSerializer(),
+ min_length=1,
+ help_text="The observations backing the report — each becomes a bound signal. At least one.",
+ )
+ actionability_explanation = serializers.CharField(
+ help_text="2-3 sentence evidence-grounded justification for the actionability call below.",
+ )
+ actionability = serializers.ChoiceField(
+ choices=[(c.value, c.value) for c in ActionabilityChoice],
+ help_text=(
+ "The scout's actionability call: `immediately_actionable` -> the report surfaces READY; "
+ "`requires_human_input` -> PENDING_INPUT; `not_actionable` -> suppressed. A safety-judge "
+ "failure suppresses the report regardless."
+ ),
+ )
+ already_addressed = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text="Whether the issue already appears fixed in recent changes (tracked separately).",
+ )
+ repository = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Optional repo for autostart (opening a draft PR): `owner/repo` targets that repo, the "
+ "`NO_REPO` sentinel opts out (report lands without a PR), and omitting it triggers free-form "
+ "selection across the team's repos — the slow path on a many-repo team, so pass `owner/repo` "
+ "when you know it."
+ ),
+ )
+ priority = serializers.ChoiceField(
+ required=False,
+ allow_null=True,
+ choices=[(p.value, p.value) for p in Priority],
+ help_text="Optional priority (`P0`-`P4`). Required for autostart; pair with `priority_explanation`.",
+ )
+ priority_explanation = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="2-3 sentence justification for `priority`. Required when `priority` is set.",
+ )
+ suggested_reviewers = serializers.ListField(
+ required=False,
+ child=serializers.CharField(),
+ help_text=(
+ "Optional GitHub logins to consider as reviewers for autostart. Autostart only opens a PR if "
+ "at least one clears their autonomy threshold; omit to skip the PR path."
+ ),
+ )
+
+
+class EmitReportResponseSerializer(serializers.Serializer):
+ report_id = serializers.CharField(
+ allow_null=True,
+ help_text="The authored report's id (null only when a preflight gate skipped the call). Returned even when suppressed, so you can edit/dedup against it.",
+ )
+ report_status = serializers.CharField(
+ allow_null=True,
+ help_text="Birth status: `ready` | `pending_input` | `suppressed`, or null when gate-skipped.",
+ )
+ emitted = serializers.BooleanField(
+ help_text="True when the report actually surfaced in the inbox (READY or PENDING_INPUT).",
+ )
+ skipped_reason = serializers.CharField(
+ allow_null=True,
+ help_text="`scout_config_missing` | `scout_emit_disabled` | `ai_processing_not_approved` | `source_disabled` | null when not gate-skipped.",
+ )
+ safety_explanation = serializers.CharField(
+ allow_null=True,
+ help_text="When the safety judge suppressed the report, why; null when safe.",
+ )
+
+
+class EditReportRequestSerializer(serializers.Serializer):
+ """Request body for `edit-report`. Can target ANY of the team's inbox reports, not just scout-authored ones."""
+
+ report_id = serializers.CharField(help_text="Id of the report to edit (must belong to this project).")
+ title = serializers.CharField(
+ required=False,
+ allow_null=True,
+ max_length=MAX_REPORT_TITLE_LENGTH,
+ help_text=(
+ "Optional new title. Conventional-commit style (`type(scope): description`) renders with "
+ "type/scope styling. The pipeline may later re-research and overwrite it."
+ ),
+ )
+ summary = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Optional new summary. Markdown is supported (headings, lists, code, links; images are not "
+ "rendered); lead with one plain declarative sentence — it becomes the inbox card headline. "
+ "The pipeline may later re-research and overwrite it."
+ ),
+ )
+ append_note = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="Optional free-form note to append to the report's work log (attributed to this scout).",
+ )
+
+
+class EditReportResponseSerializer(serializers.Serializer):
+ report_id = serializers.CharField(help_text="Id of the edited report.")
+ updated_fields = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Which presentation fields changed (e.g. `title`, `summary`); empty if only a note was appended.",
+ )
+ note_appended = serializers.BooleanField(help_text="Whether a note artefact was appended.")
+
+
# --- Project profile ------------------------------------------------------
diff --git a/products/signals/backend/scout_harness/skill_loader.py b/products/signals/backend/scout_harness/skill_loader.py
index 77abe61f9a82..67038e170d31 100644
--- a/products/signals/backend/scout_harness/skill_loader.py
+++ b/products/signals/backend/scout_harness/skill_loader.py
@@ -27,10 +27,14 @@ class LoadedSkill:
version: int
body: str
description: str
- # Portable skill metadata — opaque to the harness. Logged on spawn for observability,
- # not consulted at runtime. Downstream consumers (e.g. Claude Code) may read this list
- # to narrow their own tool exposure; the scout harness itself gates via
- # `posthog_mcp_scopes` at the OAuth/MCP boundary (scope-level), not tool-level.
+ # Portable skill metadata, and the opt-in gate for the report channel. The harness reads it at
+ # spawn time: listing `emit_report` / `edit_report` here makes the runner grant the
+ # `signals_scout_reports` scope posture (vs plain `signals_scout`), which carries
+ # `signal_scout_report:write` — the scope the report tools require. A scout that doesn't list them
+ # gets no report scope, so the MCP server strips those tools from its toolset (exposure is
+ # scope-level at the OAuth/MCP boundary). The `emit-report` / `edit-report` viewset actions also
+ # re-check this list server-side (`views.SignalScoutRunViewSet._assert_report_tool_opted_in`) as a
+ # fail-closed gate on the write. Downstream consumers (e.g. Claude Code) may also read it.
allowed_tools: list[str]
files: list[LoadedSkillFile]
skill_id: str
diff --git a/products/signals/backend/scout_harness/tools/__init__.py b/products/signals/backend/scout_harness/tools/__init__.py
index 84274aec452f..5196891ae69c 100644
--- a/products/signals/backend/scout_harness/tools/__init__.py
+++ b/products/signals/backend/scout_harness/tools/__init__.py
@@ -21,6 +21,15 @@ from products.signals.backend.scout_harness.tools.profile import (
compute_project_profile,
get_project_profile,
)
+from products.signals.backend.scout_harness.tools.report import (
+ EditReportResult,
+ EmitReportResult,
+ ReportEvidence,
+ edit_report,
+ edit_report_sync,
+ emit_report,
+ emit_report_sync,
+)
from products.signals.backend.scout_harness.tools.runs import (
DEFAULT_RUN_SEARCH_LIMIT,
MAX_RUN_SEARCH_LIMIT,
@@ -39,6 +48,8 @@ from products.signals.backend.scout_harness.tools.scratchpad import (
__all__ = [
"DEFAULT_RUN_SEARCH_LIMIT",
+ "EditReportResult",
+ "EmitReportResult",
"EmitResult",
"EvidenceEntry",
"InvalidEmitError",
@@ -49,11 +60,16 @@ __all__ = [
"MAX_TAGS_PER_FINDING",
"PROFILE_TTL",
"ProjectProfile",
+ "ReportEvidence",
"ScratchpadEntry",
"RunDetail",
"RunSummary",
"compute_project_profile",
+ "edit_report",
+ "edit_report_sync",
"emit_finding",
+ "emit_report",
+ "emit_report_sync",
"forget",
"get_project_profile",
"get_run",
diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.py
new file mode 100644
index 000000000000..e43691555b95
--- /dev/null
+++ b/products/signals/backend/scout_harness/tools/report.py
@@ -0,0 +1,619 @@
+"""Report-authoring harness tools: the second emit channel (`emit_report` / `edit_report`).
+
+Where `emit.py` forwards a weak signal through `emit_signal()` and lets the pipeline decide, these
+tools let an opted-in scout author or edit a full `SignalReport` directly. They are thin harness
+adapters: input validation + the shared preflight gates + attribution, then calls into the sanctioned
+`scout_report/` service (`judge_scout_report` + `create_scout_report` for emit; `update_scout_report` /
+`append_report_note` for edit). The tool never touches `SignalReport` or the embeddings pipeline itself
+— that boundary lives in the service (see `scout_harness/AGENTS.md`).
+
+Opt-in is by `allowed_tools`: a scout gets these only if its skill lists `emit_report` / `edit_report`,
+intersected with what `tools/__init__.py` re-exports.
+
+Like `emit_finding`, these are NOT idempotent — a retried `emit_report` authors a second report. The
+dedup story is the vanilla inbox tools (`inbox-reports-list` / `inbox-reports-retrieve`) plus a
+`report:<domain>:<entity>` scratchpad key the scout maintains; callers must not retry an authoring call
+that may have succeeded.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from typing import Any
+
+import posthoganalytics
+from asgiref.sync import async_to_sync
+
+from posthog.event_usage import groups
+from posthog.models import Team
+from posthog.sync import database_sync_to_async
+
+from products.signals.backend.artefact_schemas import (
+ ActionabilityAssessment,
+ ActionabilityChoice,
+ Priority,
+ PriorityAssessment,
+ SuggestedReviewerEntry,
+ SuggestedReviewers,
+)
+from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalScoutRun
+from products.signals.backend.report_generation.select_repo import RepoSelectionResult
+from products.signals.backend.scout_harness.tools.emit import (
+ SCOUT_SIGNAL_WEIGHT,
+ # Shared harness gates/attribution — the report channel applies the same preflight as emit.
+ _assert_team_owns_run,
+ _preflight_emit_gates,
+ _resolve_task_id,
+)
+from products.signals.backend.scout_report import (
+ MAX_REPORT_SIGNALS,
+ InvalidScoutReportError,
+ ScoutReportSignal,
+ append_report_note,
+ create_scout_report,
+ update_scout_report,
+)
+from products.signals.backend.scout_report.judge import ScoutReportJudgement, judge_scout_report
+
+logger = logging.getLogger(__name__)
+
+# Defensive caps at the tool boundary (the service caps signals too; these bound caller input early).
+MAX_REPORT_TITLE_LENGTH = 300
+MAX_SUGGESTED_REVIEWERS = 10
+# Bound the free-text the scout supplies before any of it is rendered into the safety-judge prompt or
+# the embedding requests — a report can carry up to MAX_REPORT_SIGNALS evidence items, so an unbounded
+# per-item description (or summary) lets one malformed call spend/fail on a huge LLM prompt.
+MAX_EVIDENCE_DESCRIPTION_LENGTH = 4000
+MAX_REPORT_SUMMARY_LENGTH = 20000
+
+# Repository modes for `emit_report`, mirroring `custom_agent`'s three-mode contract:
+# "owner/repo" -> that repo; NO_REPO -> explicitly no repo (lands without a draft PR);
+# omitted (None) -> free-form selection across the team's repos (`select_repository_for_team`).
+NO_REPO = "NO_REPO"
+
+
+@dataclass(frozen=True)
+class ReportEvidence:
+ """One observation backing an authored report — becomes a bound `document_embeddings` signal row."""
+
+ description: str
+ source_id: str
+ weight: float = SCOUT_SIGNAL_WEIGHT
+
+
+@dataclass(frozen=True)
+class EmitReportResult:
+ """Outcome of an `emit_report` call.
+
+ The report is always persisted when not gate-skipped (so the agent can edit/dedup against
+ `report_id` even when it was suppressed). `emitted` means it actually surfaced in the inbox
+ (status READY or PENDING_INPUT); a safety-suppressed or not-actionable report has emitted=False.
+ `skipped_reason` is set only when a preflight gate stopped the call before any report was created.
+ """
+
+ report_id: str | None
+ status: str | None
+ emitted: bool
+ skipped_reason: str | None
+ safety_explanation: str | None
+
+
+@dataclass(frozen=True)
+class EditReportResult:
+ report_id: str
+ updated_fields: list[str]
+ note_appended: bool
+
+
+def _surfaced(status: SignalReport.Status) -> bool:
+ return status in (SignalReport.Status.READY, SignalReport.Status.PENDING_INPUT)
+
+
+def _build_signals(evidence: list[ReportEvidence]) -> list[ScoutReportSignal]:
+ return [ScoutReportSignal(description=e.description, source_id=e.source_id, weight=e.weight) for e in evidence]
+
+
+def _build_actionability(*, explanation: str, choice: str, already_addressed: bool) -> ActionabilityAssessment:
+ try:
+ actionability_choice = ActionabilityChoice(choice)
+ except ValueError:
+ valid = ", ".join(c.value for c in ActionabilityChoice)
+ raise InvalidScoutReportError(f"actionability must be one of [{valid}], got {choice!r}")
+ return ActionabilityAssessment(
+ explanation=explanation, actionability=actionability_choice, already_addressed=already_addressed
+ )
+
+
+def _validate_emit_inputs(title: str, summary: str, evidence: list[ReportEvidence]) -> None:
+ if not title or not title.strip():
+ raise InvalidScoutReportError("title must not be empty")
+ if len(title) > MAX_REPORT_TITLE_LENGTH:
+ raise InvalidScoutReportError(f"title exceeds {MAX_REPORT_TITLE_LENGTH} chars ({len(title)})")
+ if len(summary) > MAX_REPORT_SUMMARY_LENGTH:
+ raise InvalidScoutReportError(f"summary exceeds {MAX_REPORT_SUMMARY_LENGTH} chars ({len(summary)})")
+ if not evidence:
+ raise InvalidScoutReportError("emit_report needs at least one piece of evidence")
+ # Enforce the service's evidence cap here, before the expensive safety-judge LLM call below — an
+ # oversized report would otherwise pay for the judge only to be rejected by `create_scout_report`.
+ if len(evidence) > MAX_REPORT_SIGNALS:
+ raise InvalidScoutReportError(
+ f"emit_report accepts at most {MAX_REPORT_SIGNALS} evidence items ({len(evidence)})"
+ )
+ for item in evidence:
+ if len(item.description) > MAX_EVIDENCE_DESCRIPTION_LENGTH:
+ raise InvalidScoutReportError(
+ f"evidence description exceeds {MAX_EVIDENCE_DESCRIPTION_LENGTH} chars ({len(item.description)})"
+ )
+
+
+def _normalize_repository(repository: str | None) -> str | None:
+ """Validate + normalize the scout's `repository` input. `None` / the `NO_REPO` sentinel pass through;
+ an explicit value is lowercased and format-checked as `owner/repo`. Raises `InvalidScoutReportError`
+ on a malformed value. Pure and cheap — called before the safety judge so a bad explicit repo fails
+ fast (rather than after paying for the judge), and reused by the resolver so the parsing lives once."""
+ if repository is None or repository == NO_REPO:
+ return repository
+ normalized = repository.strip().lower()
+ parts = normalized.split("/")
+ if len(parts) != 2 or not parts[0] or not parts[1]:
+ raise InvalidScoutReportError("repository must be in 'owner/repo' format (or the NO_REPO sentinel)")
+ return normalized
+
+
+def _gate_skip_result(preflight: str) -> EmitReportResult:
+ logger.warning("signals_scout.emit_report: skipped %s", preflight, extra={"skipped_reason": preflight})
+ return EmitReportResult(
+ report_id=None, status=None, emitted=False, skipped_reason=preflight, safety_explanation=None
+ )
+
+
+def _emit_result(persisted_report_id: str, judgement: ScoutReportJudgement) -> EmitReportResult:
+ return EmitReportResult(
+ report_id=persisted_report_id,
+ status=judgement.status,
+ emitted=_surfaced(judgement.status),
+ skipped_reason=None,
+ safety_explanation=judgement.safety.explanation,
+ )
+
+
+def _attribution_for(task_id: str | None) -> ArtefactAttribution:
+ return ArtefactAttribution.from_task(task_id) if task_id is not None else ArtefactAttribution.system()
+
+
+def _build_priority(priority: str | None, explanation: str | None) -> PriorityAssessment | None:
+ """Build the `priority_judgment` artefact content from scout-supplied inputs, or None to omit it.
+
+ Autostart needs a priority, so omitting it (or actionability != immediately_actionable) just means
+ the report lands without a draft PR. When a priority is given, an explanation is required."""
+ if priority is None:
+ return None
+ try:
+ priority_level = Priority(priority)
+ except ValueError:
+ valid = ", ".join(p.value for p in Priority)
+ raise InvalidScoutReportError(f"priority must be one of [{valid}], got {priority!r}")
+ if not explanation or not explanation.strip():
+ raise InvalidScoutReportError("priority_explanation is required when priority is set")
+ return PriorityAssessment(priority=priority_level, explanation=explanation)
+
+
+def _build_suggested_reviewers(github_logins: list[str] | None) -> SuggestedReviewers | None:
+ """Build the `suggested_reviewers` artefact from scout-supplied github logins, or None to omit it.
+
+ These are who autostart considers (each must clear their autonomy threshold). The scout supplies
+ the logins — exactly how a custom agent supplies assignees — rather than us resolving them from
+ repo history. Empty/blank logins are dropped; an all-empty list yields None."""
+ if not github_logins:
+ return None
+ cleaned = [login.strip() for login in github_logins if login and login.strip()]
+ if not cleaned:
+ return None
+ if len(cleaned) > MAX_SUGGESTED_REVIEWERS:
+ raise InvalidScoutReportError(f"at most {MAX_SUGGESTED_REVIEWERS} suggested reviewers, got {len(cleaned)}")
+ return SuggestedReviewers(root=[SuggestedReviewerEntry(github_login=login) for login in cleaned])
+
+
+def _wants_repo_selection(
+ repository: str | None, priority: PriorityAssessment | None, reviewers: SuggestedReviewers | None
+) -> bool:
+ """Whether to run repo selection at all. Resolve a repo only when the scout signalled PR intent —
+ either an explicit `repository`, or the priority + reviewers an autostart needs. An informational
+ report that supplies none of these skips selection entirely, so it never pays for the (free-form)
+ selection sandbox just to surface in the inbox."""
+ return repository is not None or (priority is not None and reviewers is not None)
+
+
+def _repo_request_section(title: str, summary: str, evidence: list[ReportEvidence]) -> str:
+ """Render the report into the free-text request the repo selector reasons over."""
+ lines = [title, "", summary]
+ if evidence:
+ lines += ["", "Evidence:"]
+ lines += [f"- {e.description}" for e in evidence]
+ return "\n".join(lines)
+
+
+async def _resolve_report_repository(
+ *, team_id: int, repository: str | None, title: str, summary: str, evidence: list[ReportEvidence]
+) -> RepoSelectionResult | None:
+ """Resolve the scout's `repository` input into a `repo_selection` artefact (or None to write none).
+
+ Three modes mirror `custom_agent`: ``NO_REPO`` -> explicitly no repo; ``"owner/repo"`` -> that
+ repo (validated, lowercased); omitted (None) -> free-form selection across the team's repos. The
+ free-form path is the slow one — for a team with many repos it spawns a selection sandbox — so a
+ scout that knows its repo should pass it explicitly (see the report contract). The cheap
+ `NO_REPO` / `owner/repo` cases are validated by `_normalize_repository` up front (before the judge),
+ so by here an explicit repo is already well-formed; only the free-form path remains."""
+ repository = _normalize_repository(repository)
+ if repository == NO_REPO:
+ return RepoSelectionResult(repository=None, reason="Scout passed NO_REPO; report lands without a draft PR.")
+ if repository is not None:
+ return RepoSelectionResult(repository=repository, reason="Repository provided by the scout.")
+
+ # Free-form: let the shared selector pick across the team's repos. Imports are deferred to keep the
+ # temporal/agentic + sandbox stack off this harness-tool module's import path (it loads at worker boot).
+ from products.signals.backend.report_generation.select_repo import (
+ select_repository_for_team, # noqa: PLC0415 — break worker-boot import cycle
+ )
+ from products.signals.backend.temporal.agentic import ( # noqa: PLC0415 — break worker-boot import cycle
+ SIGNALS_REPO_DISCOVERY_ENV_NAME,
+ get_or_create_signals_sandbox_env,
+ resolve_user_id_for_team,
+ )
+ from products.signals.backend.temporal.agentic.select_repository import (
+ GITHUB_ONLY_DOMAINS, # noqa: PLC0415 — break worker-boot import cycle
+ )
+ from products.tasks.backend.facade import api as tasks_facade # noqa: PLC0415 — break worker-boot import cycle
+
+ # A team with no GitHub integration can't resolve an acting user — `resolve_user_id_for_team`
+ # raises. Repo selection / autostart is optional, so treat that as "no repo" (the report still
+ # surfaces, just without a draft PR) rather than failing the whole emit — same null-repo outcome
+ # the repo-selection activity returns for a GitHub-less team.
+ try:
+ user_id = await database_sync_to_async(resolve_user_id_for_team, thread_sensitive=False)(team_id)
+ except Exception as exc:
+ logger.info(
+ "signals_scout.emit_report: skipping repo selection, no acting user for team",
+ extra={"team_id": team_id, "error": str(exc)},
+ )
+ return RepoSelectionResult(repository=None, reason="No GitHub integration; report lands without a draft PR.")
+
+ sandbox_env_id = await database_sync_to_async(get_or_create_signals_sandbox_env, thread_sensitive=False)(
+ team_id,
+ SIGNALS_REPO_DISCOVERY_ENV_NAME,
+ tasks_facade.SandboxNetworkAccessLevel.CUSTOM,
+ allowed_domains=GITHUB_ONLY_DOMAINS,
+ )
+ return await select_repository_for_team(
+ team_id=team_id,
+ user_id=user_id,
+ request_section=_repo_request_section(title, summary, evidence),
+ step_name="scout_repo_selection",
+ sandbox_environment_id=sandbox_env_id,
+ )
+
+
+async def _maybe_autostart_report(*, team_id: int, report_id: str) -> None:
+ """Best-effort autostart hand-off after a report surfaced. Reconstructs the autostart inputs from
+ the report's artefacts (the same shared entry point the reviewer-edit hook uses) and swallows
+ failures so a draft-PR hiccup never fails the emit. No-ops unless the report is immediately
+ actionable, has a repo + priority, and a suggested reviewer clears their autonomy threshold."""
+ from products.signals.backend.auto_start import (
+ maybe_autostart_from_report_artefacts, # noqa: PLC0415 — break worker-boot import cycle
+ )
+
+ try:
+ await maybe_autostart_from_report_artefacts(team_id=team_id, report_id=report_id)
+ except Exception:
+ logger.exception("signals_scout.emit_report: autostart failed", extra={"report_id": report_id})
+
+
+def _report_event_base(run: SignalScoutRun) -> dict[str, Any]:
+ """Shared dimensions for the report-channel lifecycle events, mirroring the `signals_scout_run_*`
+ events so the two join on `run_id` / `task_run_id` — a report event sits under the run that authored
+ it. All fields are plain columns on the bridge row (no FK query)."""
+ return {
+ "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,
+ }
+
+
+def _capture_report_emitted(*, team: Team, run: SignalScoutRun, result: EmitReportResult, evidence_count: int) -> None:
+ """Emit the scout-owned `signals_scout_report_emitted` event — the report-channel counterpart to
+ `signals_scout_run_finished`, fired once per `emit_report` call that reached a terminal outcome.
+
+ `outcome` is the single dimension to segment the channel funnel on: `gate_skipped` (a preflight gate
+ stopped the call before any report existed), `suppressed` (authored but the judge / actionability kept
+ it out of the inbox), or `surfaced` (landed in the inbox as READY / PENDING_INPUT). Keyed on the team
+ and carrying the run / task ids so it joins to the run lifecycle events. Best-effort: a capture failure
+ must never fail or mask the emit. Accesses `team.organization` — call on a sync thread."""
+ if result.skipped_reason is not None:
+ outcome = "gate_skipped"
+ elif result.emitted:
+ outcome = "surfaced"
+ else:
+ outcome = "suppressed"
+ properties = {
+ **_report_event_base(run),
+ "report_id": result.report_id,
+ "status": result.status,
+ "outcome": outcome,
+ "skipped_reason": result.skipped_reason,
+ "evidence_count": evidence_count,
+ }
+ try:
+ posthoganalytics.capture(
+ event="signals_scout_report_emitted",
+ distinct_id=str(team.uuid),
+ properties=properties,
+ groups=groups(team.organization, team),
+ )
+ except Exception:
+ logger.warning(
+ "signals_scout: failed to capture report-emitted analytics event",
+ extra={"team_id": team.id, "run_id": str(run.id), "skill_name": run.skill_name},
+ )
+
+
+def _capture_report_edited(*, team: Team, run: SignalScoutRun, result: EditReportResult) -> None:
+ """Emit the scout-owned `signals_scout_report_edited` event when a scout mutates an existing report via
+ `edit_report`, so edits are observable separately from fresh authorship. `updated_fields` /
+ `note_appended` distinguish a title/summary rewrite from a note-only append. Best-effort; never fails
+ the edit. Accesses `team.organization` — call on a sync thread."""
+ properties = {
+ **_report_event_base(run),
+ "report_id": result.report_id,
+ "updated_fields": result.updated_fields,
+ "note_appended": result.note_appended,
+ }
+ try:
+ posthoganalytics.capture(
+ event="signals_scout_report_edited",
+ distinct_id=str(team.uuid),
+ properties=properties,
+ groups=groups(team.organization, team),
+ )
+ except Exception:
+ logger.warning(
+ "signals_scout: failed to capture report-edited analytics event",
+ extra={"team_id": team.id, "run_id": str(run.id), "skill_name": run.skill_name},
+ )
+
+
+async def emit_report(
+ *,
+ team: Team,
+ run: SignalScoutRun,
+ title: str,
+ summary: str,
+ evidence: list[ReportEvidence],
+ actionability_explanation: str,
+ actionability: str,
+ already_addressed: bool = False,
+ repository: str | None = None,
+ priority: str | None = None,
+ priority_explanation: str | None = None,
+ suggested_reviewers: list[str] | None = None,
+) -> EmitReportResult:
+ """Author a full report: judge for safety, then persist at the judged status. Async entry (used by
+ the in-Temporal runner); routes the sync DB work through `database_sync_to_async`.
+
+ `repository` / `priority` / `priority_explanation` / `suggested_reviewers` are the optional
+ autostart inputs (custom_agent parity): with them a surfaced, immediately-actionable report can
+ open a draft PR. They're only resolved/written when the report actually surfaces."""
+ _assert_team_owns_run(team, run)
+ _validate_emit_inputs(title, summary, evidence)
+ # Validate the explicit repository format up front (cheap, pure) so a malformed `owner/repo` fails
+ # before the safety-judge LLM call rather than after. Free-form selection still runs only if surfaced.
+ _normalize_repository(repository)
+ signals = _build_signals(evidence)
+ actionability_assessment = _build_actionability(
+ explanation=actionability_explanation, choice=actionability, already_addressed=already_addressed
+ )
+ priority_assessment = _build_priority(priority, priority_explanation)
+ reviewers = _build_suggested_reviewers(suggested_reviewers)
+
+ preflight = await database_sync_to_async(_preflight_emit_gates, thread_sensitive=False)(team, run)
+ if preflight is not None:
+ result = _gate_skip_result(preflight)
+ await database_sync_to_async(_capture_report_emitted, thread_sensitive=False)(
+ team=team, run=run, result=result, evidence_count=len(evidence)
+ )
+ return result
+
+ task_id = await database_sync_to_async(_resolve_task_id, thread_sensitive=False)(run)
+ attribution = _attribution_for(task_id)
+ judgement = await judge_scout_report(
+ team_id=team.id, title=title, summary=summary, signals=signals, actionability=actionability_assessment
+ )
+ surfaced = _surfaced(judgement.status)
+ repo_selection = (
+ await _resolve_report_repository(
+ team_id=team.id, repository=repository, title=title, summary=summary, evidence=evidence
+ )
+ if surfaced and _wants_repo_selection(repository, priority_assessment, reviewers)
+ else None
+ )
+ persisted = await database_sync_to_async(create_scout_report, thread_sensitive=False)(
+ team_id=team.id,
+ title=title,
+ summary=summary,
+ signals=signals,
+ attribution=attribution,
+ status=judgement.status,
+ safety=judgement.safety,
+ actionability=judgement.actionability,
+ repo_selection=repo_selection,
+ priority=priority_assessment if surfaced else None,
+ suggested_reviewers=reviewers if surfaced else None,
+ # Don't index the backing observations of a safety-suppressed (unsafe) report — they'd
+ # otherwise become semantic-search / matching context despite never surfacing.
+ emit_signals=judgement.safety.choice,
+ run=run,
+ )
+ if surfaced:
+ await _maybe_autostart_report(team_id=team.id, report_id=persisted.report_id)
+ result = _emit_result(persisted.report_id, judgement)
+ await database_sync_to_async(_capture_report_emitted, thread_sensitive=False)(
+ team=team, run=run, result=result, evidence_count=len(evidence)
+ )
+ return result
+
+
+def emit_report_sync(
+ *,
+ team: Team,
+ run: SignalScoutRun,
+ title: str,
+ summary: str,
+ evidence: list[ReportEvidence],
+ actionability_explanation: str,
+ actionability: str,
+ already_addressed: bool = False,
+ repository: str | None = None,
+ priority: str | None = None,
+ priority_explanation: str | None = None,
+ suggested_reviewers: list[str] | None = None,
+) -> EmitReportResult:
+ """Sync entry used by the DRF view path. Mirrors `emit_report` but keeps the sync DB work on the
+ calling thread/connection (gates, persist) — only the safety-judge LLM call, the free-form repo
+ selection, and the autostart hand-off are bridged via `async_to_sync` (each runs before/after the
+ report transaction, so they don't share its connection). Wrapping the whole async function instead
+ would run every DB op on a separate connection, which a request's transaction can't see."""
+ _assert_team_owns_run(team, run)
+ _validate_emit_inputs(title, summary, evidence)
+ # Validate the explicit repository format up front (cheap, pure) so a malformed `owner/repo` fails
+ # before the safety-judge LLM call rather than after. Free-form selection still runs only if surfaced.
+ _normalize_repository(repository)
+ signals = _build_signals(evidence)
+ actionability_assessment = _build_actionability(
+ explanation=actionability_explanation, choice=actionability, already_addressed=already_addressed
+ )
+ priority_assessment = _build_priority(priority, priority_explanation)
+ reviewers = _build_suggested_reviewers(suggested_reviewers)
+
+ preflight = _preflight_emit_gates(team, run)
+ if preflight is not None:
+ result = _gate_skip_result(preflight)
+ _capture_report_emitted(team=team, run=run, result=result, evidence_count=len(evidence))
+ return result
+
+ task_id = _resolve_task_id(run)
+ attribution = _attribution_for(task_id)
+ judgement = async_to_sync(judge_scout_report)(
+ team_id=team.id, title=title, summary=summary, signals=signals, actionability=actionability_assessment
+ )
+ surfaced = _surfaced(judgement.status)
+ repo_selection = (
+ async_to_sync(_resolve_report_repository)(
+ team_id=team.id, repository=repository, title=title, summary=summary, evidence=evidence
+ )
+ if surfaced and _wants_repo_selection(repository, priority_assessment, reviewers)
+ else None
+ )
+ persisted = create_scout_report(
+ team_id=team.id,
+ title=title,
+ summary=summary,
+ signals=signals,
+ attribution=attribution,
+ status=judgement.status,
+ safety=judgement.safety,
+ actionability=judgement.actionability,
+ repo_selection=repo_selection,
+ priority=priority_assessment if surfaced else None,
+ suggested_reviewers=reviewers if surfaced else None,
+ # Don't index the backing observations of a safety-suppressed (unsafe) report — they'd
+ # otherwise become semantic-search / matching context despite never surfacing.
+ emit_signals=judgement.safety.choice,
+ run=run,
+ )
+ if surfaced:
+ async_to_sync(_maybe_autostart_report)(team_id=team.id, report_id=persisted.report_id)
+ result = _emit_result(persisted.report_id, judgement)
+ _capture_report_emitted(team=team, run=run, result=result, evidence_count=len(evidence))
+ return result
+
+
+def _do_edit_report(
+ *,
+ team: Team,
+ run: SignalScoutRun,
+ report_id: str,
+ title: str | None,
+ summary: str | None,
+ append_note: str | None,
+) -> EditReportResult:
+ """Fully-sync edit core (no LLM step). The async/sync entrypoints both funnel here — directly in
+ the sync path, via `database_sync_to_async` in the async path."""
+ preflight = _preflight_emit_gates(team, run)
+ if preflight is not None:
+ raise InvalidScoutReportError(f"edit_report blocked by preflight gate: {preflight}")
+
+ attribution = _attribution_for(_resolve_task_id(run))
+ updated_fields: list[str] = []
+ if title is not None or summary is not None:
+ updated_fields = update_scout_report(
+ team_id=team.id,
+ report_id=report_id,
+ title=title,
+ summary=summary,
+ attribution=attribution,
+ author=run.skill_name,
+ )
+ note_appended = False
+ if append_note is not None:
+ append_report_note(
+ team_id=team.id, report_id=report_id, note=append_note, attribution=attribution, author=run.skill_name
+ )
+ note_appended = True
+ logger.info(
+ "signals_scout.edit_report: edited",
+ extra={"team_id": team.id, "report_id": report_id, "fields": updated_fields, "note": note_appended},
+ )
+ result = EditReportResult(report_id=report_id, updated_fields=updated_fields, note_appended=note_appended)
+ _capture_report_edited(team=team, run=run, result=result)
+ return result
+
+
+def _validate_edit_inputs(team: Team, run: SignalScoutRun, title, summary, append_note) -> None:
+ _assert_team_owns_run(team, run)
+ if title is None and summary is None and append_note is None:
+ raise InvalidScoutReportError("edit_report needs at least one of title, summary, append_note")
+
+
+async def edit_report(
+ *,
+ team: Team,
+ run: SignalScoutRun,
+ report_id: str,
+ title: str | None = None,
+ summary: str | None = None,
+ append_note: str | None = None,
+) -> EditReportResult:
+ """Edit an existing inbox report: rewrite title/summary and/or append a note. Team-scoped
+ fail-closed in the service. Async entry; runs the sync edit core in the thread pool."""
+ _validate_edit_inputs(team, run, title, summary, append_note)
+ return await database_sync_to_async(_do_edit_report, thread_sensitive=False)(
+ team=team, run=run, report_id=report_id, title=title, summary=summary, append_note=append_note
+ )
+
+
+def edit_report_sync(
+ *,
+ team: Team,
+ run: SignalScoutRun,
+ report_id: str,
+ title: str | None = None,
+ summary: str | None = None,
+ append_note: str | None = None,
+) -> EditReportResult:
+ """Sync entry used by the DRF view path. Same behavior as `edit_report`, on the calling thread."""
+ _validate_edit_inputs(team, run, title, summary, append_note)
+ return _do_edit_report(
+ team=team, run=run, report_id=report_id, title=title, summary=summary, append_note=append_note
+ )
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index b0cb8c136bae..39bac982be4c 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -62,8 +62,12 @@ from products.signals.backend.scout_harness.lazy_seed import (
)
from products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAM
from products.signals.backend.scout_harness.serializers import (
+ EditReportRequestSerializer,
+ EditReportResponseSerializer,
EmitFindingRequestSerializer,
EmitFindingResponseSerializer,
+ EmitReportRequestSerializer,
+ EmitReportResponseSerializer,
EvidenceEntrySerializer,
ForgetRequestSerializer,
ForgetResponseSerializer,
@@ -81,6 +85,7 @@ from products.signals.backend.scout_harness.serializers import (
SignalScoutRunDetailSerializer,
SignalScoutRunSummarySerializer,
)
+from products.signals.backend.scout_harness.skill_loader import SkillNotFoundError, load_skill_for_run
from products.signals.backend.scout_harness.team_limits import (
resolve_sync_seed_inputs,
resolve_team_metadata,
@@ -88,6 +93,7 @@ from products.signals.backend.scout_harness.team_limits import (
)
from products.signals.backend.scout_harness.tools.emit import EvidenceEntry, InvalidEmitError, emit_finding_sync
from products.signals.backend.scout_harness.tools.profile import get_project_profile
+from products.signals.backend.scout_harness.tools.report import ReportEvidence, edit_report_sync, emit_report_sync
from products.signals.backend.scout_harness.tools.runs import get_run, search_recent_runs
from products.signals.backend.scout_harness.tools.scratchpad import (
InvalidScratchpadError,
@@ -95,6 +101,7 @@ from products.signals.backend.scout_harness.tools.scratchpad import (
remember,
search_scratchpad,
)
+from products.signals.backend.scout_report import InvalidScoutReportError
from products.signals.backend.temporal.signal_queries import fetch_report_ids_for_source_ids
from products.skills.backend.models.skills import LLMSkill
@@ -467,6 +474,173 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
status=status.HTTP_200_OK,
)
+ def _resolve_in_progress_run(self, kwargs: dict, *, required_tool: str) -> SignalScoutRun:
+ """Resolve the run for a report-channel write action: team-scoped lookup + the same in-progress
+ guard `emit_signal` uses, plus the `allowed_tools` opt-in gate. A report is authored *during* a
+ run, so a finished run can't author one.
+
+ The report channel is opt-in by `allowed_tools`. Tool *exposure* is already gated at the scope
+ layer — the runner grants the `signals_scout_reports` posture (which carries
+ `signal_scout_report:write`, the scope these actions require) only when the skill opted in, so a
+ non-opted scout never sees the tools and its token can't satisfy `required_scopes`. This server-side
+ check is the matching fail-closed gate on the write itself: reject unless the run's skill lists
+ `required_tool` in its `allowed_tools`, so the two enforcement layers can't drift."""
+ 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"Reports can only be authored on in-progress runs (current: {run.task_run.status})."}
+ )
+ self._assert_report_tool_opted_in(run, required_tool)
+ return run
+
+ def _assert_report_tool_opted_in(self, run: SignalScoutRun, required_tool: str) -> None:
+ """Fail closed unless the run's skill opted into `required_tool` via `allowed_tools`. Loads the
+ exact skill version the run snapshotted so the gate matches what actually ran; a missing/unloadable
+ skill is treated as not-opted-in (deny)."""
+ # `run.team` is the canonical team the run was resolved on (the query above filters on
+ # `_canonical_team_id`), and is where the scout's `LLMSkill` rows are seeded.
+ try:
+ skill = load_skill_for_run(run.team, run.skill_name, version=run.skill_version)
+ except SkillNotFoundError:
+ raise exceptions.PermissionDenied(
+ f"Report channel is opt-in; skill '{run.skill_name}' (v{run.skill_version}) could not be "
+ "resolved to verify its allowed_tools."
+ )
+ if required_tool not in skill.allowed_tools:
+ raise exceptions.PermissionDenied(
+ f"Report channel is opt-in: skill '{run.skill_name}' must list '{required_tool}' in its "
+ "allowed_tools to use this tool."
+ )
+
+ @validated_request(
+ request_serializer=EmitReportRequestSerializer,
+ parameters=[_RUN_ID_PATH_PARAMETER],
+ responses={
+ 200: OpenApiResponse(
+ response=EmitReportResponseSerializer,
+ description="Report authored (READY/PENDING_INPUT/suppressed), or skipped by a preflight gate.",
+ ),
+ 400: OpenApiResponse(description="Invalid report shape (empty title/summary/evidence, bad actionability)."),
+ 404: OpenApiResponse(description="Run not found for this project."),
+ },
+ summary="Author a full report for a run",
+ description=(
+ "The second emit channel: author a complete `SignalReport` directly instead of emitting a weak "
+ "signal. The report passes the safety judge, then surfaces at the status the scout's `actionability` "
+ "call implies (or is suppressed). Backing `evidence` is written as bound signals so the report "
+ "behaves like a pipeline report. NOT idempotent — a retry authors a second report; use `reports` to "
+ "find a prior report and `edit-report` to update it instead."
+ ),
+ operation_id="signals_scout_emit_report",
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="emit-report",
+ required_scopes=["signal_scout_report:write"],
+ pagination_class=None,
+ )
+ def emit_report(self, request: Request, **kwargs) -> Response:
+ run = self._resolve_in_progress_run(kwargs, required_tool="emit_report")
+ data = request.validated_data
+ evidence = [
+ ReportEvidence(
+ description=entry["description"],
+ source_id=entry["source_id"],
+ **({"weight": entry["weight"]} if entry.get("weight") is not None else {}),
+ )
+ for entry in data["evidence"]
+ ]
+ try:
+ result = emit_report_sync(
+ # `run.team` is the canonical (parent) team the run was resolved on; a child-environment
+ # request's `self.team` would mismatch the run's owner and trip `_assert_team_owns_run`.
+ team=run.team,
+ run=run,
+ title=data["title"],
+ summary=data["summary"],
+ evidence=evidence,
+ actionability_explanation=data["actionability_explanation"],
+ actionability=data["actionability"],
+ already_addressed=data.get("already_addressed", False),
+ repository=data.get("repository"),
+ priority=data.get("priority"),
+ priority_explanation=data.get("priority_explanation"),
+ suggested_reviewers=data.get("suggested_reviewers"),
+ )
+ except InvalidScoutReportError as exc:
+ raise exceptions.ValidationError({"detail": str(exc)})
+ return Response(
+ EmitReportResponseSerializer(
+ {
+ "report_id": result.report_id,
+ "report_status": result.status,
+ "emitted": result.emitted,
+ "skipped_reason": result.skipped_reason,
+ "safety_explanation": result.safety_explanation,
+ }
+ ).data,
+ status=status.HTTP_200_OK,
+ )
+
+ @validated_request(
+ request_serializer=EditReportRequestSerializer,
+ parameters=[_RUN_ID_PATH_PARAMETER],
+ responses={
+ 200: OpenApiResponse(response=EditReportResponseSerializer, description="Report edited."),
+ 400: OpenApiResponse(description="Nothing to edit, empty note, or report not found for this project."),
+ 404: OpenApiResponse(description="Run not found for this project."),
+ },
+ summary="Edit an existing report for a run",
+ description=(
+ "Rewrite a report's title/summary and/or append a note. Can target ANY of the project's inbox "
+ "reports, not just scout-authored ones — so the edit is attributed to this scout. Title/summary "
+ "edits are best-effort: the pipeline may later re-research and overwrite them."
+ ),
+ operation_id="signals_scout_edit_report",
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="edit-report",
+ required_scopes=["signal_scout_report:write"],
+ pagination_class=None,
+ )
+ def edit_report(self, request: Request, **kwargs) -> Response:
+ run = self._resolve_in_progress_run(kwargs, required_tool="edit_report")
+ data = request.validated_data
+ try:
+ result = edit_report_sync(
+ # Canonical team, as in `emit_report` above — avoids a child-env `_assert_team_owns_run` trip.
+ team=run.team,
+ run=run,
+ report_id=data["report_id"],
+ title=data.get("title"),
+ summary=data.get("summary"),
+ append_note=data.get("append_note"),
+ )
+ except InvalidScoutReportError as exc:
+ raise exceptions.ValidationError({"detail": str(exc)})
+ return Response(
+ EditReportResponseSerializer(
+ {
+ "report_id": result.report_id,
+ "updated_fields": result.updated_fields,
+ "note_appended": result.note_appended,
+ }
+ ).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.
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index 29e37e3defe6..636fbca06b7c 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -16,6 +16,7 @@ from posthog.temporal.oauth import (
ARRAY_APP_CLIENT_ID_DEV,
ARRAY_APP_CLIENT_ID_EU,
ARRAY_APP_CLIENT_ID_US,
+ PosthogMcpScopes,
create_oauth_access_token_for_user,
)
@@ -37,12 +38,16 @@ if TYPE_CHECKING:
from products.tasks.backend.models import TaskRun
-def _authenticate_as_scout(test: APIBaseTest) -> None:
+def _authenticate_as_scout(test: APIBaseTest, *, scopes: PosthogMcpScopes = "signals_scout") -> None:
"""Auth the test client with a scout-internal token, mirroring how the harness sandbox
reaches these endpoints in production. The emit / scratchpad write actions require
`signal_scout_internal:write`, which is server-mint-only and rejects session auth, so the
default `APIBaseTest` force-login isn't enough for the write surface — only reads pass on
a session. `logout()` first so the token is the sole credential on every request.
+
+ `scopes` selects the posture: the default `signals_scout` covers emit-signal / scratchpad;
+ pass `signals_scout_reports` (the report-channel posture, which adds `signal_scout_report:write`)
+ to exercise the emit-report / edit-report surface.
"""
# `create_oauth_access_token_for_user` resolves the Array app by `get_instance_region()`,
# which isn't deterministic across test contexts — create the app for every region client
@@ -59,9 +64,7 @@ def _authenticate_as_scout(test: APIBaseTest) -> None:
"algorithm": "RS256",
},
)
- token = create_oauth_access_token_for_user(
- test.user, test.team.id, scopes="signals_scout", include_internal_scopes=True
- )
+ token = create_oauth_access_token_for_user(test.user, test.team.id, scopes=scopes, include_internal_scopes=True)
test.client.logout()
test.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.py
new file mode 100644
index 000000000000..9d5b1724763e
--- /dev/null
+++ b/products/signals/backend/test/test_scout_report_api.py
@@ -0,0 +1,269 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import AsyncMock, patch
+
+from django.apps import apps
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models import Organization, Team
+
+from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalSourceConfig
+from products.signals.backend.temporal.report_safety_judge import SafetyJudgeResponse
+from products.signals.backend.test.test_scout_harness_api import _authenticate_as_scout, _make_run
+from products.skills.backend.models.skills import LLMSkill
+
+JUDGE_PATH = "products.signals.backend.scout_report.judge.judge_report_safety"
+EMBED_PATH = "products.signals.backend.scout_report.persistence.emit_embedding_request"
+# Patched at its source module so the lazy import inside `_maybe_autostart_report` picks up the mock.
+AUTOSTART_PATH = "products.signals.backend.auto_start.maybe_autostart_from_report_artefacts"
+CAPTURE_PATH = "products.signals.backend.scout_harness.tools.report.posthoganalytics.capture"
+REPORT_TOOLS = ["emit_report", "edit_report"]
+
+
+def _safe_judge(choice: bool = True, explanation: str = ""):
+ return patch(JUDGE_PATH, new=AsyncMock(return_value=SafetyJudgeResponse(choice=choice, explanation=explanation)))
+
+
+class TestScoutReportAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save(update_fields=["is_ai_data_processing_approved"])
+ SignalSourceConfig.objects.get_or_create(
+ team=self.team,
+ source_product="signals_scout",
+ source_type="cross_source_issue",
+ defaults={"enabled": True},
+ )
+ # The report channel is opt-in: `_make_run` defaults to skill `signals-scout-general` v1, so the
+ # gate needs a matching LLMSkill row that lists the report tools in `allowed_tools`.
+ LLMSkill.objects.create(
+ team=self.team,
+ name="signals-scout-general",
+ description="opted-in scout",
+ body="# scout",
+ allowed_tools=REPORT_TOOLS,
+ )
+ # The report channel requires `signal_scout_report:write`, granted only by the
+ # `signals_scout_reports` posture (mirrors the runner's opt-in posture selection).
+ _authenticate_as_scout(self, scopes="signals_scout_reports")
+
+ def _emit_url(self, run_id: str) -> str:
+ return f"/api/projects/{self.team.id}/signals/scout/runs/{run_id}/emit-report/"
+
+ def _edit_url(self, run_id: str) -> str:
+ return f"/api/projects/{self.team.id}/signals/scout/runs/{run_id}/edit-report/"
+
+ def _payload(self, **overrides) -> dict:
+ body: dict = {
+ "title": "Checkout p99 regressed after 4.2",
+ "summary": "The /checkout endpoint p99 doubled after the 4.2 deploy.",
+ "evidence": [{"description": "p99 doubled on /checkout", "source_id": "obs-1"}],
+ "actionability_explanation": "clear fix in the checkout handler",
+ "actionability": "immediately_actionable",
+ }
+ body.update(overrides)
+ return body
+
+ def test_emit_report_authors_ready_report(self) -> None:
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH) as embed_mock:
+ response = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ body = response.json()
+ assert body["emitted"] is True
+ assert body["report_status"] == SignalReport.Status.READY
+ assert body["skipped_reason"] is None
+ assert SignalReport.objects.filter(id=body["report_id"], team=self.team).exists()
+ embed_mock.assert_called_once()
+
+ def test_emit_report_unsafe_suppresses_but_returns_id(self) -> None:
+ run = _make_run(self.team)
+ with _safe_judge(choice=False, explanation="prompt injection"), patch(EMBED_PATH):
+ response = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json")
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["emitted"] is False
+ assert body["report_status"] == SignalReport.Status.SUPPRESSED
+ assert body["safety_explanation"] == "prompt injection"
+ assert body["report_id"] is not None
+
+ def test_emit_report_skips_when_ai_not_approved(self) -> None:
+ # Preflight gate: a report is never authored for an org that hasn't approved AI processing.
+ self.organization.is_ai_data_processing_approved = False
+ self.organization.save(update_fields=["is_ai_data_processing_approved"])
+ run = _make_run(self.team)
+ with _safe_judge() as judge_mock, patch(EMBED_PATH) as embed_mock:
+ response = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json")
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["skipped_reason"] == "ai_processing_not_approved"
+ assert body["report_id"] is None
+ # Gate stops before judging or persisting.
+ judge_mock.assert_not_awaited()
+ embed_mock.assert_not_called()
+ assert SignalReport.objects.filter(team=self.team).count() == 0
+
+ def test_emit_report_rejects_non_in_progress_run(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
+ run = _make_run(self.team, task_run_status=TaskRun.Status.COMPLETED)
+ response = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_emit_report_denied_when_skill_not_opted_in(self) -> None:
+ # Opt-in is enforced server-side: a run whose skill omits `emit_report` from allowed_tools is
+ # rejected even though the MCP token's scope can reach the endpoint.
+ LLMSkill.objects.create(
+ team=self.team, name="signals-scout-noreport", description="not opted in", body="# x", allowed_tools=[]
+ )
+ run = _make_run(self.team, skill_name="signals-scout-noreport")
+ with _safe_judge(), patch(EMBED_PATH) as embed_mock:
+ response = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json")
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ embed_mock.assert_not_called()
+ assert SignalReport.objects.filter(team=self.team).count() == 0
+
+ def test_emit_report_rejects_invalid_actionability(self) -> None:
+ run = _make_run(self.team)
+ response = self.client.post(
+ self._emit_url(str(run.id)), data=self._payload(actionability="made_up"), format="json"
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_edit_report_updates_title_and_appends_note(self) -> None:
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH):
+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={"report_id": created["report_id"], "title": "new title", "append_note": "re-validated"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert "title" in response.json()["updated_fields"]
+ assert response.json()["note_appended"] is True
+ assert SignalReport.objects.get(id=created["report_id"]).title == "new title"
+
+ def test_edit_report_fails_closed_on_cross_team_report(self) -> None:
+ other_org = Organization.objects.create(name="other")
+ other_team = Team.objects.create(organization=other_org, name="other")
+ other_report = SignalReport.objects.create(team=other_team, status=SignalReport.Status.READY, title="theirs")
+ run = _make_run(self.team)
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={"report_id": str(other_report.id), "title": "hijacked"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert SignalReport.objects.get(id=other_report.id).title == "theirs"
+
+ def _latest_artefact(self, report_id: str, artefact_type: str) -> SignalReportArtefact | None:
+ return (
+ SignalReportArtefact.objects.filter(report_id=report_id, type=artefact_type).order_by("-created_at").first()
+ )
+
+ def test_emit_report_writes_autostart_artefacts(self) -> None:
+ # The autostart inputs the scout supplies become the same artefacts a pipeline report carries,
+ # which is what `maybe_autostart_from_report_artefacts` reads to open a draft PR. Repo is normalized.
+ run = _make_run(self.team)
+ payload = self._payload(
+ repository="PostHog/PostHog",
+ priority="P1",
+ priority_explanation="429 users hit this in 2h",
+ suggested_reviewers=["octocat", "hubot"],
+ )
+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):
+ response = self.client.post(self._emit_url(str(run.id)), data=payload, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ report_id = response.json()["report_id"]
+ repo = self._latest_artefact(report_id, SignalReportArtefact.ArtefactType.REPO_SELECTION)
+ assert repo is not None and '"posthog/posthog"' in repo.content
+ assert self._latest_artefact(report_id, SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT) is not None
+ reviewers = self._latest_artefact(report_id, SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS)
+ assert reviewers is not None and "octocat" in reviewers.content
+
+ def test_emit_report_fires_autostart_when_surfaced(self) -> None:
+ run = _make_run(self.team)
+ payload = self._payload(repository="PostHog/PostHog", priority="P1", priority_explanation="big blast radius")
+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()) as autostart:
+ response = self.client.post(self._emit_url(str(run.id)), data=payload, format="json")
+ assert response.status_code == status.HTTP_200_OK
+ autostart.assert_awaited_once()
+ assert autostart.await_args is not None
+ assert autostart.await_args.kwargs["report_id"] == response.json()["report_id"]
+
+ def test_emit_report_skips_autostart_and_artefacts_when_suppressed(self) -> None:
+ # An unsafe report is suppressed — it must not write autostart inputs or try to open a PR.
+ run = _make_run(self.team)
+ payload = self._payload(repository="PostHog/PostHog", priority="P1", priority_explanation="x")
+ with (
+ _safe_judge(choice=False, explanation="unsafe"),
+ patch(EMBED_PATH),
+ patch(AUTOSTART_PATH, new=AsyncMock()) as autostart,
+ ):
+ response = self.client.post(self._emit_url(str(run.id)), data=payload, format="json")
+ assert response.json()["emitted"] is False
+ autostart.assert_not_awaited()
+ assert (
+ self._latest_artefact(response.json()["report_id"], SignalReportArtefact.ArtefactType.REPO_SELECTION)
+ is None
+ )
+
+ @parameterized.expand(
+ [
+ ("surfaced", True, True, "surfaced"),
+ ("suppressed", False, True, "suppressed"),
+ ("gate_skipped", True, False, "gate_skipped"),
+ ]
+ )
+ def test_emit_report_captures_lifecycle_event(
+ self, _name: str, safe: bool, ai_approved: bool, expected_outcome: str
+ ) -> None:
+ # The `signals_scout_report_emitted` event is the report channel's observability funnel — its
+ # `outcome` must classify every terminal path (surfaced / suppressed / gate_skipped) correctly and
+ # carry the run/report ids that join it to the run lifecycle events.
+ if not ai_approved:
+ self.organization.is_ai_data_processing_approved = False
+ self.organization.save(update_fields=["is_ai_data_processing_approved"])
+ run = _make_run(self.team)
+ with (
+ _safe_judge(choice=safe, explanation="" if safe else "unsafe"),
+ patch(EMBED_PATH),
+ patch(AUTOSTART_PATH, new=AsyncMock()),
+ patch(CAPTURE_PATH) as capture,
+ ):
+ body = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ event = next(c for c in capture.call_args_list if c.kwargs["event"] == "signals_scout_report_emitted")
+ props = event.kwargs["properties"]
+ assert props["outcome"] == expected_outcome
+ assert props["run_id"] == str(run.id)
+ assert props["report_id"] == body["report_id"]
+ assert props["evidence_count"] == 1
+
+ def test_edit_report_captures_edited_event(self) -> None:
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH), patch(CAPTURE_PATH) as capture:
+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ self.client.post(
+ self._edit_url(str(run.id)),
+ data={"report_id": created["report_id"], "title": "new title", "append_note": "re-validated"},
+ format="json",
+ )
+ event = next(c for c in capture.call_args_list if c.kwargs["event"] == "signals_scout_report_edited")
+ props = event.kwargs["properties"]
+ assert props["report_id"] == created["report_id"]
+ assert "title" in props["updated_fields"]
+ assert props["note_appended"] is True
+
+ @parameterized.expand(
+ [
+ ("invalid_priority", {"priority": "P9", "priority_explanation": "x"}),
+ ("priority_without_explanation", {"priority": "P1"}),
+ ]
+ )
+ def test_emit_report_rejects_bad_priority(self, _name: str, overrides: dict) -> None:
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):
+ response = self.client.post(self._emit_url(str(run.id)), data=self._payload(**overrides), format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 2fa41decfe4d..30a50ce3e0b6 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -1164,6 +1164,39 @@ export interface SignalScoutRunDetailApi {
emitted_finding_ids: string[]
}
+/**
+ * Request body for `edit-report`. Can target ANY of the team's inbox reports, not just scout-authored ones.
+ */
+export interface EditReportRequestApi {
+ /** Id of the report to edit (must belong to this project). */
+ report_id: string
+ /**
+ * Optional new title. Conventional-commit style (`type(scope): description`) renders with type/scope styling. The pipeline may later re-research and overwrite it.
+ * @maxLength 300
+ * @nullable
+ */
+ title?: string | null
+ /**
+ * Optional new summary. Markdown is supported (headings, lists, code, links; images are not rendered); lead with one plain declarative sentence — it becomes the inbox card headline. The pipeline may later re-research and overwrite it.
+ * @nullable
+ */
+ summary?: string | null
+ /**
+ * Optional free-form note to append to the report's work log (attributed to this scout).
+ * @nullable
+ */
+ append_note?: string | null
+}
+
+export interface EditReportResponseApi {
+ /** Id of the edited report. */
+ report_id: string
+ /** Which presentation fields changed (e.g. `title`, `summary`); empty if only a note was appended. */
+ updated_fields: string[]
+ /** Whether a note artefact was appended. */
+ note_appended: boolean
+}
+
/**
* * `P0` - P0
* * `P1` - P1
@@ -1255,6 +1288,107 @@ export interface ScoutEmissionReportLinkApi {
report: LinkedSignalReportApi | null
}
+/**
+ * One observation backing an authored report — becomes a bound signal row on the report.
+ */
+export interface ReportEvidenceApi {
+ /** Prose for this observation. Embedded and rendered to the safety/research surfaces. */
+ description: string
+ /** Stable id for this observation within the report (lets a later edit address it). */
+ source_id: string
+ /**
+ * Optional per-signal weight (defaults to 1.0). Scouts rarely need to set this.
+ * @minimum 0
+ */
+ weight?: number
+}
+
+/**
+ * * `immediately_actionable` - immediately_actionable
+ * * `requires_human_input` - requires_human_input
+ * * `not_actionable` - not_actionable
+ */
+export type ActionabilityEnumApi = (typeof ActionabilityEnumApi)[keyof typeof ActionabilityEnumApi]
+
+export const ActionabilityEnumApi = {
+ ImmediatelyActionable: 'immediately_actionable',
+ RequiresHumanInput: 'requires_human_input',
+ NotActionable: 'not_actionable',
+} as const
+
+/**
+ * Request body for `emit-report`. Run attribution is taken from the URL path.
+ */
+export interface EmitReportRequestApi {
+ /**
+ * One-line report title the inbox shows. Conventional-commit style (`type(scope): description`, e.g. `fix(insights): missing series color`) renders with type/scope styling.
+ * @maxLength 300
+ */
+ title: string
+ /** The report body the inbox shows. Markdown is supported (headings, lists, code, links; images are not rendered). Lead with one plain declarative sentence — the inbox card uses your first line verbatim as the headline (~140 chars, emphasis stripped), then renders the full markdown in the detail view. */
+ summary: string
+ /**
+ * The observations backing the report — each becomes a bound signal. At least one.
+ * @minItems 1
+ */
+ evidence: ReportEvidenceApi[]
+ /** 2-3 sentence evidence-grounded justification for the actionability call below. */
+ actionability_explanation: string
+ /** The scout's actionability call: `immediately_actionable` -> the report surfaces READY; `requires_human_input` -> PENDING_INPUT; `not_actionable` -> suppressed. A safety-judge failure suppresses the report regardless.
+ *
+ * * `immediately_actionable` - immediately_actionable
+ * * `requires_human_input` - requires_human_input
+ * * `not_actionable` - not_actionable */
+ actionability: ActionabilityEnumApi
+ /** Whether the issue already appears fixed in recent changes (tracked separately). */
+ already_addressed?: boolean
+ /**
+ * Optional repo for autostart (opening a draft PR): `owner/repo` targets that repo, the `NO_REPO` sentinel opts out (report lands without a PR), and omitting it triggers free-form selection across the team's repos — the slow path on a many-repo team, so pass `owner/repo` when you know it.
+ * @nullable
+ */
+ repository?: string | null
+ /** Optional priority (`P0`-`P4`). Required for autostart; pair with `priority_explanation`.
+ *
+ * * `P0` - P0
+ * * `P1` - P1
+ * * `P2` - P2
+ * * `P3` - P3
+ * * `P4` - P4 */
+ priority?: AutonomyPriorityEnumApi | null
+ /**
+ * 2-3 sentence justification for `priority`. Required when `priority` is set.
+ * @nullable
+ */
+ priority_explanation?: string | null
+ /** Optional GitHub logins to consider as reviewers for autostart. Autostart only opens a PR if at least one clears their autonomy threshold; omit to skip the PR path. */
+ suggested_reviewers?: string[]
+}
+
+export interface EmitReportResponseApi {
+ /**
+ * The authored report's id (null only when a preflight gate skipped the call). Returned even when suppressed, so you can edit/dedup against it.
+ * @nullable
+ */
+ report_id: string | null
+ /**
+ * Birth status: `ready` | `pending_input` | `suppressed`, or null when gate-skipped.
+ * @nullable
+ */
+ report_status: string | null
+ /** True when the report actually surfaced in the inbox (READY or PENDING_INPUT). */
+ emitted: boolean
+ /**
+ * `scout_config_missing` | `scout_emit_disabled` | `ai_processing_not_approved` | `source_disabled` | null when not gate-skipped.
+ * @nullable
+ */
+ skipped_reason: string | null
+ /**
+ * When the safety judge suppressed the report, why; null when safe.
+ * @nullable
+ */
+ safety_explanation: string | null
+}
+
/**
* One citation attached to a finding. Mirrors `SignalsScoutEvidenceEntry`.
*/
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 5567901e8d64..73d4d2498403 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -10,8 +10,12 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
CommitDiffResponseApi,
+ EditReportRequestApi,
+ EditReportResponseApi,
EmitFindingRequestApi,
EmitFindingResponseApi,
+ EmitReportRequestApi,
+ EmitReportResponseApi,
ForgetRequestApi,
ForgetResponseApi,
PaginatedPauseStateResponseListApi,
@@ -563,6 +567,28 @@ export const signalsScoutRunsRetrieve = async (
})
}
+export const getSignalsScoutEditReportUrl = (projectId: string, runId: string) => {
+ return `/api/projects/${projectId}/signals/scout/runs/${runId}/edit-report/`
+}
+
+/**
+ * Rewrite a report's title/summary and/or append a note. Can target ANY of the project's inbox reports, not just scout-authored ones — so the edit is attributed to this scout. Title/summary edits are best-effort: the pipeline may later re-research and overwrite them.
+ * @summary Edit an existing report for a run
+ */
+export const signalsScoutEditReport = async (
+ projectId: string,
+ runId: string,
+ editReportRequestApi: EditReportRequestApi,
+ options?: RequestInit
+): Promise<EditReportResponseApi> => {
+ return apiMutator<EditReportResponseApi>(getSignalsScoutEditReportUrl(projectId, runId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(editReportRequestApi),
+ })
+}
+
export const getSignalsScoutRunsEmissionsUrl = (projectId: string, runId: string) => {
return `/api/projects/${projectId}/signals/scout/runs/${runId}/emissions/`
}
@@ -601,6 +627,28 @@ export const signalsScoutRunsEmissionReports = async (
})
}
+export const getSignalsScoutEmitReportUrl = (projectId: string, runId: string) => {
+ return `/api/projects/${projectId}/signals/scout/runs/${runId}/emit-report/`
+}
+
+/**
+ * The second emit channel: author a complete `SignalReport` directly instead of emitting a weak signal. The report passes the safety judge, then surfaces at the status the scout's `actionability` call implies (or is suppressed). Backing `evidence` is written as bound signals so the report behaves like a pipeline report. NOT idempotent — a retry authors a second report; use `reports` to find a prior report and `edit-report` to update it instead.
+ * @summary Author a full report for a run
+ */
+export const signalsScoutEmitReport = async (
+ projectId: string,
+ runId: string,
+ emitReportRequestApi: EmitReportRequestApi,
+ options?: RequestInit
+): Promise<EmitReportResponseApi> => {
+ return apiMutator<EmitReportResponseApi>(getSignalsScoutEmitReportUrl(projectId, runId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(emitReportRequestApi),
+ })
+}
+
export const getSignalsScoutEmitSignalUrl = (projectId: string, runId: string) => {
return `/api/projects/${projectId}/signals/scout/runs/${runId}/emit-signal/`
}
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index b75e2950a928..245e5a6546d5 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -239,6 +239,129 @@ export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod
'Per-(team, skill) scout config: schedule, enablement, and emit posture.\n\nOne row per `signals-scout-\*` skill on the team. The coordinator auto-creates a row\nwhen it discovers a scout skill; this serializer lets agents tune the row.'
)
+/**
+ * Rewrite a report's title/summary and/or append a note. Can target ANY of the project's inbox reports, not just scout-authored ones — so the edit is attributed to this scout. Title/summary edits are best-effort: the pipeline may later re-research and overwrite them.
+ * @summary Edit an existing report for a run
+ */
+export const signalsScoutEditReportBodyTitleMax = 300
+
+export const SignalsScoutEditReportBody = /* @__PURE__ */ zod
+ .object({
+ report_id: zod.string().describe('Id of the report to edit (must belong to this project).'),
+ title: zod
+ .string()
+ .max(signalsScoutEditReportBodyTitleMax)
+ .nullish()
+ .describe(
+ 'Optional new title. Conventional-commit style (`type(scope): description`) renders with type\/scope styling. The pipeline may later re-research and overwrite it.'
+ ),
+ summary: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Optional new summary. Markdown is supported (headings, lists, code, links; images are not rendered); lead with one plain declarative sentence — it becomes the inbox card headline. The pipeline may later re-research and overwrite it.'
+ ),
+ append_note: zod
+ .string()
+ .nullish()
+ .describe("Optional free-form note to append to the report's work log (attributed to this scout)."),
+ })
+ .describe(
+ "Request body for `edit-report`. Can target ANY of the team's inbox reports, not just scout-authored ones."
+ )
+
+/**
+ * The second emit channel: author a complete `SignalReport` directly instead of emitting a weak signal. The report passes the safety judge, then surfaces at the status the scout's `actionability` call implies (or is suppressed). Backing `evidence` is written as bound signals so the report behaves like a pipeline report. NOT idempotent — a retry authors a second report; use `reports` to find a prior report and `edit-report` to update it instead.
+ * @summary Author a full report for a run
+ */
+export const signalsScoutEmitReportBodyTitleMax = 300
+
+export const signalsScoutEmitReportBodyEvidenceItemWeightMin = 0
+
+export const signalsScoutEmitReportBodyAlreadyAddressedDefault = false
+
+export const SignalsScoutEmitReportBody = /* @__PURE__ */ zod
+ .object({
+ title: zod
+ .string()
+ .max(signalsScoutEmitReportBodyTitleMax)
+ .describe(
+ 'One-line report title the inbox shows. Conventional-commit style (`type(scope): description`, e.g. `fix(insights): missing series color`) renders with type\/scope styling.'
+ ),
+ summary: zod
+ .string()
+ .describe(
+ 'The report body the inbox shows. Markdown is supported (headings, lists, code, links; images are not rendered). Lead with one plain declarative sentence — the inbox card uses your first line verbatim as the headline (~140 chars, emphasis stripped), then renders the full markdown in the detail view.'
+ ),
+ evidence: zod
+ .array(
+ zod
+ .object({
+ description: zod
+ .string()
+ .describe(
+ 'Prose for this observation. Embedded and rendered to the safety\/research surfaces.'
+ ),
+ source_id: zod
+ .string()
+ .describe(
+ 'Stable id for this observation within the report (lets a later edit address it).'
+ ),
+ weight: zod
+ .number()
+ .min(signalsScoutEmitReportBodyEvidenceItemWeightMin)
+ .optional()
+ .describe('Optional per-signal weight (defaults to 1.0). Scouts rarely need to set this.'),
+ })
+ .describe('One observation backing an authored report — becomes a bound signal row on the report.')
+ )
+ .min(1)
+ .describe('The observations backing the report — each becomes a bound signal. At least one.'),
+ actionability_explanation: zod
+ .string()
+ .describe('2-3 sentence evidence-grounded justification for the actionability call below.'),
+ actionability: zod
+ .enum(['immediately_actionable', 'requires_human_input', 'not_actionable'])
+ .describe(
+ '\* `immediately_actionable` - immediately_actionable\n\* `requires_human_input` - requires_human_input\n\* `not_actionable` - not_actionable'
+ )
+ .describe(
+ "The scout's actionability call: `immediately_actionable` -> the report surfaces READY; `requires_human_input` -> PENDING_INPUT; `not_actionable` -> suppressed. A safety-judge failure suppresses the report regardless.\n\n\* `immediately_actionable` - immediately_actionable\n\* `requires_human_input` - requires_human_input\n\* `not_actionable` - not_actionable"
+ ),
+ already_addressed: zod
+ .boolean()
+ .default(signalsScoutEmitReportBodyAlreadyAddressedDefault)
+ .describe('Whether the issue already appears fixed in recent changes (tracked separately).'),
+ repository: zod
+ .string()
+ .nullish()
+ .describe(
+ "Optional repo for autostart (opening a draft PR): `owner\/repo` targets that repo, the `NO_REPO` sentinel opts out (report lands without a PR), and omitting it triggers free-form selection across the team's repos — the slow path on a many-repo team, so pass `owner\/repo` when you know it."
+ ),
+ priority: zod
+ .union([
+ zod
+ .enum(['P0', 'P1', 'P2', 'P3', 'P4'])
+ .describe('\* `P0` - P0\n\* `P1` - P1\n\* `P2` - P2\n\* `P3` - P3\n\* `P4` - P4'),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Optional priority (`P0`-`P4`). Required for autostart; pair with `priority_explanation`.\n\n\* `P0` - P0\n\* `P1` - P1\n\* `P2` - P2\n\* `P3` - P3\n\* `P4` - P4'
+ ),
+ priority_explanation: zod
+ .string()
+ .nullish()
+ .describe('2-3 sentence justification for `priority`. Required when `priority` is set.'),
+ suggested_reviewers: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Optional GitHub logins to consider as reviewers for autostart. Autostart only opens a PR if at least one clears their autonomy threshold; omit to skip the PR path.'
+ ),
+ })
+ .describe('Request body for `emit-report`. Run attribution is taken from the URL path.')
+
/**
* Fire `emit_signal` with `source_product = signals_scout`. The `finding_id` is baked into the deterministic `Signal.source_id = run:<id>:finding:<id>` for traceability, but this is NOT idempotent — a second call with the same `finding_id` emits a second signal, so do not retry an emit that may have already succeeded.
* @summary Emit a finding for a run
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index b510a618574a..eb4fd1a04d2d 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -390,6 +390,44 @@ tools:
Tune one scout by its config `id`: change its schedule (`run_interval_minutes`, 30–43200), `enabled`, or
`emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). `skill_name` is fixed.
Enabling records who flipped it on and is activity-logged, since running a scout drives spend.
+ signals-scout-edit-report:
+ operation: signals_scout_edit_report
+ enabled: true
+ scopes:
+ - signal_scout_report:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Edit an existing report for a run
+ description: >
+ The report channel's edit half: rewrite a report's `title`/`summary` and/or append a note. Can target ANY of
+ the project's inbox reports, not just scout-authored ones — the edit is attributed to this scout. Prefer
+ `append_note` over rewriting a report you didn't author (additive and audit-friendly); title/summary edits
+ are best-effort, since the pipeline may later re-research and overwrite them. NOT idempotent — a retried
+ `append_note` appends a second note. Opt-in: only available to scouts that list `edit_report` in their
+ skill's `allowed_tools`.
+ signals-scout-emit-report:
+ operation: signals_scout_emit_report
+ enabled: true
+ scopes:
+ - signal_scout_report:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Author a full report for a run
+ description: >
+ The report channel: author a complete `SignalReport` directly instead of emitting a weak signal, when you've
+ already done the research and want 1:1 control over the report rather than letting the pipeline cluster it.
+ The report passes the safety judge, then surfaces at the status your `actionability` call implies
+ (`immediately_actionable` → READY, `requires_human_input` → PENDING_INPUT, `not_actionable` → suppressed);
+ an unsafe report is suppressed regardless. Backing `evidence` is written as bound signals so the report
+ behaves like a pipeline report. NOT idempotent — a retry authors a second report; use `inbox-reports-list`
+ to find a prior report and `signals-scout-edit-report` to update it instead. For a concrete, fixable issue
+ you can also open a draft PR automatically by passing `repository` + `priority` + `suggested_reviewers`
+ (autostart, custom_agent parity); omit them to just surface the report. Opt-in: only available to scouts
+ that list `emit_report` in their skill's `allowed_tools`.
signals-scout-emit-signal:
operation: signals_scout_emit_signal
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 046dfae82cda..bb2b6ca348bf 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -6303,6 +6303,34 @@
"readOnlyHint": false
}
},
+ "signals-scout-edit-report": {
+ "description": "The report channel's edit half: rewrite a report's `title`/`summary` and/or append a note. Can target ANY of the project's inbox reports, not just scout-authored ones — the edit is attributed to this scout. Prefer `append_note` over rewriting a report you didn't author (additive and audit-friendly); title/summary edits are best-effort, since the pipeline may later re-research and overwrite them. NOT idempotent — a retried `append_note` appends a second note. Opt-in: only available to scouts that list `edit_report` in their skill's `allowed_tools`.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Edit an existing report for a run",
+ "title": "Edit an existing report for a run",
+ "required_scopes": ["signal_scout_report:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "signals-scout-emit-report": {
+ "description": "The report channel: author a complete `SignalReport` directly instead of emitting a weak signal, when you've already done the research and want 1:1 control over the report rather than letting the pipeline cluster it. The report passes the safety judge, then surfaces at the status your `actionability` call implies (`immediately_actionable` → READY, `requires_human_input` → PENDING_INPUT, `not_actionable` → suppressed); an unsafe report is suppressed regardless. Backing `evidence` is written as bound signals so the report behaves like a pipeline report. NOT idempotent — a retry authors a second report; use `inbox-reports-list` to find a prior report and `signals-scout-edit-report` to update it instead. For a concrete, fixable issue you can also open a draft PR automatically by passing `repository` + `priority` + `suggested_reviewers` (autostart, custom_agent parity); omit them to just surface the report. Opt-in: only available to scouts that list `emit_report` in their skill's `allowed_tools`.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Author a full report for a run",
+ "title": "Author a full report for a run",
+ "required_scopes": ["signal_scout_report:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"signals-scout-emit-signal": {
"description": "Fire `emit_signal` with `source_product = signals_scout`. The `finding_id` is baked into the deterministic `Signal.source_id = run:<id>:finding:<id>` for traceability, but this is NOT idempotent — a second call with the same `finding_id` emits a second signal, so emit each finding exactly once and never retry an emit. Findings should carry `tags` — see the `tags` param for the slug and taxonomy convention.",
"category": "Signals",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 2c876e2ff9c4..eb48266aa4cd 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6812,6 +6812,34 @@
"readOnlyHint": false
}
},
+ "signals-scout-edit-report": {
+ "description": "The report channel's edit half: rewrite a report's `title`/`summary` and/or append a note. Can target ANY of the project's inbox reports, not just scout-authored ones — the edit is attributed to this scout. Prefer `append_note` over rewriting a report you didn't author (additive and audit-friendly); title/summary edits are best-effort, since the pipeline may later re-research and overwrite them. NOT idempotent — a retried `append_note` appends a second note. Opt-in: only available to scouts that list `edit_report` in their skill's `allowed_tools`.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Edit an existing report for a run",
+ "title": "Edit an existing report for a run",
+ "required_scopes": ["signal_scout_report:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "signals-scout-emit-report": {
+ "description": "The report channel: author a complete `SignalReport` directly instead of emitting a weak signal, when you've already done the research and want 1:1 control over the report rather than letting the pipeline cluster it. The report passes the safety judge, then surfaces at the status your `actionability` call implies (`immediately_actionable` → READY, `requires_human_input` → PENDING_INPUT, `not_actionable` → suppressed); an unsafe report is suppressed regardless. Backing `evidence` is written as bound signals so the report behaves like a pipeline report. NOT idempotent — a retry authors a second report; use `inbox-reports-list` to find a prior report and `signals-scout-edit-report` to update it instead. For a concrete, fixable issue you can also open a draft PR automatically by passing `repository` + `priority` + `suggested_reviewers` (autostart, custom_agent parity); omit them to just surface the report. Opt-in: only available to scouts that list `emit_report` in their skill's `allowed_tools`.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Author a full report for a run",
+ "title": "Author a full report for a run",
+ "required_scopes": ["signal_scout_report:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"signals-scout-emit-signal": {
"description": "Fire `emit_signal` with `source_product = signals_scout`. The `finding_id` is baked into the deterministic `Signal.source_id = run:<id>:finding:<id>` for traceability, but this is NOT idempotent — a second call with the same `finding_id` emits a second signal, so emit each finding exactly once and never retry an emit. Findings should carry `tags` — see the `tags` param for the slug and taxonomy convention.",
"category": "Signals",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f59d5a91d524..4fff6ff79c0a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -1174,6 +1174,20 @@ export namespace Schemas {
created_by: UserBasic | null;
}
+ /**
+ * * `immediately_actionable` - immediately_actionable
+ * * `requires_human_input` - requires_human_input
+ * * `not_actionable` - not_actionable
+ */
+ export type ActionabilityEnum = typeof ActionabilityEnum[keyof typeof ActionabilityEnum];
+
+
+ export const ActionabilityEnum = {
+ ImmediatelyActionable: 'immediately_actionable',
+ RequiresHumanInput: 'requires_human_input',
+ NotActionable: 'not_actionable',
+ } as const;
+
export type ActionsNodeResponse = { [key: string]: unknown } | null;
export type PropertyOperator = typeof PropertyOperator[keyof typeof PropertyOperator];
@@ -18232,6 +18246,39 @@ export namespace Schemas {
readonly updated_at: string | null;
}
+ /**
+ * Request body for `edit-report`. Can target ANY of the team's inbox reports, not just scout-authored ones.
+ */
+ export interface EditReportRequest {
+ /** Id of the report to edit (must belong to this project). */
+ report_id: string;
+ /**
+ * Optional new title. Conventional-commit style (`type(scope): description`) renders with type/scope styling. The pipeline may later re-research and overwrite it.
+ * @maxLength 300
+ * @nullable
+ */
+ title?: string | null;
+ /**
+ * Optional new summary. Markdown is supported (headings, lists, code, links; images are not rendered); lead with one plain declarative sentence — it becomes the inbox card headline. The pipeline may later re-research and overwrite it.
+ * @nullable
+ */
+ summary?: string | null;
+ /**
+ * Optional free-form note to append to the report's work log (attributed to this scout).
+ * @nullable
+ */
+ append_note?: string | null;
+ }
+
+ export interface EditReportResponse {
+ /** Id of the edited report. */
+ report_id: string;
+ /** Which presentation fields changed (e.g. `title`, `summary`); empty if only a note was appended. */
+ updated_fields: string[];
+ /** Whether a note artefact was appended. */
+ note_appended: boolean;
+ }
+
export type EffectiveMembershipLevelEnum = typeof EffectiveMembershipLevelEnum[keyof typeof EffectiveMembershipLevelEnum];
@@ -18450,6 +18497,94 @@ export namespace Schemas {
skipped_reason: string | null;
}
+ /**
+ * One observation backing an authored report — becomes a bound signal row on the report.
+ */
+ export interface ReportEvidence {
+ /** Prose for this observation. Embedded and rendered to the safety/research surfaces. */
+ description: string;
+ /** Stable id for this observation within the report (lets a later edit address it). */
+ source_id: string;
+ /**
+ * Optional per-signal weight (defaults to 1.0). Scouts rarely need to set this.
+ * @minimum 0
+ */
+ weight?: number;
+ }
+
+ /**
+ * Request body for `emit-report`. Run attribution is taken from the URL path.
+ */
+ export interface EmitReportRequest {
+ /**
+ * One-line report title the inbox shows. Conventional-commit style (`type(scope): description`, e.g. `fix(insights): missing series color`) renders with type/scope styling.
+ * @maxLength 300
+ */
+ title: string;
+ /** The report body the inbox shows. Markdown is supported (headings, lists, code, links; images are not rendered). Lead with one plain declarative sentence — the inbox card uses your first line verbatim as the headline (~140 chars, emphasis stripped), then renders the full markdown in the detail view. */
+ summary: string;
+ /**
+ * The observations backing the report — each becomes a bound signal. At least one.
+ * @minItems 1
+ */
+ evidence: ReportEvidence[];
+ /** 2-3 sentence evidence-grounded justification for the actionability call below. */
+ actionability_explanation: string;
+ /** The scout's actionability call: `immediately_actionable` -> the report surfaces READY; `requires_human_input` -> PENDING_INPUT; `not_actionable` -> suppressed. A safety-judge failure suppresses the report regardless.
+ *
+ * * `immediately_actionable` - immediately_actionable
+ * * `requires_human_input` - requires_human_input
+ * * `not_actionable` - not_actionable */
+ actionability: ActionabilityEnum;
+ /** Whether the issue already appears fixed in recent changes (tracked separately). */
+ already_addressed?: boolean;
+ /**
+ * Optional repo for autostart (opening a draft PR): `owner/repo` targets that repo, the `NO_REPO` sentinel opts out (report lands without a PR), and omitting it triggers free-form selection across the team's repos — the slow path on a many-repo team, so pass `owner/repo` when you know it.
+ * @nullable
+ */
+ repository?: string | null;
+ /** Optional priority (`P0`-`P4`). Required for autostart; pair with `priority_explanation`.
+ *
+ * * `P0` - P0
+ * * `P1` - P1
+ * * `P2` - P2
+ * * `P3` - P3
+ * * `P4` - P4 */
+ priority?: AutonomyPriorityEnum | null;
+ /**
+ * 2-3 sentence justification for `priority`. Required when `priority` is set.
+ * @nullable
+ */
+ priority_explanation?: string | null;
+ /** Optional GitHub logins to consider as reviewers for autostart. Autostart only opens a PR if at least one clears their autonomy threshold; omit to skip the PR path. */
+ suggested_reviewers?: string[];
+ }
+
+ export interface EmitReportResponse {
+ /**
+ * The authored report's id (null only when a preflight gate skipped the call). Returned even when suppressed, so you can edit/dedup against it.
+ * @nullable
+ */
+ report_id: string | null;
+ /**
+ * Birth status: `ready` | `pending_input` | `suppressed`, or null when gate-skipped.
+ * @nullable
+ */
+ report_status: string | null;
+ /** True when the report actually surfaced in the inbox (READY or PENDING_INPUT). */
+ emitted: boolean;
+ /**
+ * `scout_config_missing` | `scout_emit_disabled` | `ai_processing_not_approved` | `source_disabled` | null when not gate-skipped.
+ * @nullable
+ */
+ skipped_reason: string | null;
+ /**
+ * When the safety judge suppressed the report, why; null when safe.
+ * @nullable
+ */
+ safety_explanation: string | null;
+ }
+
export interface EnableWarehouseBackfillRequest {
/** Name for this environment's warehouse tables (events_<name>, persons_<name>, …). Lowercase letters, numbers, and underscores only; used verbatim as the suffix and must be unique across the organization's environments. */
table_name: string;
@@ -33918,10 +34053,10 @@ export namespace Schemas {
* * `medium` - Medium
* * `high` - High
*/
- export type PriorityEnum = typeof PriorityEnum[keyof typeof PriorityEnum];
+ export type TicketPriorityEnum = typeof TicketPriorityEnum[keyof typeof TicketPriorityEnum];
- export const PriorityEnum = {
+ export const TicketPriorityEnum = {
Low: 'low',
Medium: 'medium',
High: 'high',
@@ -33986,7 +34121,7 @@ export namespace Schemas {
* * `low` - Low
* * `medium` - Medium
* * `high` - High */
- priority?: PriorityEnum | BlankEnum | null;
+ priority?: TicketPriorityEnum | BlankEnum | null;
readonly assignee: TicketAssignment;
/** Customer-provided traits such as name and email */
anonymous_traits?: unknown;
@@ -41389,7 +41524,7 @@ export namespace Schemas {
* * `low` - Low
* * `medium` - Medium
* * `high` - High */
- priority?: PriorityEnum | BlankEnum | null;
+ priority?: TicketPriorityEnum | BlankEnum | null;
readonly assignee?: TicketAssignment;
/** Customer-provided traits such as name and email */
anonymous_traits?: unknown;
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index c6a08f65aa59..5fca86db2dee 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 27 enabled ops
+ * PostHog API - MCP 29 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -516,6 +516,46 @@ export const SignalsScoutRunsRetrieveParams = /* @__PURE__ */ zod.object({
run_id: zod.string().describe('UUID of the `SignalScoutRun` bridge row.'),
})
+/**
+ * Rewrite a report's title/summary and/or append a note. Can target ANY of the project's inbox reports, not just scout-authored ones — so the edit is attributed to this scout. Title/summary edits are best-effort: the pipeline may later re-research and overwrite them.
+ * @summary Edit an existing report for a run
+ */
+export const SignalsScoutEditReportParams = /* @__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 signalsScoutEditReportBodyTitleMax = 300
+
+export const SignalsScoutEditReportBody = /* @__PURE__ */ zod
+ .object({
+ report_id: zod.string().describe('Id of the report to edit (must belong to this project).'),
+ title: zod
+ .string()
+ .max(signalsScoutEditReportBodyTitleMax)
+ .nullish()
+ .describe(
+ 'Optional new title. Conventional-commit style (`type(scope): description`) renders with type/scope styling. The pipeline may later re-research and overwrite it.'
+ ),
+ summary: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Optional new summary. Markdown is supported (headings, lists, code, links; images are not rendered); lead with one plain declarative sentence — it becomes the inbox card headline. The pipeline may later re-research and overwrite it.'
+ ),
+ append_note: zod
+ .string()
+ .nullish()
+ .describe("Optional free-form note to append to the report's work log (attributed to this scout)."),
+ })
+ .describe(
+ "Request body for `edit-report`. Can target ANY of the team's inbox reports, not just scout-authored ones."
+ )
+
/**
* Return the findings a `SignalScoutRun` emitted to the inbox, newest first — one row per emit with its `description` (the finding text as surfaced), `weight`, `confidence`, `severity`, and the deterministic `source_id` that joins back to the underlying signal. Lets a team and its agents see *what* a run surfaced without parsing `emitted_finding_ids` or scanning the signal store. Strictly team-scoped — a run UUID belonging to another team returns 404.
* @summary List a run's emitted findings
@@ -542,6 +582,107 @@ export const SignalsScoutRunsEmissionReportsParams = /* @__PURE__ */ zod.object(
run_id: zod.string().describe('UUID of the `SignalScoutRun` bridge row.'),
})
+/**
+ * The second emit channel: author a complete `SignalReport` directly instead of emitting a weak signal. The report passes the safety judge, then surfaces at the status the scout's `actionability` call implies (or is suppressed). Backing `evidence` is written as bound signals so the report behaves like a pipeline report. NOT idempotent — a retry authors a second report; use `reports` to find a prior report and `edit-report` to update it instead.
+ * @summary Author a full report for a run
+ */
+export const SignalsScoutEmitReportParams = /* @__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 signalsScoutEmitReportBodyTitleMax = 300
+
+export const signalsScoutEmitReportBodyEvidenceItemWeightMin = 0
+
+export const signalsScoutEmitReportBodyAlreadyAddressedDefault = false
+
+export const SignalsScoutEmitReportBody = /* @__PURE__ */ zod
+ .object({
+ title: zod
+ .string()
+ .max(signalsScoutEmitReportBodyTitleMax)
+ .describe(
+ 'One-line report title the inbox shows. Conventional-commit style (`type(scope): description`, e.g. `fix(insights): missing series color`) renders with type/scope styling.'
+ ),
+ summary: zod
+ .string()
+ .describe(
+ 'The report body the inbox shows. Markdown is supported (headings, lists, code, links; images are not rendered). Lead with one plain declarative sentence — the inbox card uses your first line verbatim as the headline (~140 chars, emphasis stripped), then renders the full markdown in the detail view.'
+ ),
+ evidence: zod
+ .array(
+ zod
+ .object({
+ description: zod
+ .string()
+ .describe(
+ 'Prose for this observation. Embedded and rendered to the safety/research surfaces.'
+ ),
+ source_id: zod
+ .string()
+ .describe(
+ 'Stable id for this observation within the report (lets a later edit address it).'
+ ),
+ weight: zod
+ .number()
+ .min(signalsScoutEmitReportBodyEvidenceItemWeightMin)
+ .optional()
+ .describe('Optional per-signal weight (defaults to 1.0). Scouts rarely need to set this.'),
+ })
+ .describe('One observation backing an authored report — becomes a bound signal row on the report.')
+ )
+ .min(1)
+ .describe('The observations backing the report — each becomes a bound signal. At least one.'),
+ actionability_explanation: zod
+ .string()
+ .describe('2-3 sentence evidence-grounded justification for the actionability call below.'),
+ actionability: zod
+ .enum(['immediately_actionable', 'requires_human_input', 'not_actionable'])
+ .describe(
+ '* `immediately_actionable` - immediately_actionable\n* `requires_human_input` - requires_human_input\n* `not_actionable` - not_actionable'
+ )
+ .describe(
+ "The scout's actionability call: `immediately_actionable` -> the report surfaces READY; `requires_human_input` -> PENDING_INPUT; `not_actionable` -> suppressed. A safety-judge failure suppresses the report regardless.\n\n* `immediately_actionable` - immediately_actionable\n* `requires_human_input` - requires_human_input\n* `not_actionable` - not_actionable"
+ ),
+ already_addressed: zod
+ .boolean()
+ .default(signalsScoutEmitReportBodyAlreadyAddressedDefault)
+ .describe('Whether the issue already appears fixed in recent changes (tracked separately).'),
+ repository: zod
+ .string()
+ .nullish()
+ .describe(
+ "Optional repo for autostart (opening a draft PR): `owner/repo` targets that repo, the `NO_REPO` sentinel opts out (report lands without a PR), and omitting it triggers free-form selection across the team's repos — the slow path on a many-repo team, so pass `owner/repo` when you know it."
+ ),
+ priority: zod
+ .union([
+ zod
+ .enum(['P0', 'P1', 'P2', 'P3', 'P4'])
+ .describe('* `P0` - P0\n* `P1` - P1\n* `P2` - P2\n* `P3` - P3\n* `P4` - P4'),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Optional priority (`P0`-`P4`). Required for autostart; pair with `priority_explanation`.\n\n* `P0` - P0\n* `P1` - P1\n* `P2` - P2\n* `P3` - P3\n* `P4` - P4'
+ ),
+ priority_explanation: zod
+ .string()
+ .nullish()
+ .describe('2-3 sentence justification for `priority`. Required when `priority` is set.'),
+ suggested_reviewers: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Optional GitHub logins to consider as reviewers for autostart. Autostart only opens a PR if at least one clears their autonomy threshold; omit to skip the PR path.'
+ ),
+ })
+ .describe('Request body for `emit-report`. Run attribution is taken from the URL path.')
+
/**
* Fire `emit_signal` with `source_product = signals_scout`. The `finding_id` is baked into the deterministic `Signal.source_id = run:<id>:finding:<id>` for traceability, but this is NOT idempotent — a second call with the same `finding_id` emits a second signal, so do not retry an emit that may have already succeeded.
* @summary Emit a finding for a run
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index e9833642664a..3c79929a462e 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -19,6 +19,10 @@ import {
SignalsScoutConfigCreateBody,
SignalsScoutConfigUpdateBody,
SignalsScoutConfigUpdateParams,
+ SignalsScoutEditReportBody,
+ SignalsScoutEditReportParams,
+ SignalsScoutEmitReportBody,
+ SignalsScoutEmitReportParams,
SignalsScoutEmitSignalBody,
SignalsScoutEmitSignalParams,
SignalsScoutProjectProfileGetQueryParams,
@@ -554,6 +558,86 @@ const signalsScoutConfigUpdate = (): ToolBase<
},
})
+const SignalsScoutEditReportSchema = SignalsScoutEditReportParams.omit({ project_id: true }).extend(
+ SignalsScoutEditReportBody.shape
+)
+
+const signalsScoutEditReport = (): ToolBase<typeof SignalsScoutEditReportSchema, Schemas.EditReportResponse> => ({
+ name: 'signals-scout-edit-report',
+ schema: SignalsScoutEditReportSchema,
+ handler: async (context: Context, params: z.infer<typeof SignalsScoutEditReportSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.report_id !== undefined) {
+ body['report_id'] = params.report_id
+ }
+ if (params.title !== undefined) {
+ body['title'] = params.title
+ }
+ if (params.summary !== undefined) {
+ body['summary'] = params.summary
+ }
+ if (params.append_note !== undefined) {
+ body['append_note'] = params.append_note
+ }
+ const result = await context.api.request<Schemas.EditReportResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/runs/${encodeURIComponent(String(params.run_id))}/edit-report/`,
+ body,
+ })
+ return result
+ },
+})
+
+const SignalsScoutEmitReportSchema = SignalsScoutEmitReportParams.omit({ project_id: true }).extend(
+ SignalsScoutEmitReportBody.shape
+)
+
+const signalsScoutEmitReport = (): ToolBase<typeof SignalsScoutEmitReportSchema, Schemas.EmitReportResponse> => ({
+ name: 'signals-scout-emit-report',
+ schema: SignalsScoutEmitReportSchema,
+ handler: async (context: Context, params: z.infer<typeof SignalsScoutEmitReportSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.title !== undefined) {
+ body['title'] = params.title
+ }
+ if (params.summary !== undefined) {
+ body['summary'] = params.summary
+ }
+ if (params.evidence !== undefined) {
+ body['evidence'] = params.evidence
+ }
+ if (params.actionability_explanation !== undefined) {
+ body['actionability_explanation'] = params.actionability_explanation
+ }
+ if (params.actionability !== undefined) {
+ body['actionability'] = params.actionability
+ }
+ if (params.already_addressed !== undefined) {
+ body['already_addressed'] = params.already_addressed
+ }
+ if (params.repository !== undefined) {
+ body['repository'] = params.repository
+ }
+ if (params.priority !== undefined) {
+ body['priority'] = params.priority
+ }
+ if (params.priority_explanation !== undefined) {
+ body['priority_explanation'] = params.priority_explanation
+ }
+ if (params.suggested_reviewers !== undefined) {
+ body['suggested_reviewers'] = params.suggested_reviewers
+ }
+ const result = await context.api.request<Schemas.EmitReportResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/runs/${encodeURIComponent(String(params.run_id))}/emit-report/`,
+ body,
+ })
+ return result
+ },
+})
+
const SignalsScoutEmitSignalSchema = SignalsScoutEmitSignalParams.omit({ project_id: true }).extend(
SignalsScoutEmitSignalBody.shape
)
@@ -799,6 +883,8 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'signals-scout-config-list': signalsScoutConfigList,
'signals-scout-config-sync': signalsScoutConfigSync,
'signals-scout-config-update': signalsScoutConfigUpdate,
+ 'signals-scout-edit-report': signalsScoutEditReport,
+ 'signals-scout-emit-report': signalsScoutEmitReport,
'signals-scout-emit-signal': signalsScoutEmitSignal,
'signals-scout-project-profile-get': signalsScoutProjectProfileGet,
'signals-scout-runs-emission-reports': signalsScoutRunsEmissionReports,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-edit-report.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-edit-report.json
new file mode 100644
index 000000000000..00e4d50abe31
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-edit-report.json
@@ -0,0 +1,49 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "append_note": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional free-form note to append to the report's work log (attributed to this scout)."
+ },
+ "report_id": {
+ "description": "Id of the report to edit (must belong to this project).",
+ "type": "string"
+ },
+ "run_id": {
+ "description": "UUID of the `SignalScoutRun` bridge row.",
+ "type": "string"
+ },
+ "summary": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional new summary. Markdown is supported (headings, lists, code, links; images are not rendered); lead with one plain declarative sentence — it becomes the inbox card headline. The pipeline may later re-research and overwrite it."
+ },
+ "title": {
+ "anyOf": [
+ {
+ "maxLength": 300,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional new title. Conventional-commit style (`type(scope): description`) renders with type/scope styling. The pipeline may later re-research and overwrite it."
+ }
+ },
+ "required": ["run_id", "report_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-emit-report.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-emit-report.json
new file mode 100644
index 000000000000..c05520715d18
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-emit-report.json
@@ -0,0 +1,101 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "actionability": {
+ "description": "The scout's actionability call: `immediately_actionable` -> the report surfaces READY; `requires_human_input` -> PENDING_INPUT; `not_actionable` -> suppressed. A safety-judge failure suppresses the report regardless.\n\n* `immediately_actionable` - immediately_actionable\n* `requires_human_input` - requires_human_input\n* `not_actionable` - not_actionable",
+ "enum": ["immediately_actionable", "requires_human_input", "not_actionable"],
+ "type": "string"
+ },
+ "actionability_explanation": {
+ "description": "2-3 sentence evidence-grounded justification for the actionability call below.",
+ "type": "string"
+ },
+ "already_addressed": {
+ "default": false,
+ "description": "Whether the issue already appears fixed in recent changes (tracked separately).",
+ "type": "boolean"
+ },
+ "evidence": {
+ "description": "The observations backing the report — each becomes a bound signal. At least one.",
+ "items": {
+ "description": "One observation backing an authored report — becomes a bound signal row on the report.",
+ "properties": {
+ "description": {
+ "description": "Prose for this observation. Embedded and rendered to the safety/research surfaces.",
+ "type": "string"
+ },
+ "source_id": {
+ "description": "Stable id for this observation within the report (lets a later edit address it).",
+ "type": "string"
+ },
+ "weight": {
+ "description": "Optional per-signal weight (defaults to 1.0). Scouts rarely need to set this.",
+ "minimum": 0,
+ "type": "number"
+ }
+ },
+ "required": ["description", "source_id"],
+ "type": "object"
+ },
+ "minItems": 1,
+ "type": "array"
+ },
+ "priority": {
+ "anyOf": [
+ {
+ "description": "* `P0` - P0\n* `P1` - P1\n* `P2` - P2\n* `P3` - P3\n* `P4` - P4",
+ "enum": ["P0", "P1", "P2", "P3", "P4"],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional priority (`P0`-`P4`). Required for autostart; pair with `priority_explanation`.\n\n* `P0` - P0\n* `P1` - P1\n* `P2` - P2\n* `P3` - P3\n* `P4` - P4"
+ },
+ "priority_explanation": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "2-3 sentence justification for `priority`. Required when `priority` is set."
+ },
+ "repository": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional repo for autostart (opening a draft PR): `owner/repo` targets that repo, the `NO_REPO` sentinel opts out (report lands without a PR), and omitting it triggers free-form selection across the team's repos — the slow path on a many-repo team, so pass `owner/repo` when you know it."
+ },
+ "run_id": {
+ "description": "UUID of the `SignalScoutRun` bridge row.",
+ "type": "string"
+ },
+ "suggested_reviewers": {
+ "description": "Optional GitHub logins to consider as reviewers for autostart. Autostart only opens a PR if at least one clears their autonomy threshold; omit to skip the PR path.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "summary": {
+ "description": "The report body the inbox shows. Markdown is supported (headings, lists, code, links; images are not rendered). Lead with one plain declarative sentence — the inbox card uses your first line verbatim as the headline (~140 chars, emphasis stripped), then renders the full markdown in the detail view.",
+ "type": "string"
+ },
+ "title": {
+ "description": "One-line report title the inbox shows. Conventional-commit style (`type(scope): description`, e.g. `fix(insights): missing series color`) renders with type/scope styling.",
+ "maxLength": 300,
+ "type": "string"
+ }
+ },
+ "required": ["run_id", "title", "summary", "evidence", "actionability_explanation", "actionability"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 2ef422598219..65b820b2914e 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -368,7 +368,12 @@ describe('OAUTH_SCOPES_SUPPORTED completeness', () => {
// Minted directly into a server-issued token, never advertised via OAuth metadata
// (mirrors INTERNAL_API_SCOPE_OBJECTS in posthog/scopes.py). Tools may require them, but
// they are intentionally absent from OAUTH_SCOPES_SUPPORTED, so exclude them here.
- const SERVER_MINT_ONLY_SCOPES = new Set(['signal_scout_internal:read', 'signal_scout_internal:write'])
+ const SERVER_MINT_ONLY_SCOPES = new Set([
+ 'signal_scout_internal:read',
+ 'signal_scout_internal:write',
+ 'signal_scout_report:read',
+ 'signal_scout_report:write',
+ ])
it('should include every scope referenced in tool definitions', () => {
const supportedScopes = new Set<string>(OAUTH_SCOPES_SUPPORTED)