: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): add repo routing rules UI to code access settings (#97496)
Vojta Bartoš5b70d38a8a65
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 00b48c69ba31..a85876e6fd66 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7680,6 +7680,22 @@ snapshots:hash: v1.k794b7964.0b3e4e202fa54385e60e27040953cd6576ef81346e03c62c6fd38932ae05f1d8.cF9xbAe_hmO-rKLL45RToPLXmS8_zLnvi36jZ8OOpYYscenes-app-inbox-pullrequestdiffview--truncated--light:hash: v1.k794b7964.58a507666519d2ad2f2a5247605b2c903180639eae9e43580992de250bc8f258._lKwsnOWccjuN6S_pd8IgOfKLzqnIvVqmTh1uETW-TY+ scenes-app-inbox-reporoutingrules--many-rules--dark:+ hash: v1.k794b7964.df6ebd47ae9cad25071a63f62df5bba00596f2164830b7b1fecb4b12b481f8d4.mAYMPj1fJznVmDFV3duDCTRA7vFG6wFONEspN_XyJHE+ scenes-app-inbox-reporoutingrules--many-rules--light:+ hash: v1.k794b7964.37e4e90f0ab7a04cf8a8ad650be0544b79d904850aabd317c3f496ab74ff0468.MI0kMAtlgCTZiDE8TqS0GgdncHidk8L3_MVJxbBnRg0+ scenes-app-inbox-reporoutingrules--no-github-connection--dark:+ hash: v1.k794b7964.c28097b852f5efa43db4f38f30b2b1f8a48585562cff138ffab995993cc8887a.EhDhgXoRaWofDYgN83_zwbn4k4LkJkyDhMP8Ty5f7e0+ scenes-app-inbox-reporoutingrules--no-github-connection--light:+ hash: v1.k794b7964.c3970470cb263044d5a3d61873f029ee0b2f299fd3e5ec5f53248b927876e62a.Moizv3vG0jwiGyBNe2a8pBC5ppNBntXMTEoIWkvhleM+ scenes-app-inbox-reporoutingrules--no-rules--dark:+ hash: v1.k794b7964.102de9187a373efe1b53debc23969deec926251c3843e861147f4386cf332c4e.qi7uiozTmfxZ3y8DT9IHwwo6o6tdfJGNqNny291h49U+ scenes-app-inbox-reporoutingrules--no-rules--light:+ hash: v1.k794b7964.0085da218812e04cf4af4aedc8eb36b6c7d948d7ec9aed6f654c8afd7f97ad20.YMcOSzhqEDMm4Jx01NELAlB4_RV1zjSUkPQdCiXv08o+ scenes-app-inbox-reporoutingrules--with-rules--dark:+ hash: v1.k794b7964.4c821c407a94fcd72bf9dc0253cfda3ac175442059bafed964354005769d4363.goiedcRz0DK4CpkadOhtMlQ8nZUSHsDHnjewLBSPhxs+ scenes-app-inbox-reporoutingrules--with-rules--light:+ hash: v1.k794b7964.0c3c963f549f660505abd1a5a041d12f7a06ebb45425cb06455e21c6da5cdde2.BJVn3hoecT90BYZTusLudiX5sbNqxHZ0dfEqaDhwHZ4scenes-app-inbox-scene--empty--dark:hash: v1.k794b7964.7d08781760f326f7746ad15883a7ad1a12af173a118c112947ec8ad2637cb1e1.9lq59SDcw12Zz9wZmdfDUnV8V-8vVzWL4NZ0QbTOMgUscenes-app-inbox-scene--empty--light:@@ -7729,9 +7745,9 @@ snapshots:scenes-app-inbox-scene--self-driving-verdict-pending--light:hash: v1.k794b7964.18a04e43d0b1598e406b105dcdfe548f7d26376ad3ba606401c6795ae3ea1b1f.8uOUfAOgA04AY2GECIDr5Mf98040a17lVfVUA3QpRGMscenes-app-inbox-scene--settings--dark:- hash: v1.k794b7964.56e6e806e53ad186a6e7eca6aeb2b691e95e2c6d27de81d6539406d3c946e73c.lQbazW62nbdlf-uOlroYbXxWnrbL5kDefBDHOvKHkFw+ hash: v1.k794b7964.3b0dd5d698d5ee24029c00271393e53a38a1b3bea552c489cd1569c76ed0a886.Zn_fKt4Rz2_T-6UsZQNJEUSjYJF9ASDplD5GaVfJEq4scenes-app-inbox-scene--settings--light:- hash: v1.k794b7964.86fff9ce30a1cd376c9fd259ad22f99edadaa6cb66c75c18f10df207f0a2ff11.QTCPpndHx79lzLxyqzbZMOyaXjYXC_tGZj06-UQsQiA+ hash: v1.k794b7964.de101fcfa4421dcd9a470ba276f7ce01c4fdc2d9d2b9ccf27029ed0cf8c38bb6.0W-nF6W3ewFNHHSmHrM73Ggttlhl5TyVo97THVRBTMIscenes-app-inbox-scene--triage--dark:hash: v1.k794b7964.77e43b36fdcd81befecf4de80e489050f525840924ec6ddef37c23a9179dbe8a.B3qkZFYBncFaPn2EBg4cBoYu_LIwW29imNwBdLXF5eoscenes-app-inbox-scene--triage--light:diff --git a/products/signals/frontend/inbox/InboxScene.stories.tsx b/products/signals/frontend/inbox/InboxScene.stories.tsxindex 04272fc576e0..90bab6e18449 100644--- a/products/signals/frontend/inbox/InboxScene.stories.tsx+++ b/products/signals/frontend/inbox/InboxScene.stories.tsx@@ -57,6 +57,8 @@ const sceneMocks = mswDecorator({200,{ report: null, signals: mockSignals(req.params.reportId as string, 4) },],+ // Must precede the `:taskId` handler, which would otherwise swallow this path.+ '/api/projects/:id/tasks/repo_routing_rules/': () => [200, []],'/api/projects/:id/tasks/:taskId': (req) => [200, mockTask(req.params.taskId as string)],'/api/projects/:id/signals/source_configs': () => [200, mockSourceConfigs],'/api/projects/:id/signals/config': () => [200, mockTeamConfig],diff --git a/products/signals/frontend/inbox/components/config/RepoRoutingRules.stories.tsx b/products/signals/frontend/inbox/components/config/RepoRoutingRules.stories.tsxnew file mode 100644index 000000000000..4df67dae2524--- /dev/null+++ b/products/signals/frontend/inbox/components/config/RepoRoutingRules.stories.tsx@@ -0,0 +1,113 @@+import type { Meta, StoryObj } from '@storybook/react'++import { useStorybookMocks } from '~/mocks/browser'++import { RepoRoutingRules } from './RepoRoutingRules'++// The routing rules block from the Code access settings section. It reads the team's rules+// (`tasks/repo_routing_rules`) and the connected GitHub integrations, so both GETs are mocked+// per story to place the block in a given state.++const GITHUB_INTEGRATION = {+ id: 1,+ kind: 'github',+ display_name: 'PostHog',+ config: {},+ created_at: '2024-01-01T00:00:00Z',+ errors: '',+}++const CREATOR = {+ id: 1,+ uuid: '018f0000-0000-7000-8000-0000000000aa',+ email: '[email protected]',+ first_name: 'Max',+ hedgehog_config: null,+}++const RULES = [+ {+ id: '018f0000-0000-7000-8000-000000000001',+ rule_text: 'anything about the marketing site or docs',+ repository: 'posthog/posthog.com',+ priority: 0,+ created_by: CREATOR,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ },+ {+ id: '018f0000-0000-7000-8000-000000000002',+ rule_text: 'crashes in the Android app',+ repository: 'posthog/posthog-android',+ priority: 1,+ created_by: null,+ created_at: '2024-01-02T00:00:00Z',+ updated_at: '2024-01-02T00:00:00Z',+ },+]++function Block({ rules = RULES, withGithub = true }: { rules?: typeof RULES; withGithub?: boolean }): JSX.Element {+ useStorybookMocks({+ get: {+ '/api/projects/:team_id/tasks/repo_routing_rules/': rules,+ '/api/environments/: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' },+ { id: 2, name: 'posthog-android', full_name: 'posthog/posthog-android' },+ ],+ has_more: false,+ total: 2,+ },+ },+ })+ // Mimic the Settings tab card width so wrapping matches the scene.+ return (+ <div className="w-[40rem] max-w-full rounded border border-primary bg-surface-primary p-4">+ <RepoRoutingRules />+ </div>+ )+}++const meta: Meta = {+ title: 'Scenes-App/Inbox/RepoRoutingRules',+ component: RepoRoutingRules,+ parameters: {+ layout: 'centered',+ viewMode: 'story',+ mockDate: '2024-03-20',+ },+}+export default meta++type Story = StoryObj++export const WithRules: Story = {+ render: () => <Block />,+}++export const NoRules: Story = {+ render: () => <Block rules={[]} />,+}++// Without a GitHub connection the add row gives way to a pointer at the connect card above.+export const NoGithubConnection: Story = {+ render: () => <Block rules={[]} withGithub={false} />,+}++// More than one page of rules: the pager appears under the rows, ten per page.+export const ManyRules: Story = {+ render: () => (+ <Block+ rules={Array.from({ length: 14 }, (_, i) => ({+ id: `018f0000-0000-7000-8000-0000000000${String(i).padStart(2, '0')}`,+ rule_text: `rule ${i + 1}`,+ repository: i % 2 === 0 ? 'posthog/posthog.com' : 'posthog/posthog-android',+ priority: i,+ created_by: i % 2 === 0 ? CREATOR : null,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ }))}+ />+ ),+}diff --git a/products/signals/frontend/inbox/components/config/RepoRoutingRules.tsx b/products/signals/frontend/inbox/components/config/RepoRoutingRules.tsxnew file mode 100644index 000000000000..f90830af99a3--- /dev/null+++ b/products/signals/frontend/inbox/components/config/RepoRoutingRules.tsx@@ -0,0 +1,251 @@+import { useActions, useValues } from 'kea'++import { IconPencil, IconPlus, IconX } from '@posthog/icons'+import { LemonButton, LemonInput, LemonSelect, LemonSkeleton, ProfilePicture, Tooltip } from '@posthog/lemon-ui'++import { GitHubRepositoryCombobox } from 'lib/integrations/GitHubRepositoryCombobox'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { PaginationControl, usePagination } from 'lib/lemon-ui/PaginationControl'++import type { RepoRoutingRuleApi } from 'products/tasks/frontend/generated/api.schemas'++import { MAX_RULE_TEXT_LENGTH, repoRoutingRulesLogic } from '../../logics/repoRoutingRulesLogic'++const RULES_PAGE_SIZE = 10++interface RuleFieldsProps {+ ruleText: string+ repository: string+ integrationId: number | null+ onRuleTextChange: (ruleText: string) => void+ onRepositoryChange: (repository: string) => void+ onIntegrationIdChange: (integrationId: number | null) => void+ disabled: boolean+}++/** The shared field row for adding and editing a rule: description, org (when several), repository. */+function RuleFields({+ ruleText,+ repository,+ integrationId,+ onRuleTextChange,+ onRepositoryChange,+ onIntegrationIdChange,+ disabled,+}: RuleFieldsProps): JSX.Element {+ const { githubIntegrations } = useValues(integrationsLogic)+ const effectiveIntegrationId = integrationId ?? githubIntegrations[0]?.id++ return (+ <>+ <LemonInput+ size="small"+ className="min-w-0 flex-1"+ placeholder="Which requests match, e.g. anything about the marketing site"+ maxLength={MAX_RULE_TEXT_LENGTH}+ value={ruleText}+ disabledReason={disabled ? 'Saving changes' : undefined}+ onChange={onRuleTextChange}+ />+ {githubIntegrations.length > 1 && (+ <LemonSelect+ size="small"+ value={effectiveIntegrationId}+ disabledReason={disabled ? 'Saving changes' : undefined}+ options={githubIntegrations.map((integration) => ({+ value: integration.id,+ label: integration.display_name,+ }))}+ onChange={(next) => onIntegrationIdChange(next)}+ />+ )}+ {effectiveIntegrationId != null && (+ <GitHubRepositoryCombobox+ integrationId={effectiveIntegrationId}+ value={repository}+ disabled={disabled}+ onChange={(repo) => onRepositoryChange(repo ?? '')}+ placeholder="Repository"+ />+ )}+ </>+ )+}++function RuleRow({ rule }: { rule: RepoRoutingRuleApi }): JSX.Element {+ const {+ editingRuleId,+ editRuleText,+ editRepository,+ editIntegrationId,+ saveEditedRuleDisabledReason,+ rulesLoading,+ } = useValues(repoRoutingRulesLogic)+ const {+ startEditingRule,+ cancelEditingRule,+ setEditRuleText,+ setEditRepository,+ setEditIntegrationId,+ saveEditedRule,+ deleteRule,+ } = useActions(repoRoutingRulesLogic)+ const { githubIntegrations } = useValues(integrationsLogic)++ if (editingRuleId === rule.id) {+ return (+ <div className="flex flex-wrap items-center gap-1">+ <RuleFields+ ruleText={editRuleText}+ repository={editRepository}+ integrationId={editIntegrationId}+ onRuleTextChange={setEditRuleText}+ onRepositoryChange={setEditRepository}+ onIntegrationIdChange={setEditIntegrationId}+ disabled={rulesLoading}+ />+ <LemonButton+ size="small"+ type="secondary"+ loading={rulesLoading}+ disabledReason={saveEditedRuleDisabledReason ?? undefined}+ onClick={saveEditedRule}+ data-attr="signals-repo-routing-rule-save"+ >+ Save+ </LemonButton>+ <LemonButton size="small" onClick={cancelEditingRule}>+ Cancel+ </LemonButton>+ </div>+ )+ }++ // A stored rule carries only `owner/repo`, so the owning integration is recovered from the owner+ // half. A GitHub integration's display name is the installation's account login, which is that owner.+ const integrationForRule =+ githubIntegrations.find(+ (integration) => integration.display_name.toLowerCase() === rule.repository.split('/')[0].toLowerCase()+ ) ?? null++ return (+ <div className="flex items-center gap-1">+ <span className="text-xs text-default min-w-0 flex-1 truncate" title={rule.rule_text}>+ {rule.rule_text}+ </span>+ <span className="text-xs text-muted shrink-0">{rule.repository}</span>+ {rule.created_by && (+ <Tooltip+ title={`Added by ${rule.created_by.first_name || rule.created_by.email}${rule.created_by.first_name ? ` (${rule.created_by.email})` : ''}`}+ >+ <ProfilePicture+ user={{+ first_name: rule.created_by.first_name,+ last_name: rule.created_by.last_name,+ email: rule.created_by.email,+ }}+ size="sm"+ />+ </Tooltip>+ )}+ <LemonButton+ size="xsmall"+ icon={<IconPencil />}+ aria-label={`Edit routing rule for ${rule.repository}`}+ disabledReason={rulesLoading ? 'Saving changes' : undefined}+ onClick={() => startEditingRule(rule, integrationForRule?.id ?? null)}+ data-attr="signals-repo-routing-rule-edit"+ />+ <LemonButton+ size="xsmall"+ icon={<IconX />}+ aria-label={`Remove routing rule for ${rule.repository}`}+ disabledReason={rulesLoading ? 'Saving changes' : undefined}+ onClick={() => deleteRule(rule)}+ data-attr="signals-repo-routing-rule-delete"+ />+ </div>+ )+}++function AddRuleRow(): JSX.Element {+ const { draftRuleText, draftRepository, draftIntegrationId, addRuleDisabledReason, rulesLoading } =+ useValues(repoRoutingRulesLogic)+ const { setDraftRuleText, setDraftRepository, setDraftIntegrationId, addRule } = useActions(repoRoutingRulesLogic)++ return (+ <div className="flex flex-wrap items-center gap-1">+ <RuleFields+ ruleText={draftRuleText}+ repository={draftRepository}+ integrationId={draftIntegrationId}+ onRuleTextChange={setDraftRuleText}+ onRepositoryChange={setDraftRepository}+ onIntegrationIdChange={setDraftIntegrationId}+ disabled={rulesLoading}+ />+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconPlus />}+ loading={rulesLoading}+ disabledReason={addRuleDisabledReason ?? undefined}+ onClick={addRule}+ data-attr="signals-repo-routing-rule-add"+ >+ Add+ </LemonButton>+ </div>+ )+}++/**+ * CRUD block for the team's repo routing rules, rendered inside the Code access settings+ * section under the GitHub connection it depends on. The same rules the Slack `@PostHog rules`+ * commands manage.+ */+export function RepoRoutingRules(): JSX.Element {+ const { rules, rulesLoading } = useValues(repoRoutingRulesLogic)+ const { githubIntegrations } = useValues(integrationsLogic)+ // Local pagination only: the pager must not write a `page` param into the settings URL.+ const pagination = usePagination(rules ?? [], { pageSize: RULES_PAGE_SIZE, useUrl: false })++ return (+ <div className="flex flex-col gap-2 border-t border-primary pt-3">+ <div className="flex flex-col gap-0.5">+ <h4 className="m-0 text-xs font-semibold text-default">Routing rules</h4>+ <p className="m-0 max-w-2xl text-[11px] leading-snug text-tertiary">+ Steer requests to a repository. When a request matches a rule, agents prefer that rule's repository.+ Earlier rules win when several match.+ </p>+ </div>+ {rules === null ? (+ rulesLoading ? (+ <LemonSkeleton className="h-8 w-full rounded" />+ ) : (+ <p className="m-0 text-xs text-secondary">+ Couldn't load routing rules. Refresh the page to try again.+ </p>+ )+ ) : (+ <>+ {rules.length > 0 && (+ <div className="flex flex-col gap-1">+ {pagination.dataSourcePage.map((rule) => (+ <RuleRow key={rule.id} rule={rule} />+ ))}+ <PaginationControl {...pagination} nouns={['rule', 'rules']} />+ </div>+ )}+ {githubIntegrations.length > 0 ? (+ <AddRuleRow />+ ) : (+ <p className="m-0 text-[11px] leading-snug text-tertiary">+ Connect GitHub above to add a routing rule.+ </p>+ )}+ </>+ )}+ </div>+ )+}diff --git a/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx b/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsxindex 8659b470ba70..bcfaf6a7eabc 100644--- a/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx+++ b/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx@@ -16,6 +16,7 @@ import { scoutFleetLogic } from '../../logics/scoutFleetLogic'import { signalTeamConfigLogic } from '../../logics/signalTeamConfigLogic'import { userAutonomyLogic } from '../../logics/userAutonomyLogic'import { signalSourcesLogic } from '../../signalSourcesLogic'+import { RepoRoutingRules } from '../config/RepoRoutingRules'import { SelfDrivingSection } from '../config/SelfDrivingSection'import { SignalSourcesPanel } from '../config/SignalSourcesPanel'import { SlackNotificationsSection } from '../config/SlackNotificationsSection'@@ -253,10 +254,13 @@ function NotificationsWidget(): JSX.Element {function GithubSetupBody(): JSX.Element {const { location, searchParams } = useValues(router)return (- <GithubIntegration- next={combineUrl(location.pathname, { ...searchParams, setup: 'github' }).url}- connectSurface="signals_agent_setup"- />+ <div className="flex flex-col gap-3">+ <GithubIntegration+ next={combineUrl(location.pathname, { ...searchParams, setup: 'github' }).url}+ connectSurface="signals_agent_setup"+ />+ <RepoRoutingRules />+ </div>)}diff --git a/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx b/products/signals/frontend/inbox/components/tabs/SettingsTab.tsxindex 7edeaec2c404..50f9fc7e71d5 100644--- a/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx+++ b/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx@@ -6,6 +6,7 @@ import { urls } from 'scenes/urls'import { inboxUsageLogic } from '../../logics/inboxUsageLogic'import { signalSourcesLogic } from '../../signalSourcesLogic'+import { RepoRoutingRules } from '../config/RepoRoutingRules'import { SelfDrivingSection } from '../config/SelfDrivingSection'import { SignalSourcesPanel } from '../config/SignalSourcesPanel'import { SlackNotificationsSection } from '../config/SlackNotificationsSection'@@ -46,6 +47,7 @@ export function SettingsTab(): JSX.Element {>{/* The OAuth round trip returns to `next`; land back on this tab so the result is in view. */}<GithubIntegration next={urls.inbox('settings')} connectSurface="signals_agent_setup" />+ <RepoRoutingRules /></SettingsSection><SettingsSectiontitle="Notifications"diff --git a/products/signals/frontend/inbox/logics/repoRoutingRulesLogic.test.ts b/products/signals/frontend/inbox/logics/repoRoutingRulesLogic.test.tsnew file mode 100644index 000000000000..59d3333aec14--- /dev/null+++ b/products/signals/frontend/inbox/logics/repoRoutingRulesLogic.test.ts@@ -0,0 +1,109 @@+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import type { RepoRoutingRuleApi } from 'products/tasks/frontend/generated/api.schemas'++import { MAX_RULES_PER_TEAM, repoRoutingRulesLogic } from './repoRoutingRulesLogic'++function rule(id: string, ruleText: string, repository: string, priority: number): RepoRoutingRuleApi {+ return {+ id,+ rule_text: ruleText,+ repository,+ priority,+ created_by: null,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ }+}++const EXISTING = rule('rule-1', 'anything about the docs', 'posthog/posthog.com', 0)+const CREATED = rule('rule-2', 'the support dashboard', 'posthog/posthog-android', 1)+const UPDATED = rule('rule-1', 'docs and the marketing site', 'posthog/posthog.com', 0)++describe('repoRoutingRulesLogic', () => {+ let logic: ReturnType<typeof repoRoutingRulesLogic.build> | undefined++ beforeEach(() => {+ initKeaTests()+ useMocks({+ get: { '/api/projects/:team_id/tasks/repo_routing_rules/': [EXISTING] },+ post: { '/api/projects/:team_id/tasks/repo_routing_rules/': [201, CREATED] },+ patch: { '/api/projects/:team_id/tasks/repo_routing_rules/:id/': [200, UPDATED] },+ delete: { '/api/projects/:team_id/tasks/repo_routing_rules/:id/': [204, null] },+ })+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('keeps the list in sync through add, edit, and remove', async () => {+ logic = repoRoutingRulesLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.rules).toEqual([EXISTING])++ logic.actions.setDraftRuleText('the support dashboard')+ logic.actions.setDraftRepository('posthog/posthog-android')+ logic.actions.addRule()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.rules).toEqual([EXISTING, CREATED])+ // Cleared drafts keep a second click from re-posting the same rule.+ expect(logic.values.draftRuleText).toEqual('')+ expect(logic.values.draftRepository).toEqual('')++ logic.actions.startEditingRule(EXISTING, null)+ expect(logic.values.editRuleText).toEqual(EXISTING.rule_text)+ logic.actions.setEditRuleText('docs and the marketing site')+ logic.actions.saveEditedRule()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.rules).toEqual([UPDATED, CREATED])+ expect(logic.values.editingRuleId).toBeNull()++ logic.actions.deleteRule(CREATED)+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.rules).toEqual([UPDATED])+ })++ it('clears the picked repository when the GitHub org changes', () => {+ logic = repoRoutingRulesLogic()+ logic.mount()+ logic.actions.setDraftRepository('posthog/posthog.com')+ logic.actions.setDraftIntegrationId(2)+ expect(logic.values.draftRepository).toEqual('')++ logic.actions.startEditingRule(EXISTING, 1)+ logic.actions.setEditIntegrationId(2)+ expect(logic.values.editRepository).toEqual('')+ })++ it('gates the add button once the team hits the rule cap', async () => {+ const fullSet = Array.from({ length: MAX_RULES_PER_TEAM }, (_, i) =>+ rule(`rule-${i}`, `rule ${i}`, 'posthog/posthog.com', i)+ )+ useMocks({ get: { '/api/projects/:team_id/tasks/repo_routing_rules/': fullSet } })+ logic = repoRoutingRulesLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setDraftRuleText('one too many')+ logic.actions.setDraftRepository('posthog/posthog.com')+ expect(logic.values.addRuleDisabledReason).toContain(`${MAX_RULES_PER_TEAM}`)+ })++ it.each([+ ['', 'posthog/posthog-android', 'Describe which requests the rule matches'],+ ['x'.repeat(301), 'posthog/posthog-android', 'Keep the rule under 300 characters'],+ ['the support dashboard', '', 'Pick a repository'],+ ['the support dashboard', 'posthog/posthog-android', null],+ ])('gates the add button on draft validity (%#)', (ruleText, repository, reason) => {+ logic = repoRoutingRulesLogic()+ logic.mount()+ logic.actions.setDraftRuleText(ruleText)+ logic.actions.setDraftRepository(repository)+ expect(logic.values.addRuleDisabledReason).toEqual(reason)+ })+})diff --git a/products/signals/frontend/inbox/logics/repoRoutingRulesLogic.ts b/products/signals/frontend/inbox/logics/repoRoutingRulesLogic.tsnew file mode 100644index 000000000000..3dc8bcf9d4f9--- /dev/null+++ b/products/signals/frontend/inbox/logics/repoRoutingRulesLogic.ts@@ -0,0 +1,332 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'++import {+ tasksRepoRoutingRulesCreate,+ tasksRepoRoutingRulesDestroy,+ tasksRepoRoutingRulesList,+ tasksRepoRoutingRulesPartialUpdate,+} from 'products/tasks/frontend/generated/api'+import type { RepoRoutingRuleApi } from 'products/tasks/frontend/generated/api.schemas'++import { captureInboxSettingsChanged } from '../inboxAnalytics'++/** Matches the serializer's limit; the repo selection prompt truncates longer rules. */+export const MAX_RULE_TEXT_LENGTH = 300++/** Matches the API's per-team cap, so the add button explains the limit before a round trip. */+export const MAX_RULES_PER_TEAM = 50++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface repoRoutingRulesLogicValues {+ currentTeamId: number | null // teamLogic+ addRuleDisabledReason: string | null+ draftIntegrationId: number | null+ draftRepository: string+ draftRuleText: string+ editIntegrationId: number | null+ editRepository: string+ editRuleText: string+ editingRuleId: string | null+ rules: RepoRoutingRuleApi[] | null+ rulesLoading: boolean+ saveEditedRuleDisabledReason: string | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface repoRoutingRulesLogicActions {+ addRule: () => any+ addRuleFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ addRuleSuccess: (+ rules: RepoRoutingRuleApi[],+ payload?: any+ ) => {+ rules: RepoRoutingRuleApi[]+ payload?: any+ }+ cancelEditingRule: () => {+ value: true+ }+ deleteRule: (rule: RepoRoutingRuleApi) => {+ rule: RepoRoutingRuleApi+ }+ deleteRuleFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ deleteRuleSuccess: (+ rules: RepoRoutingRuleApi[],+ payload?: {+ rule: RepoRoutingRuleApi+ }+ ) => {+ rules: RepoRoutingRuleApi[]+ payload?: {+ rule: RepoRoutingRuleApi+ }+ }+ loadRules: () => any+ loadRulesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRulesSuccess: (+ rules: RepoRoutingRuleApi[],+ payload?: any+ ) => {+ rules: RepoRoutingRuleApi[]+ payload?: any+ }+ saveEditedRule: () => any+ saveEditedRuleFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ saveEditedRuleSuccess: (+ rules: RepoRoutingRuleApi[] | null,+ payload?: any+ ) => {+ rules: RepoRoutingRuleApi[] | null+ payload?: any+ }+ setDraftIntegrationId: (integrationId: number | null) => {+ integrationId: number | null+ }+ setDraftRepository: (repository: string) => {+ repository: string+ }+ setDraftRuleText: (ruleText: string) => {+ ruleText: string+ }+ setEditIntegrationId: (integrationId: number | null) => {+ integrationId: number | null+ }+ setEditRepository: (repository: string) => {+ repository: string+ }+ setEditRuleText: (ruleText: string) => {+ ruleText: string+ }+ startEditingRule: (+ rule: RepoRoutingRuleApi,+ integrationId: number | null+ ) => {+ integrationId: number | null+ rule: RepoRoutingRuleApi+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface repoRoutingRulesLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ addRuleDisabledReason: (+ draftRuleText: string,+ draftRepository: string,+ rules: RepoRoutingRuleApi[] | null+ ) => string | null+ saveEditedRuleDisabledReason: (editRuleText: string, editRepository: string) => string | null+ }+}++export type repoRoutingRulesLogicType = MakeLogicType<+ repoRoutingRulesLogicValues,+ repoRoutingRulesLogicActions,+ Record<string, any>,+ repoRoutingRulesLogicMeta+>++/**+ * CRUD state for the team's repo routing rules, shown in the Code access settings section.+ * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent reads+ * them ordered by priority when picking a repository. All mutations resolve to the full+ * updated list so the loader stays the single source of truth.+ */+export const repoRoutingRulesLogic = kea<repoRoutingRulesLogicType>([+ path(['products', 'signals', 'frontend', 'inbox', 'logics', 'repoRoutingRulesLogic']),+ connect(() => ({ values: [teamLogic, ['currentTeamId']] })),+ actions({+ deleteRule: (rule: RepoRoutingRuleApi) => ({ rule }),+ setDraftRuleText: (ruleText: string) => ({ ruleText }),+ setDraftRepository: (repository: string) => ({ repository }),+ setDraftIntegrationId: (integrationId: number | null) => ({ integrationId }),+ startEditingRule: (rule: RepoRoutingRuleApi, integrationId: number | null) => ({ rule, integrationId }),+ cancelEditingRule: true,+ setEditRuleText: (ruleText: string) => ({ ruleText }),+ setEditRepository: (repository: string) => ({ repository }),+ setEditIntegrationId: (integrationId: number | null) => ({ integrationId }),+ }),+ loaders(({ values }) => ({+ rules: [+ null as RepoRoutingRuleApi[] | null,+ {+ loadRules: async () => {+ return await tasksRepoRoutingRulesList(String(values.currentTeamId))+ },+ addRule: async () => {+ const created = await tasksRepoRoutingRulesCreate(String(values.currentTeamId), {+ rule_text: values.draftRuleText.trim(),+ repository: values.draftRepository,+ })+ return [...(values.rules ?? []), created]+ },+ saveEditedRule: async () => {+ if (!values.editingRuleId) {+ return values.rules+ }+ const updated = await tasksRepoRoutingRulesPartialUpdate(+ String(values.currentTeamId),+ values.editingRuleId,+ { rule_text: values.editRuleText.trim(), repository: values.editRepository }+ )+ return (values.rules ?? []).map((rule) => (rule.id === updated.id ? updated : rule))+ },+ deleteRule: async ({ rule }) => {+ await tasksRepoRoutingRulesDestroy(String(values.currentTeamId), rule.id)+ return (values.rules ?? []).filter((row) => row.id !== rule.id)+ },+ },+ ],+ })),+ reducers({+ draftRuleText: ['', { setDraftRuleText: (_, { ruleText }) => ruleText, addRuleSuccess: () => '' }],+ draftRepository: [+ '',+ {+ setDraftRepository: (_, { repository }) => repository,+ addRuleSuccess: () => '',+ // Another installation's repositories are a different set, so a kept selection+ // would submit a repo the shown org does not have.+ setDraftIntegrationId: () => '',+ },+ ],+ draftIntegrationId: [null as number | null, { setDraftIntegrationId: (_, { integrationId }) => integrationId }],+ editingRuleId: [+ null as string | null,+ {+ startEditingRule: (_, { rule }) => rule.id,+ cancelEditingRule: () => null,+ saveEditedRuleSuccess: () => null,+ },+ ],+ editRuleText: [+ '',+ { startEditingRule: (_, { rule }) => rule.rule_text, setEditRuleText: (_, { ruleText }) => ruleText },+ ],+ editRepository: [+ '',+ {+ startEditingRule: (_, { rule }) => rule.repository,+ setEditRepository: (_, { repository }) => repository,+ setEditIntegrationId: () => '',+ },+ ],+ editIntegrationId: [+ null as number | null,+ {+ startEditingRule: (_, { integrationId }) => integrationId,+ setEditIntegrationId: (_, { integrationId }) => integrationId,+ },+ ],+ }),+ selectors({+ addRuleDisabledReason: [+ (s) => [s.draftRuleText, s.draftRepository, s.rules],+ (draftRuleText: string, draftRepository: string, rules: RepoRoutingRuleApi[] | null): string | null => {+ if ((rules?.length ?? 0) >= MAX_RULES_PER_TEAM) {+ return `Limit of ${MAX_RULES_PER_TEAM} rules reached. Remove a rule to add another.`+ }+ return ruleDisabledReason(draftRuleText, draftRepository)+ },+ ],+ saveEditedRuleDisabledReason: [+ (s) => [s.editRuleText, s.editRepository],+ (editRuleText: string, editRepository: string): string | null =>+ ruleDisabledReason(editRuleText, editRepository),+ ],+ }),+ listeners(() => ({+ addRuleSuccess: () => {+ captureInboxSettingsChanged({+ setting: 'repo_routing_rule_added',+ newValue: null,+ success: true,+ scope: 'team',+ })+ },+ saveEditedRuleSuccess: () => {+ captureInboxSettingsChanged({+ setting: 'repo_routing_rule_updated',+ newValue: null,+ success: true,+ scope: 'team',+ })+ },+ deleteRuleSuccess: () => {+ captureInboxSettingsChanged({+ setting: 'repo_routing_rule_removed',+ newValue: null,+ success: true,+ scope: 'team',+ })+ },+ // No toasts here: the global kea loaders failure handler already raises one with the+ // server's error detail. These listeners only record the rejected change.+ addRuleFailure: () => {+ captureInboxSettingsChanged({+ setting: 'repo_routing_rule_added',+ newValue: null,+ success: false,+ scope: 'team',+ })+ },+ saveEditedRuleFailure: () => {+ captureInboxSettingsChanged({+ setting: 'repo_routing_rule_updated',+ newValue: null,+ success: false,+ scope: 'team',+ })+ },+ deleteRuleFailure: () => {+ captureInboxSettingsChanged({+ setting: 'repo_routing_rule_removed',+ newValue: null,+ success: false,+ scope: 'team',+ })+ },+ })),+ afterMount(({ actions }) => {+ actions.loadRules()+ }),+])++function ruleDisabledReason(ruleText: string, repository: string): string | null {+ if (!ruleText.trim()) {+ return 'Describe which requests the rule matches'+ }+ if (ruleText.trim().length > MAX_RULE_TEXT_LENGTH) {+ return `Keep the rule under ${MAX_RULE_TEXT_LENGTH} characters`+ }+ if (!repository) {+ return 'Pick a repository'+ }+ return null+}diff --git a/products/tasks/backend/presentation/views/repo_routing_rules_api.py b/products/tasks/backend/presentation/views/repo_routing_rules_api.pynew file mode 100644index 000000000000..0cc989bcfa19--- /dev/null+++ b/products/tasks/backend/presentation/views/repo_routing_rules_api.py@@ -0,0 +1,112 @@+import re++from django.db import connection, transaction+from django.db.models import Max, QuerySet++from rest_framework import serializers, viewsets+from rest_framework.authentication import SessionAuthentication+from rest_framework.permissions import SAFE_METHODS, BasePermission, IsAuthenticated+from rest_framework.request import Request++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.shared import UserBasicSerializer+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication+from posthog.models.repo_routing_rule import RepoRoutingRule+from posthog.permissions import APIScopePermission++from products.tasks.backend.facade.client_provenance import is_sandbox_oauth_request++_AUTH_CLASSES = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]++# The repo selection prompt truncates each rendered rule at this length, so a longer rule+# would silently lose its distinguishing terms. The Slack `rules add` path enforces the+# same limit.+MAX_RULE_TEXT_LENGTH = 300++# Every rule rides in the repo selection prompt, so an unbounded set would bloat it. The cap+# is a guardrail well above realistic use, not a product limit.+MAX_RULES_PER_TEAM = 50++_REPOSITORY_RE = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")+++class NotSandboxForWrites(BasePermission):+ """Sandbox OAuth tokens carry `task:write`, but a coding agent must not steer where the+ team's future tasks land — a prompt-injected run could redirect teammates' work to a+ repository of the attacker's choosing. Reads stay open: runs receive the rules in their+ prompt anyway."""++ message = "Task agents cannot modify routing rules."++ def has_permission(self, request: Request, view) -> bool:+ return request.method in SAFE_METHODS or not is_sandbox_oauth_request(request)+++class RepoRoutingRuleSerializer(serializers.ModelSerializer):+ rule_text = serializers.CharField(+ max_length=MAX_RULE_TEXT_LENGTH,+ help_text=(+ "Plain-text description of the requests that should route to the repository, "+ f"e.g. 'anything about the internal dashboard'. At most {MAX_RULE_TEXT_LENGTH} characters."+ ),+ )+ repository = serializers.CharField(+ max_length=255,+ help_text="Target repository as owner/repo, e.g. 'posthog/posthog.com'.",+ )+ created_by = UserBasicSerializer(+ read_only=True,+ allow_null=True,+ help_text="Who created the rule, from the UI or the Slack commands. Null when that user was deleted.",+ )++ class Meta:+ model = RepoRoutingRule+ fields = ["id", "rule_text", "repository", "priority", "created_by", "created_at", "updated_at"]+ read_only_fields = ["id", "priority", "created_by", "created_at", "updated_at"]++ def validate_repository(self, value: str) -> str:+ if not _REPOSITORY_RE.match(value):+ raise serializers.ValidationError("Enter the repository as owner/repo.")+ return value+++class RepoRoutingRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):+ """Team routing rules that steer agent repo selection (`RepoRoutingRule`).++ The same rows the Slack `@PostHog rules` commands manage; the repo selection agent+ reads them ordered by priority when picking a repository for a task. Rules whose+ repository is not connected to the project are ignored at selection time, so a+ stale rule is inert rather than harmful — which is why writes here don't check the+ connected-repository list (the UI constrains the picker to connected repos anyway).+ """++ scope_object = "task"+ authentication_classes = _AUTH_CLASSES+ permission_classes = [IsAuthenticated, APIScopePermission, NotSandboxForWrites]+ serializer_class = RepoRoutingRuleSerializer+ queryset = RepoRoutingRule.objects.all()+ # A team holds a handful of rules and the settings UI renders them all, so `list`+ # returns a raw array.+ pagination_class = None++ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:+ return queryset.order_by("priority", "id")++ def perform_create(self, serializer: serializers.BaseSerializer) -> None:+ with transaction.atomic():+ # Serialize creates per team: without the lock, concurrent requests can both pass+ # the cap check and take the same priority, breaking "earlier rules win" ordering.+ with connection.cursor() as cursor:+ cursor.execute("SELECT pg_advisory_xact_lock(%s, hashtext(%s))", [self.team_id, "repo_routing_rules"])+ if RepoRoutingRule.objects.filter(team_id=self.team_id).count() >= MAX_RULES_PER_TEAM:+ raise serializers.ValidationError(+ f"A project can have at most {MAX_RULES_PER_TEAM} routing rules. Remove one to add another."+ )+ # Append at the end, matching the Slack `rules add` path: earlier rules win ties.+ max_priority = RepoRoutingRule.objects.filter(team_id=self.team_id).aggregate(m=Max("priority"))["m"]+ serializer.save(+ team_id=self.team_id,+ created_by=self.request.user,+ priority=0 if max_priority is None else max_priority + 1,+ )diff --git a/products/tasks/backend/routes.py b/products/tasks/backend/routes.pyindex 8df4be3a0e7e..20f1b4163704 100644--- a/products/tasks/backend/routes.py+++ b/products/tasks/backend/routes.py@@ -8,6 +8,7 @@ import products.tasks.backend.presentation.views.channels_api as channelsimport products.tasks.backend.presentation.views.desktop_access as desktop_accessimport products.tasks.backend.presentation.views.task_usage_api as task_usageimport products.tasks.backend.presentation.views.sandbox_pricing_api as sandbox_pricing+import products.tasks.backend.presentation.views.repo_routing_rules_api as repo_routing_rulesdef register_routes(routers: RouterRegistry) -> None:@@ -27,6 +28,12 @@ def register_routes(routers: RouterRegistry) -> None:)routers.projects.register(r"desktop", desktop_access.DesktopAccessViewSet, "project_desktop", ["team_id"])routers.projects.register(r"tasks/config", config.TasksTeamConfigViewSet, "project_tasks_config", ["team_id"])+ routers.projects.register(+ r"tasks/repo_routing_rules",+ repo_routing_rules.RepoRoutingRuleViewSet,+ "project_tasks_repo_routing_rules",+ ["team_id"],+ )routers.projects.register(r"tasks/@me/config", config.TasksUserConfigViewSet, "project_tasks_me_config", ["team_id"])diff --git a/products/tasks/backend/tests/test_repo_routing_rules_api.py b/products/tasks/backend/tests/test_repo_routing_rules_api.pynew file mode 100644index 000000000000..bba70e15c8d8--- /dev/null+++ b/products/tasks/backend/tests/test_repo_routing_rules_api.py@@ -0,0 +1,137 @@+from datetime import timedelta+from uuid import uuid4++from posthog.test.base import APIBaseTest++from django.test import SimpleTestCase+from django.utils import timezone as django_timezone++from parameterized import parameterized+from rest_framework import status+from rest_framework.test import APIClient++from posthog.models import Team+from posthog.models.oauth import OAuthAccessToken, OAuthApplication+from posthog.models.repo_routing_rule import RepoRoutingRule+from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV++from products.tasks.backend.presentation.views.repo_routing_rules_api import (+ MAX_RULES_PER_TEAM,+ RepoRoutingRuleSerializer,+)+++class TestRepoRoutingRuleSerializerValidation(SimpleTestCase):+ @parameterized.expand(+ [+ ("missing_slash", "posthog"),+ ("extra_segment", "a/b/c"),+ ("space_in_repo", "posthog/my repo"),+ ("empty_owner", "/repo"),+ ("empty_repo", "posthog/"),+ ]+ )+ def test_rejects_malformed_repository(self, _name: str, repository: str) -> None:+ serializer = RepoRoutingRuleSerializer(data={"rule_text": "dashboards", "repository": repository})+ assert not serializer.is_valid()+ assert "repository" in serializer.errors++ def test_rejects_overlong_rule_text(self) -> None:+ serializer = RepoRoutingRuleSerializer(data={"rule_text": "x" * 301, "repository": "posthog/posthog"})+ assert not serializer.is_valid()+ assert "rule_text" in serializer.errors+++class TestRepoRoutingRulesAPI(APIBaseTest):+ def _url(self, rule_id=None) -> str:+ base = f"/api/projects/{self.team.id}/tasks/repo_routing_rules/"+ return f"{base}{rule_id}/" if rule_id else base++ def test_create_appends_priority_and_sets_created_by(self):+ RepoRoutingRule.objects.create(team=self.team, rule_text="existing", repository="posthog/posthog", priority=4)+ response = self.client.post(self._url(), {"rule_text": "docs and website", "repository": "PostHog/posthog.com"})+ assert response.status_code == status.HTTP_201_CREATED+ assert response.json()["created_by"]["email"] == self.user.email+ rule = RepoRoutingRule.objects.get(id=response.json()["id"])+ assert rule.team == self.team+ assert rule.created_by == self.user+ assert rule.priority == 5+ assert rule.repository == "PostHog/posthog.com"++ def test_create_rejects_overlong_rule_text(self):+ response = self.client.post(self._url(), {"rule_text": "x" * 301, "repository": "posthog/posthog"})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "rule_text"+ assert RepoRoutingRule.objects.count() == 0++ def test_list_is_team_scoped_and_priority_ordered(self):+ other_team = Team.objects.create(organization=self.organization, name="other")+ RepoRoutingRule.objects.create(team=other_team, rule_text="other", repository="acme/other", priority=0)+ second = RepoRoutingRule.objects.create(team=self.team, rule_text="b", repository="posthog/b", priority=2)+ first = RepoRoutingRule.objects.create(team=self.team, rule_text="a", repository="posthog/a", priority=1)+ response = self.client.get(self._url())+ assert response.status_code == status.HTTP_200_OK+ assert [row["id"] for row in response.json()] == [str(first.id), str(second.id)]++ def test_detail_actions_cannot_reach_another_teams_rule(self):+ other_team = Team.objects.create(organization=self.organization, name="other")+ rule = RepoRoutingRule.objects.create(team=other_team, rule_text="other", repository="acme/other")+ assert self.client.patch(self._url(rule.id), {"rule_text": "hijack"}).status_code == status.HTTP_404_NOT_FOUND+ assert self.client.delete(self._url(rule.id)).status_code == status.HTTP_404_NOT_FOUND+ rule.refresh_from_db()+ assert rule.rule_text == "other"++ def test_patch_edits_text_and_repo_but_not_priority(self):+ rule = RepoRoutingRule.objects.create(team=self.team, rule_text="old", repository="posthog/old", priority=3)+ response = self.client.patch(+ self._url(rule.id), {"rule_text": "new", "repository": "posthog/new", "priority": 0}+ )+ assert response.status_code == status.HTTP_200_OK+ rule.refresh_from_db()+ assert (rule.rule_text, rule.repository, rule.priority) == ("new", "posthog/new", 3)++ def test_create_rejects_at_team_rule_cap(self):+ RepoRoutingRule.objects.bulk_create(+ RepoRoutingRule(team=self.team, rule_text=f"rule {i}", repository="posthog/posthog", priority=i)+ for i in range(MAX_RULES_PER_TEAM)+ )+ response = self.client.post(self._url(), {"rule_text": "one too many", "repository": "posthog/posthog"})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert RepoRoutingRule.objects.filter(team=self.team).count() == MAX_RULES_PER_TEAM++ def test_delete_removes_rule(self):+ rule = RepoRoutingRule.objects.create(team=self.team, rule_text="temp", repository="posthog/temp")+ assert self.client.delete(self._url(rule.id)).status_code == status.HTTP_204_NO_CONTENT+ assert not RepoRoutingRule.objects.filter(id=rule.id).exists()++ def test_sandbox_token_reads_but_cannot_write(self):+ rule = RepoRoutingRule.objects.create(team=self.team, rule_text="docs", repository="posthog/posthog.com")+ application = OAuthApplication.objects.create(+ name="Loop sandbox",+ client_id=ARRAY_APP_CLIENT_ID_DEV,+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ algorithm="RS256",+ redirect_uris="https://example.com/callback",+ organization=self.organization,+ user=self.user,+ )+ access_token = OAuthAccessToken.objects.create(+ user=self.user,+ application=application,+ token="pha_loop_sandbox",+ expires=django_timezone.now() + timedelta(hours=1),+ scope="task:read task:write",+ scoped_teams=[self.team.id],+ sandbox_task_id=uuid4(),+ )+ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")++ assert client.get(self._url()).status_code == status.HTTP_200_OK+ create = client.post(self._url(), {"rule_text": "steer elsewhere", "repository": "attacker/repo"})+ assert create.status_code == status.HTTP_403_FORBIDDEN+ assert client.patch(self._url(rule.id), {"rule_text": "steer"}).status_code == status.HTTP_403_FORBIDDEN+ assert client.delete(self._url(rule.id)).status_code == status.HTTP_403_FORBIDDEN+ rule.refresh_from_db()+ assert rule.rule_text == "docs"diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 93880a1e913d..63704163d9be 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -4451,6 +4451,101 @@ export interface PinnedTaskIdsResponseApi {task_ids: string[]}+/**+ * * `engineering` - Engineering+ * * `data` - Data+ * * `product` - Product Management+ * * `founder` - Founder+ * * `leadership` - Leadership+ * * `marketing` - Marketing+ * * `sales` - Sales / Success+ * * `student` - Student+ * * `other` - Other+ */+export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]++export const RoleAtOrganizationEnumApi = {+ Engineering: 'engineering',+ Data: 'data',+ Product: 'product',+ Founder: 'founder',+ Leadership: 'leadership',+ Marketing: 'marketing',+ Sales: 'sales',+ Student: 'student',+ Other: 'other',+} as const++export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]++export const BlankEnumApi = {+ '': '',+} as const++/**+ * @nullable+ */+export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null++export interface UserBasicApi {+ readonly id: number+ readonly uuid: string+ /**+ * @maxLength 200+ * @nullable+ */+ distinct_id?: string | null+ /** @maxLength 150 */+ first_name?: string+ /** @maxLength 150 */+ last_name?: string+ /** @maxLength 254 */+ email: string+ /** @nullable */+ is_email_verified?: boolean | null+ /** @nullable */+ readonly hedgehog_config: UserBasicApiHedgehogConfig+ role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null+}++export interface RepoRoutingRuleApi {+ readonly id: string+ /**+ * Plain-text description of the requests that should route to the repository, e.g. 'anything about the internal dashboard'. At most 300 characters.+ * @maxLength 300+ */+ rule_text: string+ /**+ * Target repository as owner/repo, e.g. 'posthog/posthog.com'.+ * @maxLength 255+ */+ repository: string+ readonly priority: number+ /** Who created the rule, from the UI or the Slack commands. Null when that user was deleted. */+ readonly created_by: UserBasicApi | null+ readonly created_at: string+ readonly updated_at: string+}++export interface PatchedRepoRoutingRuleApi {+ readonly id?: string+ /**+ * Plain-text description of the requests that should route to the repository, e.g. 'anything about the internal dashboard'. At most 300 characters.+ * @maxLength 300+ */+ rule_text?: string+ /**+ * Target repository as owner/repo, e.g. 'posthog/posthog.com'.+ * @maxLength 255+ */+ repository?: string+ readonly priority?: number+ /** Who created the rule, from the UI or the Slack commands. Null when that user was deleted. */+ readonly created_by?: UserBasicApi | null+ readonly created_at?: string+ readonly updated_at?: string+}+export interface TaskRepositoriesResponseApi {/** Distinct repositories in use by non-deleted, non-internal tasks for the current team. */repositories: string[]diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex 4071da0e3900..1f1388e8638c 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -52,6 +52,7 @@ import type {PatchedChannelInstructionsWriteApi,PatchedChannelUpdateApi,PatchedLoopWriteApi,+ PatchedRepoRoutingRuleApi,PatchedSandboxCustomImageUpdateApi,PatchedSandboxEnvironmentWriteApi,PatchedTaskRunSetOutputRequestApi,@@ -59,6 +60,7 @@ import type {PatchedTaskWriteApi,PinnedTaskIdsResponseApi,ProvisionedChannelsApi,+ RepoRoutingRuleApi,RepositoryReadinessResponseApi,SandboxComputePricingApi,SandboxCustomImageBuildApi,@@ -159,6 +161,23 @@ import type {WizardCloudRunDTOApi,} from './api.schemas'+// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B++type WritableKeys<T> = {+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>+}[keyof T]++type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never++type Writable<T> = Pick<T, WritableKeys<T>>+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]+ ? {+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]+ }+ : DistributeReadOnlyOverUnions<T>+export const getCodeInvitesCheckAccessRetrieveUrl = () => {return `/api/code/invites/check-access/`}@@ -2791,6 +2810,157 @@ export const tasksPinnedRetrieve = async (})}+export const getTasksRepoRoutingRulesListUrl = (projectId: string) => {+ return `/api/projects/${projectId}/tasks/repo_routing_rules/`+}++/**+ * Team routing rules that steer agent repo selection (`RepoRoutingRule`).+ *+ * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent+ * reads them ordered by priority when picking a repository for a task. Rules whose+ * repository is not connected to the project are ignored at selection time, so a+ * stale rule is inert rather than harmful — which is why writes here don't check the+ * connected-repository list (the UI constrains the picker to connected repos anyway).+ */+export const tasksRepoRoutingRulesList = async (+ projectId: string,+ options?: RequestInit+): Promise<RepoRoutingRuleApi[]> => {+ return apiMutator<RepoRoutingRuleApi[]>(getTasksRepoRoutingRulesListUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getTasksRepoRoutingRulesCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/tasks/repo_routing_rules/`+}++/**+ * Team routing rules that steer agent repo selection (`RepoRoutingRule`).+ *+ * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent+ * reads them ordered by priority when picking a repository for a task. Rules whose+ * repository is not connected to the project are ignored at selection time, so a+ * stale rule is inert rather than harmful — which is why writes here don't check the+ * connected-repository list (the UI constrains the picker to connected repos anyway).+ */+export const tasksRepoRoutingRulesCreate = async (+ projectId: string,+ repoRoutingRuleApi: NonReadonly<RepoRoutingRuleApi>,+ options?: RequestInit+): Promise<RepoRoutingRuleApi> => {+ return apiMutator<RepoRoutingRuleApi>(getTasksRepoRoutingRulesCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(repoRoutingRuleApi),+ })+}++export const getTasksRepoRoutingRulesRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/tasks/repo_routing_rules/${id}/`+}++/**+ * Team routing rules that steer agent repo selection (`RepoRoutingRule`).+ *+ * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent+ * reads them ordered by priority when picking a repository for a task. Rules whose+ * repository is not connected to the project are ignored at selection time, so a+ * stale rule is inert rather than harmful — which is why writes here don't check the+ * connected-repository list (the UI constrains the picker to connected repos anyway).+ */+export const tasksRepoRoutingRulesRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<RepoRoutingRuleApi> => {+ return apiMutator<RepoRoutingRuleApi>(getTasksRepoRoutingRulesRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getTasksRepoRoutingRulesUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/tasks/repo_routing_rules/${id}/`+}++/**+ * Team routing rules that steer agent repo selection (`RepoRoutingRule`).+ *+ * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent+ * reads them ordered by priority when picking a repository for a task. Rules whose+ * repository is not connected to the project are ignored at selection time, so a+ * stale rule is inert rather than harmful — which is why writes here don't check the+ * connected-repository list (the UI constrains the picker to connected repos anyway).+ */+export const tasksRepoRoutingRulesUpdate = async (+ projectId: string,+ id: string,+ repoRoutingRuleApi: NonReadonly<RepoRoutingRuleApi>,+ options?: RequestInit+): Promise<RepoRoutingRuleApi> => {+ return apiMutator<RepoRoutingRuleApi>(getTasksRepoRoutingRulesUpdateUrl(projectId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(repoRoutingRuleApi),+ })+}++export const getTasksRepoRoutingRulesPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/tasks/repo_routing_rules/${id}/`+}++/**+ * Team routing rules that steer agent repo selection (`RepoRoutingRule`).+ *+ * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent+ * reads them ordered by priority when picking a repository for a task. Rules whose+ * repository is not connected to the project are ignored at selection time, so a+ * stale rule is inert rather than harmful — which is why writes here don't check the+ * connected-repository list (the UI constrains the picker to connected repos anyway).+ */+export const tasksRepoRoutingRulesPartialUpdate = async (+ projectId: string,+ id: string,+ patchedRepoRoutingRuleApi?: NonReadonly<PatchedRepoRoutingRuleApi>,+ options?: RequestInit+): Promise<RepoRoutingRuleApi> => {+ return apiMutator<RepoRoutingRuleApi>(getTasksRepoRoutingRulesPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedRepoRoutingRuleApi),+ })+}++export const getTasksRepoRoutingRulesDestroyUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/tasks/repo_routing_rules/${id}/`+}++/**+ * Team routing rules that steer agent repo selection (`RepoRoutingRule`).+ *+ * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent+ * reads them ordered by priority when picking a repository for a task. Rules whose+ * repository is not connected to the project are ignored at selection time, so a+ * stale rule is inert rather than harmful — which is why writes here don't check the+ * connected-repository list (the UI constrains the picker to connected repos anyway).+ */+export const tasksRepoRoutingRulesDestroy = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getTasksRepoRoutingRulesDestroyUrl(projectId, id), {+ ...options,+ method: 'DELETE',+ })+}+export const getTasksRepositoriesRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/tasks/repositories/`}diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex 76cd4aa65223..cba338c4cb03 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -3492,6 +3492,86 @@ export const TasksConfigCreateBody = /* @__PURE__ */ zod'The default AI run triple stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. `runtime_adapter` and `model` must be set together; send all three\nas null to clear a stored preference.')+/**+ * Team routing rules that steer agent repo selection (`RepoRoutingRule`).+ *+ * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent+ * reads them ordered by priority when picking a repository for a task. Rules whose+ * repository is not connected to the project are ignored at selection time, so a+ * stale rule is inert rather than harmful — which is why writes here don't check the+ * connected-repository list (the UI constrains the picker to connected repos anyway).+ */+export const tasksRepoRoutingRulesCreateBodyRuleTextMax = 300++export const tasksRepoRoutingRulesCreateBodyRepositoryMax = 255++export const TasksRepoRoutingRulesCreateBody = /* @__PURE__ */ zod.object({+ rule_text: zod+ .string()+ .max(tasksRepoRoutingRulesCreateBodyRuleTextMax)+ .describe(+ "Plain-text description of the requests that should route to the repository, e.g. 'anything about the internal dashboard'. At most 300 characters."+ ),+ repository: zod+ .string()+ .max(tasksRepoRoutingRulesCreateBodyRepositoryMax)+ .describe("Target repository as owner\/repo, e.g. 'posthog\/posthog.com'."),+})++/**+ * Team routing rules that steer agent repo selection (`RepoRoutingRule`).+ *+ * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent+ * reads them ordered by priority when picking a repository for a task. Rules whose+ * repository is not connected to the project are ignored at selection time, so a+ * stale rule is inert rather than harmful — which is why writes here don't check the+ * connected-repository list (the UI constrains the picker to connected repos anyway).+ */+export const tasksRepoRoutingRulesUpdateBodyRuleTextMax = 300++export const tasksRepoRoutingRulesUpdateBodyRepositoryMax = 255++export const TasksRepoRoutingRulesUpdateBody = /* @__PURE__ */ zod.object({+ rule_text: zod+ .string()+ .max(tasksRepoRoutingRulesUpdateBodyRuleTextMax)+ .describe(+ "Plain-text description of the requests that should route to the repository, e.g. 'anything about the internal dashboard'. At most 300 characters."+ ),+ repository: zod+ .string()+ .max(tasksRepoRoutingRulesUpdateBodyRepositoryMax)+ .describe("Target repository as owner\/repo, e.g. 'posthog\/posthog.com'."),+})++/**+ * Team routing rules that steer agent repo selection (`RepoRoutingRule`).+ *+ * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent+ * reads them ordered by priority when picking a repository for a task. Rules whose+ * repository is not connected to the project are ignored at selection time, so a+ * stale rule is inert rather than harmful — which is why writes here don't check the+ * connected-repository list (the UI constrains the picker to connected repos anyway).+ */+export const tasksRepoRoutingRulesPartialUpdateBodyRuleTextMax = 300++export const tasksRepoRoutingRulesPartialUpdateBodyRepositoryMax = 255++export const TasksRepoRoutingRulesPartialUpdateBody = /* @__PURE__ */ zod.object({+ rule_text: zod+ .string()+ .max(tasksRepoRoutingRulesPartialUpdateBodyRuleTextMax)+ .optional()+ .describe(+ "Plain-text description of the requests that should route to the repository, e.g. 'anything about the internal dashboard'. At most 300 characters."+ ),+ repository: zod+ .string()+ .max(tasksRepoRoutingRulesPartialUpdateBodyRepositoryMax)+ .optional()+ .describe("Target repository as owner\/repo, e.g. 'posthog\/posthog.com'."),+})+/*** Returns summary for the requested tasks, including the creator ID and the latest run's ID, status, and environment.* @summary Fetch task summaries by IDdiff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yamlindex 07480eae9b29..7c3d3fc08ee9 100644--- a/products/tasks/mcp/tools.yaml+++ b/products/tasks/mcp/tools.yaml@@ -565,6 +565,24 @@ tools:tasks-presence-destroy:operation: tasks_presence_destroyenabled: false+ tasks-repo-routing-rules-create:+ operation: tasks_repo_routing_rules_create+ enabled: false+ tasks-repo-routing-rules-destroy:+ operation: tasks_repo_routing_rules_destroy+ enabled: false+ tasks-repo-routing-rules-list:+ operation: tasks_repo_routing_rules_list+ enabled: false+ tasks-repo-routing-rules-partial-update:+ operation: tasks_repo_routing_rules_partial_update+ enabled: false+ tasks-repo-routing-rules-retrieve:+ operation: tasks_repo_routing_rules_retrieve+ enabled: false+ tasks-repo-routing-rules-update:+ operation: tasks_repo_routing_rules_update+ enabled: falsetasks-repositories-retrieve:operation: tasks_repositories_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex fa489ac5e81d..acb711ceeec5 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -67991,6 +67991,25 @@ export namespace Schemas {readonly user_access_level?: string | null;}+ export interface PatchedRepoRoutingRule {+ readonly id?: string;+ /**+ * Plain-text description of the requests that should route to the repository, e.g. 'anything about the internal dashboard'. At most 300 characters.+ * @maxLength 300+ */+ rule_text?: string;+ /**+ * Target repository as owner/repo, e.g. 'posthog/posthog.com'.+ * @maxLength 255+ */+ repository?: string;+ readonly priority?: number;+ /** Who created the rule, from the UI or the Slack commands. Null when that user was deleted. */+ readonly created_by?: UserBasic | null;+ readonly created_at?: string;+ readonly updated_at?: string;+ }+export interface PatchedReviewBlindSpotsConfigSelect {/** Set true to make this the single blind-spots skill that runs on the user's PR reviews. Only true is accepted — the blind-spot check is single-active, so you switch by selecting a different skill, not by deactivating the current one. */active?: boolean;@@ -76631,6 +76650,25 @@ export namespace Schemas {ready_to_merge_series_granularity: string;}+ export interface RepoRoutingRule {+ readonly id: string;+ /**+ * Plain-text description of the requests that should route to the repository, e.g. 'anything about the internal dashboard'. At most 300 characters.+ * @maxLength 300+ */+ rule_text: string;+ /**+ * Target repository as owner/repo, e.g. 'posthog/posthog.com'.+ * @maxLength 255+ */+ repository: string;+ readonly priority: number;+ /** Who created the rule, from the UI or the Slack commands. Null when that user was deleted. */+ readonly created_by: UserBasic | null;+ readonly created_at: string;+ readonly updated_at: string;+ }+export type ReportPriority = typeof ReportPriority[keyof typeof ReportPriority];