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(warehouse-sources): add cursor analytics and ai code tracking tables (#104394)

Tom Owersf493ed6c261a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 4736c557078c..372a15bccc47 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -2197,24 +2197,24 @@ Note: The OpenAPI 3 spec at https://api.cultureamp.com/spec declares exactly thr
## Cursor — **thin**
-Today (4): `daily_usage`, `members`, `spend`, `usage_events`
+Today (11): `agent_edits`, `ai_code_commits`, `by_user_agent_edits`, `by_user_models`, `by_user_tabs`, `by_user_top_file_extensions`, `daily_usage`, `members`, `spend`, `tabs`, `usage_events`
Diffed against: <https://cursor.com/docs/account/teams/analytics-api.md>
-- [ ] `GET /analytics/ai-code/commits` — AI-authored code attribution per commit - Cursor's headline ROI metric, entirely absent today (high)
+- [x] `GET /analytics/ai-code/commits` — AI-authored code attribution per commit - Cursor's headline ROI metric (high)
- [ ] `GET /analytics/ai-code/changes` — change-level AI vs human code accounting, the finer grain behind the commit metrics (high)
- [ ] `GET /analytics/team/models` — model usage breakdown; the dimension every cost and adoption question needs alongside spend (high)
- [ ] `GET /analytics/team/dau` — daily active users, the standard seat-utilization metric (high)
-- [ ] `GET /analytics/team/agent-edits` — agent edit volume - the primary productivity measure for agent usage (high)
-- [ ] `GET /analytics/team/tabs` — tab-completion acceptance metrics, the other half of core usage (high)
-- [ ] `GET /analytics/by-user/{agent-edits,tabs,models,top-file-extensions}` — per-user breakdowns joining directly to the members table we already sync (high)
+- [x] `GET /analytics/team/agent-edits` — agent edit volume - the primary productivity measure for agent usage (high)
+- [x] `GET /analytics/team/tabs` — tab-completion acceptance metrics, the other half of core usage (high)
+- [x] `GET /analytics/by-user/{agent-edits,tabs,models,top-file-extensions}` — per-user breakdowns joining directly to the members table we already sync (high)
- [ ] `GET /teams/groups and /teams/groups/{id}/members` — billing-group lookup and membership resolving the group IDs on member and spend rows (medium)
- [ ] `GET /analytics/team/top-file-extensions` — language/file-type breakdown of AI usage (medium)
- [ ] `GET /analytics/team/bugbot and /analytics/team/bugbot-reviews` — code-review volume and per-review analytics for the Bugbot product (medium)
- [ ] `GET /analytics/team/conversation-insights` — aggregated conversation topics and outcomes (medium)
- [ ] `GET /teams/audit-logs` — admin action history for access and compliance reporting (medium)
-Note: PostHog covers the four Admin API data endpoints (members, daily-usage-data, spend, filtered-usage-events) but none of the separate Analytics API (25 team- and by-user endpoints), AI Code Tracking API (4), or Cloud Agents API. Admin API endpoints verified at https://cursor.com/docs/account/teams/admin-api.md and AI code tracking at https://cursor.com/docs/account/teams/ai-code-tracking-api.md. Repo blocklists and spend-limit endpoints excluded as configuration. Note most analytics endpoints are POST-with-body query endpoints, not plain GETs.
+Note: PostHog covers the four Admin API data endpoints (members, daily-usage-data, spend, filtered-usage-events) plus the agent-edits and tabs team metrics, their four by-user breakdowns, and the AI Code Tracking commit metrics. The rest of the Analytics API and the Cloud Agents API are still unmapped. Admin API endpoints verified at https://cursor.com/docs/account/teams/admin-api.md and AI code tracking at https://cursor.com/docs/account/teams/ai-code-tracking-api.md. Repo blocklists and spend-limit endpoints excluded as configuration. Correcting the original sweep: every Analytics API and AI Code Tracking endpoint is a plain GET with query params, not a POST with a body, and the Analytics API caps a range at 30 inclusive calendar days.
## Customerly — gaps
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/canonical_descriptions.py
index b74cd9ede22e..933fe9ab2fb0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/canonical_descriptions.py
@@ -82,4 +82,132 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"subscriptionCycleStart": "Start of the current subscription billing cycle (epoch milliseconds).",
},
},
+ "agent_edits": {
+ "description": "Daily team-wide totals for agent-suggested code edits, covering diffs suggested, accepted, and rejected.",
+ "docs_url": "https://cursor.com/docs/account/teams/analytics-api",
+ "columns": {
+ "event_date": "Day the metrics are aggregated for.",
+ "total_suggested_diffs": "Number of agent diffs suggested on this day.",
+ "total_accepted_diffs": "Number of suggested diffs accepted.",
+ "total_rejected_diffs": "Number of suggested diffs rejected.",
+ "total_green_lines_accepted": "Added lines in accepted diffs.",
+ "total_red_lines_accepted": "Removed lines in accepted diffs.",
+ "total_green_lines_rejected": "Added lines in rejected diffs.",
+ "total_red_lines_rejected": "Removed lines in rejected diffs.",
+ "total_green_lines_suggested": "Added lines across all suggested diffs.",
+ "total_red_lines_suggested": "Removed lines across all suggested diffs.",
+ "total_lines_suggested": "Total lines across all suggested diffs.",
+ "total_lines_accepted": "Total lines across accepted diffs.",
+ },
+ },
+ "tabs": {
+ "description": "Daily team-wide totals for Tab autocomplete, covering completions suggested, accepted, and rejected.",
+ "docs_url": "https://cursor.com/docs/account/teams/analytics-api",
+ "columns": {
+ "event_date": "Day the metrics are aggregated for.",
+ "total_suggestions": "Number of Tab completions suggested on this day.",
+ "total_accepts": "Number of Tab completions accepted.",
+ "total_rejects": "Number of Tab completions rejected.",
+ "total_green_lines_accepted": "Added lines in accepted completions.",
+ "total_red_lines_accepted": "Removed lines in accepted completions.",
+ "total_green_lines_rejected": "Added lines in rejected completions.",
+ "total_red_lines_rejected": "Removed lines in rejected completions.",
+ "total_green_lines_suggested": "Added lines across all suggested completions.",
+ "total_red_lines_suggested": "Removed lines across all suggested completions.",
+ "total_lines_suggested": "Total lines across all suggested completions.",
+ "total_lines_accepted": "Total lines across accepted completions.",
+ },
+ },
+ "by_user_agent_edits": {
+ "description": "Daily agent edit metrics broken down by team member.",
+ "docs_url": "https://cursor.com/docs/account/teams/analytics-api",
+ "columns": {
+ "userEmail": "Email address of the user the row belongs to. Joins to the members table on email.",
+ "userId": "Public (encoded) Cursor user ID for that email, as returned in the response user mappings.",
+ "event_date": "Day the metrics are aggregated for.",
+ "total_suggested_diffs": "Number of agent diffs suggested on this day.",
+ "total_accepted_diffs": "Number of suggested diffs accepted.",
+ "total_rejected_diffs": "Number of suggested diffs rejected.",
+ "total_green_lines_accepted": "Added lines in accepted diffs.",
+ "total_red_lines_accepted": "Removed lines in accepted diffs.",
+ "total_green_lines_rejected": "Added lines in rejected diffs.",
+ "total_red_lines_rejected": "Removed lines in rejected diffs.",
+ "total_green_lines_suggested": "Added lines across all suggested diffs.",
+ "total_red_lines_suggested": "Removed lines across all suggested diffs.",
+ "total_lines_suggested": "Total lines across all suggested diffs.",
+ "total_lines_accepted": "Total lines across accepted diffs.",
+ },
+ },
+ "by_user_tabs": {
+ "description": "Daily Tab autocomplete metrics broken down by team member.",
+ "docs_url": "https://cursor.com/docs/account/teams/analytics-api",
+ "columns": {
+ "userEmail": "Email address of the user the row belongs to. Joins to the members table on email.",
+ "userId": "Public (encoded) Cursor user ID for that email, as returned in the response user mappings.",
+ "event_date": "Day the metrics are aggregated for.",
+ "total_suggestions": "Number of Tab completions suggested on this day.",
+ "total_accepts": "Number of Tab completions accepted.",
+ "total_rejects": "Number of Tab completions rejected.",
+ "total_green_lines_accepted": "Added lines in accepted completions.",
+ "total_red_lines_accepted": "Removed lines in accepted completions.",
+ "total_green_lines_rejected": "Added lines in rejected completions.",
+ "total_red_lines_rejected": "Removed lines in rejected completions.",
+ "total_green_lines_suggested": "Added lines across all suggested completions.",
+ "total_red_lines_suggested": "Removed lines across all suggested completions.",
+ "total_lines_suggested": "Total lines across all suggested completions.",
+ "total_lines_accepted": "Total lines across accepted completions.",
+ },
+ },
+ "by_user_models": {
+ "description": "Daily model usage broken down by team member.",
+ "docs_url": "https://cursor.com/docs/account/teams/analytics-api",
+ "columns": {
+ "userEmail": "Email address of the user the row belongs to. Joins to the members table on email.",
+ "userId": "Public (encoded) Cursor user ID for that email, as returned in the response user mappings.",
+ "date": "Day the metrics are aggregated for.",
+ "model": "Model the row covers. The API returns a map keyed by model name, which PostHog expands into one row per model.",
+ "messages": "Number of messages the user sent to this model on this day.",
+ "users": "Number of users the count covers, which is always 1 in a per-user breakdown.",
+ },
+ },
+ "by_user_top_file_extensions": {
+ "description": "Daily breakdown of AI-assisted edits by file extension, per team member.",
+ "docs_url": "https://cursor.com/docs/account/teams/analytics-api",
+ "columns": {
+ "userEmail": "Email address of the user the row belongs to. Joins to the members table on email.",
+ "userId": "Public (encoded) Cursor user ID for that email, as returned in the response user mappings.",
+ "event_date": "Day the metrics are aggregated for.",
+ "file_extension": "File extension the row covers, without the leading dot.",
+ "total_files": "Number of files with this extension the user touched.",
+ "total_accepts": "Number of AI suggestions accepted in files with this extension.",
+ "total_rejects": "Number of AI suggestions rejected in files with this extension.",
+ "total_lines_suggested": "Lines suggested in files with this extension.",
+ "total_lines_accepted": "Lines accepted in files with this extension.",
+ "total_lines_rejected": "Lines rejected in files with this extension.",
+ },
+ },
+ "ai_code_commits": {
+ "description": "Per-commit metrics attributing the lines in a commit to Tab, Composer, and non-AI authoring.",
+ "docs_url": "https://cursor.com/docs/account/teams/ai-code-tracking-api",
+ "columns": {
+ "commitHash": "Git commit hash.",
+ "userId": "Public (encoded) Cursor user ID of the commit author.",
+ "userEmail": "Email address of the commit author.",
+ "repoName": "Repository the commit belongs to.",
+ "branchName": "Branch the commit was made on.",
+ "isPrimaryBranch": "Whether the branch is the repository's primary branch.",
+ "commitSource": "Where the commit originated: ide, cli, or cloud.",
+ "totalLinesAdded": "Total lines added in the commit.",
+ "totalLinesDeleted": "Total lines deleted in the commit.",
+ "tabLinesAdded": "Lines added that came from Tab completions.",
+ "tabLinesDeleted": "Lines deleted that came from Tab completions.",
+ "composerLinesAdded": "Lines added that came from Composer.",
+ "composerLinesDeleted": "Lines deleted that came from Composer.",
+ "nonAiLinesAdded": "Lines added that were not attributed to AI.",
+ "nonAiLinesDeleted": "Lines deleted that were not attributed to AI.",
+ "message": "Commit message.",
+ "commitTs": "When the commit was made.",
+ "createdAt": "When Cursor ingested the commit metrics.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/cursor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/cursor.py
index 5f5a68bcca84..f7efc3fb109a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/cursor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/cursor.py
@@ -19,13 +19,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sou
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.cursor.settings import (
CURSOR_ENDPOINTS,
+ MAX_WINDOW_DAYS,
CursorEndpointConfig,
)
CURSOR_BASE_URL = "https://api.cursor.com"
-# The windowed endpoints reject date ranges longer than 30 days, so backfills chunk into windows.
-MAX_WINDOW_DAYS = 30
# First sync fetches this much history instead of walking back to the team's creation.
DEFAULT_LOOKBACK_DAYS = 365
REQUEST_TIMEOUT_SECONDS = 60
@@ -59,6 +58,16 @@ def _from_epoch_ms(value: Any) -> datetime:
return datetime.fromtimestamp(int(value) / 1000, tz=UTC)
+def _parse_iso(value: str) -> datetime:
+ """Parse a Cursor Analytics date (`2025-01-15`) or timestamp (`2025-01-15T14:12:03.000Z`)."""
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
+
+
+def _to_iso_date(value: int) -> str:
+ return _from_epoch_ms(value).strftime("%Y-%m-%d")
+
+
def _now_ms() -> int:
return int(datetime.now(UTC).timestamp() * 1000)
@@ -105,11 +114,13 @@ def _fetch(
url: str,
logger: FilteringBoundLogger,
json_body: dict[str, Any] | None = None,
+ params: dict[str, Any] | None = None,
) -> dict[str, Any]:
response = session.request(
method,
url,
json=json_body,
+ params=params,
timeout=REQUEST_TIMEOUT_SECONDS,
)
@@ -182,22 +193,42 @@ def _normalize_usage_event(item: dict[str, Any]) -> dict[str, Any]:
return item
-def _build_windows(start_ms: int, end_ms: int) -> Iterator[tuple[int, int]]:
- """Chunk [start_ms, end_ms] into inclusive windows of at most MAX_WINDOW_DAYS."""
- window_ms = int(timedelta(days=MAX_WINDOW_DAYS).total_seconds() * 1000)
+def _make_iso_normalizer(*field_names: str) -> Callable[[dict[str, Any]], dict[str, Any]]:
+ """Build a normalizer that turns the named Analytics API date strings into datetimes."""
+
+ def normalize(item: dict[str, Any]) -> dict[str, Any]:
+ for field_name in field_names:
+ value = item.get(field_name)
+ if isinstance(value, str):
+ item[field_name] = _parse_iso(value)
+ return item
+
+ return normalize
+
+
+@frozen
+class Window:
+ start_ms: int
+ end_ms: int
+
+
+def _build_windows(start_ms: int, end_ms: int, window_days: int = MAX_WINDOW_DAYS) -> Iterator[Window]:
+ """Chunk [start_ms, end_ms] into inclusive windows of at most `window_days`."""
+ window_ms = int(timedelta(days=window_days).total_seconds() * 1000)
window_start = start_ms
while window_start <= end_ms:
window_end = min(window_start + window_ms - 1, end_ms)
- yield window_start, window_end
+ yield Window(start_ms=window_start, end_ms=window_end)
window_start = window_end + 1
def _has_next_page(data: dict[str, Any], page: int, items_count: int, page_size: int) -> bool:
"""Read the has-more signal from whichever pagination shape the endpoint returns.
- filtered-usage-events and daily-usage-data nest `hasNextPage` (plus `numPages`/`totalPages`)
- under `pagination`; /teams/spend returns `totalPages` at the top level. Fall back to a
- full-page heuristic when neither is present (the API silently ignoring pagination params
+ filtered-usage-events, daily-usage-data and the by-user analytics endpoints nest `hasNextPage`
+ (plus `numPages`/`totalPages`) under `pagination`; /teams/spend returns `totalPages` at the top
+ level, and /analytics/ai-code/commits returns `totalCount`. Fall back to a
+ full-page heuristic when none is present (the API silently ignoring pagination params
would otherwise loop forever on the same rows).
"""
pagination = data.get("pagination")
@@ -211,6 +242,9 @@ def _has_next_page(data: dict[str, Any], page: int, items_count: int, page_size:
total_pages = data.get("totalPages")
if total_pages is not None:
return page < int(total_pages)
+ total_count = data.get("totalCount")
+ if total_count is not None:
+ return page * page_size < int(total_count)
return items_count >= page_size
@@ -263,12 +297,83 @@ def _get_spend_rows(
page += 1
-_WINDOWED_NORMALIZERS = {
+_WINDOWED_NORMALIZERS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {
"usage_events": _normalize_usage_event,
"daily_usage": _normalize_daily_usage,
+ "agent_edits": _make_iso_normalizer("event_date"),
+ "tabs": _make_iso_normalizer("event_date"),
+ "by_user_agent_edits": _make_iso_normalizer("event_date"),
+ "by_user_tabs": _make_iso_normalizer("event_date"),
+ "by_user_top_file_extensions": _make_iso_normalizer("event_date"),
+ "by_user_models": _make_iso_normalizer("date"),
+ "ai_code_commits": _make_iso_normalizer("commitTs", "createdAt"),
+}
+
+
+def _expand_model_breakdown(row: dict[str, Any]) -> list[dict[str, Any]]:
+ """Turn the per-model map into one row per model.
+
+ The map is keyed by model name, so leaving it nested would change the table's column types
+ every time the team picks up a model it has not used before.
+ """
+ breakdown = row.pop("model_breakdown", None)
+ if not isinstance(breakdown, dict):
+ return []
+ return [
+ {**row, "model": model, **(metrics if isinstance(metrics, dict) else {})}
+ for model, metrics in breakdown.items()
+ ]
+
+
+_ROW_EXPANDERS: dict[str, Callable[[dict[str, Any]], list[dict[str, Any]]]] = {
+ "by_user_models": _expand_model_breakdown,
}
+def _extract_rows(config: CursorEndpointConfig, data: dict[str, Any]) -> list[dict[str, Any]]:
+ payload = data.get(config.data_key)
+ if not config.by_user:
+ return payload or []
+ if not isinstance(payload, dict):
+ return []
+
+ # By-user responses key rows by email and carry the public user ids alongside, so stamp both
+ # onto every row — otherwise the identity a row belongs to is lost in the flattening.
+ ids_by_email = {
+ mapping["email"]: mapping.get("id")
+ for mapping in ((data.get("params") or {}).get("userMappings") or [])
+ if isinstance(mapping, dict) and mapping.get("email")
+ }
+ expand = _ROW_EXPANDERS.get(config.name)
+ rows = [
+ {**row, "userEmail": email, "userId": ids_by_email.get(email)}
+ for email, user_rows in payload.items()
+ for row in user_rows or []
+ ]
+ return [expanded for row in rows for expanded in expand(row)] if expand else rows
+
+
+def _page_item_count(config: CursorEndpointConfig, data: dict[str, Any], rows: list[dict[str, Any]]) -> int:
+ # A by-user page holds `pageSize` users, not `pageSize` rows, so the full-page fallback in
+ # `_has_next_page` has to count users.
+ if config.by_user:
+ payload = data.get(config.data_key)
+ return len(payload) if isinstance(payload, dict) else 0
+ return len(rows)
+
+
+def _window_request_params(
+ config: CursorEndpointConfig, window_start: int, window_end: int, page: int
+) -> dict[str, Any]:
+ if config.date_param_format == "iso_date":
+ params: dict[str, Any] = {"startDate": _to_iso_date(window_start), "endDate": _to_iso_date(window_end)}
+ else:
+ params = {"startDate": window_start, "endDate": window_end}
+ if config.paginated:
+ params |= {"page": page, "pageSize": config.page_size}
+ return params
+
+
@frozen
class WindowStart:
start_ms: int
@@ -317,17 +422,19 @@ def _paginate_window(
) -> Iterator[list[dict[str, Any]]]:
page = first_page
while True:
- body = {
- "startDate": window_start,
- "endDate": window_end,
- "page": page,
- "pageSize": config.page_size,
- }
- data = _fetch(session, config.method, f"{CURSOR_BASE_URL}{config.path}", logger, json_body=body)
+ request_params = _window_request_params(config, window_start, window_end, page)
+ url = f"{CURSOR_BASE_URL}{config.path}"
+ if config.query_params:
+ data = _fetch(session, config.method, url, logger, params=request_params)
+ else:
+ data = _fetch(session, config.method, url, logger, json_body=request_params)
- items = data.get(config.data_key) or []
+ items = _extract_rows(config, data)
rows = [normalize(item) for item in items]
- has_next = _has_next_page(data, page, len(items), config.page_size)
+ # A by-user page is sized in users, and a user with no activity in the window contributes
+ # no rows — so termination has to read the page's own size, not the row count.
+ page_items = _page_item_count(config, data, items)
+ has_next = config.paginated and _has_next_page(data, page, page_items, config.page_size)
if rows:
yield rows
@@ -337,7 +444,7 @@ def _paginate_window(
elif window_end + 1 <= end_ms:
resumable_source_manager.save_state(CursorResumeConfig(window_start=window_end + 1, page=1))
- if not items or not has_next:
+ if not page_items or not has_next:
break
page += 1
@@ -366,15 +473,15 @@ def _get_windowed_rows(
raise ValueError(f"No normalizer defined for windowed endpoint: {config.name}")
first_page = window_start.first_page
- for start, end in _build_windows(window_start.start_ms, end_ms):
+ for window in _build_windows(window_start.start_ms, end_ms, config.window_days):
yield from _paginate_window(
session,
config,
logger,
resumable_source_manager,
normalize,
- start,
- end,
+ window.start_ms,
+ window.end_ms,
end_ms,
first_page,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/settings.py
index f74543ae5f4c..697dc0e5153d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/settings.py
@@ -1,10 +1,27 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal, Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+MAX_WINDOW_DAYS = 30
+# The Analytics API caps a range at 30 inclusive calendar days. Windows are millisecond ranges that
+# are not midnight-aligned, so a 30-day window straddles 31 calendar dates once both ends are
+# truncated to a date. 29 is the largest window that always fits.
+ANALYTICS_MAX_WINDOW_DAYS = 29
+
+
+def _datetime_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
-@dataclass
+
+@frozen
class CursorEndpointConfig:
name: str
path: str
@@ -12,9 +29,16 @@ class CursorEndpointConfig:
data_key: str = "data" # Response key holding the list of rows
primary_keys: list[str] = field(default_factory=lambda: ["id"])
incremental_fields: list[IncrementalField] = field(default_factory=list)
- # Endpoint takes startDate/endDate epoch-ms body params with a 30-day max range,
- # so syncs chunk the requested range into windows.
+ # Endpoint takes startDate/endDate params with a maximum range, so syncs chunk the requested
+ # range into windows.
windowed: bool = False
+ window_days: int = MAX_WINDOW_DAYS
+ # Analytics API endpoints take their params in the query string and their dates as YYYY-MM-DD;
+ # the Admin API takes a JSON body with epoch-ms dates.
+ query_params: bool = False
+ date_param_format: Literal["epoch_ms", "iso_date"] = "epoch_ms"
+ # Response `data` is an object keyed by user email instead of a list of rows.
+ by_user: bool = False
paginated: bool = True
page_size: int = 100
partition_key: Optional[str] = None # Stable datetime field to partition by
@@ -40,14 +64,7 @@ CURSOR_ENDPOINTS: dict[str, CursorEndpointConfig] = {
primary_keys=["date", "userId"],
windowed=True,
partition_key="date",
- incremental_fields=[
- {
- "label": "date",
- "type": IncrementalFieldType.DateTime,
- "field": "date",
- "field_type": IncrementalFieldType.DateTime,
- },
- ],
+ incremental_fields=[_datetime_field("date")],
description="Per-user daily usage metrics (lines accepted, tabs, agent requests). Only syncs the last 365 days on initial sync",
),
"usage_events": CursorEndpointConfig(
@@ -59,14 +76,7 @@ CURSOR_ENDPOINTS: dict[str, CursorEndpointConfig] = {
primary_keys=["id"],
windowed=True,
partition_key="timestamp",
- incremental_fields=[
- {
- "label": "timestamp",
- "type": IncrementalFieldType.DateTime,
- "field": "timestamp",
- "field_type": IncrementalFieldType.DateTime,
- },
- ],
+ incremental_fields=[_datetime_field("timestamp")],
description="Per-request usage events with model, token usage, and cost. Only syncs the last 365 days on initial sync",
),
"spend": CursorEndpointConfig(
@@ -76,6 +86,127 @@ CURSOR_ENDPOINTS: dict[str, CursorEndpointConfig] = {
primary_keys=["userId"],
description="Per-member spend for the current billing cycle. Full refresh only",
),
+ "agent_edits": CursorEndpointConfig(
+ name="agent_edits",
+ path="/analytics/team/agent-edits",
+ method="GET",
+ query_params=True,
+ date_param_format="iso_date",
+ data_key="data",
+ # One aggregate row per day for the whole team.
+ primary_keys=["event_date"],
+ windowed=True,
+ window_days=ANALYTICS_MAX_WINDOW_DAYS,
+ paginated=False,
+ partition_key="event_date",
+ incremental_fields=[_datetime_field("event_date")],
+ should_sync_default=False,
+ description="Daily team totals for agent-suggested edits: diffs suggested, accepted, and rejected, with line counts. Needs a Cursor Enterprise plan. Only syncs the last 365 days on initial sync",
+ ),
+ "tabs": CursorEndpointConfig(
+ name="tabs",
+ path="/analytics/team/tabs",
+ method="GET",
+ query_params=True,
+ date_param_format="iso_date",
+ data_key="data",
+ primary_keys=["event_date"],
+ windowed=True,
+ window_days=ANALYTICS_MAX_WINDOW_DAYS,
+ paginated=False,
+ partition_key="event_date",
+ incremental_fields=[_datetime_field("event_date")],
+ should_sync_default=False,
+ description="Daily team totals for Tab autocomplete: suggestions, accepts, rejects, and line counts. Needs a Cursor Enterprise plan. Only syncs the last 365 days on initial sync",
+ ),
+ "by_user_agent_edits": CursorEndpointConfig(
+ name="by_user_agent_edits",
+ path="/analytics/by-user/agent-edits",
+ method="GET",
+ query_params=True,
+ date_param_format="iso_date",
+ data_key="data",
+ by_user=True,
+ primary_keys=["event_date", "userEmail"],
+ windowed=True,
+ window_days=ANALYTICS_MAX_WINDOW_DAYS,
+ page_size=500,
+ partition_key="event_date",
+ incremental_fields=[_datetime_field("event_date")],
+ should_sync_default=False,
+ description="Per-user daily agent edit metrics, keyed by email so they join to members. Needs a Cursor Enterprise plan. Only syncs the last 365 days on initial sync",
+ ),
+ "by_user_tabs": CursorEndpointConfig(
+ name="by_user_tabs",
+ path="/analytics/by-user/tabs",
+ method="GET",
+ query_params=True,
+ date_param_format="iso_date",
+ data_key="data",
+ by_user=True,
+ primary_keys=["event_date", "userEmail"],
+ windowed=True,
+ window_days=ANALYTICS_MAX_WINDOW_DAYS,
+ page_size=500,
+ partition_key="event_date",
+ incremental_fields=[_datetime_field("event_date")],
+ should_sync_default=False,
+ description="Per-user daily Tab autocomplete metrics, keyed by email so they join to members. Needs a Cursor Enterprise plan. Only syncs the last 365 days on initial sync",
+ ),
+ "by_user_models": CursorEndpointConfig(
+ name="by_user_models",
+ path="/analytics/by-user/models",
+ method="GET",
+ query_params=True,
+ date_param_format="iso_date",
+ data_key="data",
+ by_user=True,
+ # One row per user per day per model, expanded from the per-model map the API returns.
+ primary_keys=["date", "userEmail", "model"],
+ windowed=True,
+ window_days=ANALYTICS_MAX_WINDOW_DAYS,
+ page_size=500,
+ partition_key="date",
+ incremental_fields=[_datetime_field("date")],
+ should_sync_default=False,
+ description="Per-user daily model usage, with a message count for each model. Needs a Cursor Enterprise plan. Only syncs the last 365 days on initial sync",
+ ),
+ "by_user_top_file_extensions": CursorEndpointConfig(
+ name="by_user_top_file_extensions",
+ path="/analytics/by-user/top-file-extensions",
+ method="GET",
+ query_params=True,
+ date_param_format="iso_date",
+ data_key="data",
+ by_user=True,
+ # One row per user per day per file extension.
+ primary_keys=["event_date", "userEmail", "file_extension"],
+ windowed=True,
+ window_days=ANALYTICS_MAX_WINDOW_DAYS,
+ page_size=500,
+ partition_key="event_date",
+ incremental_fields=[_datetime_field("event_date")],
+ should_sync_default=False,
+ description="Per-user daily file extension breakdown of AI-assisted edits. Needs a Cursor Enterprise plan. Only syncs the last 365 days on initial sync",
+ ),
+ "ai_code_commits": CursorEndpointConfig(
+ name="ai_code_commits",
+ path="/analytics/ai-code/commits",
+ method="GET",
+ query_params=True,
+ date_param_format="iso_date",
+ data_key="items",
+ # A commit hash is unique per commit; the author is in the key too because the docs
+ # scope uniqueness to the aggregate, not to the hash.
+ primary_keys=["commitHash", "userId"],
+ windowed=True,
+ window_days=ANALYTICS_MAX_WINDOW_DAYS,
+ page_size=1000,
+ partition_key="commitTs",
+ incremental_fields=[_datetime_field("commitTs")],
+ should_sync_default=False,
+ description="Per-commit attribution of lines added and deleted to Tab, Composer, and non-AI authoring. Needs a Cursor Enterprise plan with AI code tracking enabled. Only syncs the last 365 days on initial sync",
+ ),
}
ENDPOINTS = tuple(CURSOR_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor.py
index cfa258247216..212dd8a2d989 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor.py
@@ -1,6 +1,6 @@
import base64
from collections.abc import Iterable, Iterator
-from datetime import UTC, datetime
+from datetime import UTC, date, datetime
from typing import Any, cast
import pytest
@@ -15,13 +15,18 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.cursor imp
from products.warehouse_sources.backend.temporal.data_imports.sources.cursor.cursor import (
CursorResumeConfig,
_build_windows,
+ _extract_rows,
_has_next_page,
+ _make_iso_normalizer,
_normalize_daily_usage,
_normalize_usage_event,
+ _page_item_count,
+ _to_iso_date,
_usage_event_id,
cursor_source,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.cursor.settings import CURSOR_ENDPOINTS
DAY_MS = 24 * 60 * 60 * 1000
WINDOW_MS = cursor.MAX_WINDOW_DAYS * DAY_MS
@@ -77,11 +82,11 @@ class TestCursorTransport:
windows = list(_build_windows(start_ms, end_ms))
assert len(windows) == expected_windows
- assert windows[0][0] == start_ms
- assert windows[-1][1] == end_ms
- for (_, prev_end), (next_start, _) in zip(windows, windows[1:]):
- assert next_start == prev_end + 1 # inclusive bounds — no gap, no overlap
- assert all(end - start < WINDOW_MS for start, end in windows)
+ assert windows[0].start_ms == start_ms
+ assert windows[-1].end_ms == end_ms
+ for previous, following in zip(windows, windows[1:]):
+ assert following.start_ms == previous.end_ms + 1 # inclusive bounds — no gap, no overlap
+ assert all(window.end_ms - window.start_ms < WINDOW_MS for window in windows)
def test_usage_event_id_is_deterministic_and_distinct(self):
event = {"timestamp": "1700000000000", "userEmail": "[email protected]", "model": "gpt-5"}
@@ -109,6 +114,8 @@ class TestCursorTransport:
({"pagination": {"totalPages": 2}}, 1, 100, True),
({"totalPages": 2}, 1, 100, True), # /teams/spend keeps totalPages at the top level
({"totalPages": 2}, 2, 100, False),
+ ({"totalCount": 250}, 1, 100, True), # /analytics/ai-code/commits reports a row total
+ ({"totalCount": 250}, 3, 100, False),
({}, 1, 100, True), # no pagination info — full page implies more
({}, 1, 50, False), # partial page implies done
]
@@ -240,6 +247,158 @@ class TestCursorTransport:
assert len(batches) == 1
assert session.request.call_args.kwargs["json"]["page"] == 3
+ def test_iso_normalizer_parses_dates_and_timestamps(self):
+ normalize = _make_iso_normalizer("commitTs", "createdAt", "event_date")
+
+ item = normalize({"commitTs": "2025-07-30T14:12:03.000Z", "createdAt": None, "event_date": "2025-01-15"})
+
+ assert item["commitTs"] == datetime(2025, 7, 30, 14, 12, 3, tzinfo=UTC)
+ assert item["createdAt"] is None
+ assert item["event_date"] == datetime(2025, 1, 15, tzinfo=UTC)
+
+ def test_by_user_rows_carry_the_user_identity(self):
+ data = {
+ "data": {
+ "[email protected]": [{"event_date": "2025-01-15", "total_accepts": 3}],
+ "[email protected]": [{"event_date": "2025-01-15", "total_accepts": 1}],
+ },
+ "params": {"userMappings": [{"id": "user_abc", "email": "[email protected]"}]},
+ }
+
+ rows = _extract_rows(CURSOR_ENDPOINTS["by_user_tabs"], data)
+
+ assert rows == [
+ {
+ "event_date": "2025-01-15",
+ "total_accepts": 3,
+ "userEmail": "[email protected]",
+ "userId": "user_abc",
+ },
+ # A user missing from the mappings still keeps the email the primary key is built on.
+ {"event_date": "2025-01-15", "total_accepts": 1, "userEmail": "[email protected]", "userId": None},
+ ]
+
+ def test_by_user_models_expands_the_per_model_map_into_rows(self):
+ # Left nested, the map's keys are model names, so the column set would change whenever the
+ # team starts using a model it has not used before.
+ data = {
+ "data": {
+ {"date": "2025-01-15", "model_breakdown": {"claude-sonnet-4.5": {"messages": 85, "users": 1}}}
+ ]
+ }
+ }
+
+ rows = _extract_rows(CURSOR_ENDPOINTS["by_user_models"], data)
+
+ assert rows == [
+ {
+ "date": "2025-01-15",
+ "userEmail": "[email protected]",
+ "userId": None,
+ "model": "claude-sonnet-4.5",
+ "messages": 85,
+ "users": 1,
+ }
+ ]
+
+ def test_by_user_pagination_walks_past_a_page_where_nobody_was_active(self):
+ # Pages are sized in users, so a page of users who did nothing in the window yields no
+ # rows. Treating that as the end of the data would drop every later user.
+ now_ms = 1_700_000_000_000
+ session = mock.Mock()
+ session.request.side_effect = [
+ _response(200, {"data": {"[email protected]": []}, "pagination": {"hasNextPage": True}}),
+ _response(
+ 200,
+ {
+ "data": {"[email protected]": [{"event_date": "2023-11-14", "total_accepts": 2}]},
+ "pagination": {"hasNextPage": False},
+ },
+ ),
+ ]
+
+ with (
+ mock.patch.object(cursor, "_now_ms", return_value=now_ms),
+ mock.patch.object(cursor, "make_tracked_session", return_value=session),
+ ):
+ batches = list(
+ _batches(
+ cursor_source(
+ "key_test",
+ "by_user_tabs",
+ mock.Mock(),
+ _manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime.fromtimestamp((now_ms - DAY_MS) / 1000, tz=UTC),
+ )
+ )
+ )
+
+ assert session.request.call_count == 2
+ assert [row["userEmail"] for batch in batches for row in batch] == ["[email protected]"]
+
+ @parameterized.expand(
+ [
+ # A by-user page holds `pageSize` users, so 200 rows spread over 100 users is 100 items.
+ ("by_user_tabs", {"data": {f"u{i}@example.com": [{}, {}] for i in range(100)}}, 200, 100),
+ ("ai_code_commits", {"items": [{}] * 7}, 7, 7),
+ ]
+ )
+ def test_page_item_count_uses_the_unit_the_page_is_sized_in(self, endpoint, data, row_count, expected):
+ assert _page_item_count(CURSOR_ENDPOINTS[endpoint], data, [{}] * row_count) == expected
+
+ @parameterized.expand(
+ [
+ ("agent_edits", {"data": []}, False),
+ ("by_user_agent_edits", {"data": {}, "pagination": {"hasNextPage": False}}, True),
+ ("ai_code_commits", {"items": [], "totalCount": 0}, True),
+ ]
+ )
+ def test_analytics_endpoints_send_calendar_dates_as_query_params(self, endpoint, payload, paginated):
+ now_ms = 1_700_000_000_000 # 2023-11-14T22:13:20Z
+ watermark = datetime.fromtimestamp((now_ms - 5 * DAY_MS) / 1000, tz=UTC)
+ session = mock.Mock()
+ session.request.return_value = _response(200, payload)
+
+ with (
+ mock.patch.object(cursor, "_now_ms", return_value=now_ms),
+ mock.patch.object(cursor, "make_tracked_session", return_value=session),
+ ):
+ list(
+ _batches(
+ cursor_source(
+ "key_test",
+ endpoint,
+ mock.Mock(),
+ _manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+ )
+ )
+
+ call = session.request.call_args
+ assert call.args[0] == "GET"
+ assert call.kwargs["json"] is None
+ # The Analytics API resolves dates to the day and documents YYYY-MM-DD as the cacheable form.
+ assert call.kwargs["params"]["startDate"] == "2023-11-09"
+ assert call.kwargs["params"]["endDate"] == "2023-11-14"
+ assert ("page" in call.kwargs["params"]) is paginated
+
+ def test_analytics_windows_stay_within_the_calendar_day_cap(self):
+ # The Analytics API rejects a range wider than 30 inclusive calendar days, and windows are
+ # millisecond ranges that are not midnight-aligned, so a 30-day window would straddle 31.
+ end_ms = 1_700_000_000_000
+ window_days = CURSOR_ENDPOINTS["agent_edits"].window_days
+
+ windows = _build_windows(end_ms - cursor.DEFAULT_LOOKBACK_DAYS * DAY_MS, end_ms, window_days)
+
+ for window in windows:
+ start_date = date.fromisoformat(_to_iso_date(window.start_ms))
+ end_date = date.fromisoformat(_to_iso_date(window.end_ms))
+ assert (end_date - start_date).days + 1 <= 30
+
def test_windowed_first_sync_starts_at_lookback(self):
now_ms = 1_700_000_000_000
session = mock.Mock()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor_source.py
index d0cd40e72fbc..35f41ce4d786 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor_source.py
@@ -8,6 +8,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.cursor.sou
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cursor import CursorSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
+ALL_ENDPOINTS = [
+ "members",
+ "daily_usage",
+ "usage_events",
+ "spend",
+ "agent_edits",
+ "tabs",
+ "by_user_agent_edits",
+ "by_user_tabs",
+ "by_user_models",
+ "by_user_top_file_extensions",
+ "ai_code_commits",
+]
+
class TestCursorSource:
def setup_method(self):
@@ -32,8 +46,19 @@ class TestCursorSource:
def test_get_schemas_returns_all_endpoints(self):
schemas = self.source.get_schemas(self.config, self.team_id)
- assert [s.name for s in schemas] == ["members", "daily_usage", "usage_events", "spend"]
- assert all(s.should_sync_default for s in schemas)
+ assert [s.name for s in schemas] == ALL_ENDPOINTS
+
+ def test_enterprise_only_endpoints_are_not_selected_by_default(self):
+ # The Analytics and AI code tracking APIs need an Enterprise plan, so a Business-plan team
+ # that accepts the defaults must not end up with schemas that 403 on every sync.
+ defaults = {s.name: s.should_sync_default for s in self.source.get_schemas(self.config, self.team_id)}
+
+ assert [name for name, default in defaults.items() if default] == [
+ "members",
+ "daily_usage",
+ "usage_events",
+ "spend",
+ ]
@parameterized.expand(
[
@@ -41,6 +66,13 @@ class TestCursorSource:
("daily_usage", True, "date"),
("usage_events", True, "timestamp"),
("spend", False, None),
+ ("agent_edits", True, "event_date"),
+ ("tabs", True, "event_date"),
+ ("by_user_agent_edits", True, "event_date"),
+ ("by_user_tabs", True, "event_date"),
+ ("by_user_models", True, "date"),
+ ("by_user_top_file_extensions", True, "event_date"),
+ ("ai_code_commits", True, "commitTs"),
]
)
def test_get_schemas_incremental_support(self, endpoint, supports_incremental, incremental_field):
@@ -63,7 +95,7 @@ class TestCursorSource:
# lists_tables_without_credentials=True drives the public docs' Supported tables section.
tables = self.source.get_documented_tables()
- assert [t["name"] for t in tables] == ["members", "daily_usage", "usage_events", "spend"]
+ assert [t["name"] for t in tables] == ALL_ENDPOINTS
assert all(t["description"] for t in tables)
@parameterized.expand([((True, None),), ((False, KEY_REJECTED_MESSAGE),)])