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): record repository and context changes on Spaces and Tasks (#95495)

Jina Yoon2c92cec6cc68
diff --git a/products/context_layer/backend/presentation/views.py b/products/context_layer/backend/presentation/views.py
index ad0c7e0da170..c171c2a0bd3d 100644
--- a/products/context_layer/backend/presentation/views.py
+++ b/products/context_layer/backend/presentation/views.py
@@ -1,3 +1,5 @@
+from typing import Literal
+
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
from rest_framework import status, viewsets
from rest_framework.decorators import action
@@ -35,6 +37,48 @@ from products.tasks.backend.facade import api as tasks_facade
RUN_COMMITS_PER_DAY_CAP = 20
+def _context_actor_type(request: Request) -> Literal["user_or_api", "task_agent", "loop_agent"]:
+ access_token = get_oauth_access_token(request)
+ token_scopes = set((getattr(access_token, "scope", "") or "").split())
+ if LOOP_CONTEXT_INTERNAL_SCOPE in token_scopes:
+ return "loop_agent"
+ if INTERNAL_RUN_SCOPE in token_scopes:
+ return "task_agent"
+ return "user_or_api"
+
+
+def _capture_context_page_update(
+ organization_id, # noqa: ANN001
+ request: Request,
+ *,
+ path: str,
+ channel_id: str | None,
+ is_first_version: bool,
+ content_bytes: int,
+ base_version_provided: bool,
+) -> None:
+ if channel_id is None:
+ return
+ path_parts = path.split("/")
+ if len(path_parts) != 4 or path_parts[0] != "projects" or path_parts[2] != "spaces":
+ return
+ try:
+ team_id = int(path_parts[1])
+ except ValueError:
+ return
+ actor_type = _context_actor_type(request)
+ tasks_facade.capture_context_wiki_changed(
+ organization_id=organization_id,
+ team_id=team_id,
+ channel_id=channel_id,
+ user_id=getattr(request.user, "id", None),
+ actor_type=actor_type,
+ is_first_version=is_first_version,
+ content_bytes=content_bytes,
+ base_version_provided=base_version_provided,
+ )
+
+
def _store_error_response(error: facade.ContextLayerStoreError) -> Response:
"""One mapping from store errors to HTTP for every action, so new writers
added in later layers cannot drift from this contract."""
@@ -189,16 +233,33 @@ def _write_page(organization_id, request: Request, *, team_id=None) -> Response:
if user and user.is_authenticated
else None
)
+ content = serializer.validated_data["content"]
+ channel_id = facade.page_frontmatter_channel_id(content)
+ is_first_version = False
+ if channel_id is not None:
+ try:
+ is_first_version = facade.resolve_channel_page(organization_id, channel_id) is None
+ except facade.ContextLayerStoreError:
+ pass
try:
head_sha = facade.write_page(
organization_id,
path=serializer.validated_data["path"],
- content=serializer.validated_data["content"],
+ content=content,
base_head=serializer.validated_data.get("base_head"),
author=author,
)
except facade.ContextLayerStoreError as error:
return _store_error_response(error)
+ _capture_context_page_update(
+ organization_id,
+ request,
+ path=serializer.validated_data["path"],
+ channel_id=channel_id,
+ is_first_version=is_first_version,
+ content_bytes=len(content.encode("utf-8")),
+ base_version_provided=serializer.validated_data.get("base_head") is not None,
+ )
return Response(ContextLayerStatusSerializer({"head_sha": head_sha}).data)
diff --git a/products/context_layer/backend/test/test_api.py b/products/context_layer/backend/test/test_api.py
index 5f73dc0177c1..a8a768508942 100644
--- a/products/context_layer/backend/test/test_api.py
+++ b/products/context_layer/backend/test/test_api.py
@@ -293,6 +293,49 @@ class TestContextLayerAPI(APIBaseTest):
assert page["content"] == _page("Analytics")
assert page["head_sha"] == new_head
+ def test_channel_page_write_captures_context_change(self, _flag) -> None:
+ with team_scope(self.team.id):
+ channel = tasks_facade.resolve_channel(self.team.id, self.user.id, name="growth", star=False)
+ assert channel is not None
+ head = self._enable()
+ path = f"projects/{self.team.id}/spaces/growth.md"
+ page = self.client.get(f"{self.base_url}/pages/", {"path": path}).json()
+
+ updated_content = f"{page['content']}\n## Direction\n\nImprove activation.\n"
+ with patch("products.tasks.backend.repository_config_analytics.posthoganalytics.capture") as capture:
+ response = self.client.put(
+ f"{self.base_url}/pages/",
+ {
+ "path": path,
+ "content": updated_content,
+ "base_head": head,
+ },
+ format="json",
+ )
+
+ assert response.status_code == 200, response.content
+ rows = [
+ call.kwargs["properties"]
+ for call in capture.call_args_list
+ if call.kwargs.get("event") == "space_context_changed"
+ ]
+ assert len(rows) == 1
+ properties = rows[0]
+ assert properties == {
+ "team_id": self.team.id,
+ "channel_id": str(channel.id),
+ "action": "published",
+ "source": "user",
+ "storage": "context_wiki",
+ "actor_type": "user_or_api",
+ "previous_version": None,
+ "new_version": None,
+ "is_first_version": False,
+ "content_bytes": len(updated_content.encode("utf-8")),
+ "previous_content_bytes": None,
+ "base_version_provided": True,
+ }
+
def test_page_write_with_stale_base_head_returns_409_with_current_head(self, _flag) -> None:
head = self._enable()
first = self.client.put(
diff --git a/products/desktop/packages/core/src/canvas/canvasAnalytics.test.ts b/products/desktop/packages/core/src/canvas/canvasAnalytics.test.ts
index 658bf096625f..531898822043 100644
--- a/products/desktop/packages/core/src/canvas/canvasAnalytics.test.ts
+++ b/products/desktop/packages/core/src/canvas/canvasAnalytics.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
buildCanvasPromptProps,
buildContextSaveProps,
+ buildTaskSpaceContextProps,
dashboardIdFromThread,
} from "./canvasAnalytics";
@@ -85,3 +86,33 @@ describe("buildContextSaveProps", () => {
},
);
});
+
+describe("buildTaskSpaceContextProps", () => {
+ it.each([
+ {
+ input: {},
+ expected: { space_context_mode: "none" },
+ },
+ {
+ input: { channelId: "c1", channelContext: " " },
+ expected: { channel_id: "c1", space_context_mode: "none" },
+ },
+ {
+ input: { channelId: "c1", channelContext: "Shared context" },
+ expected: { channel_id: "c1", space_context_mode: "legacy_inline" },
+ },
+ {
+ input: {
+ channelId: "feed-1",
+ channelContextId: "space-1",
+ channelContextPath: "projects/2/spaces/growth.md",
+ },
+ expected: {
+ channel_id: "space-1",
+ space_context_mode: "context_wiki_reference",
+ },
+ },
+ ])("returns $expected.space_context_mode", ({ input, expected }) => {
+ expect(buildTaskSpaceContextProps(input)).toEqual(expected);
+ });
+});
diff --git a/products/desktop/packages/core/src/canvas/canvasAnalytics.ts b/products/desktop/packages/core/src/canvas/canvasAnalytics.ts
index a5f62fc1c5f3..f4ce9d96b257 100644
--- a/products/desktop/packages/core/src/canvas/canvasAnalytics.ts
+++ b/products/desktop/packages/core/src/canvas/canvasAnalytics.ts
@@ -2,6 +2,8 @@ import type {
CanvasPromptSentProperties,
CanvasPromptSurface,
ContextActionProperties,
+ SpaceContextMode,
+ TaskCreateProperties,
} from "@posthog/shared/analytics-events";
/** The dashboardId a canvas thread persists to ("dashboard:<id>" → "<id>"). */
@@ -46,3 +48,22 @@ export function buildContextSaveProps(opts: {
success: opts.success,
};
}
+
+export function buildTaskSpaceContextProps(opts: {
+ channelId?: string;
+ channelContextId?: string;
+ channelContext?: string;
+ channelContextPath?: string;
+}): Pick<TaskCreateProperties, "channel_id" | "space_context_mode"> {
+ const channelId = opts.channelContextId ?? opts.channelId;
+ const spaceContextMode: SpaceContextMode = opts.channelContextPath
+ ? "context_wiki_reference"
+ : opts.channelContext?.trim()
+ ? "legacy_inline"
+ : "none";
+
+ return {
+ ...(channelId ? { channel_id: channelId } : {}),
+ space_context_mode: spaceContextMode,
+ };
+}
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index cf545793f1e3..bb1a739e5d12 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -18,6 +18,10 @@ export interface PromptHistorySelectedProperties {
type ExecutionType = "cloud" | "local";
export type RepositoryProvider = "github" | "gitlab" | "local" | "none";
+export type SpaceContextMode =
+ | "none"
+ | "legacy_inline"
+ | "context_wiki_reference";
type TaskCreatedFrom = "cli" | "command-menu" | "sidebar-worktree";
type RepositorySelectSource = "task-creation" | "task-detail";
type GitActionType =
@@ -105,6 +109,10 @@ export interface TaskCreateProperties {
adapter?: Adapter;
codex_model_access?: ModelAccess;
claude_model_access?: ModelAccess;
+ /** Space that owns the task, when it was created from a Space. */
+ channel_id?: string;
+ /** How shared Space context was delivered to the task. */
+ space_context_mode: SpaceContextMode;
}
export interface TaskViewProperties {
diff --git a/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx b/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx
index 8398309e4934..43f218b5df49 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx
@@ -357,6 +357,7 @@ function SetupTaskSection() {
has_branch: false,
cloud_run_source: "manual",
adapter,
+ space_context_mode: "none",
});
} else {
toastError("Failed to start Self-driving setup", result.error);
diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxCloudTaskRunner.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxCloudTaskRunner.ts
index 3190c9a91312..578a857f2d79 100644
--- a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxCloudTaskRunner.ts
+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxCloudTaskRunner.ts
@@ -306,6 +306,7 @@ export function useInboxCloudTaskRunner({
: { cloud_run_source: "manual" }),
adapter,
...analyticsExtras,
+ space_context_mode: "none",
});
} else {
const failureCode: InboxReportActionFailureCode = isUsageLimitResult(
diff --git a/products/desktop/packages/ui/src/features/sidebar/useStartTaskFromWorktree.ts b/products/desktop/packages/ui/src/features/sidebar/useStartTaskFromWorktree.ts
index 6e1a345fb4c8..33d109099a06 100644
--- a/products/desktop/packages/ui/src/features/sidebar/useStartTaskFromWorktree.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/useStartTaskFromWorktree.ts
@@ -62,6 +62,7 @@ export function useStartTaskFromWorktree(mainRepoPath: string) {
created_from: "sidebar-worktree",
workspace_mode: "worktree",
has_branch: true,
+ space_context_mode: "none",
});
// The adopted worktree now has a task, so it leaves the adoptable list.
void queryClient.invalidateQueries(
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts
index 3a62a832fce5..882678046ca1 100644
--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts
@@ -1,3 +1,4 @@
+import { buildTaskSpaceContextProps } from "@posthog/core/canvas/canvasAnalytics";
import { partitionLocalMcpServersForRun } from "@posthog/core/local-mcp/localMcpImport";
import {
getErrorTitle,
@@ -184,6 +185,12 @@ async function trackTaskCreated(
adapter: input.adapter,
codex_model_access: codexModelAccess,
claude_model_access: claudeModelAccess,
+ ...buildTaskSpaceContextProps({
+ channelId: input.channelId,
+ channelContextId: input.channelContextId,
+ channelContext: input.channelContext,
+ channelContextPath: input.channelContextPath,
+ }),
});
} catch (error) {
log.warn("Failed to track Task created event", { error });
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 9c204ad30be9..cbefa398c0a7 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -126,6 +126,11 @@ from products.tasks.backend.models import (
)
from products.tasks.backend.pr_urls import merge_pr_output
from products.tasks.backend.prompts import build_wizard_pr_agent_prompt, generate_wizard_head_branch
+from products.tasks.backend.repository_config_analytics import (
+ capture_repository_config_changed,
+ capture_space_context_changed,
+ repositories_differ,
+)
from products.tasks.backend.visibility import (
TEAM_READABLE_ORIGIN_PRODUCTS,
task_control_q,
@@ -232,6 +237,7 @@ __all__ = [
"resolve_task_run_preview_redirect",
"task_run_preview_ready",
"get_task_run_living_artifact",
+ "capture_context_wiki_changed",
"capture_relay_command_telemetry",
"PermissionResponseUnavailable",
"validate_permission_response_target",
@@ -6112,6 +6118,23 @@ def create_task(
relationship=signal_report_task_relationship,
)
+ # Only an override is a change. The inherited case is already counted by `task_created`.
+ if channel is not None and repositories_differ(channel.repositories, task.repositories):
+ capture_repository_config_changed(
+ team=team,
+ user_id=user_id,
+ subject="task",
+ trigger="task_created",
+ previous_repositories=channel.repositories,
+ repositories=task.repositories,
+ previous_integration_id=channel.github_integration_id,
+ integration_id=task.github_integration_id,
+ channel_id=str(channel.id),
+ task_id=str(task.id),
+ origin_product=task.origin_product,
+ space_repositories=channel.repositories,
+ )
+
return _task_detail_to_dto(_task_detail_queryset().get(pk=task.pk))
@@ -6144,6 +6167,8 @@ def update_task(
task = Task.objects.select_for_update().filter(id=task_id, team_id=team_id, deleted=False).first()
if task is None or not Task.objects.filter(id=task.id).filter(task_control_q(user_id)).exists():
return None
+ previous_repositories = list(task.repositories or [])
+ previous_integration_id = task.github_integration_id
# Repo and credential are immutable for code-access-exempt tasks: a mutable repo reopens the
# gate (see task_exempt_from_code_access), and provisioning injects whatever integration is
@@ -6166,12 +6191,34 @@ def update_task(
if "archived" in validated_data and validated_data["archived"] != task.archived:
validated_data["archived_at"] = django_timezone.now() if validated_data["archived"] else None
+ repo_fields_touched = any(key in validated_data for key in ("repositories", "repository", "github_integration"))
logger.info("perform_update called for task %s with validated_data: %s", task.id, validated_data)
for key, value in validated_data.items():
setattr(task, key, value)
task.save()
logger.info("Task %s updated successfully", task.id)
+ if repo_fields_touched:
+ space_repositories = (
+ Channel.objects.filter(id=task.channel_id).values_list("repositories", flat=True).first()
+ if task.channel_id
+ else None
+ )
+ capture_repository_config_changed(
+ team=task.team,
+ user_id=user_id,
+ subject="task",
+ trigger="task_settings_edit",
+ previous_repositories=previous_repositories,
+ repositories=task.repositories,
+ previous_integration_id=previous_integration_id,
+ integration_id=task.github_integration_id,
+ channel_id=str(task.channel_id) if task.channel_id else None,
+ task_id=str(task.id),
+ origin_product=task.origin_product,
+ space_repositories=space_repositories,
+ )
+
return _task_detail_to_dto(_task_detail_queryset().get(pk=task.pk))
@@ -8274,6 +8321,8 @@ def update_channel(
if (name is not None or channel_type is not None) and _is_general_channel(channel):
return "general"
update_fields: list[str] = []
+ previous_repositories = list(channel.repositories or [])
+ previous_integration_id = channel.github_integration_id
if channel_type is not None and channel_type != channel.channel_type:
channel.channel_type = channel_type
update_fields.append("channel_type")
@@ -8294,9 +8343,21 @@ def update_channel(
if not update_fields:
return _channel_to_dto(channel)
channel.save(update_fields=[*update_fields, "updated_at"])
- return _channel_to_dto(channel)
except IntegrityError:
return "name_taken"
+ if repositories is not None:
+ capture_repository_config_changed(
+ team=channel.team,
+ user_id=user_id,
+ subject="space",
+ trigger="space_settings_edit",
+ previous_repositories=previous_repositories,
+ repositories=channel.repositories,
+ previous_integration_id=previous_integration_id,
+ integration_id=channel.github_integration_id,
+ channel_id=str(channel.id),
+ )
+ return _channel_to_dto(channel)
def delete_channel(channel_id: str | UUID, team_id: int, user_id: int | None) -> str:
@@ -8575,6 +8636,41 @@ def loop_context_channel_id_for_task(task_id: str | UUID) -> str | None:
return str(channel_id) if channel_id else None
+def capture_context_wiki_changed(
+ organization_id: str | UUID,
+ team_id: int,
+ channel_id: str | UUID,
+ user_id: int | None,
+ *,
+ actor_type: Literal["user_or_api", "task_agent", "loop_agent"],
+ is_first_version: bool,
+ content_bytes: int,
+ base_version_provided: bool,
+) -> bool:
+ channel = (
+ Channel.objects.unscoped()
+ .select_related("team")
+ .filter(id=channel_id, team_id=team_id, team__organization_id=organization_id)
+ .first()
+ )
+ if channel is None:
+ return False
+ capture_space_context_changed(
+ team=channel.team,
+ user_id=user_id,
+ channel_id=str(channel.id),
+ action="published",
+ source="user" if actor_type == "user_or_api" else "agent",
+ previous_version=None,
+ content_bytes=content_bytes,
+ base_version_provided=base_version_provided,
+ storage="context_wiki",
+ actor_type=actor_type,
+ is_first_version=is_first_version,
+ )
+ return True
+
+
def publish_channel_instructions(
channel_id: str | UUID,
team_id: int,
@@ -8582,6 +8678,7 @@ def publish_channel_instructions(
*,
content: str,
base_version: int | None = None,
+ source: Literal["user", "agent"] = "user",
) -> contracts.ChannelInstructionsDTO | None:
with transaction.atomic():
channel = _locked_visible_channel(channel_id, team_id, user_id)
@@ -8596,6 +8693,7 @@ def publish_channel_instructions(
.first()
)
current_version = current_latest.version if current_latest is not None else 0
+ previous_content_bytes = len(current_latest.content.encode("utf-8")) if current_latest is not None else None
if base_version is not None and base_version != current_version:
raise ChannelInstructionsVersionConflictError(current_version=current_version)
if current_version >= MAX_CHANNEL_INSTRUCTIONS_VERSION:
@@ -8621,20 +8719,51 @@ def publish_channel_instructions(
raise ChannelInstructionsVersionConflictError(current_version=latest.version if latest is not None else 0)
ChannelContextGeneration.objects.filter(channel_id=channel.id).update(task_id=None)
+ capture_space_context_changed(
+ team=channel.team,
+ user_id=user_id,
+ channel_id=str(channel.id),
+ action="published",
+ source=source,
+ previous_version=current_version,
+ new_version=published.version,
+ content_bytes=len(content.encode("utf-8")),
+ previous_content_bytes=previous_content_bytes,
+ base_version_provided=base_version is not None,
+ )
return _instructions_to_dto(published)
-def delete_channel_instructions(channel_id: str | UUID, team_id: int, user_id: int | None) -> int | None:
+def delete_channel_instructions(
+ channel_id: str | UUID, team_id: int, user_id: int | None, *, source: Literal["user", "agent"] = "user"
+) -> int | None:
with transaction.atomic():
channel = _locked_visible_channel(channel_id, team_id, user_id)
if channel is None:
return None
+ previous_version = (
+ ChannelInstructions.objects.filter(channel_id=channel.id, deleted=False)
+ .order_by("-version")
+ .values_list("version", flat=True)
+ .first()
+ or 0
+ )
count = (
ChannelInstructions.objects.select_for_update()
.filter(channel_id=channel.id, deleted=False)
.update(deleted=True, is_latest=False)
)
ChannelContextGeneration.objects.filter(channel_id=channel.id).update(task_id=None)
+ if count:
+ capture_space_context_changed(
+ team=channel.team,
+ user_id=user_id,
+ channel_id=str(channel.id),
+ action="cleared",
+ source=source,
+ previous_version=previous_version,
+ versions_deleted=count,
+ )
return count
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 3aa41387a167..637075098acd 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -287,10 +287,32 @@ def clear_channel_repositories_on_github_integration_delete(
if instance.kind != Integration.IntegrationKind.GITHUB:
return
+ affected = list(
+ Channel.objects.for_team(instance.team_id)
+ .filter(github_integration_id=instance.id)
+ .values_list("id", "repositories")
+ )
Channel.objects.for_team(instance.team_id).filter(github_integration_id=instance.id).update(
github_integration=None,
repositories=[],
)
+ if not affected:
+ return
+ # One aggregate row, not one per Space: this path can touch every Space bound to the
+ # integration, and the question it answers is "repos went to zero here", not which.
+ from products.tasks.backend.repository_config_analytics import capture_repository_config_changed
+
+ capture_repository_config_changed(
+ team=instance.team,
+ user_id=None,
+ subject="space",
+ trigger="github_integration_disconnected",
+ previous_repositories=[repo for _, repositories in affected for repo in (repositories or [])],
+ repositories=[],
+ previous_integration_id=instance.id,
+ integration_id=None,
+ affected_space_count=len(affected),
+ )
SLACK_NOTIFIED_PR_URL_STATE_KEY = "slack_notified_pr_url"
@@ -613,6 +635,8 @@ class Task(DeletedMetaFields, models.Model):
}
if self.origin_key:
all_properties["origin_key"] = self.origin_key
+ if self.channel_id:
+ all_properties["channel_id"] = str(self.channel_id)
if properties:
all_properties.update(properties)
(capture_fn or posthoganalytics.capture)(
diff --git a/products/tasks/backend/presentation/views/channels_api.py b/products/tasks/backend/presentation/views/channels_api.py
index 11ca473089ee..1c89cac8a917 100644
--- a/products/tasks/backend/presentation/views/channels_api.py
+++ b/products/tasks/backend/presentation/views/channels_api.py
@@ -368,6 +368,8 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
self._user_id(),
content=serializer.validated_data["content"],
base_version=serializer.validated_data.get("base_version"),
+ # The facade never sees the request, so the loop-vs-person split is set here.
+ source="agent" if sandbox_task_id is not None else "user",
)
except tasks_facade.ChannelInstructionsVersionConflictError as err:
return Response(
diff --git a/products/tasks/backend/repository_config_analytics.py b/products/tasks/backend/repository_config_analytics.py
new file mode 100644
index 000000000000..185725cd8435
--- /dev/null
+++ b/products/tasks/backend/repository_config_analytics.py
@@ -0,0 +1,164 @@
+"""Analytics for repository and context configuration changes on Spaces and Tasks.
+
+Neither `Channel` nor `Task` carries an activity log, so before these events the only
+trace of a repo config change was the row's own `updated_at`. That cannot say who
+changed what, from what, to what.
+
+Lives outside `facade/api.py` because both that module and `models.py` emit from here,
+and the facade already imports the models.
+"""
+
+import structlog
+import posthoganalytics
+
+from posthog.event_usage import groups
+from posthog.models import Team, User
+
+logger = structlog.get_logger(__name__)
+
+REPOSITORY_CONFIG_CHANGED = "repository_config_changed"
+SPACE_CONTEXT_CHANGED = "space_context_changed"
+
+
+def _distinct_id(team: Team, user_id: int | None) -> str:
+ # Mirrors Task.capture_event: the actor when we have one, else the team.
+ if user_id is not None:
+ distinct_id = User.objects.filter(id=user_id).values_list("distinct_id", flat=True).first()
+ if distinct_id:
+ return str(distinct_id)
+ return str(team.uuid)
+
+
+def _normalized(repositories: list[str] | None) -> set[str]:
+ return {repo.strip().lower() for repo in (repositories or []) if repo and repo.strip()}
+
+
+def repositories_differ(left: list[str] | None, right: list[str] | None) -> bool:
+ """Whether two repository lists name different repos, ignoring order and case."""
+ return _normalized(left) != _normalized(right)
+
+
+def capture_repository_config_changed(
+ *,
+ team: Team,
+ user_id: int | None,
+ subject: str,
+ trigger: str,
+ previous_repositories: list[str] | None,
+ repositories: list[str] | None,
+ previous_integration_id: int | None = None,
+ integration_id: int | None = None,
+ channel_id: str | None = None,
+ task_id: str | None = None,
+ origin_product: str | None = None,
+ space_repositories: list[str] | None = None,
+ affected_space_count: int | None = None,
+) -> None:
+ """Record a repository configuration change on a Space (`subject="space"`) or a
+ Task (`subject="task"`).
+
+ Emits nothing when neither the repository set nor the integration actually moved, so
+ a PATCH that resubmits the same list stays out of the data. Best-effort: a capture
+ failure must never fail the write it describes.
+ """
+ try:
+ previous = _normalized(previous_repositories)
+ current = _normalized(repositories)
+ integration_changed = previous_integration_id != integration_id
+ if previous == current and not integration_changed:
+ return
+
+ properties: dict = {
+ "subject": subject,
+ "trigger": trigger,
+ "team_id": team.id,
+ "previous_repository_count": len(previous),
+ "repository_count": len(current),
+ "added_count": len(current - previous),
+ "removed_count": len(previous - current),
+ "is_first_configuration": not previous and bool(current),
+ "is_cleared": bool(previous) and not current,
+ "github_integration_changed": integration_changed,
+ "github_integration_id": integration_id,
+ "previous_github_integration_id": previous_integration_id,
+ }
+ if channel_id is not None:
+ properties["channel_id"] = str(channel_id)
+ if task_id is not None:
+ properties["task_id"] = str(task_id)
+ if origin_product is not None:
+ properties["origin_product"] = origin_product
+ if affected_space_count is not None:
+ properties["affected_space_count"] = affected_space_count
+ if subject == "task" and space_repositories is not None:
+ space = _normalized(space_repositories)
+ properties["space_repository_count"] = len(space)
+ properties["diverged_from_space"] = current != space
+ # True when this edit is what broke inheritance, as opposed to a task that
+ # already sat apart from its Space.
+ properties["was_inherited_from_space"] = previous == space
+
+ posthoganalytics.capture(
+ distinct_id=_distinct_id(team, user_id),
+ event=REPOSITORY_CONFIG_CHANGED,
+ properties=properties,
+ groups=groups(team=team),
+ send_feature_flags=True,
+ )
+ except Exception as e:
+ logger.warning("repository_config_changed.capture_failed", subject=subject, trigger=trigger, error=str(e))
+
+
+def capture_space_context_changed(
+ *,
+ team: Team,
+ user_id: int | None,
+ channel_id: str,
+ action: str,
+ source: str,
+ previous_version: int | None,
+ new_version: int | None = None,
+ content_bytes: int = 0,
+ previous_content_bytes: int | None = None,
+ base_version_provided: bool = False,
+ versions_deleted: int | None = None,
+ storage: str = "legacy_instructions",
+ actor_type: str | None = None,
+ is_first_version: bool | None = None,
+) -> None:
+ """Record a Space's CONTEXT.md being published or cleared.
+
+ `source` separates people from loops: a loop configured with `update_context`
+ republishes on every fire, which outnumbers human edits by orders of magnitude.
+ Carries byte counts only — CONTEXT.md is customer-authored free text.
+ """
+ try:
+ properties: dict = {
+ "action": action,
+ "source": source,
+ "storage": storage,
+ "team_id": team.id,
+ "channel_id": str(channel_id),
+ "previous_version": previous_version,
+ "new_version": new_version,
+ "is_first_version": (
+ is_first_version if is_first_version is not None else previous_version == 0 and new_version is not None
+ ),
+ "content_bytes": content_bytes,
+ "previous_content_bytes": previous_content_bytes,
+ "base_version_provided": base_version_provided,
+ }
+ if versions_deleted is not None:
+ properties["versions_deleted"] = versions_deleted
+ if actor_type is not None:
+ properties["actor_type"] = actor_type
+
+ posthoganalytics.capture(
+ distinct_id=_distinct_id(team, user_id),
+ event=SPACE_CONTEXT_CHANGED,
+ properties=properties,
+ groups=groups(team=team),
+ send_feature_flags=True,
+ )
+ except Exception as e:
+ logger.warning("space_context_changed.capture_failed", action=action, error=str(e))
diff --git a/products/tasks/backend/tests/test_channels_api.py b/products/tasks/backend/tests/test_channels_api.py
index 2e00b859505a..f78b5def98d7 100644
--- a/products/tasks/backend/tests/test_channels_api.py
+++ b/products/tasks/backend/tests/test_channels_api.py
@@ -13,6 +13,7 @@ from rest_framework.test import APIClient
from posthog.models import Integration, Organization, OrganizationMembership, PersonalAPIKey, Team, User
from posthog.models.personal_api_key import hash_key_value
+from posthog.models.scoping import team_scope
from posthog.models.utils import generate_random_token_personal
from products.tasks.backend.exceptions import ComputeBillingLimitError
@@ -1540,3 +1541,142 @@ class ChannelFeedMessageAPITestCase(TestCase):
# Same org, wrong team in the URL — the channel must not resolve.
response = self.client.get(f"/api/projects/{other_team.id}/task_channels/{channel_id}/feed/")
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+
+class RepositoryConfigAnalyticsTestCase(TestCase):
+ """Repository and CONTEXT.md changes are the only durable record of who reconfigured a
+ Space, so these assert the event fires exactly once per real change and never on a no-op."""
+
+ CAPTURE = "products.tasks.backend.repository_config_analytics.posthoganalytics.capture"
+
+ def setUp(self) -> None:
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Growth Team")
+ self.user = User.objects.create_user(email="[email protected]", first_name="Ann", password="password")
+ self.organization.members.add(self.user)
+ OrganizationMembership.objects.filter(user=self.user, organization=self.organization).update(
+ level=OrganizationMembership.Level.ADMIN
+ )
+ self.client = APIClient()
+ self.client.force_authenticate(self.user)
+ self.integration = Integration.objects.create(team=self.team, kind="github", integration_id="1", config={})
+
+ def _channels_url(self) -> str:
+ return f"/api/projects/{self.team.id}/task_channels/"
+
+ def _tasks_url(self) -> str:
+ return f"/api/projects/{self.team.id}/tasks/"
+
+ @staticmethod
+ def _rows(capture, event: str) -> list[dict]:
+ return [call.kwargs["properties"] for call in capture.call_args_list if call.kwargs.get("event") == event]
+
+ def _channel_with_repos(self, repositories: list[str], name: str = "growth") -> Channel:
+ return Channel.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ name=name,
+ github_integration=self.integration,
+ repositories=repositories,
+ )
+
+ @patch("posthog.models.integration.github.GitHubIntegration.list_all_cached_repositories")
+ def test_space_repository_patch_emits_one_row(self, list_repositories):
+ list_repositories.return_value = [{"full_name": "posthog/posthog"}]
+ channel_id = self.client.post(self._channels_url(), {"name": "growth"}).json()["id"]
+
+ with patch(self.CAPTURE) as capture:
+ response = self.client.patch(
+ f"{self._channels_url()}{channel_id}/",
+ {"github_integration": self.integration.id, "repositories": ["posthog/posthog"]},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+
+ rows = self._rows(capture, "repository_config_changed")
+ self.assertEqual(len(rows), 1)
+ self.assertEqual(rows[0]["subject"], "space")
+ self.assertEqual(rows[0]["trigger"], "space_settings_edit")
+ self.assertEqual(rows[0]["previous_repository_count"], 0)
+ self.assertEqual(rows[0]["repository_count"], 1)
+ self.assertEqual(rows[0]["added_count"], 1)
+ self.assertNotIn("added_repositories", rows[0])
+ self.assertNotIn("removed_repositories", rows[0])
+ self.assertTrue(rows[0]["is_first_configuration"])
+ self.assertTrue(rows[0]["github_integration_changed"])
+
+ @patch("posthog.models.integration.github.GitHubIntegration.list_all_cached_repositories")
+ def test_resubmitting_the_same_repositories_emits_nothing(self, list_repositories):
+ list_repositories.return_value = [{"full_name": "posthog/posthog"}]
+ channel = self._channel_with_repos(["posthog/posthog"])
+
+ with patch(self.CAPTURE) as capture:
+ response = self.client.patch(
+ f"{self._channels_url()}{channel.id}/",
+ {"github_integration": self.integration.id, "repositories": ["posthog/posthog"]},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertEqual(self._rows(capture, "repository_config_changed"), [])
+
+ def test_task_inheriting_the_space_list_emits_nothing_but_an_override_emits_one_row(self):
+ channel = self._channel_with_repos(["posthog/posthog"])
+
+ with patch(self.CAPTURE) as capture:
+ tasks_facade.create_task(
+ self.team.id,
+ self.user.id,
+ validated_data={"title": "Inherit", "description": "d", "channel": channel},
+ )
+ self.assertEqual(self._rows(capture, "repository_config_changed"), [])
+
+ with patch(self.CAPTURE) as capture:
+ tasks_facade.create_task(
+ self.team.id,
+ self.user.id,
+ validated_data={
+ "title": "Override",
+ "description": "d",
+ "channel": channel,
+ "repositories": ["posthog/posthog.com"],
+ },
+ )
+ rows = self._rows(capture, "repository_config_changed")
+ self.assertEqual(len(rows), 1)
+ self.assertEqual(rows[0]["trigger"], "task_created")
+ self.assertEqual(rows[0]["subject"], "task")
+ self.assertTrue(rows[0]["diverged_from_space"])
+ self.assertEqual(rows[0]["space_repository_count"], 1)
+
+ def test_deleting_the_github_integration_emits_one_aggregate_row(self):
+ self._channel_with_repos(["posthog/posthog"], name="growth")
+ self._channel_with_repos(["posthog/posthog.com", "posthog/marketing"], name="editorial")
+
+ with patch(self.CAPTURE) as capture:
+ Integration.objects.filter(id=self.integration.id).delete()
+
+ rows = self._rows(capture, "repository_config_changed")
+ self.assertEqual(len(rows), 1)
+ self.assertEqual(rows[0]["trigger"], "github_integration_disconnected")
+ self.assertEqual(rows[0]["affected_space_count"], 2)
+ self.assertEqual(rows[0]["previous_repository_count"], 3)
+ self.assertTrue(rows[0]["is_cleared"])
+
+ def test_context_publish_records_whether_a_person_or_a_loop_wrote_it(self):
+ channel = self._channel_with_repos([])
+
+ # The view sets the scope from the request; a direct facade call must set it itself.
+ with patch(self.CAPTURE) as capture, team_scope(self.team.id):
+ tasks_facade.publish_channel_instructions(
+ channel.id, self.team.id, self.user.id, content="# Context", source="user"
+ )
+ tasks_facade.publish_channel_instructions(
+ channel.id, self.team.id, self.user.id, content="# Context, revised", source="agent"
+ )
+
+ rows = self._rows(capture, "space_context_changed")
+ self.assertEqual([row["source"] for row in rows], ["user", "agent"])
+ self.assertEqual([row["new_version"] for row in rows], [1, 2])
+ self.assertTrue(rows[0]["is_first_version"])
+ self.assertFalse(rows[1]["is_first_version"])
+ self.assertEqual(rows[1]["previous_content_bytes"], len(b"# Context"))
+ self.assertNotIn("content", rows[0])
diff --git a/products/tasks/backend/tests/test_task_capture.py b/products/tasks/backend/tests/test_task_capture.py
index faec71076cc6..111f01bc903b 100644
--- a/products/tasks/backend/tests/test_task_capture.py
+++ b/products/tasks/backend/tests/test_task_capture.py
@@ -6,7 +6,7 @@ from posthog.models.organization import Organization
from posthog.models.team import Team
from posthog.models.user import User
-from products.tasks.backend.models import Task
+from products.tasks.backend.models import Channel, Task
class TestTaskCaptureEvent(TestCase):
@@ -39,3 +39,12 @@ class TestTaskCaptureEvent(TestCase):
unkeyed = self._task()
unkeyed.capture_event("task_created", capture_fn=capture)
self.assertNotIn("origin_key", capture.call_args.kwargs["properties"])
+
+ def test_channel_id_reaches_analytics_for_space_tasks(self):
+ channel = Channel.objects.unscoped().create(team=self.team, name="growth", created_by=self.user)
+ capture = MagicMock()
+
+ task = self._task(channel=channel)
+ task.capture_event("task_created", capture_fn=capture)
+
+ self.assertEqual(capture.call_args.kwargs["properties"]["channel_id"], str(channel.id))
diff --git a/products/tasks/docs/INSTRUMENTATION.md b/products/tasks/docs/INSTRUMENTATION.md
index 87f421bb77b6..ede04e5cc425 100644
--- a/products/tasks/docs/INSTRUMENTATION.md
+++ b/products/tasks/docs/INSTRUMENTATION.md
@@ -83,6 +83,79 @@ recipient's, even though the task's `created_by` has moved by then. Additional p
| `from_user_id` | `int?` | User ID of the previous owner |
| `to_user_id` | `int` | User ID of the recipient (new owner) |
+## Channel / Space Configuration Events
+
+Source: `repository_config_analytics.py`, called from `facade/api.py`, `models.py`, and
+`presentation/views/channels_api.py`.
+
+These do **not** go through `Task.capture_event()`, so the "Task events" standard-property table
+above does not apply — they carry only the properties listed here plus `groups()`. `distinct_id`
+is the acting user, falling back to the team UUID.
+
+Neither `Channel` nor `Task` has an activity log, so before these events the only trace of a
+repository change was the row's own `updated_at`.
+
+### `repository_config_changed`
+
+Fires when a Space's or a Task's repository configuration changes. Nothing is captured when a
+write resubmits the same repository set and the same integration.
+
+| Property | Type | Description |
+| -------------------------------- | ------- | ------------------------------------------------------------------------------------------------- |
+| `subject` | `str` | `space` or `task` |
+| `trigger` | `str` | `space_settings_edit`, `task_settings_edit`, `task_created`, or `github_integration_disconnected` |
+| `team_id` | `int` | |
+| `channel_id` | `str?` | Always set for `subject=space`; set for `subject=task` when the task has a channel |
+| `task_id` | `str?` | `subject=task` only |
+| `origin_product` | `str?` | `subject=task` only |
+| `previous_repository_count` | `int` | The "from" |
+| `repository_count` | `int` | The "to" |
+| `added_count` / `removed_count` | `int` | |
+| `is_first_configuration` | `bool` | Previous list was empty |
+| `is_cleared` | `bool` | New list is empty |
+| `github_integration_changed` | `bool` | |
+| `github_integration_id` | `int?` | PostHog-side integration id |
+| `previous_github_integration_id` | `int?` | |
+| `space_repository_count` | `int?` | `subject=task` only — the channel's current list size |
+| `diverged_from_space` | `bool?` | `subject=task` only — the new task list differs from the channel's |
+| `was_inherited_from_space` | `bool?` | `subject=task` only — this edit is what broke inheritance |
+| `affected_space_count` | `int?` | `trigger=github_integration_disconnected` only |
+
+`trigger=task_created` fires only when the caller overrode the Space default. A task that
+inherits its channel's repositories is already counted by `task_created`.
+
+`trigger=github_integration_disconnected` is one aggregate row for the whole
+`pre_delete` sweep, not one row per Space.
+
+Reading note: ticking "Use these repositories for the whole space" in the desktop repository
+dialog fires both a task-level and a space-level change from a single click. Two rows is correct
+— they are two config objects — but a "changes per user" metric counts objects, not intents.
+
+### `space_context_changed`
+
+Fires when a Space's CONTEXT.md is published or cleared. Carries byte counts only; CONTEXT.md is
+customer-authored free text.
+
+| Property | Type | Description |
+| ------------------------ | ------ | ------------------------------------------------------------------- |
+| `action` | `str` | `published` or `cleared` |
+| `source` | `str` | `user` or `agent` |
+| `storage` | `str` | `legacy_instructions` or `context_wiki` |
+| `actor_type` | `str?` | `user_or_api`, `task_agent`, or `loop_agent` for context-wiki edits |
+| `team_id` | `int` | |
+| `channel_id` | `str` | |
+| `previous_version` | `int?` | 0 when there was none; null for context-wiki commits |
+| `new_version` | `int?` | Null on `cleared` |
+| `is_first_version` | `bool` | |
+| `content_bytes` | `int` | Length only, never content |
+| `previous_content_bytes` | `int?` | Gives edit magnitude |
+| `base_version_provided` | `bool` | Whether the client used the optimistic-concurrency guard |
+| `versions_deleted` | `int?` | `cleared` only |
+
+`source` is load-bearing: a loop configured with `update_context` republishes on every fire, so
+an hourly loop produces hundreds of rows a month for one Space. Filter to `source=user` for any
+human-edit question.
+
## TaskRun Model Events
Source: `products/tasks/backend/models.py`