: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): comment back on the GitHub issue that raised a report (#99830)
posthog[bot]e26a27aabc93
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex d6bff1e5eef9..dce2ba547b81 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -335,6 +335,7 @@ rules:|SignalReport|SignalReportAction|SignalReportArtefact+ |SignalReportGithubComment|SignalReportPullRequest|SignalReportAssignment|SignalReportRefund@@ -738,6 +739,7 @@ rules:|SignalReport|SignalReportAction|SignalReportArtefact+ |SignalReportGithubComment|SignalReportPullRequest|SignalReportAssignment|SignalReportRefunddiff --git a/docs/internal/signals-github-writeback.md b/docs/internal/signals-github-writeback.mdnew file mode 100644index 000000000000..0148b145fe30--- /dev/null+++ b/docs/internal/signals-github-writeback.md@@ -0,0 +1,25 @@+# GitHub issue comments++The Inbox setting `github_issue_writeback_enabled` lets a project post public comments on GitHub issues that contributed to a ready report.+The setting defaults to `false`.+Each comment contains a report link and a stable marker. It contains no report title or research.+The report requires project access.++The notification workflow sends the report notification before it starts a separate GitHub activity.+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.++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.+After ten minutes, a later settle can claim the pending row and search the issue comments for the stable marker.+An existing marker completes the claim without a second POST.+A complete read without the marker permits a retry.+The search stops after ten pages of 100 comments. An incomplete or failed read leaves the claim pending.+This recovery is best effort. GitHub does not provide an atomic idempotency key for comment creation.++Use the `signals.github_writeback_failed` log to diagnose request failures.+The `signals.github_writeback_posted` log records the report, project, candidate issues, and comments posted.+An activity timeout appears as `inbox notification: GitHub write-back failed` in the workflow log.+Pending claims retry only when the report settles again. There is no periodic recovery job.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 582a0cd62c8f..c0435bd613aa 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8165,9 +8165,9 @@ snapshots:scenes-app-inbox-scene--self-driving-verdict-pending--light:hash: v1.k794b7964.96cdbec6c78e8daedb06be4a0134093efcd5838af69e6e7d1722a3892cf561b5.iJ2K0zNhOVgGAPY6JvduyhDBODMwk-CN7_mAdB8scOgscenes-app-inbox-scene--settings--dark:- hash: v1.k794b7964.50705f30642679b4254e32e0287c65ae31125b28d9748bac83326e461c7580f1.38uhbQQ5yYrdBVeVEcGqDQ8QTqo9YtkJz36Qfu7YfMQ+ hash: v1.k794b7964.14ed4a004e1c806fb9178be0020a0aa078874b1356db0e7c037afe48d4ecadef.0oQeLxKsUvzJDj72tiCFTC60gtvrbAeumQv-FGbJxZ4scenes-app-inbox-scene--settings--light:- hash: v1.k794b7964.7abae9cb09b2bf1daa3779bb82100c9dddad3e9c8a8c95ddd8891ec61eb2c078.TtUmePwpdGLSCTje_xVNKqhbEjBgRBVplvDjx8kCc3c+ hash: v1.k794b7964.695c2ef4914cec3959aeeddc8fc6dbdf648ffaec4bb058b2850eb2949b0c47d3.OD7Wkopvw_-ByEzsDEWIdwPdFQDvi1sUO_CbG8YiAAkscenes-app-inbox-scene--triage--dark:hash: v1.k794b7964.77e43b36fdcd81befecf4de80e489050f525840924ec6ddef37c23a9179dbe8a.B3qkZFYBncFaPn2EBg4cBoYu_LIwW29imNwBdLXF5eoscenes-app-inbox-scene--triage--light:@@ -8353,45 +8353,45 @@ snapshots:scenes-app-inbox-scoutwritescopespicker--with-granted-scopes--light:hash: v1.k794b7964.b3f53357dbbbc84b6580fa82faf34538e4f6e4e3c15691c14848541cae742227.I9ecpLcQZZ47Wrm82d-qMSDOzcmvbXUSlgD_VSYMUrgscenes-app-inbox-selfdrivingsection--daily-limit-reached--dark:- hash: v1.k794b7964.b552c9956f5b5a6b8c86665b5bf51a75cfd00211d35e8c0eb78887524b090817.IK2oYzKraEFQx1pz6sYjw648i8RgfiTphlBBAoqtjyI+ hash: v1.k794b7964.833c25a9d3cc97054dedf6c847dbed5e950b691a4fb6f0112e680b799928165c.lxNgsUnOCDGZyrQ43gqNUDN8JyV7tXH5Wtvb4JnJTL0scenes-app-inbox-selfdrivingsection--daily-limit-reached--light:- hash: v1.k794b7964.4d67adc5510406cd98c872278d3525be878d2c1b48b3a0c1cbf6ed6d39b6d007.c1GlBJLgWqdEOAkGRaI3nhU-UGWemHf4Hqq3U0rL6n4+ hash: v1.k794b7964.1ccf27c19c602284500dffb1a267cae43fe429b3a0258a2a1a7f15e620f4aa99.4cj1fYQYYGq2dT853FqyQ17HcNUV2gWI08jt5Pf7zlAscenes-app-inbox-selfdrivingsection--daily-limit-set--dark:hash: v1.k794b7964.3fa4e975d9966a9bc3557d63ff5017a07d8b2428cec986c16f386c8d0f341022.UVEV2Z_N7DdU_THXbBI8uEURPwirfncvsbjodaYYmVYscenes-app-inbox-selfdrivingsection--daily-limit-set--light:hash: v1.k794b7964.219716b5c72f7c5fc968cd475c15536bf10734cff3200a34c89f162f3ab62b80.j-EMqzNiG7OjMvEVhhQkAYxwkbvWKi3iSsGmwaFN1I0scenes-app-inbox-selfdrivingsection--disabled--dark:- hash: v1.k794b7964.356b45822035a24f8a6d2470546f47ab97e2ce7a6920ab5ab6c7e758c0b09527.d4B_z-KCjjbEvdn7tHYzYZyMlBWUJPz6PIO6pJQAYhw+ hash: v1.k794b7964.fe0b43978b5f6f9a34e4674503a972599fbaabe45ee4937b25e6a68067aa120a.Vh_Uto5i_c36XFOiFkp32jmxfz4luh-U3B7Lq49vxzQscenes-app-inbox-selfdrivingsection--disabled--light:- hash: v1.k794b7964.c68ce60f96bf110f9138efe005febc6502ec3892f94e0ebb913886fbad7b41bb.M6beePjYmpPnl--ln_30DXADcEOn3PDMwhG8jgfdqxM+ hash: v1.k794b7964.ee93e3b9bb5b4b372cffc1daa9e0b35c9a9e6dd7ec9339b07781e5ecce8a6a7b.FfOQBXsVG2nKZeMOAcQzvJuLRhrlnC63aqJdg6VI_1Ascenes-app-inbox-selfdrivingsection--git-hub-assignment-on--dark:- hash: v1.k794b7964.d3914b7ba024e1ec5701e1cdabcd22ae2b35bf01e7302c7787eafd8291ac4d7b.ZGIeUKjF07sjbVZ6nSTVJMIr_725KuAQCB5YFaauWbg+ hash: v1.k794b7964.75e207df5a376765346c96174f733fe59775363bb093edf12a99eb6ebf8c7c80.Uk3T1D8eNvCRwAZVhVLCWgutZQMrAaBSHW7PAhCXPy8scenes-app-inbox-selfdrivingsection--git-hub-assignment-on--light:- hash: v1.k794b7964.4ec0418b27d02987dee36437efae8e5da7b563f040ee4436d86d583a347aba45.yneCokblzCiuIyXV0AeRTd-6uHxfhFRznfHMnIN7FDM+ hash: v1.k794b7964.f97f75e75e8eee6b235827ac59ef866d7e221c221a2ec528a084c482fa4bc2b0._YfqT2hSPB1kQk3k_k4njuiC85uZO17eKgqGRRpOOSoscenes-app-inbox-selfdrivingsection--issue-tracker-configured--dark:- hash: v1.k794b7964.be19e707da4b6ab6fea6a519b0d98292adc24c65b3785778f88c39dbc55c45b5.clYd6voejcwUEC5cMIAVY-kF2Nq0hBzPuFTK1vxzW0M+ hash: v1.k794b7964.da38342117fa8ae6014c42db6911203a1d56699699afa960349864ba9d9f35c2.y9yF0mzBj5Gstzq-W1_jPo8-BuniKnj_VQX_0YaoAWoscenes-app-inbox-selfdrivingsection--issue-tracker-configured--light:- hash: v1.k794b7964.c6210ff2863d0727d6d789950f74e84383d1b7b5e84bdb750da3f06e659a1279.r-CqmDkAVoNB2Xm3O2I0f3W5b0XWFNbbqkWXyVkKHwM+ hash: v1.k794b7964.f5ac0ad77c941dd05efcfa2c83c91b1118d6e03068490fe472145052c567c0f4.xWIldZymU4xR4_VdN39syM4-LtwTQ6aXZs73rPwPH_Mscenes-app-inbox-selfdrivingsection--issue-tracker-unavailable--dark:- hash: v1.k794b7964.cc719ae38ec59531b78003222ff8662e86f263e35b8ea41ac8c42c09369227ab.ShzcW9Ks0KNtuLlLrx08Nl97Y5bXGEP6mBKU5cmDnkc+ hash: v1.k794b7964.2e7891ab26dbae7e2510f44f413cff3b2a7eef5bad5f0d131a5c1035cb361655.VMAo4c9Z0HdS3gmByyTtYz-xgsL9wwLLGxcienPsIvgscenes-app-inbox-selfdrivingsection--issue-tracker-unavailable--light:- hash: v1.k794b7964.5cd4422635384d0bde5d07fbc81487df9e6f7f8c14c6a9324c4985c4b32c68a2.xWbAE4IvQazaV_OlE5hiWozUYBLV4UkTJOCpby9VBgs+ hash: v1.k794b7964.24c86c24c804d234c72857d4bc91ede2424defcb84187669f7ace94cb05c9e97.iAvFq6Q1O6ImvKYAoOlzQe7x6vYex93FaI1GSSPOXgwscenes-app-inbox-selfdrivingsection--no-daily-limit--dark:hash: v1.k794b7964.3e355e2b561a2a3b3d38b00258e51531d6e9116d42129731a3c4b71bf6cb5e7e.VxAxGwO-zZ-B9OtgXOMp53Lvq5dOJjbs-qh60r-bT88scenes-app-inbox-selfdrivingsection--no-daily-limit--light:hash: v1.k794b7964.9837d5c2833b8def4c88c221e6ab65699e274a2515b210320b49f13ea0572a0a.hqgSLSsKWsmf3zXL3sEwl6kOe1jzwGeG-Fd0Zpoek70scenes-app-inbox-selfdrivingsection--personal-default--dark:- hash: v1.k794b7964.cc719ae38ec59531b78003222ff8662e86f263e35b8ea41ac8c42c09369227ab.FIvoSElhmxNRuM80-BvdlOqEtmSJZSLWDze3iAip9fQ+ hash: v1.k794b7964.2e7891ab26dbae7e2510f44f413cff3b2a7eef5bad5f0d131a5c1035cb361655.aD8rm1FJVvybW_DKodX_bZg3igdI4lEnTlsShLMjqBoscenes-app-inbox-selfdrivingsection--personal-default--light:- hash: v1.k794b7964.5cd4422635384d0bde5d07fbc81487df9e6f7f8c14c6a9324c4985c4b32c68a2.VyT07ldKlDmkAaFMwNQyw_US7EZkZSGJ3iWe5MOEmaw+ hash: v1.k794b7964.24c86c24c804d234c72857d4bc91ede2424defcb84187669f7ace94cb05c9e97.nqZZSGkteO2jVA-fkWwMp28FcKvdJwSHNTxtm-9UBCEscenes-app-inbox-selfdrivingsection--personal-override--dark:hash: v1.k794b7964.aa42dc763078e1431c621efad3dae9f298485890910510fccd861fb1bc9f7d77.Go-OjRKiACFptGQ39DNGs4H4H83nh48PwJQBaoW59CIscenes-app-inbox-selfdrivingsection--personal-override--light:hash: v1.k794b7964.11bb568d4acedc2c8471037b636ccceffd9d5132b2831c86911cb3c03dc0e761.Av0epOul8ebcU34b5lat7cvdImPzSkTHhwuYPkfV3WAscenes-app-inbox-selfdrivingsection--pull-request-ready-for-review--dark:- hash: v1.k794b7964.6e31905b3f878f3cb1be53adf4c6fd68795fe70d276735dc2468247cbdd0e754.ze8xkMkOZUFemvscgrTpm21_RDh_1GeFMJrSZyTZ6xc+ hash: v1.k794b7964.61d267c06579d429695694aeb8965b7baee948c49315afdb0ebfd88f85c6b4a7.WKG1q7jFy7Y5Wb_sQJE9gJ-YvFwnLHn7N24dC5Sz7uoscenes-app-inbox-selfdrivingsection--pull-request-ready-for-review--light:- hash: v1.k794b7964.9514ba4604e35f46cb598fe1ffc0c4302300c6978cc76f42f8b89c6135f6b629.VhrSJsMWlmzJzVDMDUmfqJpskAsRJ0Dxe3gApxUbKVo+ hash: v1.k794b7964.7a06f93ef8eb6ffb7a1f931221b77be7faf99d70f924e25972e2e1e2e808ea6e.gO-Z9ycEHRYf6X79K3HbXdmxAtcZ6fvgIAvAQ-3F_NQscenes-app-inbox-signal-cards--all-sources--dark:hash: v1.k794b7964.8220c14a1dc6de9d9aa2fa2fa829bff1d19230cf7cdb947906b3fee3ead37d98.BBzXUXAId7C0u5sasTEYZBdaqZjXRU20paQFY6thp3sscenes-app-inbox-signal-cards--all-sources--light:diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 5182f2fa3495..b5bdecdd8a95 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -379,6 +379,7 @@ field_name_overrides: dict[AuditableScope, dict[str, str]] = {"issue_tracking_integration": "issue tracker","issue_tracking_config": "issue tracker target","default_open_pull_request_ready": "PRs open as",+ "github_issue_writeback_enabled": "comment back on GitHub issues",},"OAuthApplication": {"_provisioning_config": "provisioning config",diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex 7be28a97c1f6..44493acfc35d 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -111,7 +111,11 @@ class GitHubCommitAttribution:@frozenclass PullRequestRef:- """A pull request's coordinates, parsed from its GitHub HTML URL."""+ """A pull request or an issue's coordinates, parsed from its GitHub HTML URL.++ One shape for both, because GitHub numbers issues and pull requests in one sequence per+ repository and answers for both on the issues endpoints.+ """owner: strrepo: str@@ -1015,27 +1019,40 @@ class GitHubIntegrationBase:return attributions@staticmethod- def parse_pull_request_url(pr_url: str) -> PullRequestRef | None:- """Parse a GitHub pull request URL into a :class:`PullRequestRef`.+ def _parse_repo_item_url(url: str, item_path: str) -> PullRequestRef | None:+ """Parse a ``/{owner}/{repo}/{item_path}/{number}[/...]`` GitHub URL.- Returns ``None`` if the URL does not look like a GitHub PR URL.+ Returns ``None`` when the URL is not one. Only the first four path segments are read, so a+ caller that rebuilds an API path from the result cannot be steered by anything after them."""try:- parsed = urlparse(pr_url)+ parsed = urlparse(url)except Exception:return Noneif parsed.netloc not in {"github.com", "www.github.com"}:return Noneparts = [p for p in parsed.path.split("/") if p]- # Expected path: /{owner}/{repo}/pull/{number}[/...]- if len(parts) < 4 or parts[2] != "pull":+ if len(parts) < 4 or parts[2] != item_path:+ return None+ owner, repo, _, number_str = parts[:4]+ if not number_str.isdigit():return None- owner, repo, _, pr_number_str = parts[:4]try:- pr_number = int(pr_number_str)+ # ``isdigit`` is true for digits ``int`` rejects, such as a superscript.+ number = int(number_str)except ValueError:return None- return PullRequestRef(owner=owner, repo=repo, number=pr_number)+ return PullRequestRef(owner=owner, repo=repo, number=number)++ @staticmethod+ def parse_pull_request_url(pr_url: str) -> PullRequestRef | None:+ """Parse a GitHub pull request URL. Returns ``None`` when the URL is not one."""+ return GitHubIntegrationBase._parse_repo_item_url(pr_url, "pull")++ @staticmethod+ def parse_issue_url(issue_url: str) -> PullRequestRef | None:+ """Parse a GitHub issue URL. Returns ``None`` when the URL is not one."""+ return GitHubIntegrationBase._parse_repo_item_url(issue_url, "issues")def get_pull_request(self, repository: str, pr_number: int) -> dict[str, Any]:"""Fetch a pull request by repository (``owner/repo`` or just ``repo``) and PR number."""diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.pyindex ee5b62dc3365..24ddd6f3ab7e 100644--- a/posthog/models/test/integration/test_github.py+++ b/posthog/models/test/integration/test_github.py@@ -76,6 +76,21 @@ class TestExtractFailingChecks(SimpleTestCase):assert (failing == [{"key": "CI/unit tests", "details_url": "https://ci/1"}]) is expected_reported+class TestParseRepoItemUrl(SimpleTestCase):+ @parameterized.expand(+ [+ ("a superscript digit", "²"),+ ("more digits than int converts", "1" * 4301),+ ]+ )+ def test_a_number_int_rejects_reads_as_no_reference(self, _name, number_str):+ pr_url = f"https://github.com/acme/widgets/pull/{number_str}"+ issue_url = f"https://github.com/acme/widgets/issues/{number_str}"++ assert GitHubIntegrationBase.parse_pull_request_url(pr_url) is None+ assert GitHubIntegrationBase.parse_issue_url(issue_url) is None++class TestGitHubIntegrationModel(BaseTest):def setUp(self):super().setUp()diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex 3f2982def728..8d4f358b1c16 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -121,6 +121,7 @@ class TestSignalsProductModuleIntegrity:expected_activities = ["dispatch_inbox_slack_notifications_activity","get_inbox_notification_state_activity",+ "send_report_github_comments_activity","send_report_inbox_notifications_activity","emit_backfill_signal_activity","fetch_error_tracking_issues_activity",diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex bccac2f84216..971835601824 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -532,19 +532,26 @@ Notes:Per-team singleton config for Signals settings, including the default autonomy priority threshold.-| Field | Type | Description |-| ---------------------------- | --------------- | ---------------------------------------------------------------------------- |-| `id` | UUID (PK) | Primary key (UUIDModel) |-| `team` | OneToOne → Team | Owning team (`related_name="signal_team_config"`) |-| `default_autostart_priority` | CharField | Default severity threshold for auto-start (`P0`–`P4`, where `P0` is highest) |-| `created_at` | DateTime | Auto-set on creation |-| `updated_at` | DateTime | Auto-set on save |+| Field | Type | Description |+| -------------------------------- | --------------- | ---------------------------------------------------------------------------- |+| `id` | UUID (PK) | Primary key (UUIDModel) |+| `team` | OneToOne → Team | Owning team (`related_name="signal_team_config"`) |+| `default_autostart_priority` | CharField | Default severity threshold for auto-start (`P0`–`P4`, where `P0` is highest) |+| `github_issue_writeback_enabled` | Boolean | Opt-in public comments on source GitHub issues. Defaults to `false`. |+| `created_at` | DateTime | Auto-set on creation |+| `updated_at` | DateTime | Auto-set on save |Notes:- Auto-created as a team extension via `register_team_extension_signal`- `default_autostart_priority` defaults to `P4` (every report priority auto-starts). The inbox UI exposes it as the "Project threshold" control on the PR generation card.- `SignalUserAutonomyConfig.autostart_priority` holds a per-user override (`null` = use the team default). The inbox UI exposes it as the "My threshold" control on the same card, where a "Default" segment maps to `null` and inherits the project threshold.+- `github_issue_writeback_enabled` adds a report link to each source GitHub issue after the report notification completes. The comment contains no report title or research. The report requires project access.+- GitHub comments run in a separate Temporal activity on every settle, including settles after the first notification. GitHub failures cannot prevent the report notification.+- `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.+- See [GitHub issue comments](../../docs/internal/signals-github-writeback.md) for recovery limits and diagnostic logs.### `SignalUserAutonomyConfig`diff --git a/products/signals/backend/github_writeback.py b/products/signals/backend/github_writeback.pynew file mode 100644index 000000000000..6f5fbf88b2f6--- /dev/null+++ b/products/signals/backend/github_writeback.py@@ -0,0 +1,221 @@+"""Tells a GitHub issue that raised a report that self-driving has looked at it.++A GitHub issue flows into the inbox as a signal, gets researched against the codebase, and the+result lands in the inbox only. Nobody watching the issue hears anything, so a maintainer or an+outside contributor can start on work we already research. This comments a link to the report back+on the issue, which closes that loop. Opt-in per team, because the comment is public on the issue+thread.+"""++from __future__ import annotations++from datetime import timedelta++from django.conf import settings+from django.utils import timezone++import structlog++from posthog.egress.limiter.policies import Priority+from posthog.models import Team+from posthog.models.github_integration_base import GitHubIntegrationBase, PullRequestRef+from posthog.models.integration import GitHubIntegration++from products.signals.backend.enums import SignalSourceProduct, SignalSourceType+from products.signals.backend.models import SignalReport, SignalReportGithubComment, SignalTeamConfig++logger = structlog.get_logger(__name__)++EGRESS_SOURCE = "signals_github_writeback"+CLAIM_LEASE = timedelta(minutes=10)+MAX_COMMENT_PAGES = 10+++def _comment_body(report_url: str, marker: str) -> str:+ """A pointer, deliberately carrying none of the report's own content.++ The comment is public on the issue thread, while the report is behind the PostHog project's own+ access check. Copying the title or the summary here would publish research that only the project+ is entitled to, so the comment says the work exists and links to it.+ """+ return (+ "PostHog self-driving picked up this issue and researched it. Somebody may already be "+ f"working on it, so ask before you start a fix.\n\nReport (team access only): {report_url}\n\n{marker}"+ )+++def _issue_refs(signals: list[dict]) -> list[PullRequestRef]:+ """The open GitHub issues among a report's signals, each one once.++ A closed issue is answered already, and a locked one refuses comments, so neither is worth a+ call.+ """+ refs: dict[tuple[str, int], PullRequestRef] = {}+ for signal in signals:+ if (+ signal.get("source_product") != SignalSourceProduct.GITHUB+ or signal.get("source_type") != SignalSourceType.ISSUE+ ):+ continue+ extra = signal.get("extra") or {}+ if extra.get("locked") or str(extra.get("state") or "").lower() != "open":+ continue+ ref = GitHubIntegrationBase.parse_issue_url(str(extra.get("html_url") or ""))+ if ref is not None:+ refs.setdefault((ref.repository.lower(), ref.number), ref)+ return list(refs.values())+++def _has_existing_comment(github: GitHubIntegration, repository: str, number: int, marker: str) -> bool | None:+ # An incomplete read cannot prove that a previous POST failed.+ for page in range(1, MAX_COMMENT_PAGES + 1):+ response = github.api_request(+ "GET",+ f"/repos/{repository}/issues/{number}/comments",+ endpoint="/repos/{owner}/{repo}/issues/{issue_number}/comments",+ params={"per_page": 100, "page": page},+ retry_transient=False,+ )+ response.raise_for_status()+ comments = response.json()+ if not isinstance(comments, list):+ return None+ if any(isinstance(comment, dict) and marker in str(comment.get("body") or "") for comment in comments):+ return True+ if len(comments) < 100:+ return False+ return None+++def _post_to_issue(+ *,+ team_id: int,+ report_id: str,+ ref: PullRequestRef,+ body: str,+ marker: str,+ integrations: dict[str, GitHubIntegration | None],+) -> bool:+ """Comment on one issue, once per (report, issue). Returns whether a comment went out.++ Pending claims survive uncertain POST outcomes. After the lease expires, a later settle checks+ for the stable comment marker before it retries. The lease exceeds the activity timeout.++ ``integrations`` memoizes the integration per repository for one run, because resolving one+ costs an authenticated GitHub call per integration the team has.+ """+ # GitHub compares a repository path without case, while the unique constraint below does not,+ # so the raw spelling would let a case-only rename claim a second row and comment twice.+ repository = ref.repository.lower()++ # for_team scopes the lookup; get_or_create still needs team_id in the defaults, because a+ # queryset filter does not propagate into the row it creates.+ claim, created = SignalReportGithubComment.objects.for_team(team_id).get_or_create(+ report_id=report_id,+ repository=repository,+ number=ref.number,+ defaults={"team_id": team_id},+ )+ if claim.commented_at is not None:+ return False++ claims = SignalReportGithubComment.objects.for_team(team_id).filter(pk=claim.pk, commented_at__isnull=True)+ if not created:+ acquired_at = timezone.now()+ if not claims.filter(updated_at__lt=acquired_at - CLAIM_LEASE).update(updated_at=acquired_at):+ return False+ claim.updated_at = acquired_at+ owned_claim = claims.filter(updated_at=claim.updated_at)++ try:+ if repository not in integrations:+ # Background comments must leave the interactive GitHub budget available.+ integrations[repository] = GitHubIntegration.first_for_team_repository(+ team_id, repository, source=EGRESS_SOURCE, priority=Priority.BATCH+ )+ github = integrations[repository]+ if github is None:+ return False+ if not created:+ existing = _has_existing_comment(github, repository, ref.number, marker)+ if existing is not False:+ if existing:+ owned_claim.update(commented_at=timezone.now())+ return False++ response = github.api_request(+ "GET",+ f"/repos/{repository}/issues/{ref.number}",+ endpoint="/repos/{owner}/{repo}/issues/{issue_number}",+ retry_transient=False,+ )+ response.raise_for_status()+ issue = response.json()+ if (+ not isinstance(issue, dict)+ or issue.get("state") != "open"+ or issue.get("locked") is not False+ or "pull_request" in issue+ ):+ return False+ if not owned_claim.filter(updated_at__gt=timezone.now() - CLAIM_LEASE).exists():+ return False+ outcome = github.comment_on_issue(repository, ref.number, body)+ except Exception:+ logger.exception(+ "signals.github_writeback_failed",+ report_id=report_id,+ team_id=team_id,+ repository=repository,+ number=ref.number,+ )+ return False++ if not outcome.get("success"):+ logger.warning(+ "signals.github_writeback_failed",+ report_id=report_id,+ team_id=team_id,+ repository=repository,+ number=ref.number,+ error=outcome.get("error"),+ )+ return False++ owned_claim.update(commented_at=timezone.now())+ return True+++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.++ Returns the number of comments posted. Best-effort: a failure here must not fail the report's+ notification flow, so per-issue errors are logged rather than raised.+ """+ if not SignalTeamConfig.objects.filter(team_id=team.pk, github_issue_writeback_enabled=True).exists():+ return 0++ refs = _issue_refs(signals)+ if not refs:+ return 0++ if not SignalReport.objects.filter(id=report_id, team_id=team.pk, status=SignalReport.Status.READY).exists():+ return 0++ marker = f"<!-- posthog:signal-report:{report_id} -->"+ body = _comment_body(f"{settings.SITE_URL}/project/{team.pk}/inbox/reports/{report_id}", marker)+ integrations: dict[str, GitHubIntegration | None] = {}+ posted = sum(+ _post_to_issue(+ team_id=team.pk, report_id=report_id, ref=ref, body=body, marker=marker, integrations=integrations+ )+ for ref in refs+ )+ logger.info(+ "signals.github_writeback_posted",+ report_id=report_id,+ team_id=team.pk,+ issues=len(refs),+ posted=posted,+ )+ return posteddiff --git a/products/signals/backend/migrations/0133_github_issue_writeback.py b/products/signals/backend/migrations/0133_github_issue_writeback.pynew file mode 100644index 000000000000..1eccae16a1b8--- /dev/null+++ b/products/signals/backend/migrations/0133_github_issue_writeback.py@@ -0,0 +1,66 @@+# Generated by Django 5.2.17 on 2026-09-13 15:42++import django.db.models.manager+import django.db.models.deletion+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1352_email_lookup_indexes"),+ ("signals", "0132_signalscoutconfig_repositories"),+ ]++ operations = [+ migrations.AddField(+ model_name="signalteamconfig",+ name="github_issue_writeback_enabled",+ field=models.BooleanField(db_default=False, default=False),+ ),+ migrations.CreateModel(+ name="SignalReportGithubComment",+ fields=[+ (+ "id",+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),+ ),+ ("repository", models.CharField(max_length=200)),+ ("number", models.PositiveBigIntegerField()),+ ("commented_at", models.DateTimeField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "report",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="github_comments",+ to="signals.signalreport",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "verbose_name": "Signal report GitHub comment",+ "verbose_name_plural": "Signal report GitHub comments",+ "default_manager_name": "all_teams",+ "constraints": [+ models.UniqueConstraint(+ fields=("report", "repository", "number"), name="signals_report_github_comment_unique"+ )+ ],+ },+ managers=[+ ("all_teams", django.db.models.manager.Manager()),+ ],+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex a149d00ed0bf..aa0e3a13d68a 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0132_signalscoutconfig_repositories+0133_github_issue_writebackdiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 00fb9ceda559..c00e96dedd80 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -182,6 +182,10 @@ class SignalTeamConfig(ModelActivityMixin, UUIDModel):# Off by default, because a ready pull request runs the full CI matrix on every push, which is# runner spend a team has to choose. Read only for a reviewer with no preference of their own.default_open_pull_request_ready = models.BooleanField(default=False, db_default=False)+ # Comment back on a GitHub issue that raised a report, pointing at the report (see+ # github_writeback.py). Off by default, because the comment is public on the issue thread and+ # tells everybody watching it that we are working on it, which is a team's call to make.+ github_issue_writeback_enabled = models.BooleanField(default=False, db_default=False)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)@@ -968,6 +972,39 @@ class SignalReportTrackerIssue(TeamScopedRootMixin, UUIDModel):verbose_name_plural = "Signal report tracker issues"+class SignalReportGithubComment(TeamScopedRootMixin, UUIDModel):+ """A comment self-driving posted on a GitHub issue that raised a report.++ One row per (report, issue). The row is the claim: it is taken before the comment goes out, so a+ re-notified report cannot post a second comment on the same issue, and it records which issues+ already heard back.+ """++ all_teams = models.Manager() # noqa: DJ012++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")+ report = models.ForeignKey(SignalReport, on_delete=models.CASCADE, related_name="github_comments")++ # "organization/repository", lowercased: GitHub compares it without case, this column does not.+ repository = models.CharField(max_length=200)+ number = models.PositiveBigIntegerField()+ # Null while the claim is held, set once GitHub accepted the comment.+ commented_at = models.DateTimeField(null=True, blank=True)++ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ default_manager_name = "all_teams"+ constraints = [+ models.UniqueConstraint(+ fields=["report", "repository", "number"], name="signals_report_github_comment_unique"+ ),+ ]+ verbose_name = "Signal report GitHub comment"+ verbose_name_plural = "Signal report GitHub comments"++class SignalReportPullRequest(TeamScopedRootMixin, UUIDModel):State = SignalReportAssignment.PrStatediff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex b5faff334cd2..9a2084e15440 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -320,6 +320,15 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):"github_open_pull_request_ready overrides this for reports that suggest them as reviewer."),)+ github_issue_writeback_enabled = serializers.BooleanField(+ required=False,+ help_text=(+ "Whether self-driving comments back on a GitHub issue that raised a report, linking to "+ "the report so everybody watching the issue knows it is being researched. The comment is "+ "public on the issue thread and carries a link only, never report content. False by "+ "default. Needs a GitHub integration that can reach the issue's repository."+ ),+ )reports_generated_today = serializers.SerializerMethodField(help_text=("How many reports first became visible in the inbox during the current project-timezone "@@ -368,6 +377,7 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):"issue_tracking_config","max_reports_per_day","default_open_pull_request_ready",+ "github_issue_writeback_enabled","reports_generated_today","daily_report_limit_reached","created_at",diff --git a/products/signals/backend/temporal/__init__.py b/products/signals/backend/temporal/__init__.pyindex 94266896aff9..53df1732f020 100644--- a/products/signals/backend/temporal/__init__.py+++ b/products/signals/backend/temporal/__init__.py@@ -47,6 +47,7 @@ from products.signals.backend.temporal.grouping_v2 import TeamSignalGroupingV2Wofrom products.signals.backend.temporal.inbox_notification import (SignalReportInboxNotificationWorkflow,get_inbox_notification_state_activity,+ send_report_github_comments_activity,send_report_inbox_notifications_activity,)from products.signals.backend.temporal.reingestion import (@@ -108,6 +109,7 @@ WORKFLOWS = [ACTIVITIES = [dispatch_inbox_slack_notifications_activity,get_inbox_notification_state_activity,+ send_report_github_comments_activity,send_report_inbox_notifications_activity,emit_backfill_signal_activity,fetch_error_tracking_issues_activity,diff --git a/products/signals/backend/temporal/inbox_notification.py b/products/signals/backend/temporal/inbox_notification.pyindex c728fbf2798d..f74ae317b697 100644--- a/products/signals/backend/temporal/inbox_notification.py+++ b/products/signals/backend/temporal/inbox_notification.py@@ -26,7 +26,8 @@ from posthog.models import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.scoped import scoped_temporal-from products.signals.backend.models import SignalReport+from products.signals.backend.github_writeback import post_report_link_to_github_issues+from products.signals.backend.models import SignalReport, SignalTeamConfigfrom products.signals.backend.support_writeback import post_report_findings_to_ticketsfrom products.signals.backend.task_run_artefacts import SIGNALS_PRODUCT, TASK_RUN_TYPE_IMPLEMENTATIONfrom products.signals.backend.temporal.signal_queries import fetch_signals_for_report_sync@@ -182,6 +183,23 @@ async def send_report_inbox_notifications_activity(input: InboxNotificationInput)+def _send_report_github_comments(team_id: int, report_id: str) -> int:+ if not SignalTeamConfig.objects.filter(team_id=team_id, github_issue_writeback_enabled=True).exists():+ return 0+ team = Team.objects.filter(id=team_id).first()+ if team is None:+ return 0+ return post_report_link_to_github_issues(team, report_id, fetch_signals_for_report_sync(team, report_id))+++@scoped_temporal()+async def send_report_github_comments_activity(input: InboxNotificationInput) -> int:+ return await database_sync_to_async(_send_report_github_comments, thread_sensitive=False)(+ input.team_id, input.report_id+ )++@temporalio.workflow.defn(name="signal-report-inbox-notification")class SignalReportInboxNotificationWorkflow:@staticmethod@@ -256,6 +274,16 @@ class SignalReportInboxNotificationWorkflow:"inbox notification: dispatch complete",extra={**log_ctx, "messages_sent": sent, "pr_available": state.pr_available},)+ if workflow.patched("signals-github-writeback-after-notification"):+ try:+ await workflow.execute_activity(+ send_report_github_comments_activity,+ inputs,+ start_to_close_timeout=timedelta(minutes=5),+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ except temporalio.exceptions.ActivityError:+ workflow.logger.exception("inbox notification: GitHub write-back failed", extra=log_ctx)return sentasync def _fetch_state(self, inputs: InboxNotificationInput) -> InboxNotificationState:diff --git a/products/signals/backend/test/test_github_writeback.py b/products/signals/backend/test/test_github_writeback.pynew file mode 100644index 000000000000..6adc6d5eda44--- /dev/null+++ b/products/signals/backend/test/test_github_writeback.py@@ -0,0 +1,213 @@+import pytest+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.utils import timezone++from parameterized import parameterized++from 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++WRITEBACK_MODULE_PATH = "products.signals.backend.github_writeback"+++def _signal(**extra):+ return {+ "source_product": "github",+ "source_type": "issue",+ "source_id": "2001",+ "content": "exports time out on large date ranges",+ "extra": {+ "html_url": "https://github.com/acme/widgets/issues/42",+ "number": 42,+ "state": "open",+ "locked": False,+ **extra,+ },+ }+++class TestPostReportLinkToGithubIssues(BaseTest):+ def setUp(self):+ super().setUp()+ SignalTeamConfig.objects.update_or_create(team=self.team, defaults={"github_issue_writeback_enabled": True})+ self.report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="fix(exports): page the date range",+ summary="The exporter loads the whole range into memory.",+ )+ self.signal = _signal()++ def _post(self, signals, *, issue=None):+ with patch(f"{WRITEBACK_MODULE_PATH}.GitHubIntegration") as integration:+ github = integration.first_for_team_repository.return_value+ github.api_request.return_value.json.return_value = (+ issue if issue is not None else {"state": "open", "locked": False}+ )+ comment = github.comment_on_issue+ comment.return_value = {"success": True}+ posted = post_report_link_to_github_issues(self.team, str(self.report.id), signals)+ return posted, comment++ def test_comments_a_link_to_the_report_on_the_issue(self):+ posted, comment = self._post([self.signal])++ assert posted == 1+ comment.assert_called_once()+ repository, number, body = comment.call_args.args+ assert (repository, number) == ("acme/widgets", 42)+ assert f"/project/{self.team.pk}/inbox/reports/{self.report.id}" in body++ def test_comment_carries_no_report_content(self):+ # The comment is public on the issue thread while the report is behind the project's access+ # check, so it must not publish the research itself.+ _, comment = self._post([self.signal])++ body = comment.call_args.args[2]+ assert self.report.title not in body+ assert "into memory" not in body++ @parameterized.expand(+ [+ ("the same url", "https://github.com/acme/widgets/issues/42"),+ ("the repository renamed to another case", "https://github.com/Acme/Widgets/issues/42"),+ ]+ )+ def test_is_idempotent_across_retries(self, _name, later_html_url):+ first, _ = self._post([self.signal])+ second, comment = self._post([_signal(html_url=later_html_url)])++ assert (first, second) == (1, 0)+ assert comment.call_count == 0+ assert SignalReportGithubComment.objects.for_team(self.team.pk).count() == 1++ def test_does_nothing_until_the_team_opts_in(self):+ SignalTeamConfig.objects.filter(team=self.team).update(github_issue_writeback_enabled=False)++ posted, comment = self._post([self.signal])++ assert posted == 0+ assert comment.call_count == 0++ @parameterized.expand(+ [+ ("another product", {"source_product": "error_tracking", "source_type": "issue", "extra": {}}),+ ("another source type", {"source_product": "github", "source_type": "issue_created", "extra": {}}),+ ("closed issue", _signal(state="closed")),+ ("locked issue", _signal(locked=True)),+ ("pull request url", _signal(html_url="https://github.com/acme/widgets/pull/42")),+ ("foreign host", _signal(html_url="https://evil.example.com/acme/widgets/issues/42")),+ ("no issue number", _signal(html_url="https://github.com/acme/widgets/issues/new")),+ ]+ )+ def test_leaves_everything_that_is_not_an_open_github_issue_alone(self, _name, signal):+ posted, comment = self._post([signal])++ assert posted == 0+ assert comment.call_count == 0++ def test_resolves_the_repository_once_for_two_issues_in_it(self):+ other_issue = _signal(html_url="https://github.com/acme/widgets/issues/43", number=43)++ with patch(f"{WRITEBACK_MODULE_PATH}.GitHubIntegration") as integration:+ integration.first_for_team_repository.return_value.api_request.return_value.json.return_value = {+ "state": "open",+ "locked": False,+ }+ integration.first_for_team_repository.return_value.comment_on_issue.return_value = {"success": True}+ posted = post_report_link_to_github_issues(self.team, str(self.report.id), [self.signal, other_issue])++ assert posted == 2+ # Resolving an integration costs an authenticated GitHub call per integration the team has.+ assert integration.first_for_team_repository.call_count == 1++ def test_asks_for_the_lane_the_limiter_sheds_first(self):+ with patch(f"{WRITEBACK_MODULE_PATH}.GitHubIntegration") as integration:+ integration.first_for_team_repository.return_value.comment_on_issue.return_value = {"success": True}+ post_report_link_to_github_issues(self.team, str(self.report.id), [self.signal])++ assert integration.first_for_team_repository.call_args.kwargs["priority"] == Priority.BATCH++ def test_comments_once_when_two_signals_name_the_same_issue(self):+ posted, comment = self._post([self.signal, _signal()])++ assert posted == 1+ assert comment.call_count == 1++ @parameterized.expand(+ [+ ("closed", {"state": "closed", "locked": False}),+ ("locked", {"state": "open", "locked": True}),+ ("pull request", {"state": "open", "locked": False, "pull_request": {}}),+ ]+ )+ def test_rechecks_the_current_issue_before_posting(self, _name, issue):+ posted, comment = self._post([self.signal], issue=issue)+ assert posted == 0+ comment.assert_not_called()++ @parameterized.expand([("accepted", True, 0), ("not accepted", False, 1)])+ def test_reconciles_an_uncertain_post_after_the_lease_expires(self, _name, accepted, expected_posts):+ with patch(f"{WRITEBACK_MODULE_PATH}.GitHubIntegration") as integration:+ github = integration.first_for_team_repository.return_value+ github.api_request.return_value.json.return_value = {"state": "open", "locked": False}+ github.comment_on_issue.return_value = {+ "success": False,+ "error": "Failed to comment on issue",+ }+ failed = post_report_link_to_github_issues(self.team, str(self.report.id), [self.signal])+ body = github.comment_on_issue.call_args.args[2]++ assert failed == 0+ claim = SignalReportGithubComment.objects.for_team(self.team.pk).get()+ assert claim.commented_at is None+ immediate, comment = self._post([self.signal])+ assert immediate == 0+ comment.assert_not_called()++ SignalReportGithubComment.objects.for_team(self.team.pk).filter(pk=claim.pk).update(+ updated_at=timezone.now() - CLAIM_LEASE+ )+ with patch(f"{WRITEBACK_MODULE_PATH}.GitHubIntegration") as integration:+ github = integration.first_for_team_repository.return_value+ github.api_request.side_effect = [+ MagicMock(json=lambda: [{"body": "unrelated"}] * 100),+ MagicMock(json=lambda: [{"body": body}] if accepted else []),+ MagicMock(json=lambda: {"state": "open", "locked": False}),+ ]+ github.comment_on_issue.return_value = {"success": True}+ retried = post_report_link_to_github_issues(self.team, str(self.report.id), [self.signal])+ assert retried == expected_posts+ assert github.comment_on_issue.call_count == expected_posts+ claim.refresh_from_db()+ assert claim.commented_at is not None++ @parameterized.expand([("incomplete", [{"body": "unrelated"}] * 100), ("invalid", {})])+ def test_does_not_retry_when_the_comment_read_is_incomplete(self, _name, comments):+ claim = SignalReportGithubComment.objects.for_team(self.team.pk).create(+ team=self.team, report=self.report, repository="acme/widgets", number=42+ )+ SignalReportGithubComment.objects.for_team(self.team.pk).filter(pk=claim.pk).update(+ updated_at=timezone.now() - CLAIM_LEASE+ )+ with patch(f"{WRITEBACK_MODULE_PATH}.GitHubIntegration") as integration:+ github = integration.first_for_team_repository.return_value+ github.api_request.return_value.json.return_value = comments+ assert post_report_link_to_github_issues(self.team, str(self.report.id), [self.signal]) == 0+ github.comment_on_issue.assert_not_called()+ assert github.api_request.call_count <= MAX_COMMENT_PAGES+ claim.refresh_from_db()+ assert claim.commented_at is None++ def test_skips_a_repository_no_integration_can_reach(self):+ with patch(f"{WRITEBACK_MODULE_PATH}.GitHubIntegration") as integration:+ integration.first_for_team_repository.return_value = None+ posted = post_report_link_to_github_issues(self.team, str(self.report.id), [self.signal])++ assert posted == 0+ assert SignalReportGithubComment.objects.for_team(self.team.pk).get().commented_at is Nonediff --git a/products/signals/backend/test/test_inbox_notification_workflow.py b/products/signals/backend/test/test_inbox_notification_workflow.pyindex e421e27eb98e..15a17503d2b1 100644--- a/products/signals/backend/test/test_inbox_notification_workflow.py+++ b/products/signals/backend/test/test_inbox_notification_workflow.py@@ -8,6 +8,7 @@ from django.test import override_settingsfrom django.utils import timezonefrom temporalio import activity+from temporalio.exceptions import ApplicationErrorfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker@@ -124,6 +125,8 @@ class _Recorder:self._states = statesself.state_calls = 0self.dispatch_calls = 0+ self.github_calls = 0+ self.github_fails = Falsedef next_state(self) -> InboxNotificationState:state = self._states[min(self.state_calls, len(self._states) - 1)]@@ -141,12 +144,20 @@ async def _run_workflow(recorder: _Recorder) -> int:recorder.dispatch_calls += 1return 1+ @activity.defn(name="send_report_github_comments_activity")+ async def fake_github(_input: InboxNotificationInput) -> int:+ assert recorder.dispatch_calls == 1+ recorder.github_calls += 1+ if recorder.github_fails:+ raise ApplicationError("GitHub unavailable", non_retryable=True)+ return 1+async with await WorkflowEnvironment.start_time_skipping() as env:async with Worker(env.client,task_queue=TASK_QUEUE,workflows=[SignalReportInboxNotificationWorkflow],- activities=[fake_state, fake_dispatch],+ activities=[fake_state, fake_dispatch, fake_github],workflow_runner=UnsandboxedWorkflowRunner(),):return await env.client.execute_workflow(@@ -209,10 +220,6 @@ async def test_workflow_notifies_even_without_pr(states, timeout_seconds, polls)@pytest.mark.django_dbdef test_send_stamps_the_report_and_refuses_a_second_send(team):- """One report, one card. A report re-researches whenever a new signal carries it to its next- bucket, and every settle starts this workflow again, so the second send must be refused. The- support write-back still runs on both, because its note is per ticket rather than per report: a- ticket that joins the report after its card has had no note yet and still needs one."""report = _make_report(team)with (patch("products.signals.backend.slack_inbox_notifications.dispatch_inbox_item_notifications") as dispatch,@@ -229,6 +236,17 @@ def test_send_stamps_the_report_and_refuses_a_second_send(team):assert report.inbox_notified_at is not None[email protected]("state", [NO_TASK, ALREADY_NOTIFIED])[email protected]("github_fails", [False, True])+async def test_github_writeback_runs_after_dispatch_and_cannot_fail_the_notification(state, github_fails):+ recorder = _Recorder([state])+ recorder.github_fails = github_fails+ assert await _run_workflow(recorder) == 1+ assert recorder.dispatch_calls == 1+ assert recorder.github_calls == 1++@pytest.mark.django_db@pytest.mark.parametrize("outcome", ["sent_nothing", "raised", "raised_before_dispatch"])def test_send_releases_the_claim_when_no_card_went_out(team, outcome):diff --git a/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx b/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsxindex 2cf380bddc52..e2de7b7715a1 100644--- a/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx+++ b/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx@@ -497,6 +497,35 @@ function DailyReportLimit(): JSX.Element {)}+/**+ * Team-wide opt-in to commenting back on a GitHub issue that raised a report. Off by default,+ * because the comment is public on the issue thread. It carries a link to the report and nothing+ * else, so what the report says stays behind the project's own access check.+ */+function GitHubIssueWritebackRow(): JSX.Element {+ const { githubIssueWritebackEnabled, teamConfigUpdating } = useValues(signalTeamConfigLogic)+ const { patchTeamConfig } = useActions(signalTeamConfigLogic)++ return (+ <div className="flex items-start justify-between gap-2 px-2.5 py-1.5">+ <div className="flex flex-col gap-0.5 min-w-0 flex-1">+ <span className="text-xs text-secondary">Comment back on GitHub issues</span>+ <p className="text-[11px] text-tertiary leading-snug mb-0">+ When a GitHub issue creates a report, comment on that issue with a link to the report. Everybody+ watching the issue can see the comment.+ </p>+ </div>+ <LemonSwitch+ checked={githubIssueWritebackEnabled}+ loading={teamConfigUpdating}+ onChange={(enabled) => patchTeamConfig({ github_issue_writeback_enabled: enabled })}+ aria-label="Comment back on GitHub issues that create reports"+ data-attr="signals-github-issue-writeback"+ />+ </div>+ )+}+/*** Per-user opt-in to being added as a GitHub assignee on the implementation PR for reports that* suggest this user as reviewer. Off by default, because being assigned is visible to everybody on@@ -695,6 +724,9 @@ export function SelfDrivingSection(): JSX.Element {<div className="border-t border-primary"><PullRequestStateRows /></div>+ <div className="border-t border-primary">+ <GitHubIssueWritebackRow />+ </div><div className="border-t border-primary"><GitHubAssignmentRow /></div>diff --git a/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts b/products/signals/frontend/inbox/logics/signalTeamConfigLogic.tsindex e120c382ef42..045913be5b8d 100644--- a/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts+++ b/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts@@ -35,6 +35,7 @@ export interface signalTeamConfigLogicValues {draftBaseBranchRepo: stringdraftIssueTrackerIntegrationId: number | nulldraftMaxReportsPerDay: number | null+ githubIssueWritebackEnabled: booleanissueTrackerConfig: Record<string, string>issueTrackerIntegrationId: number | nullmaxReportsPerDay: number | null@@ -135,6 +136,7 @@ export interface signalTeamConfigLogicMeta {baseBranchOverrides: (teamConfig: SignalTeamConfig | null) => BaseBranchOverride[]maxReportsPerDay: (teamConfig: SignalTeamConfig | null) => number | nulldefaultOpenPullRequestReady: (teamConfig: SignalTeamConfig | null) => boolean+ githubIssueWritebackEnabled: (teamConfig: SignalTeamConfig | null) => booleanissueTrackerIntegrationId: (teamConfig: SignalTeamConfig | null) => number | nullissueTrackerConfig: (teamConfig: SignalTeamConfig | null) => Record<string, string>selectedIssueTrackerIntegrationId: (@@ -318,6 +320,10 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([(s) => [s.teamConfig],(teamConfig: SignalTeamConfig | null): boolean => teamConfig?.default_open_pull_request_ready ?? false,],+ githubIssueWritebackEnabled: [+ (s) => [s.teamConfig],+ (teamConfig: SignalTeamConfig | null): boolean => teamConfig?.github_issue_writeback_enabled ?? false,+ ],issueTrackerIntegrationId: [(s) => [s.teamConfig],(teamConfig: SignalTeamConfig | null): number | null => teamConfig?.issue_tracking_integration ?? null,diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.tsindex 3ff9f8f4759a..96f7d60a7787 100644--- a/products/signals/frontend/inbox/types.ts+++ b/products/signals/frontend/inbox/types.ts@@ -412,6 +412,8 @@ export interface SignalTeamConfig {max_reports_per_day?: number | null/** Whether self-driving PRs open ready for review instead of draft. A reviewer's own setting overrides it. */default_open_pull_request_ready?: boolean+ /** Whether self-driving comments a link to the report back on a GitHub issue that raised it. */+ github_issue_writeback_enabled?: boolean/** Read-only: reports that first became visible today (project timezone). Never send in a patch. */reports_generated_today?: number/** Read-only: whether the daily report limit is reached, pausing new report generation until local midnight. Never send in a patch. */