: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): open a tracker issue for each self-driving PR (#95230)
posthog[bot]36a5d3cfd707
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex c706c367a194..e12a15c33cd2 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -336,6 +336,7 @@ rules:|SignalReportAssignment|SignalReportRefund|SignalReportTask+ |SignalReportTrackerIssue|SignalRepositoryAreaActivity|SignalTeamConfig|SignalSourceConfig@@ -734,6 +735,7 @@ rules:|SignalReportAssignment|SignalReportRefund|SignalReportTask+ |SignalReportTrackerIssue|SignalRepositoryAreaActivity|SignalTeamConfig|SignalSourceConfigdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 368e62f7c488..f0c2eea39801 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7789,9 +7789,9 @@ snapshots:scenes-app-inbox-scene--self-driving-verdict-pending--light:hash: v1.k794b7964.18a04e43d0b1598e406b105dcdfe548f7d26376ad3ba606401c6795ae3ea1b1f.8uOUfAOgA04AY2GECIDr5Mf98040a17lVfVUA3QpRGMscenes-app-inbox-scene--settings--dark:- hash: v1.k794b7964.3b0dd5d698d5ee24029c00271393e53a38a1b3bea552c489cd1569c76ed0a886.Zn_fKt4Rz2_T-6UsZQNJEUSjYJF9ASDplD5GaVfJEq4+ hash: v1.k794b7964.435685ca19bb5fcb1b208fa860113032c3bfe579e939ca18b659dda8d2c2835f.YLRLqkZZipYWoNuhZn6Xq_Ae5lD_s8j9MywPBHuarHgscenes-app-inbox-scene--settings--light:- hash: v1.k794b7964.de101fcfa4421dcd9a470ba276f7ce01c4fdc2d9d2b9ccf27029ed0cf8c38bb6.0W-nF6W3ewFNHHSmHrM73Ggttlhl5TyVo97THVRBTMI+ hash: v1.k794b7964.f5e30682c7adefcbdb563be476a18576c1b6bd59d1b2e3259b0c6d04fdaa57fd.Qpi3kFMb4UkXItf4OELwnGuLhBKc4USvZYoIayXFP1Mscenes-app-inbox-scene--triage--dark:hash: v1.k794b7964.77e43b36fdcd81befecf4de80e489050f525840924ec6ddef37c23a9179dbe8a.B3qkZFYBncFaPn2EBg4cBoYu_LIwW29imNwBdLXF5eoscenes-app-inbox-scene--triage--light:@@ -7937,29 +7937,37 @@ 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.69ce4baa2544ecb014be73be66ea26b07711546838a529e1ecc31ffc34f2af56.XZMsxseOg8qWoHNMRWbgu6Ae9nlB-bPk0rLXGDa-lcs+ hash: v1.k794b7964.c9f0b2588ef2a74f4410ad5a2ebed6023da8940565710c6d29698d42c7078f6f.gxSe5pFZCt06ykzwQ157aa_guht-Kl_QYaI9HLgpUjwscenes-app-inbox-selfdrivingsection--daily-limit-reached--light:- hash: v1.k794b7964.b6721831e5715a9cfb279937c0080c13d25ed0ea3bf8460f9edd6abf8b92acbf.UxuexKk4f3iuOl3ZMz3tPeOL40pDsnUUp66p5isN5iA+ hash: v1.k794b7964.c02491a0ac406a9f43a25a3c402d835875a2863417a902c1a858dc8843c3bd3c.E1uGSqsZQbR45Fi_SpQ8eeYacnIFWbVrwlM7dlZnLEgscenes-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.071a28e3ab3abce2710a949e50f8de965df209331a157db20dd69dce715b2847.r_kgmkiy6YRYoWVIw5ulrR_CBoCjwMQzVSsRF7OEcv4+ hash: v1.k794b7964.d29da3e118b86cc87a30e0e563db0b90decac4fba872f7c9398e86f3d0a318ec.V4DmJc60chPoHPrtv0Nu30l2GnI7snxwC5dPI8eNvdUscenes-app-inbox-selfdrivingsection--disabled--light:- hash: v1.k794b7964.178259484871df5abf309f7eeb353a93cf0f66422b7f7dd0251528a622eb6c16.GKEmpHunYzDJ3pPWI44ZGFDJtxN0pBM82Y7zAkSnChg+ hash: v1.k794b7964.5d9d01cb5f060c6048619c75f1521e8863d563bbffc6c71283bf65138c5afaa4.3NrtglOY205kI2yCz1hFwguqfuFa2vm9B3pTbWSDlqQscenes-app-inbox-selfdrivingsection--git-hub-assignment-on--dark:- hash: v1.k794b7964.fdf6252fecf8caf2be0cdb6d8e44d6e35d4ae3e03ac9b000a34ccd010d90e9c8.uDpQbLO8JlmHKRa9exi2KIKbxfo42e2PB3YQpIdPiFE+ hash: v1.k794b7964.c74a1825180cbf356dad0ae3f0192a723b929126dc73cf782114ee59891f4ede.iKIVtyY_BZMLchvjNM5dNdtqHqXGJ0gHMs84ZtgPOKYscenes-app-inbox-selfdrivingsection--git-hub-assignment-on--light:- hash: v1.k794b7964.68b75610d1b49fe25451736ec8369bb96142714f05cb7c7930a837ec2d06a36f.VKfjM0_AmlmZLZ20LjETXpH3LYbuBJHKnkuuyv2WqVI+ hash: v1.k794b7964.733edaf44245b2f3d53bec632aede7bae0e9d5b99f99248b8743fa973f18a84f.2MHUMxET0bTwJiXj_s6CWzSV1CjCpErnS42zMgdKk9Y+ scenes-app-inbox-selfdrivingsection--issue-tracker-configured--dark:+ hash: v1.k794b7964.f4dddb7a07c2f309dde68c8b1cab786ff8365ad5fe0972b6f91e5fe38e2cfd69.lKM1EdNPOvVRcy3VoSvPARuBVddPqNNdD4_46vWbi-0+ scenes-app-inbox-selfdrivingsection--issue-tracker-configured--light:+ hash: v1.k794b7964.1bbd3734cd76d05f02460dfa9e73ec8c775d735dceb1915f0a034b48cb41d551.vR0oB58UM5nsB9zbp4iXs4aRHsgimQlHpdmoeXjqd20+ scenes-app-inbox-selfdrivingsection--issue-tracker-unavailable--dark:+ hash: v1.k794b7964.39714af86ffcbf6085cffb182a42190419974d9dc0617b8e4810c2c39149fdb2.fEB8kLRblV6ONVo8OtXuPhNgD90F83N9UBvcNZsXBJc+ scenes-app-inbox-selfdrivingsection--issue-tracker-unavailable--light:+ hash: v1.k794b7964.8903ca8efc20c68efde8e5a00efe31d8e0dde9dcb8cbc1aef440ac223dabdc5a.ppgy141yzVPEXrO0eW8jU-G2lGagYr3UZovv3mwyDRsscenes-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.24ced759b7b95ec1f8103e3b4eb150f5cb36b1a3d5d5231b98c3e52783707a77.isVQpWqSVqdGNjo3daqgwb_QJ7rmInIYEPL2L3TA_F4+ hash: v1.k794b7964.39714af86ffcbf6085cffb182a42190419974d9dc0617b8e4810c2c39149fdb2.IZWlGWQ7FEqCGc_j7jn6oQvJmyMddoBUHwX6y2el1qsscenes-app-inbox-selfdrivingsection--personal-default--light:- hash: v1.k794b7964.d82d81d1f9d06fb3ccede3c5ca3d00a61ae5f0f61c7c5af729a610fe9ca1953a.vlmxxVfAFDADdCWfjqF_Md36hGF1NRa4nnlmxQXPMug+ hash: v1.k794b7964.8903ca8efc20c68efde8e5a00efe31d8e0dde9dcb8cbc1aef440ac223dabdc5a.ISalvq0MHCdiayMOzFM5EDTW_xfso5O1vJKuWaXd8IAscenes-app-inbox-selfdrivingsection--personal-override--dark:hash: v1.k794b7964.aa42dc763078e1431c621efad3dae9f298485890910510fccd861fb1bc9f7d77.Go-OjRKiACFptGQ39DNGs4H4H83nh48PwJQBaoW59CIscenes-app-inbox-selfdrivingsection--personal-override--light:diff --git a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.stories.tsx b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.stories.tsxindex e68a490f4790..6e242e7a3aee 100644--- a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.stories.tsx+++ b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.stories.tsx@@ -72,7 +72,7 @@ const meta: Meta<StoryArgs> = {render: ({ scope }) => {useStorybookMocks({get: {- '/api/environments/:team_id/integrations': {+ '/api/projects/:team_id/integrations': {results: [slackIntegration(scope)],},'/api/environments/:team_id/integrations/:intId/channels': {diff --git a/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.test.tsx b/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.test.tsxindex 65c331c077be..6b9cf621b88f 100644--- a/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.test.tsx+++ b/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.test.tsx@@ -23,7 +23,7 @@ describe('IntegrationChoice', () => {beforeEach(() => {useMocks({get: {- '/api/environments/:team_id/integrations': () => [200, { results: [GITHUB_INTEGRATION] }],+ '/api/projects/:team_id/integrations': () => [200, { results: [GITHUB_INTEGRATION] }],},post: {'/api/environments/:team_id/integrations': () => [diff --git a/frontend/src/lib/components/CyclotronJob/integrations/MissingScopesHint.test.tsx b/frontend/src/lib/components/CyclotronJob/integrations/MissingScopesHint.test.tsxindex 53a6299e1cdc..d001cd9745f5 100644--- a/frontend/src/lib/components/CyclotronJob/integrations/MissingScopesHint.test.tsx+++ b/frontend/src/lib/components/CyclotronJob/integrations/MissingScopesHint.test.tsx@@ -45,7 +45,7 @@ describe('MissingScopesHint', () => {])('given %s', async (_name, scope, expectHint) => {useMocks({get: {- '/api/environments/:team_id/integrations': () => [200, { results: [slackIntegration(scope)] }],+ '/api/projects/:team_id/integrations': () => [200, { results: [slackIntegration(scope)] }],},})initKeaTests()@@ -70,7 +70,7 @@ describe('MissingScopesHint', () => {let loads = 0useMocks({get: {- '/api/environments/:team_id/integrations': () => {+ '/api/projects/:team_id/integrations': () => {loads += 1return [200, { results: [] }]},diff --git a/frontend/src/lib/integrations/JiraIntegrationHelpers.tsx b/frontend/src/lib/integrations/JiraIntegrationHelpers.tsxindex 1b6c34bf221b..5d7621c0690f 100644--- a/frontend/src/lib/integrations/JiraIntegrationHelpers.tsx+++ b/frontend/src/lib/integrations/JiraIntegrationHelpers.tsx@@ -11,9 +11,15 @@ export type JiraProjectPickerProps = {integrationId: numbervalue: stringonChange: (value: string) => void+ disabled?: boolean}-export const JiraProjectPicker = ({ value, onChange, integrationId }: JiraProjectPickerProps): JSX.Element => {+export const JiraProjectPicker = ({+ value,+ onChange,+ integrationId,+ disabled,+}: JiraProjectPickerProps): JSX.Element => {const { options, loading } = useJiraProjects(integrationId)return (@@ -25,6 +31,7 @@ export const JiraProjectPicker = ({ value, onChange, integrationId }: JiraProjecplaceholder="Select a project..."options={options}loading={loading}+ disabled={disabled}/>)}diff --git a/frontend/src/lib/integrations/LinearIntegrationHelpers.tsx b/frontend/src/lib/integrations/LinearIntegrationHelpers.tsxindex f04f50eace68..e73f670adca3 100644--- a/frontend/src/lib/integrations/LinearIntegrationHelpers.tsx+++ b/frontend/src/lib/integrations/LinearIntegrationHelpers.tsx@@ -13,9 +13,10 @@ export type LinearTeamPickerProps = {integration: IntegrationTypevalue?: stringonChange?: (value: string | null) => void+ disabled?: boolean}-export function LinearTeamPicker({ onChange, value, integration }: LinearTeamPickerProps): JSX.Element {+export function LinearTeamPicker({ onChange, value, integration, disabled }: LinearTeamPickerProps): JSX.Element {const { options, loading } = useLinearTeams(integration.id)return (@@ -27,6 +28,7 @@ export function LinearTeamPicker({ onChange, value, integration }: LinearTeamPicplaceholder="Select a team..."options={options}loading={loading}+ disabled={disabled}/>)}diff --git a/frontend/src/lib/integrations/integrationsLogic.test.ts b/frontend/src/lib/integrations/integrationsLogic.test.tsindex 596993d5a8ac..ea1d015f9352 100644--- a/frontend/src/lib/integrations/integrationsLogic.test.ts+++ b/frontend/src/lib/integrations/integrationsLogic.test.ts@@ -39,7 +39,7 @@ describe('integrationsLogic', () => {// Handlers reset after every test, so register them per test.useMocks({get: {- '/api/environments/:team_id/integrations/': () => [200, { results: integrationsPayload }],+ '/api/projects/:team_id/integrations/': () => [200, { results: integrationsPayload }],'/api/projects/:team_id/integrations/:id/github_repos/': ({ params, request }) => {const offset = new URL(request.url).searchParams.get('offset') ?? '0'repoRequests.push({ integrationId: String(params.id), offset })diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.tsindex 614350a3f1f1..c6d95c1e10f7 100644--- a/frontend/src/lib/integrations/integrationsLogic.ts+++ b/frontend/src/lib/integrations/integrationsLogic.ts@@ -22,6 +22,7 @@ import { EmailIntegrationDomainGroupedType, IntegrationKind, IntegrationType } fimport {integrationsGithubAvailableInstallationsRetrieve,integrationsGithubReposRetrieve,+ integrationsList,integrationsRequestAccessCreate,} from 'products/integrations/frontend/generated/api'import type {@@ -270,120 +271,10 @@ export interface integrationsLogicActions {errorObject?: any}loadIntegrationsSuccess: (- integrations: {- config: any- created_at: string- created_by?: UserBasicType | null | undefined- display_name: string- errors?: string | undefined- files_write_requestable?: boolean | undefined- icon_url: any- id: number- installation_shared?: boolean | null | undefined- installation_status?: InstallationStatusEnumApi | null | undefined- kind:- | 'apns'- | 'aws-redshift'- | 'aws-s3'- | 'azure-blob'- | 'bing-ads'- | 'clickup'- | 'customerio-app'- | 'customerio-track'- | 'customerio-webhook'- | 'databricks'- | 'email'- | 'firebase'- | 'github'- | 'gitlab'- | 'google-ads'- | 'google-analytics'- | 'google-calendar'- | 'google-cloud-service-account'- | 'google-cloud-storage'- | 'google-pubsub'- | 'google-search-console'- | 'google-sheets'- | 'hubspot'- | 'instagram'- | 'intercom'- | 'jira'- | 'linear'- | 'linkedin-ads'- | 'meta-ads'- | 'pardot'- | 'pinterest-ads'- | 'postgresql'- | 'reddit-ads'- | 's3-compatible'- | 'salesforce'- | 'slack'- | 'snapchat'- | 'snowflake'- | 'stripe'- | 'tiktok-ads'- | 'twilio'- | 'vercel'- | 'youtube-analytics'- }[],+ integrations: IntegrationType[],payload?: any) => {- integrations: {- config: any- created_at: string- created_by?: UserBasicType | null | undefined- display_name: string- errors?: string | undefined- files_write_requestable?: boolean | undefined- icon_url: any- id: number- installation_shared?: boolean | null | undefined- installation_status?: InstallationStatusEnumApi | null | undefined- kind:- | 'apns'- | 'aws-redshift'- | 'aws-s3'- | 'azure-blob'- | 'bing-ads'- | 'clickup'- | 'customerio-app'- | 'customerio-track'- | 'customerio-webhook'- | 'databricks'- | 'email'- | 'firebase'- | 'github'- | 'gitlab'- | 'google-ads'- | 'google-analytics'- | 'google-calendar'- | 'google-cloud-service-account'- | 'google-cloud-storage'- | 'google-pubsub'- | 'google-search-console'- | 'google-sheets'- | 'hubspot'- | 'instagram'- | 'intercom'- | 'jira'- | 'linear'- | 'linkedin-ads'- | 'meta-ads'- | 'pardot'- | 'pinterest-ads'- | 'postgresql'- | 'reddit-ads'- | 's3-compatible'- | 'salesforce'- | 'slack'- | 'snapchat'- | 'snowflake'- | 'stripe'- | 'tiktok-ads'- | 'twilio'- | 'vercel'- | 'youtube-analytics'- }[]+ integrations: IntegrationType[]payload?: any}newGoogleCloudKey: (@@ -923,17 +814,40 @@ export const integrationsLogic = kea<integrationsLogicType>([null as IntegrationType[] | null,{loadIntegrations: async () => {- const res = await api.integrations.list()-- // Simple modifier here to add icons and names - we can move this to the backend at some point-- return res.results.map((integration) => {- return {- ...integration,- // TODO: Make the icons endpoint independent of hog functions- icon_url: ICONS[integration.kind],+ const integrations: IntegrationType[] = []+ let offset = 0+ let hasNext = true+ while (hasNext) {+ const res = await integrationsList(String(values.currentProjectId), { limit: 100, offset })+ for (const integration of res.results) {+ // The API serves kinds this union does not name yet, and consumers such as+ // PosthogConnect read them, so every result is kept and only the icon is optional.+ const kind = integration.kind as IntegrationKind+ integrations.push({+ ...integration,+ kind,+ config: integration.config ?? {},+ created_by: integration.created_by+ ? {+ id: integration.created_by.id,+ uuid: integration.created_by.uuid,+ distinct_id: integration.created_by.distinct_id ?? '',+ first_name: integration.created_by.first_name ?? '',+ last_name: integration.created_by.last_name,+ email: integration.created_by.email,+ is_email_verified: integration.created_by.is_email_verified,+ role_at_organization: integration.created_by.role_at_organization,+ }+ : integration.created_by,+ // TODO: Make the icons endpoint independent of hog functions+ icon_url: ICONS[kind],+ })}- })+ offset += res.results.length+ hasNext = !!res.next && res.results.length > 0+ }++ return integrations},newGoogleCloudKey: async ({ kind, key, callback }) => {try {diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.tsindex bd4ccb20ded7..dd3ee2235c0d 100644--- a/frontend/src/mocks/handlers.ts+++ b/frontend/src/mocks/handlers.ts@@ -276,7 +276,7 @@ export const defaultMocks: Mocks = {'/api/environments/:team_id/event_ingestion_restrictions/': [],'api/projects/:team_id/surveys': EMPTY_PAGINATED_RESPONSE,'api/projects/:team_id/surveys/responses_count': {},- 'api/environments/:team_id/integrations': EMPTY_PAGINATED_RESPONSE,+ 'api/projects/:team_id/integrations': EMPTY_PAGINATED_RESPONSE,'/api/organizations/:organization_id/integrations/': EMPTY_PAGINATED_RESPONSE,'/api/environments/:team_id/quick_filters/': EMPTY_PAGINATED_RESPONSE,'api/environments/:team_id/error_tracking/assignment_rules': EMPTY_PAGINATED_RESPONSE,diff --git a/frontend/src/mocks/jest.ts b/frontend/src/mocks/jest.tsindex f213a4d8d130..ba88b06de7c7 100644--- a/frontend/src/mocks/jest.ts+++ b/frontend/src/mocks/jest.ts@@ -13,7 +13,7 @@ import { Mocks, mocksToHandlers } from '~/mocks/utils'const jestOnlyDefaultHandlers = mocksToHandlers({get: {'/api/projects/:team_id/product_tours/': EMPTY_PAGINATED_RESPONSE,- '/api/environments/:team_id/integrations/': EMPTY_PAGINATED_RESPONSE,+ '/api/projects/:team_id/integrations/': EMPTY_PAGINATED_RESPONSE,'/api/environments/:team_id/llm_analytics/evaluation_config/': { active_provider_key: null },'/api/environments/:team_id/taggers/': EMPTY_PAGINATED_RESPONSE,'/api/projects/:team_id/event_definitions/primary_properties/': { primary_properties: {} },diff --git a/frontend/src/scenes/StripeConfirmInstall/stripeConfirmInstallLogic.test.ts b/frontend/src/scenes/StripeConfirmInstall/stripeConfirmInstallLogic.test.tsindex b98d0c3ae4d4..352b52bc1209 100644--- a/frontend/src/scenes/StripeConfirmInstall/stripeConfirmInstallLogic.test.ts+++ b/frontend/src/scenes/StripeConfirmInstall/stripeConfirmInstallLogic.test.ts@@ -14,7 +14,7 @@ describe('stripeConfirmInstallLogic', () => {useMocks({get: {- '/api/environments/:team_id/integrations/': () => [200, { results: [] }],+ '/api/projects/:team_id/integrations/': () => [200, { results: [] }],},})diff --git a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportScene.stories.tsx b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportScene.stories.tsxindex a890e55a866d..1bcf1ba6f11a 100644--- a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportScene.stories.tsx+++ b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportScene.stories.tsx@@ -32,7 +32,6 @@ const meta: Meta = {[`/api/environments/:team_id/batch_exports/${EXISTING_EXPORT.id}/runs/`]: { results: [] },[`/api/environments/:team_id/batch_exports/${EXISTING_EXPORT.id}/backfills/`]: { results: [] },// Integration-backed destinations (Databricks, AzureBlob, BigQuery) render IntegrationChoice.- '/api/environments/:team_id/integrations': { results: [] },'/api/projects/:team_id/integrations': { results: [] },},}),diff --git a/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.test.ts b/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.test.tsindex fd2e35ad6ea9..9d0b01ac14f5 100644--- a/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.test.ts+++ b/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.test.ts@@ -443,7 +443,7 @@ describe('batchExportConfigFormLogic', () => {get: {...getMocks,'/api/environments/:team_id/batch_exports/test': { steps: [] },- '/api/environments/:team_id/integrations/': {+ '/api/projects/:team_id/integrations/': {count: 4,results: [AWS_REDSHIFT_INTEGRATION,diff --git a/frontend/src/scenes/integrations/IntegrationFullPage.stories.tsx b/frontend/src/scenes/integrations/IntegrationFullPage.stories.tsxindex d07897a85499..a8d97b0dde19 100644--- a/frontend/src/scenes/integrations/IntegrationFullPage.stories.tsx+++ b/frontend/src/scenes/integrations/IntegrationFullPage.stories.tsx@@ -44,11 +44,11 @@ type Story = StoryObj<typeof IntegrationFullPage>// integrationsLogic loads from the environments endpoint, not projectsexport const NotConnected: Story = {- decorators: [mswDecorator({ get: { '/api/environments/:id/integrations': { results: [] } } })],+ decorators: [mswDecorator({ get: { '/api/projects/:id/integrations': { results: [] } } })],}export const Connected: Story = {- decorators: [mswDecorator({ get: { '/api/environments/:id/integrations': { results: [mockIntegration] } } })],+ decorators: [mswDecorator({ get: { '/api/projects/:id/integrations': { results: [mockIntegration] } } })],}// A connect attempt the provider sent back without a code. Slack answers `access_denied` both when@@ -70,7 +70,7 @@ export const SlackNotConfigured: Story = {realm: Realm.Cloud,slack_service: { available: false, client_id: null },},- '/api/environments/:id/integrations': { results: [] },+ '/api/projects/:id/integrations': { results: [] },},}),],@@ -82,7 +82,7 @@ export const GithubNotConnected: Story = {decorators: [mswDecorator({get: {- '/api/environments/:id/integrations': { results: [] },+ '/api/projects/:id/integrations': { results: [] },'/api/projects/:id/integrations/github/available_installations/': {installations: [],personal_github_connected: false,@@ -110,7 +110,7 @@ export const NoPermission: Story = {decorators: [mswDecorator({get: {- '/api/environments/:id/integrations': { results: [] },+ '/api/projects/:id/integrations': { results: [] },'/api/organizations/@current/': memberOrganization,},}),diff --git a/frontend/src/scenes/integrations/aws-s3/awsS3SetupModalLogic.test.ts b/frontend/src/scenes/integrations/aws-s3/awsS3SetupModalLogic.test.tsindex b5d9b14998ce..d3bf0b15ec37 100644--- a/frontend/src/scenes/integrations/aws-s3/awsS3SetupModalLogic.test.ts+++ b/frontend/src/scenes/integrations/aws-s3/awsS3SetupModalLogic.test.ts@@ -13,7 +13,7 @@ describe('awsS3SetupModalLogic', () => {useMocks({get: {- '/api/environments/:team_id/integrations/': () => [200, { results: [] }],+ '/api/projects/:team_id/integrations/': () => [200, { results: [] }],},})diff --git a/frontend/src/scenes/integrations/components/GithubIntegration.test.tsx b/frontend/src/scenes/integrations/components/GithubIntegration.test.tsxindex 3337d44a2d7c..25ed72391f0c 100644--- a/frontend/src/scenes/integrations/components/GithubIntegration.test.tsx+++ b/frontend/src/scenes/integrations/components/GithubIntegration.test.tsx@@ -22,7 +22,7 @@ describe('GithubIntegration', () => {availableInstallations = []useMocks({get: {- '/api/environments/:team_id/integrations': { results: [] },+ '/api/projects/:team_id/integrations': { results: [] },'/api/projects/:team_id/integrations/github/available_installations/': () => [200,{ installations: availableInstallations, personal_github_connected: false },diff --git a/frontend/src/scenes/integrations/components/SlackIntegration.stories.tsx b/frontend/src/scenes/integrations/components/SlackIntegration.stories.tsxindex 74daf13e8ec5..d85b20007240 100644--- a/frontend/src/scenes/integrations/components/SlackIntegration.stories.tsx+++ b/frontend/src/scenes/integrations/components/SlackIntegration.stories.tsx@@ -23,7 +23,7 @@ const meta: Meta<StoryArgs> = {useStorybookMocks({get: {- '/api/environments/:id/integrations': { results: integrated ? [mockIntegration] : [] },+ '/api/projects/:id/integrations': { results: integrated ? [mockIntegration] : [] },'/api/instance_settings': {results: instanceConfigured ? SLACK_INSTANCE_SETTINGS : [],},@@ -58,7 +58,7 @@ const renderFullPage = ({ integrations }: { integrations: IntegrationType[] }):useAvailableFeatures([AvailableFeature.SUBSCRIPTIONS])useStorybookMocks({get: {- '/api/environments/:id/integrations': { results: integrations },+ '/api/projects/:id/integrations': { results: integrations },'/api/instance_settings': { results: SLACK_INSTANCE_SETTINGS },},})diff --git a/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.test.ts b/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.test.tsindex b6dc9c2205c2..d73a74797a12 100644--- a/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.test.ts+++ b/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.test.ts@@ -33,7 +33,7 @@ describe('phaiSidePanelComposerSeedLogic', () => {get: {'/api/projects/:team/tasks/': { results: [], count: 0 },'/api/projects/:team/tasks/repositories/': { repositories: [] },- '/api/environments/:team/integrations/': { results: [] },+ '/api/projects/:team/integrations/': { results: [] },},post: {'/api/projects/:team/tasks/': async ({ request }) => {diff --git a/frontend/src/scenes/onboarding/legacy/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.stories.tsx b/frontend/src/scenes/onboarding/legacy/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.stories.tsxindex 6d34ebc9d314..22c189703098 100644--- a/frontend/src/scenes/onboarding/legacy/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.stories.tsx+++ b/frontend/src/scenes/onboarding/legacy/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.stories.tsx@@ -99,7 +99,7 @@ const meta: Meta = {'/stats': {},'/events': {},'/api/billing/': { ...billingJson },- '/api/environments/:team_id/integrations': { results: [githubIntegration] },+ '/api/projects/:team_id/integrations': { results: [githubIntegration] },'/api/environments/:team_id/integrations/:id/github_repos': githubReposResponse,'/api/projects/:project_id/tasks/:task_id/runs/:run_id/stream': () =>new Response(TASK_RUN_STREAM_BODY, {diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.stories.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.stories.tsxindex 34a71097b093..37366a260968 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.stories.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.stories.tsx@@ -153,7 +153,7 @@ function cloudRunStory({useStorybookMocks({get: {- '/api/environments/:team_id/integrations': { results: integrations },+ '/api/projects/:team_id/integrations': { results: integrations },},})@@ -226,7 +226,7 @@ export const PullRequestQueued: Story = {useStorybookMocks({get: {- '/api/environments/:team_id/integrations': { results: [githubIntegration] },+ '/api/projects/:team_id/integrations': { results: [githubIntegration] },},})@@ -256,7 +256,7 @@ export const RunItYourself: Story = {useStorybookMocks({get: {- '/api/environments/:team_id/integrations': { results: [] },+ '/api/projects/:team_id/integrations': { results: [] },},})@@ -299,7 +299,7 @@ function CloudRunPlayground({ githubConnected, repository, pullRequestQueued }:useStorybookMocks({get: {- '/api/environments/:team_id/integrations': {+ '/api/projects/:team_id/integrations': {results: githubConnected ? [githubIntegration] : [],},},diff --git a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts b/frontend/src/scenes/settings/user/personalIntegrationsLogic.tsindex fa023ee3df8d..b33f6d04ebe2 100644--- a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts+++ b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts@@ -18,7 +18,7 @@ import {} from '~/generated/core/api'import type { UserGitHubIntegrationItemApi } from '~/generated/core/api.schemas'-import type { TeamPublicType, TeamType, UserBasicType } from '../../../types'+import type { TeamPublicType, TeamType } from '../../../types'export interface PersonalGitHubIntegration {kind: 'github'@@ -115,126 +115,10 @@ export interface personalIntegrationsLogicValues {export interface personalIntegrationsLogicActions {loadProjectIntegrations: () => any // integrationsLogicprojectIntegrationsLoaded: (- integrations: {- config: any- created_at: string- created_by?: UserBasicType | null | undefined- display_name: string- errors?: string | undefined- files_write_requestable?: boolean | undefined- icon_url: any- id: number- installation_shared?: boolean | null | undefined- installation_status?:- | null- | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi- | undefined- kind:- | 'apns'- | 'aws-redshift'- | 'aws-s3'- | 'azure-blob'- | 'bing-ads'- | 'clickup'- | 'customerio-app'- | 'customerio-track'- | 'customerio-webhook'- | 'databricks'- | 'email'- | 'firebase'- | 'github'- | 'gitlab'- | 'google-ads'- | 'google-analytics'- | 'google-calendar'- | 'google-cloud-service-account'- | 'google-cloud-storage'- | 'google-pubsub'- | 'google-search-console'- | 'google-sheets'- | 'hubspot'- | 'instagram'- | 'intercom'- | 'jira'- | 'linear'- | 'linkedin-ads'- | 'meta-ads'- | 'pardot'- | 'pinterest-ads'- | 'postgresql'- | 'reddit-ads'- | 's3-compatible'- | 'salesforce'- | 'slack'- | 'snapchat'- | 'snowflake'- | 'stripe'- | 'tiktok-ads'- | 'twilio'- | 'vercel'- | 'youtube-analytics'- }[],+ integrations: import('../../../types').IntegrationType[],payload?: any) => {- integrations: {- config: any- created_at: string- created_by?: UserBasicType | null | undefined- display_name: string- errors?: string | undefined- files_write_requestable?: boolean | undefined- icon_url: any- id: number- installation_shared?: boolean | null | undefined- installation_status?:- | null- | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi- | undefined- kind:- | 'apns'- | 'aws-redshift'- | 'aws-s3'- | 'azure-blob'- | 'bing-ads'- | 'clickup'- | 'customerio-app'- | 'customerio-track'- | 'customerio-webhook'- | 'databricks'- | 'email'- | 'firebase'- | 'github'- | 'gitlab'- | 'google-ads'- | 'google-analytics'- | 'google-calendar'- | 'google-cloud-service-account'- | 'google-cloud-storage'- | 'google-pubsub'- | 'google-search-console'- | 'google-sheets'- | 'hubspot'- | 'instagram'- | 'intercom'- | 'jira'- | 'linear'- | 'linkedin-ads'- | 'meta-ads'- | 'pardot'- | 'pinterest-ads'- | 'postgresql'- | 'reddit-ads'- | 's3-compatible'- | 'salesforce'- | 'slack'- | 'snapchat'- | 'snowflake'- | 'stripe'- | 'tiktok-ads'- | 'twilio'- | 'vercel'- | 'youtube-analytics'- }[]+ integrations: import('../../../types').IntegrationType[]payload?: any} // integrationsLogicconnectGitHub: () => {diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 90cff6ece2b8..bacf584a7201 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -375,6 +375,8 @@ field_name_overrides: dict[AuditableScope, dict[str, str]] = {"default_autostart_priority": "project PR threshold","default_slack_notification_channel": "team Slack channel","autostart_base_branches": "base branch overrides",+ "issue_tracking_integration": "issue tracker",+ "issue_tracking_config": "issue tracker target",},"OAuthApplication": {"_provisioning_config": "provisioning config",diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex 839dbe5c938d..b02300807cce 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -770,13 +770,16 @@ class GitHubIntegrationBase:*,endpoint: str,json_body: Mapping[str, object],+ headers: dict[str, str] | None = None,timeout: int = 10,) -> requests.Response | None:"""PATCH with installation token via :meth:`api_request`; ``None`` instead of raising, for thesuccess/error-dict verbs built on top."""path = url.removeprefix("https://api.github.com")try:- return self.api_request("PATCH", path, endpoint=endpoint, json_body=json_body, timeout=timeout)+ return self.api_request(+ "PATCH", path, endpoint=endpoint, json_body=json_body, headers=headers, timeout=timeout+ )except GitHubIntegrationError:logger.warning("GitHubIntegration: installation PATCH failed", url=url, exc_info=True)return None@@ -1089,6 +1092,7 @@ class GitHubIntegrationBase:"additions": pr.get("additions", 0),"deletions": pr.get("deletions", 0),"changed_files": pr.get("changed_files", 0),+ "etag": response.headers.get("ETag"),}def get_pull_request_from_url(self, pr_url: str) -> dict[str, Any]:@@ -1127,6 +1131,28 @@ class GitHubIntegrationBase:return {"success": True, "number": pr.get("number", pr_number), "state": pr.get("state")}+ def update_pull_request_body(+ self, repository: str, pr_number: int, body: str, *, expected_etag: str | None = None+ ) -> dict[str, Any]:+ """Replace a pull request's description. ``repository`` is ``owner/repo`` or a bare repo."""+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"++ response = self._installation_authenticated_patch(+ f"https://api.github.com/repos/{repo_path}/pulls/{pr_number}",+ endpoint="/repos/{owner}/{repo}/pulls/{pull_number}",+ json_body={"body": body},+ headers={"If-Match": expected_etag} if expected_etag else None,+ )+ if response is None:+ return {"success": False, "error": "Network error updating pull request"}+ if response.status_code != 200:+ return {+ "success": False,+ "error": f"Failed to update pull request: {response.text}",+ "status_code": response.status_code,+ }+ return {"success": True, "number": pr_number}+def close_pull_request_from_url(self, pr_url: str) -> dict[str, Any]:"""Close a pull request by its HTML URL (e.g. ``https://github.com/owner/repo/pull/123``)."""parsed = self.parse_pull_request_url(pr_url)diff --git a/posthog/models/integration/__init__.py b/posthog/models/integration/__init__.pyindex f061c2fc9007..66615f2f69d7 100644--- a/posthog/models/integration/__init__.py+++ b/posthog/models/integration/__init__.py@@ -32,6 +32,11 @@ from .clickup import ClickUpIntegrationfrom .common import ERROR_TOKEN_REFRESH_FAILED, META_GRAPH_API_VERSION, IntegrationError, dot_getfrom .databricks import DatabricksIntegration, DatabricksIntegrationErrorfrom .email import EmailIntegration, cleanup_ses_identity_on_integration_delete+from .external_issues import (+ SUPPORTED_EXTERNAL_ISSUE_PROVIDERS,+ external_issue_url,+ is_supported_external_issue_provider,+)from .github import (GITHUB_DEFAULT_BRANCH_CACHE_TTL_SECONDS,GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS,@@ -198,6 +203,9 @@ __all__ = ["EmailIntegration","cleanup_ses_identity_on_integration_delete","LinearIntegration",+ "SUPPORTED_EXTERNAL_ISSUE_PROVIDERS",+ "external_issue_url",+ "is_supported_external_issue_provider","JiraIntegration","GITHUB_DEFAULT_BRANCH_CACHE_TTL_SECONDS","GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS",diff --git a/posthog/models/integration/external_issues.py b/posthog/models/integration/external_issues.pynew file mode 100644index 000000000000..1502de779e0a--- /dev/null+++ b/posthog/models/integration/external_issues.py@@ -0,0 +1,65 @@+"""URLs for issues created in an external tracker through an Integration."""++from typing import Any++from . import model+from .github import GitHubIntegration+from .gitlab import GitLabIntegration+from .jira import JiraIntegration+from .linear import LinearIntegration++SUPPORTED_EXTERNAL_ISSUE_PROVIDERS = frozenset(+ {+ model.Integration.IntegrationKind.LINEAR,+ model.Integration.IntegrationKind.GITHUB,+ model.Integration.IntegrationKind.GITLAB,+ model.Integration.IntegrationKind.JIRA,+ }+)+++def is_supported_external_issue_provider(kind: str) -> bool:+ return kind in SUPPORTED_EXTERNAL_ISSUE_PROVIDERS+++def external_issue_url(integration: model.Integration, external_context: dict[str, Any] | None) -> str:+ """Link to an external issue from the identifier its integration client stored.++ Returns an empty string when the context does not carry the provider's identifier, so a+ half-written reference renders as "no link" rather than a URL that goes nowhere.+ """+ context = external_context or {}++ if integration.kind == model.Integration.IntegrationKind.LINEAR:+ issue_id = context.get("id")+ if not issue_id:+ return ""+ url_key = LinearIntegration(integration).url_key()+ return f"https://linear.app/{url_key}/issue/{issue_id}"++ if integration.kind == model.Integration.IntegrationKind.GITHUB:+ repository = context.get("repository")+ number = context.get("number")+ if not repository or not number:+ return ""+ repository_path = (+ str(repository)+ if "/" in str(repository)+ else f"{GitHubIntegration(integration).organization()}/{repository}"+ )+ return f"https://github.com/{repository_path}/issues/{number}"++ if integration.kind == model.Integration.IntegrationKind.GITLAB:+ issue_id = context.get("issue_id")+ if not issue_id:+ return ""+ gitlab = GitLabIntegration(integration)+ return f"{gitlab.hostname}/{gitlab.project_path}/issues/{issue_id}"++ if integration.kind == model.Integration.IntegrationKind.JIRA:+ issue_key = context.get("key")+ if not issue_key:+ return ""+ return f"{JiraIntegration(integration).site_url()}/browse/{issue_key}"++ return ""diff --git a/posthog/models/integration/github.py b/posthog/models/integration/github.pyindex ffd5af800556..cc46b0b0b1fd 100644--- a/posthog/models/integration/github.py+++ b/posthog/models/integration/github.py@@ -399,6 +399,22 @@ class GitHubIntegration(GitHubIntegrationBase):return {"number": issue["number"], "repository": repository}+ def close_issue(self, repository: str, number: int, *, completed: bool = False) -> None:+ """Close an issue with the reason that matches the report outcome. Raises on failure."""+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"++ response = self.api_request(+ "PATCH",+ f"/repos/{repo_path}/issues/{number}",+ endpoint="/repos/{owner}/{repo}/issues/{issue_number}",+ json_body={"state": "closed", "state_reason": "completed" if completed else "not_planned"},+ )+ if response.status_code != 200:+ raise GitHubIntegrationError(+ f"GitHubIntegration: failed to close issue {repo_path}#{number}: {response.text[:300]}",+ status_code=response.status_code,+ )+def search_issues(self, repository: str, query: str, *, limit: int = 25) -> list[dict[str, Any]]:"""Search existing GitHub issues in a repository for the link-existing flow."""repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"diff --git a/posthog/models/integration/gitlab.py b/posthog/models/integration/gitlab.pyindex c946a4372db0..be498230c27d 100644--- a/posthog/models/integration/gitlab.py+++ b/posthog/models/integration/gitlab.py@@ -104,6 +104,27 @@ class GitLabIntegration:return {"issue_id": issue["iid"]}+ def close_issue(self, issue_id: int) -> None:+ """Close an issue in the connected project. Raises on failure."""+ hostname = self.integration.config.get("hostname")+ project_id = self.integration.config.get("project_id")+ access_token = self.integration.sensitive_config.get("access_token")++ url = f"{hostname}/api/v4/projects/{project_id}/issues/{issue_id}"+ allowed, error = is_url_allowed(url)+ if not allowed:+ raise GitLabIntegrationError(f"Invalid GitLab hostname: {error}")++ response = requests.put(+ url,+ json={"state_event": "close"},+ headers={"PRIVATE-TOKEN": access_token},+ allow_redirects=False,+ timeout=10,+ )+ if response.status_code != 200:+ raise GitLabIntegrationError(f"GitLabIntegration: failed to close issue: {response.text[:300]}")+def search_issues(self, query: str, *, limit: int = 25) -> list[dict[str, Any]]:"""Search existing GitLab issues in the connected project for the link-existing flow."""hostname = self.integration.config.get("hostname")diff --git a/posthog/models/integration/jira.py b/posthog/models/integration/jira.pyindex dee89e3671d3..d0c98046ddf6 100644--- a/posthog/models/integration/jira.py+++ b/posthog/models/integration/jira.py@@ -160,6 +160,45 @@ class JiraIntegration:return {"key": issue["key"], "id": issue.get("id", "")}+ def close_issue(self, issue_key: str) -> None:+ """Transition an issue into a done status. Raises on failure.++ Jira has no generic "close" verb: an issue closes through a workflow transition, and both+ the transition names and ids differ per project. So read the available transitions and take+ the first one that lands in the "done" status category.+ """+ cloud_id = self.cloud_id()+ if not cloud_id:+ raise ValidationError("Jira integration missing cloud_id - the integration may not be properly configured")++ self._ensure_token_valid()++ headers = {+ "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",+ "Accept": "application/json",+ "Content-Type": "application/json",+ }+ url = f"https://api.atlassian.com/ex/jira/{cloud_id}/rest/api/3/issue/{issue_key}/transitions"++ response = requests.get(url, headers=headers, timeout=10)+ if response.status_code != 200:+ raise ValidationError(f"Failed to read Jira transitions (status {response.status_code})")++ transition_id = next(+ (+ transition["id"]+ for transition in response.json().get("transitions", []) or []+ if common.dot_get(transition, "to.statusCategory.key") == "done" and transition.get("id")+ ),+ None,+ )+ if transition_id is None:+ raise ValidationError(f"No done transition available for Jira issue {issue_key}")++ response = requests.post(url, headers=headers, json={"transition": {"id": transition_id}}, timeout=10)+ if response.status_code != 204:+ raise ValidationError(f"Failed to close Jira issue {issue_key} (status {response.status_code})")+def search_issues(self, query: str, *, limit: int = 25) -> list[dict[str, Any]]:"""Search existing Jira issues for the link-existing flow.diff --git a/posthog/models/integration/linear.py b/posthog/models/integration/linear.pyindex cbf557bfd11d..a01a9818cc0a 100644--- a/posthog/models/integration/linear.py+++ b/posthog/models/integration/linear.py@@ -80,6 +80,34 @@ class LinearIntegration:if body.get("errors") or not common.dot_get(body, "data.attachmentCreate.success"):raise ValidationError("Failed to attach the PostHog link to the Linear issue")+ def close_issue(self, issue_id: str, *, completed: bool = False) -> None:+ """Move an issue to its team's completed or canceled state. Raises on failure.++ Linear has no generic "close" verb: an issue closes by moving to a workflow state, and+ the state ids differ per team. So read the issue's own team states first.+ """+ state_type = "completed" if completed else "canceled"+ states_query = """+ query IssueCloseState($id: String!, $stateType: String!) {+ issue(id: $id) {+ team { states(filter: { type: { eq: $stateType } }) { nodes { id } } }+ }+ }+ """+ body = self.query(states_query, variables={"id": issue_id, "stateType": state_type})+ nodes = common.dot_get(body, "data.issue.team.states.nodes") or []+ if body.get("errors") or not nodes:+ raise ValidationError(f"Failed to find a {state_type} state for the Linear issue")++ update_query = """+ mutation IssueClose($id: String!, $stateId: String!) {+ issueUpdate(id: $id, input: { stateId: $stateId }) { success }+ }+ """+ body = self.query(update_query, variables={"id": issue_id, "stateId": nodes[0]["id"]})+ if body.get("errors") or not common.dot_get(body, "data.issueUpdate.success"):+ raise ValidationError(f"Failed to move the Linear issue to a {state_type} state")+def search_issues(self, query: str, *, limit: int = 25) -> list[dict[str, Any]]:"""Search existing Linear issues by title / identifier for the link-existing flow.diff --git a/posthog/models/utils.py b/posthog/models/utils.pyindex 5816f4dd05c1..e2aed353642e 100644--- a/posthog/models/utils.py+++ b/posthog/models/utils.py@@ -537,6 +537,16 @@ class ActivityDetailEncoder(json.JSONEncoder):"id": obj.id,"short_id": obj.short_id,}+ if hasattr(obj, "__class__") and obj.__class__.__name__ == "Integration":+ # Identity only: an integration's config and sensitive_config hold credentials, and the+ # Integration scope already masks both. `integration_id` rather than `display_name`,+ # because that property reaches into per-provider OAuth config and raises when the+ # provider's app is not set up on this instance.+ return {+ "id": obj.id,+ "kind": obj.kind,+ "integration_id": obj.integration_id,+ }if hasattr(obj, "__class__") and obj.__class__.__name__ == "Tag":return {"id": obj.id,diff --git a/products/alerts/frontend/components/AlertComponents.stories.tsx b/products/alerts/frontend/components/AlertComponents.stories.tsxindex 24f71042d81b..c15f4eda7568 100644--- a/products/alerts/frontend/components/AlertComponents.stories.tsx+++ b/products/alerts/frontend/components/AlertComponents.stories.tsx@@ -308,7 +308,7 @@ const STORY_EXISTING_HOG_FUNCTIONS = [function MultipleSlackWorkspacesStory(): JSX.Element {useStorybookMocks({get: {- '/api/environments/:team_id/integrations': { results: STORY_SLACK_WORKSPACES, count: 2 },+ '/api/projects/:team_id/integrations': { results: STORY_SLACK_WORKSPACES, count: 2 },'/api/environments/:team_id/integrations/:id/channels': ({ params, request }) => {const channelId = new URL(request.url).searchParams.get('channel_id')const allChannels = (STORY_SLACK_CHANNELS[String(params.id)] ?? []).map((channel) => ({diff --git a/products/alerts/frontend/logic/alertNotificationLogic.ts b/products/alerts/frontend/logic/alertNotificationLogic.tsindex 4da6fde460c3..1ac5f3e1684e 100644--- a/products/alerts/frontend/logic/alertNotificationLogic.ts+++ b/products/alerts/frontend/logic/alertNotificationLogic.ts@@ -24,8 +24,6 @@ import {notificationTypeFromTemplateId,} from 'products/alerts/frontend/logic/alertNotifications'-import type { UserBasicType } from '../../../../frontend/src/types'-export const ALERT_NOTIFICATION_TYPE_OPTIONS = [{ label: 'Slack', value: ALERT_NOTIFICATION_TYPE_SLACK },{ label: 'Discord', value: ALERT_NOTIFICATION_TYPE_DISCORD },@@ -67,126 +65,10 @@ export interface alertNotificationLogicActions {errorObject?: any} // integrationsLogicloadIntegrationsSuccess: (- integrations: {- config: any- created_at: string- created_by?: UserBasicType | null | undefined- display_name: string- errors?: string | undefined- files_write_requestable?: boolean | undefined- icon_url: any- id: number- installation_shared?: boolean | null | undefined- installation_status?:- | null- | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi- | undefined- kind:- | 'apns'- | 'aws-redshift'- | 'aws-s3'- | 'azure-blob'- | 'bing-ads'- | 'clickup'- | 'customerio-app'- | 'customerio-track'- | 'customerio-webhook'- | 'databricks'- | 'email'- | 'firebase'- | 'github'- | 'gitlab'- | 'google-ads'- | 'google-analytics'- | 'google-calendar'- | 'google-cloud-service-account'- | 'google-cloud-storage'- | 'google-pubsub'- | 'google-search-console'- | 'google-sheets'- | 'hubspot'- | 'instagram'- | 'intercom'- | 'jira'- | 'linear'- | 'linkedin-ads'- | 'meta-ads'- | 'pardot'- | 'pinterest-ads'- | 'postgresql'- | 'reddit-ads'- | 's3-compatible'- | 'salesforce'- | 'slack'- | 'snapchat'- | 'snowflake'- | 'stripe'- | 'tiktok-ads'- | 'twilio'- | 'vercel'- | 'youtube-analytics'- }[],+ integrations: IntegrationType[],payload?: any) => {- integrations: {- config: any- created_at: string- created_by?: UserBasicType | null | undefined- display_name: string- errors?: string | undefined- files_write_requestable?: boolean | undefined- icon_url: any- id: number- installation_shared?: boolean | null | undefined- installation_status?:- | null- | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi- | undefined- kind:- | 'apns'- | 'aws-redshift'- | 'aws-s3'- | 'azure-blob'- | 'bing-ads'- | 'clickup'- | 'customerio-app'- | 'customerio-track'- | 'customerio-webhook'- | 'databricks'- | 'email'- | 'firebase'- | 'github'- | 'gitlab'- | 'google-ads'- | 'google-analytics'- | 'google-calendar'- | 'google-cloud-service-account'- | 'google-cloud-storage'- | 'google-pubsub'- | 'google-search-console'- | 'google-sheets'- | 'hubspot'- | 'instagram'- | 'intercom'- | 'jira'- | 'linear'- | 'linkedin-ads'- | 'meta-ads'- | 'pardot'- | 'pinterest-ads'- | 'postgresql'- | 'reddit-ads'- | 's3-compatible'- | 'salesforce'- | 'slack'- | 'snapchat'- | 'snowflake'- | 'stripe'- | 'tiktok-ads'- | 'twilio'- | 'vercel'- | 'youtube-analytics'- }[]+ integrations: IntegrationType[]payload?: any} // integrationsLogicaddPendingNotification: (notification: PendingAlertNotification) => {diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.tsindex f5da40c45c68..46cf3e13e824 100644--- a/products/desktop/packages/shared/src/domain-types.ts+++ b/products/desktop/packages/shared/src/domain-types.ts@@ -777,6 +777,12 @@ export interface SignalReport {implementation_pr_merged?: boolean;/** Latest known state of that PR, per the GitHub webhook. */implementation_pr_state?: SignalReportPrState | null;+ /** Link to the tracker issue self-driving opened for this report's PR, when the project tracks issues. */+ tracker_issue_url?: string | null;+ /** How that issue reads in its provider, for example '#12' or 'ENG-123'. */+ tracker_issue_reference?: string | null;+ /** Why the tracker issue could not be opened, for a project that wants one. Null when it exists. */+ tracker_issue_error?: string | null;/** Charts the report shows, placed by `[label](chart:<chart_id>)` links in the summary. */charts?: SignalReportChart[];/** The report's PR refund, when one exists (one refund per report, ever). */diff --git a/products/desktop/packages/ui/src/features/inbox/components/AgentRunDetail.tsx b/products/desktop/packages/ui/src/features/inbox/components/AgentRunDetail.tsxindex f580b1857618..93797eda4993 100644--- a/products/desktop/packages/ui/src/features/inbox/components/AgentRunDetail.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/AgentRunDetail.tsx@@ -12,7 +12,14 @@ import {deriveHeadline,parsePrUrl,} from "@posthog/core/inbox/reportPresentation";-import { Button } from "@posthog/quill";+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ Text,+} from "@posthog/quill";import {isTerminalStatus,type SignalReport,@@ -39,6 +46,7 @@ import {} from "@posthog/ui/features/inbox/components/SignalsList";import { ForYouBadge } from "@posthog/ui/features/inbox/components/utils/ForYouBadge";import { InboxBadge } from "@posthog/ui/features/inbox/components/utils/InboxBadge";+import { ReportTrackerIssueLink } from "@posthog/ui/features/inbox/components/utils/ReportTrackerIssueLink";import { SignalReportPriorityBadge } from "@posthog/ui/features/inbox/components/utils/SignalReportPriorityBadge";import { SignalReportSummaryMarkdown } from "@posthog/ui/features/inbox/components/utils/SignalReportSummaryMarkdown";import {@@ -58,7 +66,6 @@ import {reportNavigationState,} from "@posthog/ui/router/reportNavigation";import { openTask } from "@posthog/ui/router/useOpenTask";-import { DropdownMenu, Flex, Text } from "@radix-ui/themes";import { Link } from "@tanstack/react-router";import { useMemo, useState } from "react";@@ -96,19 +103,11 @@ function RunOutputWidget({ report }: { report: SignalReport }) {if (report.status === "failed") {return (- <Flex- align="center"- gap="3"- className="rounded-(--radius-2) border border-(--red-5) bg-(--red-2) px-4 py-3.5"- >- <Flex- align="center"- justify="center"- className="h-9 w-9 shrink-0 rounded-full bg-(--red-3) ring-(--red-6) ring-1 ring-inset"- >+ <div className="flex items-center gap-3 rounded-(--radius-2) border border-(--red-5) bg-(--red-2) px-4 py-3.5">+ <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-(--red-3) ring-(--red-6) ring-1 ring-inset"><WarningIcon size={16} className="text-(--red-11)" />- </Flex>- <Flex direction="column" gap="0.5" className="min-w-0 flex-1">+ </div>+ <div className="flex min-w-0 flex-1 flex-col gap-0.5"><Text className="font-medium text-[13px] text-gray-12">Run failed</Text>@@ -116,8 +115,8 @@ function RunOutputWidget({ report }: { report: SignalReport }) {Research couldn't complete – check the task log below for the error.The agent may retry automatically.</Text>- </Flex>- </Flex>+ </div>+ </div>);}@@ -268,7 +267,7 @@ function AgentRunDetailContent({ report }: { report: SignalReport }) {}, [reportTasks]);return (- <Flex direction="column" className="min-h-full">+ <div className="flex min-h-full flex-col"><InboxDetailPageHeaderbackTo="/inbox/runs"backLabel="Back to runs"@@ -363,7 +362,8 @@ function AgentRunDetailContent({ report }: { report: SignalReport }) {<div className="@container mx-auto w-full max-w-[calc(160ch+5rem)] px-6 py-5 text-[13px]"><div className="grid @4xl:grid-cols-[minmax(0,80ch)_minmax(0,1fr)] grid-cols-1 gap-5">- <Flex direction="column" gap="5" className="min-w-0">+ <div className="flex min-w-0 flex-col gap-5">+ <ReportTrackerIssueLink report={report} /><RunOutputWidget report={report} /><DetailSection@@ -378,10 +378,10 @@ function AgentRunDetailContent({ report }: { report: SignalReport }) {}>{isLoadingReportTasks ? (- <Flex direction="column" gap="2">+ <div className="flex flex-col gap-2"><span className="h-4 w-36 animate-pulse rounded bg-(--gray-3)" /><span className="h-28 w-full animate-pulse rounded-(--radius-2) bg-(--gray-2)" />- </Flex>+ </div>) : selectedTask ? (<div className="h-[calc(100vh-22rem)] min-h-[420px] w-full overflow-hidden rounded-(--radius-2) border border-border bg-(--color-panel-solid)"><TaskLogsPanel@@ -391,11 +391,7 @@ function AgentRunDetailContent({ report }: { report: SignalReport }) {/></div>) : (- <Flex- direction="column"- gap="2"- className="rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3.5"- >+ <div className="flex flex-col gap-2 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3.5"><Text className="font-medium text-[13px] text-gray-12">Waiting for the linked task</Text>@@ -404,12 +400,12 @@ function AgentRunDetailContent({ report }: { report: SignalReport }) {show the same live log UI as the task detail page. Noseparate mock log is shown here.</Text>- </Flex>+ </div>)}</DetailSection>- </Flex>+ </div>- <Flex direction="column" gap="5" className="min-w-0">+ <div className="flex min-w-0 flex-col gap-5">{(signals.length > 0 || report.signal_count > 0) && (<RightColumnSectionIcon={MagnifyingGlassIcon}@@ -429,10 +425,10 @@ function AgentRunDetailContent({ report }: { report: SignalReport }) {</RightColumnSection>)}<ReportActivitySection reportId={report.id} />- </Flex>+ </div></div></div>- </Flex>+ </div>);}@@ -454,29 +450,31 @@ function TaskLogRightSlot({);}return (- <DropdownMenu.Root>- <DropdownMenu.Trigger>- <button- type="button"- className="inline-flex items-center gap-1 rounded-(--radius-1) px-1.5 py-0.5 font-medium text-[12px] text-gray-11 hover:bg-(--gray-3) hover:text-gray-12 focus-visible:bg-(--gray-3) focus-visible:outline-none"- aria-label="Switch task"- >- <TaskRunStatusDot- status={selectedEntry.task.latest_run?.status ?? "not_started"}- />- {selectedEntry.purposeLabel}- <CaretDownIcon size={12} className="text-gray-10" />- </button>- </DropdownMenu.Trigger>- <DropdownMenu.Content align="end" sideOffset={4}>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ type="button"+ className="inline-flex items-center gap-1 rounded-(--radius-1) px-1.5 py-0.5 font-medium text-[12px] text-gray-11 hover:bg-(--gray-3) hover:text-gray-12 focus-visible:bg-(--gray-3) focus-visible:outline-none"+ aria-label="Switch task"+ >+ <TaskRunStatusDot+ status={selectedEntry.task.latest_run?.status ?? "not_started"}+ />+ {selectedEntry.purposeLabel}+ <CaretDownIcon size={12} className="text-gray-10" />+ </button>+ }+ />+ <DropdownMenuContent align="end" sideOffset={4}>{entries.map((entry) => {const status = entry.task.latest_run?.status ?? "not_started";return (- <DropdownMenu.Item+ <DropdownMenuItemkey={entry.task.id}- onSelect={() => onSelect(entry.task.id)}+ onClick={() => onSelect(entry.task.id)}>- <Flex align="center" gap="2" className="min-w-[200px]">+ <div className="flex min-w-[200px] items-center gap-2"><TaskRunStatusDot status={status} /><Text className="font-medium text-[12.5px]">{entry.purposeLabel}@@ -484,11 +482,11 @@ function TaskLogRightSlot({<Text className="ml-auto font-mono text-[11px] text-gray-10">{entry.task.id.slice(0, 8)}</Text>- </Flex>- </DropdownMenu.Item>+ </div>+ </DropdownMenuItem>);})}- </DropdownMenu.Content>- </DropdownMenu.Root>+ </DropdownMenuContent>+ </DropdownMenu>);}diff --git a/products/desktop/packages/ui/src/features/inbox/components/DismissedReportDetail.tsx b/products/desktop/packages/ui/src/features/inbox/components/DismissedReportDetail.tsxindex 68a366d2ad10..c5dd979fea43 100644--- a/products/desktop/packages/ui/src/features/inbox/components/DismissedReportDetail.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/DismissedReportDetail.tsx@@ -10,6 +10,7 @@ import { InboxDetailFrame } from "@posthog/ui/features/inbox/components/InboxDetimport { InboxReportCopyLinkMenu } from "@posthog/ui/features/inbox/components/InboxReportCopyLinkMenu";import { InboxReportDetailGate } from "@posthog/ui/features/inbox/components/InboxReportDetailGate";import { useReportPage } from "@posthog/ui/features/inbox/components/ReportPageContext";+import { ReportTrackerIssueLink } from "@posthog/ui/features/inbox/components/utils/ReportTrackerIssueLink";import {type InboxBackTarget,useInboxBackTarget,@@ -80,6 +81,7 @@ export function DismissedReportDetailContent({backLabel={back.label}fallbackTitle="Untitled report"showDismiss={false}+ metaSuffix={<ReportTrackerIssueLink report={report} />}primaryAction={<>{canRestore && <RestoreReportButton report={report} />}diff --git a/products/desktop/packages/ui/src/features/inbox/components/PullRequestDetail.tsx b/products/desktop/packages/ui/src/features/inbox/components/PullRequestDetail.tsxindex 775acbcae6a2..eb45801348f5 100644--- a/products/desktop/packages/ui/src/features/inbox/components/PullRequestDetail.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/PullRequestDetail.tsx@@ -9,6 +9,7 @@ import { PrDiffStats } from "@posthog/ui/features/inbox/components/PrDiffStats";import { ReportDetailActions } from "@posthog/ui/features/inbox/components/ReportDetailActions";import { ReportReviewersSection } from "@posthog/ui/features/inbox/components/ReportReviewersSection";import { ReportImplementationPrLink } from "@posthog/ui/features/inbox/components/utils/ReportImplementationPrLink";+import { ReportTrackerIssueLink } from "@posthog/ui/features/inbox/components/utils/ReportTrackerIssueLink";import { PrCommentsSection } from "@posthog/ui/features/pr-review/PrCommentsSection";import { PrDecisionBlock } from "@posthog/ui/features/pr-review/PrDecisionBlock";import { PrFilesChangedSection } from "@posthog/ui/features/pr-review/PrFilesChangedSection";@@ -59,8 +60,11 @@ export function PullRequestDetailContent({ report }: { report: SignalReport }) {<><InboxMetaSeparator /><ReportImplementationPrLink prUrl={prUrl} size="md" />+ <ReportTrackerIssueLink report={report} /></>- ) : undefined+ ) : (+ <ReportTrackerIssueLink report={report} />+ )}primaryAction={<ReportDetailActions report={report} prUrl={prUrl} />}summarySection={{ Icon: GitPullRequestIcon, title: "Summary" }}diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsxindex bd86a220249f..0b9b49f9a027 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx@@ -13,6 +13,7 @@ import { ReportDetailActions } from "@posthog/ui/features/inbox/components/Reporimport { ReportReviewersSection } from "@posthog/ui/features/inbox/components/ReportReviewersSection";import { ReportRunsSection } from "@posthog/ui/features/inbox/components/ReportRunsSection";import { ReportVerdictBanner } from "@posthog/ui/features/inbox/components/ReportVerdictBanner";+import { ReportTrackerIssueLink } from "@posthog/ui/features/inbox/components/utils/ReportTrackerIssueLink";import { useReportChatPanelStore } from "@posthog/ui/features/inbox/stores/reportChatPanelStore";import { useCallback, useEffect, useRef } from "react";@@ -103,11 +104,14 @@ export function ReportDetailContent({<ReportDetailActions report={report} placement="header" />}belowSummary={- <ReportVerdictBanner- key={report.id}- report={report}- initialEngagementOnly- />+ <>+ <ReportVerdictBanner+ key={report.id}+ report={report}+ initialEngagementOnly+ />+ <ReportTrackerIssueLink report={report} />+ </>}summarySection={{ Icon: FileTextIcon, title: "Report summary" }}footer={<ReportFeedbackFooter report={report} />}diff --git a/products/desktop/packages/ui/src/features/inbox/components/utils/ReportTrackerIssueLink.tsx b/products/desktop/packages/ui/src/features/inbox/components/utils/ReportTrackerIssueLink.tsxnew file mode 100644index 000000000000..af98c121285a--- /dev/null+++ b/products/desktop/packages/ui/src/features/inbox/components/utils/ReportTrackerIssueLink.tsx@@ -0,0 +1,65 @@+import { WarningIcon } from "@phosphor-icons/react";+import {+ cn,+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@posthog/quill";+import type { SignalReport } from "@posthog/shared/types";++/**+ * The tracker issue behind a report's pull request, or why there is none.+ *+ * A team that cannot merge without a tracked work item has to spot the pull requests that lack one,+ * so the failure sits next to the pull request badge rather than in a surface of its own.+ */+export function ReportTrackerIssueLink({ report }: { report: SignalReport }) {+ const badgeClass =+ "inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium";++ if (report.tracker_issue_url) {+ const trigger = (+ <a+ href={report.tracker_issue_url}+ target="_blank"+ rel="noreferrer"+ onClick={(e) => e.stopPropagation()}+ className={cn(badgeClass, "bg-gray-4 text-gray-11 hover:bg-gray-5")}+ >+ {report.tracker_issue_reference ?? "Tracked"}+ </a>+ );+ return (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger render={trigger} />+ <TooltipContent>Tracker issue for this report</TooltipContent>+ </Tooltip>+ </TooltipProvider>+ );+ }++ if (report.tracker_issue_error) {+ const trigger = (+ <button+ type="button"+ aria-label={`No tracker issue: ${report.tracker_issue_error}`}+ className={cn(badgeClass, "bg-amber-4 text-amber-11")}+ >+ <WarningIcon size={12} weight="bold" />+ No tracker issue+ </button>+ );+ return (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger render={trigger} />+ <TooltipContent>{report.tracker_issue_error}</TooltipContent>+ </Tooltip>+ </TooltipProvider>+ );+ }++ return null;+}diff --git a/products/error_tracking/backend/logic/external_references.py b/products/error_tracking/backend/logic/external_references.pyindex 6ea0ac9de279..f453e6e8bffc 100644--- a/products/error_tracking/backend/logic/external_references.py+++ b/products/error_tracking/backend/logic/external_references.py@@ -14,6 +14,8 @@ from posthog.models.integration import (Integration,JiraIntegration,LinearIntegration,+ external_issue_url,+ is_supported_external_issue_provider,)from products.error_tracking.backend.logic import get_issue_permalink_by_fingerprint@@ -24,15 +26,6 @@ class ErrorTrackingExternalReferenceValidationError(Exception):pass-SUPPORTED_EXTERNAL_ISSUE_PROVIDERS = frozenset(- {- Integration.IntegrationKind.LINEAR,- Integration.IntegrationKind.GITHUB,- Integration.IntegrationKind.GITLAB,- Integration.IntegrationKind.JIRA,- }-)-EXTERNAL_REFERENCE_REQUIRED_CONFIG_FIELDS = {Integration.IntegrationKind.GITHUB.value: ("repository", "title", "body"),Integration.IntegrationKind.GITLAB.value: ("title", "body"),@@ -59,10 +52,6 @@ LINK_EXISTING_REQUIRED_CONTEXT_FIELDS: dict[str, dict[str, type]] = {}-def is_supported_external_issue_provider(kind: str) -> bool:- return kind in SUPPORTED_EXTERNAL_ISSUE_PROVIDERS--def _validate_external_reference_config(integration: Integration, config: Any) -> None:if not isinstance(config, dict):raise ErrorTrackingExternalReferenceValidationError("External reference config must be an object.")@@ -274,36 +263,4 @@ def search_external_issues(def build_external_issue_url(reference: ErrorTrackingExternalReference) -> str:- external_context: dict[str, str] = reference.external_context or {}- integration = reference.integration-- if integration.kind == Integration.IntegrationKind.LINEAR:- issue_id = external_context.get("id")- if not issue_id:- return ""- url_key = LinearIntegration(integration).url_key()- return f"https://linear.app/{url_key}/issue/{issue_id}"-- if integration.kind == Integration.IntegrationKind.GITHUB:- repository = external_context.get("repository")- number = external_context.get("number")- if not repository or not number:- return ""- org = GitHubIntegration(integration).organization()- return f"https://github.com/{org}/{repository}/issues/{number}"-- if integration.kind == Integration.IntegrationKind.GITLAB:- issue_id = external_context.get("issue_id")- if not issue_id:- return ""- gitlab = GitLabIntegration(integration)- return f"{gitlab.hostname}/{gitlab.project_path}/issues/{issue_id}"-- if integration.kind == Integration.IntegrationKind.JIRA:- issue_key = external_context.get("key")- if not issue_key:- return ""- jira = JiraIntegration(integration)- return f"{jira.site_url()}/browse/{issue_key}"-- return ""+ return external_issue_url(reference.integration, reference.external_context)diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.tsindex 0ff9241dbc60..3923e7740c24 100644--- a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts+++ b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts@@ -11,7 +11,6 @@ import { HogFunctionType, IntegrationType } from '~/types'import { AlertNotificationUrlInput } from 'products/alerts/frontend/components/AlertNotificationDestinationEditor'import { logsAlertsDestinationsCreate, logsAlertsDestinationsDeleteCreate } from 'products/logs/frontend/generated/api'-import type { UserBasicType } from '../../../../../frontend/src/types'import {buildLogsAlertFilterConfig,groupLogsAlertDestinations,@@ -62,126 +61,10 @@ export interface logsAlertNotificationLogicActions {errorObject?: any} // integrationsLogicloadIntegrationsSuccess: (- integrations: {- config: any- created_at: string- created_by?: UserBasicType | null | undefined- display_name: string- errors?: string | undefined- files_write_requestable?: boolean | undefined- icon_url: any- id: number- installation_shared?: boolean | null | undefined- installation_status?:- | null- | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi- | undefined- kind:- | 'apns'- | 'aws-redshift'- | 'aws-s3'- | 'azure-blob'- | 'bing-ads'- | 'clickup'- | 'customerio-app'- | 'customerio-track'- | 'customerio-webhook'- | 'databricks'- | 'email'- | 'firebase'- | 'github'- | 'gitlab'- | 'google-ads'- | 'google-analytics'- | 'google-calendar'- | 'google-cloud-service-account'- | 'google-cloud-storage'- | 'google-pubsub'- | 'google-search-console'- | 'google-sheets'- | 'hubspot'- | 'instagram'- | 'intercom'- | 'jira'- | 'linear'- | 'linkedin-ads'- | 'meta-ads'- | 'pardot'- | 'pinterest-ads'- | 'postgresql'- | 'reddit-ads'- | 's3-compatible'- | 'salesforce'- | 'slack'- | 'snapchat'- | 'snowflake'- | 'stripe'- | 'tiktok-ads'- | 'twilio'- | 'vercel'- | 'youtube-analytics'- }[],+ integrations: IntegrationType[],payload?: any) => {- integrations: {- config: any- created_at: string- created_by?: UserBasicType | null | undefined- display_name: string- errors?: string | undefined- files_write_requestable?: boolean | undefined- icon_url: any- id: number- installation_shared?: boolean | null | undefined- installation_status?:- | null- | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi- | undefined- kind:- | 'apns'- | 'aws-redshift'- | 'aws-s3'- | 'azure-blob'- | 'bing-ads'- | 'clickup'- | 'customerio-app'- | 'customerio-track'- | 'customerio-webhook'- | 'databricks'- | 'email'- | 'firebase'- | 'github'- | 'gitlab'- | 'google-ads'- | 'google-analytics'- | 'google-calendar'- | 'google-cloud-service-account'- | 'google-cloud-storage'- | 'google-pubsub'- | 'google-search-console'- | 'google-sheets'- | 'hubspot'- | 'instagram'- | 'intercom'- | 'jira'- | 'linear'- | 'linkedin-ads'- | 'meta-ads'- | 'pardot'- | 'pinterest-ads'- | 'postgresql'- | 'reddit-ads'- | 's3-compatible'- | 'salesforce'- | 'slack'- | 'snapchat'- | 'snowflake'- | 'stripe'- | 'tiktok-ads'- | 'twilio'- | 'vercel'- | 'youtube-analytics'- }[]+ integrations: IntegrationType[]payload?: any} // integrationsLogicaddPendingNotification: (notification: PendingLogsAlertNotification) => {diff --git a/products/posthog_ai/frontend/logics/welcomeOverrideLogic.test.ts b/products/posthog_ai/frontend/logics/welcomeOverrideLogic.test.tsindex eeffefc728f7..d91034badf37 100644--- a/products/posthog_ai/frontend/logics/welcomeOverrideLogic.test.ts+++ b/products/posthog_ai/frontend/logics/welcomeOverrideLogic.test.ts@@ -16,7 +16,7 @@ describe('welcomeOverrideLogic', () => {get: {'/api/projects/:team/tasks/': { results: [], count: 0 },'/api/projects/:team/tasks/repositories/': { repositories: [] },- '/api/environments/:team/integrations/': { results: [] },+ '/api/projects/:team/integrations/': { results: [] },},})initKeaTests()diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsxindex 09c2592c81cf..2e37803c9083 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx@@ -131,7 +131,7 @@ const meta: Meta = {// Exact ids (not `:id`) so they never shadow the `repositories` action route.'/api/projects/:team_id/tasks/task-3/': TASKS[2],'/api/projects/:team_id/tasks/task-3/runs/': { count: 0, next: null, previous: null, results: [] },- '/api/environments/:team_id/integrations/': { results: [] },+ '/api/projects/:team_id/integrations/': { results: [] },},}),],@@ -166,7 +166,7 @@ export const NewTaskWithRepository: Story = {decorators: [mswDecorator({get: {- '/api/environments/:team_id/integrations/': { results: [GITHUB_INTEGRATION] },+ '/api/projects/:team_id/integrations/': { results: [GITHUB_INTEGRATION] },'/api/environments/:team_id/integrations/1/github_repos': {repositories: [{ id: 1, name: 'posthog', full_name: 'PostHog/posthog' },@@ -204,7 +204,7 @@ export const Loading: Story = {return HttpResponse.json(listResponse([]))},'/api/projects/:team_id/tasks/repositories/': { repositories: [] },- '/api/environments/:team_id/integrations/': { results: [] },+ '/api/projects/:team_id/integrations/': { results: [] },},}),],@@ -218,7 +218,7 @@ export const ListLoadError: Story = {'/api/projects/:team_id/tasks/': () =>HttpResponse.json({ detail: 'Could not load tasks.' }, { status: 500 }),'/api/projects/:team_id/tasks/repositories/': { repositories: [] },- '/api/environments/:team_id/integrations/': { results: [] },+ '/api/projects/:team_id/integrations/': { results: [] },},}),],@@ -319,7 +319,7 @@ export const Empty: Story = {get: {'/api/projects/:team_id/tasks/': listResponse([]),'/api/projects/:team_id/tasks/repositories/': { repositories: [] },- '/api/environments/:team_id/integrations/': { results: [] },+ '/api/projects/:team_id/integrations/': { results: [] },},}),],diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.test.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.test.tsxindex aec91a575147..abe88901cc09 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.test.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.test.tsx@@ -27,7 +27,7 @@ describe('RepositorySelector', () => {})useMocks({get: {- '/api/environments/:team/integrations/': {+ '/api/projects/:team/integrations/': {results: [{ id: 7, kind: 'github', display_name: 'acme', config: {} }],},// Gate the repo list so the loading → loaded transition is deterministic.diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.stories.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.stories.tsxindex 5ce7c73404f6..4a9fbbe33816 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.stories.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.stories.tsx@@ -36,7 +36,7 @@ const meta: Meta = {'/api/projects/:team/tasks/': { results: [], count: 0 },'/api/projects/:team/tasks/repositories/': { repositories: [] },'/api/projects/:team/tasks/@me/config/': { ai_run_preferences: {}, resolved_ai_run_defaults: {} },- '/api/environments/:team/integrations/': { results: [] },+ '/api/projects/:team/integrations/': { results: [] },},}),],diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.tsindex 9597463d310f..23d26bd35add 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts@@ -62,7 +62,7 @@ describe('taskTrackerSceneLogic', () => {'/api/projects/:team/tasks/': { results: [], count: 0 },'/api/projects/:team/tasks/repositories/': { repositories: [] },'/api/projects/:team/tasks/@me/config/': myConfigResponse(null),- '/api/environments/:team/integrations/': { results: [] },+ '/api/projects/:team/integrations/': { results: [] },},post: {'/api/projects/:team/tasks/': async ({ request }) => {@@ -493,7 +493,7 @@ describe('taskTrackerSceneLogic', () => {it('restores the repository integration after a submit so the picker reappears', async () => {useMocks({get: {- '/api/environments/:team/integrations/': {+ '/api/projects/:team/integrations/': {results: [{ id: 7, kind: 'github', display_name: 'acme/widgets', config: {} }],},},diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex 23b926279479..ff656549aaea 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -24,7 +24,7 @@ import {WarmTaskRequestOriginProductEnumApi,} from 'products/tasks/frontend/generated/api.schemas'-import type { IntegrationType, UserBasicType } from '../../../../../frontend/src/types'+import type { IntegrationType } from '../../../../../frontend/src/types'import { attachedContextItemKey, attachedContextLogic, runStreamLogic } from '../../api/logics'import type { SuggestionGroup, SuggestionItem } from '../../api/primitives'import { DEFAULT_HEADLINES, pickHeadline } from '../../api/primitives'@@ -193,126 +193,10 @@ export interface taskTrackerSceneLogicActions {seed: ComposerSeed} // composerSeedLogicloadIntegrationsSuccess: (- integrations: {- config: any- created_at: string- created_by?: UserBasicType | null | undefined- display_name: string- errors?: string | undefined- files_write_requestable?: boolean | undefined- icon_url: any- id: number- installation_shared?: boolean | null | undefined- installation_status?:- | null- | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi- | undefined- kind:- | 'apns'- | 'aws-redshift'- | 'aws-s3'- | 'azure-blob'- | 'bing-ads'- | 'clickup'- | 'customerio-app'- | 'customerio-track'- | 'customerio-webhook'- | 'databricks'- | 'email'- | 'firebase'- | 'github'- | 'gitlab'- | 'google-ads'- | 'google-analytics'- | 'google-calendar'- | 'google-cloud-service-account'- | 'google-cloud-storage'- | 'google-pubsub'- | 'google-search-console'- | 'google-sheets'- | 'hubspot'- | 'instagram'- | 'intercom'- | 'jira'- | 'linear'- | 'linkedin-ads'- | 'meta-ads'- | 'pardot'- | 'pinterest-ads'- | 'postgresql'- | 'reddit-ads'- | 's3-compatible'- | 'salesforce'- | 'slack'- | 'snapchat'- | 'snowflake'- | 'stripe'- | 'tiktok-ads'- | 'twilio'- | 'vercel'- | 'youtube-analytics'- }[],+ integrations: IntegrationType[],payload?: any) => {- integrations: {- config: any- created_at: string- created_by?: UserBasicType | null | undefined- display_name: string- errors?: string | undefined- files_write_requestable?: boolean | undefined- icon_url: any- id: number- installation_shared?: boolean | null | undefined- installation_status?:- | null- | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi- | undefined- kind:- | 'apns'- | 'aws-redshift'- | 'aws-s3'- | 'azure-blob'- | 'bing-ads'- | 'clickup'- | 'customerio-app'- | 'customerio-track'- | 'customerio-webhook'- | 'databricks'- | 'email'- | 'firebase'- | 'github'- | 'gitlab'- | 'google-ads'- | 'google-analytics'- | 'google-calendar'- | 'google-cloud-service-account'- | 'google-cloud-storage'- | 'google-pubsub'- | 'google-search-console'- | 'google-sheets'- | 'hubspot'- | 'instagram'- | 'intercom'- | 'jira'- | 'linear'- | 'linkedin-ads'- | 'meta-ads'- | 'pardot'- | 'pinterest-ads'- | 'postgresql'- | 'reddit-ads'- | 's3-compatible'- | 'salesforce'- | 'slack'- | 'snapchat'- | 'snowflake'- | 'stripe'- | 'tiktok-ads'- | 'twilio'- | 'vercel'- | 'youtube-analytics'- }[]+ integrations: IntegrationType[]payload?: any} // integrationsLogicclearActiveCreation: () => {diff --git a/products/replay_vision/frontend/replay_scanners/scannerAlertNotificationLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerAlertNotificationLogic.tsindex 2374aba3591a..99d8a5550c85 100644--- a/products/replay_vision/frontend/replay_scanners/scannerAlertNotificationLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerAlertNotificationLogic.ts@@ -59,126 +59,10 @@ export interface scannerAlertNotificationLogicActions {errorObject?: any} // integrationsLogicloadIntegrationsSuccess: (- integrations: {- config: any- created_at: string- created_by?: null | import('~/types').UserBasicType | undefined- display_name: string- errors?: string | undefined- files_write_requestable?: boolean | undefined- icon_url: any- id: number- installation_shared?: boolean | null | undefined- installation_status?:- | null- | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi- | undefined- kind:- | 'apns'- | 'aws-redshift'- | 'aws-s3'- | 'azure-blob'- | 'bing-ads'- | 'clickup'- | 'customerio-app'- | 'customerio-track'- | 'customerio-webhook'- | 'databricks'- | 'email'- | 'firebase'- | 'github'- | 'gitlab'- | 'google-ads'- | 'google-analytics'- | 'google-calendar'- | 'google-cloud-service-account'- | 'google-cloud-storage'- | 'google-pubsub'- | 'google-search-console'- | 'google-sheets'- | 'hubspot'- | 'instagram'- | 'intercom'- | 'jira'- | 'linear'- | 'linkedin-ads'- | 'meta-ads'- | 'pardot'- | 'pinterest-ads'- | 'postgresql'- | 'reddit-ads'- | 's3-compatible'- | 'salesforce'- | 'slack'- | 'snapchat'- | 'snowflake'- | 'stripe'- | 'tiktok-ads'- | 'twilio'- | 'vercel'- | 'youtube-analytics'- }[],+ integrations: IntegrationType[],payload?: any) => {- integrations: {- config: any- created_at: string- created_by?: null | import('~/types').UserBasicType | undefined- display_name: string- errors?: string | undefined- files_write_requestable?: boolean | undefined- icon_url: any- id: number- installation_shared?: boolean | null | undefined- installation_status?:- | null- | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi- | undefined- kind:- | 'apns'- | 'aws-redshift'- | 'aws-s3'- | 'azure-blob'- | 'bing-ads'- | 'clickup'- | 'customerio-app'- | 'customerio-track'- | 'customerio-webhook'- | 'databricks'- | 'email'- | 'firebase'- | 'github'- | 'gitlab'- | 'google-ads'- | 'google-analytics'- | 'google-calendar'- | 'google-cloud-service-account'- | 'google-cloud-storage'- | 'google-pubsub'- | 'google-search-console'- | 'google-sheets'- | 'hubspot'- | 'instagram'- | 'intercom'- | 'jira'- | 'linear'- | 'linkedin-ads'- | 'meta-ads'- | 'pardot'- | 'pinterest-ads'- | 'postgresql'- | 'reddit-ads'- | 's3-compatible'- | 'salesforce'- | 'slack'- | 'snapchat'- | 'snowflake'- | 'stripe'- | 'tiktok-ads'- | 'twilio'- | 'vercel'- | 'youtube-analytics'- }[]+ integrations: IntegrationType[]payload?: any} // integrationsLogicaddPendingNotification: (notification: PendingVisionAlertNotification) => {diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex b9be04ba8ce5..edc7a668cc80 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -1182,6 +1182,18 @@ Runs inside `maybe_autostart_implementation_task()` in `backend/auto_start.py`,2. `record_implementation_task` writes the legacy `SignalReportTask` implementation gate row (in the same transaction) and appends an `implementation` `task_run` artefact3. Errors are caught and logged but do not fail the report workflow+**Tracker issue per pull request** (`backend/tracker_issues.py`, off by default).++Some teams cannot merge a pull request unless a tracked work item points at it. `SignalTeamConfig.issue_tracking_integration` names the tracker (GitHub, GitLab, Linear, or Jira) and `issue_tracking_config` names the target inside it; a null integration means the team wants no tracker issues, so one field is both the switch and the target.++`_create_implementation_task_if_absent` opens the issue after it creates the implementation task, outside the report lock because the call is network I/O. This order prevents an issue from outliving a task transaction that fails. A `SignalReportTrackerIssue` row per report keeps two evaluations from opening duplicate issues. Linear receives a direct attachment after the pull request opens, and the pull request body also links to the issue.++The create never raises. A provider failure is stored on the row as `status=failed` with a short reason, which the report surfaces next to the pull request, and the run opens its pull request either way.++Once the pull request exists, `link_report_tracker_issues` (scheduled from the task-run PR sync receiver) appends the reference to the pull request body, behind an HTML-comment marker so the append happens once. GitHub gets `Closes #n`; the other providers get the issue link. A Linear issue also gets the pull request as an attachment, best effort, because the scope for it may not be granted.++An irreversible end closes the tracker issue: a resolve asked for through the state API, a merged pull request (closed as done), or a deleted report. A suppressed or snoozed report keeps its issue open, because both come back, and so does a failed run, because its report stays in the inbox and the work item is still real.+**Fleet steering in the task description** (`load_report_steering` in `backend/report_steering.py`).Scouts read the team's steering notes at the start of every run, and the implementation run that acts on their report did not, so guidance like "this area is frozen" reached the agent that filed the report but never the agent that wrote the code. The description now carries it: the `HUMAN`-origin notes addressed to the whole fleet plus those addressed to the report's authoring scout (`scout_authorship.resolve_report_scout_skill`, the same emit-time resolution the dismissal path uses), newest first, capped at 10 notes and 1,000 characters each.diff --git a/products/signals/backend/admin.py b/products/signals/backend/admin.pyindex 44756de1f34c..a3939803c052 100644--- a/products/signals/backend/admin.py+++ b/products/signals/backend/admin.py@@ -264,10 +264,11 @@ class SignalTeamConfigAdmin(admin.ModelAdmin):)list_display_links = ("id",)search_fields = ("id", "team__name", "team__organization__name", "default_slack_notification_channel")- raw_id_fields = ("team",)+ raw_id_fields = ("team", "issue_tracking_integration")# autostart_base_branches is free-form JSON with no form-level shape check; a non-dict value would# crash the autostart worker (it calls .get() on it). It's owned by the API, so keep it read-only here.- readonly_fields = ("id", "autostart_base_branches", "created_at", "updated_at")+ # issue_tracking_config is the same: the API validates it against the chosen provider.+ readonly_fields = ("id", "autostart_base_branches", "issue_tracking_config", "created_at", "updated_at")list_select_related = ("team", "team__organization")show_full_result_count = Falsediff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.pyindex 74827784880a..b7a07dee8524 100644--- a/products/signals/backend/auto_start.py+++ b/products/signals/backend/auto_start.py@@ -60,6 +60,7 @@ from products.signals.backend.task_run_artefacts import (TASK_RUN_TYPE_IMPLEMENTATION,record_implementation_task,)+from products.signals.backend.tracker_issues import create_tracker_issue_for_reportfrom products.tasks.backend.facade import api as tasks_facadelogger = structlog.get_logger(__name__)@@ -208,6 +209,7 @@ def _generate_self_driving_head_branch(title: str) -> str:can write (see tasks' ``find_signal_implementation_run``). The slug keeps branch namesreadable; the random suffix is only there to prevent collisions between runs off similarlytitled reports.+"""slug = slugify(title)if len(slug) > 40:@@ -404,6 +406,8 @@ def _create_implementation_task_if_absent(# Resolved outside the transaction: the flag read does network I/O and must not hold the row lock.agent_runtime = resolve_agent_runtime(team_id, STEP_IMPLEMENTATION)+ # Create the task before the provider issue. A failed task creation must not leave an external+ # issue that says Self-driving started work when no run exists.head_branch = _generate_self_driving_head_branch(title)description = description + _head_branch_instruction(head_branch)@@ -466,6 +470,7 @@ def _create_implementation_task_if_absent(task_id=task_id,run_id=str(created.latest_run.id),)+ create_tracker_issue_for_report(team_id=team_id, report_id=report_id, repository=repository)if exempt_reason and task_id:# After commit: the exempt report's implementation task exists — count it (includes a# best-effort ClickHouse lookup, so it must not run under the lock).diff --git a/products/signals/backend/migrations/0126_signalteamconfig_issue_tracking_config_and_more.py b/products/signals/backend/migrations/0126_signalteamconfig_issue_tracking_config_and_more.pynew file mode 100644index 000000000000..24e42b21aaaf--- /dev/null+++ b/products/signals/backend/migrations/0126_signalteamconfig_issue_tracking_config_and_more.py@@ -0,0 +1,91 @@+# Generated by Django 5.2.17 on 2026-09-04 13:05++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", "1344_squash_2026_09_07_finalize_fks"),+ ("signals", "0125_signalreport_scout_idem_key_index"),+ ]++ operations = [+ migrations.AddField(+ model_name="signalteamconfig",+ name="issue_tracking_config",+ field=models.JSONField(blank=True, db_default={}, default=dict),+ ),+ migrations.AddField(+ model_name="signalteamconfig",+ name="issue_tracking_integration",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to="posthog.integration",+ ),+ ),+ migrations.CreateModel(+ name="SignalReportTrackerIssue",+ fields=[+ (+ "id",+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),+ ),+ ("provider", models.CharField(blank=True, max_length=50, null=True)),+ (+ "status",+ models.CharField(+ choices=[("pending", "Pending"), ("created", "Created"), ("failed", "Failed")], max_length=10+ ),+ ),+ ("external_context", models.JSONField(blank=True, null=True)),+ ("issue_url", models.TextField(blank=True, null=True)),+ ("failure_reason", models.TextField(blank=True, null=True)),+ ("pr_linked_at", models.DateTimeField(blank=True, null=True)),+ ("closed_at", models.DateTimeField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "integration",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to="posthog.integration",+ ),+ ),+ (+ "report",+ models.OneToOneField(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="tracker_issue",+ 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 tracker issue",+ "verbose_name_plural": "Signal report tracker issues",+ "default_manager_name": "all_teams",+ },+ 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 31751a102276..2528dd8bdd6c 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0125_signalreport_scout_idem_key_index+0126_signalteamconfig_issue_tracking_config_and_morediff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 45be7286a4c1..259faee65652 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -167,6 +167,18 @@ class SignalTeamConfig(ModelActivityMixin, UUIDModel):# within the project-timezone day. Once reached, the whole generation pipeline pauses until# local midnight (see daily_limit.py). Null means unlimited.max_reports_per_day = models.PositiveIntegerField(null=True, blank=True, validators=[MinValueValidator(1)])+ # Tracker issue per self-driving PR (see tracker_issues.py). The integration is the switch:+ # null means the team does not want tracker issues, so there is no separate boolean that can+ # disagree with the target. `issue_tracking_config` holds the provider target, for example+ # {"team_id": ...} for Linear or {"repository": ...} for GitHub.+ issue_tracking_integration = models.ForeignKey(+ "posthog.Integration",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ related_name="+",+ )+ issue_tracking_config = models.JSONField(default=dict, db_default={}, blank=True)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)@@ -881,6 +893,58 @@ class SignalReportAssignment(TeamScopedRootMixin, UUIDModel):return SignalReportWorkState.UNCLAIMED+class SignalReportTrackerIssue(TeamScopedRootMixin, UUIDModel):+ """The tracker issue opened for a report's self-driving pull request.++ Teams under a change-management audit cannot merge a pull request unless a tracked work item+ points at it. One row per report records that work item, or records why we could not open one,+ so the team can find the gaps without reading logs.+ """++ class Status(models.TextChoices):+ # Claimed by one auto-start evaluation, which is calling the provider now. Auto-start is+ # re-evaluated from several paths at once, and this row is what keeps two of them from each+ # opening an issue for the same report.+ PENDING = "pending", "Pending"+ CREATED = "created", "Created"+ FAILED = "failed", "Failed"++ all_teams = models.Manager() # noqa: DJ012++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")+ report = models.OneToOneField(SignalReport, on_delete=models.CASCADE, related_name="tracker_issue")++ # SET_NULL rather than CASCADE: disconnecting the integration must not erase the audit trail of+ # which issues self-driving already opened.+ integration = models.ForeignKey(+ "posthog.Integration", on_delete=models.SET_NULL, null=True, blank=True, related_name="+"+ )+ # The integration kind at creation time, kept so the row still reads correctly once the+ # integration row is gone.+ provider = models.CharField(max_length=50, null=True, blank=True)++ status = models.CharField(max_length=10, choices=Status)+ # Provider identifier, in the same shape the integration clients return: {"id": "ENG-123"} for+ # Linear, {"repository": ..., "number": ...} for GitHub, {"issue_id": ...} for GitLab,+ # {"key": ...} for Jira.+ external_context = models.JSONField(null=True, blank=True)+ issue_url = models.TextField(null=True, blank=True)+ # Short, user-facing reason the issue could not be opened. Set only when status is FAILED.+ failure_reason = models.TextField(null=True, blank=True)+ # When the pull request and the issue were cross-referenced. Null while the run has no PR yet.+ pr_linked_at = models.DateTimeField(null=True, blank=True)+ # When we closed the issue in the provider, after the report was dismissed.+ closed_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"+ verbose_name = "Signal report tracker issue"+ verbose_name_plural = "Signal report tracker issues"++class SignalEmissionRecord(UUIDModel):"""Tracks which source records have been emitted as signals.diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.pyindex 9eb00ca9adf0..5fcd5ffda153 100644--- a/products/signals/backend/receivers.py+++ b/products/signals/backend/receivers.py@@ -28,7 +28,11 @@ from products.signals.backend.report_embeddings import (render_report_document,)from products.signals.backend.scout_harness.suggestions import mark_stale_if_fleet_changed-from products.signals.backend.tasks import close_dismissed_report_pr+from products.signals.backend.tasks import (+ close_dismissed_report_pr,+ close_report_tracker_issue,+ link_report_tracker_issues,+)from products.tasks.backend.facade.task_run_signals import connect_task_run_post_savelogger = structlog.get_logger(__name__)@@ -60,13 +64,22 @@ def sync_task_run_pr_to_assignments(sender: type, instance: Any, created: bool,ai_stage = (instance.state or {}).get("ai_stage")if ai_stage in {"research", "repo_selection"} or (isinstance(ai_stage, str) and ai_stage.startswith("scout:")):return- sync_task_pull_request_to_assignments(+ updated = sync_task_pull_request_to_assignments(team_id=instance.team_id,task_id=str(instance.task_id),pr_url=pr_url,pr_state=output.get("pr_state") if isinstance(output.get("pr_state"), str) else None,pr_merged=output.get("pr_merged") is True,)+ if updated:+ team_id = instance.team_id+ task_id = str(instance.task_id)+ # The pull request now exists, so it can carry a reference to the tracker issue the run+ # opened. Off the request path because it calls GitHub, and after commit so a rolled-back+ # sync never edits a pull request body.+ transaction.on_commit(+ lambda: link_report_tracker_issues.delay(team_id=team_id, task_id=task_id, pr_url=pr_url)+ )except Exception:logger.exception("signals.task_run_pr_assignment_sync_failed", task_run_id=str(instance.id))@@ -177,20 +190,33 @@ def capture_prior_state()-def _pr_close_reason(+def _status_changed_on_this_save(instance: SignalReport,*,created: bool,update_fields: set[str] | None,prior_status: str | None,-) -> PrCloseReason | None:+) -> bool:+ """Whether this save is the one that moved the report to another status."""if created:# Reports born SUPPRESSED by the scout safety/actionability judge never surfaced a PR.- return None+ return False# React only to the save that performed the transition, not later edits.if update_fields is not None and "status" not in update_fields:- return None- if prior_status is None or prior_status == instance.status:+ return False+ return prior_status is not None and prior_status != instance.status+++def _pr_close_reason(+ instance: SignalReport,+ *,+ created: bool,+ update_fields: set[str] | None,+ prior_status: str | None,+) -> PrCloseReason | None:+ if not _status_changed_on_this_save(+ instance, created=created, update_fields=update_fields, prior_status=prior_status+ ):return None# The pull request's own observed state drove this transition, so there is nothing left to close.if getattr(instance, "_status_from_pr_state", False):@@ -234,6 +260,22 @@ def close_pr_when_report_dismissed(prior_status=prior_status,)if reason is None:+ if not _status_changed_on_this_save(+ instance, created=created, update_fields=update_fields, prior_status=prior_status+ ):+ return+ team_id = instance.team_id+ report_id = str(instance.id)+ if getattr(instance, "_status_from_pr_state", False) and instance.status == SignalReport.Status.RESOLVED:+ transaction.on_commit(+ lambda: close_report_tracker_issue.delay(report_id=report_id, team_id=team_id, completed=True)+ )+ elif instance.status == SignalReport.Status.DELETED:+ # A deleted report leaves the inbox for good, so nothing will ever answer its work+ # item. The issue closes as not done, because no pull request completed the work.+ transaction.on_commit(+ lambda: close_report_tracker_issue.delay(report_id=report_id, team_id=team_id, completed=False)+ )returnteam_id = instance.team_iddiff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex 153fbd5a6379..dc3aa542cbd6 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -9,9 +9,11 @@ from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_fieldfrom rest_framework import serializers+from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import User+from posthog.models.integration import Integration, is_supported_external_issue_providerfrom products.signals.backend import contractsfrom products.signals.backend.billing import REFUND_INELIGIBILITY_REASONS, refund_ineligibility_reason@@ -29,6 +31,7 @@ from .models import (SignalReportArtefact,SignalReportAssignment,SignalReportRefund,+ SignalReportTrackerIssue,SignalReportWorkState,SignalSourceConfig,SignalTeamConfig,@@ -36,6 +39,7 @@ from .models import ()from .report_charts import CHART_SIZES, MAX_CHART_CAPTION_LENGTH, MAX_CHART_ID_LENGTH, MAX_CHART_TITLE_LENGTHfrom .report_generation.resolve_reviewers import enrich_reviewer_dicts_with_org_members+from .tracker_issues import TRACKER_TARGET_REQUIRED_FIELDS, issue_reference, validated_github_repositoryDEFAULT_SESSION_ANALYSIS_SAMPLE_RATE = 0.1@@ -249,6 +253,26 @@ MAX_AUTOSTART_BASE_BRANCH_ENTRIES = 500class SignalTeamConfigSerializer(serializers.ModelSerializer):+ issue_tracking_integration = TeamScopedPrimaryKeyRelatedField(+ queryset=Integration.objects.all(),+ required=False,+ allow_null=True,+ help_text=(+ "Connected GitHub, GitLab, Linear, or Jira integration that self-driving opens a tracker "+ "issue in for each pull request it makes. Null turns tracker issues off, which is the "+ "default."+ ),+ )+ issue_tracking_config = serializers.DictField(+ child=serializers.CharField(max_length=255, allow_blank=True),+ required=False,+ help_text=(+ "Where in the tracker the issues land. Required keys depend on the integration kind: "+ "github -> {repository}; linear -> {team_id}; jira -> {project_key}; gitlab needs none, "+ "because its integration is already bound to one project. An optional 'label' is applied "+ "to created GitHub issues."+ ),+ )autostart_base_branches = serializers.DictField(child=serializers.CharField(max_length=255, allow_blank=True),required=False,@@ -314,6 +338,8 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):"default_autostart_priority","default_slack_notification_channel","autostart_base_branches",+ "issue_tracking_integration",+ "issue_tracking_config","max_reports_per_day","reports_generated_today","daily_report_limit_reached",@@ -338,6 +364,49 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):},}+ def validate_issue_tracking_integration(self, value: Integration | None) -> Integration | None:+ if value is None:+ return None+ if not is_supported_external_issue_provider(value.kind):+ raise serializers.ValidationError(+ f"'{value.kind}' cannot track issues. Connect GitHub, GitLab, Linear, or Jira."+ )+ return value++ def validate(self, attrs: dict) -> dict:+ attrs = super().validate(attrs)+ # The target only makes sense against an integration, and the two can arrive in either the+ # same PATCH or separate ones, so fall back to what is already stored.+ integration = (+ attrs["issue_tracking_integration"]+ if "issue_tracking_integration" in attrs+ else getattr(self.instance, "issue_tracking_integration", None)+ )+ if integration is None:+ return attrs+ config = (+ attrs["issue_tracking_config"]+ if "issue_tracking_config" in attrs+ else getattr(self.instance, "issue_tracking_config", None) or {}+ )+ missing = [+ field+ for field in TRACKER_TARGET_REQUIRED_FIELDS.get(integration.kind, ())+ if not str(config.get(field) or "").strip()+ ]+ if missing:+ raise serializers.ValidationError(+ {"issue_tracking_config": f"Missing required fields for {integration.kind}: {', '.join(missing)}."}+ )+ # The repository reaches a GitHub path, so a name it cannot hold fails here rather than on+ # every run.+ if integration.kind == Integration.IntegrationKind.GITHUB:+ try:+ validated_github_repository(config["repository"])+ except serializers.ValidationError as error:+ raise serializers.ValidationError({"issue_tracking_config": error.detail})+ return attrs+def validate_autostart_base_branches(self, value: dict) -> dict:if len(value) > MAX_AUTOSTART_BASE_BRANCH_ENTRIES:raise serializers.ValidationError(@@ -679,6 +748,24 @@ class SignalReportSerializer(serializers.ModelSerializer):"resolved directly, without a merged PR."),)+ tracker_issue_url = serializers.SerializerMethodField(+ help_text=(+ "Link to the issue self-driving opened in the team's tracker for this report's pull "+ "request. Null when the team tracks no issues, or the issue could not be opened."+ ),+ )+ tracker_issue_reference = serializers.SerializerMethodField(+ help_text=(+ "How that tracker issue reads in its provider, for example '#12' or 'ENG-123'. Null "+ "when there is no tracker issue."+ ),+ )+ tracker_issue_error = serializers.SerializerMethodField(+ help_text=(+ "Why the tracker issue could not be opened, for a team that wants one. Null when the "+ "issue exists or the team tracks no issues."+ ),+ )work_state = serializers.SerializerMethodField(help_text="Derived remediation state: unclaimed, working, in_review, or done.",)@@ -724,6 +811,9 @@ class SignalReportSerializer(serializers.ModelSerializer):"implementation_pr_url","implementation_pr_state","implementation_pr_merged",+ "tracker_issue_url",+ "tracker_issue_reference",+ "tracker_issue_error","work_state","assignee","refund",@@ -883,6 +973,33 @@ class SignalReportSerializer(serializers.ModelSerializer):merged_report_ids: set[str] | None = self.context.get("implementation_pr_merged_ids")return str(obj.id) in merged_report_ids if merged_report_ids is not None else False+ @staticmethod+ def _get_tracker_issue(obj: SignalReport) -> SignalReportTrackerIssue | None:+ # Reverse OneToOne: RelatedObjectDoesNotExist subclasses AttributeError, so getattr+ # degrades to None for reports with no tracker issue. The viewset select_related()s it.+ return getattr(obj, "tracker_issue", None)++ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_tracker_issue_url(self, obj: SignalReport) -> str | None:+ tracker = self._get_tracker_issue(obj)+ if tracker is None or tracker.status != SignalReportTrackerIssue.Status.CREATED:+ return None+ return tracker.issue_url or None++ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_tracker_issue_reference(self, obj: SignalReport) -> str | None:+ tracker = self._get_tracker_issue(obj)+ if tracker is None or tracker.status != SignalReportTrackerIssue.Status.CREATED:+ return None+ return issue_reference(tracker)++ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_tracker_issue_error(self, obj: SignalReport) -> str | None:+ tracker = self._get_tracker_issue(obj)+ if tracker is None or tracker.status != SignalReportTrackerIssue.Status.FAILED:+ return None+ return tracker.failure_reason or "Could not open the tracker issue."+@extend_schema_field(serializers.ChoiceField(choices=SignalReportWorkState.choices))def get_work_state(self, obj: SignalReport) -> str:if obj.status == SignalReport.Status.RESOLVED:diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex c2f88ef95ba1..bd3013178aca 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -26,6 +26,7 @@ from products.signals.backend.implementation_pr import PrCloseReason, close_implfrom products.signals.backend.models import (SignalReport,SignalReportRefund,+ SignalReportTrackerIssue,SignalRepositoryAreaActivity,SignalScoutEmission,SignalScoutRun,@@ -49,6 +50,7 @@ from products.signals.backend.scout_harness.slack_delivery import (slack_api_error_code,)from products.signals.backend.slack_inbox_notifications import dispatch_reviewer_added_notifications+from products.signals.backend.tracker_issues import close_tracker_issue_for_report, link_pull_request_to_tracker_issuefrom products.tasks.backend.facade.repo_activity import RepositoryCommitActivityErrorlogger = structlog.get_logger(__name__)@@ -88,6 +90,69 @@ _SCOUT_SLACK_RETRY_MAX_SECONDS = 3600@with_team_scope()def close_dismissed_report_pr(report_id: str, team_id: int, reason: PrCloseReason = "suppressed") -> None:close_implementation_pr_for_report(team_id, report_id, reason=reason)+ # Suppression and snoozing are reversible. Keep their tracker issue open for a restored report.+ if reason == "resolved":+ close_report_tracker_issue.delay(report_id=report_id, team_id=team_id, completed=False)+++@shared_task(+ name="products.signals.backend.tasks.close_report_tracker_issue",+ ignore_result=True,+ bind=True,+ max_retries=5,+)+@with_team_scope()+def close_report_tracker_issue(self, report_id: str, team_id: int, completed: bool = False) -> None:+ if close_tracker_issue_for_report(team_id=team_id, report_id=report_id, completed=completed):+ return+ retry_needed = (+ SignalReportTrackerIssue.objects.for_team(team_id)+ .filter(+ report_id=report_id,+ status__in=[SignalReportTrackerIssue.Status.PENDING, SignalReportTrackerIssue.Status.CREATED],+ closed_at__isnull=True,+ )+ .exists()+ )+ if retry_needed:+ raise self.retry(countdown=min(60 * (2**self.request.retries), 900))+++@shared_task(+ name="products.signals.backend.tasks.link_report_tracker_issues",+ ignore_result=True,+ bind=True,+ max_retries=5,+)+@with_team_scope()+def link_report_tracker_issues(self, team_id: int, task_id: str, pr_url: str) -> None:+ """Cross-reference a task's new pull request with the tracker issue of every report it answers."""+ report_ids = (+ SignalReport.objects.filter(team_id=team_id)+ .filter(SignalReport.reports_for_task_filter(task_id))+ .values_list("id", flat=True)+ )+ retry_needed = False+ for report_id in report_ids:+ linked = link_pull_request_to_tracker_issue(team_id=team_id, report_id=str(report_id), pr_url=pr_url)+ if not linked:+ retry_needed = (+ retry_needed+ or SignalReportTrackerIssue.objects.for_team(team_id)+ .filter(+ # PENDING counts too: a fast run can report its pull request while the+ # provider call is still in flight, and that issue still needs the reference.+ report_id=report_id,+ status__in=(+ SignalReportTrackerIssue.Status.CREATED,+ SignalReportTrackerIssue.Status.PENDING,+ ),+ pr_linked_at__isnull=True,+ )+ .exists()+ )+ if retry_needed:+ raise self.retry(countdown=min(60 * (2**self.request.retries), 900))def _slack_retry_after_seconds(exc: Exception) -> int | None:diff --git a/products/signals/backend/test/test_dismissal_pr_close.py b/products/signals/backend/test/test_dismissal_pr_close.pyindex a9505d738051..d591e38e9b81 100644--- a/products/signals/backend/test/test_dismissal_pr_close.py+++ b/products/signals/backend/test/test_dismissal_pr_close.py@@ -105,6 +105,38 @@ class TestClosePrWhenReportDismissed(BaseTest):self._save_transition(report, SignalReport.Status.RESOLVED)mock_task.delay.assert_not_called()+ def test_pr_merge_enqueues_completed_tracker_close(self):+ report = self._create_report()+ SignalReportAssignment.all_teams.create(+ team=self.team,+ report=report,+ pr_url=_PR_URL,+ repository="posthog/posthog",+ pr_number=123,+ pr_state=SignalReportAssignment.PrState.OPEN,+ )++ with patch("products.signals.backend.receivers.close_report_tracker_issue") as mock_task:+ with self.captureOnCommitCallbacks(execute=True):+ update_assignments_for_pull_request(+ team_ids=[self.team.id],+ repository="posthog/posthog",+ pr_number=123,+ pr_state=SignalReportAssignment.PrState.MERGED,+ )++ mock_task.delay.assert_called_once_with(report_id=str(report.id), team_id=self.team.id, completed=True)++ def test_deleting_a_report_enqueues_a_tracker_close(self):+ # A deleted report never returns to the inbox, so its tracker issue would otherwise stay+ # open with nothing left to answer it.+ report = self._create_report()++ with patch("products.signals.backend.receivers.close_report_tracker_issue") as mock_task:+ self._save_transition(report, SignalReport.Status.DELETED)++ mock_task.delay.assert_called_once_with(report_id=str(report.id), team_id=self.team.id, completed=False)+def test_pr_closed_webhook_does_not_enqueue_for_any_linked_report(self):reports = [self._create_report(), self._create_report()]for report in reports:diff --git a/products/signals/backend/test/test_tracker_issues.py b/products/signals/backend/test/test_tracker_issues.pynew file mode 100644index 000000000000..d0c65d82a377--- /dev/null+++ b/products/signals/backend/test/test_tracker_issues.py@@ -0,0 +1,365 @@+from datetime import timedelta+from typing import Any++import pytest+from unittest.mock import patch++from django.utils import timezone++from celery.exceptions import Retry+from rest_framework.exceptions import ValidationError as DRFValidationError++from posthog.models import Team+from posthog.models.integration import (+ GitHubIntegration,+ GitHubIntegrationError,+ GitLabIntegration,+ Integration,+ JiraIntegration,+ LinearIntegration,+)++from products.signals.backend.models import SignalReport, SignalReportTrackerIssue, SignalTeamConfig+from products.signals.backend.serializers import SignalTeamConfigSerializer+from products.signals.backend.tasks import close_report_tracker_issue+from products.signals.backend.tracker_issues import (+ ABANDONED_CLAIM_REASON,+ PR_BODY_MARKER,+ close_tracker_issue_for_report,+ create_tracker_issue_for_report,+ issue_reference,+ link_pull_request_to_tracker_issue,+)++INTEGRATION_CONFIGS = {+ "github": {"account": {"name": "acme"}},+ "gitlab": {"hostname": "https://gitlab.com", "path_with_namespace": "acme/web", "project_id": 7},+ "linear": {"data": {"viewer": {"organization": {"urlKey": "acme"}}}},+ "jira": {"cloud_id": "cloud-1", "site_url": "https://acme.atlassian.net"},+}++TRACKER_TARGETS = {+ "github": {"repository": "web"},+ "gitlab": {},+ "linear": {"team_id": "team-uuid"},+ "jira": {"project_key": "ENG"},+}++CREATED_CONTEXTS: dict[str, dict[str, Any]] = {+ "github": {"repository": "web", "number": 12},+ "gitlab": {"issue_id": 34},+ "linear": {"id": "ENG-123"},+ "jira": {"key": "ENG-9", "id": "1001"},+}++INTEGRATION_CLIENTS = {+ "github": GitHubIntegration,+ "gitlab": GitLabIntegration,+ "linear": LinearIntegration,+ "jira": JiraIntegration,+}++EXPECTED_URLS = {+ "github": "https://github.com/acme/web/issues/12",+ "gitlab": "https://gitlab.com/acme/web/issues/34",+ "linear": "https://linear.app/acme/issue/ENG-123",+ "jira": "https://acme.atlassian.net/browse/ENG-9",+}+++def _connect_tracker(team, kind: str, config: dict[str, Any] | None = None) -> Integration:+ integration = Integration.objects.create(+ team=team,+ kind=kind,+ integration_id=f"{kind}-1",+ config=INTEGRATION_CONFIGS[kind],+ sensitive_config={"access_token": "token"},+ )+ SignalTeamConfig.objects.update_or_create(+ team=team,+ defaults={+ "issue_tracking_integration": integration,+ "issue_tracking_config": config if config is not None else TRACKER_TARGETS[kind],+ },+ )+ return integration+++def _make_report(team) -> SignalReport:+ return SignalReport.objects.create(+ team=team, status=SignalReport.Status.READY, title="t", summary="s", signal_count=0, total_weight=0.0+ )++[email protected]("kind", ["github", "gitlab", "linear", "jira"])+def test_create_tracker_issue_records_provider_identifier_and_url(team, kind):+ # Each provider's client takes a different config shape and returns a different identifier, so a+ # target wired to the wrong provider stores a reference that resolves nowhere.+ _connect_tracker(team, kind)+ report = _make_report(team)++ with patch.object(INTEGRATION_CLIENTS[kind], "create_issue", return_value=CREATED_CONTEXTS[kind]):+ tracker = create_tracker_issue_for_report(team_id=team.id, report_id=str(report.id), repository="acme/web")++ assert tracker is not None+ assert tracker.status == SignalReportTrackerIssue.Status.CREATED+ expected_context = {**CREATED_CONTEXTS[kind]}+ if kind == "github":+ expected_context["repository"] = "acme/web"+ assert tracker.external_context == expected_context+ assert tracker.issue_url == EXPECTED_URLS[kind]+++def test_create_tracker_issue_opens_one_issue_per_report(team):+ # Auto-start is re-evaluated from several paths at once, and the provider call runs outside the+ # report lock. A second evaluation must reuse the issue, not open an audit duplicate.+ _connect_tracker(team, "github")+ report = _make_report(team)++ with patch.object(GitHubIntegration, "create_issue", return_value=CREATED_CONTEXTS["github"]) as create_issue:+ first = create_tracker_issue_for_report(team_id=team.id, report_id=str(report.id), repository="acme/web")+ second = create_tracker_issue_for_report(team_id=team.id, report_id=str(report.id), repository="acme/web")++ assert create_issue.call_count == 1+ assert first is not None and second is not None+ assert first.id == second.id+++def test_create_tracker_issue_surfaces_an_abandoned_claim_without_opening_a_duplicate(team):+ _connect_tracker(team, "github")+ report = _make_report(team)+ tracker = SignalReportTrackerIssue.all_teams.create(+ team=team,+ report=report,+ provider="github",+ status=SignalReportTrackerIssue.Status.PENDING,+ )+ SignalReportTrackerIssue.all_teams.filter(id=tracker.id).update(updated_at=timezone.now() - timedelta(hours=1))++ with patch.object(GitHubIntegration, "create_issue") as create_issue:+ result = create_tracker_issue_for_report(team_id=team.id, report_id=str(report.id), repository="acme/web")++ create_issue.assert_not_called()+ assert result is not None+ result.refresh_from_db()+ assert result.status == SignalReportTrackerIssue.Status.FAILED+ assert result.failure_reason == ABANDONED_CLAIM_REASON+++def test_create_tracker_issue_is_off_without_a_configured_integration(team):+ report = _make_report(team)++ assert create_tracker_issue_for_report(team_id=team.id, report_id=str(report.id), repository="acme/web") is None+ assert not SignalReportTrackerIssue.all_teams.filter(report_id=report.id).exists()+++ ("error", "expected_reason"),+ [+ (GitHubIntegrationError("token expired"), "token expired"),+ (DRFValidationError("Linear team is gone"), "Linear team is gone"),+ ],+)+def test_create_tracker_issue_records_the_failure_instead_of_raising(team, error, expected_reason):+ # The run must open its pull request even when the tracker is down, and the team has to find the+ # pull requests that ended up with no issue without reading logs.+ _connect_tracker(team, "github")+ report = _make_report(team)++ with patch.object(GitHubIntegration, "create_issue", side_effect=error):+ tracker = create_tracker_issue_for_report(team_id=team.id, report_id=str(report.id), repository="acme/web")++ assert tracker is not None+ assert tracker.status == SignalReportTrackerIssue.Status.FAILED+ assert tracker.failure_reason is not None and expected_reason in tracker.failure_reason+++def test_jira_reference_prefers_the_readable_key():+ tracker = SignalReportTrackerIssue(provider="jira", external_context={"id": "1001", "key": "ENG-9"})++ assert issue_reference(tracker) == "ENG-9"+++def test_link_pull_request_appends_the_reference_once(team):+ # The agent writes the pull request body, so the reference is added afterwards. Every task-run+ # save re-enters this path, and a second append would stack duplicate "Closes" lines.+ _connect_tracker(team, "github")+ report = _make_report(team)+ tracker = SignalReportTrackerIssue.all_teams.create(+ team=team,+ report=report,+ provider="github",+ status=SignalReportTrackerIssue.Status.CREATED,+ external_context={"repository": "acme/web", "number": 12},+ issue_url="https://github.com/acme/web/issues/12",+ )+ pr_url = "https://github.com/acme/web/pull/50"++ with (+ patch.object(+ GitHubIntegration, "first_for_team_repository", return_value=GitHubIntegration.__new__(GitHubIntegration)+ ),+ patch.object(+ GitHubIntegration,+ "get_pull_request",+ return_value={"success": True, "body": "Fixes the thing", "etag": '"version-1"'},+ ),+ patch.object(GitHubIntegration, "update_pull_request_body", return_value={"success": True}) as update,+ ):+ assert link_pull_request_to_tracker_issue(team_id=team.id, report_id=str(report.id), pr_url=pr_url) is True+ assert link_pull_request_to_tracker_issue(team_id=team.id, report_id=str(report.id), pr_url=pr_url) is False++ assert update.call_count == 1+ body = update.call_args.args[2]+ assert PR_BODY_MARKER in body+ assert "Closes #12" in body+ assert update.call_args.kwargs["expected_etag"] == '"version-1"'+ tracker.refresh_from_db()+ assert tracker.pr_linked_at is not None+++def test_close_tracker_issue_is_recorded_once(team):+ integration = _connect_tracker(team, "github")+ report = _make_report(team)+ SignalReportTrackerIssue.all_teams.create(+ team=team,+ report=report,+ integration=integration,+ provider="github",+ status=SignalReportTrackerIssue.Status.CREATED,+ external_context={"repository": "web", "number": 12},+ )++ with patch.object(GitHubIntegration, "close_issue") as close_issue:+ assert close_tracker_issue_for_report(team_id=team.id, report_id=str(report.id)) is True+ assert close_tracker_issue_for_report(team_id=team.id, report_id=str(report.id)) is False++ close_issue.assert_called_once_with("web", 12, completed=False)+++def test_completed_report_closes_tracker_issue_as_completed(team):+ integration = _connect_tracker(team, "github")+ report = _make_report(team)+ SignalReportTrackerIssue.all_teams.create(+ team=team,+ report=report,+ integration=integration,+ provider="github",+ status=SignalReportTrackerIssue.Status.CREATED,+ external_context={"repository": "web", "number": 12},+ )++ with patch.object(GitHubIntegration, "close_issue") as close_issue:+ assert close_tracker_issue_for_report(team_id=team.id, report_id=str(report.id), completed=True) is True++ close_issue.assert_called_once_with("web", 12, completed=True)++[email protected]("status", [SignalReportTrackerIssue.Status.PENDING, SignalReportTrackerIssue.Status.CREATED])+def test_close_tracker_issue_task_retries_pending_or_failed_provider_close(team, status):+ integration = _connect_tracker(team, "github")+ report = _make_report(team)+ SignalReportTrackerIssue.all_teams.create(+ team=team,+ report=report,+ integration=integration,+ provider="github",+ status=status,+ external_context={"repository": "web", "number": 12},+ )++ with patch("products.signals.backend.tasks.close_tracker_issue_for_report", return_value=False):+ with pytest.raises(Retry):+ close_report_tracker_issue.apply(+ kwargs={"report_id": str(report.id), "team_id": team.id, "completed": False},+ throw=True,+ )+++def test_create_tracker_issue_refuses_a_repository_that_holds_a_path(team):+ # The repository name reaches a GitHub path, so a value carrying path or query characters could+ # point an authenticated write at another endpoint.+ _connect_tracker(team, "github", config={"repository": "web/issues/1/comments?x="})+ report = _make_report(team)++ with patch.object(GitHubIntegration, "create_issue") as create_issue:+ tracker = create_tracker_issue_for_report(team_id=team.id, report_id=str(report.id), repository="acme/web")++ create_issue.assert_not_called()+ assert tracker is not None+ assert tracker.status == SignalReportTrackerIssue.Status.FAILED+++def test_serializer_rejects_a_repository_that_holds_a_path(team):+ integration = Integration.objects.create(+ team=team, kind="github", integration_id="github-1", config=INTEGRATION_CONFIGS["github"]+ )+ serializer = SignalTeamConfigSerializer(+ data={+ "issue_tracking_integration": integration.id,+ "issue_tracking_config": {"repository": "web/issues/1/comments?x="},+ },+ partial=True,+ context={"team_id": team.id},+ )++ assert not serializer.is_valid()+ assert "issue_tracking_config" in serializer.errors+++def test_serializer_rejects_a_tracker_with_no_target(team):+ # The target is what tells the provider where the issue goes, so an integration saved without one+ # would fail on every run instead of at the moment the setting was saved.+ integration = Integration.objects.create(+ team=team, kind="linear", integration_id="linear-1", config=INTEGRATION_CONFIGS["linear"]+ )+ serializer = SignalTeamConfigSerializer(+ data={"issue_tracking_integration": integration.id, "issue_tracking_config": {}},+ partial=True,+ context={"team_id": team.id},+ )++ assert not serializer.is_valid()+ assert "issue_tracking_config" in serializer.errors+++def test_serializer_rejects_an_integration_from_another_project(team):+ # The field is team-scoped, so a project cannot point self-driving at a tracker it does not own.+ other_team = Team.objects.create(organization=team.organization, name="Other")+ integration = Integration.objects.create(+ team=other_team, kind="linear", integration_id="linear-1", config=INTEGRATION_CONFIGS["linear"]+ )+ serializer = SignalTeamConfigSerializer(+ data={"issue_tracking_integration": integration.id, "issue_tracking_config": {"team_id": "t"}},+ partial=True,+ context={"team_id": team.id},+ )++ assert not serializer.is_valid()+ assert "issue_tracking_integration" in serializer.errors+++def test_serializer_rejects_a_provider_that_cannot_hold_issues(team):+ integration = Integration.objects.create(team=team, kind="slack", integration_id="slack-1", config={})+ serializer = SignalTeamConfigSerializer(+ data={"issue_tracking_integration": integration.id},+ partial=True,+ context={"team_id": team.id},+ )++ assert not serializer.is_valid()+ assert "issue_tracking_integration" in serializer.errorsdiff --git a/products/signals/backend/tracker_issues.py b/products/signals/backend/tracker_issues.pynew file mode 100644index 000000000000..999f1cec8f4c--- /dev/null+++ b/products/signals/backend/tracker_issues.py@@ -0,0 +1,397 @@+"""Tracker issues for self-driving pull requests.++Some teams cannot merge a pull request unless a tracked work item points at it, which is a+standard change-management control. When a team names an issue tracker in its self-driving+settings, every auto-started run opens an issue there first, and the pull request and the issue+then reference each other. Nothing here may stop a run: an issue that cannot be opened is+recorded as a failure on the report instead, so the team can see the gap and fix it by hand.+"""++from __future__ import annotations++import re+from datetime import timedelta+from typing import Any++from django.conf import settings+from django.utils import timezone++import structlog+from rest_framework.exceptions import ValidationError as DRFValidationError++from posthog.dataclasses import frozen+from posthog.models.github_integration_base import GitHubIntegrationBase+from posthog.models.integration import (+ SUPPORTED_EXTERNAL_ISSUE_PROVIDERS,+ GitHubIntegration,+ GitLabIntegration,+ Integration,+ JiraIntegration,+ LinearIntegration,+ external_issue_url,+)++from products.signals.backend.models import SignalReport, SignalReportTrackerIssue, SignalTeamConfig++logger = structlog.get_logger(__name__)++# Target fields the team must supply per provider, on top of what the integration itself carries.+# GitLab needs none: its integration is already bound to one project.+TRACKER_TARGET_REQUIRED_FIELDS: dict[str, tuple[str, ...]] = {+ Integration.IntegrationKind.GITHUB.value: ("repository",),+ Integration.IntegrationKind.GITLAB.value: (),+ Integration.IntegrationKind.LINEAR.value: ("team_id",),+ Integration.IntegrationKind.JIRA.value: ("project_key",),+}++# A GitHub repository name is interpolated into the issues path, so anything holding a path or+# query character could steer an authenticated write to another endpoint. GitHub itself allows+# only these characters in an owner or repository name.+GITHUB_REPOSITORY_PATTERN = re.compile(r"^[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)?$")++# Hidden in the rendered description, so re-running the cross-link never appends a second block.+PR_BODY_MARKER_PREFIX = "posthog-self-driving-tracker-issue"+PR_BODY_MARKER = f"<!-- {PR_BODY_MARKER_PREFIX}"++# Enough to name the cause (expired token, deleted team) without turning a provider error body+# into an unbounded column.+MAX_FAILURE_REASON_LENGTH = 300+PENDING_CLAIM_TIMEOUT = timedelta(minutes=15)+ABANDONED_CLAIM_REASON = "Tracker issue creation stopped before it returned a result. Check the tracker manually."+++@frozen+class TrackerIssueTarget:+ """Where a team wants its self-driving tracker issues to land."""++ integration: Integration+ config: dict[str, Any]++ @property+ def label(self) -> str | None:+ """Optional label for created issues. Only the GitHub client takes one today."""+ label = self.config.get("label")+ return label.strip() if isinstance(label, str) and label.strip() else None+++def tracker_issue_target_for_team(team_id: int) -> TrackerIssueTarget | None:+ """The team's configured tracker, or ``None`` when the team does not want tracker issues."""+ team_config = SignalTeamConfig.objects.select_related("issue_tracking_integration").filter(team_id=team_id).first()+ if team_config is None:+ return None+ integration = team_config.issue_tracking_integration+ if integration is None or integration.kind not in SUPPORTED_EXTERNAL_ISSUE_PROVIDERS:+ return None+ config = team_config.issue_tracking_config if isinstance(team_config.issue_tracking_config, dict) else {}+ return TrackerIssueTarget(integration=integration, config=config)+++def validated_github_repository(repository: str) -> str:+ """The configured repository, or a validation error before any authenticated call goes out."""+ name = str(repository).strip()+ if not GITHUB_REPOSITORY_PATTERN.match(name):+ raise DRFValidationError(+ f"'{repository}' is not a GitHub repository name. Use 'repository' or 'organization/repository'."+ )+ return name+++def _issue_body(*, summary: str, report_url: str, repository: str) -> str:+ return (+ f"{summary}\n\n"+ f"PostHog self-driving is implementing this. The pull request will open against "+ f"`{repository}` and will link back to this issue.\n\n"+ f"Report: {report_url}"+ )+++def _create_provider_issue(target: TrackerIssueTarget, *, title: str, body: str, report_url: str) -> dict[str, Any]:+ kind = target.integration.kind+ label = target.label++ if kind == Integration.IntegrationKind.GITHUB:+ config: dict[str, Any] = {+ "repository": validated_github_repository(target.config["repository"]),+ "title": title,+ "body": body,+ }+ if label:+ config["labels"] = [label]+ github = GitHubIntegration(target.integration)+ context = dict(github.create_issue(config))+ repository = str(context["repository"])+ context["repository"] = repository if "/" in repository else f"{github.organization()}/{repository}"+ return context++ if kind == Integration.IntegrationKind.GITLAB:+ return GitLabIntegration(target.integration).create_issue({"title": title, "body": body})++ if kind == Integration.IntegrationKind.LINEAR:+ # Linear's client attaches the report link to the new issue itself, so the auditor can+ # walk issue → report without the description.+ return LinearIntegration(target.integration).create_issue(+ report_url,+ {"team_id": target.config["team_id"], "title": title, "description": body},+ )++ if kind == Integration.IntegrationKind.JIRA:+ return JiraIntegration(target.integration).create_issue(+ {"project_key": target.config["project_key"], "title": title, "description": body}+ )++ raise ValueError(f"Unsupported tracker provider {kind}")+++def _failure_reason(error: Exception) -> str:+ """A short, readable cause for the inbox to show next to the pull request."""+ if isinstance(error, KeyError):+ return f"The tracker target is missing {error.args[0]}. Check the self-driving settings."+ if isinstance(error, DRFValidationError):+ detail = error.detail+ text = "; ".join(str(item) for item in detail) if isinstance(detail, list) else str(detail)+ else:+ text = str(error)+ return (text or error.__class__.__name__)[:MAX_FAILURE_REASON_LENGTH]+++def _claim_tracker_issue(+ *, team_id: int, report_id: str, target: TrackerIssueTarget+) -> SignalReportTrackerIssue | None:+ """Take the one row that lets this evaluation call the provider, or ``None`` if it cannot.++ Auto-start is re-evaluated from several paths at once and the provider call happens outside the+ report lock, so without this claim two evaluations would each open an issue for one report. The+ row is unique per report, so exactly one claim wins. A row that already holds an issue is+ returned as it is; a row left by a failed attempt is retried.+ """+ # 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 = SignalReportTrackerIssue.objects.for_team(team_id).get_or_create(+ report_id=report_id,+ defaults={+ "team_id": team_id,+ "integration": target.integration,+ "provider": target.integration.kind,+ "status": SignalReportTrackerIssue.Status.PENDING,+ },+ )+ if created:+ return claim+ if claim.status == SignalReportTrackerIssue.Status.PENDING:+ if claim.updated_at <= timezone.now() - PENDING_CLAIM_TIMEOUT:+ claim.status = SignalReportTrackerIssue.Status.FAILED+ claim.failure_reason = ABANDONED_CLAIM_REASON+ claim.save(update_fields=["status", "failure_reason", "updated_at"])+ return None+ if claim.status == SignalReportTrackerIssue.Status.FAILED:+ if claim.failure_reason == ABANDONED_CLAIM_REASON:+ return None+ claim.status = SignalReportTrackerIssue.Status.PENDING+ claim.integration = target.integration+ claim.provider = target.integration.kind+ claim.save(update_fields=["status", "integration", "provider", "updated_at"])+ return claim+ return None+++def create_tracker_issue_for_report(+ *, team_id: int, report_id: str, repository: str+) -> SignalReportTrackerIssue | None:+ """Open the tracker issue for a report's upcoming pull request.++ The issue reads from the report itself, not from the task description the agent gets: an+ auditor opening the issue wants the finding, not the run's instructions.++ Returns the row, or ``None`` when the team wants no tracker issue. Never raises: a provider+ failure is stored on the row so the report can show it, and the run continues either way.+ """+ try:+ target = tracker_issue_target_for_team(team_id)+ if target is None:+ return None++ report = SignalReport.objects.filter(id=report_id, team_id=team_id).only("title", "summary").first()+ if report is None:+ return None++ tracker = _claim_tracker_issue(team_id=team_id, report_id=report_id, target=target)+ if tracker is None:+ return SignalReportTrackerIssue.objects.for_team(team_id).filter(report_id=report_id).first()++ report_url = f"{settings.SITE_URL}/project/{team_id}/inbox/reports/{report_id}"+ try:+ external_context = _create_provider_issue(+ target,+ # A report can reach dispatch before its research run writes a title.+ title=report.title or "PostHog self-driving change",+ body=_issue_body(summary=report.summary or "", report_url=report_url, repository=repository),+ report_url=report_url,+ )+ except Exception as error:+ logger.warning(+ "signals.tracker_issue_create_failed",+ report_id=report_id,+ team_id=team_id,+ provider=target.integration.kind,+ exc_info=True,+ )+ tracker.status = SignalReportTrackerIssue.Status.FAILED+ tracker.failure_reason = _failure_reason(error)+ else:+ tracker.status = SignalReportTrackerIssue.Status.CREATED+ tracker.failure_reason = None+ tracker.external_context = external_context+ tracker.issue_url = external_issue_url(target.integration, external_context) or None+ tracker.save(update_fields=["status", "failure_reason", "external_context", "issue_url", "updated_at"])+ return tracker+ except Exception:+ logger.exception("signals.tracker_issue_create_unexpected_error", report_id=report_id, team_id=team_id)+ return None+++def issue_reference(tracker: SignalReportTrackerIssue) -> str | None:+ """How the issue reads in its provider, for example "#12" or "ENG-123"."""+ context = tracker.external_context or {}+ identifier = context.get("key") or context.get("id")+ if identifier:+ return str(identifier)+ number = context.get("number") or context.get("issue_id")+ return f"#{number}" if number else None+++def _pr_body_reference(tracker: SignalReportTrackerIssue, *, pr_repository: str) -> str | None:+ """The line appended to the pull request body so the pull request names its tracker issue."""+ context = tracker.external_context or {}++ if tracker.provider == Integration.IntegrationKind.GITHUB:+ repository, number = context.get("repository"), context.get("number")+ if not repository or not number:+ return None+ # "Closes #n" only resolves inside the pull request's own repository. Anywhere else GitHub+ # needs the owner-qualified form.+ reference = f"#{number}" if repository.lower() == pr_repository.lower() else f"{repository}#{number}"+ return f"Closes {reference}"++ identifier = issue_reference(tracker)+ if identifier and tracker.issue_url:+ return f"Tracked in [{identifier}]({tracker.issue_url})"+ if tracker.issue_url:+ return f"Tracked in {tracker.issue_url}"+ return None+++def link_pull_request_to_tracker_issue(*, team_id: int, report_id: str, pr_url: str) -> bool:+ """Cross-reference an opened pull request and the report's tracker issue.++ Edits the pull request description rather than trusting the agent to write the reference, and+ attaches the pull request to a Linear issue so the link reads in both directions. Returns+ whether the pull request now carries the reference. Never raises.+ """+ try:+ tracker = (+ SignalReportTrackerIssue.objects.for_team(team_id)+ .select_related("integration")+ .filter(report_id=report_id, status=SignalReportTrackerIssue.Status.CREATED)+ .first()+ )+ if tracker is None or tracker.pr_linked_at is not None:+ return False++ parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)+ if parsed is None:+ return False+ github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)+ if github is None:+ logger.info("signals.tracker_issue_link_no_integration", report_id=report_id, pr_url=pr_url)+ return False++ pull_request = github.get_pull_request(parsed.repository, parsed.number)+ if not pull_request.get("success"):+ logger.warning(+ "signals.tracker_issue_link_pr_fetch_failed",+ report_id=report_id,+ pr_url=pr_url,+ error=pull_request.get("error"),+ )+ return False++ body = pull_request.get("body") or ""+ marker = f"{PR_BODY_MARKER}:{report_id} -->"+ if marker not in body:+ reference = _pr_body_reference(tracker, pr_repository=parsed.repository)+ if reference is None:+ return False+ outcome = github.update_pull_request_body(+ parsed.repository,+ parsed.number,+ f"{body.rstrip()}\n\n{marker}\n{reference}\n",+ expected_etag=pull_request.get("etag"),+ )+ if not outcome.get("success"):+ logger.warning(+ "signals.tracker_issue_link_pr_update_failed",+ report_id=report_id,+ pr_url=pr_url,+ error=outcome.get("error"),+ )+ return False++ if tracker.provider == Integration.IntegrationKind.LINEAR and tracker.integration is not None:+ # Best-effort: the description reference already links the two, and this attachment+ # needs a Linear scope the team may not have granted.+ try:+ LinearIntegration(tracker.integration).create_attachment(+ str((tracker.external_context or {}).get("id")), pr_url+ )+ except Exception:+ logger.warning("signals.tracker_issue_linear_attachment_failed", report_id=report_id, exc_info=True)++ tracker.pr_linked_at = timezone.now()+ tracker.save(update_fields=["pr_linked_at", "updated_at"])+ return True+ except Exception:+ logger.exception("signals.tracker_issue_link_unexpected_error", report_id=report_id, team_id=team_id)+ return False+++def _close_provider_issue(tracker: SignalReportTrackerIssue, *, completed: bool) -> None:+ integration = tracker.integration+ if integration is None:+ raise ValueError("Tracker issue has no integration left to close it through")+ context = tracker.external_context or {}++ if tracker.provider == Integration.IntegrationKind.GITHUB:+ GitHubIntegration(integration).close_issue(context["repository"], int(context["number"]), completed=completed)+ elif tracker.provider == Integration.IntegrationKind.GITLAB:+ GitLabIntegration(integration).close_issue(int(context["issue_id"]))+ elif tracker.provider == Integration.IntegrationKind.LINEAR:+ LinearIntegration(integration).close_issue(str(context["id"]), completed=completed)+ elif tracker.provider == Integration.IntegrationKind.JIRA:+ JiraIntegration(integration).close_issue(str(context["key"]))+ else:+ raise ValueError(f"Unsupported tracker provider {tracker.provider}")+++def close_tracker_issue_for_report(*, team_id: int, report_id: str, completed: bool = False) -> bool:+ """Close the report's tracker issue once the report is dismissed or completed. Never raises.++ A dismissed report will not produce a pull request, so its work item is finished. Leaving it+ open would grow a backlog of tracker issues that no pull request will ever answer.+ """+ try:+ tracker = (+ SignalReportTrackerIssue.objects.for_team(team_id)+ .select_related("integration")+ .filter(report_id=report_id, status=SignalReportTrackerIssue.Status.CREATED)+ .first()+ )+ if tracker is None or tracker.closed_at is not None:+ return False++ _close_provider_issue(tracker, completed=completed)+ tracker.closed_at = timezone.now()+ tracker.save(update_fields=["closed_at", "updated_at"])+ return True+ except Exception:+ logger.warning("signals.tracker_issue_close_failed", report_id=report_id, team_id=team_id, exc_info=True)+ return Falsediff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex b2206929c824..8f51c5a29d26 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -491,7 +491,7 @@ class SignalTeamConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@extend_schema(exclude=True)def create(self, request: Request, *args, **kwargs) -> Response:config = self._get_config()- serializer = SignalTeamConfigSerializer(config, data=request.data, partial=True)+ serializer = self.get_serializer(config, data=request.data, partial=True)serializer.is_valid(raise_exception=True)serializer.save()return Response(serializer.data)@@ -981,7 +981,7 @@ class SignalReportViewSet(# The serializer renders the reverse OneToOne rows inline.return (queryset.filter(team=self.team)- .select_related("refund", "assignment", "assignment__actor_user")+ .select_related("refund", "assignment", "assignment__actor_user", "tracker_issue").annotate(artefact_count=Coalesce(artefact_count_subquery, Value(0), output_field=IntegerField()),channel_id=channel_id_subquery,diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex ed22c847ab7c..cc4f710bd0d0 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -303,6 +303,21 @@ export interface SignalReportApi {readonly implementation_pr_state: SignalReportAssignmentPrStateEnumApi | null/** Whether that implementation PR is merged, per the GitHub webhook. False when there is no PR or it hasn't merged. Report status doesn't imply this: a resolved report may have been resolved directly, without a merged PR. */readonly implementation_pr_merged: boolean+ /**+ * Link to the issue self-driving opened in the team's tracker for this report's pull request. Null when the team tracks no issues, or the issue could not be opened.+ * @nullable+ */+ readonly tracker_issue_url: string | null+ /**+ * How that tracker issue reads in its provider, for example '#12' or 'ENG-123'. Null when there is no tracker issue.+ * @nullable+ */+ readonly tracker_issue_reference: string | null+ /**+ * Why the tracker issue could not be opened, for a team that wants one. Null when the issue exists or the team tracks no issues.+ * @nullable+ */+ readonly tracker_issue_error: string | null/** 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. */diff --git a/products/signals/frontend/inbox/components/config/RepoRoutingRules.stories.tsx b/products/signals/frontend/inbox/components/config/RepoRoutingRules.stories.tsxindex 4df67dae2524..7f42053e654a 100644--- a/products/signals/frontend/inbox/components/config/RepoRoutingRules.stories.tsx+++ b/products/signals/frontend/inbox/components/config/RepoRoutingRules.stories.tsx@@ -50,7 +50,7 @@ function Block({ rules = RULES, withGithub = true }: { rules?: typeof RULES; wituseStorybookMocks({get: {'/api/projects/:team_id/tasks/repo_routing_rules/': rules,- '/api/environments/:team_id/integrations/': { results: withGithub ? [GITHUB_INTEGRATION] : [] },+ '/api/projects/:team_id/integrations/': { results: withGithub ? [GITHUB_INTEGRATION] : [] },'/api/environments/:team_id/integrations/:id/github_repos/': {repositories: [{ id: 1, name: 'posthog.com', full_name: 'posthog/posthog.com' },diff --git a/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx b/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsxindex 1678172ef05c..f3ece6cd4858 100644--- a/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx+++ b/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx@@ -19,8 +19,15 @@ interface CardState {reportsToday?: number/** Personal opt-in to being added as a GitHub assignee on the implementation PR. */githubAssign?: boolean+ /** Connected integrations the issue tracker picker can choose from. */+ integrations?: Record<string, unknown>[]+ /** Integration id the project already tracks issues in, and where inside it they land. */+ issueTrackingIntegration?: number | null+ issueTrackingConfig?: Record<string, string>}+const GITHUB_INTEGRATION = { id: 1, kind: 'github', display_name: 'PostHog', config: {}, created_at: '2024-03-01' }+function Card({enabled = true,projectThreshold = 'P2',@@ -28,6 +35,9 @@ function Card({dailyLimit = null,reportsToday = 0,githubAssign = false,+ integrations = [],+ issueTrackingIntegration = null,+ issueTrackingConfig = {},}: CardState): JSX.Element {useStorybookMocks({get: {@@ -36,6 +46,8 @@ function Card({autostart_enabled: enabled,default_autostart_priority: projectThreshold,autostart_base_branches: {},+ issue_tracking_integration: issueTrackingIntegration,+ issue_tracking_config: issueTrackingConfig,max_reports_per_day: dailyLimit,reports_generated_today: reportsToday,daily_report_limit_reached: dailyLimit != null && reportsToday >= dailyLimit,@@ -47,7 +59,7 @@ function Card({slack_notification_min_priority: null,github_assign_on_pull_request: githubAssign,},- '/api/environments/:team_id/integrations/': { results: [] },+ '/api/projects/:team_id/integrations/': { results: integrations },},})// Mimic the agents rail (`w-80` aside + the column's `px-4 py-3`) so the card lays out as in the scene.@@ -102,3 +114,19 @@ export const GitHubAssignmentOn: Story = {export const Disabled: Story = {render: () => <Card enabled={false} />,}++// No tracker connected: the issue tracker row points at the integrations settings instead.+export const IssueTrackerUnavailable: Story = {+ render: () => <Card />,+}++// A project under a change-management control: every PR gets a GitHub issue in `PostHog/posthog`.+export const IssueTrackerConfigured: Story = {+ render: () => (+ <Card+ integrations={[GITHUB_INTEGRATION]}+ issueTrackingIntegration={1}+ issueTrackingConfig={{ repository: 'posthog' }}+ />+ ),+}diff --git a/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx b/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsxindex 6f8278ae0935..3501ceebce5e 100644--- a/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx+++ b/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx@@ -1,7 +1,16 @@import { useActions, useValues } from 'kea'import { IconPlus, IconRocket, IconX } from '@posthog/icons'-import { LemonButton, LemonInput, LemonSegmentedButton, LemonSkeleton, LemonSwitch } from '@posthog/lemon-ui'+import {+ LemonButton,+ LemonCollapse,+ LemonInput,+ LemonSegmentedButton,+ LemonSelect,+ LemonSkeleton,+ LemonSwitch,+ Link,+} from '@posthog/lemon-ui'import {Button,ButtonGroup,@@ -21,6 +30,11 @@ import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { GitHubBranchCombobox } from 'lib/integrations/GitHubBranchCombobox'import { GitHubRepositoryCombobox } from 'lib/integrations/GitHubRepositoryCombobox'import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { JiraProjectPicker } from 'lib/integrations/JiraIntegrationHelpers'+import { LinearTeamPicker } from 'lib/integrations/LinearIntegrationHelpers'+import { urls } from 'scenes/urls'++import { IntegrationType } from '~/types'import { signalTeamConfigLogic } from '../../logics/signalTeamConfigLogic'import { userAutonomyLogic } from '../../logics/userAutonomyLogic'@@ -225,6 +239,186 @@ function BaseBranchOverrides(): JSX.Element {)}+/** Providers that can hold a tracker issue, with the label the picker shows for each. */+const ISSUE_TRACKER_LABELS: Partial<Record<IntegrationType['kind'], string>> = {+ github: 'GitHub issues',+ linear: 'Linear',+ jira: 'Jira',+ gitlab: 'GitLab issues',+}++/** LemonSelect has no null option value, so "off" needs a sentinel that no integration id can take. */+const ISSUE_TRACKER_OFF = -1++/**+ * Where inside the chosen tracker the issues land. The shape follows the provider, so this renders+ * one picker per provider. GitLab needs no pick at all: its integration is already bound to one+ * project.+ */+function IssueTrackerTarget({+ integration,+ target,+ disabled,+ onSave,+}: {+ integration: IntegrationType+ target: Record<string, string>+ disabled: boolean+ onSave: (config: Record<string, string>) => void+}): JSX.Element | null {+ if (integration.kind === 'github') {+ return (+ <GitHubRepositoryCombobox+ integrationId={integration.id}+ // Stored bare so the issue link can re-prefix the account that owns it, while the+ // picker works in the `owner/repo` form it shows.+ value={target.repository ? `${integration.display_name}/${target.repository}` : ''}+ disabled={disabled}+ placeholder="Repository"+ onChange={(repo) => repo && onSave({ ...target, repository: repo.split('/')[1] })}+ />+ )+ }+ if (integration.kind === 'linear') {+ return (+ <LinearTeamPicker+ integration={integration}+ value={target.team_id}+ disabled={disabled}+ onChange={(teamId) => teamId && onSave({ team_id: teamId })}+ />+ )+ }+ if (integration.kind === 'jira') {+ return (+ <JiraProjectPicker+ integrationId={integration.id}+ value={target.project_key ?? ''}+ disabled={disabled}+ onChange={(projectKey) => projectKey && onSave({ project_key: projectKey })}+ />+ )+ }+ return <p className="text-[11px] text-tertiary leading-snug mb-0">Issues go to {integration.display_name}.</p>+}++/**+ * Per-project switch for the change-management control some teams work under: a pull request can+ * only merge when a tracked work item points at it. Off unless a tracker is picked, so one field is+ * both the switch and the target and the two can never disagree.+ */+function IssueTracker(): JSX.Element {+ const { issueTrackerConfig, issueTrackerIntegrationId, selectedIssueTrackerIntegrationId, teamConfigUpdating } =+ useValues(signalTeamConfigLogic)+ const { patchTeamConfig, setDraftIssueTrackerIntegrationId } = useActions(signalTeamConfigLogic)+ const { integrations, integrationsLoading } = useValues(integrationsLogic)+ const { loadIntegrations } = useActions(integrationsLogic)++ const trackers = (integrations ?? []).filter((integration) => integration.kind in ISSUE_TRACKER_LABELS)+ const selected = trackers.find((integration) => integration.id === selectedIssueTrackerIntegrationId) ?? null+ // A freshly picked provider has no target yet, so the stored one belongs to the old provider.+ const target = selectedIssueTrackerIntegrationId === issueTrackerIntegrationId ? issueTrackerConfig : {}+ const saved = trackers.find((integration) => integration.id === issueTrackerIntegrationId) ?? null+ const summary =+ integrations === null ? 'Loading…' : saved ? (ISSUE_TRACKER_LABELS[saved.kind] ?? saved.kind) : 'Off'++ const saveTarget = (config: Record<string, string>): void => {+ if (selected) {+ patchTeamConfig({+ issue_tracking_integration: selected.id,+ issue_tracking_config: { ...target, ...config },+ })+ }+ }++ const chooseTracker = (next: number): void => {+ if (next === ISSUE_TRACKER_OFF) {+ setDraftIssueTrackerIntegrationId(null)+ patchTeamConfig({ issue_tracking_integration: null, issue_tracking_config: {} })+ return+ }++ setDraftIssueTrackerIntegrationId(next)+ if (trackers.find((integration) => integration.id === next)?.kind === 'gitlab') {+ patchTeamConfig({ issue_tracking_integration: next, issue_tracking_config: {} })+ }+ }++ const content = (+ <div className="flex flex-col gap-1.5">+ <p className="text-[11px] text-tertiary leading-snug mb-0">+ Open an issue for every PR agents make, and link the two. Use this when a PR can only merge with a+ tracked work item behind it.+ </p>+ {integrations === null ? (+ integrationsLoading ? (+ <LemonSkeleton className="h-7 max-w-xs" />+ ) : (+ <div className="flex items-center gap-2">+ <span className="text-[11px] text-tertiary">Could not load integrations.</span>+ <LemonButton size="xsmall" type="secondary" onClick={() => loadIntegrations()}>+ Retry+ </LemonButton>+ </div>+ )+ ) : trackers.length > 0 ? (+ <>+ <LemonSelect+ size="xsmall"+ fullWidth+ className="max-w-xs"+ value={selectedIssueTrackerIntegrationId ?? ISSUE_TRACKER_OFF}+ options={[+ { value: ISSUE_TRACKER_OFF, label: 'Off' },+ ...trackers.map((integration) => ({+ value: integration.id,+ label: `${ISSUE_TRACKER_LABELS[integration.kind]} · ${integration.display_name}`,+ })),+ ]}+ disabledReason={teamConfigUpdating ? 'Saving changes' : undefined}+ onChange={chooseTracker}+ />+ {selected && (+ <IssueTrackerTarget+ integration={selected}+ target={target}+ disabled={teamConfigUpdating}+ onSave={saveTarget}+ />+ )}+ <p className="text-[11px] text-tertiary leading-snug mb-0">+ If the tracker fails, the PR still opens and the report shows that the issue is missing.+ </p>+ </>+ ) : (+ <p className="text-[11px] text-tertiary leading-snug mb-0">+ <Link to={urls.settings('project-integrations')}>Connect GitHub, GitLab, Linear, or Jira</Link> to+ track issues.+ </p>+ )}+ </div>+ )++ return (+ <LemonCollapse+ embedded+ size="small"+ panels={[+ {+ key: 'issue-tracker',+ header: (+ <div className="flex flex-1 items-center justify-between gap-2">+ <span className="text-xs text-secondary">Issue tracker</span>+ <span className="text-xs text-tertiary">{summary}</span>+ </div>+ ),+ content,+ },+ ]}+ />+ )+}+/*** A self-imposed cap on reports per day, deliberately housed with the autonomy throttles rather* than the billing usage card: it is "how much should the agents do", not "what does the plan@@ -433,6 +627,9 @@ export function SelfDrivingSection(): JSX.Element {<div className="border-t border-primary"><GitHubAssignmentRow /></div>+ <div className="border-t border-primary">+ <IssueTracker />+ </div><div className="border-t border-primary"><DailyReportLimit /></div>diff --git a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.stories.tsx b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.stories.tsxindex 5adaf08d11f1..7ff146acfaeb 100644--- a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.stories.tsx+++ b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.stories.tsx@@ -28,7 +28,7 @@ function Cards({}: CardsState): JSX.Element {useStorybookMocks({get: {- '/api/environments/:team_id/integrations/': { results: connected ? [WORKSPACE] : [] },+ '/api/projects/:team_id/integrations/': { results: connected ? [WORKSPACE] : [] },'/api/environments/:team_id/integrations/:id/channels': { channels: CHANNELS, has_more: false },'/api/projects/:team_id/signals/config/': {id: 'cfg-1',diff --git a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.test.tsx b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.test.tsxindex 8fe63f845046..750112cc2b32 100644--- a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.test.tsx+++ b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.test.tsx@@ -28,7 +28,7 @@ describe('SlackNotificationsSection', () => {// msw handlers reset between tests, so register per test rather than once per file.useMocks({get: {- '/api/environments/:team_id/integrations/': () => [200, { results: [WORKSPACE] }],+ '/api/projects/:team_id/integrations/': () => [200, { results: [WORKSPACE] }],'/api/environments/:team_id/integrations/:id/channels': () => [200, { channels: [], has_more: false }],'/api/projects/:team_id/signals/config/': () => [200, { default_slack_notification_channel: null }],'/api/users/@me/signal_autonomy/': () =>diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.stories.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.stories.tsxindex 67fd91f6d313..88fe1d492d06 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.stories.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.stories.tsx@@ -69,7 +69,7 @@ export const SlackChannelDestination: Story = {decorators: [mswDecorator({get: {- '/api/environments/:team_id/integrations/': () => [+ '/api/projects/:team_id/integrations/': () => [200,{ results: [{ id: 1, kind: 'slack', display_name: 'PostHog', config: {}, errors: null }] },],diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsxindex 7087870ff400..3aff1367c7dd 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsx@@ -43,7 +43,7 @@ const config: SignalScoutConfigApi = {describe('ScoutConfigForm', () => {useMocks({get: {- '/api/environments/:team_id/integrations/': () => [200, { results: [] }],+ '/api/projects/:team_id/integrations/': () => [200, { results: [] }],},})diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.test.tsxindex 6cf167d394ea..58a48e9a16c1 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.test.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.test.tsx@@ -10,7 +10,7 @@ describe('ScoutCreateModal', () => {initKeaTests()useMocks({get: {- '/api/environments/:team_id/integrations/': () => [200, { results: [] }],+ '/api/projects/:team_id/integrations/': () => [200, { results: [] }],},})})diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.test.tsxindex e19e5d679a53..841be10ed69a 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.test.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.test.tsx@@ -22,7 +22,7 @@ describe('ScoutSlackDestination', () => {// msw handlers reset between tests, so register per test rather than once per file.useMocks({get: {- '/api/environments/:team_id/integrations/': () => [200, { results: workspaces }],+ '/api/projects/:team_id/integrations/': () => [200, { results: workspaces }],},})})diff --git a/products/signals/frontend/inbox/components/detail/ReportDetail.tsx b/products/signals/frontend/inbox/components/detail/ReportDetail.tsxindex 662f6c46a4fe..a114239a7c88 100644--- a/products/signals/frontend/inbox/components/detail/ReportDetail.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportDetail.tsx@@ -51,6 +51,7 @@ import { ReportFeedbackFooter } from './ReportFeedbackFooter'import { ReportSummaryBody } from './ReportSummaryBody'import { ReportTasksSection } from './ReportTasksSection'import { SuggestedReviewersSection } from './SuggestedReviewersSection'+import { TrackerIssueNote } from './TrackerIssueNote'/*** Status / priority / actionability badges for a report's detail header. Mirrors desktop `InboxDetailFrame`.@@ -317,9 +318,12 @@ export function InboxDetailFrame({pullRequestNote={pullRequestNote}/>) : (- <p className={`text-sm text-tertiary m-0${summaryPending ? ' italic' : ''}`}>- No summary yet. An agent is still investigating.- </p>+ <>+ <p className={`text-sm text-tertiary m-0${summaryPending ? ' italic' : ''}`}>+ No summary yet. An agent is still investigating.+ </p>+ {pullRequestNote}+ </>)}{trailingCharts.length > 0 && (<div className="flex flex-col gap-4 mt-5">@@ -560,6 +564,9 @@ export function ReportDetail({ report }: { report: SignalReport }): JSX.Elementconst prUrl = safeHttpUrl(report.implementation_pr_url)const prRef = prUrl ? parsePrUrlParts(prUrl) : nullconst hasPr = !!(prRef && prUrl)+ // A tracker-issue failure has to show even on a report whose run never reached a pull request:+ // that is exactly the case an audit has to find.+ const hasTrackerNote = !!(report.tracker_issue_url || report.tracker_issue_error)// The branch to diff comes from the latest "Commit pushed" artefact; the diff needs the repo + branch// it carries. A PR-bearing report gets the tab bar right away off `hasPr` (immediate) rather than the@@ -599,6 +606,11 @@ export function ReportDetail({ report }: { report: SignalReport }): JSX.Element</span></span><OpenPullRequestButton report={report} prUrl={prUrl} prRef={prRef} />+ <TrackerIssueNote report={report} />+ </div>+ ) : hasTrackerNote ? (+ <div className="flex flex-wrap items-center gap-3" data-attr="inbox-report-solution-pr-note">+ <TrackerIssueNote report={report} /></div>) : undefined}diff --git a/products/signals/frontend/inbox/components/detail/ReportDetailLegacy.tsx b/products/signals/frontend/inbox/components/detail/ReportDetailLegacy.tsxindex 486af26e94e5..82128c65d777 100644--- a/products/signals/frontend/inbox/components/detail/ReportDetailLegacy.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportDetailLegacy.tsx@@ -56,6 +56,7 @@ import { useReportDetailActions } from './ReportDetailActions'import { ReportFeedbackFooter } from './ReportFeedbackFooter'import { ReportTasksSection } from './ReportTasksSection'import { SuggestedReviewersSection } from './SuggestedReviewersSection'+import { TrackerIssueNote } from './TrackerIssueNote'const SIGNALS_TOOLTIP ='Signals are the individual pieces of evidence from your connected sources and scouts that were grouped into this report.'@@ -596,7 +597,14 @@ export function ReportDetailLegacy({ report, tab }: { report: SignalReport; tab:}// The PR conversation sits under the Summary as primary content; CI checks stay in the// sidebar. Both drop themselves when there's nothing to show.- summaryFooter={hasPr ? <PrCommentsSection report={report} /> : undefined}+ summaryFooter={+ hasPr || report.tracker_issue_url || report.tracker_issue_error ? (+ <>+ <TrackerIssueNote report={report} />+ {hasPr && <PrCommentsSection report={report} />}+ </>+ ) : undefined+ }>{hasPr && <PrChecksSection report={report} />}</InboxDetailFrameLegacy>diff --git a/products/signals/frontend/inbox/components/detail/TrackerIssueNote.tsx b/products/signals/frontend/inbox/components/detail/TrackerIssueNote.tsxnew file mode 100644index 000000000000..538ab1b64634--- /dev/null+++ b/products/signals/frontend/inbox/components/detail/TrackerIssueNote.tsx@@ -0,0 +1,35 @@+import { IconWarning } from '@posthog/icons'+import { Link } from '@posthog/lemon-ui'++import { SignalReport } from '../../types'+import { safeHttpUrl } from '../../utils/reportPresentation'++/**+ * The tracker issue behind a report's pull request, or why there is none.+ *+ * A team that cannot merge without a tracked work item has to find the pull requests that lack one+ * without reading logs, so the failure sits next to the pull request rather than in a state of its+ * own.+ */+export function TrackerIssueNote({ report }: { report: SignalReport }): JSX.Element | null {+ const issueUrl = safeHttpUrl(report.tracker_issue_url)++ if (issueUrl) {+ return (+ <span className="text-sm text-secondary">+ Tracked in <Link to={issueUrl}>{report.tracker_issue_reference ?? 'the issue tracker'}</Link>+ </span>+ )+ }++ if (report.tracker_issue_error) {+ return (+ <span className="text-sm text-warning flex items-center gap-1">+ <IconWarning />+ No tracker issue: {report.tracker_issue_error}+ </span>+ )+ }++ return null+}diff --git a/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts b/products/signals/frontend/inbox/logics/signalTeamConfigLogic.tsindex 4ca6a2d36f6b..82193663e44d 100644--- a/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts+++ b/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts@@ -32,11 +32,15 @@ export interface signalTeamConfigLogicValues {draftBaseBranchBranch: stringdraftBaseBranchIntegrationId: number | nulldraftBaseBranchRepo: string+ draftIssueTrackerIntegrationId: number | nulldraftMaxReportsPerDay: number | null+ issueTrackerConfig: Record<string, string>+ issueTrackerIntegrationId: number | nullmaxReportsPerDay: number | nullpatchesInFlight: numberreportsGeneratedToday: numbersaveMaxReportsPerDayDisabledReason: string | null+ selectedIssueTrackerIntegrationId: number | nullteamConfig: SignalTeamConfig | nullteamConfigLoading: booleanteamConfigUpdating: boolean@@ -107,6 +111,9 @@ export interface signalTeamConfigLogicActions {setDraftBaseBranchRepo: (repo: string) => {repo: string}+ setDraftIssueTrackerIntegrationId: (integrationId: number | null) => {+ integrationId: number | null+ }setDraftMaxReportsPerDay: (value: number | null) => {value: number | null}@@ -126,6 +133,12 @@ export interface signalTeamConfigLogicMeta {defaultAutostartPriority: (teamConfig: SignalTeamConfig | null) => SignalReportPrioritybaseBranchOverrides: (teamConfig: SignalTeamConfig | null) => BaseBranchOverride[]maxReportsPerDay: (teamConfig: SignalTeamConfig | null) => number | null+ issueTrackerIntegrationId: (teamConfig: SignalTeamConfig | null) => number | null+ issueTrackerConfig: (teamConfig: SignalTeamConfig | null) => Record<string, string>+ selectedIssueTrackerIntegrationId: (+ draftIssueTrackerIntegrationId: number | null,+ issueTrackerIntegrationId: number | null+ ) => number | nullreportsGeneratedToday: (teamConfig: SignalTeamConfig | null) => numberdailyReportLimitReached: (teamConfig: SignalTeamConfig | null) => booleanteamConfigUpdating: (patchesInFlight: number) => boolean@@ -175,6 +188,7 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([removeBaseBranchOverride: (repo: string) => ({ repo }),setDraftMaxReportsPerDay: (value: number | null) => ({ value }),saveDraftMaxReportsPerDay: true,+ setDraftIssueTrackerIntegrationId: (integrationId: number | null) => ({ integrationId }),}),loaders(() => {// Every patch of `autostart_base_branches` sends the whole map, so two in flight at once let the@@ -247,6 +261,18 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([patchTeamConfigFailure: (state: number) => Math.max(0, state - 1),},],+ // Which tracker the person just picked, before they have chosen a target inside it. The+ // backend rejects an integration with no target, so the pair is only sent once both exist.+ // Null means no pending pick: turning tracking off saves straight away, so the draft never+ // has to hold that state.+ draftIssueTrackerIntegrationId: [+ null as number | null,+ {+ setDraftIssueTrackerIntegrationId: (_, { integrationId }) => integrationId,+ patchTeamConfigSuccess: (state, { payload }) =>+ payload?.patch && 'issue_tracking_integration' in payload.patch ? null : state,+ },+ ],// The daily-limit input's draft. Seeded from the server once on first load (see the// loadTeamConfigSuccess listener) and re-anchored only when its own save settles, so saving// an unrelated setting on this shared singleton logic never wipes an unsaved edit.@@ -286,6 +312,19 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([(s) => [s.teamConfig],(teamConfig: SignalTeamConfig | null): number | null => teamConfig?.max_reports_per_day ?? null,],+ issueTrackerIntegrationId: [+ (s) => [s.teamConfig],+ (teamConfig: SignalTeamConfig | null): number | null => teamConfig?.issue_tracking_integration ?? null,+ ],+ issueTrackerConfig: [+ (s) => [s.teamConfig],+ (teamConfig: SignalTeamConfig | null): Record<string, string> => teamConfig?.issue_tracking_config ?? {},+ ],+ selectedIssueTrackerIntegrationId: [+ (s) => [s.draftIssueTrackerIntegrationId, s.issueTrackerIntegrationId],+ (draftIssueTrackerIntegrationId: number | null, issueTrackerIntegrationId: number | null): number | null =>+ draftIssueTrackerIntegrationId ?? issueTrackerIntegrationId,+ ],reportsGeneratedToday: [(s) => [s.teamConfig],(teamConfig: SignalTeamConfig | null): number => teamConfig?.reports_generated_today ?? 0,@@ -393,6 +432,7 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([},patchTeamConfigFailure: ({ error, errorObject }) => {captureSettled(false)+ actions.setDraftIssueTrackerIntegrationId(null)lemonToast.error(errorObject?.detail ?? error ?? 'Failed to update team self-driving settings')// The optimistic value is now a lie, and the server holds the truth about what stuck.actions.loadTeamConfig()diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.tsindex e6e96eda54da..fa4bd7b21eb7 100644--- a/products/signals/frontend/inbox/types.ts+++ b/products/signals/frontend/inbox/types.ts@@ -101,6 +101,12 @@ export interface SignalReport {implementation_pr_merged?: boolean/** Latest known state of that PR: unknown, draft, open, closed, or merged. */implementation_pr_state?: SignalReportAssignmentPrStateEnumApi | null+ /** Link to the tracker issue self-driving opened for this report's PR. Null when the project tracks no issues. */+ tracker_issue_url?: string | null+ /** How that issue reads in its provider, for example '#12' or 'ENG-123'. */+ tracker_issue_reference?: string | null+ /** Why the tracker issue could not be opened, for a project that wants one. Null when it exists. */+ tracker_issue_error?: string | null/** Reason code from the latest dismissal artefact (when archived). See dismissalReasons. */dismissal_reason?: string | null/** Free-form note from the latest dismissal artefact (when archived). */@@ -391,6 +397,10 @@ export interface SignalTeamConfig {default_slack_notification_channel?: string | null/** Per-repo base-branch overrides for auto-started PRs, keyed by 'org/repo'. */autostart_base_branches?: Record<string, string>+ /** Integration self-driving opens a tracker issue in for each PR it makes. Null turns tracker issues off. */+ issue_tracking_integration?: number | null+ /** Where those issues land: github {repository}, linear {team_id}, jira {project_key}, plus an optional 'label'. */+ issue_tracking_config?: Record<string, string>/** Daily cap on new reports surfacing to the inbox (project-timezone day). Null means unlimited. */max_reports_per_day?: number | null/** Read-only: reports that first became visible today (project timezone). Never send in a patch. */diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex e3f6c6f003b2..86c901d90340 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -219,6 +219,9 @@ tools:- implementation_pr_url- implementation_pr_state- implementation_pr_merged+ - tracker_issue_url+ - tracker_issue_reference+ - tracker_issue_error- work_state- assignee- created_atdiff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 5a88688158a2..068df287d542 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -6184,6 +6184,15 @@ def create_task(space_repositories=channel.repositories,)+ if signal_report_id and signal_report_task_relationship in (None, "implementation") and task.repository:+ from products.signals.backend.tracker_issues import create_tracker_issue_for_report++ create_tracker_issue_for_report(+ team_id=team_id,+ report_id=signal_report_id,+ repository=task.repository,+ )+return _task_detail_to_dto(_task_detail_queryset().get(pk=task.pk))diff --git a/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.tsindex c1dd3151492b..6817899f0bd6 100644--- a/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts+++ b/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts@@ -9,7 +9,7 @@ import { Breadcrumb } from '~/types'import type { GitHubRepoApi } from 'products/integrations/frontend/generated/api.schemas'-import type { IntegrationType, UserBasicType } from '../../../../frontend/src/types'+import type { IntegrationType } from '../../../../frontend/src/types'import { visualReviewReposCreate, visualReviewReposList, visualReviewReposPartialUpdate } from '../generated/api'import type { PatchedUpdateRepoRequestInputApi, RepoApi } from '../generated/api.schemas'@@ -51,126 +51,10 @@ export interface visualReviewSettingsSceneLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface visualReviewSettingsSceneLogicActions {loadIntegrationsSuccess: (- integrations: {- config: any- created_at: string- created_by?: UserBasicType | null | undefined- display_name: string- errors?: string | undefined- files_write_requestable?: boolean | undefined- icon_url: any- id: number- installation_shared?: boolean | null | undefined- installation_status?:- | null- | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi- | undefined- kind:- | 'apns'- | 'aws-redshift'- | 'aws-s3'- | 'azure-blob'- | 'bing-ads'- | 'clickup'- | 'customerio-app'- | 'customerio-track'- | 'customerio-webhook'- | 'databricks'- | 'email'- | 'firebase'- | 'github'- | 'gitlab'- | 'google-ads'- | 'google-analytics'- | 'google-calendar'- | 'google-cloud-service-account'- | 'google-cloud-storage'- | 'google-pubsub'- | 'google-search-console'- | 'google-sheets'- | 'hubspot'- | 'instagram'- | 'intercom'- | 'jira'- | 'linear'- | 'linkedin-ads'- | 'meta-ads'- | 'pardot'- | 'pinterest-ads'- | 'postgresql'- | 'reddit-ads'- | 's3-compatible'- | 'salesforce'- | 'slack'- | 'snapchat'- | 'snowflake'- | 'stripe'- | 'tiktok-ads'- | 'twilio'- | 'vercel'- | 'youtube-analytics'- }[],+ integrations: IntegrationType[],payload?: any) => {- integrations: {- config: any- created_at: string- created_by?: UserBasicType | null | undefined- display_name: string- errors?: string | undefined- files_write_requestable?: boolean | undefined- icon_url: any- id: number- installation_shared?: boolean | null | undefined- installation_status?:- | null- | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi- | undefined- kind:- | 'apns'- | 'aws-redshift'- | 'aws-s3'- | 'azure-blob'- | 'bing-ads'- | 'clickup'- | 'customerio-app'- | 'customerio-track'- | 'customerio-webhook'- | 'databricks'- | 'email'- | 'firebase'- | 'github'- | 'gitlab'- | 'google-ads'- | 'google-analytics'- | 'google-calendar'- | 'google-cloud-service-account'- | 'google-cloud-storage'- | 'google-pubsub'- | 'google-search-console'- | 'google-sheets'- | 'hubspot'- | 'instagram'- | 'intercom'- | 'jira'- | 'linear'- | 'linkedin-ads'- | 'meta-ads'- | 'pardot'- | 'pinterest-ads'- | 'postgresql'- | 'reddit-ads'- | 's3-compatible'- | 'salesforce'- | 'slack'- | 'snapchat'- | 'snowflake'- | 'stripe'- | 'tiktok-ads'- | 'twilio'- | 'vercel'- | 'youtube-analytics'- }[]+ integrations: IntegrationType[]payload?: any} // integrationsLogicaddRepo: (githubRepo: GitHubRepoApi) => {diff --git a/products/workflows/frontend/TemplateLibrary/messageTemplateTestSendLogic.test.ts b/products/workflows/frontend/TemplateLibrary/messageTemplateTestSendLogic.test.tsindex 4a58a325eda8..1ca725067d5a 100644--- a/products/workflows/frontend/TemplateLibrary/messageTemplateTestSendLogic.test.ts+++ b/products/workflows/frontend/TemplateLibrary/messageTemplateTestSendLogic.test.ts@@ -29,7 +29,7 @@ describe('messageTemplateTestSendLogic', () => {useMocks({get: {- '/api/environments/:team_id/integrations/': {+ '/api/projects/:team_id/integrations/': {results: [{id: 4,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 92590d2d82c0..44d7ddda555e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -58873,6 +58873,21 @@ export namespace Schemas {readonly implementation_pr_state: SignalReportAssignmentPrStateEnum | null;/** Whether that implementation PR is merged, per the GitHub webhook. False when there is no PR or it hasn't merged. Report status doesn't imply this: a resolved report may have been resolved directly, without a merged PR. */readonly implementation_pr_merged: boolean;+ /**+ * Link to the issue self-driving opened in the team's tracker for this report's pull request. Null when the team tracks no issues, or the issue could not be opened.+ * @nullable+ */+ readonly tracker_issue_url: string | null;+ /**+ * How that tracker issue reads in its provider, for example '#12' or 'ENG-123'. Null when there is no tracker issue.+ * @nullable+ */+ readonly tracker_issue_reference: string | null;+ /**+ * Why the tracker issue could not be opened, for a team that wants one. Null when the issue exists or the team tracks no issues.+ * @nullable+ */+ readonly tracker_issue_error: string | null;/** 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/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex e26af2ca2710..2f28f3664317 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -286,6 +286,9 @@ const inboxReportsList = (): ToolBase<'implementation_pr_url','implementation_pr_state','implementation_pr_merged',+ 'tracker_issue_url',+ 'tracker_issue_reference',+ 'tracker_issue_error','work_state','assignee','created_at',