: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(tasks): add task profiles and accept one at task creation (#123784)
Charles Vienc7a60f6f5e68
diff --git a/products/business_knowledge/backend/api/playground.py b/products/business_knowledge/backend/api/playground.pyindex 7202c049df7d..cecbde215882 100644--- a/products/business_knowledge/backend/api/playground.py+++ b/products/business_knowledge/backend/api/playground.py@@ -20,6 +20,7 @@ from posthog.rate_limit import BurstRateThrottle, SustainedRateThrottlefrom products.access_control.backend.facade.user_access_control import UserAccessControl+from ..constants import MAX_OPEN_RUNS_PER_OWNERfrom ..models import PlaygroundChatfrom ..playground import (ask_playground_chat,@@ -27,7 +28,7 @@ from ..playground import (serialize_playground_chat,serialize_playground_chat_list,)-from ..sandbox import MAX_OPEN_RUNS_PER_OWNER, SandboxRunInProgress, SandboxRunLimitReached+from ..sandbox import SandboxRunInProgress, SandboxRunLimitReachedfrom .sandbox import SandboxConflictfrom .serializers import PlaygroundChatListSerializer, PlaygroundChatSerializer, SandboxQuestionSerializerfrom .settings import CanonicalTeamTokenPermissiondiff --git a/products/business_knowledge/backend/apps.py b/products/business_knowledge/backend/apps.pyindex 8445ab24d444..7b9a9c6fc02b 100644--- a/products/business_knowledge/backend/apps.py+++ b/products/business_knowledge/backend/apps.py@@ -9,4 +9,6 @@ class BusinessKnowledgeConfig(AppConfig):verbose_name = "Business knowledge"def ready(self) -> None:- from . import signals # noqa: F401+ from . import signals, task_profiles # noqa: F401++ task_profiles.register()diff --git a/products/business_knowledge/backend/constants.py b/products/business_knowledge/backend/constants.pyindex dc7b252ce94b..058b6765a72d 100644--- a/products/business_knowledge/backend/constants.py+++ b/products/business_knowledge/backend/constants.py@@ -240,3 +240,12 @@ BK_DRILLDOWN_DEFAULT_RADIUS = 5# Hard cap on drill-down radius. radius=15 => up to 31 chunks ~= 50k chars;# bounds how much one read_data call can pull.BK_DRILLDOWN_MAX_RADIUS = 15++# Chats run in parallel, but the request throttles skip session auth, so this caps billable runs per person.+MAX_OPEN_RUNS_PER_OWNER = 3++BK_MCP_SCOPE = "business_knowledge:read"+# The PostHog MCP server reads /api/users/@me/ to start a session, so without user:read it never connects.+# It reads the project to find its organization, and the business knowledge tools sit behind a flag+# targeted by organization, so without project:read the search tool is hidden.+BK_MCP_SCOPES = [BK_MCP_SCOPE, "user:read", "project:read"]diff --git a/products/business_knowledge/backend/playground.py b/products/business_knowledge/backend/playground.pyindex cbe94e430aed..7a284de25901 100644--- a/products/business_knowledge/backend/playground.py+++ b/products/business_knowledge/backend/playground.py@@ -11,9 +11,9 @@ from posthog.models.user import Userfrom products.tasks.backend.facade.contracts import CreatedTaskDTO, TaskRunDTO+from .constants import MAX_OPEN_RUNS_PER_OWNERfrom .models import PlaygroundChat, PlaygroundTurnfrom .sandbox import (- MAX_OPEN_RUNS_PER_OWNER,SandboxPollStatus,SandboxRunInProgress,SandboxRunLimitReached,diff --git a/products/business_knowledge/backend/sandbox.py b/products/business_knowledge/backend/sandbox.pyindex 9cbf0719ccb7..4703cd1040cc 100644--- a/products/business_knowledge/backend/sandbox.py+++ b/products/business_knowledge/backend/sandbox.py@@ -18,6 +18,7 @@ from posthog.models.user import Userfrom products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.contracts import CreatedTaskDTO, TaskRunDTO+from .constants import BK_MCP_SCOPESfrom .github_repos import repository_tools_enabledfrom .logic import KnowledgeSearchResult, get_always_on_context@@ -25,15 +26,8 @@ BUSINESS_KNOWLEDGE_SANDBOX_ENV_NAME = "BUSINESS_KNOWLEDGE_SANDBOX"SANDBOX_MODEL = "claude-sonnet-5"SANDBOX_RUNTIME_ADAPTER = "claude"MAX_SANDBOX_QUESTION_CHARS = 4_000-# Chats run in parallel, but the request throttles skip session auth, so this caps billable runs per person.-MAX_OPEN_RUNS_PER_OWNER = 3FINISHED_ACTIVITY_CACHE_SECONDS = 60 * 60-BK_MCP_SCOPE = "business_knowledge:read"-# The PostHog MCP server reads /api/users/@me/ to start a session, so without user:read it never connects.-# It reads the project to find its organization, and the business knowledge tools sit behind a flag-# targeted by organization, so without project:read the search tool is hidden.-BK_MCP_SCOPES = [BK_MCP_SCOPE, "user:read", "project:read"]BK_SEARCH_TOOL = "business-knowledge-documents-search"BK_WINDOW_TOOL = "business-knowledge-document-window-retrieve"BK_REPO_SEARCH_TOOL = "business-knowledge-repositories-search"diff --git a/products/business_knowledge/backend/task_profiles.py b/products/business_knowledge/backend/task_profiles.pynew file mode 100644index 000000000000..ccd948b7eafc--- /dev/null+++ b/products/business_knowledge/backend/task_profiles.py@@ -0,0 +1,55 @@+from products.tasks.backend.facade.profiles import (+ AccessGate,+ DrivePolicy,+ GithubResolution,+ OAuthApp,+ PrAuthorship,+ Read,+ TaskProfile,+ register_task_profiles,+)++from .constants import BK_MCP_SCOPES, MAX_OPEN_RUNS_PER_OWNER++BUSINESS_KNOWLEDGE = TaskProfile(+ key="business_knowledge",+ origin_product="business_knowledge",+ public=False,+ public_options=frozenset(),+ source_kind=None,+ listed=False,+ read_without_channel=Read.CREATOR,+ api_visible=False,+ drive=DrivePolicy.OWNER,+ access_gate=AccessGate.NONE,+ max_live_per_user=MAX_OPEN_RUNS_PER_OWNER,+ warm=None,+ runtimes=("acp",),+ sandbox_templates=("default_base",),+ inherit_user_defaults=False,+ personal_mcp=False,+ mcp_agent=None,+ mcp_scopes=BK_MCP_SCOPES,+ mcp_store_servers=False,+ oauth_app=OAuthApp.ARRAY,+ github_resolution=GithubResolution.ALWAYS,+ user_authorable_prs=False,+ default_pr_authorship=PrAuthorship.BOT,+ finish_tool=False,+ done_on_turn_close=False,+ idle_minutes=30,+ inactivity_minutes=10,+ tool_call_minutes=None,+ max_wake_minutes=180,+ billing_product="background_agents",+ bills_compute=False,+ max_cost_usd=None,+ task_budget_usd=None,+ finish_in_flight=True,+)++PROFILES = (BUSINESS_KNOWLEDGE,)+++def register() -> None:+ register_task_profiles(PROFILES)diff --git a/products/business_knowledge/backend/tests/test_playground.py b/products/business_knowledge/backend/tests/test_playground.pyindex eb219fa25200..f92131fc52d2 100644--- a/products/business_knowledge/backend/tests/test_playground.py+++ b/products/business_knowledge/backend/tests/test_playground.py@@ -12,8 +12,8 @@ from posthog.models.team import Teamfrom posthog.models.user import Userfrom products.business_knowledge.backend.api.playground import BusinessKnowledgePlaygroundChatViewSet+from products.business_knowledge.backend.constants import MAX_OPEN_RUNS_PER_OWNERfrom products.business_knowledge.backend.models import PlaygroundChat, PlaygroundTurn-from products.business_knowledge.backend.sandbox import MAX_OPEN_RUNS_PER_OWNERfrom products.tasks.backend.models import Task, TaskRunWORKFLOW = "products.tasks.backend.temporal.client.execute_task_processing_workflow"diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex ccaa5e2cd046..4052877d0014 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -9,7 +9,7 @@ from concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclass, field, replacefrom datetime import UTC, datetime, timedeltafrom pathlib import PurePosixPath-from typing import TYPE_CHECKING, Any, Literal, TypeVar+from typing import TYPE_CHECKING, Any, Literal, TypeVar, castfrom urllib.parse import urlparsefrom uuid import UUID, uuid4@@ -101,6 +101,7 @@ from products.tasks.backend.constants import ()from products.tasks.backend.error_telemetry import truncate_error_messagefrom products.tasks.backend.facade.gateway import mint_private_gateway_token, revoke_private_gateway_token+from products.tasks.backend.facade.profiles import TaskProfile, resolve_task_originfrom products.tasks.backend.feature_flags import (get_model_access_error,own_subscription_cloud_enabled as own_subscription_cloud_enabled,@@ -1988,8 +1989,9 @@ def create_and_run_task(team,title: str,description: str,- origin_product: "Task.OriginProduct",user_id: int,+ origin_product: "Task.OriginProduct | None" = None,+ profile: TaskProfile | None = None,repository: str | None = None,create_pr: bool = True,mode: str = "background",@@ -1998,7 +2000,7 @@ def create_and_run_task(branch: str | None = None,signal_report_id: str | None = None,free_trial_enabled: bool | None = None,- internal: bool = False,+ internal: bool | None = None,sandbox_environment_id: str | None = None,channel_id: str | UUID | None = None,**extra,@@ -2021,6 +2023,9 @@ def create_and_run_task(materializes it at or after that time. The run still stores its complete execution settings."""+ origin = resolve_task_origin(profile=profile, origin_product=origin_product, internal=internal)+ origin_product = cast("Task.OriginProduct", origin.origin_product)+ internal = origin.internal# create_pr=False sessions (research, repo selection, custom agents) can never open the# billable PR, so the quota gate must not block them.if origin_product == Task.OriginProduct.SIGNAL_REPORT and create_pr:@@ -2039,6 +2044,7 @@ def create_and_run_task(title=title,description=description,origin_product=origin_product,+ profile=profile,user_id=user_id,repository=repository,channel=channel,@@ -2225,7 +2231,8 @@ def create_task_without_run(*,team,user_id: int,- origin_product: "Task.OriginProduct",+ origin_product: "Task.OriginProduct | None" = None,+ profile: TaskProfile | None = None,title: str = "",description: str = "",repository: str | None = None,@@ -2237,15 +2244,19 @@ def create_task_without_run(For callers that own run creation themselves — e.g. the sandbox warm path, which boots the firstrun via the warming facade. ``team`` is a core ``posthog.Team`` (not a tasks model)."""+ origin = resolve_task_origin(profile=profile, origin_product=origin_product, internal=None)if channel is None:channel = (- None if origin_product in TEAM_READABLE_ORIGIN_PRODUCTS else _ensure_personal_channel(team.id, user_id)[0]+ None+ if origin.origin_product in TEAM_READABLE_ORIGIN_PRODUCTS+ else _ensure_personal_channel(team.id, user_id)[0])task = Task.create_without_run(team=team,title=title,description=description,- origin_product=origin_product,+ origin_product=cast("Task.OriginProduct", origin.origin_product),+ profile=profile,user_id=user_id,repository=repository,channel=channel,diff --git a/products/tasks/backend/facade/profiles.py b/products/tasks/backend/facade/profiles.pynew file mode 100644index 000000000000..0a8618c1c971--- /dev/null+++ b/products/tasks/backend/facade/profiles.py@@ -0,0 +1,310 @@+from __future__ import annotations++from collections.abc import Iterable+from decimal import Decimal+from enum import StrEnum+from typing import TYPE_CHECKING, Any++from posthog.dataclasses import frozen++if TYPE_CHECKING:+ from posthog.temporal.oauth import PosthogMcpScopes+++class Read(StrEnum):+ CREATOR = "creator"+ TEAM = "team"+++class DrivePolicy(StrEnum):+ OWNER = "owner"+ AUDIENCE = "audience"+ NONE = "none"+++class AccessGate(StrEnum):+ DESKTOP_CODE = "desktop_code"+ INBOX = "inbox"+ NONE = "none"+++class GithubResolution(StrEnum):+ ALWAYS = "always"+ WITH_REPOSITORY = "with_repository"+ NEVER = "never"+++class OAuthApp(StrEnum):+ ARRAY = "array"+ POSTHOG_AI = "posthog_ai"+ SIGNALS = "signals"+++class PrAuthorship(StrEnum):+ USER = "user"+ BOT = "bot"+++class WarmQuota(StrEnum):+ NONE = "none"+ AI_CREDITS = "ai_credits"+++class GithubAccess(StrEnum):+ NONE = "none"+ READ = "read"+ WRITE = "write"+++@frozen+class WarmPolicy:+ """Lets a profile start a sandbox before the first message arrives, so the first reply is fast."""++ # AI_CREDITS checks the team's AI credit quota before it warms a sandbox. NONE warms with no quota check.+ quota: WarmQuota+ # The most warm runs one user may hold at once. A warm run stops counting when it gets its first message.+ per_user_cap: int+ # The most warm runs one organization may hold at once, counted the same way.+ per_org_cap: int+ # Feature flag checked for the user and their organization before warming. None warms for every user.+ feature_flag: str | None+++@frozen+class TaskProfile:+ """The limits and defaults for one kind of task.++ Each product defines its own profiles and registers them when its app loads, so the tasks+ product never imports another product. A task keeps its profile for its whole life. Values+ that change per call go in RunOptions, which can only choose from or narrow what the profile+ allows.+ """++ # Stable ID stored on Task.profile, such as "signals.implementation". Never rename a key,+ # because stored tasks keep the old one.+ key: str+ # The analytics label, stored on Task.origin_product. Each profile has exactly one.+ # Behavior comes from the fields below, never from this label.+ origin_product: str+ # True lets callers create this kind of task through the public task API.+ public: bool+ # The RunOptions fields a public API caller may set. The server refuses any other field from+ # a public caller.+ public_options: frozenset[str]+ # The kind of row that started the task, such as "signal_report". The server checks that the+ # row exists in the caller's team. None means the task has no source row.+ source_kind: str | None++ # True shows the task in task lists, personal channel filing, auto-archive, the MCP task filter+ # and the Desktop staff toggle. Automated work such as loops and scouts is unlisted.+ # Task.internal stores the inverse of this value.+ listed: bool+ # Who can read a task that is not filed in a channel. CREATOR means only the creator. TEAM+ # means every member of the team. A task in a channel follows the channel's members instead.+ read_without_channel: Read+ # False hides the task from the public task API, because it holds another product's data that+ # only that product reads through its own facade. The sandbox that runs the task keeps access.+ api_visible: bool+ # Who can send follow-up messages. OWNER means only the owner. Everyone else gets a 403.+ # AUDIENCE means anyone who can read the task, such as the people in a Slack thread.+ # NONE means nobody, for tasks that finish on their own.+ drive: DrivePolicy+ # A check on the person that runs at create and again on every wake. DESKTOP_CODE requires+ # PostHog Code access in the organization. INBOX requires inbox access. NONE runs no check.+ access_gate: AccessGate+ # The most queued or running tasks one person may have on this profile at once. Create and+ # wake refuse at the cap. None means no cap.+ max_live_per_user: int | None+ # How the profile warms sandboxes before the first message. None means it cannot warm.+ warm: WarmPolicy | None++ # The agent runtimes a task may use, "acp" or "pi". The first one is the default.+ runtimes: tuple[str, ...]+ # The sandbox templates a task may boot from. The first one is the default.+ sandbox_templates: tuple[str, ...]+ # True applies the creator's and the team's default model settings to each run.+ inherit_user_defaults: bool+ # True also installs the creator's personal MCP servers. It has no effect when+ # mcp_store_servers is False.+ personal_mcp: bool+ # The built-in MCP agent the task acts as: "support", "scout" or "workflow". The sandbox then+ # gets that agent's MCP servers instead of its creator's MCP store connections. None means the+ # task uses its creator's connections.+ mcp_agent: str | None+ # The widest PostHog MCP scope preset the agent can get. RunOptions.mcp_scopes can narrow it+ # but never widen it.+ mcp_scopes: PosthogMcpScopes+ # True installs the team's MCP store servers in the sandbox. False installs none, personal+ # servers included.+ mcp_store_servers: bool+ # The OAuth application that mints the sandbox's PostHog tokens. The LLM gateway pins billing+ # products per application, so a token from a shared application is valid for every product on+ # it. A product with its own billing needs its own application.+ oauth_app: OAuthApp+ # When the task gets the team's GitHub integration. ALWAYS attaches it. WITH_REPOSITORY+ # attaches it only when the task has a repository. NEVER attaches none. Use NEVER for tasks+ # that read text members wrote, because a token there turns planted text into repository access.+ github_resolution: GithubResolution+ # True lets runs open pull requests as the creator through their personal GitHub installation.+ # A creator without a usable installation falls back to the bot. False always uses the bot.+ user_authorable_prs: bool+ # Who authors pull requests when the run does not set RunOptions.pr_authorship_mode.+ default_pr_authorship: PrAuthorship+ # True gives the agent a finish tool that moves the task to done.+ finish_tool: bool+ # True moves the task to done when a turn closes, including a failed turn. Use it for work that+ # nobody replies to, such as loops, workflow steps and scouts, so idle tasks don't pile up.+ done_on_turn_close: bool++ # How long the sandbox stays up after a turn closes, in case someone replies. After that the+ # task snapshots, releases the sandbox and goes idle. RunOptions.idle_minutes can lower it.+ idle_minutes: int+ # How long an open turn may go without an agent heartbeat. After that the run fails, so a retry+ # can pick the task back up.+ inactivity_minutes: int+ # How long one tool call or permission prompt may hold the sandbox. None means no cap.+ tool_call_minutes: int | None+ # Wall-clock cap on one wake. Heartbeats do not reset it, so it stops an agent that hangs but+ # keeps heartbeating. None means no cap.+ max_wake_minutes: int | None++ # The exact LLM gateway product, pinned on the run's credential when it is minted. The gateway+ # ignores any product the agent sends. The usage report groups customer billing by this value.+ billing_product: str+ # True bills sandbox compute to the customer. Compute cost is recorded either way.+ bills_compute: bool+ # Spend cap for one wake, counting inference and compute. It resets on every wake. None means+ # no cap.+ max_cost_usd: Decimal | None+ # Spend cap for the whole task across every wake, counting inference and compute. None means+ # no cap.+ task_budget_usd: Decimal | None+ # True lets a running wake finish when the organization runs out of credit. False stops the+ # wake and snapshots the task.+ finish_in_flight: bool+++@frozen+class Repository:+ # The GitHub repository as "org/repo".+ name: str+ # The branch the first run starts from. Later runs boot from the task's snapshot instead.+ initial_branch: str | None = None+++@frozen+class RunOptions:+ """Per-call settings for one task, checked against its TaskProfile.++ A public API caller can only set the fields in TaskProfile.public_options. None or an empty+ tuple means the profile's default.+ """++ # "acp" or "pi". It must be one of TaskProfile.runtimes and cannot change after create.+ runtime: str | None = None+ # The agent harness, "claude" or "codex". The server derives it from the model when unset.+ adapter: str | None = None+ # The LLM model ID. A pi task runs any listed model and takes no adapter.+ model: str | None = None+ # Reasoning effort for models that expose an effort control. A follow-up can change it.+ reasoning_effort: str | None = None+ # The repositories cloned into the sandbox.+ repositories: tuple[Repository, ...] = ()+ # A local folder used as the workspace instead of repositories. Local runs only.+ folder: str | None = None+ # It must be one of TaskProfile.sandbox_templates.+ sandbox_template: str | None = None+ # A JSON schema that the agent's final answer must match.+ output_schema: dict[str, Any] | None = None+ # It can lower TaskProfile.idle_minutes but never raise it.+ idle_minutes: int | None = None+ # NONE, READ or WRITE. It can never go above the GitHub access the profile allows.+ github_access: GithubAccess | None = None+ # It can narrow TaskProfile.mcp_scopes but never widen it.+ mcp_scopes: PosthogMcpScopes | None = None+ # The MCP servers to install, by ID. Only server callers can set it. The profile must have an+ # mcp_agent.+ mcp_server_ids: tuple[str, ...] = ()+ # Context window size for models that support the 1M window.+ context_window: str | None = None+ # Fast mode for models that support it.+ fast_mode: bool | None = None+ # The agent's starting permission mode, such as "plan". Claude and Codex accept different values.+ permission_mode: str | None = None+ # Who authors pull requests for this task. It overrides TaskProfile.default_pr_authorship.+ pr_authorship_mode: PrAuthorship | None = None+ # True makes the agent push its work and open a draft pull request when it finishes, without+ # waiting to be asked.+ auto_publish: bool | None = None+++@frozen+class TaskOrigin:+ origin_product: str+ internal: bool+ profile_key: str | None+++class TaskProfileError(ValueError):+ pass+++# Tasks stored without a profile and SQL filters only know a task's origin_product, so every profile+# that shares an origin must agree on these fields.+_ORIGIN_SCOPED_FIELDS = (+ "read_without_channel",+ "drive",+ "api_visible",+ "access_gate",+ "idle_minutes",+ "max_wake_minutes",+ "warm",+)++_profiles: dict[str, TaskProfile] = {}+++def register_task_profile(profile: TaskProfile) -> None:+ existing = _profiles.get(profile.key)+ if existing is not None and existing != profile:+ raise TaskProfileError(f"Task profile {profile.key!r} is already registered with different values")+ for other in _profiles.values():+ if other.key == profile.key or other.origin_product != profile.origin_product:+ continue+ for name in _ORIGIN_SCOPED_FIELDS:+ if getattr(other, name) != getattr(profile, name):+ raise TaskProfileError(+ f"Task profiles {other.key!r} and {profile.key!r} share origin {profile.origin_product!r} "+ f"but disagree on {name}"+ )+ _profiles[profile.key] = profile+++def register_task_profiles(profiles: Iterable[TaskProfile]) -> None:+ for profile in profiles:+ register_task_profile(profile)+++def get_task_profile(key: str) -> TaskProfile:+ try:+ return _profiles[key]+ except KeyError:+ raise TaskProfileError(f"Unknown task profile {key!r}") from None+++def task_profiles() -> tuple[TaskProfile, ...]:+ return tuple(_profiles.values())+++def resolve_task_origin(+ *, profile: TaskProfile | None, origin_product: str | None, internal: bool | None+) -> TaskOrigin:+ if profile is None:+ if not origin_product:+ raise TaskProfileError("Pass a task profile or an origin product")+ return TaskOrigin(origin_product=origin_product, internal=bool(internal), profile_key=None)+ if origin_product is not None and origin_product != profile.origin_product:+ raise TaskProfileError(f"Origin {origin_product!r} does not match task profile {profile.key!r}")+ if internal is not None and internal == profile.listed:+ raise TaskProfileError(f"internal={internal} does not match task profile {profile.key!r}")+ return TaskOrigin(origin_product=profile.origin_product, internal=not profile.listed, profile_key=profile.key)diff --git a/products/tasks/backend/migrations/0142_task_profile_and_source.py b/products/tasks/backend/migrations/0142_task_profile_and_source.pynew file mode 100644index 000000000000..14a10390de7e--- /dev/null+++ b/products/tasks/backend/migrations/0142_task_profile_and_source.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.18 on 2026-10-20 18:37++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("tasks", "0141_remove_agent_peer_message"),+ ]++ operations = [+ migrations.AddField(+ model_name="task",+ name="profile",+ field=models.CharField(blank=True, max_length=64, null=True),+ ),+ ]diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txtindex 58031de06b1b..719d6408f792 100644--- a/products/tasks/backend/migrations/max_migration.txt+++ b/products/tasks/backend/migrations/max_migration.txt@@ -1 +1 @@-0141_remove_agent_peer_message+0142_task_profile_and_sourcediff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 6ef5a40232b9..bda5ba5e84e3 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -5,7 +5,7 @@ import jsonimport uuidfrom collections.abc import Callable, Iterablefrom datetime import datetime-from typing import TYPE_CHECKING, Any, Literal, Optional+from typing import TYPE_CHECKING, Any, Literal, Optional, castfrom django.db.models.signals import post_delete, post_save, pre_deletefrom django.dispatch import receiver@@ -52,6 +52,7 @@ from products.tasks.backend.dev_stack_image_models import (DevStackImageTarget as DevStackImageTarget,)from products.tasks.backend.error_telemetry import truncate_error_message+from products.tasks.backend.facade.profiles import TaskProfile, resolve_task_originfrom products.tasks.backend.feature_flags import (is_task_run_stream_presence_gated,is_task_run_stream_thin_tail,@@ -456,6 +457,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):title_manually_set = models.BooleanField(default=False)description = models.TextField()origin_product = models.CharField(max_length=20, choices=task_origin_product_choices)+ profile = models.CharField(max_length=64, null=True, blank=True)client_provenance = models.CharField(max_length=32,choices=task_client_provenance_choices,@@ -1252,6 +1254,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):mcp_credential_owner_id: int | None = None,mcp_gateway_server_ids: list[str] | None = None,mcp_tool_allowlist: list[str] | None = None,+ profile_key: str | None = None,) -> tuple["Task", dict[str, Any]]:"""Prepare an unsaved Task and the initial run's `extra_state`.@@ -1383,6 +1386,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):title_manually_set=title_manually_set,description=description,origin_product=origin_product,+ profile=profile_key,client_provenance=client_provenance,created_by=created_by,github_integration=github_integration,@@ -1536,8 +1540,9 @@ class Task(Taggable, DeletedMetaFields, models.Model):team: Team,title: str,description: str,- origin_product: "Task.OriginProduct",user_id: int,+ origin_product: "Task.OriginProduct | None" = None,+ profile: TaskProfile | None = None,repository: str | None = None,repositories: list[str] | None = None,channel: Channel | None = None,@@ -1546,7 +1551,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):branch: str | None = None,signal_report_id: str | None = None,sandbox_environment_id: str | None = None,- internal: bool = False,+ internal: bool | None = None,output_schema: type[BaseModel] | dict | None = None,interaction_origin: str | None = None,model: str | None = None,@@ -1562,11 +1567,13 @@ class Task(Taggable, DeletedMetaFields, models.Model):(`products/tasks/backend/logic/services/warm.py`), which creates the first run with itsown state. The run `extra_state` assembled by `_build_task` is discarded here."""+ origin = resolve_task_origin(profile=profile, origin_product=origin_product, internal=internal)task, _ = Task._build_task(team=team,title=title,description=description,- origin_product=origin_product,+ origin_product=cast("Task.OriginProduct", origin.origin_product),+ profile_key=origin.profile_key,user_id=user_id,repository=repository,repositories=repositories,@@ -1576,7 +1583,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):branch=branch,signal_report_id=signal_report_id,sandbox_environment_id=sandbox_environment_id,- internal=internal,+ internal=origin.internal,output_schema=output_schema,interaction_origin=interaction_origin,model=model,@@ -1595,8 +1602,9 @@ class Task(Taggable, DeletedMetaFields, models.Model):team: Team,title: str,description: str,- origin_product: "Task.OriginProduct",user_id: int,+ origin_product: "Task.OriginProduct | None" = None,+ profile: TaskProfile | None = None,title_manually_set: bool = False,repository: str | None = None, # Format: "organization/repository", e.g. "posthog/posthog-js"repositories: list[str] | None = None,@@ -1615,7 +1623,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):origin_key: str | None = None,extra_run_state: dict[str, Any] | None = None,sandbox_environment_id: str | None = None,- internal: bool = False,+ internal: bool | None = None,client_provenance: TaskClientProvenance | None = None,output_schema: type[BaseModel] | dict | None = None,interaction_origin: str | None = None,@@ -1663,11 +1671,15 @@ class Task(Taggable, DeletedMetaFields, models.Model):if carried_template is not None:sandbox_template = carried_template+ origin = resolve_task_origin(profile=profile, origin_product=origin_product, internal=internal)+ origin_product = cast("Task.OriginProduct", origin.origin_product)+ internal = origin.internaltask, extra_state = Task._build_task(team=team,title=title,description=description,origin_product=origin_product,+ profile_key=origin.profile_key,user_id=user_id,title_manually_set=title_manually_set,repository=repository,diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex 4a4a65ba0bbc..fe9eea498160 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -28,6 +28,7 @@ from products.tasks.backend.facade import (contracts,warm as warm_facade,)+from products.tasks.backend.facade.profiles import TaskProfileError, get_task_profilefrom products.tasks.backend.models import (TASK_OWNERSHIP_VERSION_STATE_KEY,Channel,@@ -1755,6 +1756,60 @@ class TestFacadeReadsAndMappers(TestCase):assert created.latest_run is not Noneself.assertEqual(created.latest_run.task_id, created.task_id)+ @parameterized.expand(+ [+ (+ "create_and_run_task_origin",+ "create_and_run_task",+ {"origin_product": facade.TaskOriginProduct.BUSINESS_KNOWLEDGE, "internal": True},+ ("business_knowledge", True, None),+ ),+ (+ "create_and_run_task_profile",+ "create_and_run_task",+ {"profile": get_task_profile("business_knowledge")},+ ("business_knowledge", True, "business_knowledge"),+ ),+ (+ "create_task_without_run_origin",+ "create_task_without_run",+ {"origin_product": facade.TaskOriginProduct.BUSINESS_KNOWLEDGE},+ ("business_knowledge", False, None),+ ),+ (+ "create_task_without_run_profile",+ "create_task_without_run",+ {"profile": get_task_profile("business_knowledge")},+ ("business_knowledge", True, "business_knowledge"),+ ),+ ]+ )+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_facade_creates_a_task_from_an_origin_or_a_profile(+ self, _name: str, entry: str, origin_kwargs: dict, expected: tuple[str, bool, str | None], _mock_workflow+ ) -> None:+ created = getattr(facade, entry)(+ team=self.team, title="t", description="d", user_id=self.user.id, **origin_kwargs+ )++ task = Task.objects.get(id=created if isinstance(created, UUID) else created.task_id)+ self.assertEqual((task.origin_product, task.internal, task.profile), expected)++ @parameterized.expand(+ [+ ("create_and_run_task_neither", "create_and_run_task", {}),+ ("create_and_run_task_internal_only", "create_and_run_task", {"internal": True}),+ ("create_and_run_task_empty_origin", "create_and_run_task", {"origin_product": ""}),+ ("create_task_without_run_neither", "create_task_without_run", {}),+ ("create_task_without_run_empty_origin", "create_task_without_run", {"origin_product": ""}),+ ]+ )+ def test_facade_refuses_a_task_with_no_profile_or_origin(self, _name: str, entry: str, origin_kwargs: dict) -> None:+ with self.assertRaises(TaskProfileError):+ getattr(facade, entry)(team=self.team, title="t", description="d", user_id=self.user.id, **origin_kwargs)++ self.assertFalse(Task.objects.filter(team=self.team, title="t").exists())+@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_slack_report_link_is_idempotent_and_does_not_claim_implementation(self, _mock_workflow):from products.signals.backend.models import (diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.pyindex 891f5e178c43..ffafc66930b1 100644--- a/products/tasks/backend/tests/test_models.py+++ b/products/tasks/backend/tests/test_models.py@@ -21,6 +21,7 @@ from posthog.models.user import Userfrom posthog.models.user_integration import UserIntegrationfrom posthog.storage import object_storage+from products.tasks.backend.facade.profiles import TaskProfileError, get_task_profilefrom products.tasks.backend.models import (MAX_PENDING_FOLLOWUP_CONTENT_CHARS,MAX_PENDING_FOLLOWUP_MESSAGES,@@ -34,6 +35,8 @@ from products.tasks.backend.models import (bump_task_activity,)+BUSINESS_KNOWLEDGE = get_task_profile("business_knowledge")+# Far enough back that any bump is unambiguously forward, and stable so a test can assert the# clock did *not* move.STALE_ACTIVITY_AT = datetime(2020, 1, 1, tzinfo=UTC)@@ -128,6 +131,50 @@ class TestTask(TestCase):self.assertEqual(task_run.task, task)self.assertEqual(task_run.status, TaskRun.Status.QUEUED)+ @parameterized.expand(+ [+ (f"{entry}_{path}", entry, origin_kwargs, expected_profile)+ for entry in ("create_and_run", "create_without_run")+ for path, origin_kwargs, expected_profile in (+ ("origin", {"origin_product": Task.OriginProduct.BUSINESS_KNOWLEDGE, "internal": True}, None),+ ("profile", {"profile": BUSINESS_KNOWLEDGE}, "business_knowledge"),+ )+ ]+ )+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_task_creation_stores_the_same_origin_from_an_origin_or_a_profile(+ self, name: str, entry: str, origin_kwargs: dict, expected_profile: str | None, _mock_execute_workflow+ ) -> None:+ user = User.objects.create(email=f"{name}@test.com")++ task = getattr(Task, entry)(team=self.team, title="t", description="d", user_id=user.id, **origin_kwargs)++ task.refresh_from_db()+ self.assertEqual(+ (task.origin_product, task.internal, task.profile), ("business_knowledge", True, expected_profile)+ )++ @parameterized.expand(+ [+ (f"{entry}_{path}", entry, origin_kwargs)+ for entry in ("create_and_run", "create_without_run")+ for path, origin_kwargs in (+ ("neither", {}),+ ("internal_only", {"internal": True}),+ ("empty_origin", {"origin_product": ""}),+ )+ ]+ )+ def test_task_creation_refuses_a_task_with_no_profile_or_origin(+ self, name: str, entry: str, origin_kwargs: dict+ ) -> None:+ user = User.objects.create(email=f"{name}@test.com")++ with self.assertRaises(TaskProfileError):+ getattr(Task, entry)(team=self.team, title="t", description="d", user_id=user.id, **origin_kwargs)++ self.assertFalse(Task.objects.filter(team=self.team).exists())+@parameterized.expand([("committed", False), ("rolled_back", True)])def test_create_and_run_captures_only_committed_tasks(self, _name: str, rolled_back: bool) -> None:user = User.objects.create(email="[email protected]")diff --git a/products/tasks/backend/tests/test_profiles.py b/products/tasks/backend/tests/test_profiles.pynew file mode 100644index 000000000000..41699ab82863--- /dev/null+++ b/products/tasks/backend/tests/test_profiles.py@@ -0,0 +1,78 @@+from dataclasses import replace++from django.test import SimpleTestCase++from parameterized import parameterized++from products.tasks.backend.facade.profiles import (+ Read,+ TaskProfile,+ TaskProfileError,+ get_task_profile,+ register_task_profile,+ resolve_task_origin,+)++BUSINESS_KNOWLEDGE = get_task_profile("business_knowledge")+++class TestTaskProfileRegistry(SimpleTestCase):+ @parameterized.expand(+ [+ ("read_without_channel", {"read_without_channel": Read.TEAM}),+ ("idle_minutes", {"idle_minutes": 5}),+ ]+ )+ def test_rejects_a_profile_that_disagrees_with_its_origin(self, _name: str, overrides: dict) -> None:+ conflicting = replace(BUSINESS_KNOWLEDGE, key="test.conflicting", **overrides)++ with self.assertRaises(TaskProfileError):+ register_task_profile(conflicting)++ @parameterized.expand(+ [+ ("profile_only", BUSINESS_KNOWLEDGE, None, None, ("business_knowledge", True, "business_knowledge")),+ (+ "profile_and_matching_origin",+ BUSINESS_KNOWLEDGE,+ "business_knowledge",+ None,+ ("business_knowledge", True, "business_knowledge"),+ ),+ (+ "profile_and_matching_internal",+ BUSINESS_KNOWLEDGE,+ None,+ True,+ ("business_knowledge", True, "business_knowledge"),+ ),+ ("origin_and_internal", None, "business_knowledge", True, ("business_knowledge", True, None)),+ ("origin_without_internal", None, "user_created", None, ("user_created", False, None)),+ ]+ )+ def test_resolve_task_origin_accepts_a_profile_or_an_origin(+ self,+ _name: str,+ profile: TaskProfile | None,+ origin: str | None,+ internal: bool | None,+ expected: tuple[str, bool, str | None],+ ) -> None:+ resolved = resolve_task_origin(profile=profile, origin_product=origin, internal=internal)++ self.assertEqual((resolved.origin_product, resolved.internal, resolved.profile_key), expected)++ @parameterized.expand(+ [+ ("neither", None, None, None),+ ("empty_origin", None, "", None),+ ("internal_without_origin", None, None, True),+ ("origin_mismatch", BUSINESS_KNOWLEDGE, "loop", None),+ ("internal_mismatch", BUSINESS_KNOWLEDGE, None, False),+ ]+ )+ def test_resolve_task_origin_rejects_conflicting_input(+ self, _name: str, profile: TaskProfile | None, origin: str | None, internal: bool | None+ ) -> None:+ with self.assertRaises(TaskProfileError):+ resolve_task_origin(profile=profile, origin_product=origin, internal=internal)