Skip to content

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

feat(signals): allow resolving inbox reports via the state API (#71986)

Alex Lebedev9900bfe067c3
diff --git a/frontend/src/scenes/inbox/components/cards/ReportCard.tsx b/frontend/src/scenes/inbox/components/cards/ReportCard.tsx
index 572a2d579237..cab8eb638897 100644
--- a/frontend/src/scenes/inbox/components/cards/ReportCard.tsx
+++ b/frontend/src/scenes/inbox/components/cards/ReportCard.tsx
@@ -85,9 +85,9 @@ export function InboxCardSourceMeta({
/**
* PR open/merged/closed state, mapped to muted palette tags (outlined: --success / --purple /
- * --danger). We have no real PR status from GitHub on the report, so it's inferred from the
- * report status: a resolved report means its implementation PR merged (webhook-driven on merge),
- * a failed one means the PR never landed, everything else is still an open PR.
+ * --danger). "merged" comes from `implementation_pr_merged`, the flag the GitHub webhook sets on
+ * merge — report status can't stand in for it, since a report can be resolved directly without its
+ * PR ever landing. A failed report means the PR never landed; everything else is still an open PR.
*/
const PR_BADGE_STATE: Record<'open' | 'merged' | 'closed', { label: string; type: LemonTagType }> = {
open: { label: 'open', type: 'success' },
@@ -97,8 +97,8 @@ const PR_BADGE_STATE: Record<'open' | 'merged' | 'closed', { label: string; type
type PrBadgeState = keyof typeof PR_BADGE_STATE
-function derivePrState(status: SignalReportStatus): PrBadgeState {
- if (status === SignalReportStatus.RESOLVED) {
+function derivePrState(status: SignalReportStatus, prMerged: boolean): PrBadgeState {
+ if (prMerged) {
return 'merged'
}
if (status === SignalReportStatus.FAILED) {
@@ -220,7 +220,11 @@ export function ReportCard({
<div className={clsx('relative', inboxCardRowClassName(attached, { dashed: !hasPr }))}>
{hasPr && prNumber != null ? (
<div className="absolute right-4 top-3 z-10">
- <PrBadge prNumber={prNumber} prUrl={prUrl} state={derivePrState(report.status)} />
+ <PrBadge
+ prNumber={prNumber}
+ prUrl={prUrl}
+ state={derivePrState(report.status, report.implementation_pr_merged === true)}
+ />
</div>
) : null}
diff --git a/frontend/src/scenes/inbox/components/detail/ReportDetailActions.tsx b/frontend/src/scenes/inbox/components/detail/ReportDetailActions.tsx
index 4f7ee5d695e1..bbd955615b57 100644
--- a/frontend/src/scenes/inbox/components/detail/ReportDetailActions.tsx
+++ b/frontend/src/scenes/inbox/components/detail/ReportDetailActions.tsx
@@ -69,8 +69,12 @@ export function useReportDetailActions(report: SignalReport): ReportDetailAction
const showCreatePr = canCreateImplementationPr(report)
const isArchived = report.status === SignalReportStatus.SUPPRESSED
- // Resolved reports are terminal (their implementation PR merged) – nothing to archive, restore, or kick off.
+ // Resolved reports are terminal – nothing to archive, restore, or kick off.
const isResolved = report.status === SignalReportStatus.RESOLVED
+ // Refund leaves a report in place only when a merged PR resolved it; anything else it archives
+ // (so the open PR gets closed), which means the view has to navigate away. Mirrors the
+ // `resolved_via_merged_pr` branch in the refund endpoint.
+ const staysPutOnRefund = isResolved && report.implementation_pr_merged === true
const { isArchiving, onArchiveClick } = useReportArchive({
reportId: report.id,
@@ -92,10 +96,10 @@ export function useReportDetailActions(report: SignalReport): ReportDetailAction
// return to the list — except for resolved reports, which stay where they are.
onRefunded: () => {
reportArchived()
- if (report.status !== SignalReportStatus.RESOLVED) {
+ if (!staysPutOnRefund) {
router.actions.push(urls.inbox(activeTab))
} else {
- // Resolved reports stay on this page, so refetch: the fresh copy carries `refund`,
+ // These reports stay on this page, so refetch: the fresh copy carries `refund`,
// which surfaces the Refunded badge and drops Refund from the actions.
loadSelectedReport({ id: report.id })
}
diff --git a/frontend/src/scenes/inbox/types.ts b/frontend/src/scenes/inbox/types.ts
index 59b616244104..140dc3ce5675 100644
--- a/frontend/src/scenes/inbox/types.ts
+++ b/frontend/src/scenes/inbox/types.ts
@@ -83,6 +83,9 @@ export interface SignalReport {
scout_name?: string | null
/** PR URL from the latest implementation task run, if available. */
implementation_pr_url?: string | null
+ /** Whether that implementation PR is merged, per the GitHub webhook. Status doesn't imply it: a
+ * resolved report may have been resolved directly, without a merged PR. */
+ implementation_pr_merged?: boolean
/** Reason code from the latest dismissal artefact (when archived). See dismissalReasons. */
dismissal_reason?: string | null
/** Free-form note from the latest dismissal artefact (when archived). */
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 00bc646ea24a..2d9395e0ce8c 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -695,7 +695,7 @@ SPECTACULAR_SETTINGS = {
# SignalReportBulkStateRequest) that both expose the same `state` ChoiceField. Pin the
# shared enum to a stable name so it doesn't collide with the other `state` enums
# (tasks, cdp) into a component-prefixed auto-name.
- "SignalReportStateEnum": ["suppressed", "potential"],
+ "SignalReportStateEnum": ["suppressed", "potential", "resolved"],
# Two serializers now expose an `op` ChoiceField (metrics filters and email-template design
# patches). Pin both to stable names so neither gets a component-prefixed auto-name on collision.
# "OpEnum" keeps the metrics filter enum at its pre-existing generated name.
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index a1f093674bc5..668899ed8bb6 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -209,7 +209,7 @@ Bulk sync (`sync_full_cache`) fans the per-repo sync out via `run_parallel_with_
Reports are re-promoted when new evidence arrives. A `READY` / `RESOLVED` report re-promotes on every new matching signal (so research reruns with the latest evidence), and a report reset to `potential` re-promotes once it clears the `signals_at_run` snooze gate again.
-**Re-research cap.** The research activity reads every non-deleted signal, so re-research cost scales with report size. Once an already-researched report exceeds `RERESEARCH_MAX_SIGNALS` (`SIGNAL_RERESEARCH_MAX_SIGNALS`, default 10), `READY` / `RESOLVED` re-promotion is suppressed: new signals are still assigned, weighted, and emitted, but no new summary run spawns. The cap is enforced in two places: the grouping promotion gate (`assign_and_emit_signal_activity`), which fires the `signal_report_reresearch_skipped` event per suppressed signal so the saved volume is trackable, and the summary self-loop (`mark_report_ready_activity`), which stops an in-flight run from looping into another research pass (no event — this is a rare mid-run edge).
+**Re-research cap.** The research activity reads every non-deleted signal, so re-research cost scales with report size. Once an already-researched report exceeds `RERESEARCH_MAX_SIGNALS` (`SIGNAL_RERESEARCH_MAX_SIGNALS`, default 10), `READY` re-promotion is suppressed: new signals are still assigned, weighted, and emitted, but no new summary run spawns. The cap is enforced in two places: the grouping promotion gate (`assign_and_emit_signal_activity`), which fires the `signal_report_reresearch_skipped` event per suppressed signal so the saved volume is trackable, and the summary self-loop (`mark_report_ready_activity`), which stops an in-flight run from looping into another research pass (no event — this is a rare mid-run edge).
The cap covers **only** the `READY` / `RESOLVED` path (the one that re-promotes on every signal). Re-promotions through the `potential` gate stay uncapped — first research, `candidate` self-heal, snooze return, and a not-actionable reset re-accumulating weight — because they are weight / `signals_at_run`-gated rather than per-signal, so strong new evidence can still resurface a large report.
@@ -354,11 +354,31 @@ potential → candidate → in_progress → ready
# Re-promotion: READY reports are re-promoted to candidate on each new matching signal,
# triggering a new summary run that reuses the previous repo selection and findings for
# already-seen signals. Suppressed once signal_count > RERESEARCH_MAX_SIGNALS (see Re-research cap).
+# RESOLVED is terminal and never re-promotes: a recurrence spawns a fresh report, linked back to the
+# resolved one via a related_to artefact (assign_and_emit_signal_activity).
ready → candidate
+# Resolve: a report is marked resolved when the requested work is done. Two paths:
+# - automatic: the tasks GitHub webhook resolves a report when its linked implementation PR merges
+# - user-driven: the state API accepts state='resolved' (single + bulk) so a user or MCP agent
+# can resolve directly — useful for PR-less fixes (skill-body changes, NO_REPO reports) that the
+# webhook could never reach. Restricted to the same statuses the machine allows below.
+ready | pending_input → resolved
+suppressed → resolved (resolve an archived report straight out of the archive; the state action
+ refuses this unless it was researched before being archived, so an unresearched
+ report can't be laundered candidate → suppressed → resolved)
+
+# Refund interaction: a refund is final (later PR runs are never billed). The refund path suppresses
+# the report so it leaves the inbox and the dismissal receiver closes the implementation PR that was
+# paid for and then refunded — including a manually-resolved one, whose PR may still be open. Only a
+# report resolved by a merged PR stays resolved (nothing to close). The state action then refuses to
+# move a refunded report back to potential — the live status the pipeline re-promotes from — whether
+# it sits in suppressed or resolved, and refuses to resolve it back out of the archive.
+
# Transitions enforced by SignalReport.transition_to():
# - deleted is terminal (no transitions out; excluded from API via queryset)
-# - suppressed only transitions back to potential
+# - suppressed transitions back to potential, or straight to the researched status it held before
+# being archived (ready | pending_input | resolved | failed) — see restore_target_status()
# - any non-deleted status can transition to deleted or suppressed
# - snooze = transition to potential with snooze_for=N (sets signals_at_run = signal_count + N)
suppressed → potential
@@ -745,16 +765,16 @@ Notes:
Read + delete + state transitions. Uses `IsAuthenticated` + `APIScopePermission` (scope: `task`). Composed from `RetrieveModelMixin`, `ListModelMixin`, `DestroyModelMixin`, and `GenericViewSet`. Deleted reports are excluded from all endpoints via `safely_get_queryset`.
-| Method | Path | Description |
-| ------ | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| GET | `signals/reports/` | List reports. Excludes `deleted` always and excludes `suppressed` by default. Supports `?status=`, `?search=`, `?source_product=`, `?suggested_reviewers=`, `?task_id=` (resolved through `task_run` artefacts), and `?ordering=`. |
-| GET | `signals/reports/{id}/` | Retrieve a single report |
-| DELETE | `signals/reports/{id}/` | Soft-delete a report and its signals. Starts `SignalReportDeletionWorkflow`. On success returns `202`. If the workflow is already running, returns `200 {"status": "already_running"}`. The API immediately transitions the Postgres report to `deleted` to hide it from list results while ClickHouse cleanup runs asynchronously. |
-| POST | `signals/reports/{id}/state/` | Transition report state. Body: `{ "state": "suppressed" \| "potential", ...transition_to kwargs }`. Only `suppressed` and `potential` are exposed via API. Returns `409` on invalid transitions and `400` on invalid arguments. |
-| POST | `signals/reports/{id}/reingest/` | Delete a report and re-ingest its signals. Starts `SignalReportReingestionWorkflow`. On success returns `202`. If already running, returns `200 {"status": "already_running"}`. Same team access as other report endpoints; personal API keys need `task:write`. |
-| GET | `signals/reports/{id}/artefacts/` | List **all** artefacts for a report, ordered by `-created_at` |
-| GET | `signals/reports/{id}/signals/` | Fetch all signals for a report from ClickHouse, including full metadata |
-| GET | `signals/reports/available_reviewers/` | List available suggested reviewers for the team |
+| Method | Path | Description |
+| ------ | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| GET | `signals/reports/` | List reports. Excludes `deleted` always and excludes `suppressed` by default. Supports `?status=`, `?search=`, `?source_product=`, `?suggested_reviewers=`, `?task_id=` (resolved through `task_run` artefacts), and `?ordering=`. |
+| GET | `signals/reports/{id}/` | Retrieve a single report |
+| DELETE | `signals/reports/{id}/` | Soft-delete a report and its signals. Starts `SignalReportDeletionWorkflow`. On success returns `202`. If the workflow is already running, returns `200 {"status": "already_running"}`. The API immediately transitions the Postgres report to `deleted` to hide it from list results while ClickHouse cleanup runs asynchronously. |
+| POST | `signals/reports/{id}/state/` | Transition report state. Body: `{ "state": "suppressed" \| "potential" \| "resolved", ...transition_to kwargs }`. `suppressed`, `potential`, and `resolved` are exposed via API (`resolved` for user-driven "work is done"; the model still gates which statuses may resolve). Returns `409` on invalid transitions and `400` on invalid arguments. |
+| POST | `signals/reports/{id}/reingest/` | Delete a report and re-ingest its signals. Starts `SignalReportReingestionWorkflow`. On success returns `202`. If already running, returns `200 {"status": "already_running"}`. Same team access as other report endpoints; personal API keys need `task:write`. |
+| GET | `signals/reports/{id}/artefacts/` | List **all** artefacts for a report, ordered by `-created_at` |
+| GET | `signals/reports/{id}/signals/` | Fetch all signals for a report from ClickHouse, including full metadata |
+| GET | `signals/reports/available_reviewers/` | List available suggested reviewers for the team |
**Ordering:** Configurable via `?ordering=` with comma-separated fields. Supported fields: `status`, `is_suggested_reviewer`, `signal_count`, `total_weight`, `priority`, `created_at`, `updated_at`, `id`.
diff --git a/products/signals/backend/billing.py b/products/signals/backend/billing.py
index fefc8c2f5d0a..15b7e69a86e3 100644
--- a/products/signals/backend/billing.py
+++ b/products/signals/backend/billing.py
@@ -207,6 +207,32 @@ def first_billable_pr_run_at(report_id: str | uuid.UUID) -> datetime | None:
return run.created_at if run else None
+def report_pr_is_merged(report_id: str | uuid.UUID, pr_url: str) -> bool:
+ """Whether *this* PR of the report merged, per the tasks GitHub webhook.
+
+ Reads `output.pr_merged`, the flag the webhook persists when a PR merges — the factual record of
+ a merge, independent of report status. A report can now reach RESOLVED without a merged PR (a
+ user or agent can resolve it directly), so status alone no longer attests a merge.
+
+ Scoped to one `pr_url` rather than the whole report, because the caller is deciding about a
+ specific PR: the refund reverses the charge for the billable run's PR, and it's that PR which
+ must be closed if it never merged. A report-level check would let an unrelated later PR that did
+ merge vouch for the refunded one, leaving the refunded PR open.
+
+ Fail closed like `_bridges_with_pr_run`: the PR URL, the merge flag, and the four team checks all
+ sit in one `filter()` so they resolve against the same `TaskRun` row.
+ """
+ return SignalReportTask.objects.filter(
+ relationship=_IMPLEMENTATION,
+ report_id=report_id,
+ task__team_id=F("team_id"),
+ report__team_id=F("team_id"),
+ task__runs__team_id=F("team_id"),
+ task__runs__output__pr_url=pr_url,
+ task__runs__output__pr_merged=True,
+ ).exists()
+
+
def annotate_first_billable_pr_run_at(queryset: QuerySet[SignalReport]) -> QuerySet[SignalReport]:
"""Annotate each report with `first_billable_pr_run_at` (its billable moment, batched form of
`first_billable_pr_run`), NULL when it never shipped a billable PR run. Applies the same
diff --git a/products/signals/backend/implementation_pr.py b/products/signals/backend/implementation_pr.py
index d5c0f0e2340f..d43edba24703 100644
--- a/products/signals/backend/implementation_pr.py
+++ b/products/signals/backend/implementation_pr.py
@@ -1,5 +1,6 @@
"""Resolve implementation PR URLs linked to signal reports."""
+from dataclasses import dataclass
from typing import Literal, cast
import structlog
@@ -14,13 +15,26 @@ from products.tasks.backend.facade import api as tasks_facade
logger = structlog.get_logger(__name__)
-def fetch_implementation_pr_urls_for_reports(report_ids: list[str]) -> dict[str, str]:
- """PR URL from the latest implementation task run for each report, when available.
+@dataclass(frozen=True)
+class ImplementationPr:
+ """The one implementation PR surfaced for a report, and whether the webhook saw it merge."""
+
+ url: str
+ merged: bool
+
+
+def fetch_implementation_pr_state_for_reports(report_ids: list[str]) -> dict[str, ImplementationPr]:
+ """The implementation PR surfaced for each report, with its merge state, when one exists.
The task↔report association comes from `SignalReport.associated_task_runs_for_reports` (the
unified view of the `task_run` artefact log + legacy gate rows, batched over the whole page);
the facade then resolves the latest PR-bearing run for each task, so multiple runs of a task
collapse to the newest PR.
+
+ A report can be associated with several implementation tasks (retries), but only one PR is
+ surfaced — the first associated task that has one. The merge flag is read from *that* task, so
+ the URL and its state always describe the same PR. Reading them independently would let a
+ retry's merged PR vouch for a different PR's URL.
"""
if not report_ids:
return {}
@@ -38,16 +52,23 @@ def fetch_implementation_pr_urls_for_reports(report_ids: list[str]) -> dict[str,
if not pairs:
return {}
- pr_url_by_task = tasks_facade.get_latest_pr_url_by_task([task_id for _, task_id in pairs])
+ task_ids = [task_id for _, task_id in pairs]
+ pr_url_by_task = tasks_facade.get_latest_pr_url_by_task(task_ids)
+ merged_task_ids = tasks_facade.get_merged_pr_task_ids(task_ids)
- result: dict[str, str] = {}
+ result: dict[str, ImplementationPr] = {}
for report_id, task_id in pairs:
pr_url = pr_url_by_task.get(task_id)
if pr_url and report_id not in result:
- result[report_id] = pr_url
+ result[report_id] = ImplementationPr(url=pr_url, merged=task_id in merged_task_ids)
return result
+def fetch_implementation_pr_urls_for_reports(report_ids: list[str]) -> dict[str, str]:
+ """PR URL from the latest implementation task run for each report, when available."""
+ return {report_id: pr.url for report_id, pr in fetch_implementation_pr_state_for_reports(report_ids).items()}
+
+
PrCloseReason = Literal["suppressed", "snoozed"]
# Left on the PR before it's closed, so anyone looking at the PR sees why it was closed and how to undo it.
diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.py
index 16c2a3f7a956..96433f2cbd23 100644
--- a/products/signals/backend/receivers.py
+++ b/products/signals/backend/receivers.py
@@ -149,6 +149,11 @@ def capture_status_change_analytics(
new_status = instance.status
team = instance.team
transition_at = timezone.now()
+ # Set by the state API when this same request is about to write a dismissal artefact. Read here
+ # rather than inferred from the transition, because a resolve carries feedback only when the
+ # caller supplied it — a PR-merge resolve from the tasks webhook writes none, and must not pick
+ # up an unrelated earlier reason that happens to fall inside the freshness window.
+ wrote_dismissal_feedback = bool(getattr(instance, "_wrote_dismissal_feedback", False))
def _capture() -> None:
try:
@@ -175,7 +180,8 @@ def capture_status_change_analytics(
"previous_status": previous_status,
**_classification_snapshot(
report_id,
- include_dismissal=_is_dismissal_transition(previous_status, new_status),
+ include_dismissal=wrote_dismissal_feedback
+ or _is_dismissal_transition(previous_status, new_status),
transition_at=transition_at,
),
},
@@ -201,8 +207,13 @@ _SNAPSHOT_ARTEFACT_FIELDS = [
def _is_dismissal_transition(previous_status: str, new_status: str) -> bool:
- """Whether this transition is one the state API writes dismissal feedback for: a dismissal
- (into suppressed) or a snooze (researched report back to potential)."""
+ """Whether this transition inherently carries dismissal feedback: a dismissal (into suppressed)
+ or a snooze (researched report back to potential).
+
+ Resolve is deliberately absent. It carries feedback only when the caller supplied a reason or
+ note, which the state API signals explicitly via `_wrote_dismissal_feedback` — a resolve driven
+ by the tasks PR-merge webhook writes none, and inferring it from the status would attach
+ whatever unrelated reason last landed inside the freshness window."""
return new_status == SignalReport.Status.SUPPRESSED or (
new_status == SignalReport.Status.POTENTIAL and previous_status in _SNOOZE_SOURCE_STATUSES
)
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 0b7e0d06e3be..8fa342c6f4a0 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -369,6 +369,13 @@ class SignalReportSerializer(serializers.ModelSerializer):
implementation_pr_url = serializers.SerializerMethodField(
help_text="PR URL from the latest implementation task run, if available.",
)
+ implementation_pr_merged = serializers.SerializerMethodField(
+ help_text=(
+ "Whether that implementation PR is merged, per the GitHub webhook. False when there is no "
+ "PR or it hasn't merged. Report status doesn't imply this: a resolved report may have been "
+ "resolved directly, without a merged PR."
+ ),
+ )
refund = serializers.SerializerMethodField(
help_text="The report's PR refund, when one exists. One refund per report, ever.",
)
@@ -395,6 +402,7 @@ class SignalReportSerializer(serializers.ModelSerializer):
"source_products",
"scout_name",
"implementation_pr_url",
+ "implementation_pr_merged",
"refund",
"refund_ineligibility_reason",
"billing_exempt_reason",
@@ -511,6 +519,14 @@ class SignalReportSerializer(serializers.ModelSerializer):
value = getattr(obj, "implementation_pr_url", None)
return value if isinstance(value, str) else None
+ def get_implementation_pr_merged(self, obj: SignalReport) -> bool:
+ merged_report_ids: set[str] | None = self.context.get("implementation_pr_merged_ids")
+ if merged_report_ids is not None:
+ return str(obj.id) in merged_report_ids
+ # Annotated path: the JSON flag arrives as text, and NULL means no PR-bearing run at all.
+ value = getattr(obj, "implementation_pr_merged", None)
+ return value in (True, "true", "True")
+
@extend_schema_field(SignalReportRefundSerializer(allow_null=True))
def get_refund(self, obj: SignalReport) -> dict | None:
# Reverse OneToOne: RelatedObjectDoesNotExist subclasses AttributeError, so getattr
diff --git a/products/signals/backend/test/test_refunds.py b/products/signals/backend/test/test_refunds.py
index d74ff5307c70..2e5b56ddae2b 100644
--- a/products/signals/backend/test/test_refunds.py
+++ b/products/signals/backend/test/test_refunds.py
@@ -221,16 +221,24 @@ class TestSignalReportRefundAPI(APIBaseTest):
report.refresh_from_db()
assert report.status == SignalReport.Status.SUPPRESSED
+ @parameterized.expand(
+ [
+ # A merged PR is a genuine terminal state — the work shipped — so refund leaves it RESOLVED.
+ ("merged_pr", {"pr_url": "https://github.com/x/y/pull/1", "pr_merged": True}, SignalReport.Status.RESOLVED),
+ # Resolved manually without a merged PR: refund must suppress it, otherwise the linked PR
+ # is never closed and the caller keeps the implementation work after being refunded.
+ ("resolved_without_merge", {"pr_url": "https://github.com/x/y/pull/1"}, SignalReport.Status.SUPPRESSED),
+ ]
+ )
@freeze_time(_NOW)
- def test_refund_keeps_resolved_report_resolved(self, _flag):
- report = self._report_with_pr(
- pr_created_at=datetime(2026, 6, 10, tzinfo=UTC), report_status=SignalReport.Status.RESOLVED
- )
+ def test_refund_of_resolved_report_suppresses_unless_pr_merged(self, _flag, _name, output, expected_status):
+ report = _make_report(self.team, status=SignalReport.Status.RESOLVED)
+ _make_pr_run(self.team, report, created_at=datetime(2026, 6, 10, tzinfo=UTC), output=output)
response = self._refund(report)
- assert response.status_code == status.HTTP_200_OK
+ assert response.status_code == status.HTTP_200_OK, response.json()
report.refresh_from_db()
- assert report.status == SignalReport.Status.RESOLVED
- # The permanent marker still lands even though the status did not change.
+ assert report.status == expected_status
+ # The permanent marker lands regardless of whether the status changed.
assert SignalReportArtefact.objects.filter(
report=report, type=SignalReportArtefact.ArtefactType.DISMISSAL
).exists()
@@ -273,6 +281,84 @@ class TestSignalReportRefundAPI(APIBaseTest):
assert properties["pr_merged"] is False
assert properties["days_since_pr"] == 5
+ @parameterized.expand(
+ [
+ # A merged PR (output.pr_merged) reports pr_merged=True whatever the report status.
+ (
+ "merged_pr",
+ SignalReport.Status.READY,
+ {"pr_url": "https://github.com/x/y/pull/1", "pr_merged": True},
+ True,
+ ),
+ # Resolved without a merged PR must NOT report a merge: status alone can't attest one.
+ (
+ "resolved_without_merge",
+ SignalReport.Status.RESOLVED,
+ {"pr_url": "https://github.com/x/y/pull/1"},
+ False,
+ ),
+ ]
+ )
+ @freeze_time(_NOW)
+ def test_analytics_pr_merged_reflects_merge_flag_not_status(self, _flag, _name, report_status, output, expected):
+ report = _make_report(self.team, status=report_status)
+ _make_pr_run(self.team, report, created_at=datetime(2026, 6, 10, tzinfo=UTC), output=output)
+ with patch("products.signals.backend.views.report_user_action") as mock_report:
+ assert self._refund(report).status_code == status.HTTP_200_OK
+ assert mock_report.call_args.kwargs["properties"]["pr_merged"] is expected
+
+ @freeze_time(_NOW)
+ def test_later_merged_pr_does_not_vouch_for_the_refunded_one(self, _flag):
+ # The refund reverses the charge for the first billable PR, and it's that PR which must be
+ # closed if it never merged. A different, later PR on the same report merging says nothing
+ # about it — treating the report as merged would leave the refunded PR open.
+ report = _make_report(self.team, status=SignalReport.Status.RESOLVED)
+ _make_pr_run(
+ self.team,
+ report,
+ created_at=datetime(2026, 6, 10, tzinfo=UTC),
+ output={"pr_url": "https://github.com/x/y/pull/1"},
+ )
+ _make_pr_run(
+ self.team,
+ report,
+ created_at=datetime(2026, 6, 12, tzinfo=UTC),
+ output={"pr_url": "https://github.com/x/y/pull/2", "pr_merged": True},
+ )
+
+ with patch("products.signals.backend.views.report_user_action") as mock_report:
+ assert self._refund(report).status_code == status.HTTP_200_OK
+
+ assert mock_report.call_args.kwargs["properties"]["pr_merged"] is False
+ report.refresh_from_db()
+ assert report.status == SignalReport.Status.SUPPRESSED
+
+ @freeze_time(_NOW)
+ def test_merge_flag_on_non_github_run_does_not_attest_a_merge(self, _flag):
+ # A billable GitHub run makes the report refundable, while a second implementation run
+ # carries a merge flag on a URL the billing path never counts. That flag must not attest a
+ # merge: if it did, the refund would leave the report resolved and its real PR unclosed.
+ report = _make_report(self.team, status=SignalReport.Status.RESOLVED)
+ _make_pr_run(
+ self.team,
+ report,
+ created_at=datetime(2026, 6, 10, tzinfo=UTC),
+ output={"pr_url": "https://github.com/x/y/pull/1"},
+ )
+ _make_pr_run(
+ self.team,
+ report,
+ created_at=datetime(2026, 6, 11, tzinfo=UTC),
+ output={"pr_url": "https://gitlab.example.com/x/y/-/merge_requests/1", "pr_merged": True},
+ )
+
+ with patch("products.signals.backend.views.report_user_action") as mock_report:
+ assert self._refund(report).status_code == status.HTTP_200_OK
+
+ assert mock_report.call_args.kwargs["properties"]["pr_merged"] is False
+ report.refresh_from_db()
+ assert report.status == SignalReport.Status.SUPPRESSED
+
@freeze_time(_NOW)
def test_restore_of_refunded_report_is_blocked(self, _flag):
report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))
@@ -284,6 +370,58 @@ class TestSignalReportRefundAPI(APIBaseTest):
report.refresh_from_db()
assert report.status == SignalReport.Status.SUPPRESSED
+ @freeze_time(_NOW)
+ def test_snooze_of_refunded_resolved_report_is_blocked(self, _flag):
+ # A merged-PR report stays RESOLVED through its refund, so the guard can't key on SUPPRESSED:
+ # snoozing it to POTENTIAL would put a refunded report back where grouping re-promotes it to
+ # candidate, and later PR runs on it are never billable.
+ report = _make_report(self.team, status=SignalReport.Status.RESOLVED)
+ _make_pr_run(
+ self.team,
+ report,
+ created_at=datetime(2026, 6, 10, tzinfo=UTC),
+ output={"pr_url": "https://github.com/x/y/pull/1", "pr_merged": True},
+ )
+ assert self._refund(report).status_code == status.HTTP_200_OK
+ report.refresh_from_db()
+ assert report.status == SignalReport.Status.RESOLVED
+
+ response = self.client.post(self._state_url(str(report.id)), {"state": "potential"}, format="json")
+ assert response.status_code == status.HTTP_409_CONFLICT
+ assert response.json()["error"] == "Refunded reports can't be restored."
+ report.refresh_from_db()
+ assert report.status == SignalReport.Status.RESOLVED
+
+ @freeze_time(_NOW)
+ def test_resolve_of_refunded_report_is_blocked(self, _flag):
+ # A refunded report is suppressed; resolving would undo that suppression — and the PR close
+ # it triggers — so the refund guard must cover resolve too (not just restore to potential).
+ report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))
+ assert self._refund(report).status_code == status.HTTP_200_OK
+
+ response = self.client.post(self._state_url(str(report.id)), {"state": "resolved"}, format="json")
+ assert response.status_code == status.HTTP_409_CONFLICT
+ assert response.json()["error"] == "Refunded reports can't be restored."
+ report.refresh_from_db()
+ assert report.status == SignalReport.Status.SUPPRESSED
+
+ @freeze_time(_NOW)
+ def test_resolve_then_refund_suppresses_report(self, _flag):
+ # The exploit path the refund must close: a task:write caller resolves a ready report through
+ # the API while its PR is still open, then refunds it. If the refund left it RESOLVED the
+ # dismissal receiver would never close that PR, so the caller keeps the work and the money.
+ # The refund must suppress it, and it must then be non-restorable.
+ report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))
+ resolve = self.client.post(self._state_url(str(report.id)), {"state": "resolved"}, format="json")
+ assert resolve.status_code == status.HTTP_200_OK, resolve.json()
+
+ assert self._refund(report).status_code == status.HTTP_200_OK
+ report.refresh_from_db()
+ assert report.status == SignalReport.Status.SUPPRESSED
+
+ reopen = self.client.post(self._state_url(str(report.id)), {"state": "resolved"}, format="json")
+ assert reopen.status_code == status.HTTP_409_CONFLICT
+
@freeze_time(_NOW)
def test_bulk_restore_of_refunded_report_is_blocked(self, _flag):
refunded = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index 5534b1441b08..898e0d2cb89c 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -20,7 +20,10 @@ from social_django.models import UserSocialAuth
from posthog.models.team.team import Team
-from products.signals.backend.implementation_pr import fetch_implementation_pr_urls_for_reports
+from products.signals.backend.implementation_pr import (
+ fetch_implementation_pr_state_for_reports,
+ fetch_implementation_pr_urls_for_reports,
+)
from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportTask
from products.signals.backend.signal_metadata import ReportSignalMeta
from products.signals.backend.task_run_artefacts import append_task_run_artefact, record_implementation_task
@@ -615,6 +618,41 @@ class TestSignalReportListAPI(APIBaseTest):
row = next(r for r in response.json()["results"] if r["id"] == str(report.id))
assert row["implementation_pr_url"] == "https://github.com/o/r/pull/7"
+ @parameterized.expand(
+ [
+ # The badge reads this flag, so it must track the webhook's merge record rather than the
+ # report status — a resolved report may have been resolved directly, PR still open.
+ ("merged_pr", SignalReport.Status.READY, {"pr_url": "https://github.com/o/r/pull/7", "pr_merged": True}),
+ ("resolved_without_merge", SignalReport.Status.RESOLVED, {"pr_url": "https://github.com/o/r/pull/7"}),
+ ("no_pr_run", SignalReport.Status.RESOLVED, None),
+ ]
+ )
+ def test_implementation_pr_merged_reflects_merge_flag_not_status(self, _name, report_status, output):
+ report = self._create_report(status=report_status)
+ if output is not None:
+ self._create_implementation_task_with_run(report, output=output)
+ expected = bool(output and output.get("pr_merged"))
+
+ list_row = next(r for r in self.client.get(self._list_url()).json()["results"] if r["id"] == str(report.id))
+ detail = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/").json()
+
+ assert list_row["implementation_pr_merged"] is expected
+ assert detail["implementation_pr_merged"] is expected
+
+ def test_implementation_pr_merged_describes_the_surfaced_pr_not_a_sibling_task(self):
+ # A retried report has several implementation tasks but surfaces one PR. The merge flag must
+ # come from that same task — otherwise a sibling task's merged PR vouches for the PR whose
+ # URL is on screen, and the badge shows "merged" over an open PR.
+ report = self._create_report()
+ self._create_implementation_task_with_run(report, output={"pr_url": "https://github.com/o/r/pull/1"})
+ self._create_implementation_task_with_run(
+ report, output={"pr_url": "https://github.com/o/r/pull/2", "pr_merged": True}
+ )
+
+ row = next(r for r in self.client.get(self._list_url()).json()["results"] if r["id"] == str(report.id))
+
+ assert row["implementation_pr_merged"] is (row["implementation_pr_url"] == "https://github.com/o/r/pull/2")
+
def test_implementation_pr_url_null_when_no_implementation_task(self):
report = self._create_report()
@@ -703,17 +741,18 @@ class TestSignalReportListAPI(APIBaseTest):
single = seed(1)
with CaptureQueriesContext(connection) as for_one:
- fetch_implementation_pr_urls_for_reports(single)
+ fetch_implementation_pr_state_for_reports(single)
baseline = len(for_one.captured_queries)
page = single + seed(5)
with CaptureQueriesContext(connection) as for_many:
- result = fetch_implementation_pr_urls_for_reports(page)
+ result = fetch_implementation_pr_state_for_reports(page)
assert len(result) == 6
- # Constant in the page size, and a small fixed cost (artefacts + gate rows + PR lookup).
+ # Constant in the page size, and a small fixed cost (artefacts + gate rows + PR url lookup +
+ # merge-flag lookup).
assert len(for_many.captured_queries) == baseline
- assert baseline <= 3
+ assert baseline <= 4
# --- has_implementation_pr filter ---
@@ -918,7 +957,7 @@ class TestSignalReportListAPI(APIBaseTest):
@parameterized.expand(
[
("source_products", "fetch_source_products_for_reports"),
- ("implementation_pr_urls", "fetch_implementation_pr_urls_for_reports"),
+ ("implementation_pr_urls", "fetch_implementation_pr_state_for_reports"),
]
)
def test_list_resilient_to_supplementary_fetch_failure(self, _name, fetch_fn):
@@ -1293,6 +1332,17 @@ class TestSignalReportSuppressionAPI(APIBaseTest):
"wontfix_irrelevant",
"snoozing for now",
),
+ (
+ "resolve_with_reason_and_note",
+ {
+ "state": "resolved",
+ "dismissal_reason": "already_fixed",
+ "dismissal_note": "shipped a fix by hand",
+ },
+ SignalReport.Status.RESOLVED,
+ "already_fixed",
+ "shipped a fix by hand",
+ ),
]
)
def test_state_transition_with_dismissal(self, _name, body, expected_final_status, expected_reason, expected_note):
@@ -1323,6 +1373,32 @@ class TestSignalReportSuppressionAPI(APIBaseTest):
assert content["user_id"] == self.user.id
assert content["user_uuid"] == str(self.user.uuid)
+ @parameterized.expand(
+ [
+ ("resolve_with_reason", {"state": "resolved", "dismissal_reason": "already_fixed"}, "already_fixed"),
+ # A resolve carrying no feedback must not pick a reason up from anywhere.
+ ("resolve_without_reason", {"state": "resolved"}, None),
+ ]
+ )
+ def test_resolve_feedback_reaches_the_status_change_label(self, _name, body, expected_reason):
+ # The state API writes the dismissal artefact, but the label stream is produced by a separate
+ # post_save receiver — feedback that never reaches the label is invisible to inbox ranking.
+ report = self._create_report()
+ with patch("products.signals.backend.receivers.posthoganalytics.capture") as mock_capture:
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.client.post(
+ self._state_url(str(report.id)), data=json.dumps(body), content_type="application/json"
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ label = next(
+ call.kwargs
+ for call in mock_capture.call_args_list
+ if call.kwargs["event"] == "signal_report_status_changed"
+ )
+ assert label["properties"]["status"] == SignalReport.Status.RESOLVED
+ assert label["properties"]["dismissal_reason"] == expected_reason
+
def test_state_transition_response_includes_source_products(self):
report = self._create_report()
@@ -1453,6 +1529,86 @@ class TestSignalReportSuppressionAPI(APIBaseTest):
report.refresh_from_db()
assert report.status == SignalReport.Status.POTENTIAL
+ @parameterized.expand(
+ [
+ # initial status, status before suppression, expected HTTP code, expected status after.
+ # Resolve is allowed only from a researched status, or from an archive that holds a
+ # researched report; every other status keeps returning 409 (the model state machine is
+ # not loosened).
+ ("ready", SignalReport.Status.READY, None, status.HTTP_200_OK, SignalReport.Status.RESOLVED),
+ (
+ "pending_input",
+ SignalReport.Status.PENDING_INPUT,
+ None,
+ status.HTTP_200_OK,
+ SignalReport.Status.RESOLVED,
+ ),
+ (
+ "suppressed_from_ready",
+ SignalReport.Status.SUPPRESSED,
+ SignalReport.Status.READY,
+ status.HTTP_200_OK,
+ SignalReport.Status.RESOLVED,
+ ),
+ # Archived before it was ever researched: resolving would land it in RESOLVED with no
+ # title or summary, so the archive can't launder an unresearched report to resolved.
+ (
+ "suppressed_from_candidate",
+ SignalReport.Status.SUPPRESSED,
+ SignalReport.Status.CANDIDATE,
+ status.HTTP_409_CONFLICT,
+ SignalReport.Status.SUPPRESSED,
+ ),
+ (
+ "suppressed_without_prior_status",
+ SignalReport.Status.SUPPRESSED,
+ None,
+ status.HTTP_409_CONFLICT,
+ SignalReport.Status.SUPPRESSED,
+ ),
+ # The model refuses failed -> resolved directly, so archiving must not launder a failed
+ # pipeline run into looking successfully resolved.
+ (
+ "suppressed_from_failed",
+ SignalReport.Status.SUPPRESSED,
+ SignalReport.Status.FAILED,
+ status.HTTP_409_CONFLICT,
+ SignalReport.Status.SUPPRESSED,
+ ),
+ (
+ "suppressed_from_pending_input",
+ SignalReport.Status.SUPPRESSED,
+ SignalReport.Status.PENDING_INPUT,
+ status.HTTP_200_OK,
+ SignalReport.Status.RESOLVED,
+ ),
+ ("candidate", SignalReport.Status.CANDIDATE, None, status.HTTP_409_CONFLICT, SignalReport.Status.CANDIDATE),
+ (
+ "in_progress",
+ SignalReport.Status.IN_PROGRESS,
+ None,
+ status.HTTP_409_CONFLICT,
+ SignalReport.Status.IN_PROGRESS,
+ ),
+ ("potential", SignalReport.Status.POTENTIAL, None, status.HTTP_409_CONFLICT, SignalReport.Status.POTENTIAL),
+ ]
+ )
+ def test_resolve_state_transition_by_status(
+ self, _name, initial_status, prior_status, expected_code, expected_status
+ ):
+ report = self._create_report(report_status=initial_status)
+ if prior_status is not None:
+ report.status_before_suppression = prior_status
+ report.save(update_fields=["status_before_suppression"])
+ response = self.client.post(
+ self._state_url(str(report.id)),
+ data=json.dumps({"state": "resolved"}),
+ content_type="application/json",
+ )
+ assert response.status_code == expected_code, response.json()
+ report.refresh_from_db()
+ assert report.status == expected_status
+
@parameterized.expand(
[
# prior status before archiving, expected status after restore
@@ -1698,6 +1854,28 @@ class TestSignalReportBulkStateAPI(APIBaseTest):
report.refresh_from_db()
assert report.status == SignalReport.Status.READY
+ def test_bulk_resolve_mixed_statuses(self):
+ ready = self._create_report(report_status=SignalReport.Status.READY)
+ pending = self._create_report(report_status=SignalReport.Status.PENDING_INPUT)
+ # candidate can't resolve, so it comes back skipped while the rest still go through.
+ candidate = self._create_report(report_status=SignalReport.Status.CANDIDATE)
+
+ response = self._post({"ids": [str(ready.id), str(pending.id), str(candidate.id)], "state": "resolved"})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ body = response.json()
+ assert body["transitioned_count"] == 2
+ assert body["skipped_count"] == 1
+ outcomes = {row["id"]: row["outcome"] for row in body["results"]}
+ assert outcomes[str(ready.id)] == "transitioned"
+ assert outcomes[str(pending.id)] == "transitioned"
+ assert outcomes[str(candidate.id)] == "skipped"
+
+ ready.refresh_from_db()
+ candidate.refresh_from_db()
+ assert ready.status == SignalReport.Status.RESOLVED
+ assert candidate.status == SignalReport.Status.CANDIDATE
+
@parameterized.expand(
[
("empty_ids", {"ids": [], "state": "suppressed"}),
diff --git a/products/signals/backend/test/test_status_change_telemetry.py b/products/signals/backend/test/test_status_change_telemetry.py
index 2cf8560616a1..b058885f87c8 100644
--- a/products/signals/backend/test/test_status_change_telemetry.py
+++ b/products/signals/backend/test/test_status_change_telemetry.py
@@ -55,12 +55,18 @@ class TestCaptureStatusChangeAnalytics(BaseTest):
@parameterized.expand(
[
("dismissal_includes_fresh_reason", SignalReport.Status.SUPPRESSED, False, "wontfix_irrelevant"),
- # Dismissal artefacts are append-only, so an old reason must not leak onto later
- # non-dismissal transitions (e.g. a restored report getting resolved)...
- ("non_dismissal_excludes_reason", SignalReport.Status.RESOLVED, False, None),
- # ...nor onto a later feedback-less dismissal (the state API only writes a new
- # dismissal artefact when the user actually gave a reason or note).
+ # A resolve that wrote no feedback of its own — the PR-merge webhook path — must not
+ # adopt an unrelated earlier reason just because it landed inside the freshness window.
+ # Resolve-with-feedback goes through the state API and is covered separately.
+ ("webhook_resolve_excludes_fresh_reason", SignalReport.Status.RESOLVED, False, None),
+ # Dismissal artefacts are append-only, so an old reason must not leak onto a later
+ # transition — neither a resolve...
+ ("stale_reason_excluded_from_resolve", SignalReport.Status.RESOLVED, True, None),
+ # ...nor a later feedback-less dismissal (the state API only writes a new dismissal
+ # artefact when the user actually gave a reason or note).
("stale_reason_excluded_from_new_dismissal", SignalReport.Status.SUPPRESSED, True, None),
+ # A pipeline transition never carries dismissal feedback, however fresh the artefact.
+ ("pipeline_transition_excludes_reason", SignalReport.Status.CANDIDATE, False, None),
]
)
def test_label_snapshots_latest_classification_artefacts(
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index a4d6540bea9e..3f506cf1616b 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -80,9 +80,10 @@ from products.signals.backend.billing import (
first_billable_pr_run,
period_billable_credits_for_org,
refund_ineligibility_reason,
+ report_pr_is_merged,
)
from products.signals.backend.facade.api import emit_signal
-from products.signals.backend.implementation_pr import fetch_implementation_pr_urls_for_reports
+from products.signals.backend.implementation_pr import fetch_implementation_pr_state_for_reports
from products.signals.backend.models import (
ArtefactAttribution,
AutonomyPriority,
@@ -449,9 +450,11 @@ SIGNAL_REPORT_DISMISSAL_REASON_CHOICES = [
_DISMISSAL_REASON_HELP_TEXT = (
"Optional canonical reason code for the dismissal. Must be one of: already_fixed, "
"report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match "
- "the inbox UI so the rationale renders as a labelled chip rather than a raw code. 'already_fixed' "
- "is a snooze, not a dismissal: pair it with state='potential' (restore) so the report reappears if "
- "the issue recurs. Use 'other' together with a dismissal_note for anything that doesn't fit a code."
+ "the inbox UI so the rationale renders as a labelled chip rather than a raw code. When the work "
+ "this report asked for is done, the honest transition is state='resolved' (the reason/note records "
+ "why). Reserve 'already_fixed' with state='potential' (snooze/restore) for \"fixed by something "
+ "else / might recur\" cases, so the report reappears if the issue comes back. Use 'other' together "
+ "with a dismissal_note for anything that doesn't fit a code."
)
@@ -465,12 +468,28 @@ class SignalReportBulkStateOutcome(models.TextChoices):
NOT_FOUND = "not_found", "not_found"
+# Statuses a report may have held before being archived and still resolve straight out of the
+# archive. Mirrors the model's direct resolve edge (pending_input | ready -> resolved) plus RESOLVED
+# itself, which makes archive-then-resolve idempotent. FAILED is deliberately absent: the model
+# refuses FAILED -> RESOLVED directly, and suppression must not launder a failed report into looking
+# successfully resolved.
+_RESOLVABLE_STATUSES_BEFORE_SUPPRESSION = frozenset(
+ {
+ SignalReport.Status.READY,
+ SignalReport.Status.PENDING_INPUT,
+ SignalReport.Status.RESOLVED,
+ }
+)
+
+
class SignalReportStateRequestSerializer(serializers.Serializer):
state = serializers.ChoiceField(
- choices=[("suppressed", "suppressed"), ("potential", "potential")],
+ choices=[("suppressed", "suppressed"), ("potential", "potential"), ("resolved", "resolved")],
help_text=(
"Target state for the report. Use 'suppressed' to dismiss the report from the inbox, "
- "or 'potential' to snooze/reopen it for later review."
+ "'potential' to snooze/reopen it for later review, or 'resolved' when the work this report "
+ "asked for has been done. Resolving is only allowed from a researched status (ready or "
+ "pending_input) or a suppressed report; other statuses return 409 (skipped in bulk)."
),
)
dismissal_reason = serializers.ChoiceField(
@@ -1089,7 +1108,14 @@ class SignalReportViewSet(
latest_impl_pr_url = tasks_facade.latest_task_run_pr_url_subquery(
SignalReport.associated_task_runs_filter(OuterRef(OuterRef("id"))),
)
- return queryset.annotate(implementation_pr_url=latest_impl_pr_url)
+ # Resolved over the same run, so the merge flag always describes the PR URL alongside it.
+ latest_impl_pr_merged = tasks_facade.latest_task_run_pr_merged_subquery(
+ SignalReport.associated_task_runs_filter(OuterRef(OuterRef("id"))),
+ )
+ return queryset.annotate(
+ implementation_pr_url=latest_impl_pr_url,
+ implementation_pr_merged=latest_impl_pr_merged,
+ )
def filter_queryset(self, queryset):
queryset = super().filter_queryset(queryset)
@@ -1153,15 +1179,16 @@ class SignalReportViewSet(
logger.exception("signals.enriched_context.source_products_failed", report_id=str(report.id))
signal_meta_map = {}
try:
- implementation_pr_url_map = fetch_implementation_pr_urls_for_reports(report_ids)
+ implementation_pr_by_report = fetch_implementation_pr_state_for_reports(report_ids)
except Exception:
logger.exception("signals.enriched_context.implementation_pr_url_failed", report_id=str(report.id))
- implementation_pr_url_map = {}
+ implementation_pr_by_report = {}
return {
**self.get_serializer_context(),
"source_products_map": {rid: meta.source_products for rid, meta in signal_meta_map.items()},
"scout_names_map": {rid: meta.scout_name for rid, meta in signal_meta_map.items() if meta.scout_name},
- "implementation_pr_url_map": implementation_pr_url_map,
+ "implementation_pr_url_map": {rid: pr.url for rid, pr in implementation_pr_by_report.items()},
+ "implementation_pr_merged_ids": {rid for rid, pr in implementation_pr_by_report.items() if pr.merged},
}
def retrieve(self, request, *args, **kwargs):
@@ -1341,16 +1368,17 @@ class SignalReportViewSet(
with tracer.start_as_current_span("signals.reports.list.fetch_implementation_pr_urls"):
try:
- implementation_pr_url_map = fetch_implementation_pr_urls_for_reports(report_ids)
+ implementation_pr_by_report = fetch_implementation_pr_state_for_reports(report_ids)
except Exception:
logger.exception("signals.reports.list.implementation_pr_url_failed", report_count=len(report_ids))
- implementation_pr_url_map = {}
+ implementation_pr_by_report = {}
context = {
**self.get_serializer_context(),
"source_products_map": {rid: meta.source_products for rid, meta in signal_meta_map.items()},
"scout_names_map": {rid: meta.scout_name for rid, meta in signal_meta_map.items() if meta.scout_name},
- "implementation_pr_url_map": implementation_pr_url_map,
+ "implementation_pr_url_map": {rid: pr.url for rid, pr in implementation_pr_by_report.items()},
+ "implementation_pr_merged_ids": {rid for rid, pr in implementation_pr_by_report.items() if pr.merged},
}
serializer = self.get_serializer(reports, many=True, context=context)
@@ -1483,8 +1511,8 @@ class SignalReportViewSet(
so internal transition_to kwargs (reset_weight, error, ...) can't be injected.
Body: {
- "state": "suppressed" | "potential",
- # Optional dismissal feedback (honored when state == "suppressed" or "potential"):
+ "state": "suppressed" | "potential" | "resolved",
+ # Optional dismissal feedback (honored when state == "suppressed", "potential", or "resolved"):
"dismissal_reason": "<canonical reason code, see SIGNAL_REPORT_DISMISSAL_REASON_CHOICES>",
"dismissal_note": "free-form text",
# Optional, only honored for state == "potential":
@@ -1518,6 +1546,17 @@ class SignalReportViewSet(
return Response(SignalReportSerializer(report, context=self._enriched_report_context(report)).data)
+ def _request_attribution(self) -> ArtefactAttribution:
+ """Attribution for this request, resolved once and reused.
+
+ `resolve_request_attribution` validates the `X-PostHog-Task-Id` header with a DB lookup, and
+ both the request and the team are invariant across a call — so bulk_state, which transitions
+ up to the per-call id cap in a loop, would otherwise repeat the identical query per report.
+ """
+ if not hasattr(self, "_cached_request_attribution"):
+ self._cached_request_attribution = resolve_request_attribution(self.request, self.team.id)
+ return self._cached_request_attribution
+
def _transition_report_state(
self,
report: SignalReport,
@@ -1541,35 +1580,86 @@ class SignalReportViewSet(
internal pipeline concern and must never be reachable from this public API surface, so it is
passed explicitly rather than splatting caller-supplied kwargs.
"""
- # "potential" on a suppressed report means "restore" (un-archive): return it to the state it
- # held before suppression when that was a researched, user-visible report, instead of always
- # dropping back to potential. snooze_for is irrelevant here and ignored by transition_to.
target_status = SignalReport.Status(target)
- if report.status == SignalReport.Status.SUPPRESSED and target_status == SignalReport.Status.POTENTIAL:
- # Restore guard: a refunded report can never be billed again (see billing.py), so
- # refund → restore → new PR would be repeatable free work. The refund is final.
- if getattr(report, "refund", None) is not None:
+
+ with transaction.atomic():
+ # Lock the report row for the whole guard + transition so it serializes with the refund
+ # path (which locks the same row before suppressing). Re-read committed state under the
+ # lock: a resolve/restore that raced a refund must observe the refund's SUPPRESSED status
+ # and refund row and refuse, instead of overwriting the suppression and re-opening
+ # already-refunded work.
+ if SignalReport.objects.select_for_update().filter(id=report.id, team_id=self.team.id).first() is not None:
+ report.refresh_from_db()
+ is_refunded = SignalReportRefund.objects.filter(report_id=report.id).exists()
+
+ # Refund guard: a refunded report can never be billed again (see billing.py), so putting
+ # it back where the pipeline can pick it up again is repeatable free work. POTENTIAL is
+ # the live status — a potential report re-promotes to candidate on new signals and can
+ # spawn a fresh research run (grouping.py). The refund is final, so any transition of a
+ # refunded report back to POTENTIAL is refused, whether it currently sits in SUPPRESSED
+ # (refund's own archive step) or in RESOLVED (a refunded merged-PR report stays resolved,
+ # so the guard can't key on SUPPRESSED alone). RESOLVED is terminal and never re-promotes,
+ # so resolving a refunded report is refused only out of the archive, to keep the refund's
+ # suppression — and the PR close it triggers — from being undone.
+ if is_refunded and (
+ target_status == SignalReport.Status.POTENTIAL
+ or (report.status == SignalReport.Status.SUPPRESSED and target_status == SignalReport.Status.RESOLVED)
+ ):
return SignalReportBulkStateOutcome.SKIPPED, "Refunded reports can't be restored."
- target_status = report.restore_target_status()
- effective_snooze_for = snooze_for if target == "potential" else None
+ # Archiving must not grant a transition the report couldn't make directly. "Any
+ # non-deleted status can be suppressed", so without this a report could be laundered
+ # through the archive into RESOLVED from a status the model refuses to resolve from —
+ # candidate/in_progress (landing in RESOLVED with no title or summary), or failed
+ # (a failed pipeline run presented as successfully resolved). So a suppressed report may
+ # only resolve when it was in a directly-resolvable status before being archived.
+ # Deliberately narrower than restore_target_status()'s researched set, which exists to
+ # answer "where does restore put this report back", not "may it resolve".
+ if (
+ report.status == SignalReport.Status.SUPPRESSED
+ and target_status == SignalReport.Status.RESOLVED
+ and report.status_before_suppression not in _RESOLVABLE_STATUSES_BEFORE_SUPPRESSION
+ ):
+ return (
+ SignalReportBulkStateOutcome.SKIPPED,
+ "Only a report that was ready, awaiting input, or already resolved when it was "
+ "archived can be resolved from the archive.",
+ )
- try:
- updated_fields = report.transition_to(target_status, snooze_for=effective_snooze_for)
- except InvalidStatusTransition as e:
- logger.warning("Invalid status transition for SignalReport %s: %s", report.id, e, exc_info=True)
- return SignalReportBulkStateOutcome.SKIPPED, None
- except (ValueError, TypeError) as e:
- logger.warning("Invalid data when transitioning SignalReport %s: %s", report.id, e, exc_info=True)
- return SignalReportBulkStateOutcome.FAILED, None
+ # "potential" on a suppressed report means "restore" (un-archive): return it to the state
+ # it held before suppression when that was a researched, user-visible report, instead of
+ # always dropping back to potential. snooze_for is irrelevant here and ignored.
+ effective_target = target_status
+ if report.status == SignalReport.Status.SUPPRESSED and target_status == SignalReport.Status.POTENTIAL:
+ effective_target = report.restore_target_status()
+
+ effective_snooze_for = snooze_for if target == "potential" else None
+
+ try:
+ updated_fields = report.transition_to(effective_target, snooze_for=effective_snooze_for)
+ except InvalidStatusTransition as e:
+ logger.warning("Invalid status transition for SignalReport %s: %s", report.id, e, exc_info=True)
+ return SignalReportBulkStateOutcome.SKIPPED, None
+ except (ValueError, TypeError) as e:
+ logger.warning("Invalid data when transitioning SignalReport %s: %s", report.id, e, exc_info=True)
+ return SignalReportBulkStateOutcome.FAILED, None
+
+ writes_dismissal_feedback = target in ("suppressed", "potential", "resolved") and bool(
+ dismissal_reason or dismissal_note
+ )
+ # Tell the status-changed receiver that this transition carries caller-supplied feedback,
+ # so the label picks up the artefact written just below. Set before the save because the
+ # post_save receiver snapshots it there. Matters most for resolve: a resolve driven by
+ # the PR-merge webhook has no feedback, and only this flag distinguishes the two.
+ report._wrote_dismissal_feedback = writes_dismissal_feedback # type: ignore[attr-defined]
- with transaction.atomic():
report.save(update_fields=updated_fields)
# Persist the dismissal feedback as its own artefact so it survives status changes
# and so multiple dismissals (with different rationales) can stack over time.
- # Captured for both suppress and snooze (transition to potential) flows.
- if target in ("suppressed", "potential") and (dismissal_reason or dismissal_note):
+ # Captured for suppress, snooze (transition to potential), and resolve flows — on a
+ # resolve it records why the report was resolved with user attribution.
+ if writes_dismissal_feedback:
user = self.request.user
is_authenticated = getattr(user, "is_authenticated", False)
user_uuid = getattr(user, "uuid", None) if is_authenticated else None
@@ -1582,7 +1672,7 @@ class SignalReportViewSet(
user_id=getattr(user, "id", None) if is_authenticated else None,
user_uuid=str(user_uuid) if user_uuid else None,
),
- attribution=resolve_request_attribution(self.request, self.team.id),
+ attribution=self._request_attribution(),
)
# The dismissal prefetch may have been evaluated before this artefact
# existed; drop the stale cache so a follow-up serializer re-reads the
@@ -1770,7 +1860,11 @@ class SignalReportViewSet(
# the next UTC day), so the report can simply be excluded from usage; anything later
# must go through a billing-service credit. Decided once, stored, never recomputed.
now = timezone.now()
- pr_merged = SignalReport.Status.RESOLVED in (report.status, report.status_before_suppression)
+ # Derived from the persisted merge flag, not the report status: a report can be resolved
+ # manually without a merged PR, so RESOLVED no longer implies the PR shipped. Asked about
+ # the PR being refunded specifically — it's that PR the refund reverses the charge for,
+ # and that PR which has to be closed if it never merged.
+ pr_merged = report_pr_is_merged(report.id, billable_run.pr_url)
billing_path = (
SignalReportRefund.BillingPath.EXCLUDED
if billable_run.created_at.astimezone(UTC).date() == now.astimezone(UTC).date()
@@ -1799,10 +1893,16 @@ class SignalReportViewSet(
raise
return self._refund_response(existing, already_refunded=True)
- # Refund doubles as archive: suppress unless the report is resolved (stays resolved —
- # the merged PR shipped) or already suppressed. The dismissal artefact records the
- # rationale like any other dismissal; the structured truth lives on the refund row.
- if report.status not in (SignalReport.Status.RESOLVED, SignalReport.Status.SUPPRESSED):
+ # Refund doubles as archive: suppress the report so it leaves the inbox, and so the
+ # dismissal receiver closes the implementation PR that was paid for and then refunded.
+ # The one exception is a report resolved by a merged PR: that PR shipped, so the report
+ # stays put as a genuine terminal state and there is no open PR to close. A report
+ # resolved manually without a merged PR is NOT exempt — its PR may still be open, and
+ # leaving it resolved would let the caller keep the implementation work after the refund.
+ # Already-suppressed reports need no transition. The dismissal artefact records the
+ # rationale; the structured truth lives on the refund row.
+ resolved_via_merged_pr = report.status == SignalReport.Status.RESOLVED and pr_merged
+ if report.status != SignalReport.Status.SUPPRESSED and not resolved_via_merged_pr:
updated_fields = report.transition_to(SignalReport.Status.SUPPRESSED)
report.save(update_fields=updated_fields)
SignalReportArtefact.append_dismissal(
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index e909ab4726f9..49a7cde28673 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -196,6 +196,8 @@ export interface SignalReportApi {
* @nullable
*/
readonly implementation_pr_url: string | null
+ /** Whether that implementation PR is merged, per the GitHub webhook. False when there is no PR or it hasn't merged. Report status doesn't imply this: a resolved report may have been resolved directly, without a merged PR. */
+ readonly implementation_pr_merged: boolean
/** The report's PR refund, when one exists. One refund per report, ever. */
readonly refund: SignalReportRefundApi | null
/** Why refunding this report's PR would be rejected right now, or null when a refund would be accepted (see the field's schema for the reason values). */
@@ -760,12 +762,14 @@ export interface ReportSignalsResponseApi {
/**
* * `suppressed` - suppressed
* * `potential` - potential
+ * * `resolved` - resolved
*/
export type SignalReportStateEnumApi = (typeof SignalReportStateEnumApi)[keyof typeof SignalReportStateEnumApi]
export const SignalReportStateEnumApi = {
Suppressed: 'suppressed',
Potential: 'potential',
+ Resolved: 'resolved',
} as const
/**
@@ -788,12 +792,13 @@ export const DismissalReasonEnumApi = {
} as const
export interface SignalReportStateRequestApi {
- /** Target state for the report. Use 'suppressed' to dismiss the report from the inbox, or 'potential' to snooze/reopen it for later review.
+ /** Target state for the report. Use 'suppressed' to dismiss the report from the inbox, 'potential' to snooze/reopen it for later review, or 'resolved' when the work this report asked for has been done. Resolving is only allowed from a researched status (ready or pending_input) or a suppressed report; other statuses return 409 (skipped in bulk).
*
* * `suppressed` - suppressed
- * * `potential` - potential */
+ * * `potential` - potential
+ * * `resolved` - resolved */
state: SignalReportStateEnumApi
- /** Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. 'already_fixed' is a snooze, not a dismissal: pair it with state='potential' (restore) so the report reappears if the issue recurs. Use 'other' together with a dismissal_note for anything that doesn't fit a code.
+ /** Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. When the work this report asked for is done, the honest transition is state='resolved' (the reason/note records why). Reserve 'already_fixed' with state='potential' (snooze/restore) for "fixed by something else / might recur" cases, so the report reappears if the issue comes back. Use 'other' together with a dismissal_note for anything that doesn't fit a code.
*
* * `already_fixed` - Already fixed
* * `report_unclear` - Report is unclear to me
@@ -952,12 +957,13 @@ export interface CommitDiffResponseApi {
}
export interface SignalReportBulkStateRequestApi {
- /** Target state for the report. Use 'suppressed' to dismiss the report from the inbox, or 'potential' to snooze/reopen it for later review.
+ /** Target state for the report. Use 'suppressed' to dismiss the report from the inbox, 'potential' to snooze/reopen it for later review, or 'resolved' when the work this report asked for has been done. Resolving is only allowed from a researched status (ready or pending_input) or a suppressed report; other statuses return 409 (skipped in bulk).
*
* * `suppressed` - suppressed
- * * `potential` - potential */
+ * * `potential` - potential
+ * * `resolved` - resolved */
state: SignalReportStateEnumApi
- /** Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. 'already_fixed' is a snooze, not a dismissal: pair it with state='potential' (restore) so the report reappears if the issue recurs. Use 'other' together with a dismissal_note for anything that doesn't fit a code.
+ /** Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. When the work this report asked for is done, the honest transition is state='resolved' (the reason/note records why). Reserve 'already_fixed' with state='potential' (snooze/restore) for "fixed by something else / might recur" cases, so the report reappears if the issue comes back. Use 'other' together with a dismissal_note for anything that doesn't fit a code.
*
* * `already_fixed` - Already fixed
* * `report_unclear` - Report is unclear to me
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index f51697e95efa..14e7604038ac 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -269,8 +269,8 @@ export const getSignalsReportsStateCreateUrl = (projectId: string, id: string) =
* so internal transition_to kwargs (reset_weight, error, ...) can't be injected.
*
* Body: {
- * "state": "suppressed" | "potential",
- * # Optional dismissal feedback (honored when state == "suppressed" or "potential"):
+ * "state": "suppressed" | "potential" | "resolved",
+ * # Optional dismissal feedback (honored when state == "suppressed", "potential", or "resolved"):
* "dismissal_reason": "<canonical reason code, see SIGNAL_REPORT_DISMISSAL_REASON_CHOICES>",
* "dismissal_note": "free-form text",
* # Optional, only honored for state == "potential":
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 1328460c740a..8715165fbf1e 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -80,8 +80,8 @@ export const SignalsReportsRefundCreateBody = /* @__PURE__ */ zod.object({
* so internal transition_to kwargs (reset_weight, error, ...) can't be injected.
*
* Body: {
- * "state": "suppressed" | "potential",
- * # Optional dismissal feedback (honored when state == "suppressed" or "potential"):
+ * "state": "suppressed" | "potential" | "resolved",
+ * # Optional dismissal feedback (honored when state == "suppressed", "potential", or "resolved"):
* "dismissal_reason": "<canonical reason code, see SIGNAL_REPORT_DISMISSAL_REASON_CHOICES>",
* "dismissal_note": "free-form text",
* # Optional, only honored for state == "potential":
@@ -94,10 +94,10 @@ export const signalsReportsStateCreateBodySnoozeForMax = 100000
export const SignalsReportsStateCreateBody = /* @__PURE__ */ zod.object({
state: zod
- .enum(['suppressed', 'potential'])
- .describe('\* `suppressed` - suppressed\n\* `potential` - potential')
+ .enum(['suppressed', 'potential', 'resolved'])
+ .describe('\* `suppressed` - suppressed\n\* `potential` - potential\n\* `resolved` - resolved')
.describe(
- "Target state for the report. Use 'suppressed' to dismiss the report from the inbox, or 'potential' to snooze\/reopen it for later review.\n\n\* `suppressed` - suppressed\n\* `potential` - potential"
+ "Target state for the report. Use 'suppressed' to dismiss the report from the inbox, 'potential' to snooze\/reopen it for later review, or 'resolved' when the work this report asked for has been done. Resolving is only allowed from a researched status (ready or pending_input) or a suppressed report; other statuses return 409 (skipped in bulk).\n\n\* `suppressed` - suppressed\n\* `potential` - potential\n\* `resolved` - resolved"
),
dismissal_reason: zod
.enum([
@@ -113,7 +113,7 @@ export const SignalsReportsStateCreateBody = /* @__PURE__ */ zod.object({
)
.optional()
.describe(
- "Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. 'already_fixed' is a snooze, not a dismissal: pair it with state='potential' (restore) so the report reappears if the issue recurs. Use 'other' together with a dismissal_note for anything that doesn't fit a code.\n\n\* `already_fixed` - Already fixed\n\* `report_unclear` - Report is unclear to me\n\* `analysis_wrong` - Agent's analysis is wrong\n\* `wontfix_intentional` - Won't fix - intentional behavior\n\* `wontfix_irrelevant` - Won't fix - issue is real but insignificant\n\* `other` - Something else…"
+ "Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. When the work this report asked for is done, the honest transition is state='resolved' (the reason\/note records why). Reserve 'already_fixed' with state='potential' (snooze\/restore) for \"fixed by something else \/ might recur\" cases, so the report reappears if the issue comes back. Use 'other' together with a dismissal_note for anything that doesn't fit a code.\n\n\* `already_fixed` - Already fixed\n\* `report_unclear` - Report is unclear to me\n\* `analysis_wrong` - Agent's analysis is wrong\n\* `wontfix_intentional` - Won't fix - intentional behavior\n\* `wontfix_irrelevant` - Won't fix - issue is real but insignificant\n\* `other` - Something else…"
),
dismissal_note: zod
.string()
@@ -183,10 +183,10 @@ export const signalsReportsBulkStateCreateBodyIdsMax = 100
export const SignalsReportsBulkStateCreateBody = /* @__PURE__ */ zod.object({
state: zod
- .enum(['suppressed', 'potential'])
- .describe('\* `suppressed` - suppressed\n\* `potential` - potential')
+ .enum(['suppressed', 'potential', 'resolved'])
+ .describe('\* `suppressed` - suppressed\n\* `potential` - potential\n\* `resolved` - resolved')
.describe(
- "Target state for the report. Use 'suppressed' to dismiss the report from the inbox, or 'potential' to snooze\/reopen it for later review.\n\n\* `suppressed` - suppressed\n\* `potential` - potential"
+ "Target state for the report. Use 'suppressed' to dismiss the report from the inbox, 'potential' to snooze\/reopen it for later review, or 'resolved' when the work this report asked for has been done. Resolving is only allowed from a researched status (ready or pending_input) or a suppressed report; other statuses return 409 (skipped in bulk).\n\n\* `suppressed` - suppressed\n\* `potential` - potential\n\* `resolved` - resolved"
),
dismissal_reason: zod
.enum([
@@ -202,7 +202,7 @@ export const SignalsReportsBulkStateCreateBody = /* @__PURE__ */ zod.object({
)
.optional()
.describe(
- "Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. 'already_fixed' is a snooze, not a dismissal: pair it with state='potential' (restore) so the report reappears if the issue recurs. Use 'other' together with a dismissal_note for anything that doesn't fit a code.\n\n\* `already_fixed` - Already fixed\n\* `report_unclear` - Report is unclear to me\n\* `analysis_wrong` - Agent's analysis is wrong\n\* `wontfix_intentional` - Won't fix - intentional behavior\n\* `wontfix_irrelevant` - Won't fix - issue is real but insignificant\n\* `other` - Something else…"
+ "Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. When the work this report asked for is done, the honest transition is state='resolved' (the reason\/note records why). Reserve 'already_fixed' with state='potential' (snooze\/restore) for \"fixed by something else \/ might recur\" cases, so the report reappears if the issue comes back. Use 'other' together with a dismissal_note for anything that doesn't fit a code.\n\n\* `already_fixed` - Already fixed\n\* `report_unclear` - Report is unclear to me\n\* `analysis_wrong` - Agent's analysis is wrong\n\* `wontfix_intentional` - Won't fix - intentional behavior\n\* `wontfix_irrelevant` - Won't fix - issue is real but insignificant\n\* `other` - Something else…"
),
dismissal_note: zod
.string()
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index 509aafede0b0..3357851a85f3 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -117,13 +117,14 @@ tools:
title: Dismiss or snooze signal reports in bulk
description: >
Transition many signal reports to the same state in one call — the bulk form of `inbox-reports-set-state`,
- for clearing or snoozing a batch of inbox reports without one request per report. Pass `ids` (1–100 report
- ids) and a `state` ('suppressed' to dismiss, 'potential' to snooze/restore); the optional `dismissal_reason`
- (same canonical codes as the single-report tool), `dismissal_note`, and `snooze_for` apply to every id. Each
- id is processed independently, so the whole call returns 200 even on partial failure: inspect `results` (one
- entry per id, in request order) and the `transitioned_count` / `skipped_count` / `failed_count` /
- `not_found_count` summary. An id whose transition isn't allowed from its current status comes back as
- `skipped` (the single-report 409) while the rest still go through.
+ for clearing, snoozing, or resolving a batch of inbox reports without one request per report. Pass `ids`
+ (1–100 report ids) and a `state` ('resolved' when the requested work is done, 'suppressed' to dismiss,
+ 'potential' to snooze/restore); the optional `dismissal_reason` (same canonical codes as the single-report
+ tool), `dismissal_note`, and `snooze_for` apply to every id. Each id is processed independently, so the
+ whole call returns 200 even on partial failure: inspect `results` (one entry per id, in request order) and
+ the `transitioned_count` / `skipped_count` / `failed_count` / `not_found_count` summary. An id whose
+ transition isn't allowed from its current status comes back as `skipped` (the single-report 409) while the
+ rest still go through.
inbox-reports-list:
operation: signals_reports_list
enabled: true
@@ -222,16 +223,20 @@ tools:
enrich_url: '{id}'
title: Dismiss or snooze a signal report
description: >
- Transition a single signal report to a new state. Use 'suppressed' to dismiss the report from the inbox (the
+ Transition a single signal report to a new state. Use 'resolved' when the work this report asked for has
+ been done (e.g. you fixed the issue it describes), 'suppressed' to dismiss the report from the inbox (the
user has reviewed it and decided no action is needed), or 'potential' to snooze/restore it back into the
- pipeline for later review. Optionally include a `dismissal_reason` — a canonical code from the inbox UI
- (`already_fixed`, `report_unclear`, `analysis_wrong`, `wontfix_intentional`, `wontfix_irrelevant`, `other`),
- so it renders as a labelled chip rather than a raw string. `already_fixed` is a snooze, not a dismissal:
- pair it with state='potential'. Use `other` plus a `dismissal_note` (free-form text, up to 4000 chars) for
- anything that doesn't fit a code. Both are persisted as a DISMISSAL artefact on the report so the rationale
- survives later transitions. Returns 409 if the transition is not allowed from the report's current status.
- To transition several reports at once, use `inbox-reports-bulk-set-state` instead of calling this per
- report.
+ pipeline for later review. Resolving is only allowed from a researched status (ready or pending_input) or a
+ suppressed report — other statuses return 409. Optionally include a `dismissal_reason` — a canonical code
+ from the inbox UI (`already_fixed`, `report_unclear`, `analysis_wrong`, `wontfix_intentional`,
+ `wontfix_irrelevant`, `other`), so it renders as a labelled chip rather than a raw string; on a 'resolved'
+ transition it records why it was resolved. When the requested work is done, prefer state='resolved' over
+ `already_fixed`+snooze — reserve `already_fixed` with state='potential' for "fixed by something else / might
+ recur" cases, so the report reappears if the issue comes back. Use `other` plus a `dismissal_note`
+ (free-form text, up to 4000 chars) for anything that doesn't fit a code. Both are persisted as a DISMISSAL
+ artefact on the report so the rationale survives later transitions. Returns 409 if the transition is not
+ allowed from the report's current status. To transition several reports at once, use
+ `inbox-reports-bulk-set-state` instead of calling this per report.
inbox-reports-update:
operation: signals_reports_partial_update
enabled: true
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 8276e9ce77e8..e825b5825b8f 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -152,6 +152,7 @@ __all__ = [
"get_code_workflow_config",
"get_conversation_task_dtos",
"get_latest_pr_url_by_task",
+ "get_merged_pr_task_ids",
"get_latest_run_by_task",
"get_resume_snapshot_carry_state",
"get_sandbox_custom_image",
@@ -172,6 +173,7 @@ __all__ = [
"is_internal_debug_team",
"is_task_controllable_by_user",
"is_valid_sandbox_env_var_key",
+ "latest_task_run_pr_merged_subquery",
"latest_task_run_pr_url_subquery",
"leave_task_presence",
"list_sandbox_custom_images",
@@ -613,6 +615,41 @@ def latest_task_run_pr_url_subquery(*conditions: Q, **task_run_filter) -> Subque
)
+def latest_task_run_pr_merged_subquery(*conditions: Q, **task_run_filter) -> Subquery:
+ """``Subquery`` of the webhook-attested merge flag on the same run ``latest_task_run_pr_url_subquery``
+ resolves for the same correlation — so a caller displaying that PR can say whether it merged rather
+ than inferring it. Same filter and ordering, so the two always describe one run. NULL when no
+ PR-bearing run matches; treat that as "not merged"."""
+ return Subquery(
+ TaskRun.objects.filter(*conditions, output__pr_url__isnull=False, **task_run_filter)
+ .exclude(output__pr_url="")
+ .order_by("-created_at")
+ .annotate(output_pr_merged_flag=KeyTextTransform("pr_merged", "output"))
+ .values("output_pr_merged_flag")[:1],
+ output_field=CharField(),
+ )
+
+
+def get_merged_pr_task_ids(task_ids: Iterable[str | UUID]) -> set[str]:
+ """Of the supplied tasks, those whose latest PR-bearing run has a webhook-attested merged PR.
+
+ Batched counterpart to ``latest_task_run_pr_merged_subquery``, matching ``get_latest_pr_url_by_task``
+ run-for-run so the merge flag describes the PR URL that helper returns.
+ """
+ ids = [str(t) for t in task_ids]
+ if not ids:
+ return set()
+ rows = (
+ TaskRun.objects.filter(task_id__in=ids, output__pr_url__isnull=False)
+ .exclude(output__pr_url="")
+ .order_by("task_id", "-created_at", "-id")
+ .annotate(output_pr_merged_flag=KeyTextTransform("pr_merged", "output"))
+ .values("task_id", "output_pr_merged_flag")
+ .distinct("task_id")
+ )
+ return {str(row["task_id"]) for row in rows if row["output_pr_merged_flag"] in ("true", "True")}
+
+
def get_latest_run_by_task(task_ids: Iterable[str | UUID]) -> dict[str, contracts.TaskRunDTO]:
"""Most-recent run per task (by ``created_at`` then ``id``), for the supplied task ids."""
ids = [str(t) for t in task_ids]
@@ -1645,6 +1682,32 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(
_TERMINAL_TASK_RUN_STATUSES = (TaskRun.Status.COMPLETED, TaskRun.Status.FAILED, TaskRun.Status.CANCELLED)
+# `output.pr_merged` is GitHub's word, recorded by the PR webhook (`_record_run_pr_merged`) — never
+# the caller's. Signals reads it to decide refund finality (billing.report_pr_is_merged): a report
+# whose PR merged keeps its resolved status through a refund instead of being suppressed and having
+# its PR closed. Any caller-writable path to this flag would let a `task:write` holder mark an open
+# PR merged, resolve the report, and refund it while keeping the work — so every output writer has to
+# go through `_merge_caller_output`, not merge caller output directly.
+_WEBHOOK_ATTESTED_RUN_OUTPUT_KEYS = frozenset({"pr_merged"})
+
+
+def _apply_caller_output(stored: object, incoming: dict, merged: dict) -> dict:
+ """Enforce the webhook-attested keys on a caller's output write.
+
+ `merged` is whatever the writer built from `incoming` (a wholesale replacement for
+ `set_task_run_output`, a merge over stored output for the PATCH path); this drops any attested
+ key the caller supplied and restores the stored one. The attestation is bound to the PR it was
+ made about, so when the caller points the run at a different `pr_url` the stored flag described
+ the old PR and is dropped rather than silently transferred onto the new one.
+ """
+ existing = stored if isinstance(stored, dict) else {}
+ same_pr = not incoming.get("pr_url") or incoming["pr_url"] == existing.get("pr_url")
+ for key in _WEBHOOK_ATTESTED_RUN_OUTPUT_KEYS:
+ merged.pop(key, None)
+ if same_pr and existing.get(key):
+ merged[key] = existing[key]
+ return merged
+
def _task_run_queryset():
return TaskRun.objects.select_related(
@@ -1896,7 +1959,9 @@ def update_task_run(
for key, value in validated_data.items():
if key == "output" and isinstance(value, dict):
existing_output = run.output if isinstance(run.output, dict) else {}
- setattr(run, key, {**existing_output, **value})
+ # Same attested-key policy as set_task_run_output — this PATCH surface is
+ # caller-controlled too, so it can't be a back door to output.pr_merged.
+ setattr(run, key, _apply_caller_output(existing_output, value, {**existing_output, **value}))
update_fields.add(key)
continue
if key == "state_remove_keys":
@@ -2001,13 +2066,12 @@ def set_task_run_output(
return None
task = run.task
# Preserve PR facts a webhook may have written concurrently: this assignment is wholesale,
- # so a bare `= output` would drop output.pr_url / output.pr_merged recorded out of band.
+ # so a bare `= output` would drop output.pr_url recorded out of band.
existing = run.output if isinstance(run.output, dict) else {}
merged = {**output}
- for key in ("pr_url", "pr_merged"):
- if not merged.get(key) and existing.get(key):
- merged[key] = existing[key]
- run.output = merged
+ if not merged.get("pr_url") and existing.get("pr_url"):
+ merged["pr_url"] = existing["pr_url"]
+ run.output = _apply_caller_output(existing, output, merged)
run.save(update_fields=["output", "updated_at"])
if task.json_schema:
signal_workflow_completion(run.id, TaskRun.Status.COMPLETED, None)
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 1d9de7f2f009..f887523bcb81 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -3959,6 +3959,10 @@ class TestTaskAutomationAPI(BaseTaskAPITest):
mock_run_task_automation.assert_not_called()
+_PR_URL = "https://github.com/posthog/posthog-js/pull/1"
+_OTHER_PR_URL = "https://github.com/posthog/posthog-js/pull/2"
+
+
class TestTaskRunAPI(BaseTaskAPITest):
def _create_run_for_origin(self, origin_product: Task.OriginProduct) -> tuple[Task, TaskRun]:
task = Task.objects.create(
@@ -3993,6 +3997,52 @@ class TestTaskRunAPI(BaseTaskAPITest):
response = self.client.get("/api/projects/@current/tasks/not-a-uuid/runs/")
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ @parameterized.expand(
+ [
+ # Both caller-controlled output writers have to enforce this: the dedicated set_output
+ # action and the generic run PATCH, which merges `output` just the same.
+ (endpoint, case_name, webhook_flag, caller_pr_url, expected)
+ for endpoint in ("set_output/", "")
+ for case_name, webhook_flag, caller_pr_url, expected in [
+ ("caller_cannot_forge", None, _PR_URL, False),
+ ("webhook_flag_survives_caller_write", True, _PR_URL, True),
+ # The attestation is about one PR — repointing the run drops it rather than
+ # transferring GitHub's word about the old PR onto a new one.
+ ("flag_dropped_when_caller_changes_pr", True, _OTHER_PR_URL, False),
+ ]
+ ]
+ )
+ @patch("products.tasks.backend.facade.api._post_slack_update_for_pr")
+ @patch("products.tasks.backend.models.TaskRun.emit_progress_event")
+ @patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")
+ def test_caller_output_writes_never_set_pr_merged(
+ self,
+ endpoint: str,
+ _case_name: str,
+ webhook_flag: bool | None,
+ caller_pr_url: str,
+ expected: bool,
+ _mock_publish_stream_state_event: MagicMock,
+ _mock_emit_progress_event: MagicMock,
+ _mock_post_slack_update_for_pr: MagicMock,
+ ) -> None:
+ # pr_merged is GitHub's word that the PR merged, and signals reads it to decide refund
+ # finality — so a task:write caller must not be able to write, clear, or move it.
+ task, run = self._create_run_for_origin(Task.OriginProduct.USER_CREATED)
+ if webhook_flag is not None:
+ run.output = {"pr_url": _PR_URL, "pr_merged": webhook_flag}
+ run.save(update_fields=["output"])
+
+ response = self.client.patch(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/{endpoint}",
+ {"output": {"pr_url": caller_pr_url, "pr_merged": True}},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ run.refresh_from_db()
+ self.assertEqual((run.output or {}).get("pr_merged", False), expected)
+
@patch("products.tasks.backend.facade.api._post_slack_update_for_pr")
@patch("products.tasks.backend.models.TaskRun.emit_progress_event")
@patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 5b4bd8563bdd..9fe599ec0277 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -4380,7 +4380,7 @@
}
},
"inbox-reports-bulk-set-state": {
- "description": "Transition many signal reports to the same state in one call — the bulk form of `inbox-reports-set-state`, for clearing or snoozing a batch of inbox reports without one request per report. Pass `ids` (1–100 report ids) and a `state` ('suppressed' to dismiss, 'potential' to snooze/restore); the optional `dismissal_reason` (same canonical codes as the single-report tool), `dismissal_note`, and `snooze_for` apply to every id. Each id is processed independently, so the whole call returns 200 even on partial failure: inspect `results` (one entry per id, in request order) and the `transitioned_count` / `skipped_count` / `failed_count` / `not_found_count` summary. An id whose transition isn't allowed from its current status comes back as `skipped` (the single-report 409) while the rest still go through.",
+ "description": "Transition many signal reports to the same state in one call — the bulk form of `inbox-reports-set-state`, for clearing, snoozing, or resolving a batch of inbox reports without one request per report. Pass `ids` (1–100 report ids) and a `state` ('resolved' when the requested work is done, 'suppressed' to dismiss, 'potential' to snooze/restore); the optional `dismissal_reason` (same canonical codes as the single-report tool), `dismissal_note`, and `snooze_for` apply to every id. Each id is processed independently, so the whole call returns 200 even on partial failure: inspect `results` (one entry per id, in request order) and the `transitioned_count` / `skipped_count` / `failed_count` / `not_found_count` summary. An id whose transition isn't allowed from its current status comes back as `skipped` (the single-report 409) while the rest still go through.",
"category": "Signals",
"feature": "signals",
"summary": "Dismiss or snooze signal reports in bulk",
@@ -4422,7 +4422,7 @@
}
},
"inbox-reports-set-state": {
- "description": "Transition a single signal report to a new state. Use 'suppressed' to dismiss the report from the inbox (the user has reviewed it and decided no action is needed), or 'potential' to snooze/restore it back into the pipeline for later review. Optionally include a `dismissal_reason` — a canonical code from the inbox UI (`already_fixed`, `report_unclear`, `analysis_wrong`, `wontfix_intentional`, `wontfix_irrelevant`, `other`), so it renders as a labelled chip rather than a raw string. `already_fixed` is a snooze, not a dismissal: pair it with state='potential'. Use `other` plus a `dismissal_note` (free-form text, up to 4000 chars) for anything that doesn't fit a code. Both are persisted as a DISMISSAL artefact on the report so the rationale survives later transitions. Returns 409 if the transition is not allowed from the report's current status. To transition several reports at once, use `inbox-reports-bulk-set-state` instead of calling this per report.",
+ "description": "Transition a single signal report to a new state. Use 'resolved' when the work this report asked for has been done (e.g. you fixed the issue it describes), 'suppressed' to dismiss the report from the inbox (the user has reviewed it and decided no action is needed), or 'potential' to snooze/restore it back into the pipeline for later review. Resolving is only allowed from a researched status (ready or pending_input) or a suppressed report — other statuses return 409. Optionally include a `dismissal_reason` — a canonical code from the inbox UI (`already_fixed`, `report_unclear`, `analysis_wrong`, `wontfix_intentional`, `wontfix_irrelevant`, `other`), so it renders as a labelled chip rather than a raw string; on a 'resolved' transition it records why it was resolved. When the requested work is done, prefer state='resolved' over `already_fixed`+snooze — reserve `already_fixed` with state='potential' for \"fixed by something else / might recur\" cases, so the report reappears if the issue comes back. Use `other` plus a `dismissal_note` (free-form text, up to 4000 chars) for anything that doesn't fit a code. Both are persisted as a DISMISSAL artefact on the report so the rationale survives later transitions. Returns 409 if the transition is not allowed from the report's current status. To transition several reports at once, use `inbox-reports-bulk-set-state` instead of calling this per report.",
"category": "Signals",
"feature": "signals",
"summary": "Dismiss or snooze a signal report",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 94b424431eec..56e052daaa34 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -4661,7 +4661,7 @@
}
},
"inbox-reports-bulk-set-state": {
- "description": "Transition many signal reports to the same state in one call — the bulk form of `inbox-reports-set-state`, for clearing or snoozing a batch of inbox reports without one request per report. Pass `ids` (1–100 report ids) and a `state` ('suppressed' to dismiss, 'potential' to snooze/restore); the optional `dismissal_reason` (same canonical codes as the single-report tool), `dismissal_note`, and `snooze_for` apply to every id. Each id is processed independently, so the whole call returns 200 even on partial failure: inspect `results` (one entry per id, in request order) and the `transitioned_count` / `skipped_count` / `failed_count` / `not_found_count` summary. An id whose transition isn't allowed from its current status comes back as `skipped` (the single-report 409) while the rest still go through.",
+ "description": "Transition many signal reports to the same state in one call — the bulk form of `inbox-reports-set-state`, for clearing, snoozing, or resolving a batch of inbox reports without one request per report. Pass `ids` (1–100 report ids) and a `state` ('resolved' when the requested work is done, 'suppressed' to dismiss, 'potential' to snooze/restore); the optional `dismissal_reason` (same canonical codes as the single-report tool), `dismissal_note`, and `snooze_for` apply to every id. Each id is processed independently, so the whole call returns 200 even on partial failure: inspect `results` (one entry per id, in request order) and the `transitioned_count` / `skipped_count` / `failed_count` / `not_found_count` summary. An id whose transition isn't allowed from its current status comes back as `skipped` (the single-report 409) while the rest still go through.",
"category": "Signals",
"feature": "signals",
"summary": "Dismiss or snooze signal reports in bulk",
@@ -4703,7 +4703,7 @@
}
},
"inbox-reports-set-state": {
- "description": "Transition a single signal report to a new state. Use 'suppressed' to dismiss the report from the inbox (the user has reviewed it and decided no action is needed), or 'potential' to snooze/restore it back into the pipeline for later review. Optionally include a `dismissal_reason` — a canonical code from the inbox UI (`already_fixed`, `report_unclear`, `analysis_wrong`, `wontfix_intentional`, `wontfix_irrelevant`, `other`), so it renders as a labelled chip rather than a raw string. `already_fixed` is a snooze, not a dismissal: pair it with state='potential'. Use `other` plus a `dismissal_note` (free-form text, up to 4000 chars) for anything that doesn't fit a code. Both are persisted as a DISMISSAL artefact on the report so the rationale survives later transitions. Returns 409 if the transition is not allowed from the report's current status. To transition several reports at once, use `inbox-reports-bulk-set-state` instead of calling this per report.",
+ "description": "Transition a single signal report to a new state. Use 'resolved' when the work this report asked for has been done (e.g. you fixed the issue it describes), 'suppressed' to dismiss the report from the inbox (the user has reviewed it and decided no action is needed), or 'potential' to snooze/restore it back into the pipeline for later review. Resolving is only allowed from a researched status (ready or pending_input) or a suppressed report — other statuses return 409. Optionally include a `dismissal_reason` — a canonical code from the inbox UI (`already_fixed`, `report_unclear`, `analysis_wrong`, `wontfix_intentional`, `wontfix_irrelevant`, `other`), so it renders as a labelled chip rather than a raw string; on a 'resolved' transition it records why it was resolved. When the requested work is done, prefer state='resolved' over `already_fixed`+snooze — reserve `already_fixed` with state='potential' for \"fixed by something else / might recur\" cases, so the report reappears if the issue comes back. Use `other` plus a `dismissal_note` (free-form text, up to 4000 chars) for anything that doesn't fit a code. Both are persisted as a DISMISSAL artefact on the report so the rationale survives later transitions. Returns 409 if the transition is not allowed from the report's current status. To transition several reports at once, use `inbox-reports-bulk-set-state` instead of calling this per report.",
"category": "Signals",
"feature": "signals",
"summary": "Dismiss or snooze a signal report",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 79eabc6d719f..0338462a3d5f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -39986,6 +39986,8 @@ export namespace Schemas {
* @nullable
*/
readonly implementation_pr_url: string | null;
+ /** Whether that implementation PR is merged, per the GitHub webhook. False when there is no PR or it hasn't merged. Report status doesn't imply this: a resolved report may have been resolved directly, without a merged PR. */
+ readonly implementation_pr_merged: boolean;
/** The report's PR refund, when one exists. One refund per report, ever. */
readonly refund: SignalReportRefund | null;
/** Why refunding this report's PR would be rejected right now, or null when a refund would be accepted (see the field's schema for the reason values). */
@@ -56783,6 +56785,7 @@ export namespace Schemas {
/**
* * `suppressed` - suppressed
* * `potential` - potential
+ * * `resolved` - resolved
*/
export type SignalReportStateEnum = typeof SignalReportStateEnum[keyof typeof SignalReportStateEnum];
@@ -56790,15 +56793,17 @@ export namespace Schemas {
export const SignalReportStateEnum = {
Suppressed: 'suppressed',
Potential: 'potential',
+ Resolved: 'resolved',
} as const;
export interface SignalReportBulkStateRequest {
- /** Target state for the report. Use 'suppressed' to dismiss the report from the inbox, or 'potential' to snooze/reopen it for later review.
+ /** Target state for the report. Use 'suppressed' to dismiss the report from the inbox, 'potential' to snooze/reopen it for later review, or 'resolved' when the work this report asked for has been done. Resolving is only allowed from a researched status (ready or pending_input) or a suppressed report; other statuses return 409 (skipped in bulk).
*
* * `suppressed` - suppressed
- * * `potential` - potential */
+ * * `potential` - potential
+ * * `resolved` - resolved */
state: SignalReportStateEnum;
- /** Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. 'already_fixed' is a snooze, not a dismissal: pair it with state='potential' (restore) so the report reappears if the issue recurs. Use 'other' together with a dismissal_note for anything that doesn't fit a code.
+ /** Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. When the work this report asked for is done, the honest transition is state='resolved' (the reason/note records why). Reserve 'already_fixed' with state='potential' (snooze/restore) for "fixed by something else / might recur" cases, so the report reappears if the issue comes back. Use 'other' together with a dismissal_note for anything that doesn't fit a code.
*
* * `already_fixed` - Already fixed
* * `report_unclear` - Report is unclear to me
@@ -56916,12 +56921,13 @@ export namespace Schemas {
}
export interface SignalReportStateRequest {
- /** Target state for the report. Use 'suppressed' to dismiss the report from the inbox, or 'potential' to snooze/reopen it for later review.
+ /** Target state for the report. Use 'suppressed' to dismiss the report from the inbox, 'potential' to snooze/reopen it for later review, or 'resolved' when the work this report asked for has been done. Resolving is only allowed from a researched status (ready or pending_input) or a suppressed report; other statuses return 409 (skipped in bulk).
*
* * `suppressed` - suppressed
- * * `potential` - potential */
+ * * `potential` - potential
+ * * `resolved` - resolved */
state: SignalReportStateEnum;
- /** Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. 'already_fixed' is a snooze, not a dismissal: pair it with state='potential' (restore) so the report reappears if the issue recurs. Use 'other' together with a dismissal_note for anything that doesn't fit a code.
+ /** Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. When the work this report asked for is done, the honest transition is state='resolved' (the reason/note records why). Reserve 'already_fixed' with state='potential' (snooze/restore) for "fixed by something else / might recur" cases, so the report reappears if the issue comes back. Use 'other' together with a dismissal_note for anything that doesn't fit a code.
*
* * `already_fixed` - Already fixed
* * `report_unclear` - Report is unclear to me
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 0f2202f82ffb..3acb521944ed 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -124,8 +124,8 @@ export const SignalsReportsPartialUpdateBody = /* @__PURE__ */ zod
* so internal transition_to kwargs (reset_weight, error, ...) can't be injected.
*
* Body: {
- * "state": "suppressed" | "potential",
- * # Optional dismissal feedback (honored when state == "suppressed" or "potential"):
+ * "state": "suppressed" | "potential" | "resolved",
+ * # Optional dismissal feedback (honored when state == "suppressed", "potential", or "resolved"):
* "dismissal_reason": "<canonical reason code, see SIGNAL_REPORT_DISMISSAL_REASON_CHOICES>",
* "dismissal_note": "free-form text",
* # Optional, only honored for state == "potential":
@@ -147,10 +147,10 @@ export const signalsReportsStateCreateBodySnoozeForMax = 100000
export const SignalsReportsStateCreateBody = /* @__PURE__ */ zod.object({
state: zod
- .enum(['suppressed', 'potential'])
- .describe('* `suppressed` - suppressed\n* `potential` - potential')
+ .enum(['suppressed', 'potential', 'resolved'])
+ .describe('* `suppressed` - suppressed\n* `potential` - potential\n* `resolved` - resolved')
.describe(
- "Target state for the report. Use 'suppressed' to dismiss the report from the inbox, or 'potential' to snooze/reopen it for later review.\n\n* `suppressed` - suppressed\n* `potential` - potential"
+ "Target state for the report. Use 'suppressed' to dismiss the report from the inbox, 'potential' to snooze/reopen it for later review, or 'resolved' when the work this report asked for has been done. Resolving is only allowed from a researched status (ready or pending_input) or a suppressed report; other statuses return 409 (skipped in bulk).\n\n* `suppressed` - suppressed\n* `potential` - potential\n* `resolved` - resolved"
),
dismissal_reason: zod
.enum([
@@ -166,7 +166,7 @@ export const SignalsReportsStateCreateBody = /* @__PURE__ */ zod.object({
)
.optional()
.describe(
- "Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. 'already_fixed' is a snooze, not a dismissal: pair it with state='potential' (restore) so the report reappears if the issue recurs. Use 'other' together with a dismissal_note for anything that doesn't fit a code.\n\n* `already_fixed` - Already fixed\n* `report_unclear` - Report is unclear to me\n* `analysis_wrong` - Agent's analysis is wrong\n* `wontfix_intentional` - Won't fix - intentional behavior\n* `wontfix_irrelevant` - Won't fix - issue is real but insignificant\n* `other` - Something else…"
+ "Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. When the work this report asked for is done, the honest transition is state='resolved' (the reason/note records why). Reserve 'already_fixed' with state='potential' (snooze/restore) for \"fixed by something else / might recur\" cases, so the report reappears if the issue comes back. Use 'other' together with a dismissal_note for anything that doesn't fit a code.\n\n* `already_fixed` - Already fixed\n* `report_unclear` - Report is unclear to me\n* `analysis_wrong` - Agent's analysis is wrong\n* `wontfix_intentional` - Won't fix - intentional behavior\n* `wontfix_irrelevant` - Won't fix - issue is real but insignificant\n* `other` - Something else…"
),
dismissal_note: zod
.string()
@@ -338,10 +338,10 @@ export const signalsReportsBulkStateCreateBodyIdsMax = 100
export const SignalsReportsBulkStateCreateBody = /* @__PURE__ */ zod.object({
state: zod
- .enum(['suppressed', 'potential'])
- .describe('* `suppressed` - suppressed\n* `potential` - potential')
+ .enum(['suppressed', 'potential', 'resolved'])
+ .describe('* `suppressed` - suppressed\n* `potential` - potential\n* `resolved` - resolved')
.describe(
- "Target state for the report. Use 'suppressed' to dismiss the report from the inbox, or 'potential' to snooze/reopen it for later review.\n\n* `suppressed` - suppressed\n* `potential` - potential"
+ "Target state for the report. Use 'suppressed' to dismiss the report from the inbox, 'potential' to snooze/reopen it for later review, or 'resolved' when the work this report asked for has been done. Resolving is only allowed from a researched status (ready or pending_input) or a suppressed report; other statuses return 409 (skipped in bulk).\n\n* `suppressed` - suppressed\n* `potential` - potential\n* `resolved` - resolved"
),
dismissal_reason: zod
.enum([
@@ -357,7 +357,7 @@ export const SignalsReportsBulkStateCreateBody = /* @__PURE__ */ zod.object({
)
.optional()
.describe(
- "Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. 'already_fixed' is a snooze, not a dismissal: pair it with state='potential' (restore) so the report reappears if the issue recurs. Use 'other' together with a dismissal_note for anything that doesn't fit a code.\n\n* `already_fixed` - Already fixed\n* `report_unclear` - Report is unclear to me\n* `analysis_wrong` - Agent's analysis is wrong\n* `wontfix_intentional` - Won't fix - intentional behavior\n* `wontfix_irrelevant` - Won't fix - issue is real but insignificant\n* `other` - Something else…"
+ "Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. When the work this report asked for is done, the honest transition is state='resolved' (the reason/note records why). Reserve 'already_fixed' with state='potential' (snooze/restore) for \"fixed by something else / might recur\" cases, so the report reappears if the issue comes back. Use 'other' together with a dismissal_note for anything that doesn't fit a code.\n\n* `already_fixed` - Already fixed\n* `report_unclear` - Report is unclear to me\n* `analysis_wrong` - Agent's analysis is wrong\n* `wontfix_intentional` - Won't fix - intentional behavior\n* `wontfix_irrelevant` - Won't fix - issue is real but insignificant\n* `other` - Something else…"
),
dismissal_note: zod
.string()
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-bulk-set-state.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-bulk-set-state.json
index e248e07bc244..3b1ab0c9cbc2 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-bulk-set-state.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-bulk-set-state.json
@@ -7,7 +7,7 @@
"type": "string"
},
"dismissal_reason": {
- "description": "Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. 'already_fixed' is a snooze, not a dismissal: pair it with state='potential' (restore) so the report reappears if the issue recurs. Use 'other' together with a dismissal_note for anything that doesn't fit a code.\n\n* `already_fixed` - Already fixed\n* `report_unclear` - Report is unclear to me\n* `analysis_wrong` - Agent's analysis is wrong\n* `wontfix_intentional` - Won't fix - intentional behavior\n* `wontfix_irrelevant` - Won't fix - issue is real but insignificant\n* `other` - Something else…",
+ "description": "Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. When the work this report asked for is done, the honest transition is state='resolved' (the reason/note records why). Reserve 'already_fixed' with state='potential' (snooze/restore) for \"fixed by something else / might recur\" cases, so the report reappears if the issue comes back. Use 'other' together with a dismissal_note for anything that doesn't fit a code.\n\n* `already_fixed` - Already fixed\n* `report_unclear` - Report is unclear to me\n* `analysis_wrong` - Agent's analysis is wrong\n* `wontfix_intentional` - Won't fix - intentional behavior\n* `wontfix_irrelevant` - Won't fix - issue is real but insignificant\n* `other` - Something else…",
"enum": [
"already_fixed",
"report_unclear",
@@ -33,8 +33,8 @@
"type": "number"
},
"state": {
- "description": "Target state for the report. Use 'suppressed' to dismiss the report from the inbox, or 'potential' to snooze/reopen it for later review.\n\n* `suppressed` - suppressed\n* `potential` - potential",
- "enum": ["suppressed", "potential"],
+ "description": "Target state for the report. Use 'suppressed' to dismiss the report from the inbox, 'potential' to snooze/reopen it for later review, or 'resolved' when the work this report asked for has been done. Resolving is only allowed from a researched status (ready or pending_input) or a suppressed report; other statuses return 409 (skipped in bulk).\n\n* `suppressed` - suppressed\n* `potential` - potential\n* `resolved` - resolved",
+ "enum": ["suppressed", "potential", "resolved"],
"type": "string"
}
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-set-state.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-set-state.json
index d69c06104b17..16fe5f793c8b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-set-state.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-set-state.json
@@ -7,7 +7,7 @@
"type": "string"
},
"dismissal_reason": {
- "description": "Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. 'already_fixed' is a snooze, not a dismissal: pair it with state='potential' (restore) so the report reappears if the issue recurs. Use 'other' together with a dismissal_note for anything that doesn't fit a code.\n\n* `already_fixed` - Already fixed\n* `report_unclear` - Report is unclear to me\n* `analysis_wrong` - Agent's analysis is wrong\n* `wontfix_intentional` - Won't fix - intentional behavior\n* `wontfix_irrelevant` - Won't fix - issue is real but insignificant\n* `other` - Something else…",
+ "description": "Optional canonical reason code for the dismissal. Must be one of: already_fixed, report_unclear, analysis_wrong, wontfix_intentional, wontfix_irrelevant, other — these match the inbox UI so the rationale renders as a labelled chip rather than a raw code. When the work this report asked for is done, the honest transition is state='resolved' (the reason/note records why). Reserve 'already_fixed' with state='potential' (snooze/restore) for \"fixed by something else / might recur\" cases, so the report reappears if the issue comes back. Use 'other' together with a dismissal_note for anything that doesn't fit a code.\n\n* `already_fixed` - Already fixed\n* `report_unclear` - Report is unclear to me\n* `analysis_wrong` - Agent's analysis is wrong\n* `wontfix_intentional` - Won't fix - intentional behavior\n* `wontfix_irrelevant` - Won't fix - issue is real but insignificant\n* `other` - Something else…",
"enum": [
"already_fixed",
"report_unclear",
@@ -29,8 +29,8 @@
"type": "number"
},
"state": {
- "description": "Target state for the report. Use 'suppressed' to dismiss the report from the inbox, or 'potential' to snooze/reopen it for later review.\n\n* `suppressed` - suppressed\n* `potential` - potential",
- "enum": ["suppressed", "potential"],
+ "description": "Target state for the report. Use 'suppressed' to dismiss the report from the inbox, 'potential' to snooze/reopen it for later review, or 'resolved' when the work this report asked for has been done. Resolving is only allowed from a researched status (ready or pending_input) or a suppressed report; other statuses return 409 (skipped in bulk).\n\n* `suppressed` - suppressed\n* `potential` - potential\n* `resolved` - resolved",
+ "enum": ["suppressed", "potential", "resolved"],
"type": "string"
}
},