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): make scout emit_report safe to retry (#96298)

posthog[bot]848f3e031070
diff --git a/products/signals/backend/migrations/0124_signalreport_scout_idempotency_key.py b/products/signals/backend/migrations/0124_signalreport_scout_idempotency_key.py
new file mode 100644
index 000000000000..4b0cfeb2d93c
--- /dev/null
+++ b/products/signals/backend/migrations/0124_signalreport_scout_idempotency_key.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0123_alter_signalsourceconfig_team"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalreport",
+ name="scout_idempotency_key",
+ field=models.CharField(blank=True, max_length=255, null=True),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/0125_signalreport_scout_idem_key_index.py b/products/signals/backend/migrations/0125_signalreport_scout_idem_key_index.py
new file mode 100644
index 000000000000..a50588a772bb
--- /dev/null
+++ b/products/signals/backend/migrations/0125_signalreport_scout_idem_key_index.py
@@ -0,0 +1,36 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import CreateIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # Required by CreateIndexConcurrently, and why the column it indexes is added in 0124 instead.
+ atomic = False
+
+ dependencies = [
+ ("signals", "0124_signalreport_scout_idempotency_key"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="signals_report_scout_idem_key",
+ table_name="signals_signalreport",
+ columns="(team_id, scout_idempotency_key)",
+ unique=True,
+ where="WHERE scout_idempotency_key IS NOT NULL",
+ ),
+ ],
+ state_operations=[
+ migrations.AddConstraint(
+ model_name="signalreport",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(scout_idempotency_key__isnull=False),
+ fields=("team", "scout_idempotency_key"),
+ name="signals_report_scout_idem_key",
+ ),
+ ),
+ ],
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 1d3bdb3981bb..31751a102276 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0123_alter_signalsourceconfig_team
+0125_signalreport_scout_idem_key_index
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 06eb8517329f..45be7286a4c1 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -312,6 +312,11 @@ class SignalReport(UUIDModel):
# ID de-duplication would not. Null for reports that never notified or predate the field.
inbox_notified_at = models.DateTimeField(null=True, blank=True)
+ # The emit key of the scout `emit_report` call that authored this report. An emission can take
+ # minutes, so the caller can time out at a proxy while the request keeps running here, and the
+ # key is what makes the retry that follows return this report instead of authoring a second one.
+ scout_idempotency_key = models.CharField(max_length=255, null=True, blank=True)
+
# Video segment clustering fields
cluster_centroid = deprecate_field(
ArrayField(
@@ -339,6 +344,15 @@ class SignalReport(UUIDModel):
name="signals_report_first_visible",
),
]
+ constraints = [
+ # The barrier itself, not a lookup aid: two emits racing on one key both reach the
+ # insert, and Postgres is what lets exactly one through.
+ models.UniqueConstraint(
+ fields=["team", "scout_idempotency_key"],
+ condition=models.Q(scout_idempotency_key__isnull=False),
+ name="signals_report_scout_idem_key",
+ ),
+ ]
@property
def researched_signal_count(self) -> int:
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 4e29ebfd0817..2a14c3d89a6c 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -173,5 +173,6 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
- 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.
Both report-channel actions are tracked on the run as queryable columns: `emit_report` appends to `SignalScoutRun.emitted_report_ids` (via `_record_report_emit`), and `edit_report` appends — deduped — to `edited_report_ids` (via `record_report_edit`), so "which reports did this run author vs. edit?" is a column lookup, not an event-stream or artefact-log join. Both writes are best-effort and post-commit (an edit/emit never fails because its tally write did).
+ `emit_report` is retry-safe, `edit_report` is not. Every emission is stored under a key (`_emit_idempotency_key`: the caller's `idempotency_key`, else a digest of the report's content, run-scoped either way) held by a partial unique index on `SignalReport.scout_idempotency_key`, so a retry after a proxy timeout returns the first report with `idempotent_replay` set instead of authoring a twin. The tool checks the key before the safety judge so a retry costs no LLM call; the index is what settles a retry that arrives while the first call is still judging, surfacing to the tool as `ScoutReportAlreadyEmittedError`. A replay never re-queues the Slack delivery or re-fires autostart, and books its own `idempotent_replay` outcome on `signals_scout_report_emitted` so retries stay measurable without counting as reports. This covers the transport failure only; telling a topic an earlier run already filed from a new one is still the scout's job (inbox search + the `report:` scratchpad pointer).
- **If you add or rename a workflow/activity in `temporal/agentic/`, update `posthog/temporal/tests/ai/test_module_integrity.py` (`TestSignalsProductModuleIntegrity`) to match.**
- **If you change the harness layout or tool surface, update this file to match.**
diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.py
index f3ddbcba0042..ec06eeaee5e1 100644
--- a/products/signals/backend/scout_harness/prompt.py
+++ b/products/signals/backend/scout_harness/prompt.py
@@ -401,22 +401,21 @@ _REPORT_SEARCH_BULLET = (
# Per-capability, so an emit-only scout is never told about a tool it can't call: the shared wording
# would otherwise name `edit_report` in a prompt whose scout has no edit scope.
-_RETRY_TAIL = (
- " If unsure whether a call landed, re-read with `inbox-reports-list` / `inbox-reports-retrieve` "
- "rather than re-sending."
+_EMIT_RETRY_SAFE = (
+ "An `emit_report` call that timed out or died mid-flight is safe to send again, unchanged: the "
+ "retry returns the report the first call authored, flagged `idempotent_replay`, never a second "
+ "report. Without an `idempotency_key` the report's content is the key, so pass one when your retry "
+ "might reword the report."
)
-_REPORT_NOT_IDEMPOTENT_BOTH = (
- "Neither `emit_report` nor `edit_report` is idempotent, so never retry a call that looked like it "
- "failed: a retried `emit_report` that actually landed silently doubles the report, and a retried "
- "`edit_report(append_note=...)` appends a second note, and `edit_report(append_evidence=...)` "
- "appends duplicate signals and increases the report counters again." + _RETRY_TAIL
+_REPORT_RETRY_RULE_BOTH = (
+ _EMIT_RETRY_SAFE + " `edit_report` has no such barrier: a retried `edit_report(append_note=...)` "
+ "appends a second note, and `edit_report(append_evidence=...)` appends duplicate signals and "
+ "increases the report counters again. If unsure whether an edit landed, re-read the report with "
+ "`inbox-reports-retrieve` rather than re-sending."
)
-_REPORT_NOT_IDEMPOTENT_EMIT_ONLY = (
- "`emit_report` is not idempotent, so never retry one that looked like it failed: a retry that "
- "actually succeeded the first time silently doubles the report." + _RETRY_TAIL
-)
+_REPORT_RETRY_RULE_EMIT_ONLY = _EMIT_RETRY_SAFE
# The two additive channels on an edit, stated once and shared by both edit-capable personas.
# An emit-only prompt names neither, because the scout has no edit scope.
@@ -435,19 +434,19 @@ _EDIT_EVIDENCE_VS_NOTE = (
_AUTHORING_VS_EDITING_REPORT_BOTH = f"""# Authoring vs. editing: search the inbox first
-`scout-emit-report` is NOT idempotent: calling it twice authors two reports, and there is no dedupe matcher on this channel. Duplicate reports are the main failure mode here, so the discipline is **search, then decide**:
+`scout-emit-report` has no dedupe matcher: two calls covering one issue in different words author two reports. Duplicate reports are the main failure mode here, so the discipline is **search, then decide**:
{_REPORT_SEARCH_BULLET}
- **Edit when it already exists *and is still live*.** If a report covers the issue, prefer `scout-edit-report`. {_EDIT_EVIDENCE_VS_NOTE} Rewrite `title`/`summary` only on a report you own. One living report beats three near-duplicates fragmenting the inbox. But `edit_report` can't change a report's status, so appending to a `resolved` / `suppressed` / `failed` report buries a real relapse under a closed item: when the match is no longer live, treat the relapse as genuinely new, author a fresh report, and repoint your `report:` pointer at it.
-- **Author only when it's genuinely new.** A materially new issue, a known one with new evidence that changes the verdict, or a relapse whose prior report is no longer live. {_REPORT_NOT_IDEMPOTENT_BOTH}"""
+- **Author only when it's genuinely new.** A materially new issue, a known one with new evidence that changes the verdict, or a relapse whose prior report is no longer live. {_REPORT_RETRY_RULE_BOTH}"""
_AUTHORING_REPORT_EMIT_ONLY = f"""# Authoring reports: search the inbox first
-`scout-emit-report` is NOT idempotent: calling it twice authors two reports, and there is no dedupe matcher on this channel. Duplicate reports are the main failure mode here, so the discipline is **search, then decide**:
+`scout-emit-report` has no dedupe matcher: two calls covering one issue in different words author two reports. Duplicate reports are the main failure mode here, so the discipline is **search, then decide**:
{_REPORT_SEARCH_BULLET}
- **Don't duplicate a *live* report.** This run can't edit reports, so when a still-open report already covers the issue, record a `remember(...)` note and skip rather than authoring a near-duplicate. A `resolved` / `suppressed` / `failed` report won't resurface and you can't reopen it, so a genuine relapse of a closed report *is* genuinely new: author a fresh report for it.
-- **Author only when it's genuinely new.** A materially new issue, or a relapse whose prior report is no longer live. {_REPORT_NOT_IDEMPOTENT_EMIT_ONLY}"""
+- **Author only when it's genuinely new.** A materially new issue, or a relapse whose prior report is no longer live. {_REPORT_RETRY_RULE_EMIT_ONLY}"""
_EDITING_REPORT_EDIT_ONLY = f"""# Editing existing reports
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index d00dd7157979..2b7f4910575e 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -53,6 +53,7 @@ from products.signals.backend.scout_harness.tools.emit import (
from products.signals.backend.scout_harness.tools.notes import MAX_NOTE_CONTENT_LENGTH, MAX_NOTES_LIST_LIMIT
from products.signals.backend.scout_harness.tools.report import (
MAX_EVIDENCE_DESCRIPTION_LENGTH,
+ MAX_IDEMPOTENCY_KEY_LENGTH,
MAX_REPORT_SIGNALS,
MAX_REPORT_SUMMARY_LENGTH,
MAX_REPORT_TITLE_LENGTH,
@@ -1346,6 +1347,18 @@ class EmitReportRequestSerializer(serializers.Serializer):
"research left open, phrased as the reader would send them."
),
)
+ idempotency_key = serializers.CharField(
+ required=False,
+ allow_null=True,
+ max_length=MAX_IDEMPOTENCY_KEY_LENGTH,
+ help_text=(
+ "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."
+ ),
+ )
class EmitReportResponseSerializer(serializers.Serializer):
@@ -1376,6 +1389,13 @@ class EmitReportResponseSerializer(serializers.Serializer):
"or the skip isn't something the scout can act on."
),
)
+ idempotent_replay = serializers.BooleanField(
+ help_text=(
+ "True when this call authored nothing because the emission had already landed — the fields "
+ "above describe that first report. Expected on a retry; treat the report as filed and don't "
+ "send it again."
+ ),
+ )
class EditReportRequestSerializer(serializers.Serializer):
diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.py
index e84c65495f03..c49408d1f943 100644
--- a/products/signals/backend/scout_harness/tools/report.py
+++ b/products/signals/backend/scout_harness/tools/report.py
@@ -10,10 +10,13 @@ adapters: input validation + the shared preflight gates + attribution, then call
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.
+`emit_report` carries an idempotency key, so a retried emission returns the report the first call
+authored instead of a second one. The key is the caller's `idempotency_key` when it supplies one, and
+the report's own content when it doesn't, scoped to the authoring run either way. This covers the
+retry a scout sends after a proxy timeout, not cross-run dedup: telling one run's finding from a
+previous run's is still the vanilla inbox tools (`inbox-reports-list` / `inbox-reports-retrieve`) plus
+a `report:<domain>:<entity>` scratchpad key the scout maintains. `edit_report` remains NOT idempotent
+— a retried edit appends a second note.
"""
from __future__ import annotations
@@ -22,6 +25,7 @@ import re
import json
import uuid
import asyncio
+import hashlib
import logging
from collections.abc import Sequence
from dataclasses import dataclass
@@ -74,12 +78,15 @@ from products.signals.backend.scout_harness.tools.notes import MAX_NOTE_CONTENT_
from products.signals.backend.scout_report import (
INFERRED_REPOSITORY_REASON,
MAX_REPORT_SIGNALS,
+ ExistingScoutReport,
InvalidScoutReportError,
+ ScoutReportAlreadyEmittedError,
ScoutReportSignal,
append_report_evidence,
append_report_note,
create_scout_report,
emit_appended_report_evidence,
+ find_scout_report_by_idempotency_key,
get_scout_report_signal_count,
get_scout_report_status,
get_scout_report_title,
@@ -110,6 +117,8 @@ MAX_SUGGESTED_REVIEWERS = 10
# 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
+# The caller-supplied part of an emit key, bounded so the stored key (run id + this) fits the column.
+MAX_IDEMPOTENCY_KEY_LENGTH = 200
# 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);
@@ -167,6 +176,8 @@ class EmitReportResult:
`remediation` carries a one-line, scout-actionable next step for that skip (see
`EMIT_SKIP_REMEDIATION`) so a gate-skipped report isn't a dead end — the scout learns why its
report was dropped and how to unblock it rather than losing a full run to a silent skip.
+ `idempotent_replay` means this call authored nothing because its emit key already had a report:
+ the fields above describe that first report, so the caller reads its own emission back.
"""
report_id: str | None
@@ -175,6 +186,7 @@ class EmitReportResult:
skipped_reason: str | None
safety_explanation: str | None
remediation: str | None = None
+ idempotent_replay: bool = False
@dataclass(frozen=True)
@@ -372,6 +384,43 @@ def _gate_skip_result(preflight: str) -> EmitReportResult:
)
+def _emit_idempotency_key(
+ *, run: SignalScoutRun, supplied: str | None, title: str, summary: str, evidence: list[ReportEvidence]
+) -> str:
+ """The key this emission is stored under, always scoped to the authoring run.
+
+ A supplied key is the caller's own name for the emission, so a retry that rewords the report still
+ resolves to the first one. Without a key the report's identity is the key, which still covers the
+ case the barrier exists for: an emission times out at a proxy while the server keeps working, and
+ the scout sends the same call again. Identity is the title, the summary, and the evidence, not the
+ routing around them — a resend that only adds `suggested_reviewers` is the same report, and belongs
+ on `edit_report`. Run-scoped either way, so a later run can still report a finding nothing fixed."""
+ if supplied is not None:
+ key = supplied.strip()
+ if not key:
+ raise InvalidScoutReportError("idempotency_key must not be blank")
+ if len(key) > MAX_IDEMPOTENCY_KEY_LENGTH:
+ raise InvalidScoutReportError(f"idempotency_key must be at most {MAX_IDEMPOTENCY_KEY_LENGTH} characters")
+ return f"{run.id}:key:{key}"
+ content = json.dumps(
+ [title, summary, [[item.source_id, item.description] for item in evidence]], separators=(",", ":")
+ )
+ return f"{run.id}:auto:{hashlib.sha256(content.encode()).hexdigest()}"
+
+
+def _replay_result(existing: ExistingScoutReport) -> EmitReportResult:
+ """What a retried emission returns: the first report, at the status it holds now. No
+ `safety_explanation` — the judge ran on the call that authored it, not on this one."""
+ return EmitReportResult(
+ report_id=existing.report_id,
+ status=existing.status,
+ emitted=_surfaced(existing.status),
+ skipped_reason=None,
+ safety_explanation=None,
+ idempotent_replay=True,
+ )
+
+
def _emit_result(persisted_report_id: str, judgement: ScoutReportJudgement) -> EmitReportResult:
return EmitReportResult(
report_id=persisted_report_id,
@@ -960,8 +1009,10 @@ def _capture_report_emitted(
`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). The event also
- carries the report's content (`title` / `summary` / `actionability` / `priority` / `repository` /
+ it out of the inbox), `surfaced` (landed in the inbox as READY / PENDING_INPUT), or
+ `idempotent_replay` (the emit key already had a report, so this call authored nothing — its own
+ bucket, so a retry never counts as a second report, and so the retry rate stays measurable).
+ The event also carries the report's content (`title` / `summary` / `actionability` / `priority` / `repository` /
`safety_explanation`) — parity with the signal channel's `signal_emitted`, so internal consumers
(dashboards, alerts, CDP forwards) can act on a report's substance, not just its ids. Content rides
every outcome, including `gate_skipped` (it records what would have been authored). Also stamped
@@ -973,7 +1024,9 @@ def _capture_report_emitted(
Returns the customer-facing fan-out payload for the caller to forward, or None to suppress the
fan-out — a disabled / dry-run gate-skip records the attempt on the internal stream here but must
not fire an automation-driving event into the team's own project."""
- if result.skipped_reason is not None:
+ if result.idempotent_replay:
+ outcome = "idempotent_replay"
+ elif result.skipped_reason is not None:
outcome = "gate_skipped"
elif result.emitted:
outcome = "surfaced"
@@ -1150,6 +1203,7 @@ async def emit_report(
suggested_reviewers: list[ReviewerInput] | None = None,
charts: list[ReportChartInput] | None = None,
suggested_prompts: list[str] | 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
the in-Temporal runner); routes the sync DB work through `database_sync_to_async`.
@@ -1159,7 +1213,11 @@ async def emit_report(
open a draft PR. They're only resolved/written when the report actually surfaces.
`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."""
+ optional prompts (questions or next-step actions) it offers above the report's "Ask AI" box.
+
+ `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."""
_assert_team_owns_run(team, run)
_validate_emit_inputs(title, summary, evidence)
chart_contents = _build_charts(charts)
@@ -1172,15 +1230,10 @@ async def emit_report(
explanation=actionability_explanation, choice=actionability, already_addressed=already_addressed
)
priority_assessment = _build_priority(priority, priority_explanation)
- # Resolves user_uuid → github_login (a DB read), so bridge it off the event loop. Runs before the
- # safety judge so an unresolvable reviewer fails fast rather than after paying for the LLM call.
- reviewers = await database_sync_to_async(_build_suggested_reviewers, thread_sensitive=False)(
- team, suggested_reviewers, skill_name=run.skill_name
- )
+ emit_key = _emit_idempotency_key(run=run, supplied=idempotency_key, title=title, summary=summary, evidence=evidence)
- preflight = await database_sync_to_async(_preflight_emit_gates, thread_sensitive=False)(team, run)
- if preflight is not None:
- result = _gate_skip_result(preflight)
+ async def finish(result: EmitReportResult) -> EmitReportResult:
+ # Every exit reports the same call, so the capture and the fan-out sit here, not beside each return.
forward = await database_sync_to_async(_capture_report_emitted, thread_sensitive=False)(
team=team,
run=run,
@@ -1198,6 +1251,24 @@ async def emit_report(
await _forward_report_event_async(team, forward)
return result
+ # Ahead of the gates: the report this emission already authored outranks a gate the project has
+ # crossed since, and answering a retry with "skipped" would hide a report that exists.
+ existing = await database_sync_to_async(find_scout_report_by_idempotency_key, thread_sensitive=False)(
+ team_id=team.id, idempotency_key=emit_key
+ )
+ if existing is not None:
+ return await finish(_replay_result(existing))
+
+ # Resolves user_uuid → github_login (a DB read), so bridge it off the event loop. Runs before the
+ # safety judge so an unresolvable reviewer fails fast rather than after paying for the LLM call.
+ reviewers = await database_sync_to_async(_build_suggested_reviewers, thread_sensitive=False)(
+ team, suggested_reviewers, skill_name=run.skill_name
+ )
+
+ preflight = await database_sync_to_async(_preflight_emit_gates, thread_sensitive=False)(team, run)
+ if preflight is not None:
+ return await finish(_gate_skip_result(preflight))
+
task_id = await database_sync_to_async(_resolve_task_id, thread_sensitive=False)(run)
attribution = _attribution_for(task_id)
judgement = await judge_scout_report(
@@ -1229,28 +1300,34 @@ async def emit_report(
reviewers = await database_sync_to_async(_stamp_owner_provenance, thread_sensitive=False)(
team, reviewers, skill_name=run.skill_name
)
- 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,
- charts=chart_contents,
- # A judged-unsafe report keeps its prose for audit, but not its prompts: a suppressed 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 (),
- # 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,
- )
+ try:
+ 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,
+ charts=chart_contents,
+ # A judged-unsafe report keeps its prose for audit, but not its prompts: a suppressed 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 (),
+ # 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,
+ idempotency_key=emit_key,
+ )
+ except ScoutReportAlreadyEmittedError as already_emitted:
+ # The retry arrived while this call was still judging, so both reached the insert. The winner's
+ # report is the answer, and the Slack delivery and autostart below are its business, not ours.
+ return await finish(_replay_result(already_emitted.existing))
if surfaced:
await database_sync_to_async(queue_configured_scout_slack_delivery, thread_sensitive=False)(
run_id=run.id,
@@ -1261,23 +1338,7 @@ async def emit_report(
delivery_id=persisted.report_id,
)
await _maybe_autostart_report(team_id=team.id, report_id=persisted.report_id)
- result = _emit_result(persisted.report_id, judgement)
- forward = await database_sync_to_async(_capture_report_emitted, thread_sensitive=False)(
- team=team,
- run=run,
- result=result,
- evidence_count=len(evidence),
- title=title,
- summary=summary,
- actionability=actionability,
- already_addressed=already_addressed,
- priority=priority,
- repository=repository,
- chart_count=len(chart_contents),
- suggested_prompt_count=len(prompt_contents),
- )
- await _forward_report_event_async(team, forward)
- return result
+ return await finish(_emit_result(persisted.report_id, judgement))
def emit_report_sync(
@@ -1296,6 +1357,7 @@ def emit_report_sync(
suggested_reviewers: list[ReviewerInput] | None = None,
charts: list[ReportChartInput] | None = None,
suggested_prompts: list[str] | 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
calling thread/connection (gates, persist) — only the safety-judge LLM call, the free-form repo
@@ -1314,11 +1376,10 @@ def emit_report_sync(
explanation=actionability_explanation, choice=actionability, already_addressed=already_addressed
)
priority_assessment = _build_priority(priority, priority_explanation)
- reviewers = _build_suggested_reviewers(team, suggested_reviewers, skill_name=run.skill_name)
+ emit_key = _emit_idempotency_key(run=run, supplied=idempotency_key, title=title, summary=summary, evidence=evidence)
- preflight = _preflight_emit_gates(team, run)
- if preflight is not None:
- result = _gate_skip_result(preflight)
+ def finish(result: EmitReportResult) -> EmitReportResult:
+ # The sync twin of `emit_report.finish` — see there for why the capture lives in one place.
forward = _capture_report_emitted(
team=team,
run=run,
@@ -1337,6 +1398,16 @@ def emit_report_sync(
_forward_report_event_to_team(team=team, forward=forward)
return result
+ existing = find_scout_report_by_idempotency_key(team_id=team.id, idempotency_key=emit_key)
+ if existing is not None:
+ return finish(_replay_result(existing))
+
+ reviewers = _build_suggested_reviewers(team, suggested_reviewers, skill_name=run.skill_name)
+
+ preflight = _preflight_emit_gates(team, run)
+ if preflight is not None:
+ return finish(_gate_skip_result(preflight))
+
task_id = _resolve_task_id(run)
attribution = _attribution_for(task_id)
judgement = async_to_sync(judge_scout_report)(
@@ -1366,28 +1437,33 @@ def emit_report_sync(
# Re-stamp owner provenance from the live owner set after the judge wait (see
# `_stamp_owner_provenance`) — autostart trusts the stored stamp.
reviewers = _stamp_owner_provenance(team, reviewers, skill_name=run.skill_name)
- 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,
- charts=chart_contents,
- # A judged-unsafe report keeps its prose for audit, but not its prompts: a suppressed 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 (),
- # 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,
- )
+ try:
+ 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,
+ charts=chart_contents,
+ # A judged-unsafe report keeps its prose for audit, but not its prompts: a suppressed 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 (),
+ # 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,
+ idempotency_key=emit_key,
+ )
+ except ScoutReportAlreadyEmittedError as already_emitted:
+ # As in `emit_report`: a concurrent retry won the insert, so hand back its report.
+ return finish(_replay_result(already_emitted.existing))
if surfaced:
queue_configured_scout_slack_delivery(
run_id=run.id,
@@ -1396,24 +1472,7 @@ def emit_report_sync(
delivery_id=persisted.report_id,
)
async_to_sync(_maybe_autostart_report)(team_id=team.id, report_id=persisted.report_id)
- result = _emit_result(persisted.report_id, judgement)
- forward = _capture_report_emitted(
- team=team,
- run=run,
- result=result,
- evidence_count=len(evidence),
- title=title,
- summary=summary,
- actionability=actionability,
- already_addressed=already_addressed,
- priority=priority,
- repository=repository,
- chart_count=len(chart_contents),
- suggested_prompt_count=len(prompt_contents),
- )
- if forward is not None:
- _forward_report_event_to_team(team=team, forward=forward)
- return result
+ return finish(_emit_result(persisted.report_id, judgement))
def _do_edit_report(
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index af6b007e941a..205fa8c2c5bf 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -1067,8 +1067,10 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"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."
+ "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. Use `reports` to find a report from an earlier run and "
+ "`edit-report` to update it instead of authoring a near-duplicate."
),
operation_id="signals_scout_emit_report",
)
@@ -1101,6 +1103,7 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
suggested_reviewers=_to_reviewer_inputs(data.get("suggested_reviewers")),
charts=_to_report_charts(data.get("charts")),
suggested_prompts=data.get("suggested_prompts"),
+ idempotency_key=data.get("idempotency_key"),
)
except InvalidScoutReportError as exc:
raise exceptions.ValidationError({"detail": str(exc)})
@@ -1113,6 +1116,7 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"skipped_reason": result.skipped_reason,
"safety_explanation": result.safety_explanation,
"remediation": result.remediation,
+ "idempotent_replay": result.idempotent_replay,
}
).data,
status=status.HTTP_200_OK,
diff --git a/products/signals/backend/scout_report/__init__.py b/products/signals/backend/scout_report/__init__.py
index f633b1e2f0aa..0dfcbc8139c5 100644
--- a/products/signals/backend/scout_report/__init__.py
+++ b/products/signals/backend/scout_report/__init__.py
@@ -11,13 +11,16 @@ from products.signals.backend.report_prompts import MAX_SUGGESTED_PROMPTS
from products.signals.backend.scout_report.persistence import (
INFERRED_REPOSITORY_REASON,
MAX_REPORT_SIGNALS,
+ ExistingScoutReport,
InvalidScoutReportError,
PersistedScoutReport,
+ ScoutReportAlreadyEmittedError,
ScoutReportSignal,
append_report_evidence,
append_report_note,
create_scout_report,
emit_appended_report_evidence,
+ find_scout_report_by_idempotency_key,
get_scout_report_signal_count,
get_scout_report_status,
get_scout_report_title,
@@ -37,13 +40,16 @@ __all__ = [
"MAX_REPORT_CHARTS",
"MAX_REPORT_SIGNALS",
"MAX_SUGGESTED_PROMPTS",
+ "ExistingScoutReport",
"InvalidScoutReportError",
"PersistedScoutReport",
+ "ScoutReportAlreadyEmittedError",
"ScoutReportSignal",
"append_report_evidence",
"append_report_note",
"create_scout_report",
"emit_appended_report_evidence",
+ "find_scout_report_by_idempotency_key",
"get_scout_report_signal_count",
"get_scout_report_status",
"get_scout_report_title",
diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.py
index b6c9579e0a52..5946f07dba22 100644
--- a/products/signals/backend/scout_report/persistence.py
+++ b/products/signals/backend/scout_report/persistence.py
@@ -31,7 +31,7 @@ from dataclasses import dataclass, field
from datetime import datetime
from functools import partial
-from django.db import transaction
+from django.db import IntegrityError, transaction
from django.db.models import F
from django.utils import timezone
@@ -84,6 +84,26 @@ class InvalidScoutReportError(ValueError):
"""The caller tried to author/edit a report with an invalid shape (empty title, no signals, ...)."""
+@dataclass(frozen=True)
+class ExistingScoutReport:
+ """A report an `idempotency_key` already resolves to, and the status it currently holds."""
+
+ report_id: str
+ status: SignalReport.Status
+
+
+class ScoutReportAlreadyEmittedError(Exception):
+ """`create_scout_report` was called with an `idempotency_key` a report already holds.
+
+ Not an error the caller has to fix: it is how the emit path learns that this emission already
+ landed, so it can return the first report instead of authoring a twin. Carries the report the key
+ resolves to."""
+
+ def __init__(self, existing: ExistingScoutReport) -> None:
+ super().__init__(f"report {existing.report_id} already holds this idempotency key")
+ self.existing = existing
+
+
@dataclass(frozen=True)
class ScoutReportSignal:
"""One observation backing an authored report — written as a `signals/signal` embedding row.
@@ -131,6 +151,7 @@ def create_scout_report(
suggested_prompts: Sequence[str] = (),
emit_signals: bool = True,
run: SignalScoutRun | None = None,
+ idempotency_key: str | None = None,
) -> PersistedScoutReport:
"""Author a `SignalReport` directly plus its backing signal rows, in one report-owning transaction.
@@ -161,6 +182,12 @@ 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.
+ `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
+ that into the first report's result. Callers that pass no key keep the old behavior: every call
+ authors a report.
+
`emit_signals` gates whether the backing observations are written to `document_embeddings`. It
defaults to True; callers pass False for a report the safety judge marked unsafe (born SUPPRESSED)
so the adversarial-looking descriptions are never indexed — an unsafe report's signals must not
@@ -183,91 +210,108 @@ def create_scout_report(
document_ids = [s.document_id or str(uuid.uuid4()) for s in signals]
total_weight = sum(s.weight for s in signals)
- with transaction.atomic():
- report = SignalReport.objects.create(
- team_id=team_id,
- status=status,
- title=title,
- summary=summary,
- signal_count=len(signals),
- total_weight=total_weight,
- charts=[chart.model_dump(mode="json") for chart in charts],
- suggested_prompts=prompts,
- # Born directly in a user-visible status without passing through transition_to (which
- # stamps this for pipeline reports), so the daily report limit counts it from creation.
- first_visible_at=(
- timezone.now() if status in (SignalReport.Status.READY, SignalReport.Status.PENDING_INPUT) else None
- ),
- )
- report_id = str(report.id)
- # Provenance: every authored report carries a note marking it scout-authored, attributed to
- # the scout's task. This keeps an agentic report auditable as NOT pipeline-generated (a
- # concern raised by edit_report's any-report reach) and gives it a non-empty work log so it
- # isn't evidence-less in the UI. Written in-txn with the report so the two never diverge.
- SignalReportArtefact.append(
- team_id=team_id,
- report_id=report_id,
- content=NoteArtefact(note=_provenance_note_text(run), author=_provenance_author(run)),
- attribution=attribution,
- reevaluate_autostart=False,
- )
- # Link the authoring scout run itself as a `task_run` artefact, so the report's Runs section
- # and activity log can surface the scout's transcript — without it the run is only visible as
- # an anonymous "by agent" byline on the rows above. Written in-txn for the same no-divergence
- # reason as the note; skipped when the run isn't bridged to a resolvable task.
- if run is not None and attribution.task_id is not None:
- SignalReportArtefact.add_log(
+ try:
+ with transaction.atomic():
+ report = SignalReport.objects.create(
team_id=team_id,
- report_id=report_id,
- content=_scout_task_run_content(run, attribution.task_id),
- attribution=attribution,
- )
- # The judge verdicts that set `status`, recorded as the report's status artefacts so the
- # decision is auditable on the report (and so the inbox derives the same actionability/safety
- # state a pipeline report would). Written in-txn with the report for the same no-divergence reason.
- if safety is not None:
- SignalReportArtefact.append_status(
- team_id=team_id, report_id=report_id, content=safety, attribution=attribution
- )
- if actionability is not None:
- SignalReportArtefact.append_status(
- team_id=team_id, report_id=report_id, content=actionability, attribution=attribution
+ status=status,
+ title=title,
+ summary=summary,
+ scout_idempotency_key=idempotency_key,
+ signal_count=len(signals),
+ total_weight=total_weight,
+ charts=[chart.model_dump(mode="json") for chart in charts],
+ suggested_prompts=prompts,
+ # Born directly in a user-visible status without passing through transition_to (which
+ # stamps this for pipeline reports), so the daily report limit counts it from creation.
+ first_visible_at=(
+ timezone.now() if status in (SignalReport.Status.READY, SignalReport.Status.PENDING_INPUT) else None
+ ),
)
- # Autostart inputs (mirroring `create_custom_agent_ready_report`): the repo the fix lands in,
- # the priority, and the suggested reviewers. The reviewers append opts out of the autostart
- # re-eval hook — autostart is fired explicitly by the caller after commit, never in-txn.
- if repo_selection is not None:
- SignalReportArtefact.append_status(
- team_id=team_id, report_id=report_id, content=repo_selection, attribution=attribution
- )
- if priority is not None:
- SignalReportArtefact.append_status(
- team_id=team_id, report_id=report_id, content=priority, attribution=attribution
- )
- if suggested_reviewers is not None and len(suggested_reviewers.root) > 0:
- SignalReportArtefact.append_status(
+ report_id = str(report.id)
+ # Provenance: every authored report carries a note marking it scout-authored, attributed to
+ # the scout's task. This keeps an agentic report auditable as NOT pipeline-generated (a
+ # concern raised by edit_report's any-report reach) and gives it a non-empty work log so it
+ # isn't evidence-less in the UI. Written in-txn with the report so the two never diverge.
+ SignalReportArtefact.append(
team_id=team_id,
report_id=report_id,
- content=suggested_reviewers,
+ content=NoteArtefact(note=_provenance_note_text(run), author=_provenance_author(run)),
attribution=attribution,
reevaluate_autostart=False,
)
- # on_commit, not inline: telemetry must not fire for a rolled-back report, and it must
- # still fire when the post-commit signal emits below fail (they propagate).
- transaction.on_commit(
- partial(
- capture_suggested_reviewers_resolved,
+ # Link the authoring scout run itself as a `task_run` artefact, so the report's Runs section
+ # and activity log can surface the scout's transcript — without it the run is only visible as
+ # an anonymous "by agent" byline on the rows above. Written in-txn for the same no-divergence
+ # reason as the note; skipped when the run isn't bridged to a resolvable task.
+ if run is not None and attribution.task_id is not None:
+ SignalReportArtefact.add_log(
team_id=team_id,
report_id=report_id,
- github_logins=[entry.github_login for entry in suggested_reviewers.root if entry.github_login],
- user_uuids=[
- entry.user_uuid
- for entry in suggested_reviewers.root
- if entry.user_uuid and not entry.github_login
- ],
- source="scout",
+ content=_scout_task_run_content(run, attribution.task_id),
+ attribution=attribution,
)
- )
+ # The judge verdicts that set `status`, recorded as the report's status artefacts so the
+ # decision is auditable on the report (and so the inbox derives the same actionability/safety
+ # state a pipeline report would). Written in-txn with the report for the same no-divergence reason.
+ if safety is not None:
+ SignalReportArtefact.append_status(
+ team_id=team_id, report_id=report_id, content=safety, attribution=attribution
+ )
+ if actionability is not None:
+ SignalReportArtefact.append_status(
+ team_id=team_id, report_id=report_id, content=actionability, attribution=attribution
+ )
+ # Autostart inputs (mirroring `create_custom_agent_ready_report`): the repo the fix lands in,
+ # the priority, and the suggested reviewers. The reviewers append opts out of the autostart
+ # re-eval hook — autostart is fired explicitly by the caller after commit, never in-txn.
+ if repo_selection is not None:
+ SignalReportArtefact.append_status(
+ team_id=team_id, report_id=report_id, content=repo_selection, attribution=attribution
+ )
+ if priority is not None:
+ SignalReportArtefact.append_status(
+ team_id=team_id, report_id=report_id, content=priority, attribution=attribution
+ )
+ if suggested_reviewers is not None and len(suggested_reviewers.root) > 0:
+ SignalReportArtefact.append_status(
+ team_id=team_id,
+ report_id=report_id,
+ content=suggested_reviewers,
+ attribution=attribution,
+ reevaluate_autostart=False,
+ )
+ # on_commit, not inline: telemetry must not fire for a rolled-back report, and it must
+ # still fire when the post-commit signal emits below fail (they propagate).
+ transaction.on_commit(
+ partial(
+ capture_suggested_reviewers_resolved,
+ team_id=team_id,
+ report_id=report_id,
+ github_logins=[entry.github_login for entry in suggested_reviewers.root if entry.github_login],
+ user_uuids=[
+ entry.user_uuid
+ for entry in suggested_reviewers.root
+ if entry.user_uuid and not entry.github_login
+ ],
+ source="scout",
+ )
+ )
+ except IntegrityError:
+ # A concurrent emit of the same emission won the race, so this transaction rolled back. Hand
+ # its report back: the loser is a retry, and it wants the twin it just avoided creating.
+ existing = (
+ find_scout_report_by_idempotency_key(team_id=team_id, idempotency_key=idempotency_key)
+ if idempotency_key is not None
+ else None
+ )
+ if existing is None:
+ raise
+ logger.info(
+ "signals_scout.emit_report: idempotency key already held",
+ extra={"team_id": team_id, "report_id": existing.report_id},
+ )
+ raise ScoutReportAlreadyEmittedError(existing) from None
# Committed: now emit the backing signals (unless suppressed-unsafe — see `emit_signals`).
# Sequential (not on_commit) so the call is observable and so a Kafka failure surfaces to the
@@ -297,6 +341,19 @@ def create_scout_report(
)
+def find_scout_report_by_idempotency_key(*, team_id: int, idempotency_key: str) -> ExistingScoutReport | None:
+ """The report an emit key already authored for this team, or None when the key is unused."""
+ row = (
+ SignalReport.objects.filter(team_id=team_id, scout_idempotency_key=idempotency_key)
+ .values_list("id", "status")
+ .first()
+ )
+ if row is None:
+ return None
+ report_id, report_status = row
+ return ExistingScoutReport(report_id=str(report_id), status=SignalReport.Status(report_status))
+
+
def get_scout_report_title(*, team_id: int, report_id: str) -> str | None:
"""Team-scoped title lookup, for the edit-path event telemetry: an edit that doesn't rewrite the
title still needs the report's effective title to classify the lifecycle event (self-improvement
diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.py
index 6550897a4b69..7c26f72340a5 100644
--- a/products/signals/backend/test/test_scout_report_api.py
+++ b/products/signals/backend/test/test_scout_report_api.py
@@ -132,6 +132,59 @@ class TestScoutReportAPI(APIBaseTest):
assert SignalReport.objects.filter(id=body["report_id"], team=self.team).exists()
embed_mock.assert_called_once()
+ def test_emit_report_retry_returns_the_first_report(self) -> None:
+ # The failure this exists for: the caller times out at a proxy, the server keeps working, and
+ # the scout resends. The resend reads its report back instead of doubling it, judge unpaid.
+ run = _make_run(self.team)
+ with _safe_judge() as judge, patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()) as autostart:
+ first = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ with patch(CAPTURE_PATH) as capture:
+ retry = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ assert retry["report_id"] == first["report_id"]
+ assert retry["idempotent_replay"] is True
+ assert retry["emitted"] is True
+ assert first["idempotent_replay"] is False
+ assert SignalReport.objects.filter(team=self.team).count() == 1
+ judge.assert_awaited_once()
+ # The report already surfaced, so its draft PR must not be started a second time.
+ autostart.assert_awaited_once()
+ event = next(c for c in capture.call_args_list if c.kwargs["event"] == "signals_scout_report_emitted")
+ assert event.kwargs["properties"]["outcome"] == "idempotent_replay"
+
+ def test_emit_report_key_covers_a_retry_that_rewords_the_report(self) -> None:
+ # Without a key the content is the key, so a scout that rewrites its summary on the retry would
+ # file twice. Naming the emission is what makes the second call resolve to the first report.
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH):
+ first = self.client.post(
+ self._emit_url(str(run.id)),
+ data=self._payload(idempotency_key="checkout-p99"),
+ format="json",
+ ).json()
+ retry = self.client.post(
+ self._emit_url(str(run.id)),
+ data=self._payload(summary="Reworded: p99 on /checkout doubled.", idempotency_key="checkout-p99"),
+ format="json",
+ ).json()
+ assert retry["report_id"] == first["report_id"]
+ assert retry["idempotent_replay"] is True
+ assert SignalReport.objects.filter(team=self.team).count() == 1
+
+ def test_emit_report_still_authors_a_second_report_for_a_different_finding(self) -> None:
+ # The barrier must not swallow a real second finding: one run routinely reports more than one
+ # thing, and those calls differ in content and (when supplied) in key.
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH):
+ first = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ second = self.client.post(
+ self._emit_url(str(run.id)),
+ data=self._payload(title="Signup funnel dropped 12% after 4.2"),
+ format="json",
+ ).json()
+ assert second["report_id"] != first["report_id"]
+ assert second["idempotent_replay"] is False
+ assert SignalReport.objects.filter(team=self.team).count() == 2
+
def test_report_emit_and_edit_enqueue_configured_slack_destination_after_commit(self) -> None:
run = _make_run(self.team)
config = run.scout_config
diff --git a/products/signals/backend/test/test_scout_report_persistence.py b/products/signals/backend/test/test_scout_report_persistence.py
index f2eb60f3e196..5c7640ccde1f 100644
--- a/products/signals/backend/test/test_scout_report_persistence.py
+++ b/products/signals/backend/test/test_scout_report_persistence.py
@@ -34,6 +34,7 @@ from products.signals.backend.report_prompts import MAX_SUGGESTED_PROMPT_LENGTH,
from products.signals.backend.scout_harness.tools.emit import SOURCE_PRODUCT, SOURCE_TYPE
from products.signals.backend.scout_report import (
InvalidScoutReportError,
+ ScoutReportAlreadyEmittedError,
ScoutReportSignal,
create_scout_report,
set_report_charts,
@@ -109,6 +110,33 @@ class TestScoutReportPersistence(BaseTest):
report = SignalReport.objects.get(id=result.report_id)
assert (report.first_visible_at is not None) is expect_stamp
+ def test_create_refuses_a_second_report_for_a_key_one_already_holds(self) -> None:
+ # The case the emit path's own pre-check can't see: a retry arriving mid-judge passes it and
+ # reaches the insert too. The index has to stop it, and surface the first report, not a 500.
+ run = self._make_run()
+ first = create_scout_report(
+ team_id=self.team.id,
+ title="Checkout API p99 latency regressed",
+ summary="The checkout endpoint p99 doubled after the 4.2 deploy.",
+ signals=[ScoutReportSignal(description="p99 doubled on /checkout", source_id="obs-1", weight=1.0)],
+ attribution=ArtefactAttribution.from_task(str(run.task_run.task_id)),
+ run=run,
+ idempotency_key="emission-1",
+ )
+ with pytest.raises(ScoutReportAlreadyEmittedError) as raised:
+ create_scout_report(
+ team_id=self.team.id,
+ title="Checkout API p99 latency regressed",
+ summary="The checkout endpoint p99 doubled after the 4.2 deploy.",
+ signals=[ScoutReportSignal(description="p99 doubled on /checkout", source_id="obs-1", weight=1.0)],
+ attribution=ArtefactAttribution.from_task(str(run.task_run.task_id)),
+ run=run,
+ idempotency_key="emission-1",
+ )
+ assert raised.value.existing.report_id == first.report_id
+ assert raised.value.existing.status == SignalReport.Status.READY
+ assert SignalReport.objects.filter(team=self.team).count() == 1
+
def test_create_writes_report_with_bound_signals_metadata(self) -> None:
# The load-bearing contract (decision #5): each backing signal is written to the embeddings
# pipeline with report_id pre-set, as a signals/signal row, so every read-side consumer
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index e3aab9b52784..47fbf802b81b 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -3775,6 +3775,12 @@ export interface EmitReportRequestApi {
* @items.maxLength 200
*/
suggested_prompts?: string[]
+ /**
+ * 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
+ * @nullable
+ */
+ idempotency_key?: string | null
}
export interface EmitReportResponseApi {
@@ -3805,6 +3811,8 @@ export interface EmitReportResponseApi {
* @nullable
*/
remediation: string | null
+ /** True when this call authored nothing because the emission had already landed — the fields above describe that first report. Expected on a retry; treat the report as filed and don't send it again. */
+ idempotent_replay: boolean
}
/**
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index c82fb8cc727b..e6db88552d0d 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -1216,7 +1216,7 @@ export const getSignalsScoutEmitReportUrl = (projectId: string, runId: string) =
}
/**
- * 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.
+ * 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. 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. Use `reports` to find a report from an earlier run and `edit-report` to update it instead of authoring a near-duplicate.
* @summary Author a full report for a run
*/
export const signalsScoutEmitReport = async (
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 118e03b348b2..09fe00da7030 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -1167,7 +1167,7 @@ export const SignalsScoutEditReportBody = /* @__PURE__ */ zod
)
/**
- * 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.
+ * 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. 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. Use `reports` to find a report from an earlier run and `edit-report` to update it instead of authoring a near-duplicate.
* @summary Author a full report for a run
*/
export const signalsScoutEmitReportBodyTitleMax = 300
@@ -1193,6 +1193,8 @@ export const signalsScoutEmitReportBodySuggestedPromptsItemMax = 200
export const signalsScoutEmitReportBodySuggestedPromptsMax = 3
+export const signalsScoutEmitReportBodyIdempotencyKeyMax = 200
+
export const SignalsScoutEmitReportBody = /* @__PURE__ */ zod
.object({
title: zod
@@ -1350,6 +1352,13 @@ 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."
),
+ idempotency_key: zod
+ .string()
+ .max(signalsScoutEmitReportBodyIdempotencyKeyMax)
+ .nullish()
+ .describe(
+ "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."
+ ),
})
.describe('Request body for `emit-report`. Run attribution is taken from the URL path.')
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index 94fead53f6da..e3f6c6f003b2 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -550,7 +550,7 @@ tools:
annotations:
readOnly: false
destructive: false
- idempotent: false
+ idempotent: true
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
@@ -558,14 +558,17 @@ tools:
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 `scout-edit-report` to update it instead. `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. Opt-in: only available to scouts that
- list `emit_report` in their skill's `allowed_tools`.
+ 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. 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/products/signals/skills/authoring-scouts/references/report-contract.md b/products/signals/skills/authoring-scouts/references/report-contract.md
index 22e9c82fbe4e..fd4c8f26f4f4 100644
--- a/products/signals/skills/authoring-scouts/references/report-contract.md
+++ b/products/signals/skills/authoring-scouts/references/report-contract.md
@@ -261,11 +261,14 @@ Before authoring, list the team's existing reports so you reconcile against one
- `inbox-reports-list` — filter by title/summary free-text (`search`), `status`, `source_product`, or your own `task_id`; newest-updated first.
- `inbox-reports-retrieve` — fetch a single report by id (use the `report_id` you stashed in the scratchpad last run).
-## Dedup: the channel is NOT idempotent
+## Dedup: the retry is covered, the near-duplicate is not
-`emit_report` is **not idempotent** — a retried call authors a _second_ report.
-There is no server-side dedup key.
-The dedup story is two-sided and the scout owns it:
+`emit_report` carries an emit key, so resending a call that timed out returns the report the first one authored (`idempotent_replay` true) rather than a twin.
+The key is the `idempotency_key` you pass, or the report's own content when you pass none, and it is scoped to your run.
+Pass one when a retry might reword the report, since a reworded report is a different content key.
+
+That barrier covers the transport failure and nothing else.
+A report on a topic an earlier run already filed is a fresh emission with a fresh key, so the cross-run dedup is still two-sided and the scout owns it:
1. **Before authoring**, `inbox-reports-list` for a prior report on the same topic.
Found one?
@@ -273,8 +276,8 @@ The dedup story is two-sided and the scout owns it:
2. **After authoring**, write a `report:<domain>:<entity>` scratchpad entry recording the `report_id` so the next run finds it (via `inbox-reports-retrieve`) without a title-search guess.
(This is the report-channel member of the scratchpad key-prefix vocabulary — see [`dedupe-and-memory.md`](dedupe-and-memory.md).)
-**Never retry an `emit_report` / `edit_report` call that may have succeeded** — a transport error after the write commits, retried, double-files.
-If you're unsure whether a call landed, `inbox-reports-list` to check before retrying.
+`edit_report` has no such barrier: **never retry an `edit_report` call that may have succeeded**, since a transport error after the write commits, retried, appends a second note.
+If you're unsure whether an edit landed, `inbox-reports-retrieve` to check before retrying.
## The pipeline may rewrite what you authored (accepted)
diff --git a/products/signals/skills/authoring-scouts/references/scout-patterns.md b/products/signals/skills/authoring-scouts/references/scout-patterns.md
index 4307179eea31..6e2befa1876c 100644
--- a/products/signals/skills/authoring-scouts/references/scout-patterns.md
+++ b/products/signals/skills/authoring-scouts/references/scout-patterns.md
@@ -418,7 +418,7 @@ Proven shapes: a daily LLM-analytics digest (latency / errors / clusters / cost
Score every section as the latest window vs the team's own trailing like-for-like baseline, lead with anything urgent, and keep steady-state items to one line.
(One exception to "always emittable": if the watched surface isn't in use at all, write a `not-in-use:<domain>` memory and skip the digest entirely — don't post an empty report.)
- **Channel + cadence:** the report channel (`emit_report`), **exactly one report per calendar day**.
- Before emitting, check `dedupe:<domain>:{date}` in the scratchpad **and** `inbox-reports-list` — `emit_report` is not idempotent, so a same-day re-run must skip, and an emit that may have already landed must never be retried.
+ Before emitting, check `dedupe:<domain>:{date}` in the scratchpad **and** `inbox-reports-list` — the emit key only covers a retry of the same call within one run, so a same-day re-run must skip rather than file the finding again.
After emitting, record `report:<domain>:{date}` with the returned `report_id` and `dedupe:<domain>:{date}`.
- **Memory is what lets it speak in deltas.** A cursor (`pattern:<domain>:cursor` — the timestamp the last digest covered through) windows each run; baseline snapshots (`pattern:<domain>:cost-baseline`, `:latency-bands`, a cluster/state snapshot) let the digest say what moved rather than what is; `noise:` entries fold known recurring things (a nightly batch spike, a deliberate model swap) in as context instead of re-raising them.
- **Budget discipline is load-bearing.** The digest has a fixed section structure and a hard run budget, so query economically: one combined SQL returning several sections' numbers beats one query per section, and a shallow digest that posts beats a thorough one that times out.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index e061e7f90621..d75cd3c50866 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -9749,7 +9749,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. NOT idempotent — a retry authors a second report; use `inbox-reports-list` to find a prior report and `scout-edit-report` to update it instead. `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. 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. 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",
@@ -9757,7 +9757,7 @@
"required_scopes": ["signal_scout_report:write"],
"annotations": {
"destructiveHint": false,
- "idempotentHint": false,
+ "idempotentHint": true,
"openWorldHint": true,
"readOnlyHint": false
}
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 622281a3ba9c..205af90e5aa2 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -10321,7 +10321,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. NOT idempotent — a retry authors a second report; use `inbox-reports-list` to find a prior report and `scout-edit-report` to update it instead. `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. 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. 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",
@@ -10329,7 +10329,7 @@
"required_scopes": ["signal_scout_report:write"],
"annotations": {
"destructiveHint": false,
- "idempotentHint": false,
+ "idempotentHint": true,
"openWorldHint": true,
"readOnlyHint": false
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 15ba82f33371..cffb47ad0370 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -31354,6 +31354,12 @@ export namespace Schemas {
* @items.maxLength 200
*/
suggested_prompts?: string[];
+ /**
+ * 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
+ * @nullable
+ */
+ idempotency_key?: string | null;
}
export interface EmitReportResponse {
@@ -31384,6 +31390,8 @@ export namespace Schemas {
* @nullable
*/
remediation: string | null;
+ /** True when this call authored nothing because the emission had already landed — the fields above describe that first report. Expected on a retry; treat the report as filed and don't send it again. */
+ idempotent_replay: boolean;
}
export interface EndExperiment {
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 0fe321c63262..08c2b200431f 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -1615,7 +1615,7 @@ export const SignalsScoutRunsEmissionReportsParams = () => zod.object({
})
/**
- * 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.
+ * 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. 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. Use `reports` to find a report from an earlier run and `edit-report` to update it instead of authoring a near-duplicate.
* @summary Author a full report for a run
*/
export const SignalsScoutEmitReportParams = () => zod.object({
@@ -1650,6 +1650,8 @@ export const signalsScoutEmitReportBodySuggestedPromptsItemMax = 200
export const signalsScoutEmitReportBodySuggestedPromptsMax = 3
+export const signalsScoutEmitReportBodyIdempotencyKeyMax = 200
+
export const SignalsScoutEmitReportBody = () => zod
.object({
title: zod
@@ -1807,6 +1809,13 @@ 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."
),
+ idempotency_key: zod
+ .string()
+ .max(signalsScoutEmitReportBodyIdempotencyKeyMax)
+ .nullish()
+ .describe(
+ "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."
+ ),
})
.describe('Request body for `emit-report`. Run attribution is taken from the URL path.')
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 3b4f95f5233d..e26af2ca2710 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -930,6 +930,9 @@ const scoutEmitReport = (): ToolBase<ReturnType<typeof ScoutEmitReportSchema>, S
if (params.suggested_prompts !== undefined) {
body['suggested_prompts'] = params.suggested_prompts
}
+ if (params.idempotency_key !== undefined) {
+ body['idempotency_key'] = params.idempotency_key
+ }
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/`,
@@ -1675,6 +1678,9 @@ const signalsScoutEmitReport = (): ToolBase<
if (params.suggested_prompts !== undefined) {
body['suggested_prompts'] = params.suggested_prompts
}
+ if (params.idempotency_key !== undefined) {
+ body['idempotency_key'] = params.idempotency_key
+ }
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/`,