:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(self-driving): add project and role-specific agent steering (#116137)
Georgiy Tarasov6e104bf4f143
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d631c7519755..7bc5ba233a65 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -11006,6 +11006,14 @@ snapshots:hash: v1.k794b7964.88fa6281da94dbad16ae7c7e1f36219eb0b063d7b665ee0ba29d6238bd21824a.jZFwP-MM1kveuuaJoeKjUQj5lsW28UIbhIPd14zIvaQscenes-app-identitymatching--identity-matching-paid-attribution--light:hash: v1.k794b7964.f03553d78131d130ceaeb2df5f49c72e4e0ffde0d2db48d9fa8d97677490eeb7.WopQgucFAMz-6URparfwrJLeb30wxWhND35g-bo_Cxc+ scenes-app-inbox-agent-steering--configured--dark:+ hash: v1.k794b7964.a6a976d812d8c5cc144901de1f6256dc5762c545d4465f1a677a158a8203f27e.4_xn1UoyEJbr8R_A5Ke5YpoXcUyB7CjxmWDgPflOlHU+ scenes-app-inbox-agent-steering--configured--light:+ hash: v1.k794b7964.fee3126adeb13eb24aff1671803ff0501bc548f1304e28e0cc01004e782a5c04.xft5BqCslTAHqz-NUSWT0aZgPxWBVHHrTbLU5NE9JV4+ scenes-app-inbox-agent-steering--empty--dark:+ hash: v1.k794b7964.4a86dfd000a181a1ef94a27e95f7312abc3906042529a3eddccdef2bd499e616.tZ9vwMy1hM7FQMLslbJyA3_LCGPjPoc1LmCU2bFxoBA+ scenes-app-inbox-agent-steering--empty--light:+ hash: v1.k794b7964.8adf1aa893baffeccf09c959ceb43997a3d0dd7b802f915f683721bb3178811c.yiCitLDCxycb1PBAgQTZ4xqjtSr02cPmmNj0VOb8bu8scenes-app-inbox-badges--all-badges--dark:hash: v1.k794b7964.53905d82a430d879b42b90781915bc47ada17d1634f6145b5b141d0e6e6204bc.oEkMuoSWfz-n8QLBO2OpyTDUxhKzVOi9Tvb0erHRKi8scenes-app-inbox-badges--all-badges--light:@@ -11359,9 +11367,9 @@ snapshots:scenes-app-inbox-scene--self-driving-verdict-pending--light:hash: v1.k794b7964.96cdbec6c78e8daedb06be4a0134093efcd5838af69e6e7d1722a3892cf561b5.iJ2K0zNhOVgGAPY6JvduyhDBODMwk-CN7_mAdB8scOgscenes-app-inbox-scene--settings--dark:- hash: v1.k794b7964.bc6182512f1a869ea994e7cef98731a96730d9bae156279e154ee73404674b1d.2RklYWoL5d3jqDKf1UHoQHO9dRxrTKeU8qZHAS7HE2M+ hash: v1.k794b7964.3a09b371dfcc049acc97eb1e2682d0fd201d38c4da0bffd99c604e2e64b8b18a.DDoXBuROBx-ORO785uDMT76XnmJMVgQ-Vjn6RKV8UDEscenes-app-inbox-scene--settings--light:- hash: v1.k794b7964.960cbf32355909e10651cc28d7e7f9f5ebc9095bd30f040a31e6c922399ba415.eDxCx3M_sNwJKuBuo5GBxSZH3iCojFsRRb9Hjcmlljs+ hash: v1.k794b7964.dac3c4ea75724904b985cd5cce6e172b0f96a0dff0a73765c64fc6ca2d9f4e7c.y6MRlO5cx7JT44gZbZ4DP1nYyE-gk-XSbciuFxtqaXIscenes-app-inbox-scene--triage--dark:hash: v1.k794b7964.77e43b36fdcd81befecf4de80e489050f525840924ec6ddef37c23a9179dbe8a.B3qkZFYBncFaPn2EBg4cBoYu_LIwW29imNwBdLXF5eoscenes-app-inbox-scene--triage--light:@@ -13995,9 +14003,9 @@ snapshots:scenes-app-settings-environment--settings-environment-activity-logs--light:hash: v1.k794b7964.de8dbf30bb81f750a69b2defaa2bd2b3a4220aabf8a61a7a2398649692153059.NUqLmVSIt8TCiWzubIwEDrdObbZR8wrD3acZTxCeiFgscenes-app-settings-environment--settings-environment-agent-instructions--dark:- hash: v1.k794b7964.76d3bb8634330d3ed70f09b902ad46746901d2c73a7a13e3e1f483b03cafceb0.WyXlq7w6s83nYoX8RQ-9Xdj1fpCFG6s4-tgUttwypeg+ hash: v1.k794b7964.cc500a6329ddf9175271350ba4b2d2e336bd93d9e09243e9dd2cc9fbba2baf87.9HdYpurrKQAjghcgG2Xm9v5mHpxeHqonGHM4w3TGqMIscenes-app-settings-environment--settings-environment-agent-instructions--light:- hash: v1.k794b7964.00dc76db396de42eaf972dbf28987985767db39af78fdf77c11b980336070d46.Me0QFKNQdODrHjzr-Mb1Qq35obQoUK6dhnrDT-nmxkA+ hash: v1.k794b7964.f5b9c4bd2219dd2ea9871bbd718f54c83f8565e839fdac7e7d61e0d2838fea5c.u5fQ60DQeJYk1P-Xjjg3RDSH4W3yZKCu_1kesA7v-ewscenes-app-settings-environment--settings-environment-ai-subscriptions-codex-connect-modal--dark:hash: v1.k794b7964.a736395d4f5e26d3df100c0620467dcf3d0f4d8c68e009238e19f96ca0ded1c2.oKore0IeXbtNi-INrktyldmjfaDYFu3qoykEMwtweUkscenes-app-settings-environment--settings-environment-ai-subscriptions-codex-connect-modal--light:diff --git a/frontend/src/lib/lemon-ui/LemonTextArea/LemonTextArea.tsx b/frontend/src/lib/lemon-ui/LemonTextArea/LemonTextArea.tsxindex 15aead876b5f..8a48a54dbcfd 100644--- a/frontend/src/lib/lemon-ui/LemonTextArea/LemonTextArea.tsx+++ b/frontend/src/lib/lemon-ui/LemonTextArea/LemonTextArea.tsx@@ -35,6 +35,8 @@ interface LemonTextAreaPropsBase extends Pick<* Used for informational notes like whether markdown content is supported*/rightFooter?: ReactElement+ /** Replaces the built-in actions and character count. */+ footer?: ReactElement}export interface LemonTextAreaWithCmdEnterProps extends LemonTextAreaPropsBase {@@ -62,6 +64,7 @@ export const LemonTextArea = React.forwardRef<HTMLTextAreaElement, LemonTextAreastopPropagation,actions,rightFooter,+ footer,autoFocus,hideFocus = false,...textProps@@ -71,7 +74,7 @@ export const LemonTextArea = React.forwardRef<HTMLTextAreaElement, LemonTextAreaconst _ref = useRef<HTMLTextAreaElement | null>(null)const textRef = ref || _ref- const hasFooter = (actions || []).length || textProps.maxLength || rightFooter+ const hasFooter = footer || (actions || []).length || textProps.maxLength || rightFooterconst textLength = textProps.value?.length ?? 0@@ -109,21 +112,22 @@ export const LemonTextArea = React.forwardRef<HTMLTextAreaElement, LemonTextAreaautoFocus={!!autoFocus}{...textProps}/>- {hasFooter ? (- <div className="flex flex-row gap-x-2 justify-between border-l border-r border-b rounded-b px-1">- <div className="flex flex-row items-center">{actions}</div>- <div className="flex flex-row gap-x-1 items-center">- <div className="flex flex-row gap-x-1 justify-end flex-grow">- {rightFooter}- {textProps.maxLength ? (- <div className={cn('text-sm', textLength >= textProps?.maxLength && 'text-error')}>- {textLength} / {textProps.maxLength}- </div>- ) : null}+ {footer ??+ (hasFooter ? (+ <div className="flex flex-row gap-x-2 justify-between border-l border-r border-b rounded-b px-1">+ <div className="flex flex-row items-center">{actions}</div>+ <div className="flex flex-row gap-x-1 items-center">+ <div className="flex flex-row gap-x-1 justify-end flex-grow">+ {rightFooter}+ {textProps.maxLength ? (+ <div className={cn('text-sm', textLength >= textProps?.maxLength && 'text-error')}>+ {textLength} / {textProps.maxLength}+ </div>+ ) : null}+ </div></div></div>- </div>- ) : null}+ ) : null)}</div>)})diff --git a/frontend/src/scenes/settings/environment/AgentPersonalInstructionsSettings.tsx b/frontend/src/scenes/settings/environment/AgentPersonalInstructionsSettings.tsxindex e669b841388e..77c389cbf85c 100644--- a/frontend/src/scenes/settings/environment/AgentPersonalInstructionsSettings.tsx+++ b/frontend/src/scenes/settings/environment/AgentPersonalInstructionsSettings.tsx@@ -18,6 +18,7 @@ export function AgentPersonalInstructionsSettings(): JSX.Element {onChange={setPersonalDraft}onSave={submitPersonalDraft}dataAttr="agent-personal-instructions"+ ariaLabel="My instructions"/>)}diff --git a/frontend/src/scenes/settings/environment/AgentProjectInstructionsSettings.tsx b/frontend/src/scenes/settings/environment/AgentProjectInstructionsSettings.tsxindex 6eeebfe77738..888be907ae44 100644--- a/frontend/src/scenes/settings/environment/AgentProjectInstructionsSettings.tsx+++ b/frontend/src/scenes/settings/environment/AgentProjectInstructionsSettings.tsx@@ -1,12 +1,18 @@import { useActions, useValues } from 'kea'+import { IconArrowRight } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'-import { TeamMembershipLevel } from 'lib/constants'+import { FEATURE_FLAGS, TeamMembershipLevel } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { urls } from 'scenes/urls'import { agentInstructionsSettingsLogic } from './agentInstructionsSettingsLogic'import { InstructionsEditor } from './InstructionsEditor'export function AgentProjectInstructionsSettings(): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)const { projectInstructions, projectValue, projectDirty, projectInstructionsLoading } =useValues(agentInstructionsSettingsLogic)const { setProjectDraft, submitProjectDraft } = useActions(agentInstructionsSettingsLogic)@@ -27,7 +33,20 @@ export function AgentProjectInstructionsSettings(): JSX.Element {onSave={submitProjectDraft}restrictionReason={restrictionReason}dataAttr="agent-project-instructions"+ ariaLabel="Project instructions"/>+ {featureFlags[FEATURE_FLAGS.INBOX_REDESIGN] && (+ <LemonButton+ className="self-start"+ type="tertiary"+ size="small"+ to={`${urls.inbox('settings')}#steering`}+ sideIcon={<IconArrowRight aria-hidden />}+ data-attr="agent-project-instructions-self-driving"+ >+ Customize Self-driving agents+ </LemonButton>+ )}{restrictionReason ? (<p className="text-secondary mb-0">Only project admins can change these. You can still add your own instructions below.diff --git a/frontend/src/scenes/settings/environment/InstructionsEditor.tsx b/frontend/src/scenes/settings/environment/InstructionsEditor.tsxindex 5bab7c47959f..52d40453a82b 100644--- a/frontend/src/scenes/settings/environment/InstructionsEditor.tsx+++ b/frontend/src/scenes/settings/environment/InstructionsEditor.tsx@@ -1,5 +1,7 @@import { LemonButton, LemonSkeleton, LemonTextArea } from '@posthog/lemon-ui'+import { cn } from 'lib/utils/css-classes'+// Matches AGENT_INSTRUCTIONS_MAX_LENGTH on the backend, which rejects anything longer.const MAX_LENGTH = 20_000@@ -11,8 +13,11 @@ interface InstructionsEditorProps {placeholder: stringonChange: (value: string) => voidonSave: () => void+ onDiscard?: () => void+ discardDataAttr?: stringrestrictionReason?: string | nulldataAttr: string+ ariaLabel?: string}export function InstructionsEditor({@@ -23,8 +28,11 @@ export function InstructionsEditor({placeholder,onChange,onSave,+ onDiscard,+ discardDataAttr,restrictionReason,dataAttr,+ ariaLabel,}: InstructionsEditorProps): JSX.Element {if (stored === null) {return loading ? (@@ -35,28 +43,53 @@ export function InstructionsEditor({}return (- <div className="flex flex-col gap-2">- <LemonTextArea- value={value}- onChange={onChange}- placeholder={placeholder}- minRows={6}- maxRows={24}- maxLength={MAX_LENGTH}- disabled={!!restrictionReason || loading}- data-attr={`${dataAttr}-input`}- />- <div className="flex flex-wrap gap-2">- <LemonButton- type="primary"- onClick={onSave}- loading={loading}- disabledReason={restrictionReason ?? (dirty ? undefined : 'No changes to save')}- data-attr={`${dataAttr}-save`}- >- Save- </LemonButton>- </div>- </div>+ <LemonTextArea+ className="[&>textarea]:p-4 [&>textarea]:leading-relaxed"+ value={value}+ onChange={onChange}+ placeholder={placeholder}+ minRows={7}+ maxRows={24}+ maxLength={MAX_LENGTH}+ disabled={!!restrictionReason || loading}+ data-attr={`${dataAttr}-input`}+ aria-label={ariaLabel}+ footer={+ <div className="flex flex-wrap items-center justify-between gap-2 rounded-b border-t bg-surface-secondary px-3 py-2">+ <span+ className={cn(+ 'text-xs tabular-nums',+ value.length >= MAX_LENGTH ? 'text-danger' : 'text-secondary'+ )}+ translate="no"+ >+ {value.length.toLocaleString()} / {MAX_LENGTH.toLocaleString()}+ </span>+ <div className="ml-auto flex flex-wrap items-center gap-1">+ {dirty && (+ <LemonButton+ type="tertiary"+ size="small"+ onClick={onDiscard ?? (() => onChange(stored))}+ disabled={!!restrictionReason || loading}+ data-attr={discardDataAttr ?? `${dataAttr}-discard`}+ >+ Discard+ </LemonButton>+ )}+ <LemonButton+ type="primary"+ size="small"+ onClick={onSave}+ loading={loading}+ disabledReason={restrictionReason ?? (dirty ? undefined : 'No changes to save')}+ data-attr={`${dataAttr}-save`}+ >+ Save+ </LemonButton>+ </div>+ </div>+ }+ />)}diff --git a/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx b/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsxindex 339a7897663e..f986edf3e16d 100644--- a/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx+++ b/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx@@ -329,6 +329,7 @@ export const SettingsEnvironmentAiSubscriptionsCodexConnectModal: Story = {export const SettingsEnvironmentAgentInstructions: Story = {args: { sectionId: 'environment-task-agent-instructions' },+ parameters: { featureFlags: [...STORYBOOK_FEATURE_FLAGS, FEATURE_FLAGS.INBOX_REDESIGN] },decorators: [mswDecorator({get: {diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 8bbf27a4bd0c..0b4b2f338ace 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -490,6 +490,9 @@ field_name_overrides: dict[AuditableScope, dict[str, str]] = {"github_issue_writeback_enabled": "comment back on GitHub issues","pull_request_label_enabled": "label self-driving PRs","pull_request_label": "self-driving PR label",+ "scout_instructions": "scout instructions",+ "research_instructions": "research instructions",+ "implementation_instructions": "implementation instructions",},"OAuthApplication": {"_provisioning_config": "provisioning config",diff --git a/products/signals/backend/agent_instructions.py b/products/signals/backend/agent_instructions.pynew file mode 100644index 000000000000..986a32508db4--- /dev/null+++ b/products/signals/backend/agent_instructions.py@@ -0,0 +1,47 @@+from enum import StrEnum++from products.signals.backend.models import SignalTeamConfig++AGENT_STEERING_MAX_LENGTH = 20_000+++class SignalAgentRole(StrEnum):+ SCOUT = "scout"+ RESEARCH = "research"+ IMPLEMENTATION = "implementation"+++STEERING_FIELDS = {+ SignalAgentRole.SCOUT: "scout_instructions",+ SignalAgentRole.RESEARCH: "research_instructions",+ SignalAgentRole.IMPLEMENTATION: "implementation_instructions",+}+++class SignalAgentInstructions:+ @staticmethod+ def role_for_run(origin_product: str, ai_stage: str | None) -> SignalAgentRole | None:+ if origin_product == "signals_scout":+ return SignalAgentRole.SCOUT+ if origin_product == "signal_report":+ if ai_stage == "research":+ return SignalAgentRole.RESEARCH+ if ai_stage == "implementation":+ return SignalAgentRole.IMPLEMENTATION+ return None++ def resolve(self, team_id: int, origin_product: str, ai_stage: str | None) -> str:+ role = self.role_for_run(origin_product, ai_stage)+ if role is None:+ return ""+ instructions = (+ SignalTeamConfig.objects.filter(team_id=team_id).values_list(STEERING_FIELDS[role], flat=True).first() or ""+ ).strip()+ if not instructions:+ return ""+ return (+ f"# Self-driving {role.value} instructions\n\n"+ f"You are part of PostHog Self-driving. Your role is {role.value}. "+ "Apply these role-specific instructions together with the project instructions.\n\n"+ f"{instructions}"+ )diff --git a/products/signals/backend/facade/agent_instructions.py b/products/signals/backend/facade/agent_instructions.pynew file mode 100644index 000000000000..2ffbdbada071--- /dev/null+++ b/products/signals/backend/facade/agent_instructions.py@@ -0,0 +1,5 @@+from products.signals.backend.agent_instructions import SignalAgentInstructions+++def get_agent_instructions(*, team_id: int, origin_product: str, ai_stage: str | None) -> str:+ return SignalAgentInstructions().resolve(team_id, origin_product, ai_stage)diff --git a/products/signals/backend/migrations/0175_signalteamconfig_agent_instructions.py b/products/signals/backend/migrations/0175_signalteamconfig_agent_instructions.pynew file mode 100644index 000000000000..aebd6e9dbdd0--- /dev/null+++ b/products/signals/backend/migrations/0175_signalteamconfig_agent_instructions.py@@ -0,0 +1,25 @@+# Generated by Django 5.2.18 on 2026-10-13 12:54++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("signals", "0174_signalreport_search_trgm_indexes")]++ operations = [+ migrations.AddField(+ model_name="signalteamconfig",+ name="implementation_instructions",+ field=models.TextField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="signalteamconfig",+ name="research_instructions",+ field=models.TextField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="signalteamconfig",+ name="scout_instructions",+ field=models.TextField(blank=True, null=True),+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex fd3571ac8f3a..4e33c20491c3 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0174_signalreport_search_trgm_indexes+0175_signalteamconfig_agent_instructionsdiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 2d2c8af44a74..38c56bdf70f6 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -200,6 +200,9 @@ class SignalTeamConfig(ModelActivityMixin, UUIDModel):default_autostart_priority = models.CharField(max_length=2, choices=AutonomyPriority, default=AutonomyPriority.P4)default_slack_notification_channel = models.CharField(max_length=255, null=True, blank=True)autostart_base_branches = models.JSONField(default=dict, blank=True)+ scout_instructions = models.TextField(null=True, blank=True)+ research_instructions = models.TextField(null=True, blank=True)+ implementation_instructions = models.TextField(null=True, blank=True)# Daily cap on reports surfacing to the inbox, counted against SignalReport.first_visible_at# within the project-timezone day. Once reached, the whole generation pipeline pauses until# local midnight (see daily_limit.py). Null means unlimited.diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex bb3d36a0a87b..450c5844f510 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -20,6 +20,7 @@ from posthog.models import Team, Userfrom posthog.models.integration import Integration, is_supported_external_issue_providerfrom products.signals.backend import contracts+from products.signals.backend.agent_instructions import AGENT_STEERING_MAX_LENGTH, STEERING_FIELDSfrom products.signals.backend.billing import REFUND_INELIGIBILITY_REASONS, refund_ineligibility_reasonfrom products.signals.backend.contracts import (DEFAULT_NOT_ACTIONABLE_KEY,@@ -356,6 +357,24 @@ class _AutostartBaseBranchesField(serializers.DictField):# singleton. Without this drf-spectacular types the response as a paginated list.@extend_schema_serializer(many=False)class SignalTeamConfigSerializer(serializers.ModelSerializer):+ scout_instructions = serializers.CharField(+ required=False,+ allow_blank=True,+ max_length=AGENT_STEERING_MAX_LENGTH,+ help_text="Project-level instructions added to every scout run, alongside project instructions and the scout's own brief. Blank uses project instructions only.",+ )+ research_instructions = serializers.CharField(+ required=False,+ allow_blank=True,+ max_length=AGENT_STEERING_MAX_LENGTH,+ help_text="Project-level instructions for the dedicated signal report research stage. Other agent roles do not receive them. Blank uses project instructions only.",+ )+ implementation_instructions = serializers.CharField(+ required=False,+ allow_blank=True,+ max_length=AGENT_STEERING_MAX_LENGTH,+ help_text="Project-level instructions for agents implementing signal reports. Other agent roles do not receive them. Blank uses project instructions only.",+ )issue_tracking_integration = TeamScopedPrimaryKeyRelatedField(queryset=Integration.objects.all(),required=False,@@ -442,6 +461,12 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):))+ def to_representation(self, instance: SignalTeamConfig) -> dict[str, object]:+ representation = dict(super().to_representation(instance))+ for field in STEERING_FIELDS.values():+ representation[field] = representation[field] or ""+ return representation+def validate_pull_request_label(self, value: str | None) -> str | None:# One stored shape for "use the default", so a team that clears the box does not get a# label GitHub would refuse.@@ -478,6 +503,9 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):"default_autostart_priority","default_slack_notification_channel","autostart_base_branches",+ "scout_instructions",+ "research_instructions",+ "implementation_instructions","issue_tracking_integration","issue_tracking_config","max_reports_per_day",diff --git a/products/signals/backend/test/test_signal_team_config_api.py b/products/signals/backend/test/test_signal_team_config_api.pyindex 5bf6a0adc8cc..c8ecee44abc1 100644--- a/products/signals/backend/test/test_signal_team_config_api.py+++ b/products/signals/backend/test/test_signal_team_config_api.py@@ -1,6 +1,7 @@from datetime import UTC, datetimefrom posthog.test.base import APIBaseTest+from unittest.mock import patchfrom django.test import SimpleTestCase@@ -8,11 +9,14 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.organization import OrganizationMembershipfrom posthog.models.team.extensions import get_or_create_team_extension+from products.signals.backend.agent_instructions import AGENT_STEERING_MAX_LENGTH, STEERING_FIELDSfrom products.signals.backend.facade.api import set_default_slack_notification_channelfrom products.signals.backend.models import SignalReport, SignalTeamConfigfrom products.signals.backend.serializers import MAX_AUTOSTART_BASE_BRANCH_ENTRIES, SignalTeamConfigSerializer+from products.signals.backend.views import SignalTeamConfigViewSetclass TestSignalTeamConfigAPI(APIBaseTest):@@ -26,11 +30,61 @@ class TestSignalTeamConfigAPI(APIBaseTest):def _activity(self) -> list[ActivityLog]:return list(ActivityLog.objects.filter(team_id=self.team.pk, scope="SignalTeamConfig").order_by("created_at"))- def test_get_config_includes_default_slack_notification_channel(self):+ def test_admin_can_save_and_clear_roles_independently(self) -> None:+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ initial = {field: f"Instructions for {role}." for role, field in STEERING_FIELDS.items()}+ response = self.client.post(self._url(), initial, format="json")+ assert response.status_code == 200, response.content+ assert all(response.json()[field] == text for field, text in initial.items())++ response = self.client.post(self._url(), {"research_instructions": ""}, format="json")+ assert response.status_code == 200, response.content+ saved = self.client.get(self._url()).json()+ assert saved["research_instructions"] == ""+ assert saved["scout_instructions"] == initial["scout_instructions"]+ assert saved["implementation_instructions"] == initial["implementation_instructions"]+ entries = self._activity()+ assert len(entries) == 2+ assert entries[0].user == self.user+ assert entries[0].detail is not None+ assert {change["field"] for change in entries[0].detail["changes"]} == {+ "scout instructions",+ "research instructions",+ "implementation instructions",+ }++ def test_member_can_read_but_not_change_steering(self) -> None:+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ assert self.client.get(self._url()).status_code == 200+ for field in STEERING_FIELDS.values():+ response = self.client.post(self._url(), {field: "New rules."}, format="json")+ assert response.status_code == 403, response.content+ assert self.client.post(self._url(), {"autostart_enabled": False}, format="json").status_code == 200++ def test_steering_save_preserves_a_concurrent_autonomy_change(self) -> None:+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ stale_config = SignalTeamConfig.objects.get(pk=self.config.pk)+ self.config.autostart_enabled = False+ self.config.save(update_fields=["autostart_enabled"])++ with patch.object(SignalTeamConfigViewSet, "_get_config", return_value=stale_config):+ response = self.client.post(self._url(), {"research_instructions": "Check product intent."}, format="json")+ assert response.status_code == 200, response.content+ self.config.refresh_from_db()+ assert self.config.autostart_enabled is False+ assert self.config.research_instructions == "Check product intent."++ def test_get_config_includes_default_settings(self):response = self.client.get(self._url())data = response.json()assert response.status_code == status.HTTP_200_OK, dataassert data["default_slack_notification_channel"] is None+ for field in STEERING_FIELDS.values():+ assert getattr(self.config, field) is None+ assert data[field] == ""assert data["default_autostart_priority"] == "P4"# Null until a team explicitly opts out; the guard treats null as autostart-on.assert data["autostart_enabled"] is None@@ -324,6 +378,14 @@ class TestSignalTeamConfigAPI(APIBaseTest):class TestSignalTeamConfigSerializerValidation(SimpleTestCase):+ @parameterized.expand(list(STEERING_FIELDS.values()))+ def test_steering_rejects_oversized_instructions(self, field: str) -> None:+ serializer = SignalTeamConfigSerializer(data={field: "x" * AGENT_STEERING_MAX_LENGTH}, partial=True)+ assert serializer.is_valid(), serializer.errors+ serializer = SignalTeamConfigSerializer(data={field: "x" * (AGENT_STEERING_MAX_LENGTH + 1)}, partial=True)+ assert not serializer.is_valid()+ assert field in serializer.errors+# No DB needed: these are field-level rejections that short-circuit in to_internal_value.# The endpoint wiring guard lives in TestSignalTeamConfigAPI.@parameterized.expand(diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex f0bf76c6730e..087d8578f682 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -72,12 +72,19 @@ from posthog.models.github_integration_base import GitHubIntegrationBase, PullRefrom posthog.models.integration import GitHubIntegration, Integrationfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.user_integration import ReauthorizationRequired, UserGitHubIntegration, UserIntegration-from posthog.permissions import APIScopePermission, get_authenticator_scoped_team_ids, get_authenticator_scopes+from posthog.oauth_provenance import is_sandbox_oauth_request+from posthog.permissions import (+ APIScopePermission,+ TeamMemberStrictManagementPermission,+ get_authenticator_scoped_team_ids,+ get_authenticator_scopes,+)from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottlefrom posthog.temporal.common.client import sync_connectfrom posthog.user_permissions import UserPermissionsfrom products.data_warehouse.backend.facade.api import trigger_external_data_workflow+from products.signals.backend.agent_instructions import STEERING_FIELDSfrom products.signals.backend.artefact_schemas import (DISMISSAL_NOTE_MAX_LENGTH,DISMISSAL_REASON_WRONG_REPO,@@ -574,6 +581,20 @@ class SignalSourceConfigViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)+class SignalSteeringPermission(TeamMemberStrictManagementPermission):+ def has_permission(self, request: Request, view: APIView) -> bool:+ if (+ request.method in ("GET", "HEAD", "OPTIONS")+ or not isinstance(request.data, dict)+ or not any(field in request.data for field in STEERING_FIELDS.values())+ ):+ return True+ if is_sandbox_oauth_request(request):+ self.message = "Task agents cannot modify steering instructions."+ return False+ return super().has_permission(request, view)++class SignalTeamConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"""Team-level signal autonomy config (singleton per team).@@ -582,7 +603,7 @@ class SignalTeamConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"""authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]- permission_classes = [IsAuthenticated, APIScopePermission]+ permission_classes = [IsAuthenticated, APIScopePermission, SignalSteeringPermission]serializer_class = SignalTeamConfigSerializerqueryset = SignalTeamConfig.objects.all()scope_object = "task"@@ -612,9 +633,12 @@ class SignalTeamConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)def create(self, request: Request, *args, **kwargs) -> Response:config = self._get_config()- serializer = self.get_serializer(config, data=request.data, partial=True)- serializer.is_valid(raise_exception=True)- serializer.save()+ with transaction.atomic():+ # Independent settings editors share this row; refetch under lock to keep concurrent edits.+ config = SignalTeamConfig.objects.select_for_update().get(pk=config.pk, team_id=self.team.pk)+ serializer = self.get_serializer(config, data=request.data, partial=True)+ serializer.is_valid(raise_exception=True)+ serializer.save()return Response(serializer.data)diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 36a764440f44..b8af40daafaf 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -50,6 +50,21 @@ export interface SignalTeamConfigApi {default_slack_notification_channel?: string | null/** Per-repository base branch overrides for auto-started inbox PRs, keyed by 'organization/repository'. The branch is what the auto-PR targets; omit a repo (or send {}) to keep targeting the repo default branch. */autostart_base_branches?: SignalTeamConfigApiAutostartBaseBranches+ /**+ * Project-level instructions added to every scout run, alongside project instructions and the scout's own brief. Blank uses project instructions only.+ * @maxLength 20000+ */+ scout_instructions?: string+ /**+ * Project-level instructions for the dedicated signal report research stage. Other agent roles do not receive them. Blank uses project instructions only.+ * @maxLength 20000+ */+ research_instructions?: string+ /**+ * Project-level instructions for agents implementing signal reports. Other agent roles do not receive them. Blank uses project instructions only.+ * @maxLength 20000+ */+ implementation_instructions?: string/*** Connected GitHub, GitLab, Linear, or Jira integration that self-driving opens a tracker issue in for each pull request it makes. Null turns tracker issues off, which is the default.* @nullablediff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex ccaabef84dd5..748bc13240c2 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -17,6 +17,12 @@ export const signalsConfigCreateBodyDefaultSlackNotificationChannelMax = 255export const signalsConfigCreateBodyAutostartBaseBranchesMaxOne = 255+export const signalsConfigCreateBodyScoutInstructionsMax = 20000++export const signalsConfigCreateBodyResearchInstructionsMax = 20000++export const signalsConfigCreateBodyImplementationInstructionsMax = 20000+export const signalsConfigCreateBodyIssueTrackingConfigMaxOne = 255export const signalsConfigCreateBodyMaxReportsPerDayMax = 2147483647@@ -47,6 +53,27 @@ export const SignalsConfigCreateBody = /* @__PURE__ */ zod.object({.describe("Per-repository base branch overrides for auto-started inbox PRs, keyed by 'organization\/repository'. The branch is what the auto-PR targets; omit a repo (or send {}) to keep targeting the repo default branch."),+ scout_instructions: zod+ .string()+ .max(signalsConfigCreateBodyScoutInstructionsMax)+ .optional()+ .describe(+ "Project-level instructions added to every scout run, alongside project instructions and the scout's own brief. Blank uses project instructions only."+ ),+ research_instructions: zod+ .string()+ .max(signalsConfigCreateBodyResearchInstructionsMax)+ .optional()+ .describe(+ 'Project-level instructions for the dedicated signal report research stage. Other agent roles do not receive them. Blank uses project instructions only.'+ ),+ implementation_instructions: zod+ .string()+ .max(signalsConfigCreateBodyImplementationInstructionsMax)+ .optional()+ .describe(+ 'Project-level instructions for agents implementing signal reports. Other agent roles do not receive them. Blank uses project instructions only.'+ ),issue_tracking_integration: zod.number().nullish()diff --git a/products/signals/frontend/inbox/components/config/AgentSteeringSection.stories.tsx b/products/signals/frontend/inbox/components/config/AgentSteeringSection.stories.tsxnew file mode 100644index 000000000000..856ad0a8ea01--- /dev/null+++ b/products/signals/frontend/inbox/components/config/AgentSteeringSection.stories.tsx@@ -0,0 +1,53 @@+import type { Meta, StoryObj } from '@storybook/react'++import { mswDecorator } from '~/mocks/browser'++import type { SignalTeamConfigApi } from '../../../generated/api.schemas'+import { AgentSteeringSection } from './AgentSteeringSection'++const config = {+ scout_instructions: 'Focus on onboarding failures. Exclude demo accounts from impact estimates.',+ research_instructions: 'Confirm whether the behavior is intentional before proposing a fix.',+ implementation_instructions: 'Keep changes focused. Add regression coverage and open draft pull requests.',+}++const meta: Meta<typeof AgentSteeringSection> = {+ title: 'Scenes-App/Inbox/Agent steering',+ component: AgentSteeringSection,+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:id/signals/config/': config,+ },+ post: {+ '/api/projects/:id/signals/config/': async ({ request }) => [+ 200,+ { ...config, ...((await request.json()) as SignalTeamConfigApi) },+ ],+ },+ }),+ (Story) => (+ <div className="max-w-160">+ <Story />+ </div>+ ),+ ],+}+export default meta+type Story = StoryObj<typeof AgentSteeringSection>++export const Configured: Story = {}++export const Empty: Story = {+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:id/signals/config/': {+ scout_instructions: '',+ research_instructions: '',+ implementation_instructions: '',+ },+ },+ }),+ ],+}diff --git a/products/signals/frontend/inbox/components/config/AgentSteeringSection.tsx b/products/signals/frontend/inbox/components/config/AgentSteeringSection.tsxnew file mode 100644index 000000000000..3875fb92fc3d--- /dev/null+++ b/products/signals/frontend/inbox/components/config/AgentSteeringSection.tsx@@ -0,0 +1,146 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'++import { IconCode, IconCompass, IconSearch } from '@posthog/icons'+import { LemonBadge, LemonButton, LemonTabs, Link } from '@posthog/lemon-ui'++import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { TeamMembershipLevel } from 'lib/constants'+import { useAnchor } from 'lib/hooks/useAnchor'+import { InstructionsEditor } from 'scenes/settings/environment/InstructionsEditor'+import { urls } from 'scenes/urls'++import { SteeringRole, agentSteeringLogic } from '../../logics/agentSteeringLogic'+import { SettingsSection } from '../tabs/SettingsSection'++export function AgentSteeringSection(): JSX.Element {+ const { location } = useValues(router)+ useAnchor(location.hash === '#steering' ? location.hash : '')+ const { selectedRole, storedInstructions, instructions, instructionsDirty, steeringConfigLoading, dirtyRoles } =+ useValues(agentSteeringLogic)+ const { selectRole, setDraft, discardDraft, submitInstructions, loadSteeringConfig } =+ useActions(agentSteeringLogic)+ const restrictionReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })+ const roles: Record<SteeringRole, { title: string; description: string; placeholder: string }> = {+ scout: {+ title: 'Scout instructions',+ description:+ 'Scouts explore product data and connected sources, find problems and opportunities, and create signals or reports.',+ placeholder: 'For example: Focus on onboarding failures. Exclude demo accounts from impact estimates.',+ },+ research: {+ title: 'Research instructions',+ description: 'Investigate signals, assess priority, and write reports.',+ placeholder: 'For example: Confirm whether the behavior is intentional before proposing a fix.',+ },+ implementation: {+ title: 'Implementation instructions',+ description:+ 'Implementation agents turn reports into code changes, run checks, open pull requests, and address review feedback.',+ placeholder: 'For example: Keep changes focused. Add regression coverage and open draft pull requests.',+ },+ }+ const role = roles[selectedRole]++ return (+ <SettingsSection+ id="steering"+ title="Steering"+ description={+ <>+ Guide each agent's work in addition to your{' '}+ <Link+ to={urls.settings('environment-task-agent-instructions', 'task-agent-project-instructions')}+ data-attr="signals-steering-project-instructions"+ >+ project instructions+ </Link>+ .+ </>+ }+ >+ <div>+ <LemonTabs+ activeKey={selectedRole}+ onChange={selectRole}+ size="small"+ tabs={[+ {+ key: 'research',+ label: (+ <span className="flex items-center gap-1">+ <IconSearch aria-hidden />+ <span>Research</span>+ <LemonBadge+ size="xsmall"+ visible={dirtyRoles.includes('research')}+ title="Unsaved changes"+ />+ </span>+ ),+ 'data-attr': 'signals-steering-research-tab',+ },+ {+ key: 'implementation',+ label: (+ <span className="flex items-center gap-1">+ <IconCode aria-hidden />+ <span>Implementation</span>+ <LemonBadge+ size="xsmall"+ visible={dirtyRoles.includes('implementation')}+ title="Unsaved changes"+ />+ </span>+ ),+ 'data-attr': 'signals-steering-implementation-tab',+ },+ {+ key: 'scout',+ label: (+ <span className="flex items-center gap-1">+ <IconCompass aria-hidden />+ <span>Scouts</span>+ <LemonBadge+ size="xsmall"+ visible={dirtyRoles.includes('scout')}+ title="Unsaved changes"+ />+ </span>+ ),+ 'data-attr': 'signals-steering-scout-tab',+ },+ ]}+ />+ <div className="flex flex-col gap-2">+ <p className="m-0 text-xs text-secondary">{role.description}</p>+ <InstructionsEditor+ stored={storedInstructions}+ value={instructions}+ dirty={instructionsDirty}+ loading={steeringConfigLoading}+ placeholder={role.placeholder}+ onChange={(value) => setDraft(selectedRole, value)}+ onSave={submitInstructions}+ onDiscard={() => discardDraft(selectedRole)}+ discardDataAttr="signals-steering-discard"+ restrictionReason={restrictionReason}+ dataAttr="signals-steering-instructions"+ ariaLabel={role.title}+ />+ {storedInstructions === null && !steeringConfigLoading && (+ <LemonButton onClick={loadSteeringConfig} size="small" data-attr="signals-steering-retry">+ Retry+ </LemonButton>+ )}+ {restrictionReason && (+ <p className="m-0 text-xs text-secondary">Only project admins can edit these instructions.</p>+ )}+ </div>+ </div>+ </SettingsSection>+ )+}diff --git a/products/signals/frontend/inbox/components/tabs/SettingsSection.tsx b/products/signals/frontend/inbox/components/tabs/SettingsSection.tsxindex 31c9f615ecd7..01af60146e7f 100644--- a/products/signals/frontend/inbox/components/tabs/SettingsSection.tsx+++ b/products/signals/frontend/inbox/components/tabs/SettingsSection.tsx@@ -7,15 +7,20 @@ import { ReactNode } from 'react'*/export function SettingsSection({title,+ id,description,children,}: {title: string- description?: string+ id?: string+ description?: ReactNodechildren: ReactNode}): JSX.Element {return (- <section className="flex flex-col gap-3 rounded border border-primary bg-surface-primary p-4">+ <section+ id={id}+ className="flex flex-col gap-3 rounded border border-primary bg-surface-primary p-4 scroll-mt-4"+ ><div className="flex flex-col gap-0.5"><h3 className="m-0 text-sm font-semibold text-default">{title}</h3>{description && <p className="m-0 max-w-2xl text-xs leading-snug text-secondary">{description}</p>}diff --git a/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx b/products/signals/frontend/inbox/components/tabs/SettingsTab.tsxindex 50f9fc7e71d5..a6358c6cb725 100644--- a/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx+++ b/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx@@ -6,6 +6,7 @@ import { urls } from 'scenes/urls'import { inboxUsageLogic } from '../../logics/inboxUsageLogic'import { signalSourcesLogic } from '../../signalSourcesLogic'+import { AgentSteeringSection } from '../config/AgentSteeringSection'import { RepoRoutingRules } from '../config/RepoRoutingRules'import { SelfDrivingSection } from '../config/SelfDrivingSection'import { SignalSourcesPanel } from '../config/SignalSourcesPanel'@@ -41,6 +42,7 @@ export function SettingsTab(): JSX.Element {><SelfDrivingSection /></SettingsSection>+ <AgentSteeringSection /><SettingsSectiontitle="Code access"description="Connect GitHub so agents can read repositories and open pull requests."diff --git a/products/signals/frontend/inbox/logics/agentSteeringLogic.test.ts b/products/signals/frontend/inbox/logics/agentSteeringLogic.test.tsnew file mode 100644index 000000000000..87f906c5fbc2--- /dev/null+++ b/products/signals/frontend/inbox/logics/agentSteeringLogic.test.ts@@ -0,0 +1,122 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { agentSteeringLogic } from './agentSteeringLogic'++describe('agentSteeringLogic', () => {+ let logic: ReturnType<typeof agentSteeringLogic.build>+ let posted: unknown[]+ let config: Record<string, string>++ beforeEach(() => {+ initKeaTests()+ posted = []+ config = {+ scout_instructions: 'Focus on onboarding.',+ research_instructions: 'Check intent.',+ implementation_instructions: 'Open draft PRs.',+ }+ useMocks({+ get: { '/api/projects/:id/signals/config/': () => [200, config] },+ post: {+ '/api/projects/:id/signals/config/': async ({ request }) => {+ const body = (await request.json()) as Record<string, string>+ posted.push(body)+ config = { ...config, ...body }+ return [200, config]+ },+ },+ })+ logic = agentSteeringLogic()+ logic.mount()+ })++ afterEach(() => logic.unmount())++ it('keeps drafts separate when switching roles and only saves or clears the selected role', async () => {+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.selectedRole).toBe('research')+ expect(logic.values.dirtyRoles).toEqual([])+ logic.actions.setDraft('implementation', 'Open draft PRs.')+ expect(logic.values.dirtyRoles).toEqual([])+ logic.actions.setDraft('scout', 'Inspect new user sessions.')+ logic.actions.selectRole('research')+ expect(logic.values.instructions).toBe('Check intent.')+ logic.actions.setDraft('research', '')+ expect(logic.values.dirtyRoles).toEqual(['scout', 'research'])++ await expectLogic(logic, () => logic.actions.submitInstructions())+ .toDispatchActions(['saveSteeringInstructionsSuccess'])+ .toMatchValues({ instructions: '', instructionsDirty: false })+ expect(posted).toEqual([{ research_instructions: '' }])+ expect(logic.values.dirtyRoles).toEqual(['scout'])++ logic.actions.selectRole('scout')+ expect(logic.values.instructions).toBe('Inspect new user sessions.')+ logic.actions.discardDraft('scout')+ expect(logic.values.dirtyRoles).toEqual([])+ expect(logic.values.instructions).toBe('Focus on onboarding.')+ logic.actions.selectRole('implementation')+ expect(logic.values.instructions).toBe('Open draft PRs.')+ })++ it('prevents double submission and preserves another role draft during a save', async () => {+ await expectLogic(logic).toFinishAllListeners()+ let finishSave!: () => void+ const saving = new Promise<void>((resolve) => {+ finishSave = resolve+ })+ useMocks({+ post: {+ '/api/projects/:id/signals/config/': async ({ request }) => {+ const body = (await request.json()) as Record<string, string>+ posted.push(body)+ await saving+ return [200, { ...config, ...body }]+ },+ },+ })+ logic.actions.selectRole('scout')+ logic.actions.setDraft('scout', 'New scout rules.')+ logic.actions.submitInstructions()+ logic.actions.submitInstructions()+ logic.actions.selectRole('research')+ logic.actions.setDraft('research', 'New research rules.')+ expect(logic.values.steeringConfigLoading).toBe(true)+ finishSave()+ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({ instructions: 'New research rules.', instructionsDirty: true })+ expect(posted).toEqual([{ scout_instructions: 'New scout rules.' }])+ logic.actions.selectRole('scout')+ expect(logic.values.instructionsDirty).toBe(false)+ })++ it('retains the draft after a failed save and allows retrying', async () => {+ await expectLogic(logic).toFinishAllListeners()+ useMocks({ post: { '/api/projects/:id/signals/config/': () => [500, { detail: 'Unavailable' }] } })+ logic.actions.selectRole('scout')+ logic.actions.setDraft('scout', 'Retry these rules.')+ await expectLogic(logic, () => logic.actions.submitInstructions())+ .toDispatchActions(['saveSteeringInstructionsFailure'])+ .toMatchValues({+ instructions: 'Retry these rules.',+ instructionsDirty: true,+ steeringConfigLoading: false,+ })+ useMocks({+ post: {+ '/api/projects/:id/signals/config/': () => [+ 200,+ { ...config, scout_instructions: 'Retry these rules.' },+ ],+ },+ })+ await expectLogic(logic, () => logic.actions.submitInstructions())+ .toDispatchActions(['saveSteeringInstructionsSuccess'])+ .toMatchValues({ instructions: 'Retry these rules.', instructionsDirty: false })+ expect(logic.values.steeringConfig?.scout_instructions).toBe('Retry these rules.')+ })+})diff --git a/products/signals/frontend/inbox/logics/agentSteeringLogic.ts b/products/signals/frontend/inbox/logics/agentSteeringLogic.tsnew file mode 100644index 000000000000..43219959ff60--- /dev/null+++ b/products/signals/frontend/inbox/logics/agentSteeringLogic.ts@@ -0,0 +1,193 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { projectLogic } from 'scenes/projectLogic'++import { signalsConfigCreate, signalsConfigList } from '../../generated/api'+import type { SignalTeamConfigApi } from '../../generated/api.schemas'++export const STEERING_FIELDS = {+ scout: 'scout_instructions',+ research: 'research_instructions',+ implementation: 'implementation_instructions',+} as const++export type SteeringRole = keyof typeof STEERING_FIELDS++export interface SaveSteeringInstructions {+ role: SteeringRole+ instructions: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface agentSteeringLogicValues {+ currentProjectId: number | null // projectLogic+ dirtyRoles: SteeringRole[]+ drafts: Partial<Record<SteeringRole, string>>+ instructions: string+ instructionsDirty: boolean+ selectedRole: SteeringRole+ steeringConfig: SignalTeamConfigApi | null+ steeringConfigLoading: boolean+ storedInstructions: string | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface agentSteeringLogicActions {+ discardDraft: (role: SteeringRole) => {+ role: 'implementation' | 'research' | 'scout'+ }+ loadSteeringConfig: () => any+ loadSteeringConfigFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSteeringConfigSuccess: (+ steeringConfig: SignalTeamConfigApi | null,+ payload?: any+ ) => {+ steeringConfig: SignalTeamConfigApi | null+ payload?: any+ }+ saveSteeringInstructions: ({ role, instructions }: SaveSteeringInstructions) => SaveSteeringInstructions+ saveSteeringInstructionsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ saveSteeringInstructionsSuccess: (+ steeringConfig: SignalTeamConfigApi,+ payload?: SaveSteeringInstructions+ ) => {+ steeringConfig: SignalTeamConfigApi+ payload?: SaveSteeringInstructions+ }+ selectRole: (role: SteeringRole) => {+ role: 'implementation' | 'research' | 'scout'+ }+ setDraft: (+ role: SteeringRole,+ instructions: string+ ) => {+ instructions: string+ role: 'implementation' | 'research' | 'scout'+ }+ submitInstructions: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface agentSteeringLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ dirtyRoles: (+ drafts: Partial<Record<'implementation' | 'research' | 'scout', string>>,+ steeringConfig: SignalTeamConfigApi | null+ ) => SteeringRole[]+ storedInstructions: (+ steeringConfig: SignalTeamConfigApi | null,+ selectedRole: 'implementation' | 'research' | 'scout'+ ) => string | null+ instructions: (+ drafts: Partial<Record<'implementation' | 'research' | 'scout', string>>,+ selectedRole: 'implementation' | 'research' | 'scout',+ storedInstructions: string | null+ ) => string+ instructionsDirty: (instructions: string, storedInstructions: string | null) => boolean+ }+}++export type agentSteeringLogicType = MakeLogicType<+ agentSteeringLogicValues,+ agentSteeringLogicActions,+ Record<string, any>,+ agentSteeringLogicMeta+>++export const agentSteeringLogic = kea<agentSteeringLogicType>([+ path(['products', 'signals', 'inbox', 'logics', 'agentSteeringLogic']),+ connect(() => ({ values: [projectLogic, ['currentProjectId']] })),+ actions({+ selectRole: (role: SteeringRole) => ({ role }),+ setDraft: (role: SteeringRole, instructions: string) => ({ role, instructions }),+ discardDraft: (role: SteeringRole) => ({ role }),+ submitInstructions: true,+ }),+ loaders(({ values }) => ({+ steeringConfig: {+ __default: null as SignalTeamConfigApi | null,+ loadSteeringConfig: async (): Promise<SignalTeamConfigApi | null> =>+ values.currentProjectId == null ? null : signalsConfigList(String(values.currentProjectId)),+ saveSteeringInstructions: async ({+ role,+ instructions,+ }: SaveSteeringInstructions): Promise<SignalTeamConfigApi> =>+ signalsConfigCreate(String(values.currentProjectId), { [STEERING_FIELDS[role]]: instructions }),+ },+ })),+ reducers({+ selectedRole: ['research' as SteeringRole, { selectRole: (_, { role }) => role }],+ drafts: [+ {} as Partial<Record<SteeringRole, string>>,+ {+ setDraft: (state, { role, instructions }) => ({ ...state, [role]: instructions }),+ discardDraft: (state, { role }) => {+ const next = { ...state }+ delete next[role]+ return next+ },+ saveSteeringInstructionsSuccess: (state, { payload }) => {+ if (!payload || state[payload.role] !== payload.instructions) {+ return state+ }+ const next = { ...state }+ delete next[payload.role]+ return next+ },+ },+ ],+ }),+ selectors({+ dirtyRoles: [+ (s) => [s.drafts, s.steeringConfig],+ (drafts: Partial<Record<SteeringRole, string>>, config: SignalTeamConfigApi | null): SteeringRole[] =>+ config === null+ ? []+ : (Object.keys(STEERING_FIELDS) as SteeringRole[]).filter(+ (role) => drafts[role] !== undefined && drafts[role] !== (config[STEERING_FIELDS[role]] ?? '')+ ),+ ],+ storedInstructions: [+ (s) => [s.steeringConfig, s.selectedRole],+ (config: SignalTeamConfigApi | null, role: SteeringRole): string | null =>+ config === null ? null : (config[STEERING_FIELDS[role]] ?? ''),+ ],+ instructions: [+ (s) => [s.drafts, s.selectedRole, s.storedInstructions],+ (drafts: Partial<Record<SteeringRole, string>>, role: SteeringRole, stored: string | null): string =>+ drafts[role] ?? stored ?? '',+ ],+ instructionsDirty: [+ (s) => [s.instructions, s.storedInstructions],+ (instructions: string, stored: string | null): boolean => stored !== null && instructions !== stored,+ ],+ }),+ listeners(({ actions, values }) => ({+ submitInstructions: () => {+ if (values.steeringConfigLoading || !values.instructionsDirty || values.currentProjectId == null) {+ return+ }+ actions.saveSteeringInstructions({ role: values.selectedRole, instructions: values.instructions })+ },+ saveSteeringInstructionsSuccess: () => {+ lemonToast.success('Steering instructions saved')+ },+ })),+ afterMount(({ actions }) => actions.loadSteeringConfig()),+])diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex 474c720c6da0..fccf97865d56 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -534,6 +534,48 @@ tools:Replace an existing signal source config by ID (full update — `source_product` and `source_type` arerequired; `enabled` and `config` are optional and keep their current values if omitted). Prefer`inbox-source-configs-partial-update` when you only need to flip `enabled` or tweak `config`.+ inbox-steering-instructions-get:+ operation: signals_config_list+ enabled: true+ scopes:+ - task:read+ title: Get Self-driving steering instructions+ description: >+ Read the current project's research, implementation, and scout instructions. Returns only the three+ instruction fields from the project's Self-driving config singleton, with empty strings for unset roles.+ Read shared project instructions separately with tasks-config-list. A role's instructions supplement the+ shared project instructions; scouts also retain their individual briefs.+ response:+ include:+ - research_instructions+ - implementation_instructions+ - scout_instructions+ inbox-steering-instructions-update:+ operation: signals_config_create+ enabled: true+ scopes:+ - task:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Update Self-driving steering instructions+ description: >+ Set project-level instructions for research agents, implementation agents, or all scouts. Requires project+ admin. Sandbox agents cannot change these instructions. Read inbox-steering-instructions-get first. Send the+ full replacement text for each role you change, not a diff; omitted roles keep their instructions. Send an+ empty string to clear a role while retaining shared project instructions. Each field accepts up to 20,000+ characters. New and resumed runs receive the saved instructions. Use tasks-config-agent-instructions-create+ to edit the shared project instructions instead.+ include_params:+ - research_instructions+ - implementation_instructions+ - scout_instructions+ response:+ include:+ - research_instructions+ - implementation_instructions+ - scout_instructionsscout-check-record-result:operation: signals_scout_record_check_resultenabled: truediff --git a/products/tasks/backend/logic/services/agent_instructions.py b/products/tasks/backend/logic/services/agent_instructions.pyindex 3b521b09b09b..055e1af81bdc 100644--- a/products/tasks/backend/logic/services/agent_instructions.py+++ b/products/tasks/backend/logic/services/agent_instructions.py@@ -11,11 +11,22 @@ from posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.team import Teamfrom posthog.models.user import User+from products.signals.backend.facade.agent_instructions import get_agent_instructionsfrom products.tasks.backend.constants import AGENT_INSTRUCTIONS_STATE_KEYfrom products.tasks.backend.models import Task, TaskRun, TeamTasksConfig, UserTasksConfiglogger = structlog.get_logger(__name__)+# Signals uses internal tasks to hide pipeline runs, not to isolate them from project instructions.+SIGNALS_ORIGINS = frozenset(+ {+ Task.OriginProduct.SIGNAL_REPORT,+ Task.OriginProduct.SIGNALS_SCOUT,+ Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS,+ Task.OriginProduct.SIGNALS_CHAT,+ }+)+# Runs nobody is driving. They act for the project, so they get the project instructions but# never their creator's personal ones, which describe how that person likes to work.PERSONLESS_ORIGINS = frozenset(@@ -92,33 +103,44 @@ class AgentInstructionsResolver:def __init__(self, store: AgentInstructionsStore | None = None) -> None:self._store = store or AgentInstructionsStore()- def resolve(self, task: Task, actor_user: User | None) -> str | None:- if task.internal or task.origin_product in EXCLUDED_ORIGINS:+ def resolve(self, task: Task, actor_user: User | None, *, ai_stage: str | None = None) -> str | None:+ if task.origin_product in EXCLUDED_ORIGINS or (task.internal and task.origin_product not in SIGNALS_ORIGINS):return Noneproject = self._store.get_project(task.team_id).strip()personal = ""- if task.origin_product not in PERSONLESS_ORIGINS:+ if not task.internal and task.origin_product not in PERSONLESS_ORIGINS:user_id = actor_user.id if actor_user is not None else task.created_by_idif user_id is not None:personal = self._store.get_personal(task.team_id, user_id).strip()- return self.render(project, personal)+ steering = (+ get_agent_instructions(+ team_id=_canonical_team_id(task.team_id), origin_product=task.origin_product, ai_stage=ai_stage+ )+ if task.origin_product in SIGNALS_ORIGINS+ else ""+ )+ return self.render(project, personal, steering)@staticmethod- def render(project: str, personal: str) -> str | None:+ def render(project: str, personal: str, steering: str = "") -> str | None:sections: list[str] = []if project:sections.append(f"{PROJECT_HEADING}\n\n{project}")+ if steering:+ sections.append(steering)if personal:sections.append(f"{PERSONAL_HEADING}\n\n{personal}")return "\n\n".join(sections) or None-def agent_instructions_state_update(task: Task, actor_user: User | None) -> tuple[dict[str, str], list[str]]:+def agent_instructions_state_update(+ task: Task, actor_user: User | None, *, ai_stage: str | None = None+) -> tuple[dict[str, str], list[str]]:"""The run-state `(updates, remove_keys)` that stamp the resolved instructions on a run.An empty result removes the key, so a resumed run never keeps text the user has since cleared."""- instructions = AgentInstructionsResolver().resolve(task, actor_user)+ instructions = AgentInstructionsResolver().resolve(task, actor_user, ai_stage=ai_stage)if instructions is None:return {}, [AGENT_INSTRUCTIONS_STATE_KEY]return {AGENT_INSTRUCTIONS_STATE_KEY: instructions}, []@@ -132,7 +154,9 @@ def refresh_agent_instructions_state(task_run: TaskRun, user: User, *, reason: s"""run_id = str(task_run.id)try:- updates, remove_keys = agent_instructions_state_update(task_run.task, user)+ updates, remove_keys = agent_instructions_state_update(+ task_run.task, user, ai_stage=(task_run.state or {}).get("ai_stage")+ )TaskRun.update_state_atomic(task_run.id, updates=updates, remove_keys=remove_keys)except Exception:logger.warning("agent_instructions_refresh_failed", run_id=run_id, reason=reason, exc_info=True)diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.pyindex e69eb37c1c25..225691a178ee 100644--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py@@ -1372,7 +1372,9 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro# Best-effort for the same reason as store skills.state_remove_keys: list[str] = []try:- instruction_updates, state_remove_keys = agent_instructions_state_update(task, actor_user)+ instruction_updates, state_remove_keys = agent_instructions_state_update(+ task, actor_user, ai_stage=state.get("ai_stage")+ )state_updates.update(instruction_updates)except Exception as e:log_with_activity_context("agent_instructions_resolve_failed", run_id=run_id, error=str(e))diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.pyindex a764a0b4ccbb..93901a9911fa 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py@@ -12,6 +12,7 @@ from temporalio.testing import ActivityEnvironmentfrom posthog.models import OrganizationMembership, Userfrom posthog.models.user_integration import UserIntegration+from products.signals.backend.models import SignalTeamConfigfrom products.skills.backend.models.skills import LLMSkillfrom products.tasks.backend.constants import (AGENT_PROXY_KEEP_STREAM_OPEN_FEATURE_FLAG,@@ -34,6 +35,7 @@ from products.tasks.backend.constants import (vm_sandbox_origin_rollout_percentages,)from products.tasks.backend.exceptions import ProcessTaskFatalError, TaskInvalidStateError, TaskRunNotReadyError+from products.tasks.backend.logic.services.agent_instructions import AgentInstructionsStorefrom products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, SandboxEnvironment, Task, TaskRunfrom products.tasks.backend.temporal.process_task.activities import provision_sandboxfrom products.tasks.backend.temporal.process_task.activities.get_task_processing_context import (@@ -226,6 +228,28 @@ class TestIsAgentOtelTelemetryEnabled:class TestGetTaskProcessingContextActivity:+ @pytest.mark.django_db(transaction=True)+ def test_internal_research_gets_project_and_role_instructions_at_start(+ self, activity_environment: ActivityEnvironment, test_task: Task+ ) -> None:+ test_task.origin_product = Task.OriginProduct.SIGNAL_REPORT+ test_task.internal = True+ test_task.save(update_fields=["origin_product", "internal"])+ AgentInstructionsStore().set_project(test_task.team_id, "Use pnpm.")+ SignalTeamConfig.objects.update_or_create(+ team_id=test_task.team_id,+ defaults={+ "research_instructions": "Check the product intent.",+ "implementation_instructions": "Open draft PRs.",+ },+ )+ run = test_task.create_run(extra_state={"ai_stage": "research"})+ async_to_sync(_run_context)(activity_environment, GetTaskProcessingContextInput(run_id=str(run.id)))+ run.refresh_from_db()+ assert "Use pnpm." in run.state["agent_instructions"]+ assert "Check the product intent." in run.state["agent_instructions"]+ assert "Open draft PRs." not in run.state["agent_instructions"]+def _create_task_with_repo(self, team, user, github_integration, repo_config):return Task.objects.create(team=team,diff --git a/products/tasks/backend/tests/test_agent_instructions.py b/products/tasks/backend/tests/test_agent_instructions.pyindex b68b4829e1f3..b1a8f67e3979 100644--- a/products/tasks/backend/tests/test_agent_instructions.py+++ b/products/tasks/backend/tests/test_agent_instructions.py@@ -13,13 +13,15 @@ from posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization import OrganizationMembershipfrom posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV+from products.signals.backend.models import SignalTeamConfigfrom products.tasks.backend.constants import AGENT_INSTRUCTIONS_MAX_LENGTH, AGENT_INSTRUCTIONS_STATE_KEYfrom products.tasks.backend.logic.services.agent_instructions import (AgentInstructionsResolver,AgentInstructionsStore,agent_instructions_state_update,+ refresh_agent_instructions_state,)-from products.tasks.backend.models import Task+from products.tasks.backend.models import Task, TaskRunTEAM_TRIPLE = {"runtime_adapter": "claude", "model": "claude-opus-4-8", "reasoning_effort": "high"}@@ -48,9 +50,18 @@ class TestAgentInstructionsResolver(APIBaseTest):("loop", Task.OriginProduct.LOOP, False, True, False),("workflow", Task.OriginProduct.WORKFLOW, False, True, False),("signals_scout", Task.OriginProduct.SIGNALS_SCOUT, False, True, False),+ ("internal_signals_scout", Task.OriginProduct.SIGNALS_SCOUT, True, True, False),+ ("scout_suggestions", Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS, False, True, False),+ ("internal_scout_suggestions", Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS, True, True, False),("signal_report", Task.OriginProduct.SIGNAL_REPORT, False, True, False),+ ("internal_signal_report", Task.OriginProduct.SIGNAL_REPORT, True, True, False),+ ("signals_chat", Task.OriginProduct.SIGNALS_CHAT, False, True, True),+ ("internal_signals_chat", Task.OriginProduct.SIGNALS_CHAT, True, True, False),("posthog_ai", Task.OriginProduct.POSTHOG_AI, False, True, True),("internal", Task.OriginProduct.USER_CREATED, True, False, False),+ ("business_knowledge", Task.OriginProduct.BUSINESS_KNOWLEDGE, False, False, False),+ ("image_builder", Task.OriginProduct.IMAGE_BUILDER, False, False, False),+ ("task_analysis", Task.OriginProduct.TASK_ANALYSIS, False, False, False),])def test_levels_follow_the_run_origin(@@ -72,6 +83,62 @@ class TestAgentInstructionsResolver(APIBaseTest):self.store.set_personal(self.team.id, self.user.id, "")assert agent_instructions_state_update(self._task(), actor_user=None) == ({}, [AGENT_INSTRUCTIONS_STATE_KEY])+ @parameterized.expand(+ [+ ("signals_scout", "scout_custom", "scout"),+ ("signal_report", "research", "research"),+ ("signal_report", "implementation", "implementation"),+ ("signal_report", "repo_selection", None),+ ("signal_report", None, None),+ ("scout_suggestions", "research", None),+ ("signals_chat", None, None),+ ]+ )+ def test_internal_signals_receive_project_and_only_their_role(+ self, origin: str, stage: str | None, expected_role: str | None+ ) -> None:+ role_instructions = {+ "scout": "Focus on onboarding failures.",+ "research": "Check whether the behavior is intentional.",+ "implementation": "Open draft pull requests.",+ }+ SignalTeamConfig.objects.update_or_create(+ team=self.team, defaults={f"{role}_instructions": text for role, text in role_instructions.items()}+ )+ updates, removed = agent_instructions_state_update(self._task(origin, internal=True), None, ai_stage=stage)+ rendered = updates[AGENT_INSTRUCTIONS_STATE_KEY]+ assert "Use pnpm." in rendered+ assert "Reply tersely." not in rendered+ assert removed == []+ for role, text in role_instructions.items():+ assert (text in rendered) is (role == expected_role)+ if expected_role:+ assert f"Your role is {expected_role}." in rendered++ def test_resume_refreshes_and_clears_the_runs_role_instructions(self) -> None:+ task = self._task(Task.OriginProduct.SIGNAL_REPORT, internal=True)+ run = TaskRun.objects.create(task=task, team=self.team, state={"ai_stage": "research"})+ config, _ = SignalTeamConfig.objects.update_or_create(+ team=self.team, defaults={"research_instructions": "Inspect session recordings."}+ )+ refresh_agent_instructions_state(run, self.user, reason="test")+ run.refresh_from_db()+ assert "Use pnpm." in run.state[AGENT_INSTRUCTIONS_STATE_KEY]+ assert "Inspect session recordings." in run.state[AGENT_INSTRUCTIONS_STATE_KEY]++ self.store.set_project(self.team.id, "")+ refresh_agent_instructions_state(run, self.user, reason="test")+ run.refresh_from_db()+ assert "Project instructions" not in run.state[AGENT_INSTRUCTIONS_STATE_KEY]+ assert "Inspect session recordings." in run.state[AGENT_INSTRUCTIONS_STATE_KEY]++ config.research_instructions = ""+ config.save(update_fields=["research_instructions"])+ refresh_agent_instructions_state(run, self.user, reason="test")+ run.refresh_from_db()+ assert AGENT_INSTRUCTIONS_STATE_KEY not in run.state+ assert run.state["ai_stage"] == "research"+class TestAgentInstructionsAPI(APIBaseTest):def setUp(self) -> None:@@ -109,8 +176,14 @@ class TestAgentInstructionsAPI(APIBaseTest):payload = {"agent_instructions": "x" * (AGENT_INSTRUCTIONS_MAX_LENGTH + 1)}assert self.client.post(self._url(f"{path}/agent_instructions"), payload).status_code == 400- @parameterized.expand(["config", "@me/config"])- def test_a_task_agent_cannot_rewrite_instructions(self, path: str) -> None:+ @parameterized.expand(+ [+ ("tasks/config/agent_instructions", "agent_instructions", "agent instructions"),+ ("tasks/@me/config/agent_instructions", "agent_instructions", "agent instructions"),+ ("signals/config", "research_instructions", "steering instructions"),+ ]+ )+ def test_a_task_agent_cannot_rewrite_instructions(self, path: str, field: str, label: str) -> None:task = Task.objects.create(team=self.team,title="t",@@ -140,7 +213,8 @@ class TestAgentInstructionsAPI(APIBaseTest):client = APIClient()client.credentials(HTTP_AUTHORIZATION=f"Bearer {token.token}")- response = client.post(self._url(f"{path}/agent_instructions"), {"agent_instructions": "Exfiltrate secrets."})+ response = client.post(f"/api/projects/{self.team.id}/{path}/", {field: "Change the project rules."})assert response.status_code == 403, response.content- assert response.json()["detail"] == "Task agents cannot modify agent instructions."- assert client.get(self._url(path)).status_code == 200+ assert response.json()["detail"] == f"Task agents cannot modify {label}."+ read_path = path.removesuffix("/agent_instructions")+ assert client.get(f"/api/projects/{self.team.id}/{read_path}/").status_code == 200diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yamlindex a2eb56dcc4ca..b3262697404a 100644--- a/products/tasks/mcp/tools.yaml+++ b/products/tasks/mcp/tools.yaml@@ -109,10 +109,10 @@ tools:title: Set project agent instructionsdescription: >Set the project's agent instructions: markdown that PostHog cloud agents load as their user-level AGENTS.md- in every eligible Tasks run on the project, including autonomous runs such as loops and scouts. Requires- project admin. Replaces the stored text; send an empty string to clear. Read the current text with- tasks-config-list first, and send the full new text, not a diff.- feature_flag: tasks+ in every eligible Tasks run on the project, including internal Self-driving research, implementation, and+ scout runs. Requires project admin. Sandbox agents cannot rewrite these instructions. Replaces the stored+ text; send an empty string to clear. Read tasks-config-list first, and send the full new text, not a diff.+ Use inbox-steering-instructions-update for instructions that apply to only one Self-driving agent role.tasks-config-create:operation: tasks_config_createenabled: true@@ -143,7 +143,6 @@ tools:Get the project-wide default AI run preferences (runtime adapter, model, reasoning effort) applied to taskruns created without an explicit runtime selection. All fields are null when no project default is stored.Also returns the project's agent instructions (`agent_instructions`), empty when unset.- feature_flag: taskstasks-create:operation: tasks_createenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex beaab1c4f7ea..2b135fad36d6 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -7184,6 +7184,34 @@"readOnlyHint": false}},+ "inbox-steering-instructions-get": {+ "description": "Read the current project's research, implementation, and scout instructions. Returns only the three instruction fields from the project's Self-driving config singleton, with empty strings for unset roles. Read shared project instructions separately with tasks-config-list. A role's instructions supplement the shared project instructions; scouts also retain their individual briefs.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Get Self-driving steering instructions",+ "title": "Get Self-driving steering instructions",+ "required_scopes": ["task:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "inbox-steering-instructions-update": {+ "description": "Set project-level instructions for research agents, implementation agents, or all scouts. Requires project admin. Sandbox agents cannot change these instructions. Read inbox-steering-instructions-get first. Send the full replacement text for each role you change, not a diff; omitted roles keep their instructions. Send an empty string to clear a role while retaining shared project instructions. Each field accepts up to 20,000 characters. New and resumed runs receive the saved instructions. Use tasks-config-agent-instructions-create to edit the shared project instructions instead.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Update Self-driving steering instructions",+ "title": "Update Self-driving steering instructions",+ "required_scopes": ["task:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"insight-create": {"description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel /\nquery-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save.\nReturns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if\nyou want to see the computed results.\n\nPut the insight definition in `query.source`, under the wrapper node that matches it. Use\n`InsightVizNode` for a product analytics query and `DataVisualizationNode` for a SQL one:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"DataVisualizationNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```\n\nA bare query is accepted too. `{ \"kind\": \"TrendsQuery\", ... }` and `{ \"kind\": \"HogQLQuery\", ... }` are each\nwrapped for you, so a query you just ran through one of the `query-*` tools can be passed straight through.\n\nChoose the TrendsQuery `trendsFilter.display` from the question the insight answers:\n- Change over time: `ActionsLineGraph` (default), `ActionsAreaGraph`, or `ActionsBar`.\n- Compare breakdown values or series as totals (\"top pages\", \"failures by reason\"): `ActionsBarValue`, or `ActionsPie` for the share of a whole with a few values.\n- One number for the period, or this period against the previous one: `Metric` with `compareFilter.compare: true` for a comparison, or `BoldNumber` when a trend has no meaning.\n- Many breakdown rows that a person reads rather than compares: `ActionsTable`.\n- Totals per country from a `$geoip_country_code` breakdown: `WorldMap`.\n\nIn a TrendsQuery, `ActionsBar` is a time series with one bar per interval and the breakdown values stacked in each bar. It is not one bar per category. In a SQL `DataVisualizationNode`, `ActionsBar` is one bar per X-axis value, and `ActionsBarValue` draws the same bars horizontally.","category": "Product analytics",@@ -12902,7 +12930,7 @@"feature_flag": "context-layer"},"tasks-config-agent-instructions-create": {- "description": "Set the project's agent instructions: markdown that PostHog cloud agents load as their user-level AGENTS.md in every eligible Tasks run on the project, including autonomous runs such as loops and scouts. Requires project admin. Replaces the stored text; send an empty string to clear. Read the current text with tasks-config-list first, and send the full new text, not a diff.",+ "description": "Set the project's agent instructions: markdown that PostHog cloud agents load as their user-level AGENTS.md in every eligible Tasks run on the project, including internal Self-driving research, implementation, and scout runs. Requires project admin. Sandbox agents cannot rewrite these instructions. Replaces the stored text; send an empty string to clear. Read tasks-config-list first, and send the full new text, not a diff. Use inbox-steering-instructions-update for instructions that apply to only one Self-driving agent role.","category": "Tasks","feature": "tasks","summary": "Set project agent instructions",@@ -12913,8 +12941,7 @@"idempotentHint": true,"openWorldHint": true,"readOnlyHint": false- },- "feature_flag": "tasks"+ }},"tasks-config-create": {"description": "Set the project-wide default AI run preferences (runtime adapter, model, reasoning effort) applied to task runs created without an explicit runtime selection. Requires project admin. `runtime_adapter` and `model` must be set together; send all three fields as null to clear the project default. Use tasks-models-retrieve to list valid model identifiers.",@@ -12943,8 +12970,7 @@"idempotentHint": true,"openWorldHint": true,"readOnlyHint": true- },- "feature_flag": "tasks"+ }},"tasks-create": {"description": "Create a task without starting a run. Set `description` to the agent's instructions. For code tasks, set `repository` to `organization/repo`. A person can start the task at the returned URL. Use `tasks-create-and-run` to start a run immediately when that tool is available.",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 9fda99fd762f..d8bc2130f4b8 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -7381,6 +7381,34 @@"readOnlyHint": false}},+ "inbox-steering-instructions-get": {+ "description": "Read the current project's research, implementation, and scout instructions. Returns only the three instruction fields from the project's Self-driving config singleton, with empty strings for unset roles. Read shared project instructions separately with tasks-config-list. A role's instructions supplement the shared project instructions; scouts also retain their individual briefs.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Get Self-driving steering instructions",+ "title": "Get Self-driving steering instructions",+ "required_scopes": ["task:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "inbox-steering-instructions-update": {+ "description": "Set project-level instructions for research agents, implementation agents, or all scouts. Requires project admin. Sandbox agents cannot change these instructions. Read inbox-steering-instructions-get first. Send the full replacement text for each role you change, not a diff; omitted roles keep their instructions. Send an empty string to clear a role while retaining shared project instructions. Each field accepts up to 20,000 characters. New and resumed runs receive the saved instructions. Use tasks-config-agent-instructions-create to edit the shared project instructions instead.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Update Self-driving steering instructions",+ "title": "Update Self-driving steering instructions",+ "required_scopes": ["task:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"insight-create": {"description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel /\nquery-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save.\nReturns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if\nyou want to see the computed results.\n\nPut the insight definition in `query.source`, under the wrapper node that matches it. Use\n`InsightVizNode` for a product analytics query and `DataVisualizationNode` for a SQL one:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"DataVisualizationNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```\n\nA bare query is accepted too. `{ \"kind\": \"TrendsQuery\", ... }` and `{ \"kind\": \"HogQLQuery\", ... }` are each\nwrapped for you, so a query you just ran through one of the `query-*` tools can be passed straight through.\n\nChoose the TrendsQuery `trendsFilter.display` from the question the insight answers:\n- Change over time: `ActionsLineGraph` (default), `ActionsAreaGraph`, or `ActionsBar`.\n- Compare breakdown values or series as totals (\"top pages\", \"failures by reason\"): `ActionsBarValue`, or `ActionsPie` for the share of a whole with a few values.\n- One number for the period, or this period against the previous one: `Metric` with `compareFilter.compare: true` for a comparison, or `BoldNumber` when a trend has no meaning.\n- Many breakdown rows that a person reads rather than compares: `ActionsTable`.\n- Totals per country from a `$geoip_country_code` breakdown: `WorldMap`.\n\nIn a TrendsQuery, `ActionsBar` is a time series with one bar per interval and the breakdown values stacked in each bar. It is not one bar per category. In a SQL `DataVisualizationNode`, `ActionsBar` is one bar per X-axis value, and `ActionsBarValue` draws the same bars horizontally.","category": "Product analytics",@@ -13562,7 +13590,7 @@}},"tasks-config-agent-instructions-create": {- "description": "Set the project's agent instructions: markdown that PostHog cloud agents load as their user-level AGENTS.md in every eligible Tasks run on the project, including autonomous runs such as loops and scouts. Requires project admin. Replaces the stored text; send an empty string to clear. Read the current text with tasks-config-list first, and send the full new text, not a diff.",+ "description": "Set the project's agent instructions: markdown that PostHog cloud agents load as their user-level AGENTS.md in every eligible Tasks run on the project, including internal Self-driving research, implementation, and scout runs. Requires project admin. Sandbox agents cannot rewrite these instructions. Replaces the stored text; send an empty string to clear. Read tasks-config-list first, and send the full new text, not a diff. Use inbox-steering-instructions-update for instructions that apply to only one Self-driving agent role.","category": "Tasks","feature": "tasks","summary": "Set project agent instructions",@@ -13573,8 +13601,7 @@"idempotentHint": true,"openWorldHint": true,"readOnlyHint": false- },- "feature_flag": "tasks"+ }},"tasks-config-create": {"description": "Set the project-wide default AI run preferences (runtime adapter, model, reasoning effort) applied to task runs created without an explicit runtime selection. Requires project admin. `runtime_adapter` and `model` must be set together; send all three fields as null to clear the project default. Use tasks-models-retrieve to list valid model identifiers.",@@ -13603,8 +13630,7 @@"idempotentHint": true,"openWorldHint": true,"readOnlyHint": true- },- "feature_flag": "tasks"+ }},"tasks-create": {"description": "Create a task without starting a run. Set `description` to the agent's instructions. For code tasks, set `repository` to `organization/repo`. A person can start the task at the returned URL. Use `tasks-create-and-run` to start a run immediately when that tool is available.",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 71115565e0ff..f78c004e0e40 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -101858,6 +101858,21 @@ export namespace Schemas {default_slack_notification_channel?: string | null;/** Per-repository base branch overrides for auto-started inbox PRs, keyed by 'organization/repository'. The branch is what the auto-PR targets; omit a repo (or send {}) to keep targeting the repo default branch. */autostart_base_branches?: SignalTeamConfigAutostartBaseBranches;+ /**+ * Project-level instructions added to every scout run, alongside project instructions and the scout's own brief. Blank uses project instructions only.+ * @maxLength 20000+ */+ scout_instructions?: string;+ /**+ * Project-level instructions for the dedicated signal report research stage. Other agent roles do not receive them. Blank uses project instructions only.+ * @maxLength 20000+ */+ research_instructions?: string;+ /**+ * Project-level instructions for agents implementing signal reports. Other agent roles do not receive them. Blank uses project instructions only.+ * @maxLength 20000+ */+ implementation_instructions?: string;/*** Connected GitHub, GitLab, Linear, or Jira integration that self-driving opens a tracker issue in for each pull request it makes. Null turns tracker issues off, which is the default.* @nullablediff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex 0eb7d0df79f1..96332c68950a 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -3,11 +3,146 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 63 enabled ops+ * PostHog API - MCP 65 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'+/**+ * Team-level signal autonomy config (singleton per team).+ *+ * GET /signals/config/ → retrieve+ * POST /signals/config/ → update+ * @summary Read the project's signals config+ */+export const SignalsConfigListParams = () => zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++/**+ * Partial update of the per-project singleton. Omitted fields keep their value.+ * @summary Update the project's signals config+ */+export const SignalsConfigCreateParams = () => zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const signalsConfigCreateBodyDefaultSlackNotificationChannelMax = 255++export const signalsConfigCreateBodyAutostartBaseBranchesMaxOne = 255++export const signalsConfigCreateBodyScoutInstructionsMax = 20000++export const signalsConfigCreateBodyResearchInstructionsMax = 20000++export const signalsConfigCreateBodyImplementationInstructionsMax = 20000++export const signalsConfigCreateBodyIssueTrackingConfigMaxOne = 255++export const signalsConfigCreateBodyMaxReportsPerDayMax = 2147483647++export const signalsConfigCreateBodyPullRequestLabelMax = 50++export const SignalsConfigCreateBody = () => zod.object({+ autostart_enabled: zod+ .boolean()+ .nullish()+ .describe(+ 'Master switch for autonomous inbox PRs. Null (never set) leaves autostart on; set false to opt out, so actionable reports still generate and notify but the team never auto-starts an implementation task or opens a PR — reviewers open PRs manually.'+ ),+ default_autostart_priority: zod+ .enum(['P0', 'P1', 'P2', 'P3', 'P4'])+ .optional()+ .describe('\* `P0` - P0\n\* `P1` - P1\n\* `P2` - P2\n\* `P3` - P3\n\* `P4` - P4'),+ default_slack_notification_channel: zod+ .string()+ .max(signalsConfigCreateBodyDefaultSlackNotificationChannelMax)+ .nullish()+ .describe(+ "Default Slack channel for this team's signal inbox notifications, in the same `channel_id|#channel-name` shape PostHog uses elsewhere (only the channel id is required). Null means no team-level default; per-user channels still apply."+ ),+ autostart_base_branches: zod+ .record(zod.string(), zod.string().max(signalsConfigCreateBodyAutostartBaseBranchesMaxOne))+ .optional()+ .describe(+ "Per-repository base branch overrides for auto-started inbox PRs, keyed by 'organization\/repository'. The branch is what the auto-PR targets; omit a repo (or send {}) to keep targeting the repo default branch."+ ),+ scout_instructions: zod+ .string()+ .max(signalsConfigCreateBodyScoutInstructionsMax)+ .optional()+ .describe(+ "Project-level instructions added to every scout run, alongside project instructions and the scout's own brief. Blank uses project instructions only."+ ),+ research_instructions: zod+ .string()+ .max(signalsConfigCreateBodyResearchInstructionsMax)+ .optional()+ .describe(+ 'Project-level instructions for the dedicated signal report research stage. Other agent roles do not receive them. Blank uses project instructions only.'+ ),+ implementation_instructions: zod+ .string()+ .max(signalsConfigCreateBodyImplementationInstructionsMax)+ .optional()+ .describe(+ 'Project-level instructions for agents implementing signal reports. Other agent roles do not receive them. Blank uses project instructions only.'+ ),+ issue_tracking_integration: zod+ .number()+ .nullish()+ .describe(+ 'Connected GitHub, GitLab, Linear, or Jira integration that self-driving opens a tracker issue in for each pull request it makes. Null turns tracker issues off, which is the default.'+ ),+ issue_tracking_config: zod+ .record(zod.string(), zod.string().max(signalsConfigCreateBodyIssueTrackingConfigMaxOne))+ .optional()+ .describe(+ "Where in the tracker the issues land. Required keys depend on the integration kind: github -> {repository}; linear -> {team_id}; jira -> {project_key}; gitlab needs none, because its integration is already bound to one project. An optional 'label' is applied to created GitHub issues."+ ),+ max_reports_per_day: zod+ .number()+ .min(1)+ .max(signalsConfigCreateBodyMaxReportsPerDayMax)+ .nullish()+ .describe(+ "Daily cap on new reports surfacing to the inbox, counted per calendar day in the project's timezone. Once reached, signal ingestion, scout runs, and report research pause until local midnight. Null means unlimited."+ ),+ default_open_pull_request_ready: zod+ .boolean()+ .optional()+ .describe(+ "Whether self-driving pull requests open ready for review instead of draft, so the full CI matrix starts when the pull request is created. False by default. A reviewer's own github_open_pull_request_ready overrides this for reports that suggest them as reviewer."+ ),+ github_issue_writeback_enabled: zod+ .boolean()+ .optional()+ .describe(+ "Whether self-driving comments back on a GitHub issue that raised a report, linking to the report so everybody watching the issue knows it is being researched. The comment is public on the issue thread and carries a link only, never report content. False by default. Needs a GitHub integration that can reach the issue's repository."+ ),+ pull_request_label_enabled: zod+ .boolean()+ .optional()+ .describe(+ 'Whether self-driving adds a label to every pull request it opens, so GitHub search, saved searches, and notification rules can separate them from other automation on the repository. False by default. Needs a GitHub integration that can reach the repository.'+ ),+ pull_request_label: zod+ .string()+ .max(signalsConfigCreateBodyPullRequestLabelMax)+ .nullish()+ .describe(+ "The label name self-driving applies, at most 50 characters. Null or blank means 'self-driving'. The label is created in the repository when it does not exist yet. Only used while pull_request_label_enabled is true."+ ),+})+export const SignalsReportsListParams = () => zod.object({project_id: zod.string()diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex 142b009855d4..0604568bae5f 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -782,6 +782,78 @@ const inboxSourceConfigsUpdate = (): ToolBase<},})+const InboxSteeringInstructionsGetSchema = () => z.object({})++const inboxSteeringInstructionsGet = (): ToolBase<+ ReturnType<typeof InboxSteeringInstructionsGetSchema>,+ Schemas.SignalTeamConfig+> => ({+ name: 'inbox-steering-instructions-get',+ schema: InboxSteeringInstructionsGetSchema(),+ handler: async (context: Context, _params: z.infer<ReturnType<typeof InboxSteeringInstructionsGetSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.SignalTeamConfig>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/config/`,+ })+ const filtered = pickResponseFields(result, [+ 'research_instructions',+ 'implementation_instructions',+ 'scout_instructions',+ ]) as typeof result+ return filtered+ },+})++const InboxSteeringInstructionsUpdateSchema = () => {+ const SignalsConfigCreateBody = orvalSchemas.SignalsConfigCreateBody()+ return SignalsConfigCreateBody.omit({+ autostart_enabled: true,+ default_autostart_priority: true,+ default_slack_notification_channel: true,+ autostart_base_branches: true,+ issue_tracking_integration: true,+ issue_tracking_config: true,+ max_reports_per_day: true,+ default_open_pull_request_ready: true,+ github_issue_writeback_enabled: true,+ pull_request_label_enabled: true,+ pull_request_label: true,+ })+}++const inboxSteeringInstructionsUpdate = (): ToolBase<+ ReturnType<typeof InboxSteeringInstructionsUpdateSchema>,+ Schemas.SignalTeamConfig+> => ({+ name: 'inbox-steering-instructions-update',+ schema: InboxSteeringInstructionsUpdateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof InboxSteeringInstructionsUpdateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.scout_instructions !== undefined) {+ body['scout_instructions'] = params.scout_instructions+ }+ if (params.research_instructions !== undefined) {+ body['research_instructions'] = params.research_instructions+ }+ if (params.implementation_instructions !== undefined) {+ body['implementation_instructions'] = params.implementation_instructions+ }+ const result = await context.api.request<Schemas.SignalTeamConfig>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/config/`,+ body,+ })+ const filtered = pickResponseFields(result, [+ 'research_instructions',+ 'implementation_instructions',+ 'scout_instructions',+ ]) as typeof result+ return filtered+ },+})+const ScoutCheckRecordResultSchema = () => {const SignalsScoutRecordCheckResultBody = orvalSchemas.SignalsScoutRecordCheckResultBody()const SignalsScoutRecordCheckResultParams = orvalSchemas.SignalsScoutRecordCheckResultParams()@@ -3052,6 +3124,8 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'inbox-source-configs-partial-update': inboxSourceConfigsPartialUpdate,'inbox-source-configs-retrieve': inboxSourceConfigsRetrieve,'inbox-source-configs-update': inboxSourceConfigsUpdate,+ 'inbox-steering-instructions-get': inboxSteeringInstructionsGet,+ 'inbox-steering-instructions-update': inboxSteeringInstructionsUpdate,'scout-check-record-result': scoutCheckRecordResult,'scout-config-create': scoutConfigCreate,'scout-config-delete': scoutConfigDelete,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-steering-instructions-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-steering-instructions-get.jsonnew file mode 100644index 000000000000..7b7ea9186078--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-steering-instructions-get.json@@ -0,0 +1,5 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {},+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-steering-instructions-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-steering-instructions-update.jsonnew file mode 100644index 000000000000..b6e9dcc19dfd--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-steering-instructions-update.json@@ -0,0 +1,21 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "implementation_instructions": {+ "description": "Project-level instructions for agents implementing signal reports. Other agent roles do not receive them. Blank uses project instructions only.",+ "maxLength": 20000,+ "type": "string"+ },+ "research_instructions": {+ "description": "Project-level instructions for the dedicated signal report research stage. Other agent roles do not receive them. Blank uses project instructions only.",+ "maxLength": 20000,+ "type": "string"+ },+ "scout_instructions": {+ "description": "Project-level instructions added to every scout run, alongside project instructions and the scout's own brief. Blank uses project instructions only.",+ "maxLength": 20000,+ "type": "string"+ }+ },+ "type": "object"+}diff --git a/services/mcp/tests/unit/signals-steering-generated.test.ts b/services/mcp/tests/unit/signals-steering-generated.test.tsnew file mode 100644index 000000000000..dcec71f9902b--- /dev/null+++ b/services/mcp/tests/unit/signals-steering-generated.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it, vi } from 'vitest'++import { GENERATED_TOOLS } from '@/tools/generated/signals'+import type { Context } from '@/tools/types'++describe('Self-driving steering tools', () => {+ it.each(['inbox-steering-instructions-get', 'inbox-steering-instructions-update'])(+ '%s uses the current project and returns only steering fields',+ async (name) => {+ const instructions = {+ research_instructions: '',+ implementation_instructions: 'Run regression tests.',+ scout_instructions: 'Inspect onboarding.',+ }+ const request = vi.fn().mockResolvedValue({ ...instructions, autostart_enabled: false })+ const context = {+ api: { request },+ stateManager: { getProjectId: async () => '42' },+ } as unknown as Context+ const tool = GENERATED_TOOLS[name]!()+ const input =+ name === 'inbox-steering-instructions-update'+ ? { research_instructions: '', autostart_enabled: true }+ : {}++ expect(await tool.handler(context, tool.schema.parse(input))).toEqual(instructions)+ expect(request).toHaveBeenCalledWith({+ method: name === 'inbox-steering-instructions-get' ? 'GET' : 'POST',+ path: '/api/projects/42/signals/config/',+ ...(name === 'inbox-steering-instructions-update' ? { body: { research_instructions: '' } } : {}),+ })+ }+ )++ it.each(['research_instructions', 'implementation_instructions', 'scout_instructions'])(+ 'enforces the API length and null constraints for %s',+ (field) => {+ const schema = GENERATED_TOOLS['inbox-steering-instructions-update']!().schema+ expect(schema.safeParse({ [field]: null }).success).toBe(false)+ expect(schema.safeParse({ [field]: 'x'.repeat(20_001) }).success).toBe(false)+ expect(schema.parse({ [field]: 'x'.repeat(20_000) })).toEqual({ [field]: 'x'.repeat(20_000) })+ }+ )+})