: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): link scout reports to their source github issues (#129914)
posthog[bot]3dcdcc640fd9
diff --git a/docs/internal/signals-github-writeback.md b/docs/internal/signals-github-writeback.mdindex 0148b145fe30..af22e4c8e0e7 100644--- a/docs/internal/signals-github-writeback.md+++ b/docs/internal/signals-github-writeback.md@@ -10,6 +10,16 @@ The activity has a five-minute timeout and uses the BATCH request priority.It runs on later report settles too, so an issue added after the first notification can receive a comment.The worker checks the current GitHub issue state before posting and skips closed issues, locked issues, and pull requests.+A report learns its issues two ways: from GitHub issue signals, and from `source_issue` artefacts.+A scout or person writes a `source_issue` with the `source_issues` field of `scout-emit-report` or `scout-edit-report`.+These reports skip research, so the notification workflow never runs for them.+Instead, the write queues the `post_source_issue_links` Celery task after commit when the report is `ready`.+A source issue gets a comment only after the project's GitHub source ingests that issue as a signal.+Anyone who files a report can name any issue URL, so this check keeps the comment on issues the pipeline picked up.+When the issue's signal later joins the report by exact match, grouping queues the same task again.+An edit queues it only when it adds an issue the report did not name yet.+The task has no retry. A pending claim on a scout report recovers on the next edit that adds an issue, or when a GitHub issue signal joins the report and research settles it.+One `SignalReportGithubComment` row claims each report and issue.`commented_at` records a confirmed comment. A pending claim has a null value.The worker keeps pending claims after network failures because GitHub can accept a comment before the response is lost.diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex 90204636c896..7ed6d38779b8 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -624,6 +624,8 @@ Notes:- `SignalReportGithubComment` holds one claim per report and issue, with a lowercase repository name. Completed claims prevent repeat comments. Pending claims expire after ten minutes.- A later settle checks existing comments for a stable marker before it retries an expired claim. An incomplete comment read leaves the claim pending. GitHub provides no atomic comment idempotency key, so this is best-effort recovery.- The worker checks the current issue state immediately before posting. Closed issues, locked issues, and pull requests receive no comment.+- A report's `source_issue` artefacts count as source issues too. Scout and user-authored reports skip research, so their writeback runs from a Celery task queued after the write commits (`source_issues.py`). A source issue gets a comment only after the team's GitHub source ingests that issue; grouping queues the writeback again when the issue's signal joins the report.+- Grouping attaches a GitHub issue signal to the oldest open report whose `source_issue` names the same issue, before similarity matching and without the specificity check. Resolved, suppressed, failed, closed, and deleted reports do not take it.- See [GitHub issue comments](../../docs/internal/signals-github-writeback.md) for recovery limits and diagnostic logs.### `SignalUserAutonomyConfig`diff --git a/products/signals/backend/artefact_schemas.py b/products/signals/backend/artefact_schemas.pyindex b1690c358149..734893b6ee01 100644--- a/products/signals/backend/artefact_schemas.py+++ b/products/signals/backend/artefact_schemas.py@@ -962,6 +962,44 @@ class ReportLink(BaseModel):raise ValueError("must be a UUID")+# One report is about a handful of issues at most. The cap bounds the writeback each write can start.+MAX_SOURCE_ISSUES_PER_WRITE = 5+++class SourceIssue(BaseModel):+ """Content schema for a `source_issue` artefact: an issue in an external tracker that this+ report is about, one row per issue.++ A scout that files a report about a GitHub issue records it here, so the GitHub writeback can+ comment on the issue and grouping can attach the issue's own signal to this report instead of+ opening a second one. `url` is normalized from (`repository`, `number`), so an exact match on it+ finds every report about one issue. GitHub is the only provider today; the field leaves room for+ others.+ """++ provider: Literal["github"] = Field(default="github", description="Tracker the issue lives in.")+ repository: str = Field(description="`owner/repo` of the issue, lowercased.")+ number: int = Field(gt=0, description="Issue number in the repository.")+ url: str = Field(description="Normalized issue URL, `https://github.com/<owner>/<repo>/issues/<number>`.")++ # GitHub compares repository paths without case, so one spelling keeps one issue one row.+ @field_validator("repository")+ @classmethod+ def repository_is_lowercase(cls, v: str) -> str:+ return v.lower()++ @model_validator(mode="after")+ def url_must_be_normalized(self) -> SourceIssue:+ if self.url != f"https://github.com/{self.repository}/issues/{self.number}":+ raise ValueError("url must be the normalized URL of `repository` and `number`")+ return self++ @classmethod+ def github(cls, repository: str, number: int) -> SourceIssue:+ repository = repository.lower()+ return cls(repository=repository, number=number, url=f"https://github.com/{repository}/issues/{number}")++MAX_AUTOSTART_SKIP_DETAIL_LENGTH = 500@@ -1344,6 +1382,7 @@ LogArtefactContent = (| CodeReview| RelatedTo| ReportLink+ | SourceIssue| AutostartSkip| WorkClaim| WorkRelease@@ -1385,6 +1424,7 @@ ARTEFACT_CONTENT_SCHEMAS: Mapping[str, type[BaseModel]] = {"code_review": CodeReview,"related_to": RelatedTo,"report_link": ReportLink,+ "source_issue": SourceIssue,"autostart_skip": AutostartSkip,"work_claim": WorkClaim,"work_release": WorkRelease,@@ -1425,6 +1465,9 @@ _ARTEFACT_TYPE_BY_MODEL: Mapping[type[BaseModel], str] = {model: t for t, model# may write them; API writes would let callers fabricate automation provenance or completion.# `ranking_score` is model output: the scoring sweep is its only writer, so accepting it through# the API would let a caller fabricate a probability the model never produced.+# `source_issue` is written by the report authoring tools, which validate the URL and start the+# writeback that comments on the issue. A row written here would route another issue's signals+# into this report without either.NON_WRITABLE_ARTEFACT_TYPES: frozenset[str] = frozenset({"reviewer_corrections",@@ -1445,6 +1488,7 @@ NON_WRITABLE_ARTEFACT_TYPES: frozenset[str] = frozenset("check_expired","check_cancelled","report_link",+ "source_issue","autostart_skip","implementation_decision","implementation_dispatch",diff --git a/products/signals/backend/github_writeback.py b/products/signals/backend/github_writeback.pyindex 3dbfd094c7ec..4747ad60a849 100644--- a/products/signals/backend/github_writeback.py+++ b/products/signals/backend/github_writeback.py@@ -5,24 +5,39 @@ result lands in the inbox only. Nobody watching the issue hears anything, so a moutside contributor can start on work we already research. This comments a link to the report backon the issue, which closes that loop. Opt-in per team, because the comment is public on the issuethread.++A scout that files a report about an issue records it as a `source_issue` artefact instead of a+signal, so the writeback reads both (see `source_issues.py`). Anyone who files a report can name any+URL, so a source issue gets a comment only once the team's GitHub source has ingested that issue as a+signal. That keeps the comment on the issues the pipeline actually picked up."""from __future__ import annotations+from collections.abc import Collection, Sequencefrom datetime import timedeltafrom django.utils import timezoneimport structlog+from posthog.hogql import ast+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.client.connection import ClickHouseUser+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.clickhouse.workload import Workloadfrom posthog.egress.limiter.policies import Priorityfrom posthog.models import Teamfrom posthog.models.github_integration_base import GitHubIntegrationBase, PullRequestReffrom posthog.models.integration import GitHubIntegration+from products.signals.backend.artefact_schemas import SourceIssuefrom products.signals.backend.enums import SignalSourceProduct, SignalSourceTypefrom products.signals.backend.models import SignalReport, SignalReportGithubComment, SignalTeamConfigfrom products.signals.backend.report_urls import ReportLinkSource, build_report_url+from products.signals.backend.signal_metadata import EMBEDDING_MODEL, _deduped_signals_subquery, _signals_query_context+from products.signals.backend.source_issues import source_issues_by_reportlogger = structlog.get_logger(__name__)@@ -44,11 +59,43 @@ def _comment_body(report_url: str, marker: str) -> str:)-def _issue_refs(signals: list[dict]) -> list[PullRequestRef]:- """The open GitHub issues among a report's signals, each one once.+def _ingested_issue_urls(team: Team, urls: Collection[str]) -> set[str]:+ """The issue URLs, of those given, that the team's GitHub source has ingested as a signal."""+ if not urls:+ return set()+ issue_filter = (+ "JSONExtractString(metadata, 'source_product') = 'github' "+ "AND JSONExtractString(metadata, 'source_type') = 'issue' "+ "AND lower(JSONExtractString(metadata, 'extra', 'html_url')) IN {urls}"+ )+ query = f"""+ SELECT DISTINCT lower(JSONExtractString(metadata, 'extra', 'html_url'))+ FROM ({_deduped_signals_subquery(include_content=False, candidate_document_filter=issue_filter)})+ WHERE NOT JSONExtractBool(metadata, 'deleted')+ AND {issue_filter}+ """+ tag_queries(product=Product.SIGNALS, feature=Feature.QUERY)+ result = execute_hogql_query(+ ch_user=ClickHouseUser.SIGNALS,+ workload=Workload.OFFLINE,+ query_type="SignalsGithubWritebackIngestedIssues",+ query=query,+ team=team,+ placeholders={+ "model_name": ast.Constant(value=EMBEDDING_MODEL.value),+ "urls": ast.Tuple(exprs=[ast.Constant(value=url) for url in urls]),+ },+ context=_signals_query_context(team),+ )+ return {str(row[0]) for row in result.results or []}+++def _issue_refs(signals: list[dict], source_issues: Sequence[SourceIssue] = ()) -> list[PullRequestRef]:+ """The open GitHub issues among a report's signals and its recorded source issues, each one once.A closed issue is answered already, and a locked one refuses comments, so neither is worth a- call.+ call. A source issue carries no state of its own, so `_post_to_issue` reads it from GitHub+ before it comments."""refs: dict[tuple[str, int], PullRequestRef] = {}for signal in signals:@@ -63,6 +110,9 @@ def _issue_refs(signals: list[dict]) -> list[PullRequestRef]:ref = GitHubIntegrationBase.parse_issue_url(str(extra.get("html_url") or ""))if ref is not None:refs.setdefault((ref.repository.lower(), ref.number), ref)+ for issue in source_issues:+ owner, repo = issue.repository.split("/", 1)+ refs.setdefault((issue.repository, issue.number), PullRequestRef(owner=owner, repo=repo, number=issue.number))return list(refs.values())@@ -187,7 +237,8 @@ def _post_to_issue(def post_report_link_to_github_issues(team: Team, report_id: str, signals: list[dict]) -> int:- """Comment a link to a ready report on each GitHub issue that contributed to it.+ """Comment a link to a ready report on each GitHub issue that contributed to it, or that the+ report names as a `source_issue`.Returns the number of comments posted. Best-effort: a failure here must not fail the report'snotification flow, so per-issue errors are logged rather than raised.@@ -195,7 +246,11 @@ def post_report_link_to_github_issues(team: Team, report_id: str, signals: list[if not SignalTeamConfig.objects.filter(team_id=team.pk, github_issue_writeback_enabled=True).exists():return 0- refs = _issue_refs(signals)+ source_issues = source_issues_by_report(team_id=team.pk, report_ids=[report_id]).get(report_id, [])+ if source_issues:+ ingested = _ingested_issue_urls(team, {issue.url for issue in source_issues})+ source_issues = [issue for issue in source_issues if issue.url in ingested]+ refs = _issue_refs(signals, source_issues)if not refs:return 0diff --git a/products/signals/backend/github_writeback_tasks.py b/products/signals/backend/github_writeback_tasks.pynew file mode 100644index 000000000000..3c7e57e44673--- /dev/null+++ b/products/signals/backend/github_writeback_tasks.py@@ -0,0 +1,22 @@+from celery import shared_task++from posthog.models import Team+from posthog.models.scoping import with_team_scope++from products.signals.backend.github_writeback import post_report_link_to_github_issues+++@shared_task(ignore_result=True, soft_time_limit=240, time_limit=300)+@with_team_scope()+def post_source_issue_links(team_id: int, report_id: str, signals: list[dict] | None = None) -> None:+ """Comment a link to a scout-authored report on the GitHub issues it names as its source.++ `signals` carries a GitHub issue signal that just joined the report by exact match, which+ ClickHouse may not show yet. No retry: the writeback swallows per-issue failures, and a later+ edit or a GitHub signal joining the report settles again through the same per-issue claim,+ which never posts twice.+ """+ team = Team.objects.filter(id=team_id).first()+ if team is None:+ return+ post_report_link_to_github_issues(team, report_id, signals=signals or [])diff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex b0f1ce6a5869..c05dbb3ba25c 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -1498,6 +1498,7 @@ class SignalReportArtefact(UUIDModel):CODE_REVIEW = "code_review"RELATED_TO = "related_to"REPORT_LINK = "report_link"+ SOURCE_ISSUE = "source_issue"AUTOSTART_SKIP = "autostart_skip"WORK_CLAIM = "work_claim"WORK_RELEASE = "work_release"@@ -1572,6 +1573,7 @@ class SignalReportArtefact(UUIDModel):ArtefactType.CODE_REVIEW,ArtefactType.RELATED_TO,ArtefactType.REPORT_LINK,+ ArtefactType.SOURCE_ISSUE,ArtefactType.AUTOSTART_SKIP,ArtefactType.IMPLEMENTATION_REPLACEMENT,ArtefactType.IMPLEMENTATION_HANDOVER,diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex 6d47171aceda..dd6687d46c82 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -226,6 +226,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e- A project member can author through the same channel. `tools/report_author.py` holds two `ReportAuthor` implementations: `ScoutRunReportAuthor` and `UserReportAuthor`, which backs `POST /signals/reports/` (`inbox-reports-create`, behind the `inbox-reports-create-mcp` flag). The user author has its own idempotency scope (`user:<id>`), checks AI-processing consent and a per-user daily cap (`USER_REPORT_DAILY_LIMIT`, returned as 429) in `preflight_skip_reason`, so a replay returns before the cap and the cap stops a call before the judge. The report is stored `user_authored`, and `auto_start.maybe_autostart_from_report_artefacts` blocks it on every evaluation, because the endpoint needs only `inbox:write`. Its backing signals carry the `user_authored` source product instead of `signals_scout`.- A report's routing is correctable in place. `edit_report` takes `suggested_reviewers` and `repository`, each replacing what the report holds and re-running autostart, so a report that surfaced routed to no one, or against the wrong codebase, is fixed rather than re-filed as a duplicate. `repository` takes the same `owner/repo` / `NO_REPO` input `emit_report` does (`_normalize_repository`), and the selection it writes is `autostart_eligible` because a scout naming a repository is a decision, not the reading of the prose that `_refresh_inferred_repository` may overturn. Omitting the field leaves the report's target alone, and a repository-only edit changes Inbox routing without queueing another Slack report delivery. The result's `repository` is the target the report holds once the edit settles, read back from the stored selection rather than echoed from the input, and a requested target the report did not take fails the call — `repository_set` alone reports only this process's intent, which a dropped field or a later write can outlive.- A report's work decision is correctable in place too. `edit_report` takes `actionability` + `actionability_explanation` (+ `already_addressed`) as one unit, and `priority` + `priority_explanation`. Each replaces the `actionability_judgment` / `priority_judgment` status artefact that autostart reads (`set_scout_report_decision`), logs an attributed work-log note, and re-runs autostart after the commit, so a promoted report can open a draft PR and a demoted or already-addressed one stops autostart from opening one. The report's inbox status does not move, because an edit must never take down a report someone else authored. A re-send of the stored decision is a no-op. The explanations pass the edit safety judge, since autostart copies the priority explanation into the implementation task. A decision-only edit changes Inbox routing without queueing another Slack report delivery.+- A report can name the GitHub issues it is about. `emit_report` and `edit_report` take `source_issues` (GitHub issue URLs only, at most five per call), stored as one `source_issue` artefact per issue (`../source_issues.py`). The edit is additive and skips an issue the report already names. A READY report queues the GitHub writeback after commit, which comments only on an issue the team's GitHub source has ingested, and grouping attaches that issue's own signal to the report instead of opening a second one. A private trial rejects the field, since the writeback comment is public.- An `edit_report` result carries `warnings`: one entry per request field the edit did not apply, with the reason, while the rest of the edit landed. `supersedes_implementation` uses it today.- Report metrics are typed report content with a maximum of six entries. `metrics` on `emit_report` is the initial whole set. On `edit_report`, omit it or send null to preserve the current set, send `[]` to clear it, or send a list to replace it. A metrics-only edit changes Inbox content and does not queue another Slack report delivery.Every metric requires a bounded live `InsightVizNode`/`TrendsQuery` built only from `EventsNode` or `ActionsNode` sources. It rejects breakdown and compare mode and produces exactly one output series. An `affected_users` metric uses exactly one series with `math: dau`. An `affected_sessions` metric uses exactly one series with `math: unique_session`. Neither kind uses formulas or group math. Consumers derive `BoldNumber` for the whole-window value and `ActionsBar` for longitudinal buckets. List and detail responses omit legacy authored comparisons.diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 6a26d29c59ef..f8236c36834d 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -38,6 +38,7 @@ from products.signals.backend.activity_summary.search import MAX_MEMBER_ACTIVITYfrom products.signals.backend.artefact_schemas import (MAX_REPORT_LINK_REASON_LENGTH,MAX_REPORT_LINKS_PER_WRITE,+ MAX_SOURCE_ISSUES_PER_WRITE,ActionabilityChoice,Priority,)@@ -124,6 +125,7 @@ from products.signals.backend.serializers import (ReviewerProposalSerializer,SignalReportCheckWriteSerializer,)+from products.signals.backend.source_issues import parse_source_issue_urlfrom products.skills.backend.api.skill_serializers import (MAX_SKILL_FILE_COUNT,SPEC_DESCRIPTION_MAX_LENGTH,@@ -1584,6 +1586,35 @@ _REPORT_METRICS_WRITE_HELP = ()+class SourceIssueWriteSerializer(serializers.Serializer):+ """One external issue the report is about."""++ url = serializers.CharField(+ max_length=500,+ help_text=(+ "The issue's URL, `https://github.com/<owner>/<repo>/issues/<number>`. Only GitHub issues are "+ "accepted today. Pull request URLs are rejected."+ ),+ )++ def validate_url(self, value: str) -> str:+ if parse_source_issue_url(value) is None:+ raise serializers.ValidationError(+ "Not a GitHub issue URL. Use https://github.com/<owner>/<repo>/issues/<number>."+ )+ return value+++_SOURCE_ISSUES_HELP = (+ "The GitHub issues this report is about, when the finding came from an issue tracker. Pass the "+ "issue whenever the report is about one, so the report links back to it: a GitHub issue signal "+ "for the same issue then joins this report instead of opening a second one. When the project "+ "turned on GitHub issue comments, the issue gets one comment that links the report once its "+ "GitHub source ingests the issue. At most "+ f"{MAX_SOURCE_ISSUES_PER_WRITE} per call."+)++class EmitReportRequestSerializer(serializers.Serializer):"""Request body for the scout `emit-report` action and the inbox report `create` action. A scout run istaken from the URL path; a person is the authenticated caller."""@@ -1709,6 +1740,12 @@ class EmitReportRequestSerializer(serializers.Serializer):"every report must be in this project."),)+ source_issues = serializers.ListField(+ required=False,+ child=SourceIssueWriteSerializer(),+ max_length=MAX_SOURCE_ISSUES_PER_WRITE,+ help_text=_SOURCE_ISSUES_HELP,+ )tags = serializers.ListField(required=False,child=serializers.CharField(),@@ -1924,6 +1961,15 @@ class EditReportRequestSerializer(ReviewerProposalSerializer):"Links of the same kind must stay acyclic and every report must be in this project."),)+ source_issues = serializers.ListField(+ required=False,+ child=SourceIssueWriteSerializer(),+ max_length=MAX_SOURCE_ISSUES_PER_WRITE,+ help_text=(+ f"{_SOURCE_ISSUES_HELP} Additive: issues join the ones the report already names, and an issue "+ "it already names is skipped. Only a newly added issue gets a comment."+ ),+ )tags = serializers.ListField(required=False,allow_null=True,@@ -2031,6 +2077,9 @@ class EditReportResponseSerializer(serializers.Serializer):links_appended = serializers.IntegerField(help_text="How many typed report-to-report links this edit wrote; 0 if none.")+ source_issues_appended = serializers.IntegerField(+ help_text="How many source issues this edit added that the report did not name yet; 0 if none."+ )reviewers_set = serializers.BooleanField(help_text="Whether the report's suggested reviewers were replaced.")repository_set = serializers.BooleanField(help_text="Whether the report's repository was replaced (true for a cleared target too)."diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.pyindex 2b20b2f5cb79..18d39b9e1815 100644--- a/products/signals/backend/scout_harness/tools/report.py+++ b/products/signals/backend/scout_harness/tools/report.py@@ -51,12 +51,14 @@ from posthog.sync import database_sync_to_asyncfrom products.signals.backend.artefact_schemas import (MAX_REPORT_LINKS_PER_WRITE,+ MAX_SOURCE_ISSUES_PER_WRITE,ActionabilityAssessment,ActionabilityChoice,Priority,PriorityAssessment,ReportLink,SafetyJudgment,+ SourceIssue,SuggestedReviewerEntry,SuggestedReviewers,)@@ -117,6 +119,7 @@ from products.signals.backend.scout_report import (append_report_evidence,append_report_links,append_report_note,+ append_report_source_issues,create_scout_report,emit_appended_report_evidence,find_scout_report_by_idempotency_key,@@ -153,6 +156,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.source_issues import parse_source_issue_urlfrom products.signals.backend.supersession import NO_IMPLEMENTATION_CONTEXTfrom products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.repo_selection_types import ReportResearchContext@@ -333,6 +337,9 @@ class EditReportResult:# How many typed report-to-report links the edit wrote. Additive like `evidence_appended`, so a# plain count rather than the nullable "set or untouched" the replace-semantics fields carry.links_appended: int = 0+ # How many source issues the edit recorded that the report did not name yet. Additive like+ # `links_appended`.+ source_issues_appended: int = 0# Which work decisions (`actionability`, `priority`) the edit replaced. Empty when the edit set# none, or re-sent the decisions the report already held.decision_fields_set: tuple[str, ...] = ()@@ -359,6 +366,7 @@ class EditReportResult:or self.repository_setor self.evidence_appendedor self.links_appended+ or self.source_issues_appendedor self.decision_fields_set)or self.charts_set is not None@@ -406,6 +414,13 @@ def _reject_trial_report_links(store: ScoutTrialStore | None, links: Sequence[Reraise InvalidScoutReportError("Report links are not supported for this run.")+def _reject_trial_source_issues(store: ScoutTrialStore | None, source_issues: Sequence[str] | None) -> None:+ # A source issue starts a public comment on the issue, which a private trial must never do.+ if store is not None and source_issues:+ store.invalidate("Source issues are not supported by private capture; this run cannot be compared.")+ raise InvalidScoutReportError("Source issues are not supported for this run.")++def _private_report_gateway(function: Callable[_Parameters, _Return]) -> Callable[_Parameters, _Return]:@wraps(function)def wrapped(*args: _Parameters.args, **kwargs: _Parameters.kwargs) -> _Return:@@ -1015,6 +1030,29 @@ def _build_links(links: list[ReportLinkInput] | None) -> list[ReportLink]:return built+def _build_source_issues(source_issues: list[str] | None) -> list[SourceIssue]:+ """Turn the caller's issue URLs into normalized `SourceIssue`s, rejecting anything but a GitHub issue.++ Pure and cheap, so a malformed URL fails before the emit or edit spends a judge call.+ """+ if not source_issues:+ return []+ if len(source_issues) > MAX_SOURCE_ISSUES_PER_WRITE:+ raise InvalidScoutReportError(+ f"a report write accepts at most {MAX_SOURCE_ISSUES_PER_WRITE} source issues ({len(source_issues)})"+ )+ built: list[SourceIssue] = []+ for url in source_issues:+ issue = parse_source_issue_url(url)+ if issue is None:+ raise InvalidScoutReportError(+ f"source issue {url!r} is not a GitHub issue URL; use https://github.com/<owner>/<repo>/issues/<number>"+ )+ if issue not in built:+ built.append(issue)+ return built++def _build_metrics(metrics: list[ReportMetricInput] | None) -> list[ReportMetric]:if not metrics:return []@@ -1847,6 +1885,7 @@ def _capture_report_emitted(suggested_prompt_count: int = 0,tag_count: int = 0,links: Sequence[ReportLink] = (),+ source_issue_count: int = 0,) -> _ReportForward | None:"""Emit the scout-owned `signals_scout_report_emitted` event — the report-channel counterpart to`signals_scout_run_finished`, fired once per `emit_report` call that reached a terminal outcome.@@ -1890,6 +1929,7 @@ def _capture_report_emitted("tag_count": tag_count,"link_count": len(links),"link_kinds": sorted({link.kind.value for link in links}),+ "source_issue_count": source_issue_count,"title": title,"summary": _forwarded_summary(summary),"actionability": actionability,@@ -1939,6 +1979,7 @@ def _capture_report_edited(actionability: ActionabilityAssessment | None = None,priority: PriorityAssessment | None = None,tags: list[str] | None = None,+ source_issues: list[SourceIssue] | None = None,) -> _ReportForward | None:"""Emit the scout-owned `signals_scout_report_edited` event when a scout mutates an existing report via`edit_report`, so edits are observable separately from fresh authorship. `updated_fields` /@@ -1976,6 +2017,7 @@ def _capture_report_edited("corroboration_collapsed": result.corroboration_collapsed,"links_appended": result.links_appended,"link_kinds": sorted({link.kind.value for link in links or []}),+ "source_issues_appended": result.source_issues_appended,"decision_fields_set": list(result.decision_fields_set),"actionability": actionability.actionability.valueif "actionability" in result.decision_fields_set and actionability@@ -2089,6 +2131,10 @@ def _capture_report_edited(written_tags = tags if result.tags_set is not None and tags is not None else Noneif written_tags is not None:parts.append(f"tags:{json.dumps(written_tags, separators=(',', ':'))}")+ # Source issues are a valid sole input too. Field-tagged and appended only when the edit wrote one.+ appended_source_issues = source_issues if result.source_issues_appended and source_issues else None+ if appended_source_issues:+ parts.append(f"source_issues:{json.dumps([issue.url for issue in appended_source_issues])}")return _ReportForward(event_name=CUSTOMER_REPORT_EDITED_EVENT,distinct_id=author.distinct_id,@@ -2101,7 +2147,8 @@ def _capture_report_edited(or appended_links is not Noneor result.repository_setor bool(decision_key)- or written_tags is not None,+ or written_tags is not None+ or appended_source_issues is not None,),properties=properties,)@@ -2128,6 +2175,7 @@ async def emit_report(links: list[ReportLinkInput] | None = None,idempotency_key: str | None = None,tags: list[str] | None = None,+ source_issues: list[str] | None = None,) -> EmitReportResult:"""Author a full report: judge for safety, then persist at the judged status. Async entry (used bythe in-Temporal runner); routes the sync DB work through `database_sync_to_async`.@@ -2142,6 +2190,10 @@ async def emit_report(`links` are typed links from the new report to others. They are written with the report, so thelink gates see a `duplicate_of` or `depends_on` link before autostart decides.+ `source_issues` are the GitHub issue URLs the report is about. They are written with the report,+ so the issue's own signal groups into it, and a READY report comments a link on each issue when+ the team opted into the GitHub writeback.+`tags` are the report's slug tags. A private trial does not keep them.`idempotency_key` names this emission, so a retry after a timeout returns the first report instead@@ -2152,6 +2204,8 @@ async def emit_report(trial_store = _trial_store(run) if run is not None else Noneif trial_store is not None and links:await database_sync_to_async(_reject_trial_report_links, thread_sensitive=False)(trial_store, links)+ if trial_store is not None and source_issues:+ await database_sync_to_async(_reject_trial_source_issues, thread_sensitive=False)(trial_store, source_issues)_validate_emit_inputs(title, summary, evidence)chart_contents = _build_charts(charts)# Off the loop because the gate reads a feature flag, which can block on the flag service.@@ -2159,6 +2213,7 @@ async def emit_report(metric_contents = _build_metrics(allowed_metrics)prompt_contents = _build_suggested_prompts(suggested_prompts)built_links = _build_links(links)+ built_source_issues = _build_source_issues(source_issues)built_tags = _build_tags(tags) or []# Validate the explicit repository format up front (cheap, pure) so a malformed `owner/repo` fails# before the safety-judge LLM call rather than after. Free-form selection still runs only if surfaced.@@ -2193,6 +2248,7 @@ async def emit_report(suggested_prompt_count=len(prompt_contents),tag_count=len(built_tags),links=built_links,+ source_issue_count=len(built_source_issues),)await _forward_report_event_async(team, forward)return result@@ -2306,6 +2362,8 @@ async def emit_report(suggested_prompts=prompt_contents if judgement.safety.choice else (),# Same reason as the prompts: an unsafe report must not steer another report's autostart.links=built_links if judgement.safety.choice else (),+ # Same reason: an unsafe report must not capture the issue's signals or comment on it.+ source_issues=built_source_issues if judgement.safety.choice else (),# Same reason as the prompts: other report scouts read the team's tags in their prompts.tags=built_tags if judgement.safety.choice else (),# Don't index the backing observations of a safety-suppressed (unsafe) report — they'd@@ -2356,6 +2414,7 @@ def emit_report_sync(links: list[ReportLinkInput] | None = None,idempotency_key: str | None = None,tags: list[str] | None = None,+ source_issues: list[str] | None = None,) -> EmitReportResult:"""Sync entry used by the DRF view path. Mirrors `emit_report` but keeps the sync DB work on thecalling thread/connection (gates, persist) — only the safety-judge LLM call, the free-form repo@@ -2366,11 +2425,13 @@ def emit_report_sync(run = author.scout_runtrial_store = _trial_store(run) if run is not None else None_reject_trial_report_links(trial_store, links)+ _reject_trial_source_issues(trial_store, source_issues)_validate_emit_inputs(title, summary, evidence)chart_contents = _build_charts(charts)metric_contents = _build_metrics(_allowed_metrics(team, metrics))prompt_contents = _build_suggested_prompts(suggested_prompts)built_links = _build_links(links)+ built_source_issues = _build_source_issues(source_issues)built_tags = _build_tags(tags) or []# Validate the explicit repository format up front (cheap, pure) so a malformed `owner/repo` fails# before the safety-judge LLM call rather than after. Free-form selection still runs only if surfaced.@@ -2405,6 +2466,7 @@ def emit_report_sync(suggested_prompt_count=len(prompt_contents),tag_count=len(built_tags),links=built_links,+ source_issue_count=len(built_source_issues),)if forward is not None:_forward_report_event_to_team(team=team, forward=forward)@@ -2507,6 +2569,8 @@ def emit_report_sync(suggested_prompts=prompt_contents if judgement.safety.choice else (),# Same reason as the prompts: an unsafe report must not steer another report's autostart.links=built_links if judgement.safety.choice else (),+ # Same reason: an unsafe report must not capture the issue's signals or comment on it.+ source_issues=built_source_issues if judgement.safety.choice else (),# Same reason as the prompts: other report scouts read the team's tags in their prompts.tags=built_tags if judgement.safety.choice else (),# Don't index the backing observations of a safety-suppressed (unsafe) report — they'd@@ -2554,6 +2618,7 @@ def _do_edit_report(actionability: ActionabilityAssessment | None = None,priority: PriorityAssessment | None = None,tags: list[str] | None = None,+ source_issues: list[SourceIssue] | None = None,) -> EditReportResult:"""Fully-sync edit core (no LLM step). The async/sync entrypoints both funnel here — directly inthe sync path, via `database_sync_to_async` in the async path. The autostart re-eval bridges an@@ -2596,6 +2661,7 @@ def _do_edit_report(note_appended = Falserepository_set = Falselinks_appended = 0+ source_issues_appended = 0evidence_document_ids: list[str] = []charts_changed = Falsemetrics_changed = False@@ -2734,6 +2800,15 @@ def _do_edit_report(links=links,attribution=attribution,)+ # Additive like the links above. Only an issue the report does not name yet is written, and+ # only that one gets a writeback comment.+ if source_issues:+ source_issues_appended = append_report_source_issues(+ team_id=team.id,+ report_id=report_id,+ source_issues=source_issues,+ attribution=attribution,+ )# Replace the report's charts, the way a summary rewrite replaces the summary. Omitting the# field leaves the existing ones alone, so an edit that only appends a note keeps them; an# explicit empty list takes them down.@@ -2792,6 +2867,7 @@ def _do_edit_report(or repository_setor evidence_appendedor links_appended+ or source_issues_appendedor decision_fields_set)or charts_set is not None@@ -2835,6 +2911,7 @@ def _do_edit_report(or tags_set is not Noneor repository_setor links_appended+ or source_issues_appendedor decision_fields_set) and not (updated_fields or note_appended or reviewers_set or evidence_appended or charts_set is not None)if report_status is not None and _surfaced(report_status) and not inbox_only:@@ -2951,6 +3028,7 @@ def _do_edit_report("supersedes_implementation": supersede_recorded,"decision_fields_set": decision_fields_set,"corroboration_collapsed": corroboration_collapsed,+ "source_issues_appended": source_issues_appended,},)# Resolve the report's effective title for the edited event's classification — the rewritten title@@ -2985,6 +3063,7 @@ def _do_edit_report(supersedes_implementation=supersede_recorded,corroboration_collapsed=corroboration_collapsed,links_appended=links_appended,+ source_issues_appended=source_issues_appended,decision_fields_set=tuple(decision_fields_set),warnings=reviewer_warnings+ (@@ -3086,10 +3165,12 @@ def _validate_edit_inputs(priority=None,priority_explanation=None,tags=None,+ source_issues=None,) -> None:author.assert_owned_by(team)trial_store = _author_trial_store(author)_reject_trial_report_links(trial_store, links)+ _reject_trial_source_issues(trial_store, source_issues)if trial_store is not None:validate_scout_report_text("title", title)validate_scout_report_text("summary", summary)@@ -3129,10 +3210,12 @@ def _validate_edit_inputs(and priority is Noneand priority_explanation is Noneand tags is None+ and not source_issues):raise InvalidScoutReportError("edit_report needs at least one of title, summary, append_note, append_evidence, "- "suggested_reviewers, repository, charts, metrics, suggested_prompts, links, actionability, priority, tags"+ "suggested_reviewers, repository, charts, metrics, suggested_prompts, links, actionability, priority, "+ "tags, source_issues")@@ -3161,6 +3244,7 @@ async def edit_report(priority: str | None = None,priority_explanation: str | None = None,tags: list[str] | None = None,+ source_issues: list[str] | None = None,) -> EditReportResult:"""Edit an existing inbox report: rewrite title/summary, append a note or fresh evidence, setsuggested reviewers, and/or repoint it at another repository (both re-run autostart, so a report@@ -3191,6 +3275,7 @@ async def edit_report(priority,priority_explanation,tags,+ source_issues,)# Validated up front (cheap, pure) so a malformed `owner/repo` fails before the safety-judge call.normalized_repository = _normalize_repository(repository)@@ -3202,6 +3287,7 @@ async def edit_report(built_charts = _build_edit_charts(charts)built_prompts = _build_edit_suggested_prompts(suggested_prompts)built_links = _build_links(links)+ built_source_issues = _build_source_issues(source_issues)built_tags = _build_tags(tags)# Off the loop because the gate reads a feature flag, which can block on the flag service.allowed_metrics = await database_sync_to_async(_allowed_metrics, thread_sensitive=False)(team, metrics)@@ -3253,6 +3339,7 @@ async def edit_report(actionability=built_actionability,priority=built_priority,tags=built_tags,+ source_issues=built_source_issues,)if _author_trial_store(author) is not None:return result@@ -3274,6 +3361,7 @@ async def edit_report(actionability=built_actionability,priority=built_priority,tags=built_tags,+ source_issues=built_source_issues,)await _forward_report_event_async(team, forward)return result@@ -3304,6 +3392,7 @@ def edit_report_sync(priority: str | None = None,priority_explanation: str | None = None,tags: list[str] | None = None,+ source_issues: list[str] | None = None,) -> EditReportResult:"""Sync entry used by the DRF view path. Same behavior as `edit_report`, on the calling thread."""if reviewer_proposal is not None and reviewer_proposal.outcome != "selected" and suggested_reviewers is None:@@ -3327,6 +3416,7 @@ def edit_report_sync(priority,priority_explanation,tags,+ source_issues,)# Validated up front (cheap, pure) so a malformed `owner/repo` fails before the safety-judge call.normalized_repository = _normalize_repository(repository)@@ -3338,6 +3428,7 @@ def edit_report_sync(built_charts = _build_edit_charts(charts)built_prompts = _build_edit_suggested_prompts(suggested_prompts)built_links = _build_links(links)+ built_source_issues = _build_source_issues(source_issues)built_tags = _build_tags(tags)allowed_metrics = _allowed_metrics(team, metrics)built_metrics = _build_edit_metrics(allowed_metrics)@@ -3384,6 +3475,7 @@ def edit_report_sync(actionability=built_actionability,priority=built_priority,tags=built_tags,+ source_issues=built_source_issues,)if _author_trial_store(author) is not None:return result@@ -3405,6 +3497,7 @@ def edit_report_sync(actionability=built_actionability,priority=built_priority,tags=built_tags,+ source_issues=built_source_issues,)if forward is not None:_forward_report_event_to_team(team=team, forward=forward)diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 266361950b2d..9662c8ca47d3 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -575,6 +575,13 @@ def _to_report_links(entries: list[dict] | None) -> list[ReportLinkInput] | None]+def _to_source_issue_urls(entries: list[dict] | None) -> list[str] | None:+ """Map validated `source_issues` entries to the issue URLs the report tools take."""+ if not entries:+ return None+ return [entry["url"] for entry in entries]++def _to_reviewer_inputs(entries: list[dict] | None) -> list[ReviewerInput] | None:"""Convert serializer UUIDs to tool inputs, keeping an empty selection distinct from an omitted field."""if entries is None:@@ -612,6 +619,7 @@ def emit_report_from_validated_data(*, team: Team, author: ReportAuthor, data: dlinks=_to_report_links(data.get("links")),idempotency_key=data.get("idempotency_key"),tags=data.get("tags"),+ source_issues=_to_source_issue_urls(data.get("source_issues")),)except InvalidScoutReportError as exc:raise exceptions.ValidationError({"detail": str(exc)})@@ -1432,6 +1440,7 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):priority=data.get("priority"),priority_explanation=data.get("priority_explanation"),tags=data.get("tags"),+ source_issues=_to_source_issue_urls(data.get("source_issues")),)except (InvalidScoutReportError, ReviewerWriteError, ValueError) as exc:raise exceptions.ValidationError({"detail": str(exc)})@@ -1443,6 +1452,7 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"note_appended": result.note_appended,"evidence_appended": result.evidence_appended,"links_appended": result.links_appended,+ "source_issues_appended": result.source_issues_appended,"reviewers_set": result.reviewers_set,"repository_set": result.repository_set,"repository": result.repository,diff --git a/products/signals/backend/scout_report/__init__.py b/products/signals/backend/scout_report/__init__.pyindex 987a4a736b3f..d7fb134581b5 100644--- a/products/signals/backend/scout_report/__init__.py+++ b/products/signals/backend/scout_report/__init__.py@@ -22,6 +22,7 @@ from products.signals.backend.scout_report.persistence import (append_report_evidence,append_report_links,append_report_note,+ append_report_source_issues,create_scout_report,emit_appended_report_evidence,find_scout_report_by_idempotency_key,@@ -72,6 +73,7 @@ __all__ = ["append_report_evidence","append_report_links","append_report_note",+ "append_report_source_issues","create_scout_report","emit_appended_report_evidence","find_scout_report_by_idempotency_key",diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.pyindex e15db67d1a9f..a8cbfe04bae1 100644--- a/products/signals/backend/scout_report/persistence.py+++ b/products/signals/backend/scout_report/persistence.py@@ -59,6 +59,7 @@ from products.signals.backend.artefact_schemas import (ReportLink,ReviewerState,SafetyJudgment,+ SourceIssue,SuggestedReviewerEntry,SuggestedReviewers,SummaryChange,@@ -86,6 +87,7 @@ from products.signals.backend.report_tags import set_report_tagsfrom products.signals.backend.reviewer_rules import ReviewerProposal, ReviewerRulesfrom products.signals.backend.scout_harness.tags import slugify_tagfrom products.signals.backend.scout_harness.tools.emit import SCOUT_SIGNAL_WEIGHT, SOURCE_PRODUCT, SOURCE_TYPE+from products.signals.backend.source_issues import append_source_issuesfrom products.signals.backend.spend import SignalMetadataChange, submit_signal_metadata_updatesfrom products.signals.backend.supersession import NO_IMPLEMENTATION_CONTEXT, research_implementation_context@@ -193,6 +195,7 @@ def create_scout_report(metrics: Sequence[ReportMetric] = (),suggested_prompts: Sequence[str] = (),links: Sequence[ReportLink] = (),+ source_issues: Sequence[SourceIssue] = (),tags: Sequence[str] = (),emit_signals: bool = True,run: SignalScoutRun | None = None,@@ -242,6 +245,10 @@ def create_scout_report(fires autostart. A link that `add_log` rejects rolls back the whole report and raises`InvalidScoutReportError`.+ `source_issues`, when supplied, become the report's `source_issue` rows in the same transaction.+ A report born READY then comments a link on each issue after commit, when the team opted into+ the GitHub writeback (`source_issues.append_source_issues`).+`idempotency_key`, when supplied, is stored on the report under a per-team unique index, so onekey can only ever author one report. A call whose key a report already holds raises`ScoutReportAlreadyEmittedError` carrying that report, and writes nothing — the emit path turns@@ -356,6 +363,7 @@ def create_scout_report()except ArtefactContentValidationError as err:raise InvalidScoutReportError(str(err))+ append_source_issues(team_id=team_id, report_id=report_id, issues=source_issues, attribution=attribution)reviewers_written = (suggested_reviewers is not None and bool(suggested_reviewers.root)) or assignment.enabled@@ -797,6 +805,30 @@ def append_report_links(return len(links)+def append_report_source_issues(+ *,+ team_id: int,+ report_id: str,+ source_issues: Sequence[SourceIssue],+ attribution: ArtefactAttribution,+) -> int:+ """Record the source issues an existing report does not hold yet, returning how many landed.++ Additive like `append_report_links`: an issue the report already names is skipped, so a retried+ edit writes nothing and comments on nothing. Only the new issues get a writeback comment.+ """+ _validate_report_id(report_id)+ if not source_issues:+ return 0+ with transaction.atomic():+ if not SignalReport.objects.filter(team_id=team_id, id=report_id).exists():+ raise InvalidScoutReportError(f"report {report_id} not found for team {team_id}")+ written = append_source_issues(+ team_id=team_id, report_id=report_id, issues=source_issues, attribution=attribution+ )+ return len(written)++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.diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex 2cccca1babc6..5a9b5841e666 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -77,6 +77,7 @@ from products.signals.backend.report_content_gates import team_report_monitoringfrom products.signals.backend.report_monitoring_attempts import current_monitoring_attemptfrom products.signals.backend.reviewer_rules import ReviewerRulesfrom products.signals.backend.scout_harness.tools.report import is_self_improvement_title+from products.signals.backend.source_issues import source_issues_by_reportfrom products.warehouse_sources.backend.facade.models import ExternalDataSchemafrom products.warehouse_sources.backend.facade.types import ExternalDataSchemaStatus@@ -89,7 +90,13 @@ if TYPE_CHECKING:from products.signals.backend.report_claims import ReportClaimfrom products.signals.backend.report_plan import ReportPlan, ReportPlanStep-from .artefact_schemas import NON_WRITABLE_ARTEFACT_TYPES, ActionabilityChoice, SourceSuggestion, priority_from_judgment+from .artefact_schemas import (+ NON_WRITABLE_ARTEFACT_TYPES,+ ActionabilityChoice,+ SourceIssue,+ SourceSuggestion,+ priority_from_judgment,+)from .briefing_reports import SUMMARY_LEAD_LIMIT, summary_leadfrom .daily_limit import reports_generated_today, team_day_startfrom .implementation_repositories import (@@ -2050,6 +2057,14 @@ class SignalReportSerializer(serializers.ModelSerializer):"request. Null when the team tracks no issues, or the issue could not be opened."),)+ source_issues = serializers.SerializerMethodField(+ help_text=(+ "URLs of the external issues this report is about, as recorded by the scout or person that "+ "filed it, oldest first. Normalized to `https://github.com/<owner>/<repo>/issues/<number>`. "+ "Empty when the report names none. Issues the report learned about from a GitHub issue signal "+ "are not listed here."+ ),+ )tracker_issue_reference = serializers.SerializerMethodField(help_text=("How that tracker issue reads in its provider, for example '#12' or 'ENG-123'. Null "@@ -2150,6 +2165,7 @@ class SignalReportSerializer(serializers.ModelSerializer):"tracker_issue_url","tracker_issue_reference","tracker_issue_error",+ "source_issues","work_state","assignee","refund",@@ -2505,6 +2521,13 @@ class SignalReportSerializer(serializers.ModelSerializer):return Nonereturn tracker.issue_url or None+ @extend_schema_field(serializers.ListField(child=serializers.CharField()))+ def get_source_issues(self, obj: SignalReport) -> list[str]:+ by_report: dict[str, list[SourceIssue]] | None = self.context.get("source_issues_map")+ if by_report is None:+ by_report = source_issues_by_report(team_id=obj.team_id, report_ids=[str(obj.id)])+ return [issue.url for issue in by_report.get(str(obj.id), [])]+@extend_schema_field(serializers.CharField(allow_null=True))def get_tracker_issue_reference(self, obj: SignalReport) -> str | None:tracker = self._get_tracker_issue(obj)diff --git a/products/signals/backend/source_issues.py b/products/signals/backend/source_issues.pynew file mode 100644index 000000000000..297aa9d7b418--- /dev/null+++ b/products/signals/backend/source_issues.py@@ -0,0 +1,134 @@+"""The external issues a report is about, recorded as `source_issue` artefacts.++A GitHub issue reaches the inbox two ways: the GitHub source ingests it as a signal, or a scout+reads it and files a report itself. Only the first carried the issue's identity, so a scout's report+never commented on the issue, and the issue's own signal later grouped by embedding alone and often+opened a second report. A scout now names the issue when it files the report, and this module is the+one place that writes and reads that record:++- `append_source_issues` writes one row per new issue and, after commit, starts the GitHub+ writeback for a READY report.+- `open_report_for_source_issue` is the exact match grouping tries before embedding similarity.+- `source_issues_by_report` is what the writeback and the report serializer read.+"""++from __future__ import annotations++import json+from collections.abc import Collection, Sequence++from django.db import transaction++from posthog.models.github_integration_base import GitHubIntegrationBase++from products.signals.backend.artefact_schemas import SourceIssue+from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact++# A report in one of these states no longer takes new signals by exact issue match. A GitHub issue+# that comes back after its report closed falls through to embedding matching, as it did before.+CLOSED_REPORT_STATUSES = (+ SignalReport.Status.RESOLVED,+ SignalReport.Status.SUPPRESSED,+ SignalReport.Status.FAILED,+ SignalReport.Status.CLOSED,+ SignalReport.Status.DELETED,+)+++def parse_source_issue_url(url: str) -> SourceIssue | None:+ """The normalized GitHub issue a URL names, or None when it names no GitHub issue."""+ ref = GitHubIntegrationBase.parse_issue_url(url.strip())+ if ref is None:+ return None+ return SourceIssue.github(ref.repository, ref.number)+++def _url_filter(url: str) -> str:+ # The closing quote is part of the match, so `.../issues/12` never matches `.../issues/123`.+ return f'"url":{json.dumps(url)}'+++def source_issues_by_report(*, team_id: int, report_ids: Collection[str]) -> dict[str, list[SourceIssue]]:+ """Each report's source issues, oldest first, in one query over the reports."""+ if not report_ids:+ return {}+ rows = (+ SignalReportArtefact.objects.filter(+ team_id=team_id, report_id__in=list(report_ids), type=SignalReportArtefact.ArtefactType.SOURCE_ISSUE+ )+ .order_by("created_at")+ .values_list("report_id", "content")+ )+ issues: dict[str, list[SourceIssue]] = {}+ for report_id, content in rows:+ issue = SourceIssue.model_validate_json(content)+ held = issues.setdefault(str(report_id), [])+ if issue not in held:+ held.append(issue)+ return issues+++def append_source_issues(+ *, team_id: int, report_id: str, issues: Sequence[SourceIssue], attribution: ArtefactAttribution+) -> list[SourceIssue]:+ """Record the issues the report does not hold yet, returning the ones written.++ Additive and deduplicated, like typed report links: naming an issue twice is a no-op, so a+ retried edit writes nothing new and starts no second writeback. Must run inside the caller's+ report transaction. The writeback is scheduled on commit, so a rolled-back write never comments,+ and it only comments on a READY report.+ """+ held = source_issues_by_report(team_id=team_id, report_ids=[report_id]).get(report_id, [])+ written: list[SourceIssue] = []+ for issue in issues:+ if issue in held or issue in written:+ continue+ SignalReportArtefact.add_log(team_id=team_id, report_id=report_id, content=issue, attribution=attribution)+ written.append(issue)+ if written:+ transaction.on_commit(lambda: schedule_source_issue_writeback(team_id=team_id, report_id=report_id))+ return written+++def schedule_source_issue_writeback(*, team_id: int, report_id: str, signals: list[dict] | None = None) -> None:+ """Queue the GitHub writeback for a READY report's source issues.++ Scout reports skip research, so the inbox notification workflow that comments for a researched+ report never runs for them. A source issue only gets a comment once the GitHub source ingested+ it, which often happens after the scout filed the report, so grouping calls this again with the+ issue's signal when that signal joins the report. The task re-checks the team opt-in and the+ report status itself.+ """+ if not SignalReport.objects.filter(team_id=team_id, id=report_id, status=SignalReport.Status.READY).exists():+ return+ from products.signals.backend.github_writeback_tasks import ( # noqa: PLC0415 - keep Celery off the import path+ post_source_issue_links,+ )++ post_source_issue_links.delay(team_id=team_id, report_id=report_id, signals=signals)+++def open_report_for_source_issue(*, team_id: int, url: str) -> SignalReport | None:+ """The oldest open report that names this GitHub issue as its source, if any.++ Reads the team's `source_issue` rows through the (team, type) index, so the cost per signal is+ bounded by how many issues the team's reports name, not by its artefact log.+ """+ issue = parse_source_issue_url(url)+ if issue is None:+ return None+ report_ids = (+ SignalReportArtefact.objects.filter(+ team_id=team_id,+ type=SignalReportArtefact.ArtefactType.SOURCE_ISSUE,+ content__contains=_url_filter(issue.url),+ )+ .values_list("report_id", flat=True)+ .distinct()+ )+ return (+ SignalReport.objects.filter(team_id=team_id, id__in=list(report_ids))+ .exclude(status__in=CLOSED_REPORT_STATUSES)+ .order_by("created_at")+ .first()+ )diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex 0f7e96d5a621..8a27670df844 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -37,6 +37,7 @@ from products.signals.backend.first_report_notification_tasks import (dispatch_first_report_notification as dispatch_first_report_notification,sweep_first_report_notifications as sweep_first_report_notifications,)+from products.signals.backend.github_writeback_tasks import post_source_issue_links as post_source_issue_linksfrom products.signals.backend.implementation_dispatch_tasks import (dispatch_implementation_replacement as dispatch_implementation_replacement,sweep_implementation_dispatches as sweep_implementation_dispatches,diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.pyindex db4b16b893d9..6b9366c2a088 100644--- a/products/signals/backend/temporal/grouping.py+++ b/products/signals/backend/temporal/grouping.py@@ -43,6 +43,7 @@ from products.signals.backend.recurrence import forks_recurrencefrom products.signals.backend.report_merge import signal_target_reportfrom products.signals.backend.report_monitoring_signals import current_research_attemptfrom products.signals.backend.signal_metadata import EMBEDDING_MODEL+from products.signals.backend.source_issues import open_report_for_source_issue, schedule_source_issue_writebackfrom products.signals.backend.spend import begin_report_spend, complete_signal_pipeline, signal_spend_summariesfrom products.signals.backend.spend_billing import system_source_exemptfrom products.signals.backend.temporal import metrics@@ -470,6 +471,41 @@ class MatchSignalToReportInput:sync_with_source: bool = Falsesource_match_signal_id: str | None = Nonesource_match_report_id: str | None = None+ # The issue URL of a GitHub issue signal, so an open report that names the issue as its source+ # can take the signal before similarity matching runs.+ source_issue_url: str | None = None+++def source_issue_url_for_signal(source_product: str, source_type: str, extra: dict | None) -> str | None:+ if source_product != SignalSourceProduct.GITHUB or source_type != SignalSourceType.ISSUE:+ return None+ url = (extra or {}).get("html_url")+ return url if isinstance(url, str) and url else None+++def _source_issue_match(team_id: int, url: str) -> ExistingReportMatch | None:+ report = open_report_for_source_issue(team_id=team_id, url=url)+ if report is None or report.triggering_signal_id is None:+ return None+ return ExistingReportMatch(+ report_id=str(report.id),+ match_metadata=MatchedMetadata(+ parent_signal_id=str(report.triggering_signal_id),+ match_query="source issue",+ reason="The report names this GitHub issue as its source issue",+ ),+ source_issue_matched=True,+ )+++async def _match_by_source_issue_or_similarity(input: MatchSignalToReportInput) -> MatchResult:+ if input.team_id is not None and input.source_issue_url:+ match = await database_sync_to_async(_source_issue_match, thread_sensitive=False)(+ input.team_id, input.source_issue_url+ )+ if match is not None:+ return match+ return await match_signal_to_report(input)async def match_signal_to_report(input: MatchSignalToReportInput) -> MatchResult:@@ -569,9 +605,9 @@ async def match_signal_to_report_activity(input: MatchSignalToReportInput) -> Masource_synced=True,)else:- result = await match_signal_to_report(input)+ result = await _match_by_source_issue_or_similarity(input)else:- result = await match_signal_to_report(input)+ result = await _match_by_source_issue_or_similarity(input)if isinstance(result, ExistingReportMatch) and input.team_id is not None:report = await SignalReport.objects.filter(team_id=input.team_id, id=result.report_id).afirst()if report is not None and report.status != SignalReport.Status.DELETED:@@ -852,6 +888,23 @@ def _link_check_follow_up(*, team_id: int, report_id: str, source_product: str,)+async def _schedule_writeback_for_source_issue_signal(input: "AssignAndEmitSignalInput", report_id: str) -> None:+ # The report names this issue as its source, and the issue only now reached the pipeline, so this+ # is the first moment the writeback may comment on it. Best-effort, like the writeback itself.+ extra = input.extra or {}+ signal = {+ "source_product": input.source_product,+ "source_type": input.source_type,+ "extra": {key: extra.get(key) for key in ("html_url", "state", "locked")},+ }+ try:+ await database_sync_to_async(schedule_source_issue_writeback, thread_sensitive=False)(+ team_id=input.team_id, report_id=report_id, signals=[signal]+ )+ except Exception:+ logger.exception("Failed to schedule source issue writeback", report_id=report_id, team_id=input.team_id)++@temporalio.activity.defn@scoped_temporal()@close_db_connections@@ -1206,6 +1259,8 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Asteam_id=input.team_id,source_id=input.source_id,)+ if isinstance(match_result, ExistingReportMatch) and match_result.source_issue_matched:+ await _schedule_writeback_for_source_issue_signal(input, db_result.report_id)# A signal on an already-researched report that did not spawn re-research, because the# report is either between buckets or past its last one. Emitted so the withheld# re-research volume is trackable, split by which of the two reasons held it back.diff --git a/products/signals/backend/temporal/parallel_grouping.py b/products/signals/backend/temporal/parallel_grouping.pyindex 2595b88c1052..931dec822de3 100644--- a/products/signals/backend/temporal/parallel_grouping.py+++ b/products/signals/backend/temporal/parallel_grouping.py@@ -22,6 +22,7 @@ from products.signals.backend.temporal.grouping import (_ProcessedBatchSignal,assign_and_emit_signal_activity,match_signal_to_report_activity,+ source_issue_url_for_signal,verify_match_specificity_activity,)from products.signals.backend.temporal.signal_queries import (@@ -43,6 +44,8 @@ from products.signals.backend.temporal.types import (logger = structlog.get_logger(__name__)+SOURCE_ISSUE_MATCH_PATCH = "signals-source-issue-match-2026-11"+@dataclassclass _SignalResult:@@ -180,15 +183,22 @@ async def _process_signal(sync_with_source=signal.sync_with_source,source_match_signal_id=signal.source_match_signal_id,source_match_report_id=signal.source_match_report_id,+ source_issue_url=source_issue_url_for_signal(signal.source_product, signal.source_type, signal.extra),),start_to_close_timeout=timedelta(minutes=10),retry_policy=RetryPolicy(maximum_attempts=5),)- # Step 5.5: PR-specificity verification for existing matches+ # Step 5.5: PR-specificity verification for existing matches. A report that names the signal's+ # issue as its source took it by exact match, so similarity has nothing to verify. Patched in+ # front of the data check, so a history recorded before the field existed keeps its commands.updated_title: Optional[str] = None- if isinstance(match_result, ExistingReportMatch) and not match_result.source_synced:+ if (+ isinstance(match_result, ExistingReportMatch)+ and not match_result.source_synced+ and not (workflow.patched(SOURCE_ISSUE_MATCH_PATCH) and match_result.source_issue_matched)+ ):report_ctx = report_contexts.get(match_result.report_id)report_title = report_ctx.title if report_ctx else ""diff --git a/products/signals/backend/temporal/types.py b/products/signals/backend/temporal/types.pyindex b08f0da32725..d501ca701fd3 100644--- a/products/signals/backend/temporal/types.py+++ b/products/signals/backend/temporal/types.py@@ -136,6 +136,9 @@ class ExistingReportMatch:match_metadata: MatchedMetadatareport_title: str | None = Nonesource_synced: bool = False+ # The signal is a GitHub issue that an open report names as its source issue, so it attached by+ # that exact match rather than by similarity, and the specificity check has nothing to add.+ source_issue_matched: bool = False@dataclassdiff --git a/products/signals/backend/test/test_assign_and_emit_signal.py b/products/signals/backend/test/test_assign_and_emit_signal.pyindex 7445d0f3249c..960e1d0c7865 100644--- a/products/signals/backend/test/test_assign_and_emit_signal.py+++ b/products/signals/backend/test/test_assign_and_emit_signal.py@@ -16,7 +16,7 @@ from posthog.sync import database_sync_to_asyncfrom products.signals.backend.agent_runtime import DEFAULT_RUNTIMEfrom products.signals.backend.artefact_attribution import ArtefactAttribution-from products.signals.backend.artefact_schemas import Dismissal, PullRequestLink, RelatedTo, ReportLink+from products.signals.backend.artefact_schemas import Dismissal, PullRequestLink, RelatedTo, ReportLink, SourceIssuefrom products.signals.backend.daily_limit import DailyReportLimitGatefrom products.signals.backend.enums import ReportLinkKind, SignalSourceProduct, SignalSourceTypefrom products.signals.backend.models import (@@ -1063,6 +1063,61 @@ async def test_source_sync_matches_without_semantic_rejudgment(ateam):semantic_match.assert_not_awaited()+ "status,attaches",+ [+ (SignalReport.Status.READY, True),+ (SignalReport.Status.PENDING_INPUT, True),+ (SignalReport.Status.RESOLVED, False),+ (SignalReport.Status.SUPPRESSED, False),+ (SignalReport.Status.FAILED, False),+ ],+)+async def test_github_issue_signal_attaches_to_the_open_report_naming_it_as_source_issue(ateam, status, attaches):+ triggering_signal_id = uuid.uuid4()+ report = await database_sync_to_async(SignalReport.objects.create)(+ team=ateam, status=status, title="Scout report", triggering_signal_id=triggering_signal_id+ )+ await database_sync_to_async(SignalReportArtefact.add_log)(+ team_id=ateam.id,+ report_id=str(report.id),+ content=SourceIssue.github("acme/widgets", 42),+ attribution=ArtefactAttribution.system(),+ )+ semantic = NewReportMatch(+ title="Exports time out", summary="", match_metadata=NoMatchMetadata(reason="nothing similar")+ )+ with (+ patch(f"{GROUPING_MODULE_PATH}.fetch_source_signal_matches", return_value={}),+ patch(f"{GROUPING_MODULE_PATH}.match_signal_to_report", new=AsyncMock(return_value=semantic)) as semantic_match,+ ):+ match = await match_signal_to_report_activity(+ MatchSignalToReportInput(+ team_id=ateam.id,+ description="Exports time out on large date ranges",+ source_product="github",+ source_type="issue",+ source_id="2001",+ sync_with_source=True,+ queries=[],+ query_results=[],+ report_contexts={},+ source_issue_url="https://github.com/Acme/Widgets/issues/42",+ )+ )++ if attaches:+ assert isinstance(match, ExistingReportMatch)+ assert match.report_id == str(report.id)+ assert match.match_metadata.parent_signal_id == str(triggering_signal_id)+ assert match.source_issue_matched is True+ semantic_match.assert_not_awaited()+ else:+ assert match is semantic++@pytest.mark.asyncio@pytest.mark.django_db@pytest.mark.parametrize("researching,pending_is_driver", [(False, False), (True, False), (True, True)])diff --git a/products/signals/backend/test/test_github_writeback.py b/products/signals/backend/test/test_github_writeback.pyindex 35a4793e158a..682a757762bb 100644--- a/products/signals/backend/test/test_github_writeback.py+++ b/products/signals/backend/test/test_github_writeback.py@@ -8,8 +8,21 @@ from parameterized import parameterizedfrom posthog.egress.limiter.policies import Priority-from products.signals.backend.github_writeback import CLAIM_LEASE, MAX_COMMENT_PAGES, post_report_link_to_github_issues-from products.signals.backend.models import SignalReport, SignalReportGithubComment, SignalTeamConfig+from products.signals.backend.artefact_attribution import ArtefactAttribution+from products.signals.backend.artefact_schemas import SourceIssue+from products.signals.backend.github_writeback import (+ CLAIM_LEASE,+ MAX_COMMENT_PAGES,+ _ingested_issue_urls,+ post_report_link_to_github_issues,+)+from products.signals.backend.models import (+ SignalReport,+ SignalReportArtefact,+ SignalReportGithubComment,+ SignalTeamConfig,+)+from products.signals.backend.test.test_signal_queries import _SignalEmbeddingsTestBaseWRITEBACK_MODULE_PATH = "products.signals.backend.github_writeback"@@ -133,6 +146,29 @@ class TestPostReportLinkToGithubIssues(BaseTest):assert integration.first_for_team_repository.call_args.kwargs["priority"] == Priority.BATCH+ @parameterized.expand(+ [+ ("a source issue the source ingested", False, {"https://github.com/acme/widgets/issues/42"}, 1),+ ("a source issue the source never ingested", False, set(), 0),+ ("the same issue from a signal and a source issue", True, set(), 1),+ ]+ )+ def test_comments_on_a_source_issue_only_once_the_source_ingested_it(self, _name, with_signal, synced, expected):+ # Anyone who files a report can name any issue URL, so the app comments only on issues the+ # team's GitHub source actually picked up.+ SignalReportArtefact.add_log(+ team_id=self.team.pk,+ report_id=str(self.report.id),+ content=SourceIssue.github("Acme/Widgets", 42),+ attribution=ArtefactAttribution.system(),+ )++ with patch(f"{WRITEBACK_MODULE_PATH}._ingested_issue_urls", return_value=synced):+ posted, comment = self._post([self.signal] if with_signal else [])++ assert posted == expected+ assert [call.args[:2] for call in comment.call_args_list] == [("acme/widgets", 42)] * expected+def test_comments_once_when_two_signals_name_the_same_issue(self):posted, comment = self._post([self.signal, _signal()])@@ -211,3 +247,25 @@ class TestPostReportLinkToGithubIssues(BaseTest):assert posted == 0assert SignalReportGithubComment.objects.for_team(self.team.pk).get().commented_at is None+++class TestIngestedIssueUrls(_SignalEmbeddingsTestBase):+ def test_finds_only_issues_with_a_live_github_issue_signal(self) -> None:+ for document_id, source_product, html_url, deleted in [+ ("ingested", "github", "https://github.com/Acme/Widgets/issues/7", False),+ ("deleted", "github", "https://github.com/acme/widgets/issues/8", True),+ ("other-source", "linear", "https://github.com/acme/widgets/issues/9", False),+ ]:+ self._emit_version(+ document_id=document_id,+ report_id="r-1",+ source_product=source_product,+ source_type="issue",+ inserted_at=self.base,+ deleted=deleted,+ extra={"html_url": html_url},+ )++ urls = {f"https://github.com/acme/widgets/issues/{number}" for number in (7, 8, 9, 10)}++ assert _ingested_issue_urls(self.team, urls) == {"https://github.com/acme/widgets/issues/7"}diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.pyindex e67a6c6a8028..920b5ad61569 100644--- a/products/signals/backend/test/test_scout_report_api.py+++ b/products/signals/backend/test/test_scout_report_api.py@@ -636,6 +636,69 @@ class TestScoutReportAPI(APIBaseTest):run.refresh_from_db()assert run.edited_report_ids == [first["report_id"]]+ @parameterized.expand(+ [+ ("ready", "immediately_actionable", True),+ ("pending input", "requires_human_input", False),+ ]+ )+ def test_source_issues_are_recorded_once_and_start_the_writeback_for_a_ready_report(+ self, _name: str, actionability: str, writes_back: bool+ ) -> None:+ run = _make_run(self.team)+ issue_42 = "https://github.com/Acme/Widgets/issues/42"+ issue_43 = "https://github.com/acme/widgets/issues/43"+ with (+ _safe_judge(),+ patch(EMBED_PATH),+ patch("products.signals.backend.github_writeback_tasks.post_source_issue_links") as writeback,+ ):+ with self.captureOnCommitCallbacks(execute=True):+ created = self.client.post(+ self._emit_url(str(run.id)),+ data=self._payload(actionability=actionability, source_issues=[{"url": issue_42}]),+ format="json",+ )+ assert created.status_code == status.HTTP_200_OK, created.json()+ report_id = created.json()["report_id"]+ assert writeback.delay.call_count == (1 if writes_back else 0)++ # Naming the held issue again writes nothing and comments on nothing; only #43 is new.+ with self.captureOnCommitCallbacks(execute=True):+ edited = self.client.post(+ self._edit_url(str(run.id)),+ data={"report_id": report_id, "source_issues": [{"url": issue_42}, {"url": issue_43}]},+ format="json",+ )+ assert edited.status_code == status.HTTP_200_OK, edited.json()+ assert edited.json()["source_issues_appended"] == 1+ assert writeback.delay.call_count == (2 if writes_back else 0)++ stored = SignalReportArtefact.objects.filter(+ report_id=report_id, type=SignalReportArtefact.ArtefactType.SOURCE_ISSUE+ ).order_by("created_at")+ assert [json.loads(row.content)["url"] for row in stored] == [+ "https://github.com/acme/widgets/issues/42",+ "https://github.com/acme/widgets/issues/43",+ ]++ @parameterized.expand(+ [+ ("pull request", "https://github.com/acme/widgets/pull/42"),+ ("another tracker", "https://gitlab.com/acme/widgets/-/issues/42"),+ ("no number", "https://github.com/acme/widgets/issues/new"),+ ]+ )+ def test_emit_report_rejects_a_source_issue_that_is_not_a_github_issue(self, _name: str, url: str) -> None:+ run = _make_run(self.team)+ with _safe_judge() as judge, patch(EMBED_PATH):+ response = self.client.post(+ self._emit_url(str(run.id)), data=self._payload(source_issues=[{"url": url}]), format="json"+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ judge.assert_not_called()+def test_edit_report_rejects_an_unknown_link_kind(self) -> None:run = _make_run(self.team)with _safe_judge(), patch(EMBED_PATH):diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 5f893b053dae..78d773c90991 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -315,6 +315,7 @@ from products.signals.backend.slack_notification_targets import (saved_notification_integration,validate_slack_notification_target,)+from products.signals.backend.source_issues import source_issues_by_reportfrom products.signals.backend.source_suggestions import current_source_suggestionfrom products.signals.backend.spend_reporting import SpendReportingfrom products.signals.backend.suggested_reviewer_index import report_ids_naming_reviewers@@ -2861,6 +2862,7 @@ class SignalReportViewSet(**self._claim_and_pull_request_context(report_ids, pull_requests_map, claims),"source_suggestions_map": {str(report.id): source_suggestion},"report_plans_map": {str(report.id): plan},+ "source_issues_map": source_issues_by_report(team_id=self.team_id, report_ids=report_ids),}@extend_schema(responses=ReportSpendSerializer, operation_id="signals_report_spend")@@ -3285,6 +3287,7 @@ class SignalReportViewSet(**self._claim_and_pull_request_context(report_ids, pull_requests_map, claims),"first_billable_pr_run_at_map": first_billable_pr_run_at_map,"inbox_ranker": self._inbox_ranker,+ "source_issues_map": source_issues_by_report(team_id=self.team_id, report_ids=report_ids),}serializer = self.get_serializer(reports, many=True, context=context)diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 3c40997a4138..4c0675c609ff 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -2498,6 +2498,8 @@ export interface SignalReportListApi {* @nullable*/readonly tracker_issue_error: string | null+ /** URLs of the external issues this report is about, as recorded by the scout or person that filed it, oldest first. Normalized to `https://github.com/<owner>/<repo>/issues/<number>`. Empty when the report names none. Issues the report learned about from a GitHub issue signal are not listed here. */+ readonly source_issues: readonly string[]/** Derived remediation state: unclaimed, working, in_review, or done. */readonly work_state: SignalReportWorkStateEnumApi/** Current user, internal task, or external agent claim owner. Null when unclaimed. */@@ -2717,6 +2719,17 @@ export interface ReportLinkWriteApi {reason?: string}+/**+ * One external issue the report is about.+ */+export interface SourceIssueWriteApi {+ /**+ * The issue's URL, `https://github.com/<owner>/<repo>/issues/<number>`. Only GitHub issues are accepted today. Pull request URLs are rejected.+ * @maxLength 500+ */+ url: string+}+/*** Request body for the scout `emit-report` action and the inbox report `create` action. A scout run is* taken from the URL path; a person is the authenticated caller.@@ -2788,6 +2801,11 @@ export interface EmitReportRequestApi {* @maxItems 10*/links?: ReportLinkWriteApi[]+ /**+ * The GitHub issues this report is about, when the finding came from an issue tracker. Pass the issue whenever the report is about one, so the report links back to it: a GitHub issue signal for the same issue then joins this report instead of opening a second one. When the project turned on GitHub issue comments, the issue gets one comment that links the report once its GitHub source ingests the issue. At most 5 per call.+ * @maxItems 5+ */+ source_issues?: SourceIssueWriteApi[]/*** Optional slug tags that group the report with related ones, at most 10. Write lowercase kebab-case slugs that name the category of the report (`cost-spike`, `tracking-gap`), not the specific entity. Reuse a slug the project already uses before you coin a new one. Near-miss formats are normalized to slugs, and a tag that is empty or longer than 50 characters after normalization is rejected.* @maxItems 10@@ -3045,6 +3063,8 @@ export interface SignalReportApi {* @nullable*/readonly tracker_issue_error: string | null+ /** URLs of the external issues this report is about, as recorded by the scout or person that filed it, oldest first. Normalized to `https://github.com/<owner>/<repo>/issues/<number>`. Empty when the report names none. Issues the report learned about from a GitHub issue signal are not listed here. */+ readonly source_issues: readonly string[]/** Derived remediation state: unclaimed, working, in_review, or done. */readonly work_state: SignalReportWorkStateEnumApi/** Current user, internal task, or external agent claim owner. Null when unclaimed. */@@ -5719,6 +5739,7 @@ export interface SignalReportStateRequestApi {* * `code_review` - Code Review* * `related_to` - Related To* * `report_link` - Report Link+ * * `source_issue` - Source Issue* * `autostart_skip` - Autostart Skip* * `work_claim` - Work Claim* * `work_release` - Work Release@@ -5762,6 +5783,7 @@ export const SignalReportArtefactArtefactTypeEnumApi = {CodeReview: 'code_review',RelatedTo: 'related_to',ReportLink: 'report_link',+ SourceIssue: 'source_issue',AutostartSkip: 'autostart_skip',WorkClaim: 'work_claim',WorkRelease: 'work_release',@@ -10082,6 +10104,11 @@ export interface EditReportRequestApi {* @maxItems 10*/links?: ReportLinkWriteApi[]+ /**+ * The GitHub issues this report is about, when the finding came from an issue tracker. Pass the issue whenever the report is about one, so the report links back to it: a GitHub issue signal for the same issue then joins this report instead of opening a second one. When the project turned on GitHub issue comments, the issue gets one comment that links the report once its GitHub source ingests the issue. At most 5 per call. Additive: issues join the ones the report already names, and an issue it already names is skipped. Only a newly added issue gets a comment.+ * @maxItems 5+ */+ source_issues?: SourceIssueWriteApi[]/*** The report's full set of slug tags, at most 10. Replaces the report's tags rather than adding to them, so send every tag you want kept. Omit the field (or send null) to leave them untouched, and send an empty list to remove them. Reuse a slug the project already uses before you coin a new one.* @maxItems 10@@ -10139,6 +10166,8 @@ export interface EditReportResponseApi {evidence_appended: number/** How many typed report-to-report links this edit wrote; 0 if none. */links_appended: number+ /** How many source issues this edit added that the report did not name yet; 0 if none. */+ source_issues_appended: number/** Whether the report's suggested reviewers were replaced. */reviewers_set: boolean/** Whether the report's repository was replaced (true for a cleared target too). */diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 6503f6f21cdf..ff2af6688706 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -1369,7 +1369,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: `autostart_skip`, `check_authoring`, `check_cancelled`, `check_expired`, `check_observation`, `check_result`, `check_scheduled`, `code_review`, `impact_measurement_plan`, `implementation_decision`, `implementation_dispatch`, `implementation_handover`, `implementation_replacement`, `pr_owner_assignment`, `pull_request`, `ranking_score`, `report_link`, `reviewer_corrections`, `scout_note_left`, `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: `autostart_skip`, `check_authoring`, `check_cancelled`, `check_expired`, `check_observation`, `check_result`, `check_scheduled`, `code_review`, `impact_measurement_plan`, `implementation_decision`, `implementation_dispatch`, `implementation_handover`, `implementation_replacement`, `pr_owner_assignment`, `pull_request`, `ranking_score`, `report_link`, `reviewer_corrections`, `scout_note_left`, `source_issue`, `summary_change`, `task_run`, `title_change`, `video_segment`, `work_claim`, `work_release`.* @summary Delete an artefact*/export const signalsReportArtefactsDestroy = async (diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 13747971c23e..e703e3360875 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -708,6 +708,10 @@ export const signalsReportsCreateBodyLinksItemReasonMax = 500export const signalsReportsCreateBodyLinksMax = 10+export const signalsReportsCreateBodySourceIssuesItemUrlMax = 500++export const signalsReportsCreateBodySourceIssuesMax = 5+export const signalsReportsCreateBodyTagsMax = 10export const signalsReportsCreateBodyIdempotencyKeyMax = 200@@ -1001,6 +1005,24 @@ export const SignalsReportsCreateBody = /* @__PURE__ */ zod.describe('Typed, directed links from the new report to reports that already exist. Send them here, not in a later `edit-report` call, because autostart reads them when the report is created: a `duplicate_of` link to a report that already has a pull request, or a `depends_on` link to a report with no pull request yet, stops a second draft PR. Only the new report gets a row, so link from the side the sentence starts at. Links of the same kind must stay acyclic and every report must be in this project.'),+ source_issues: zod+ .array(+ zod+ .object({+ url: zod+ .string()+ .max(signalsReportsCreateBodySourceIssuesItemUrlMax)+ .describe(+ "The issue's URL, `https:\/\/github.com\/<owner>\/<repo>\/issues\/<number>`. Only GitHub issues are accepted today. Pull request URLs are rejected."+ ),+ })+ .describe('One external issue the report is about.')+ )+ .max(signalsReportsCreateBodySourceIssuesMax)+ .optional()+ .describe(+ 'The GitHub issues this report is about, when the finding came from an issue tracker. Pass the issue whenever the report is about one, so the report links back to it: a GitHub issue signal for the same issue then joins this report instead of opening a second one. When the project turned on GitHub issue comments, the issue gets one comment that links the report once its GitHub source ingests the issue. At most 5 per call.'+ ),tags: zod.array(zod.string()).max(signalsReportsCreateBodyTagsMax)@@ -3109,6 +3131,10 @@ export const signalsScoutEditReportBodyLinksItemReasonMax = 500export const signalsScoutEditReportBodyLinksMax = 10+export const signalsScoutEditReportBodySourceIssuesItemUrlMax = 500++export const signalsScoutEditReportBodySourceIssuesMax = 5+export const signalsScoutEditReportBodyTagsMax = 10export const SignalsScoutEditReportBody = /* @__PURE__ */ zod@@ -3424,6 +3450,24 @@ export const SignalsScoutEditReportBody = /* @__PURE__ */ zod.describe("Typed, directed links from this report to others, recording how the work relates. Use `depends_on` when you split one finding into a stack and the second report's fix cannot land until the first one's does, so the order is recorded rather than left to a reader of the diffs. Additive: links join what the report already has rather than replacing them, and only this report gets a row, so link from the side the sentence starts at. Links of the same kind must stay acyclic and every report must be in this project."),+ source_issues: zod+ .array(+ zod+ .object({+ url: zod+ .string()+ .max(signalsScoutEditReportBodySourceIssuesItemUrlMax)+ .describe(+ "The issue's URL, `https:\/\/github.com\/<owner>\/<repo>\/issues\/<number>`. Only GitHub issues are accepted today. Pull request URLs are rejected."+ ),+ })+ .describe('One external issue the report is about.')+ )+ .max(signalsScoutEditReportBodySourceIssuesMax)+ .optional()+ .describe(+ 'The GitHub issues this report is about, when the finding came from an issue tracker. Pass the issue whenever the report is about one, so the report links back to it: a GitHub issue signal for the same issue then joins this report instead of opening a second one. When the project turned on GitHub issue comments, the issue gets one comment that links the report once its GitHub source ingests the issue. At most 5 per call. Additive: issues join the ones the report already names, and an issue it already names is skipped. Only a newly added issue gets a comment.'+ ),tags: zod.array(zod.string()).max(signalsScoutEditReportBodyTagsMax)@@ -3527,6 +3571,10 @@ export const signalsScoutEmitReportBodyLinksItemReasonMax = 500export const signalsScoutEmitReportBodyLinksMax = 10+export const signalsScoutEmitReportBodySourceIssuesItemUrlMax = 500++export const signalsScoutEmitReportBodySourceIssuesMax = 5+export const signalsScoutEmitReportBodyTagsMax = 10export const signalsScoutEmitReportBodyIdempotencyKeyMax = 200@@ -3820,6 +3868,24 @@ export const SignalsScoutEmitReportBody = /* @__PURE__ */ zod.describe('Typed, directed links from the new report to reports that already exist. Send them here, not in a later `edit-report` call, because autostart reads them when the report is created: a `duplicate_of` link to a report that already has a pull request, or a `depends_on` link to a report with no pull request yet, stops a second draft PR. Only the new report gets a row, so link from the side the sentence starts at. Links of the same kind must stay acyclic and every report must be in this project.'),+ source_issues: zod+ .array(+ zod+ .object({+ url: zod+ .string()+ .max(signalsScoutEmitReportBodySourceIssuesItemUrlMax)+ .describe(+ "The issue's URL, `https:\/\/github.com\/<owner>\/<repo>\/issues\/<number>`. Only GitHub issues are accepted today. Pull request URLs are rejected."+ ),+ })+ .describe('One external issue the report is about.')+ )+ .max(signalsScoutEmitReportBodySourceIssuesMax)+ .optional()+ .describe(+ 'The GitHub issues this report is about, when the finding came from an issue tracker. Pass the issue whenever the report is about one, so the report links back to it: a GitHub issue signal for the same issue then joins this report instead of opening a second one. When the project turned on GitHub issue comments, the issue gets one comment that links the report once its GitHub source ingests the issue. At most 5 per call.'+ ),tags: zod.array(zod.string()).max(signalsScoutEmitReportBodyTagsMax)diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 696f23d2be2f..9cef44e53817 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -36494,6 +36494,17 @@ export namespace Schemas {reason?: string;}+ /**+ * One external issue the report is about.+ */+ export interface SourceIssueWrite {+ /**+ * The issue's URL, `https://github.com/<owner>/<repo>/issues/<number>`. Only GitHub issues are accepted today. Pull request URLs are rejected.+ * @maxLength 500+ */+ url: string;+ }+/*** Request body for `edit-report`. Can target ANY of the team's inbox reports, not just scout-authored ones.*/@@ -36578,6 +36589,11 @@ export namespace Schemas {* @maxItems 10*/links?: ReportLinkWrite[];+ /**+ * The GitHub issues this report is about, when the finding came from an issue tracker. Pass the issue whenever the report is about one, so the report links back to it: a GitHub issue signal for the same issue then joins this report instead of opening a second one. When the project turned on GitHub issue comments, the issue gets one comment that links the report once its GitHub source ingests the issue. At most 5 per call. Additive: issues join the ones the report already names, and an issue it already names is skipped. Only a newly added issue gets a comment.+ * @maxItems 5+ */+ source_issues?: SourceIssueWrite[];/*** The report's full set of slug tags, at most 10. Replaces the report's tags rather than adding to them, so send every tag you want kept. Omit the field (or send null) to leave them untouched, and send an empty list to remove them. Reuse a slug the project already uses before you coin a new one.* @maxItems 10@@ -36635,6 +36651,8 @@ export namespace Schemas {evidence_appended: number;/** How many typed report-to-report links this edit wrote; 0 if none. */links_appended: number;+ /** How many source issues this edit added that the report did not name yet; 0 if none. */+ source_issues_appended: number;/** Whether the report's suggested reviewers were replaced. */reviewers_set: boolean;/** Whether the report's repository was replaced (true for a cleared target too). */@@ -37577,6 +37595,11 @@ export namespace Schemas {* @maxItems 10*/links?: ReportLinkWrite[];+ /**+ * The GitHub issues this report is about, when the finding came from an issue tracker. Pass the issue whenever the report is about one, so the report links back to it: a GitHub issue signal for the same issue then joins this report instead of opening a second one. When the project turned on GitHub issue comments, the issue gets one comment that links the report once its GitHub source ingests the issue. At most 5 per call.+ * @maxItems 5+ */+ source_issues?: SourceIssueWrite[];/*** Optional slug tags that group the report with related ones, at most 10. Write lowercase kebab-case slugs that name the category of the report (`cost-spike`, `tracking-gap`), not the specific entity. Reuse a slug the project already uses before you coin a new one. Near-miss formats are normalized to slugs, and a tag that is empty or longer than 50 characters after normalization is rejected.* @maxItems 10@@ -73674,6 +73697,7 @@ export namespace Schemas {* * `code_review` - Code Review* * `related_to` - Related To* * `report_link` - Report Link+ * * `source_issue` - Source Issue* * `autostart_skip` - Autostart Skip* * `work_claim` - Work Claim* * `work_release` - Work Release@@ -73717,6 +73741,7 @@ export namespace Schemas {CodeReview: 'code_review',RelatedTo: 'related_to',ReportLink: 'report_link',+ SourceIssue: 'source_issue',AutostartSkip: 'autostart_skip',WorkClaim: 'work_claim',WorkRelease: 'work_release',@@ -74700,6 +74725,8 @@ export namespace Schemas {* @nullable*/readonly tracker_issue_error: string | null;+ /** URLs of the external issues this report is about, as recorded by the scout or person that filed it, oldest first. Normalized to `https://github.com/<owner>/<repo>/issues/<number>`. Empty when the report names none. Issues the report learned about from a GitHub issue signal are not listed here. */+ readonly source_issues: readonly string[];/** Derived remediation state: unclaimed, working, in_review, or done. */readonly work_state: SignalReportWorkStateEnum;/** Current user, internal task, or external agent claim owner. Null when unclaimed. */@@ -98804,6 +98831,8 @@ export namespace Schemas {* @nullable*/readonly tracker_issue_error: string | null;+ /** URLs of the external issues this report is about, as recorded by the scout or person that filed it, oldest first. Normalized to `https://github.com/<owner>/<repo>/issues/<number>`. Empty when the report names none. Issues the report learned about from a GitHub issue signal are not listed here. */+ readonly source_issues: readonly string[];/** Derived remediation state: unclaimed, working, in_review, or done. */readonly work_state: SignalReportWorkStateEnum;/** Current user, internal task, or external agent claim owner. Null when unclaimed. */diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex e7609f5abe41..76d257e26f7c 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -616,6 +616,10 @@ export const signalsReportsCreateBodyLinksItemReasonMax = 500export const signalsReportsCreateBodyLinksMax = 10+export const signalsReportsCreateBodySourceIssuesItemUrlMax = 500++export const signalsReportsCreateBodySourceIssuesMax = 5+export const signalsReportsCreateBodyTagsMax = 10export const signalsReportsCreateBodyIdempotencyKeyMax = 200@@ -805,6 +809,24 @@ export const SignalsReportsCreateBody = () => zod.describe('Typed, directed links from the new report to reports that already exist. Send them here, not in a later `edit-report` call, because autostart reads them when the report is created: a `duplicate_of` link to a report that already has a pull request, or a `depends_on` link to a report with no pull request yet, stops a second draft PR. Only the new report gets a row, so link from the side the sentence starts at. Links of the same kind must stay acyclic and every report must be in this project.'),+ source_issues: zod+ .array(+ zod+ .object({+ url: zod+ .string()+ .max(signalsReportsCreateBodySourceIssuesItemUrlMax)+ .describe(+ "The issue's URL, `https:\/\/github.com\/<owner>\/<repo>\/issues\/<number>`. Only GitHub issues are accepted today. Pull request URLs are rejected."+ ),+ })+ .describe('One external issue the report is about.')+ )+ .max(signalsReportsCreateBodySourceIssuesMax)+ .optional()+ .describe(+ 'The GitHub issues this report is about, when the finding came from an issue tracker. Pass the issue whenever the report is about one, so the report links back to it: a GitHub issue signal for the same issue then joins this report instead of opening a second one. When the project turned on GitHub issue comments, the issue gets one comment that links the report once its GitHub source ingests the issue. At most 5 per call.'+ ),tags: zod.array(zod.string()).max(signalsReportsCreateBodyTagsMax)@@ -1459,7 +1481,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: `autostart_skip`, `check_authoring`, `check_cancelled`, `check_expired`, `check_observation`, `check_result`, `check_scheduled`, `code_review`, `impact_measurement_plan`, `implementation_decision`, `implementation_dispatch`, `implementation_handover`, `implementation_replacement`, `pr_owner_assignment`, `pull_request`, `ranking_score`, `report_link`, `reviewer_corrections`, `scout_note_left`, `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: `autostart_skip`, `check_authoring`, `check_cancelled`, `check_expired`, `check_observation`, `check_result`, `check_scheduled`, `code_review`, `impact_measurement_plan`, `implementation_decision`, `implementation_dispatch`, `implementation_handover`, `implementation_replacement`, `pr_owner_assignment`, `pull_request`, `ranking_score`, `report_link`, `reviewer_corrections`, `scout_note_left`, `source_issue`, `summary_change`, `task_run`, `title_change`, `video_segment`, `work_claim`, `work_release`.* @summary Delete an artefact*/export const SignalsReportArtefactsDestroyParams = () => zod.object({@@ -3574,6 +3596,10 @@ export const signalsScoutEditReportBodyLinksItemReasonMax = 500export const signalsScoutEditReportBodyLinksMax = 10+export const signalsScoutEditReportBodySourceIssuesItemUrlMax = 500++export const signalsScoutEditReportBodySourceIssuesMax = 5+export const signalsScoutEditReportBodyTagsMax = 10export const SignalsScoutEditReportBody = () => zod@@ -3889,6 +3915,24 @@ export const SignalsScoutEditReportBody = () => zod.describe("Typed, directed links from this report to others, recording how the work relates. Use `depends_on` when you split one finding into a stack and the second report's fix cannot land until the first one's does, so the order is recorded rather than left to a reader of the diffs. Additive: links join what the report already has rather than replacing them, and only this report gets a row, so link from the side the sentence starts at. Links of the same kind must stay acyclic and every report must be in this project."),+ source_issues: zod+ .array(+ zod+ .object({+ url: zod+ .string()+ .max(signalsScoutEditReportBodySourceIssuesItemUrlMax)+ .describe(+ "The issue's URL, `https:\/\/github.com\/<owner>\/<repo>\/issues\/<number>`. Only GitHub issues are accepted today. Pull request URLs are rejected."+ ),+ })+ .describe('One external issue the report is about.')+ )+ .max(signalsScoutEditReportBodySourceIssuesMax)+ .optional()+ .describe(+ 'The GitHub issues this report is about, when the finding came from an issue tracker. Pass the issue whenever the report is about one, so the report links back to it: a GitHub issue signal for the same issue then joins this report instead of opening a second one. When the project turned on GitHub issue comments, the issue gets one comment that links the report once its GitHub source ingests the issue. At most 5 per call. Additive: issues join the ones the report already names, and an issue it already names is skipped. Only a newly added issue gets a comment.'+ ),tags: zod.array(zod.string()).max(signalsScoutEditReportBodyTagsMax)@@ -4027,6 +4071,10 @@ export const signalsScoutEmitReportBodyLinksItemReasonMax = 500export const signalsScoutEmitReportBodyLinksMax = 10+export const signalsScoutEmitReportBodySourceIssuesItemUrlMax = 500++export const signalsScoutEmitReportBodySourceIssuesMax = 5+export const signalsScoutEmitReportBodyTagsMax = 10export const signalsScoutEmitReportBodyIdempotencyKeyMax = 200@@ -4320,6 +4368,24 @@ export const SignalsScoutEmitReportBody = () => zod.describe('Typed, directed links from the new report to reports that already exist. Send them here, not in a later `edit-report` call, because autostart reads them when the report is created: a `duplicate_of` link to a report that already has a pull request, or a `depends_on` link to a report with no pull request yet, stops a second draft PR. Only the new report gets a row, so link from the side the sentence starts at. Links of the same kind must stay acyclic and every report must be in this project.'),+ source_issues: zod+ .array(+ zod+ .object({+ url: zod+ .string()+ .max(signalsScoutEmitReportBodySourceIssuesItemUrlMax)+ .describe(+ "The issue's URL, `https:\/\/github.com\/<owner>\/<repo>\/issues\/<number>`. Only GitHub issues are accepted today. Pull request URLs are rejected."+ ),+ })+ .describe('One external issue the report is about.')+ )+ .max(signalsScoutEmitReportBodySourceIssuesMax)+ .optional()+ .describe(+ 'The GitHub issues this report is about, when the finding came from an issue tracker. Pass the issue whenever the report is about one, so the report links back to it: a GitHub issue signal for the same issue then joins this report instead of opening a second one. When the project turned on GitHub issue comments, the issue gets one comment that links the report once its GitHub source ingests the issue. At most 5 per call.'+ ),tags: zod.array(zod.string()).max(signalsScoutEmitReportBodyTagsMax)diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex 19ab13aeb781..47b17534c203 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -683,6 +683,9 @@ const inboxReportsCreate = (): ToolBase<if (params.links !== undefined) {body['links'] = params.links}+ if (params.source_issues !== undefined) {+ body['source_issues'] = params.source_issues+ }if (params.tags !== undefined) {body['tags'] = params.tags}@@ -1812,6 +1815,9 @@ const scoutEditReport = (): ToolBase<ReturnType<typeof ScoutEditReportSchema>, Sif (params.links !== undefined) {body['links'] = params.links}+ if (params.source_issues !== undefined) {+ body['source_issues'] = params.source_issues+ }if (params.tags !== undefined) {body['tags'] = params.tags}@@ -1898,6 +1904,9 @@ const scoutEmitReport = (): ToolBase<ReturnType<typeof ScoutEmitReportSchema>, Sif (params.links !== undefined) {body['links'] = params.links}+ if (params.source_issues !== undefined) {+ body['source_issues'] = params.source_issues+ }if (params.tags !== undefined) {body['tags'] = params.tags}@@ -3303,6 +3312,9 @@ const signalsScoutEditReport = (): ToolBase<if (params.links !== undefined) {body['links'] = params.links}+ if (params.source_issues !== undefined) {+ body['source_issues'] = params.source_issues+ }if (params.tags !== undefined) {body['tags'] = params.tags}@@ -3392,6 +3404,9 @@ const signalsScoutEmitReport = (): ToolBase<if (params.links !== undefined) {body['links'] = params.links}+ if (params.source_issues !== undefined) {+ body['source_issues'] = params.source_issues+ }if (params.tags !== undefined) {body['tags'] = params.tags}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-create.jsonindex c779eeb1bc43..93c6cb815db3 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-create.json@@ -160,6 +160,23 @@],"description": "Optional repo for opening a draft PR, by autostart of a scout report or by a person from the inbox. Pass `owner/repo` whenever you can say where a fix would land. Omit the field when you can't, which triggers free-form selection across the team's repos (the slow path on a many-repo team). Keep the `NO_REPO` sentinel for the rare report where nothing under version control could change, since a skill body, a config file, or a doc still lives in a repo."},+ "source_issues": {+ "description": "The GitHub issues this report is about, when the finding came from an issue tracker. Pass the issue whenever the report is about one, so the report links back to it: a GitHub issue signal for the same issue then joins this report instead of opening a second one. When the project turned on GitHub issue comments, the issue gets one comment that links the report once its GitHub source ingests the issue. At most 5 per call.",+ "items": {+ "description": "One external issue the report is about.",+ "properties": {+ "url": {+ "description": "The issue's URL, `https://github.com/<owner>/<repo>/issues/<number>`. Only GitHub issues are accepted today. Pull request URLs are rejected.",+ "maxLength": 500,+ "type": "string"+ }+ },+ "required": ["url"],+ "type": "object"+ },+ "maxItems": 5,+ "type": "array"+ },"suggested_prompts": {"description": "Optional follow-up prompts to offer above the report's `Ask AI` box: questions to ask, or next-step actions to request (e.g. carrying out the report's recommendation). The reader clicks one to fill the box with it, then sends or edits it. Write the prompts your own research left open, phrased as the reader would send them.","items": {