Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): send scout run output to Slack (#72937)

Radu Raiceac867f7699f9b
diff --git a/frontend/src/scenes/inbox/components/config/scouts/ScoutConfigControls.test.tsx b/frontend/src/scenes/inbox/components/config/scouts/ScoutConfigControls.test.tsx
index e254fa87f11b..3b813ba9a7d3 100644
--- a/frontend/src/scenes/inbox/components/config/scouts/ScoutConfigControls.test.tsx
+++ b/frontend/src/scenes/inbox/components/config/scouts/ScoutConfigControls.test.tsx
@@ -1,5 +1,6 @@
import { fireEvent, render } from '@testing-library/react'
+import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import type { SignalScoutConfigApi } from 'products/signals/frontend/generated/api.schemas'
@@ -15,16 +16,23 @@ const config: SignalScoutConfigApi = {
emit: true,
run_interval_minutes: 1440,
run_cron_schedule: '0 9 * * *',
+ output_destinations: {},
last_run_at: null,
created_at: '2026-07-21T12:00:00Z',
}
describe('ScoutConfigForm', () => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/integrations/': () => [200, { results: [] }],
+ },
+ })
+
beforeEach(() => initKeaTests())
it('saves the daily run time on blur and never clears the schedule from an empty input', () => {
const onUpdate = jest.fn()
- const { container } = render(<ScoutConfigForm config={config} onUpdate={onUpdate} />)
+ const { container, unmount } = render(<ScoutConfigForm config={config} onUpdate={onUpdate} />)
const input = container.querySelector<HTMLInputElement>('input[type="time"]')
expect(input).not.toBeNull()
@@ -40,15 +48,17 @@ describe('ScoutConfigForm', () => {
fireEvent.change(input!, { target: { value: '' } })
fireEvent.blur(input!)
expect(onUpdate).toHaveBeenCalledTimes(1)
+ unmount()
})
it('shows an unexpressible cron as a read-only custom mode without a time picker', () => {
const onUpdate = jest.fn()
- const { container, getByText } = render(
+ const { container, getByText, unmount } = render(
<ScoutConfigForm config={{ ...config, run_cron_schedule: '0 9 * * 1-5' }} onUpdate={onUpdate} />
)
expect(container.querySelector('input[type="time"]')).toBeNull()
expect(getByText('Custom (0 9 * * 1-5)')).toBeTruthy()
+ unmount()
})
})
diff --git a/frontend/src/scenes/inbox/components/config/scouts/ScoutConfigControls.tsx b/frontend/src/scenes/inbox/components/config/scouts/ScoutConfigControls.tsx
index 2b06ba4a0468..8d4df5f44461 100644
--- a/frontend/src/scenes/inbox/components/config/scouts/ScoutConfigControls.tsx
+++ b/frontend/src/scenes/inbox/components/config/scouts/ScoutConfigControls.tsx
@@ -1,9 +1,14 @@
-import { useValues } from 'kea'
+import { useMountedLogic, useValues } from 'kea'
import { IconTrash } from '@posthog/icons'
-import { LemonButton, LemonDialog, LemonInput, LemonSelect, LemonSwitch, Tooltip } from '@posthog/lemon-ui'
+import { LemonButton, LemonDialog, LemonInput, LemonSelect, LemonSwitch, Link, Tooltip } from '@posthog/lemon-ui'
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { SlackChannelPicker } from 'lib/integrations/SlackIntegrationHelpers'
import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import type { IntegrationType } from '~/types'
import type {
PatchedSignalScoutConfigUpdateApi as SignalScoutConfigUpdate,
@@ -21,6 +26,7 @@ import {
interface ScoutConfigControlsProps {
config: SignalScoutConfig
onUpdate: (configId: string, updates: SignalScoutConfigUpdate) => void
+ updating?: boolean
}
interface ScoutConfigFormProps extends ScoutConfigControlsProps {
@@ -60,11 +66,7 @@ function scheduleOptions(config: SignalScoutConfig, scheduleMode: string): { val
}
/** Enable/disable toggle for a scout. Lives on the row, not in the settings form. */
-export function ScoutEnabledSwitch({
- config,
- onUpdate,
- updating = false,
-}: ScoutConfigControlsProps & { updating?: boolean }): JSX.Element {
+export function ScoutEnabledSwitch({ config, onUpdate, updating = false }: ScoutConfigControlsProps): JSX.Element {
return (
<Tooltip title={config.enabled ? 'Disable scout' : 'Enable scout'}>
<span>
@@ -72,6 +74,7 @@ export function ScoutEnabledSwitch({
size="small"
checked={config.enabled}
onChange={(checked) => onUpdate(config.id, { enabled: checked })}
+ loading={updating}
disabledReason={updating ? 'Saving scout settings' : undefined}
aria-label={`${config.skill_name} enabled`}
/>
@@ -91,6 +94,8 @@ export function ScoutConfigForm({
deleting,
updating = false,
}: ScoutConfigFormProps): JSX.Element {
+ useMountedLogic(integrationsLogic)
+ const { slackIntegrations, integrationsLoading } = useValues(integrationsLogic)
const { timezone: projectTimezone } = useValues(teamLogic)
const dailyTime = dailyCronToTime(config.run_cron_schedule)
const scheduleMode = config.run_cron_schedule
@@ -163,6 +168,14 @@ export function ScoutConfigForm({
/>
</div>
) : null}
+ <ScoutSlackDestination
+ config={config}
+ onUpdate={onUpdate}
+ integrations={slackIntegrations ?? []}
+ loading={integrationsLoading && slackIntegrations === undefined}
+ updating={updating}
+ disabledReason={controlsDisabledReason}
+ />
{/* Only custom scouts are deletable. A canonical scout would be re-seeded from disk after
deletion (and couldn't be re-added from the UI), so its terminal action stays disable. */}
{onDelete && config.scout_origin === 'custom' ? (
@@ -187,6 +200,86 @@ export function ScoutConfigForm({
)
}
+function ScoutSlackDestination({
+ config,
+ onUpdate,
+ integrations,
+ loading,
+ updating = false,
+ disabledReason,
+}: ScoutConfigControlsProps & {
+ integrations: IntegrationType[]
+ loading: boolean
+ disabledReason?: string
+}): JSX.Element {
+ const destination = config.output_destinations?.slack
+ const configuredIntegration = destination
+ ? integrations.find((integration) => integration.id === destination.integration_id)
+ : undefined
+ const selectedIntegration = configuredIntegration ?? (integrations.length === 1 ? integrations[0] : null)
+
+ const selectWorkspace = (integrationId: number): void => {
+ onUpdate(config.id, {
+ output_destinations: { slack: { integration_id: integrationId, channel: null } },
+ })
+ }
+
+ const selectChannel = (channel: string | null): void => {
+ if (!channel || !selectedIntegration) {
+ onUpdate(config.id, { output_destinations: {} })
+ return
+ }
+ onUpdate(config.id, {
+ output_destinations: {
+ slack: { integration_id: selectedIntegration.id, channel },
+ },
+ })
+ }
+
+ return (
+ <div className="flex flex-col gap-2 border-t border-primary pt-2">
+ <div className="flex flex-col min-w-0">
+ <span className="text-xs text-default">Slack destination</span>
+ <span className="text-[11.5px] text-muted">Post each scout run's output to a channel</span>
+ </div>
+ {loading ? (
+ <span className="text-xs text-muted">Loading Slack workspaces…</span>
+ ) : integrations.length === 0 ? (
+ <Link to={urls.settings('environment-integrations', 'integration-slack')}>
+ Connect a Slack workspace
+ </Link>
+ ) : (
+ <div className="flex flex-col gap-2 max-w-md">
+ {integrations.length > 1 ? (
+ <LemonSelect
+ size="small"
+ value={selectedIntegration?.id ?? null}
+ options={integrations.map((integration) => ({
+ value: integration.id,
+ label: integration.display_name || `Slack workspace ${integration.id}`,
+ }))}
+ onChange={(integrationId) => integrationId != null && selectWorkspace(integrationId)}
+ placeholder="Select workspace"
+ disabledReason={disabledReason ?? (updating ? 'Saving…' : undefined)}
+ />
+ ) : null}
+ {selectedIntegration ? (
+ <SlackChannelPicker
+ integration={selectedIntegration}
+ value={configuredIntegration ? (destination?.channel ?? undefined) : undefined}
+ onChange={selectChannel}
+ disabled={updating || disabledReason !== undefined}
+ />
+ ) : null}
+ <span className="text-[11.5px] text-muted">
+ PostHog must be in the channel. Invite it with <code>/invite @PostHog</code>.
+ </span>
+ </div>
+ )}
+ </div>
+ )
+}
+
/**
* Confirm-then-delete for a custom scout. Deletion archives the scout's skill (the permanent off
* switch — the coordinator won't re-seed a tombstoned skill or re-create its config) and removes
diff --git a/frontend/src/scenes/inbox/components/config/scouts/ScoutDetailView.tsx b/frontend/src/scenes/inbox/components/config/scouts/ScoutDetailView.tsx
index a31c8c48b2b9..f80aa7a40e8a 100644
--- a/frontend/src/scenes/inbox/components/config/scouts/ScoutDetailView.tsx
+++ b/frontend/src/scenes/inbox/components/config/scouts/ScoutDetailView.tsx
@@ -21,7 +21,7 @@ import { ScoutRunHistorySection } from './ScoutRunHistorySection'
* rollup line. The Signals section (emission cards) and per-scout run history land next (W2/W3).
*/
export function ScoutDetailView({ skillName }: { skillName: string }): JSX.Element {
- const { scoutConfigs, rollups, runsWindowComplete } = useValues(scoutFleetLogic)
+ const { scoutConfigs, rollups, runsWindowComplete, updatingScoutIds } = useValues(scoutFleetLogic)
const { updateScoutConfig, startRunsPolling, stopRunsPolling } = useActions(scoutFleetLogic)
const { setSelectedScoutSkillName } = useActions(inboxSceneLogic)
@@ -57,7 +57,13 @@ export function ScoutDetailView({ skillName }: { skillName: string }): JSX.Eleme
<div className="flex flex-1 items-center justify-center text-sm text-tertiary">Scout not found.</div>
) : (
<>
- <ScoutRowCard config={config} rollup={rollup} onUpdate={updateScoutConfig} asHeader />
+ <ScoutRowCard
+ config={config}
+ rollup={rollup}
+ onUpdate={updateScoutConfig}
+ updating={updatingScoutIds.includes(config.id)}
+ asHeader
+ />
{config.description ? (
<p className="text-sm text-secondary leading-snug mb-0">{config.description}</p>
diff --git a/frontend/src/scenes/inbox/inboxSceneLogic.test.ts b/frontend/src/scenes/inbox/inboxSceneLogic.test.ts
index 1f606a253619..9c3f5d8d47ae 100644
--- a/frontend/src/scenes/inbox/inboxSceneLogic.test.ts
+++ b/frontend/src/scenes/inbox/inboxSceneLogic.test.ts
@@ -10,6 +10,7 @@ function scoutRun(overrides: Partial<SignalScoutRunSummary> = {}): SignalScoutRu
skill_name: 'signals-scout-error-tracking',
skill_version: 1,
status: 'completed',
+ metadata: {},
created_at: '2026-06-11T10:00:00Z',
started_at: '2026-06-11T10:00:00Z',
completed_at: null,
diff --git a/frontend/src/scenes/inbox/logics/scoutFleetLogic.test.ts b/frontend/src/scenes/inbox/logics/scoutFleetLogic.test.ts
new file mode 100644
index 000000000000..40466a65633d
--- /dev/null
+++ b/frontend/src/scenes/inbox/logics/scoutFleetLogic.test.ts
@@ -0,0 +1,169 @@
+import { MOCK_TEAM_ID } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import {
+ signalsScoutConfigList,
+ signalsScoutConfigUpdate,
+ signalsScoutMetadataGet,
+} from 'products/signals/frontend/generated/api'
+import type { SignalScoutConfigApi } from 'products/signals/frontend/generated/api.schemas'
+
+import { scoutFleetLogic } from './scoutFleetLogic'
+
+jest.mock('products/signals/frontend/generated/api', () => ({
+ signalsScoutConfigDestroy: jest.fn(),
+ signalsScoutConfigList: jest.fn(),
+ signalsScoutConfigUpdate: jest.fn(),
+ signalsScoutMetadataGet: jest.fn(),
+ signalsScoutRunsFindingsSummary: jest.fn(),
+}))
+
+const mockSignalsScoutConfigList = signalsScoutConfigList as jest.MockedFunction<typeof signalsScoutConfigList>
+const mockSignalsScoutConfigUpdate = signalsScoutConfigUpdate as jest.MockedFunction<typeof signalsScoutConfigUpdate>
+const mockSignalsScoutMetadataGet = signalsScoutMetadataGet as jest.MockedFunction<typeof signalsScoutMetadataGet>
+
+const BASE_CONFIG: SignalScoutConfigApi = {
+ id: 'config-1',
+ skill_name: 'signals-scout-errors',
+ description: 'Finds error trends.',
+ scout_origin: 'canonical',
+ enabled: true,
+ emit: true,
+ run_interval_minutes: 1440,
+ run_cron_schedule: null,
+ output_destinations: {},
+ last_run_at: null,
+ created_at: '2026-07-22T00:00:00Z',
+}
+
+function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void; reject: (error: Error) => void } {
+ let resolvePromise!: (value: T) => void
+ let rejectPromise!: (error: Error) => void
+ const promise = new Promise<T>((resolve, reject) => {
+ resolvePromise = resolve
+ rejectPromise = reject
+ })
+ return { promise, resolve: resolvePromise, reject: rejectPromise }
+}
+
+describe('scoutFleetLogic', () => {
+ let logic: ReturnType<typeof scoutFleetLogic.build>
+
+ beforeEach(async () => {
+ initKeaTests()
+ mockSignalsScoutConfigList.mockReset().mockResolvedValue([])
+ mockSignalsScoutConfigUpdate.mockReset()
+ mockSignalsScoutMetadataGet.mockReset().mockResolvedValue({
+ enrolled: true,
+ banner_message: null,
+ limits: {
+ max_runs_per_tick: 1,
+ max_runs_per_day: null,
+ runs_today: 0,
+ runs_remaining_today: null,
+ },
+ })
+
+ logic = scoutFleetLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.loadScoutConfigsSuccess([BASE_CONFIG])
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ it('queues updates for a scout while its previous update is in flight', async () => {
+ const firstRequest = deferred<SignalScoutConfigApi>()
+ const queuedUpdates = {
+ run_interval_minutes: 60,
+ output_destinations: {
+ slack: { integration_id: 42, channel: 'CSCOUTS|#scout-findings' },
+ },
+ }
+ const finalConfig: SignalScoutConfigApi = {
+ ...BASE_CONFIG,
+ enabled: false,
+ ...queuedUpdates,
+ }
+ mockSignalsScoutConfigUpdate.mockReturnValueOnce(firstRequest.promise).mockResolvedValueOnce(finalConfig)
+
+ logic.actions.updateScoutConfig(BASE_CONFIG.id, { enabled: false })
+ logic.actions.updateScoutConfig(BASE_CONFIG.id, { run_interval_minutes: 60 })
+ logic.actions.updateScoutConfig(BASE_CONFIG.id, { output_destinations: queuedUpdates.output_destinations })
+
+ expect(mockSignalsScoutConfigUpdate).toHaveBeenCalledTimes(1)
+ expect(logic.values.scoutConfigs?.[0]).toMatchObject({ enabled: false, ...queuedUpdates })
+
+ firstRequest.resolve({ ...BASE_CONFIG, enabled: false })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockSignalsScoutConfigUpdate).toHaveBeenNthCalledWith(1, String(MOCK_TEAM_ID), BASE_CONFIG.id, {
+ enabled: false,
+ })
+ expect(mockSignalsScoutConfigUpdate).toHaveBeenNthCalledWith(
+ 2,
+ String(MOCK_TEAM_ID),
+ BASE_CONFIG.id,
+ queuedUpdates
+ )
+ expect(logic.values.scoutConfigs?.[0]).toEqual(finalConfig)
+ expect(logic.values.updatingScoutIds).toEqual([])
+ })
+
+ it('keeps configs unresolved until the current team is available', async () => {
+ logic.unmount()
+ teamLogic.actions.loadCurrentTeamSuccess(null)
+ mockSignalsScoutConfigList.mockClear()
+ logic = scoutFleetLogic()
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockSignalsScoutConfigList).not.toHaveBeenCalled()
+ expect(logic.values.scoutConfigs).toBeNull()
+ })
+
+ it('sends newer queued updates after an earlier request fails', async () => {
+ const firstRequest = deferred<SignalScoutConfigApi>()
+ const failingRequest = deferred<SignalScoutConfigApi>()
+ const outputDestinations = {
+ slack: { integration_id: 42, channel: 'CSCOUTS|#scout-findings' },
+ }
+ const finalConfig: SignalScoutConfigApi = {
+ ...BASE_CONFIG,
+ enabled: false,
+ output_destinations: outputDestinations,
+ }
+ mockSignalsScoutConfigUpdate
+ .mockReturnValueOnce(firstRequest.promise)
+ .mockReturnValueOnce(failingRequest.promise)
+ .mockResolvedValueOnce(finalConfig)
+
+ logic.actions.updateScoutConfig(BASE_CONFIG.id, { enabled: false })
+ logic.actions.updateScoutConfig(BASE_CONFIG.id, { run_interval_minutes: 60 })
+
+ firstRequest.resolve({ ...BASE_CONFIG, enabled: false })
+ await expectLogic(logic).toDispatchActions(['patchScoutConfigLocally'])
+ expect(mockSignalsScoutConfigUpdate).toHaveBeenCalledTimes(2)
+
+ logic.actions.updateScoutConfig(BASE_CONFIG.id, { output_destinations: outputDestinations })
+ failingRequest.reject(new Error('request failed'))
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockSignalsScoutConfigUpdate).toHaveBeenNthCalledWith(2, String(MOCK_TEAM_ID), BASE_CONFIG.id, {
+ run_interval_minutes: 60,
+ })
+ expect(mockSignalsScoutConfigUpdate).toHaveBeenNthCalledWith(3, String(MOCK_TEAM_ID), BASE_CONFIG.id, {
+ output_destinations: outputDestinations,
+ })
+ expect(logic.values.scoutConfigs?.[0]).toEqual(finalConfig)
+ expect(logic.values.updatingScoutIds).toEqual([])
+ })
+})
diff --git a/frontend/src/scenes/inbox/logics/scoutFleetLogic.ts b/frontend/src/scenes/inbox/logics/scoutFleetLogic.ts
index fd3dc2d9fe96..02b9e92c6eed 100644
--- a/frontend/src/scenes/inbox/logics/scoutFleetLogic.ts
+++ b/frontend/src/scenes/inbox/logics/scoutFleetLogic.ts
@@ -16,6 +16,7 @@ import {
signalsScoutConfigUpdate,
signalsScoutMetadataGet,
signalsScoutRunsFindingsSummary,
+ signalsScoutRunsList,
} from 'products/signals/frontend/generated/api'
import type {
FleetFindingsSummaryApi,
@@ -141,10 +142,10 @@ export interface scoutFleetLogicActions {
errorObject?: any
}
loadScoutConfigsSuccess: (
- scoutConfigs: SignalScoutConfigApi[],
+ scoutConfigs: SignalScoutConfigApi[] | null,
payload?: any
) => {
- scoutConfigs: SignalScoutConfigApi[]
+ scoutConfigs: SignalScoutConfigApi[] | null
payload?: any
}
loadScoutMetadata: () => any
@@ -281,7 +282,7 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
{
loadScoutConfigs: async () => {
const teamId = teamLogic.values.currentTeamId
- return teamId ? await signalsScoutConfigList(String(teamId)) : []
+ return teamId ? await signalsScoutConfigList(String(teamId)) : null
},
},
],
@@ -326,6 +327,10 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
},
{
loadRunsWindow: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return values.runsWindow
+ }
// Walk the full window newest→oldest, paginating via a `date_to` cursor so
// every scout shows its real run history (not just the fleet-wide newest 100).
const windowStart = dayjs().subtract(SCOUT_RUNS_WINDOW_HOURS, 'hours').toISOString()
@@ -335,7 +340,7 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
let complete = false
for (let page = 0; page < MAX_RUNS_PAGES; page++) {
- const pageRuns = await api.signalScout.runs.list({
+ const pageRuns = await signalsScoutRunsList(String(teamId), {
limit: RUNS_PAGE_LIMIT,
date_from: windowStart,
date_to: cursor,
@@ -528,38 +533,61 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
listeners(({ actions, values, cache }) => ({
updateScoutConfig: async ({ configId, updates }) => {
const inFlight: Set<string> = (cache.updatingScoutIds ??= new Set())
+ const pendingUpdates: Map<string, SignalScoutConfigUpdate> = (cache.pendingScoutConfigUpdates ??= new Map())
+
if (inFlight.has(configId)) {
- // The controls disable while a save is in flight, so this only catches the
- // sub-render race (e.g. blur-save then an immediate click). Say so instead of
- // silently dropping the change.
- lemonToast.info('Still saving the previous change. Try again in a moment.')
+ actions.patchScoutConfigLocally(configId, updates)
+ pendingUpdates.set(configId, { ...pendingUpdates.get(configId), ...updates })
return
}
+
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ actions.updateScoutConfigFinished(configId)
+ return
+ }
+
+ let confirmedConfig = values.scoutConfigs?.find((config) => config.id === configId)
+ let updatesToSend: SignalScoutConfigUpdate | undefined = updates
+ let queuedUpdatesAfterFailure: SignalScoutConfigUpdate | undefined
inFlight.add(configId)
- const previousConfig = values.scoutConfigs?.find((config) => config.id === configId)
- // Optimistic update so the toggle/select feels instant.
actions.patchScoutConfigLocally(configId, updates)
+
try {
- const teamId = teamLogic.values.currentTeamId
- if (!teamId) {
- throw new Error('Could not resolve the active project')
- }
- const updated = await signalsScoutConfigUpdate(String(teamId), configId, updates)
- // Reconcile this one row against the server (preserves concurrent edits to others).
- actions.patchScoutConfigLocally(configId, updated)
- if (updates.run_cron_schedule === null && previousConfig?.run_cron_schedule) {
- // Clearing the schedule is a valid save, not an error — but it can also come
- // from a half-typed time input blurring empty, so never let it pass silently.
- lemonToast.info('Scheduled run time cleared. The scout is back on its rolling interval.')
+ while (updatesToSend) {
+ const previousCronSchedule = confirmedConfig?.run_cron_schedule
+ const updated = await signalsScoutConfigUpdate(String(teamId), configId, updatesToSend)
+ confirmedConfig = updated
+
+ if (updatesToSend.run_cron_schedule === null && previousCronSchedule) {
+ lemonToast.info('Scheduled run time cleared. The scout is back on its rolling interval.')
+ }
+
+ const queuedUpdates = pendingUpdates.get(configId)
+ if (!queuedUpdates) {
+ actions.patchScoutConfigLocally(configId, updated)
+ updatesToSend = undefined
+ continue
+ }
+
+ pendingUpdates.delete(configId)
+ // Keep queued optimistic changes visible while their follow-up request runs.
+ actions.patchScoutConfigLocally(configId, { ...updated, ...queuedUpdates })
+ updatesToSend = queuedUpdates
}
} catch (error: any) {
- if (previousConfig) {
- actions.patchScoutConfigLocally(configId, previousConfig)
+ queuedUpdatesAfterFailure = pendingUpdates.get(configId)
+ if (confirmedConfig) {
+ actions.patchScoutConfigLocally(configId, confirmedConfig)
}
lemonToast.error(error?.detail || error?.message || 'Failed to update scout config')
} finally {
inFlight.delete(configId)
+ pendingUpdates.delete(configId)
actions.updateScoutConfigFinished(configId)
+ if (queuedUpdatesAfterFailure) {
+ actions.updateScoutConfig(configId, queuedUpdatesAfterFailure)
+ }
}
},
deleteScout: async ({ configId }) => {
diff --git a/frontend/src/scenes/inbox/types.ts b/frontend/src/scenes/inbox/types.ts
index 22f37fc452a4..362c8c39a81c 100644
--- a/frontend/src/scenes/inbox/types.ts
+++ b/frontend/src/scenes/inbox/types.ts
@@ -2,6 +2,7 @@ import type { UserBasicType } from '~/types'
import {
type SignalReportRefundApi,
+ type SignalScoutRunSummaryApi,
SignalSourceProductApi as SignalSourceProduct,
SignalSourceTypeApi as SignalSourceType,
} from 'products/signals/frontend/generated/api.schemas'
@@ -291,32 +292,12 @@ export interface SignalRun {
// ── Scouts (backend SignalScoutConfigViewSet / SignalScoutRunViewSet) ─────────
/** Status from the linked TaskRun behind a scout run. */
-export type SignalScoutRunStatus = 'not_started' | 'queued' | 'in_progress' | 'completed' | 'failed' | 'cancelled'
+export type SignalScoutRunStatus = SignalScoutRunSummaryApi['status']
-/** Lightweight projection of a scout run row (newest-first list response). */
-export interface SignalScoutRunSummary {
- run_id: string
- skill_name: string
- skill_version: number
- status: SignalScoutRunStatus
- /** Bridge-row creation timestamp — the field the runs endpoint filters/orders on (the pagination cursor). */
- created_at: string
- started_at: string
- completed_at: string | null
- task_id?: string | null
- task_run_id?: string | null
- /** Relative deep-link to cloud's Tasks UI, e.g. `/project/{id}/tasks/{task}?runId={run}`. */
- task_url?: string | null
- summary: string
- emitted_count: number
- emitted_finding_ids: string[]
- /** Reports this run authored directly via the `emit_report` channel. Distinct from `emitted_count`
- * (weak `emit_signal` findings): a report-authoring run writes a full report instead of a finding. */
- emitted_report_ids: string[]
- /** Reports this run mutated via the `edit_report` channel (retitled/resummarized and/or appended a
- * note), deduped. Can target any inbox report, so these are generally not reports the run authored. */
- edited_report_ids: string[]
-}
+/** Lightweight projection of a scout run row (newest-first list response).
+ * An interface extension (not a type alias) so kea-typegen keeps the domain name
+ * instead of inlining `import(...)` references to the generated type. */
+export interface SignalScoutRunSummary extends SignalScoutRunSummaryApi {}
/** One finding a scout run emitted to the inbox. */
export interface SignalScoutEmission {
diff --git a/frontend/src/scenes/inbox/utils/scoutRunsWindow.test.ts b/frontend/src/scenes/inbox/utils/scoutRunsWindow.test.ts
index 5d6b7bd1b3cd..3803a7de117c 100644
--- a/frontend/src/scenes/inbox/utils/scoutRunsWindow.test.ts
+++ b/frontend/src/scenes/inbox/utils/scoutRunsWindow.test.ts
@@ -20,6 +20,7 @@ function makeRun(overrides: Partial<SignalScoutRunSummary> = {}): SignalScoutRun
skill_name: 'signals-scout-dev-report-probe',
skill_version: 1,
status: 'completed',
+ metadata: {},
created_at: '2026-06-27T21:00:00Z',
started_at: '2026-06-27T21:00:00Z',
completed_at: '2026-06-27T21:02:00Z',
diff --git a/products/signals/backend/migrations/0070_signalscoutconfig_output_destinations.py b/products/signals/backend/migrations/0070_signalscoutconfig_output_destinations.py
new file mode 100644
index 000000000000..8046f70f9433
--- /dev/null
+++ b/products/signals/backend/migrations/0070_signalscoutconfig_output_destinations.py
@@ -0,0 +1,15 @@
+# Generated by Django 5.2.14 on 2026-07-22 15:11
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("signals", "0069_signalrepositoryareaactivity")]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalscoutconfig",
+ name="output_destinations",
+ field=models.JSONField(db_default={}, default=dict),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index d9cd85d88ecb..649baca994bb 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0069_signalrepositoryareaactivity
+0070_signalscoutconfig_output_destinations
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index f7a7e6c2e182..002b1d49d851 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1122,6 +1122,11 @@ class SignalScoutConfig(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
db_default=1440,
validators=[MinValueValidator(30), MaxValueValidator(43200)],
)
+ # Optional destinations for each finding or report this scout emits. Kept as a typed JSON object at
+ # the API boundary so adding another destination does not require another pair of nullable
+ # config columns. A Slack destination is active only when both its integration and channel
+ # are present; the UI may persist the integration first while the user chooses a channel.
+ output_destinations = models.JSONField(default=dict, db_default={})
# Optional five-field cron expression anchoring runs to wall-clock slots (e.g. "30 9 * * *",
# "0 9,17 * * *", "0 9 * * 1-5"). Takes precedence over the rolling `run_interval_minutes`
# when set. The coordinator evaluates it in `team.timezone`, so scheduled times follow
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 890f5fb071f1..dbfd5b1d0d9b 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -90,6 +90,11 @@ it is exercised via the `run_signals_scout` management command (see `../manageme
`SignalScoutConfig` for any `signals-scout-*` skill lacking one ("author a skill, get a
scout"). Called by the coordinator tick; the HTTP surface registers explicitly via the
write-scoped config `create` endpoint instead (reads stay side-effect free).
+- `slack_delivery.py` / `slack_delivery_queue.py`
+ Best-effort direct Slack delivery for configured scout outputs. Finding emissions and surfaced
+ report emits/edits snapshot the run config's destination after their database write commits, then
+ enqueue the shared retrying Celery worker. Integrations are project-scoped, so a workspace connected
+ from any environment in the project can receive the canonical parent team's scout output.
- `tools/`
Implementations of the four harness-internal tools the agent calls during a run.
The effective toolset for a run is the intersection of the skill's `allowed_tools`
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index ee85e717296f..a8c511f17c6d 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -16,6 +16,10 @@ from croniter import croniter
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
+from rest_framework.exceptions import PermissionDenied
+
+from posthog.models.integration import Integration
+from posthog.permissions import get_authenticator_scopes
from products.signals.backend.artefact_schemas import ActionabilityChoice, Priority
from products.signals.backend.models import SignalScoutConfig, SignalScoutEmission
@@ -43,8 +47,11 @@ class SignalScoutRunSummarySerializer(serializers.Serializer):
help_text="Canonical skill name the run executed (e.g. `signals-scout-general`)."
)
skill_version = serializers.IntegerField(help_text="Skill version snapshotted at run start.")
- status = serializers.CharField(
- help_text="Status from the linked TaskRun: not_started | queued | in_progress | completed | failed | cancelled.",
+ status = serializers.ChoiceField(
+ # Value-only literals so drf-spectacular reuses the existing `RunStatusEnum` override
+ # (label-bearing TaskRun.Status choices would resolve to `TaskRunStatusEnum` instead).
+ choices=["not_started", "queued", "in_progress", "completed", "failed", "cancelled"],
+ help_text="Status from the linked TaskRun.",
)
created_at = serializers.CharField(
help_text=(
@@ -1499,8 +1506,71 @@ class ProjectProfileSerializer(serializers.Serializer):
# --- Scout config ----------------------------------------------------------
+class SignalScoutSlackDestinationSerializer(serializers.Serializer):
+ integration_id = serializers.IntegerField(
+ min_value=1,
+ help_text="ID of the Slack integration whose bot posts this scout's findings and reports.",
+ )
+ channel = serializers.CharField(
+ required=False,
+ allow_null=True,
+ allow_blank=False,
+ max_length=255,
+ trim_whitespace=True,
+ help_text=(
+ "Slack channel target in the channel picker's `channel_id|#channel-name` format. "
+ "Null while choosing a channel; no messages are sent until it is set."
+ ),
+ )
+
+
+class SignalScoutOutputDestinationsSerializer(serializers.Serializer):
+ slack = SignalScoutSlackDestinationSerializer(
+ required=False,
+ allow_null=True,
+ help_text="Slack destination for each emitted scout finding or report. Null or omitted disables Slack delivery.",
+ )
+
+
+def _validate_output_destinations(value: dict, context: dict) -> dict:
+ slack = value.get("slack")
+ if slack is None:
+ return {}
+
+ project_id = context.get("project_id")
+ if not isinstance(project_id, int):
+ raise RuntimeError("Scout config output destination validation requires project_id in its context")
+
+ integration_id = slack["integration_id"]
+ integration = Integration.objects.filter(
+ id=integration_id,
+ team__project_id=project_id,
+ kind=Integration.IntegrationKind.SLACK,
+ ).first()
+ if integration is None:
+ raise serializers.ValidationError(
+ {"slack": {"integration_id": "No Slack integration with this ID exists on this project."}}
+ )
+
+ request = context.get("request")
+ if request is None:
+ raise RuntimeError("Scout config output destination validation requires request in its context")
+
+ key_scopes = get_authenticator_scopes(getattr(request, "successful_authenticator", None))
+ if key_scopes is not None and "*" not in key_scopes:
+ if not any(scope in key_scopes for scope in ("integration:read", "integration:write")):
+ raise PermissionDenied("API key missing required scope 'integration:read'")
+ # Delivery pushes report titles/summaries to the channel — content the report API gates
+ # behind `task` scope — so a scoped key without it must not be able to route that content
+ # out via a destination.
+ if not any(scope in key_scopes for scope in ("task:read", "task:write")):
+ raise PermissionDenied("API key missing required scope 'task:read'")
+
+ return {"slack": slack}
+
+
class SignalScoutConfigSerializer(serializers.ModelSerializer):
- """Per-(team, skill) scout config: schedule, enablement, and emit posture.
+ """Read shape for a per-(team, skill) scout config.
One row per `signals-scout-*` skill on the team. The coordinator auto-creates a row
when it discovers a scout skill; this serializer lets agents tune the row.
@@ -1548,6 +1618,10 @@ class SignalScoutConfigSerializer(serializers.ModelSerializer):
"Takes precedence over `run_interval_minutes` when set. Null means the rolling interval schedule."
),
)
+ output_destinations = SignalScoutOutputDestinationsSerializer(
+ read_only=True,
+ help_text="Destinations that receive each finding or report this scout emits. Empty when none is configured.",
+ )
last_run_at = serializers.DateTimeField(
read_only=True,
allow_null=True,
@@ -1579,6 +1653,7 @@ class SignalScoutConfigSerializer(serializers.ModelSerializer):
"emit",
"run_interval_minutes",
"run_cron_schedule",
+ "output_destinations",
"last_run_at",
"created_at",
]
@@ -1638,10 +1713,17 @@ class SignalScoutConfigUpdateSerializer(serializers.ModelSerializer):
"apart. Set null to return to the rolling interval schedule."
),
)
+ output_destinations = SignalScoutOutputDestinationsSerializer(
+ required=False,
+ help_text="Destinations that receive each finding or report this scout emits. Pass an empty object to disable delivery.",
+ )
def validate_run_cron_schedule(self, value: str | None) -> str | None:
return _validate_run_cron_schedule(value) if value is not None else None
+ def validate_output_destinations(self, value: dict) -> dict:
+ return _validate_output_destinations(value, self.context)
+
def update(self, instance: SignalScoutConfig, validated_data: dict) -> SignalScoutConfig:
# Re-anchor the coordinator's cron due-check only when the schedule actually changes —
# an emit/enabled-only save must not defer an already-overdue scheduled run.
@@ -1654,7 +1736,7 @@ class SignalScoutConfigUpdateSerializer(serializers.ModelSerializer):
class Meta:
model = SignalScoutConfig
- fields = ["enabled", "emit", "run_interval_minutes", "run_cron_schedule"]
+ fields = ["enabled", "emit", "run_interval_minutes", "run_cron_schedule", "output_destinations"]
class SignalScoutConfigCreateSerializer(serializers.Serializer):
@@ -1688,6 +1770,10 @@ class SignalScoutConfigCreateSerializer(serializers.Serializer):
max_value=43200,
help_text="Minutes between runs (30–43200). Defaults to 1440 (every 24 hours).",
)
+ output_destinations = SignalScoutOutputDestinationsSerializer(
+ required=False,
+ help_text="Destinations that receive each finding or report this scout emits. Empty by default.",
+ )
run_cron_schedule = serializers.CharField(
required=False,
allow_null=True,
@@ -1709,6 +1795,9 @@ class SignalScoutConfigCreateSerializer(serializers.Serializer):
raise serializers.ValidationError(f"Scout skill names must start with '{SIGNALS_SCOUT_SKILL_PREFIX}'.")
return value
+ def validate_output_destinations(self, value: dict) -> dict:
+ return _validate_output_destinations(value, self.context)
+
class SignalScoutManualRunSerializer(serializers.Serializer):
"""Response for an on-demand (`run now`) scout dispatch.
diff --git a/products/signals/backend/scout_harness/slack_delivery.py b/products/signals/backend/scout_harness/slack_delivery.py
new file mode 100644
index 000000000000..1a3c888b1622
--- /dev/null
+++ b/products/signals/backend/scout_harness/slack_delivery.py
@@ -0,0 +1,249 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Literal
+from urllib.parse import quote
+
+from django.conf import settings
+
+from slack_sdk.errors import SlackApiError
+
+from posthog.models.integration import Integration, SlackIntegration
+
+from products.signals.backend.models import SignalReport, SignalScoutEmission, SignalScoutRun
+from products.signals.backend.slack_formatting import (
+ escape_slack_mrkdwn,
+ markdown_to_slack_mrkdwn,
+ slack_channel_id_from_target,
+ truncate_slack_section,
+)
+
+_PERMANENT_SLACK_ERROR_CODES = frozenset(
+ {
+ "account_inactive",
+ "channel_not_found",
+ "ekm_access_denied",
+ "invalid_auth",
+ "is_archived",
+ "missing_scope",
+ "not_authed",
+ "not_in_channel",
+ "org_login_required",
+ "restricted_action",
+ "token_revoked",
+ }
+)
+
+ScoutSlackOutputType = Literal["finding", "report"]
+
+
+@dataclass(frozen=True)
+class ScoutSlackDestination:
+ integration_id: int
+ channel: str
+
+
+class ScoutSlackPermanentDeliveryError(RuntimeError):
+ def __init__(self, message: str, *, error_code: str) -> None:
+ super().__init__(message)
+ self.error_code = error_code
+
+
+def get_scout_slack_destination(output_destinations: object) -> ScoutSlackDestination | None:
+ """Return an active Slack destination from persisted config, tolerating malformed legacy data."""
+ if not isinstance(output_destinations, dict):
+ return None
+ slack = output_destinations.get("slack")
+ if not isinstance(slack, dict):
+ return None
+ integration_id = slack.get("integration_id")
+ channel = slack.get("channel")
+ if not isinstance(integration_id, int) or isinstance(integration_id, bool) or integration_id < 1:
+ return None
+ if not isinstance(channel, str) or not channel.strip():
+ return None
+ return ScoutSlackDestination(integration_id=integration_id, channel=channel.strip())
+
+
+def slack_api_error_code(exc: SlackApiError) -> str | None:
+ error_code = exc.response.get("error") if exc.response else None
+ return error_code if isinstance(error_code, str) else None
+
+
+def _prettify_scout_name(skill_name: str) -> str:
+ cleaned = skill_name.removeprefix("signals-scout-").replace("-", " ").replace("_", " ").strip()
+ return cleaned[:1].upper() + cleaned[1:] if cleaned else "Scout"
+
+
+def _slack_integration_for_project(*, integration_id: int, project_id: int) -> Integration:
+ integration = Integration.objects.filter(
+ id=integration_id,
+ team__project_id=project_id,
+ kind=Integration.IntegrationKind.SLACK,
+ ).first()
+ if integration is None:
+ raise ScoutSlackPermanentDeliveryError(
+ "The configured Slack integration no longer exists on this project",
+ error_code="integration_not_found",
+ )
+ return integration
+
+
+def _slack_channel_id(channel: str) -> str:
+ channel_id = slack_channel_id_from_target(channel)
+ if not channel_id:
+ raise ScoutSlackPermanentDeliveryError(
+ "The configured Slack channel is empty",
+ error_code="channel_missing",
+ )
+ return channel_id
+
+
+def build_scout_slack_message(emission: SignalScoutEmission) -> tuple[list[dict], str]:
+ """Render a direct scout finding with the same safe Markdown conversion as inbox signals."""
+ scout_name = _prettify_scout_name(emission.scout_run.skill_name)
+ blocks: list[dict] = [
+ {
+ "type": "context",
+ "elements": [{"type": "mrkdwn", "text": f"*Scout · {escape_slack_mrkdwn(scout_name)}*"}],
+ }
+ ]
+
+ rendered_description = truncate_slack_section(markdown_to_slack_mrkdwn(emission.description.strip()))
+ if rendered_description:
+ blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": rendered_description}})
+
+ details: list[str] = []
+ if emission.severity:
+ details.append(escape_slack_mrkdwn(emission.severity))
+ details.append(f"{round(emission.confidence * 100)}% confidence")
+ if emission.tags:
+ safe_tags = [escape_slack_mrkdwn(str(tag)).replace("`", "'") for tag in emission.tags[:5]]
+ details.append(" ".join(f"`{tag}`" for tag in safe_tags))
+ blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": " · ".join(details)}]})
+
+ skill_segment = quote(emission.scout_run.skill_name, safe="")
+ finding_segment = quote(emission.finding_id, safe="")
+ finding_url = (
+ f"{settings.SITE_URL.rstrip('/')}/project/{emission.team_id}/inbox/scouts/{skill_segment}/{finding_segment}"
+ )
+ blocks.append(
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": "View finding in PostHog"},
+ "url": finding_url,
+ }
+ ],
+ }
+ )
+
+ first_line = emission.description.strip().splitlines()[0] if emission.description.strip() else "New finding"
+ fallback = f"Scout · {escape_slack_mrkdwn(scout_name)}: {escape_slack_mrkdwn(first_line[:200])}"
+ return blocks, fallback
+
+
+def post_scout_emission_to_slack(
+ emission: SignalScoutEmission,
+ *,
+ integration_id: int,
+ channel: str,
+) -> None:
+ integration = _slack_integration_for_project(
+ integration_id=integration_id,
+ project_id=emission.team.project_id,
+ )
+ channel_id = _slack_channel_id(channel)
+
+ blocks, fallback = build_scout_slack_message(emission)
+ try:
+ SlackIntegration(integration).client.chat_postMessage(
+ channel=channel_id,
+ blocks=blocks,
+ text=fallback,
+ client_msg_id=str(emission.id),
+ unfurl_links=False,
+ unfurl_media=False,
+ )
+ except SlackApiError as exc:
+ error_code = slack_api_error_code(exc)
+ if error_code in _PERMANENT_SLACK_ERROR_CODES:
+ raise ScoutSlackPermanentDeliveryError(
+ f"Slack rejected the scout finding with {error_code}",
+ error_code=error_code,
+ ) from exc
+ raise
+
+
+def build_scout_report_slack_message(report: SignalReport, run: SignalScoutRun) -> tuple[list[dict], str]:
+ scout_name = _prettify_scout_name(run.skill_name)
+ title = " ".join((report.title or "").split()) or "New scout report"
+ header = title if len(title) <= 150 else title[:147].rstrip() + "..."
+ blocks: list[dict] = [
+ {
+ "type": "context",
+ "elements": [{"type": "mrkdwn", "text": f"*Scout · {escape_slack_mrkdwn(scout_name)}*"}],
+ },
+ {"type": "header", "text": {"type": "plain_text", "text": header}},
+ ]
+
+ rendered_summary = truncate_slack_section(markdown_to_slack_mrkdwn((report.summary or "").strip()))
+ if rendered_summary:
+ blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": rendered_summary}})
+
+ report_url = f"{settings.SITE_URL.rstrip('/')}/project/{report.team_id}/inbox/reports/{report.id}"
+ blocks.append(
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": "View report in PostHog"},
+ "url": report_url,
+ }
+ ],
+ }
+ )
+ fallback = f"Scout · {escape_slack_mrkdwn(scout_name)}: {escape_slack_mrkdwn(title[:200])}"
+ return blocks, fallback
+
+
+def post_scout_report_to_slack(
+ report: SignalReport,
+ run: SignalScoutRun,
+ *,
+ delivery_id: str,
+ integration_id: int,
+ channel: str,
+) -> None:
+ if report.team_id != run.team_id:
+ raise ScoutSlackPermanentDeliveryError(
+ "The scout run does not own the configured report",
+ error_code="output_team_mismatch",
+ )
+
+ integration = _slack_integration_for_project(
+ integration_id=integration_id,
+ project_id=report.team.project_id,
+ )
+ channel_id = _slack_channel_id(channel)
+ blocks, fallback = build_scout_report_slack_message(report, run)
+ try:
+ SlackIntegration(integration).client.chat_postMessage(
+ channel=channel_id,
+ blocks=blocks,
+ text=fallback,
+ client_msg_id=delivery_id,
+ unfurl_links=False,
+ unfurl_media=False,
+ )
+ except SlackApiError as exc:
+ error_code = slack_api_error_code(exc)
+ if error_code in _PERMANENT_SLACK_ERROR_CODES:
+ raise ScoutSlackPermanentDeliveryError(
+ f"Slack rejected the scout report with {error_code}",
+ error_code=error_code,
+ ) from exc
+ raise
diff --git a/products/signals/backend/scout_harness/slack_delivery_queue.py b/products/signals/backend/scout_harness/slack_delivery_queue.py
new file mode 100644
index 000000000000..b7cc58b53d63
--- /dev/null
+++ b/products/signals/backend/scout_harness/slack_delivery_queue.py
@@ -0,0 +1,63 @@
+from __future__ import annotations
+
+import uuid
+import logging
+from functools import partial
+
+from django.db import transaction
+
+from posthog.exceptions_capture import capture_exception
+
+from products.signals.backend.models import SignalScoutRun
+from products.signals.backend.scout_harness.slack_delivery import ScoutSlackOutputType, get_scout_slack_destination
+from products.signals.backend.tasks import enqueue_scout_slack_delivery
+
+logger = logging.getLogger(__name__)
+
+
+def queue_configured_scout_slack_delivery(
+ *,
+ run_id: uuid.UUID | str,
+ output_type: ScoutSlackOutputType,
+ output_id: str,
+ delivery_id: str | None = None,
+) -> None:
+ """Snapshot a run's configured destination and enqueue delivery after the current commit."""
+ try:
+ run = SignalScoutRun.all_teams.select_related("scout_config").filter(pk=run_id).first()
+ if run is None:
+ logger.warning("signals_scout.slack_delivery_run_missing", extra={"run_id": str(run_id)})
+ return
+
+ destination = get_scout_slack_destination(
+ run.scout_config.output_destinations if run.scout_config is not None else None
+ )
+ if destination is None:
+ return
+
+ transaction.on_commit(
+ partial(
+ enqueue_scout_slack_delivery,
+ team_id=run.team_id,
+ output_type=output_type,
+ output_id=output_id,
+ run_id=str(run.id),
+ delivery_id=delivery_id or str(uuid.uuid4()),
+ integration_id=destination.integration_id,
+ channel=destination.channel,
+ ),
+ robust=True,
+ )
+ except Exception as exc:
+ capture_exception(
+ exc,
+ {
+ "run_id": str(run_id),
+ "output_type": output_type,
+ "output_id": output_id,
+ },
+ )
+ logger.exception(
+ "signals_scout.slack_delivery_queue_failed",
+ extra={"run_id": str(run_id), "output_type": output_type, "output_id": output_id},
+ )
diff --git a/products/signals/backend/scout_harness/tools/emit.py b/products/signals/backend/scout_harness/tools/emit.py
index 66fd264c5d99..0dcadbf5cf84 100644
--- a/products/signals/backend/scout_harness/tools/emit.py
+++ b/products/signals/backend/scout_harness/tools/emit.py
@@ -37,6 +37,7 @@ from posthog.models import Team
from posthog.sync import database_sync_to_async
from products.signals.backend.models import SignalScoutConfig, SignalScoutEmission, SignalScoutRun, SignalSourceConfig
+from products.signals.backend.scout_harness.slack_delivery_queue import queue_configured_scout_slack_delivery
from products.tasks.backend.facade import api as tasks_facade
logger = logging.getLogger(__name__)
@@ -449,12 +450,13 @@ def _record_emit(
the read-modify-write on `emitted_finding_ids` is safe even though emits within a single
run are sequential today, and keeps `emitted_count` exactly `len(emitted_finding_ids)`
so the two never drift. The emission row is written in the same atomic block so the tally
- and the per-finding record never diverge — one row per appended `finding_id`. Uses the
- unscoped `all_teams` manager because the caller already validated `team`/`run` ownership
- and emit can run with no team scope set (Temporal activity)."""
+ and the per-finding record never diverge — one row per appended `finding_id`. A configured
+ Slack delivery is queued only after this transaction commits, with the destination snapshotted
+ at emit time. Uses the unscoped `all_teams` manager because the caller already validated
+ `team`/`run` ownership and emit can run with no team scope set (Temporal activity)."""
try:
with transaction.atomic():
- run = SignalScoutRun.all_teams.select_for_update().filter(pk=run_id).first()
+ run = SignalScoutRun.all_teams.select_for_update(of=("self",)).filter(pk=run_id).first()
if run is None:
logger.warning("signals_scout.emit: run %s gone, skipping emit tally", run_id)
return
@@ -462,7 +464,7 @@ def _record_emit(
run.emitted_finding_ids = finding_ids
run.emitted_count = len(finding_ids)
run.save(update_fields=["emitted_finding_ids", "emitted_count"])
- SignalScoutEmission.all_teams.create(
+ emission = SignalScoutEmission.all_teams.create(
team_id=run.team_id,
scout_run=run,
finding_id=finding_id,
@@ -473,6 +475,12 @@ def _record_emit(
source_id=source_id,
tags=tags or [],
)
+ queue_configured_scout_slack_delivery(
+ run_id=run.id,
+ output_type="finding",
+ output_id=str(emission.id),
+ delivery_id=str(emission.id),
+ )
except Exception:
# Tally and emission row are best-effort; the signal already emitted. Log and move on
# so the emit call returns success rather than a false failure the caller might retry.
diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.py
index db4d90bbde08..a378ed2b0a53 100644
--- a/products/signals/backend/scout_harness/tools/report.py
+++ b/products/signals/backend/scout_harness/tools/report.py
@@ -47,6 +47,7 @@ from products.signals.backend.models import ArtefactAttribution, SignalReport, S
from products.signals.backend.report_generation.resolve_reviewers import get_org_member_github_logins_by_user_uuid
from products.signals.backend.report_generation.select_repo import RepoSelectionResult
from products.signals.backend.scout_harness.prompt import SELF_IMPROVEMENT_REPORT_TITLE_PREFIX
+from products.signals.backend.scout_harness.slack_delivery_queue import queue_configured_scout_slack_delivery
from products.signals.backend.scout_harness.tools.emit import (
SCOUT_SIGNAL_WEIGHT,
# Shared harness gates/attribution — the report channel applies the same preflight as emit.
@@ -61,6 +62,7 @@ from products.signals.backend.scout_report import (
ScoutReportSignal,
append_report_note,
create_scout_report,
+ get_scout_report_status,
get_scout_report_title,
record_report_edit,
record_scout_run_task_artefact,
@@ -765,6 +767,14 @@ async def emit_report(
run=run,
)
if surfaced:
+ await database_sync_to_async(queue_configured_scout_slack_delivery, thread_sensitive=False)(
+ run_id=run.id,
+ output_type="report",
+ output_id=persisted.report_id,
+ # A report is emitted once, so its id is the natural idempotency key (mirrors
+ # findings using the emission id); edits keep per-delivery ids since each notifies.
+ delivery_id=persisted.report_id,
+ )
await _maybe_autostart_report(team_id=team.id, report_id=persisted.report_id)
result = _emit_result(persisted.report_id, judgement)
forward = await database_sync_to_async(_capture_report_emitted, thread_sensitive=False)(
@@ -865,6 +875,12 @@ def emit_report_sync(
run=run,
)
if surfaced:
+ queue_configured_scout_slack_delivery(
+ run_id=run.id,
+ output_type="report",
+ output_id=persisted.report_id,
+ delivery_id=persisted.report_id,
+ )
async_to_sync(_maybe_autostart_report)(team_id=team.id, report_id=persisted.report_id)
result = _emit_result(persisted.report_id, judgement)
forward = _capture_report_emitted(
@@ -982,6 +998,17 @@ def _do_edit_report(
# Also link the run itself on the report's work log (deduped), so the editing scout's
# transcript is reachable from the report — not just the run-side `edited_report_ids` tally.
record_scout_run_task_artefact(team_id=team.id, report_id=report_id, run=run, task_id=attribution.task_id)
+ # Mirror emit's surfaced gate: an edit to a suppressed / never-surfaced report must not push
+ # its content to a configured destination. The delivery worker re-checks status at send time
+ # (the report can be suppressed after enqueue), so this mainly keeps the two paths symmetric
+ # and skips queueing work that would no-op.
+ report_status = get_scout_report_status(team_id=team.id, report_id=report_id)
+ if report_status is not None and _surfaced(report_status):
+ queue_configured_scout_slack_delivery(
+ run_id=run.id,
+ output_type="report",
+ output_id=report_id,
+ )
return result
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 8c29bd648a9f..7288cc297a2c 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -1406,7 +1406,7 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
description=(
"Register the config for a `signals-scout-*` skill immediately, without waiting "
"for the coordinator to auto-register it. The same call can optionally set "
- "`run_interval_minutes`, a cron `run_cron_schedule`, `enabled`, and `emit`. "
+ "`run_interval_minutes`, a cron `run_cron_schedule`, `enabled`, `emit`, and output destinations. "
"The skill must already exist on this project. Upsert: if a config already exists "
"for the skill, the provided fields are applied to it."
),
@@ -1414,7 +1414,10 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
def create(self, request: Request, *args, **kwargs) -> Response:
team_id = _canonical_team_id(self)
- serializer = SignalScoutConfigCreateSerializer(data=request.data)
+ serializer = SignalScoutConfigCreateSerializer(
+ data=request.data,
+ context={**self.get_serializer_context(), "project_id": self.team.project_id},
+ )
serializer.is_valid(raise_exception=True)
skill_name = serializer.validated_data["skill_name"]
if not LLMSkill.objects.filter(team_id=team_id, name=skill_name, is_latest=True, deleted=False).exists():
@@ -1451,7 +1454,12 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
if not created and tunables:
# The coordinator tick (or a concurrent caller) won the race — apply the provided
# fields to the existing row so the call still lands the requested settings.
- update = SignalScoutConfigUpdateSerializer(config, data=tunables, partial=True)
+ update = SignalScoutConfigUpdateSerializer(
+ config,
+ data=tunables,
+ partial=True,
+ context={**self.get_serializer_context(), "project_id": self.team.project_id},
+ )
update.is_valid(raise_exception=True)
save_kwargs = {}
if not config.enabled and update.validated_data.get("enabled"):
@@ -1476,8 +1484,8 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
description=(
"Tune one scout: change its schedule (rolling `run_interval_minutes`, or a cron "
"`run_cron_schedule` that takes precedence when set), `enabled`, or `emit` (dry-run) "
- "posture. `skill_name` is fixed. Enabling records `enabled_by` and is activity-logged "
- "since it drives spend."
+ "posture, or output destinations. `skill_name` is fixed. Enabling records `enabled_by` "
+ "and is activity-logged since it drives spend."
),
operation_id="signals_scout_config_update",
)
@@ -1487,7 +1495,12 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
config = SignalScoutConfig.objects.unscoped().filter(team_id=team_id, id=config_id).first()
if config is None:
raise exceptions.NotFound()
- serializer = SignalScoutConfigUpdateSerializer(config, data=request.data, partial=True)
+ serializer = SignalScoutConfigUpdateSerializer(
+ config,
+ data=request.data,
+ partial=True,
+ context={**self.get_serializer_context(), "project_id": self.team.project_id},
+ )
serializer.is_valid(raise_exception=True)
enabling = not config.enabled and serializer.validated_data.get("enabled")
if enabling:
diff --git a/products/signals/backend/scout_report/__init__.py b/products/signals/backend/scout_report/__init__.py
index 67f07ca2ee81..8f24a4129fa0 100644
--- a/products/signals/backend/scout_report/__init__.py
+++ b/products/signals/backend/scout_report/__init__.py
@@ -13,6 +13,7 @@ from products.signals.backend.scout_report.persistence import (
ScoutReportSignal,
append_report_note,
create_scout_report,
+ get_scout_report_status,
get_scout_report_title,
record_report_edit,
record_scout_run_task_artefact,
@@ -28,6 +29,7 @@ __all__ = [
"ScoutReportSignal",
"append_report_note",
"create_scout_report",
+ "get_scout_report_status",
"get_scout_report_title",
"record_report_edit",
"record_scout_run_task_artefact",
diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.py
index f0d8546d2aa7..916d2ecf6a11 100644
--- a/products/signals/backend/scout_report/persistence.py
+++ b/products/signals/backend/scout_report/persistence.py
@@ -255,6 +255,14 @@ def get_scout_report_title(*, team_id: int, report_id: str) -> str | None:
return SignalReport.objects.filter(team_id=team_id, id=report_id).values_list("title", flat=True).first()
+def get_scout_report_status(*, team_id: int, report_id: str) -> SignalReport.Status | None:
+ """Team-scoped status lookup, for the edit path's Slack-delivery gate: only a surfaced report may
+ have its content pushed to a configured destination, matching emit. Returns None when the report
+ doesn't exist for the team."""
+ value = SignalReport.objects.filter(team_id=team_id, id=report_id).values_list("status", flat=True).first()
+ return SignalReport.Status(value) if value is not None else None
+
+
def update_scout_report(
*,
team_id: int,
diff --git a/products/signals/backend/slack_formatting.py b/products/signals/backend/slack_formatting.py
new file mode 100644
index 000000000000..2357e2b85e78
--- /dev/null
+++ b/products/signals/backend/slack_formatting.py
@@ -0,0 +1,54 @@
+from __future__ import annotations
+
+import re
+
+from markdown_to_mrkdwn import SlackMarkdownConverter
+
+_SLACK_MRKDWN_CONVERTER = SlackMarkdownConverter()
+SLACK_SECTION_TEXT_MAX_LEN = 2900
+
+# Matches a converter-emitted Slack angle token: `<dest>` or `<dest|label>`. Input `<`/`>`
+# are escaped before conversion, so any literal angle bracket here was produced by the converter.
+_SLACK_ANGLE_TOKEN_RE = re.compile(r"<([^<>|]*)(\|[^<>]*)?>")
+
+
+def escape_slack_mrkdwn(text: str) -> str:
+ """Neutralize Slack control syntax so untrusted text cannot inject mentions or links."""
+ return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+
+
+def is_safe_slack_http_url(value: object) -> bool:
+ """Allow only URL forms that cannot break out of a Slack `<url|label>` token."""
+ if not isinstance(value, str):
+ return False
+ if not (value.startswith("http://") or value.startswith("https://")):
+ return False
+ return not any(char in value for char in ("<", ">", "|"))
+
+
+def _defang_unsafe_slack_tokens(text: str) -> str:
+ """Render converter-created non-URL angle tokens as inert literal text."""
+
+ def _replace(match: re.Match[str]) -> str:
+ if is_safe_slack_http_url(match.group(1)):
+ return match.group(0)
+ return match.group(0).replace("<", "&lt;").replace(">", "&gt;")
+
+ return _SLACK_ANGLE_TOKEN_RE.sub(_replace, text)
+
+
+def markdown_to_slack_mrkdwn(text: str) -> str:
+ """Convert untrusted Markdown to Slack mrkdwn without allowing mention injection."""
+ return _defang_unsafe_slack_tokens(_SLACK_MRKDWN_CONVERTER.convert(escape_slack_mrkdwn(text)))
+
+
+def truncate_slack_section(text: str) -> str:
+ """Keep mrkdwn below Slack's 3000-character section limit with headroom."""
+ if len(text) <= SLACK_SECTION_TEXT_MAX_LEN:
+ return text
+ return text[: SLACK_SECTION_TEXT_MAX_LEN - 1].rstrip() + "…"
+
+
+def slack_channel_id_from_target(value: str) -> str:
+ """Extract the Slack channel ID from the frontend picker's `id|#name` value."""
+ return value.split("|", 1)[0].strip()
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
index c278417c0511..f4261d016224 100644
--- a/products/signals/backend/slack_inbox_notifications.py
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -13,14 +13,12 @@ All sends are best-effort.
from __future__ import annotations
-import re
import json
import logging
from collections.abc import Iterable
from django.conf import settings
-from markdown_to_mrkdwn import SlackMarkdownConverter
from slack_sdk.errors import SlackApiError
from posthog.models import User
@@ -40,6 +38,13 @@ from products.signals.backend.report_generation.resolve_reviewers import (
normalized_github_logins_from_suggested_reviewer_artefacts,
resolve_org_github_login_to_users,
)
+from products.signals.backend.slack_formatting import (
+ escape_slack_mrkdwn as _escape_mrkdwn,
+ is_safe_slack_http_url as _is_safe_http_url,
+ markdown_to_slack_mrkdwn as _markdown_to_slack_mrkdwn,
+ slack_channel_id_from_target as _channel_id_from_target,
+ truncate_slack_section as _truncate_slack_section,
+)
# Actionability values shown in the inbox Reports tab. Slack notifications mirror that tab, so a
# report notifies iff its latest actionability judgment is one of these (and it's READY).
@@ -49,8 +54,6 @@ _ACTIONABLE_VALUES = frozenset(
logger = logging.getLogger(__name__)
-_SLACK_MRKDWN_CONVERTER = SlackMarkdownConverter()
-
_SUMMARY_EXCERPT_MAX_LEN = 600
_SLACK_HEADER_MAX_LEN = 150
# Bound message size / avoid pinging a crowd.
@@ -231,11 +234,6 @@ def _team_notification_channel(team_id: int) -> str | None:
return channel or None
-def _channel_id_from_target(value: str) -> str:
- """Mirror `getSlackChannelIdFromTargetValue` in the frontend."""
- return value.split("|", 1)[0].strip()
-
-
def _channel_display_name(value: str) -> str:
pipe = value.find("|")
if pipe == -1:
@@ -280,44 +278,6 @@ def lookup_slack_user_id_by_email(slack: SlackIntegration, email: str) -> str |
return str(slack_user["id"])
-def _escape_mrkdwn(text: str) -> str:
- """Neutralize Slack control syntax (`&`, `<`, `>`) so untrusted text can't inject mentions/links."""
- return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
-
-
-# Matches a converter-emitted Slack angle token: `<dest>` or `<dest|label>`. Input `<`/`>`
-# are escaped before conversion, so any literal angle bracket here was produced by the converter.
-_SLACK_ANGLE_TOKEN_RE = re.compile(r"<([^<>|]*)(\|[^<>]*)?>")
-
-
-def _defang_unsafe_slack_tokens(text: str) -> str:
- """Render any non-URL `<dest|label>` token the converter emitted as inert literal text.
-
- `markdown_to_mrkdwn` turns `[text](dest)` into Slack's `<dest|label>` form without checking
- the scheme, so untrusted signal content could smuggle a broadcast or ping via `[x](!channel)`
- or `[x](@U123)`. Tokens whose destination isn't a plain http(s) URL get their angle brackets
- escaped so Slack shows the text instead of firing a mention.
- """
-
- def _replace(match: re.Match[str]) -> str:
- if _is_safe_http_url(match.group(1)):
- return match.group(0)
- return match.group(0).replace("<", "&lt;").replace(">", "&gt;")
-
- return _SLACK_ANGLE_TOKEN_RE.sub(_replace, text)
-
-
-def _markdown_to_slack_mrkdwn(text: str) -> str:
- """Convert signal markdown to Slack mrkdwn, then neutralize any injected mentions.
-
- Escaping runs first so raw `<@U…>`/`<!channel>` in untrusted content can't reach Slack;
- after conversion, `_defang_unsafe_slack_tokens` strips any mention/broadcast the converter
- synthesized from a `[text](!channel)`-style link. Kept local rather than shared with the
- other `SlackMarkdownConverter` call sites: they render trusted LLM output, signals does not.
- """
- return _defang_unsafe_slack_tokens(_SLACK_MRKDWN_CONVERTER.convert(_escape_mrkdwn(text)))
-
-
def _resolve_reviewer_mentions(slack: SlackIntegration, reviewer_users: list[User]) -> list[str]:
# `<@U…>` mention when the reviewer's email resolves in this workspace, else escaped name.
mentions: list[str] = []
@@ -416,9 +376,6 @@ def _build_message_blocks(
# Bound how many evidence signals we post into a thread so a large report can't flood a channel.
_MAX_THREAD_SIGNALS = 30
-# Slack section text caps at 3000 chars; leave headroom for the ellipsis.
-_SIGNAL_CONTENT_MAX_LEN = 2900
-
# Explicit "Product · Signal type" labels, mirroring `signalCardSourceLine` in the canonical Inbox UI
# (PostHog Code's apps/code/.../detail/SignalCard.tsx). Keep in sync with it.
_SIGNAL_SOURCE_LINES: dict[tuple[str, str], str] = {
@@ -460,15 +417,6 @@ def _signal_source_line(source_product: str, source_type: str, extra: dict | Non
return f"{product_label} · {type_label}" if type_label else product_label
-def _is_safe_http_url(value: object) -> bool:
- # mrkdwn link injection guard: only plain http(s) URLs without the chars that break `<url|text>`.
- if not isinstance(value, str):
- return False
- if not (value.startswith("http://") or value.startswith("https://")):
- return False
- return not any(char in value for char in ("<", ">", "|"))
-
-
def _signal_detail_parts(source_product: str, extra: dict) -> list[str]:
"""A compact, source-specific metadata line mirroring the inbox SignalCard footer."""
parts: list[str] = []
@@ -520,8 +468,7 @@ def _build_signal_thread_blocks(signal: dict) -> tuple[list[dict], str]:
# text past Slack's section limit. Truncating post-defang output stays safe — a
# trailing cut can't synthesize a live mention (no closing `>` can appear).
rendered = _markdown_to_slack_mrkdwn(content)
- if len(rendered) > _SIGNAL_CONTENT_MAX_LEN:
- rendered = rendered[: _SIGNAL_CONTENT_MAX_LEN - 1].rstrip() + "…"
+ rendered = _truncate_slack_section(rendered)
blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": rendered}})
detail_parts = _signal_detail_parts(source_product, extra)
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 35c241d35760..053827e99c26 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -6,6 +6,7 @@ from django.utils import timezone
import structlog
from celery import shared_task
+from slack_sdk.errors import SlackApiError
from posthog.cloud_utils import get_cached_instance_license
from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError
@@ -18,12 +19,25 @@ from posthog.scoping_audit import skip_team_scope_audit
from products.signals.backend.billing import current_billing_period_bounds
from products.signals.backend.implementation_pr import PrCloseReason, close_implementation_pr_for_report
-from products.signals.backend.models import SignalReportRefund, SignalRepositoryAreaActivity
+from products.signals.backend.models import (
+ SignalReport,
+ SignalReportRefund,
+ SignalRepositoryAreaActivity,
+ SignalScoutEmission,
+ SignalScoutRun,
+)
from products.signals.backend.report_generation.repo_activity import (
ACTIVITY_KEEP_WARM_WINDOW,
rebuild_repository_activity,
repository_activity_needs_rebuild,
)
+from products.signals.backend.scout_harness.slack_delivery import (
+ ScoutSlackOutputType,
+ ScoutSlackPermanentDeliveryError,
+ post_scout_emission_to_slack,
+ post_scout_report_to_slack,
+ slack_api_error_code,
+)
from products.signals.backend.slack_inbox_notifications import dispatch_reviewer_added_notifications
from products.tasks.backend.facade.repo_activity import RepositoryCommitActivityError
@@ -51,6 +65,11 @@ _REFUND_SYNC_SWEEP_MAX_AGE = timedelta(days=7)
# older), so the sweeper skips these rows and recovery is the documented manual credit path.
_OUT_OF_PERIOD_SYNC_ERROR = "billing: refund period no longer creditable at sync time; credit needs manual recovery"
+_SCOUT_SLACK_MAX_RETRIES = 5
+_SCOUT_SLACK_RETRY_BASE_SECONDS = 60
+_SCOUT_SLACK_RETRY_MAX_SECONDS = 3600
+_SCOUT_SLACK_DELIVERABLE_REPORT_STATUSES = frozenset((SignalReport.Status.READY, SignalReport.Status.PENDING_INPUT))
+
@shared_task(
name="products.signals.backend.tasks.close_dismissed_report_pr",
@@ -62,6 +81,168 @@ def close_dismissed_report_pr(report_id: str, team_id: int, reason: PrCloseReaso
close_implementation_pr_for_report(team_id, report_id, reason=reason)
+def _slack_retry_after_seconds(exc: Exception) -> int | None:
+ if not isinstance(exc, SlackApiError) or not exc.response:
+ return None
+ headers = exc.response.headers or {}
+ raw_value = headers.get("Retry-After") or headers.get("retry-after")
+ try:
+ retry_after = int(raw_value) if raw_value is not None else None
+ except (TypeError, ValueError):
+ return None
+ return retry_after if retry_after is not None and retry_after > 0 else None
+
+
+def _scout_slack_retry_countdown(exc: Exception, retries: int) -> int:
+ backoff = min(_SCOUT_SLACK_RETRY_BASE_SECONDS * (2**retries), _SCOUT_SLACK_RETRY_MAX_SECONDS)
+ retry_after = _slack_retry_after_seconds(exc)
+ return min(max(backoff, retry_after or 0), _SCOUT_SLACK_RETRY_MAX_SECONDS)
+
+
+@shared_task(
+ name="products.signals.backend.tasks.deliver_scout_slack_output",
+ ignore_result=True,
+ bind=True,
+ acks_late=True,
+ reject_on_worker_lost=True,
+ max_retries=_SCOUT_SLACK_MAX_RETRIES,
+)
+@with_team_scope(canonical=True)
+def deliver_scout_slack_output(
+ self,
+ team_id: int,
+ output_type: str,
+ output_id: str,
+ run_id: str,
+ delivery_id: str,
+ integration_id: int,
+ channel: str,
+) -> None:
+ context = {
+ "team_id": team_id,
+ "output_type": output_type,
+ "output_id": output_id,
+ "run_id": run_id,
+ "integration_id": integration_id,
+ }
+ try:
+ if output_type == "finding":
+ emission = (
+ SignalScoutEmission.objects.select_related("scout_run", "team")
+ .filter(id=output_id, team_id=team_id, scout_run_id=run_id)
+ .first()
+ )
+ if emission is None:
+ logger.warning("signals_scout.slack_delivery_output_missing", **context)
+ return
+ post_scout_emission_to_slack(
+ emission,
+ integration_id=integration_id,
+ channel=channel,
+ )
+ elif output_type == "report":
+ report = SignalReport.objects.select_related("team").filter(id=output_id, team_id=team_id).first()
+ run = SignalScoutRun.objects.select_related("team").filter(id=run_id, team_id=team_id).first()
+ if report is None or run is None:
+ logger.warning("signals_scout.slack_delivery_output_missing", **context)
+ return
+ if report.status not in _SCOUT_SLACK_DELIVERABLE_REPORT_STATUSES:
+ logger.info(
+ "signals_scout.slack_delivery_report_not_surfaced",
+ **context,
+ report_status=report.status,
+ )
+ return
+ post_scout_report_to_slack(
+ report,
+ run,
+ delivery_id=delivery_id,
+ integration_id=integration_id,
+ channel=channel,
+ )
+ else:
+ logger.warning("signals_scout.slack_delivery_output_type_invalid", **context)
+ return
+ except ScoutSlackPermanentDeliveryError as exc:
+ capture_exception(exc, {**context, "error_code": exc.error_code})
+ logger.warning(
+ "signals_scout.slack_delivery_permanent_failure",
+ **context,
+ error_code=exc.error_code,
+ )
+ return
+ except Exception as exc:
+ if self.request.retries < _SCOUT_SLACK_MAX_RETRIES:
+ countdown = _scout_slack_retry_countdown(exc, self.request.retries)
+ logger.warning(
+ "signals_scout.slack_delivery_retrying",
+ **context,
+ error_code=slack_api_error_code(exc) if isinstance(exc, SlackApiError) else None,
+ attempt=self.request.retries + 1,
+ countdown=countdown,
+ )
+ raise self.retry(exc=exc, countdown=countdown)
+
+ capture_exception(
+ exc,
+ {
+ **context,
+ "error_code": slack_api_error_code(exc) if isinstance(exc, SlackApiError) else None,
+ "attempts": self.request.retries + 1,
+ },
+ )
+ logger.exception(
+ "signals_scout.slack_delivery_exhausted",
+ **context,
+ attempts=self.request.retries + 1,
+ )
+ return
+
+ logger.info("signals_scout.slack_delivery_sent", **context)
+
+
+def enqueue_scout_slack_delivery(
+ *,
+ team_id: int,
+ output_type: ScoutSlackOutputType,
+ output_id: str,
+ run_id: str,
+ delivery_id: str,
+ integration_id: int,
+ channel: str,
+) -> None:
+ """Publish after commit, capturing broker failures without affecting the completed emit."""
+ try:
+ deliver_scout_slack_output.delay(
+ team_id,
+ output_type,
+ output_id,
+ run_id,
+ delivery_id,
+ integration_id,
+ channel,
+ )
+ except Exception as exc:
+ capture_exception(
+ exc,
+ {
+ "team_id": team_id,
+ "output_type": output_type,
+ "output_id": output_id,
+ "run_id": run_id,
+ "integration_id": integration_id,
+ },
+ )
+ logger.exception(
+ "signals_scout.slack_delivery_enqueue_failed",
+ team_id=team_id,
+ output_type=output_type,
+ output_id=output_id,
+ run_id=run_id,
+ integration_id=integration_id,
+ )
+
+
@shared_task(
name="products.signals.backend.tasks.send_reviewer_added_slack_notifications",
ignore_result=True,
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index dd4eddede499..5583a2169d6c 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -16,6 +16,7 @@ from social_django.models import UserSocialAuth
from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.models import OAuthApplication
+from posthog.models.integration import Integration
from posthog.models.organization import Organization
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -1124,6 +1125,81 @@ class TestScoutHarnessConfigAPI(APIBaseTest):
assert config.run_interval_minutes == 60
assert config.enabled_by_id == self.user.id
+ def test_partial_update_slack_destination_is_project_scoped_and_round_trips(self) -> None:
+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ other_integration = Integration.objects.create(team=other_team, kind=Integration.IntegrationKind.SLACK)
+
+ response = self.client.patch(
+ self._detail_url(str(config.id)),
+ data={
+ "output_destinations": {"slack": {"integration_id": other_integration.id, "channel": "COTHER|#other"}}
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ config.refresh_from_db()
+ assert config.output_destinations == {}
+
+ child_team = Team.objects.create(
+ organization=self.organization,
+ project=self.team.project,
+ parent_team=self.team,
+ name="Child environment",
+ )
+ integration = Integration.objects.create(team=child_team, kind=Integration.IntegrationKind.SLACK)
+ destination = {"slack": {"integration_id": integration.id, "channel": "CSCOUTS|#scout-findings"}}
+ response = self.client.patch(
+ self._detail_url(str(config.id)),
+ data={"output_destinations": destination},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["output_destinations"] == destination
+ config.refresh_from_db()
+ assert config.output_destinations == destination
+
+ @parameterized.expand(
+ [
+ ("missing_integration_scope", ["signal_scout:write"], status.HTTP_403_FORBIDDEN, "integration:read"),
+ (
+ "missing_task_scope",
+ ["signal_scout:write", "integration:read"],
+ status.HTTP_403_FORBIDDEN,
+ "task:read",
+ ),
+ (
+ "integration_and_task_scopes",
+ ["signal_scout:write", "integration:read", "task:read"],
+ status.HTTP_200_OK,
+ None,
+ ),
+ ]
+ )
+ def test_partial_update_slack_destination_requires_integration_and_task_scopes(
+ self, _name: str, scopes: list[str], expected_status: int, expected_missing_scope: str | None
+ ) -> None:
+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")
+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)
+ destination = {"slack": {"integration_id": integration.id, "channel": "CSCOUTS|#scout-findings"}}
+ api_key = self.create_personal_api_key_with_scopes(scopes)
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")
+
+ response = self.client.patch(
+ self._detail_url(str(config.id)),
+ data={"output_destinations": destination},
+ format="json",
+ )
+
+ assert response.status_code == expected_status
+ config.refresh_from_db()
+ assert config.output_destinations == (destination if expected_status == status.HTTP_200_OK else {})
+ if expected_missing_scope is not None:
+ assert expected_missing_scope in response.json()["detail"]
+
def test_partial_update_rejects_interval_below_min(self) -> None:
config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")
# 20 is below the 30-minute floor (the tightest cadence the UI offers) but above the old
diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.py
index 3cd976b22273..e840a1932417 100644
--- a/products/signals/backend/test/test_scout_report_api.py
+++ b/products/signals/backend/test/test_scout_report_api.py
@@ -104,9 +104,54 @@ class TestScoutReportAPI(APIBaseTest):
assert SignalReport.objects.filter(id=body["report_id"], team=self.team).exists()
embed_mock.assert_called_once()
+ def test_report_emit_and_edit_enqueue_configured_slack_destination_after_commit(self) -> None:
+ run = _make_run(self.team)
+ config = run.scout_config
+ assert config is not None
+ config.output_destinations = {"slack": {"integration_id": 17, "channel": "CSCOUTS|#scout-findings"}}
+ config.save(update_fields=["output_destinations"])
+
+ with (
+ _safe_judge(),
+ patch(EMBED_PATH),
+ patch(
+ "products.signals.backend.scout_harness.slack_delivery_queue.enqueue_scout_slack_delivery"
+ ) as enqueue,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ emitted = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json")
+ report_id = emitted.json()["report_id"]
+ edited = self.client.post(
+ self._edit_url(str(run.id)),
+ data={"report_id": report_id, "append_note": "Re-validated on the next run"},
+ format="json",
+ )
+
+ assert emitted.status_code == status.HTTP_200_OK, emitted.json()
+ assert edited.status_code == status.HTTP_200_OK, edited.json()
+ assert enqueue.call_count == 2
+ for call in enqueue.call_args_list:
+ assert call.kwargs["team_id"] == self.team.id
+ assert call.kwargs["output_type"] == "report"
+ assert call.kwargs["output_id"] == report_id
+ assert call.kwargs["run_id"] == str(run.id)
+ assert call.kwargs["integration_id"] == 17
+ assert call.kwargs["channel"] == "CSCOUTS|#scout-findings"
+ # Emit deliveries are keyed on the report id (idempotent); each edit gets its own id.
+ assert enqueue.call_args_list[0].kwargs["delivery_id"] == report_id
+ assert enqueue.call_args_list[1].kwargs["delivery_id"] != report_id
+
def test_emit_report_unsafe_suppresses_but_returns_id(self) -> None:
run = _make_run(self.team)
- with _safe_judge(choice=False, explanation="prompt injection"), patch(EMBED_PATH):
+ config = run.scout_config
+ assert config is not None
+ config.output_destinations = {"slack": {"integration_id": 17, "channel": "CSCOUTS|#scout-findings"}}
+ config.save(update_fields=["output_destinations"])
+ with (
+ _safe_judge(choice=False, explanation="prompt injection"),
+ patch(EMBED_PATH),
+ patch("products.signals.backend.scout_harness.tools.report.queue_configured_scout_slack_delivery") as queue,
+ ):
response = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json")
assert response.status_code == status.HTTP_200_OK
body = response.json()
@@ -114,6 +159,29 @@ class TestScoutReportAPI(APIBaseTest):
assert body["report_status"] == SignalReport.Status.SUPPRESSED
assert body["safety_explanation"] == "prompt injection"
assert body["report_id"] is not None
+ queue.assert_not_called()
+
+ def test_edit_of_suppressed_report_does_not_enqueue_slack_delivery(self) -> None:
+ run = _make_run(self.team)
+ config = run.scout_config
+ assert config is not None
+ config.output_destinations = {"slack": {"integration_id": 17, "channel": "CSCOUTS|#scout-findings"}}
+ config.save(update_fields=["output_destinations"])
+ with (
+ _safe_judge(choice=False, explanation="prompt injection"),
+ patch(EMBED_PATH),
+ patch("products.signals.backend.scout_harness.tools.report.queue_configured_scout_slack_delivery") as queue,
+ ):
+ emitted = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json")
+ report_id = emitted.json()["report_id"]
+ edited = self.client.post(
+ self._edit_url(str(run.id)),
+ data={"report_id": report_id, "append_note": "note on a suppressed report"},
+ format="json",
+ )
+ assert emitted.status_code == status.HTTP_200_OK, emitted.json()
+ assert edited.status_code == status.HTTP_200_OK, edited.json()
+ queue.assert_not_called()
def test_emit_report_skips_when_ai_not_approved(self) -> None:
# Preflight gate: a report is never authored for an org that hasn't approved AI processing.
diff --git a/products/signals/backend/test/test_scout_slack_delivery.py b/products/signals/backend/test/test_scout_slack_delivery.py
new file mode 100644
index 000000000000..30c35523abe7
--- /dev/null
+++ b/products/signals/backend/test/test_scout_slack_delivery.py
@@ -0,0 +1,295 @@
+import pytest
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.apps import apps
+from django.conf import settings
+
+from celery.exceptions import Retry
+from slack_sdk.errors import SlackApiError
+
+from posthog.models import Team
+from posthog.models.integration import Integration
+
+from products.signals.backend.models import SignalReport, SignalScoutEmission, SignalScoutRun
+from products.signals.backend.scout_harness.slack_delivery import (
+ ScoutSlackPermanentDeliveryError,
+ post_scout_emission_to_slack,
+)
+from products.signals.backend.scout_harness.slack_delivery_queue import queue_configured_scout_slack_delivery
+from products.signals.backend.tasks import deliver_scout_slack_output, enqueue_scout_slack_delivery
+
+
+class FakeSlackResponse(dict):
+ def __init__(self, data: dict, headers: dict | None = None) -> None:
+ super().__init__(data)
+ self.headers = headers or {}
+
+
+class TestScoutSlackDelivery(BaseTest):
+ def _make_emission(self, description: str = "**Checkout** failures") -> SignalScoutEmission:
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
+ task = Task.objects.create(
+ team=self.team,
+ title="scout run",
+ description="scout run",
+ origin_product=Task.OriginProduct.SIGNALS_SCOUT,
+ )
+ task_run = TaskRun.objects.create(task=task, team=self.team)
+ run = SignalScoutRun.all_teams.create(
+ task_run=task_run,
+ team=self.team,
+ skill_name="signals-scout-error-tracking",
+ skill_version=1,
+ )
+ return SignalScoutEmission.all_teams.create(
+ team=self.team,
+ scout_run=run,
+ finding_id="checkout/500s",
+ description=description,
+ weight=1.0,
+ confidence=0.84,
+ severity="P1",
+ tags=["checkout", "regression"],
+ source_id=f"run:{run.id}:finding:checkout-500s",
+ )
+
+ def test_posts_safe_slack_mrkdwn_through_project_integration_with_stable_delivery_id(self) -> None:
+ emission = self._make_emission(
+ "**Checkout** failures [trace](https://example.com/trace) <!channel> [ping](!here)"
+ )
+ child_team = Team.objects.create(
+ organization=self.organization,
+ project=self.team.project,
+ parent_team=self.team,
+ name="Child environment",
+ )
+ integration = Integration.objects.create(team=child_team, kind=Integration.IntegrationKind.SLACK)
+ fake_client = MagicMock()
+
+ with patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration:
+ slack_integration.return_value.client = fake_client
+ post_scout_emission_to_slack(
+ emission,
+ integration_id=integration.id,
+ channel="CSCOUTS|#scout-findings",
+ )
+
+ call = fake_client.chat_postMessage.call_args.kwargs
+ assert call["channel"] == "CSCOUTS"
+ assert call["client_msg_id"] == str(emission.id)
+ section = call["blocks"][1]["text"]["text"]
+ assert "*Checkout*" in section
+ assert "<https://example.com/trace|trace>" in section
+ assert "<!channel>" not in section
+ assert "<!here>" not in section
+ assert "&lt;!channel&gt;" in section
+ assert call["blocks"][-1]["elements"][0]["url"] == (
+ f"{settings.SITE_URL}/project/{self.team.id}/inbox/scouts/signals-scout-error-tracking/checkout%2F500s"
+ )
+
+ def test_posts_report_with_safe_markdown_and_delivery_id(self) -> None:
+ emission = self._make_emission()
+ report = SignalReport.objects.create(
+ team=self.team,
+ status=SignalReport.Status.READY,
+ title="Checkout failures",
+ summary="**Checkout** failed for <!channel> [trace](https://example.com/trace)",
+ )
+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)
+ fake_client = MagicMock()
+ delivery_id = "01864f4c-6957-7d3f-8d85-1d775e527265"
+
+ with patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration:
+ slack_integration.return_value.client = fake_client
+ deliver_scout_slack_output.run(
+ self.team.id,
+ "report",
+ str(report.id),
+ str(emission.scout_run_id),
+ delivery_id,
+ integration.id,
+ "CSCOUTS|#scout-findings",
+ )
+
+ call = fake_client.chat_postMessage.call_args.kwargs
+ assert call["channel"] == "CSCOUTS"
+ assert call["client_msg_id"] == delivery_id
+ section = call["blocks"][2]["text"]["text"]
+ assert "*Checkout*" in section
+ assert "<!channel>" not in section
+ assert "&lt;!channel&gt;" in section
+ assert "<https://example.com/trace|trace>" in section
+ assert call["blocks"][-1]["elements"][0]["url"] == (
+ f"{settings.SITE_URL}/project/{self.team.id}/inbox/reports/{report.id}"
+ )
+
+ def test_task_skips_report_suppressed_before_delivery(self) -> None:
+ emission = self._make_emission()
+ report = SignalReport.objects.create(
+ team=self.team,
+ status=SignalReport.Status.SUPPRESSED,
+ title="Unsafe report",
+ summary="This report must not leave PostHog.",
+ )
+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)
+ fake_client = MagicMock()
+
+ with patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration:
+ slack_integration.return_value.client = fake_client
+ deliver_scout_slack_output.run(
+ self.team.id,
+ "report",
+ str(report.id),
+ str(emission.scout_run_id),
+ "01864f4c-6957-7d3f-8d85-1d775e527265",
+ integration.id,
+ "CSCOUTS|#scout-findings",
+ )
+
+ fake_client.chat_postMessage.assert_not_called()
+
+ def test_task_retries_transient_delivery_failure(self) -> None:
+ emission = self._make_emission()
+ error = SlackApiError(
+ message="rate limited",
+ response=FakeSlackResponse({"error": "ratelimited"}, headers={"retry-after": "120"}),
+ )
+
+ with patch(
+ "products.signals.backend.tasks.post_scout_emission_to_slack",
+ side_effect=error,
+ ):
+ with pytest.raises(Retry) as retry:
+ deliver_scout_slack_output.apply(
+ args=(
+ self.team.id,
+ "finding",
+ str(emission.id),
+ str(emission.scout_run_id),
+ str(emission.id),
+ 1,
+ "CSCOUTS|#scout-findings",
+ ),
+ throw=True,
+ )
+
+ assert retry.value.when == 120
+
+ def test_task_captures_known_permanent_failure_without_retry(self) -> None:
+ emission = self._make_emission()
+ error = ScoutSlackPermanentDeliveryError("channel unavailable", error_code="channel_not_found")
+
+ with (
+ patch("products.signals.backend.tasks.post_scout_emission_to_slack", side_effect=error),
+ patch("products.signals.backend.tasks.capture_exception") as capture,
+ ):
+ deliver_scout_slack_output.run(
+ self.team.id,
+ "finding",
+ str(emission.id),
+ str(emission.scout_run_id),
+ str(emission.id),
+ 9,
+ "CMISSING|#missing",
+ )
+
+ capture.assert_called_once_with(
+ error,
+ {
+ "team_id": self.team.id,
+ "output_type": "finding",
+ "output_id": str(emission.id),
+ "run_id": str(emission.scout_run_id),
+ "integration_id": 9,
+ "error_code": "channel_not_found",
+ },
+ )
+
+ def test_task_captures_transient_failure_after_retries_are_exhausted(self) -> None:
+ emission = self._make_emission()
+ error = ConnectionError("Slack unavailable")
+
+ with (
+ patch("products.signals.backend.tasks.post_scout_emission_to_slack", side_effect=error),
+ patch("products.signals.backend.tasks.capture_exception") as capture,
+ ):
+ result = deliver_scout_slack_output.apply(
+ args=(
+ self.team.id,
+ "finding",
+ str(emission.id),
+ str(emission.scout_run_id),
+ str(emission.id),
+ 9,
+ "CSCOUTS|#scout-findings",
+ ),
+ retries=5,
+ throw=True,
+ )
+
+ assert result.successful()
+ capture.assert_called_once_with(
+ error,
+ {
+ "team_id": self.team.id,
+ "output_type": "finding",
+ "output_id": str(emission.id),
+ "run_id": str(emission.scout_run_id),
+ "integration_id": 9,
+ "error_code": None,
+ "attempts": 6,
+ },
+ )
+
+ def test_enqueue_captures_broker_failure(self) -> None:
+ error = ConnectionError("broker unavailable")
+
+ with (
+ patch.object(deliver_scout_slack_output, "delay", side_effect=error),
+ patch("products.signals.backend.tasks.capture_exception") as capture,
+ ):
+ enqueue_scout_slack_delivery(
+ team_id=self.team.id,
+ output_type="report",
+ output_id="ddab8ee5-2bb8-4226-b145-6732d31dc344",
+ run_id="e3865391-bc89-44e6-86f7-2d4405627daf",
+ delivery_id="b316c1d1-6901-49eb-8223-96d4df69f67f",
+ integration_id=9,
+ channel="CSCOUTS|#scout-findings",
+ )
+
+ capture.assert_called_once_with(
+ error,
+ {
+ "team_id": self.team.id,
+ "output_type": "report",
+ "output_id": "ddab8ee5-2bb8-4226-b145-6732d31dc344",
+ "run_id": "e3865391-bc89-44e6-86f7-2d4405627daf",
+ "integration_id": 9,
+ },
+ )
+
+ def test_queue_captures_failure_before_enqueue(self) -> None:
+ error = ConnectionError("database unavailable")
+ run_id = "e3865391-bc89-44e6-86f7-2d4405627daf"
+
+ with (
+ patch.object(SignalScoutRun.all_teams, "select_related", side_effect=error),
+ patch("products.signals.backend.scout_harness.slack_delivery_queue.capture_exception") as capture,
+ ):
+ queue_configured_scout_slack_delivery(
+ run_id=run_id,
+ output_type="report",
+ output_id="ddab8ee5-2bb8-4226-b145-6732d31dc344",
+ )
+
+ capture.assert_called_once_with(
+ error,
+ {
+ "run_id": run_id,
+ "output_type": "report",
+ "output_id": "ddab8ee5-2bb8-4226-b145-6732d31dc344",
+ },
+ )
diff --git a/products/signals/backend/test/test_signal_scout_models.py b/products/signals/backend/test/test_signal_scout_models.py
index b4aa100b4dc0..9d97dfb8c785 100644
--- a/products/signals/backend/test/test_signal_scout_models.py
+++ b/products/signals/backend/test/test_signal_scout_models.py
@@ -3,6 +3,7 @@ from typing import TYPE_CHECKING
import pytest
from posthog.test.base import BaseTest
+from unittest.mock import patch
from django.apps import apps
from django.db import IntegrityError
@@ -13,6 +14,7 @@ from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.scoping import team_scope
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun, SignalScratchpad
+from products.signals.backend.scout_harness.tools.emit import _record_emit
if TYPE_CHECKING:
from products.tasks.backend.models import TaskRun
@@ -79,6 +81,46 @@ class TestSignalScoutModels(_ScoutTeamScopedTestMixin, BaseTest):
SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-bar")
assert SignalScoutConfig.objects.filter(team=self.team).count() == 2
+ def test_record_emit_enqueues_configured_slack_destination_after_commit(self) -> None:
+ config = SignalScoutConfig.objects.create(
+ team=self.team,
+ skill_name="signals-scout-errors",
+ output_destinations={"slack": {"integration_id": 17, "channel": "CSCOUTS|#scout-findings"}},
+ )
+ run = SignalScoutRun.objects.create(
+ task_run=self._make_task_run(),
+ team=self.team,
+ scout_config=config,
+ skill_name=config.skill_name,
+ skill_version=1,
+ )
+
+ with patch(
+ "products.signals.backend.scout_harness.slack_delivery_queue.enqueue_scout_slack_delivery"
+ ) as enqueue:
+ with self.captureOnCommitCallbacks(execute=True):
+ _record_emit(
+ run_id=run.id,
+ finding_id="finding-1",
+ description="A finding",
+ weight=1.0,
+ confidence=0.8,
+ severity="P1",
+ source_id=f"run:{run.id}:finding:finding-1",
+ tags=["checkout"],
+ )
+
+ emission = run.emissions.get(finding_id="finding-1")
+ enqueue.assert_called_once_with(
+ team_id=self.team.id,
+ output_type="finding",
+ output_id=str(emission.id),
+ run_id=str(run.id),
+ delivery_id=str(emission.id),
+ integration_id=17,
+ channel="CSCOUTS|#scout-findings",
+ )
+
def test_enabling_scout_logs_activity(self) -> None:
config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo", enabled=False)
config.enabled = True
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index b3f34474ce37..afdb21811463 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -1467,8 +1467,27 @@ export const ScoutOriginEnumApi = {
Custom: 'custom',
} as const
+export interface SignalScoutSlackDestinationApi {
+ /**
+ * ID of the Slack integration whose bot posts this scout's findings and reports.
+ * @minimum 1
+ */
+ integration_id: number
+ /**
+ * Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set.
+ * @maxLength 255
+ * @nullable
+ */
+ channel?: string | null
+}
+
+export interface SignalScoutOutputDestinationsApi {
+ /** Slack destination for each emitted scout finding or report. Null or omitted disables Slack delivery. */
+ slack?: SignalScoutSlackDestinationApi | null
+}
+
/**
- * Per-(team, skill) scout config: schedule, enablement, and emit posture.
+ * Read shape for a per-(team, skill) scout config.
*
* One row per `signals-scout-*` skill on the team. The coordinator auto-creates a row
* when it discovers a scout skill; this serializer lets agents tune the row.
@@ -1496,6 +1515,8 @@ export interface SignalScoutConfigApi {
* @nullable
*/
readonly run_cron_schedule: string | null
+ /** Destinations that receive each finding or report this scout emits. Empty when none is configured. */
+ readonly output_destinations: SignalScoutOutputDestinationsApi
/**
* When the coordinator last dispatched this scout. Null if it has never run.
* @nullable
@@ -1526,6 +1547,8 @@ export interface SignalScoutConfigCreateApi {
* @maximum 43200
*/
run_interval_minutes?: number
+ /** Destinations that receive each finding or report this scout emits. Empty by default. */
+ output_destinations?: SignalScoutOutputDestinationsApi
/**
* Optional five-field cron expression, e.g. '30 9 * * *' (daily at 09:30), '0 9,17 * * *' (twice daily), or '0 9 * * 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart.
* @maxLength 100
@@ -1554,6 +1577,8 @@ export interface PatchedSignalScoutConfigUpdateApi {
* @nullable
*/
run_cron_schedule?: string | null
+ /** Destinations that receive each finding or report this scout emits. Pass an empty object to disable delivery. */
+ output_destinations?: SignalScoutOutputDestinationsApi
}
/**
@@ -2251,6 +2276,25 @@ export interface ProjectProfileApi {
*/
export type SignalScoutRunSummaryApiMetadata = { [key: string]: string }
+/**
+ * * `not_started` - not_started
+ * * `queued` - queued
+ * * `in_progress` - in_progress
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled
+ */
+export type RunStatusEnumApi = (typeof RunStatusEnumApi)[keyof typeof RunStatusEnumApi]
+
+export const RunStatusEnumApi = {
+ NotStarted: 'not_started',
+ Queued: 'queued',
+ InProgress: 'in_progress',
+ Completed: 'completed',
+ Failed: 'failed',
+ Cancelled: 'cancelled',
+} as const
+
/**
* Lightweight projection of a `SignalScoutRun` row used by `search-recent-runs`.
*
@@ -2263,8 +2307,15 @@ export interface SignalScoutRunSummaryApi {
skill_name: string
/** Skill version snapshotted at run start. */
skill_version: number
- /** Status from the linked TaskRun: not_started | queued | in_progress | completed | failed | cancelled. */
- status: string
+ /** Status from the linked TaskRun.
+ *
+ * * `not_started` - not_started
+ * * `queued` - queued
+ * * `in_progress` - in_progress
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled */
+ status: RunStatusEnumApi
/** ISO-8601 timestamp the bridge row was created — the field `date_from` / `date_to` filter and order on. Use this (not `started_at`) as the `date_to` cursor when walking past the 100-row cap, so runs created in the gap between a boundary run's TaskRun and its bridge row aren't skipped. */
created_at: string
/** ISO-8601 timestamp the TaskRun was created. */
@@ -2330,8 +2381,15 @@ export interface SignalScoutRunDetailApi {
skill_name: string
/** Skill version snapshotted at run start. */
skill_version: number
- /** Status from the linked TaskRun: not_started | queued | in_progress | completed | failed | cancelled. */
- status: string
+ /** Status from the linked TaskRun.
+ *
+ * * `not_started` - not_started
+ * * `queued` - queued
+ * * `in_progress` - in_progress
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled */
+ status: RunStatusEnumApi
/** ISO-8601 timestamp the bridge row was created — the field `date_from` / `date_to` filter and order on. Use this (not `started_at`) as the `date_to` cursor when walking past the 100-row cap, so runs created in the gap between a boundary run's TaskRun and its bridge row aren't skipped. */
created_at: string
/** ISO-8601 timestamp the TaskRun was created. */
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index b44c48289e4c..73bada49079c 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -505,7 +505,7 @@ export const getSignalsScoutConfigCreateUrl = (projectId: string) => {
}
/**
- * Register the config for a `signals-scout-*` skill immediately, without waiting for the coordinator to auto-register it. The same call can optionally set `run_interval_minutes`, a cron `run_cron_schedule`, `enabled`, and `emit`. The skill must already exist on this project. Upsert: if a config already exists for the skill, the provided fields are applied to it.
+ * Register the config for a `signals-scout-*` skill immediately, without waiting for the coordinator to auto-register it. The same call can optionally set `run_interval_minutes`, a cron `run_cron_schedule`, `enabled`, `emit`, and output destinations. The skill must already exist on this project. Upsert: if a config already exists for the skill, the provided fields are applied to it.
* @summary Create a scout config
*/
export const signalsScoutConfigCreate = async (
@@ -526,7 +526,7 @@ export const getSignalsScoutConfigUpdateUrl = (projectId: string, id: string) =>
}
/**
- * Tune one scout: change its schedule (rolling `run_interval_minutes`, or a cron `run_cron_schedule` that takes precedence when set), `enabled`, or `emit` (dry-run) posture. `skill_name` is fixed. Enabling records `enabled_by` and is activity-logged since it drives spend.
+ * Tune one scout: change its schedule (rolling `run_interval_minutes`, or a cron `run_cron_schedule` that takes precedence when set), `enabled`, or `emit` (dry-run) posture, or output destinations. `skill_name` is fixed. Enabling records `enabled_by` and is activity-logged since it drives spend.
* @summary Update a scout config
*/
export const signalsScoutConfigUpdate = async (
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 6daf0fe536c6..8d7d856a6926 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -226,7 +226,7 @@ export const SignalsReportsBulkStateCreateBody = /* @__PURE__ */ zod.object({
})
/**
- * Register the config for a `signals-scout-*` skill immediately, without waiting for the coordinator to auto-register it. The same call can optionally set `run_interval_minutes`, a cron `run_cron_schedule`, `enabled`, and `emit`. The skill must already exist on this project. Upsert: if a config already exists for the skill, the provided fields are applied to it.
+ * Register the config for a `signals-scout-*` skill immediately, without waiting for the coordinator to auto-register it. The same call can optionally set `run_interval_minutes`, a cron `run_cron_schedule`, `enabled`, `emit`, and output destinations. The skill must already exist on this project. Upsert: if a config already exists for the skill, the provided fields are applied to it.
* @summary Create a scout config
*/
export const signalsScoutConfigCreateBodySkillNameMax = 200
@@ -234,6 +234,8 @@ export const signalsScoutConfigCreateBodySkillNameMax = 200
export const signalsScoutConfigCreateBodyRunIntervalMinutesMin = 30
export const signalsScoutConfigCreateBodyRunIntervalMinutesMax = 43200
+export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneChannelMax = 255
+
export const signalsScoutConfigCreateBodyRunCronScheduleMax = 100
export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod
@@ -257,6 +259,34 @@ export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod
.max(signalsScoutConfigCreateBodyRunIntervalMinutesMax)
.optional()
.describe('Minutes between runs (30–43200). Defaults to 1440 (every 24 hours).'),
+ output_destinations: zod
+ .object({
+ slack: zod
+ .union([
+ zod.object({
+ integration_id: zod
+ .number()
+ .min(1)
+ .describe(
+ "ID of the Slack integration whose bot posts this scout's findings and reports."
+ ),
+ channel: zod
+ .string()
+ .max(signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneChannelMax)
+ .nullish()
+ .describe(
+ "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Slack destination for each emitted scout finding or report. Null or omitted disables Slack delivery.'
+ ),
+ })
+ .optional()
+ .describe('Destinations that receive each finding or report this scout emits. Empty by default.'),
run_cron_schedule: zod
.string()
.max(signalsScoutConfigCreateBodyRunCronScheduleMax)
@@ -270,7 +300,7 @@ export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod
)
/**
- * Tune one scout: change its schedule (rolling `run_interval_minutes`, or a cron `run_cron_schedule` that takes precedence when set), `enabled`, or `emit` (dry-run) posture. `skill_name` is fixed. Enabling records `enabled_by` and is activity-logged since it drives spend.
+ * Tune one scout: change its schedule (rolling `run_interval_minutes`, or a cron `run_cron_schedule` that takes precedence when set), `enabled`, or `emit` (dry-run) posture, or output destinations. `skill_name` is fixed. Enabling records `enabled_by` and is activity-logged since it drives spend.
* @summary Update a scout config
*/
export const signalsScoutConfigUpdateBodyRunIntervalMinutesMin = 30
@@ -278,6 +308,8 @@ export const signalsScoutConfigUpdateBodyRunIntervalMinutesMax = 43200
export const signalsScoutConfigUpdateBodyRunCronScheduleMax = 100
+export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneChannelMax = 255
+
export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod
.object({
enabled: zod
@@ -303,6 +335,36 @@ export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod
.describe(
"Optional five-field cron expression, e.g. '30 9 \* \* \*' (daily at 09:30), '0 9,17 \* \* \*' (twice daily), or '0 9 \* \* 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart. Set null to return to the rolling interval schedule."
),
+ output_destinations: zod
+ .object({
+ slack: zod
+ .union([
+ zod.object({
+ integration_id: zod
+ .number()
+ .min(1)
+ .describe(
+ "ID of the Slack integration whose bot posts this scout's findings and reports."
+ ),
+ channel: zod
+ .string()
+ .max(signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneChannelMax)
+ .nullish()
+ .describe(
+ "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Slack destination for each emitted scout finding or report. Null or omitted disables Slack delivery.'
+ ),
+ })
+ .optional()
+ .describe(
+ 'Destinations that receive each finding or report this scout emits. Pass an empty object to disable delivery.'
+ ),
})
.describe('Editable schedule, enablement, and emit posture for one scout config.')
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index e53c0f2d637e..28e5af65b36b 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -364,9 +364,10 @@ tools:
coordinator to auto-register it. The same call can optionally set its schedule (rolling
`run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *' that takes
precedence when set), `enabled`, and `emit` (false = dry-run). Cron schedules use the project timezone
- automatically and occurrences must be at least 30 minutes apart. The skill must already exist on the project
- (author it via the skills store first). Upsert: if a config already exists for the skill, the provided
- fields are applied to it. Creating an enabled config is activity-logged, since running a scout drives spend.
+ automatically and occurrences must be at least 30 minutes apart. The same call can configure
+ `output_destinations`. The skill must already exist on the project (author it via the skills store first).
+ Upsert: if a config already exists for the skill, the provided fields are applied to it. Creating an enabled
+ config is activity-logged, since running a scout drives spend.
scout-config-delete:
operation: signals_scout_config_destroy
enabled: true
@@ -398,10 +399,10 @@ tools:
description: >
List the per-scout configs for this project. Each `signals-scout-*` skill has one row with its schedule
(rolling `run_interval_minutes`, or a project-local cron `run_cron_schedule` when set), `enabled` flag, and
- `emit` (dry-run) posture. A freshly authored scout appears once its config is registered: immediately via
- `scout-config-create` (one skill) or `scout-config-sync` (the whole fleet), or on the coordinator's next
- tick. Use this to see which scouts run, how often, and whether they emit findings to the inbox. Pair with
- `scout-config-update` to tune them.
+ `emit` (dry-run) posture, and output destinations. A freshly authored scout appears once its config is
+ registered: immediately via `scout-config-create` (one skill) or `scout-config-sync` (the whole fleet), or
+ on the coordinator's next tick. Use this to see which scouts run, how often, whether they emit findings to
+ the inbox, and where those findings are delivered. Pair with `scout-config-update` to tune them.
scout-config-sync:
operation: signals_scout_config_sync
enabled: true
@@ -434,8 +435,9 @@ tools:
five-field cron `run_cron_schedule` like '30 9 * * *', '0 9,17 * * *', or '0 9 * * 1-5' that takes
precedence when set), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to
the inbox). Cron schedules use the project timezone automatically and occurrences must be at least 30
- minutes apart; set null to return to the rolling interval. `skill_name` is fixed. Enabling records who
- flipped it on and is activity-logged, since running a scout drives spend.
+ minutes apart; set null to return to the rolling interval. You can also configure
+ `output_destinations.slack` with a Slack integration and channel. `skill_name` is fixed. Enabling records
+ who flipped it on and is activity-logged, since running a scout drives spend.
scout-edit-report:
operation: signals_scout_edit_report
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 5126c3a4b9dc..f93383518fbf 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -7803,7 +7803,7 @@
}
},
"scout-config-create": {
- "description": "Register the config for a freshly authored `signals-scout-*` skill immediately, without waiting for the coordinator to auto-register it. The same call can optionally set its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *' that takes precedence when set), `enabled`, and `emit` (false = dry-run). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart. The skill must already exist on the project (author it via the skills store first). Upsert: if a config already exists for the skill, the provided fields are applied to it. Creating an enabled config is activity-logged, since running a scout drives spend.",
+ "description": "Register the config for a freshly authored `signals-scout-*` skill immediately, without waiting for the coordinator to auto-register it. The same call can optionally set its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *' that takes precedence when set), `enabled`, and `emit` (false = dry-run). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart. The same call can configure `output_destinations`. The skill must already exist on the project (author it via the skills store first). Upsert: if a config already exists for the skill, the provided fields are applied to it. Creating an enabled config is activity-logged, since running a scout drives spend.",
"category": "Signals",
"feature": "signals",
"summary": "Create a scout config",
@@ -7831,7 +7831,7 @@
}
},
"scout-config-list": {
- "description": "List the per-scout configs for this project. Each `signals-scout-*` skill has one row with its schedule (rolling `run_interval_minutes`, or a project-local cron `run_cron_schedule` when set), `enabled` flag, and `emit` (dry-run) posture. A freshly authored scout appears once its config is registered: immediately via `scout-config-create` (one skill) or `scout-config-sync` (the whole fleet), or on the coordinator's next tick. Use this to see which scouts run, how often, and whether they emit findings to the inbox. Pair with `scout-config-update` to tune them.",
+ "description": "List the per-scout configs for this project. Each `signals-scout-*` skill has one row with its schedule (rolling `run_interval_minutes`, or a project-local cron `run_cron_schedule` when set), `enabled` flag, and `emit` (dry-run) posture, and output destinations. A freshly authored scout appears once its config is registered: immediately via `scout-config-create` (one skill) or `scout-config-sync` (the whole fleet), or on the coordinator's next tick. Use this to see which scouts run, how often, whether they emit findings to the inbox, and where those findings are delivered. Pair with `scout-config-update` to tune them.",
"category": "Signals",
"feature": "signals",
"summary": "List scout configs",
@@ -7859,7 +7859,7 @@
}
},
"scout-config-update": {
- "description": "Tune one scout by its config `id`: change its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *', '0 9,17 * * *', or '0 9 * * 1-5' that takes precedence when set), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart; set null to return to the rolling interval. `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.",
+ "description": "Tune one scout by its config `id`: change its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *', '0 9,17 * * *', or '0 9 * * 1-5' that takes precedence when set), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart; set null to return to the rolling interval. You can also configure `output_destinations.slack` with a Slack integration and channel. `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.",
"category": "Signals",
"feature": "signals",
"summary": "Update a scout config",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index a8f4d6aa3191..cc496bfff22c 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -8338,7 +8338,7 @@
}
},
"scout-config-create": {
- "description": "Register the config for a freshly authored `signals-scout-*` skill immediately, without waiting for the coordinator to auto-register it. The same call can optionally set its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *' that takes precedence when set), `enabled`, and `emit` (false = dry-run). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart. The skill must already exist on the project (author it via the skills store first). Upsert: if a config already exists for the skill, the provided fields are applied to it. Creating an enabled config is activity-logged, since running a scout drives spend.",
+ "description": "Register the config for a freshly authored `signals-scout-*` skill immediately, without waiting for the coordinator to auto-register it. The same call can optionally set its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *' that takes precedence when set), `enabled`, and `emit` (false = dry-run). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart. The same call can configure `output_destinations`. The skill must already exist on the project (author it via the skills store first). Upsert: if a config already exists for the skill, the provided fields are applied to it. Creating an enabled config is activity-logged, since running a scout drives spend.",
"category": "Signals",
"feature": "signals",
"summary": "Create a scout config",
@@ -8366,7 +8366,7 @@
}
},
"scout-config-list": {
- "description": "List the per-scout configs for this project. Each `signals-scout-*` skill has one row with its schedule (rolling `run_interval_minutes`, or a project-local cron `run_cron_schedule` when set), `enabled` flag, and `emit` (dry-run) posture. A freshly authored scout appears once its config is registered: immediately via `scout-config-create` (one skill) or `scout-config-sync` (the whole fleet), or on the coordinator's next tick. Use this to see which scouts run, how often, and whether they emit findings to the inbox. Pair with `scout-config-update` to tune them.",
+ "description": "List the per-scout configs for this project. Each `signals-scout-*` skill has one row with its schedule (rolling `run_interval_minutes`, or a project-local cron `run_cron_schedule` when set), `enabled` flag, and `emit` (dry-run) posture, and output destinations. A freshly authored scout appears once its config is registered: immediately via `scout-config-create` (one skill) or `scout-config-sync` (the whole fleet), or on the coordinator's next tick. Use this to see which scouts run, how often, whether they emit findings to the inbox, and where those findings are delivered. Pair with `scout-config-update` to tune them.",
"category": "Signals",
"feature": "signals",
"summary": "List scout configs",
@@ -8394,7 +8394,7 @@
}
},
"scout-config-update": {
- "description": "Tune one scout by its config `id`: change its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *', '0 9,17 * * *', or '0 9 * * 1-5' that takes precedence when set), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart; set null to return to the rolling interval. `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.",
+ "description": "Tune one scout by its config `id`: change its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *', '0 9,17 * * *', or '0 9 * * 1-5' that takes precedence when set), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart; set null to return to the rolling interval. You can also configure `output_destinations.slack` with a Slack integration and channel. `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.",
"category": "Signals",
"feature": "signals",
"summary": "Update a scout config",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 296a7e728f5f..a183f05a5290 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -51809,6 +51809,25 @@ export namespace Schemas {
summary?: string;
}
+ export interface SignalScoutSlackDestination {
+ /**
+ * ID of the Slack integration whose bot posts this scout's findings and reports.
+ * @minimum 1
+ */
+ integration_id: number;
+ /**
+ * Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set.
+ * @maxLength 255
+ * @nullable
+ */
+ channel?: string | null;
+ }
+
+ export interface SignalScoutOutputDestinations {
+ /** Slack destination for each emitted scout finding or report. Null or omitted disables Slack delivery. */
+ slack?: SignalScoutSlackDestination | null;
+ }
+
/**
* Editable schedule, enablement, and emit posture for one scout config.
*/
@@ -51829,6 +51848,8 @@ export namespace Schemas {
* @nullable
*/
run_cron_schedule?: string | null;
+ /** Destinations that receive each finding or report this scout emits. Pass an empty object to disable delivery. */
+ output_destinations?: SignalScoutOutputDestinations;
}
export interface PatchedSignalSourceConfig {
@@ -61283,7 +61304,7 @@ export namespace Schemas {
}
/**
- * Per-(team, skill) scout config: schedule, enablement, and emit posture.
+ * Read shape for a per-(team, skill) scout config.
*
* One row per `signals-scout-*` skill on the team. The coordinator auto-creates a row
* when it discovers a scout skill; this serializer lets agents tune the row.
@@ -61311,6 +61332,8 @@ export namespace Schemas {
* @nullable
*/
readonly run_cron_schedule: string | null;
+ /** Destinations that receive each finding or report this scout emits. Empty when none is configured. */
+ readonly output_destinations: SignalScoutOutputDestinations;
/**
* When the coordinator last dispatched this scout. Null if it has never run.
* @nullable
@@ -61341,6 +61364,8 @@ export namespace Schemas {
* @maximum 43200
*/
run_interval_minutes?: number;
+ /** Destinations that receive each finding or report this scout emits. Empty by default. */
+ output_destinations?: SignalScoutOutputDestinations;
/**
* Optional five-field cron expression, e.g. '30 9 * * *' (daily at 09:30), '0 9,17 * * *' (twice daily), or '0 9 * * 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart.
* @maxLength 100
@@ -61424,8 +61449,15 @@ export namespace Schemas {
skill_name: string;
/** Skill version snapshotted at run start. */
skill_version: number;
- /** Status from the linked TaskRun: not_started | queued | in_progress | completed | failed | cancelled. */
- status: string;
+ /** Status from the linked TaskRun.
+ *
+ * * `not_started` - not_started
+ * * `queued` - queued
+ * * `in_progress` - in_progress
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled */
+ status: RunStatusEnum;
/** ISO-8601 timestamp the bridge row was created — the field `date_from` / `date_to` filter and order on. Use this (not `started_at`) as the `date_to` cursor when walking past the 100-row cap, so runs created in the gap between a boundary run's TaskRun and its bridge row aren't skipped. */
created_at: string;
/** ISO-8601 timestamp the TaskRun was created. */
@@ -61491,8 +61523,15 @@ export namespace Schemas {
skill_name: string;
/** Skill version snapshotted at run start. */
skill_version: number;
- /** Status from the linked TaskRun: not_started | queued | in_progress | completed | failed | cancelled. */
- status: string;
+ /** Status from the linked TaskRun.
+ *
+ * * `not_started` - not_started
+ * * `queued` - queued
+ * * `in_progress` - in_progress
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled */
+ status: RunStatusEnum;
/** ISO-8601 timestamp the bridge row was created — the field `date_from` / `date_to` filter and order on. Use this (not `started_at`) as the `date_to` cursor when walking past the 100-row cap, so runs created in the gap between a boundary run's TaskRun and its bridge row aren't skipped. */
created_at: string;
/** ISO-8601 timestamp the TaskRun was created. */
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index c0201a1f0b84..07551d9fb388 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -399,7 +399,7 @@ export const SignalsScoutConfigListParams = /* @__PURE__ */ zod.object({
})
/**
- * Register the config for a `signals-scout-*` skill immediately, without waiting for the coordinator to auto-register it. The same call can optionally set `run_interval_minutes`, a cron `run_cron_schedule`, `enabled`, and `emit`. The skill must already exist on this project. Upsert: if a config already exists for the skill, the provided fields are applied to it.
+ * Register the config for a `signals-scout-*` skill immediately, without waiting for the coordinator to auto-register it. The same call can optionally set `run_interval_minutes`, a cron `run_cron_schedule`, `enabled`, `emit`, and output destinations. The skill must already exist on this project. Upsert: if a config already exists for the skill, the provided fields are applied to it.
* @summary Create a scout config
*/
export const SignalsScoutConfigCreateParams = /* @__PURE__ */ zod.object({
@@ -415,6 +415,8 @@ export const signalsScoutConfigCreateBodySkillNameMax = 200
export const signalsScoutConfigCreateBodyRunIntervalMinutesMin = 30
export const signalsScoutConfigCreateBodyRunIntervalMinutesMax = 43200
+export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneChannelMax = 255
+
export const signalsScoutConfigCreateBodyRunCronScheduleMax = 100
export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod
@@ -438,6 +440,34 @@ export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod
.max(signalsScoutConfigCreateBodyRunIntervalMinutesMax)
.optional()
.describe('Minutes between runs (30–43200). Defaults to 1440 (every 24 hours).'),
+ output_destinations: zod
+ .object({
+ slack: zod
+ .union([
+ zod.object({
+ integration_id: zod
+ .number()
+ .min(1)
+ .describe(
+ "ID of the Slack integration whose bot posts this scout's findings and reports."
+ ),
+ channel: zod
+ .string()
+ .max(signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneChannelMax)
+ .nullish()
+ .describe(
+ "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Slack destination for each emitted scout finding or report. Null or omitted disables Slack delivery.'
+ ),
+ })
+ .optional()
+ .describe('Destinations that receive each finding or report this scout emits. Empty by default.'),
run_cron_schedule: zod
.string()
.max(signalsScoutConfigCreateBodyRunCronScheduleMax)
@@ -451,7 +481,7 @@ export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod
)
/**
- * Tune one scout: change its schedule (rolling `run_interval_minutes`, or a cron `run_cron_schedule` that takes precedence when set), `enabled`, or `emit` (dry-run) posture. `skill_name` is fixed. Enabling records `enabled_by` and is activity-logged since it drives spend.
+ * Tune one scout: change its schedule (rolling `run_interval_minutes`, or a cron `run_cron_schedule` that takes precedence when set), `enabled`, or `emit` (dry-run) posture, or output destinations. `skill_name` is fixed. Enabling records `enabled_by` and is activity-logged since it drives spend.
* @summary Update a scout config
*/
export const SignalsScoutConfigUpdateParams = /* @__PURE__ */ zod.object({
@@ -468,6 +498,8 @@ export const signalsScoutConfigUpdateBodyRunIntervalMinutesMax = 43200
export const signalsScoutConfigUpdateBodyRunCronScheduleMax = 100
+export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneChannelMax = 255
+
export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod
.object({
enabled: zod
@@ -493,6 +525,36 @@ export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod
.describe(
"Optional five-field cron expression, e.g. '30 9 * * *' (daily at 09:30), '0 9,17 * * *' (twice daily), or '0 9 * * 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart. Set null to return to the rolling interval schedule."
),
+ output_destinations: zod
+ .object({
+ slack: zod
+ .union([
+ zod.object({
+ integration_id: zod
+ .number()
+ .min(1)
+ .describe(
+ "ID of the Slack integration whose bot posts this scout's findings and reports."
+ ),
+ channel: zod
+ .string()
+ .max(signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneChannelMax)
+ .nullish()
+ .describe(
+ "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Slack destination for each emitted scout finding or report. Null or omitted disables Slack delivery.'
+ ),
+ })
+ .optional()
+ .describe(
+ 'Destinations that receive each finding or report this scout emits. Pass an empty object to disable delivery.'
+ ),
})
.describe('Editable schedule, enablement, and emit posture for one scout config.')
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 05dd67aa49d9..23737ac959ed 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -513,6 +513,9 @@ const scoutConfigCreate = (): ToolBase<typeof ScoutConfigCreateSchema, Schemas.S
if (params.run_interval_minutes !== undefined) {
body['run_interval_minutes'] = params.run_interval_minutes
}
+ if (params.output_destinations !== undefined) {
+ body['output_destinations'] = params.output_destinations
+ }
if (params.run_cron_schedule !== undefined) {
body['run_cron_schedule'] = params.run_cron_schedule
}
@@ -594,6 +597,9 @@ const scoutConfigUpdate = (): ToolBase<typeof ScoutConfigUpdateSchema, WithPostH
if (params.run_cron_schedule !== undefined) {
body['run_cron_schedule'] = params.run_cron_schedule
}
+ if (params.output_destinations !== undefined) {
+ body['output_destinations'] = params.output_destinations
+ }
const result = await context.api.request<Schemas.SignalScoutConfig>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/configs/${encodeURIComponent(String(params.id))}/`,
@@ -994,6 +1000,9 @@ const signalsScoutConfigCreate = (): ToolBase<typeof SignalsScoutConfigCreateSch
if (params.run_interval_minutes !== undefined) {
body['run_interval_minutes'] = params.run_interval_minutes
}
+ if (params.output_destinations !== undefined) {
+ body['output_destinations'] = params.output_destinations
+ }
if (params.run_cron_schedule !== undefined) {
body['run_cron_schedule'] = params.run_cron_schedule
}
@@ -1084,6 +1093,9 @@ const signalsScoutConfigUpdate = (): ToolBase<
if (params.run_cron_schedule !== undefined) {
body['run_cron_schedule'] = params.run_cron_schedule
}
+ if (params.output_destinations !== undefined) {
+ body['output_destinations'] = params.output_destinations
+ }
const result = await context.api.request<Schemas.SignalScoutConfig>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/configs/${encodeURIComponent(String(params.id))}/`,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json
index b14d2febd197..22643ab5a29f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json
@@ -10,6 +10,43 @@
"description": "Whether this scout runs on its schedule. Defaults to true.",
"type": "boolean"
},
+ "output_destinations": {
+ "description": "Destinations that receive each finding or report this scout emits. Empty by default.",
+ "properties": {
+ "slack": {
+ "anyOf": [
+ {
+ "properties": {
+ "channel": {
+ "anyOf": [
+ {
+ "maxLength": 255,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ },
+ "integration_id": {
+ "description": "ID of the Slack integration whose bot posts this scout's findings and reports.",
+ "minimum": 1,
+ "type": "number"
+ }
+ },
+ "required": ["integration_id"],
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Slack destination for each emitted scout finding or report. Null or omitted disables Slack delivery."
+ }
+ },
+ "type": "object"
+ },
"run_cron_schedule": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json
index 37d5787ff6f4..d6d2ff4512ad 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json
@@ -13,6 +13,43 @@
"description": "A UUID string identifying this Signal scout config.",
"type": "string"
},
+ "output_destinations": {
+ "description": "Destinations that receive each finding or report this scout emits. Pass an empty object to disable delivery.",
+ "properties": {
+ "slack": {
+ "anyOf": [
+ {
+ "properties": {
+ "channel": {
+ "anyOf": [
+ {
+ "maxLength": 255,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ },
+ "integration_id": {
+ "description": "ID of the Slack integration whose bot posts this scout's findings and reports.",
+ "minimum": 1,
+ "type": "number"
+ }
+ },
+ "required": ["integration_id"],
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Slack destination for each emitted scout finding or report. Null or omitted disables Slack delivery."
+ }
+ },
+ "type": "object"
+ },
"run_cron_schedule": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json
index b14d2febd197..22643ab5a29f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json
@@ -10,6 +10,43 @@
"description": "Whether this scout runs on its schedule. Defaults to true.",
"type": "boolean"
},
+ "output_destinations": {
+ "description": "Destinations that receive each finding or report this scout emits. Empty by default.",
+ "properties": {
+ "slack": {
+ "anyOf": [
+ {
+ "properties": {
+ "channel": {
+ "anyOf": [
+ {
+ "maxLength": 255,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ },
+ "integration_id": {
+ "description": "ID of the Slack integration whose bot posts this scout's findings and reports.",
+ "minimum": 1,
+ "type": "number"
+ }
+ },
+ "required": ["integration_id"],
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Slack destination for each emitted scout finding or report. Null or omitted disables Slack delivery."
+ }
+ },
+ "type": "object"
+ },
"run_cron_schedule": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json
index 37d5787ff6f4..d6d2ff4512ad 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json
@@ -13,6 +13,43 @@
"description": "A UUID string identifying this Signal scout config.",
"type": "string"
},
+ "output_destinations": {
+ "description": "Destinations that receive each finding or report this scout emits. Pass an empty object to disable delivery.",
+ "properties": {
+ "slack": {
+ "anyOf": [
+ {
+ "properties": {
+ "channel": {
+ "anyOf": [
+ {
+ "maxLength": 255,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ },
+ "integration_id": {
+ "description": "ID of the Slack integration whose bot posts this scout's findings and reports.",
+ "minimum": 1,
+ "type": "number"
+ }
+ },
+ "required": ["integration_id"],
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Slack destination for each emitted scout finding or report. Null or omitted disables Slack delivery."
+ }
+ },
+ "type": "object"
+ },
"run_cron_schedule": {
"anyOf": [
{