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.

fix(signals): write scout report links at emit, before autostart (#108212)

posthog[bot]537966e857ce
diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.py
index 350ddc603d2b..4e9a912d1195 100644
--- a/products/signals/backend/auto_start.py
+++ b/products/signals/backend/auto_start.py
@@ -548,6 +548,22 @@ def _capture_autostart_skipped(
logger.exception("Failed to capture signals_autostart_skipped", report_id=report_id)
+def _duplicate_claims(*, team_id: int, report_id: str, duplicate_ids: list[str]) -> list[str]:
+ """Every report this one duplicates, directly or through a chain, the oldest claim's chain first.
+
+ `duplicate_chain` follows only the oldest `duplicate_of` link, so the cluster keeps a stable name.
+ The gate asks whether the work is already in flight, and the work can sit behind any claim, so
+ each later claim's chain is walked too. The node budget bounds a report that holds many claims.
+ """
+ claims = duplicate_chain(team_id=team_id, report_id=report_id)
+ for target_id in duplicate_ids:
+ if len(claims) >= SignalReportArtefact.MAX_REPORT_LINK_GRAPH_NODES:
+ break
+ if target_id not in claims:
+ claims += [target_id, *duplicate_chain(team_id=team_id, report_id=target_id)]
+ return list(dict.fromkeys(claims))
+
+
def _duplicate_already_worked_on(*, team_id: int, chain: list[str]) -> str | None:
"""The nearest report in the duplicate chain that already holds this work, or None.
@@ -585,9 +601,11 @@ def _evaluate_link_gates(team_id: int, report_id: str) -> AutostartSkip | None:
"""
links = outgoing_links(team_id=team_id, report_id=report_id)
- if any(edge.kind == ReportLinkKind.DUPLICATE_OF for edge in links):
+ duplicate_ids = [edge.target_id for edge in links if edge.kind == ReportLinkKind.DUPLICATE_OF]
+ if duplicate_ids:
deciding_id = _duplicate_already_worked_on(
- team_id=team_id, chain=duplicate_chain(team_id=team_id, report_id=report_id)
+ team_id=team_id,
+ chain=_duplicate_claims(team_id=team_id, report_id=report_id, duplicate_ids=duplicate_ids),
)
if deciding_id is not None:
return AutostartSkip(
diff --git a/products/signals/backend/enums.py b/products/signals/backend/enums.py
index 5d2f6230d115..4de10374ca34 100644
--- a/products/signals/backend/enums.py
+++ b/products/signals/backend/enums.py
@@ -30,6 +30,14 @@ class ReportLinkKind(StrEnum):
RECURRENCE_OF = "recurrence_of"
+class ReportLinkWritePath(StrEnum):
+ # Which surface wrote a `report_link`. `EMIT` writes it with the report, before auto-start reads
+ # the link gates. `EDIT` writes it on a report that exists, possibly after auto-start ran.
+ EMIT = "emit"
+ EDIT = "edit"
+ PIPELINE = "pipeline"
+
+
REPORT_LINK_KIND_LABELS: dict[ReportLinkKind, str] = {
ReportLinkKind.DEPENDS_ON: "Depends on",
ReportLinkKind.PART_OF: "Part of",
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index a27f533fb111..63413a221f58 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -42,6 +42,7 @@ from products.signals.backend.artefact_schemas import (
)
from products.signals.backend.enums import (
ReportLinkKind,
+ ReportLinkWritePath,
SignalSourceProduct,
SignalSourceType,
signal_source_product_choices,
@@ -1698,6 +1699,7 @@ class SignalReportArtefact(UUIDModel):
content: LogArtefactContent,
attribution: ArtefactAttribution,
claim_id: str | None = None,
+ write_path: ReportLinkWritePath | None = None,
) -> "SignalReportArtefact":
"""Append a log artefact (see `LOG_ARTEFACT_TYPES`) to a report and return it.
@@ -1710,6 +1712,7 @@ class SignalReportArtefact(UUIDModel):
`report_link` is the typed, directed counterpart and gets no mirror row, because the
direction is what it records. Its invariants are checked here, on the common write path,
so every surface (the REST API, the MCP tools, a scout edit, the pipeline) gets them.
+ `write_path` names that surface on the `signals_report_linked` event.
"""
if artefact_type_for(content) not in cls.LOG_ARTEFACT_TYPES:
raise ValueError(f"{type(content).__name__} is not a log artefact content model")
@@ -1722,7 +1725,7 @@ class SignalReportArtefact(UUIDModel):
attribution=attribution,
claim_id=claim_id,
)
- cls._capture_report_linked(artefact, content)
+ cls._capture_report_linked(artefact, content, write_path)
cls._schedule_plan_rollup(artefact, content)
return artefact
artefact = cls._create(
@@ -1740,7 +1743,9 @@ class SignalReportArtefact(UUIDModel):
return artefact
@staticmethod
- def _capture_report_linked(artefact: "SignalReportArtefact", content: ReportLink) -> None:
+ def _capture_report_linked(
+ artefact: "SignalReportArtefact", content: ReportLink, write_path: ReportLinkWritePath | None
+ ) -> None:
"""Count the link after it commits, from the one write path every producer shares.
Scheduled on commit so a rolled-back write is never counted, and imported lazily to avoid a
@@ -1760,6 +1765,7 @@ class SignalReportArtefact(UUIDModel):
),
actor_kind=artefact.actor_kind,
actor_agent=artefact.actor_agent,
+ write_path=write_path,
)
transaction.on_commit(_run)
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index baf921dece83..48c282608d66 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -1471,6 +1471,27 @@ class SuggestedReviewerSerializer(serializers.Serializer):
return attrs
+class ReportLinkWriteSerializer(serializers.Serializer):
+ """One typed, directed link to write on the report being emitted or edited."""
+
+ kind = serializers.ChoiceField(
+ choices=report_link_kind_choices(),
+ help_text=(
+ "How this report relates to `report_id`. `depends_on` for work that cannot land "
+ "until the other report's fix does, `part_of` for one piece of a larger report, "
+ "`follow_up_of` for work the other report left behind, `duplicate_of` for the same "
+ "problem filed twice, and `recurrence_of` for a problem a resolved report already covered."
+ ),
+ )
+ report_id = serializers.CharField(help_text="Id of the report to link to. Must be another report in this project.")
+ reason = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ max_length=MAX_REPORT_LINK_REASON_LENGTH,
+ help_text="Optional one-line note on why the reports are linked this way.",
+ )
+
+
class EmitReportRequestSerializer(serializers.Serializer):
"""Request body for `emit-report`. Run attribution is taken from the URL path."""
@@ -1587,6 +1608,19 @@ class EmitReportRequestSerializer(serializers.Serializer):
"research left open, phrased as the reader would send them."
),
)
+ links = serializers.ListField(
+ required=False,
+ child=ReportLinkWriteSerializer(),
+ max_length=MAX_REPORT_LINKS_PER_WRITE,
+ help_text=(
+ "Typed, directed links from the new report to reports that already exist. Send them here, "
+ "not in a later `edit-report` call, because autostart reads them when the report is created: "
+ "a `duplicate_of` link to a report that already has a pull request, or a `depends_on` link to "
+ "a report with no pull request yet, stops a second draft PR. Only the new report gets a row, "
+ "so link from the side the sentence starts at. Links of the same kind must stay acyclic and "
+ "every report must be in this project."
+ ),
+ )
idempotency_key = serializers.CharField(
required=False,
allow_null=True,
@@ -1638,27 +1672,6 @@ class EmitReportResponseSerializer(serializers.Serializer):
)
-class ReportLinkWriteSerializer(serializers.Serializer):
- """One typed, directed link to write on the report being edited."""
-
- kind = serializers.ChoiceField(
- choices=report_link_kind_choices(),
- help_text=(
- "How the edited report relates to `report_id`. `depends_on` for work that cannot land "
- "until the other report's fix does, `part_of` for one piece of a larger report, "
- "`follow_up_of` for work the other report left behind, `duplicate_of` for the same "
- "problem filed twice, and `recurrence_of` for a problem a resolved report already covered."
- ),
- )
- report_id = serializers.CharField(help_text="Id of the report to link to. Must be another report in this project.")
- reason = serializers.CharField(
- required=False,
- allow_blank=True,
- max_length=MAX_REPORT_LINK_REASON_LENGTH,
- help_text="Optional one-line note on why the reports are linked this way.",
- )
-
-
class EditReportRequestSerializer(serializers.Serializer):
"""Request body for `edit-report`. Can target ANY of the team's inbox reports, not just scout-authored ones."""
diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.py
index c6c4c22948f9..3eb4b1b7bc3b 100644
--- a/products/signals/backend/scout_harness/tools/report.py
+++ b/products/signals/backend/scout_harness/tools/report.py
@@ -110,6 +110,7 @@ from products.signals.backend.scout_report import (
get_scout_report_signal_count,
get_scout_report_status,
get_scout_report_title,
+ missing_link_targets,
prepare_scout_supersession,
record_content_revision,
record_implementation_decision,
@@ -199,7 +200,7 @@ class ReportMetricInput:
@dataclass(frozen=True)
class ReportLinkInput:
- """One typed, directed link the edit should write on the report: "this report `kind` that report"."""
+ """One typed, directed link to write on the report: "this report `kind` that report"."""
kind: str
report_id: str
@@ -426,14 +427,16 @@ def _build_edit_charts(charts: list[ReportChartInput] | None) -> list[ReportChar
def _build_links(links: list[ReportLinkInput] | None) -> list[ReportLink]:
"""Turn the caller's links into content models, rejecting an unknown kind or a malformed id.
- Pure and cheap, so a scout that named a kind wrong fails before the edit spends a judge call.
+ Pure and cheap, so a scout that named a kind wrong fails before the emit or edit spends a judge call.
The invariants that need the database (a live target in this team, no cycle) are checked at the
write, in `SignalReportArtefact.add_log`.
"""
if not links:
return []
if len(links) > MAX_REPORT_LINKS_PER_WRITE:
- raise InvalidScoutReportError(f"edit_report accepts at most {MAX_REPORT_LINKS_PER_WRITE} links ({len(links)})")
+ raise InvalidScoutReportError(
+ f"a report write accepts at most {MAX_REPORT_LINKS_PER_WRITE} links ({len(links)})"
+ )
built: list[ReportLink] = []
for link in links:
try:
@@ -777,13 +780,23 @@ def _reviewer_reasons(reviewers: SuggestedReviewers | None) -> list[str]:
def _link_reasons(links: Sequence[ReportLink]) -> list[str]:
- """The scout-authored `reason` strings from the links an edit writes, for the safety judge.
+ """The scout-authored `reason` strings from the links an emit or edit writes, for the safety judge.
A reason persists in the report-link artefact and renders in the work log that action-capable
report agents read, so it goes in front of the judge like a reviewer reason does."""
return [link.reason for link in links if link.reason]
+def _assert_emit_link_targets_live(team: Team, links: Sequence[ReportLink]) -> None:
+ """Reject an emit whose links name a dead or foreign report, before the judge and repo selection.
+
+ A scout can easily name a well-formed id that no longer resolves, and the write would reject it
+ only after both were paid for. Does a DB read, so callers on the async path must bridge it."""
+ missing = missing_link_targets(team_id=team.id, links=links)
+ if missing:
+ raise InvalidScoutReportError(f"Report {missing[0]} was not found in this project.")
+
+
def _wants_repo_selection(
repository: str | None, priority: PriorityAssessment | None, reviewers: SuggestedReviewers | None
) -> bool:
@@ -1234,6 +1247,7 @@ def _capture_report_emitted(
chart_count: int = 0,
metric_count: int = 0,
suggested_prompt_count: int = 0,
+ links: Sequence[ReportLink] = (),
) -> _ReportForward | 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.
@@ -1274,6 +1288,8 @@ def _capture_report_emitted(
"chart_count": chart_count,
"metric_count": metric_count,
"suggested_prompt_count": suggested_prompt_count,
+ "link_count": len(links),
+ "link_kinds": sorted({link.kind.value for link in links}),
"title": title,
"summary": _forwarded_summary(summary),
"actionability": actionability,
@@ -1473,6 +1489,7 @@ async def emit_report(
charts: list[ReportChartInput] | None = None,
metrics: list[ReportMetricInput] | None = None,
suggested_prompts: list[str] | None = None,
+ links: list[ReportLinkInput] | None = None,
idempotency_key: str | None = None,
) -> EmitReportResult:
"""Author a full report: judge for safety, then persist at the judged status. Async entry (used by
@@ -1485,6 +1502,9 @@ async def emit_report(
`charts` are the optional queries the inbox renders on the report, and `suggested_prompts` the
optional prompts (questions or next-step actions) it offers above the report's "Ask AI" box.
+ `links` are typed links from the new report to others. They are written with the report, so the
+ link gates see a `duplicate_of` or `depends_on` link before autostart decides.
+
`idempotency_key` names this emission, so a retry after a timeout returns the first report instead
of a twin (see `_emit_idempotency_key`). One is derived from the content when the caller supplies
none, so a resent call is safe either way."""
@@ -1495,6 +1515,7 @@ async def emit_report(
allowed_metrics = await database_sync_to_async(_allowed_metrics, thread_sensitive=False)(team, metrics)
metric_contents = _build_metrics(allowed_metrics)
prompt_contents = _build_suggested_prompts(suggested_prompts)
+ built_links = _build_links(links)
# 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)
@@ -1521,6 +1542,7 @@ async def emit_report(
chart_count=len(chart_contents),
metric_count=len(metric_contents),
suggested_prompt_count=len(prompt_contents),
+ links=built_links,
)
await _forward_report_event_async(team, forward)
return result
@@ -1543,6 +1565,8 @@ async def emit_report(
if preflight is not None:
return await finish(_gate_skip_result(preflight))
+ await database_sync_to_async(_assert_emit_link_targets_live, thread_sensitive=False)(team, built_links)
+
task_id = await database_sync_to_async(_resolve_task_id, thread_sensitive=False)(run)
attribution = _attribution_for(task_id)
judgement = await judge_scout_report(
@@ -1555,6 +1579,7 @@ async def emit_report(
metrics=metric_contents,
suggested_prompts=prompt_contents,
reviewer_reasons=_reviewer_reasons(reviewers),
+ link_reasons=_link_reasons(built_links),
)
surfaced = _surfaced(judgement.status)
repo_selection = (
@@ -1594,6 +1619,8 @@ async def emit_report(
# is still reachable from the Dismissed view, where a click would hand the judge-rejected
# wording to an action-capable agent run.
suggested_prompts=prompt_contents if judgement.safety.choice else (),
+ # Same reason as the prompts: an unsafe report must not steer another report's autostart.
+ links=built_links if judgement.safety.choice else (),
# 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,
@@ -1634,6 +1661,7 @@ def emit_report_sync(
charts: list[ReportChartInput] | None = None,
metrics: list[ReportMetricInput] | None = None,
suggested_prompts: list[str] | None = None,
+ links: list[ReportLinkInput] | None = None,
idempotency_key: str | None = None,
) -> EmitReportResult:
"""Sync entry used by the DRF view path. Mirrors `emit_report` but keeps the sync DB work on the
@@ -1646,6 +1674,7 @@ def emit_report_sync(
chart_contents = _build_charts(charts)
metric_contents = _build_metrics(_allowed_metrics(team, metrics))
prompt_contents = _build_suggested_prompts(suggested_prompts)
+ built_links = _build_links(links)
# 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)
@@ -1672,6 +1701,7 @@ def emit_report_sync(
chart_count=len(chart_contents),
metric_count=len(metric_contents),
suggested_prompt_count=len(prompt_contents),
+ links=built_links,
)
if forward is not None:
_forward_report_event_to_team(team=team, forward=forward)
@@ -1687,6 +1717,8 @@ def emit_report_sync(
if preflight is not None:
return finish(_gate_skip_result(preflight))
+ _assert_emit_link_targets_live(team, built_links)
+
task_id = _resolve_task_id(run)
attribution = _attribution_for(task_id)
judgement = async_to_sync(judge_scout_report)(
@@ -1699,6 +1731,7 @@ def emit_report_sync(
metrics=metric_contents,
suggested_prompts=prompt_contents,
reviewer_reasons=_reviewer_reasons(reviewers),
+ link_reasons=_link_reasons(built_links),
)
surfaced = _surfaced(judgement.status)
repo_selection = (
@@ -1736,6 +1769,8 @@ def emit_report_sync(
# is still reachable from the Dismissed view, where a click would hand the judge-rejected
# wording to an action-capable agent run.
suggested_prompts=prompt_contents if judgement.safety.choice else (),
+ # Same reason as the prompts: an unsafe report must not steer another report's autostart.
+ links=built_links if judgement.safety.choice else (),
# 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,
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 91f1e3b242a3..4cd343222a30 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -1253,6 +1253,7 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
charts=_to_report_charts(data.get("charts")),
metrics=_to_report_metrics(data.get("metrics")),
suggested_prompts=data.get("suggested_prompts"),
+ links=_to_report_links(data.get("links")),
idempotency_key=data.get("idempotency_key"),
)
except InvalidScoutReportError as exc:
diff --git a/products/signals/backend/scout_report/__init__.py b/products/signals/backend/scout_report/__init__.py
index 53eb280db029..83d0c3efaaae 100644
--- a/products/signals/backend/scout_report/__init__.py
+++ b/products/signals/backend/scout_report/__init__.py
@@ -28,6 +28,7 @@ from products.signals.backend.scout_report.persistence import (
get_scout_report_signal_count,
get_scout_report_status,
get_scout_report_title,
+ missing_link_targets,
prepare_scout_supersession,
record_content_revision,
record_implementation_decision,
@@ -66,6 +67,7 @@ __all__ = [
"get_content_revision_count",
"get_scout_report_status",
"get_scout_report_title",
+ "missing_link_targets",
"prepare_scout_supersession",
"record_content_revision",
"record_implementation_decision",
diff --git a/products/signals/backend/scout_report/judge.py b/products/signals/backend/scout_report/judge.py
index b56180c34ddd..886090f646b4 100644
--- a/products/signals/backend/scout_report/judge.py
+++ b/products/signals/backend/scout_report/judge.py
@@ -223,11 +223,12 @@ async def judge_scout_report(
metrics: Sequence[ReportMetric] = (),
suggested_prompts: Sequence[str] = (),
reviewer_reasons: Sequence[str] = (),
+ link_reasons: Sequence[str] = (),
) -> ScoutReportJudgement:
"""Run the safety judge on the authored report and resolve the birth status.
The judge sees the authored `title`/`summary`, the backing observations, any attached charts,
- any suggested prompts, *and* any reviewer reasons — so prompt-injection anywhere the agent
+ any suggested prompts, any reviewer reasons, *and* any link reasons — so prompt-injection anywhere the agent
authored (not just the evidence) is caught before the report can surface or feed autostart. The
safety judge is a plain LLM call (`judge_report_safety`) — no Temporal workflow, no sandbox — so
this runs inline on whatever worker is authoring the report.
@@ -236,12 +237,14 @@ async def judge_scout_report(
metric_signal = _metric_signal(metrics)
prompts_signal = _suggested_prompts_signal(suggested_prompts)
reasons_signal = _reviewer_reasons_signal(reviewer_reasons)
+ link_signal = _link_reasons_signal(link_reasons)
safety_input = [
_report_content_signal(title, summary),
*([chart_signal] if chart_signal is not None else []),
*([metric_signal] if metric_signal is not None else []),
*([prompts_signal] if prompts_signal is not None else []),
*([reasons_signal] if reasons_signal is not None else []),
+ *([link_signal] if link_signal is not None else []),
*_to_signal_data(signals),
]
safety_response = await judge_report_safety(team_id=team_id, signals=safety_input)
diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.py
index c635deb0e099..ddb23bf967d6 100644
--- a/products/signals/backend/scout_report/persistence.py
+++ b/products/signals/backend/scout_report/persistence.py
@@ -60,6 +60,7 @@ from products.signals.backend.artefact_schemas import (
TaskRunArtefact,
TitleChange,
)
+from products.signals.backend.enums import ReportLinkWritePath
from products.signals.backend.models import (
MAX_SCOUT_CONTENT_REVISIONS,
MAX_SCOUT_REPORT_NOTES,
@@ -169,6 +170,7 @@ def create_scout_report(
charts: Sequence[ReportChart] = (),
metrics: Sequence[ReportMetric] = (),
suggested_prompts: Sequence[str] = (),
+ links: Sequence[ReportLink] = (),
emit_signals: bool = True,
run: SignalScoutRun | None = None,
idempotency_key: str | None = None,
@@ -202,6 +204,11 @@ def create_scout_report(
inbox offers above the report's "Ask AI" box. Written on the same terms as `charts`, and for
the same reason.
+ `links`, when supplied, become the report's typed `report_link` rows. They are written in the
+ same transaction as the report, so the link gates in `auto_start` see them when the caller
+ fires autostart. A link that `add_log` rejects rolls back the whole report and raises
+ `InvalidScoutReportError`.
+
`idempotency_key`, when supplied, is stored on the report under a per-team unique index, so one
key can only ever author one report. A call whose key a report already holds raises
`ScoutReportAlreadyEmittedError` carrying that report, and writes nothing — the emit path turns
@@ -296,6 +303,17 @@ def create_scout_report(
SignalReportArtefact.append_status(
team_id=team_id, report_id=report_id, content=priority, attribution=attribution
)
+ for link in links:
+ try:
+ SignalReportArtefact.add_log(
+ team_id=team_id,
+ report_id=report_id,
+ content=link,
+ attribution=attribution,
+ write_path=ReportLinkWritePath.EMIT,
+ )
+ except ArtefactContentValidationError as err:
+ raise InvalidScoutReportError(str(err))
if suggested_reviewers is not None and len(suggested_reviewers.root) > 0:
SignalReportArtefact.append_status(
team_id=team_id,
@@ -393,6 +411,24 @@ def scout_report_exists(*, team_id: int, report_id: str) -> bool:
return SignalReport.objects.filter(team_id=team_id, id=report_id).exists()
+def missing_link_targets(*, team_id: int, links: Sequence[ReportLink]) -> list[str]:
+ """The link targets that name no live report in this team, in the order the caller gave them.
+
+ For the emit path's pre-judge gate: a new report has no incoming links, so a dead or foreign target
+ is the only link check the write can fail. A cost gate only — `add_log` re-checks every link under
+ the team's link lock."""
+ target_ids = list(dict.fromkeys(link.report_id for link in links))
+ if not target_ids:
+ return []
+ live = {
+ str(report_id)
+ for report_id in SignalReport.objects.filter(team_id=team_id, id__in=target_ids)
+ .exclude(status=SignalReport.Status.DELETED)
+ .values_list("id", flat=True)
+ }
+ return [target_id for target_id in target_ids if target_id not in live]
+
+
def get_scout_report_signal_count(*, team_id: int, report_id: str) -> int | None:
"""Team-scoped signal-count lookup, for the edit path's pre-judge evidence cap. Returns None when
the report doesn't exist for the team. A cost gate only — `append_report_evidence` re-checks the
@@ -619,6 +655,7 @@ def append_report_links(
report_id=report_id,
content=link,
attribution=attribution,
+ write_path=ReportLinkWritePath.EDIT,
)
except ArtefactContentValidationError as err:
raise InvalidScoutReportError(str(err))
diff --git a/products/signals/backend/stack_plan.py b/products/signals/backend/stack_plan.py
index 98c55ad8b802..7f12afaca6de 100644
--- a/products/signals/backend/stack_plan.py
+++ b/products/signals/backend/stack_plan.py
@@ -30,7 +30,7 @@ from products.signals.backend.artefact_schemas import (
TaskRunArtefact,
)
from products.signals.backend.billing import system_billing_exempt_reason
-from products.signals.backend.enums import ReportLinkKind
+from products.signals.backend.enums import ReportLinkKind, ReportLinkWritePath
from products.signals.backend.implementation_pr import fetch_implementation_prs_for_reports
from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportPullRequest
from products.signals.backend.report_generation.research import ReportLayer
@@ -141,6 +141,7 @@ def create_layer_reports(
reason=f"Layer {index + 1} of {len(layers)} of the research plan.",
),
attribution=attribution,
+ write_path=ReportLinkWritePath.PIPELINE,
)
if layer.depends_on is not None:
SignalReportArtefact.add_log(
@@ -152,6 +153,7 @@ def create_layer_reports(
reason=f"Layer {index + 1} stacks on layer {layer.depends_on + 1}.",
),
attribution=attribution,
+ write_path=ReportLinkWritePath.PIPELINE,
)
child_ids.append(child_id)
logger.info("signals.stack_plan.layers_created", report_id=str(parent.id), team_id=team_id, layers=len(child_ids))
diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.py
index 20bb7a243e83..9a5c9fac4823 100644
--- a/products/signals/backend/temporal/grouping.py
+++ b/products/signals/backend/temporal/grouping.py
@@ -34,7 +34,7 @@ from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.artefact_schemas import MAX_REPORT_LINK_REASON_LENGTH, ReportLink
from products.signals.backend.billing import BILLING_EXEMPT_SOURCE_PRODUCTS
from products.signals.backend.daily_limit import capture_signal_report_daily_limit_paused, daily_report_limit_gate
-from products.signals.backend.enums import ReportLinkKind, SignalSourceProduct
+from products.signals.backend.enums import ReportLinkKind, ReportLinkWritePath, SignalSourceProduct
from products.signals.backend.models import SignalReport, SignalReportArtefact
from products.signals.backend.quota import capture_signal_report_quota_paused, self_driving_quota_gate
from products.signals.backend.receivers import _is_safety_suppressed
@@ -730,6 +730,7 @@ def _link_check_follow_up(*, team_id: int, report_id: str, source_product: str,
report_id=report_id,
content=ReportLink(kind=ReportLinkKind.FOLLOW_UP_OF, report_id=str(origin_id), reason=reason),
attribution=ArtefactAttribution.system(),
+ write_path=ReportLinkWritePath.PIPELINE,
)
except Exception:
logger.exception(
@@ -827,6 +828,7 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As
report_id=str(report.id),
content=ReportLink(kind=ReportLinkKind.RECURRENCE_OF, report_id=str(parent_report.id)),
attribution=ArtefactAttribution.system(),
+ write_path=ReportLinkWritePath.PIPELINE,
)
else:
report.total_weight += input.weight
diff --git a/products/signals/backend/test/test_auto_start.py b/products/signals/backend/test/test_auto_start.py
index 64650211a64c..a46e4d90e3f8 100644
--- a/products/signals/backend/test/test_auto_start.py
+++ b/products/signals/backend/test/test_auto_start.py
@@ -925,6 +925,7 @@ def _link(team_id: int, source: SignalReport, target: SignalReport, kind: Report
("duplicate_of_resolved", "duplicate_of"),
("duplicate_of_with_pr", "duplicate_of"),
("duplicate_chain_with_pr_midway", "duplicate_of"),
+ ("later_duplicate_of_with_pr", "duplicate_of"),
("depends_on_without_pr", "blocked_by_dependency"),
("depends_on_with_open_pr", None),
("incoming_part_of", "plan_parent"),
@@ -994,6 +995,16 @@ async def test_typed_links_hold_back_autostart(link, expect_skip_reason, link_be
_attach_open_pr(midway, 23)
_link(team.id, midway, root, ReportLinkKind.DUPLICATE_OF)
_link(team.id, report, midway, ReportLinkKind.DUPLICATE_OF)
+ elif link == "later_duplicate_of_with_pr":
+ # The oldest claim holds no work, so only the later claim shows the fix is in flight.
+ oldest = _report()
+ later = _report()
+ _attach_open_pr(later, 24)
+ _link(team.id, report, oldest, ReportLinkKind.DUPLICATE_OF)
+ _link(team.id, report, later, ReportLinkKind.DUPLICATE_OF)
+ SignalReportArtefact.objects.filter(
+ team_id=team.id, report_id=report.id, content__contains=str(oldest.id)
+ ).update(created_at=timezone.now() - timedelta(minutes=5))
elif link == "depends_on_without_pr":
_link(team.id, report, _report(), ReportLinkKind.DEPENDS_ON)
elif link == "depends_on_with_open_pr":
diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.py
index b602c337a9f8..06fa15037583 100644
--- a/products/signals/backend/test/test_scout_report_api.py
+++ b/products/signals/backend/test/test_scout_report_api.py
@@ -20,7 +20,14 @@ from social_django.models import UserSocialAuth
from posthog.models import Organization, Team, User
from posthog.models.organization import OrganizationMembership
-from products.signals.backend.artefact_schemas import Priority, PriorityAssessment, SuggestedReviewers, TaskRunArtefact
+from products.signals.backend.artefact_schemas import (
+ AutostartSkip,
+ Priority,
+ PriorityAssessment,
+ SuggestedReviewers,
+ TaskRunArtefact,
+)
+from products.signals.backend.auto_start import _evaluate_link_gates
from products.signals.backend.models import (
MAX_SCOUT_CONTENT_REVISIONS,
ArtefactAttribution,
@@ -514,6 +521,55 @@ class TestScoutReportAPI(APIBaseTest):
)
assert cycle.status_code == status.HTTP_400_BAD_REQUEST, cycle.json()
+ def test_emit_report_writes_links_before_autostart_reads_the_link_gates(self) -> None:
+ run = _make_run(self.team)
+ resolved = SignalReport.objects.create(team=self.team, status=SignalReport.Status.RESOLVED, title="fixed")
+ gate_at_autostart: list[AutostartSkip | None] = []
+
+ async def _read_gates(*, team_id: int, report_id: str) -> None:
+ gate_at_autostart.append(await sync_to_async(_evaluate_link_gates)(team_id, report_id))
+
+ payload = self._payload(
+ repository="PostHog/PostHog",
+ priority="P1",
+ priority_explanation="big blast radius",
+ links=[{"kind": "duplicate_of", "report_id": str(resolved.id), "reason": "same root cause"}],
+ )
+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock(side_effect=_read_gates)):
+ response = self.client.post(self._emit_url(str(run.id)), data=payload, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert len(gate_at_autostart) == 1
+ gate = gate_at_autostart[0]
+ assert gate is not None
+ assert (gate.skip_reason, gate.linked_report_id) == ("duplicate_of", str(resolved.id))
+
+ @parameterized.expand(
+ [
+ ("unknown_target", lambda self: str(uuid4())),
+ (
+ "other_team_target",
+ lambda self: str(
+ SignalReport.objects.create(
+ team=Team.objects.create(organization=self.organization, name="other"),
+ status=SignalReport.Status.READY,
+ title="other team",
+ ).id
+ ),
+ ),
+ ]
+ )
+ def test_emit_report_with_a_rejected_link_authors_no_report(self, _name: str, target_factory: Any) -> None:
+ run = _make_run(self.team)
+ payload = self._payload(links=[{"kind": "depends_on", "report_id": target_factory(self)}])
+ with _safe_judge() as 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_400_BAD_REQUEST, response.json()
+ assert not SignalReport.objects.filter(team=self.team, title=payload["title"]).exists()
+ judge.assert_not_called()
+ autostart.assert_not_awaited()
+
def test_a_links_only_edit_counts_as_an_edit(self) -> None:
# A links-only edit commits the link and answers 200, so it has to reach the edit tally and
# the report-to-run work-log link too. Left out of the `changed` predicate, the link lands
diff --git a/products/signals/backend/typed_report_links.py b/products/signals/backend/typed_report_links.py
index 42dabacf2fff..9c562a602b52 100644
--- a/products/signals/backend/typed_report_links.py
+++ b/products/signals/backend/typed_report_links.py
@@ -25,7 +25,7 @@ from posthog.event_usage import groups
from posthog.models import Team
from products.signals.backend.artefact_schemas import ReportLink
-from products.signals.backend.enums import ReportLinkKind
+from products.signals.backend.enums import ReportLinkKind, ReportLinkWritePath
from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportPullRequest
logger = structlog.get_logger(__name__)
@@ -200,7 +200,14 @@ def has_open_or_merged_pull_request(*, team_id: int, report_ids: Collection[str]
return {report_id for report_id, prs in prs_by_report.items() if any(pr.state in live_states for pr in prs)}
-def capture_report_linked(*, team_id: int, edge: ReportEdge, actor_kind: str | None, actor_agent: str | None) -> None:
+def capture_report_linked(
+ *,
+ team_id: int,
+ edge: ReportEdge,
+ actor_kind: str | None,
+ actor_agent: str | None,
+ write_path: ReportLinkWritePath | None,
+) -> None:
"""`signals_report_linked` — one event per stored link, so the share of reports that carry each
kind of edge becomes readable.
@@ -225,6 +232,7 @@ def capture_report_linked(*, team_id: int, edge: ReportEdge, actor_kind: str | N
"has_reason": bool(edge.reason),
"actor_kind": actor_kind,
"actor_agent": actor_agent,
+ "write_path": write_path.value if write_path is not None else None,
},
groups=groups(team.organization, team),
)
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 1df3a545ee67..deb4e65da683 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -5239,10 +5239,10 @@ export const ReportLinkKindEnumApi = {
} as const
/**
- * One typed, directed link to write on the report being edited.
+ * One typed, directed link to write on the report being emitted or edited.
*/
export interface ReportLinkWriteApi {
- /** How the edited report relates to `report_id`. `depends_on` for work that cannot land until the other report's fix does, `part_of` for one piece of a larger report, `follow_up_of` for work the other report left behind, `duplicate_of` for the same problem filed twice, and `recurrence_of` for a problem a resolved report already covered.
+ /** How this report relates to `report_id`. `depends_on` for work that cannot land until the other report's fix does, `part_of` for one piece of a larger report, `follow_up_of` for work the other report left behind, `duplicate_of` for the same problem filed twice, and `recurrence_of` for a problem a resolved report already covered.
*
* * `depends_on` - Depends on
* * `part_of` - Part of
@@ -5514,6 +5514,11 @@ export interface EmitReportRequestApi {
* @items.maxLength 200
*/
suggested_prompts?: string[]
+ /**
+ * Typed, directed links from the new report to reports that already exist. Send them here, not in a later `edit-report` call, because autostart reads them when the report is created: a `duplicate_of` link to a report that already has a pull request, or a `depends_on` link to a report with no pull request yet, stops a second draft PR. Only the new report gets a row, so link from the side the sentence starts at. Links of the same kind must stay acyclic and every report must be in this project.
+ * @maxItems 10
+ */
+ links?: ReportLinkWriteApi[]
/**
* Optional name for this emission, unique within the run. Reuse it verbatim to retry a call whose outcome you don't know (a timeout, a dropped connection): the retry returns the report the first call authored, with `idempotent_replay` true, instead of a second report. Omit it and the report's own content is the key, which covers a retry of the identical call — pass one when a retry might reword the report.
* @maxLength 200
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index fdeb9d518a38..0a2ad6c01d68 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -1719,7 +1719,7 @@ export const SignalsScoutEditReportBody = /* @__PURE__ */ zod
'\* `depends_on` - Depends on\n\* `part_of` - Part of\n\* `follow_up_of` - Follow-up of\n\* `duplicate_of` - Duplicate of\n\* `recurrence_of` - Recurrence of'
)
.describe(
- "How the edited report relates to `report_id`. `depends_on` for work that cannot land until the other report's fix does, `part_of` for one piece of a larger report, `follow_up_of` for work the other report left behind, `duplicate_of` for the same problem filed twice, and `recurrence_of` for a problem a resolved report already covered.\n\n\* `depends_on` - Depends on\n\* `part_of` - Part of\n\* `follow_up_of` - Follow-up of\n\* `duplicate_of` - Duplicate of\n\* `recurrence_of` - Recurrence of"
+ "How this report relates to `report_id`. `depends_on` for work that cannot land until the other report's fix does, `part_of` for one piece of a larger report, `follow_up_of` for work the other report left behind, `duplicate_of` for the same problem filed twice, and `recurrence_of` for a problem a resolved report already covered.\n\n\* `depends_on` - Depends on\n\* `part_of` - Part of\n\* `follow_up_of` - Follow-up of\n\* `duplicate_of` - Duplicate of\n\* `recurrence_of` - Recurrence of"
),
report_id: zod
.string()
@@ -1730,7 +1730,7 @@ export const SignalsScoutEditReportBody = /* @__PURE__ */ zod
.optional()
.describe('Optional one-line note on why the reports are linked this way.'),
})
- .describe('One typed, directed link to write on the report being edited.')
+ .describe('One typed, directed link to write on the report being emitted or edited.')
)
.max(signalsScoutEditReportBodyLinksMax)
.optional()
@@ -1796,6 +1796,10 @@ export const signalsScoutEmitReportBodySuggestedPromptsItemMax = 200
export const signalsScoutEmitReportBodySuggestedPromptsMax = 3
+export const signalsScoutEmitReportBodyLinksItemReasonMax = 500
+
+export const signalsScoutEmitReportBodyLinksMax = 10
+
export const signalsScoutEmitReportBodyIdempotencyKeyMax = 200
export const SignalsScoutEmitReportBody = /* @__PURE__ */ zod
@@ -2097,6 +2101,34 @@ export const SignalsScoutEmitReportBody = /* @__PURE__ */ zod
.describe(
"Optional follow-up prompts to offer above the report's `Ask AI` box: questions to ask, or next-step actions to request (e.g. carrying out the report's recommendation). The reader clicks one to fill the box with it, then sends or edits it. Write the prompts your own research left open, phrased as the reader would send them."
),
+ links: zod
+ .array(
+ zod
+ .object({
+ kind: zod
+ .enum(['depends_on', 'part_of', 'follow_up_of', 'duplicate_of', 'recurrence_of'])
+ .describe(
+ '\* `depends_on` - Depends on\n\* `part_of` - Part of\n\* `follow_up_of` - Follow-up of\n\* `duplicate_of` - Duplicate of\n\* `recurrence_of` - Recurrence of'
+ )
+ .describe(
+ "How this report relates to `report_id`. `depends_on` for work that cannot land until the other report's fix does, `part_of` for one piece of a larger report, `follow_up_of` for work the other report left behind, `duplicate_of` for the same problem filed twice, and `recurrence_of` for a problem a resolved report already covered.\n\n\* `depends_on` - Depends on\n\* `part_of` - Part of\n\* `follow_up_of` - Follow-up of\n\* `duplicate_of` - Duplicate of\n\* `recurrence_of` - Recurrence of"
+ ),
+ report_id: zod
+ .string()
+ .describe('Id of the report to link to. Must be another report in this project.'),
+ reason: zod
+ .string()
+ .max(signalsScoutEmitReportBodyLinksItemReasonMax)
+ .optional()
+ .describe('Optional one-line note on why the reports are linked this way.'),
+ })
+ .describe('One typed, directed link to write on the report being emitted or edited.')
+ )
+ .max(signalsScoutEmitReportBodyLinksMax)
+ .optional()
+ .describe(
+ 'Typed, directed links from the new report to reports that already exist. Send them here, not in a later `edit-report` call, because autostart reads them when the report is created: a `duplicate_of` link to a report that already has a pull request, or a `depends_on` link to a report with no pull request yet, stops a second draft PR. Only the new report gets a row, so link from the side the sentence starts at. Links of the same kind must stay acyclic and every report must be in this project.'
+ ),
idempotency_key: zod
.string()
.max(signalsScoutEmitReportBodyIdempotencyKeyMax)
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index ef54025dc53e..e7d332ee9c9b 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -724,8 +724,10 @@ tools:
estimated longitudinal points; its snapshot is only an optional cached fallback. An affected-users metric
counts distinct people through one series with `math: dau`. Consumers derive a `BoldNumber` query for each
metric's whole-window `aggregated_value` and an `ActionsBar` query for its longitudinal buckets; never sum
- affected-user buckets. Opt-in: only available to scouts that list `emit_report` in their skill's
- `allowed_tools`.
+ affected-user buckets. Optional `links` records how the new report relates to existing reports
+ (`duplicate_of`, `depends_on`, `part_of`, `follow_up_of`, `recurrence_of`). Send them here rather than in a
+ later `scout-edit-report`, because autostart reads them when the report is created. Opt-in: only available
+ to scouts that list `emit_report` in their skill's `allowed_tools`.
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 ecc076feac8a..6758e0422338 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -10629,7 +10629,7 @@
}
},
"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. Safe to retry: resending an emission returns the report the first call authored (`idempotent_replay` true) rather than a second one, keyed on `idempotency_key` or, without one, on the report's content — so a call that timed out is worth sending again. That is not cross-run dedup: use `inbox-reports-list` to find a report from an earlier run and `scout-edit-report` to update it instead of authoring a near-duplicate. `suggested_reviewers` is the primary way a report reaches a human (each a `github_login` and/or a PostHog `user_uuid` resolved server-side); for a concrete, fixable issue, passing `repository` + `priority` + `suggested_reviewers` also opens a draft PR automatically (autostart, custom_agent parity); omit them to just surface the report. Optional `charts` attach queries the inbox renders inline — reference one from `summary` as `[label](chart:<chart_id>)` to place it in the body, or leave it unreferenced and it renders below. Optional `metrics` adds at most six typed impact measurements: one primary metric for the key observation and supporting facts around it. Every metric requires a bounded live InsightVizNode/TrendsQuery built only from EventsNode or ActionsNode sources, with no more than 1,000 estimated longitudinal points; its snapshot is only an optional cached fallback. An affected-users metric counts distinct people through one series with `math: dau`. Consumers derive a `BoldNumber` query for each metric's whole-window `aggregated_value` and an `ActionsBar` query for its longitudinal buckets; never sum affected-user buckets. Opt-in: only available to scouts that list `emit_report` in their skill's `allowed_tools`.",
+ "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. Safe to retry: resending an emission returns the report the first call authored (`idempotent_replay` true) rather than a second one, keyed on `idempotency_key` or, without one, on the report's content — so a call that timed out is worth sending again. That is not cross-run dedup: use `inbox-reports-list` to find a report from an earlier run and `scout-edit-report` to update it instead of authoring a near-duplicate. `suggested_reviewers` is the primary way a report reaches a human (each a `github_login` and/or a PostHog `user_uuid` resolved server-side); for a concrete, fixable issue, passing `repository` + `priority` + `suggested_reviewers` also opens a draft PR automatically (autostart, custom_agent parity); omit them to just surface the report. Optional `charts` attach queries the inbox renders inline — reference one from `summary` as `[label](chart:<chart_id>)` to place it in the body, or leave it unreferenced and it renders below. Optional `metrics` adds at most six typed impact measurements: one primary metric for the key observation and supporting facts around it. Every metric requires a bounded live InsightVizNode/TrendsQuery built only from EventsNode or ActionsNode sources, with no more than 1,000 estimated longitudinal points; its snapshot is only an optional cached fallback. An affected-users metric counts distinct people through one series with `math: dau`. Consumers derive a `BoldNumber` query for each metric's whole-window `aggregated_value` and an `ActionsBar` query for its longitudinal buckets; never sum affected-user buckets. Optional `links` records how the new report relates to existing reports (`duplicate_of`, `depends_on`, `part_of`, `follow_up_of`, `recurrence_of`). Send them here rather than in a later `scout-edit-report`, because autostart reads them when the report is created. 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",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 11f502c79e99..471ef6e4a9b3 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -11204,7 +11204,7 @@
}
},
"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. Safe to retry: resending an emission returns the report the first call authored (`idempotent_replay` true) rather than a second one, keyed on `idempotency_key` or, without one, on the report's content — so a call that timed out is worth sending again. That is not cross-run dedup: use `inbox-reports-list` to find a report from an earlier run and `scout-edit-report` to update it instead of authoring a near-duplicate. `suggested_reviewers` is the primary way a report reaches a human (each a `github_login` and/or a PostHog `user_uuid` resolved server-side); for a concrete, fixable issue, passing `repository` + `priority` + `suggested_reviewers` also opens a draft PR automatically (autostart, custom_agent parity); omit them to just surface the report. Optional `charts` attach queries the inbox renders inline — reference one from `summary` as `[label](chart:<chart_id>)` to place it in the body, or leave it unreferenced and it renders below. Optional `metrics` adds at most six typed impact measurements: one primary metric for the key observation and supporting facts around it. Every metric requires a bounded live InsightVizNode/TrendsQuery built only from EventsNode or ActionsNode sources, with no more than 1,000 estimated longitudinal points; its snapshot is only an optional cached fallback. An affected-users metric counts distinct people through one series with `math: dau`. Consumers derive a `BoldNumber` query for each metric's whole-window `aggregated_value` and an `ActionsBar` query for its longitudinal buckets; never sum affected-user buckets. Opt-in: only available to scouts that list `emit_report` in their skill's `allowed_tools`.",
+ "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. Safe to retry: resending an emission returns the report the first call authored (`idempotent_replay` true) rather than a second one, keyed on `idempotency_key` or, without one, on the report's content — so a call that timed out is worth sending again. That is not cross-run dedup: use `inbox-reports-list` to find a report from an earlier run and `scout-edit-report` to update it instead of authoring a near-duplicate. `suggested_reviewers` is the primary way a report reaches a human (each a `github_login` and/or a PostHog `user_uuid` resolved server-side); for a concrete, fixable issue, passing `repository` + `priority` + `suggested_reviewers` also opens a draft PR automatically (autostart, custom_agent parity); omit them to just surface the report. Optional `charts` attach queries the inbox renders inline — reference one from `summary` as `[label](chart:<chart_id>)` to place it in the body, or leave it unreferenced and it renders below. Optional `metrics` adds at most six typed impact measurements: one primary metric for the key observation and supporting facts around it. Every metric requires a bounded live InsightVizNode/TrendsQuery built only from EventsNode or ActionsNode sources, with no more than 1,000 estimated longitudinal points; its snapshot is only an optional cached fallback. An affected-users metric counts distinct people through one series with `math: dau`. Consumers derive a `BoldNumber` query for each metric's whole-window `aggregated_value` and an `ActionsBar` query for its longitudinal buckets; never sum affected-user buckets. Optional `links` records how the new report relates to existing reports (`duplicate_of`, `depends_on`, `part_of`, `follow_up_of`, `recurrence_of`). Send them here rather than in a later `scout-edit-report`, because autostart reads them when the report is created. 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",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4a5f903c73ca..e7322d89a716 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -35278,10 +35278,10 @@ export namespace Schemas {
} as const;
/**
- * One typed, directed link to write on the report being edited.
+ * One typed, directed link to write on the report being emitted or edited.
*/
export interface ReportLinkWrite {
- /** How the edited report relates to `report_id`. `depends_on` for work that cannot land until the other report's fix does, `part_of` for one piece of a larger report, `follow_up_of` for work the other report left behind, `duplicate_of` for the same problem filed twice, and `recurrence_of` for a problem a resolved report already covered.
+ /** How this report relates to `report_id`. `depends_on` for work that cannot land until the other report's fix does, `part_of` for one piece of a larger report, `follow_up_of` for work the other report left behind, `duplicate_of` for the same problem filed twice, and `recurrence_of` for a problem a resolved report already covered.
*
* * `depends_on` - Depends on
* * `part_of` - Part of
@@ -35822,6 +35822,11 @@ export namespace Schemas {
* @items.maxLength 200
*/
suggested_prompts?: string[];
+ /**
+ * Typed, directed links from the new report to reports that already exist. Send them here, not in a later `edit-report` call, because autostart reads them when the report is created: a `duplicate_of` link to a report that already has a pull request, or a `depends_on` link to a report with no pull request yet, stops a second draft PR. Only the new report gets a row, so link from the side the sentence starts at. Links of the same kind must stay acyclic and every report must be in this project.
+ * @maxItems 10
+ */
+ links?: ReportLinkWrite[];
/**
* Optional name for this emission, unique within the run. Reuse it verbatim to retry a call whose outcome you don't know (a timeout, a dropped connection): the retry returns the report the first call authored, with `idempotent_replay` true, instead of a second report. Omit it and the report's own content is the key, which covers a retry of the identical call — pass one when a retry might reword the report.
* @maxLength 200
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 724c022fceaf..d9ce4940c4f1 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -2020,7 +2020,7 @@ export const SignalsScoutEditReportBody = () => zod
'\* `depends_on` - Depends on\n\* `part_of` - Part of\n\* `follow_up_of` - Follow-up of\n\* `duplicate_of` - Duplicate of\n\* `recurrence_of` - Recurrence of'
)
.describe(
- "How the edited report relates to `report_id`. `depends_on` for work that cannot land until the other report's fix does, `part_of` for one piece of a larger report, `follow_up_of` for work the other report left behind, `duplicate_of` for the same problem filed twice, and `recurrence_of` for a problem a resolved report already covered.\n\n\* `depends_on` - Depends on\n\* `part_of` - Part of\n\* `follow_up_of` - Follow-up of\n\* `duplicate_of` - Duplicate of\n\* `recurrence_of` - Recurrence of"
+ "How this report relates to `report_id`. `depends_on` for work that cannot land until the other report's fix does, `part_of` for one piece of a larger report, `follow_up_of` for work the other report left behind, `duplicate_of` for the same problem filed twice, and `recurrence_of` for a problem a resolved report already covered.\n\n\* `depends_on` - Depends on\n\* `part_of` - Part of\n\* `follow_up_of` - Follow-up of\n\* `duplicate_of` - Duplicate of\n\* `recurrence_of` - Recurrence of"
),
report_id: zod
.string()
@@ -2031,7 +2031,7 @@ export const SignalsScoutEditReportBody = () => zod
.optional()
.describe('Optional one-line note on why the reports are linked this way.'),
})
- .describe('One typed, directed link to write on the report being edited.')
+ .describe('One typed, directed link to write on the report being emitted or edited.')
)
.max(signalsScoutEditReportBodyLinksMax)
.optional()
@@ -2132,6 +2132,10 @@ export const signalsScoutEmitReportBodySuggestedPromptsItemMax = 200
export const signalsScoutEmitReportBodySuggestedPromptsMax = 3
+export const signalsScoutEmitReportBodyLinksItemReasonMax = 500
+
+export const signalsScoutEmitReportBodyLinksMax = 10
+
export const signalsScoutEmitReportBodyIdempotencyKeyMax = 200
export const SignalsScoutEmitReportBody = () => zod
@@ -2433,6 +2437,34 @@ export const SignalsScoutEmitReportBody = () => zod
.describe(
"Optional follow-up prompts to offer above the report's `Ask AI` box: questions to ask, or next-step actions to request (e.g. carrying out the report's recommendation). The reader clicks one to fill the box with it, then sends or edits it. Write the prompts your own research left open, phrased as the reader would send them."
),
+ links: zod
+ .array(
+ zod
+ .object({
+ kind: zod
+ .enum(['depends_on', 'part_of', 'follow_up_of', 'duplicate_of', 'recurrence_of'])
+ .describe(
+ '\* `depends_on` - Depends on\n\* `part_of` - Part of\n\* `follow_up_of` - Follow-up of\n\* `duplicate_of` - Duplicate of\n\* `recurrence_of` - Recurrence of'
+ )
+ .describe(
+ "How this report relates to `report_id`. `depends_on` for work that cannot land until the other report's fix does, `part_of` for one piece of a larger report, `follow_up_of` for work the other report left behind, `duplicate_of` for the same problem filed twice, and `recurrence_of` for a problem a resolved report already covered.\n\n\* `depends_on` - Depends on\n\* `part_of` - Part of\n\* `follow_up_of` - Follow-up of\n\* `duplicate_of` - Duplicate of\n\* `recurrence_of` - Recurrence of"
+ ),
+ report_id: zod
+ .string()
+ .describe('Id of the report to link to. Must be another report in this project.'),
+ reason: zod
+ .string()
+ .max(signalsScoutEmitReportBodyLinksItemReasonMax)
+ .optional()
+ .describe('Optional one-line note on why the reports are linked this way.'),
+ })
+ .describe('One typed, directed link to write on the report being emitted or edited.')
+ )
+ .max(signalsScoutEmitReportBodyLinksMax)
+ .optional()
+ .describe(
+ 'Typed, directed links from the new report to reports that already exist. Send them here, not in a later `edit-report` call, because autostart reads them when the report is created: a `duplicate_of` link to a report that already has a pull request, or a `depends_on` link to a report with no pull request yet, stops a second draft PR. Only the new report gets a row, so link from the side the sentence starts at. Links of the same kind must stay acyclic and every report must be in this project.'
+ ),
idempotency_key: zod
.string()
.max(signalsScoutEmitReportBodyIdempotencyKeyMax)
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 173fc1559cd1..3903ccccbb67 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -1106,6 +1106,9 @@ const scoutEmitReport = (): ToolBase<ReturnType<typeof ScoutEmitReportSchema>, S
if (params.suggested_prompts !== undefined) {
body['suggested_prompts'] = params.suggested_prompts
}
+ if (params.links !== undefined) {
+ body['links'] = params.links
+ }
if (params.idempotency_key !== undefined) {
body['idempotency_key'] = params.idempotency_key
}
@@ -2049,6 +2052,9 @@ const signalsScoutEmitReport = (): ToolBase<
if (params.suggested_prompts !== undefined) {
body['suggested_prompts'] = params.suggested_prompts
}
+ if (params.links !== undefined) {
+ body['links'] = params.links
+ }
if (params.idempotency_key !== undefined) {
body['idempotency_key'] = params.idempotency_key
}