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): iterate a scout report on content revisions, not every edit (#86649)

Georgiy Tarasov1c724eccb67c
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.md
index 4dfdbe594262..f110367435c4 100644
--- a/docs/internal/signals-pr-lifecycle.md
+++ b/docs/internal/signals-pr-lifecycle.md
@@ -8,6 +8,22 @@ The shared PR-linking service applies this rule to task outputs and agent attach
An existing attachment retry does not reopen a report, and importing legacy assignments preserves its status.
Suppressed reports remain suppressed when another PR is attached.
+## Scout revisions
+
+Scout edits increment the content revision count only when the title or summary changes. Notes, evidence, routing updates, and unchanged text do not spend a revision. The edit response always includes the report's running revision total.
+
+The revision and corroboration counters are nullable, with no database or model default. Reads treat `NULL` as zero, so existing reports and reports created by older workers need no backfill. The migration adds nullable columns without rewriting rows or validating a `NOT NULL` constraint. PostgreSQL still needs a brief exclusive table lock to add the columns.
+
+A scout can request a replacement when its rewrite changes the fix. The server binds that decision to verified automated predecessor PRs and the exact research pass and content revision. It starts at most one replacement per version, within the scout revision cap, and stops automatic closure if another edit changes the report while the replacement runs. Free-form scout notes always remain individual activity entries. Only notes explicitly marked `corroboration_only` count towards the four-confirmation cap; later confirmations increase the collapsed count shown by both the web and desktop inboxes.
+
+Autostart binds task content to the report title, summary, research pass, and scout revision captured before external lookups. It checks that snapshot under the report lock before stamping a version as implemented, and retries from current content if the report changed.
+
+Supersession verifies predecessors only for a real rewrite within the revision cap. Missing or stale verification rejects the edit before commit so the same request can be retried. GitHub calls happen outside the report lock.
+
+An accepted scout replacement decision commits a protected `implementation_dispatch` artefact with the edit. A Celery worker resumes repository preparation, retains the editing scout's owner exclusion, and rechecks the exact decision before creating a task. Technical failures retry with exponential backoff from one minute to fifteen minutes. A five-minute sweep recovers lost queue messages and expired worker leases in bounded pages. The dispatch state records pending, processing, retrying, blocked, started, or canceled work; it is available through the existing artefact API. A policy block waits for a new edit or research trigger, rather than starting automatically when a setting or quota changes.
+
+Only the first four content revisions can request a scout replacement, including revisions that did not request one. An over-cap request preserves the rewrite and records the revision-limit reason without claiming that the old fix is still correct. Reports under active research cannot accept a supersede claim. The current revision count is read inside the edit transaction, so a failed read cannot report a failed edit after committing a note or evidence.
+
## Verification plans
After research completes, actionable reports can include a `Verification plan` note for the implementation agent.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index b38f45770049..cfa18e9e278c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10216,6 +10216,10 @@ snapshots:
hash: v1.k794b7964.f723b2160bdf85cd5a827fa3dac4c281d75950f47555cdef7fc01f2ef689dfc6.wAOg7AG2Pf4mYO8EjKdD8lFlC1Ulv4MhkXIEMkzfCrg
scenes-app-signals-artefactloglist--replacement-lifecycle--light:
hash: v1.k794b7964.9c43f6666a1a6a374d7de2874e8041d143d372b268675b7effc129b4759c676f.1ksfg48ORs-DX0VjvAFzGKg98c7Ikzp_Cr-tksdqVZ8
+ scenes-app-signals-artefactloglist--revision-limit--dark:
+ hash: v1.k794b7964.d9e475caa06b8c102d144f5a714e26addf9fdfe71d0b5008a4d09448142d60d7.KrLa7tfvjyW7kx7jRx7f8a2uctJrVoOP47m2TBccgrc
+ scenes-app-signals-artefactloglist--revision-limit--light:
+ hash: v1.k794b7964.58b202e3e75574aea881674a34f3f4acb53f580c5a825ba170184ad997668fca.SOS8aKqoFBzkUv7HNSriyld2FYPYUPsq4Pqhb-91h64
scenes-app-signals-artefactpullrequest--open--dark:
hash: v1.k794b7964.9cdaa27967468d3b2fc4431b8833b9cc184af6584881b783b28be6d504695272.v-TYHIq6zFNHT_YPm60gY4WyJE45sSXL_JmtDGW5h8M
scenes-app-signals-artefactpullrequest--open--light:
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 8b0b948b5aaa..2ee2ae517b7e 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -114,6 +114,7 @@ from products.signals.backend.tasks import (
pause_inactive_signal_scouts,
prune_expired_scratchpad_entries_task,
refresh_signal_repository_activity,
+ sweep_implementation_dispatches,
sync_pending_signals_refund_credits,
)
from products.skills.backend.tasks import sync_community_skills
@@ -399,6 +400,14 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
expires_seconds=2 * 60,
)
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(minute="*/5"),
+ sweep_implementation_dispatches.s(),
+ name="recover pending signals implementation starts",
+ expires_seconds=5 * 60,
+ )
+
# Re-enqueue signals PR refunds whose billing credit sync hasn't landed - hourly at minute 25
sender.add_periodic_task(
crontab(hour="*", minute="25"),
diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.ts
index 8f38854836eb..b7bd461c4ca1 100644
--- a/products/desktop/packages/shared/src/domain-types.ts
+++ b/products/desktop/packages/shared/src/domain-types.ts
@@ -753,6 +753,7 @@ export interface SignalReport {
created_at: string;
updated_at: string;
artefact_count: number;
+ collapsed_note_count?: number;
/** P0–P4 from priority judgment when the report is researched */
priority?: SignalReportPriority | null;
/** Actionability choice from the actionability judgment artefact. */
diff --git a/products/desktop/packages/ui/src/features/inbox/components/AgentRunDetail.tsx b/products/desktop/packages/ui/src/features/inbox/components/AgentRunDetail.tsx
index 93797eda4993..aa380c763a87 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/AgentRunDetail.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/AgentRunDetail.tsx
@@ -424,7 +424,10 @@ function AgentRunDetailContent({ report }: { report: SignalReport }) {
)}
</RightColumnSection>
)}
- <ReportActivitySection reportId={report.id} />
+ <ReportActivitySection
+ reportId={report.id}
+ collapsedNoteCount={report.collapsed_note_count}
+ />
</div>
</div>
</div>
diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx
index d3ad715fad2c..cbc29556d019 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx
@@ -101,7 +101,10 @@ export function ReportDetailContent({
>
<ReportReviewersSection report={report} />
<ReportRunsSection report={report} />
- <ReportActivitySection reportId={report.id} />
+ <ReportActivitySection
+ reportId={report.id}
+ collapsedNoteCount={report.collapsed_note_count}
+ />
</InboxDetailFrame>
</ReportChatLayout>
);
diff --git a/products/desktop/packages/ui/src/features/inbox/components/detail/ReportActivitySection.stories.tsx b/products/desktop/packages/ui/src/features/inbox/components/detail/ReportActivitySection.stories.tsx
new file mode 100644
index 000000000000..7f1807231b3b
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/components/detail/ReportActivitySection.stories.tsx
@@ -0,0 +1,18 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { ReportActivitySection } from "./ReportActivitySection";
+
+const meta: Meta<typeof ReportActivitySection> = {
+ title: "Inbox/Reports/Activity confirmations",
+ component: ReportActivitySection,
+ parameters: { layout: "padded" },
+ args: { reportId: "example-report", collapsedNoteCount: 3 },
+ play: async ({ canvas, userEvent }): Promise<void> => {
+ await userEvent.click(canvas.getByText("Activity"));
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof ReportActivitySection>;
+
+export const SeveralConfirmations: Story = {};
+export const OneConfirmation: Story = { args: { collapsedNoteCount: 1 } };
diff --git a/products/desktop/packages/ui/src/features/inbox/components/detail/ReportActivitySection.test.tsx b/products/desktop/packages/ui/src/features/inbox/components/detail/ReportActivitySection.test.tsx
new file mode 100644
index 000000000000..b04149eedb0b
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/components/detail/ReportActivitySection.test.tsx
@@ -0,0 +1,34 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("@posthog/ui/features/inbox/hooks/useInboxReports", () => ({
+ useInboxReportArtefacts: () => ({ data: { results: [] } }),
+}));
+vi.mock("./ArtefactLogList", () => ({ ArtefactLogList: () => null }));
+
+import { ReportActivitySection } from "./ReportActivitySection";
+
+describe("ReportActivitySection", () => {
+ it.each([1, 3])(
+ "shows %i collapsed confirmations without visible artefacts",
+ (count) => {
+ render(
+ <ReportActivitySection
+ reportId="report-1"
+ collapsedNoteCount={count}
+ />,
+ );
+ fireEvent.click(screen.getByText("Activity"));
+ expect(
+ screen.getByText(
+ `Corroborated ${count} more ${count === 1 ? "time" : "times"} by a scout, with nothing new to add.`,
+ ),
+ ).toBeTruthy();
+ },
+ );
+
+ it("hides an activity section with no entries or confirmations", () => {
+ const { container } = render(<ReportActivitySection reportId="report-1" />);
+ expect(container.firstChild).toBeNull();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/inbox/components/detail/ReportActivitySection.tsx b/products/desktop/packages/ui/src/features/inbox/components/detail/ReportActivitySection.tsx
index 1f7cc7baf8ab..f9c7a663a663 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/detail/ReportActivitySection.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/detail/ReportActivitySection.tsx
@@ -3,6 +3,7 @@ import { ArtefactLogList } from "@posthog/ui/features/inbox/components/detail/Ar
import { selectUsefulReportActivity } from "@posthog/ui/features/inbox/components/detail/reportActivity";
import { RightColumnSection } from "@posthog/ui/features/inbox/components/RightColumnSection";
import { useInboxReportArtefacts } from "@posthog/ui/features/inbox/hooks/useInboxReports";
+import type { ReactElement } from "react";
/**
* The report's useful work history, shared by every report detail surface.
@@ -12,11 +13,13 @@ import { useInboxReportArtefacts } from "@posthog/ui/features/inbox/hooks/useInb
export function ReportActivitySection({
reportId,
hideCommitDiffs,
+ collapsedNoteCount = 0,
}: {
reportId: string;
/** Drop the per-commit diff toggle (PR detail shows the full diff already). */
hideCommitDiffs?: boolean;
-}) {
+ collapsedNoteCount?: number;
+}): ReactElement | null {
// Agents append artefacts while the report is open, so the app-wide
// 5-minute stale time would hide progress from someone watching the report.
const { data: artefactsResp } = useInboxReportArtefacts(reportId, {
@@ -25,7 +28,7 @@ export function ReportActivitySection({
});
const artefacts = selectUsefulReportActivity(artefactsResp?.results ?? []);
- if (artefacts.length === 0) return null;
+ if (artefacts.length === 0 && collapsedNoteCount === 0) return null;
return (
<RightColumnSection
@@ -36,9 +39,18 @@ export function ReportActivitySection({
rightSlot={
<span className="cursor-default select-none text-[12px] text-gray-10 tabular-nums">
{artefacts.length} entr{artefacts.length === 1 ? "y" : "ies"}
+ {collapsedNoteCount > 0 &&
+ ` · ${collapsedNoteCount} ${collapsedNoteCount === 1 ? "confirmation" : "confirmations"}`}
</span>
}
>
+ {collapsedNoteCount > 0 && (
+ <p className="mb-3 text-gray-10 text-xs">
+ Corroborated {collapsedNoteCount} more{" "}
+ {collapsedNoteCount === 1 ? "time" : "times"} by a scout, with nothing
+ new to add.
+ </p>
+ )}
<ArtefactLogList
reportId={reportId}
artefacts={artefacts}
diff --git a/products/signals/backend/artefact_schemas.py b/products/signals/backend/artefact_schemas.py
index 1d4cf16b8de1..97fd8bafbeeb 100644
--- a/products/signals/backend/artefact_schemas.py
+++ b/products/signals/backend/artefact_schemas.py
@@ -618,6 +618,8 @@ class ImplementationDecision(BaseModel):
targets: list[ImplementationTarget] = Field(default_factory=list)
research_run_count: int | None = None
research_started_at: datetime | None = None
+ content_revision_count: int = 0
+ blocked_reason: Literal["revision_limit"] | None = None
@field_validator("reason")
@classmethod
@@ -633,6 +635,17 @@ class ImplementationReplacement(BaseModel):
run_id: UUID
+class ImplementationDispatch(BaseModel):
+ decision_id: UUID
+ source_skill: str | None = None
+ status: Literal["pending", "processing", "retrying", "blocked", "started", "cancelled"] = "pending"
+ attempt: int = 0
+ next_retry_at: datetime | None = None
+ worker_token: UUID | None = None
+ lease_until: datetime | None = None
+ reason: str = ""
+
+
class ImplementationHandover(BaseModel):
replacement_id: UUID
status: Literal["processing", "completed", "failed", "cancelled", "needs_attention"]
@@ -744,6 +757,7 @@ StatusArtefactContent = (
| SuggestedReviewers
| ChannelAssignment
| ImplementationDecision
+ | ImplementationDispatch
)
LogArtefactContent = (
CodeReference
@@ -788,6 +802,7 @@ ARTEFACT_CONTENT_SCHEMAS: Mapping[str, type[BaseModel]] = {
"pull_request": PullRequestLink,
"check_result": CheckResult,
"implementation_decision": ImplementationDecision,
+ "implementation_dispatch": ImplementationDispatch,
"implementation_replacement": ImplementationReplacement,
"implementation_handover": ImplementationHandover,
}
@@ -820,6 +835,7 @@ NON_WRITABLE_ARTEFACT_TYPES: frozenset[str] = frozenset(
"pull_request",
"check_result",
"implementation_decision",
+ "implementation_dispatch",
"implementation_replacement",
"implementation_handover",
}
diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.py
index 28be3c092765..d52a8235aae4 100644
--- a/products/signals/backend/auto_start.py
+++ b/products/signals/backend/auto_start.py
@@ -3,11 +3,12 @@ from __future__ import annotations
import json
import secrets
from datetime import datetime
-from typing import TypedDict, TypeVar
+from typing import Literal, TypedDict, TypeVar
from uuid import UUID
from django.conf import settings
from django.db import transaction
+from django.utils import timezone
from django.utils.text import slugify
import structlog
@@ -23,7 +24,7 @@ from posthog.temporal.oauth import McpScopePreset, grants_scratchpad_write
from products.signals.backend.agent_runtime import STEP_IMPLEMENTATION, resolve_agent_runtime
from products.signals.backend.artefact_attribution import ArtefactAttribution
-from products.signals.backend.artefact_schemas import ImplementationReplacement
+from products.signals.backend.artefact_schemas import ImplementationDispatch, ImplementationReplacement
from products.signals.backend.billing import (
BillingExemptionError,
mark_report_billing_exempt,
@@ -31,6 +32,7 @@ from products.signals.backend.billing import (
)
from products.signals.backend.free_trial import capture_signal_report_free_trial_paused, self_driving_free_trial_enabled
from products.signals.backend.models import (
+ MAX_SCOUT_CONTENT_REVISIONS,
SignalReport,
SignalReportArtefact,
SignalSourceConfig,
@@ -104,6 +106,35 @@ class SupersedeDecision:
NO_SUPERSEDE = SupersedeDecision(allowed=False)
+@frozen
+class AutostartOutcome:
+ status: Literal["started", "blocked", "cancelled", "queued"]
+ reason: str = ""
+
+
+@frozen
+class ImplementationReportContent:
+ title: str | None
+ summary: str | None
+ run_count: int
+ last_run_at: datetime | None
+ revision_count: int
+
+ @classmethod
+ def from_report(cls, report: SignalReport) -> ImplementationReportContent:
+ return cls(
+ title=report.title,
+ summary=report.summary,
+ run_count=report.run_count,
+ last_run_at=report.last_run_at,
+ revision_count=report.content_revision_count or 0,
+ )
+
+
+class ReportChangedDuringAutostart(RuntimeError):
+ pass
+
+
class ReviewerContent(TypedDict):
# Null for a reviewer with no linked GitHub account: they route the report like anyone else, but
# can never be the autostart runner, which mints its session under a GitHub identity.
@@ -430,7 +461,27 @@ def _capture_steering_attached(*, team: Team, report_id: str, task_id: str, stee
logger.exception("Failed to capture signals_autostart_steering_attached", report_id=report_id)
-def _resolve_supersede(report: SignalReport, decision: ImplementationDecision | None) -> SupersedeDecision:
+def _has_unimplemented_work(report: SignalReport) -> bool:
+ """Whether the report has moved past the version its current implementation PR was built from.
+
+ Two producers can move it, and either one is enough. The pipeline researches again, raising
+ `run_count`; a scout rewrites the report's title or summary, raising `content_revision_count`.
+ Each is compared against its own stamp, which is what bounds replacements to one per pass or
+ per rewrite and stops a single decision opening two pull requests.
+
+ Research is capped by its buckets, so the pipeline arm needs no separate cap. A scout has no
+ such ceiling, so the revision arm carries one: past `MAX_SCOUT_CONTENT_REVISIONS` the rewrite
+ still lands, it just stops buying a new pull request.
+ """
+ if report.run_count > (report.implemented_at_run_count or 0):
+ return True
+ revisions = report.content_revision_count or 0
+ return 0 < revisions <= MAX_SCOUT_CONTENT_REVISIONS and revisions > (report.implemented_at_revision_count or 0)
+
+
+def _resolve_supersede(
+ report: SignalReport, decision: ImplementationDecision | None, *, retry_verification: bool = False
+) -> SupersedeDecision:
if decision is None or not decision_is_current(report, decision) or not targets_still_eligible(report, decision):
return NO_SUPERSEDE
artefact = (
@@ -448,6 +499,8 @@ def _resolve_supersede(report: SignalReport, decision: ImplementationDecision |
# reach the settle-point activity and use its retries instead of reading as "not eligible".
raise
except Exception:
+ if retry_verification:
+ raise
logger.exception("signals_supersede_verification_failed", report_id=str(report.id))
return NO_SUPERSEDE
return SupersedeDecision(
@@ -465,6 +518,7 @@ def _create_implementation_task_if_absent(
report_id: str,
title: str,
description: str,
+ expected_content: ImplementationReportContent,
user_id: int,
repository: str,
base_branch: str | None,
@@ -472,6 +526,7 @@ def _create_implementation_task_if_absent(
steering: ReportSteering = NO_STEERING,
free_trial_enabled: bool | None = None,
supersede: SupersedeDecision = NO_SUPERSEDE,
+ dispatch: ImplementationDispatch | None = None,
) -> bool:
"""Create the implementation task and record it (gate row + work-log artefact), serialized per report.
@@ -506,13 +561,43 @@ def _create_implementation_task_if_absent(
report = SignalReport.objects.select_for_update().filter(id=report_id, team_id=team_id).first()
if report is None:
return False
+ if ImplementationReportContent.from_report(report) != expected_content:
+ raise ReportChangedDuringAutostart("Report changed before its implementation task could start")
+ if dispatch is not None:
+ latest = (
+ SignalReportArtefact.objects.filter(
+ team_id=team_id, report_id=report_id, type="implementation_dispatch"
+ )
+ .order_by("-created_at", "-id")
+ .first()
+ )
+ progress = ImplementationDispatch.model_validate_json(latest.content) if latest else None
+ if (
+ progress is None
+ or progress.decision_id != dispatch.decision_id
+ or progress.worker_token != dispatch.worker_token
+ or progress.status != "processing"
+ or progress.lease_until is None
+ or progress.lease_until <= timezone.now()
+ or supersede.decision_id != str(dispatch.decision_id)
+ ):
+ raise ReportChangedDuringAutostart("Replacement dispatch lease changed")
claim = get_active_claim(team_id=team_id, report_id=report_id)
if supersede.allowed:
+ current_decision_id = (
+ SignalReportArtefact.objects.filter(
+ team_id=team_id, report_id=report_id, type="implementation_decision"
+ )
+ .order_by("-created_at", "-id")
+ .values_list("id", flat=True)
+ .first()
+ )
if (
not supersede.decision
or not supersede.decision_id
or not decision_is_current(report, supersede.decision)
or not targets_still_eligible(report, supersede.decision)
+ or str(current_decision_id) != supersede.decision_id
):
return False
if any(
@@ -535,14 +620,17 @@ def _create_implementation_task_if_absent(
)
if already_implemented and not supersede.allowed:
return False
- if already_implemented and report.run_count <= (report.implemented_at_run_count or 0):
+ if already_implemented and not _has_unimplemented_work(report):
# Re-checked under the lock: the caller resolved the supersede decision outside it, so a
# racing evaluation that already stamped this pass must not open a second replacement.
return False
if supersede.allowed and claim is not None:
release_claim(claim, ArtefactAttribution.system(), takeover=True)
+ # Both stamps move together. The task about to start is built from the report as it stands
+ # now, so neither a research pass nor a rewrite already folded into it may buy another one.
report.implemented_at_run_count = report.run_count
- report.save(update_fields=["implemented_at_run_count"])
+ report.implemented_at_revision_count = report.content_revision_count or 0
+ report.save(update_fields=["implemented_at_run_count", "implemented_at_revision_count"])
exempt_reason = _stamp_billing_exemption(report, billing_exempt_reason)
team = Team.objects.select_related("organization").get(id=team_id)
created = tasks_facade.create_and_run_task(
@@ -614,7 +702,7 @@ def _create_implementation_task_if_absent(
def _live_skill_owner_identities(
- team: Team, report_id: str, reviewers_content: list[ReviewerContent]
+ team: Team, report_id: str, reviewers_content: list[ReviewerContent], source_skill: str | None = None
) -> ReviewerIdentitySet:
"""GitHub logins (lowercased) of the *current* owners of every scout that touched the report.
@@ -634,6 +722,8 @@ def _live_skill_owner_identities(
commits atomically with the pick it guards, and covers the entries that actually stand for
selection even when a tally write was lost."""
skill_names = set(resolve_touching_scout_skills(team.id, report_id))
+ if source_skill:
+ skill_names.add(source_skill)
skill_names |= {str(r["source_skill"]) for r in reviewers_content if r.get("source_skill")}
owner_uuids: set[str] = set()
for skill_name in skill_names:
@@ -827,7 +917,9 @@ async def maybe_autostart_implementation_task(
billing_exempt_reason: str | None = None,
repository_autostart_eligible: bool = True,
implementation_decision: ImplementationDecision | None = None,
-) -> None:
+ remaining_retries: int = 2,
+ dispatch: ImplementationDispatch | None = None,
+) -> AutostartOutcome:
"""Start an implementation Task for a SignalReport if autonomy + priority allow it.
``triggering_user_id`` is set when a *user edit* of the report's `suggested_reviewers` re-ran
@@ -880,11 +972,21 @@ async def maybe_autostart_implementation_task(
report = await SignalReport.objects.filter(id=report_id, team_id=team_id).afirst()
if report is None:
logger.info("self-driving auto-start skipped", report_id=report_id, team_id=team_id, reason="report gone")
- return
+ return AutostartOutcome(status="cancelled", reason="Report no longer exists")
+ expected_content = ImplementationReportContent.from_report(report)
+ if title != expected_content.title or summary != expected_content.summary:
+ if remaining_retries:
+ return await maybe_autostart_from_report_artefacts(
+ team_id=team_id, report_id=report_id, remaining_retries=remaining_retries - 1, dispatch=dispatch
+ )
+ raise ReportChangedDuringAutostart("Report kept changing during autostart")
supersede = await database_sync_to_async(_resolve_supersede, thread_sensitive=False)(
- report, implementation_decision
+ report, implementation_decision, retry_verification=dispatch is not None
)
+ if dispatch is not None and supersede.decision_id != str(dispatch.decision_id):
+ return AutostartOutcome(status="cancelled", reason="Replacement decision is no longer eligible")
+
skip_reason: str | None = None
if task_exists and not supersede.allowed:
skip_reason = "implementation task already exists"
@@ -896,7 +998,7 @@ async def maybe_autostart_implementation_task(
skip_reason = "no priority assessment"
if skip_reason is not None:
logger.info("self-driving auto-start skipped", report_id=report_id, team_id=team_id, reason=skip_reason)
- return
+ return AutostartOutcome(status="blocked", reason=skip_reason)
assert priority is not None # narrowed by the `priority is None` skip_reason guard above
@@ -911,7 +1013,7 @@ async def maybe_autostart_implementation_task(
team_id=team_id,
reason="autostart disabled for team",
)
- return
+ return AutostartOutcome(status="blocked", reason="Autostart is disabled")
team_default_priority = Priority(team_config.default_autostart_priority) if team_config else Priority.P4
# Quota gate: the implementation task is the step that leads to the billable PR, so a team
@@ -929,7 +1031,7 @@ async def maybe_autostart_implementation_task(
team_id=team_id,
reason="org over self-driving credits quota",
)
- return
+ return AutostartOutcome(status="blocked", reason="Self-driving quota is exhausted")
# A user-triggered auto-start runs as the triggering user; otherwise resolve a trusted
# (commit-authorship) reviewer. Either way the task's user is never an attacker-named colleague.
@@ -943,7 +1045,7 @@ async def maybe_autostart_implementation_task(
# `_live_skill_owner_identities`). Skipped when no reviewer is up for selection.
live_owner_identities = (
await database_sync_to_async(_live_skill_owner_identities, thread_sensitive=False)(
- team, report_id, reviewers_content
+ team, report_id, reviewers_content, dispatch.source_skill if dispatch else None
)
if reviewers_content
else ReviewerIdentitySet.empty()
@@ -967,7 +1069,7 @@ async def maybe_autostart_implementation_task(
team_id=team_id,
reason="no autostart runner: no reviewer met threshold, and no enabling member for a report at/above the team autostart priority",
)
- return
+ return AutostartOutcome(status="blocked", reason="No eligible autostart runner")
# Free trial gate: a trial org gets reports, not pull requests, so no implementation task on
# any path. The report stays ready and gets its PR after the trial, on the next re-evaluation
@@ -982,7 +1084,7 @@ async def maybe_autostart_implementation_task(
team_id=team_id,
reason="org on self-driving free trial",
)
- return
+ return AutostartOutcome(status="blocked", reason="Organization is on a free trial")
base_branch = team_config.base_branch_for(repository) if team_config else None
@@ -993,34 +1095,45 @@ async def maybe_autostart_implementation_task(
team_id, report_id, memory_writable=grants_scratchpad_write(IMPLEMENTATION_MCP_SCOPES)
)
- created = await database_sync_to_async(_create_implementation_task_if_absent, thread_sensitive=False)(
- team_id=team_id,
- report_id=report_id,
- title=title,
- description=_build_autostart_task_description(
- report_id=report_id,
+ try:
+ created = await database_sync_to_async(_create_implementation_task_if_absent, thread_sensitive=False)(
team_id=team_id,
- summary=summary,
+ report_id=report_id,
+ title=title,
+ expected_content=expected_content,
+ description=_build_autostart_task_description(
+ report_id=report_id,
+ team_id=team_id,
+ summary=summary,
+ repository=repository,
+ priority=priority,
+ source_references=source_references,
+ steering=steering,
+ supersede=supersede,
+ ),
+ user_id=task_user.id,
repository=repository,
- priority=priority,
- source_references=source_references,
+ base_branch=base_branch,
+ billing_exempt_reason=billing_exempt_reason,
steering=steering,
+ # The verdict resolved above, so the create-time gate re-reads no flag while it holds the
+ # report row lock.
+ free_trial_enabled=on_free_trial,
supersede=supersede,
- ),
- user_id=task_user.id,
- repository=repository,
- base_branch=base_branch,
- billing_exempt_reason=billing_exempt_reason,
- steering=steering,
- # The verdict resolved above, so the create-time gate re-reads no flag while it holds the
- # report row lock.
- free_trial_enabled=on_free_trial,
- supersede=supersede,
- )
+ dispatch=dispatch,
+ )
+ except ReportChangedDuringAutostart:
+ if remaining_retries:
+ return await maybe_autostart_from_report_artefacts(
+ team_id=team_id, report_id=report_id, remaining_retries=remaining_retries - 1, dispatch=dispatch
+ )
+ raise ReportChangedDuringAutostart("Report kept changing during autostart")
if not created:
# Another evaluation won the race and already created the implementation task.
logger.info("self-driving auto-start skipped", report_id=report_id, team_id=team_id, reason="lost create race")
- return
+ return AutostartOutcome(status="cancelled", reason="Another start or report change won the race")
+
+ return AutostartOutcome(status="started")
async def _latest_artefact_as(
@@ -1086,7 +1199,9 @@ async def _latest_reviewers_content(report_id: str) -> tuple[list[ReviewerConten
return reviewers, editor_user_id
-async def maybe_autostart_from_report_artefacts(*, team_id: int, report_id: str) -> None:
+async def maybe_autostart_from_report_artefacts(
+ *, team_id: int, report_id: str, remaining_retries: int = 2, dispatch: ImplementationDispatch | None = None
+) -> AutostartOutcome:
"""Re-evaluate auto-start from a report's *current* artefacts.
Called when reviewers change after the report was created (e.g. a human edits them via the
@@ -1098,6 +1213,14 @@ async def maybe_autostart_from_report_artefacts(*, team_id: int, report_id: str)
When the latest reviewers artefact was user-edited, the task runs as that editing user (not a
named colleague) — see `_latest_reviewers_content` and `triggering_user_id`.
"""
+ if dispatch is None:
+ from products.signals.backend.implementation_dispatch import (
+ ImplementationDispatcher, # noqa: PLC0415 - breaks the dispatcher/autostart cycle
+ )
+
+ if await database_sync_to_async(ImplementationDispatcher().trigger, thread_sensitive=False)(team_id, report_id):
+ return AutostartOutcome(status="queued")
+
report = (
await SignalReport.objects.filter(id=report_id, team_id=team_id)
.only("title", "summary", "last_run_at")
@@ -1110,7 +1233,7 @@ async def maybe_autostart_from_report_artefacts(*, team_id: int, report_id: str)
team_id=team_id,
reason="report missing or not yet summarized",
)
- return
+ return AutostartOutcome(status="cancelled", reason="Report is missing or has no summary")
actionability = await _latest_artefact_as(
report_id, SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT, ActionabilityAssessment
@@ -1122,7 +1245,7 @@ async def maybe_autostart_from_report_artefacts(*, team_id: int, report_id: str)
team_id=team_id,
reason="no actionability artefact",
)
- return
+ return AutostartOutcome(status="blocked", reason="No actionability assessment")
repo_selection = await _latest_artefact_as(
report_id, SignalReportArtefact.ArtefactType.REPO_SELECTION, RepoSelectionResult
)
@@ -1134,7 +1257,7 @@ async def maybe_autostart_from_report_artefacts(*, team_id: int, report_id: str)
team_id=team_id,
reason="no repository selected",
)
- return
+ return AutostartOutcome(status="blocked", reason="No repository selected")
priority = await _latest_artefact_as(
report_id, SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT, PriorityAssessment
)
@@ -1156,7 +1279,7 @@ async def maybe_autostart_from_report_artefacts(*, team_id: int, report_id: str)
# via `triggering_user_id` below.
reviewers_content, editor_user_id = await _latest_reviewers_content(report_id)
- await maybe_autostart_implementation_task(
+ return await maybe_autostart_implementation_task(
team_id=team_id,
report_id=report_id,
repository=repository,
@@ -1170,4 +1293,6 @@ async def maybe_autostart_from_report_artefacts(*, team_id: int, report_id: str)
triggering_user_id=editor_user_id,
repository_autostart_eligible=repo_selection.autostart_eligible,
implementation_decision=implementation_decision,
+ remaining_retries=remaining_retries,
+ dispatch=dispatch,
)
diff --git a/products/signals/backend/implementation_dispatch.py b/products/signals/backend/implementation_dispatch.py
new file mode 100644
index 000000000000..b630452f2a73
--- /dev/null
+++ b/products/signals/backend/implementation_dispatch.py
@@ -0,0 +1,226 @@
+from __future__ import annotations
+
+from datetime import timedelta
+from uuid import uuid4
+
+from django.db import transaction
+from django.db.models import OuterRef, Subquery
+from django.utils import timezone
+
+import structlog
+from asgiref.sync import async_to_sync
+from pydantic import ValidationError
+
+from products.signals.backend.artefact_attribution import ArtefactAttribution
+from products.signals.backend.artefact_schemas import (
+ ImplementationDecision,
+ ImplementationDispatch,
+ ImplementationReplacement,
+)
+from products.signals.backend.auto_start import AutostartOutcome, maybe_autostart_from_report_artefacts
+from products.signals.backend.models import SignalReport, SignalReportArtefact
+from products.signals.backend.supersession import decision_is_current
+
+logger = structlog.get_logger(__name__)
+DISPATCH_LEASE_SECONDS = 300
+DISPATCH_SWEEP_BATCH_SIZE = 500
+
+
+class ImplementationDispatcher:
+ def _latest(self, team_id: int, report_id: str, artefact_type: str) -> SignalReportArtefact | None:
+ return (
+ SignalReportArtefact.objects.filter(team_id=team_id, report_id=report_id, type=artefact_type)
+ .order_by("-created_at", "-id")
+ .first()
+ )
+
+ def _progress(self, decision: SignalReportArtefact) -> ImplementationDispatch | None:
+ row = self._latest(decision.team_id, str(decision.report_id), "implementation_dispatch")
+ if row is None:
+ return None
+ progress = ImplementationDispatch.model_validate_json(row.content)
+ return progress if progress.decision_id == decision.id else None
+
+ def _save(self, decision: SignalReportArtefact, progress: ImplementationDispatch) -> None:
+ SignalReportArtefact.append_status(
+ team_id=decision.team_id,
+ report_id=str(decision.report_id),
+ content=progress,
+ attribution=ArtefactAttribution.system(),
+ )
+
+ def _started(self, decision: SignalReportArtefact) -> bool:
+ replacement = self._latest(decision.team_id, str(decision.report_id), "implementation_replacement")
+ return bool(
+ replacement
+ and ImplementationReplacement.model_validate_json(replacement.content).decision_id == decision.id
+ )
+
+ def _current(self, decision: SignalReportArtefact, report: SignalReport) -> bool:
+ latest = self._latest(decision.team_id, str(report.id), "implementation_decision")
+ return bool(
+ latest
+ and latest.id == decision.id
+ and decision_is_current(report, ImplementationDecision.model_validate_json(decision.content))
+ )
+
+ def _enqueue(self, team_id: int, decision_id: str, countdown: int = 0) -> None:
+ from products.signals.backend.tasks import (
+ dispatch_implementation_replacement, # noqa: PLC0415 - breaks the task/service cycle
+ )
+
+ try:
+ dispatch_implementation_replacement.apply_async(args=[team_id, decision_id], countdown=countdown)
+ except Exception:
+ logger.exception("signals_implementation_dispatch_enqueue_failed", decision_id=decision_id)
+
+ def trigger(self, team_id: int, report_id: str) -> bool:
+ with transaction.atomic():
+ report = SignalReport.objects.select_for_update().filter(team_id=team_id, id=report_id).first()
+ if report is None:
+ return False
+ decision = self._latest(team_id, report_id, "implementation_decision")
+ progress = self._progress(decision) if decision else None
+ if decision is None or progress is None:
+ return False
+ if progress.status in {"started", "cancelled", "processing"}:
+ return True
+ if progress.status == "blocked":
+ progress.status = "pending"
+ progress.next_retry_at = None
+ progress.reason = ""
+ self._save(decision, progress)
+ transaction.on_commit(lambda: self._enqueue(team_id, str(decision.id)), robust=True)
+ return True
+
+ def _claim(self, decision: SignalReportArtefact) -> ImplementationDispatch | None:
+ with transaction.atomic():
+ report = (
+ SignalReport.objects.select_for_update().filter(team_id=decision.team_id, id=decision.report_id).first()
+ )
+ progress = self._progress(decision)
+ if report is None or progress is None or progress.status in {"started", "cancelled", "blocked"}:
+ return None
+ if self._started(decision):
+ progress.status = "started"
+ progress.lease_until = None
+ self._save(decision, progress)
+ return None
+ if not self._current(decision, report):
+ progress.status = "cancelled"
+ progress.reason = "The report or replacement decision changed."
+ progress.lease_until = None
+ self._save(decision, progress)
+ return None
+ now = timezone.now()
+ if (progress.lease_until and progress.lease_until > now) or (
+ progress.next_retry_at and progress.next_retry_at > now
+ ):
+ return None
+ progress.status = "processing"
+ progress.worker_token = uuid4()
+ progress.lease_until = now + timedelta(seconds=DISPATCH_LEASE_SECONDS)
+ progress.next_retry_at = None
+ progress.attempt += 1
+ self._save(decision, progress)
+ return progress
+
+ def _finish(
+ self, decision: SignalReportArtefact, reservation: ImplementationDispatch, outcome: AutostartOutcome | None
+ ) -> None:
+ with transaction.atomic():
+ report = (
+ SignalReport.objects.select_for_update().filter(team_id=decision.team_id, id=decision.report_id).first()
+ )
+ progress = self._progress(decision)
+ if report is None or progress is None or progress.worker_token != reservation.worker_token:
+ return
+ progress.lease_until = None
+ if self._started(decision):
+ progress.status = "started"
+ progress.reason = ""
+ elif not self._current(decision, report):
+ progress.status = "cancelled"
+ progress.reason = "The report or replacement decision changed."
+ elif outcome is not None and (outcome.status == "blocked" or outcome.status == "cancelled"):
+ progress.status = outcome.status
+ progress.reason = outcome.reason
+ else:
+ progress.status = "retrying"
+ progress.reason = "The replacement could not start. It will be retried automatically."
+ delay = min(60 * 2 ** min(progress.attempt - 1, 4), 900)
+ progress.next_retry_at = timezone.now() + timedelta(seconds=delay)
+ transaction.on_commit(lambda: self._enqueue(decision.team_id, str(decision.id), delay), robust=True)
+ self._save(decision, progress)
+ logger.info(
+ "signals_implementation_dispatch_finished",
+ decision_id=str(decision.id),
+ status=progress.status,
+ attempt=progress.attempt,
+ )
+
+ def dispatch(self, team_id: int, decision_id: str) -> None:
+ from products.signals.backend.scout_harness.tools.report import (
+ _refresh_inferred_repository, # noqa: PLC0415 - breaks the report/autostart cycle
+ )
+
+ decision = SignalReportArtefact.objects.filter(
+ team_id=team_id, id=decision_id, type="implementation_decision"
+ ).first()
+ if decision is None:
+ return
+ reservation = self._claim(decision)
+ if reservation is None:
+ return
+ outcome = None
+ try:
+ _refresh_inferred_repository(
+ team_id=team_id, report_id=str(decision.report_id), attribution=ArtefactAttribution.system()
+ )
+ outcome = async_to_sync(maybe_autostart_from_report_artefacts)(
+ team_id=team_id, report_id=str(decision.report_id), dispatch=reservation
+ )
+ except Exception:
+ logger.exception("signals_implementation_dispatch_failed", decision_id=decision_id)
+ self._finish(decision, reservation, outcome)
+
+ def enqueue_page(self, after_id: str | None = None, through_id: str | None = None) -> None:
+ from products.signals.backend.tasks import (
+ sweep_implementation_dispatches, # noqa: PLC0415 - breaks the task/service cycle
+ )
+
+ decisions = SignalReportArtefact.objects.filter(type="implementation_decision")
+ if through_id is None:
+ last_id = decisions.order_by("-id").values_list("id", flat=True).first()
+ if last_id is None:
+ return
+ through_id = str(last_id)
+ decisions = decisions.filter(id__lte=through_id)
+ if after_id is not None:
+ decisions = decisions.filter(id__gt=after_id)
+ progress = SignalReportArtefact.objects.filter(
+ team_id=OuterRef("team_id"), report_id=OuterRef("report_id"), type="implementation_dispatch"
+ ).order_by("-created_at", "-id")
+ page = list(
+ decisions.annotate(dispatch_content=Subquery(progress.values("content")[:1]))
+ .order_by("id")
+ .values_list("id", "team_id", "dispatch_content")[:DISPATCH_SWEEP_BATCH_SIZE]
+ )
+ now = timezone.now()
+ for decision_id, team_id, content in page:
+ if content is None:
+ continue
+ try:
+ state = ImplementationDispatch.model_validate_json(content)
+ except ValidationError:
+ logger.exception("signals_implementation_dispatch_invalid", decision_id=str(decision_id))
+ continue
+ if (
+ state.decision_id == decision_id
+ and state.status in {"pending", "processing", "retrying"}
+ and (state.lease_until is None or state.lease_until <= now)
+ and (state.next_retry_at is None or state.next_retry_at <= now)
+ ):
+ self._enqueue(team_id, str(decision_id))
+ if len(page) == DISPATCH_SWEEP_BATCH_SIZE and str(page[-1][0]) != through_id:
+ sweep_implementation_dispatches.delay(str(page[-1][0]), through_id)
diff --git a/products/signals/backend/implementation_dispatch_tasks.py b/products/signals/backend/implementation_dispatch_tasks.py
new file mode 100644
index 000000000000..9c714348727b
--- /dev/null
+++ b/products/signals/backend/implementation_dispatch_tasks.py
@@ -0,0 +1,31 @@
+from celery import shared_task
+
+from posthog.models.scoping import with_team_scope
+from posthog.scoping_audit import skip_team_scope_audit
+
+
+@shared_task(ignore_result=True, soft_time_limit=210, time_limit=240, acks_late=True, reject_on_worker_lost=True)
+@with_team_scope()
+def dispatch_implementation_replacement(team_id: int, decision_id: str) -> None:
+ from products.signals.backend.implementation_dispatch import (
+ ImplementationDispatcher, # noqa: PLC0415 - keeps the task/autostart cycle lazy
+ )
+
+ ImplementationDispatcher().dispatch(team_id, decision_id)
+
+
+@shared_task(
+ ignore_result=True,
+ autoretry_for=(Exception,),
+ retry_backoff=True,
+ max_retries=3,
+ soft_time_limit=210,
+ time_limit=240,
+)
+@skip_team_scope_audit
+def sweep_implementation_dispatches(after_id: str | None = None, through_id: str | None = None) -> None:
+ from products.signals.backend.implementation_dispatch import (
+ ImplementationDispatcher, # noqa: PLC0415 - keeps the task/autostart cycle lazy
+ )
+
+ ImplementationDispatcher().enqueue_page(after_id, through_id)
diff --git a/products/signals/backend/migrations/0138_signalreport_content_revision_count_and_more.py b/products/signals/backend/migrations/0138_signalreport_content_revision_count_and_more.py
new file mode 100644
index 000000000000..fd51f53fb34e
--- /dev/null
+++ b/products/signals/backend/migrations/0138_signalreport_content_revision_count_and_more.py
@@ -0,0 +1,27 @@
+# Generated by Django 5.2.17 on 2026-08-20 15:11
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0137_signalreport_implemented_at_run_count"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalreport",
+ name="content_revision_count",
+ field=models.IntegerField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="signalreport",
+ name="corroboration_count",
+ field=models.IntegerField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="signalreport",
+ name="implemented_at_revision_count",
+ field=models.IntegerField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/0139_implementation_dispatch.py b/products/signals/backend/migrations/0139_implementation_dispatch.py
new file mode 100644
index 000000000000..5afffe2bba98
--- /dev/null
+++ b/products/signals/backend/migrations/0139_implementation_dispatch.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.17 on 2026-09-16 15:17
+
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("signals", "0138_signalreport_content_revision_count_and_more"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="signalreportartefact",
+ index=models.Index(
+ condition=models.Q(("type", "implementation_decision")),
+ fields=["id"],
+ name="signals_dispatch_sweep_idx",
+ ),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index e39749115d11..a3a0c6050106 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0137_signalreport_implemented_at_run_count
+0139_implementation_dispatch
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index e12f59b4f77d..37ef01187d9d 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -250,6 +250,13 @@ class SignalUserAutonomyConfig(UUIDModel):
# run. `SignalReport.researched_signal_count` subtracts it to recover the count a run started on.
SIGNALS_AT_RUN_INCREMENT = 3
+# How many times a scout may rewrite one report's title or summary and still earn a replacement
+# pull request, and how many revalidation notes a report keeps as separate entries before they
+# collapse into a count. Both bound the same thing: a scout runs on its own schedule, so nothing
+# about a report going quiet stops it writing to that report.
+MAX_SCOUT_CONTENT_REVISIONS = 4
+MAX_SCOUT_REPORT_NOTES = 4
+
class InvalidStatusTransition(Exception):
def __init__(self, from_status: str, to_status: str):
@@ -308,6 +315,18 @@ class SignalReport(UUIDModel):
# Null for reports implemented before superseding existed — safe, because those reports also have
# no `implementation_decision` artefact and the supersede path requires one.
implemented_at_run_count = models.IntegerField(null=True, blank=True)
+ # How many times a scout has rewritten this report's title or summary. Its own counter rather
+ # than `run_count`, which feeds Temporal workflow IDs and must never gain a second producer.
+ # Only a real diff counts, so a scout restating what the report already says does not tick it.
+ content_revision_count = models.IntegerField(null=True, blank=True)
+ # The revision the report's current implementation PR was built from, the scout-side twin of
+ # `implemented_at_run_count`. Null for reports implemented before scout superseding existed.
+ implemented_at_revision_count = models.IntegerField(null=True, blank=True)
+ # How many explicit corroborations a scout has appended. The first `MAX_SCOUT_REPORT_NOTES`
+ # land as entries in the work log and the rest live
+ # only as this count, which the inbox renders as one line instead of a wall of near-identical
+ # entries.
+ corroboration_count = models.IntegerField(null=True, blank=True)
# LLM-generated during signal matching
title = models.TextField(null=True, blank=True)
@@ -1089,6 +1108,7 @@ class SignalReportArtefact(UUIDModel):
PULL_REQUEST = "pull_request"
CHECK_RESULT = "check_result"
IMPLEMENTATION_DECISION = "implementation_decision"
+ IMPLEMENTATION_DISPATCH = "implementation_dispatch"
IMPLEMENTATION_REPLACEMENT = "implementation_replacement"
IMPLEMENTATION_HANDOVER = "implementation_handover"
@@ -1112,6 +1132,7 @@ class SignalReportArtefact(UUIDModel):
ArtefactType.SUGGESTED_REVIEWERS,
ArtefactType.CHANNEL_ASSIGNMENT,
ArtefactType.IMPLEMENTATION_DECISION,
+ ArtefactType.IMPLEMENTATION_DISPATCH,
}
)
LOG_ARTEFACT_TYPES: frozenset[str] = frozenset(
@@ -1192,6 +1213,11 @@ class SignalReportArtefact(UUIDModel):
models.Index(fields=["channel"], name="signals_sig_channel_idx"),
models.Index(fields=["pull_request", "report"], name="signals_artefact_pr_report_idx"),
models.Index(fields=["claim"], name="signals_artefact_claim_idx"),
+ models.Index(
+ fields=["id"],
+ condition=models.Q(type="implementation_decision"),
+ name="signals_dispatch_sweep_idx",
+ ),
]
@classmethod
diff --git a/products/signals/backend/report_generation/research.py b/products/signals/backend/report_generation/research.py
index d6d2caf2e7d9..5bf7265b5e65 100644
--- a/products/signals/backend/report_generation/research.py
+++ b/products/signals/backend/report_generation/research.py
@@ -1211,6 +1211,7 @@ async def run_multi_turn_research(
targets=[candidates[url] for url in selected],
research_run_count=implementation_context.run_count,
research_started_at=implementation_context.started_at,
+ content_revision_count=implementation_context.content_revision_count,
)
except Exception:
logger.exception("multi_turn_research: supersede turn failed, keeping the report's open PR")
diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.py
index ee28fb32f8ba..260fd3e17f0e 100644
--- a/products/signals/backend/scout_harness/prompt.py
+++ b/products/signals/backend/scout_harness/prompt.py
@@ -461,6 +461,22 @@ This run updates reports that already exist; it can't author new ones. Find the
{_EDIT_REPOSITORY_BULLET}
- **Don't retry blindly.** `edit_report` is NOT idempotent. A retried `append_note` adds a second note. A retried `append_evidence` adds duplicate signals and increases the report counters again. If unsure whether an edit landed, re-read the report rather than re-sending."""
+# Rendered for every persona that holds `edit_report`, since both of its rules live on that call.
+# The counters it names are enforced server-side (`scout_report/persistence.py`), so a scout that
+# ignores this section can't overrun them; the section is here so it knows what its call did.
+_REVISING_A_REPORT = """# Revising a report that already has a pull request
+
+A report that autostarted has an open draft pull request built from the summary as it read at the time. When your rewrite changes **what the fix should be** (a different root cause, a different file or layer, a materially wider or narrower scope), pass `supersedes_implementation: true` on the same `scout-edit-report` call. This records a replacement decision for a ready report. Autostart checks the current policy and eligibility before starting a replacement from your new summary. Technical failures retry automatically; a policy block waits for a new edit or research trigger. The existing pull request stays open until the replacement succeeds with a verified open pull request.
+
+- **More evidence for the same fix is not a reason to set it.** The open pull request already implements that fix, and replacing it throws away review someone may already have done. Use `append_note` there instead.
+- **It rides on a real rewrite.** It is ignored unless the same call actually changed the `title` or `summary`. Restating text the report already holds, appending a note, and setting reviewers all count for nothing; the response's `is_content_revision` tells you whether yours counted.
+- **Only the first four content revisions can request replacements.** Every title or summary rewrite counts, including one that did not request a replacement. Past that your rewrite still lands, but it cannot request a replacement. The response's `supersedes_implementation` is true only when the decision was recorded.
+
+# Re-confirming a report still holds
+
+Use `append_note` for new information, recovery details, or observations that exceed the evidence cap. These notes always remain in the work log. For a confirmation with nothing new to add, also set `corroboration_only: true`. Only these confirmations count towards the four-entry cap; later confirmations increase the corroboration count and set `corroboration_collapsed` in the response. Notes never spend a content revision."""
+
+
# Heading matches the cross-reference in the authoring sections exactly; "not a copy" lives in the
# body, which is where the rule it names is actually stated.
_REPORT_SCRATCHPAD_POINTER = """# The `report:` scratchpad entry is a pointer
@@ -972,6 +988,7 @@ def _report_tail_sections(
how_a_run_works = f"{_HOW_A_RUN_WORKS}\n{_REPORT_STEPS_BOTH}\n{_REPORT_CLOSE_OUT_STEP}"
channel_sections = [
_AUTHORING_VS_EDITING_REPORT_BOTH,
+ _REVISING_A_REPORT,
_REPORT_SCRATCHPAD_POINTER,
_SUGGESTED_REVIEWERS_REPORT,
*([_github_evidence_section(can_emit=can_emit)] if github_read_access else []),
@@ -996,6 +1013,7 @@ def _report_tail_sections(
how_a_run_works = f"{_HOW_A_RUN_WORKS}\n{_REPORT_STEPS_EDIT_ONLY}\n{_REPORT_CLOSE_OUT_STEP}"
channel_sections = [
_EDITING_REPORT_EDIT_ONLY,
+ _REVISING_A_REPORT,
_REPORT_SCRATCHPAD_POINTER,
*([_github_evidence_section(can_emit=can_emit)] if github_read_access else []),
_REPORT_METRICS,
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index 05c07ae93c4f..71c0d326df16 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -1601,6 +1601,10 @@ class EditReportRequestSerializer(serializers.Serializer):
max_length=MAX_NOTE_CONTENT_LENGTH,
help_text="Optional free-form note to append to the report's work log (attributed to this scout).",
)
+ corroboration_only = serializers.BooleanField(
+ required=False,
+ help_text="Set only when append_note confirms the finding with no new information. After four confirmations, store only the count. Other notes remain in the work log.",
+ )
append_evidence = serializers.ListField(
required=False,
allow_null=True,
@@ -1676,6 +1680,19 @@ class EditReportRequestSerializer(serializers.Serializer):
"left them pointing at the old report."
),
)
+ supersedes_implementation = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "Set this only when your rewrite changes what the fix should be: a different root cause, "
+ "a different file or layer, a materially wider or narrower scope. More evidence for the "
+ "same fix is not a reason, because the report's open pull request already implements it. "
+ "Setting it true records a replacement decision for a ready report. Policy and eligibility "
+ "checks gate the replacement. The existing pull request closes only after a successful, "
+ "verified replacement. Technical failures retry automatically; policy blocks wait for a new "
+ "edit or research trigger. Only honored alongside a `title` or `summary` that actually changes, "
+ "and only within the first four content revisions, including revisions that did not request replacement."
+ ),
+ )
def validate(self, attrs: dict) -> dict:
"""Reject a body field this serializer does not declare.
@@ -1697,7 +1714,13 @@ class EditReportResponseSerializer(serializers.Serializer):
child=serializers.CharField(),
help_text="Which presentation fields changed (e.g. `title`, `summary`); empty if only a note was appended.",
)
- note_appended = serializers.BooleanField(help_text="Whether a note artefact was appended.")
+ note_appended = serializers.BooleanField(
+ help_text=(
+ "Whether the edit included a note. True for a collapsed corroboration too, where the "
+ "report's count moves and no work-log entry is written. Read `corroboration_collapsed` "
+ "to tell the two apart."
+ ),
+ )
evidence_appended = serializers.IntegerField(
help_text="How many observations this edit added to the report's evidence rail; 0 if none."
)
@@ -1736,6 +1759,28 @@ class EditReportResponseSerializer(serializers.Serializer):
"report's suggested prompts down."
),
)
+ is_content_revision = serializers.BooleanField(
+ help_text=(
+ "Whether this edit actually rewrote the report's title or summary. False for a note, a "
+ "reviewer change, or a re-send of the text the report already had."
+ ),
+ )
+ content_revision_count = serializers.IntegerField(
+ help_text="How many times a scout has rewritten this report's title or summary, counting this edit.",
+ )
+ supersedes_implementation = serializers.BooleanField(
+ help_text=(
+ "Whether the edit recorded that the report's pull request should be replaced. False when "
+ "you did not ask for it, when the edit changed no content, or when the report has already "
+ "been rewritten too many times."
+ ),
+ )
+ corroboration_collapsed = serializers.BooleanField(
+ help_text=(
+ "Whether your note raised the report's corroboration count instead of landing as its own "
+ "entry. Only notes marked corroboration_only can collapse; free-form notes remain in the work log."
+ ),
+ )
# --- Project profile ------------------------------------------------------
diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.py
index 0d388ddaab4d..e4f94d6632b9 100644
--- a/products/signals/backend/scout_harness/tools/report.py
+++ b/products/signals/backend/scout_harness/tools/report.py
@@ -54,7 +54,12 @@ from products.signals.backend.artefact_schemas import (
SuggestedReviewerEntry,
SuggestedReviewers,
)
-from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalScoutRun
+from products.signals.backend.models import (
+ MAX_SCOUT_CONTENT_REVISIONS,
+ ArtefactAttribution,
+ SignalReport,
+ SignalScoutRun,
+)
from products.signals.backend.repo_corrections import sanitized_repository
from products.signals.backend.report_charts import ChartSize, ReportChart, chart_batch_error
from products.signals.backend.report_content_gates import organization_report_metrics_enabled
@@ -97,9 +102,13 @@ from products.signals.backend.scout_report import (
create_scout_report,
emit_appended_report_evidence,
find_scout_report_by_idempotency_key,
+ get_content_revision_count,
get_scout_report_signal_count,
get_scout_report_status,
get_scout_report_title,
+ prepare_scout_supersession,
+ record_content_revision,
+ record_implementation_decision,
record_report_edit,
record_scout_run_task_artefact,
scout_report_exists,
@@ -117,6 +126,7 @@ from products.signals.backend.scout_report.judge import (
judge_scout_report,
)
from products.signals.backend.slack_formatting import strip_chart_references
+from products.signals.backend.supersession import NO_IMPLEMENTATION_CONTEXT
from products.tasks.backend.facade import api as tasks_facade
logger = logging.getLogger(__name__)
@@ -257,6 +267,18 @@ class EditReportResult:
# note/reviewer-only edit) — telemetry-only, so the edited lifecycle event can classify the report
# (`_report_classification_props`) even when the edit didn't touch the title.
report_title: str | None = None
+ # Whether this edit actually rewrote the report's title or summary, and the report's running
+ # total of such rewrites. A note append, a reviewer change, and a restatement of the current text
+ # all leave both untouched — only a real diff to the report's content counts.
+ is_content_revision: bool = False
+ content_revision_count: int = 0
+ # Whether the edit recorded a decision to replace the report's implementation PR. False when the
+ # caller didn't ask, when the edit wasn't a content revision, or when the report is past
+ # `MAX_SCOUT_CONTENT_REVISIONS`.
+ supersedes_implementation: bool = False
+ # True when the appended note only raised the report's corroboration count instead of landing as
+ # its own entry (see `append_report_note`).
+ corroboration_collapsed: bool = False
@property
def changed(self) -> bool:
@@ -1264,6 +1286,13 @@ def _capture_report_edited(
"charts_set": result.charts_set,
"metrics_set": result.metrics_set,
"suggested_prompts_set": result.suggested_prompts_set,
+ # The iteration counter and its two outcomes. `is_content_revision` is the predicate the cap
+ # counts, so the share of edits that are re-confirmation rather than rewrite is readable
+ # straight off this event.
+ "is_content_revision": result.is_content_revision,
+ "content_revision_count": result.content_revision_count,
+ "supersedes_implementation": result.supersedes_implementation,
+ "corroboration_collapsed": result.corroboration_collapsed,
"title": _clip(title, MAX_REPORT_TITLE_LENGTH),
"summary": _forwarded_summary(summary),
"note": _clip(note, _MAX_TELEMETRY_TEXT_LEN),
@@ -1669,6 +1698,8 @@ def _do_edit_report(
charts: list[ReportChart] | None,
metrics: list[ReportMetric] | None,
suggested_prompts: list[str] | None,
+ supersedes_implementation: bool = False,
+ corroboration_only: bool = False,
) -> EditReportResult:
"""Fully-sync edit core (no LLM step). The async/sync entrypoints both funnel here — directly in
the sync path, via `database_sync_to_async` in the async path. The autostart re-eval bridges an
@@ -1683,6 +1714,8 @@ def _do_edit_report(
reviewers untouched; a supplied set replaces them verbatim (nothing injected), with owner
provenance stamped so a picked owner can't become the autostart identity."""
_assert_edit_gates(team, run, report_id)
+ if corroboration_only and not append_note:
+ raise InvalidScoutReportError("corroboration_only requires append_note")
attribution = _attribution_for(_resolve_task_id(run))
updated_fields: list[str] = []
@@ -1692,6 +1725,14 @@ def _do_edit_report(
charts_changed = False
metrics_changed = False
prompts_changed = False
+ content_revision_count = 0
+ corroboration_collapsed = False
+ supersede_recorded = False
+ implementation_context = (
+ prepare_scout_supersession(team_id=team.id, report_id=report_id, title=title, summary=summary)
+ if supersedes_implementation
+ else NO_IMPLEMENTATION_CONTEXT
+ )
# One edit is one transaction, so a rejection part-way through takes the whole edit with it
# instead of leaving the report half-changed. The side effects below (autostart, telemetry,
# delivery) stay outside, and the `on_commit` hooks these writes register fire on this commit.
@@ -1721,6 +1762,22 @@ def _do_edit_report(
attribution=attribution,
reviewed=title is not None and summary is not None,
)
+ if updated_fields:
+ content_revision_count = record_content_revision(team_id=team.id, report_id=report_id)
+ # A supersede claim rides on the rewrite, never on its own. Appending a note or
+ # re-routing a report says nothing about whether the fix changed, and restating the
+ # text the report already carries says nothing at all.
+ supersede_recorded = supersedes_implementation and content_revision_count <= MAX_SCOUT_CONTENT_REVISIONS
+ record_implementation_decision(
+ team_id=team.id,
+ report_id=report_id,
+ supersede=supersede_recorded,
+ supersede_requested=supersedes_implementation,
+ updated_fields=updated_fields,
+ attribution=attribution,
+ author=run.skill_name,
+ implementation_context=implementation_context,
+ )
# Re-stamp owner provenance from the live owner set at the write: the safety-judge call sits
# between resolution and this transaction, autostart trusts the stored stamp, and an owner
# added during that wait must not remain an identity candidate.
@@ -1752,10 +1809,16 @@ def _do_edit_report(
author=run.skill_name,
)
if append_note is not None:
- append_report_note(
- team_id=team.id, report_id=report_id, note=append_note, attribution=attribution, author=run.skill_name
+ appended = append_report_note(
+ team_id=team.id,
+ report_id=report_id,
+ note=append_note,
+ attribution=attribution,
+ author=run.skill_name,
+ corroboration_only=corroboration_only,
)
note_appended = True
+ corroboration_collapsed = appended.collapsed
# Additive, unlike the charts and prompts below: appended observations join the report's
# existing evidence rail rather than replacing it, which is why the field is named for it.
if append_evidence:
@@ -1795,6 +1858,19 @@ def _do_edit_report(
attribution=attribution,
author=run.skill_name,
)
+ # `content_revision_count` is the report's running total, the number the scout reasons about
+ # the cap with. A revision above already set it to the report's new total; every other edit
+ # shape — a note, a reviewer change, cleared charts, or a restatement that diffed to nothing —
+ # leaves that total untouched, so read it back rather than echoing the 0 initializer as if the
+ # report had never been revised.
+ #
+ # Inside the transaction, unlike the read-backs below, because those degrade to a best-effort
+ # answer and this one cannot: reporting the report as never revised is the wrong answer this
+ # read exists to prevent. So a failure here has to take the edit with it. `edit_report` is not
+ # retry-safe, and an edit that committed and then reported failure is retried into a second
+ # note, a second corroboration count, or a second set of evidence rows.
+ if not updated_fields:
+ content_revision_count = get_content_revision_count(team_id=team.id, report_id=report_id)
charts_set = len(charts) if charts is not None and charts_changed else None
metrics_set = len(metrics) if metrics is not None and metrics_changed else None
prompts_set = len(suggested_prompts) if suggested_prompts is not None and prompts_changed else None
@@ -1927,11 +2003,12 @@ def _do_edit_report(
# Also link the run itself on the report's work log (deduped), so the editing scout's
# transcript is reachable from the report — not just the run-side `edited_report_ids` tally.
record_scout_run_task_artefact(team_id=team.id, report_id=report_id, run=run, task_id=attribution.task_id)
- # Re-run autostart only when the routing changed: it's idempotent (a report with an
- # implementation task already started no-ops), but a report that was missing a qualifying
- # reviewer, or that had no repository to open a PR against, can now open a draft PR. Fired
- # outside any txn since it spawns a Task — mirrors emit's post-commit hand-off.
- if reviewers_set or repository_set:
+ # Keyed on whether *this* edit rewrote the content, unlike the running total the transaction
+ # above resolved.
+ is_content_revision = bool(updated_fields)
+ # Routing changes and a new replacement decision each need an autostart evaluation.
+ # Run it after the commit because it spawns a task.
+ if reviewers_set or repository_set or supersede_recorded:
async_to_sync(_maybe_autostart_report)(team_id=team.id, report_id=report_id)
logger.info(
"signals_scout.edit_report: edited",
@@ -1946,6 +2023,9 @@ def _do_edit_report(
"charts_set": charts_set,
"metrics_set": metrics_set,
"suggested_prompts_set": prompts_set,
+ "content_revision_count": content_revision_count,
+ "supersedes_implementation": supersede_recorded,
+ "corroboration_collapsed": corroboration_collapsed,
},
)
# Resolve the report's effective title for the edited event's classification — the rewritten title
@@ -1974,6 +2054,10 @@ def _do_edit_report(
suggested_prompts_set=prompts_set,
repository=settled_repository,
report_title=report_title,
+ is_content_revision=is_content_revision,
+ content_revision_count=content_revision_count,
+ supersedes_implementation=supersede_recorded,
+ corroboration_collapsed=corroboration_collapsed,
)
return result
@@ -2087,6 +2171,8 @@ async def edit_report(
charts: list[ReportChartInput] | None = None,
metrics: list[ReportMetricInput] | None = None,
suggested_prompts: list[str] | None = None,
+ supersedes_implementation: bool = False,
+ corroboration_only: bool = False,
) -> EditReportResult:
"""Edit an existing inbox report: rewrite title/summary, append a note or fresh evidence, set
suggested reviewers, and/or repoint it at another repository (both re-run autostart, so a report
@@ -2152,6 +2238,8 @@ async def edit_report(
charts=built_charts,
metrics=built_metrics,
suggested_prompts=built_prompts,
+ supersedes_implementation=supersedes_implementation,
+ corroboration_only=corroboration_only,
)
forward = await database_sync_to_async(_capture_report_edited, thread_sensitive=False)(
team=team,
@@ -2186,6 +2274,8 @@ def edit_report_sync(
charts: list[ReportChartInput] | None = None,
metrics: list[ReportMetricInput] | None = None,
suggested_prompts: list[str] | None = None,
+ supersedes_implementation: bool = False,
+ corroboration_only: bool = False,
) -> EditReportResult:
"""Sync entry used by the DRF view path. Same behavior as `edit_report`, on the calling thread."""
_validate_edit_inputs(
@@ -2239,6 +2329,8 @@ def edit_report_sync(
charts=built_charts,
metrics=built_metrics,
suggested_prompts=built_prompts,
+ supersedes_implementation=supersedes_implementation,
+ corroboration_only=corroboration_only,
)
forward = _capture_report_edited(
team=team,
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 771866ca51f3..71288a968332 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -1238,7 +1238,9 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"report that was missing a qualifying reviewer or a repository can open a draft PR. The response "
"carries the repository the report holds after the edit, and the call fails when a repository it "
"named did not land. "
- "Title/summary edits are best-effort: the pipeline may later re-research them."
+ "Title/summary edits are best-effort: the pipeline may later re-research them. "
+ "Set `supersedes_implementation` alongside a rewrite when the fix changed. Verified automated "
+ "predecessor PRs close only after the replacement completes with verified open PRs."
),
operation_id="signals_scout_edit_report",
)
@@ -1267,6 +1269,8 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
charts=_to_report_charts(data.get("charts")),
metrics=_to_report_metrics(data.get("metrics")),
suggested_prompts=data.get("suggested_prompts"),
+ supersedes_implementation=bool(data.get("supersedes_implementation")),
+ corroboration_only=bool(data.get("corroboration_only")),
)
except InvalidScoutReportError as exc:
raise exceptions.ValidationError({"detail": str(exc)})
@@ -1283,6 +1287,10 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"charts_set": result.charts_set,
"metrics_set": result.metrics_set,
"suggested_prompts_set": result.suggested_prompts_set,
+ "is_content_revision": result.is_content_revision,
+ "content_revision_count": result.content_revision_count,
+ "supersedes_implementation": result.supersedes_implementation,
+ "corroboration_collapsed": result.corroboration_collapsed,
}
).data,
status=status.HTTP_200_OK,
diff --git a/products/signals/backend/scout_report/__init__.py b/products/signals/backend/scout_report/__init__.py
index 4b0402e9dcc1..6e51b7db586b 100644
--- a/products/signals/backend/scout_report/__init__.py
+++ b/products/signals/backend/scout_report/__init__.py
@@ -12,6 +12,7 @@ from products.signals.backend.report_prompts import MAX_SUGGESTED_PROMPTS
from products.signals.backend.scout_report.persistence import (
INFERRED_REPOSITORY_REASON,
MAX_REPORT_SIGNALS,
+ AppendedNote,
ExistingScoutReport,
InvalidScoutReportError,
PersistedScoutReport,
@@ -22,9 +23,13 @@ from products.signals.backend.scout_report.persistence import (
create_scout_report,
emit_appended_report_evidence,
find_scout_report_by_idempotency_key,
+ get_content_revision_count,
get_scout_report_signal_count,
get_scout_report_status,
get_scout_report_title,
+ prepare_scout_supersession,
+ record_content_revision,
+ record_implementation_decision,
record_report_edit,
record_scout_run_task_artefact,
scout_report_exists,
@@ -45,6 +50,7 @@ __all__ = [
"MAX_REPORT_SIGNALS",
"MAX_SUGGESTED_PROMPTS",
"ExistingScoutReport",
+ "AppendedNote",
"InvalidScoutReportError",
"PersistedScoutReport",
"ScoutReportAlreadyEmittedError",
@@ -55,8 +61,12 @@ __all__ = [
"emit_appended_report_evidence",
"find_scout_report_by_idempotency_key",
"get_scout_report_signal_count",
+ "get_content_revision_count",
"get_scout_report_status",
"get_scout_report_title",
+ "prepare_scout_supersession",
+ "record_content_revision",
+ "record_implementation_decision",
"record_report_edit",
"record_scout_run_task_artefact",
"scout_report_exists",
diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.py
index d3bd3c5e6db0..541deb18ed89 100644
--- a/products/signals/backend/scout_report/persistence.py
+++ b/products/signals/backend/scout_report/persistence.py
@@ -30,6 +30,7 @@ from collections.abc import Sequence
from dataclasses import dataclass, field
from datetime import datetime
from functools import partial
+from typing import TYPE_CHECKING, Literal
from django.db import IntegrityError, transaction
from django.db.models import F
@@ -40,11 +41,14 @@ from pydantic import ValidationError
from posthog.schema import EmbeddingModelName
from posthog.api.embedding_worker import emit_embedding_request
+from posthog.dataclasses import frozen
from products.signals.backend.artefact_schemas import (
SIGNALS_PRODUCT,
TASK_RUN_TYPE_SCOUT,
ActionabilityAssessment,
+ ImplementationDecision,
+ ImplementationDispatch,
NoteArtefact,
PriorityAssessment,
SafetyJudgment,
@@ -54,7 +58,14 @@ from products.signals.backend.artefact_schemas import (
TaskRunArtefact,
TitleChange,
)
-from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact, SignalScoutRun
+from products.signals.backend.models import (
+ MAX_SCOUT_CONTENT_REVISIONS,
+ MAX_SCOUT_REPORT_NOTES,
+ ArtefactAttribution,
+ SignalReport,
+ SignalReportArtefact,
+ SignalScoutRun,
+)
from products.signals.backend.repo_corrections import SCOUT_REPOSITORY_REASON
from products.signals.backend.report_charts import ReportChart, chart_batch_error
from products.signals.backend.report_generation.resolve_reviewers import ReviewerPayloadIndex
@@ -63,6 +74,10 @@ from products.signals.backend.report_generation.select_repo import RepoSelection
from products.signals.backend.report_metrics import ReportMetric, metric_batch_error
from products.signals.backend.report_prompts import normalize_suggested_prompts, suggested_prompts_batch_error
from products.signals.backend.scout_harness.tools.emit import SCOUT_SIGNAL_WEIGHT, SOURCE_PRODUCT, SOURCE_TYPE
+from products.signals.backend.supersession import NO_IMPLEMENTATION_CONTEXT, research_implementation_context
+
+if TYPE_CHECKING:
+ from products.signals.backend.supersession import ImplementationResearchContext
logger = logging.getLogger(__name__)
@@ -391,6 +406,35 @@ def get_scout_report_status(*, team_id: int, report_id: str) -> SignalReport.Sta
return SignalReport.Status(value) if value is not None else None
+def get_content_revision_count(*, team_id: int, report_id: str) -> int:
+ """Team-scoped read of the report's running content-revision total, so an edit that doesn't itself
+ revise content (a note, a reviewer change, a restatement) can still echo the running total the
+ scout reasons about the cap with. Returns 0 when the counter is null or the report doesn't exist
+ for the team; `record_content_revision` is what mutates it."""
+ value = (
+ SignalReport.objects.filter(team_id=team_id, id=report_id)
+ .values_list("content_revision_count", flat=True)
+ .first()
+ )
+ return value if value is not None else 0
+
+
+def prepare_scout_supersession(
+ *, team_id: int, report_id: str, title: str | None, summary: str | None
+) -> ImplementationResearchContext:
+ report = SignalReport.objects.filter(team_id=team_id, id=report_id).first()
+ if (
+ report is None
+ or (report.content_revision_count or 0) >= MAX_SCOUT_CONTENT_REVISIONS
+ or not ((title is not None and title != report.title) or (summary is not None and summary != report.summary))
+ ):
+ return NO_IMPLEMENTATION_CONTEXT
+ context = research_implementation_context(team_id, report_id)
+ if not context.candidates:
+ raise InvalidScoutReportError("Could not verify an implementation PR to replace. Retry the edit.")
+ return context
+
+
def update_scout_report(
*,
team_id: int,
@@ -472,6 +516,17 @@ def update_scout_report(
return updated_fields
+@frozen
+class AppendedNote:
+ """What one `append_report_note` call did to the report."""
+
+ report_id: str
+ # Counts only explicit corroborations so substantive notes never consume the cap.
+ corroboration_count: int
+ # Only confirmations marked as having no new information may discard their text.
+ collapsed: bool
+
+
def append_report_note(
*,
team_id: int,
@@ -479,29 +534,163 @@ def append_report_note(
note: str,
attribution: ArtefactAttribution,
author: str | None = None,
-) -> str:
+ corroboration_only: bool = False,
+) -> AppendedNote:
"""Append a free-form `note` artefact to an existing report (the `edit_report` annotate path).
Team-scoped fail-closed: a `report_id` the team doesn't own raises. `edit_report` can target ANY
inbox report (decision #2), pipeline-authored ones included, so the note is attributed (to the
- scout's task) to keep the edit auditable and distinguishable from pipeline output. Returns the
- report_id on success.
+ scout's task) to keep the edit auditable and distinguishable from pipeline output.
+
+ Only explicit corroborations count towards `MAX_SCOUT_REPORT_NOTES`. Free-form notes can carry
+ recovery details or new evidence, so they must remain in the work log regardless of that cap.
+
+ The report row is locked for the read-then-increment so two runs appending at once cannot both
+ read the same count. The count is written with a queryset update so `updated_at` stays put — a
+ scout re-confirming a report has not changed it, and bumping the timestamp would reorder the
+ inbox and, on the pipeline side, read as the report still moving.
"""
if not note or not note.strip():
raise InvalidScoutReportError("note must not be empty")
_validate_report_id(report_id)
with transaction.atomic():
# Existence is the team-scoped gate; the artefact append itself is keyed by report_id.
- if not SignalReport.objects.filter(team_id=team_id, id=report_id).exists():
+ existing = (
+ SignalReport.objects.select_for_update()
+ .filter(team_id=team_id, id=report_id)
+ .values("corroboration_count")
+ .first()
+ )
+ if existing is None:
raise InvalidScoutReportError(f"report {report_id} not found for team {team_id}")
- SignalReportArtefact.add_log(
+ previous_count = existing["corroboration_count"] or 0
+ collapsed = corroboration_only and previous_count >= MAX_SCOUT_REPORT_NOTES
+ corroboration_count = previous_count + int(corroboration_only)
+ if corroboration_only:
+ SignalReport.objects.filter(team_id=team_id, id=report_id).update(corroboration_count=corroboration_count)
+ if not collapsed:
+ SignalReportArtefact.add_log(
+ team_id=team_id,
+ report_id=report_id,
+ content=NoteArtefact(note=note, author=author),
+ attribution=attribution,
+ )
+ logger.info(
+ "signals_scout.edit_report: note appended",
+ extra={
+ "team_id": team_id,
+ "report_id": report_id,
+ "corroboration_count": corroboration_count,
+ "collapsed": collapsed,
+ },
+ )
+ return AppendedNote(report_id=report_id, corroboration_count=corroboration_count, collapsed=collapsed)
+
+
+def record_content_revision(*, team_id: int, report_id: str) -> int:
+ """Count one scout rewrite of a report's title or summary and return the report's new total.
+
+ Kept out of `update_scout_report` so the field list that call returns stays the report's
+ presentation fields, which is what the edit echoes back to the scout. Locked and written the
+ same way as `append_report_note` above, and for the same reasons.
+ """
+ _validate_report_id(report_id)
+ with transaction.atomic():
+ existing = (
+ SignalReport.objects.select_for_update()
+ .filter(team_id=team_id, id=report_id)
+ .values("content_revision_count")
+ .first()
+ )
+ if existing is None:
+ raise InvalidScoutReportError(f"report {report_id} not found for team {team_id}")
+ content_revision_count = (existing["content_revision_count"] or 0) + 1
+ SignalReport.objects.filter(team_id=team_id, id=report_id).update(content_revision_count=content_revision_count)
+ return content_revision_count
+
+
+def record_implementation_decision(
+ *,
+ team_id: int,
+ report_id: str,
+ supersede: bool,
+ updated_fields: list[str],
+ attribution: ArtefactAttribution,
+ implementation_context: ImplementationResearchContext,
+ author: str | None = None,
+ supersede_requested: bool = False,
+) -> None:
+ """Record what this rewrite means for the report's pull request, as the same
+ `implementation_decision` artefact the research agent writes.
+
+ One shape for both producers, so auto-start reads the decision the same way regardless of who
+ made it. The reason names the rewrite rather than restating it: the report's new summary is the
+ argument, and this artefact only has to say which version of it the open pull request predates.
+
+ Written on every content revision, including the ones that claim nothing. The artefact is
+ latest-wins and auto-start re-reads it from paths a scout never sees (a reviewer edit, a later
+ research pass), so leaving an old `supersede=True` standing after a rewrite that made no such
+ claim would let one of those paths open a replacement off a decision nobody made.
+
+ `supersede_requested` is the caller's ask, `supersede` the policy answer to it. They part company
+ past the revision cap, where the reason has to say the cap refused the claim: reading the refusal
+ back as "the fix did not change" states the scout's judgment backwards, in the one entry a
+ reviewer opens to find out why no replacement started.
+ """
+ fields = " and ".join(sorted(set(updated_fields) & {"title", "summary"})) or "content"
+ who = author or "A scout"
+ blocked_reason: Literal["revision_limit"] | None = (
+ "revision_limit" if supersede_requested and not supersede else None
+ )
+ if supersede:
+ reason = (
+ f"{who} rewrote the report's {fields}. "
+ "The open pull request was built from the version before that rewrite."
+ )
+ elif supersede_requested:
+ reason = (
+ f"{who} rewrote the report's {fields} and asked to replace the open pull request. "
+ f"Only a report's first {MAX_SCOUT_CONTENT_REVISIONS} rewrites can do that, "
+ "so the pull request stays open."
+ )
+ else:
+ reason = f"{who} rewrote the report's {fields} without changing what the fix should be."
+ report = SignalReport.objects.get(team_id=team_id, id=report_id)
+ context_matches = (
+ implementation_context.run_count == report.run_count
+ and implementation_context.started_at == report.last_run_at
+ and implementation_context.content_revision_count + 1 == report.content_revision_count
+ )
+ if supersede and (not context_matches or not implementation_context.candidates):
+ raise InvalidScoutReportError("The implementation context changed before the edit was saved. Retry the edit.")
+ # A research pass writes the report's title and summary as it leaves IN_PROGRESS, and that write
+ # moves none of the fields `decision_matches_report` compares. A claim recorded before it would
+ # still read as current afterwards, against content the scout never assessed.
+ if supersede and report.status != SignalReport.Status.READY:
+ raise InvalidScoutReportError(
+ "The report's content is not settled yet. Retry the edit once the report is ready."
+ )
+ decision = SignalReportArtefact.append_status(
+ team_id=team_id,
+ report_id=report_id,
+ content=ImplementationDecision(
+ supersede=supersede,
+ reason=reason,
+ targets=list(implementation_context.candidates) if supersede and context_matches else [],
+ research_run_count=report.run_count,
+ research_started_at=report.last_run_at,
+ content_revision_count=report.content_revision_count or 0,
+ blocked_reason=blocked_reason,
+ ),
+ attribution=attribution,
+ )
+ if supersede:
+ SignalReportArtefact.append_status(
team_id=team_id,
report_id=report_id,
- content=NoteArtefact(note=note, author=author),
- attribution=attribution,
+ content=ImplementationDispatch(decision_id=decision.id, source_skill=author),
+ attribution=ArtefactAttribution.system(),
)
- logger.info("signals_scout.edit_report: note appended", extra={"team_id": team_id, "report_id": report_id})
- return report_id
def append_report_evidence(
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 43f5858ac9c1..790448f777c9 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -45,6 +45,7 @@ if TYPE_CHECKING:
from .artefact_schemas import NON_WRITABLE_ARTEFACT_TYPES
from .daily_limit import reports_generated_today, team_day_start
from .models import (
+ MAX_SCOUT_REPORT_NOTES,
AutonomyPriority,
SignalActorKind,
SignalReport,
@@ -1111,6 +1112,13 @@ class SignalReportSerializer(serializers.ModelSerializer):
"The general view lists every report regardless of this value."
),
)
+ collapsed_note_count = serializers.SerializerMethodField(
+ help_text=(
+ "How many scout notes this report received beyond the few its work log keeps as entries. "
+ "0 when nothing was dropped. These say the finding still holds, so the count is shown in "
+ "place of the entries."
+ ),
+ )
class Meta:
model = SignalReport
@@ -1122,6 +1130,7 @@ class SignalReportSerializer(serializers.ModelSerializer):
"total_weight", # Used for priority scoring
"signal_count", # Used for occurrence count
"signals_at_run", # Snooze threshold: re-promote when signal_count >= this value
+ "collapsed_note_count", # Scout notes the work log dropped, rendered as one line instead
"created_at",
"updated_at",
"artefact_count",
@@ -1378,6 +1387,9 @@ class SignalReportSerializer(serializers.ModelSerializer):
claims[report_id] = get_active_claim(team_id=obj.team_id, report_id=report_id)
return claims[report_id]
+ def get_collapsed_note_count(self, obj: SignalReport) -> int:
+ return max(0, (obj.corroboration_count or 0) - MAX_SCOUT_REPORT_NOTES)
+
@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/supersession.py b/products/signals/backend/supersession.py
index 912274aafdd4..10635c8751f4 100644
--- a/products/signals/backend/supersession.py
+++ b/products/signals/backend/supersession.py
@@ -27,7 +27,12 @@ from products.signals.backend.implementation_pr import (
fetch_implementation_prs_for_reports,
implementation_pr_needed_by_another_report,
)
-from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportTask
+from products.signals.backend.models import (
+ MAX_SCOUT_CONTENT_REVISIONS,
+ SignalReport,
+ SignalReportArtefact,
+ SignalReportTask,
+)
from products.signals.backend.report_claims import get_active_claim
from products.tasks.backend.facade import api as tasks_facade
@@ -41,6 +46,7 @@ class ImplementationResearchContext:
candidates: tuple[ImplementationTarget, ...] = ()
run_count: int | None = None
started_at: datetime | None = None
+ content_revision_count: int = 0
NO_IMPLEMENTATION_CONTEXT = ImplementationResearchContext()
@@ -70,6 +76,15 @@ def _verify_replacement_prs(replacement: SignalReportArtefact, run_id: UUID, url
raise ReplacementPullRequestUnverified("Could not verify an open PR created by the replacement run")
+def decision_matches_report(report: SignalReport, decision: ImplementationDecision) -> bool:
+ return bool(
+ decision.research_run_count == report.run_count
+ and decision.research_started_at == report.last_run_at
+ and decision.content_revision_count == (report.content_revision_count or 0)
+ and (decision.research_started_at is not None or decision.content_revision_count > 0)
+ )
+
+
def _can_close_target(
replacement: SignalReportArtefact,
content: ImplementationReplacement,
@@ -93,8 +108,7 @@ def _can_close_target(
reservation
and reservation.worker_token == progress.worker_token
and report.status == SignalReport.Status.READY
- and report.run_count == content.decision.research_run_count
- and report.last_run_at == content.decision.research_started_at
+ and decision_matches_report(report, content.decision)
and claim
and claim.claim_id == replacement.claim_id
and claim.actor_task_id == replacement.task_id
@@ -239,7 +253,10 @@ def research_implementation_context(team_id: int, report_id: str) -> Implementat
if sha:
candidates.append(target.model_copy(update={"head_sha": sha}))
return ImplementationResearchContext(
- candidates=tuple(candidates), run_count=report.run_count, started_at=report.last_run_at
+ candidates=tuple(candidates),
+ run_count=report.run_count,
+ started_at=report.last_run_at,
+ content_revision_count=report.content_revision_count or 0,
)
except Exception:
logger.exception("signals_automated_pr_lookup_failed", report_id=report_id)
@@ -294,11 +311,15 @@ def decision_is_current(report: SignalReport, decision: ImplementationDecision)
return bool(
decision.supersede
and decision.targets
- and decision.research_started_at
and report.status == SignalReport.Status.READY
- and decision.research_run_count == report.run_count
- and decision.research_started_at == report.last_run_at
- and report.run_count > (report.implemented_at_run_count or 0)
+ and decision_matches_report(report, decision)
+ and (
+ report.run_count > (report.implemented_at_run_count or 0)
+ or (
+ 0 < (report.content_revision_count or 0) <= MAX_SCOUT_CONTENT_REVISIONS
+ and (report.content_revision_count or 0) > (report.implemented_at_revision_count or 0)
+ )
+ )
and pending_replacement(report.team_id, str(report.id)) is None
)
@@ -397,7 +418,7 @@ def reconcile_replacement(team_id: int, replacement_id: str) -> bool:
return False
if not run.is_terminal:
return False
- if report.run_count != content.decision.research_run_count or report.status != SignalReport.Status.READY:
+ if not decision_matches_report(report, content.decision) or report.status != SignalReport.Status.READY:
_finish(
replacement,
progress.model_copy(
@@ -477,7 +498,7 @@ def reconcile_replacement(team_id: int, replacement_id: str) -> bool:
return False
if (
current_report.status != SignalReport.Status.READY
- or current_report.run_count != content.decision.research_run_count
+ or not decision_matches_report(current_report, content.decision)
or not current_claim
or current_claim.claim_id != replacement.claim_id
):
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 52dd753b32f8..0b13ac65751d 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -23,6 +23,10 @@ from posthog.ph_client import ph_scoped_capture
from posthog.scoping_audit import skip_team_scope_audit
from products.signals.backend.billing import current_billing_period_bounds
+from products.signals.backend.implementation_dispatch_tasks import (
+ dispatch_implementation_replacement as dispatch_implementation_replacement,
+ sweep_implementation_dispatches as sweep_implementation_dispatches,
+)
from products.signals.backend.implementation_pr import PrCloseReason, close_implementation_pr_for_report
from products.signals.backend.models import (
SignalReport,
diff --git a/products/signals/backend/test/test_auto_start.py b/products/signals/backend/test/test_auto_start.py
index c78157b92a88..5ee525217b40 100644
--- a/products/signals/backend/test/test_auto_start.py
+++ b/products/signals/backend/test/test_auto_start.py
@@ -21,12 +21,15 @@ from products.signals.backend.agent_runtime import AgentRuntime
from products.signals.backend.auto_start import (
NO_STEERING,
NO_SUPERSEDE,
+ ImplementationReportContent,
+ ReportChangedDuringAutostart,
ReportSteering,
ReviewerContent,
SupersedeDecision,
_build_autostart_task_description,
_create_implementation_task_if_absent,
_generate_self_driving_head_branch,
+ _has_unimplemented_work,
_live_skill_owner_identities,
_report_meets_team_autostart_threshold,
_resolve_autostart_assignee,
@@ -37,6 +40,7 @@ from products.signals.backend.auto_start import (
maybe_autostart_implementation_task,
)
from products.signals.backend.models import (
+ MAX_SCOUT_CONTENT_REVISIONS,
SignalReport,
SignalReportArtefact,
SignalReportTask,
@@ -237,7 +241,8 @@ def test_live_owner_logins_span_every_scout_that_touched_the_report(organization
@pytest.mark.django_db
-def test_live_owner_logins_survive_a_lost_edit_tally(organization, team):
[email protected]("source", ["reviewer", "dispatch"])
+def test_live_owner_logins_survive_a_lost_edit_tally(organization, team, source):
# The run tallies are best-effort writes that swallow failures, so a scout whose tally write was
# lost leaves no `edited_report_ids` trace — the entry's own `source_skill` stamp (committed
# atomically with the pick) must still bring that scout's current owners into the exclusion.
@@ -249,8 +254,11 @@ def test_live_owner_logins_survive_a_lost_edit_tally(organization, team):
with team_scope(team.id, canonical=True):
LLMSkillOwner.objects.create(team=team, skill_name="signals-scout-tallyless", user=owner)
- reviewers = [_reviewer("tallylessowner", source_skill="signals-scout-tallyless")]
- assert _live_skill_owner_identities(team, str(report.id), reviewers).github_logins == frozenset({"tallylessowner"})
+ reviewers = [_reviewer("tallylessowner", source_skill="signals-scout-tallyless" if source == "reviewer" else None)]
+ identities = _live_skill_owner_identities(
+ team, str(report.id), reviewers, source_skill="signals-scout-tallyless" if source == "dispatch" else None
+ )
+ assert identities.github_logins == frozenset({"tallylessowner"})
@pytest.mark.parametrize(
@@ -382,7 +390,10 @@ def test_generate_self_driving_head_branch_is_readable_and_valid(title, expected
@pytest.mark.django_db
-def test_create_implementation_task_if_absent_is_idempotent(organization, team):
+ "concurrent_change", [None, {"summary": "A newer fix"}, {"run_count": 2}, {"content_revision_count": 1}]
+)
+def test_create_implementation_task_if_absent_is_idempotent(organization, team, concurrent_change):
# The locked create guards against duplicate auto-start tasks: a second evaluation that
# observes the link row must no-op rather than spawn another Task / draft PR. It also asserts
# the facade is invoked with the SIGNAL_REPORT origin and ai_stage="implementation" so the
@@ -413,6 +424,7 @@ def test_create_implementation_task_if_absent_is_idempotent(organization, team):
"report_id": str(report.id),
"title": "t",
"description": "d",
+ "expected_content": ImplementationReportContent.from_report(report),
"user_id": user.id,
"repository": "owner/repo",
"base_branch": None,
@@ -423,6 +435,15 @@ def test_create_implementation_task_if_absent_is_idempotent(organization, team):
assert _create_implementation_task_if_absent(**kwargs) is False
mock_create.assert_not_called()
assignment_model.all_teams.filter(report=report).update(actor_kind=None, actor_user=None)
+ if concurrent_change is not None:
+ SignalReport.objects.filter(id=report.id).update(**concurrent_change)
+ with pytest.raises(ReportChangedDuringAutostart):
+ _create_implementation_task_if_absent(**kwargs)
+ mock_create.assert_not_called()
+ report.refresh_from_db()
+ assert report.implemented_at_run_count is None
+ assert report.implemented_at_revision_count is None
+ kwargs["expected_content"] = ImplementationReportContent.from_report(report)
first = _create_implementation_task_if_absent(**kwargs)
second = _create_implementation_task_if_absent(**kwargs)
@@ -509,6 +530,7 @@ def test_create_implementation_task_freezes_billing_exemption(
report_id=str(report.id),
title="t",
description="d",
+ expected_content=ImplementationReportContent.from_report(report),
user_id=user.id,
repository="owner/repo",
base_branch=None,
@@ -545,6 +567,7 @@ def test_create_implementation_task_threads_resolved_runtime(organization, team)
"report_id": str(report.id),
"title": "t",
"description": "d",
+ "expected_content": ImplementationReportContent.from_report(report),
"user_id": user.id,
"repository": "owner/repo",
"base_branch": None,
@@ -564,8 +587,10 @@ def test_create_implementation_task_threads_resolved_runtime(organization, team)
@pytest.mark.asyncio
@pytest.mark.django_db(transaction=True)
[email protected]("autostart_enabled", [True, False, None])
-async def test_team_autostart_switch_gates_reviewerless_fallback(autostart_enabled):
+ ("autostart_enabled", "concurrent_edit"), [(True, False), (False, False), (None, False), (True, True)]
+)
+async def test_team_autostart_switch_gates_reviewerless_fallback(autostart_enabled, concurrent_edit):
# The master switch must gate the reviewer-less fallback — the path email-login teams (no linked
# GitHub) hit. An actionable, prioritized report with no resolvable reviewer auto-starts under the
# team's signals enabler unless the switch is an explicit False (null leaves autostart on); committed
@@ -586,6 +611,16 @@ async def test_team_autostart_switch_gates_reviewerless_fallback(autostart_enabl
report = SignalReport.objects.create(
team=team, status=SignalReport.Status.READY, title="t", summary="s", signal_count=0, total_weight=0.0
)
+ if concurrent_edit:
+ for kind, content in [
+ (
+ "actionability_judgment",
+ {"explanation": "Clear fix", "actionability": "immediately_actionable", "already_addressed": False},
+ ),
+ ("priority_judgment", {"explanation": "Affects sessions", "priority": "P2"}),
+ ("repo_selection", {"repository": "owner/repo", "reason": "Selected", "autostart_eligible": True}),
+ ]:
+ SignalReportArtefact.objects.create(team=team, report=report, type=kind, content=json.dumps(content))
return team, report
team, report = await sync_to_async(_setup)()
@@ -601,9 +636,18 @@ async def test_team_autostart_switch_gates_reviewerless_fallback(autostart_enabl
return SimpleNamespace(task_id=task.id, team_id=team.id, latest_run=SimpleNamespace(id=run.id))
pinned = AgentRuntime(runtime_adapter="codex", model="gpt-5.6-terra", reasoning_effort="medium")
+ runtime_calls = 0
+
+ def resolve_runtime(*_args):
+ nonlocal runtime_calls
+ runtime_calls += 1
+ if concurrent_edit and runtime_calls == 1:
+ SignalReport.objects.filter(id=report.id).update(summary="A newer fix", content_revision_count=1)
+ return pinned
+
with (
patch.object(tasks_facade, "create_and_run_task", side_effect=_fake_create_and_run_task) as mock_create,
- patch("products.signals.backend.auto_start.resolve_agent_runtime", return_value=pinned),
+ patch("products.signals.backend.auto_start.resolve_agent_runtime", side_effect=resolve_runtime),
):
await maybe_autostart_implementation_task(
team_id=team.id,
@@ -622,6 +666,11 @@ async def test_team_autostart_switch_gates_reviewerless_fallback(autostart_enabl
assert (mock_create.call_count == 1) is (autostart_enabled is not False)
+ if concurrent_edit:
+ assert "A newer fix" in mock_create.call_args.kwargs["description"]
+ await sync_to_async(report.refresh_from_db)()
+ assert report.implemented_at_revision_count == 1
+
@pytest.mark.asyncio
@pytest.mark.django_db(transaction=True)
@@ -1132,6 +1181,7 @@ def test_supersede_without_permission_leaves_the_gate_closed(organization, team)
"report_id": str(report.id),
"title": "t",
"description": "d",
+ "expected_content": ImplementationReportContent.from_report(report),
"user_id": user.id,
"repository": "owner/repo",
"base_branch": None,
@@ -1222,3 +1272,37 @@ async def test_only_the_current_passs_implementation_decision_is_read(written_du
passed_decision = mock_autostart.call_args.kwargs["implementation_decision"]
assert (passed_decision is not None) is written_during_current_pass
+
+
+ ("run_count", "implemented_at_run_count", "revisions", "implemented_at_revision_count", "expected"),
+ [
+ # Pipeline arm, unchanged: research ran again since the PR was built.
+ (2, 1, 0, None, True),
+ (2, 2, 0, None, False),
+ # Scout arm: a rewrite the current PR predates, on a report the pipeline never re-researched.
+ (0, 0, 1, 0, True),
+ (0, 0, 1, 1, False),
+ # A report the scout keeps rewriting stops earning replacements at the cap. Without this a
+ # scout on a daily schedule opens a pull request per run, forever.
+ (0, 0, MAX_SCOUT_CONTENT_REVISIONS, MAX_SCOUT_CONTENT_REVISIONS - 1, True),
+ (0, 0, MAX_SCOUT_CONTENT_REVISIONS + 1, MAX_SCOUT_CONTENT_REVISIONS, False),
+ # Null stamps: a report implemented before either counter existed.
+ (1, None, 0, None, True),
+ (0, None, 1, None, True),
+ (0, None, 0, None, False),
+ (0, None, None, None, False),
+ (2, 1, None, None, True),
+ (2, 2, None, None, False),
+ ],
+)
+def test_has_unimplemented_work(
+ run_count, implemented_at_run_count, revisions, implemented_at_revision_count, expected
+):
+ report = SignalReport(
+ run_count=run_count,
+ implemented_at_run_count=implemented_at_run_count,
+ content_revision_count=revisions,
+ implemented_at_revision_count=implemented_at_revision_count,
+ )
+ assert _has_unimplemented_work(report) is expected
diff --git a/products/signals/backend/test/test_implementation_dispatch.py b/products/signals/backend/test/test_implementation_dispatch.py
new file mode 100644
index 000000000000..1472db6adde7
--- /dev/null
+++ b/products/signals/backend/test/test_implementation_dispatch.py
@@ -0,0 +1,194 @@
+from datetime import timedelta
+from uuid import uuid4
+
+from posthog.test.base import BaseTest
+from time_machine import travel
+from unittest.mock import AsyncMock, patch
+
+from django.utils import timezone
+
+from asgiref.sync import sync_to_async
+from parameterized import parameterized
+
+from products.signals.backend.artefact_attribution import ArtefactAttribution
+from products.signals.backend.artefact_schemas import (
+ ImplementationDecision,
+ ImplementationDispatch,
+ ImplementationReplacement,
+ ImplementationTarget,
+)
+from products.signals.backend.auto_start import AutostartOutcome
+from products.signals.backend.implementation_dispatch import ImplementationDispatcher
+from products.signals.backend.models import SignalReport, SignalReportArtefact
+
+DISPATCH_TASK = "products.signals.backend.tasks.dispatch_implementation_replacement.apply_async"
+AUTOSTART = "products.signals.backend.implementation_dispatch.maybe_autostart_from_report_artefacts"
+
+
+class TestImplementationDispatch(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.report = SignalReport.objects.create(
+ team=self.team,
+ status="ready",
+ title="Retry checkout",
+ summary="Move the retry to the request boundary",
+ content_revision_count=1,
+ )
+ self.decision = SignalReportArtefact.append_status(
+ team_id=self.team.id,
+ report_id=str(self.report.id),
+ content=ImplementationDecision(
+ supersede=True,
+ reason="The request boundary owns retries.",
+ content_revision_count=1,
+ research_run_count=self.report.run_count,
+ research_started_at=self.report.last_run_at,
+ targets=[
+ ImplementationTarget(
+ task_id=uuid4(),
+ run_id=uuid4(),
+ automation_artefact_id=uuid4(),
+ pr_url="https://github.com/example/repo/pull/1",
+ head_sha="original-sha",
+ )
+ ],
+ ),
+ attribution=ArtefactAttribution.system(),
+ )
+ self.save_progress(ImplementationDispatch(decision_id=self.decision.id, source_skill="example-scout"))
+ self.dispatcher = ImplementationDispatcher()
+
+ def save_progress(self, progress: ImplementationDispatch) -> None:
+ SignalReportArtefact.append_status(
+ team_id=self.team.id,
+ report_id=str(self.report.id),
+ content=progress,
+ attribution=ArtefactAttribution.system(),
+ )
+
+ def progress(self) -> ImplementationDispatch:
+ row = SignalReportArtefact.objects.filter(report=self.report, type="implementation_dispatch").latest(
+ "created_at", "id"
+ )
+ return ImplementationDispatch.model_validate_json(row.content)
+
+ def start(self) -> None:
+ self.dispatcher.dispatch(self.team.id, str(self.decision.id))
+
+ @parameterized.expand([("quota",), ("disabled",), ("no_runner",)])
+ def test_policy_block_needs_a_new_trigger(self, reason: str) -> None:
+ with patch(AUTOSTART, new=AsyncMock(return_value=AutostartOutcome(status="blocked", reason=reason))):
+ self.start()
+ assert self.progress().status == "blocked"
+ with patch(DISPATCH_TASK) as enqueue:
+ self.dispatcher.enqueue_page()
+ enqueue.assert_not_called()
+ with self.captureOnCommitCallbacks(execute=True):
+ self.dispatcher.trigger(self.team.id, str(self.report.id))
+ enqueue.assert_called_once_with(args=[self.team.id, str(self.decision.id)], countdown=0)
+ assert self.progress().status == "pending"
+
+ def test_lost_publish_is_recovered_and_transient_failure_retries(self) -> None:
+ with patch(DISPATCH_TASK, side_effect=ConnectionError), self.captureOnCommitCallbacks(execute=True):
+ assert self.dispatcher.trigger(self.team.id, str(self.report.id))
+ with patch(DISPATCH_TASK) as enqueue:
+ self.dispatcher.enqueue_page()
+ enqueue.assert_called_once_with(args=[self.team.id, str(self.decision.id)], countdown=0)
+ with patch(AUTOSTART, new=AsyncMock(side_effect=ConnectionError)), patch(DISPATCH_TASK) as enqueue:
+ with self.captureOnCommitCallbacks(execute=True):
+ self.start()
+ enqueue.assert_called_once_with(args=[self.team.id, str(self.decision.id)], countdown=60)
+ state = self.progress()
+ assert state.status == "retrying"
+ assert state.attempt == 1
+ assert state.next_retry_at is not None
+ with patch(DISPATCH_TASK) as enqueue:
+ self.dispatcher.enqueue_page()
+ enqueue.assert_not_called()
+ with travel(state.next_retry_at + timedelta(seconds=1), tick=False):
+ self.dispatcher.enqueue_page()
+ enqueue.assert_called_once()
+
+ def test_live_worker_is_not_duplicated_and_dead_worker_is_recovered(self) -> None:
+ self.save_progress(
+ ImplementationDispatch(
+ decision_id=self.decision.id,
+ status="processing",
+ attempt=1,
+ worker_token=uuid4(),
+ lease_until=timezone.now() + timedelta(seconds=300),
+ )
+ )
+ with patch(AUTOSTART, new=AsyncMock(return_value=AutostartOutcome(status="blocked"))) as start:
+ self.start()
+ start.assert_not_awaited()
+ with travel(timezone.now() + timedelta(seconds=301), tick=False):
+ self.start()
+ start.assert_awaited_once()
+ assert self.progress().attempt == 2
+
+ @parameterized.expand([("revision",), ("research",), ("dismissal",), ("new_decision",)])
+ def test_obsolete_dispatch_never_starts(self, change: str) -> None:
+ if change == "new_decision":
+ decision = ImplementationDecision.model_validate_json(self.decision.content)
+ decision.supersede = False
+ SignalReportArtefact.append_status(
+ team_id=self.team.id,
+ report_id=str(self.report.id),
+ content=decision,
+ attribution=ArtefactAttribution.system(),
+ )
+ else:
+ changes: dict[str, dict[str, int | str]] = {
+ "revision": {"content_revision_count": 2},
+ "research": {"status": "in_progress"},
+ "dismissal": {"status": "suppressed"},
+ }
+ SignalReport.objects.filter(id=self.report.id).update(**changes[change])
+ with patch(AUTOSTART, new=AsyncMock()) as start:
+ self.start()
+ start.assert_not_awaited()
+ assert self.progress().status == "cancelled"
+
+ def test_committed_replacement_wins_over_a_postcommit_failure(self) -> None:
+ async def start_and_fail(**kwargs: object) -> None:
+ await sync_to_async(SignalReportArtefact.add_log)(
+ team_id=self.team.id,
+ report_id=str(self.report.id),
+ content=ImplementationReplacement(
+ decision_id=self.decision.id,
+ decision=ImplementationDecision.model_validate_json(self.decision.content),
+ run_id=uuid4(),
+ ),
+ attribution=ArtefactAttribution.system(),
+ )
+ raise ConnectionError
+
+ with patch(AUTOSTART, side_effect=start_and_fail) as start, patch(DISPATCH_TASK) as enqueue:
+ with self.captureOnCommitCallbacks(execute=True):
+ self.start()
+ self.start()
+ self.dispatcher.enqueue_page()
+ assert start.call_count == 1
+ enqueue.assert_not_called()
+ assert self.progress().status == "started"
+
+ def test_sweep_pages_past_blocked_work(self) -> None:
+ state = self.progress()
+ state.status = "blocked"
+ self.save_progress(state)
+ SignalReportArtefact.append_status(
+ team_id=self.team.id,
+ report_id=str(self.report.id),
+ content=ImplementationDecision(supersede=False, reason="No replacement"),
+ attribution=ArtefactAttribution.system(),
+ )
+ with (
+ patch("products.signals.backend.implementation_dispatch.DISPATCH_SWEEP_BATCH_SIZE", 1),
+ patch("products.signals.backend.tasks.sweep_implementation_dispatches.delay") as continuation,
+ patch(DISPATCH_TASK) as enqueue,
+ ):
+ self.dispatcher.enqueue_page()
+ continuation.assert_called_once()
+ enqueue.assert_not_called()
diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.py
index 8e467e10328c..9f064b8d106b 100644
--- a/products/signals/backend/test/test_scout_report_api.py
+++ b/products/signals/backend/test/test_scout_report_api.py
@@ -4,9 +4,10 @@ from uuid import uuid4
import pytest
from posthog.test.base import APIBaseTest
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
from django.apps import apps
+from django.db import OperationalError, transaction
from django.test import SimpleTestCase
from django.utils import timezone
@@ -19,8 +20,15 @@ from posthog.models import Organization, Team, User
from posthog.models.organization import OrganizationMembership
from products.signals.backend.artefact_schemas import Priority, PriorityAssessment, SuggestedReviewers, TaskRunArtefact
-from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact, SignalSourceConfig
+from products.signals.backend.models import (
+ MAX_SCOUT_CONTENT_REVISIONS,
+ ArtefactAttribution,
+ SignalReport,
+ SignalReportArtefact,
+ SignalSourceConfig,
+)
from products.signals.backend.report_generation.resolve_reviewers import ReviewerIdentitySet
+from products.signals.backend.scout_harness.serializers import EditReportRequestSerializer
from products.signals.backend.scout_harness.tools.report import (
MAX_EVIDENCE_DESCRIPTION_LENGTH,
MAX_REPORT_SIGNALS,
@@ -42,12 +50,14 @@ from products.signals.backend.scout_harness.tools.report import (
edit_report_sync,
)
from products.signals.backend.scout_report import ScoutReportSignal
+from products.signals.backend.task_run_artefacts import record_implementation_task
from products.signals.backend.temporal.report_safety_judge import SafetyJudgeResponse
from products.signals.backend.temporal.types import SignalData, render_signal_to_text
from products.signals.backend.test.report_metric_test_fixtures import trends_metric_query
from products.signals.backend.test.test_scout_harness_api import _authenticate_as_scout, _make_run
from products.skills.backend.models.skills import LLMSkill, LLMSkillOwner
from products.tasks.backend.facade.repo_selection import RepoSelectionResult
+from products.tasks.backend.models import Task, TaskRun
JUDGE_PATH = "products.signals.backend.scout_report.judge.judge_report_safety"
EMBED_PATH = "products.signals.backend.scout_report.persistence.emit_embedding_request"
@@ -59,6 +69,7 @@ METRICS_GATE_PATH = "products.signals.backend.scout_harness.tools.report.organiz
CAPTURE_INTERNAL_PATH = "products.signals.backend.scout_harness.tools.report.capture_internal"
CONNECTED_REPOS_PATH = "products.signals.backend.scout_harness.tools.report._connected_repositories"
SET_REPOSITORY_PATH = "products.signals.backend.scout_harness.tools.report.set_scout_report_repository"
+REVISION_COUNT_PATH = "products.signals.backend.scout_harness.tools.report.get_content_revision_count"
_CONNECTED_REPOS = ["acme/widgets", "acme/gadgets"]
REPORT_TOOLS = ["emit_report", "edit_report"]
@@ -117,6 +128,47 @@ class TestScoutReportAPI(APIBaseTest):
body.update(overrides)
return body
+ def _seed_implementation(self, report_id: str) -> MagicMock:
+ task = Task.objects.create(
+ team=self.team,
+ signal_report_id=report_id,
+ title="Original fix",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ repository="example/repo",
+ internal=True,
+ )
+ run = TaskRun.objects.create(
+ team=self.team,
+ task=task,
+ status="completed",
+ environment="cloud",
+ state={"ai_stage": "implementation", "self_driving_head_branch": "automated-original"},
+ output={"pr_url": "https://github.com/example/repo/pull/1"},
+ )
+ with transaction.atomic():
+ record_implementation_task(
+ team_id=self.team.id,
+ report_id=report_id,
+ task_id=str(task.id),
+ run_id=str(run.id),
+ automation_branch="automated-original",
+ )
+ github = MagicMock()
+ github.get_pull_request.return_value = {
+ "success": True,
+ "state": "open",
+ "merged": False,
+ "head_sha": "sha-1",
+ "head_branch": "automated-original",
+ "head_repository": "example/repo",
+ }
+ patcher = patch(
+ "products.signals.backend.supersession.GitHubIntegration.first_for_team_repository", return_value=github
+ )
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ return github
+
def _affected_users_metric(self, *, value: int = 17) -> dict:
return {
"metric_id": "affected-users",
@@ -466,6 +518,15 @@ class TestScoutReportAPI(APIBaseTest):
judge_mock.assert_not_awaited()
embed_mock.assert_not_called()
+ @parameterized.expand([("corroboration_only",), ("supersedes_implementation",)])
+ def test_an_omitted_edit_flag_stays_out_of_the_request_body(self, field: str) -> None:
+ # A DRF default renders as a default on the generated client, which sends an explicit `false`
+ # for a flag the caller omitted. The validator below rejects a field it does not declare, so a
+ # client deployed ahead of this endpoint would fail every edit, not only a supersede request.
+ serializer = EditReportRequestSerializer(data={"report_id": str(uuid4())})
+ assert serializer.is_valid(), serializer.errors
+ assert field not in serializer.validated_data
+
def test_evidence_append_is_rejected_at_the_report_cap_before_the_judge(self) -> None:
# Emit plus every append share one cap, and it is checked before the safety judge so a call
# the write would reject never pays for an LLM call.
@@ -598,6 +659,281 @@ class TestScoutReportAPI(APIBaseTest):
)
assert "- Source ID: checkout-errors" in rendered
+ @parameterized.expand(
+ [
+ ("title_rewrite", {"title": "a different root cause"}, True),
+ ("summary_rewrite", {"summary": "the checkout handler is fine, the queue is not"}, True),
+ # The 13x difference between counting edits and counting rewrites. A scout re-sending the
+ # text the report already holds has not revised anything.
+ ("restated_title", {"title": "Checkout p99 regressed after 4.2"}, False),
+ ("note_only", {"append_note": "still there"}, False),
+ ("reviewers_only", {"suggested_reviewers": [{"github_login": "OctoCat"}]}, False),
+ ("charts_only", {"charts": []}, False),
+ ]
+ )
+ def test_only_a_real_rewrite_counts_as_a_content_revision(self, _name, edit, expected) -> None:
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):
+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ with _safe_judge(), patch(AUTOSTART_PATH, new=AsyncMock()):
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={"report_id": created["report_id"], **edit},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["is_content_revision"] is expected
+ assert response.json()["content_revision_count"] == (1 if expected else 0)
+ assert SignalReport.objects.get(id=created["report_id"]).content_revision_count == (1 if expected else None)
+
+ @parameterized.expand(
+ [
+ ("note_only", {"append_note": "still there"}),
+ ("reviewers_only", {"suggested_reviewers": [{"github_login": "OctoCat"}]}),
+ ]
+ )
+ def test_non_revision_edit_returns_the_stored_running_total(self, _name, edit) -> None:
+ # The count is a running total, not a per-edit sentinel: a note or reviewer change on a report
+ # that has already been rewritten must echo the stored total, not the 0 initializer. The
+ # freshly-emitted case above (count 0) can't tell the two apart, so revise once first.
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):
+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ with _safe_judge(), patch(AUTOSTART_PATH, new=AsyncMock()):
+ self.client.post(
+ self._edit_url(str(run.id)),
+ data={"report_id": created["report_id"], "summary": "the queue, not the handler"},
+ format="json",
+ )
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={"report_id": created["report_id"], **edit},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["is_content_revision"] is False
+ assert response.json()["content_revision_count"] == 1
+ assert SignalReport.objects.get(id=created["report_id"]).content_revision_count == 1
+
+ def test_a_failed_running_total_read_takes_the_edit_with_it(self) -> None:
+ # The read above runs inside the edit's transaction, so a database failure on it rolls the
+ # note back instead of reporting a committed edit as failed. `edit_report` is not retry-safe:
+ # the scout's retry would append a second note and count a second corroboration.
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):
+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ report_id = created["report_id"]
+ before = SignalReport.objects.get(id=report_id)
+ with (
+ _safe_judge(),
+ patch(AUTOSTART_PATH, new=AsyncMock()),
+ patch("products.signals.backend.scout_harness.tools.report.emit_appended_report_evidence") as emit,
+ patch(REVISION_COUNT_PATH, side_effect=OperationalError("connection lost")),
+ ):
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={
+ "report_id": report_id,
+ "append_note": "still there",
+ "corroboration_only": True,
+ "append_evidence": [{"description": "The retry failed again", "source_id": "retry-2"}],
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
+ assert not SignalReportArtefact.objects.filter(
+ report_id=report_id, type="note", content__contains="still there"
+ ).exists()
+ after = SignalReport.objects.get(id=report_id)
+ assert after.corroboration_count == before.corroboration_count
+ assert after.signal_count == before.signal_count
+ emit.assert_not_called()
+
+ @parameterized.expand(
+ [
+ # A note says the finding still holds. It is not an argument that the fix changed, so it
+ # must not be a way to close someone's open pull request.
+ ("note_only", {"append_note": "still there"}),
+ ("reviewers_only", {"suggested_reviewers": [{"github_login": "OctoCat"}]}),
+ ("restated_title", {"title": "Checkout p99 regressed after 4.2"}),
+ ]
+ )
+ def test_supersede_needs_a_rewrite_behind_it(self, _name, edit) -> None:
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):
+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ with _safe_judge(), patch(AUTOSTART_PATH, new=AsyncMock()):
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={"report_id": created["report_id"], "supersedes_implementation": True, **edit},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["supersedes_implementation"] is False
+ assert (
+ self._latest_artefact(created["report_id"], SignalReportArtefact.ArtefactType.IMPLEMENTATION_DECISION)
+ is None
+ )
+
+ def test_supersede_records_a_decision_until_the_report_runs_out_of_revisions(self) -> None:
+ # Past the cap the rewrite still has to land: a scout must always be able to correct a
+ # report. Only the pull-request side stops.
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):
+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ report_id = created["report_id"]
+ self._seed_implementation(report_id)
+ recorded = []
+ for index in range(MAX_SCOUT_CONTENT_REVISIONS + 1):
+ with _safe_judge(), patch(AUTOSTART_PATH, new=AsyncMock()) as autostart:
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={
+ "report_id": report_id,
+ "summary": f"root cause number {index}",
+ "supersedes_implementation": True,
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["is_content_revision"] is True
+ recorded.append((response.json()["supersedes_implementation"], autostart.await_count))
+ if response.json()["supersedes_implementation"]:
+ decision = self._latest_artefact(report_id, SignalReportArtefact.ArtefactType.IMPLEMENTATION_DECISION)
+ dispatch = self._latest_artefact(report_id, SignalReportArtefact.ArtefactType.IMPLEMENTATION_DISPATCH)
+ assert decision is not None and dispatch is not None
+ progress = json.loads(dispatch.content)
+ assert progress["decision_id"] == str(decision.id)
+ assert progress["status"] == "pending"
+ assert progress["source_skill"] == run.skill_name
+
+ assert recorded == [(True, 1)] * MAX_SCOUT_CONTENT_REVISIONS + [(False, 0)]
+ report = SignalReport.objects.get(id=report_id)
+ assert report.content_revision_count == MAX_SCOUT_CONTENT_REVISIONS + 1
+ assert report.summary == f"root cause number {MAX_SCOUT_CONTENT_REVISIONS}"
+ # The decision is latest-wins and auto-start re-reads it from paths a scout never sees, so
+ # the refused rewrite has to leave a `False` standing rather than the last honored `True`.
+ decision = self._latest_artefact(report_id, SignalReportArtefact.ArtefactType.IMPLEMENTATION_DECISION)
+ assert decision is not None
+ refused = json.loads(decision.content)
+ assert refused["supersede"] is False
+ # A reviewer opens this entry to find out why no replacement started, so the refused claim
+ # must not read back as the scout judging the open pull request still right.
+ assert "asked to replace the open pull request" in refused["reason"]
+ assert "without changing what the fix should be" not in refused["reason"]
+ assert refused["blocked_reason"] == "revision_limit"
+
+ def test_a_rewrite_that_claims_nothing_retracts_the_last_supersede_decision(self) -> None:
+ # Same hazard from the other side: a scout supersedes once, then rewrites again saying
+ # nothing about the fix. A reviewer edit firing auto-start afterwards must not read the old
+ # claim and open a second replacement.
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):
+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ report_id = created["report_id"]
+ self._seed_implementation(report_id)
+ for summary, supersede in (("the queue, not the handler", True), ("the queue, with numbers", False)):
+ with _safe_judge(), patch(AUTOSTART_PATH, new=AsyncMock()):
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={"report_id": report_id, "summary": summary, "supersedes_implementation": supersede},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ decision = self._latest_artefact(report_id, SignalReportArtefact.ArtefactType.IMPLEMENTATION_DECISION)
+ assert decision is not None and json.loads(decision.content)["supersede"] is False
+
+ @parameterized.expand(
+ [
+ ("lookup_failed",),
+ ("report_changed",),
+ ("no_predecessor",),
+ # A pass rewrites the content on its way out of IN_PROGRESS without moving any counter
+ # the decision is fenced on, so a claim recorded during it would outlive the content.
+ ("report_in_progress",),
+ ]
+ )
+ def test_supersede_rejection_preserves_content_for_retry(self, failure: str) -> None:
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):
+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ report_id = created["report_id"]
+ github = self._seed_implementation(report_id)
+ verified = github.get_pull_request.return_value
+ if failure == "lookup_failed":
+ github.get_pull_request.return_value = {"success": False, "status_code": 502}
+ elif failure == "no_predecessor":
+ github.get_pull_request.return_value = {**verified, "state": "closed"}
+ elif failure == "report_in_progress":
+ SignalReport.objects.filter(id=report_id).update(status=SignalReport.Status.IN_PROGRESS)
+ else:
+
+ def change_during_lookup(*_args):
+ SignalReport.objects.filter(id=report_id).update(content_revision_count=1)
+ return verified
+
+ github.get_pull_request.side_effect = change_during_lookup
+ edit = {"report_id": report_id, "summary": "The queue needs backpressure.", "supersedes_implementation": True}
+ with _safe_judge(), patch(AUTOSTART_PATH, new=AsyncMock()) as autostart:
+ rejected = self.client.post(self._edit_url(str(run.id)), data=edit, format="json")
+ assert rejected.status_code == status.HTTP_400_BAD_REQUEST
+ assert SignalReport.objects.get(id=report_id).summary == self._payload()["summary"]
+ assert self._latest_artefact(report_id, SignalReportArtefact.ArtefactType.IMPLEMENTATION_DECISION) is None
+ autostart.assert_not_awaited()
+ github.get_pull_request.side_effect = None
+ github.get_pull_request.return_value = verified
+ SignalReport.objects.filter(id=report_id).update(status=SignalReport.Status.READY)
+ with _safe_judge(), patch(AUTOSTART_PATH, new=AsyncMock()):
+ accepted = self.client.post(self._edit_url(str(run.id)), data=edit, format="json")
+ assert accepted.status_code == status.HTTP_200_OK, accepted.json()
+ assert accepted.json()["supersedes_implementation"] is True
+ decision = self._latest_artefact(report_id, SignalReportArtefact.ArtefactType.IMPLEMENTATION_DECISION)
+ assert decision is not None
+ content = json.loads(decision.content)
+ assert len(content["targets"]) == 1
+ assert "summary" in content["reason"] and "updated_at" not in content["reason"]
+
+ @parameterized.expand([("note",), ("unchanged",), ("over_cap",)])
+ def test_ineligible_supersede_does_not_query_github(self, shape: str) -> None:
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):
+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ report_id = created["report_id"]
+ github = self._seed_implementation(report_id)
+ edit = {"append_note": "Still observed"} if shape == "note" else {"summary": self._payload()["summary"]}
+ if shape == "over_cap":
+ SignalReport.objects.filter(id=report_id).update(content_revision_count=MAX_SCOUT_CONTENT_REVISIONS)
+ edit = {"summary": "A new root cause"}
+ with _safe_judge(), patch(AUTOSTART_PATH, new=AsyncMock()):
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={"report_id": report_id, "supersedes_implementation": True, **edit},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["supersedes_implementation"] is False
+ github.get_pull_request.assert_not_called()
+
+ def test_free_form_note_survives_after_corroboration_cap(self) -> None:
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):
+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ report_id = created["report_id"]
+ SignalReport.objects.filter(id=report_id).update(corroboration_count=4)
+ for corroboration_only, note in [(True, "Still observed"), (False, "The deployment fixed the timeout")]:
+ with _safe_judge():
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={"report_id": report_id, "append_note": note, "corroboration_only": corroboration_only},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["corroboration_collapsed"] is corroboration_only
+ assert SignalReportArtefact.objects.filter(
+ report_id=report_id, type="note", content__contains=note
+ ).exists() is (not corroboration_only)
+ assert SignalReport.objects.get(id=report_id).corroboration_count == 5
+
def test_edit_report_records_edited_report_once_across_repeated_edits(self) -> None:
# The edited tally is set-membership, not a per-edit log: a run editing the same report twice
# records it once (the per-edit detail lives in the report's artefact log).
diff --git a/products/signals/backend/test/test_scout_report_persistence.py b/products/signals/backend/test/test_scout_report_persistence.py
index 3c6135db4337..69143c1895e6 100644
--- a/products/signals/backend/test/test_scout_report_persistence.py
+++ b/products/signals/backend/test/test_scout_report_persistence.py
@@ -23,6 +23,7 @@ from products.signals.backend.artefact_schemas import (
TitleChange,
)
from products.signals.backend.models import (
+ MAX_SCOUT_REPORT_NOTES,
ArtefactAttribution,
SignalReport,
SignalReportArtefact,
@@ -37,7 +38,9 @@ from products.signals.backend.scout_report import (
InvalidScoutReportError,
ScoutReportAlreadyEmittedError,
ScoutReportSignal,
+ append_report_note,
create_scout_report,
+ record_content_revision,
set_report_charts,
set_report_metrics,
set_report_suggested_prompts,
@@ -311,6 +314,60 @@ class TestScoutReportPersistence(BaseTest):
== 1
)
+ def test_note_appends_collapse_into_a_count_past_the_cap(self) -> None:
+ # A scout re-runs on its own schedule, so nothing about a report going quiet stops it
+ # appending "still there" notes. Without the cap the work log grows without bound and the
+ # entries that carry real work are buried under near-identical ones.
+ result = create_scout_report(
+ team_id=self.team.id,
+ title="t",
+ summary="s",
+ signals=[ScoutReportSignal(description="d", source_id="s")],
+ attribution=ArtefactAttribution.system(),
+ )
+ before = SignalReport.objects.get(id=result.report_id).updated_at
+ appended = [
+ append_report_note(
+ team_id=self.team.id,
+ report_id=result.report_id,
+ note=f"still there {index}",
+ corroboration_only=True,
+ attribution=ArtefactAttribution.system(),
+ )
+ for index in range(MAX_SCOUT_REPORT_NOTES + 2)
+ ]
+
+ assert [a.collapsed for a in appended] == [False] * MAX_SCOUT_REPORT_NOTES + [True, True]
+ assert [a.corroboration_count for a in appended] == list(range(1, MAX_SCOUT_REPORT_NOTES + 3))
+ report = SignalReport.objects.get(id=result.report_id)
+ assert report.corroboration_count == MAX_SCOUT_REPORT_NOTES + 2
+ written = SignalReportArtefact.objects.filter(
+ report_id=result.report_id, type=SignalReportArtefact.ArtefactType.NOTE
+ ).count()
+ # The creation provenance note is in there too, so the cap is what bounds the scout's own.
+ assert written == MAX_SCOUT_REPORT_NOTES + 1
+ # A re-confirmation has not changed the report, so it must not reorder the inbox or read as
+ # the report still moving.
+ assert report.updated_at == before
+
+ def test_content_revisions_count_per_report(self) -> None:
+ # The counter is what caps superseding, so it must not be shared between reports.
+ reports = [
+ create_scout_report(
+ team_id=self.team.id,
+ title=f"t{index}",
+ summary="s",
+ signals=[ScoutReportSignal(description="d", source_id=f"s{index}")],
+ attribution=ArtefactAttribution.system(),
+ )
+ for index in range(2)
+ ]
+ assert record_content_revision(team_id=self.team.id, report_id=reports[0].report_id) == 1
+ assert record_content_revision(team_id=self.team.id, report_id=reports[0].report_id) == 2
+ assert record_content_revision(team_id=self.team.id, report_id=reports[1].report_id) == 1
+ assert SignalReport.objects.get(id=reports[0].report_id).content_revision_count == 2
+ assert SignalReport.objects.get(id=reports[1].report_id).content_revision_count == 1
+
def test_update_fails_closed_on_cross_team_report(self) -> None:
# edit_report can target any inbox report (decision #2) — so the team scope is the only thing
# standing between a scout and another team's report. A cross-team id must raise, not no-op.
diff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.py
index 35b3680f5b0a..f34b6603f0dd 100644
--- a/products/signals/backend/test/test_signal_report_artefact_api.py
+++ b/products/signals/backend/test/test_signal_report_artefact_api.py
@@ -1454,6 +1454,11 @@ class TestSignalReportArtefactLogWriteViewSet(APIBaseTest):
{"replacement_id": str(uuid.UUID(int=1)), "status": "completed"},
{"replacement_id": str(uuid.UUID(int=2)), "status": "failed"},
),
+ (
+ "implementation_dispatch",
+ {"decision_id": str(uuid.UUID(int=1)), "status": "pending"},
+ {"decision_id": str(uuid.UUID(int=2)), "status": "started"},
+ ),
]
)
def test_implementation_lifecycle_artefacts_cannot_be_forged_or_removed(
diff --git a/products/signals/backend/test/test_supersede_handover.py b/products/signals/backend/test/test_supersede_handover.py
index baa571a033e6..1eaa84acb3b0 100644
--- a/products/signals/backend/test/test_supersede_handover.py
+++ b/products/signals/backend/test/test_supersede_handover.py
@@ -1,3 +1,4 @@
+from contextlib import nullcontext
from datetime import timedelta
from types import SimpleNamespace
from uuid import uuid4
@@ -14,10 +15,13 @@ from parameterized import parameterized
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.artefact_schemas import (
ImplementationDecision,
+ ImplementationDispatch,
ImplementationHandover,
ImplementationReplacement,
)
from products.signals.backend.auto_start import (
+ ImplementationReportContent,
+ ReportChangedDuringAutostart,
_create_implementation_task_if_absent,
_resolve_supersede,
maybe_autostart_implementation_task,
@@ -27,6 +31,7 @@ from products.signals.backend.models import SignalReport, SignalReportArtefact,
from products.signals.backend.report_assignments import create_claim, release_claim, update_assignments_for_pull_request
from products.signals.backend.report_claims import ReportClaim, get_active_claim
from products.signals.backend.report_generation.research import ActionabilityAssessment, ActionabilityChoice
+from products.signals.backend.scout_harness.tools.report import record_implementation_decision
from products.signals.backend.supersession import (
MAX_HANDOVER_ATTEMPTS,
TargetVerificationUnavailable,
@@ -127,6 +132,7 @@ class TestSupersedeHandover(BaseTest):
targets=[target for target in context.candidates if target.pr_url == OLD_PR],
research_run_count=context.run_count,
research_started_at=context.started_at,
+ content_revision_count=context.content_revision_count,
)
SignalReportArtefact.append_status(
team_id=self.team.id,
@@ -136,8 +142,10 @@ class TestSupersedeHandover(BaseTest):
)
return decision
- def start_replacement(self) -> SignalReportArtefact:
- decision = self.decision()
+ def start_replacement(
+ self, decision: ImplementationDecision | None = None, dispatch: ImplementationDispatch | None = None
+ ) -> SignalReportArtefact:
+ decision = decision or self.decision()
supersede = _resolve_supersede(self.report, decision)
assert supersede.allowed
@@ -167,16 +175,50 @@ class TestSupersedeHandover(BaseTest):
report_id=str(self.report.id),
title="Replacement",
description="Fix the changed layer",
+ expected_content=ImplementationReportContent.from_report(self.report),
user_id=self.user.id,
repository="example/repo",
base_branch=None,
supersede=supersede,
+ dispatch=dispatch,
)
for _ in range(2)
]
assert outcomes == [True, False]
return SignalReportArtefact.objects.get(report=self.report, type="implementation_replacement")
+ @parameterized.expand([("expired",), ("replaced",), ("current",)])
+ def test_dispatch_lease_fences_task_creation(self, lease: str) -> None:
+ decision = self.decision()
+ row = SignalReportArtefact.objects.get(report=self.report, type="implementation_decision")
+ reservation = ImplementationDispatch(
+ decision_id=row.id,
+ status="processing",
+ worker_token=uuid4(),
+ lease_until=timezone.now() + timedelta(seconds=300),
+ )
+ stored = reservation.model_copy()
+ if lease == "expired":
+ stored.lease_until = timezone.now() - timedelta(seconds=1)
+ elif lease == "replaced":
+ stored.worker_token = uuid4()
+ SignalReportArtefact.append_status(
+ team_id=self.team.id,
+ report_id=str(self.report.id),
+ content=stored,
+ attribution=ArtefactAttribution.system(),
+ )
+ if lease == "current":
+ replacement = self.start_replacement(decision, reservation)
+ assert ImplementationReplacement.model_validate_json(replacement.content).decision_id == row.id
+ else:
+ with self.assertRaises(ReportChangedDuringAutostart):
+ self.start_replacement(decision, reservation)
+ assert not SignalReportArtefact.objects.filter(
+ report=self.report, type="implementation_replacement"
+ ).exists()
+ self.github.close_pull_request.assert_not_called()
+
def complete(self, replacement: SignalReportArtefact) -> TaskRun:
content = ImplementationReplacement.model_validate_json(replacement.content)
run = TaskRun.objects.get(id=content.run_id)
@@ -186,6 +228,37 @@ class TestSupersedeHandover(BaseTest):
run.save(update_fields=["status", "output"])
return run
+ @parameterized.expand([("unchanged", False), ("revised_again", True)])
+ def test_scout_replacement_is_bound_to_its_content_revision(self, _name: str, revised_again: bool) -> None:
+ self.report.run_count = 0
+ self.report.implemented_at_run_count = 0
+ self.report.last_run_at = None
+ self.report.save()
+ context = research_implementation_context(self.team.id, str(self.report.id))
+ self.report.content_revision_count = 1
+ self.report.save(update_fields=["content_revision_count"])
+ record_implementation_decision(
+ team_id=self.team.id,
+ report_id=str(self.report.id),
+ supersede=True,
+ updated_fields=["summary"],
+ attribution=ArtefactAttribution.system(),
+ implementation_context=context,
+ )
+ row = SignalReportArtefact.objects.get(report=self.report, type="implementation_decision")
+ decision = ImplementationDecision.model_validate_json(row.content)
+ assert {target.pr_url for target in decision.targets} == {OLD_PR, KEPT_PR}
+ replacement = self.start_replacement(decision)
+ self.report.refresh_from_db()
+ assert self.report.implemented_at_revision_count == 1
+ self.complete(replacement)
+ if revised_again:
+ self.report.content_revision_count = 2
+ self.report.save(update_fields=["content_revision_count"])
+ assert not reconcile_replacement(self.team.id, str(replacement.id))
+ assert self.github.close_pull_request.call_count == (0 if revised_again else 2)
+ assert self.handover(replacement).status == ("needs_attention" if revised_again else "completed")
+
def test_selective_handover_transfers_claim_and_is_idempotent(self) -> None:
replacement = self.start_replacement()
assert self.current_claim().actor_task_id == replacement.task_id
@@ -271,12 +344,16 @@ class TestSupersedeHandover(BaseTest):
SignalReport.objects.filter(id=self.report.id).update(
**({"run_count": 3} if change == "new_pass" else {"status": "suppressed"})
)
- with patch("products.signals.backend.auto_start.tasks_facade.create_and_run_task") as create:
+ with (
+ patch("products.signals.backend.auto_start.tasks_facade.create_and_run_task") as create,
+ self.assertRaises(ReportChangedDuringAutostart) if change == "new_pass" else nullcontext(),
+ ):
assert not _create_implementation_task_if_absent(
team_id=self.team.id,
report_id=str(self.report.id),
title="t",
description="d",
+ expected_content=ImplementationReportContent.from_report(self.report),
user_id=self.user.id,
repository="example/repo",
base_branch=None,
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index d4cde3273ecc..4446d91ba2a7 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -432,6 +432,8 @@ export interface SignalReportListApi {
readonly total_weight: number
readonly signal_count: number
readonly signals_at_run: number
+ /** How many scout notes this report received beyond the few its work log keeps as entries. 0 when nothing was dropped. These say the finding still holds, so the count is shown in place of the entries. */
+ readonly collapsed_note_count: number
readonly created_at: string
readonly updated_at: string
readonly artefact_count: number
@@ -616,6 +618,8 @@ export interface SignalReportApi {
readonly total_weight: number
readonly signal_count: number
readonly signals_at_run: number
+ /** How many scout notes this report received beyond the few its work log keeps as entries. 0 when nothing was dropped. These say the finding still holds, so the count is shown in place of the entries. */
+ readonly collapsed_note_count: number
readonly created_at: string
readonly updated_at: string
readonly artefact_count: number
@@ -2111,6 +2115,7 @@ export interface SignalReportStateRequestApi {
* * `pull_request` - Pull Request
* * `check_result` - Check Result
* * `implementation_decision` - Implementation Decision
+ * * `implementation_dispatch` - Implementation Dispatch
* * `implementation_replacement` - Implementation Replacement
* * `implementation_handover` - Implementation Handover
*/
@@ -2140,6 +2145,7 @@ export const SignalReportArtefactArtefactTypeEnumApi = {
PullRequest: 'pull_request',
CheckResult: 'check_result',
ImplementationDecision: 'implementation_decision',
+ ImplementationDispatch: 'implementation_dispatch',
ImplementationReplacement: 'implementation_replacement',
ImplementationHandover: 'implementation_handover',
} as const
@@ -4490,6 +4496,8 @@ export interface EditReportRequestApi {
* @nullable
*/
append_note?: string | null
+ /** Set only when append_note confirms the finding with no new information. After four confirmations, store only the count. Other notes remain in the work log. */
+ corroboration_only?: boolean
/**
* Optional observations to add to the report's evidence rail, each becoming a bound signal attributed to this scout — adds to the report's evidence rather than replacing it. Use this for a new observation a reader should be able to check, and `append_note` for commentary (the owning team knows, a deploy fixed it). The report's signal count and weight move with the appended rows. Emit plus every append share a cap of 50 signals per report.
* @maxItems 50
@@ -4525,6 +4533,8 @@ export interface EditReportRequestApi {
* @items.maxLength 200
*/
suggested_prompts?: string[] | null
+ /** Set this only when your rewrite changes what the fix should be: a different root cause, a different file or layer, a materially wider or narrower scope. More evidence for the same fix is not a reason, because the report's open pull request already implements it. Setting it true records a replacement decision for a ready report. Policy and eligibility checks gate the replacement. The existing pull request closes only after a successful, verified replacement. Technical failures retry automatically; policy blocks wait for a new edit or research trigger. Only honored alongside a `title` or `summary` that actually changes, and only within the first four content revisions, including revisions that did not request replacement. */
+ supersedes_implementation?: boolean
}
export interface EditReportResponseApi {
@@ -4532,7 +4542,7 @@ export interface EditReportResponseApi {
report_id: string
/** Which presentation fields changed (e.g. `title`, `summary`); empty if only a note was appended. */
updated_fields: string[]
- /** Whether a note artefact was appended. */
+ /** Whether the edit included a note. True for a collapsed corroboration too, where the report's count moves and no work-log entry is written. Read `corroboration_collapsed` to tell the two apart. */
note_appended: boolean
/** How many observations this edit added to the report's evidence rail; 0 if none. */
evidence_appended: number
@@ -4560,6 +4570,14 @@ export interface EditReportResponseApi {
* @nullable
*/
suggested_prompts_set: number | null
+ /** Whether this edit actually rewrote the report's title or summary. False for a note, a reviewer change, or a re-send of the text the report already had. */
+ is_content_revision: boolean
+ /** How many times a scout has rewritten this report's title or summary, counting this edit. */
+ content_revision_count: number
+ /** Whether the edit recorded that the report's pull request should be replaced. False when you did not ask for it, when the edit changed no content, or when the report has already been rewritten too many times. */
+ supersedes_implementation: boolean
+ /** Whether your note raised the report's corroboration count instead of landing as its own entry. Only notes marked corroboration_only can collapse; free-form notes remain in the work log. */
+ corroboration_collapsed: boolean
}
/**
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 97f5874bcb50..2fdae056f7a7 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -795,7 +795,7 @@ export const getSignalsReportArtefactsDestroyUrl = (projectId: string, reportId:
}
/**
- * Delete an artefact, addressed by id. Deleting the latest row of a status type reverts the report's canonical status to the previous version (latest-wins over what remains). `task_run` artefacts are an append-only work log and cannot be deleted. Neither can the types this API cannot write, which the pipeline owns: `check_result`, `code_review`, `implementation_decision`, `implementation_handover`, `implementation_replacement`, `pull_request`, `summary_change`, `task_run`, `title_change`, `video_segment`, `work_claim`, `work_release`.
+ * Delete an artefact, addressed by id. Deleting the latest row of a status type reverts the report's canonical status to the previous version (latest-wins over what remains). `task_run` artefacts are an append-only work log and cannot be deleted. Neither can the types this API cannot write, which the pipeline owns: `check_result`, `code_review`, `implementation_decision`, `implementation_dispatch`, `implementation_handover`, `implementation_replacement`, `pull_request`, `summary_change`, `task_run`, `title_change`, `video_segment`, `work_claim`, `work_release`.
* @summary Delete an artefact
*/
export const signalsReportArtefactsDestroy = async (
@@ -1442,7 +1442,7 @@ export const getSignalsScoutEditReportUrl = (projectId: string, runId: string) =
}
/**
- * Rewrite a report's title/summary, append a note or fresh evidence, set its suggested reviewers, and/or point it at another repository. Can target ANY of the project's inbox reports, not just scout-authored ones — so the edit is attributed to this scout. Reviewers and repository are how you rescue a report that surfaced routed to no one or against the wrong codebase: each replaces what the report holds and re-runs autostart, so a report that was missing a qualifying reviewer or a repository can open a draft PR. The response carries the repository the report holds after the edit, and the call fails when a repository it named did not land. Title/summary edits are best-effort: the pipeline may later re-research them.
+ * Rewrite a report's title/summary, append a note or fresh evidence, set its suggested reviewers, and/or point it at another repository. Can target ANY of the project's inbox reports, not just scout-authored ones — so the edit is attributed to this scout. Reviewers and repository are how you rescue a report that surfaced routed to no one or against the wrong codebase: each replaces what the report holds and re-runs autostart, so a report that was missing a qualifying reviewer or a repository can open a draft PR. The response carries the repository the report holds after the edit, and the call fails when a repository it named did not land. Title/summary edits are best-effort: the pipeline may later re-research them. Set `supersedes_implementation` alongside a rewrite when the fix changed. Verified automated predecessor PRs close only after the replacement completes with verified open PRs.
* @summary Edit an existing report for a run
*/
export const signalsScoutEditReport = async (
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 9dbaca8c152f..843058ba1388 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -1273,7 +1273,7 @@ export const SignalsScoutRecordCheckResultBody = /* @__PURE__ */ zod
.describe('Request body for `scout-check-record-result`: the verdict on one dispatched report check.')
/**
- * Rewrite a report's title/summary, append a note or fresh evidence, set its suggested reviewers, and/or point it at another repository. Can target ANY of the project's inbox reports, not just scout-authored ones — so the edit is attributed to this scout. Reviewers and repository are how you rescue a report that surfaced routed to no one or against the wrong codebase: each replaces what the report holds and re-runs autostart, so a report that was missing a qualifying reviewer or a repository can open a draft PR. The response carries the repository the report holds after the edit, and the call fails when a repository it named did not land. Title/summary edits are best-effort: the pipeline may later re-research them.
+ * Rewrite a report's title/summary, append a note or fresh evidence, set its suggested reviewers, and/or point it at another repository. Can target ANY of the project's inbox reports, not just scout-authored ones — so the edit is attributed to this scout. Reviewers and repository are how you rescue a report that surfaced routed to no one or against the wrong codebase: each replaces what the report holds and re-runs autostart, so a report that was missing a qualifying reviewer or a repository can open a draft PR. The response carries the repository the report holds after the edit, and the call fails when a repository it named did not land. Title/summary edits are best-effort: the pipeline may later re-research them. Set `supersedes_implementation` alongside a rewrite when the fix changed. Verified automated predecessor PRs close only after the replacement completes with verified open PRs.
* @summary Edit an existing report for a run
*/
export const signalsScoutEditReportBodyTitleMax = 300
@@ -1342,6 +1342,12 @@ export const SignalsScoutEditReportBody = /* @__PURE__ */ zod
.max(signalsScoutEditReportBodyAppendNoteMax)
.nullish()
.describe("Optional free-form note to append to the report's work log (attributed to this scout)."),
+ corroboration_only: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Set only when append_note confirms the finding with no new information. After four confirmations, store only the count. Other notes remain in the work log.'
+ ),
append_evidence: zod
.array(
zod
@@ -1561,6 +1567,12 @@ export const SignalsScoutEditReportBody = /* @__PURE__ */ zod
.describe(
"The full set of follow-up prompts (questions or next-step actions) the report should offer above its `Ask AI` box. Replaces the report's prompts rather than adding to them, so send every one you want kept. Omit the field (or send null) to leave them untouched, and send an empty list to take them down, which is what you want once a rewrite has left them pointing at the old report."
),
+ supersedes_implementation: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Set this only when your rewrite changes what the fix should be: a different root cause, a different file or layer, a materially wider or narrower scope. More evidence for the same fix is not a reason, because the report's open pull request already implements it. Setting it true records a replacement decision for a ready report. Policy and eligibility checks gate the replacement. The existing pull request closes only after a successful, verified replacement. Technical failures retry automatically; policy blocks wait for a new edit or research trigger. Only honored alongside a `title` or `summary` that actually changes, and only within the first four content revisions, including revisions that did not request replacement."
+ ),
})
.describe(
"Request body for `edit-report`. Can target ANY of the team's inbox reports, not just scout-authored ones."
diff --git a/products/signals/frontend/inbox/components/detail/ArtefactLogList.stories.tsx b/products/signals/frontend/inbox/components/detail/ArtefactLogList.stories.tsx
index 751cf7c38df5..ddb60ff9b9bb 100644
--- a/products/signals/frontend/inbox/components/detail/ArtefactLogList.stories.tsx
+++ b/products/signals/frontend/inbox/components/detail/ArtefactLogList.stories.tsx
@@ -76,6 +76,22 @@ export default meta
type Story = StoryObj<typeof meta>
export const ReplacementLifecycle: Story = {}
+export const RevisionLimit: Story = {
+ args: {
+ artefacts: [
+ {
+ id: 'capped-decision',
+ type: 'implementation_decision',
+ created_at: '2026-09-14T10:00:00Z',
+ content: {
+ supersede: false,
+ blocked_reason: 'revision_limit',
+ reason: 'The rewrite was saved, but the content revision limit prevents another replacement.',
+ },
+ },
+ ],
+ },
+}
export const Narrow: Story = {
decorators: [
(Story) => (
diff --git a/products/signals/frontend/inbox/components/detail/ArtefactLogList.test.tsx b/products/signals/frontend/inbox/components/detail/ArtefactLogList.test.tsx
index 87fb266c1ddf..7a3fae6e823f 100644
--- a/products/signals/frontend/inbox/components/detail/ArtefactLogList.test.tsx
+++ b/products/signals/frontend/inbox/components/detail/ArtefactLogList.test.tsx
@@ -21,13 +21,16 @@ describe('ArtefactLogList', () => {
})
it.each([
- ['a replacement recommendation', true, 'Replacement recommended'],
- ['a kept PR', false, 'Still the right fix'],
- ])('shows the decision and its reason for %s', (_name, supersede, expectedTag) => {
+ ['a replacement recommendation', true, undefined, 'Replacement recommended'],
+ ['a kept PR', false, undefined, 'Still the right fix'],
+ ['a capped request', false, 'revision_limit', 'Replacement limit reached'],
+ ])('shows the decision and its reason for %s', (_name, supersede, blocked_reason, expectedTag) => {
render(
<ArtefactLogList
reportId="report-1"
- artefacts={[makeArtefact({ supersede, reason: 'The root cause moved to the ingestion path.' })]}
+ artefacts={[
+ makeArtefact({ supersede, blocked_reason, reason: 'The root cause moved to the ingestion path.' }),
+ ]}
/>
)
diff --git a/products/signals/frontend/inbox/components/detail/ArtefactLogList.tsx b/products/signals/frontend/inbox/components/detail/ArtefactLogList.tsx
index ca31f7e867b4..351017a5d7d4 100644
--- a/products/signals/frontend/inbox/components/detail/ArtefactLogList.tsx
+++ b/products/signals/frontend/inbox/components/detail/ArtefactLogList.tsx
@@ -1,4 +1,4 @@
-import { type ComponentType, useState } from 'react'
+import { type ComponentType, Fragment, useState } from 'react'
import {
IconActivity,
@@ -451,13 +451,17 @@ function renderArtefactSummary(artefact: SignalReportArtefact): JSX.Element | nu
) : null
}
case 'implementation_decision': {
- const supersede = (content as ImplementationDecisionContent).supersede
+ const { supersede, blocked_reason } = content as ImplementationDecisionContent
if (typeof supersede !== 'boolean') {
return null
}
return (
<LemonTag size="small" type={supersede ? 'warning' : 'muted'}>
- {supersede ? 'Replacement recommended' : 'Still the right fix'}
+ {blocked_reason === 'revision_limit'
+ ? 'Replacement limit reached'
+ : supersede
+ ? 'Replacement recommended'
+ : 'Still the right fix'}
</LemonTag>
)
}
@@ -680,12 +684,31 @@ function ArtefactRow({
* findings, code references, diffs, commits, task runs, notes, and reviewers. Mirrors desktop
* `ArtefactLogList`. Returns null when there are no artefacts.
*/
+/**
+ * Stands in for the scout notes the work log stopped keeping. Past the first few, a scout's notes
+ * restate that the finding is still there, so the count carries what the entries would have.
+ * Rendered above the newest note, where those entries would otherwise sit.
+ */
+function CollapsedNotesRow({ count }: { count: number }): JSX.Element {
+ return (
+ <div className="relative flex gap-3 pb-4 last:pb-0">
+ <span className="z-10 flex size-5 shrink-0 items-center justify-center rounded-full border bg-surface-primary text-secondary">
+ <IconComment className="size-3" />
+ </span>
+ <div className="min-w-0 flex-1 text-xs text-tertiary">
+ Corroborated {count} more {count === 1 ? 'time' : 'times'} by a scout, with nothing new to add.
+ </div>
+ </div>
+ )
+}
+
export function ArtefactLogList({
reportId,
artefacts,
knownTasks,
knownSignals,
pullRequests,
+ collapsedNoteCount = 0,
}: {
reportId: string
artefacts: SignalReportArtefact[]
@@ -693,6 +716,8 @@ export function ArtefactLogList({
knownTasks?: Map<string, Task>
knownSignals?: Map<string, SignalNode>
pullRequests?: readonly SignalReportPullRequestApi[]
+ /** Scout notes the report received beyond the entries kept below, shown as one line instead. */
+ collapsedNoteCount?: number
}): JSX.Element | null {
if (artefacts.length === 0) {
return null
@@ -702,18 +727,31 @@ export function ArtefactLogList({
if (ordered.length === 0) {
return null
}
+ // The dropped notes came after every note still in the log, and the list runs newest-first, so
+ // they sit above the newest surviving note. With no note left to anchor to they lead the log.
+ const anchorIndex =
+ collapsedNoteCount > 0
+ ? Math.max(
+ 0,
+ ordered.findIndex((a) => a.type === 'note')
+ )
+ : -1
return (
<div className="relative">
<span className="absolute bottom-2.5 left-2.5 top-2.5 w-px bg-border" aria-hidden />
- {ordered.map((artefact) => (
- <ArtefactRow
- key={artefact.id}
- reportId={reportId}
- artefact={artefact}
- knownTasks={knownTasks}
- knownSignals={knownSignals}
- knownPullRequests={knownPullRequests}
- />
+ {ordered.map((artefact, index) => (
+ // Fragment rather than a wrapper element: `ArtefactRow`'s `last:pb-0` resolves
+ // against this container's children, and a wrapper would make every row the last.
+ <Fragment key={artefact.id}>
+ {index === anchorIndex ? <CollapsedNotesRow count={collapsedNoteCount} /> : null}
+ <ArtefactRow
+ reportId={reportId}
+ artefact={artefact}
+ knownTasks={knownTasks}
+ knownSignals={knownSignals}
+ knownPullRequests={knownPullRequests}
+ />
+ </Fragment>
))}
</div>
)
diff --git a/products/signals/frontend/inbox/components/detail/ReportActivitySection.tsx b/products/signals/frontend/inbox/components/detail/ReportActivitySection.tsx
index e699252c8163..2da16b50053a 100644
--- a/products/signals/frontend/inbox/components/detail/ReportActivitySection.tsx
+++ b/products/signals/frontend/inbox/components/detail/ReportActivitySection.tsx
@@ -50,6 +50,7 @@ export function ReportActivitySection({ report }: { report: SignalReport }): JSX
knownTasks={knownTasks}
knownSignals={knownSignals}
pullRequests={report.pull_requests}
+ collapsedNoteCount={report.collapsed_note_count ?? 0}
/>
</DetailSection>
)
diff --git a/products/signals/frontend/inbox/components/detail/artefactTypes.ts b/products/signals/frontend/inbox/components/detail/artefactTypes.ts
index bb7d6e2e2308..872c4efa6d3f 100644
--- a/products/signals/frontend/inbox/components/detail/artefactTypes.ts
+++ b/products/signals/frontend/inbox/components/detail/artefactTypes.ts
@@ -105,6 +105,7 @@ export interface SummaryChangeContent {
export interface ImplementationDecisionContent {
supersede?: boolean
+ blocked_reason?: 'revision_limit' | null
reason?: string
targets?: { pr_url: string }[]
}
@@ -130,8 +131,9 @@ export interface ImplementationHandoverContent {
export function selectVisibleReportActivity(artefacts: SignalReportArtefact[]): SignalReportArtefact[] {
return artefacts.filter(
(artefact) =>
- artefact.type !== 'implementation_handover' ||
- (artefact.content as ImplementationHandoverContent).status !== 'processing'
+ artefact.type !== 'implementation_dispatch' &&
+ (artefact.type !== 'implementation_handover' ||
+ (artefact.content as ImplementationHandoverContent).status !== 'processing')
)
}
diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.ts
index 96f7d60a7787..ab9d49657764 100644
--- a/products/signals/frontend/inbox/types.ts
+++ b/products/signals/frontend/inbox/types.ts
@@ -89,6 +89,8 @@ export interface SignalReport {
suggested_prompts?: string[]
/** Count of signals at the time the latest research run kicked off. */
signals_at_run?: number
+ /** Scout notes the work log dropped because they restate earlier ones. 0 when nothing was dropped. */
+ collapsed_note_count?: number
/** P0–P4 from the priority judgment when the report is researched. */
priority?: SignalReportPriority | null
/** Actionability choice from the actionability judgment artefact. */
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index 45f1f0682b4a..595703511aa6 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -598,7 +598,12 @@ tools:
cached fallback. An affected-users metric uses one series with `math: dau`. Consumers derive a `BoldNumber`
query for each metric's whole-window `aggregated_value` and an `ActionsBar` query for its longitudinal
buckets; never sum affected-user buckets. NOT idempotent - a retried `append_note` appends a second note.
- Opt-in: only available to scouts that list `edit_report` in their skill's `allowed_tools`.
+ Set `supersedes_implementation` alongside a rewrite when the fix itself changed. Verified automated
+ predecessor PRs close only after the replacement completes with verified open PRs. More evidence for the
+ same fix belongs in `append_note`. Free-form notes always stay in the work log. Set `corroboration_only`
+ only for confirmations with no new information; the first four stay as entries and later confirmations raise
+ the corroboration count. Opt-in: only available to scouts that list `edit_report` in their skill's
+ `allowed_tools`.
scout-emit-report:
operation: signals_scout_emit_report
enabled: true
diff --git a/products/signals/skills/authoring-scouts/references/report-contract.md b/products/signals/skills/authoring-scouts/references/report-contract.md
index 54807990d360..dea748d881df 100644
--- a/products/signals/skills/authoring-scouts/references/report-contract.md
+++ b/products/signals/skills/authoring-scouts/references/report-contract.md
@@ -264,6 +264,29 @@ Rules of good behavior:
- **Use `suggested_reviewers` to rescue an unrouted report.** Setting reviewers (same `{github_login?, user_uuid?}` shape as `emit_report`) replaces the report's reviewer list and re-runs autostart — so a report that surfaced routed to no one can be assigned to an owner you resolved later, and a now-actionable report with a repo + priority can open a draft PR.
An empty list is a no-op (it never clears existing reviewers).
+### Replacing the report's pull request
+
+A report that autostarted has an open draft PR built from the summary as it read at the time.
+When your rewrite changes what the fix should be, set `supersedes_implementation: true` alongside the `title` / `summary` you are changing.
+This records a replacement decision for a ready report. Autostart checks policy and eligibility before starting a replacement from your new summary. Technical failures retry automatically; a policy block waits for a new edit or research trigger. The existing PR stays open until the replacement succeeds with a verified open PR.
+
+Set it only when the fix itself changed: a different root cause, a different file or layer, a materially wider or narrower scope.
+More evidence for the same fix is not a reason — the open PR already implements it, and replacing it throws away review someone may already have done.
+An `append_note` is the right move there instead.
+
+Two things bound it, and the response tells you which one applied:
+
+- It is only honored alongside a rewrite that actually changed the title or summary. Restating the text the report already holds is not a revision, and neither is a note or a reviewer change. `is_content_revision` in the response says whether yours counted.
+- Only the first four content revisions can request replacements. `content_revision_count` counts every title or summary rewrite, including ones that did not request replacement. Past four your rewrite still lands, but it cannot request a replacement. `supersedes_implementation` in the response is `true` only when the decision was recorded.
+
+### Re-confirming a report you already filed
+
+Appending a note that says the finding still holds is worth doing, and it is not a revision — it leaves `content_revision_count` alone.
+Free-form `append_note` text always remains in the work log, including recovery details and observations beyond the evidence cap. Set `corroboration_only: true` only for a confirmation with no new information. A report keeps its first four confirmations as separate entries and counts later confirmations; the web and desktop inboxes show the collapsed count.
+The call still succeeds, and `corroboration_collapsed` in the response tells you it happened.
+
+A replacement request that cannot bind verified predecessor PRs, or whose report changes during verification, fails without saving the edit. Retry the same edit to resolve the context again.
+
## Finding "the report I made last time"
There is no scout-specific report search — use the **vanilla inbox tools** the scout already has.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 21a49a9dd693..6a99ed24f013 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -9939,7 +9939,7 @@
}
},
"scout-edit-report": {
- "description": "The report channel's edit half: rewrite a report's `title`/`summary`, append a note, set its `suggested_reviewers`, and/or point it at another `repository`. Can target ANY of the project's inbox reports, not just scout-authored ones — the edit is attributed to this scout. Setting reviewers is how you rescue a report that surfaced routed to no one: it replaces the reviewer list and re-runs autostart, so a report missing a qualifying reviewer can open a draft PR. Each reviewer is a `github_login` and/or a PostHog `user_uuid` (resolved server-side to the linked GitHub login). Optional `repository` is the same rescue for a report routed to the wrong codebase: pass `owner/repo` to replace the report's target in place, rather than authoring a duplicate that carries the right one, or the `NO_REPO` sentinel for a report where nothing under version control could change. It re-runs autostart too, and omitting it leaves the report's target alone. The response carries `repository`, the target the report holds after the edit, read back from the report — check it against what you sent, because the call fails when a correction you named did not land. Prefer `append_note` over rewriting a report you didn't author (additive and audit-friendly); title/summary edits are best-effort, since the pipeline may later re-research and overwrite them. Optional `append_evidence` adds observations to the report's evidence rail, each becoming a bound signal that moves the report's signal count and weight — use it for a new observation a reader should be able to check, and `append_note` for commentary. Optional `charts` is the full set of queries the inbox renders on the report — it replaces the report's charts rather than adding to them (omit it to leave them alone), so read the report first when you mean to add one. Optional `metrics` is the report's complete typed impact-metric set: omit it or send null to preserve the set, send an empty list to clear it, or send the complete replacement. Every submitted metric requires a bounded live InsightVizNode/TrendsQuery built only from EventsNode or ActionsNode sources, with no more than 1,000 estimated longitudinal points; its snapshot is only an optional cached fallback. An affected-users metric uses one series with `math: dau`. Consumers derive a `BoldNumber` query for each metric's whole-window `aggregated_value` and an `ActionsBar` query for its longitudinal buckets; never sum affected-user buckets. NOT idempotent - a retried `append_note` appends a second note. Opt-in: only available to scouts that list `edit_report` in their skill's `allowed_tools`.",
+ "description": "The report channel's edit half: rewrite a report's `title`/`summary`, append a note, set its `suggested_reviewers`, and/or point it at another `repository`. Can target ANY of the project's inbox reports, not just scout-authored ones — the edit is attributed to this scout. Setting reviewers is how you rescue a report that surfaced routed to no one: it replaces the reviewer list and re-runs autostart, so a report missing a qualifying reviewer can open a draft PR. Each reviewer is a `github_login` and/or a PostHog `user_uuid` (resolved server-side to the linked GitHub login). Optional `repository` is the same rescue for a report routed to the wrong codebase: pass `owner/repo` to replace the report's target in place, rather than authoring a duplicate that carries the right one, or the `NO_REPO` sentinel for a report where nothing under version control could change. It re-runs autostart too, and omitting it leaves the report's target alone. The response carries `repository`, the target the report holds after the edit, read back from the report — check it against what you sent, because the call fails when a correction you named did not land. Prefer `append_note` over rewriting a report you didn't author (additive and audit-friendly); title/summary edits are best-effort, since the pipeline may later re-research and overwrite them. Optional `append_evidence` adds observations to the report's evidence rail, each becoming a bound signal that moves the report's signal count and weight — use it for a new observation a reader should be able to check, and `append_note` for commentary. Optional `charts` is the full set of queries the inbox renders on the report — it replaces the report's charts rather than adding to them (omit it to leave them alone), so read the report first when you mean to add one. Optional `metrics` is the report's complete typed impact-metric set: omit it or send null to preserve the set, send an empty list to clear it, or send the complete replacement. Every submitted metric requires a bounded live InsightVizNode/TrendsQuery built only from EventsNode or ActionsNode sources, with no more than 1,000 estimated longitudinal points; its snapshot is only an optional cached fallback. An affected-users metric uses one series with `math: dau`. Consumers derive a `BoldNumber` query for each metric's whole-window `aggregated_value` and an `ActionsBar` query for its longitudinal buckets; never sum affected-user buckets. NOT idempotent - a retried `append_note` appends a second note. Set `supersedes_implementation` alongside a rewrite when the fix itself changed. Verified automated predecessor PRs close only after the replacement completes with verified open PRs. More evidence for the same fix belongs in `append_note`. Free-form notes always stay in the work log. Set `corroboration_only` only for confirmations with no new information; the first four stay as entries and later confirmations raise the corroboration count. Opt-in: only available to scouts that list `edit_report` in their skill's `allowed_tools`.",
"category": "Signals",
"feature": "signals",
"summary": "Edit an existing report for a run",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index d5f56a0e10d9..878b4bc6907a 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -10511,7 +10511,7 @@
}
},
"scout-edit-report": {
- "description": "The report channel's edit half: rewrite a report's `title`/`summary`, append a note, set its `suggested_reviewers`, and/or point it at another `repository`. Can target ANY of the project's inbox reports, not just scout-authored ones — the edit is attributed to this scout. Setting reviewers is how you rescue a report that surfaced routed to no one: it replaces the reviewer list and re-runs autostart, so a report missing a qualifying reviewer can open a draft PR. Each reviewer is a `github_login` and/or a PostHog `user_uuid` (resolved server-side to the linked GitHub login). Optional `repository` is the same rescue for a report routed to the wrong codebase: pass `owner/repo` to replace the report's target in place, rather than authoring a duplicate that carries the right one, or the `NO_REPO` sentinel for a report where nothing under version control could change. It re-runs autostart too, and omitting it leaves the report's target alone. The response carries `repository`, the target the report holds after the edit, read back from the report — check it against what you sent, because the call fails when a correction you named did not land. Prefer `append_note` over rewriting a report you didn't author (additive and audit-friendly); title/summary edits are best-effort, since the pipeline may later re-research and overwrite them. Optional `append_evidence` adds observations to the report's evidence rail, each becoming a bound signal that moves the report's signal count and weight — use it for a new observation a reader should be able to check, and `append_note` for commentary. Optional `charts` is the full set of queries the inbox renders on the report — it replaces the report's charts rather than adding to them (omit it to leave them alone), so read the report first when you mean to add one. Optional `metrics` is the report's complete typed impact-metric set: omit it or send null to preserve the set, send an empty list to clear it, or send the complete replacement. Every submitted metric requires a bounded live InsightVizNode/TrendsQuery built only from EventsNode or ActionsNode sources, with no more than 1,000 estimated longitudinal points; its snapshot is only an optional cached fallback. An affected-users metric uses one series with `math: dau`. Consumers derive a `BoldNumber` query for each metric's whole-window `aggregated_value` and an `ActionsBar` query for its longitudinal buckets; never sum affected-user buckets. NOT idempotent - a retried `append_note` appends a second note. Opt-in: only available to scouts that list `edit_report` in their skill's `allowed_tools`.",
+ "description": "The report channel's edit half: rewrite a report's `title`/`summary`, append a note, set its `suggested_reviewers`, and/or point it at another `repository`. Can target ANY of the project's inbox reports, not just scout-authored ones — the edit is attributed to this scout. Setting reviewers is how you rescue a report that surfaced routed to no one: it replaces the reviewer list and re-runs autostart, so a report missing a qualifying reviewer can open a draft PR. Each reviewer is a `github_login` and/or a PostHog `user_uuid` (resolved server-side to the linked GitHub login). Optional `repository` is the same rescue for a report routed to the wrong codebase: pass `owner/repo` to replace the report's target in place, rather than authoring a duplicate that carries the right one, or the `NO_REPO` sentinel for a report where nothing under version control could change. It re-runs autostart too, and omitting it leaves the report's target alone. The response carries `repository`, the target the report holds after the edit, read back from the report — check it against what you sent, because the call fails when a correction you named did not land. Prefer `append_note` over rewriting a report you didn't author (additive and audit-friendly); title/summary edits are best-effort, since the pipeline may later re-research and overwrite them. Optional `append_evidence` adds observations to the report's evidence rail, each becoming a bound signal that moves the report's signal count and weight — use it for a new observation a reader should be able to check, and `append_note` for commentary. Optional `charts` is the full set of queries the inbox renders on the report — it replaces the report's charts rather than adding to them (omit it to leave them alone), so read the report first when you mean to add one. Optional `metrics` is the report's complete typed impact-metric set: omit it or send null to preserve the set, send an empty list to clear it, or send the complete replacement. Every submitted metric requires a bounded live InsightVizNode/TrendsQuery built only from EventsNode or ActionsNode sources, with no more than 1,000 estimated longitudinal points; its snapshot is only an optional cached fallback. An affected-users metric uses one series with `math: dau`. Consumers derive a `BoldNumber` query for each metric's whole-window `aggregated_value` and an `ActionsBar` query for its longitudinal buckets; never sum affected-user buckets. NOT idempotent - a retried `append_note` appends a second note. Set `supersedes_implementation` alongside a rewrite when the fix itself changed. Verified automated predecessor PRs close only after the replacement completes with verified open PRs. More evidence for the same fix belongs in `append_note`. Free-form notes always stay in the work log. Set `corroboration_only` only for confirmations with no new information; the first four stay as entries and later confirmations raise the corroboration count. Opt-in: only available to scouts that list `edit_report` in their skill's `allowed_tools`.",
"category": "Signals",
"feature": "signals",
"summary": "Edit an existing report for a run",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1f904f1d5752..3030f645c9c8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -32368,6 +32368,8 @@ export namespace Schemas {
* @nullable
*/
append_note?: string | null;
+ /** Set only when append_note confirms the finding with no new information. After four confirmations, store only the count. Other notes remain in the work log. */
+ corroboration_only?: boolean;
/**
* Optional observations to add to the report's evidence rail, each becoming a bound signal attributed to this scout — adds to the report's evidence rather than replacing it. Use this for a new observation a reader should be able to check, and `append_note` for commentary (the owning team knows, a deploy fixed it). The report's signal count and weight move with the appended rows. Emit plus every append share a cap of 50 signals per report.
* @maxItems 50
@@ -32403,6 +32405,8 @@ export namespace Schemas {
* @items.maxLength 200
*/
suggested_prompts?: string[] | null;
+ /** Set this only when your rewrite changes what the fix should be: a different root cause, a different file or layer, a materially wider or narrower scope. More evidence for the same fix is not a reason, because the report's open pull request already implements it. Setting it true records a replacement decision for a ready report. Policy and eligibility checks gate the replacement. The existing pull request closes only after a successful, verified replacement. Technical failures retry automatically; policy blocks wait for a new edit or research trigger. Only honored alongside a `title` or `summary` that actually changes, and only within the first four content revisions, including revisions that did not request replacement. */
+ supersedes_implementation?: boolean;
}
export interface EditReportResponse {
@@ -32410,7 +32414,7 @@ export namespace Schemas {
report_id: string;
/** Which presentation fields changed (e.g. `title`, `summary`); empty if only a note was appended. */
updated_fields: string[];
- /** Whether a note artefact was appended. */
+ /** Whether the edit included a note. True for a collapsed corroboration too, where the report's count moves and no work-log entry is written. Read `corroboration_collapsed` to tell the two apart. */
note_appended: boolean;
/** How many observations this edit added to the report's evidence rail; 0 if none. */
evidence_appended: number;
@@ -32438,6 +32442,14 @@ export namespace Schemas {
* @nullable
*/
suggested_prompts_set: number | null;
+ /** Whether this edit actually rewrote the report's title or summary. False for a note, a reviewer change, or a re-send of the text the report already had. */
+ is_content_revision: boolean;
+ /** How many times a scout has rewritten this report's title or summary, counting this edit. */
+ content_revision_count: number;
+ /** Whether the edit recorded that the report's pull request should be replaced. False when you did not ask for it, when the edit changed no content, or when the report has already been rewritten too many times. */
+ supersedes_implementation: boolean;
+ /** Whether your note raised the report's corroboration count instead of landing as its own entry. Only notes marked corroboration_only can collapse; free-form notes remain in the work log. */
+ corroboration_collapsed: boolean;
}
/**
@@ -60998,6 +61010,7 @@ export namespace Schemas {
* * `pull_request` - Pull Request
* * `check_result` - Check Result
* * `implementation_decision` - Implementation Decision
+ * * `implementation_dispatch` - Implementation Dispatch
* * `implementation_replacement` - Implementation Replacement
* * `implementation_handover` - Implementation Handover
*/
@@ -61027,6 +61040,7 @@ export namespace Schemas {
PullRequest: 'pull_request',
CheckResult: 'check_result',
ImplementationDecision: 'implementation_decision',
+ ImplementationDispatch: 'implementation_dispatch',
ImplementationReplacement: 'implementation_replacement',
ImplementationHandover: 'implementation_handover',
} as const;
@@ -61484,6 +61498,8 @@ export namespace Schemas {
readonly total_weight: number;
readonly signal_count: number;
readonly signals_at_run: number;
+ /** How many scout notes this report received beyond the few its work log keeps as entries. 0 when nothing was dropped. These say the finding still holds, so the count is shown in place of the entries. */
+ readonly collapsed_note_count: number;
readonly created_at: string;
readonly updated_at: string;
readonly artefact_count: number;
@@ -80192,6 +80208,8 @@ export namespace Schemas {
readonly total_weight: number;
readonly signal_count: number;
readonly signals_at_run: number;
+ /** How many scout notes this report received beyond the few its work log keeps as entries. 0 when nothing was dropped. These say the finding still holds, so the count is shown in place of the entries. */
+ readonly collapsed_note_count: number;
readonly created_at: string;
readonly updated_at: string;
readonly artefact_count: number;
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 3506ff9f6244..d5d307c447d4 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -435,7 +435,7 @@ export const SignalsReportArtefactsPartialUpdateBody = () => zod
)
/**
- * Delete an artefact, addressed by id. Deleting the latest row of a status type reverts the report's canonical status to the previous version (latest-wins over what remains). `task_run` artefacts are an append-only work log and cannot be deleted. Neither can the types this API cannot write, which the pipeline owns: `check_result`, `code_review`, `implementation_decision`, `implementation_handover`, `implementation_replacement`, `pull_request`, `summary_change`, `task_run`, `title_change`, `video_segment`, `work_claim`, `work_release`.
+ * Delete an artefact, addressed by id. Deleting the latest row of a status type reverts the report's canonical status to the previous version (latest-wins over what remains). `task_run` artefacts are an append-only work log and cannot be deleted. Neither can the types this API cannot write, which the pipeline owns: `check_result`, `code_review`, `implementation_decision`, `implementation_dispatch`, `implementation_handover`, `implementation_replacement`, `pull_request`, `summary_change`, `task_run`, `title_change`, `video_segment`, `work_claim`, `work_release`.
* @summary Delete an artefact
*/
export const SignalsReportArtefactsDestroyParams = () => zod.object({
@@ -1554,7 +1554,7 @@ export const SignalsScoutRecordCheckResultBody = () => zod
.describe('Request body for `scout-check-record-result`: the verdict on one dispatched report check.')
/**
- * Rewrite a report's title/summary, append a note or fresh evidence, set its suggested reviewers, and/or point it at another repository. Can target ANY of the project's inbox reports, not just scout-authored ones — so the edit is attributed to this scout. Reviewers and repository are how you rescue a report that surfaced routed to no one or against the wrong codebase: each replaces what the report holds and re-runs autostart, so a report that was missing a qualifying reviewer or a repository can open a draft PR. The response carries the repository the report holds after the edit, and the call fails when a repository it named did not land. Title/summary edits are best-effort: the pipeline may later re-research them.
+ * Rewrite a report's title/summary, append a note or fresh evidence, set its suggested reviewers, and/or point it at another repository. Can target ANY of the project's inbox reports, not just scout-authored ones — so the edit is attributed to this scout. Reviewers and repository are how you rescue a report that surfaced routed to no one or against the wrong codebase: each replaces what the report holds and re-runs autostart, so a report that was missing a qualifying reviewer or a repository can open a draft PR. The response carries the repository the report holds after the edit, and the call fails when a repository it named did not land. Title/summary edits are best-effort: the pipeline may later re-research them. Set `supersedes_implementation` alongside a rewrite when the fix changed. Verified automated predecessor PRs close only after the replacement completes with verified open PRs.
* @summary Edit an existing report for a run
*/
export const SignalsScoutEditReportParams = () => zod.object({
@@ -1632,6 +1632,12 @@ export const SignalsScoutEditReportBody = () => zod
.max(signalsScoutEditReportBodyAppendNoteMax)
.nullish()
.describe("Optional free-form note to append to the report's work log (attributed to this scout)."),
+ corroboration_only: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Set only when append_note confirms the finding with no new information. After four confirmations, store only the count. Other notes remain in the work log.'
+ ),
append_evidence: zod
.array(
zod
@@ -1851,6 +1857,12 @@ export const SignalsScoutEditReportBody = () => zod
.describe(
"The full set of follow-up prompts (questions or next-step actions) the report should offer above its `Ask AI` box. Replaces the report's prompts rather than adding to them, so send every one you want kept. Omit the field (or send null) to leave them untouched, and send an empty list to take them down, which is what you want once a rewrite has left them pointing at the old report."
),
+ supersedes_implementation: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Set this only when your rewrite changes what the fix should be: a different root cause, a different file or layer, a materially wider or narrower scope. More evidence for the same fix is not a reason, because the report's open pull request already implements it. Setting it true records a replacement decision for a ready report. Policy and eligibility checks gate the replacement. The existing pull request closes only after a successful, verified replacement. Technical failures retry automatically; policy blocks wait for a new edit or research trigger. Only honored alongside a `title` or `summary` that actually changes, and only within the first four content revisions, including revisions that did not request replacement."
+ ),
})
.describe(
"Request body for `edit-report`. Can target ANY of the team's inbox reports, not just scout-authored ones."
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 535b6bc68753..e4fbd8da100d 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -886,6 +886,9 @@ const scoutEditReport = (): ToolBase<ReturnType<typeof ScoutEditReportSchema>, S
if (params.append_note !== undefined) {
body['append_note'] = params.append_note
}
+ if (params.corroboration_only !== undefined) {
+ body['corroboration_only'] = params.corroboration_only
+ }
if (params.append_evidence !== undefined) {
body['append_evidence'] = params.append_evidence
}
@@ -904,6 +907,9 @@ const scoutEditReport = (): ToolBase<ReturnType<typeof ScoutEditReportSchema>, S
if (params.suggested_prompts !== undefined) {
body['suggested_prompts'] = params.suggested_prompts
}
+ if (params.supersedes_implementation !== undefined) {
+ body['supersedes_implementation'] = params.supersedes_implementation
+ }
const result = await context.api.request<Schemas.EditReportResponse>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/runs/${encodeURIComponent(String(params.run_id))}/edit-report/`,
@@ -1687,6 +1693,9 @@ const signalsScoutEditReport = (): ToolBase<
if (params.append_note !== undefined) {
body['append_note'] = params.append_note
}
+ if (params.corroboration_only !== undefined) {
+ body['corroboration_only'] = params.corroboration_only
+ }
if (params.append_evidence !== undefined) {
body['append_evidence'] = params.append_evidence
}
@@ -1705,6 +1714,9 @@ const signalsScoutEditReport = (): ToolBase<
if (params.suggested_prompts !== undefined) {
body['suggested_prompts'] = params.suggested_prompts
}
+ if (params.supersedes_implementation !== undefined) {
+ body['supersedes_implementation'] = params.supersedes_implementation
+ }
const result = await context.api.request<Schemas.EditReportResponse>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/runs/${encodeURIComponent(String(params.run_id))}/edit-report/`,
diff --git a/services/mcp/tests/unit/signals-edit-handler.test.ts b/services/mcp/tests/unit/signals-edit-handler.test.ts
new file mode 100644
index 000000000000..56e612b69087
--- /dev/null
+++ b/services/mcp/tests/unit/signals-edit-handler.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { GENERATED_TOOLS } from '@/tools/generated/signals'
+import type { Context } from '@/tools/types'
+
+describe('signals-scout-edit-report handler', () => {
+ it.each([
+ {},
+ { corroboration_only: false, supersedes_implementation: false },
+ { corroboration_only: true, supersedes_implementation: true },
+ ])('preserves explicitly supplied flags without inserting omitted flags: %j', async (flags) => {
+ const request = vi.fn().mockResolvedValue({ report_id: 'report-1' })
+ const context = {
+ api: { request, getProjectBaseUrl: vi.fn().mockReturnValue('https://us.posthog.com/project/42') },
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('42') },
+ } as unknown as Context
+ const tool = GENERATED_TOOLS['signals-scout-edit-report']!()
+ const input = { run_id: 'run-1', report_id: 'report-1', append_note: 'Checked again', ...flags }
+ await tool.handler(context, tool.schema.parse(input))
+ expect(request.mock.calls[0]![0].body).toEqual({
+ report_id: 'report-1',
+ append_note: 'Checked again',
+ ...flags,
+ })
+ })
+})