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(signals): add external agent report claims (#94017)

Mikayla Thompson97547481cd29
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index f25628d6ec39..d93a21804640 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -322,6 +322,7 @@ rules:
|SignalReport
|SignalReportAction
|SignalReportArtefact
+ |SignalReportAssignment
|SignalReportRefund
|SignalReportTask
|SignalRepositoryAreaActivity
@@ -707,6 +708,7 @@ rules:
|SignalReport
|SignalReportAction
|SignalReportArtefact
+ |SignalReportAssignment
|SignalReportRefund
|SignalReportTask
|SignalRepositoryAreaActivity
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index 6c4f4d64af9f..cadedc446d86 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -209,6 +209,7 @@ post_save:products.signals.backend.receivers.close_pr_when_report_dismissed
post_save:products.signals.backend.receivers.emit_report_embedding_on_document_change
post_save:products.signals.backend.receivers.mark_scout_suggestions_stale_on_fleet_change
post_save:products.signals.backend.receivers.reconcile_report_embedding_on_verdict_saved
+post_save:products.signals.backend.receivers.sync_task_run_pr_to_assignments
post_save:products.signals.backend.receivers.tombstone_report_embedding_on_delete
post_save:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_change
post_save:products.slack_app.backend.signals.onboard_slack_inbox_on_install
diff --git a/products/posthog_ai/frontend/policy/toolPolicy.test.ts b/products/posthog_ai/frontend/policy/toolPolicy.test.ts
index dd71ffe5010d..0d2a30d8a4e6 100644
--- a/products/posthog_ai/frontend/policy/toolPolicy.test.ts
+++ b/products/posthog_ai/frontend/policy/toolPolicy.test.ts
@@ -67,6 +67,7 @@ describe('toolPolicy', () => {
'workflows-publish',
'experiment-ship-variant',
'feature-requests-remove-evidence-create',
+ 'inbox-reports-claim',
'skill-archive',
'error-tracking-issues-merge-create',
])('%s is destructive', (sub) => expect(isPostHogDestructiveSubTool(sub)).toBe(true))
diff --git a/products/posthog_ai/frontend/policy/toolPolicy.ts b/products/posthog_ai/frontend/policy/toolPolicy.ts
index ba1b327c60b6..9236fd4aedce 100644
--- a/products/posthog_ai/frontend/policy/toolPolicy.ts
+++ b/products/posthog_ai/frontend/policy/toolPolicy.ts
@@ -50,6 +50,7 @@ const POSTHOG_DESTRUCTIVE_SUB_TOOLS = new Set([
'feature-requests-remove-evidence-create',
'heatmaps-saved-regenerate',
'inbox-reports-bulk-set-state',
+ 'inbox-reports-claim',
'inbox-reports-set-state',
'llma-prompt-label-set',
'opt-outs-add',
diff --git a/products/signals/AGENT_REMEDIATION_PLAN.md b/products/signals/AGENT_REMEDIATION_PLAN.md
new file mode 100644
index 000000000000..2a1b5ac0a787
--- /dev/null
+++ b/products/signals/AGENT_REMEDIATION_PLAN.md
@@ -0,0 +1,117 @@
+# Self-driving inbox: agent remediation flow
+
+Follow-on to PR #92769.
+
+## Goal
+
+Let an internal task or an external coding agent claim an actionable report, show that work is underway, and optionally attach one implementation pull request. External-agent remediation must not require a task or any task-backed data.
+
+## Actor model
+
+Assignments and report artefacts use four actor kinds:
+
+- `user`: a person acting directly through PostHog or the API.
+- `task`: an internal PostHog task. This is the only actor kind that references the tasks product.
+- `agent`: an external MCP coding agent acting on behalf of an authenticated user.
+- `system`: an automated PostHog process.
+
+For MCP requests without an internal task header, the backend derives the agent name from the MCP client identity forwarded by the MCP server. The authenticated user remains the principal. The client name is attribution metadata, not an authorization boundary.
+
+Existing artefacts are not backfilled. A null actor kind on a legacy row is read as `system`.
+
+## Claim behavior
+
+`inbox-reports-claim` accepts:
+
+- `report_id`
+- optional `pr_url`
+- optional `release`, defaulting to `false`
+
+Claiming upserts the current assignment. A new actor silently takes over an existing claim. Repeating an identical claim is idempotent.
+
+`release=true` clears only the owner. It keeps an attached PR and its state. Only the current actor may release a claim. A request cannot combine `release=true` with `pr_url`.
+
+Claims do not expire. Expiration and heartbeats are deferred.
+
+Reports in `potential`, `candidate`, `in_progress`, `pending_input`, `ready`, or `failed` may be claimed. Suppressed and resolved reports remain terminal.
+
+## Pull requests
+
+A report has at most one attached implementation PR. One PR may be attached to several reports.
+
+The assignment stores the supplied URL and its normalized `(repository, pr_number)` identity. Replacing the URL updates the assignment and records the before/after values in the activity log.
+
+When the repository is connected, attaching a PR immediately fetches its state. Open and draft PRs put the report in review. A merged PR resolves the report. A closed, unmerged PR suppresses it, matching the existing inbox behavior.
+
+PRs from unconnected repositories are allowed. Their state is `unknown`, they are treated as in review, and they require a manual state transition because PostHog cannot fetch their state or receive their webhooks.
+
+GitHub webhook matching is scoped by the teams associated with the installation, then matched by normalized repository and PR number. A matching merge or close transitions every unresolved report attached to that PR.
+
+Internal implementation tasks claim their report when they start. When a PR-bearing task run records a PR, the signals receiver copies it into the assignment without requiring the task to call the public claim API. Existing task-backed PRs remain readable as a compatibility fallback when an assignment has no PR; assignment data always wins.
+
+Resolving a report never requires a PR. Manual resolution keeps the existing behavior: `fixed_outside_posthog` describes a fix without a PR, and `pr_merged` describes a merged PR that did not resolve the report automatically. A direct resolve or suppression closes an attached open PR only when the current assignment actor is `task` or `system` and PostHog can access it. PRs owned by users or external agents are not modified.
+
+## Derived work state
+
+Work state is derived in this order:
+
+1. `done`: the report is resolved.
+2. `in_review`: an attached PR is open, draft, or unknown.
+3. `working`: the report has an owner and no in-review PR.
+4. `unclaimed`: the report has no owner and no in-review PR.
+
+Pipeline `status` and remediation `work_state` remain separate. Claimed reports still appear in actionable views.
+
+## Data model
+
+Add `SignalReportAssignment`, one row per report:
+
+- team and report
+- nullable actor kind, authenticated user ID, internal task ID, and external agent name
+- optional PR URL, normalized repository and PR number
+- optional PR state and merged flag
+- `claimed_at`, `created_at`, and `updated_at`
+
+Ownership fields are nullable so release can preserve PR state. External-agent rows never carry a task ID.
+
+Add `actor_kind` and `actor_agent` to `SignalReportArtefact`. Keep `created_by` and `task`. New writes persist explicit actor kinds; legacy null kinds serialize as `system`.
+
+## API and MCP surface
+
+- Add `inbox-reports-claim` for claim, takeover, PR attachment, PR replacement, and release.
+- Keep `inbox-reports-set-state` for resolve, suppress, and restore.
+- Extend `inbox-reports-list` with `unclaimed` and `assignee=me` filters.
+- Return `work_state`, assignment actor details, `claimed_at`, PR URL, and PR state from every report list and retrieve response.
+- Back `has_implementation_pr`, `implementation_pr_url`, and `implementation_pr_merged` from the assignment table first, with existing task-backed PRs as a compatibility fallback.
+- Update list and retrieve agent guidance to claim before starting work. External agents no longer need or create a task association.
+
+`assignee=me` means the exact current actor: the authenticated user for direct user requests, or the authenticated user plus derived MCP client name for external agents.
+
+## Audit trail
+
+Use the existing `ActivityLog` mechanism with `scope=SignalReport`. Record claim, takeover, release, PR attachment, and PR replacement as before/after assignment changes. Do not write an entry for an identical repeat request.
+
+No new assignment-history table or assignment artefact type is required.
+
+## Deferred work
+
+- Claim expiration and heartbeats.
+- Force-takeover or compare-and-swap ownership.
+- More than one PR per report.
+- Rich assignee search beyond `assignee=me`.
+- Polling or reconciliation for PRs in unconnected repositories.
+
+## Follow-up verification
+
+- Model constraints and actor attribution for user, task, agent, system, and legacy rows.
+- MCP client-name forwarding, generic MCP fallback, and direct-user attribution.
+- Claim, silent takeover, same-actor idempotency, authorized release, and rejected release by another actor.
+- Team scoping for claim, retrieve, filtering, and cross-project report IDs.
+- PR attach, replace, release-with-PR, connected-state fetch, and unconnected unknown state.
+- Derived work state across report status, ownership, and PR state combinations.
+- `unclaimed`, `assignee=me`, and `has_implementation_pr` list filtering.
+- Activity-log before/after entries and no-op suppression.
+- Connected webhook scoping, one PR linked to several reports, merge resolution, and closed-unmerged suppression.
+- Manual resolve/suppress PR-closing behavior.
+- Verify that new task PRs populate assignments and existing task-run-backed PRs remain visible through the fallback.
+- OpenAPI generation, generated MCP schema, tool-name lint, MCP typecheck, and focused backend tests.
diff --git a/products/signals/backend/apps.py b/products/signals/backend/apps.py
index 2a56ea96690c..c74c87f59318 100644
--- a/products/signals/backend/apps.py
+++ b/products/signals/backend/apps.py
@@ -16,6 +16,7 @@ class SignalsConfig(AppConfig):
receivers, # noqa: F401
)
+ receivers.connect_task_run_assignment_sync()
self._register_signal_emission_gate()
def _register_signal_emission_gate(self) -> None:
diff --git a/products/signals/backend/artefact_attribution.py b/products/signals/backend/artefact_attribution.py
index a53be6ae9fd2..fb64cebaba0e 100644
--- a/products/signals/backend/artefact_attribution.py
+++ b/products/signals/backend/artefact_attribution.py
@@ -1,38 +1,40 @@
"""Attribution for artefact writes — who (or what) produced a row.
-Kept in its own stdlib-only leaf (no Django, no pydantic) so any artefact-store consumer can
-import it without dragging the heavy models module. Re-exported from `models.py` for existing
-importers.
+Kept in its own lightweight leaf without Django or pydantic so artefact-store consumers can
+import it without dragging in the models module. Re-exported from `models.py` for existing importers.
"""
from __future__ import annotations
-from dataclasses import dataclass
from typing import Literal
+from posthog.dataclasses import frozen
-@dataclass(frozen=True)
+
+@frozen
class ArtefactAttribution:
- """Who (or what) produced an artefact — exactly one of a user, a task, or the system.
+ """Who or what produced an artefact.
Required on every artefact write helper so no write site can silently skip attribution:
- callers must consciously pick `from_user` / `from_task` / `system()`. System attribution
- covers pipeline writers with neither in scope (e.g. the safety judge); it stores NULLs,
- indistinguishable from legacy rows by design.
+ callers must consciously pick a constructor. An external agent keeps both the authenticated
+ user principal and the MCP client name, while an internal task uses only its task id.
"""
- kind: Literal["user", "task", "system"]
+ kind: Literal["user", "task", "agent", "system"]
user_id: int | None = None
task_id: str | None = None
+ agent_name: str | None = None
def __post_init__(self) -> None:
match self.kind:
case "user":
- valid = self.user_id is not None and self.task_id is None
+ valid = self.user_id is not None and self.task_id is None and self.agent_name is None
case "task":
- valid = self.task_id is not None and self.user_id is None
+ valid = self.task_id is not None and self.user_id is None and self.agent_name is None
+ case "agent":
+ valid = self.user_id is not None and self.task_id is None and bool(self.agent_name)
case _:
- valid = self.user_id is None and self.task_id is None
+ valid = self.user_id is None and self.task_id is None and self.agent_name is None
if not valid:
raise ValueError(f"ArtefactAttribution kind {self.kind!r} does not match its id fields")
@@ -44,6 +46,10 @@ class ArtefactAttribution:
def from_task(cls, task_id: str) -> ArtefactAttribution:
return cls(kind="task", task_id=str(task_id))
+ @classmethod
+ def from_agent(cls, user_id: int, agent_name: str) -> ArtefactAttribution:
+ return cls(kind="agent", user_id=user_id, agent_name=agent_name)
+
@classmethod
def system(cls) -> ArtefactAttribution:
return cls(kind="system")
diff --git a/products/signals/backend/implementation_pr.py b/products/signals/backend/implementation_pr.py
index a77289babfab..8950a8850dff 100644
--- a/products/signals/backend/implementation_pr.py
+++ b/products/signals/backend/implementation_pr.py
@@ -1,16 +1,16 @@
"""Resolve implementation PR URLs linked to signal reports."""
-from dataclasses import dataclass
from typing import Literal, cast
from django.db.models import Q
import structlog
+from posthog.dataclasses import frozen
from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.integration import GitHubIntegration
-from products.signals.backend.models import SignalReport
+from products.signals.backend.models import SignalActorKind, SignalReport, SignalReportAssignment
from products.signals.backend.task_run_artefacts import (
NON_PR_BEARING_TASK_RUN_TYPES,
SIGNALS_PRODUCT,
@@ -20,85 +20,76 @@ from products.tasks.backend.facade import api as tasks_facade
logger = structlog.get_logger(__name__)
+# A report in one of these statuses is finished with its pull request. Anything else still holds
+# it open — a status this list doesn't know about keeps the PR, which is the safe direction.
+_FINISHED_REPORT_STATUSES = frozenset(
+ {SignalReport.Status.RESOLVED, SignalReport.Status.SUPPRESSED, SignalReport.Status.DELETED}
+)
+
-@dataclass(frozen=True)
+@frozen
class ImplementationPr:
- """The one implementation PR surfaced for a report, and whether the webhook saw it merge."""
+ """The implementation PR surfaced for a report and its latest known state."""
url: str
merged: bool
+ state: str = SignalReportAssignment.PrState.UNKNOWN
def fetch_implementation_pr_state_for_reports(report_ids: list[str]) -> dict[str, ImplementationPr]:
- """The implementation PR surfaced for each report, with its merge state, when one exists.
-
- The task↔report association comes from `SignalReport.associated_task_runs_for_reports` (the
- unified view of the `task_run` artefact log + legacy gate rows, batched over the whole page);
- the facade then resolves the latest PR-bearing run for each task, so multiple runs of a task
- collapse to the newest PR.
-
- Every code-shipping signals task associated with the report is a candidate, not just the `implementation`
- ones: a task started from the inbox's "Discuss" button runs the same agent against the same
- repo, so it can push a branch and open a PR too, and that PR is the report's PR as much as an
- auto-started one is. Implementation tasks are still consulted first, so a report that has both
- surfaces exactly what it surfaced before.
-
- Research, repo-selection, and scout runs are never candidates (`NON_PR_BEARING_TASK_RUN_TYPES`):
- they read other people's PRs while checking for in-flight work, and a PR URL recorded on one of
- them is a PR the agent saw, not one it opened. Surfacing it would label a stranger's PR as the
- report's, and `close_implementation_pr_for_report` would then close it on dismissal.
-
- A report can be associated with several tasks (retries, plus any discussion), but only one PR is
- surfaced — the first candidate that has one. The merge flag is read from *that* task, so the URL
- and its state always describe the same PR. Reading them independently would let a retry's merged
- PR vouch for a different PR's URL.
- """
+ """Return assignment PRs first, falling back to existing task-backed PRs."""
if not report_ids:
return {}
+ result = {
+ str(assignment.report_id): ImplementationPr(
+ url=assignment.pr_url,
+ merged=assignment.pr_merged,
+ state=assignment.pr_state or SignalReportAssignment.PrState.UNKNOWN,
+ )
+ for assignment in SignalReportAssignment.all_teams.filter(
+ report_id__in=report_ids,
+ pr_url__isnull=False,
+ ).exclude(pr_url="")
+ if assignment.pr_url is not None
+ }
+
+ missing_report_ids = [str(report_id) for report_id in report_ids if str(report_id) not in result]
+ if not missing_report_ids:
+ return result
- # (report_id, task_id) for each report's signals task(s); signals owns this mapping.
- # Batched across the whole page so association costs two queries, not two per report (N+1).
runs_by_report = SignalReport.associated_task_runs_for_reports(
- report_ids=[str(report_id) for report_id in report_ids],
+ report_ids=missing_report_ids,
product=SIGNALS_PRODUCT,
)
- pairs: list[tuple[str, str]] = [
+ pairs = [
(report_id, run.task_id)
for report_id, runs in runs_by_report.items()
- # Stable sort, so implementation tasks lead and each group keeps its oldest-first order.
for run in sorted(runs, key=lambda run: run.type != TASK_RUN_TYPE_IMPLEMENTATION)
if run.type not in NON_PR_BEARING_TASK_RUN_TYPES
]
- if not pairs:
- return {}
-
task_ids = [task_id for _, task_id in pairs]
pr_url_by_task = tasks_facade.get_latest_pr_url_by_task(task_ids)
merged_task_ids = tasks_facade.get_merged_pr_task_ids(task_ids)
-
- result: dict[str, ImplementationPr] = {}
for report_id, task_id in pairs:
pr_url = pr_url_by_task.get(task_id)
if pr_url and report_id not in result:
- result[report_id] = ImplementationPr(url=pr_url, merged=task_id in merged_task_ids)
+ merged = task_id in merged_task_ids
+ result[report_id] = ImplementationPr(
+ url=pr_url,
+ merged=merged,
+ state=SignalReportAssignment.PrState.MERGED if merged else SignalReportAssignment.PrState.UNKNOWN,
+ )
return result
def pr_bearing_task_run_filter() -> Q:
- """SQL counterpart of the `NON_PR_BEARING_TASK_RUN_TYPES` exclusion, as a `Q` on `tasks.TaskRun`.
-
- The run type lives in artefact JSON the SQL path deliberately doesn't cast, so this keys on the
- `state.ai_stage` stamp the pipeline writes at run creation, which carries the same names
- (`research`, `repo_selection`, `scout:<skill>`). Runs without a stamp pass, matching the Python
- path, where an unlabelled legacy association is a candidate.
- """
return Q(state__ai_stage__isnull=True) | (
~Q(state__ai_stage__in=sorted(NON_PR_BEARING_TASK_RUN_TYPES)) & ~Q(state__ai_stage__startswith="scout:")
)
def fetch_implementation_pr_urls_for_reports(report_ids: list[str]) -> dict[str, str]:
- """PR URL from the latest PR-bearing task run for each report, when available."""
+ """PR URL stored on each report assignment, when available."""
return {report_id: pr.url for report_id, pr in fetch_implementation_pr_state_for_reports(report_ids).items()}
@@ -126,7 +117,7 @@ def close_implementation_pr_for_report(
*,
reason: PrCloseReason = "suppressed",
) -> bool:
- """Best-effort: comment on and close the GitHub PR opened for this report's implementation task.
+ """Best-effort: comment on and close the GitHub PR attached to this report.
Called when a report is suppressed, snoozed, or resolved without its PR — the open PR shouldn't linger. Only acts on a PR
that is still open: an already-closed or merged PR is left untouched (no comment, no close), so
@@ -136,15 +127,57 @@ def close_implementation_pr_for_report(
must succeed regardless.
"""
try:
- pr_url = fetch_implementation_pr_urls_for_reports([str(report_id)]).get(str(report_id))
- if not pr_url:
+ assignment = SignalReportAssignment.all_teams.filter(
+ report_id=report_id,
+ report__team_id=team_id,
+ ).first()
+ if assignment is None or not assignment.pr_url:
+ return False
+ if assignment.actor_kind not in {SignalActorKind.TASK, SignalActorKind.SYSTEM}:
+ logger.info(
+ "close_implementation_pr_untrusted_actor",
+ report_id=str(report_id),
+ actor_kind=assignment.actor_kind,
+ )
return False
+ pr_url = assignment.pr_url
parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)
if parsed is None:
logger.warning("close_implementation_pr_unparseable_url", report_id=str(report_id), pr_url=pr_url)
return False
+ # Nothing serializes this call with a re-claim that swaps the pull request or with a merge
+ # webhook, and both write the same row. Scope every write back to the pull request this call
+ # read, so a result that arrives late lands on nothing instead of on its replacement.
+ assignment_for_pr = SignalReportAssignment.all_teams.filter(
+ report_id=report_id,
+ report__team_id=team_id,
+ repository=parsed.repository.lower(),
+ pr_number=parsed.number,
+ )
+
+ # One pull request can back several reports. Closing it for one dismissal would close the
+ # work the others still depend on, and the close webhook would then suppress them too, so
+ # only the last report still using it closes it.
+ still_used_elsewhere = (
+ SignalReportAssignment.all_teams.filter(
+ report__team_id=team_id,
+ repository=parsed.repository.lower(),
+ pr_number=parsed.number,
+ )
+ .exclude(report_id=report_id)
+ .exclude(report__status__in=_FINISHED_REPORT_STATUSES)
+ .exists()
+ )
+ if still_used_elsewhere:
+ logger.info(
+ "close_implementation_pr_still_used_by_another_report",
+ report_id=str(report_id),
+ pr_url=pr_url,
+ )
+ return False
+
github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)
if github is None:
logger.info(
@@ -166,6 +199,16 @@ def close_implementation_pr_for_report(
status_code=pr_status.get("status_code"),
)
return False
+ if pr_status.get("merged"):
+ assignment_for_pr.update(
+ pr_state=SignalReportAssignment.PrState.MERGED,
+ pr_merged=True,
+ )
+ elif pr_status.get("state") == "closed":
+ assignment_for_pr.update(
+ pr_state=SignalReportAssignment.PrState.CLOSED,
+ pr_merged=False,
+ )
if pr_status.get("state") != "open" or pr_status.get("merged"):
logger.info(
"close_implementation_pr_not_open",
@@ -176,7 +219,7 @@ def close_implementation_pr_for_report(
)
return False
- # Explain first, close second — a failed comment shouldn't stop the close.
+ # Explain first, close second. A failed comment should not stop the close.
comment_outcome = github.comment_on_pull_request(parsed.repository, parsed.number, _PR_CLOSE_COMMENTS[reason])
if not comment_outcome.get("success"):
logger.warning(
@@ -197,6 +240,13 @@ def close_implementation_pr_for_report(
status_code=outcome.get("status_code"),
)
return False
+ # Closing a merged pull request is a no-op that still reports success, so a merge that landed
+ # during the round trip must keep its state. A merge is terminal: no later webhook would
+ # correct a downgrade here.
+ assignment_for_pr.exclude(pr_state=SignalReportAssignment.PrState.MERGED).update(
+ pr_state=SignalReportAssignment.PrState.CLOSED,
+ pr_merged=False,
+ )
return True
except Exception:
logger.exception("close_implementation_pr_unexpected_error", report_id=str(report_id))
diff --git a/products/signals/backend/migrations/0115_signalreportartefact_actor_agent_and_more.py b/products/signals/backend/migrations/0115_signalreportartefact_actor_agent_and_more.py
new file mode 100644
index 000000000000..cbddbf96a0de
--- /dev/null
+++ b/products/signals/backend/migrations/0115_signalreportartefact_actor_agent_and_more.py
@@ -0,0 +1,142 @@
+# Generated by Django 5.2.17 on 2026-09-02 13:31
+
+import django.db.models.manager
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1333_uploaded_media_library_index"),
+ ("signals", "0114_signalscoutnote_reviewer_correction_origin"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalreportartefact",
+ name="actor_agent",
+ field=models.CharField(blank=True, max_length=200, null=True),
+ ),
+ migrations.AddField(
+ model_name="signalreportartefact",
+ name="actor_kind",
+ field=models.CharField(
+ blank=True,
+ choices=[
+ ("user", "User"),
+ ("task", "Task"),
+ ("agent", "Agent"),
+ ("system", "System"),
+ ],
+ max_length=10,
+ null=True,
+ ),
+ ),
+ migrations.CreateModel(
+ name="SignalReportAssignment",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "actor_kind",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("user", "User"),
+ ("task", "Task"),
+ ("agent", "Agent"),
+ ("system", "System"),
+ ],
+ max_length=10,
+ null=True,
+ ),
+ ),
+ ("actor_task_id", models.UUIDField(blank=True, null=True)),
+ (
+ "actor_agent",
+ models.CharField(blank=True, max_length=200, null=True),
+ ),
+ ("claimed_at", models.DateTimeField(blank=True, null=True)),
+ ("pr_url", models.TextField(blank=True, null=True)),
+ ("repository", models.CharField(blank=True, max_length=200, null=True)),
+ ("pr_number", models.PositiveBigIntegerField(blank=True, null=True)),
+ (
+ "pr_state",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("unknown", "Unknown"),
+ ("draft", "Draft"),
+ ("open", "Open"),
+ ("closed", "Closed"),
+ ("merged", "Merged"),
+ ],
+ max_length=10,
+ null=True,
+ ),
+ ),
+ ("pr_merged", models.BooleanField(db_default=False, default=False)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "actor_user",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "report",
+ models.OneToOneField(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="assignment",
+ to="signals.signalreport",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "default_manager_name": "all_teams",
+ "indexes": [
+ models.Index(
+ fields=["repository", "pr_number", "team"],
+ name="signals_assign_pr_identity",
+ ),
+ models.Index(
+ fields=["team", "actor_kind", "actor_user", "actor_agent"],
+ name="signals_assign_actor_idx",
+ ),
+ models.Index(
+ fields=["team", "actor_kind", "actor_task_id"],
+ name="signals_assign_task_idx",
+ ),
+ ],
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 34c4aa8d61fd..e394e73a3f34 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0114_signalscoutnote_reviewer_correction_origin
+0115_signalreportartefact_actor_agent_and_more
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 14b6551114de..89ea627e4c85 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -39,6 +39,20 @@ from products.signals.backend.enums import SignalSourceProduct, signal_source_pr
logger = logging.getLogger(__name__)
+class SignalActorKind(models.TextChoices):
+ USER = "user", "User"
+ TASK = "task", "Task"
+ AGENT = "agent", "Agent"
+ SYSTEM = "system", "System"
+
+
+class SignalReportWorkState(models.TextChoices):
+ UNCLAIMED = "unclaimed", "Unclaimed"
+ WORKING = "working", "Working"
+ IN_REVIEW = "in_review", "In review"
+ DONE = "done", "Done"
+
+
def signal_source_type_choices() -> list[tuple[str, str | Promise]]:
# Callable so growing the enum doesn't generate a no-op migration.
return list(SignalSourceConfig.SourceType.choices)
@@ -706,6 +720,7 @@ class SignalReport(UUIDModel):
task_id=task_id, run_id=None, product=product, type=run_type
).model_dump_json(),
created_at=report_task.created_at,
+ actor_kind=SignalActorKind.TASK,
task_id=report_task.task_id,
)
)
@@ -730,7 +745,16 @@ class SignalReport(UUIDModel):
report_id=report_ref, type=SignalReportArtefact.ArtefactType.TASK_RUN, task_id__isnull=False
).values("task_id")
legacy_task_ids = SignalReportTask.objects.filter(report_id=report_ref).values("task_id")
- return models.Q(task_id__in=artefact_task_ids) | models.Q(task_id__in=legacy_task_ids)
+ assignment_task_ids = SignalReportAssignment.all_teams.filter(
+ report_id=report_ref,
+ actor_kind=SignalActorKind.TASK,
+ actor_task_id__isnull=False,
+ ).values("actor_task_id")
+ return (
+ models.Q(task_id__in=artefact_task_ids)
+ | models.Q(task_id__in=legacy_task_ids)
+ | models.Q(task_id__in=assignment_task_ids)
+ )
@staticmethod
def reports_for_task_filter(task_id: Any) -> "models.Q":
@@ -746,7 +770,15 @@ class SignalReport(UUIDModel):
type=SignalReportArtefact.ArtefactType.TASK_RUN, task_id=task_id
).values("report_id")
legacy_report_ids = SignalReportTask.objects.filter(task_id=task_id).values("report_id")
- return models.Q(id__in=artefact_report_ids) | models.Q(id__in=legacy_report_ids)
+ assignment_report_ids = SignalReportAssignment.all_teams.filter(
+ actor_kind=SignalActorKind.TASK,
+ actor_task_id=task_id,
+ ).values("report_id")
+ return (
+ models.Q(id__in=artefact_report_ids)
+ | models.Q(id__in=legacy_report_ids)
+ | models.Q(id__in=assignment_report_ids)
+ )
@staticmethod
def reports_for_task_ids_filter(task_ids: Any, *, team_id: int | None = None) -> "models.Q":
@@ -768,10 +800,68 @@ class SignalReport(UUIDModel):
type=SignalReportArtefact.ArtefactType.TASK_RUN, task_id__in=task_ids
)
legacy_rows = SignalReportTask.objects.filter(task_id__in=task_ids)
+ assignment_rows = SignalReportAssignment.all_teams.filter(
+ actor_kind=SignalActorKind.TASK,
+ actor_task_id__in=task_ids,
+ )
if team_id is not None:
artefact_rows = artefact_rows.filter(team_id=team_id)
legacy_rows = legacy_rows.filter(team_id=team_id)
- return models.Q(id__in=artefact_rows.values("report_id")) | models.Q(id__in=legacy_rows.values("report_id"))
+ assignment_rows = assignment_rows.filter(team_id=team_id)
+ return (
+ models.Q(id__in=artefact_rows.values("report_id"))
+ | models.Q(id__in=legacy_rows.values("report_id"))
+ | models.Q(id__in=assignment_rows.values("report_id"))
+ )
+
+
+class SignalReportAssignment(TeamScopedRootMixin, UUIDModel):
+ class PrState(models.TextChoices):
+ UNKNOWN = "unknown", "Unknown"
+ DRAFT = "draft", "Draft"
+ OPEN = "open", "Open"
+ CLOSED = "closed", "Closed"
+ MERGED = "merged", "Merged"
+
+ all_teams = models.Manager() # noqa: DJ012
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
+ report = models.OneToOneField(SignalReport, on_delete=models.CASCADE, related_name="assignment")
+
+ actor_kind = models.CharField(max_length=10, choices=SignalActorKind, null=True, blank=True)
+ actor_user = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False, related_name="+"
+ )
+ actor_task_id = models.UUIDField(null=True, blank=True)
+ actor_agent = models.CharField(max_length=200, null=True, blank=True)
+ claimed_at = models.DateTimeField(null=True, blank=True)
+
+ pr_url = models.TextField(null=True, blank=True)
+ repository = models.CharField(max_length=200, null=True, blank=True)
+ pr_number = models.PositiveBigIntegerField(null=True, blank=True)
+ pr_state = models.CharField(max_length=10, choices=PrState, null=True, blank=True)
+ pr_merged = models.BooleanField(default=False, db_default=False)
+
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ default_manager_name = "all_teams"
+ indexes = [
+ models.Index(fields=["repository", "pr_number", "team"], name="signals_assign_pr_identity"),
+ models.Index(fields=["team", "actor_kind", "actor_user", "actor_agent"], name="signals_assign_actor_idx"),
+ models.Index(fields=["team", "actor_kind", "actor_task_id"], name="signals_assign_task_idx"),
+ ]
+
+ @property
+ def work_state(self) -> SignalReportWorkState:
+ if self.report.status == SignalReport.Status.RESOLVED:
+ return SignalReportWorkState.DONE
+ if self.pr_url and self.pr_state in {self.PrState.UNKNOWN, self.PrState.DRAFT, self.PrState.OPEN}:
+ return SignalReportWorkState.IN_REVIEW
+ if self.actor_kind:
+ return SignalReportWorkState.WORKING
+ return SignalReportWorkState.UNCLAIMED
class SignalEmissionRecord(UUIDModel):
@@ -874,6 +964,8 @@ class SignalReportArtefact(UUIDModel):
# because legacy rows (and explicit system writes) legitimately carry NULLs in both.
# SET_NULL: deleting a user/task degrades attribution to "system/unknown" rather than
# destroying the report's work log.
+ actor_kind = models.CharField(max_length=10, choices=SignalActorKind, null=True, blank=True)
+ actor_agent = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
task = models.ForeignKey("tasks.Task", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
channel = models.ForeignKey(
@@ -923,6 +1015,8 @@ class SignalReportArtefact(UUIDModel):
report_id=report_id,
type=artefact_type_for(content),
content=content.model_dump_json(),
+ actor_kind=attribution.kind,
+ actor_agent=attribution.agent_name,
created_by_id=attribution.user_id,
task_id=attribution.task_id,
channel_id=content.channel_id if isinstance(content, ChannelAssignment) else None,
diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.py
index 8beb12dbef58..9eb00ca9adf0 100644
--- a/products/signals/backend/receivers.py
+++ b/products/signals/backend/receivers.py
@@ -21,6 +21,7 @@ from posthog.event_usage import groups
from products.signals.backend.implementation_pr import PrCloseReason
from products.signals.backend.models import SignalReport, SignalReportArtefact
+from products.signals.backend.report_assignments import sync_task_pull_request_to_assignments
from products.signals.backend.report_embeddings import (
emit_report_embedding,
emit_report_tombstone,
@@ -28,6 +29,7 @@ from products.signals.backend.report_embeddings import (
)
from products.signals.backend.scout_harness.suggestions import mark_stale_if_fleet_changed
from products.signals.backend.tasks import close_dismissed_report_pr
+from products.tasks.backend.facade.task_run_signals import connect_task_run_post_save
logger = structlog.get_logger(__name__)
@@ -38,6 +40,37 @@ _SNOOZE_SOURCE_STATUSES = frozenset({SignalReport.Status.READY, SignalReport.Sta
_DOCUMENT_FIELDS = frozenset({"title", "summary"})
+def connect_task_run_assignment_sync() -> None:
+ connect_task_run_post_save(
+ sync_task_run_pr_to_assignments,
+ dispatch_uid="signals_sync_task_run_pr_to_assignments",
+ )
+
+
+def sync_task_run_pr_to_assignments(sender: type, instance: Any, created: bool, **kwargs: Any) -> None:
+ """Copy a PR reported by a PR-bearing task run onto its signal report assignments."""
+ try:
+ update_fields = kwargs.get("update_fields")
+ if update_fields is not None and "output" not in update_fields:
+ return
+ output = instance.output if isinstance(instance.output, dict) else {}
+ pr_url = output.get("pr_url")
+ if not isinstance(pr_url, str) or not pr_url:
+ return
+ ai_stage = (instance.state or {}).get("ai_stage")
+ if ai_stage in {"research", "repo_selection"} or (isinstance(ai_stage, str) and ai_stage.startswith("scout:")):
+ return
+ sync_task_pull_request_to_assignments(
+ team_id=instance.team_id,
+ task_id=str(instance.task_id),
+ pr_url=pr_url,
+ pr_state=output.get("pr_state") if isinstance(output.get("pr_state"), str) else None,
+ pr_merged=output.get("pr_merged") is True,
+ )
+ except Exception:
+ logger.exception("signals.task_run_pr_assignment_sync_failed", task_run_id=str(instance.id))
+
+
def _schedule_tombstone(*, team_id: int, report_id: str, created_at: datetime, reason: str) -> None:
"""Retract the report's vector after the current transaction commits.
@@ -159,6 +192,9 @@ def _pr_close_reason(
return None
if prior_status is None or prior_status == instance.status:
return None
+ # The pull request's own observed state drove this transition, so there is nothing left to close.
+ if getattr(instance, "_status_from_pr_state", False):
+ return None
if instance.status == SignalReport.Status.SUPPRESSED:
return "suppressed"
diff --git a/products/signals/backend/report_assignments.py b/products/signals/backend/report_assignments.py
new file mode 100644
index 000000000000..37c78f93d962
--- /dev/null
+++ b/products/signals/backend/report_assignments.py
@@ -0,0 +1,434 @@
+"""Claim and pull request lifecycle for signal reports."""
+
+from __future__ import annotations
+
+from typing import TypedDict
+
+from django.db import transaction
+from django.utils import timezone
+
+import structlog
+
+from posthog.dataclasses import frozen
+from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
+from posthog.models.github_integration_base import GitHubIntegrationBase
+from posthog.models.integration import GitHubIntegration
+from posthog.models.user import User
+
+from products.signals.backend.artefact_attribution import ArtefactAttribution
+from products.signals.backend.models import InvalidStatusTransition, SignalReport, SignalReportAssignment
+
+logger = structlog.get_logger(__name__)
+
+# The parser accepts any integer and any owner/repo length, but the columns are a positive bigint
+# and a bounded varchar — so a hand-crafted URL only fails once the row reaches Postgres.
+MAX_PR_NUMBER = 2**63 - 1
+MAX_REPOSITORY_LENGTH = SignalReportAssignment._meta.get_field("repository").max_length or 200
+
+CLAIMABLE_REPORT_STATUSES = frozenset(
+ {
+ SignalReport.Status.READY,
+ SignalReport.Status.PENDING_INPUT,
+ SignalReport.Status.POTENTIAL,
+ SignalReport.Status.CANDIDATE,
+ SignalReport.Status.IN_PROGRESS,
+ SignalReport.Status.FAILED,
+ }
+)
+
+
+class ReportClaimConflict(Exception):
+ pass
+
+
+class InvalidPullRequestUrl(Exception):
+ pass
+
+
+class AssigneeSnapshot(TypedDict):
+ kind: str
+ user_id: int | None
+ task_id: str | None
+ agent: str | None
+ claimed_at: str | None
+
+
+class PullRequestSnapshot(TypedDict):
+ url: str
+ repository: str | None
+ number: int | None
+ state: str | None
+ merged: bool
+
+
+class AssignmentSnapshot(TypedDict):
+ assignee: AssigneeSnapshot | None
+ implementation_pr: PullRequestSnapshot | None
+
+
+@frozen
+class PullRequestDetails:
+ url: str
+ repository: str
+ number: int
+ state: str
+ merged: bool
+
+
+def assignment_snapshot(assignment: SignalReportAssignment | None) -> AssignmentSnapshot:
+ if assignment is None:
+ return {"assignee": None, "implementation_pr": None}
+ assignee: AssigneeSnapshot | None = None
+ if assignment.actor_kind:
+ assignee = {
+ "kind": assignment.actor_kind,
+ "user_id": assignment.actor_user_id,
+ "task_id": str(assignment.actor_task_id) if assignment.actor_task_id else None,
+ "agent": assignment.actor_agent,
+ "claimed_at": assignment.claimed_at.isoformat() if assignment.claimed_at else None,
+ }
+ implementation_pr: PullRequestSnapshot | None = None
+ if assignment.pr_url:
+ implementation_pr = {
+ "url": assignment.pr_url,
+ "repository": assignment.repository,
+ "number": assignment.pr_number,
+ "state": assignment.pr_state,
+ "merged": assignment.pr_merged,
+ }
+ return {"assignee": assignee, "implementation_pr": implementation_pr}
+
+
+def actor_owns_assignment(assignment: SignalReportAssignment, actor: ArtefactAttribution) -> bool:
+ if assignment.actor_kind != actor.kind:
+ return False
+ if actor.kind == "user":
+ return assignment.actor_user_id == actor.user_id
+ if actor.kind == "task":
+ return str(assignment.actor_task_id) == actor.task_id
+ if actor.kind == "agent":
+ return assignment.actor_user_id == actor.user_id and assignment.actor_agent == actor.agent_name
+ return actor.kind == "system"
+
+
+def _set_actor(assignment: SignalReportAssignment, actor: ArtefactAttribution) -> None:
+ assignment.actor_kind = actor.kind
+ assignment.actor_user_id = actor.user_id
+ assignment.actor_task_id = actor.task_id
+ assignment.actor_agent = actor.agent_name
+ assignment.claimed_at = timezone.now()
+
+
+def _clear_actor(assignment: SignalReportAssignment) -> None:
+ assignment.actor_kind = None
+ assignment.actor_user_id = None
+ assignment.actor_task_id = None
+ assignment.actor_agent = None
+ assignment.claimed_at = None
+
+
+def claim_report_for_task(*, team_id: int, report_id: str, task_id: str) -> SignalReportAssignment:
+ """Record an internal task as the current owner without going through the public claim API."""
+ with transaction.atomic():
+ report = SignalReport.objects.select_for_update().get(id=report_id, team_id=team_id)
+ assignment = SignalReportAssignment.all_teams.select_for_update().filter(report_id=report.id).first()
+ if assignment is None:
+ assignment = SignalReportAssignment(team_id=team_id, report_id=report.id)
+ _set_actor(assignment, ArtefactAttribution.from_task(task_id))
+ assignment.save()
+ return assignment
+
+
+def _pull_request_details(team_id: int, pr_url: str) -> PullRequestDetails:
+ parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)
+ if parsed is None:
+ raise InvalidPullRequestUrl("pr_url must be a GitHub pull request URL.")
+ if not 0 < parsed.number <= MAX_PR_NUMBER:
+ raise InvalidPullRequestUrl("pr_url must end in a positive pull request number.")
+ repository = parsed.repository.lower()
+ if len(repository) > MAX_REPOSITORY_LENGTH:
+ raise InvalidPullRequestUrl("pr_url repository name is too long.")
+
+ details = PullRequestDetails(
+ url=pr_url,
+ repository=repository,
+ number=parsed.number,
+ state=SignalReportAssignment.PrState.UNKNOWN,
+ merged=False,
+ )
+ try:
+ github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)
+ except Exception:
+ logger.exception(
+ "signals.assignment.integration_lookup_failed",
+ team_id=team_id,
+ repository=parsed.repository,
+ )
+ return details
+ if github is None:
+ return details
+
+ try:
+ status = github.get_pull_request(parsed.repository, parsed.number)
+ except Exception:
+ logger.exception(
+ "signals.assignment.pr_fetch_failed",
+ team_id=team_id,
+ repository=parsed.repository,
+ pr_number=parsed.number,
+ )
+ return details
+ if not status.get("success"):
+ logger.warning(
+ "signals.assignment.pr_fetch_failed",
+ team_id=team_id,
+ repository=parsed.repository,
+ pr_number=parsed.number,
+ error=status.get("error"),
+ )
+ return details
+
+ merged = bool(status.get("merged"))
+ if merged:
+ pr_state = SignalReportAssignment.PrState.MERGED
+ elif status.get("state") == "closed":
+ pr_state = SignalReportAssignment.PrState.CLOSED
+ elif status.get("draft"):
+ pr_state = SignalReportAssignment.PrState.DRAFT
+ elif status.get("state") == "open":
+ pr_state = SignalReportAssignment.PrState.OPEN
+ else:
+ pr_state = SignalReportAssignment.PrState.UNKNOWN
+ return PullRequestDetails(
+ url=status.get("url") or pr_url,
+ repository=details.repository,
+ number=details.number,
+ state=pr_state,
+ merged=merged,
+ )
+
+
+def sync_task_pull_request_to_assignments(
+ *,
+ team_id: int,
+ task_id: str,
+ pr_url: str,
+ pr_state: str | None = None,
+ pr_merged: bool = False,
+) -> int:
+ """Copy a task-run PR onto reports still owned by that task, or without an explicit PR."""
+ parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)
+ if parsed is None or not 0 < parsed.number <= MAX_PR_NUMBER:
+ return 0
+ repository = parsed.repository.lower()
+ if len(repository) > MAX_REPOSITORY_LENGTH:
+ return 0
+
+ state = pr_state if pr_state in SignalReportAssignment.PrState.values else SignalReportAssignment.PrState.UNKNOWN
+ merged = pr_merged or state == SignalReportAssignment.PrState.MERGED
+ if merged:
+ state = SignalReportAssignment.PrState.MERGED
+
+ report_ids = list(
+ SignalReport.objects.filter(team_id=team_id)
+ .filter(SignalReport.reports_for_task_filter(task_id))
+ .values_list("id", flat=True)
+ )
+ if not report_ids:
+ return 0
+
+ updated = 0
+ with transaction.atomic():
+ reports = {
+ report.id: report
+ for report in SignalReport.objects.select_for_update().filter(team_id=team_id, id__in=report_ids)
+ }
+ assignments = {
+ assignment.report_id: assignment
+ for assignment in SignalReportAssignment.all_teams.select_for_update().filter(
+ team_id=team_id,
+ report_id__in=report_ids,
+ )
+ }
+ for report_id, report in reports.items():
+ assignment = assignments.get(report_id)
+ assignment_state = state
+ assignment_merged = merged
+ actor_changed = False
+ if assignment is None:
+ assignment = SignalReportAssignment(team_id=team_id, report_id=report_id)
+ _set_actor(assignment, ArtefactAttribution.from_task(task_id))
+ actor_changed = True
+ elif assignment.pr_url and not (
+ assignment.actor_kind == "task" and str(assignment.actor_task_id) == str(task_id)
+ ):
+ continue
+ elif assignment.actor_kind is None:
+ _set_actor(assignment, ArtefactAttribution.from_task(task_id))
+ actor_changed = True
+
+ if assignment.pr_url == pr_url and pr_state is None and not pr_merged:
+ assignment_state = assignment.pr_state or SignalReportAssignment.PrState.UNKNOWN
+ assignment_merged = assignment.pr_merged
+
+ changed = (
+ assignment.pr_url != pr_url
+ or assignment.repository != repository
+ or assignment.pr_number != parsed.number
+ or assignment.pr_state != assignment_state
+ or assignment.pr_merged != assignment_merged
+ or actor_changed
+ or assignment._state.adding
+ )
+ if not changed:
+ continue
+
+ assignment.pr_url = pr_url
+ assignment.repository = repository
+ assignment.pr_number = parsed.number
+ assignment.pr_state = assignment_state
+ assignment.pr_merged = assignment_merged
+ assignment.save()
+ _apply_pr_report_state(report, assignment_state)
+ updated += 1
+ return updated
+
+
+def _apply_pr_report_state(report: SignalReport, pr_state: str | None) -> None:
+ target = None
+ if pr_state == SignalReportAssignment.PrState.MERGED:
+ target = SignalReport.Status.RESOLVED
+ elif pr_state == SignalReportAssignment.PrState.CLOSED:
+ target = SignalReport.Status.SUPPRESSED
+ if target is None or report.status == target:
+ return
+ # Resolving a report closes its own pull request, and GitHub reports that close as an unmerged
+ # close. Suppressing on it would undo the resolution moments after the person made it.
+ if target == SignalReport.Status.SUPPRESSED and report.status == SignalReport.Status.RESOLVED:
+ return
+ try:
+ updated_fields = report.transition_to(target)
+ except (InvalidStatusTransition, ValueError, TypeError):
+ logger.info(
+ "signals.assignment.pr_state_transition_skipped",
+ report_id=str(report.id),
+ report_status=report.status,
+ pr_state=pr_state,
+ )
+ return
+ # GitHub already reports this pull request as closed or merged. Without this marker the
+ # dismissal receiver queues a redundant close for every report that shares the pull request.
+ report._status_from_pr_state = True # type: ignore[attr-defined]
+ report.save(update_fields=updated_fields)
+
+
+def claim_report(
+ *,
+ report: SignalReport,
+ actor: ArtefactAttribution,
+ user: User,
+ was_impersonated: bool,
+ pr_url: str | None,
+ release: bool,
+) -> SignalReportAssignment | None:
+ """Claim, release, or attach a PR to one report and return the current assignment."""
+ if not release and report.status not in CLAIMABLE_REPORT_STATUSES:
+ raise ReportClaimConflict(f"Reports with status '{report.status}' cannot be claimed.")
+ pr_details = _pull_request_details(report.team_id, pr_url) if pr_url is not None else None
+
+ with transaction.atomic():
+ locked_report = SignalReport.objects.select_for_update().get(id=report.id, team_id=report.team_id)
+ assignment = SignalReportAssignment.all_teams.select_for_update().filter(report_id=locked_report.id).first()
+ before = assignment_snapshot(assignment)
+
+ if release:
+ if assignment is None:
+ return None
+ if assignment.actor_kind and not actor_owns_assignment(assignment, actor):
+ raise ReportClaimConflict("Only the current assignee can release this report.")
+ _clear_actor(assignment)
+ else:
+ if locked_report.status not in CLAIMABLE_REPORT_STATUSES:
+ raise ReportClaimConflict(f"Reports with status '{locked_report.status}' cannot be claimed.")
+ if assignment is None:
+ assignment = SignalReportAssignment(
+ team_id=locked_report.team_id,
+ report_id=locked_report.id,
+ )
+ if not actor_owns_assignment(assignment, actor):
+ _set_actor(assignment, actor)
+ if pr_details is not None:
+ assignment.pr_url = pr_details.url
+ assignment.repository = pr_details.repository
+ assignment.pr_number = pr_details.number
+ assignment.pr_state = pr_details.state
+ assignment.pr_merged = pr_details.merged
+
+ after = assignment_snapshot(assignment)
+ if before == after:
+ return assignment
+
+ assignment.save()
+ _apply_pr_report_state(locked_report, assignment.pr_state)
+ changes: list[Change] = []
+ if before["assignee"] != after["assignee"]:
+ changes.append(
+ Change(
+ type="SignalReport",
+ action="changed",
+ field="assignee",
+ before=before["assignee"],
+ after=after["assignee"],
+ )
+ )
+ if before["implementation_pr"] != after["implementation_pr"]:
+ changes.append(
+ Change(
+ type="SignalReport",
+ action="changed",
+ field="implementation_pr",
+ before=before["implementation_pr"],
+ after=after["implementation_pr"],
+ )
+ )
+ log_activity(
+ organization_id=None,
+ team_id=locked_report.team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=locked_report.id,
+ scope="SignalReport",
+ activity="assignment_changed",
+ detail=Detail(name=locked_report.title, changes=changes),
+ )
+ return assignment
+
+
+def update_assignments_for_pull_request(
+ *,
+ team_ids: list[int],
+ repository: str,
+ pr_number: int,
+ pr_state: str,
+) -> int:
+ """Apply a scoped GitHub webhook state to every report linked to the PR."""
+ if not team_ids:
+ return 0
+ normalized_repository = repository.lower()
+ updated = 0
+ with transaction.atomic():
+ assignments = list(
+ SignalReportAssignment.all_teams.select_for_update()
+ .select_related("report")
+ .filter(report__team_id__in=team_ids, repository=normalized_repository, pr_number=pr_number)
+ )
+ for assignment in assignments:
+ merged = pr_state == SignalReportAssignment.PrState.MERGED
+ changed = assignment.pr_state != pr_state or assignment.pr_merged != merged
+ assignment.pr_state = pr_state
+ assignment.pr_merged = merged
+ if changed:
+ assignment.save(update_fields=["pr_state", "pr_merged", "updated_at"])
+ _apply_pr_report_state(assignment.report, pr_state)
+ updated += 1
+ return updated
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 97187e78f09c..1bca7b208220 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -21,9 +21,12 @@ from .artefact_schemas import NON_WRITABLE_ARTEFACT_TYPES
from .daily_limit import reports_generated_today, team_day_start
from .models import (
AutonomyPriority,
+ SignalActorKind,
SignalReport,
SignalReportArtefact,
+ SignalReportAssignment,
SignalReportRefund,
+ SignalReportWorkState,
SignalSourceConfig,
SignalTeamConfig,
SignalUserAutonomyConfig,
@@ -300,6 +303,31 @@ class _UserSerializer(serializers.ModelSerializer):
read_only_fields = fields
+class SignalReportClaimSerializer(serializers.Serializer):
+ pr_url = serializers.URLField(
+ required=False,
+ help_text=("Optional GitHub pull request to attach to the claim. The report may be claimed without one."),
+ )
+ release = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text="Release ownership while preserving any attached pull request.",
+ )
+
+ def validate(self, attrs: dict) -> dict:
+ if attrs.get("release") and "pr_url" in attrs:
+ raise serializers.ValidationError("release and pr_url cannot be supplied together.")
+ return attrs
+
+
+class SignalReportAssigneeSerializer(serializers.Serializer):
+ kind = serializers.ChoiceField(choices=SignalActorKind.choices)
+ user = _UserSerializer(allow_null=True)
+ task_id = serializers.UUIDField(allow_null=True)
+ agent = serializers.CharField(allow_null=True)
+ claimed_at = serializers.DateTimeField(allow_null=True)
+
+
class SignalUserAutonomyConfigSerializer(serializers.ModelSerializer):
user = _UserSerializer(read_only=True)
slack_notification_integration_id = serializers.IntegerField(
@@ -531,7 +559,10 @@ class SignalReportSerializer(serializers.ModelSerializer):
help_text="skill_name slug of the scout that authored this report, when scout-authored (from ClickHouse); null otherwise.",
)
implementation_pr_url = serializers.SerializerMethodField(
- help_text="PR URL from the latest implementation task run, if available.",
+ help_text="Pull request attached to this report's claim, if available.",
+ )
+ implementation_pr_state = serializers.SerializerMethodField(
+ help_text="Latest known pull request state: unknown, draft, open, closed, or merged.",
)
implementation_pr_merged = serializers.SerializerMethodField(
help_text=(
@@ -540,6 +571,12 @@ class SignalReportSerializer(serializers.ModelSerializer):
"resolved directly, without a merged PR."
),
)
+ work_state = serializers.SerializerMethodField(
+ help_text="Derived remediation state: unclaimed, working, in_review, or done.",
+ )
+ assignee = serializers.SerializerMethodField(
+ help_text="Current user, internal task, or external agent claim owner. Null when unclaimed.",
+ )
refund = serializers.SerializerMethodField(
help_text="The report's PR refund, when one exists. One refund per report, ever.",
)
@@ -576,7 +613,10 @@ class SignalReportSerializer(serializers.ModelSerializer):
"source_products",
"scout_name",
"implementation_pr_url",
+ "implementation_pr_state",
"implementation_pr_merged",
+ "work_state",
+ "assignee",
"refund",
"refund_ineligibility_reason",
"billing_exempt_reason",
@@ -688,19 +728,77 @@ class SignalReportSerializer(serializers.ModelSerializer):
return None
def get_implementation_pr_url(self, obj: SignalReport) -> str | None:
+ assignment = self._get_assignment(obj)
+ if assignment is not None and assignment.pr_url:
+ return assignment.pr_url
implementation_pr_url_map: dict[str, str] | None = self.context.get("implementation_pr_url_map")
- if implementation_pr_url_map is not None:
- return implementation_pr_url_map.get(str(obj.id))
- value = getattr(obj, "implementation_pr_url", None)
- return value if isinstance(value, str) else None
+ return implementation_pr_url_map.get(str(obj.id)) if implementation_pr_url_map is not None else None
+
+ @extend_schema_field(serializers.ChoiceField(choices=SignalReportAssignment.PrState.choices, allow_null=True))
+ def get_implementation_pr_state(self, obj: SignalReport) -> str | None:
+ assignment = self._get_assignment(obj)
+ if assignment is not None and assignment.pr_url:
+ return assignment.pr_state or SignalReportAssignment.PrState.UNKNOWN
+ implementation_pr_state_map: dict[str, str] | None = self.context.get("implementation_pr_state_map")
+ return implementation_pr_state_map.get(str(obj.id)) if implementation_pr_state_map is not None else None
def get_implementation_pr_merged(self, obj: SignalReport) -> bool:
+ assignment = self._get_assignment(obj)
+ if assignment is not None and assignment.pr_url:
+ return assignment.pr_merged
merged_report_ids: set[str] | None = self.context.get("implementation_pr_merged_ids")
- if merged_report_ids is not None:
- return str(obj.id) in merged_report_ids
- # Annotated path: the JSON flag arrives as text, and NULL means no PR-bearing run at all.
- value = getattr(obj, "implementation_pr_merged", None)
- return value in (True, "true", "True")
+ return str(obj.id) in merged_report_ids if merged_report_ids is not None else False
+
+ @extend_schema_field(serializers.ChoiceField(choices=SignalReportWorkState.choices))
+ def get_work_state(self, obj: SignalReport) -> str:
+ if obj.status == SignalReport.Status.RESOLVED:
+ return "done"
+ assignment = self._get_assignment(obj)
+ if (
+ assignment is not None
+ and assignment.pr_url
+ and assignment.pr_state
+ in {
+ SignalReportAssignment.PrState.UNKNOWN,
+ SignalReportAssignment.PrState.DRAFT,
+ SignalReportAssignment.PrState.OPEN,
+ }
+ ):
+ return "in_review"
+ fallback_url_map: dict[str, str] | None = self.context.get("implementation_pr_url_map")
+ fallback_state_map: dict[str, str] | None = self.context.get("implementation_pr_state_map")
+ report_id = str(obj.id)
+ if (
+ fallback_url_map
+ and fallback_url_map.get(report_id)
+ and (fallback_state_map or {}).get(report_id)
+ in {
+ SignalReportAssignment.PrState.UNKNOWN,
+ SignalReportAssignment.PrState.DRAFT,
+ SignalReportAssignment.PrState.OPEN,
+ }
+ ):
+ return "in_review"
+ if assignment is not None and assignment.actor_kind:
+ return "working"
+ return "unclaimed"
+
+ @extend_schema_field(SignalReportAssigneeSerializer(allow_null=True))
+ def get_assignee(self, obj: SignalReport) -> dict | None:
+ assignment = self._get_assignment(obj)
+ if assignment is None or not assignment.actor_kind:
+ return None
+ return {
+ "kind": assignment.actor_kind,
+ "user": _UserSerializer(assignment.actor_user).data if assignment.actor_user else None,
+ "task_id": str(assignment.actor_task_id) if assignment.actor_task_id else None,
+ "agent": assignment.actor_agent,
+ "claimed_at": assignment.claimed_at,
+ }
+
+ @staticmethod
+ def _get_assignment(obj: SignalReport) -> SignalReportAssignment | None:
+ return getattr(obj, "assignment", None)
@extend_schema_field(SignalReportRefundSerializer(allow_null=True))
def get_refund(self, obj: SignalReport) -> dict | None:
@@ -842,19 +940,43 @@ class SignalReportArtefactSerializer(serializers.ModelSerializer):
created_by = _UserSerializer(
read_only=True,
allow_null=True,
- help_text="User the artefact is attributed to, when a user produced it. Null for task/system writes.",
+ help_text=(
+ "Authenticated user principal for user or external agent writes. Null for internal task and system writes."
+ ),
)
task_id = serializers.UUIDField(
read_only=True,
allow_null=True,
- help_text="Task the artefact is attributed to, when an agent produced it. Null for user/system writes.",
+ help_text="Internal task the artefact is attributed to. Null for user, external agent, and system writes.",
+ )
+ actor_kind = serializers.SerializerMethodField(
+ help_text="Actor kind. Legacy rows without attribution are returned as system.",
+ )
+ actor_agent = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text="MCP client name when an external agent produced the artefact.",
)
class Meta:
model = SignalReportArtefact
- fields = ["id", "type", "content", "created_at", "updated_at", "created_by", "task_id"]
+ fields = [
+ "id",
+ "type",
+ "content",
+ "created_at",
+ "updated_at",
+ "actor_kind",
+ "actor_agent",
+ "created_by",
+ "task_id",
+ ]
read_only_fields = fields
+ @extend_schema_field(serializers.ChoiceField(choices=SignalActorKind.choices))
+ def get_actor_kind(self, obj: SignalReportArtefact) -> str:
+ return obj.actor_kind or SignalActorKind.SYSTEM
+
def get_content(self, obj: SignalReportArtefact) -> dict | list:
try:
parsed = json.loads(obj.content)
diff --git a/products/signals/backend/task_attribution.py b/products/signals/backend/task_attribution.py
index 941ea9f803f7..76f40e189bc9 100644
--- a/products/signals/backend/task_attribution.py
+++ b/products/signals/backend/task_attribution.py
@@ -1,13 +1,16 @@
-"""Task attribution for signals API writes, derived from the `X-PostHog-Task-Id` header.
+"""Actor attribution for signals API writes.
Sandbox agents authenticate with an OAuth token issued on behalf of the task's creator, so
`request.user` alone would mis-attribute agent writes to that human. The sandbox provisioning
-bakes the agent's task id into an `X-PostHog-Task-Id` header on its MCP config (and the
-agent-server's direct API calls), and the MCP server forwards it — the LLM never handles its own
-task id, so attribution is deterministic.
+bakes the agent's task id into an `X-PostHog-Task-Id` header on its MCP config and direct API
+calls. The MCP server forwards it, so the LLM never handles its own task id and attribution is
+deterministic.
-Trust model: the header is caller-supplied attribution metadata, not an authorization boundary —
-the bearer token is already team-scoped, and the named task must belong to the same team, so a
+External MCP agents do not have an internal task. The MCP server forwards their effective client
+name, which is stored together with the authenticated user principal.
+
+Trust model: the header is caller-supplied attribution metadata, not an authorization boundary.
+The bearer token is already team-scoped, and the named task must belong to the same team, so a
caller can only attribute writes to tasks it could already see.
"""
@@ -22,12 +25,15 @@ from products.signals.backend.models import ArtefactAttribution
from products.tasks.backend.facade import api as tasks_api
TASK_ID_HEADER = "X-PostHog-Task-Id"
+MCP_CLIENT_NAME_HEADER = "X-Posthog-Mcp-Client-Name"
+MCP_CLIENT_HEADER = "X-PostHog-Client"
+MAX_AGENT_NAME_LENGTH = 200
def resolve_task_id_from_header(request: Request, team_id: int) -> str | None:
"""Return the validated task id from `X-PostHog-Task-Id`, or None when the header is absent.
- Raises a DRF `ValidationError` (→ 400) when the header value is not a UUID, or names a task
+ Raises a DRF `ValidationError` with a 400 response when the header value is not a UUID, or names a task
that doesn't exist on this team.
"""
raw = request.headers.get(TASK_ID_HEADER)
@@ -43,11 +49,23 @@ def resolve_task_id_from_header(request: Request, team_id: int) -> str | None:
def resolve_request_attribution(request: Request, team_id: int) -> ArtefactAttribution:
- """Attribution for an API write: the header task when present, else the requesting user."""
+ """Resolve the internal task, external MCP agent, or requesting user for an API write."""
task_id = resolve_task_id_from_header(request, team_id)
if task_id is not None:
return ArtefactAttribution.from_task(task_id)
user_id = request.user.id
if user_id is None: # unreachable behind authentication, but keeps attribution honest
raise ValidationError("Cannot attribute a write to an anonymous user.")
+ agent_name = resolve_external_agent_name(request)
+ if agent_name is not None:
+ return ArtefactAttribution.from_agent(user_id, agent_name)
return ArtefactAttribution.from_user(user_id)
+
+
+def resolve_external_agent_name(request: Request) -> str | None:
+ """Return the MCP client identity forwarded by the gateway, when this is an MCP request."""
+ raw = request.headers.get(MCP_CLIENT_NAME_HEADER)
+ if not raw and request.headers.get(MCP_CLIENT_HEADER, "").strip().lower() == "mcp":
+ raw = "mcp"
+ value = raw.strip() if raw else ""
+ return value[:MAX_AGENT_NAME_LENGTH] or None
diff --git a/products/signals/backend/task_run_artefacts.py b/products/signals/backend/task_run_artefacts.py
index 79f40e3fb9b9..043b360850dd 100644
--- a/products/signals/backend/task_run_artefacts.py
+++ b/products/signals/backend/task_run_artefacts.py
@@ -31,6 +31,7 @@ from products.signals.backend.artefact_schemas import (
)
from products.signals.backend.billing import first_billable_pr_run_at, mark_report_billing_exempt
from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact, SignalReportTask
+from products.signals.backend.report_assignments import claim_report_for_task
# The task-run vocabulary lives in `artefact_schemas` (a leaf module the model layer can import
# without a cycle); re-exported here so existing `from task_run_artefacts import …` callers keep
@@ -134,12 +135,14 @@ async def aappend_task_run_artefact(
different connection and not see the caller's uncommitted rows); content validation and
task attribution match `append_task_run_artefact`.
"""
+ attribution = ArtefactAttribution.from_task(task_id)
return await SignalReportArtefact.objects.acreate(
team_id=team_id,
report_id=str(report_id),
type=SignalReportArtefact.ArtefactType.TASK_RUN,
content=_task_run_content(product, type, task_id, run_id).model_dump_json(),
- task_id=str(task_id),
+ actor_kind=attribution.kind,
+ task_id=attribution.task_id,
)
@@ -316,7 +319,7 @@ def record_implementation_task(
task_id=task_id,
defaults={"relationship": TASK_RUN_TYPE_IMPLEMENTATION},
)
- return append_task_run_artefact(
+ artefact = append_task_run_artefact(
team_id=team_id,
report_id=report_id,
product=SIGNALS_PRODUCT,
@@ -324,6 +327,8 @@ def record_implementation_task(
task_id=task_id,
run_id=run_id,
)
+ claim_report_for_task(team_id=team_id, report_id=report_id, task_id=task_id)
+ return artefact
def record_report_task(
diff --git a/products/signals/backend/test/test_dismissal_pr_close.py b/products/signals/backend/test/test_dismissal_pr_close.py
index ab989d6a93f9..11c4c0554275 100644
--- a/products/signals/backend/test/test_dismissal_pr_close.py
+++ b/products/signals/backend/test/test_dismissal_pr_close.py
@@ -1,10 +1,15 @@
+import uuid
+
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from parameterized import parameterized
+from posthog.models.team.team import Team
+
from products.signals.backend.implementation_pr import PrCloseReason, close_implementation_pr_for_report
-from products.signals.backend.models import SignalReport
+from products.signals.backend.models import SignalActorKind, SignalReport, SignalReportAssignment
+from products.signals.backend.report_assignments import update_assignments_for_pull_request
from products.signals.backend.tasks import close_dismissed_report_pr
_PR_URL = "https://github.com/PostHog/posthog/pull/123"
@@ -99,6 +104,32 @@ class TestClosePrWhenReportDismissed(BaseTest):
self._save_transition(report, SignalReport.Status.RESOLVED)
mock_task.delay.assert_not_called()
+ def test_pr_closed_webhook_does_not_enqueue_for_any_linked_report(self):
+ reports = [self._create_report(), self._create_report()]
+ for report in reports:
+ SignalReportAssignment.all_teams.create(
+ team=self.team,
+ report=report,
+ pr_url=_PR_URL,
+ repository="posthog/posthog",
+ pr_number=123,
+ pr_state=SignalReportAssignment.PrState.OPEN,
+ )
+
+ with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ with self.captureOnCommitCallbacks(execute=True):
+ update_assignments_for_pull_request(
+ team_ids=[self.team.id],
+ repository="posthog/posthog",
+ pr_number=123,
+ pr_state=SignalReportAssignment.PrState.CLOSED,
+ )
+
+ mock_task.delay.assert_not_called()
+ for report in reports:
+ report.refresh_from_db()
+ assert report.status == SignalReport.Status.SUPPRESSED
+
def test_unrelated_save_of_suppressed_report_does_not_enqueue(self):
report = self._create_report(report_status=SignalReport.Status.SUPPRESSED)
with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
@@ -116,6 +147,57 @@ class TestCloseDismissedReportPrTask(BaseTest):
class TestCloseImplementationPrForReport(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.report = SignalReport.objects.create(
+ team=self.team,
+ status=SignalReport.Status.READY,
+ title="Test report",
+ summary="Test summary",
+ )
+ self.assignment = SignalReportAssignment.all_teams.create(
+ team=self.team,
+ report=self.report,
+ actor_kind=SignalActorKind.SYSTEM,
+ pr_url=_PR_URL,
+ repository="posthog/posthog",
+ pr_number=123,
+ pr_state=SignalReportAssignment.PrState.OPEN,
+ )
+
+ @parameterized.expand(
+ [
+ ("unclaimed", None),
+ ("user", SignalActorKind.USER),
+ ("agent", SignalActorKind.AGENT),
+ ]
+ )
+ def test_does_not_touch_pr_without_trusted_claim_actor(self, _name: str, actor_kind: str | None):
+ self.assignment.actor_kind = actor_kind
+ self.assignment.save(update_fields=["actor_kind", "updated_at"])
+
+ with patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository"
+ ) as mock_resolve:
+ assert close_implementation_pr_for_report(self.team.id, str(self.report.id)) is False
+
+ mock_resolve.assert_not_called()
+
+ def test_task_claim_actor_can_close_pr(self):
+ self.assignment.actor_kind = SignalActorKind.TASK
+ self.assignment.actor_task_id = uuid.uuid4()
+ self.assignment.save(update_fields=["actor_kind", "actor_task_id", "updated_at"])
+ github = MagicMock()
+ github.get_pull_request.return_value = {"success": True, "state": "open", "merged": False}
+ github.comment_on_pull_request.return_value = {"success": True}
+ github.close_pull_request.return_value = {"success": True}
+
+ with patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ):
+ assert close_implementation_pr_for_report(self.team.id, str(self.report.id)) is True
+
@parameterized.expand(
[
("suppressed", "suppressed"),
@@ -128,84 +210,198 @@ class TestCloseImplementationPrForReport(BaseTest):
github.get_pull_request.return_value = {"success": True, "state": "open", "merged": False}
github.comment_on_pull_request.return_value = {"success": True}
github.close_pull_request.return_value = {"success": True, "number": 123, "state": "closed"}
- with (
- patch(
- "products.signals.backend.implementation_pr.fetch_implementation_pr_urls_for_reports",
- return_value={"report-1": _PR_URL},
- ),
- patch(
- "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository",
- return_value=github,
- ) as mock_resolve,
- ):
- assert close_implementation_pr_for_report(self.team.id, "report-1", reason=reason) is True
+ with patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ) as mock_resolve:
+ assert close_implementation_pr_for_report(self.team.id, str(self.report.id), reason=reason) is True
+
mock_resolve.assert_called_once_with(self.team.id, "PostHog/posthog")
comment_body = github.comment_on_pull_request.call_args.args[2]
assert reason in comment_body
github.close_pull_request.assert_called_once_with("PostHog/posthog", 123)
+ self.assignment.refresh_from_db()
+ assert self.assignment.pr_state == SignalReportAssignment.PrState.CLOSED
+ assert self.assignment.pr_merged is False
def test_returns_false_and_skips_github_without_linked_pr(self):
- with (
- patch(
- "products.signals.backend.implementation_pr.fetch_implementation_pr_urls_for_reports",
- return_value={},
- ),
- patch(
- "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository"
- ) as mock_resolve,
- ):
- assert close_implementation_pr_for_report(self.team.id, "report-1") is False
+ self.assignment.pr_url = None
+ self.assignment.repository = None
+ self.assignment.pr_number = None
+ self.assignment.pr_state = None
+ self.assignment.save(update_fields=["pr_url", "repository", "pr_number", "pr_state", "updated_at"])
+
+ with patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository"
+ ) as mock_resolve:
+ assert close_implementation_pr_for_report(self.team.id, str(self.report.id)) is False
+
mock_resolve.assert_not_called()
def test_returns_false_when_no_integration_resolves(self):
- with (
- patch(
- "products.signals.backend.implementation_pr.fetch_implementation_pr_urls_for_reports",
- return_value={"report-1": _PR_URL},
- ),
- patch(
- "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository",
- return_value=None,
- ),
+ with patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository",
+ return_value=None,
):
- assert close_implementation_pr_for_report(self.team.id, "report-1") is False
+ assert close_implementation_pr_for_report(self.team.id, str(self.report.id)) is False
+
+ self.assignment.refresh_from_db()
+ assert self.assignment.pr_state == SignalReportAssignment.PrState.OPEN
+
+ def test_does_not_close_a_report_pr_from_another_team(self):
+ other_team = Team.objects.create(organization=self.organization, name="Other team")
+
+ with patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository"
+ ) as mock_resolve:
+ assert close_implementation_pr_for_report(other_team.id, str(self.report.id)) is False
+
+ mock_resolve.assert_not_called()
+ self.assignment.refresh_from_db()
+ assert self.assignment.pr_state == SignalReportAssignment.PrState.OPEN
+
+ def _other_report_sharing_the_pr(self, report_status: str) -> SignalReport:
+ other_report = SignalReport.objects.create(
+ team=self.team,
+ status=report_status,
+ title="Other report",
+ summary="Other summary",
+ )
+ SignalReportAssignment.all_teams.create(
+ team=self.team,
+ report=other_report,
+ pr_url=_PR_URL,
+ repository="posthog/posthog",
+ pr_number=123,
+ pr_state=SignalReportAssignment.PrState.OPEN,
+ )
+ return other_report
+
+ def test_does_not_close_a_pr_another_live_report_still_uses(self):
+ self._other_report_sharing_the_pr(SignalReport.Status.READY)
+
+ with patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository"
+ ) as mock_resolve:
+ assert close_implementation_pr_for_report(self.team.id, str(self.report.id)) is False
+
+ mock_resolve.assert_not_called()
+ self.assignment.refresh_from_db()
+ assert self.assignment.pr_state == SignalReportAssignment.PrState.OPEN
@parameterized.expand(
[
- ("already_closed", {"success": True, "state": "closed", "merged": False}),
- ("already_merged", {"success": True, "state": "closed", "merged": True}),
+ ("suppressed", SignalReport.Status.SUPPRESSED),
+ ("resolved", SignalReport.Status.RESOLVED),
]
)
- def test_skips_comment_and_close_when_pr_not_open(self, _name: str, pr_status: dict):
+ def test_closes_the_pr_once_every_other_linked_report_is_finished(self, _name: str, other_status: str):
+ self._other_report_sharing_the_pr(other_status)
github = MagicMock()
- github.get_pull_request.return_value = pr_status
- with (
- patch(
- "products.signals.backend.implementation_pr.fetch_implementation_pr_urls_for_reports",
- return_value={"report-1": _PR_URL},
+ github.get_pull_request.return_value = {"success": True, "state": "open", "merged": False}
+ github.comment_on_pull_request.return_value = {"success": True}
+ github.close_pull_request.return_value = {"success": True, "number": 123, "state": "closed"}
+
+ with patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ):
+ assert close_implementation_pr_for_report(self.team.id, str(self.report.id)) is True
+
+ github.close_pull_request.assert_called_once_with("PostHog/posthog", 123)
+
+ def test_keeps_a_merge_that_lands_during_the_github_round_trip(self):
+ # Closing a merged PR reports success without reopening it, so a merge that arrives after the
+ # status fetch would otherwise be overwritten with closed, permanently.
+ def merge_lands(*args, **kwargs):
+ SignalReportAssignment.all_teams.filter(pk=self.assignment.pk).update(
+ pr_state=SignalReportAssignment.PrState.MERGED,
+ pr_merged=True,
+ )
+ return {"success": True, "number": 123, "state": "closed"}
+
+ github = MagicMock()
+ github.get_pull_request.return_value = {"success": True, "state": "open", "merged": False}
+ github.comment_on_pull_request.return_value = {"success": True}
+ github.close_pull_request.side_effect = merge_lands
+ with patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ):
+ close_implementation_pr_for_report(self.team.id, str(self.report.id))
+
+ self.assignment.refresh_from_db()
+ assert self.assignment.pr_state == SignalReportAssignment.PrState.MERGED
+ assert self.assignment.pr_merged is True
+
+ def test_does_not_write_the_result_onto_a_replacement_pr(self):
+ replacement_url = "https://github.com/PostHog/posthog/pull/456"
+
+ def reclaim_swaps_the_pr(*args, **kwargs):
+ SignalReportAssignment.all_teams.filter(pk=self.assignment.pk).update(
+ pr_url=replacement_url,
+ pr_number=456,
+ pr_state=SignalReportAssignment.PrState.OPEN,
+ )
+ return {"success": True, "number": 123, "state": "closed"}
+
+ github = MagicMock()
+ github.get_pull_request.return_value = {"success": True, "state": "open", "merged": False}
+ github.comment_on_pull_request.return_value = {"success": True}
+ github.close_pull_request.side_effect = reclaim_swaps_the_pr
+ with patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ):
+ close_implementation_pr_for_report(self.team.id, str(self.report.id))
+
+ self.assignment.refresh_from_db()
+ assert self.assignment.pr_url == replacement_url
+ assert self.assignment.pr_state == SignalReportAssignment.PrState.OPEN
+
+ @parameterized.expand(
+ [
+ (
+ "already_closed",
+ {"success": True, "state": "closed", "merged": False},
+ SignalReportAssignment.PrState.CLOSED,
+ False,
),
- patch(
- "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository",
- return_value=github,
+ (
+ "already_merged",
+ {"success": True, "state": "closed", "merged": True},
+ SignalReportAssignment.PrState.MERGED,
+ True,
),
+ ]
+ )
+ def test_skips_comment_and_close_when_pr_not_open(
+ self, _name: str, pr_status: dict, expected_state: str, expected_merged: bool
+ ):
+ github = MagicMock()
+ github.get_pull_request.return_value = pr_status
+ with patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository",
+ return_value=github,
):
- assert close_implementation_pr_for_report(self.team.id, "report-1") is False
+ assert close_implementation_pr_for_report(self.team.id, str(self.report.id)) is False
+
github.comment_on_pull_request.assert_not_called()
github.close_pull_request.assert_not_called()
+ self.assignment.refresh_from_db()
+ assert self.assignment.pr_state == expected_state
+ assert self.assignment.pr_merged is expected_merged
def test_skips_comment_and_close_when_status_unavailable(self):
github = MagicMock()
github.get_pull_request.return_value = {"success": False, "error": "boom", "status_code": 404}
- with (
- patch(
- "products.signals.backend.implementation_pr.fetch_implementation_pr_urls_for_reports",
- return_value={"report-1": _PR_URL},
- ),
- patch(
- "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository",
- return_value=github,
- ),
+ with patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository",
+ return_value=github,
):
- assert close_implementation_pr_for_report(self.team.id, "report-1") is False
+ assert close_implementation_pr_for_report(self.team.id, str(self.report.id)) is False
+
github.comment_on_pull_request.assert_not_called()
github.close_pull_request.assert_not_called()
+ self.assignment.refresh_from_db()
+ assert self.assignment.pr_state == SignalReportAssignment.PrState.OPEN
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index 84850202dbfe..c9e4ba37c549 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -40,17 +40,14 @@ from products.signals.backend.models import (
ArtefactAttribution,
SignalReport,
SignalReportArtefact,
+ SignalReportAssignment,
SignalReportTask,
SignalTeamConfig,
SignalUserAutonomyConfig,
)
from products.signals.backend.signal_metadata import ReportSignalMeta
from products.signals.backend.task_run_artefacts import (
- TASK_RUN_TYPE_DISCUSSION,
TASK_RUN_TYPE_IMPLEMENTATION,
- TASK_RUN_TYPE_REPO_SELECTION,
- TASK_RUN_TYPE_RESEARCH,
- TASK_RUN_TYPE_SCOUT,
append_task_run_artefact,
record_implementation_task,
record_report_task,
@@ -706,238 +703,173 @@ class TestSignalReportListAPI(APIBaseTest):
)
return task, run
- def test_implementation_pr_url_present_when_task_has_pr(self):
+ def _create_assignment(
+ self,
+ report: SignalReport,
+ *,
+ pr_url: str | None = None,
+ pr_state: str = SignalReportAssignment.PrState.UNKNOWN,
+ pr_merged: bool = False,
+ ) -> SignalReportAssignment:
+ parts = pr_url.rstrip("/").split("/") if pr_url else []
+ return SignalReportAssignment.all_teams.create(
+ team=self.team,
+ report=report,
+ pr_url=pr_url,
+ repository="/".join(parts[-4:-2]) if parts else None,
+ pr_number=int(parts[-1]) if parts else None,
+ pr_state=pr_state if pr_url else None,
+ pr_merged=pr_merged,
+ )
+
+ def test_implementation_pr_fields_come_from_assignment(self):
report = self._create_report()
- self._create_implementation_task_with_run(report, pr_url="https://github.com/org/repo/pull/42")
+ self._create_assignment(report, pr_url="https://github.com/org/repo/pull/42")
response = self.client.get(self._list_url())
assert response.status_code == status.HTTP_200_OK
row = next(r for r in response.json()["results"] if r["id"] == str(report.id))
assert row["implementation_pr_url"] == "https://github.com/org/repo/pull/42"
+ assert row["implementation_pr_state"] == SignalReportAssignment.PrState.UNKNOWN
+ assert row["implementation_pr_merged"] is False
+ assert row["work_state"] == "in_review"
- def test_retrieve_implementation_pr_url_present_when_task_has_pr(self):
+ def test_retrieve_implementation_pr_fields_come_from_assignment(self):
report = self._create_report()
- self._create_implementation_task_with_run(report, pr_url="https://github.com/org/repo/pull/42")
+ self._create_assignment(
+ report,
+ pr_url="https://github.com/org/repo/pull/42",
+ pr_state=SignalReportAssignment.PrState.OPEN,
+ )
response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/")
assert response.status_code == status.HTTP_200_OK
assert response.json()["implementation_pr_url"] == "https://github.com/org/repo/pull/42"
- assert response.json()["implementation_pr_url"] == response.json()["implementation_pr_url"].strip('"')
+ assert response.json()["implementation_pr_state"] == SignalReportAssignment.PrState.OPEN
- def test_implementation_pr_url_resolves_from_artefact_only_association(self):
- # A task associated purely via a task_run artefact (no SignalReportTask gate row, e.g. a
- # custom-agent run) still resolves its PR — the unified association covers both sources.
+ def test_task_run_pr_is_used_as_fallback_when_assignment_has_no_pr(self):
Task = apps.get_model("tasks", "Task")
TaskRun = apps.get_model("tasks", "TaskRun")
report = self._create_report()
task = Task.objects.create(
- team=self.team, title="t", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
- )
- append_task_run_artefact(
- team_id=self.team.id,
- report_id=str(report.id),
- product="signals",
- type="implementation",
- task_id=str(task.id),
+ team=self.team,
+ title="Implementation task",
+ description="Fix the bug",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
)
- assert not SignalReportTask.objects.filter(report=report).exists()
TaskRun.objects.create(
team=self.team,
task=task,
status=TaskRun.Status.COMPLETED,
- output={"pr_url": "https://github.com/o/r/pull/7"},
+ output={"pr_url": "https://github.com/org/repo/pull/7"},
)
-
- response = self.client.get(self._list_url())
- assert response.status_code == status.HTTP_200_OK
- row = next(r for r in response.json()["results"] if r["id"] == str(report.id))
- assert row["implementation_pr_url"] == "https://github.com/o/r/pull/7"
-
- @parameterized.expand(
- [
- # A "Discuss" task runs the same agent against the same repo, so the PR it opens is the
- # report's PR. Without it the report offers "Create PR" for work that already shipped.
- ("discussion_only", False, "https://github.com/o/r/pull/5"),
- # Implementation still wins when both have one, even though the discussion task is older
- # and would come first on association order alone.
- ("implementation_wins_over_discussion", True, "https://github.com/o/r/pull/6"),
- ]
- )
- def test_implementation_pr_url_resolves_discussion_task_pr(self, _name, with_implementation, expected_url):
- report = self._create_report()
- self._create_implementation_task_with_run(
- report, pr_url="https://github.com/o/r/pull/5", relationship=TASK_RUN_TYPE_DISCUSSION
+ record_report_task(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ task_id=str(task.id),
+ relationship=TASK_RUN_TYPE_IMPLEMENTATION,
)
- if with_implementation:
- self._create_implementation_task_with_run(report, pr_url="https://github.com/o/r/pull/6")
row = next(r for r in self.client.get(self._list_url()).json()["results"] if r["id"] == str(report.id))
- assert row["implementation_pr_url"] == expected_url
-
- @parameterized.expand(
- [
- ("research", TASK_RUN_TYPE_RESEARCH, "research"),
- ("repo_selection", TASK_RUN_TYPE_REPO_SELECTION, "repo_selection"),
- ("scout", TASK_RUN_TYPE_SCOUT, "scout:some-skill"),
- ]
- )
- def test_implementation_pr_url_ignores_pr_recorded_on_non_code_run(self, _name, relationship, ai_stage):
- # A research run checks GitHub for in-flight work and the agent-server can record a PR it
- # merely read as the run's own. That must never surface as the report's PR, on the list, the
- # detail view, or the "has PR" filter the Pull requests tab counts.
- report = self._create_report()
- self._create_implementation_task_with_run(
- report,
- pr_url="https://github.com/o/r/pull/99",
- relationship=relationship,
- state={"ai_stage": ai_stage},
- )
-
- row = next(r for r in self.client.get(self._list_url()).json()["results"] if r["id"] == str(report.id))
- detail = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/").json()
- with_pr = self.client.get(self._list_url(has_implementation_pr="true")).json()
+ assert row["implementation_pr_url"] == "https://github.com/org/repo/pull/7"
+ assert row["implementation_pr_state"] == SignalReportAssignment.PrState.UNKNOWN
+ assert row["work_state"] == "in_review"
- assert row["implementation_pr_url"] is None
- assert detail["implementation_pr_url"] is None
- assert with_pr["count"] == 0
+ with_pr = self.client.get(self._list_url(has_implementation_pr="true"))
+ assert str(report.id) in {item["id"] for item in with_pr.json()["results"]}
+ unclaimed = self.client.get(self._list_url(unclaimed="true"))
+ assert str(report.id) not in {item["id"] for item in unclaimed.json()["results"]}
- def test_implementation_pr_url_prefers_real_pr_over_one_read_by_research(self):
+ def test_assignment_pr_wins_over_task_run_output(self):
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
report = self._create_report()
- self._create_implementation_task_with_run(
- report,
- pr_url="https://github.com/o/r/pull/99",
- relationship=TASK_RUN_TYPE_RESEARCH,
- state={"ai_stage": "research"},
+ task = Task.objects.create(
+ team=self.team,
+ title="Implementation task",
+ description="Fix the bug",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
)
- self._create_implementation_task_with_run(
- report, pr_url="https://github.com/o/r/pull/100", state={"ai_stage": "implementation"}
+ record_report_task(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ task_id=str(task.id),
+ relationship=TASK_RUN_TYPE_IMPLEMENTATION,
+ )
+ TaskRun.objects.create(
+ team=self.team,
+ task=task,
+ status=TaskRun.Status.COMPLETED,
+ output={"pr_url": "https://github.com/org/repo/pull/7"},
)
+ assignment = SignalReportAssignment.all_teams.get(report=report)
+ assignment.pr_url = "https://github.com/org/repo/pull/42"
+ assignment.repository = "org/repo"
+ assignment.pr_number = 42
+ assignment.pr_state = SignalReportAssignment.PrState.UNKNOWN
+ assignment.save()
row = next(r for r in self.client.get(self._list_url()).json()["results"] if r["id"] == str(report.id))
- with_pr = self.client.get(self._list_url(has_implementation_pr="true")).json()
- assert row["implementation_pr_url"] == "https://github.com/o/r/pull/100"
- assert with_pr["count"] == 1
+ assert row["implementation_pr_url"] == "https://github.com/org/repo/pull/42"
@parameterized.expand(
[
- # The badge reads this flag, so it must track the webhook's merge record rather than the
- # report status — a resolved report may have been resolved directly, PR still open.
- ("merged_pr", SignalReport.Status.READY, {"pr_url": "https://github.com/o/r/pull/7", "pr_merged": True}),
- ("resolved_without_merge", SignalReport.Status.RESOLVED, {"pr_url": "https://github.com/o/r/pull/7"}),
- ("no_pr_run", SignalReport.Status.RESOLVED, None),
+ ("merged_pr", SignalReport.Status.READY, True),
+ ("resolved_without_merge", SignalReport.Status.RESOLVED, False),
]
)
- def test_implementation_pr_merged_reflects_merge_flag_not_status(self, _name, report_status, output):
+ def test_implementation_pr_merged_reflects_assignment_flag(self, _name, report_status, merged):
report = self._create_report(status=report_status)
- if output is not None:
- self._create_implementation_task_with_run(report, output=output)
- expected = bool(output and output.get("pr_merged"))
+ self._create_assignment(
+ report,
+ pr_url="https://github.com/org/repo/pull/7",
+ pr_state=(SignalReportAssignment.PrState.MERGED if merged else SignalReportAssignment.PrState.OPEN),
+ pr_merged=merged,
+ )
list_row = next(r for r in self.client.get(self._list_url()).json()["results"] if r["id"] == str(report.id))
detail = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/").json()
- assert list_row["implementation_pr_merged"] is expected
- assert detail["implementation_pr_merged"] is expected
+ assert list_row["implementation_pr_merged"] is merged
+ assert detail["implementation_pr_merged"] is merged
- def test_implementation_pr_merged_describes_the_surfaced_pr_not_a_sibling_task(self):
- # A retried report has several implementation tasks but surfaces one PR. The merge flag must
- # come from that same task — otherwise a sibling task's merged PR vouches for the PR whose
- # URL is on screen, and the badge shows "merged" over an open PR.
- report = self._create_report()
- self._create_implementation_task_with_run(report, output={"pr_url": "https://github.com/o/r/pull/1"})
- self._create_implementation_task_with_run(
- report, output={"pr_url": "https://github.com/o/r/pull/2", "pr_merged": True}
- )
-
- row = next(r for r in self.client.get(self._list_url()).json()["results"] if r["id"] == str(report.id))
-
- assert row["implementation_pr_merged"] is (row["implementation_pr_url"] == "https://github.com/o/r/pull/2")
-
- def test_implementation_pr_url_null_when_no_implementation_task(self):
+ def test_implementation_pr_url_null_without_assignment(self):
report = self._create_report()
response = self.client.get(self._list_url())
assert response.status_code == status.HTTP_200_OK
row = next(r for r in response.json()["results"] if r["id"] == str(report.id))
assert row["implementation_pr_url"] is None
+ assert row["implementation_pr_state"] is None
- def test_implementation_pr_url_null_when_output_has_no_pr_url(self):
+ def test_implementation_pr_url_null_when_assignment_url_is_empty(self):
report = self._create_report()
- self._create_implementation_task_with_run(report, output={"commit_sha": "abc123"})
+ self._create_assignment(report, pr_url="")
response = self.client.get(self._list_url())
assert response.status_code == status.HTTP_200_OK
row = next(r for r in response.json()["results"] if r["id"] == str(report.id))
assert row["implementation_pr_url"] is None
-
- def test_implementation_pr_url_null_when_pr_url_is_empty_string(self):
- report = self._create_report()
- self._create_implementation_task_with_run(report, pr_url="")
-
- response = self.client.get(self._list_url())
- assert response.status_code == status.HTTP_200_OK
- row = next(r for r in response.json()["results"] if r["id"] == str(report.id))
- assert row["implementation_pr_url"] is None
-
- def test_implementation_pr_url_uses_latest_task_run(self):
- Task = apps.get_model("tasks", "Task")
- TaskRun = apps.get_model("tasks", "TaskRun")
- report = self._create_report()
- task = Task.objects.create(
- team=self.team,
- title="Implementation task",
- description="Fix the bug",
- origin_product=Task.OriginProduct.SIGNAL_REPORT,
- )
- record_implementation_task(
- team_id=self.team.id,
- report_id=str(report.id),
- task_id=str(task.id),
- )
- old_run = TaskRun.objects.create(
- team=self.team,
- task=task,
- status=TaskRun.Status.COMPLETED,
- output={"pr_url": "https://github.com/org/repo/pull/1"},
- )
- # Force older created_at
- TaskRun.objects.filter(pk=old_run.pk).update(created_at=timezone.now() - timedelta(hours=1))
- TaskRun.objects.create(
- team=self.team,
- task=task,
- status=TaskRun.Status.COMPLETED,
- output={"pr_url": "https://github.com/org/repo/pull/99"},
- )
-
- response = self.client.get(self._list_url())
- assert response.status_code == status.HTTP_200_OK
- row = next(r for r in response.json()["results"] if r["id"] == str(report.id))
- assert row["implementation_pr_url"] == "https://github.com/org/repo/pull/99"
+ assert row["implementation_pr_state"] is None
def test_fetches_implementation_pr_urls_for_current_report_page(self):
report_with_pr = self._create_report(title="Report with PR")
report_without_pr = self._create_report(title="Report without PR")
- self._create_implementation_task_with_run(report_with_pr, pr_url="https://github.com/org/repo/pull/42")
- self._create_implementation_task_with_run(report_without_pr, output={"commit_sha": "abc123"})
+ self._create_assignment(report_with_pr, pr_url="https://github.com/org/repo/pull/42")
+ self._create_assignment(report_without_pr)
result = fetch_implementation_pr_urls_for_reports([str(report_with_pr.id), str(report_without_pr.id)])
- assert result == {
- str(report_with_pr.id): "https://github.com/org/repo/pull/42",
- }
+ assert result == {str(report_with_pr.id): "https://github.com/org/repo/pull/42"}
def test_fetch_implementation_pr_urls_issues_constant_queries(self):
- # N+1 guard: association is batched across the page, so resolving PR urls for many reports
- # costs the same number of queries as for one. A per-report `associated_task_runs` loop
- # scaled at two queries per report (one artefact read + one gate-row read), the exact
- # regression this asserts against.
def seed(count: int) -> list[str]:
ids = []
for i in range(count):
report = self._create_report(title=f"PR report {i}")
- self._create_implementation_task_with_run(report, pr_url=f"https://github.com/org/repo/pull/{i}")
+ self._create_assignment(report, pr_url=f"https://github.com/org/repo/pull/{i}")
ids.append(str(report.id))
return ids
@@ -951,10 +883,8 @@ class TestSignalReportListAPI(APIBaseTest):
result = fetch_implementation_pr_state_for_reports(page)
assert len(result) == 6
- # Constant in the page size, and a small fixed cost (artefacts + gate rows + PR url lookup +
- # merge-flag lookup).
assert len(for_many.captured_queries) == baseline
- assert baseline <= 4
+ assert baseline == 1
# --- has_implementation_pr filter ---
@@ -967,7 +897,7 @@ class TestSignalReportListAPI(APIBaseTest):
def test_filter_has_implementation_pr(self, _name, query_value, expected):
report_with_pr = self._create_report(title="Report with PR")
report_without_pr = self._create_report(title="Report without PR")
- self._create_implementation_task_with_run(report_with_pr, pr_url="https://github.com/org/repo/pull/42")
+ self._create_assignment(report_with_pr, pr_url="https://github.com/org/repo/pull/42")
expected_id = str(report_with_pr.id if expected == "with_pr" else report_without_pr.id)
response = self.client.get(self._list_url(has_implementation_pr=query_value))
@@ -979,7 +909,7 @@ class TestSignalReportListAPI(APIBaseTest):
def test_filter_has_implementation_pr_ignores_empty_pr_url(self):
report_empty_pr = self._create_report(title="Report with empty PR url")
- self._create_implementation_task_with_run(report_empty_pr, pr_url="")
+ self._create_assignment(report_empty_pr, pr_url="")
with_pr = self.client.get(self._list_url(has_implementation_pr="true"))
assert with_pr.json()["count"] == 0
@@ -994,7 +924,7 @@ class TestSignalReportListAPI(APIBaseTest):
response = self.client.get(self._list_url(has_implementation_pr="true"))
assert response.status_code == status.HTTP_200_OK
- # Both association subqueries must stay team-scoped. Without the scope the planner can
+ # All association subqueries must stay team-scoped. Without the scope the planner can
# invert the join and scan every team's task_run artefacts per request.
filter_sql = [
query["sql"]
@@ -1003,14 +933,13 @@ class TestSignalReportListAPI(APIBaseTest):
]
assert filter_sql
for sql in filter_sql:
- # Django aliases both association tables as V0; two scoped subqueries means two
- # V0-qualified team filters.
- assert sql.count(f'V0."team_id" = {self.team.id}') == 2
+ # Django aliases the task, legacy artefact, and assignment association tables as V0.
+ assert sql.count(f'V0."team_id" = {self.team.id}') == 3
def test_filter_has_implementation_pr_absent_returns_all(self):
report_with_pr = self._create_report(title="Report with PR")
report_without_pr = self._create_report(title="Report without PR")
- self._create_implementation_task_with_run(report_with_pr, pr_url="https://github.com/org/repo/pull/42")
+ self._create_assignment(report_with_pr, pr_url="https://github.com/org/repo/pull/42")
response = self.client.get(self._list_url())
assert response.status_code == status.HTTP_200_OK
@@ -1020,7 +949,7 @@ class TestSignalReportListAPI(APIBaseTest):
def test_filter_has_implementation_pr_count_via_limit_one(self):
for i in range(3):
report = self._create_report(title=f"PR report {i}")
- self._create_implementation_task_with_run(report, pr_url=f"https://github.com/org/repo/pull/{i}")
+ self._create_assignment(report, pr_url=f"https://github.com/org/repo/pull/{i}")
self._create_report(title="No PR report")
response = self.client.get(self._list_url(has_implementation_pr="true", limit=1))
@@ -1032,26 +961,20 @@ class TestSignalReportListAPI(APIBaseTest):
def test_filter_has_implementation_pr_count_only_skips_report_enrichment(self):
for i in range(3):
report = self._create_report(title=f"PR report {i}")
- self._create_implementation_task_with_run(report, pr_url=f"https://github.com/org/repo/pull/{i}")
+ self._create_assignment(report, pr_url=f"https://github.com/org/repo/pull/{i}")
self._create_report(title="No PR report")
- with (
- patch("products.signals.backend.views.fetch_source_products_for_reports") as fetch_source_products,
- patch(
- "products.signals.backend.views.fetch_implementation_pr_state_for_reports"
- ) as fetch_implementation_prs,
- ):
+ with patch("products.signals.backend.views.fetch_source_products_for_reports") as fetch_source_products:
response = self.client.get(self._list_url(has_implementation_pr="true", count_only="true"))
assert response.status_code == status.HTTP_200_OK
assert response.json() == {"count": 3, "next": None, "previous": None, "results": []}
fetch_source_products.assert_not_called()
- fetch_implementation_prs.assert_not_called()
def test_filter_has_implementation_pr_empty_value_is_noop(self):
report_with_pr = self._create_report(title="Report with PR")
report_without_pr = self._create_report(title="Report without PR")
- self._create_implementation_task_with_run(report_with_pr, pr_url="https://github.com/org/repo/pull/42")
+ self._create_assignment(report_with_pr, pr_url="https://github.com/org/repo/pull/42")
response = self.client.get(self._list_url(has_implementation_pr=""))
assert response.status_code == status.HTTP_200_OK
@@ -1245,19 +1168,11 @@ class TestSignalReportListAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["source_products"] == []
- @parameterized.expand(
- [
- ("source_products", "fetch_source_products_for_reports"),
- ("implementation_pr_urls", "fetch_implementation_pr_state_for_reports"),
- ]
- )
- def test_list_resilient_to_supplementary_fetch_failure(self, _name, fetch_fn):
- # A transient failure in either decorative metadata fetch must degrade to empty badges
- # rather than 500 the whole inbox load — the list still renders from Postgres data.
+ def test_list_resilient_to_source_product_fetch_failure(self):
report = self._create_report()
with patch(
- f"products.signals.backend.views.{fetch_fn}",
+ "products.signals.backend.views.fetch_source_products_for_reports",
side_effect=Exception("clickhouse timeout"),
):
response = self.client.get(self._list_url())
@@ -2513,11 +2428,49 @@ class TestSignalReportLegacyTaskArtefactList(APIBaseTest):
assert len(task_runs) == 1
artefact = task_runs[0]
assert artefact["id"] == str(report_task.id)
+ assert artefact["actor_kind"] == "task"
+ assert artefact["actor_agent"] is None
assert str(artefact["task_id"]) == str(task.id)
assert artefact["content"]["task_id"] == str(task.id)
assert artefact["content"]["product"] == expected_product
assert artefact["content"]["type"] == expected_type
+ def test_pre_attribution_rows_are_reported_as_system(self):
+ # The old FK columns cannot prove which actor initiated a write: legacy system paths could
+ # persist either column as context. Keep the documented null-kind fallback deterministic.
+ report = self._create_report()
+ task = self._create_task()
+ legacy_rows = [
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.NOTE,
+ content=json.dumps({"note": "task note"}),
+ task=task,
+ ),
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.NOTE,
+ content=json.dumps({"note": "user note"}),
+ created_by=self.user,
+ ),
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.NOTE,
+ content=json.dumps({"note": "system note"}),
+ ),
+ ]
+
+ response = self.client.get(self._artefacts_url(str(report.id)))
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ actor_kind_by_id = {a["id"]: a["actor_kind"] for a in response.json()["results"]}
+
+ for row in legacy_rows:
+ assert row.actor_kind is None
+ assert actor_kind_by_id[str(row.id)] == "system"
+
def test_real_task_run_artefact_wins_over_legacy_row(self):
report = self._create_report()
task = self._create_task()
@@ -2708,6 +2661,8 @@ class TestSignalReportContentUpdateAPI(APIBaseTest):
content = json.loads(artefacts[0].content)
assert content == {"old_title": "Original title", "new_title": "New title"}
# Attributed to the requesting user, not a task, when no task header is present.
+ assert artefacts[0].actor_kind == "user"
+ assert artefacts[0].actor_agent is None
assert artefacts[0].created_by_id == self.user.id
assert artefacts[0].task_id is None
@@ -2755,9 +2710,29 @@ class TestSignalReportContentUpdateAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
artefacts = self._artefacts(report, SignalReportArtefact.ArtefactType.TITLE_CHANGE)
assert len(artefacts) == 1
+ assert artefacts[0].actor_kind == "task"
+ assert artefacts[0].actor_agent is None
assert str(artefacts[0].task_id) == str(task.id)
assert artefacts[0].created_by_id is None
+ def test_edit_attributed_to_external_agent_from_mcp_registration(self):
+ report = self._create_report()
+
+ response = self.client.patch(
+ self._url(str(report.id)),
+ data={"title": "Externally edited title"},
+ format="json",
+ headers={"X-PostHog-Client": "mcp", "X-Posthog-Mcp-Client-Name": "codex"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ artefacts = self._artefacts(report, SignalReportArtefact.ArtefactType.TITLE_CHANGE)
+ assert len(artefacts) == 1
+ assert artefacts[0].actor_kind == "agent"
+ assert artefacts[0].actor_agent == "codex"
+ assert artefacts[0].created_by_id == self.user.id
+ assert artefacts[0].task_id is None
+
@parameterized.expand([("title_change",), ("summary_change",)])
def test_change_artefacts_are_read_only_via_artefact_api(self, artefact_type):
# Edit-history artefacts are system-generated; the generic artefact write API must refuse
@@ -2773,14 +2748,24 @@ class TestSignalReportContentUpdateAPI(APIBaseTest):
class TestSignalReportPrEndpoints(APIBaseTest):
- def _create_report(self, report_status: str = SignalReport.Status.READY) -> SignalReport:
- return SignalReport.objects.create(
+ def _create_report(self, report_status: str = SignalReport.Status.READY, *, with_pr: bool = True) -> SignalReport:
+ report = SignalReport.objects.create(
team=self.team,
status=report_status,
title="Test report",
summary="Test summary",
signal_count=1,
)
+ if with_pr:
+ SignalReportAssignment.all_teams.create(
+ team=self.team,
+ report=report,
+ pr_url="https://github.com/PostHog/posthog/pull/7",
+ repository="PostHog/posthog",
+ pr_number=7,
+ pr_state=SignalReportAssignment.PrState.OPEN,
+ )
+ return report
def _checks_url(self, report_id: str) -> str:
return f"/api/projects/{self.team.id}/signals/reports/{report_id}/pr_checks/"
@@ -2815,13 +2800,11 @@ class TestSignalReportPrEndpoints(APIBaseTest):
},
}
user_github.return_value.delete_pull_request_review_comment.return_value = {"success": True}
- with patch(
- "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
- return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
- ):
- response = getattr(self.client, method)(
- self._review_comment_url(str(report.id), "99") + suffix, data=payload, format="json"
- )
+
+ response = getattr(self.client, method)(
+ self._review_comment_url(str(report.id), "99") + suffix, data=payload, format="json"
+ )
+
assert response.status_code == expected_status
@parameterized.expand(
@@ -2834,33 +2817,22 @@ class TestSignalReportPrEndpoints(APIBaseTest):
]
)
def test_sandbox_oauth_token_cannot_write_review_comments_as_the_user(self, _name, method, suffix, payload):
- # These writes reach GitHub under the requesting human's personal connection. A sandbox/agent
- # token is minted as the task actor and carries task:write, so without the guard a prompt-injected
- # run could comment, edit, delete, or react as the person who started it.
report = self._create_report()
UserIntegration.objects.create(user=self.user, kind=UserIntegration.IntegrationKind.GITHUB, integration_id="42")
user_github = patch("products.signals.backend.views.UserGitHubIntegration").start()
self.addCleanup(patch.stopall)
authenticate_as_sandbox_token(self)
- with patch(
- "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
- return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
- ):
- response = getattr(self.client, method)(
- f"/api/projects/{self.team.id}/signals/reports/{report.id}/pr_review_comments/{suffix}",
- data=payload,
- format="json",
- )
+ response = getattr(self.client, method)(
+ f"/api/projects/{self.team.id}/signals/reports/{report.id}/pr_review_comments/{suffix}",
+ data=payload,
+ format="json",
+ )
assert response.status_code == status.HTTP_403_FORBIDDEN
user_github.assert_not_called()
def test_personal_api_key_cannot_write_review_comments_as_the_user(self):
- # A personal API key is issued to automate against the API, not to act as its owner on
- # GitHub. Only a browser session is admitted, so holding task:write must not be enough to
- # reach the user's linked GitHub account. One endpoint is enough: every write resolves the
- # caller through the same guard.
report = self._create_report()
UserIntegration.objects.create(user=self.user, kind=UserIntegration.IntegrationKind.GITHUB, integration_id="42")
user_github = patch("products.signals.backend.views.UserGitHubIntegration").start()
@@ -2869,51 +2841,33 @@ class TestSignalReportPrEndpoints(APIBaseTest):
self.client.logout()
self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {key_value}")
- with patch(
- "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
- return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
- ):
- response = self.client.post(
- f"/api/projects/{self.team.id}/signals/reports/{report.id}/pr_review_comments/",
- data={"body": "hi", "in_reply_to": "1"},
- format="json",
- )
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/signals/reports/{report.id}/pr_review_comments/",
+ data={"body": "hi", "in_reply_to": "1"},
+ format="json",
+ )
assert response.status_code == status.HTTP_403_FORBIDDEN
user_github.assert_not_called()
def test_pr_checks_404_when_report_has_no_implementation_pr(self):
- report = self._create_report()
- with patch(
- "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
- return_value={},
- ):
- response = self.client.get(self._checks_url(str(report.id)))
+ report = self._create_report(with_pr=False)
+
+ response = self.client.get(self._checks_url(str(report.id)))
+
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_pr_checks_404_when_no_integration_can_access_repo(self):
report = self._create_report()
- with (
- patch(
- "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
- return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
- ),
- patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository", return_value=None),
- ):
+ with patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository", return_value=None):
response = self.client.get(self._checks_url(str(report.id)))
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_pr_checks_503_when_egress_budget_sheds_request(self):
report = self._create_report()
- with (
- patch(
- "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
- return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
- ),
- patch(
- "products.signals.backend.views.GitHubIntegration.first_for_team_repository",
- side_effect=GitHubEgressBudgetExhausted("shed"),
- ),
+ with patch(
+ "products.signals.backend.views.GitHubIntegration.first_for_team_repository",
+ side_effect=GitHubEgressBudgetExhausted("shed"),
):
response = self.client.get(self._checks_url(str(report.id)))
assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
@@ -2923,11 +2877,9 @@ class TestSignalReportPrEndpoints(APIBaseTest):
github = patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository").start()
self.addCleanup(patch.stopall)
github.return_value.get_pull_request_checks.side_effect = GitHubEgressBudgetExhausted("shed")
- with patch(
- "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
- return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
- ):
- response = self.client.get(self._checks_url(str(report.id)))
+
+ response = self.client.get(self._checks_url(str(report.id)))
+
assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
def test_pr_checks_success_returns_checks(self):
@@ -2936,17 +2888,14 @@ class TestSignalReportPrEndpoints(APIBaseTest):
self.addCleanup(patch.stopall)
checks = [{"name": "unit", "status": "completed", "conclusion": "success", "url": "https://gh/1"}]
github.return_value.get_pull_request_checks.return_value = {"success": True, "checks": checks}
- with patch(
- "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
- return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
- ):
- response = self.client.get(self._checks_url(str(report.id)))
- cached_response = self.client.get(self._checks_url(str(report.id)))
+
+ response = self.client.get(self._checks_url(str(report.id)))
+ cached_response = self.client.get(self._checks_url(str(report.id)))
+
assert response.status_code == status.HTTP_200_OK
assert response.json() == {"checks": checks}
assert cached_response.status_code == status.HTTP_200_OK
assert cached_response.json() == {"checks": checks}
- # The PR number is parsed off the stored URL and passed through to the integration.
assert github.return_value.get_pull_request_checks.call_args.args == ("PostHog/posthog", 7)
github.return_value.get_pull_request_checks.assert_called_once()
github.assert_called_once_with(
@@ -2969,11 +2918,7 @@ class TestSignalReportPrEndpoints(APIBaseTest):
github = patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository").start()
self.addCleanup(patch.stopall)
getattr(github.return_value, fetch_name).return_value = {"success": True, key: []}
- with patch(
- "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
- return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
- ):
- response = self.client.get(getattr(self, url_attr)(str(report.id)))
+ response = self.client.get(getattr(self, url_attr)(str(report.id)))
assert response.status_code == status.HTTP_200_OK
assert response.json() == {key: []}
@@ -2982,11 +2927,9 @@ class TestSignalReportPrEndpoints(APIBaseTest):
github = patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository").start()
self.addCleanup(patch.stopall)
github.return_value.get_pull_request_checks.return_value = {"success": False, "error": "boom"}
- with patch(
- "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
- return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
- ):
- response = self.client.get(self._checks_url(str(report.id)))
+
+ response = self.client.get(self._checks_url(str(report.id)))
+
assert response.status_code == status.HTTP_502_BAD_GATEWAY
def test_pr_comments_success_returns_comments(self):
@@ -3006,10 +2949,8 @@ class TestSignalReportPrEndpoints(APIBaseTest):
}
]
github.return_value.get_pull_request_comments.return_value = {"success": True, "comments": comments}
- with patch(
- "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
- return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
- ):
- response = self.client.get(self._comments_url(str(report.id)))
+
+ response = self.client.get(self._comments_url(str(report.id)))
+
assert response.status_code == status.HTTP_200_OK
assert response.json() == {"comments": comments}
diff --git a/products/signals/backend/test/test_signal_report_assignment_api.py b/products/signals/backend/test/test_signal_report_assignment_api.py
new file mode 100644
index 000000000000..4d28839eed19
--- /dev/null
+++ b/products/signals/backend/test/test_signal_report_assignment_api.py
@@ -0,0 +1,404 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.apps import apps
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.team.team import Team
+
+from products.signals.backend.models import SignalActorKind, SignalReport, SignalReportAssignment
+
+
+class TestSignalReportAssignmentAPI(APIBaseTest):
+ def _create_report(
+ self,
+ *,
+ team: Team | None = None,
+ report_status: str = SignalReport.Status.READY,
+ title: str = "Test report",
+ ) -> SignalReport:
+ return SignalReport.objects.create(
+ team=team or self.team,
+ status=report_status,
+ title=title,
+ summary="Test summary",
+ signal_count=1,
+ total_weight=1,
+ )
+
+ def _claim_url(self, report: SignalReport) -> str:
+ return f"/api/projects/{self.team.id}/signals/reports/{report.id}/claim/"
+
+ def _list_url(self, **query: str) -> str:
+ suffix = "&".join(f"{key}={value}" for key, value in query.items())
+ return f"/api/projects/{self.team.id}/signals/reports/{'?' + suffix if suffix else ''}"
+
+ @staticmethod
+ def _agent_headers(name: str) -> dict[str, str]:
+ return {"X-PostHog-Client": "mcp", "X-Posthog-Mcp-Client-Name": name}
+
+ def test_user_claim_returns_assignment_and_writes_activity(self):
+ report = self._create_report()
+
+ response = self.client.post(self._claim_url(report), data={}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK
+ assignment = SignalReportAssignment.all_teams.get(report=report)
+ assert assignment.actor_kind == SignalActorKind.USER
+ assert assignment.actor_user_id == self.user.id
+ assert assignment.actor_task_id is None
+ assert assignment.actor_agent is None
+ assert assignment.claimed_at is not None
+ assert response.json()["work_state"] == "working"
+ assert response.json()["assignee"]["kind"] == SignalActorKind.USER
+ assert response.json()["assignee"]["user"]["id"] == self.user.id
+
+ log = ActivityLog.objects.get(
+ team_id=self.team.id,
+ scope="SignalReport",
+ item_id=str(report.id),
+ activity="assignment_changed",
+ )
+ assert log.detail is not None
+ assert log.detail["changes"][0]["field"] == "assignee"
+ assert log.detail["changes"][0]["before"] is None
+ assert log.detail["changes"][0]["after"]["kind"] == SignalActorKind.USER
+
+ def test_identical_claim_is_idempotent(self):
+ report = self._create_report()
+ self.client.post(self._claim_url(report), data={}, format="json")
+ claimed_at = SignalReportAssignment.all_teams.get(report=report).claimed_at
+
+ response = self.client.post(self._claim_url(report), data={}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK
+ assignment = SignalReportAssignment.all_teams.get(report=report)
+ assert assignment.claimed_at == claimed_at
+ assert (
+ ActivityLog.objects.filter(
+ team_id=self.team.id,
+ scope="SignalReport",
+ item_id=str(report.id),
+ activity="assignment_changed",
+ ).count()
+ == 1
+ )
+
+ def test_external_agent_silently_takes_over_claim(self):
+ report = self._create_report()
+ self.client.post(
+ self._claim_url(report),
+ data={},
+ format="json",
+ headers=self._agent_headers("claude-code"),
+ )
+
+ response = self.client.post(
+ self._claim_url(report),
+ data={},
+ format="json",
+ headers=self._agent_headers("codex"),
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assignment = SignalReportAssignment.all_teams.get(report=report)
+ assert assignment.actor_kind == SignalActorKind.AGENT
+ assert assignment.actor_user_id == self.user.id
+ assert assignment.actor_task_id is None
+ assert assignment.actor_agent == "codex"
+ logs = ActivityLog.objects.filter(
+ team_id=self.team.id,
+ scope="SignalReport",
+ item_id=str(report.id),
+ activity="assignment_changed",
+ ).order_by("created_at")
+ assert logs.count() == 2
+ takeover = logs.last()
+ assert takeover is not None and takeover.detail is not None
+ change = takeover.detail["changes"][0]
+ assert change["before"]["agent"] == "claude-code"
+ assert change["after"]["agent"] == "codex"
+
+ def test_generic_mcp_client_name_is_used_when_registration_name_is_missing(self):
+ report = self._create_report()
+
+ response = self.client.post(
+ self._claim_url(report),
+ data={},
+ format="json",
+ headers={"X-PostHog-Client": "mcp"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assignment = SignalReportAssignment.all_teams.get(report=report)
+ assert assignment.actor_kind == SignalActorKind.AGENT
+ assert assignment.actor_agent == "mcp"
+
+ def test_internal_task_claim_uses_task_attribution(self):
+ Task = apps.get_model("tasks", "Task")
+ task = Task.objects.create(
+ team=self.team,
+ created_by=self.user,
+ title="Signal task",
+ description="Implement the report",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ )
+ report = self._create_report()
+
+ response = self.client.post(
+ self._claim_url(report),
+ data={},
+ format="json",
+ headers={"X-PostHog-Task-Id": str(task.id)},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assignment = SignalReportAssignment.all_teams.get(report=report)
+ assert assignment.actor_kind == SignalActorKind.TASK
+ assert assignment.actor_user_id is None
+ assert assignment.actor_task_id == task.id
+ assert assignment.actor_agent is None
+ assert response.json()["assignee"]["task_id"] == str(task.id)
+
+ @patch("products.signals.backend.report_assignments.GitHubIntegration.first_for_team_repository")
+ def test_connected_pull_request_details_are_fetched(self, mock_first_for_repository):
+ github = MagicMock()
+ github.get_pull_request.return_value = {
+ "success": True,
+ "url": "https://github.com/PostHog/posthog/pull/123",
+ "state": "open",
+ "draft": False,
+ "merged": False,
+ }
+ mock_first_for_repository.return_value = github
+ report = self._create_report()
+
+ response = self.client.post(
+ self._claim_url(report),
+ data={"pr_url": "https://github.com/PostHog/posthog/pull/123"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ mock_first_for_repository.assert_called_once_with(self.team.id, "PostHog/posthog")
+ github.get_pull_request.assert_called_once_with("PostHog/posthog", 123)
+ assignment = SignalReportAssignment.all_teams.get(report=report)
+ assert assignment.repository == "posthog/posthog"
+ assert assignment.pr_number == 123
+ assert assignment.pr_state == SignalReportAssignment.PrState.OPEN
+ assert assignment.pr_merged is False
+ assert response.json()["work_state"] == "in_review"
+
+ @patch("products.signals.backend.report_assignments.GitHubIntegration.first_for_team_repository")
+ def test_merged_pull_request_resolves_report_on_claim(self, mock_first_for_repository):
+ github = MagicMock()
+ github.get_pull_request.return_value = {
+ "success": True,
+ "url": "https://github.com/PostHog/posthog/pull/123",
+ "state": "closed",
+ "draft": False,
+ "merged": True,
+ }
+ mock_first_for_repository.return_value = github
+ report = self._create_report()
+
+ response = self.client.post(
+ self._claim_url(report),
+ data={"pr_url": "https://github.com/PostHog/posthog/pull/123"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ report.refresh_from_db()
+ assignment = SignalReportAssignment.all_teams.get(report=report)
+ assert report.status == SignalReport.Status.RESOLVED
+ assert assignment.pr_state == SignalReportAssignment.PrState.MERGED
+ assert assignment.pr_merged is True
+ assert response.json()["work_state"] == "done"
+
+ @patch(
+ "products.signals.backend.report_assignments.GitHubIntegration.first_for_team_repository",
+ return_value=None,
+ )
+ def test_unconnected_pull_request_is_allowed_with_unknown_state(self, mock_first_for_repository):
+ report = self._create_report()
+
+ response = self.client.post(
+ self._claim_url(report),
+ data={"pr_url": "https://github.com/PostHog/posthog/pull/123"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ mock_first_for_repository.assert_called_once_with(self.team.id, "PostHog/posthog")
+ assignment = SignalReportAssignment.all_teams.get(report=report)
+ assert assignment.repository == "posthog/posthog"
+ assert assignment.pr_number == 123
+ assert assignment.pr_state == SignalReportAssignment.PrState.UNKNOWN
+ assert assignment.pr_merged is False
+
+ def test_only_current_actor_can_release_and_pr_is_preserved(self):
+ report = self._create_report()
+ claim = self.client.post(
+ self._claim_url(report),
+ data={"pr_url": "https://github.com/PostHog/posthog/pull/123"},
+ format="json",
+ headers=self._agent_headers("claude-code"),
+ )
+ assert claim.status_code == status.HTTP_200_OK
+
+ rejected = self.client.post(
+ self._claim_url(report),
+ data={"release": True},
+ format="json",
+ headers=self._agent_headers("codex"),
+ )
+ assert rejected.status_code == status.HTTP_409_CONFLICT
+
+ released = self.client.post(
+ self._claim_url(report),
+ data={"release": True},
+ format="json",
+ headers=self._agent_headers("claude-code"),
+ )
+
+ assert released.status_code == status.HTTP_200_OK
+ assignment = SignalReportAssignment.all_teams.get(report=report)
+ assert assignment.actor_kind is None
+ assert assignment.actor_user_id is None
+ assert assignment.actor_agent is None
+ assert assignment.pr_url == "https://github.com/PostHog/posthog/pull/123"
+ assert assignment.pr_state == SignalReportAssignment.PrState.UNKNOWN
+ assert released.json()["work_state"] == "in_review"
+ assert released.json()["assignee"] is None
+
+ @parameterized.expand(
+ [
+ ("negative_number", "https://github.com/PostHog/posthog/pull/-5"),
+ ("zero_number", "https://github.com/PostHog/posthog/pull/0"),
+ ("number_above_bigint", "https://github.com/PostHog/posthog/pull/99999999999999999999999"),
+ ("overlong_repository", f"https://github.com/{'o' * 300}/posthog/pull/5"),
+ ]
+ )
+ def test_unstorable_pull_request_url_is_rejected(self, _name: str, pr_url: str):
+ report = self._create_report()
+
+ response = self.client.post(self._claim_url(report), data={"pr_url": pr_url}, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "pr_url" in response.json()["attr"]
+ assert not SignalReportAssignment.all_teams.filter(report=report).exists()
+
+ def test_release_and_pr_url_cannot_be_combined(self):
+ report = self._create_report()
+
+ response = self.client.post(
+ self._claim_url(report),
+ data={"release": True, "pr_url": "https://github.com/PostHog/posthog/pull/123"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert not SignalReportAssignment.all_teams.filter(report=report).exists()
+
+ @parameterized.expand(
+ [
+ ("ready", SignalReport.Status.READY),
+ ("pending_input", SignalReport.Status.PENDING_INPUT),
+ ("potential", SignalReport.Status.POTENTIAL),
+ ("candidate", SignalReport.Status.CANDIDATE),
+ ("in_progress", SignalReport.Status.IN_PROGRESS),
+ ("failed", SignalReport.Status.FAILED),
+ ]
+ )
+ def test_claimable_report_statuses(self, _name: str, report_status: str):
+ report = self._create_report(report_status=report_status)
+
+ response = self.client.post(self._claim_url(report), data={}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert SignalReportAssignment.all_teams.filter(report=report).exists()
+
+ def test_resolved_report_cannot_be_claimed(self):
+ report = self._create_report(report_status=SignalReport.Status.RESOLVED)
+
+ response = self.client.post(self._claim_url(report), data={}, format="json")
+
+ assert response.status_code == status.HTTP_409_CONFLICT
+ assert not SignalReportAssignment.all_teams.filter(report=report).exists()
+
+ def test_suppressed_report_cannot_be_claimed(self):
+ report = self._create_report(report_status=SignalReport.Status.SUPPRESSED)
+
+ response = self.client.post(self._claim_url(report), data={}, format="json")
+
+ assert response.status_code == status.HTTP_409_CONFLICT
+ assert not SignalReportAssignment.all_teams.filter(report=report).exists()
+
+ def test_claim_cannot_cross_team_boundary(self):
+ other_team = Team.objects.create(organization=self.organization, name="Other team")
+ report = self._create_report(team=other_team)
+
+ response = self.client.post(self._claim_url(report), data={}, format="json")
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ assert not SignalReportAssignment.all_teams.filter(report=report).exists()
+
+ def test_unclaimed_filter_excludes_claims_and_open_prs(self):
+ unclaimed = self._create_report(title="Unclaimed")
+ claimed = self._create_report(title="Claimed")
+ in_review = self._create_report(title="In review")
+ self.client.post(self._claim_url(claimed), data={}, format="json")
+ SignalReportAssignment.all_teams.create(
+ team=self.team,
+ report=in_review,
+ pr_url="https://github.com/PostHog/posthog/pull/123",
+ repository="posthog/posthog",
+ pr_number=123,
+ pr_state=SignalReportAssignment.PrState.OPEN,
+ )
+
+ response = self.client.get(self._list_url(unclaimed="true"))
+
+ assert response.status_code == status.HTTP_200_OK
+ ids = {row["id"] for row in response.json()["results"]}
+ assert str(unclaimed.id) in ids
+ assert str(claimed.id) not in ids
+ assert str(in_review.id) not in ids
+
+ def test_assignee_me_matches_exact_external_agent(self):
+ mine = self._create_report(title="Mine")
+ other = self._create_report(title="Other")
+ self.client.post(
+ self._claim_url(mine),
+ data={},
+ format="json",
+ headers=self._agent_headers("codex"),
+ )
+ self.client.post(
+ self._claim_url(other),
+ data={},
+ format="json",
+ headers=self._agent_headers("claude-code"),
+ )
+
+ response = self.client.get(
+ self._list_url(assignee="me"),
+ headers=self._agent_headers("codex"),
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert {row["id"] for row in response.json()["results"]} == {str(mine.id)}
+
+ def test_claimed_report_remains_in_default_actionable_list(self):
+ report = self._create_report()
+ self.client.post(self._claim_url(report), data={}, format="json")
+
+ response = self.client.get(self._list_url())
+
+ assert response.status_code == status.HTTP_200_OK
+ row = next(row for row in response.json()["results"] if row["id"] == str(report.id))
+ assert row["work_state"] == "working"
diff --git a/products/signals/backend/test/test_task_run_artefacts.py b/products/signals/backend/test/test_task_run_artefacts.py
index ce2229c67d4e..48f63212bd00 100644
--- a/products/signals/backend/test/test_task_run_artefacts.py
+++ b/products/signals/backend/test/test_task_run_artefacts.py
@@ -8,7 +8,14 @@ from parameterized import parameterized
from products.signals.backend.billing import first_billable_pr_run_at
from products.signals.backend.custom_agent.persistence import create_custom_agent_ready_report
from products.signals.backend.custom_agent.schemas import CustomAgentFinalReport
-from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportTask
+from products.signals.backend.models import (
+ SignalActorKind,
+ SignalReport,
+ SignalReportArtefact,
+ SignalReportAssignment,
+ SignalReportTask,
+)
+from products.signals.backend.report_assignments import sync_task_pull_request_to_assignments
from products.signals.backend.report_generation.research import (
ActionabilityAssessment,
ActionabilityChoice,
@@ -93,6 +100,7 @@ class TestTaskRunArtefacts(BaseTest):
)
assert str(artefact.task_id) == str(task.id)
+ assert artefact.actor_kind == SignalActorKind.TASK
assert artefact.created_by_id is None
async def test_aappend_carries_run_id(self):
@@ -125,6 +133,8 @@ class TestTaskRunArtefacts(BaseTest):
assert content["run_id"] == "run-789"
assert content["product"] == "signals"
assert content["type"] == "implementation"
+ assert str(artefact.task_id) == str(task.id)
+ assert artefact.actor_kind == SignalActorKind.TASK
def test_signals_task_ids_filters_by_product_and_type(self):
report = self._report()
@@ -159,11 +169,61 @@ class TestTaskRunArtefacts(BaseTest):
report=report, task=task, relationship=TASK_RUN_TYPE_IMPLEMENTATION
).exists()
assert signals_task_ids(report_id=str(report.id), type=TASK_RUN_TYPE_IMPLEMENTATION) == [str(task.id)]
+ assignment = SignalReportAssignment.all_teams.get(report=report)
+ assert assignment.actor_kind == SignalActorKind.TASK
+ assert assignment.actor_task_id == task.id
# Idempotent on the gate row for the same task — re-recording doesn't duplicate the link.
record_implementation_task(team_id=self.team.id, report_id=str(report.id), task_id=str(task.id))
assert SignalReportTask.objects.filter(report=report, task=task).count() == 1
+ def test_task_run_pr_is_copied_to_the_assignment(self):
+ report = self._report()
+ task = self._task()
+ record_implementation_task(team_id=self.team.id, report_id=str(report.id), task_id=str(task.id))
+
+ TaskRun.objects.create(
+ team=self.team,
+ task=task,
+ status=TaskRun.Status.COMPLETED,
+ output={"pr_url": "https://github.com/PostHog/posthog/pull/42", "pr_state": "open"},
+ )
+
+ assignment = SignalReportAssignment.all_teams.get(report=report)
+ assert assignment.pr_url == "https://github.com/PostHog/posthog/pull/42"
+ assert assignment.repository == "posthog/posthog"
+ assert assignment.pr_number == 42
+ assert assignment.pr_state == SignalReportAssignment.PrState.OPEN
+
+ def test_task_pr_sync_preserves_each_assignments_existing_state(self):
+ merged_report = self._report()
+ new_report = self._report()
+ task = self._task()
+ for report in (merged_report, new_report):
+ record_implementation_task(team_id=self.team.id, report_id=str(report.id), task_id=str(task.id))
+
+ pr_url = "https://github.com/PostHog/posthog/pull/42"
+ SignalReportAssignment.all_teams.filter(report=merged_report).update(
+ pr_url=pr_url,
+ repository="posthog/posthog",
+ pr_number=42,
+ pr_state=SignalReportAssignment.PrState.MERGED,
+ pr_merged=True,
+ )
+
+ sync_task_pull_request_to_assignments(
+ team_id=self.team.id,
+ task_id=str(task.id),
+ pr_url=pr_url,
+ )
+
+ merged_assignment = SignalReportAssignment.all_teams.get(report=merged_report)
+ new_assignment = SignalReportAssignment.all_teams.get(report=new_report)
+ assert merged_assignment.pr_state == SignalReportAssignment.PrState.MERGED
+ assert merged_assignment.pr_merged is True
+ assert new_assignment.pr_state == SignalReportAssignment.PrState.UNKNOWN
+ assert new_assignment.pr_merged is False
+
def test_record_implementation_task_declared_billing_exemption_marks_report(self):
# A caller that knows its origin is PostHog-system freezes the exemption in the same
# transaction that records the task — dropping this plumbing would silently bill it.
@@ -289,6 +349,18 @@ class TestAssociatedTaskRunsFilter(BaseTest):
assert not SignalReportArtefact.objects.filter(report=report).exists()
assert self._matched_task_ids(report) == {str(task.id)}
+ def test_matches_task_associated_via_current_assignment(self):
+ report = self._report()
+ task, _run = self._task_with_run()
+ SignalReportAssignment.all_teams.create(
+ team=self.team,
+ report=report,
+ actor_kind=SignalActorKind.TASK,
+ actor_task_id=task.id,
+ )
+
+ assert self._matched_task_ids(report) == {str(task.id)}
+
def test_unions_both_sources_without_duplicate_rows(self):
report = self._report()
task, _run = self._task_with_run()
@@ -357,6 +429,18 @@ class TestReportsForTaskFilter(BaseTest):
assert not SignalReportArtefact.objects.filter(task=task).exists()
assert self._matched_report_ids(task) == {str(report.id)}
+ def test_matches_report_associated_via_current_assignment(self):
+ report = self._report()
+ task = self._task()
+ SignalReportAssignment.all_teams.create(
+ team=self.team,
+ report=report,
+ actor_kind=SignalActorKind.TASK,
+ actor_task_id=task.id,
+ )
+
+ assert self._matched_report_ids(task) == {str(report.id)}
+
def test_unions_both_sources_without_duplicate_rows(self):
report = self._report()
task = self._task()
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 836b01b58acd..a80335624f0e 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -99,16 +99,17 @@ from products.signals.backend.facade.api import emit_signal
from products.signals.backend.feedback_notes import forward_feedback_note
from products.signals.backend.implementation_pr import (
fetch_implementation_pr_state_for_reports,
- fetch_implementation_pr_urls_for_reports,
pr_bearing_task_run_filter,
)
from products.signals.backend.models import (
ArtefactAttribution,
AutonomyPriority,
InvalidStatusTransition,
+ SignalActorKind,
SignalReport,
SignalReportAction,
SignalReportArtefact,
+ SignalReportAssignment,
SignalReportRefund,
SignalSourceConfig,
SignalTeamConfig,
@@ -116,6 +117,7 @@ from products.signals.backend.models import (
)
from products.signals.backend.quota import self_driving_quota_enforcement_enabled, self_driving_quota_gate
from products.signals.backend.repo_corrections import sanitized_repository
+from products.signals.backend.report_assignments import InvalidPullRequestUrl, ReportClaimConflict, claim_report
from products.signals.backend.report_generation.research import ActionabilityChoice
from products.signals.backend.report_generation.resolve_reviewers import (
get_org_member_github_login_to_user_map,
@@ -140,6 +142,7 @@ from products.signals.backend.serializers import (
SignalReportArtefactSerializer,
SignalReportArtefactWriteResponseSerializer,
SignalReportArtefactWriteSerializer,
+ SignalReportClaimSerializer,
SignalReportRefundSerializer,
SignalReportSerializer,
SignalSourceConfigSerializer,
@@ -873,6 +876,8 @@ class SignalReportViewSet(
qs = self._apply_signal_report_scout_filter(qs)
qs = self._apply_signal_report_scout_prefix_filter(qs)
qs = self._apply_signal_report_implementation_pr_filter(qs)
+ qs = self._apply_signal_report_unclaimed_filter(qs)
+ qs = self._apply_signal_report_assignee_filter(qs)
qs = self._apply_signal_report_channel_filter(qs)
qs = self._apply_signal_report_suggested_reviewer_filter(qs)
qs = self._apply_signal_report_inbox_scope_filter(qs)
@@ -887,11 +892,10 @@ class SignalReportViewSet(
qs = self._prefetch_signal_report_priority_artefacts(qs)
qs = self._annotate_is_suggested_reviewer(qs)
if self.action not in self._MULTI_REPORT_ACTIONS:
- # Both of these are correlated subqueries, so they cost one walk per row the query
- # matches. The multi-row actions do without them: `list` serves the same two values
- # from batched lookups over the page it returns, and `bulk_state` renders no report.
+ # This correlated subquery costs one walk per matching row. Multi-row actions do
+ # without it: `list` serves the value from a batched page lookup, and `bulk_state`
+ # renders no report.
qs = annotate_first_billable_pr_run_at(qs)
- qs = self._annotate_implementation_pr_url(qs)
return qs
def _scope_signal_report_queryset(self, queryset):
@@ -920,10 +924,10 @@ class SignalReportViewSet(
.values("live_channel_id")[:1],
output_field=models.UUIDField(),
)
- # select_related("refund"): the serializer renders the reverse OneToOne inline.
+ # The serializer renders the reverse OneToOne rows inline.
return (
queryset.filter(team=self.team)
- .select_related("refund")
+ .select_related("refund", "assignment", "assignment__actor_user")
.annotate(
artefact_count=Coalesce(artefact_count_subquery, Value(0), output_field=IntegerField()),
channel_id=channel_id_subquery,
@@ -952,7 +956,18 @@ class SignalReportViewSet(
# open like any other. `pr_checks` and `pr_comments` are there because that same view renders the
# read-only PR panel whatever the report's status is.
_SUPPRESSED_VISIBLE_ACTIONS = frozenset(
- {"state", "bulk_state", "retrieve", "signals", "refund", "feedback", "viewed", "pr_checks", "pr_comments"}
+ {
+ "state",
+ "bulk_state",
+ "retrieve",
+ "signals",
+ "refund",
+ "feedback",
+ "viewed",
+ "pr_checks",
+ "pr_comments",
+ "claim",
+ }
)
# Human-readable explanation per bulk outcome, surfaced in each result's `detail` field
@@ -1119,18 +1134,15 @@ class SignalReportViewSet(
).filter(~has_newer)
def _implementation_pr_report_filter(self):
- # Reports with a shipped implementation PR, as a `Q` on `SignalReport.id`. Decorrelated:
- # starts from the (small, index-backed) set of this team's tasks whose runs carry a non-empty
- # `pr_url` and maps them to reports via the indexed `task_id` columns — instead of a correlated
- # `Exists` over `tasks.TaskRun` evaluated once per candidate report (which made the inbox
- # PR-tab count scan the whole `ready` set per PR'd run).
- return SignalReport.reports_for_task_ids_filter(
+ assignment_pr = Q(assignment__pr_url__isnull=False) & ~Q(assignment__pr_url="")
+ task_pr = SignalReport.reports_for_task_ids_filter(
tasks_facade.task_ids_with_pr_url_subquery(self.team.id, pr_bearing_task_run_filter()),
team_id=self.team.id,
)
+ return assignment_pr | task_pr
def _apply_signal_report_implementation_pr_filter(self, queryset):
- # `has_implementation_pr=true|false` filters reports by whether a shipped
+ # `has_implementation_pr=true|false` filters reports by whether an attached
# implementation PR exists. Lets the inbox count PR reports (the "Pull
# requests" tab) with a cheap count query instead of paging the whole list
# and filtering client-side. Absent or empty param leaves the list
@@ -1150,6 +1162,66 @@ class SignalReportViewSet(
pr_filter = self._implementation_pr_report_filter()
return queryset.filter(pr_filter) if wants_pr else queryset.exclude(pr_filter)
+ def _apply_signal_report_unclaimed_filter(self, queryset):
+ raw = self.request.query_params.get("unclaimed")
+ if raw is None or not raw.strip():
+ return queryset
+ value = raw.strip().lower()
+ if value in ("1", "true", "yes"):
+ wants_unclaimed = True
+ elif value in ("0", "false", "no"):
+ wants_unclaimed = False
+ else:
+ raise serializers.ValidationError({"unclaimed": f"Invalid value: {raw!r}. Allowed: true, false."})
+ has_review_pr = Q(
+ assignment__pr_url__isnull=False,
+ assignment__pr_state__in=[
+ SignalReportAssignment.PrState.UNKNOWN,
+ SignalReportAssignment.PrState.DRAFT,
+ SignalReportAssignment.PrState.OPEN,
+ ],
+ ) & ~Q(assignment__pr_url="")
+ task_pr = SignalReport.reports_for_task_ids_filter(
+ tasks_facade.task_ids_with_pr_url_subquery(self.team.id, pr_bearing_task_run_filter()),
+ team_id=self.team.id,
+ )
+ is_unclaimed = (
+ ~Q(status=SignalReport.Status.RESOLVED) & Q(assignment__actor_kind__isnull=True) & ~has_review_pr & ~task_pr
+ )
+ return queryset.filter(is_unclaimed) if wants_unclaimed else queryset.exclude(is_unclaimed)
+
+ def _apply_signal_report_assignee_filter(self, queryset):
+ raw = self.request.query_params.get("assignee")
+ if raw is None or not raw.strip():
+ return queryset
+ if raw.strip().lower() != "me":
+ raise serializers.ValidationError({"assignee": "Invalid value. Allowed: me."})
+ actor = self._request_attribution()
+ # The tenant bound sits on the report side of the join, and Postgres derives no equality
+ # between the two team columns. Repeating it on the assignment binds the leading column of
+ # the actor indexes, which turns a full index scan into a seek. An assignment always
+ # carries its report's team, so this narrows nothing.
+ if actor.kind == "user":
+ return queryset.filter(
+ assignment__team_id=self.team_id,
+ assignment__actor_kind=actor.kind,
+ assignment__actor_user_id=actor.user_id,
+ )
+ if actor.kind == "task":
+ return queryset.filter(
+ assignment__team_id=self.team_id,
+ assignment__actor_kind=actor.kind,
+ assignment__actor_task_id=actor.task_id,
+ )
+ if actor.kind == "agent":
+ return queryset.filter(
+ assignment__team_id=self.team_id,
+ assignment__actor_kind=actor.kind,
+ assignment__actor_user_id=actor.user_id,
+ assignment__actor_agent=actor.agent_name,
+ )
+ return queryset.filter(assignment__team_id=self.team_id, assignment__actor_kind=SignalActorKind.SYSTEM)
+
def _apply_signal_report_channel_filter(self, queryset):
# `channel_id=<uuid>` narrows to reports assigned to one space. Absent or empty
# leaves the list unchanged (the general view lists every report); a non-UUID is a 400.
@@ -1460,25 +1532,6 @@ class SignalReportViewSet(
),
)
- def _annotate_implementation_pr_url(self, queryset):
- # Latest TaskRun output->pr_url across the tasks associated with each report, unified over
- # the task_run artefact log + legacy SignalReportTask rows (see associated_task_runs_filter).
- # The non-empty-pr_url filter inside the facade subquery is what narrows "any associated
- # task" to the one that opened the report's PR.
- latest_impl_pr_url = tasks_facade.latest_task_run_pr_url_subquery(
- SignalReport.associated_task_runs_filter(OuterRef(OuterRef("id"))),
- pr_bearing_task_run_filter(),
- )
- # Resolved over the same run, so the merge flag always describes the PR URL alongside it.
- latest_impl_pr_merged = tasks_facade.latest_task_run_pr_merged_subquery(
- SignalReport.associated_task_runs_filter(OuterRef(OuterRef("id"))),
- pr_bearing_task_run_filter(),
- )
- return queryset.annotate(
- implementation_pr_url=latest_impl_pr_url,
- implementation_pr_merged=latest_impl_pr_merged,
- )
-
def filter_queryset(self, queryset):
queryset = super().filter_queryset(queryset)
if self.action != "list":
@@ -1543,11 +1596,8 @@ class SignalReportViewSet(
}
def _enriched_report_context(self, report: SignalReport) -> dict:
- # Detail-view parity with list(): inject the source-product and PR-url maps the
- # SignalReportSerializer reads, so single-report responses aren't silently degraded.
- # Both lookups are best-effort: the serializer degrades to empty values when a map
- # is missing, so a ClickHouse/Postgres hiccup must not turn an otherwise-available
- # report (or an already-committed state change) into a 500.
+ # Detail-view parity with list(): inject the source metadata map the serializer reads.
+ # This lookup is best-effort so a ClickHouse failure cannot hide the report.
report_ids = [str(report.id)]
try:
signal_meta_map = fetch_source_products_for_reports(self.team, report_ids)
@@ -1557,13 +1607,14 @@ class SignalReportViewSet(
try:
implementation_pr_by_report = fetch_implementation_pr_state_for_reports(report_ids)
except Exception:
- logger.exception("signals.enriched_context.implementation_pr_url_failed", report_id=str(report.id))
+ logger.exception("signals.enriched_context.implementation_pr_failed", report_id=str(report.id))
implementation_pr_by_report = {}
return {
**self.get_serializer_context(),
"source_products_map": {rid: meta.source_products for rid, meta in signal_meta_map.items()},
"scout_names_map": {rid: meta.scout_name for rid, meta in signal_meta_map.items() if meta.scout_name},
"implementation_pr_url_map": {rid: pr.url for rid, pr in implementation_pr_by_report.items()},
+ "implementation_pr_state_map": {rid: pr.state for rid, pr in implementation_pr_by_report.items()},
"implementation_pr_merged_ids": {rid for rid, pr in implementation_pr_by_report.items() if pr.merged},
}
@@ -1572,6 +1623,48 @@ class SignalReportViewSet(
serializer = self.get_serializer(report, context=self._enriched_report_context(report))
return Response(serializer.data)
+ @extend_schema(
+ request=SignalReportClaimSerializer,
+ responses={
+ 200: OpenApiResponse(response=SignalReportSerializer, description="Current report and assignment."),
+ 400: OpenApiResponse(description="The pull request URL or request shape is invalid."),
+ 409: OpenApiResponse(description="The report cannot be claimed or released in its current state."),
+ },
+ summary="Claim or release a signal report",
+ description=(
+ "Claim a report for the current user, internal task, or external MCP agent. A later claim "
+ "silently takes over ownership. Supply pr_url to attach or replace the report's pull request, "
+ "or release=true to clear only ownership while preserving the pull request."
+ ),
+ operation_id="signals_reports_claim",
+ )
+ @action(detail=True, methods=["post"], url_path="claim", required_scopes=["task:write"])
+ def claim(self, request: Request, *args, **kwargs) -> Response:
+ request_serializer = SignalReportClaimSerializer(data=request.data)
+ request_serializer.is_valid(raise_exception=True)
+ report = cast(SignalReport, self.get_object())
+ data = request_serializer.validated_data
+ try:
+ claim_report(
+ report=report,
+ actor=self._request_attribution(),
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ pr_url=data.get("pr_url"),
+ release=data["release"],
+ )
+ except InvalidPullRequestUrl as err:
+ raise serializers.ValidationError({"pr_url": str(err)})
+ except ReportClaimConflict as err:
+ return Response({"detail": str(err)}, status=status.HTTP_409_CONFLICT)
+
+ updated_report = self._scope_signal_report_queryset(SignalReport.objects.all()).get(id=report.id)
+ response_serializer = self.get_serializer(
+ updated_report,
+ context=self._enriched_report_context(updated_report),
+ )
+ return Response(response_serializer.data)
+
@validated_request(
request_serializer=SignalReportContentUpdateSerializer,
responses={
@@ -1832,11 +1925,29 @@ class SignalReportViewSet(
location=OpenApiParameter.QUERY,
required=False,
description=(
- "Filter reports by whether a shipped implementation pull request exists. "
+ "Filter reports by whether an implementation pull request is attached. "
"'true' keeps only reports with a PR; 'false' keeps only those without. "
"Pair with count_only=true to return only the filtered total."
),
),
+ OpenApiParameter(
+ name="unclaimed",
+ type=OpenApiTypes.BOOL,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description=(
+ "Filter by whether the report has no owner and no draft, open, or unknown PR. "
+ "Resolved reports are never unclaimed."
+ ),
+ ),
+ OpenApiParameter(
+ name="assignee",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ enum=["me"],
+ description="Use 'me' to return reports claimed by the current user, task, or MCP agent.",
+ ),
OpenApiParameter(
name="count_only",
type=OpenApiTypes.BOOL,
@@ -1890,9 +2001,8 @@ class SignalReportViewSet(
"signals.reports.list.has_next_page", page_offset + len(report_ids) < total_count
)
- # Both lookups are best-effort decorative metadata (source-product badges, scout names, PR
- # urls). The serializer degrades to empty values when a map is missing, so a ClickHouse or
- # backend hiccup in either must not 500 the whole inbox load — fall back to empty and log.
+ # Source metadata is decorative. The serializer degrades to empty values when ClickHouse is
+ # unavailable, so a metadata failure does not hide otherwise available reports.
with tracer.start_as_current_span("signals.reports.list.fetch_source_products"):
try:
signal_meta_map = fetch_source_products_for_reports(self.team, report_ids) if report_ids else {}
@@ -1900,23 +2010,23 @@ class SignalReportViewSet(
logger.exception("signals.reports.list.source_products_failed", report_count=len(report_ids))
signal_meta_map = {}
- with tracer.start_as_current_span("signals.reports.list.fetch_implementation_pr_urls"):
+ with tracer.start_as_current_span("signals.reports.list.fetch_implementation_prs"):
try:
implementation_pr_by_report = fetch_implementation_pr_state_for_reports(report_ids)
except Exception:
- logger.exception("signals.reports.list.implementation_pr_url_failed", report_count=len(report_ids))
+ logger.exception("signals.reports.list.implementation_pr_failed", report_count=len(report_ids))
implementation_pr_by_report = {}
# One grouped query for the whole page, in place of the per-row annotation the other
# actions carry, for the serializer's refund_ineligibility_reason field.
with tracer.start_as_current_span("signals.reports.list.fetch_billable_pr_runs"):
first_billable_pr_run_at_map = first_billable_pr_run_at_by_report(report_ids)
-
context = {
**self.get_serializer_context(),
"source_products_map": {rid: meta.source_products for rid, meta in signal_meta_map.items()},
"scout_names_map": {rid: meta.scout_name for rid, meta in signal_meta_map.items() if meta.scout_name},
"implementation_pr_url_map": {rid: pr.url for rid, pr in implementation_pr_by_report.items()},
+ "implementation_pr_state_map": {rid: pr.state for rid, pr in implementation_pr_by_report.items()},
"implementation_pr_merged_ids": {rid for rid, pr in implementation_pr_by_report.items() if pr.merged},
"first_billable_pr_run_at_map": first_billable_pr_run_at_map,
}
@@ -2846,10 +2956,12 @@ class SignalReportViewSet(
def _resolve_report_pr_reference(self, report: SignalReport) -> tuple[str, int] | None:
"""Resolve a report's implementation PR to ``(owner/repo, pr_number)``, or None if it has none
(or the stored URL isn't a parseable GitHub PR URL)."""
- pr_url = fetch_implementation_pr_urls_for_reports([str(report.id)]).get(str(report.id))
- if not pr_url:
+ assignment = getattr(report, "assignment", None)
+ if assignment is None or not assignment.pr_url:
return None
- parsed = GitHubIntegration.parse_pull_request_url(pr_url)
+ if assignment.repository and assignment.pr_number:
+ return assignment.repository, assignment.pr_number
+ parsed = GitHubIntegration.parse_pull_request_url(assignment.pr_url)
if parsed is None:
return None
return parsed.repository, parsed.number
@@ -2869,7 +2981,7 @@ class SignalReportViewSet(
summary="Fetch CI checks for a report's implementation PR",
description=(
"Fetch the CI status (GitHub Actions check runs and legacy commit statuses) of the pull "
- "request the report's implementation task opened, via the team's GitHub integration."
+ "request attached to the report, via the team's GitHub integration."
),
operation_id="signals_report_pr_checks",
)
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 6db4a8611e48..75053a8d4a77 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -104,6 +104,55 @@ export interface ReportChartApi {
size?: SizeEnumApi | null
}
+export type SignalReportAssignmentPrStateEnumApi =
+ (typeof SignalReportAssignmentPrStateEnumApi)[keyof typeof SignalReportAssignmentPrStateEnumApi]
+
+export const SignalReportAssignmentPrStateEnumApi = {
+ Unknown: 'unknown',
+ Draft: 'draft',
+ Open: 'open',
+ Closed: 'closed',
+ Merged: 'merged',
+} as const
+
+export type SignalReportWorkStateEnumApi =
+ (typeof SignalReportWorkStateEnumApi)[keyof typeof SignalReportWorkStateEnumApi]
+
+export const SignalReportWorkStateEnumApi = {
+ Unclaimed: 'unclaimed',
+ Working: 'working',
+ InReview: 'in_review',
+ Done: 'done',
+} as const
+
+export type SignalActorKindEnumApi = (typeof SignalActorKindEnumApi)[keyof typeof SignalActorKindEnumApi]
+
+export const SignalActorKindEnumApi = {
+ User: 'user',
+ Task: 'task',
+ Agent: 'agent',
+ System: 'system',
+} as const
+
+export interface _UserApi {
+ readonly id: number
+ readonly uuid: string
+ readonly first_name: string
+ readonly last_name: string
+ readonly email: string
+}
+
+export interface SignalReportAssigneeApi {
+ kind: SignalActorKindEnumApi
+ user: _UserApi | null
+ /** @nullable */
+ task_id: string | null
+ /** @nullable */
+ agent: string | null
+ /** @nullable */
+ claimed_at: string | null
+}
+
/**
* * `pr_incorrect` - PR incorrect
* * `pr_not_useful` - PR not useful
@@ -241,12 +290,18 @@ export interface SignalReportApi {
*/
readonly scout_name: string | null
/**
- * PR URL from the latest implementation task run, if available.
+ * Pull request attached to this report's claim, if available.
* @nullable
*/
readonly implementation_pr_url: string | null
+ /** Latest known pull request state: unknown, draft, open, closed, or merged. */
+ readonly implementation_pr_state: SignalReportAssignmentPrStateEnumApi | null
/** Whether that implementation PR is merged, per the GitHub webhook. False when there is no PR or it hasn't merged. Report status doesn't imply this: a resolved report may have been resolved directly, without a merged PR. */
readonly implementation_pr_merged: boolean
+ /** Derived remediation state: unclaimed, working, in_review, or done. */
+ readonly work_state: SignalReportWorkStateEnumApi
+ /** Current user, internal task, or external agent claim owner. Null when unclaimed. */
+ readonly assignee: SignalReportAssigneeApi | null
/** The report's PR refund, when one exists. One refund per report, ever. */
readonly refund: SignalReportRefundApi | null
/** Why refunding this report's PR would be rejected right now, or null when a refund would be accepted (see the field's schema for the reason values). */
@@ -295,6 +350,13 @@ export interface PatchedSignalReportContentUpdateApi {
summary?: string
}
+export interface SignalReportClaimApi {
+ /** Optional GitHub pull request to attach to the claim. The report may be claimed without one. */
+ pr_url?: string
+ /** Release ownership while preserving any attached pull request. */
+ release?: boolean
+}
+
/**
* * `positive` - positive
* * `negative` - negative
@@ -1664,14 +1726,6 @@ export const SignalReportArtefactArtefactTypeEnumApi = {
RelatedTo: 'related_to',
} as const
-export interface _UserApi {
- readonly id: number
- readonly uuid: string
- readonly first_name: string
- readonly last_name: string
- readonly email: string
-}
-
export type SignalReportArtefactApiContent = { [key: string]: unknown } | unknown[]
export interface SignalReportArtefactApi {
@@ -1681,10 +1735,17 @@ export interface SignalReportArtefactApi {
readonly created_at: string
/** @nullable */
readonly updated_at: string | null
- /** User the artefact is attributed to, when a user produced it. Null for task/system writes. */
+ /** Actor kind. Legacy rows without attribution are returned as system. */
+ readonly actor_kind: SignalActorKindEnumApi
+ /**
+ * MCP client name when an external agent produced the artefact.
+ * @nullable
+ */
+ readonly actor_agent: string | null
+ /** Authenticated user principal for user or external agent writes. Null for internal task and system writes. */
readonly created_by: _UserApi | null
/**
- * Task the artefact is attributed to, when an agent produced it. Null for user/system writes.
+ * Internal task the artefact is attributed to. Null for user, external agent, and system writes.
* @nullable
*/
readonly task_id: string | null
@@ -4278,6 +4339,10 @@ export type SignalsReportsListParams = {
* Filter by whether the latest actionability judgment says the issue is already being handled. False also includes older reports where that judgment did not record a value.
*/
already_addressed?: boolean
+ /**
+ * Use 'me' to return reports claimed by the current user, task, or MCP agent.
+ */
+ assignee?: SignalsReportsListAssignee
/**
* Narrow to reports assigned to one space (channel). Absent or empty means all reports regardless of assignment.
*/
@@ -4287,7 +4352,7 @@ export type SignalsReportsListParams = {
*/
count_only?: boolean
/**
- * Filter reports by whether a shipped implementation pull request exists. 'true' keeps only reports with a PR; 'false' keeps only those without. Pair with count_only=true to return only the filtered total.
+ * Filter reports by whether an implementation pull request is attached. 'true' keeps only reports with a PR; 'false' keeps only those without. Pair with count_only=true to return only the filtered total.
*/
has_implementation_pr?: boolean
/**
@@ -4354,6 +4419,10 @@ export type SignalsReportsListParams = {
* PostHog user UUID used when scope=teammate.
*/
teammate_uuid?: string
+ /**
+ * Filter by whether the report has no owner and no draft, open, or unknown PR. Resolved reports are never unclaimed.
+ */
+ unclaimed?: boolean
/**
* When true and priority is omitted, include priorities at or above the requesting user's personal PR-generation threshold, falling back to the project threshold.
*/
@@ -4364,6 +4433,12 @@ export type SignalsReportsListParams = {
view?: string
}
+export type SignalsReportsListAssignee = (typeof SignalsReportsListAssignee)[keyof typeof SignalsReportsListAssignee]
+
+export const SignalsReportsListAssignee = {
+ Me: 'me',
+} as const
+
export type SignalsReportArtefactsListParams = {
/**
* Number of results to return per page.
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 64c4d2fa20e3..a20a95c8dc74 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -60,6 +60,7 @@ import type {
SignalReportArtefactWriteResponseApi,
SignalReportBulkStateRequestApi,
SignalReportBulkStateResponseApi,
+ SignalReportClaimApi,
SignalReportFeedbackRequestApi,
SignalReportFeedbackResponseApi,
SignalReportRefundRequestApi,
@@ -240,6 +241,28 @@ export const signalsReportsPartialUpdate = async (
})
}
+export const getSignalsReportsClaimUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/reports/${id}/claim/`
+}
+
+/**
+ * Claim a report for the current user, internal task, or external MCP agent. A later claim silently takes over ownership. Supply pr_url to attach or replace the report's pull request, or release=true to clear only ownership while preserving the pull request.
+ * @summary Claim or release a signal report
+ */
+export const signalsReportsClaim = async (
+ projectId: string,
+ id: string,
+ signalReportClaimApi?: SignalReportClaimApi,
+ options?: RequestInit
+): Promise<SignalReportApi> => {
+ return apiMutator<SignalReportApi>(getSignalsReportsClaimUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(signalReportClaimApi),
+ })
+}
+
export const getSignalsReportsFeedbackCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/signals/reports/${id}/feedback/`
}
@@ -267,7 +290,7 @@ export const getSignalsReportPrChecksUrl = (projectId: string, id: string) => {
}
/**
- * Fetch the CI status (GitHub Actions check runs and legacy commit statuses) of the pull request the report's implementation task opened, via the team's GitHub integration.
+ * Fetch the CI status (GitHub Actions check runs and legacy commit statuses) of the pull request attached to the report, via the team's GitHub integration.
* @summary Fetch CI checks for a report's implementation PR
*/
export const signalsReportPrChecks = async (
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 1b2ac55a33ea..3913f6f76c6a 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -47,6 +47,23 @@ export const SignalsReportsPartialUpdateBody = /* @__PURE__ */ zod
'Editable human-facing fields on a signal report (PATCH).\n\nBoth fields are optional so a caller can change either independently, but at least one\nmust be supplied. Every other report field — status, weights, judgments — is owned by the\nsignals pipeline and is deliberately not writable here.'
)
+/**
+ * Claim a report for the current user, internal task, or external MCP agent. A later claim silently takes over ownership. Supply pr_url to attach or replace the report's pull request, or release=true to clear only ownership while preserving the pull request.
+ * @summary Claim or release a signal report
+ */
+export const signalsReportsClaimBodyReleaseDefault = false
+
+export const SignalsReportsClaimBody = /* @__PURE__ */ zod.object({
+ pr_url: zod
+ .url()
+ .optional()
+ .describe('Optional GitHub pull request to attach to the claim. The report may be claimed without one.'),
+ release: zod
+ .boolean()
+ .default(signalsReportsClaimBodyReleaseDefault)
+ .describe('Release ownership while preserving any attached pull request.'),
+})
+
/**
* Record the thumbs rating at the end of a report, with an optional note. For browser-session requests the rating is persisted as a per-person report action, which counts as consumption evidence for the scout that authored the report (scouts whose output nobody consumes are eventually paused); requests authenticated any other way record no action. When a note is present and the report was authored by a scout, the note is also forwarded to that scout as a steering note it reads on its next run; for any other report there is nothing to steer. The report's state is never changed.
* @summary Leave feedback on a report
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index e07ab6acf845..e94a4ee85a7a 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -127,6 +127,30 @@ tools:
`results` (one entry per id, in request order) and the `transitioned_count` / `skipped_count` /
`failed_count` / `not_found_count` summary. An id whose transition isn't allowed from its current status
comes back as `skipped` (the single-report 409) while the rest still go through.
+ inbox-reports-claim:
+ operation: signals_reports_claim
+ enabled: true
+ scopes:
+ - task:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ enrich_url: '{id}'
+ title: Claim or release a signal report
+ description: >
+ Claim a potential, candidate, in_progress, pending_input, ready, or failed report before working on it.
+ Calling this again as another actor silently takes over the claim. Optionally pass `pr_url` to attach or
+ replace one GitHub pull request; the report does not need a pull request to be claimed or resolved. Pass
+ `release=true` to clear only ownership; the attached pull request is kept, so sending `pr_url` in the same
+ call is rejected. Only the current owner can release a claim. A connected repository is checked immediately;
+ an unconnected GitHub pull request is accepted with unknown state and will not receive webhook updates. A
+ pull request that the check finds already merged resolves the report, and one already closed dismisses it.
+ Returns the full report with work_state, assignee, and pull request fields.
+ param_overrides:
+ id:
+ aliases:
+ - report_id
inbox-reports-list:
operation: signals_reports_list
enabled: true
@@ -143,28 +167,29 @@ tools:
List signal reports for the current project. A signal report is a cluster of related observations (signals)
that PostHog has aggregated into a single issue or trend. Reports surface in the Inbox. Supports filtering
by status (potential, candidate, in_progress, pending_input, ready, resolved, failed, suppressed), free-text
- search across title and summary, source_product (e.g. error_tracking, session_replay), suggested_reviewers
- (PostHog user UUIDs), and task_id (only reports associated with that task — pass your own task id to see
- which reports you are already working against). Some statuses are hidden by default (currently suppressed,
- i.e. human-dismissed); pass `include_all_statuses=true` to list reports in every status — do this when
- deduplicating against the full inbox state, and read each row's `status` (plus `dismissal_reason` /
+ search across title and summary, source_product (e.g. error_tracking, session_replay), suggested_reviewers,
+ `unclaimed`, and `assignee=me`. Claimed reports remain actionable and visible; use `unclaimed=true` to pick
+ work that has no owner and no draft, open, or unknown PR. Some statuses are hidden by default (currently
+ suppressed, i.e. human-dismissed); pass `include_all_statuses=true` to list reports in every status. Do this
+ when deduplicating against the full inbox state, and read each row's `status` (plus `dismissal_reason` /
`dismissal_note` on dismissed rows) before acting. For picking up work, filter to `ready` — earlier statuses
are still moving through the pipeline, and `pending_input` reports are waiting on a human. Each report's
- full work log — signal findings (evidence), judgments, and log entries — is readable via
+ full work log, including signal findings, judgments, and log entries, is readable via
inbox-report-artefacts-list; read it before acting on a report. Results are paginated and ordered by
'-is_suggested_reviewer,status,-updated_at' by default. To find the self-driving reports for one source
record — e.g. what the inbox already investigated for a specific support ticket — pass that record's id as
`source_id` together with exactly one `source_product` (for a support ticket: `source_product=conversations`
and the ticket's UUID as `source_id`); add `include_all_statuses=true` to include dismissed ones.
- agent_note:
- "If you do ANY work connected to one of these reports — even pure research or investigation — always first
- associate your task with it: call inbox-report-artefacts-create with artefact_type `task_run` and content {}
- (your own task id is filled in automatically). That task_run artefact IS the task↔report association —
- commits you push are recorded on the report through it, and without it your work is invisible to the report.
- If that call fails with a 400 saying a task id is required, you simply have no task id of your own — that's
- expected, not an error to fix; skip the association and carry on. Without the write tools (a read-only
- session) ignore the association step entirely — artefact persistence is handled for you. Read the report's
- work log via inbox-report-artefacts-list before acting."
+ agent_note: >
+ You may inspect reports without claiming them. A claim indicates active work that should not be duplicated.
+ Before claiming a report, read the report and its work log. If you decide to begin working to fix the issues
+ identified in the report, call inbox-reports-claim to record that you are working on it. A later claim can
+ replace the current owner.
+
+ If you create a pull request implementing the remediation, call inbox-reports-claim again with `pr_url` to
+ attach it. Release the claim if you stop work without completing the report. If the report should be
+ considered resolved without a pull request, or PostHog cannot observe the pull request merge, resolve it
+ with inbox-reports-set-state.
response:
include:
- id
@@ -181,6 +206,10 @@ tools:
- source_products
- is_suggested_reviewer
- implementation_pr_url
+ - implementation_pr_state
+ - implementation_pr_merged
+ - work_state
+ - assignee
- created_at
- updated_at
inbox-reports-retrieve:
@@ -195,27 +224,21 @@ tools:
enrich_url: '{id}'
title: Get signal report
description: >
- Get a single signal report by ID. Returns the full report including title, summary, status, priority and
- actionability judgments, signal_count, total_weight, source products, and the URL of the implementation PR
- if one has been opened. The report's full work log — signal findings (evidence), judgments, and log entries
- — is readable via inbox-report-artefacts-list; read it before acting on the report. The raw underlying
- signals require a HogQL query (see the 'signals' skill). If you do any work prompted by this report — even
- research — first associate your task with it by appending a `task_run` artefact via
- inbox-report-artefacts-create. Report lifecycle is pipeline-managed — don't try to drive it: act on `ready`
- reports; `pending_input` means the report is waiting on human input, so surface it to a human rather than
- acting on it yourself.
- agent_note:
- "If you do ANY work connected to this report — even pure research or investigation — always first associate
- your task with it: call inbox-report-artefacts-create with artefact_type `task_run` and content {} (your own
- task id is filled in automatically). That task_run artefact IS the task↔report association — commits you
- push via git_signed_commit are recorded on the report through it, and without it your work is invisible to
- the report. If that call fails with a 400 saying a task id is required, you simply have no task id of your
- own — that's expected, not an error to fix; skip the association and continue. Then log the work as
- artefacts as you go — notes, code references, and any commit you have already pushed to a remote branch
- outside git_signed_commit (signed pushes are recorded automatically; never record a commit that is not on a
- remote branch). Status artefacts (priority, actionability, reviewers) are latest-wins — append a new version
- to re-assess. Without the write tools, work as instructed by your task — artefact persistence is handled for
- you."
+ Get a single signal report by ID. Returns the full report, including work_state, current assignee, and the
+ attached pull request and its latest known state. The report's full work log is readable via
+ inbox-report-artefacts-list; read it before acting. The raw underlying signals require a HogQL query (see
+ the 'signals' skill). Claim the report before doing work. A report may be claimed in potential, candidate,
+ in_progress, pending_input, ready, or failed state.
+ agent_note: >
+ You may inspect reports without claiming them. A claim indicates active work that should not be duplicated.
+ Before claiming a report, read the report and its work log. If you decide to begin working to fix the issues
+ identified in the report, call inbox-reports-claim to record that you are working on it. A later claim can
+ replace the current owner.
+
+ If you create a pull request implementing the remediation, call inbox-reports-claim again with `pr_url` to
+ attach it. Release the claim if you stop work without completing the report. If the report should be
+ considered resolved without a pull request, or PostHog cannot observe the pull request merge, resolve it
+ with inbox-reports-set-state.
param_overrides:
id:
aliases:
diff --git a/products/signals/skills/inbox-exploration/SKILL.md b/products/signals/skills/inbox-exploration/SKILL.md
index 2fbdd04eaf8d..f728594380ef 100644
--- a/products/signals/skills/inbox-exploration/SKILL.md
+++ b/products/signals/skills/inbox-exploration/SKILL.md
@@ -60,6 +60,7 @@ _underlying detail_ — pair them when the user wants to dig in.
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| `inbox-reports-list` | Paginated list of reports with filters (status, search, etc.) |
| `inbox-reports-retrieve` | Full detail for a single report |
+| `inbox-reports-claim` | Claim or release a report, and optionally attach its implementation PR |
| `inbox-report-artefacts-list` | A report's full work log — `signal_finding` evidence, status judgments, commits, task runs, notes (read-only) |
| `inbox-report-artefacts-retrieve` | Full detail for a single artefact (read-only) |
| `inbox-reports-set-state` | Resolve (`resolved`), dismiss (`suppressed`), or snooze (`potential`) a single report |
@@ -71,12 +72,12 @@ _underlying detail_ — pair them when the user wants to dig in.
The `inbox-reports-*-list` / `-retrieve`, `inbox-report-artefacts-list` / `-retrieve`, and
`inbox-source-configs-*-list` / `-retrieve` tools are read-only. The exposed writes are `inbox-reports-set-state` (resolve / dismiss / snooze a single report),
-`inbox-reports-bulk-set-state` (the same transition for 1–100 reports in one call) — see
+`inbox-reports-bulk-set-state` (the same transition for 1–100 reports in one call),
+`inbox-reports-claim` (claim / release / attach a PR), see
_Workflow: resolve, dismiss, or snooze a report_ — and `inbox-source-configs-partial-update`, which flips a
source's `enabled` flag on or off (e.g. `{enabled: false}` to stop a source feeding the inbox);
-`-create` / `-update` exist too for standing a source up or replacing it wholesale. Other writes
-(pause processing, set `implementation_pr_url`) are not exposed via MCP today — the PR link is
-populated on the product surface when a PR is opened against a report.
+`-create` / `-update` exist too for standing a source up or replacing it wholesale. Pausing
+processing is not exposed via MCP.
## Terminology
@@ -198,6 +199,10 @@ inbox-reports-list
If `count: 0` comes back, jump to the empty/unconfigured workflow above before saying "your
inbox is empty" — the right reply depends on whether sources are configured.
+A claimed report keeps its pipeline status, so this queue also returns work someone else already
+owns. Add `"unclaimed": true` when the user is asking what is free to pick up, and
+`"assignee": "me"` to list what the caller already owns and may want to resume.
+
### Step 2 — Summarize by source and actionability
For each report, the response includes:
@@ -211,6 +216,10 @@ For each report, the response includes:
report (see "What 'suggested reviewer' means" above — it's based on GitHub commit
authorship of the relevant code, mapped to PostHog users via linked GitHub identity)
- `implementation_pr_url` — if a PR has been opened against this report
+- `work_state` — `unclaimed`, `working`, `in_review`, or `done`
+- `assignee` — who claimed the report (a user, an internal task, or an external agent), or `null`
+ when nobody has. Say so when you list a report someone else owns, so it doesn't read as free
+ work
- `_posthogUrl` — clickable deep-link to the report; **always include this in your response**
Group the results so the user can scan quickly. **Lead with reports where
@@ -285,7 +294,7 @@ implement.** Reports from `signals_scout` (and any LLM-research source) are espe
double-checking; their `summary` often reads as a confident root-cause with file and function
names, but it can be stale or wrong.
-### Step 1 — Retrieve and check it isn't already handled
+### Step 1 — Retrieve, check existing work, and claim it
```json
inbox-reports-retrieve
@@ -297,9 +306,23 @@ Before doing any work, look at:
- `already_addressed` — if `true`, the fix may already be in flight or merged; confirm with the
user before duplicating it.
- `implementation_pr_url` — if a PR is already linked, surface it instead of opening a second one.
+- `work_state` and `assignee` — show whether someone else has already picked it up. A takeover is
+ allowed, but make it deliberate rather than overlooking active work.
- `status` — only `ready` reports carry a finished judgment. A `candidate` / `pending_input`
report hasn't been researched yet; don't implement off a half-formed summary.
+Before starting research or implementation, claim the report:
+
+```json
+posthog:inbox-reports-claim
+{ "report_id": "<report_uuid>" }
+```
+
+The claim is attributed to the current internal task or external MCP client. Claims do not expire, so
+release the report whenever you walk away without landing a fix — including when you dismiss it instead.
+Release clears ownership only; an attached pull request stays on the report, and release works from any
+status, so a dismissed report can be released too.
+
### Step 2 — Verify the diagnosis against the code (do not skip)
Start by reading the report's work log — its evidence and the judgments behind it:
@@ -317,7 +340,13 @@ way the report describes, and actually produces the described failure. As a deep
the raw underlying signals via the `signals` skill (`metadata.report_id`) if you need the signal
text behind the curated findings. If the diagnosis doesn't hold up, say so and stop — a wrong
report is itself a useful finding (and a candidate for _dismiss_ below), not a license to write a
-speculative fix.
+speculative fix. Release the claim you took in Step 1 before you stop, so the report returns to the
+unclaimed view instead of reading as active work nobody is doing:
+
+```json
+posthog:inbox-reports-claim
+{ "report_id": "<report_uuid>", "release": true }
+```
### Step 3 — Scope the fix to the right layer
@@ -329,15 +358,25 @@ speculative fix.
area-specific skills), make the change minimal, and add a regression test that would have caught
the reported failure.
-### Step 4 — Open the PR and link it back
+### Step 4 — Open the PR and attach it
+
+Open the PR following the repo's PR conventions, then attach it to the report:
+
+```json
+posthog:inbox-reports-claim
+{
+ "report_id": "<report_uuid>",
+ "pr_url": "https://github.com/example/repository/pull/123"
+}
+```
-Open the PR following the repo's PR conventions. There is no MCP tool to set
-`implementation_pr_url` — that link is populated on the product surface when a PR is opened
-against the report. So reference the report in the PR description (its `_posthogUrl`) and tell the
-user which report the PR addresses, so the loop is traceable.
+The same PR may be attached to multiple reports. Connected repositories receive immediate state
+validation and webhook updates. PRs from unconnected repositories are accepted with unknown state,
+so resolve those reports manually after the work lands. Also reference the report's `_posthogUrl`
+in the PR description so the loop is traceable from either side.
-**Don't resolve a report because you opened a PR.** When the fix ships as a PR, the merge is what
-resolves the report — the tasks GitHub webhook does it automatically. Resolving by hand at PR-open
+**Don't resolve a report because you opened a PR.** When the fix ships as a connected PR, the merge
+resolves the report automatically. Resolving by hand at PR-open
time asserts work that hasn't landed, and a reviewer looking at the inbox can't tell the difference.
Manual resolve is for fixes a PR merge will never cover — a skill-body change, a config change, a
`NO_REPO` report — see the workflow below.
@@ -488,12 +527,12 @@ inbox-source-configs-partial-update
- `suppressed` reports are excluded by default; pass `status: "suppressed"` explicitly if the
user wants to see hidden items
- The inbox writes exposed via MCP are `inbox-reports-set-state` (resolve / dismiss / snooze one
- report), `inbox-reports-bulk-set-state` (the same for 1–100 reports), and
+ report), `inbox-reports-bulk-set-state` (the same for 1–100 reports), `inbox-reports-claim`
+ (claim / release / attach a PR), and
`inbox-source-configs-partial-update` (toggle a source's `enabled` flag). To _act_ on a report
- (implement a fix), verify the diagnosis against the code first, then open a PR — see
+ (implement a fix), claim it, verify the diagnosis against the code, then open and attach a PR — see
_Workflow: act on an actionable report_. A PR-backed fix is resolved automatically when the PR
- merges, so don't resolve it by hand at PR-open time; setting `implementation_pr_url` happens on
- the product surface, not via MCP. Always also surface the `_posthogUrl` deep-link
+ merges, so don't resolve it by hand at PR-open time. Always also surface the `_posthogUrl` deep-link
- **Never implement a report's fix straight from its `summary`.** Reports — especially
`signals_scout` ones — are LLM diagnoses; confirm the cited files / functions / behavior in the
actual code before writing a fix. A report that doesn't hold up is a dismissal candidate, not a
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index c0112d7d2691..4d8560d20a36 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -270,6 +270,7 @@ POSTHOG_EXEC_DESTRUCTIVE_SUB_TOOLS: tuple[str, ...] = (
"feature-requests-remove-evidence-create",
"heatmaps-saved-regenerate",
"inbox-reports-bulk-set-state",
+ "inbox-reports-claim",
"inbox-reports-set-state",
"llma-prompt-label-set",
"opt-outs-add",
diff --git a/products/tasks/backend/facade/task_run_signals.py b/products/tasks/backend/facade/task_run_signals.py
new file mode 100644
index 000000000000..6e0944e63958
--- /dev/null
+++ b/products/tasks/backend/facade/task_run_signals.py
@@ -0,0 +1,9 @@
+from collections.abc import Callable
+
+from django.db.models.signals import post_save
+
+from products.tasks.backend.models import TaskRun
+
+
+def connect_task_run_post_save(receiver: Callable[..., None], *, dispatch_uid: str) -> None:
+ post_save.connect(receiver, sender=TaskRun, dispatch_uid=dispatch_uid)
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.py
index 4b8bace2a2c8..90e8c4e650af 100644
--- a/products/tasks/backend/tests/test_webhooks.py
+++ b/products/tasks/backend/tests/test_webhooks.py
@@ -21,8 +21,7 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.models.user_integration import UserIntegration
-from products.signals.backend.models import SignalReport
-from products.signals.backend.task_run_artefacts import append_task_run_artefact
+from products.signals.backend.models import SignalReport, SignalReportAssignment
from products.tasks.backend.facade.api import find_signal_implementation_run
from products.tasks.backend.models import Task, TaskRun, TaskThreadMessage
from products.tasks.backend.webhooks import (
@@ -1126,7 +1125,7 @@ class TestGitHubPRReviewWebhook(TestCase):
class TestGitHubPRWebhookResolvesSignalReports(TestCase):
- """Webhook resolves a SignalReport when its PR merges, and archives it when the PR closes unmerged."""
+ """GitHub PR webhooks update matching SignalReport assignments independently of tasks."""
organization: ClassVar[Organization]
team: ClassVar[Team]
@@ -1141,20 +1140,11 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
def setUp(self):
self.client = APIClient()
self.webhook_secret = "test-webhook-secret"
- self.task = Task.objects.create(
+ self.integration = Integration.objects.create(
team=self.team,
- created_by=self.user,
- title="Signal task",
- description="Implementation of a signal report",
- origin_product=Task.OriginProduct.SIGNAL_REPORT,
- repository="posthog/posthog",
- )
- self.task_run = TaskRun.objects.create(
- task=self.task,
- team=self.team,
- status=TaskRun.Status.COMPLETED,
- state={"verified_pr_urls": ["https://github.com/posthog/posthog/pull/42"]},
- output={"pr_url": "https://github.com/posthog/posthog/pull/42"},
+ kind="github",
+ integration_id="555000",
+ config={"account": {"name": "posthog"}},
)
self.report = SignalReport.objects.create(
team=self.team,
@@ -1162,12 +1152,13 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
title="Test report",
summary="Test summary",
)
- append_task_run_artefact(
- team_id=self.team.id,
- report_id=str(self.report.id),
- product="signals",
- type="implementation",
- task_id=str(self.task.id),
+ self.assignment = SignalReportAssignment.all_teams.create(
+ team=self.team,
+ report=self.report,
+ pr_url="https://github.com/posthog/posthog/pull/42",
+ repository="posthog/posthog",
+ pr_number=42,
+ pr_state=SignalReportAssignment.PrState.OPEN,
)
def _post_pr_webhook(self, action: str, merged: bool, pr_url: str = "https://github.com/posthog/posthog/pull/42"):
@@ -1176,7 +1167,10 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
"pull_request": {
"html_url": pr_url,
"merged": merged,
+ "number": int(pr_url.rstrip("/").split("/")[-1]),
},
+ "repository": {"full_name": "posthog/posthog"},
+ "installation": {"id": 555000},
}
payload_bytes = json.dumps(payload).encode("utf-8")
signature = generate_github_signature(payload_bytes, self.webhook_secret)
@@ -1192,54 +1186,65 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
[
(
"merged_pr_resolves_ready_report",
- "closed",
True,
SignalReport.Status.READY,
SignalReport.Status.RESOLVED,
+ SignalReportAssignment.PrState.MERGED,
),
(
- "closed_without_merge_archives_ready_report",
- "closed",
+ "closed_without_merge_suppresses_ready_report",
False,
SignalReport.Status.READY,
SignalReport.Status.SUPPRESSED,
+ SignalReportAssignment.PrState.CLOSED,
),
(
- "suppressed_report_is_skipped",
- "closed",
+ "merged_pr_resolves_suppressed_report",
True,
SignalReport.Status.SUPPRESSED,
- SignalReport.Status.SUPPRESSED,
+ SignalReport.Status.RESOLVED,
+ SignalReportAssignment.PrState.MERGED,
+ ),
+ (
+ "closed_pr_leaves_resolved_report_resolved",
+ False,
+ SignalReport.Status.RESOLVED,
+ SignalReport.Status.RESOLVED,
+ SignalReportAssignment.PrState.CLOSED,
),
]
)
@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_pr_event_transitions_linked_report(
- self, _name, action, merged, initial_status, expected_status, _mock_capture, mock_get_secret
+ self,
+ _name,
+ merged,
+ initial_status,
+ expected_status,
+ expected_pr_state,
+ _mock_capture,
+ mock_get_secret,
):
mock_get_secret.return_value = self.webhook_secret
if self.report.status != initial_status:
self.report.status = initial_status
self.report.save(update_fields=["status"])
- response = self._post_pr_webhook(action=action, merged=merged)
+ response = self._post_pr_webhook(action="closed", merged=merged)
self.assertEqual(response.status_code, 200)
self.report.refresh_from_db()
+ self.assignment.refresh_from_db()
self.assertEqual(self.report.status, expected_status)
- if merged:
- self.task_run.refresh_from_db()
- assert self.task_run.output is not None
- self.assertIs(self.task_run.output.get("pr_merged"), True)
+ self.assertEqual(self.assignment.pr_state, expected_pr_state)
+ self.assertIs(self.assignment.pr_merged, merged)
@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
- def test_merge_on_task_without_linked_report_is_a_noop(self, _mock_capture, mock_get_secret):
+ def test_merge_without_matching_assignment_is_a_noop(self, _mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
- from products.signals.backend.models import SignalReportArtefact
-
- SignalReportArtefact.objects.filter(task=self.task).delete()
+ self.assignment.delete()
response = self._post_pr_webhook(action="closed", merged=True)
@@ -1249,134 +1254,94 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
@parameterized.expand(
[
- ("merged", True, SignalReport.Status.RESOLVED),
- ("closed", False, SignalReport.Status.SUPPRESSED),
+ ("merged", True, SignalReport.Status.RESOLVED, SignalReportAssignment.PrState.MERGED),
+ ("closed", False, SignalReport.Status.SUPPRESSED, SignalReportAssignment.PrState.CLOSED),
]
)
@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
- def test_pr_event_transitions_report_when_pr_is_bound_to_another_task(
- self, _name, merged, expected_status, _mock_capture, mock_get_secret
+ def test_pr_event_transitions_every_report_linked_to_the_pr(
+ self, _name, merged, expected_status, expected_pr_state, _mock_capture, mock_get_secret
):
mock_get_secret.return_value = self.webhook_secret
- pr_url = "https://github.com/posthog/posthog/pull/42"
- self.task_run.state = {}
- self.task_run.save(update_fields=["state"])
- review_task = Task.objects.create(
+ second_report = SignalReport.objects.create(
team=self.team,
- created_by=self.user,
- title="Review task",
- description="Review the implementation",
- origin_product=Task.OriginProduct.REVIEW_HOG,
- repository="posthog/posthog",
+ status=SignalReport.Status.PENDING_INPUT,
+ title="Second report",
+ summary="Second summary",
)
- TaskRun.objects.create(
- task=review_task,
+ second_assignment = SignalReportAssignment.all_teams.create(
team=self.team,
- status=TaskRun.Status.COMPLETED,
- state={"verified_pr_urls": [pr_url]},
- output={"pr_url": pr_url},
+ report=second_report,
+ pr_url=self.assignment.pr_url,
+ repository=self.assignment.repository,
+ pr_number=self.assignment.pr_number,
+ pr_state=SignalReportAssignment.PrState.OPEN,
)
response = self._post_pr_webhook(action="closed", merged=merged)
self.assertEqual(response.status_code, 200)
self.report.refresh_from_db()
+ second_report.refresh_from_db()
+ self.assignment.refresh_from_db()
+ second_assignment.refresh_from_db()
self.assertEqual(self.report.status, expected_status)
- if merged:
- self.task_run.refresh_from_db()
- assert self.task_run.output is not None
- self.assertIs(self.task_run.output.get("pr_merged"), True)
+ self.assertEqual(second_report.status, expected_status)
+ self.assertEqual(self.assignment.pr_state, expected_pr_state)
+ self.assertEqual(second_assignment.pr_state, expected_pr_state)
+ self.assertIs(self.assignment.pr_merged, merged)
+ self.assertIs(second_assignment.pr_merged, merged)
@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
- def test_pr_event_does_not_transition_report_for_older_pr(self, _mock_capture, mock_get_secret):
+ def test_pr_event_does_not_transition_assignment_for_another_pr(self, _mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
- TaskRun.objects.create(
- task=self.task,
- team=self.team,
- status=TaskRun.Status.COMPLETED,
- output={"pr_url": "https://github.com/posthog/posthog/pull/99"},
- )
+ self.assignment.pr_url = "https://github.com/posthog/posthog/pull/99"
+ self.assignment.pr_number = 99
+ self.assignment.save(update_fields=["pr_url", "pr_number", "updated_at"])
response = self._post_pr_webhook(action="closed", merged=True)
self.assertEqual(response.status_code, 200)
self.report.refresh_from_db()
+ self.assignment.refresh_from_db()
self.assertEqual(self.report.status, SignalReport.Status.READY)
+ self.assertEqual(self.assignment.pr_state, SignalReportAssignment.PrState.OPEN)
+ self.assertFalse(self.assignment.pr_merged)
@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
- def test_implementation_pr_takes_priority_over_newer_discussion_pr(self, _mock_capture, mock_get_secret):
+ def test_pr_event_only_updates_teams_connected_to_the_installation(self, _mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
- discussion_task = Task.objects.create(
- team=self.team,
- created_by=self.user,
- title="Discuss report",
- description="Discuss the signal report",
- origin_product=Task.OriginProduct.SIGNAL_REPORT,
- repository="posthog/posthog",
- )
- TaskRun.objects.create(
- task=discussion_task,
- team=self.team,
- status=TaskRun.Status.COMPLETED,
- output={"pr_url": "https://github.com/posthog/posthog/pull/99"},
- )
- append_task_run_artefact(
- team_id=self.team.id,
- report_id=str(self.report.id),
- product="signals",
- type="discussion",
- task_id=str(discussion_task.id),
- )
-
- response = self._post_pr_webhook(
- action="closed", merged=False, pr_url="https://github.com/posthog/posthog/pull/99"
- )
-
- self.assertEqual(response.status_code, 200)
- self.report.refresh_from_db()
- self.assertEqual(self.report.status, SignalReport.Status.READY)
-
- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
- @patch("products.tasks.backend.models.posthoganalytics.capture")
- def test_merge_attests_the_run_the_badge_reads(self, _mock_capture, mock_get_secret):
- mock_get_secret.return_value = self.webhook_secret
- self.task_run.status = TaskRun.Status.IN_PROGRESS
- self.task_run.save(update_fields=["status"])
- newest_run = TaskRun.objects.create(
- task=self.task,
- team=self.team,
- status=TaskRun.Status.COMPLETED,
- output={"pr_url": "https://github.com/posthog/posthog/pull/42"},
+ other_organization = Organization.objects.create(name="Other Org")
+ other_team = Team.objects.create(organization=other_organization, name="Other Team")
+ other_report = SignalReport.objects.create(
+ team=other_team,
+ status=SignalReport.Status.READY,
+ title="Other report",
+ summary="Other summary",
)
-
- response = self._post_pr_webhook(action="closed", merged=True)
-
- self.assertEqual(response.status_code, 200)
- newest_run.refresh_from_db()
- assert newest_run.output is not None
- self.assertIs(newest_run.output.get("pr_merged"), True)
-
- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
- @patch("products.tasks.backend.models.posthoganalytics.capture")
- def test_merge_does_not_attest_a_run_that_only_read_the_pr(self, _mock_capture, mock_get_secret):
- mock_get_secret.return_value = self.webhook_secret
- research_run = TaskRun.objects.create(
- task=self.task,
- team=self.team,
- status=TaskRun.Status.COMPLETED,
- state={"ai_stage": "research"},
- output={"pr_url": "https://github.com/posthog/posthog/pull/42"},
+ other_assignment = SignalReportAssignment.all_teams.create(
+ team=other_team,
+ report=other_report,
+ pr_url=self.assignment.pr_url,
+ repository=self.assignment.repository,
+ pr_number=self.assignment.pr_number,
+ pr_state=SignalReportAssignment.PrState.OPEN,
)
response = self._post_pr_webhook(action="closed", merged=True)
self.assertEqual(response.status_code, 200)
- research_run.refresh_from_db()
- assert research_run.output is not None
- self.assertIsNone(research_run.output.get("pr_merged"))
+ self.report.refresh_from_db()
+ other_report.refresh_from_db()
+ self.assignment.refresh_from_db()
+ other_assignment.refresh_from_db()
+ self.assertEqual(self.report.status, SignalReport.Status.RESOLVED)
+ self.assertEqual(self.assignment.pr_state, SignalReportAssignment.PrState.MERGED)
+ self.assertEqual(other_report.status, SignalReport.Status.READY)
+ self.assertEqual(other_assignment.pr_state, SignalReportAssignment.PrState.OPEN)
@parameterized.expand(
[
@@ -1387,19 +1352,19 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
)
@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
- def test_pr_url_variants_match_the_webhook_pr(self, _name, stored_pr_url, _mock_capture, mock_get_secret):
+ def test_pr_url_variants_match_by_repository_and_number(self, _name, stored_pr_url, _mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
- self.task_run.output = {"pr_url": stored_pr_url}
- self.task_run.save(update_fields=["output"])
+ self.assignment.pr_url = stored_pr_url
+ self.assignment.save(update_fields=["pr_url", "updated_at"])
response = self._post_pr_webhook(action="closed", merged=True)
self.assertEqual(response.status_code, 200)
self.report.refresh_from_db()
- self.task_run.refresh_from_db()
+ self.assignment.refresh_from_db()
self.assertEqual(self.report.status, SignalReport.Status.RESOLVED)
- assert self.task_run.output is not None
- self.assertIs(self.task_run.output.get("pr_merged"), True)
+ self.assertEqual(self.assignment.pr_state, SignalReportAssignment.PrState.MERGED)
+ self.assertTrue(self.assignment.pr_merged)
class TestExternalPRWebhook(TestCase):
diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.py
index 621d5fa35e95..83e32c7cb6e9 100644
--- a/products/tasks/backend/webhooks.py
+++ b/products/tasks/backend/webhooks.py
@@ -15,7 +15,6 @@ import posthoganalytics
from social_django.models import UserSocialAuth
from posthog.event_usage import groups
-from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.instance_setting import get_instance_setting
from posthog.models.integration import Integration
from posthog.models.organization import OrganizationMembership
@@ -23,11 +22,7 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.models.user_integration import UserIntegration
-from products.signals.backend.implementation_pr import (
- fetch_implementation_pr_state_for_reports,
- pr_bearing_task_run_filter,
-)
-from products.signals.backend.models import InvalidStatusTransition, SignalReport
+from products.signals.backend.report_assignments import update_assignments_for_pull_request
from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users
from products.tasks.backend.constants import PR_LOOP_ENABLED_STATE_KEY
from products.tasks.backend.facade.api import post_pr_created_thread_update, signal_workflow_completion
@@ -272,6 +267,7 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:
branch = pull_request.get("head", {}).get("ref")
repository_full_name = (payload.get("repository") or {}).get("full_name")
scoped_team_ids = _task_run_scope_team_ids(payload)
+ assignment_team_ids = _installation_team_ids(payload)
task_run = find_task_run(pr_url=pr_url, branch=branch, repository=repository_full_name, team_ids=scoped_team_ids)
claimed_pr_urls = (
read_pr_urls(task_run.output if isinstance(task_run.output, dict) else {}) if task_run is not None else []
@@ -315,6 +311,19 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:
):
_record_run_pr_state(task_run, pr_state)
+ if pr_state is not None and repository_full_name and assignment_team_ids:
+ try:
+ update_assignments_for_pull_request(
+ team_ids=assignment_team_ids,
+ repository=repository_full_name,
+ pr_number=int(pull_request.get("number")),
+ pr_state=pr_state,
+ )
+ except (TypeError, ValueError):
+ logger.warning("github_pr_webhook_signal_assignment_missing_number", pr_url=pr_url)
+ except Exception:
+ logger.exception("github_pr_webhook_signal_assignment_update_failed", pr_url=pr_url)
+
if analytics_event is not None:
# Deterministic UUID dedupes duplicate webhook deliveries of the same PR action.
event_uuid = str(uuid.uuid5(uuid.NAMESPACE_URL, f"{pr_url}:{analytics_event}"))
@@ -326,24 +335,11 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:
# same-branch webhook for a different PR from marking this run's PR as merged.
if task_run and pr_url in claimed_pr_urls:
_record_run_pr_merged(task_run)
- _transition_signal_reports_for_pr(
- pr_url,
- SignalReport.Status.RESOLVED,
- "github_pr_webhook_signal_report_resolved",
- scoped_team_ids or ([task_run.team_id] if task_run else None),
- record_merge=True,
- )
if action == "closed" and not merged:
# Same trust rule as the merge branch: only the run that claims this PR URL.
if task_run and pr_url in claimed_pr_urls:
_cancel_wizard_run_on_close(task_run)
- _transition_signal_reports_for_pr(
- pr_url,
- SignalReport.Status.SUPPRESSED,
- "github_pr_webhook_signal_report_archived",
- scoped_team_ids or ([task_run.team_id] if task_run else None),
- )
return HttpResponse(status=200)
@@ -943,113 +939,3 @@ def _resolve_external_team(payload: dict) -> Team | None:
if not team_ids:
return None
return Team.objects.filter(pk=team_ids[0]).first()
-
-
-def _pull_request_identity(pr_url: str) -> tuple[str, int] | None:
- parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)
- if parsed is None:
- return None
- return parsed.repository.lower(), parsed.number
-
-
-def _pr_url_lookup_values(pr_url: str) -> list[str]:
- """The ``output.pr_url`` strings that can stand for ``pr_url``.
-
- ``output.pr_url`` is caller-supplied: the agent server PATCHes it onto the run, so it can hold
- a valid but noncanonical form of the URL GitHub sends as ``html_url``. The variants are
- enumerated rather than matched with a prefix or a normalizing scan so the lookup stays on the
- partial index ``task_run_output_pr_url_idx``. A prefix match cannot use that index, and this
- lookup runs on every closed-PR delivery, including the many for PRs no run ever opened.
- """
- parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)
- if parsed is None:
- return [pr_url]
- values = {pr_url}
- for host in ("github.com", "www.github.com"):
- for repository in (parsed.repository, parsed.repository.lower()):
- base = f"https://{host}/{repository}/pull/{parsed.number}"
- values.update((base, f"{base}/"))
- return sorted(values)
-
-
-def _signal_reports_for_pr_runs(pr_url: str, runs: list[TaskRun]) -> list[SignalReport]:
- if not runs:
- return []
-
- reports = list(
- SignalReport.objects.filter(SignalReport.reports_for_task_ids_filter({run.task_id for run in runs}))
- .exclude(
- status__in=[
- SignalReport.Status.RESOLVED,
- SignalReport.Status.DELETED,
- SignalReport.Status.SUPPRESSED,
- ]
- )
- .distinct()
- )
- pr_identity = _pull_request_identity(pr_url)
- surfaced_prs = fetch_implementation_pr_state_for_reports([str(report.id) for report in reports])
- return [
- report
- for report in reports
- if (surfaced_pr := surfaced_prs.get(str(report.id))) and _pull_request_identity(surfaced_pr.url) == pr_identity
- ]
-
-
-def _transition_signal_reports_for_pr(
- pr_url: str,
- target_status: SignalReport.Status,
- success_log_event: str,
- team_ids: list[int] | None,
- *,
- record_merge: bool = False,
-) -> None:
- """Transition signal reports whose surfaced implementation PR matches ``pr_url``.
-
- Covers both PR outcomes: a merged PR resolves its reports, a closed-unmerged PR archives
- (suppresses) them so they leave the inbox instead of lingering as if work were still pending.
- Kept tolerant: a single bad transition should not fail the whole webhook, since GitHub retries
- 5xx responses and we've already acknowledged the PR event.
- """
- run_candidates = TaskRun.objects.filter(output__pr_url__in=_pr_url_lookup_values(pr_url))
- if team_ids:
- run_candidates = run_candidates.filter(team_id__in=team_ids)
- reports = _signal_reports_for_pr_runs(pr_url, list(run_candidates))
-
- if record_merge and reports:
- # The inbox badge reads pr_merged off the run the report's surfaced PR came from, so the
- # attestation has to land there and not only on the run the webhook bound to.
- # Research, repo-selection and scout runs are excluded because a PR URL on one of them is a
- # PR the agent read while checking for in-flight work, not one it opened.
- # Newest run per task, matching get_latest_pr_url_by_task and get_merged_pr_task_ids
- # run-for-run. Those two decide which run the badge reads, so any other ordering here can
- # attest one run while the badge reads another, which is the bug this block exists to fix.
- report_task_runs = SignalReport.associated_task_runs_for_reports(
- report_ids=[str(report.id) for report in reports]
- )
- associated_task_ids = {run.task_id for runs in report_task_runs.values() for run in runs}
- surfaced_runs = (
- run_candidates.filter(pr_bearing_task_run_filter(), task_id__in=associated_task_ids)
- .order_by("task_id", "-created_at", "-id")
- .distinct("task_id")
- )
- for run in surfaced_runs:
- _record_run_pr_merged(run)
-
- for report in reports:
- try:
- updated_fields = report.transition_to(target_status)
- except InvalidStatusTransition:
- logger.warning(
- "github_pr_webhook_signal_report_invalid_transition",
- report_id=str(report.id),
- from_status=report.status,
- pr_url=pr_url,
- )
- continue
- report.save(update_fields=updated_fields)
- logger.info(
- success_log_event,
- report_id=str(report.id),
- pr_url=pr_url,
- )
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index ba13bfe72884..32b799ef53ea 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -5658,8 +5658,22 @@
"readOnlyHint": false
}
},
+ "inbox-reports-claim": {
+ "description": "Claim a potential, candidate, in_progress, pending_input, ready, or failed report before working on it. Calling this again as another actor silently takes over the claim. Optionally pass `pr_url` to attach or replace one GitHub pull request; the report does not need a pull request to be claimed or resolved. Pass `release=true` to clear only ownership; the attached pull request is kept, so sending `pr_url` in the same call is rejected. Only the current owner can release a claim. A connected repository is checked immediately; an unconnected GitHub pull request is accepted with unknown state and will not receive webhook updates. A pull request that the check finds already merged resolves the report, and one already closed dismisses it. Returns the full report with work_state, assignee, and pull request fields.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Claim or release a signal report",
+ "title": "Claim or release a signal report",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"inbox-reports-list": {
- "description": "List signal reports for the current project. A signal report is a cluster of related observations (signals) that PostHog has aggregated into a single issue or trend. Reports surface in the Inbox. Supports filtering by status (potential, candidate, in_progress, pending_input, ready, resolved, failed, suppressed), free-text search across title and summary, source_product (e.g. error_tracking, session_replay), suggested_reviewers (PostHog user UUIDs), and task_id (only reports associated with that task — pass your own task id to see which reports you are already working against). Some statuses are hidden by default (currently suppressed, i.e. human-dismissed); pass `include_all_statuses=true` to list reports in every status — do this when deduplicating against the full inbox state, and read each row's `status` (plus `dismissal_reason` / `dismissal_note` on dismissed rows) before acting. For picking up work, filter to `ready` — earlier statuses are still moving through the pipeline, and `pending_input` reports are waiting on a human. Each report's full work log — signal findings (evidence), judgments, and log entries — is readable via inbox-report-artefacts-list; read it before acting on a report. Results are paginated and ordered by '-is_suggested_reviewer,status,-updated_at' by default. To find the self-driving reports for one source record — e.g. what the inbox already investigated for a specific support ticket — pass that record's id as `source_id` together with exactly one `source_product` (for a support ticket: `source_product=conversations` and the ticket's UUID as `source_id`); add `include_all_statuses=true` to include dismissed ones.",
+ "description": "List signal reports for the current project. A signal report is a cluster of related observations (signals) that PostHog has aggregated into a single issue or trend. Reports surface in the Inbox. Supports filtering by status (potential, candidate, in_progress, pending_input, ready, resolved, failed, suppressed), free-text search across title and summary, source_product (e.g. error_tracking, session_replay), suggested_reviewers, `unclaimed`, and `assignee=me`. Claimed reports remain actionable and visible; use `unclaimed=true` to pick work that has no owner and no draft, open, or unknown PR. Some statuses are hidden by default (currently suppressed, i.e. human-dismissed); pass `include_all_statuses=true` to list reports in every status. Do this when deduplicating against the full inbox state, and read each row's `status` (plus `dismissal_reason` / `dismissal_note` on dismissed rows) before acting. For picking up work, filter to `ready` — earlier statuses are still moving through the pipeline, and `pending_input` reports are waiting on a human. Each report's full work log, including signal findings, judgments, and log entries, is readable via inbox-report-artefacts-list; read it before acting on a report. Results are paginated and ordered by '-is_suggested_reviewer,status,-updated_at' by default. To find the self-driving reports for one source record — e.g. what the inbox already investigated for a specific support ticket — pass that record's id as `source_id` together with exactly one `source_product` (for a support ticket: `source_product=conversations` and the ticket's UUID as `source_id`); add `include_all_statuses=true` to include dismissed ones.",
"category": "Signals",
"feature": "signals",
"summary": "List signal reports",
@@ -5673,7 +5687,7 @@
}
},
"inbox-reports-retrieve": {
- "description": "Get a single signal report by ID. Returns the full report including title, summary, status, priority and actionability judgments, signal_count, total_weight, source products, and the URL of the implementation PR if one has been opened. The report's full work log — signal findings (evidence), judgments, and log entries — is readable via inbox-report-artefacts-list; read it before acting on the report. The raw underlying signals require a HogQL query (see the 'signals' skill). If you do any work prompted by this report — even research — first associate your task with it by appending a `task_run` artefact via inbox-report-artefacts-create. Report lifecycle is pipeline-managed — don't try to drive it: act on `ready` reports; `pending_input` means the report is waiting on human input, so surface it to a human rather than acting on it yourself.",
+ "description": "Get a single signal report by ID. Returns the full report, including work_state, current assignee, and the attached pull request and its latest known state. The report's full work log is readable via inbox-report-artefacts-list; read it before acting. The raw underlying signals require a HogQL query (see the 'signals' skill). Claim the report before doing work. A report may be claimed in potential, candidate, in_progress, pending_input, ready, or failed state.",
"category": "Signals",
"feature": "signals",
"summary": "Get signal report",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 8868969b969f..2852766dda66 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -5855,8 +5855,22 @@
"readOnlyHint": false
}
},
+ "inbox-reports-claim": {
+ "description": "Claim a potential, candidate, in_progress, pending_input, ready, or failed report before working on it. Calling this again as another actor silently takes over the claim. Optionally pass `pr_url` to attach or replace one GitHub pull request; the report does not need a pull request to be claimed or resolved. Pass `release=true` to clear only ownership; the attached pull request is kept, so sending `pr_url` in the same call is rejected. Only the current owner can release a claim. A connected repository is checked immediately; an unconnected GitHub pull request is accepted with unknown state and will not receive webhook updates. A pull request that the check finds already merged resolves the report, and one already closed dismisses it. Returns the full report with work_state, assignee, and pull request fields.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Claim or release a signal report",
+ "title": "Claim or release a signal report",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"inbox-reports-list": {
- "description": "List signal reports for the current project. A signal report is a cluster of related observations (signals) that PostHog has aggregated into a single issue or trend. Reports surface in the Inbox. Supports filtering by status (potential, candidate, in_progress, pending_input, ready, resolved, failed, suppressed), free-text search across title and summary, source_product (e.g. error_tracking, session_replay), suggested_reviewers (PostHog user UUIDs), and task_id (only reports associated with that task — pass your own task id to see which reports you are already working against). Some statuses are hidden by default (currently suppressed, i.e. human-dismissed); pass `include_all_statuses=true` to list reports in every status — do this when deduplicating against the full inbox state, and read each row's `status` (plus `dismissal_reason` / `dismissal_note` on dismissed rows) before acting. For picking up work, filter to `ready` — earlier statuses are still moving through the pipeline, and `pending_input` reports are waiting on a human. Each report's full work log — signal findings (evidence), judgments, and log entries — is readable via inbox-report-artefacts-list; read it before acting on a report. Results are paginated and ordered by '-is_suggested_reviewer,status,-updated_at' by default. To find the self-driving reports for one source record — e.g. what the inbox already investigated for a specific support ticket — pass that record's id as `source_id` together with exactly one `source_product` (for a support ticket: `source_product=conversations` and the ticket's UUID as `source_id`); add `include_all_statuses=true` to include dismissed ones.",
+ "description": "List signal reports for the current project. A signal report is a cluster of related observations (signals) that PostHog has aggregated into a single issue or trend. Reports surface in the Inbox. Supports filtering by status (potential, candidate, in_progress, pending_input, ready, resolved, failed, suppressed), free-text search across title and summary, source_product (e.g. error_tracking, session_replay), suggested_reviewers, `unclaimed`, and `assignee=me`. Claimed reports remain actionable and visible; use `unclaimed=true` to pick work that has no owner and no draft, open, or unknown PR. Some statuses are hidden by default (currently suppressed, i.e. human-dismissed); pass `include_all_statuses=true` to list reports in every status. Do this when deduplicating against the full inbox state, and read each row's `status` (plus `dismissal_reason` / `dismissal_note` on dismissed rows) before acting. For picking up work, filter to `ready` — earlier statuses are still moving through the pipeline, and `pending_input` reports are waiting on a human. Each report's full work log, including signal findings, judgments, and log entries, is readable via inbox-report-artefacts-list; read it before acting on a report. Results are paginated and ordered by '-is_suggested_reviewer,status,-updated_at' by default. To find the self-driving reports for one source record — e.g. what the inbox already investigated for a specific support ticket — pass that record's id as `source_id` together with exactly one `source_product` (for a support ticket: `source_product=conversations` and the ticket's UUID as `source_id`); add `include_all_statuses=true` to include dismissed ones.",
"category": "Signals",
"feature": "signals",
"summary": "List signal reports",
@@ -5870,7 +5884,7 @@
}
},
"inbox-reports-retrieve": {
- "description": "Get a single signal report by ID. Returns the full report including title, summary, status, priority and actionability judgments, signal_count, total_weight, source products, and the URL of the implementation PR if one has been opened. The report's full work log — signal findings (evidence), judgments, and log entries — is readable via inbox-report-artefacts-list; read it before acting on the report. The raw underlying signals require a HogQL query (see the 'signals' skill). If you do any work prompted by this report — even research — first associate your task with it by appending a `task_run` artefact via inbox-report-artefacts-create. Report lifecycle is pipeline-managed — don't try to drive it: act on `ready` reports; `pending_input` means the report is waiting on human input, so surface it to a human rather than acting on it yourself.",
+ "description": "Get a single signal report by ID. Returns the full report, including work_state, current assignee, and the attached pull request and its latest known state. The report's full work log is readable via inbox-report-artefacts-list; read it before acting. The raw underlying signals require a HogQL query (see the 'signals' skill). Claim the report before doing work. A report may be claimed in potential, candidate, in_progress, pending_input, ready, or failed state.",
"category": "Signals",
"feature": "signals",
"summary": "Get signal report",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b99ac78127df..9ea381f0e960 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -57037,6 +57037,16 @@ export namespace Schemas {
RelatedTo: 'related_to',
} as const;
+ export type SignalActorKindEnum = typeof SignalActorKindEnum[keyof typeof SignalActorKindEnum];
+
+
+ export const SignalActorKindEnum = {
+ User: 'user',
+ Task: 'task',
+ Agent: 'agent',
+ System: 'system',
+ } as const;
+
export interface _User {
readonly id: number;
readonly uuid: string;
@@ -57054,10 +57064,17 @@ export namespace Schemas {
readonly created_at: string;
/** @nullable */
readonly updated_at: string | null;
- /** User the artefact is attributed to, when a user produced it. Null for task/system writes. */
+ /** Actor kind. Legacy rows without attribution are returned as system. */
+ readonly actor_kind: SignalActorKindEnum;
+ /**
+ * MCP client name when an external agent produced the artefact.
+ * @nullable
+ */
+ readonly actor_agent: string | null;
+ /** Authenticated user principal for user or external agent writes. Null for internal task and system writes. */
readonly created_by: _User | null;
/**
- * Task the artefact is attributed to, when an agent produced it. Null for user/system writes.
+ * Internal task the artefact is attributed to. Null for user, external agent, and system writes.
* @nullable
*/
readonly task_id: string | null;
@@ -57098,6 +57115,38 @@ export namespace Schemas {
Suppressed: 'suppressed',
} as const;
+ export type SignalReportAssignmentPrStateEnum = typeof SignalReportAssignmentPrStateEnum[keyof typeof SignalReportAssignmentPrStateEnum];
+
+
+ export const SignalReportAssignmentPrStateEnum = {
+ Unknown: 'unknown',
+ Draft: 'draft',
+ Open: 'open',
+ Closed: 'closed',
+ Merged: 'merged',
+ } as const;
+
+ export type SignalReportWorkStateEnum = typeof SignalReportWorkStateEnum[keyof typeof SignalReportWorkStateEnum];
+
+
+ export const SignalReportWorkStateEnum = {
+ Unclaimed: 'unclaimed',
+ Working: 'working',
+ InReview: 'in_review',
+ Done: 'done',
+ } as const;
+
+ export interface SignalReportAssignee {
+ kind: SignalActorKindEnum;
+ user: _User | null;
+ /** @nullable */
+ task_id: string | null;
+ /** @nullable */
+ agent: string | null;
+ /** @nullable */
+ claimed_at: string | null;
+ }
+
/**
* * `pr_incorrect` - PR incorrect
* * `pr_not_useful` - PR not useful
@@ -57235,12 +57284,18 @@ export namespace Schemas {
*/
readonly scout_name: string | null;
/**
- * PR URL from the latest implementation task run, if available.
+ * Pull request attached to this report's claim, if available.
* @nullable
*/
readonly implementation_pr_url: string | null;
+ /** Latest known pull request state: unknown, draft, open, closed, or merged. */
+ readonly implementation_pr_state: SignalReportAssignmentPrStateEnum | null;
/** Whether that implementation PR is merged, per the GitHub webhook. False when there is no PR or it hasn't merged. Report status doesn't imply this: a resolved report may have been resolved directly, without a merged PR. */
readonly implementation_pr_merged: boolean;
+ /** Derived remediation state: unclaimed, working, in_review, or done. */
+ readonly work_state: SignalReportWorkStateEnum;
+ /** Current user, internal task, or external agent claim owner. Null when unclaimed. */
+ readonly assignee: SignalReportAssignee | null;
/** The report's PR refund, when one exists. One refund per report, ever. */
readonly refund: SignalReportRefund | null;
/** Why refunding this report's PR would be rejected right now, or null when a refund would be accepted (see the field's schema for the reason values). */
@@ -77697,6 +77752,13 @@ export namespace Schemas {
not_found_count: number;
}
+ export interface SignalReportClaim {
+ /** Optional GitHub pull request to attach to the claim. The report may be claimed without one. */
+ pr_url?: string;
+ /** Release ownership while preserving any attached pull request. */
+ release?: boolean;
+ }
+
export interface SignalReportFeedbackRequest {
/** The rating left on the report: 'positive' (thumbs up) or 'negative' (thumbs down).
*
@@ -99239,6 +99301,10 @@ export namespace Schemas {
* Filter by whether the latest actionability judgment says the issue is already being handled. False also includes older reports where that judgment did not record a value.
*/
already_addressed?: boolean;
+ /**
+ * Use 'me' to return reports claimed by the current user, task, or MCP agent.
+ */
+ assignee?: SignalsReportsListAssignee;
/**
* Narrow to reports assigned to one space (channel). Absent or empty means all reports regardless of assignment.
*/
@@ -99248,7 +99314,7 @@ export namespace Schemas {
*/
count_only?: boolean;
/**
- * Filter reports by whether a shipped implementation pull request exists. 'true' keeps only reports with a PR; 'false' keeps only those without. Pair with count_only=true to return only the filtered total.
+ * Filter reports by whether an implementation pull request is attached. 'true' keeps only reports with a PR; 'false' keeps only those without. Pair with count_only=true to return only the filtered total.
*/
has_implementation_pr?: boolean;
/**
@@ -99315,6 +99381,10 @@ export namespace Schemas {
* PostHog user UUID used when scope=teammate.
*/
teammate_uuid?: string;
+ /**
+ * Filter by whether the report has no owner and no draft, open, or unknown PR. Resolved reports are never unclaimed.
+ */
+ unclaimed?: boolean;
/**
* When true and priority is omitted, include priorities at or above the requesting user's personal PR-generation threshold, falling back to the project threshold.
*/
@@ -99325,6 +99395,13 @@ export namespace Schemas {
view?: string;
};
+ export type SignalsReportsListAssignee = typeof SignalsReportsListAssignee[keyof typeof SignalsReportsListAssignee];
+
+
+ export const SignalsReportsListAssignee = {
+ Me: 'me',
+ } as const;
+
export type SignalsReportArtefactsListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index d3f704700186..89c93216c931 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 40 enabled ops
+ * PostHog API - MCP 41 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -29,6 +29,10 @@ export const SignalsReportsListQueryParams = () => zod.object({
.describe(
'Filter by whether the latest actionability judgment says the issue is already being handled. False also includes older reports where that judgment did not record a value.'
),
+ assignee: zod
+ .enum(['me'])
+ .optional()
+ .describe("Use 'me' to return reports claimed by the current user, task, or MCP agent."),
channel_id: zod
.string()
.optional()
@@ -45,7 +49,7 @@ export const SignalsReportsListQueryParams = () => zod.object({
.boolean()
.optional()
.describe(
- "Filter reports by whether a shipped implementation pull request exists. 'true' keeps only reports with a PR; 'false' keeps only those without. Pair with count_only=true to return only the filtered total."
+ "Filter reports by whether an implementation pull request is attached. 'true' keeps only reports with a PR; 'false' keeps only those without. Pair with count_only=true to return only the filtered total."
),
include_all_statuses: zod
.boolean()
@@ -117,6 +121,12 @@ export const SignalsReportsListQueryParams = () => zod.object({
.optional()
.describe("Only reports associated with this task (via the report's task associations)."),
teammate_uuid: zod.string().optional().describe('PostHog user UUID used when scope=teammate.'),
+ unclaimed: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Filter by whether the report has no owner and no draft, open, or unknown PR. Resolved reports are never unclaimed.'
+ ),
use_priority_preference: zod
.boolean()
.optional()
@@ -178,6 +188,32 @@ export const SignalsReportsPartialUpdateBody = () => zod
'Editable human-facing fields on a signal report (PATCH).\n\nBoth fields are optional so a caller can change either independently, but at least one\nmust be supplied. Every other report field — status, weights, judgments — is owned by the\nsignals pipeline and is deliberately not writable here.'
)
+/**
+ * Claim a report for the current user, internal task, or external MCP agent. A later claim silently takes over ownership. Supply pr_url to attach or replace the report's pull request, or release=true to clear only ownership while preserving the pull request.
+ * @summary Claim or release a signal report
+ */
+export const SignalsReportsClaimParams = () => zod.object({
+ id: zod.string().describe('A UUID string identifying this signal report.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const signalsReportsClaimBodyReleaseDefault = false
+
+export const SignalsReportsClaimBody = () => zod.object({
+ pr_url: zod
+ .url()
+ .optional()
+ .describe('Optional GitHub pull request to attach to the claim. The report may be claimed without one.'),
+ release: zod
+ .boolean()
+ .default(signalsReportsClaimBodyReleaseDefault)
+ .describe('Release ownership while preserving any attached pull request.'),
+})
+
/**
* Transition a report to a new state. The model validates allowed transitions.
*
diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.ts
index 54e28013ec1d..6400db881fe9 100644
--- a/services/mcp/src/hono/request-context.ts
+++ b/services/mcp/src/hono/request-context.ts
@@ -19,6 +19,7 @@ import { getCustomApiBaseUrl, getPublicBaseUrl } from './constants'
import {
buildMCPRequestContext,
buildMCPSessionAnalyticsProperties,
+ getEffectiveMCPClientContext,
type MCPRequestContext,
type MCPSessionContext,
} from './mcp-context'
@@ -77,6 +78,7 @@ export class RequestContext {
private async api(): Promise<ApiClient> {
if (!this.apiInstance) {
+ const clientContext = getEffectiveMCPClientContext(this.requestContext, this.sessionContext)
const customApiBaseUrl = getCustomApiBaseUrl()
let baseUrl: string
if (customApiBaseUrl) {
@@ -93,10 +95,10 @@ export class RequestContext {
baseUrl,
publicBaseUrl: getPublicBaseUrl(),
clientUserAgent: this.props.clientUserAgent,
- mcpClientName: this.props.mcpClientName,
- mcpClientVersion: this.props.mcpClientVersion,
- mcpProtocolVersion: this.props.mcpProtocolVersion,
- mcpConsumer: this.props.mcpConsumer,
+ mcpClientName: clientContext.mcpClientName,
+ mcpClientVersion: clientContext.mcpClientVersion,
+ mcpProtocolVersion: clientContext.mcpProtocolVersion,
+ mcpConsumer: clientContext.mcpConsumer,
// Cached from a previous request's token introspection. On a cold cache this is
// still unset here, so `StateManager` also stamps it onto the live client's config
// the moment introspection resolves it — otherwise a token's first request would
@@ -177,6 +179,10 @@ export class RequestContext {
setMcpContexts(requestContext: MCPRequestContext, sessionContext: MCPSessionContext | null): void {
this.requestContext = requestContext
this.sessionContext = sessionContext
+ if (this.apiInstance) {
+ const clientContext = getEffectiveMCPClientContext(requestContext, sessionContext)
+ Object.assign(this.apiInstance.config, clientContext)
+ }
}
async safelyGetAnalyticsContext(context: Pick<Context, 'stateManager'>): Promise<MCPAnalyticsContext | undefined> {
diff --git a/services/mcp/src/lib/instructions.ts b/services/mcp/src/lib/instructions.ts
index 75155fdede0b..18351e8c1630 100644
--- a/services/mcp/src/lib/instructions.ts
+++ b/services/mcp/src/lib/instructions.ts
@@ -230,6 +230,7 @@ export class ToolDomainExtractor {
'run',
'archive',
'calculate',
+ 'claim',
'complete',
'copy',
'disable',
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 2e73a8073d8f..43f3e5a51d31 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -189,6 +189,39 @@ const inboxReportsBulkSetState = (): ToolBase<
},
})
+const InboxReportsClaimSchema = () => {
+ const SignalsReportsClaimBody = orvalSchemas.SignalsReportsClaimBody()
+ const SignalsReportsClaimParams = orvalSchemas.SignalsReportsClaimParams()
+ return z.preprocess(
+ normalizeParamAliases({ id: ['report_id'] }),
+ SignalsReportsClaimParams.omit({ project_id: true }).extend(SignalsReportsClaimBody.shape)
+ )
+}
+
+const inboxReportsClaim = (): ToolBase<
+ ReturnType<typeof InboxReportsClaimSchema>,
+ WithPostHogUrl<Schemas.SignalReport>
+> => ({
+ name: 'inbox-reports-claim',
+ schema: InboxReportsClaimSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof InboxReportsClaimSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.pr_url !== undefined) {
+ body['pr_url'] = params.pr_url
+ }
+ if (params.release !== undefined) {
+ body['release'] = params.release
+ }
+ const result = await context.api.request<Schemas.SignalReport>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/reports/${encodeURIComponent(String(params.id))}/claim/`,
+ body,
+ })
+ return await withPostHogUrl(context, result, `/inbox/${result.id}`)
+ },
+})
+
const InboxReportsListSchema = () => {
const SignalsReportsListQueryParams = orvalSchemas.SignalsReportsListQueryParams()
return SignalsReportsListQueryParams
@@ -208,6 +241,7 @@ const inboxReportsList = (): ToolBase<
query: {
actionability: params.actionability,
already_addressed: params.already_addressed,
+ assignee: params.assignee,
channel_id: params.channel_id,
count_only: params.count_only,
has_implementation_pr: params.has_implementation_pr,
@@ -227,6 +261,7 @@ const inboxReportsList = (): ToolBase<
suggested_reviewers: params.suggested_reviewers,
task_id: params.task_id,
teammate_uuid: params.teammate_uuid,
+ unclaimed: params.unclaimed,
use_priority_preference: params.use_priority_preference,
view: params.view,
},
@@ -249,6 +284,10 @@ const inboxReportsList = (): ToolBase<
'source_products',
'is_suggested_reviewer',
'implementation_pr_url',
+ 'implementation_pr_state',
+ 'implementation_pr_merged',
+ 'work_state',
+ 'assignee',
'created_at',
'updated_at',
])
@@ -265,7 +304,7 @@ const inboxReportsList = (): ToolBase<
},
'/inbox'
),
- "If you do ANY work connected to one of these reports — even pure research or investigation — always first associate your task with it: call inbox-report-artefacts-create with artefact_type `task_run` and content {} (your own task id is filled in automatically). That task_run artefact IS the task↔report association — commits you push are recorded on the report through it, and without it your work is invisible to the report. If that call fails with a 400 saying a task id is required, you simply have no task id of your own — that's expected, not an error to fix; skip the association and carry on. Without the write tools (a read-only session) ignore the association step entirely — artefact persistence is handled for you. Read the report's work log via inbox-report-artefacts-list before acting."
+ 'You may inspect reports without claiming them. A claim indicates active work that should not be duplicated. Before claiming a report, read the report and its work log. If you decide to begin working to fix the issues identified in the report, call inbox-reports-claim to record that you are working on it. A later claim can replace the current owner.\nIf you create a pull request implementing the remediation, call inbox-reports-claim again with `pr_url` to attach it. Release the claim if you stop work without completing the report. If the report should be considered resolved without a pull request, or PostHog cannot observe the pull request merge, resolve it with inbox-reports-set-state.\n'
)
},
})
@@ -292,7 +331,7 @@ const inboxReportsRetrieve = (): ToolBase<
})
return withAgentNote(
await withPostHogUrl(context, result, `/inbox/${result.id}`),
- "If you do ANY work connected to this report — even pure research or investigation — always first associate your task with it: call inbox-report-artefacts-create with artefact_type `task_run` and content {} (your own task id is filled in automatically). That task_run artefact IS the task↔report association — commits you push via git_signed_commit are recorded on the report through it, and without it your work is invisible to the report. If that call fails with a 400 saying a task id is required, you simply have no task id of your own — that's expected, not an error to fix; skip the association and continue. Then log the work as artefacts as you go — notes, code references, and any commit you have already pushed to a remote branch outside git_signed_commit (signed pushes are recorded automatically; never record a commit that is not on a remote branch). Status artefacts (priority, actionability, reviewers) are latest-wins — append a new version to re-assess. Without the write tools, work as instructed by your task — artefact persistence is handled for you."
+ 'You may inspect reports without claiming them. A claim indicates active work that should not be duplicated. Before claiming a report, read the report and its work log. If you decide to begin working to fix the issues identified in the report, call inbox-reports-claim to record that you are working on it. A later claim can replace the current owner.\nIf you create a pull request implementing the remediation, call inbox-reports-claim again with `pr_url` to attach it. Release the claim if you stop work without completing the report. If the report should be considered resolved without a pull request, or PostHog cannot observe the pull request merge, resolve it with inbox-reports-set-state.\n'
)
},
})
@@ -2014,6 +2053,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'inbox-report-artefacts-retrieve': inboxReportArtefactsRetrieve,
'inbox-report-artefacts-update': inboxReportArtefactsUpdate,
'inbox-reports-bulk-set-state': inboxReportsBulkSetState,
+ 'inbox-reports-claim': inboxReportsClaim,
'inbox-reports-list': inboxReportsList,
'inbox-reports-retrieve': inboxReportsRetrieve,
'inbox-reports-set-state': inboxReportsSetState,
diff --git a/services/mcp/tests/hono/request-context.test.ts b/services/mcp/tests/hono/request-context.test.ts
index 849a0a4dd1d3..924b52d1ee78 100644
--- a/services/mcp/tests/hono/request-context.test.ts
+++ b/services/mcp/tests/hono/request-context.test.ts
@@ -2,8 +2,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
const { mockMe, mockApiClientCtor } = vi.hoisted(() => {
const mockMe = vi.fn()
- const mockApiClientCtor = vi.fn().mockImplementation(function () {
+ const mockApiClientCtor = vi.fn().mockImplementation(function (config) {
return {
+ config,
users: () => ({ me: mockMe }),
}
})
@@ -120,6 +121,55 @@ describe('RequestContext', () => {
expect(mockApiClientCtor.mock.calls[0]![0].oauthClientName).toBe(expected)
})
+
+ it('forwards the session client identity after the API client already exists', async () => {
+ mockMe.mockResolvedValue({ success: true, data: { distinct_id: 'user-1' } })
+ const ctx = new RequestContext(fakeRedis(), env, makeProps({ mcpClientName: undefined }))
+ await ctx.getContext()
+
+ ctx.setMcpContexts(
+ {
+ authMethod: 'personal_api_key',
+ mcpClientName: undefined,
+ },
+ {
+ mcpClientName: 'external-claims-smoke-a',
+ mcpClientVersion: '1.0',
+ mcpProtocolVersion: '2025-03-26',
+ }
+ )
+
+ const api = mockApiClientCtor.mock.results[0]!.value
+ expect(api.config).toMatchObject({
+ mcpClientName: 'external-claims-smoke-a',
+ mcpClientVersion: '1.0',
+ mcpProtocolVersion: '2025-03-26',
+ })
+ })
+
+ it('uses the session client identity when API construction happens later', async () => {
+ mockMe.mockResolvedValue({ success: true, data: { distinct_id: 'user-1' } })
+ const ctx = new RequestContext(fakeRedis(), env, makeProps({ mcpClientName: undefined }))
+ ctx.setMcpContexts(
+ {
+ authMethod: 'personal_api_key',
+ mcpClientName: undefined,
+ },
+ {
+ mcpClientName: 'external-claims-smoke-b',
+ mcpClientVersion: '2.0',
+ mcpProtocolVersion: '2025-03-26',
+ }
+ )
+
+ await ctx.getContext()
+
+ expect(mockApiClientCtor.mock.calls[0]![0]).toMatchObject({
+ mcpClientName: 'external-claims-smoke-b',
+ mcpClientVersion: '2.0',
+ mcpProtocolVersion: '2025-03-26',
+ })
+ })
})
describe('getDistinctId', () => {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-claim.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-claim.json
new file mode 100644
index 000000000000..2c05ed8001a1
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-claim.json
@@ -0,0 +1,21 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this signal report.",
+ "type": "string"
+ },
+ "pr_url": {
+ "description": "Optional GitHub pull request to attach to the claim. The report may be claimed without one.",
+ "format": "uri",
+ "type": "string"
+ },
+ "release": {
+ "default": false,
+ "description": "Release ownership while preserving any attached pull request.",
+ "type": "boolean"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.json
index fbf6e81d5191..dc63c770e363 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.json
@@ -9,6 +9,11 @@
"description": "Filter by whether the latest actionability judgment says the issue is already being handled. False also includes older reports where that judgment did not record a value.",
"type": "boolean"
},
+ "assignee": {
+ "description": "Use 'me' to return reports claimed by the current user, task, or MCP agent.",
+ "enum": ["me"],
+ "type": "string"
+ },
"channel_id": {
"description": "Narrow to reports assigned to one space (channel). Absent or empty means all reports regardless of assignment.",
"type": "string"
@@ -18,7 +23,7 @@
"type": "boolean"
},
"has_implementation_pr": {
- "description": "Filter reports by whether a shipped implementation pull request exists. 'true' keeps only reports with a PR; 'false' keeps only those without. Pair with count_only=true to return only the filtered total.",
+ "description": "Filter reports by whether an implementation pull request is attached. 'true' keeps only reports with a PR; 'false' keeps only those without. Pair with count_only=true to return only the filtered total.",
"type": "boolean"
},
"include_all_statuses": {
@@ -85,6 +90,10 @@
"description": "PostHog user UUID used when scope=teammate.",
"type": "string"
},
+ "unclaimed": {
+ "description": "Filter by whether the report has no owner and no draft, open, or unknown PR. Resolved reports are never unclaimed.",
+ "type": "boolean"
+ },
"use_priority_preference": {
"description": "When true and priority is omitted, include priorities at or above the requesting user's personal PR-generation threshold, falling back to the project threshold.",
"type": "boolean"
diff --git a/services/mcp/tests/unit/instructions.test.ts b/services/mcp/tests/unit/instructions.test.ts
index 70d0a1532653..97b1c873e294 100644
--- a/services/mcp/tests/unit/instructions.test.ts
+++ b/services/mcp/tests/unit/instructions.test.ts
@@ -155,6 +155,7 @@ describe('buildToolDomainsBlock', () => {
const trailingActions = [
'archive',
'calculate',
+ 'claim',
'complete',
'copy',
'disable',
diff --git a/services/mcp/tests/unit/signals-claim-handler.test.ts b/services/mcp/tests/unit/signals-claim-handler.test.ts
new file mode 100644
index 000000000000..7907b483f9fe
--- /dev/null
+++ b/services/mcp/tests/unit/signals-claim-handler.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { GENERATED_TOOLS } from '@/tools/generated/signals'
+import type { Context } from '@/tools/types'
+
+interface RequestArgs {
+ method: string
+ path: string
+ body?: Record<string, unknown>
+}
+
+function createMockContext(): { context: Context; request: ReturnType<typeof vi.fn> } {
+ const request = vi.fn().mockResolvedValue({ id: 'report-123' })
+ const context = {
+ api: {
+ request,
+ getProjectBaseUrl: vi.fn().mockReturnValue('https://us.posthog.com/project/42'),
+ },
+ stateManager: {
+ getProjectId: vi.fn().mockResolvedValue('42'),
+ },
+ } as unknown as Context
+
+ return { context, request }
+}
+
+const claimTool = GENERATED_TOOLS['inbox-reports-claim']!()
+
+describe('inbox-reports-claim handler', () => {
+ it('accepts report_id and posts claim fields to the report action', async () => {
+ const { context, request } = createMockContext()
+ const params = claimTool.schema.parse({
+ report_id: 'report-123',
+ pr_url: 'https://github.com/PostHog/posthog/pull/123',
+ release: false,
+ })
+
+ await claimTool.handler(context, params)
+
+ const call = request.mock.calls[0]![0] as RequestArgs
+ expect(call).toEqual({
+ method: 'POST',
+ path: '/api/projects/42/signals/reports/report-123/claim/',
+ body: {
+ pr_url: 'https://github.com/PostHog/posthog/pull/123',
+ release: false,
+ },
+ })
+ })
+
+ it('sends release without inventing a pull request field', async () => {
+ const { context, request } = createMockContext()
+ const params = claimTool.schema.parse({ report_id: 'report-123', release: true })
+
+ await claimTool.handler(context, params)
+
+ const call = request.mock.calls[0]![0] as RequestArgs
+ expect(call.body).toEqual({ release: true })
+ })
+})