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): write agent task tags to the shared tag system (#109315)

posthog[bot]254f8126ce09
diff --git a/posthog/models/tagged_item_registry.py b/posthog/models/tagged_item_registry.py
index 341dc194b3e7..869a23c9b03b 100644
--- a/posthog/models/tagged_item_registry.py
+++ b/posthog/models/tagged_item_registry.py
@@ -70,6 +70,7 @@ TAGGABLE_MODELS: tuple[TaggableModel, ...] = (
TaggableModel(model_label="replay_vision.ReplayScanner", legacy_field="replay_scanner", object_field=OBJECT_UUID),
TaggableModel(model_label="posthog.Project", legacy_field="project", object_field=OBJECT_ID),
TaggableModel(model_label="experiments.Experiment", legacy_field="experiment", object_field=OBJECT_ID),
+ TaggableModel(model_label="tasks.Task", legacy_field="task", object_field=OBJECT_UUID),
)
_BY_LABEL: dict[str, TaggableModel] = {entry.model_label: entry for entry in TAGGABLE_MODELS}
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 1648d76150a5..387e82cfc10f 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -46,6 +46,7 @@ from django.utils.http import content_disposition_header
import posthoganalytics
+from posthog.api.tagged_item import cleanup_orphan_tags, set_tags_on_object
from posthog.dataclasses import frozen
from posthog.event_usage import groups
from posthog.ingress.contracts import WebhookDelivery
@@ -3462,7 +3463,11 @@ def set_task_run_summary(
# Omitted tags keep the current set, so a summary-only call does not erase them.
if tags is not None:
updates[TASK_RUN_TAGS_STATE_KEY] = list(dict.fromkeys(tags))
- run.state = TaskRun.update_state_atomic(run.id, updates=updates)
+ with transaction.atomic():
+ run.state = TaskRun.update_state_atomic(run.id, updates=updates)
+ if tags is not None:
+ set_tags_on_object(tags, run.task)
+ cleanup_orphan_tags(run.team_id)
run.refresh_from_db()
run.publish_stream_state_event()
return _task_run_detail_to_dto(run, include_agent_state=include_agent_state, user_id=user_id)
diff --git a/products/tasks/backend/management/commands/backfill_task_tags.py b/products/tasks/backend/management/commands/backfill_task_tags.py
new file mode 100644
index 000000000000..c2404ad65637
--- /dev/null
+++ b/products/tasks/backend/management/commands/backfill_task_tags.py
@@ -0,0 +1,50 @@
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandParser
+from django.db.models import OuterRef, Q, Subquery
+
+from posthog.api.tagged_item import set_tags_on_object
+
+from products.tasks.backend.models import (
+ PRIOR_RUN_TAGS_STATE_KEY,
+ TASK_RUN_TAGS_STATE_KEY,
+ Task,
+ TaskRun,
+ task_tags_from_state,
+)
+
+
+def backfill_task_tags(team_id: int | None = None, dry_run: bool = False) -> int:
+ """Copy the tags of each live task's latest run into TaggedItem rows. Returns the count of tagged tasks."""
+ runs_with_tags = TaskRun.objects.filter(
+ Q(state__has_key=TASK_RUN_TAGS_STATE_KEY) | Q(state__has_key=PRIOR_RUN_TAGS_STATE_KEY)
+ )
+ tasks = Task.objects.filter(deleted=False)
+ if team_id is not None:
+ runs_with_tags = runs_with_tags.filter(team_id=team_id)
+ tasks = tasks.filter(team_id=team_id)
+ latest_run_state = TaskRun.objects.filter(task_id=OuterRef("pk")).order_by("-created_at", "-id").values("state")[:1]
+ tasks = tasks.filter(id__in=runs_with_tags.values("task_id")).annotate(latest_run_state=Subquery(latest_run_state))
+
+ tagged = 0
+ for task in tasks.iterator(chunk_size=500):
+ tags = task_tags_from_state(task.latest_run_state)
+ if not tags:
+ continue
+ if not dry_run:
+ set_tags_on_object(tags, task)
+ tagged += 1
+ return tagged
+
+
+class Command(BaseCommand):
+ help = "Write the tags of each task's latest run as tags on the task, so the shared tag tools can read them."
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--team-id", type=int, metavar="ID", help="Only tasks in this team")
+ parser.add_argument("--dry-run", action="store_true", help="Count the tasks without writing tags")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ tagged = backfill_task_tags(team_id=options["team_id"], dry_run=options["dry_run"])
+ verb = "Would tag" if options["dry_run"] else "Tagged"
+ self.stdout.write(f"{verb} {tagged} tasks")
diff --git a/products/tasks/backend/management/commands/test/test_backfill_task_tags.py b/products/tasks/backend/management/commands/test/test_backfill_task_tags.py
new file mode 100644
index 000000000000..4734f8caf949
--- /dev/null
+++ b/products/tasks/backend/management/commands/test/test_backfill_task_tags.py
@@ -0,0 +1,43 @@
+from datetime import timedelta
+
+from django.test import TestCase
+from django.utils import timezone
+
+from posthog.models import Organization, Team
+
+from products.tasks.backend.management.commands.backfill_task_tags import backfill_task_tags
+from products.tasks.backend.models import Task, TaskRun
+
+
+class TestBackfillTaskTags(TestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.team = Team.objects.create(organization=Organization.objects.create(name="Org"), name="Team")
+
+ def _task_with_runs(self, *states: dict, deleted: bool = False) -> Task:
+ task = Task.objects.create(
+ team=self.team,
+ title="Task",
+ description="d",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ deleted=deleted,
+ )
+ start = timezone.now() - timedelta(hours=len(states))
+ for offset, state in enumerate(states):
+ TaskRun.objects.create(task=task, team=self.team, state=state, created_at=start + timedelta(hours=offset))
+ return task
+
+ def test_writes_the_latest_run_tags_of_live_tasks(self) -> None:
+ current = self._task_with_runs({"task_tags": ["old-tag"]}, {"task_tags": ["bug-fix"]})
+ inherited = self._task_with_runs({"task_tags": ["old-tag"]}, {"prior_run_tags": ["research"]})
+ cleared = self._task_with_runs({"task_tags": ["old-tag"]}, {"task_tags": []})
+ deleted = self._task_with_runs({"task_tags": ["bug-fix"]}, deleted=True)
+
+ self.assertEqual(backfill_task_tags(dry_run=True), 2)
+ self.assertFalse(current.tagged_items.exists())
+
+ self.assertEqual(backfill_task_tags(), 2)
+ self.assertEqual(list(current.tagged_items.values_list("tag__name", flat=True)), ["bug-fix"])
+ self.assertEqual(list(inherited.tagged_items.values_list("tag__name", flat=True)), ["research"])
+ self.assertFalse(cleared.tagged_items.exists())
+ self.assertFalse(deleted.tagged_items.exists())
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 99618b14de42..bf1d022efbaa 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -34,6 +34,7 @@ from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.github_integration_base import INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY
from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.tagged_items_relation import Taggable
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.models.utils import DeletedMetaFields, UUIDModel
@@ -336,7 +337,18 @@ def task_origin_product_choices() -> list[tuple[str, str | Promise]]:
return list(Task.OriginProduct.choices)
-class Task(DeletedMetaFields, models.Model):
+def task_tags_from_state(state: Any) -> list[str]:
+ """The tags a run shows, read from its state."""
+ state = state if isinstance(state, dict) else {}
+ # An explicit list on this run wins, even an empty one, so clearing tags hides inherited ones.
+ for key in (TASK_RUN_TAGS_STATE_KEY, PRIOR_RUN_TAGS_STATE_KEY):
+ tags = state.get(key)
+ if isinstance(tags, list):
+ return [tag for tag in tags if isinstance(tag, str)]
+ return []
+
+
+class Task(Taggable, DeletedMetaFields, models.Model):
class Runtime(models.TextChoices):
ACP = "acp", "ACP"
PI = "pi", "Pi"
@@ -2524,13 +2536,7 @@ class TaskRun(models.Model):
@property
def task_tags(self) -> list[str]:
- state = self.state if isinstance(self.state, dict) else {}
- # An explicit list on this run wins, even an empty one, so clearing tags hides inherited ones.
- for key in (TASK_RUN_TAGS_STATE_KEY, PRIOR_RUN_TAGS_STATE_KEY):
- tags = state.get(key)
- if isinstance(tags, list):
- return [tag for tag in tags if isinstance(tag, str)]
- return []
+ return task_tags_from_state(self.state)
@property
def mode(self) -> str:
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 20522e4de35d..b1c9e0191a63 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -30,6 +30,7 @@ from posthog.models import Integration, Organization, OrganizationMembership, Pe
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
from posthog.models.personal_api_key import hash_key_value
from posthog.models.scoping import team_scope
+from posthog.models.tag import Tag
from posthog.models.user_integration import UserIntegration
from posthog.models.utils import generate_random_token_personal
from posthog.scopes import MCP_BUILT_IN_AGENT_SCOPE
@@ -6528,6 +6529,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(summary_only.status_code, status.HTTP_200_OK)
self.assertEqual(summary_only.json()["task_summary"], "Opening the PR")
self.assertEqual(summary_only.json()["task_tags"], ["bug-fix", "feature-flags"])
+ self.assertEqual(set(task.tagged_items.values_list("tag__name", flat=True)), {"bug-fix", "feature-flags"})
cleared = client.patch(
f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/set_summary/",
@@ -6537,6 +6539,8 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(cleared.status_code, status.HTTP_200_OK)
self.assertEqual(cleared.json()["task_tags"], [])
+ self.assertFalse(task.tagged_items.exists())
+ self.assertFalse(Tag.objects.filter(team=self.team, name__in=["bug-fix", "feature-flags"]).exists())
def test_unbound_sandbox_scope_does_not_bypass_task_visibility(self):
owner = self.create_organization_user("sandbox-owner")