Skip to content

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

feat(tasks): read pr authorship from the task profile (#126064)

Charles Vien5ebf52a81a90
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index ab8f1f057efb..d01d01696cbc 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -54,10 +54,13 @@ from products.tasks.backend.dev_stack_image_models import (
)
from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.facade.profiles import (
+ PrAuthorship,
TaskProfile,
+ TaskProfileError,
TaskRunOptions,
TaskSource,
check_task_source,
+ get_task_profile,
resolve_task_origin,
)
from products.tasks.backend.feature_flags import (
@@ -647,6 +650,22 @@ class Task(Taggable, DeletedMetaFields, models.Model):
if is_new:
transaction.on_commit(self._track_task_created)
+ @property
+ def stored_profile(self) -> TaskProfile | None:
+ if not self.profile:
+ return None
+ try:
+ return get_task_profile(self.profile)
+ except TaskProfileError:
+ logger.warning("task_profile_not_registered", task_id=str(self.id), profile=self.profile)
+ return None
+
+ def _resolves_pr_authorship_per_run(self) -> bool:
+ profile = self.stored_profile
+ if profile is None:
+ return self.origin_product == Task.OriginProduct.POSTHOG_AI
+ return profile.user_authorable_prs and profile.default_pr_authorship == PrAuthorship.BOT
+
@property
def mcp_builtin_agent_key(self) -> MCPBuiltInAgentKey | None:
expected_key = MCP_BUILT_IN_AGENT_KEY_BY_ORIGIN.get(self.origin_product)
@@ -937,7 +956,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
# Later runs keep the image the task was first provisioned with.
if carry_sandbox_template and previous_state.get("sandbox_template"):
state["sandbox_template"] = previous_state["sandbox_template"]
- if task.origin_product == Task.OriginProduct.POSTHOG_AI and "pr_authorship_mode" not in state:
+ if task._resolves_pr_authorship_per_run() and "pr_authorship_mode" not in state:
from products.tasks.backend.temporal.process_task.utils import (
PrAuthorshipMode,
resolve_user_github_integration_for_task,
@@ -1289,7 +1308,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,
+ profile: TaskProfile | None = None,
) -> tuple["Task", dict[str, Any]]:
"""Prepare an unsaved Task and the initial run's `extra_state`.
@@ -1318,10 +1337,10 @@ class Task(Taggable, DeletedMetaFields, models.Model):
parse_requested_sandbox_template(sandbox_template) if sandbox_template is not None else None
)
from products.tasks.backend.temporal.process_task.utils import (
- USER_AUTHORABLE_ORIGIN_PRODUCTS,
PrAuthorshipMode,
RunSource,
apply_runtime_adapter_run_state,
+ is_user_authorable,
resolve_user_github_integration_for_task,
user_github_integration_is_usable,
)
@@ -1349,9 +1368,8 @@ class Task(Taggable, DeletedMetaFields, models.Model):
github_integration_id=github_integration_id,
runtime=runtime,
)
- authorship_mode = (
- PrAuthorshipMode.USER if origin_product in USER_AUTHORABLE_ORIGIN_PRODUCTS else PrAuthorshipMode.BOT
- )
+ user_authorable = is_user_authorable(origin_product, profile)
+ authorship_mode = PrAuthorshipMode.USER if user_authorable else PrAuthorshipMode.BOT
if not github_resolution_allowed:
pass
elif authorship_mode == PrAuthorshipMode.USER:
@@ -1412,7 +1430,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
title_manually_set=title_manually_set,
description=description,
origin_product=origin_product,
- profile=profile_key,
+ profile=profile.key if profile else None,
client_provenance=client_provenance,
created_by=created_by,
github_integration_id=github_integration_id,
@@ -1443,7 +1461,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
if origin_product == Task.OriginProduct.SIGNAL_REPORT:
extra_state["run_source"] = RunSource.SIGNAL_REPORT.value
extra_state["pr_authorship_mode"] = PrAuthorshipMode.BOT.value
- elif origin_product in USER_AUTHORABLE_ORIGIN_PRODUCTS:
+ elif user_authorable:
extra_state["pr_authorship_mode"] = (
PrAuthorshipMode.USER.value if github_user_integration is not None else PrAuthorshipMode.BOT.value
)
@@ -1630,7 +1648,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
title=title,
description=description,
origin_product=cast("Task.OriginProduct", origin.origin_product),
- profile_key=origin.profile_key,
+ profile=profile,
user_id=user_id,
repository=repository,
repositories=repositories,
@@ -1785,7 +1803,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
title=title,
description=description,
origin_product=origin_product,
- profile_key=origin.profile_key,
+ profile=profile,
user_id=user_id,
title_manually_set=title_manually_set,
repository=repository,
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.py
index 318ae5d3c560..5278970a4e01 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
@@ -48,7 +48,6 @@ from products.tasks.backend.exceptions import (
TaskRunNotReadyError,
)
from products.tasks.backend.facade.api import ensure_task_run_session
-from products.tasks.backend.facade.profiles import TaskProfile, TaskProfileError, get_task_profile
from products.tasks.backend.feature_flags import own_subscription_cloud_enabled
from products.tasks.backend.logic.model_access import ModelAccess, resolve_model_access
from products.tasks.backend.logic.services.agent_instructions import agent_instructions_state_update
@@ -889,16 +888,6 @@ def _resolve_sandbox_backend(
return "hogland" if enabled else "modal"
-def _stored_task_profile(task: Task, run_id: str) -> TaskProfile | None:
- if not task.profile:
- return None
- try:
- return get_task_profile(task.profile)
- except TaskProfileError:
- log_with_activity_context("task_profile_not_registered", run_id=run_id, profile=task.profile)
- return None
-
-
def _compile_effective_network_policy(allowed_domains: list[str]) -> EffectiveNetworkPolicy:
debug_domains = _get_debug_only_domains() if settings.DEBUG else []
debug_ports = _get_debug_only_ports() if settings.DEBUG else []
@@ -1302,7 +1291,7 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
if user_github_integration is not None:
user_github_integration_id = str(user_github_integration.integration.id)
- profile = _stored_task_profile(task, run_id)
+ profile = task.stored_profile
return TaskProcessingContext(
task_id=str(task.id),
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py
index ddf1ec8dbe2f..2888db811153 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py
@@ -129,6 +129,7 @@ class TestSendFollowupToSandbox(BaseTest):
task_run.state = {"sandbox_id": "sandbox-123"}
task_run.task.created_by_id = 42
task_run.task.created_by = MagicMock(id=42)
+ task_run.task.stored_profile = None
mock_task_run_objects.select_related.return_value.get.return_value = task_run
mock_send_user_message.return_value = MagicMock(
success=True,
diff --git a/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py
index 79420bbc0946..466027952894 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py
@@ -121,7 +121,7 @@ class TestGitHubSandboxCredential:
"products.tasks.backend.temporal.process_task.sandbox_credentials.get_sandbox_github_token",
return_value="ghs_resolved",
) as resolve:
- outcome = GitHubSandboxCredential().refresh(sandbox, ctx, MagicMock())
+ outcome = GitHubSandboxCredential().refresh(sandbox, ctx, MagicMock(stored_profile=None))
resolve.assert_called_once()
assert outcome.refreshed is True
@@ -140,7 +140,7 @@ class TestGitHubSandboxCredential:
"products.tasks.backend.temporal.process_task.sandbox_credentials.get_sandbox_github_token",
return_value="ghu_resolved",
):
- outcome = GitHubSandboxCredential().refresh(sandbox, _context(), MagicMock())
+ outcome = GitHubSandboxCredential().refresh(sandbox, _context(), MagicMock(stored_profile=None))
assert outcome.next_refresh_seconds == 2 * 60 * 60
@@ -193,7 +193,7 @@ class TestGitHubSandboxCredential:
def test_deleted_integration_raises_credential_unavailable(self):
from products.tasks.backend.exceptions import CredentialUnavailableError
- task = MagicMock()
+ task = MagicMock(stored_profile=None)
task.github_integration_id = None
task.github_user_integration_id = None
@@ -210,7 +210,7 @@ class TestGitHubSandboxCredential:
sandbox = MagicMock()
sandbox.execute.return_value = _ok("")
sandbox.write_file.return_value = _ok()
- task = MagicMock()
+ task = MagicMock(stored_profile=None)
task.github_integration_id = 456
task.github_user_integration_id = None
diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.py
index b7314bd475bb..227280ae2b19 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py
@@ -21,6 +21,7 @@ from products.tasks.backend.temporal.process_task.utils import (
POSTHOG_MCP_DESCRIPTION,
GitHubCredentialSource,
McpServerConfig,
+ PrAuthorshipMode,
RunState,
build_imported_mcp_server_configs,
build_sandbox_environment_variables,
@@ -29,6 +30,7 @@ from products.tasks.backend.temporal.process_task.utils import (
get_github_token,
get_imported_mcp_server_configs,
get_models_for_runtime_adapter,
+ get_pr_authorship_mode,
get_relayed_mcp_server_names,
get_sandbox_github_token,
get_sandbox_ph_mcp_configs,
@@ -715,6 +717,7 @@ class TestGetGitIdentityEnvVars(TestCase):
def _make_task(origin_product: str, user: object | None = None) -> MagicMock:
task = MagicMock(spec=Task)
task.origin_product = origin_product
+ task.stored_profile = None
task.created_by = user
return task
@@ -1803,6 +1806,11 @@ class TestUpgradeRunToUserAuthorship(_AuthorshipFixture):
self.task.origin_product = Task.OriginProduct.SIGNAL_REPORT
self.task.save(update_fields=["origin_product"])
+ def _profile_without_user_authorable_prs(self) -> None:
+ self.connect_personal_github()
+ self.task.profile = "business_knowledge"
+ self.task.save(update_fields=["profile"])
+
def _set_state(self, state: dict) -> None:
self.task_run.state = state
self.task_run.save(update_fields=["state"])
@@ -1815,6 +1823,7 @@ class TestUpgradeRunToUserAuthorship(_AuthorshipFixture):
("already_user_authored",),
("caller_token_run",),
("signal_report_origin",),
+ ("profile_without_user_authorable_prs",),
("a_different_actor_than_the_creator",),
]
)
@@ -1850,12 +1859,17 @@ class TestIsBotAuthorshipFallback(_AuthorshipFixture):
self.task.origin_product = Task.OriginProduct.SIGNAL_REPORT
self.task.save(update_fields=["origin_product"])
+ def _profile_without_user_authorable_prs(self) -> None:
+ self.task.profile = "business_knowledge"
+ self.task.save(update_fields=["profile"])
+
@parameterized.expand(
[
("user_authored",),
("caller_token_run",),
("signal_report_run",),
("signal_report_origin",),
+ ("profile_without_user_authorable_prs",),
]
)
def test_nothing_is_flagged(self, case: str) -> None:
@@ -1864,6 +1878,27 @@ class TestIsBotAuthorshipFallback(_AuthorshipFixture):
assert is_bot_authorship_fallback(self.task, str(self.task_run.id), self.task_run.state) is False
+class TestGetPrAuthorshipMode(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("profile_wins_over_origin", "business_knowledge", None, PrAuthorshipMode.BOT),
+ ("unregistered_profile_uses_origin", "test.unregistered", None, PrAuthorshipMode.USER),
+ (
+ "run_state_wins_over_profile",
+ "business_knowledge",
+ {"pr_authorship_mode": "user"},
+ PrAuthorshipMode.USER,
+ ),
+ ]
+ )
+ def test_reads_run_state_then_profile_then_origin(
+ self, _name: str, profile: str, state: dict | None, expected: PrAuthorshipMode
+ ) -> None:
+ task = Task(origin_product=Task.OriginProduct.USER_CREATED, profile=profile)
+
+ assert get_pr_authorship_mode(task, state) == expected
+
+
class TestMcpExecSkillsEnvVars(SimpleTestCase):
@parameterized.expand(
[
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 269f9491ecd6..31e8b6ad662e 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -51,6 +51,7 @@ from products.tasks.backend.exceptions import (
ProcessTaskTransientError,
)
from products.tasks.backend.facade.gateway import mint_private_gateway_token, revoke_private_gateway_token
+from products.tasks.backend.facade.profiles import TaskProfile
from products.tasks.backend.feature_flags import is_mcp_exec_skills_enabled
from products.tasks.backend.logic.model_access import ModelAccess, resolve_model_access
from products.tasks.backend.logic.services.desktop_gateway_token import (
@@ -130,6 +131,12 @@ def mcp_scopes_for_run_source(run_source: RunSource | None) -> Literal["read_onl
USER_AUTHORABLE_ORIGIN_PRODUCTS: tuple[str, ...] = ("user_created", "slack", "posthog_ai")
+def is_user_authorable(origin_product: str | None, profile: TaskProfile | None) -> bool:
+ if profile is not None:
+ return profile.user_authorable_prs
+ return origin_product in USER_AUTHORABLE_ORIGIN_PRODUCTS
+
+
# The labels repeat the values because the published OpenAPI enum lists these exact pairs.
class RuntimeAdapter(LabeledStrEnum):
CLAUDE = "claude", "claude"
@@ -1902,6 +1909,10 @@ def get_pr_authorship_mode(task: Task, state: dict[str, Any] | None = None) -> P
if run_state.pr_authorship_mode is not None:
return run_state.pr_authorship_mode
+ profile = task.stored_profile
+ if profile is not None:
+ return PrAuthorshipMode(profile.default_pr_authorship)
+
if task.origin_product in (TaskModel.OriginProduct.SIGNAL_REPORT, TaskModel.OriginProduct.POSTHOG_AI):
return PrAuthorshipMode.BOT
@@ -1921,7 +1932,7 @@ def is_bot_authorship_fallback(task: Task, run_id: str, state: dict[str, Any] |
tell someone their pull request went out under the bot's name and know that connecting
is what changes it.
"""
- if task.origin_product not in USER_AUTHORABLE_ORIGIN_PRODUCTS:
+ if not is_user_authorable(task.origin_product, task.stored_profile):
return False
if parse_run_state(state).run_source == RunSource.SIGNAL_REPORT:
return False
@@ -1954,7 +1965,7 @@ def upgrade_run_to_user_authorship(
if actor_user is None:
return None
task = task_run.task
- if task.origin_product not in USER_AUTHORABLE_ORIGIN_PRODUCTS:
+ if not is_user_authorable(task.origin_product, task.stored_profile):
return None
# Promotion is only for the creator. A thread participant's connection would retarget a run
# they don't own, and later turns by a creator without one would then resolve to nothing
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index 67e34e557889..8886e6ebe6a1 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -54,6 +54,7 @@ BUSINESS_KNOWLEDGE = get_task_profile("business_knowledge")
SOURCE_ID = uuid.UUID("5ab01f4d-5b1e-4990-9802-4f8792a76759")
FLOW_SOURCE = TaskSource(kind=SourceKind.HOG_FLOW, id=str(SOURCE_ID))
REPORT_PROFILE = replace(BUSINESS_KNOWLEDGE, key="test.report", source_kind=SourceKind.SIGNAL_REPORT)
+POSTHOG_AI_BOT_PROFILE = replace(BUSINESS_KNOWLEDGE, key="test.posthog_ai_bot", origin_product="posthog_ai")
# Far enough back that any bump is unambiguously forward, and stable so a test can assert the
# clock did *not* move.
@@ -989,13 +990,14 @@ class TestTask(TestCase):
@parameterized.expand(
[
- ("connected_creator", True, "user"),
- ("creator_without_personal_github", False, "bot"),
+ ("connected_creator", True, None, "user"),
+ ("creator_without_personal_github", False, None, "bot"),
+ ("profile_without_user_authorable_prs", True, POSTHOG_AI_BOT_PROFILE, None),
]
)
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_create_and_run_posthog_ai_authorship_follows_the_creators_personal_github(
- self, _name, connected, expected_mode, mock_execute_workflow
+ self, _name, connected, profile, expected_mode, mock_execute_workflow
):
user = User.objects.create(email="[email protected]")
OrganizationMembership.objects.create(user=user, organization=self.organization)
@@ -1011,19 +1013,23 @@ class TestTask(TestCase):
else None
)
- with self.captureOnCommitCallbacks(execute=True):
+ registered = {profile.key: profile} if profile else {}
+ with (
+ patch.dict("products.tasks.backend.facade.profiles._profiles", registered),
+ self.captureOnCommitCallbacks(execute=True),
+ ):
task = Task.create_and_run(
team=self.team,
title="PostHog AI",
description="Repo-less",
- origin_product=Task.OriginProduct.POSTHOG_AI,
+ **({"profile": profile} if profile else {"origin_product": Task.OriginProduct.POSTHOG_AI}),
user_id=user.id,
)
self.assertIsNone(task.github_integration)
self.assertEqual(task.github_user_integration, user_integration)
state = TaskRun.objects.get(id=mock_execute_workflow.call_args.kwargs["run_id"]).state
- self.assertEqual(state["pr_authorship_mode"], expected_mode)
+ self.assertEqual(state.get("pr_authorship_mode"), expected_mode)
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_create_and_run_signal_report_raises_when_no_integration_anywhere(self, mock_execute_workflow):