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): artefacts as report response log (#61545)

Oliver Browneb362fcf0166e
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index 46d10a7e8479..ffc5957fb2a7 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -1,3 +1,4 @@
+import re
import hmac
import json
import time
@@ -84,6 +85,37 @@ oauth_refresh_counter = Counter(
GITHUB_API_VERSION = "2022-11-28"
+# `owner/repo`, single slash, no traversal. Used to keep repo/ref/sha values out of GitHub API URL
+# paths where a crafted value (e.g. `../../other-repo/contents/x?ref=y`) could redirect the
+# authenticated request to a different endpoint.
+_GITHUB_REPO_PATH_RE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$")
+_GITHUB_REF_RE = re.compile(r"^[A-Za-z0-9._\-/]+$")
+_GITHUB_COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,40}$")
+
+# Upper bound on the diff text we return, to keep a pathological diff (generated/vendored
+# files) from bloating the JSON response and worker memory. ~1 MB of text.
+_MAX_DIFF_CHARS = 1_000_000
+
+
+def _is_safe_github_repo_path(repo_path: str) -> bool:
+ return ".." not in repo_path and bool(_GITHUB_REPO_PATH_RE.fullmatch(repo_path))
+
+
+def _is_safe_github_ref(ref: str) -> bool:
+ """A git ref safe to interpolate into a GitHub API URL path (no traversal / URL-control chars)."""
+ return (
+ bool(ref)
+ and ".." not in ref
+ and not ref.startswith("/")
+ and not ref.endswith("/")
+ and bool(_GITHUB_REF_RE.fullmatch(ref))
+ )
+
+
+def _is_safe_github_sha(sha: str) -> bool:
+ return bool(_GITHUB_COMMIT_SHA_RE.fullmatch(sha))
+
+
PRIVATE_CHANNEL_WITHOUT_ACCESS = "PRIVATE_CHANNEL_WITHOUT_ACCESS"
@@ -2471,7 +2503,15 @@ class GitHubIntegration(GitHubIntegrationBase):
@classmethod
def first_for_team_repository(cls, team_id: int, repository: str) -> "GitHubIntegration | None":
- """First GitHub integration for the team whose installation can access ``repository`` (``owner/name``)."""
+ """First GitHub integration for the team whose installation can access ``repository`` (``owner/name``).
+
+ ``repository`` reaches us from team-writable content (e.g. artefact payloads), and the access
+ check below interpolates it into an authenticated ``GET /repos/{repository}``. Reject anything
+ that isn't a plain ``owner/repo`` first, so a crafted value (``owner/repo/contents/x?ref=y``)
+ can't steer that authenticated request to a different GitHub endpoint as a probe.
+ """
+ if not _is_safe_github_repo_path(repository):
+ return None
for integration in Integration.objects.filter(team_id=team_id, kind="github").order_by("id"):
github = cls(integration)
if github.installation_can_access_repository(repository):
@@ -2582,6 +2622,70 @@ class GitHubIntegration(GitHubIntegrationBase):
"status_code": response.status_code,
}
+ def get_diff(
+ self,
+ repository: str,
+ target_branch: str,
+ base_branch: str,
+ target_sha: str | None = None,
+ base_sha: str | None = None,
+ ) -> dict[str, Any]:
+ """Return the unified diff of one branch/commit against another for ``repository``.
+
+ ``repository`` may be ``owner/name`` or a bare name (resolved against the installation's
+ org). The diff is ``base...target``: ``target_branch`` compared against ``base_branch``.
+ A SHA, when supplied, pins that side to an exact commit; otherwise the side tracks the
+ branch tip (``None`` means "use latest"). The branch is what's used when no SHA pins the
+ point — diffing branch tips keeps the result useful as a branch keeps moving (e.g. after PR
+ babysitting or customer tweaks), which a single pinned commit would not.
+
+ Uses the GitHub compare API with the ``diff`` media type, so the response body is raw
+ unified-diff text. Repository / ref / SHA values come from team-writable artefact content,
+ so they're validated before interpolation — a crafted value could otherwise redirect the
+ authenticated request to a different GitHub endpoint.
+ """
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+
+ if not _is_safe_github_repo_path(repo_path):
+ return {"success": False, "error": f"Invalid repository '{repository}'.", "status_code": 400}
+ for ref in (target_branch, base_branch):
+ if not _is_safe_github_ref(ref):
+ return {"success": False, "error": f"Invalid branch '{ref}'.", "status_code": 400}
+ for sha in (target_sha, base_sha):
+ if sha is not None and not _is_safe_github_sha(sha):
+ return {"success": False, "error": f"Invalid commit SHA '{sha}'.", "status_code": 400}
+
+ # Pin to the SHA when we have one, else compare branch tips. Both sides are now built from
+ # validated values, so the compare path can't be steered off-endpoint.
+ base_ref = base_sha or base_branch
+ target_ref = target_sha or target_branch
+ access_token = self.integration.sensitive_config["access_token"]
+
+ try:
+ response = self._github_api_get(
+ f"https://api.github.com/repos/{repo_path}/compare/{base_ref}...{target_ref}",
+ endpoint="/repos/{owner}/{repo}/compare/{basehead}",
+ headers={
+ "Accept": "application/vnd.github.diff",
+ "Authorization": f"Bearer {access_token}",
+ "X-GitHub-Api-Version": GITHUB_API_VERSION,
+ },
+ timeout=10,
+ )
+ except requests.RequestException:
+ # Don't let a slow/unreachable GitHub hang a worker or 500 the caller.
+ return {"success": False, "error": "Could not reach GitHub.", "status_code": 502}
+ if response.status_code != 200:
+ return {"success": False, "error": response.text, "status_code": response.status_code}
+ # Cap the diff we return: a branch touching generated/vendored files can produce a diff of
+ # many MB, which would bloat the JSON response and worker memory. Truncate with a marker so
+ # the consumer can tell the diff was cut rather than silently showing a partial diff.
+ diff_text = response.text
+ truncated = len(diff_text) > _MAX_DIFF_CHARS
+ if truncated:
+ diff_text = diff_text[:_MAX_DIFF_CHARS] + "\n\n… diff truncated (too large to display in full) …\n"
+ return {"success": True, "diff": diff_text, "truncated": truncated}
+
def update_file(
self, repository: str, file_path: str, content: str, commit_message: str, branch: str, sha: str | None = None
) -> dict[str, Any]:
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index 4aba733d279b..c2148736890f 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -887,6 +887,124 @@ class TestGitHubIntegrationModel(BaseTest):
return _client_request
+ def test_get_diff_compares_branch_tips(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=200, text="diff --git a b")
+ with patch.object(github, "_github_api_get", return_value=mock_response) as mock_get:
+ result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")
+ assert result == {
+ "success": True,
+ "diff": "diff --git a b",
+ "truncated": False,
+ }
+ mock_get.assert_called_once()
+ assert "/compare/master...feature/foo" in mock_get.call_args.args[0]
+
+ def test_get_diff_pins_to_shas_when_given(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=200, text="diff --git a b")
+ with patch.object(github, "_github_api_get", return_value=mock_response) as mock_get:
+ result = github.get_diff(
+ "PostHog/posthog",
+ target_branch="feature/foo",
+ base_branch="master",
+ target_sha="abc123f",
+ base_sha="def456a",
+ )
+ assert result["success"] is True
+ assert "/compare/def456a...abc123f" in mock_get.call_args.args[0]
+
+ def test_get_diff_maps_upstream_error(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=404, text="Not Found")
+ with patch.object(github, "_github_api_get", return_value=mock_response):
+ result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")
+ assert result == {"success": False, "error": "Not Found", "status_code": 404}
+
+ def test_get_diff_handles_request_exception(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ with patch.object(github, "_github_api_get", side_effect=requests.ConnectionError("boom")):
+ result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")
+ assert result["success"] is False
+ assert result["status_code"] == 502
+
+ def test_get_diff_truncates_oversized_diff(self):
+ from posthog.models.integration import _MAX_DIFF_CHARS
+
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ oversized = "x" * (_MAX_DIFF_CHARS + 100)
+ mock_response = MagicMock(status_code=200, text=oversized)
+ with patch.object(github, "_github_api_get", return_value=mock_response):
+ result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")
+ assert result["success"] is True
+ assert result["truncated"] is True
+ assert len(result["diff"]) < len(oversized)
+ assert result["diff"].startswith("x" * 100)
+ assert "truncated" in result["diff"]
+
+ @parameterized.expand(
+ [
+ ("repo_traversal", {"repository": "../../other/repo"}),
+ ("repo_extra_path", {"repository": "owner/repo/contents/x"}),
+ ("target_branch_traversal", {"target_branch": "../../../etc"}),
+ ("target_branch_query", {"target_branch": "main?ref=x"}),
+ ("base_branch_traversal", {"base_branch": "..%2f"}),
+ ("target_sha_not_hex", {"target_sha": "main?ref=x"}),
+ ("base_sha_not_hex", {"base_sha": "../../x"}),
+ ]
+ )
+ def test_get_diff_rejects_unsafe_values(self, _name, overrides):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ kwargs: dict = {"repository": "PostHog/posthog", "target_branch": "feature/foo", "base_branch": "master"}
+ kwargs.update(overrides)
+ with patch.object(github, "_github_api_get") as mock_get:
+ result = github.get_diff(**kwargs)
+ assert result["success"] is False
+ assert result["status_code"] == 400
+ mock_get.assert_not_called()
+
+ def test_get_diff_allows_nested_branch_names(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=200, text="diff --git a b")
+ with patch.object(github, "_github_api_get", return_value=mock_response) as mock_get:
+ result = github.get_diff(
+ "PostHog/posthog", target_branch="feature/nested/branch", base_branch="release/v1.2"
+ )
+ assert result["success"] is True
+ mock_get.assert_called_once()
+
+ @parameterized.expand(
+ [
+ ("traversal", "../../other/repo"),
+ ("extra_path_segment", "owner/repo/contents/secret"),
+ ("query_injection", "owner/repo?ref=x"),
+ ("fragment", "owner/repo#"),
+ ("bare_name", "repo"),
+ ]
+ )
+ def test_first_for_team_repository_rejects_unsafe_path_without_probing(self, _name, repository):
+ # The access check interpolates `repository` into an authenticated GET /repos/{repository};
+ # an unsafe path must be rejected before any request fires, so it can't probe other endpoints.
+ self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ with patch.object(GitHubIntegration, "installation_can_access_repository") as mock_access:
+ result = GitHubIntegration.first_for_team_repository(self.team.id, repository)
+ assert result is None
+ mock_access.assert_not_called()
+
+ def test_first_for_team_repository_allows_owner_repo(self):
+ self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ with patch.object(GitHubIntegration, "installation_can_access_repository", return_value=True) as mock_access:
+ result = GitHubIntegration.first_for_team_repository(self.team.id, "PostHog/posthog")
+ assert result is not None
+ mock_access.assert_called_once_with("PostHog/posthog")
+
@parameterized.expand(
[
(
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index 899293b00c00..e6b8378f0bb1 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -4266,6 +4266,7 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
from posthog.tasks.usage_report import get_teams_with_signals_credits_used_in_period
+ from products.signals.backend.artefact_schemas import TASK_RUN_TYPE_IMPLEMENTATION
from products.signals.backend.models import SignalReport, SignalReportTask
# `products.tasks` is isolated; reach its models via the app registry, not a cross-boundary import.
@@ -4286,9 +4287,7 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
task = Task.objects.create(
team=team, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
)
- SignalReportTask.objects.create(
- team=team, report=report, task=task, relationship=SignalReportTask.Relationship.IMPLEMENTATION
- )
+ SignalReportTask.objects.create(team=team, report=report, task=task, relationship=TASK_RUN_TYPE_IMPLEMENTATION)
TaskRun.objects.create(
team=team,
task=task,
diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.py
index ee080b6e0708..b07902ea5f45 100644
--- a/posthog/temporal/oauth.py
+++ b/posthog/temporal/oauth.py
@@ -106,11 +106,10 @@ def resolve_scopes(scopes: PosthogMcpScopes = "read_only", *, include_internal_s
def has_write_scopes(scopes: PosthogMcpScopes) -> bool:
if isinstance(scopes, str):
- # `signals_scout` reports True so the MCP server doesn't enable read-only mode for
- # the harness sandbox — the agent IS allowed to call its own internal-write tools
- # (remember, forget, emit_finding) as well as the narrow user-facing writes in
- # `SCOUT_USER_WRITE_SCOPES` (e.g. `notebook:write`). Read-only mode is a
- # tool-annotation filter, not a scope filter, and would strip those tools
+ # `signals_scout` reports True so the MCP server doesn't enable read-only mode for the
+ # scout sandbox — the agent IS allowed to call the write tools its preset exists for
+ # (remember/forget/emit_finding + the narrow `SCOUT_USER_WRITE_SCOPES`). Read-only mode
+ # is a tool-annotation filter, not a scope filter, and would strip those tools
# categorically without this opt-out.
return scopes in ("full", "signals_scout")
return any(s in MCP_WRITE_SCOPES for s in scopes)
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index ac33c9b3b1d2..d7ec9cbd6042 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -6,6 +6,8 @@ The **Signals** product is a signal grouping and report-generation pipeline. Sig
Today the active ingestion path is **emitter → buffer → grouping v2**. The summary path is no longer a simple "summarize signals" LLM step: it runs a report-level safety judge, selects a repository, then performs sandbox-backed multi-turn research that produces findings, actionability, priority, title, summary, and suggested reviewers. Reports that are immediately actionable can automatically start a Tasks coding run via the **autonomy** system.
+A report is a **living document**: every piece of work done on it — judgments, repo selection, research findings, pushed commits, task runs, free-form notes — is recorded as an attributed, schema-validated, append-only `SignalReportArtefact`. The status-bearing types resolve latest-wins; the rest accumulate as a work log. This is the surface autonomous agents (the pipeline, custom scouts, and other inbox-driven products) read and write as they act on a report.
+
---
## Temporal Workflows
@@ -157,7 +159,7 @@ Defined in `backend/temporal/summary.py`.
- If no repository is selected, the workflow synthesizes a “repository selection required” title/summary and transitions to `pending_input`
5. **Agentic research** → `run_agentic_report_activity` (`temporal/agentic/report.py`)
- Sandbox-backed multi-turn research over the selected repository plus MCP data
- - Persists `repo_selection`, `signal_finding`, `actionability_judgment`, `priority_judgment`, and `suggested_reviewers` artefacts atomically on success
+ - Appends `repo_selection`, `signal_finding`, `actionability_judgment`, `priority_judgment`, and `suggested_reviewers` artefacts atomically on success (append-only — on re-research only entries that actually changed are appended)
6. **Conditional coding-task auto-start** (inside `run_agentic_report_activity`) — see Autonomy & Auto-Start below
7. **Apply the decision**:
- If **not actionable** → `reset_report_to_potential_activity` (weight resets to 0, status becomes `potential`)
@@ -215,9 +217,9 @@ On re-promotion:
- **Repo selection** reuses the previous `repo_selection` artefact when possible
- **Agentic research** reconstructs previous findings / actionability / priority from artefacts and reuses prior work signal-by-signal when still valid
-- **Agentic artefacts** from the previous run are deleted and replaced atomically before writing the new run’s artefacts
-- **`SignalReportTask` rows are not deleted** on re-promotion; they are historical records of research and auto-started coding runs
-- **Auto-start is deduplicated per report** by checking for an existing `SignalReportTask` with `relationship=implementation`
+- **Agentic artefacts** are append-only — the previous run's rows are kept; the new run appends only the entries that actually changed (the agent confirms a still-correct finding/judgment instead of regenerating it), and status types resolve latest-wins
+- **`task_run` artefacts are never removed** on re-promotion; they are the historical record of research and auto-started coding runs
+- **Auto-start is deduplicated per report** by a legacy `SignalReportTask` implementation link (not the freeform `task_run` log), checked inside the report-row `select_for_update`
- **Workflow ID** includes `run_count` on reruns to avoid Temporal ID collisions with earlier executions
### `SignalReportReingestionWorkflow` (`signal-report-reingestion`)
@@ -386,33 +388,57 @@ any (except deleted) → suppressed
### `SignalReportArtefact`
-JSON artefacts attached to reports. Used for video segments, safety / actionability judgments, research findings, repo selection, and suggested reviewers.
+An **append-only, attributed, schema-validated log of the work done on a report**. A report reads as a living document: the evidence the research agent gathered, the commits it pushed, the task runs that executed, and free-form notes, accumulating over time. Producers never mutate in place — re-assessing appends a new row.
+
+| Field | Type | Description |
+| ------------ | -------------------------------- | ---------------------------------------------------- |
+| `team` | FK → Team | Owning team |
+| `report` | FK → SignalReport | Parent report (`related_name="artefacts"`) |
+| `type` | CharField | Artefact type (see `ArtefactType` enum) |
+| `content` | TextField | JSON content stored as text |
+| `created_at` | DateTime | Auto-set; rows are ordered newest-first |
+| `updated_at` | DateTime (nullable, `auto_now`) | Log entries are editable in place |
+| `created_by` | FK → User (`SET_NULL`, nullable) | Attribution — the user who produced the row, if any |
+| `task` | FK → Task (`SET_NULL`, nullable) | Attribution — the task that produced the row, if any |
+
+`created_by` / `task` are nullable: legacy rows and explicit system writes carry NULLs.
+
+**Status vs log.** Everything is append-only; the `STATUS_ARTEFACT_TYPES` / `LOG_ARTEFACT_TYPES` sets classify what an entry _means_:
-| Field | Type | Description |
-| --------- | ----------------- | ------------------------------------------ |
-| `team` | FK → Team | Owning team |
-| `report` | FK → SignalReport | Parent report (`related_name="artefacts"`) |
-| `type` | CharField | Artefact type (see `ArtefactType` enum) |
-| `content` | TextField | JSON content stored as text |
+- **status** — the report's current state (`safety_judgment`, `actionability_judgment`, `priority_judgment`, `repo_selection`, `suggested_reviewers`). Each (re)assessment appends a row; the current status is the **latest row of that type** (serializers derive priority/actionability/reviewers via `order_by("-created_at")[:1]`).
+- **log** — discrete work (`code_reference`, `commit`, `task_run`, `note`); these accumulate and are addressable by UUID (PATCH/DELETE).
+- `signal_finding` is in neither set: its identity is `(report, content.signal_id)`, latest per signal wins. `dismissal` entries stack.
**Artefact types** (`SignalReportArtefact.ArtefactType` enum):
-| Type | Content |
-| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
-| `video_segment` | Video segment data from session clustering |
-| `safety_judgment` | `{"choice": bool, "explanation": "..."}` — true = safe |
-| `actionability_judgment` | `{"actionability": "immediately_actionable" \| "requires_human_input" \| "not_actionable", "explanation": "...", "already_addressed": bool}` |
-| `priority_judgment` | `{"priority": "P0"\|"P1"\|"P2"\|"P3"\|"P4", "explanation": "..."}` |
-| `signal_finding` | `{"signal_id": "...", "relevant_code_paths": [...], "relevant_commit_hashes": {"abc1234": "reason"}, "data_queried": "...", "verified": bool}` |
-| `repo_selection` | `{"repository": "owner/repo" \| null, "reason": "..."}` |
-| `suggested_reviewers` | `[{"github_login": "...", "github_name": "...", "relevant_commits": [...]}]` — enriched with current PostHog user data at serializer read time |
+| Type | Content |
+| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `video_segment` | Video segment data from session clustering |
+| `safety_judgment` | `{"choice": bool, "explanation": "..."}` — true = safe |
+| `actionability_judgment` | `{"actionability": "immediately_actionable" \| "requires_human_input" \| "not_actionable", "explanation": "...", "already_addressed": bool}` |
+| `priority_judgment` | `{"priority": "P0"\|"P1"\|"P2"\|"P3"\|"P4", "explanation": "..."}` |
+| `signal_finding` | `{"signal_id": "...", "relevant_code_paths": [...], "relevant_commit_hashes": {"abc1234": "reason"}, "data_queried": "...", "verified": bool}` |
+| `repo_selection` | `{"repository": "owner/repo" \| null, "reason": "...", "task_id"?: "..."}` |
+| `suggested_reviewers` | `[{"github_login": "...", "github_name": "...", "relevant_commits": [...]}]` — enriched with current PostHog user data at serializer read time |
+| `dismissal` | `{"reason"?, "note"?, "user_id"?, "user_uuid"?, "slack_user_id"?}` — stacking dismissal entries |
+| `code_reference` | `{"file_path": "...", "start_line": int, "end_line": int, "contents": "...", "relevance_note": "..."}` — a span of source lines (single line = equal start/end) |
+| `commit` | `{"repository": "owner/repo", "branch": "...", "commit_sha": "...", "message": "...", "note"?: "..."}` — one pushed commit |
+| `task_run` | `{"task_id": "...", "run_id"?: "...", "product": "...", "type": "..."}` — a task run associated with the report (see below) |
+| `note` | `{"note": "...", "author"?: "..."}` — free-form note (markdown allowed) |
+
+**Content schemas.** `artefact_schemas.py` is the canonical, pydantic-only home of every content shape, collected in `ARTEFACT_CONTENT_SCHEMAS` (one model per type; a test asserts exact coverage). Raw payloads become typed models once, at the boundaries (`parse_artefact_content`); the model helpers derive a row's type from the content model's class (`artefact_type_for`), so a type can never mismatch its content. `repo_selection` reuses the tasks product's `RepoSelectionResult` DTO directly (kept in the dependency-light leaf module `repo_selection/types.py` so importing the schema registry doesn't pull in the sandbox runtime). Reads of legacy rows stay tolerant — parse failures are skipped or degraded, never raised.
+
+**Attribution.** Every write helper (`append_status` / `add_log` / `append_finding` / `append_dismissal`) requires an `ArtefactAttribution` — exactly one of `from_user(user_id)` / `from_task(task_id)` / `system()` — so no write site can silently skip it. Agent writes are attributed deterministically: sandbox provisioning bakes the agent's task id into an `X-PostHog-Task-Id` header on its MCP config, forwarded by the MCP server on every API call; the LLM never handles its own task id. The header is attribution metadata, not an authorization boundary (the token is team-scoped and the named task must belong to the same team).
+
+**Write surface.** `SignalReportArtefactViewSet` exposes POST / PATCH / DELETE for any type (a status write appends a new latest-wins row), the bespoke `suggested_reviewers` PUT, and a `diff` action that renders a `commit` artefact's branch against the repository default branch via `GitHubIntegration.get_diff` (GitHub compare API, validated repo/ref/sha). All gated by `scope_object = "task"` (`task:write`). Custom agents queue artefacts during a run via `CustomSignalAgent.register_artefact`, persisted in the report's transaction and attributed to the agent's task — except `commit` (written automatically by the signed-commit harness) and `task_run` (written by report persistence), which never need registering there.
+
+**Task↔report association.** A `task_run` artefact _is_ the association (no link table): its `task` FK is the task it records. Associating is just POSTing a `task_run` (its `content.task_id` defaults from the header — "associate me"); the reports list accepts `?task_id=`. Auto-start idempotency does **not** key on this freeform, API-mutable log — it uses a legacy `SignalReportTask` implementation row, which auto-start dual-writes alongside the `task_run` artefact (see Autonomy & Auto-Start).
Notes:
- The serializer still supports legacy `actionability_judgment` payloads that used `choice` instead of `actionability`.
-- Agentic report persistence deletes and replaces only the artefact types owned by the agentic path (`repo_selection`, `signal_finding`, `actionability_judgment`, `priority_judgment`, `suggested_reviewers`). `safety_judgment` is written separately by the safety judge.
-**Indexes:** `(report)` (`signals_sig_report__idx`)
+**Indexes:** `(report)` (`signals_sig_report__idx`) plus a latest-wins `(report, type, -created_at)` index backing status derivation.
### `SignalTeamConfig`
@@ -450,25 +476,9 @@ Notes:
- User is not scoped to a team — the autostart logic resolves team membership at runtime
- Managed via `PUT /api/users/@me/signal_autonomy/` (opt in / update) and `DELETE` (opt out)
-### `SignalReportTask`
-
-Tracks the relationship between signal reports and tasks (research sandbox runs, auto-started implementation tasks, etc.).
-
-| Field | Type | Description |
-| -------------- | ----------------- | ---------------------------------------------------------------------- |
-| `id` | UUID (PK) | Primary key (UUIDModel) |
-| `team` | FK → Team | Owning team |
-| `report` | FK → SignalReport | Parent report (`related_name="report_tasks"`, cascade delete) |
-| `task` | FK → Task | The linked task (`related_name="signal_report_tasks"`, cascade delete) |
-| `relationship` | CharField(200) | One of: `repo_selection`, `research`, `implementation` |
-| `created_at` | DateTime | Auto-set on creation |
+### `SignalReportTask` (legacy — implementation gate only)
-Notes:
-
-- `research` rows are created immediately when the multi-turn research sandbox session starts
-- `implementation` rows are created when autonomy auto-starts a fix task
-- Cascading delete on both `report` and `task` FKs
-- Used as the guard against duplicate auto-starts (checks for existing `implementation` row)
+The legacy report↔task link table. General task↔report association has moved to `task_run` artefacts (a `task_run` artefact's `task` FK is the association; purpose comes from its `(product, type)`). This table survives for **one** job: it's the auto-start idempotency gate. `record_implementation_task` dual-writes a `relationship="implementation"` row here **and** the `task_run` artefact; auto-start checks this table (not the freeform, API-mutable artefact log) when deciding whether an implementation has already started. Once `backfill_task_run_artefacts` has converted every legacy row into a `task_run` artefact, the gate can move to the artefact log and this table can be dropped.
### `SignalSourceConfig`
@@ -511,7 +521,7 @@ Per-scout binding for the headless **Signals agent**: one row per `(team, skill_
### `SignalScoutRun`
-Thin bridge from a Tasks `TaskRun` to the scout skill that ran inside it. Mirrors `SignalReportTask` (the bridge used by the SignalReport research flow): one scout-domain row per scheduled agent run that links its `TaskRun` to the skill it executed. Status, timing, error context, and the full chat log live on the `TaskRun`; emitted findings are `Signal` / `SignalReport` rows written by `emit_signal()`. This row carries only the scout-specific fields that need to be queryable as real columns.
+Thin bridge from a Tasks `TaskRun` to the scout skill that ran inside it: one scout-domain row per scheduled agent run that links its `TaskRun` to the skill it executed. Status, timing, error context, and the full chat log live on the `TaskRun`; emitted findings are `Signal` / `SignalReport` rows written by `emit_signal()`. This row carries only the scout-specific fields that need to be queryable as real columns.
| Field | Type | Description |
| --------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
@@ -737,7 +747,7 @@ Read + delete + state transitions. Uses `IsAuthenticated` + `APIScopePermission`
| Method | Path | Description |
| ------ | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| GET | `signals/reports/` | List reports. Excludes `deleted` always and excludes `suppressed` by default. Supports `?status=`, `?search=`, `?source_product=`, `?suggested_reviewers=`, and `?ordering=`. |
+| GET | `signals/reports/` | List reports. Excludes `deleted` always and excludes `suppressed` by default. Supports `?status=`, `?search=`, `?source_product=`, `?suggested_reviewers=`, `?task_id=` (resolved through `task_run` artefacts), and `?ordering=`. |
| GET | `signals/reports/{id}/` | Retrieve a single report |
| DELETE | `signals/reports/{id}/` | Soft-delete a report and its signals. Starts `SignalReportDeletionWorkflow`. On success returns `202`. If the workflow is already running, returns `200 {"status": "already_running"}`. The API immediately transitions the Postgres report to `deleted` to hide it from list results while ClickHouse cleanup runs asynchronously. |
| POST | `signals/reports/{id}/state/` | Transition report state. Body: `{ "state": "suppressed" \| "potential", ...transition_to kwargs }`. Only `suppressed` and `potential` are exposed via API. Returns `409` on invalid transitions and `400` on invalid arguments. |
@@ -764,15 +774,20 @@ So with `ordering=status`, **`failed` sorts after actionable `ready`**. With `or
Default ordering is **`-is_suggested_reviewer,status,-updated_at,id`**.
-#### `SignalReportTaskViewSet`
+#### `SignalReportArtefactViewSet`
-Read-only list of tasks associated with a signal report. Nested under the reports router.
+The artefact log read/write surface, nested under the reports router (`environment_signal_report_artefacts`). Team-scoped via `safely_get_queryset` (report id from the URL + `self.team`); gated by `scope_object = "task"`.
-| Method | Path | Description |
-| ------ | ----------------------------- | -------------------------------------------- |
-| GET | `signals/reports/{id}/tasks/` | List `SignalReportTask` entries for a report |
+| Method | Path | Description |
+| ------ | -------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
+| GET | `signals/reports/{id}/artefacts/` | List all artefacts for a report, ordered by `-created_at` |
+| GET | `signals/reports/{id}/artefacts/{aid}/` | Retrieve one artefact |
+| POST | `signals/reports/{id}/artefacts/` | Append an artefact of any type (status types append a new latest-wins row); per-type schema validation |
+| PATCH | `signals/reports/{id}/artefacts/{aid}/` | Edit a log/status row's content in place |
+| DELETE | `signals/reports/{id}/artefacts/{aid}/` | Delete an artefact row |
+| GET | `signals/reports/{id}/artefacts/{aid}/diff/` | Render a `commit` artefact's branch against the repo default branch via `GitHubIntegration.get_diff` |
-Supports ordering via `?ordering=` with fields: `created_at`, `relationship`. Default: `-created_at`. Each item includes `id`, `relationship`, `task_id`, and `created_at`.
+POSTing a `task_run` artefact is the "associate me" operation: `content.task_id` defaults from the `X-PostHog-Task-Id` header, `product`/`type` default to `tasks`/`agent_run`, the named task must belong to the team, and re-association is idempotent. The bespoke `suggested_reviewers` PUT (reviewer enrichment) also lives here. Writes are attributed to the header's task when present, else the requesting user.
#### `SignalProcessingViewSet`
@@ -829,9 +844,6 @@ Generated MCP tool names:
- Exposes `id`, `type`, `content`, `created_at`
- Parses JSON text into structured content
- For `suggested_reviewers`, enriches the stored GitHub-only payload with fresh PostHog org-member data at read time
-- **`SignalReportTaskSerializer`**
- - Exposes `id`, `relationship`, `task_id`, `task_title`, `task_status`, `created_at`
- - `task_status` is derived from the latest `TaskRun` via prefetch
---
@@ -949,7 +961,7 @@ The research flow produces:
These are assembled into `ReportResearchOutput`, then persisted by `run_agentic_report_activity`.
-A `SignalReportTask(relationship=RESEARCH)` row is created immediately after the `MultiTurnSession` starts (before any research turns), linking the sandbox `Task` to the report.
+A `task_run` artefact (`type=research`) is appended immediately after the `MultiTurnSession` starts (before any research turns), associating the sandbox `Task` with the report and attributing it to that task.
---
@@ -980,7 +992,7 @@ Runs inside `maybe_autostart_implementation_task()` in `backend/auto_start.py`,
- Report actionability is `immediately_actionable`
- Report has a `priority_judgment`
- Report has suggested reviewers
-- No existing `SignalReportTask` with `relationship=implementation` for this report
+- No legacy `SignalReportTask` implementation row exists for the report (checked inside a `select_for_update` on the report row, so concurrent evaluations can't double-start)
**User selection** via `_resolve_autostart_assignee()` in `backend/auto_start.py`:
@@ -995,7 +1007,7 @@ Runs inside `maybe_autostart_implementation_task()` in `backend/auto_start.py`,
**Task creation:**
1. `Task.create_and_run(origin_product=SIGNAL_REPORT, ...)`
-2. Create `SignalReportTask(relationship=IMPLEMENTATION)` linking the task to the report
+2. `record_implementation_task` writes the legacy `SignalReportTask` implementation gate row (in the same transaction) and appends an `implementation` `task_run` artefact
3. Errors are caught and logged but do not fail the report workflow
### Priority Rank
@@ -1004,15 +1016,9 @@ Runs inside `maybe_autostart_implementation_task()` in `backend/auto_start.py`,
### Task Tracking
-All report ↔ task relationships are tracked via `SignalReportTask`:
-
-| Relationship | Created when | Created where |
-| ---------------- | ----------------------------------------------------- | ------------------------------------------------------------------ |
-| `research` | Immediately after the research sandbox session starts | `run_multi_turn_research()` in `report_generation/research.py` |
-| `implementation` | After auto-starting a coding task | `maybe_autostart_implementation_task()` in `backend/auto_start.py` |
-| `repo_selection` | Reserved for future use | Not yet created anywhere |
+Report ↔ task relationships are recorded as `task_run` artefacts (see `SignalReportArtefact`), one per associated run, with the run's purpose carried in the artefact's `(product, type)`. The built-in pipeline writes `product="signals"` with `type` in `{research, implementation, repo_selection}`; custom agents supply their own `identifier()` pair.
-Both `report` and `task` FKs cascade on delete — deleting a report or task cleans up the relationship rows automatically.
+Auto-start dedup is separate from this freeform log: `maybe_autostart_implementation_task()` (`backend/auto_start.py`) gates on a legacy `SignalReportTask` implementation row, checked inside the report-row `select_for_update`, so concurrent evaluations can't double-start. Both the auto-start and the manual tasks-API path go through `record_implementation_task`, which dual-writes that gate row and the `implementation` `task_run` artefact — the transitional arrangement until the backfill lets the gate move to artefacts (see `SignalReportTask`).
### Eval-signal summarization (`backend/temporal/emit_eval_signal.py`)
@@ -1111,9 +1117,9 @@ products/signals/
│ ├── api.py # emit_signal() entry point + source/org guards
│ ├── apps.py # Django app config
│ ├── models.py # SignalReport, SignalReportArtefact, SignalTeamConfig, SignalUserAutonomyConfig, SignalReportTask, SignalSourceConfig, SignalScoutConfig, SignalScoutRun, SignalScratchpad, SignalProjectProfile, SignalEmissionRecord
-│ ├── serializers.py # DRF serializers for source configs, reports, artefacts, team config, user autonomy config, report tasks
+│ ├── serializers.py # DRF serializers for source configs, reports, artefacts, team config, user autonomy config
│ ├── utils.py # Compatibility re-exports for signal query helpers
-│ ├── views.py # SignalViewSet, InternalSignalViewSet, SignalSourceConfigViewSet, SignalTeamConfigViewSet, SignalReportViewSet, SignalReportTaskViewSet, SignalProcessingViewSet
+│ ├── views.py # SignalViewSet, InternalSignalViewSet, SignalSourceConfigViewSet, SignalTeamConfigViewSet, SignalReportViewSet, SignalReportArtefactViewSet, SignalProcessingViewSet
│ ├── scout_harness/ # Headless Signals agent — see scout_harness/AGENTS.md
│ │ ├── AGENTS.md
│ │ ├── __init__.py # Public re-exports (LoadedSkill, sync helpers, …)
@@ -1155,7 +1161,7 @@ products/signals/
│ │ └── sync_signals_scout_skills.py # Force a canonical SKILL.md sync to LLMSkill rows
│ ├── report_generation/
│ │ ├── AGENTS.md # Documentation for the agentic report generation flow
-│ │ ├── research.py # Multi-turn sandbox research orchestration + output schemas + SignalReportTask(RESEARCH) creation
+│ │ ├── research.py # Multi-turn sandbox research orchestration + output schemas + research task_run artefact creation
│ │ ├── resolve_reviewers.py # Suggested-reviewer resolution and enrichment helpers
│ │ └── select_repo.py # Repository selection sandbox flow
│ ├── test/
diff --git a/products/signals/backend/artefact_schemas.py b/products/signals/backend/artefact_schemas.py
new file mode 100644
index 000000000000..6d05ec4278db
--- /dev/null
+++ b/products/signals/backend/artefact_schemas.py
@@ -0,0 +1,451 @@
+"""Pydantic content schemas for `SignalReportArtefact` rows.
+
+Each `SignalReportArtefact` stores its typed payload as JSON text in `content`. This module is
+the canonical home of every artefact content shape: one model per artefact type. Raw payloads
+are parsed into these models once, at the boundaries — `parse_artefact_content` for API writes
+and for reads that consume stored rows — and everything in between passes the typed model
+around; the model helpers derive a row's type from the content model's class. The module is
+kept deliberately dependency-light so models, views, and temporal code can all import it without
+pulling in the report-research / sandbox machinery — its only non-pydantic import is a leaf DTO that
+carries no such weight: the cross-product `RepoSelectionResult` (`tasks` facade types re-export).
+`RelevantCommit` is defined here rather than reused from the generated `posthog.schema`: importing
+that module drags ~1s of generated pydantic onto every process's `django.setup()` path, since this
+module loads with the signals models (see docs/internal/django-startup-time.md).
+
+Reads of legacy rows that predate these schemas stay tolerant (parse failures are skipped or
+degraded, never raised to users).
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Mapping
+from enum import Enum
+from typing import Any, cast
+
+from pydantic import BaseModel, ConfigDict, Field, RootModel, ValidationError, field_validator, model_validator
+
+from products.tasks.backend.facade.repo_selection_types import RepoSelectionResult
+
+# Product / type identifier parts must be routing-safe — mirrors the custom-agent identifier
+# contract (see custom_agent.schemas.validate_identifier_part), kept inline so this module stays
+# dependency-light (pydantic only).
+_IDENTIFIER_PART_RE = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
+
+
+class ArtefactContentValidationError(ValueError):
+ """Raised when artefact content does not match the schema registered for its type."""
+
+
+# ── Status artefact schemas ──────────────────────────────────────────────────────
+#
+# Status artefacts describe the report's current state (judgments, repo selection, suggested
+# reviewers); append-only, latest row of each type wins. The judgment models double as LLM
+# output schemas in `report_generation/research.py` — their field descriptions are prompt
+# material, not just docs.
+
+
+class ActionabilityChoice(str, Enum):
+ IMMEDIATELY_ACTIONABLE = "immediately_actionable"
+ REQUIRES_HUMAN_INPUT = "requires_human_input"
+ NOT_ACTIONABLE = "not_actionable"
+
+
+class Priority(str, Enum):
+ P0 = "P0"
+ P1 = "P1"
+ P2 = "P2"
+ P3 = "P3"
+ P4 = "P4"
+
+
+class SignalFinding(BaseModel):
+ """Content schema for a `signal_finding` artefact: one investigation result per signal."""
+
+ signal_id: str = Field(description="The signal_id from the input signal list")
+ relevant_code_paths: list[str] = Field(
+ description=(
+ "File paths in the codebase relevant to this signal, ordered from most critical first. "
+ "The first path should be the highest-impact file (e.g. the buggy module or core feature file). "
+ "Then include supporting paths."
+ ),
+ )
+ relevant_commit_hashes: dict[str, str] = Field(
+ default_factory=dict,
+ json_schema_extra={"minProperties": 1},
+ description=(
+ "A mapping of 'git commit short SHA (7 characters)' -> 'reason'. "
+ "Values are short explanations of WHY each commit is relevant. "
+ "Use `git blame` on the most critical code paths to identify commits that caused, or are most closely related to, "
+ "the issue described by this report. Prioritize causative commits "
+ "(e.g. the commit that introduced a bug) over general authorship commits. Include 1-5 commits."
+ ),
+ )
+ data_queried: str = Field(
+ description=(
+ "What PostHog MCP queries you ran (e.g. execute-sql, query-run, insight-query) "
+ "and what the results showed. If no relevant queries could be run, explain why."
+ ),
+ )
+ verified: bool = Field(
+ description=(
+ "Whether you could confirm the signal's claim by finding supporting evidence "
+ "in code or data. False if the claim couldn't be verified either way."
+ ),
+ )
+
+
+class ActionabilityAssessment(BaseModel):
+ """Content schema for an `actionability_judgment` artefact."""
+
+ explanation: str = Field(
+ description=(
+ "2-3 sentence evidence-grounded explanation of your actionability assessment. "
+ "Reference specific code paths and data points from your research."
+ ),
+ )
+ actionability: ActionabilityChoice = Field(
+ description="Overall actionability assessment. Must be one of the allowed enum values — do not invent new ones.",
+ )
+ already_addressed: bool = Field(
+ description=(
+ "Whether the core issue described by this report appears to have been "
+ "already fixed or addressed in recent code changes. Tracked separately from `actionability`."
+ ),
+ )
+
+ @field_validator("explanation")
+ @classmethod
+ def explanation_must_not_be_empty(cls, v: str) -> str:
+ if not v.strip():
+ raise ValueError("Explanation must not be empty")
+ return v
+
+
+class PriorityAssessment(BaseModel):
+ """Content schema for a `priority_judgment` artefact."""
+
+ explanation: str = Field(
+ description=(
+ "2-3 sentence justification for the priority level. "
+ "Cite a quantified figure from your research — error frequency, affected user/session count, "
+ "or scope of affected code paths. If impact could not be measured, say so explicitly and explain "
+ "why the priority is not lowered further."
+ ),
+ )
+ priority: Priority = Field(description="Priority (P0-P4)")
+ dollar_value: float | None = Field(
+ default=None,
+ description=(
+ "Peak estimate (USD) of the real dollar value of merging the fix/change this report leads to. "
+ "Reason internally about a plausible value range first; set this to the most likely point "
+ "within that range (the peak of your belief distribution). Should align with the assigned "
+ "priority. Nullable for backward compatibility only — prefer a best-effort peak over null."
+ ),
+ )
+
+ @field_validator("explanation")
+ @classmethod
+ def explanation_must_not_be_empty(cls, v: str) -> str:
+ if not v.strip():
+ raise ValueError("Explanation must not be empty")
+ return v
+
+
+class SafetyJudgment(BaseModel):
+ """Content schema for a `safety_judgment` artefact: the prompt-injection safety verdict."""
+
+ choice: bool = Field(description="True when the report's signals are judged safe to act on.")
+ explanation: str | None = Field(
+ default=None, description="Why the report was judged unsafe; null/omitted when safe."
+ )
+
+
+class RelevantCommit(BaseModel):
+ """A commit attributed to a suggested reviewer. Shape mirrors the generated
+ `posthog.schema.RelevantCommit` exactly so the two stay interchangeable on the wire — defined
+ here to keep this module off the heavy `posthog.schema` import path (see module docstring)."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ reason: str
+ sha: str
+ url: str
+
+
+class SuggestedReviewerEntry(BaseModel):
+ """One reviewer in a `suggested_reviewers` artefact's content list."""
+
+ github_login: str = Field(description="GitHub login identifying the reviewer (stored lowercased).")
+ github_name: str | None = Field(default=None, description="Optional human-readable display name.")
+ relevant_commits: list[RelevantCommit] = Field(
+ default_factory=list,
+ description="Commit evidence explaining why this reviewer is relevant.",
+ )
+
+ @field_validator("github_login")
+ @classmethod
+ def github_login_must_not_be_empty(cls, v: str) -> str:
+ if not v.strip():
+ raise ValueError("must not be empty or whitespace-only")
+ return v
+
+
+class SuggestedReviewers(RootModel[list[SuggestedReviewerEntry]]):
+ """Content schema for a `suggested_reviewers` artefact — the content root is a JSON list."""
+
+
+class Dismissal(BaseModel):
+ """Content schema for a `dismissal` artefact: feedback captured when a report is dismissed/snoozed.
+
+ The user fields predate row-level attribution and are kept for compatibility with existing
+ rows and readers; new rows also carry attribution on the artefact row itself.
+ """
+
+ reason: str | None = Field(default=None, description="Caller-owned dismissal reason code.")
+ note: str | None = Field(default=None, description="Free-form dismissal note.")
+ user_id: int | None = Field(default=None, description="ID of the dismissing user, when known.")
+ user_uuid: str | None = Field(default=None, description="UUID of the dismissing user, when known.")
+ slack_user_id: str | None = Field(
+ default=None, description="Slack user who dismissed via a Slack action, when that's where the click came from."
+ )
+
+
+class VideoSegment(RootModel[dict[str, Any] | list[Any]]):
+ """Content schema for a `video_segment` artefact.
+
+ Deliberately permissive: the type predates this registry and has no in-repo production
+ writer, so any JSON object/array validates rather than guessing at a shape.
+ """
+
+
+# ── Log artefact schemas ─────────────────────────────────────────────────────────
+#
+# Log artefacts record discrete work done on a report; they accumulate and are addressable by id.
+
+
+# Bounds for referenced source text: references are pointers with a small excerpt, not a vehicle
+# for shipping file contents into the report log.
+_MAX_CODE_LINE_LENGTH = 1000
+_MAX_CODE_REFERENCE_LINES = 20
+
+
+class CodeReference(BaseModel):
+ """Content schema for a `code_reference` artefact: a contiguous span of source lines.
+
+ A single-line callout is just `start_line == end_line`.
+ """
+
+ file_path: str = Field(description="Repository-relative path to the referenced file.")
+ start_line: int = Field(ge=1, description="First line of the referenced range (1-indexed, inclusive).")
+ end_line: int = Field(ge=1, description="Last line of the referenced range (1-indexed, inclusive).")
+ contents: str = Field(
+ description=f"The exact source text of lines start_line through end_line. At most "
+ f"{_MAX_CODE_REFERENCE_LINES} lines of at most {_MAX_CODE_LINE_LENGTH} characters each."
+ )
+ relevance_note: str = Field(
+ description="Short note on why this code is relevant to the report.",
+ )
+
+ @field_validator("file_path", "contents", "relevance_note")
+ @classmethod
+ def fields_must_not_be_empty(cls, v: str) -> str:
+ if not v.strip():
+ raise ValueError("must not be empty or whitespace-only")
+ return v
+
+ @field_validator("contents")
+ @classmethod
+ def contents_must_be_bounded(cls, v: str) -> str:
+ lines = v.split("\n")
+ if len(lines) > _MAX_CODE_REFERENCE_LINES:
+ raise ValueError(f"must not exceed {_MAX_CODE_REFERENCE_LINES} lines")
+ if any(len(line) > _MAX_CODE_LINE_LENGTH for line in lines):
+ raise ValueError(f"lines must not exceed {_MAX_CODE_LINE_LENGTH} characters")
+ return v
+
+ @model_validator(mode="after")
+ def line_span_must_be_valid(self) -> CodeReference:
+ if self.end_line < self.start_line:
+ raise ValueError("end_line must be greater than or equal to start_line")
+ if self.end_line - self.start_line + 1 > _MAX_CODE_REFERENCE_LINES:
+ raise ValueError(f"the referenced range must not exceed {_MAX_CODE_REFERENCE_LINES} lines")
+ return self
+
+
+class Commit(BaseModel):
+ """Content schema for a `commit` artefact: one commit pushed in relation to the report.
+
+ Recorded automatically by the agent harness after each successful signed-commit push (one
+ artefact per commit), so the report log shows exactly what landed, when, and from which task.
+ A `commit` artefact only ever records a commit that has already been pushed to a remote branch;
+ recording an unpushed or local-only commit is always a mistake.
+ """
+
+ repository: str = Field(description="GitHub repository the commit was pushed to, as `owner/repo`.")
+ branch: str = Field(description="Branch the commit was pushed to.")
+ commit_sha: str = Field(description="Full or abbreviated SHA of the pushed commit.")
+ message: str = Field(description="The commit message headline.")
+ note: str | None = Field(default=None, description="Optional short note on what this commit does.")
+
+ @field_validator("repository", "branch", "commit_sha", "message")
+ @classmethod
+ def fields_must_not_be_empty(cls, v: str) -> str:
+ if not v.strip():
+ raise ValueError("must not be empty or whitespace-only")
+ return v
+
+
+class TaskRunArtefact(BaseModel):
+ """Content schema for a `task_run` artefact: a reference to a `tasks.Task` run executed for
+ the report (research, implementation, …), surfaced as an entry in the report work log.
+
+ `product` / `type` follow the custom-agent identifier shape: the built-in signals pipeline
+ uses `product="signals"` with `type` in `{research, implementation, repo_selection}`, while a
+ custom agent supplies its own `identifier()` pair. The artefact is only a pointer — the run's
+ logs, status and output are read live from the tasks API by `task_id` / `run_id`.
+ """
+
+ task_id: str = Field(description="UUID of the `tasks.Task` this run belongs to.")
+ run_id: str | None = Field(default=None, description="UUID of the specific `TaskRun`, if known.")
+ product: str = Field(
+ description="Product that ran the task — `signals` for the built-in pipeline, or a custom agent's "
+ "product identifier."
+ )
+ type: str = Field(
+ description="Task type within the product — e.g. `research` / `implementation` / `repo_selection` "
+ "for the signals pipeline, or a custom agent's type identifier."
+ )
+
+ @field_validator("task_id")
+ @classmethod
+ def task_id_must_not_be_empty(cls, v: str) -> str:
+ if not v.strip():
+ raise ValueError("must not be empty or whitespace-only")
+ return v
+
+ @field_validator("product", "type")
+ @classmethod
+ def identifier_part_must_be_routing_safe(cls, v: str) -> str:
+ normalized = v.strip()
+ if not _IDENTIFIER_PART_RE.fullmatch(normalized):
+ raise ValueError(
+ "must contain only lowercase letters, numbers, underscores, or hyphens, "
+ "and must start with a lowercase letter or number"
+ )
+ return normalized
+
+
+# ── Task-run vocabulary ──────────────────────────────────────────────────────────
+#
+# A `task_run` artefact carries a `(product, type)` pair. The built-in signals pipeline uses
+# `product="signals"` with one of the `TASK_RUN_TYPE_*` types below; custom agents supply their
+# own identifier pair. These live in this leaf module so both the artefact helpers and the
+# `SignalReport` model can share them without an import cycle (`task_run_artefacts` re-exports
+# them for existing importers).
+SIGNALS_PRODUCT = "signals"
+
+TASK_RUN_TYPE_REPO_SELECTION = "repo_selection"
+TASK_RUN_TYPE_RESEARCH = "research"
+TASK_RUN_TYPE_IMPLEMENTATION = "implementation"
+
+# Generic identifiers for a legacy `SignalReportTask` row with no `(product, type)` label — an
+# unlabelled link from the brief link-only window before associations carried identifiers.
+_LEGACY_TASK_RUN_PRODUCT = "tasks"
+_LEGACY_TASK_RUN_TYPE = "agent_run"
+
+_SIGNALS_TASK_RUN_TYPES = frozenset(
+ {TASK_RUN_TYPE_REPO_SELECTION, TASK_RUN_TYPE_RESEARCH, TASK_RUN_TYPE_IMPLEMENTATION}
+)
+
+
+def task_run_identifier_for_legacy_relationship(relationship: str | None) -> tuple[str, str]:
+ """Map a legacy `SignalReportTask.relationship` to the `(product, type)` its `task_run` artefact
+ would carry — the same mapping `backfill_task_run_artefacts` applies. A labelled signals
+ relationship keeps its label under `product="signals"`; anything else (including the unlabelled
+ link-only rows) collapses to the generic `tasks` / `agent_run` identifiers.
+ """
+ if relationship is not None and relationship in _SIGNALS_TASK_RUN_TYPES:
+ return SIGNALS_PRODUCT, relationship
+ return _LEGACY_TASK_RUN_PRODUCT, _LEGACY_TASK_RUN_TYPE
+
+
+class NoteArtefact(BaseModel):
+ """Content schema for a `note` artefact: a free-form note authored by an agent or by code."""
+
+ note: str = Field(description="The note text (markdown allowed).")
+ author: str | None = Field(default=None, description="Optional label for who authored the note.")
+
+ @field_validator("note")
+ @classmethod
+ def note_must_not_be_empty(cls, v: str) -> str:
+ if not v.strip():
+ raise ValueError("must not be empty or whitespace-only")
+ return v
+
+
+# ── Type mapping ─────────────────────────────────────────────────────────────────
+
+# Content models that describe the report's current state (latest row of each type wins) vs
+# entries that record discrete work (accumulate). `SignalFinding` (keyed by signal_id) and
+# `Dismissal` (stacking) have their own semantics; `VideoSegment` is a legacy plain append.
+StatusArtefactContent = (
+ SafetyJudgment | ActionabilityAssessment | PriorityAssessment | RepoSelectionResult | SuggestedReviewers
+)
+LogArtefactContent = CodeReference | Commit | TaskRunArtefact | NoteArtefact
+ArtefactContent = StatusArtefactContent | LogArtefactContent | SignalFinding | Dismissal | VideoSegment
+
+# Keys are `SignalReportArtefact.ArtefactType` values, kept as plain strings so this module stays
+# Django-free; a test asserts the key set matches the model enum exactly.
+ARTEFACT_CONTENT_SCHEMAS: Mapping[str, type[BaseModel]] = {
+ "video_segment": VideoSegment,
+ "safety_judgment": SafetyJudgment,
+ "actionability_judgment": ActionabilityAssessment,
+ "priority_judgment": PriorityAssessment,
+ "signal_finding": SignalFinding,
+ "repo_selection": RepoSelectionResult,
+ "suggested_reviewers": SuggestedReviewers,
+ "dismissal": Dismissal,
+ "code_reference": CodeReference,
+ "commit": Commit,
+ "task_run": TaskRunArtefact,
+ "note": NoteArtefact,
+}
+
+_ARTEFACT_TYPE_BY_MODEL: Mapping[type[BaseModel], str] = {model: t for t, model in ARTEFACT_CONTENT_SCHEMAS.items()}
+
+# Artefact types the write API must reject. `video_segment` is a legacy, fully-permissive type
+# (`dict | list`, so even `{}` validates) that predates the typed-content contract; accepting writes
+# would let callers persist arbitrary or empty payloads. It stays readable so stored legacy rows
+# still parse, but new ones can never be created or updated through the API.
+NON_WRITABLE_ARTEFACT_TYPES: frozenset[str] = frozenset({"video_segment"})
+
+
+def artefact_type_for(content: BaseModel) -> str:
+ """The artefact type a content model persists as (exact class match).
+
+ Deriving the row's type from the model class makes a type/content mismatch unrepresentable.
+ Raises `ArtefactContentValidationError` for models that aren't artefact content schemas.
+ """
+ artefact_type = _ARTEFACT_TYPE_BY_MODEL.get(type(content))
+ if artefact_type is None:
+ raise ArtefactContentValidationError(f"{type(content).__name__} is not an artefact content model")
+ return artefact_type
+
+
+def parse_artefact_content(artefact_type: str, content: str | dict | list) -> ArtefactContent:
+ """Parse a raw payload (JSON text or deserialized JSON) into `artefact_type`'s content model.
+
+ The boundary parser: API writes and reads of stored rows come through here once, and
+ everything past the boundary passes the typed model around. Raises
+ `ArtefactContentValidationError` on an unknown type, malformed JSON, or schema mismatch.
+ """
+ schema = ARTEFACT_CONTENT_SCHEMAS.get(artefact_type)
+ if schema is None:
+ raise ArtefactContentValidationError(f"Unknown artefact type {artefact_type!r}")
+ try:
+ if isinstance(content, str):
+ return cast(ArtefactContent, schema.model_validate_json(content))
+ return cast(ArtefactContent, schema.model_validate(content))
+ except ValidationError as e:
+ raise ArtefactContentValidationError(str(e)) from e
diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.py
index c2ee69b732d0..8f80ba30a314 100644
--- a/products/signals/backend/auto_start.py
+++ b/products/signals/backend/auto_start.py
@@ -1,13 +1,22 @@
from __future__ import annotations
-from typing import TypedDict
+import json
+from typing import TypedDict, TypeVar
+
+from django.db import transaction
import structlog
+from pydantic import BaseModel, ValidationError
from posthog.models import Team, User
from posthog.sync import database_sync_to_async
-from products.signals.backend.models import SignalReportTask, SignalTeamConfig, SignalUserAutonomyConfig
+from products.signals.backend.models import (
+ SignalReport,
+ SignalReportArtefact,
+ SignalTeamConfig,
+ SignalUserAutonomyConfig,
+)
from products.signals.backend.report_generation.research import (
ActionabilityAssessment,
ActionabilityChoice,
@@ -15,11 +24,19 @@ from products.signals.backend.report_generation.research import (
PriorityAssessment,
)
from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users
+from products.signals.backend.report_generation.select_repo import RepoSelectionResult
from products.signals.backend.slack_inbox_notifications import POSTHOG_CODE_INBOX_DEEP_LINK_SCHEME
+from products.signals.backend.task_run_artefacts import (
+ SIGNALS_PRODUCT,
+ TASK_RUN_TYPE_IMPLEMENTATION,
+ record_implementation_task,
+)
from products.tasks.backend.facade import api as tasks_facade
logger = structlog.get_logger(__name__)
+_M = TypeVar("_M", bound=BaseModel)
+
class ReviewerContent(TypedDict):
github_login: str
@@ -75,6 +92,69 @@ def _build_autostart_task_description(
)
+def _create_implementation_task_if_absent(
+ *,
+ team_id: int,
+ report_id: str,
+ title: str,
+ description: str,
+ user_id: int,
+ repository: str,
+ base_branch: str | None,
+) -> bool:
+ """Create the implementation task and record it (gate row + work-log artefact), serialized per report.
+
+ Auto-start is re-evaluated from several independent paths — the reviewer-edit on-commit hook,
+ the agentic pipeline, and custom agents — so two evaluations can race. A bare check-then-create
+ would let both observe "no implementation task yet" and each spawn one (duplicate Temporal
+ workflow, duplicate draft PR, duplicate spend). Locking the `SignalReport` row and re-checking
+ inside the lock makes the decision atomic: the second evaluation blocks, then sees the gate and
+ returns ``False``. Returns ``True`` if it created the task, ``False`` if one already exists / the
+ report is gone.
+ """
+ with transaction.atomic():
+ report = SignalReport.objects.select_for_update().filter(id=report_id, team_id=team_id).first()
+ if report is None:
+ return False
+ # The gate reads the unified task↔report view (`associated_task_runs` merges the legacy
+ # `SignalReportTask` rows with the `task_run` artefact log). Unifying only *adds* sources,
+ # so it can never under-detect a started implementation — and `record_implementation_task`
+ # below always writes the `SignalReportTask` row, so deleting the (API-mutable) artefact
+ # can't reopen the gate. Both writes happen under this lock, so a racing evaluation that
+ # blocks here observes them and returns False.
+ if SignalReport.associated_task_runs(
+ report_id=report_id, team_id=team_id, product=SIGNALS_PRODUCT, type=TASK_RUN_TYPE_IMPLEMENTATION
+ ):
+ return False
+ team = Team.objects.select_related("organization").get(id=team_id)
+ created = tasks_facade.create_and_run_task(
+ team=team,
+ title=title,
+ description=description,
+ origin_product=tasks_facade.TaskOriginProduct.SIGNAL_REPORT,
+ user_id=user_id,
+ repository=repository,
+ branch=base_branch,
+ signal_report_id=report_id,
+ # Full scopes so the implementation agent can log its work on the report (notes,
+ # code references) via the task:write artefact tools.
+ posthog_mcp_scopes="full",
+ interaction_origin="signal_report", # Makes the agent auto-push and open a draft PR
+ ai_stage="implementation",
+ )
+ if created.latest_run is None:
+ raise RuntimeError(f"Task {created.task_id} auto-started without producing a TaskRun")
+ # Written inside the lock so the gate check above and this write are serialized — the
+ # `SignalReportTask` gate row must be visible before the lock releases.
+ record_implementation_task(
+ team_id=team_id,
+ report_id=report_id,
+ task_id=str(created.task_id),
+ run_id=str(created.latest_run.id),
+ )
+ return True
+
+
def _resolve_autostart_assignee(
team_id: int,
report_priority: Priority,
@@ -149,29 +229,43 @@ async def maybe_autostart_implementation_task(
) -> None:
"""Start an implementation Task for a SignalReport if autonomy + priority allow it.
- Idempotent: skipped if an IMPLEMENTATION task already exists for the report,
- if the report is not immediately actionable, if it's already addressed, if
- priority is missing, if there are no suggested reviewers, or if no reviewer's
- autonomy threshold is met.
+ Idempotent: skipped if an implementation task already started for the report
+ (a `SignalReportTask` implementation gate row), if the report is not immediately
+ actionable, if it's already addressed, if priority is missing, if there are no
+ suggested reviewers, or if no reviewer's autonomy threshold is met. The
+ "already started" check is enforced atomically under a row lock in
+ `_create_implementation_task_if_absent`, so concurrent evaluations
+ (reviewer-edit hook, pipeline, custom agent) can't double-start.
Both the agentic signals pipeline (``temporal/agentic/report.py``) and the
custom agent activity (``temporal/custom_agent.py``) call this after persisting
their report and artefacts. Callers should wrap this in try/except so an
autostart failure does not fail the report itself.
"""
- task_exists = await SignalReportTask.objects.filter(
- team_id=team_id, report_id=report_id, relationship=SignalReportTask.Relationship.IMPLEMENTATION
- ).aexists()
- if (
- actionability.actionability != ActionabilityChoice.IMMEDIATELY_ACTIONABLE
- or actionability.already_addressed
- or priority is None
- or not reviewers_content
- or task_exists
- ):
+ # Cheap pre-check to skip the expensive assignee resolution when a task already exists;
+ # the authoritative, race-free check happens under the lock below.
+ task_exists = bool(
+ await SignalReport.aassociated_task_runs(
+ report_id=report_id, team_id=team_id, product=SIGNALS_PRODUCT, type=TASK_RUN_TYPE_IMPLEMENTATION
+ )
+ )
+ skip_reason: str | None = None
+ if task_exists:
+ skip_reason = "implementation task already exists"
+ elif actionability.actionability != ActionabilityChoice.IMMEDIATELY_ACTIONABLE:
+ skip_reason = f"not immediately actionable: {actionability.actionability.value}"
+ elif actionability.already_addressed:
+ skip_reason = "report already addressed"
+ elif priority is None:
+ skip_reason = "no priority assessment"
+ elif not reviewers_content:
+ skip_reason = "no suggested reviewers"
+ if skip_reason is not None:
+ logger.info("signals auto-start skipped", report_id=report_id, team_id=team_id, reason=skip_reason)
return
- team = await Team.objects.select_related("organization").aget(id=team_id)
+ assert priority is not None # narrowed by the `priority is None` skip_reason guard above
+
team_config = await SignalTeamConfig.objects.filter(team_id=team_id).afirst()
team_default_priority = Priority(team_config.default_autostart_priority) if team_config else Priority.P4
@@ -179,33 +273,141 @@ async def maybe_autostart_implementation_task(
team_id, priority.priority, reviewers_content, team_default_priority
)
if task_user is None:
+ logger.info(
+ "signals auto-start skipped",
+ report_id=report_id,
+ team_id=team_id,
+ reason="no reviewer meets the autonomy priority threshold",
+ )
return
base_branch = None
if repository and team_config:
base_branch = (team_config.autostart_base_branches or {}).get(repository.lower())
- created = await database_sync_to_async(tasks_facade.create_and_run_task, thread_sensitive=False)(
- team=team,
+ created = await database_sync_to_async(_create_implementation_task_if_absent, thread_sensitive=False)(
+ team_id=team_id,
+ report_id=report_id,
title=title,
description=_build_autostart_task_description(
report_id=report_id, summary=summary, repository=repository, priority=priority
),
- origin_product=tasks_facade.TaskOriginProduct.SIGNAL_REPORT,
user_id=task_user.id,
repository=repository,
- branch=base_branch,
- signal_report_id=report_id,
- posthog_mcp_scopes="read_only",
- interaction_origin="signal_report", # Makes the agent auto-push and open a draft PR
- ai_stage="implementation",
+ base_branch=base_branch,
+ )
+ if not created:
+ # Another evaluation won the race and already created the implementation task.
+ logger.info("signals auto-start skipped", report_id=report_id, team_id=team_id, reason="lost create race")
+ return
+
+
+async def _latest_artefact_as(report_id: str, artefact_type: str, model_cls: type[_M]) -> _M | None:
+ """Parse the latest artefact of ``artefact_type`` for a report (append-only, latest-wins)."""
+ artefact = (
+ await SignalReportArtefact.objects.filter(report_id=report_id, type=artefact_type)
+ .order_by("-created_at")
+ .afirst()
+ )
+ if artefact is None:
+ return None
+ try:
+ return model_cls.model_validate_json(artefact.content)
+ except ValidationError:
+ return None
+
+
+async def _latest_reviewers_content(report_id: str) -> list[ReviewerContent]:
+ artefact = (
+ await SignalReportArtefact.objects.filter(
+ report_id=report_id, type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS
+ )
+ .order_by("-created_at")
+ .afirst()
+ )
+ if artefact is None:
+ return []
+ try:
+ data = json.loads(artefact.content)
+ except (json.JSONDecodeError, ValueError):
+ return []
+ if not isinstance(data, list):
+ return []
+ reviewers: list[ReviewerContent] = []
+ for entry in data:
+ if isinstance(entry, dict) and entry.get("github_login"):
+ reviewers.append(
+ ReviewerContent(
+ github_login=str(entry["github_login"]),
+ github_name=entry.get("github_name"),
+ relevant_commits=entry.get("relevant_commits") or [],
+ )
+ )
+ return reviewers
+
+
+async def maybe_autostart_from_report_artefacts(*, team_id: int, report_id: str) -> None:
+ """Re-evaluate auto-start from a report's *current* artefacts.
+
+ Called when reviewers change after the report was created (e.g. a human edits them via the
+ artefact API), so a newly-qualifying reviewer can still trigger auto-start. Reconstructs the
+ latest actionability / priority / repo-selection / suggested-reviewers and delegates to
+ `maybe_autostart_implementation_task`, which is idempotent — it no-ops if an implementation
+ task already exists for the report.
+ """
+ report = await SignalReport.objects.filter(id=report_id, team_id=team_id).only("title", "summary").afirst()
+ if report is None or not report.title or not report.summary:
+ logger.info(
+ "signals auto-start re-eval skipped",
+ report_id=report_id,
+ team_id=team_id,
+ reason="report missing or not yet summarized",
+ )
+ return
+
+ actionability = await _latest_artefact_as(
+ report_id, SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT, ActionabilityAssessment
+ )
+ if actionability is None:
+ logger.info(
+ "signals auto-start re-eval skipped",
+ report_id=report_id,
+ team_id=team_id,
+ reason="no actionability artefact",
+ )
+ return
+ repo_selection = await _latest_artefact_as(
+ report_id, SignalReportArtefact.ArtefactType.REPO_SELECTION, RepoSelectionResult
)
- if created.latest_run is None:
- raise RuntimeError(f"Task {created.task_id} auto-started without producing a TaskRun")
+ repository = repo_selection.repository if repo_selection else None
+ if not repository:
+ logger.info(
+ "signals auto-start re-eval skipped",
+ report_id=report_id,
+ team_id=team_id,
+ reason="no repository selected",
+ )
+ return
+ priority = await _latest_artefact_as(
+ report_id, SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT, PriorityAssessment
+ )
+ reviewers_content = await _latest_reviewers_content(report_id)
+ if not reviewers_content:
+ logger.info(
+ "signals auto-start re-eval skipped",
+ report_id=report_id,
+ team_id=team_id,
+ reason="no suggested reviewers",
+ )
+ return
- await SignalReportTask.objects.acreate(
+ await maybe_autostart_implementation_task(
team_id=team_id,
report_id=report_id,
- task_id=created.task_id,
- relationship=SignalReportTask.Relationship.IMPLEMENTATION,
+ repository=repository,
+ title=report.title,
+ summary=report.summary,
+ actionability=actionability,
+ reviewers_content=reviewers_content,
+ priority=priority,
)
diff --git a/products/signals/backend/billing.py b/products/signals/backend/billing.py
index 2262542b26c6..b79bba15e189 100644
--- a/products/signals/backend/billing.py
+++ b/products/signals/backend/billing.py
@@ -6,7 +6,7 @@ deterministic — the first implementation `TaskRun` with a `pr_url` set — so
billed exactly once, in the period that PR first appeared, regardless of any later status
changes, re-judgements, or additional runs.
-The PR↔report link lives on the `SignalReportTask` bridge (relationship=IMPLEMENTATION); the
+The PR↔report link lives on the `SignalReportTask` bridge (relationship="implementation"); the
PR URL itself is written to `TaskRun.output['pr_url']`. There is no artefact that records the
implementation task or its PR, so the query is rooted on that bridge, not on artefacts.
@@ -24,9 +24,10 @@ from datetime import datetime
from django.db.models import F, QuerySet
+from products.signals.backend.artefact_schemas import TASK_RUN_TYPE_IMPLEMENTATION
from products.signals.backend.models import SignalReportTask
-_IMPLEMENTATION = SignalReportTask.Relationship.IMPLEMENTATION
+_IMPLEMENTATION = TASK_RUN_TYPE_IMPLEMENTATION
# Only PRs hosted on GitHub are billable. The PR URL is GitHub's `html_url`
# (https://github.com/owner/repo/pull/N), so validate the host prefix to avoid charging
diff --git a/products/signals/backend/custom_agent/base.py b/products/signals/backend/custom_agent/base.py
index 9a6596d7af05..baf33c799fe9 100644
--- a/products/signals/backend/custom_agent/base.py
+++ b/products/signals/backend/custom_agent/base.py
@@ -10,7 +10,8 @@ from pydantic import BaseModel, Field, ValidationError
from posthog.models import Team
from posthog.sync import database_sync_to_async
-from products.signals.backend.auto_start import ReviewerContent, maybe_autostart_implementation_task
+from products.signals.backend.artefact_schemas import ArtefactContent, artefact_type_for
+from products.signals.backend.auto_start import maybe_autostart_from_report_artefacts
from products.signals.backend.custom_agent.persistence import (
PersistedCustomAgentReport,
create_custom_agent_ready_report,
@@ -115,6 +116,15 @@ class CustomSignalAgent:
Any non-registered report components (other than title and description)
will be auto-resolved by default resolvers.
+ Artefacts
+ ---------
+ :py:meth:`register_artefact` queues artefacts of any type for the report
+ being built. They are persisted in the same transaction as the report at
+ the next finalization point, attributed like every other component, and
+ cleared along with the report components by :py:meth:`report_and_continue`.
+ Status types (judgments, repo selection, suggested reviewers) are
+ latest-wins — the newest row of each type is the report's current status.
+
Return falsy from :py:meth:`run` after the last ``report_and_continue`` to
prevent a final report from being generated.
@@ -195,6 +205,7 @@ class CustomSignalAgent:
self._assignees: list[CustomAgentAssignee] | None = None
self._actionability: ActionabilityAssessment | None = None
self._priority: PriorityAssessment | None = None
+ self._registered_artefacts: list[ArtefactContent] = []
self._persisted_reports: list[PersistedCustomAgentReport] = []
# ------------------------------------------------------------------
@@ -284,6 +295,11 @@ class CustomSignalAgent:
def register_assignees(self, assignees: list[CustomAgentAssignee]) -> None:
self._assignees = list(assignees)
+ def register_artefact(self, content: ArtefactContent) -> None:
+ """Queue an artefact (typed from ``artefact_schemas``) to be written with the report."""
+ artefact_type_for(content) # fail at the call site for models that aren't artefact content
+ self._registered_artefacts.append(content)
+
# ------------------------------------------------------------------
# 4. Likely to be overridden (prompt customization)
# ------------------------------------------------------------------
@@ -463,45 +479,26 @@ Rules:
final_report=final,
repo_selection=self._resolved_repository,
task_id=task_id,
+ agent_identifier=type(self).identifier(),
+ registered_artefacts=list(self._registered_artefacts),
)
self._persisted_reports.append(persisted)
- await self._maybe_autostart(persisted, final)
+ await self._maybe_autostart(persisted)
return persisted
- async def _maybe_autostart(
- self,
- persisted: PersistedCustomAgentReport,
- final: CustomAgentFinalReport,
- ) -> None:
- """Best-effort autostart hand-off; swallows failures so they don't fail the report."""
- repository = self.repository
- if repository is None:
- return
- reviewers_content: list[ReviewerContent] = [
- ReviewerContent(
- github_login=a.github_login,
- github_name=a.github_name,
- relevant_commits=[c.model_dump(mode="json") for c in a.relevant_commits],
- )
- for a in final.assignees
- ]
+ async def _maybe_autostart(self, persisted: PersistedCustomAgentReport) -> None:
+ """Best-effort autostart hand-off; swallows failures so they don't fail the report.
+
+ The report and its artefacts are already persisted, so this reconstructs the auto-start
+ inputs from them — the same shared entry point the in-app reviewer edit uses.
+ """
try:
- await maybe_autostart_implementation_task(
- team_id=self.team_id,
- report_id=persisted.report_id,
- repository=repository,
- title=final.title,
- summary=final.description,
- actionability=final.actionability,
- reviewers_content=reviewers_content,
- priority=final.priority,
- )
+ await maybe_autostart_from_report_artefacts(team_id=self.team_id, report_id=persisted.report_id)
except Exception as error:
posthoganalytics.capture_exception(error)
logger.exception(
"custom signal agent auto-start task failed",
report_id=persisted.report_id,
- repository=repository,
error=str(error),
)
@@ -511,6 +508,7 @@ Rules:
self._assignees = None
self._actionability = None
self._priority = None
+ self._registered_artefacts = []
def _final_report(self) -> CustomAgentFinalReport:
missing = []
diff --git a/products/signals/backend/custom_agent/persistence.py b/products/signals/backend/custom_agent/persistence.py
index 4b836b12b547..1ccf8da9710f 100644
--- a/products/signals/backend/custom_agent/persistence.py
+++ b/products/signals/backend/custom_agent/persistence.py
@@ -1,13 +1,15 @@
from __future__ import annotations
-import json
+from collections.abc import Sequence
from dataclasses import dataclass
from django.db import transaction
+from products.signals.backend.artefact_schemas import ArtefactContent, SuggestedReviewers
from products.signals.backend.custom_agent.schemas import CustomAgentFinalReport
-from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportTask
+from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact
from products.signals.backend.report_generation.select_repo import RepoSelectionResult
+from products.signals.backend.task_run_artefacts import append_task_run_artefact
@dataclass(frozen=True)
@@ -22,8 +24,16 @@ def create_custom_agent_ready_report(
final_report: CustomAgentFinalReport,
repo_selection: RepoSelectionResult,
task_id: str | None = None,
+ agent_identifier: tuple[str, str],
+ registered_artefacts: Sequence[ArtefactContent] = (),
) -> PersistedCustomAgentReport:
- """Create a final READY report plus compatible artefacts in one transaction."""
+ """Create a final READY report plus compatible artefacts in one transaction.
+
+ `agent_identifier` is the agent's `(product, type)` pair; it labels the `task_run` artefact
+ when this run produced a task. `registered_artefacts` are typed content models of any
+ artefact type, queued during the run via the agent's `register_artefact`, written in queue
+ order (status types route through their latest-wins append semantics).
+ """
with transaction.atomic():
report = SignalReport.objects.create(
team_id=team_id,
@@ -34,46 +44,60 @@ def create_custom_agent_ready_report(
total_weight=0.0,
)
- artefacts: list[SignalReportArtefact] = [
- SignalReportArtefact(
- team_id=team_id,
- report=report,
- type=SignalReportArtefact.ArtefactType.REPO_SELECTION,
- content=repo_selection.model_dump_json(),
- ),
- SignalReportArtefact(
- team_id=team_id,
- report=report,
- type=SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT,
- content=final_report.actionability.model_dump_json(),
- ),
- ]
+ # Written through the model helpers (the single artefact write path). Auto-start is
+ # orchestrated explicitly by the caller after persistence, so the suggested_reviewers
+ # append opts out of the model's auto-start re-evaluation hook. Everything the agent
+ # produced is attributed to its sandbox task; runs that never spawned one (no `send()`
+ # call) fall back to system attribution.
+ report_id = str(report.id)
+ attribution = ArtefactAttribution.from_task(task_id) if task_id is not None else ArtefactAttribution.system()
+ SignalReportArtefact.append_status(
+ team_id=team_id,
+ report_id=report_id,
+ content=repo_selection,
+ attribution=attribution,
+ )
+ SignalReportArtefact.append_status(
+ team_id=team_id,
+ report_id=report_id,
+ content=final_report.actionability,
+ attribution=attribution,
+ )
if final_report.priority is not None:
- artefacts.append(
- SignalReportArtefact(
- team_id=team_id,
- report=report,
- type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,
- content=final_report.priority.model_dump_json(),
- )
+ SignalReportArtefact.append_status(
+ team_id=team_id,
+ report_id=report_id,
+ content=final_report.priority,
+ attribution=attribution,
)
if final_report.assignees:
- artefacts.append(
- SignalReportArtefact(
- team_id=team_id,
- report=report,
- type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
- content=json.dumps([assignee.model_dump(mode="json") for assignee in final_report.assignees]),
- )
+ SignalReportArtefact.append_status(
+ team_id=team_id,
+ report_id=report_id,
+ content=SuggestedReviewers.model_validate(
+ [assignee.model_dump(mode="json") for assignee in final_report.assignees]
+ ),
+ attribution=attribution,
+ reevaluate_autostart=False,
+ )
+
+ for artefact_content in registered_artefacts:
+ SignalReportArtefact.append(
+ team_id=team_id,
+ report_id=report_id,
+ content=artefact_content,
+ attribution=attribution,
+ reevaluate_autostart=False,
)
- SignalReportArtefact.objects.bulk_create(artefacts)
if task_id is not None:
- SignalReportTask.objects.create(
+ product, type = agent_identifier
+ append_task_run_artefact(
team_id=team_id,
- report=report,
+ report_id=str(report.id),
+ product=product,
+ type=type,
task_id=task_id,
- relationship=SignalReportTask.Relationship.RESEARCH,
)
return PersistedCustomAgentReport(report_id=str(report.id), task_id=task_id)
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index df14568267ef..a1b71e33e409 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -29,13 +29,15 @@ def _token_count(text: str) -> int:
return len(get_tiktoken_encoding_for_model(LLM_TOKEN_COUNT_PROXY_MODEL).encode(text))
-def dismiss_report_from_slack(team_id: int, report_id: str, *, slack_user_id: str | None = None) -> bool:
+def dismiss_report_from_slack(
+ team_id: int, report_id: str, *, slack_user_id: str | None = None, user_id: int | None = None
+) -> bool:
"""Facade entrypoint for the Slack 'Dismiss' button. See report_actions.suppress_report_from_slack."""
from products.signals.backend.report_actions import (
suppress_report_from_slack, # noqa: PLC0415 — avoids importing model layer at facade import time
)
- return suppress_report_from_slack(team_id, report_id, slack_user_id=slack_user_id)
+ return suppress_report_from_slack(team_id, report_id, slack_user_id=slack_user_id, user_id=user_id)
def _get_field_values(field: pydantic.fields.FieldInfo) -> tuple[str, ...]:
diff --git a/products/signals/backend/implementation_pr.py b/products/signals/backend/implementation_pr.py
index d58ed29658ab..fee15760568e 100644
--- a/products/signals/backend/implementation_pr.py
+++ b/products/signals/backend/implementation_pr.py
@@ -1,27 +1,28 @@
"""Resolve implementation PR URLs linked to signal reports."""
-from products.signals.backend.models import SignalReportTask
+from products.signals.backend.models import SignalReport
+from products.signals.backend.task_run_artefacts import SIGNALS_PRODUCT, TASK_RUN_TYPE_IMPLEMENTATION
from products.tasks.backend.facade import api as tasks_facade
def fetch_implementation_pr_urls_for_reports(report_ids: list[str]) -> dict[str, str]:
"""PR URL from the latest implementation task run for each report, when available.
- A report has a single implementation task in practice; the facade resolves the latest
- PR-bearing run for each task, so multiple runs of that task collapse to the newest PR.
+ The task↔report association comes from `SignalReport.associated_task_runs` (the unified view of
+ the `task_run` artefact log + legacy gate rows); the facade then resolves the latest PR-bearing
+ run for each task, so multiple runs of a task collapse to the newest PR.
"""
if not report_ids:
return {}
- # report_id -> task_id for the report's implementation task(s); signals owns this mapping.
- pairs = list(
- SignalReportTask.objects.filter(
- report_id__in=report_ids,
- relationship=SignalReportTask.Relationship.IMPLEMENTATION,
+ # (report_id, task_id) for each report's implementation task(s); signals owns this mapping.
+ pairs: list[tuple[str, str]] = [
+ (str(report_id), run.task_id)
+ for report_id in report_ids
+ for run in SignalReport.associated_task_runs(
+ report_id=str(report_id), product=SIGNALS_PRODUCT, type=TASK_RUN_TYPE_IMPLEMENTATION
)
- .order_by("report_id")
- .values_list("report_id", "task_id")
- )
+ ]
if not pairs:
return {}
@@ -29,7 +30,7 @@ def fetch_implementation_pr_urls_for_reports(report_ids: list[str]) -> dict[str,
result: dict[str, str] = {}
for report_id, task_id in pairs:
- pr_url = pr_url_by_task.get(str(task_id))
- if pr_url and str(report_id) not in result:
- result[str(report_id)] = pr_url
+ pr_url = pr_url_by_task.get(task_id)
+ if pr_url and report_id not in result:
+ result[report_id] = pr_url
return result
diff --git a/products/signals/backend/management/AGENTS.md b/products/signals/backend/management/AGENTS.md
index 5b738e5cedfb..841d4a150a46 100644
--- a/products/signals/backend/management/AGENTS.md
+++ b/products/signals/backend/management/AGENTS.md
@@ -154,6 +154,30 @@ left alone), `tombstoned` (rows the team already soft-deleted — left alone, ne
coordinator stops dispatching them). Same function the coordinator and runner call lazily —
this command is just the impatient path.
+## Backfilling task_run artefacts
+
+One-off data migration: turn legacy `SignalReportTask` rows (those carrying the old `relationship`
+label) into `task_run` log artefacts so the research / implementation / repo-selection runs tied to
+a report show up in its artefact timeline. `SignalReportTask` lives on as the unlabelled
+task↔report association; rows without a legacy label are skipped — their `task_run` artefact is
+written at creation time.
+
+```bash
+# Preview, scoped to one team
+python manage.py backfill_task_run_artefacts --team-id 1 --dry-run
+
+# Backfill for real (all teams, or add --team-id N)
+python manage.py backfill_task_run_artefacts
+```
+
+Idempotent — skips any report that already has a `task_run` artefact referencing the same task, so it
+is safe to re-run. Each artefact carries a `(product, type)` pair: these are signals-pipeline runs, so
+`product` is `signals` and `type` is the legacy relationship label (`research` / `implementation` /
+`repo_selection`). Backfilled artefacts are attributed to their task and backdated to their
+`SignalReportTask.created_at` so the log stays chronologically correct (the artefact row is created
+now, but the run happened earlier). Live creation paths append the same artefacts at run time going
+forward — custom agents instead use their own `identifier()` `(product, type)` pair.
+
## Tips
- Compare runs by saving output: `list_signal_reports --json > run_baseline.json`
diff --git a/products/signals/backend/management/commands/analyze_report.py b/products/signals/backend/management/commands/analyze_report.py
index 4efba015d580..c6c17a524761 100644
--- a/products/signals/backend/management/commands/analyze_report.py
+++ b/products/signals/backend/management/commands/analyze_report.py
@@ -234,16 +234,18 @@ class Command(BaseCommand):
self.stdout.write(self.style.SUCCESS("=== Research Result ==="))
self.stdout.write(f"Title: {result.title}")
self.stdout.write(f"Summary: {result.summary}")
- self.stdout.write(f"Actionability: {result.actionability.actionability}")
- self.stdout.write(f"Already addressed: {result.actionability.already_addressed}")
- self.stdout.write(f"Actionability explanation: {result.actionability.explanation}")
- if result.priority:
- self.stdout.write(f"Priority: {result.priority.priority}")
- self.stdout.write(f"Priority explanation: {result.priority.explanation}")
+ actionability = result.effective_actionability()
+ priority = result.effective_priority()
+ self.stdout.write(f"Actionability: {actionability.actionability}")
+ self.stdout.write(f"Already addressed: {actionability.already_addressed}")
+ self.stdout.write(f"Actionability explanation: {actionability.explanation}")
+ if priority:
+ self.stdout.write(f"Priority: {priority.priority}")
+ self.stdout.write(f"Priority explanation: {priority.explanation}")
else:
self.stdout.write("Priority: N/A (not actionable)")
self.stdout.write("")
- for finding in result.findings:
+ for finding in result.effective_findings():
self.stdout.write(self.style.WARNING(f"--- Signal: {finding.signal_id} ---"))
self.stdout.write(f" Verified: {finding.verified}")
self.stdout.write(f" Code paths: {finding.relevant_code_paths}")
diff --git a/products/signals/backend/management/commands/backfill_task_run_artefacts.py b/products/signals/backend/management/commands/backfill_task_run_artefacts.py
new file mode 100644
index 000000000000..8213b934f9d7
--- /dev/null
+++ b/products/signals/backend/management/commands/backfill_task_run_artefacts.py
@@ -0,0 +1,87 @@
+import json
+
+from django.core.management.base import BaseCommand
+
+from products.signals.backend.artefact_schemas import task_run_identifier_for_legacy_relationship
+from products.signals.backend.models import SignalReportArtefact, SignalReportTask
+from products.signals.backend.task_run_artefacts import append_task_run_artefact
+
+
+class Command(BaseCommand):
+ help = (
+ "Backfill `task_run` log artefacts from existing SignalReportTask rows, so the work tied to "
+ "a report (research / implementation / repo-selection runs) shows up in its artefact timeline. "
+ "Idempotent: skips any report that already has a task_run artefact referencing the same task."
+ )
+
+ def add_arguments(self, parser):
+ parser.add_argument("--team-id", type=int, default=None, help="Only backfill tasks for this team.")
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Report what would be created without writing anything.",
+ )
+
+ def _already_backfilled(self, report_id: str, task_id: str) -> bool:
+ # `content` is a TextField; the cheap __contains pre-filter narrows to rows that mention the
+ # task id, then we parse-confirm so a coincidental substring match can't cause a false skip.
+ candidates = SignalReportArtefact.objects.filter(
+ report_id=report_id,
+ type=SignalReportArtefact.ArtefactType.TASK_RUN,
+ content__contains=task_id,
+ )
+ for artefact in candidates:
+ try:
+ if json.loads(artefact.content).get("task_id") == task_id:
+ return True
+ except (json.JSONDecodeError, ValueError):
+ continue
+ return False
+
+ def handle(self, *args, **options):
+ team_id = options["team_id"]
+ dry_run = options["dry_run"]
+
+ report_tasks = SignalReportTask.objects.all().order_by("created_at")
+ if team_id is not None:
+ report_tasks = report_tasks.filter(team_id=team_id)
+
+ created = 0
+ skipped = 0
+ for report_task in report_tasks.iterator():
+ # Labelled legacy rows are signals-pipeline runs (`signals` / relationship label);
+ # unlabelled rows collapse to the generic `tasks` / `agent_run` identifiers — the same
+ # mapping `SignalReport.associated_task_runs` fakes for these rows at read time.
+ product, task_type = task_run_identifier_for_legacy_relationship(report_task.relationship)
+
+ task_id = str(report_task.task_id)
+ report_id = str(report_task.report_id)
+ if self._already_backfilled(report_id, task_id):
+ skipped += 1
+ continue
+
+ if dry_run:
+ self.stdout.write(
+ f"[dry-run] would create task_run artefact for report {report_id} "
+ f"(task {task_id}, {product}/{task_type})"
+ )
+ created += 1
+ continue
+
+ artefact = append_task_run_artefact(
+ team_id=report_task.team_id,
+ report_id=report_id,
+ product=product,
+ type=task_type,
+ task_id=task_id,
+ )
+ # Backdate to when the task actually ran (the artefact is created now, but the run
+ # happened when its SignalReportTask was recorded). `.update()` bypasses auto_now(_add)
+ # so the log stays chronologically correct.
+ SignalReportArtefact.objects.filter(pk=artefact.pk).update(created_at=report_task.created_at)
+ created += 1
+
+ verb = "would create" if dry_run else "created"
+ self.stdout.write(
+ self.style.SUCCESS(f"Done: {verb} {created} task_run artefact(s), skipped {skipped} (already present).")
+ )
diff --git a/products/signals/backend/management/commands/ingest_report_json.py b/products/signals/backend/management/commands/ingest_report_json.py
index 3c9db8b3cce1..93607dcd5f61 100644
--- a/products/signals/backend/management/commands/ingest_report_json.py
+++ b/products/signals/backend/management/commands/ingest_report_json.py
@@ -93,15 +93,16 @@ class Command(BaseCommand):
raise CommandError(f"Team {options['team_id']} not found")
signal_ids = payload.get("signal_ids") or []
- signal_count = max(len(signal_ids), len(result.findings))
+ signal_count = max(len(signal_ids), len(result.effective_findings()))
report = self._create_and_advance_report(team, signal_count)
self.stdout.write(f"Created SignalReport {report.id} for team {team.id} in state {report.status}")
self.stdout.write(f"Repository: {repository}")
- self.stdout.write(f"Actionability: {result.actionability.actionability.value}")
- if result.priority:
- self.stdout.write(f"Priority: {result.priority.priority.value}")
+ self.stdout.write(f"Actionability: {result.effective_actionability().actionability.value}")
+ priority = result.effective_priority()
+ if priority:
+ self.stdout.write(f"Priority: {priority.priority.value}")
else:
self.stdout.write("Priority: N/A (not actionable)")
diff --git a/products/signals/backend/migrations/0047_signalreportartefact_updated_at_and_more.py b/products/signals/backend/migrations/0047_signalreportartefact_updated_at_and_more.py
new file mode 100644
index 000000000000..a0eb0c7cb8aa
--- /dev/null
+++ b/products/signals/backend/migrations/0047_signalreportartefact_updated_at_and_more.py
@@ -0,0 +1,74 @@
+# Generated by Django 5.2.14 on 2026-06-09 13:38
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1218_team_ingested_production_event_last_checked_at"),
+ ("signals", "0046_signalteamconfig_backfill_default_autostart_p4"),
+ ("tasks", "0037_codeworkflowconfig_codeprsnapshot_codeworkstream"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalreportartefact",
+ name="updated_at",
+ field=models.DateTimeField(auto_now=True, null=True),
+ ),
+ migrations.AlterField(
+ model_name="signalreportartefact",
+ name="type",
+ field=models.CharField(
+ choices=[
+ ("video_segment", "Video Segment"),
+ ("safety_judgment", "Safety Judgment"),
+ ("actionability_judgment", "Actionability Judgment"),
+ ("priority_judgment", "Priority Judgment"),
+ ("signal_finding", "Signal Finding"),
+ ("repo_selection", "Repo Selection"),
+ ("suggested_reviewers", "Suggested Reviewers"),
+ ("dismissal", "Dismissal"),
+ ("code_reference", "Code Reference"),
+ ("commit", "Commit"),
+ ("task_run", "Task Run"),
+ ("note", "Note"),
+ ],
+ max_length=100,
+ ),
+ ),
+ migrations.AddField(
+ model_name="signalreportartefact",
+ name="created_by",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ migrations.AddField(
+ model_name="signalreportartefact",
+ name="task",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="tasks.task",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="signalreporttask",
+ name="relationship",
+ field=models.CharField(blank=True, max_length=200, null=True),
+ ),
+ migrations.AddConstraint(
+ model_name="signalreporttask",
+ constraint=models.UniqueConstraint(fields=("report", "task"), name="unique_signal_report_task"),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/0048_signalreportartefact_latest_index.py b/products/signals/backend/migrations/0048_signalreportartefact_latest_index.py
new file mode 100644
index 000000000000..1e2194bda2e0
--- /dev/null
+++ b/products/signals/backend/migrations/0048_signalreportartefact_latest_index.py
@@ -0,0 +1,34 @@
+# Latest-wins lookups: artefacts are append-only, so deriving a report's current status / log
+# tail is `WHERE report=? AND type=? ORDER BY created_at DESC` — this index makes it a seek.
+# Kept separate from 0047 (and atomic=False) because CONCURRENTLY cannot run in a transaction,
+# and bin/migrate re-runs a failed migration in full — non-idempotent ops must not share it.
+
+from django.db import migrations, models
+
+from posthog.migration_helpers import CreateIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False # Required for CONCURRENTLY
+
+ dependencies = [
+ ("signals", "0047_signalreportartefact_updated_at_and_more"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddIndex(
+ model_name="signalreportartefact",
+ index=models.Index(fields=["report", "type", "-created_at"], name="signals_sig_rpt_type_ct_idx"),
+ ),
+ ],
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="signals_sig_rpt_type_ct_idx",
+ table_name="signals_signalreportartefact",
+ columns="(report_id, type, created_at DESC)",
+ ),
+ ],
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 33653aebac2a..bba5624efd97 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0046_signalteamconfig_backfill_default_autostart_p4
+0048_signalreportartefact_latest_index
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 8e9c14d1de75..3d3a0e35b48c 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1,18 +1,35 @@
import logging
-from typing import Any
+from dataclasses import dataclass
+from datetime import datetime
+from typing import Any, Literal, cast
from django.contrib.postgres.fields import ArrayField
from django.core.validators import MaxValueValidator, MinValueValidator
-from django.db import models
+from django.db import models, transaction
from django.utils import timezone
+from asgiref.sync import async_to_sync
from django_deprecate_fields import deprecate_field
+from pydantic import ValidationError
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.team.extensions import register_team_extension_signal
from posthog.models.utils import UUIDModel
+from products.signals.backend.artefact_schemas import (
+ ArtefactContent,
+ ArtefactContentValidationError,
+ Dismissal,
+ LogArtefactContent,
+ SignalFinding,
+ StatusArtefactContent,
+ TaskRunArtefact,
+ artefact_type_for,
+ parse_artefact_content,
+ task_run_identifier_for_legacy_relationship,
+)
+
logger = logging.getLogger(__name__)
@@ -352,6 +369,135 @@ class SignalReport(UUIDModel):
return S(prior)
return S.POTENTIAL
+ @staticmethod
+ def _merge_task_runs(
+ artefact_rows: "list[tuple[datetime, str]]",
+ report_task_rows: "list[tuple[datetime, str | None, Any]]",
+ *,
+ product: str | None,
+ type: str | None,
+ ) -> list[TaskRunArtefact]:
+ """Merge `task_run` artefact contents with faked-from-`SignalReportTask` runs into one
+ de-duplicated, oldest-first list — the view that would exist once the backfill has run.
+
+ A `SignalReportTask` row is surfaced as the `task_run` artefact the backfill would create
+ for it (same `(product, type)` mapping). De-dup is by `task_id` (mirroring the backfill,
+ which skips a task that already has an artefact); when a task appears in both sources the
+ real artefact wins, since on equal timestamps it is ordered first.
+ """
+ # (created_at, source_rank, run); source_rank 0 = real artefact, so it wins ties.
+ candidates: list[tuple[datetime, int, TaskRunArtefact]] = []
+ for created_at, content in artefact_rows:
+ try:
+ run = TaskRunArtefact.model_validate_json(content)
+ except ValidationError:
+ continue # tolerate malformed legacy TextField content
+ candidates.append((created_at, 0, run))
+ for created_at, relationship, task_id in report_task_rows:
+ run_product, run_type = task_run_identifier_for_legacy_relationship(relationship)
+ candidates.append(
+ (created_at, 1, TaskRunArtefact(task_id=str(task_id), run_id=None, product=run_product, type=run_type))
+ )
+
+ candidates = [
+ c
+ for c in candidates
+ if (product is None or c[2].product == product) and (type is None or c[2].type == type)
+ ]
+ candidates.sort(key=lambda c: (c[0], c[1]))
+
+ seen: set[str] = set()
+ result: list[TaskRunArtefact] = []
+ for _created_at, _rank, run in candidates:
+ if run.task_id in seen:
+ continue
+ seen.add(run.task_id)
+ result.append(run)
+ return result
+
+ @classmethod
+ def associated_task_runs(
+ cls, *, report_id: str, team_id: int | None = None, product: str | None = None, type: str | None = None
+ ) -> list[TaskRunArtefact]:
+ """The task runs associated with a report, unified across the `task_run` artefact log and the
+ legacy `SignalReportTask` gate rows and de-duplicated by task — the view you would get once
+ `backfill_task_run_artefacts` has converted every gate row into a `task_run` artefact.
+
+ Gate rows are surfaced as if they were `task_run` artefacts, so "does this report have an
+ associated task (of a given product/type)?" is a single question against one artefact-shaped
+ list — callers should not query `SignalReportArtefact` / `SignalReportTask` directly. Pass
+ `product` / `type` to narrow (e.g. `product="signals", type="implementation"`).
+ """
+ artefacts = SignalReportArtefact.objects.filter(
+ report_id=report_id, type=SignalReportArtefact.ArtefactType.TASK_RUN
+ )
+ report_tasks = SignalReportTask.objects.filter(report_id=report_id)
+ if team_id is not None:
+ artefacts = artefacts.filter(team_id=team_id)
+ report_tasks = report_tasks.filter(team_id=team_id)
+ return cls._merge_task_runs(
+ list(artefacts.values_list("created_at", "content")),
+ list(report_tasks.values_list("created_at", "relationship", "task_id")),
+ product=product,
+ type=type,
+ )
+
+ @classmethod
+ async def aassociated_task_runs(
+ cls, *, report_id: str, team_id: int | None = None, product: str | None = None, type: str | None = None
+ ) -> list[TaskRunArtefact]:
+ """Async counterpart of `associated_task_runs`."""
+ artefacts = SignalReportArtefact.objects.filter(
+ report_id=report_id, type=SignalReportArtefact.ArtefactType.TASK_RUN
+ )
+ report_tasks = SignalReportTask.objects.filter(report_id=report_id)
+ if team_id is not None:
+ artefacts = artefacts.filter(team_id=team_id)
+ report_tasks = report_tasks.filter(team_id=team_id)
+ return cls._merge_task_runs(
+ [row async for row in artefacts.values_list("created_at", "content")],
+ [row async for row in report_tasks.values_list("created_at", "relationship", "task_id")],
+ product=product,
+ type=type,
+ )
+
+ @staticmethod
+ def associated_task_runs_filter(report_ref: Any) -> "models.Q":
+ """A `Q` matching `tasks.TaskRun`s whose task is associated with the correlated report,
+ unified across the `task_run` artefact log and the legacy `SignalReportTask` gate rows —
+ the SQL-level counterpart of `associated_task_runs`, for embedding in a queryset
+ annotation/filter (e.g. via `tasks` facade subquery helpers) so report→task correlation
+ stays in one query instead of N per-report calls.
+
+ `report_ref` is the report-id expression at the nesting depth where the `Q` is embedded —
+ inside the facade's `TaskRun` subquery that is one level below the report queryset, so
+ `OuterRef(OuterRef("id"))`. Unfiltered by `(product, type)`: those discriminators live in
+ the artefact's JSON content, which we deliberately don't cast in SQL — the caller's own run
+ filter (e.g. a non-empty `output.pr_url`, which only implementation runs produce) supplies
+ the specificity.
+ """
+ artefact_task_ids = SignalReportArtefact.objects.filter(
+ 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)
+
+ @staticmethod
+ def reports_for_task_filter(task_id: Any) -> "models.Q":
+ """A `Q` on `SignalReport.id` matching the reports `task_id` is associated with, unified
+ across the `task_run` artefact log and the legacy `SignalReportTask` gate rows — the
+ reverse-direction (task → reports) counterpart of `associated_task_runs_filter`, for
+ embedding in a `SignalReport` queryset filter.
+
+ Both subqueries seek the indexed `task_id` FK column (artefact + gate row), so this stays a
+ couple of index lookups regardless of how many artefacts a report accumulates.
+ """
+ artefact_report_ids = SignalReportArtefact.objects.filter(
+ 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)
+
class SignalEmissionRecord(UUIDModel):
"""Tracks which source records have been emitted as signals.
@@ -381,6 +527,44 @@ class SignalEmissionRecord(UUIDModel):
]
+@dataclass(frozen=True)
+class ArtefactAttribution:
+ """Who (or what) produced an artefact — exactly one of a user, a task, or the system.
+
+ 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.
+ """
+
+ kind: Literal["user", "task", "system"]
+ user_id: int | None = None
+ task_id: 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
+ case "task":
+ valid = self.task_id is not None and self.user_id is None
+ case _:
+ valid = self.user_id is None and self.task_id is None
+ if not valid:
+ raise ValueError(f"ArtefactAttribution kind {self.kind!r} does not match its id fields")
+
+ @classmethod
+ def from_user(cls, user_id: int) -> "ArtefactAttribution":
+ return cls(kind="user", user_id=user_id)
+
+ @classmethod
+ def from_task(cls, task_id: str) -> "ArtefactAttribution":
+ return cls(kind="task", task_id=str(task_id))
+
+ @classmethod
+ def system(cls) -> "ArtefactAttribution":
+ return cls(kind="system")
+
+
class SignalReportArtefact(UUIDModel):
class ArtefactType(models.TextChoices):
VIDEO_SEGMENT = "video_segment"
@@ -391,36 +575,255 @@ class SignalReportArtefact(UUIDModel):
REPO_SELECTION = "repo_selection"
SUGGESTED_REVIEWERS = "suggested_reviewers"
DISMISSAL = "dismissal"
+ CODE_REFERENCE = "code_reference"
+ COMMIT = "commit"
+ TASK_RUN = "task_run"
+ NOTE = "note"
+
+ # Every artefact is an append-only, point-in-time log entry — nothing is mutated in place by
+ # the producers. The two sets below classify *what an entry means*, not how it is written:
+ # - status artefacts describe the report's current state (judgments, repo selection,
+ # suggested reviewers). They are appended on each (re)assessment via `append_status`; the
+ # report's *current* status is the latest row of that type by `created_at` (the serializer
+ # derives priority/actionability/reviewers with `order_by("-created_at")[:1]` subqueries).
+ # - log artefacts record discrete work done on a report (code references, commits,
+ # task runs, notes). Appended via `add_log`.
+ # `signal_finding` is appended too, but its logical identity is `(report, content.signal_id)`:
+ # a new signal yields a new entry, re-researching an existing signal appends a new version
+ # (latest per signal_id wins). It is intentionally in neither set.
+ STATUS_ARTEFACT_TYPES: frozenset[str] = frozenset(
+ {
+ ArtefactType.SAFETY_JUDGMENT,
+ ArtefactType.ACTIONABILITY_JUDGMENT,
+ ArtefactType.PRIORITY_JUDGMENT,
+ ArtefactType.REPO_SELECTION,
+ ArtefactType.SUGGESTED_REVIEWERS,
+ }
+ )
+ LOG_ARTEFACT_TYPES: frozenset[str] = frozenset(
+ {
+ ArtefactType.CODE_REFERENCE,
+ ArtefactType.COMMIT,
+ ArtefactType.TASK_RUN,
+ ArtefactType.NOTE,
+ }
+ )
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
report = models.ForeignKey(SignalReport, on_delete=models.CASCADE, related_name="artefacts")
type = models.CharField(max_length=100, choices=ArtefactType)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
+ # Nullable so the migration is a fast, rolling-deploy-safe `ADD COLUMN ... NULL`; `auto_now`
+ # populates it on every subsequent save, so existing rows fill in the next time they change.
+ updated_at = models.DateTimeField(auto_now=True, null=True)
+ # Attribution: who produced this artefact. Exactly one of (created_by, task) is set on new
+ # rows — enforced at the write helpers via `ArtefactAttribution`, not as a DB constraint,
+ # 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.
+ 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="+")
class Meta:
indexes = [
models.Index(fields=["report"], name="signals_sig_report__idx"),
# For JOINs involving matching a report to artifact of a certain type
models.Index(fields=["report", "type"], name="signals_sig_report_type_idx"),
+ # Latest-wins lookups: artefacts are append-only, so deriving the current status / log
+ # tail is `WHERE report=? AND type=? ORDER BY created_at DESC` — this makes it a seek.
+ models.Index(fields=["report", "type", "-created_at"], name="signals_sig_rpt_type_ct_idx"),
]
+ @classmethod
+ def _create(
+ cls,
+ *,
+ team_id: int,
+ report_id: str,
+ content: ArtefactContent,
+ attribution: ArtefactAttribution,
+ ) -> "SignalReportArtefact":
+ """Single write funnel: derive the row's type from the content model's class, map
+ attribution to columns, and insert. Content is a typed model (parsed at the API boundary
+ or constructed directly), so a row's type can never mismatch its content shape and no row
+ can be written unattributed.
+ """
+ # A task_run's content.task_id is the same association as the row's `task` FK — they must
+ # not diverge. The FK comes from attribution, so require task attribution that matches.
+ if isinstance(content, TaskRunArtefact) and content.task_id != attribution.task_id:
+ raise ArtefactContentValidationError("task_run content.task_id must match the artefact's attributed task")
+ return cls.objects.create(
+ team_id=team_id,
+ report_id=report_id,
+ type=artefact_type_for(content),
+ content=content.model_dump_json(),
+ created_by_id=attribution.user_id,
+ task_id=attribution.task_id,
+ )
+
+ @classmethod
+ def append_status(
+ cls,
+ *,
+ team_id: int,
+ report_id: str,
+ content: StatusArtefactContent,
+ attribution: ArtefactAttribution,
+ reevaluate_autostart: bool = True,
+ ) -> "SignalReportArtefact":
+ """Append a new version of a status artefact (see `STATUS_ARTEFACT_TYPES`) and return it.
+
+ Status artefacts are append-only: each (re)assessment creates a new row, and the report's
+ current status is the latest row of that type (by `created_at`).
+
+ Appending a `suggested_reviewers` status re-evaluates auto-start on commit (idempotent),
+ since changing reviewers can newly satisfy it. Callers that orchestrate auto-start
+ themselves with full in-hand context — the agentic pipeline / custom agents, which run on
+ the async worker and call it directly — pass ``reevaluate_autostart=False``.
+ """
+ if artefact_type_for(content) not in cls.STATUS_ARTEFACT_TYPES:
+ raise ValueError(f"{type(content).__name__} is not a status artefact content model")
+ artefact = cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)
+ if reevaluate_autostart and artefact.type == cls.ArtefactType.SUGGESTED_REVIEWERS:
+ cls._schedule_autostart_reevaluation(team_id=team_id, report_id=str(report_id))
+ return artefact
+
+ @classmethod
+ def append_finding(
+ cls, *, team_id: int, report_id: str, content: SignalFinding, attribution: ArtefactAttribution
+ ) -> "SignalReportArtefact":
+ """Append a `signal_finding` artefact (one investigation result; latest per `signal_id` wins).
+
+ `signal_finding` is neither a status nor a log type — it has its own identity keyed by the
+ finding's `signal_id` — so it gets a dedicated appender rather than going through
+ `append_status` / `add_log`.
+ """
+ return cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)
+
+ @classmethod
+ def append_dismissal(
+ cls, *, team_id: int, report_id: str, content: Dismissal, attribution: ArtefactAttribution
+ ) -> "SignalReportArtefact":
+ """Append a `dismissal` artefact (dismissal/snooze feedback; entries stack over time).
+
+ `dismissal` is neither a status nor a log type — each dismissal is its own point-in-time
+ record — so it gets a dedicated appender.
+ """
+ return cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)
+
+ @staticmethod
+ def _schedule_autostart_reevaluation(*, team_id: int, report_id: str) -> None:
+ """After the current transaction commits, re-evaluate auto-start for the report.
+
+ Changing a report's suggested reviewers can newly satisfy auto-start (e.g. adding a
+ reviewer whose autonomy threshold qualifies), so any path that appends a reviewers status
+ re-runs the idempotent auto-start check. Scheduled on commit so the new reviewers are
+ visible and the task-start side effect isn't rolled back; best-effort so it never breaks
+ the write. Imported lazily to avoid a models <-> auto_start import cycle.
+ """
+
+ def _run() -> None:
+ from products.signals.backend import auto_start
+
+ try:
+ async_to_sync(auto_start.maybe_autostart_from_report_artefacts)(team_id=team_id, report_id=report_id)
+ except Exception:
+ logger.exception(
+ "signals reviewer-change auto-start re-evaluation failed", extra={"report_id": report_id}
+ )
+
+ transaction.on_commit(_run)
+
+ @classmethod
+ def add_log(
+ cls, *, team_id: int, report_id: str, content: LogArtefactContent, attribution: ArtefactAttribution
+ ) -> "SignalReportArtefact":
+ """Append a log artefact (see `LOG_ARTEFACT_TYPES`) to a report and return it.
+
+ Log artefacts accumulate — each call creates a new row.
+ """
+ if artefact_type_for(content) not in cls.LOG_ARTEFACT_TYPES:
+ raise ValueError(f"{type(content).__name__} is not a log artefact content model")
+ return cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)
+
+ @classmethod
+ def append(
+ cls,
+ *,
+ team_id: int,
+ report_id: str,
+ content: ArtefactContent,
+ attribution: ArtefactAttribution,
+ reevaluate_autostart: bool = True,
+ ) -> "SignalReportArtefact":
+ """Append an artefact of any content model, routing to its type's append semantics.
+
+ Status types are latest-wins (`append_status`), `signal_finding` is keyed by signal_id,
+ `dismissal` entries stack, log types accumulate (`add_log`), and anything else
+ (`video_segment`) is a plain append. This model-level helper accepts every content model —
+ an agent can append a new status version just like the pipeline, and the newest row of a
+ status type is the report's canonical status. (The HTTP write API additionally refuses
+ legacy read-only types such as `video_segment` — see `NON_WRITABLE_ARTEFACT_TYPES`.)
+ """
+ artefact_type = artefact_type_for(content)
+ if artefact_type in cls.STATUS_ARTEFACT_TYPES:
+ return cls.append_status(
+ team_id=team_id,
+ report_id=report_id,
+ content=cast(StatusArtefactContent, content),
+ attribution=attribution,
+ reevaluate_autostart=reevaluate_autostart,
+ )
+ return cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)
+
+ def update_content(self, content: str | dict | list) -> None:
+ """Replace this artefact's content in place (bumps `updated_at`), parsed and validated
+ against the row's type. Attribution is creation-time only — edits don't reassign it.
+
+ Editing the latest `suggested_reviewers` row changes the report's canonical reviewers,
+ so it re-evaluates auto-start the same way appending a new reviewers row does."""
+ parsed = parse_artefact_content(self.type, content)
+ # The `task` FK is the association and is creation-time only; an edit must not let
+ # content.task_id drift away from it.
+ if isinstance(parsed, TaskRunArtefact) and str(parsed.task_id) != str(self.task_id):
+ raise ArtefactContentValidationError(
+ "task_run content.task_id must match the artefact's task and cannot be reassigned by editing"
+ )
+ self.content = parsed.model_dump_json()
+ self.save(update_fields=["content", "updated_at"])
+ if self.type == SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS:
+ self._schedule_autostart_reevaluation(team_id=self.team_id, report_id=str(self.report_id))
+
class SignalReportTask(UUIDModel):
- class Relationship(models.TextChoices):
- REPO_SELECTION = "repo_selection"
- RESEARCH = "research"
- IMPLEMENTATION = "implementation"
+ """Legacy task↔report link. Still the auto-start idempotency gate (an `implementation` row),
+ but being migrated out in favour of `task_run` artefacts.
+
+ Auto-start and the manual start-task API write *both* a `relationship="implementation"` row
+ here and a `task_run` artefact (`record_implementation_task`). The gate reads this table — see
+ `auto_start.py` — because the artefact log is freeform and API-mutable and so can't be trusted
+ for a spend-controlling decision. Once `backfill_task_run_artefacts` has converted every legacy
+ row to a `task_run` artefact, the gate can switch to the artefact log and this table can be
+ dropped. General task↔report association already lives only in artefacts; this table is kept
+ solely for the implementation gate during that transition.
+ """
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
report = models.ForeignKey(SignalReport, on_delete=models.CASCADE, related_name="report_tasks")
task = models.ForeignKey("tasks.Task", on_delete=models.CASCADE, related_name="signal_report_tasks")
- relationship = models.CharField(max_length=200, choices=Relationship)
+ # "implementation" for the rows the gate reads; legacy rows also carry "research" /
+ # "repo_selection". Nullable because the brief link-only window allowed unlabelled rows; the
+ # backfill maps those to default artefacts.
+ relationship = models.CharField(max_length=200, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = "Signal report task"
verbose_name_plural = "Signal report tasks"
+ constraints = [
+ models.UniqueConstraint(fields=["report", "task"], name="unique_signal_report_task"),
+ ]
indexes = [
# Billing and PR-URL lookups traverse this bridge by report filtered on relationship.
models.Index(fields=["report", "relationship"], name="signals_report_task_rel_idx"),
diff --git a/products/signals/backend/report_actions.py b/products/signals/backend/report_actions.py
index 8797590a7244..79a1610030ba 100644
--- a/products/signals/backend/report_actions.py
+++ b/products/signals/backend/report_actions.py
@@ -2,20 +2,31 @@
from __future__ import annotations
-import json
import logging
from django.db import transaction
-from products.signals.backend.models import InvalidStatusTransition, SignalReport, SignalReportArtefact
+from products.signals.backend.artefact_schemas import Dismissal
+from products.signals.backend.models import (
+ ArtefactAttribution,
+ InvalidStatusTransition,
+ SignalReport,
+ SignalReportArtefact,
+)
logger = logging.getLogger(__name__)
-def suppress_report_from_slack(team_id: int, report_id: str, *, slack_user_id: str | None = None) -> bool:
+def suppress_report_from_slack(
+ team_id: int, report_id: str, *, slack_user_id: str | None = None, user_id: int | None = None
+) -> bool:
"""Suppress (dismiss) a report from a Slack 'Dismiss' click. Idempotent — an
already-suppressed report is treated as success; returns False if the report
doesn't exist or the transition isn't allowed.
+
+ `user_id` is the PostHog user the clicking Slack identity resolved to — the caller already
+ resolves it to gate the dismiss to org members. When present the dismissal is attributed to
+ them; the `slack_user_id` is kept in the content either way as the Slack-side trace.
"""
# Row-lock the report so concurrent Dismiss clicks can't both transition + write artefacts.
with transaction.atomic():
@@ -39,10 +50,14 @@ def suppress_report_from_slack(team_id: int, report_id: str, *, slack_user_id: s
return False
report.save(update_fields=updated_fields)
- SignalReportArtefact.objects.create(
+ # Attribute to the resolved PostHog user when the caller mapped the Slack click to one;
+ # fall back to system if not. Either way the slack_user_id stays in the content as the
+ # Slack-side trace.
+ attribution = ArtefactAttribution.from_user(user_id) if user_id is not None else ArtefactAttribution.system()
+ SignalReportArtefact.append_dismissal(
team_id=team_id,
- report=report,
- type=SignalReportArtefact.ArtefactType.DISMISSAL,
- content=json.dumps({"reason": "slack_dismiss", "note": None, "slack_user_id": slack_user_id}),
+ report_id=str(report.id),
+ content=Dismissal(reason="slack_dismiss", slack_user_id=slack_user_id),
+ attribution=attribution,
)
return True
diff --git a/products/signals/backend/report_generation/AGENTS.md b/products/signals/backend/report_generation/AGENTS.md
index d1ac11030196..f55a32d28536 100644
--- a/products/signals/backend/report_generation/AGENTS.md
+++ b/products/signals/backend/report_generation/AGENTS.md
@@ -47,7 +47,11 @@ the safety judge first, then calls into this flow via a Temporal activity if the
lightly validate old findings before reusing them
fully research only new or stale signals
show previous actionability, priority, title, and summary as context
- regenerate those outputs only as much as needed
+ the agent confirms still-correct findings/assessments (via the `*Update` wrapper schemas)
+ instead of regenerating them — `ReportResearchOutput` splits its findings/assessments into
+ `old_artefacts` (confirmed unchanged, already persisted) and `new_artefacts` (produced this run),
+ and the caller activity persists the new ones unconditionally; read the report's effective state
+ via the `effective_*` accessors
In production, the `update` path is triggered automatically when a `ready` report is
re-promoted after accumulating enough new signals. The caller activity (`temporal/agentic/report.py`)
diff --git a/products/signals/backend/report_generation/fixtures/analyze_report_funnel_research_output.json b/products/signals/backend/report_generation/fixtures/analyze_report_funnel_research_output.json
index 9799416f4e43..e8fb7187b5dc 100644
--- a/products/signals/backend/report_generation/fixtures/analyze_report_funnel_research_output.json
+++ b/products/signals/backend/report_generation/fixtures/analyze_report_funnel_research_output.json
@@ -12,7 +12,8 @@
"result": {
"title": "Funnel insights lack time-based comparison and statistical options",
"summary": "The signals point to missing funnel analysis capabilities rather than a broken funnel engine. The consistent gaps are native time-period comparison, fixed Time to Convert histogram buckets, and percentile-based conversion-time summaries, while the onboarding drop-off report could not be verified without customer data.",
- "findings": [
+ "new_artefacts": [],
+ "old_artefacts": [
{
"signal_id": "test-funnel-compare-42606",
"relevant_code_paths": [
@@ -56,17 +57,17 @@
],
"data_queried": "1. Ran execute-sql to check for user_signed_up and onboarding_completed events in PostHog's own project data over the last 4 weeks. Neither event exists - only $pageview was returned. This is expected: these are the customer's custom events in their own PostHog project, not in PostHog's internal instance. The MCP tools only query the active PostHog project (PostHog's own), so we cannot verify the customer's claim about event volume drops. 2. Checked git history for recent changes to funnel query code (posthog/hogql_queries/insights/funnels/) - found no funnel logic changes in the relevant timeframe. The only recent commit touching this directory is error-tracking related (4412bf7e), not funnel calculation logic. 3. Searched for onboarding_completed and user_signed_up in the codebase - found only test fixtures and documentation examples, not production code. There is no evidence of a codebase-level regression that would cause funnel conversion drops. The issue is customer-specific and would require access to their project data to investigate (checking event volumes, SDK configuration, ingestion warnings in their project).",
"verified": false
+ },
+ {
+ "explanation": "All three feature requests (signals 1-3) are verified as genuine gaps in the codebase, but each involves significant architectural decisions that require human input. Signal 1 (compare filter) needs a new compareFilter field added to FunnelsQuery in the schema plus implementation mirroring trends_query_runner.py - but the design of how comparison results are returned and displayed needs product input. Signal 2 (fixed bin width) requires adding a binWidth option to FunnelsFilter and reworking the histogram calculation in funnel_time_to_convert.py - but the UX for how users specify fixed widths vs auto-binning needs design decisions. Signal 3 (percentiles) is the most straightforward - the regular funnel view already computes median, but the Time to Convert histogram only uses arrayAvg; adding percentile aggregation options requires schema and UI choices. Signal 4 (customer conversion drop) is unverifiable without access to the customer's project data and showed no code-level regression.",
+ "actionability": "requires_human_input",
+ "already_addressed": false
+ },
+ {
+ "explanation": "All three verified signals (1-3) are feature enhancement requests with workarounds available (HogQL breakdown for comparison, adjusting bin count manually, using the existing median_conversion_time from the regular funnel steps view). None represent broken functionality - funnels work correctly, they just lack advanced statistical options. The unverified bug report (signal 4) could not be corroborated by any code regression in git history, and no funnel logic changes were found in the relevant timeframe. The signals carry 0.5 weight each (low confidence) except signal 4 at 0.8 which could not be verified. These are clear improvement opportunities with existing workarounds, fitting P2.",
+ "priority": "P2",
+ "dollar_value": 15000.0
}
- ],
- "actionability": {
- "explanation": "All three feature requests (signals 1-3) are verified as genuine gaps in the codebase, but each involves significant architectural decisions that require human input. Signal 1 (compare filter) needs a new compareFilter field added to FunnelsQuery in the schema plus implementation mirroring trends_query_runner.py - but the design of how comparison results are returned and displayed needs product input. Signal 2 (fixed bin width) requires adding a binWidth option to FunnelsFilter and reworking the histogram calculation in funnel_time_to_convert.py - but the UX for how users specify fixed widths vs auto-binning needs design decisions. Signal 3 (percentiles) is the most straightforward - the regular funnel view already computes median, but the Time to Convert histogram only uses arrayAvg; adding percentile aggregation options requires schema and UI choices. Signal 4 (customer conversion drop) is unverifiable without access to the customer's project data and showed no code-level regression.",
- "actionability": "requires_human_input",
- "already_addressed": false
- },
- "priority": {
- "explanation": "All three verified signals (1-3) are feature enhancement requests with workarounds available (HogQL breakdown for comparison, adjusting bin count manually, using the existing median_conversion_time from the regular funnel steps view). None represent broken functionality - funnels work correctly, they just lack advanced statistical options. The unverified bug report (signal 4) could not be corroborated by any code regression in git history, and no funnel logic changes were found in the relevant timeframe. The signals carry 0.5 weight each (low confidence) except signal 4 at 0.8 which could not be verified. These are clear improvement opportunities with existing workarounds, fitting P2.",
- "priority": "P2",
- "dollar_value": 15000.0
- }
+ ]
}
}
diff --git a/products/signals/backend/report_generation/fixtures/insight_scene_logic_mode_property_bug.json b/products/signals/backend/report_generation/fixtures/insight_scene_logic_mode_property_bug.json
index 64e7f2ae177f..95980bf7a20c 100644
--- a/products/signals/backend/report_generation/fixtures/insight_scene_logic_mode_property_bug.json
+++ b/products/signals/backend/report_generation/fixtures/insight_scene_logic_mode_property_bug.json
@@ -7,7 +7,8 @@
"result": {
"title": "fix(backups): correct 'succesful' typo in docstring",
"summary": "The docstring of the `_get_base_backup` function in `posthog/dags/backups.py` (line 346) misspells 'successful' as 'succesful'. This is a single-word typo in a docstring — no code behavior is affected.",
- "findings": [
+ "old_artefacts": [],
+ "new_artefacts": [
{
"signal_id": "7e000000-0000-0000-0000-000000000001",
"relevant_code_paths": [
@@ -16,17 +17,17 @@
"relevant_commit_hashes": {},
"data_queried": "Verified via source that posthog/dags/backups.py line 346 reads 'Checks the latest succesful backup to use it as a base backup.' — the correct spelling is 'successful'.",
"verified": true
+ },
+ {
+ "explanation": "Single docstring typo fix in a single file. One word to change. Pure docstring, so zero test/behavior impact. An agent can perform this end to end without any human input.",
+ "actionability": "immediately_actionable",
+ "already_addressed": false
+ },
+ {
+ "explanation": "Low-risk, low-impact, but immediately actionable and suitable for agent autonomy testing.",
+ "priority": "P1",
+ "dollar_value": 0.0
}
- ],
- "actionability": {
- "explanation": "Single docstring typo fix in a single file. One word to change. Pure docstring, so zero test/behavior impact. An agent can perform this end to end without any human input.",
- "actionability": "immediately_actionable",
- "already_addressed": false
- },
- "priority": {
- "explanation": "Low-risk, low-impact, but immediately actionable and suitable for agent autonomy testing.",
- "priority": "P1",
- "dollar_value": 0.0
- }
+ ]
}
}
diff --git a/products/signals/backend/report_generation/research.py b/products/signals/backend/report_generation/research.py
index 3a7540b3e812..e6fe06948095 100644
--- a/products/signals/backend/report_generation/research.py
+++ b/products/signals/backend/report_generation/research.py
@@ -3,10 +3,20 @@ from __future__ import annotations
import json
import asyncio
import logging
-from enum import Enum
from typing import TYPE_CHECKING
-from pydantic import BaseModel, Field, field_validator
+from pydantic import BaseModel, Field, field_validator, model_validator
+
+# Canonical homes of the judgment/finding shapes are the artefact content schemas (they are
+# persisted as artefacts); re-exported here because this module is where research callers and
+# prompts historically import them from.
+from products.signals.backend.artefact_schemas import (
+ ActionabilityAssessment,
+ ActionabilityChoice,
+ Priority,
+ PriorityAssessment,
+ SignalFinding,
+)
# Deferred: importing temporal.types here runs the signals temporal package __init__, which
# eager-imports agentic -> report -> back into this module, forming a circular import.
@@ -15,114 +25,24 @@ from pydantic import BaseModel, Field, field_validator
if TYPE_CHECKING:
from products.signals.backend.temporal.types import SignalData
-
-class ActionabilityChoice(str, Enum):
- IMMEDIATELY_ACTIONABLE = "immediately_actionable"
- REQUIRES_HUMAN_INPUT = "requires_human_input"
- NOT_ACTIONABLE = "not_actionable"
-
-
-class Priority(str, Enum):
- P0 = "P0"
- P1 = "P1"
- P2 = "P2"
- P3 = "P3"
- P4 = "P4"
-
-
if TYPE_CHECKING:
from products.tasks.backend.facade.agents import CustomPromptSandboxContext, OutputFn
logger = logging.getLogger(__name__)
-# TODO: Signals deduplication step before the research
-
-
-class SignalFinding(BaseModel):
- signal_id: str = Field(description="The signal_id from the input signal list")
- relevant_code_paths: list[str] = Field(
- description=(
- "File paths in the codebase relevant to this signal, ordered from most critical first. "
- "The first path should be the highest-impact file (e.g. the buggy module or core feature file). "
- "Then include supporting paths."
- ),
- )
- relevant_commit_hashes: dict[str, str] = Field(
- default_factory=dict,
- json_schema_extra={"minProperties": 1},
- description=(
- "A mapping of 'git commit short SHA (7 characters)' -> 'reason'. "
- "Values are short explanations of WHY each commit is relevant. "
- "Use `git blame` on the most critical code paths to identify commits that caused, or are most closely related to, "
- "the issue described by this report. Prioritize causative commits "
- "(e.g. the commit that introduced a bug) over general authorship commits. Include 1-5 commits."
- ),
- )
- data_queried: str = Field(
- description=(
- "What PostHog MCP queries you ran (e.g. execute-sql, query-run, insight-query) "
- "and what the results showed. If no relevant queries could be run, explain why."
- ),
- )
- verified: bool = Field(
- description=(
- "Whether you could confirm the signal's claim by finding supporting evidence "
- "in code or data. False if the claim couldn't be verified either way."
- ),
- )
-
-
-class ActionabilityAssessment(BaseModel):
- explanation: str = Field(
- description=(
- "2-3 sentence evidence-grounded explanation of your actionability assessment. "
- "Reference specific code paths and data points from your research."
- ),
- )
- actionability: ActionabilityChoice = Field(
- description="Overall actionability assessment. Must be one of the allowed enum values — do not invent new ones.",
- )
- already_addressed: bool = Field(
- description=(
- "Whether the core issue described by this report appears to have been "
- "already fixed or addressed in recent code changes. Tracked separately from `actionability`."
- ),
- )
-
- @field_validator("explanation")
- @classmethod
- def explanation_must_not_be_empty(cls, v: str) -> str:
- if not v.strip():
- raise ValueError("Explanation must not be empty")
- return v
-
-
-class PriorityAssessment(BaseModel):
- explanation: str = Field(
- description=(
- "2-3 sentence justification for the priority level. "
- "Cite a quantified figure from your research — error frequency, affected user/session count, "
- "or scope of affected code paths. If impact could not be measured, say so explicitly and explain "
- "why the priority is not lowered further."
- ),
- )
- priority: Priority = Field(description="Priority (P0-P4)")
- dollar_value: float | None = Field(
- default=None,
- description=(
- "Peak estimate (USD) of the real dollar value of merging the fix/change this report leads to. "
- "Reason internally about a plausible value range first; set this to the most likely point "
- "within that range (the peak of your belief distribution). Should align with the assigned "
- "priority. Nullable for backward compatibility only — prefer a best-effort peak over null."
- ),
- )
+__all__ = [
+ "ActionabilityAssessment",
+ "ActionabilityChoice",
+ "Priority",
+ "PriorityAssessment",
+ "ReportPresentationOutput",
+ "ReportResearchOutput",
+ "ResearchArtefactContent",
+ "SignalFinding",
+ "run_multi_turn_research",
+]
- @field_validator("explanation")
- @classmethod
- def explanation_must_not_be_empty(cls, v: str) -> str:
- if not v.strip():
- raise ValueError("Explanation must not be empty")
- return v
+# TODO: Signals deduplication step before the research
class ReportPresentationOutput(BaseModel):
@@ -162,17 +82,119 @@ Principles:
return v
+# The report artefacts a research run produces: one finding per signal plus the two assessments.
+ResearchArtefactContent = SignalFinding | ActionabilityAssessment | PriorityAssessment
+
+
class ReportResearchOutput(BaseModel):
title: str = Field(description="Generated report title.")
summary: str = Field(description="Generated factual report summary.")
- findings: list[SignalFinding] = Field(
- description="One finding per signal in the report, in the same order as the input signals.",
+ research_task_id: str | None = Field(
+ default=None,
+ description="UUID of the sandbox task that performed the research; artefacts persisted from "
+ "this output are attributed to it. None for saved fixtures / pre-existing outputs.",
+ )
+ # The run's findings and assessments split by whether they changed: `old_artefacts` were
+ # confirmed unchanged (already persisted — a re-research reusing them writes nothing) and
+ # `new_artefacts` were produced or changed this run (persisted unconditionally). The report's
+ # effective state is the union of the two — read it via the `effective_*` accessors rather than
+ # picking a list, since a given assessment lives in whichever list this run put it in.
+ old_artefacts: list[ResearchArtefactContent] = Field(
+ default_factory=list,
+ description="Findings/assessments confirmed unchanged this run; already persisted, not re-written.",
+ )
+ new_artefacts: list[ResearchArtefactContent] = Field(
+ default_factory=list,
+ description="Findings/assessments produced or changed this run; persisted unconditionally.",
+ )
+
+ def _artefacts(self) -> tuple[ResearchArtefactContent, ...]:
+ # new wins over old — a changed value supersedes the confirmed-unchanged one.
+ return (*self.new_artefacts, *self.old_artefacts)
+
+ def effective_findings(self) -> list[SignalFinding]:
+ by_signal: dict[str, SignalFinding] = {}
+ for artefact in self._artefacts():
+ if isinstance(artefact, SignalFinding) and artefact.signal_id not in by_signal:
+ by_signal[artefact.signal_id] = artefact
+ return list(by_signal.values())
+
+ def effective_actionability(self) -> ActionabilityAssessment:
+ for artefact in self._artefacts():
+ if isinstance(artefact, ActionabilityAssessment):
+ return artefact
+ raise ValueError("ReportResearchOutput has no actionability assessment")
+
+ def effective_priority(self) -> PriorityAssessment | None:
+ for artefact in self._artefacts():
+ if isinstance(artefact, PriorityAssessment):
+ return artefact
+ return None
+
+
+# On re-research, the agent confirms still-valid prior artefacts instead of regenerating them —
+# a confirmation persists nothing, so the report log only grows when something actually changed.
+# These wrappers are session output shapes only; they are never stored.
+
+
+class SignalFindingUpdate(BaseModel):
+ """Re-research response for a signal that already has a finding: confirm it or replace it."""
+
+ previous_finding_correct: bool = Field(
+ description="True when the previous finding is still accurate as-is. It will be kept unchanged "
+ "and no new finding recorded."
+ )
+ finding: SignalFinding | None = Field(
+ default=None,
+ description="The replacement finding. Required when previous_finding_correct is false; omit when it is true.",
+ )
+
+ @model_validator(mode="after")
+ def finding_required_when_changed(self) -> SignalFindingUpdate:
+ if not self.previous_finding_correct and self.finding is None:
+ raise ValueError("finding is required when previous_finding_correct is false")
+ return self
+
+
+class ActionabilityUpdate(BaseModel):
+ """Re-assessment response when a previous actionability assessment exists."""
+
+ previous_assessment_correct: bool = Field(
+ description="True when the previous actionability assessment still holds as-is. It will be kept "
+ "unchanged and no new assessment recorded."
+ )
+ assessment: ActionabilityAssessment | None = Field(
+ default=None,
+ description="The replacement assessment. Required when previous_assessment_correct is false; "
+ "omit when it is true.",
+ )
+
+ @model_validator(mode="after")
+ def assessment_required_when_changed(self) -> ActionabilityUpdate:
+ if not self.previous_assessment_correct and self.assessment is None:
+ raise ValueError("assessment is required when previous_assessment_correct is false")
+ return self
+
+
+class PriorityUpdate(BaseModel):
+ """Re-assessment response when a previous priority assessment exists."""
+
+ previous_assessment_correct: bool = Field(
+ description="True when the previous priority assessment still holds as-is. It will be kept "
+ "unchanged and no new assessment recorded."
)
- actionability: ActionabilityAssessment = Field(description="Actionability assessment.")
- priority: PriorityAssessment | None = Field(
- default=None, description="Priority assessment. None when not actionable."
+ assessment: PriorityAssessment | None = Field(
+ default=None,
+ description="The replacement assessment. Required when previous_assessment_correct is false; "
+ "omit when it is true.",
)
+ @model_validator(mode="after")
+ def assessment_required_when_changed(self) -> PriorityUpdate:
+ if not self.previous_assessment_correct and self.assessment is None:
+ raise ValueError("assessment is required when previous_assessment_correct is false")
+ return self
+
def _render_existing_report_context(previous_report_id: str | None) -> str:
if not previous_report_id:
@@ -198,8 +220,8 @@ def _render_previous_finding_context(previous_finding: SignalFinding | None) ->
This signal was already analyzed in an earlier report run.
- First, lightly validate whether the cited code paths still exist and whether the previous claim still appears true.
-- If the previous finding is still valid, reuse it with only minimal edits and avoid deep re-research.
-- If the old code paths are stale or the evidence no longer holds, investigate the signal as new.
+- If the previous finding is still valid, respond with `previous_finding_correct: true` and no new finding — it will be kept as-is.
+- If the old code paths are stale or the evidence no longer holds, investigate the signal as new and return the replacement in `finding`.
- When lightly validating a previous finding, aim to spend fewer tool calls than a fresh investigation.
Previous finding:
@@ -224,8 +246,8 @@ This report was previously assessed as:
Decide whether the updated set of signal findings changes that assessment.
-- If it still holds, keep the assessment materially the same and update the explanation only as much as needed.
-- If it changed, return the new assessment and explain what changed.
+- If it still holds, respond with `previous_assessment_correct: true` and no new assessment — it will be kept as-is.
+- If it changed, return the new assessment in `assessment` and explain what changed.
"""
@@ -244,8 +266,8 @@ This report was previously prioritized as:
Decide whether the updated set of signal findings changes that priority.
-- If it still holds, keep the priority materially the same and update the explanation only as much as needed.
-- If it changed, return the new priority and explain what changed.
+- If it still holds, respond with `previous_assessment_correct: true` and no new assessment — it will be kept as-is.
+- If it changed, return the new priority in `assessment` and explain what changed.
"""
@@ -305,6 +327,8 @@ You have two investigation tools:
1. **The codebase** — the full PostHog repository is available on disk. Use file search, grep, and code reading.
2. **PostHog MCP** — you can query PostHog analytics data via MCP tools like `execute-sql`, `query-run`, `read-data-schema`, `insights-get-all`, `experiment-get`, `list-errors`, `feature-flag-get-all`, etc.
+The report's history lives in its artefacts (prior findings, judgments, notes, task runs). You can list them with the `inbox-report-artefacts-list` MCP tool when prior context would help. Do not create or modify artefacts yourself — at the end of the session you will be asked for your findings and assessments as structured responses, and the pipeline persists them. Where an existing artefact of a given type is still correct, you will be able to confirm it instead of producing a new one.
+
When a signal includes **Attached images**, the URLs are publicly reachable — fetch them directly to inspect screenshots, UI issues, or other visual evidence.
When a signal includes a **`remediation`** field, treat its guidance as authoritative — it tells you exactly how to fix the issue (which MCP tools to call and, where the fix lives in the user's codebase, how to apply it). Do not re-derive the fix from scratch: follow the guidance, then still do the work a good report needs — locate the relevant code, identify the causative commits, confirm the problem via the PostHog MCP, and verify the fix (e.g. query whether the expected events now arrive)."""
@@ -356,7 +380,10 @@ def build_initial_research_prompt(
) -> str:
"""Build the opening prompt for the first signal in a multi-turn research session."""
signal_block = _render_signal_for_research(first_signal, 1, total_signals)
- finding_schema = json.dumps(SignalFinding.model_json_schema(), indent=2)
+ # With a previous finding the agent answers with the update wrapper, so it can confirm the
+ # existing finding instead of regenerating it.
+ finding_model = SignalFindingUpdate if previous_finding else SignalFinding
+ finding_schema = json.dumps(finding_model.model_json_schema(), indent=2)
report_context = ""
if title or summary:
@@ -416,7 +443,8 @@ def build_signal_investigation_prompt(
) -> str:
"""Build a follow-up prompt for signal N (2..total)."""
signal_block = _render_signal_for_research(signal, index, total)
- finding_schema = json.dumps(SignalFinding.model_json_schema(), indent=2)
+ finding_model = SignalFindingUpdate if previous_finding else SignalFinding
+ finding_schema = json.dumps(finding_model.model_json_schema(), indent=2)
previous_finding_context = _render_previous_finding_context(previous_finding)
return f"""## Signal {index} of {total}
@@ -441,7 +469,8 @@ def build_actionability_prompt(
previous_actionability: ActionabilityAssessment | None = None,
) -> str:
"""Build the prompt asking for an actionability assessment after all signals are investigated."""
- schema = json.dumps(ActionabilityAssessment.model_json_schema(), indent=2)
+ model = ActionabilityUpdate if previous_actionability else ActionabilityAssessment
+ schema = json.dumps(model.model_json_schema(), indent=2)
previous_actionability_context = _render_previous_actionability_context(previous_actionability)
return f"""You have investigated all {total_signals} signal(s). Now assess: **is this report actionable?**
@@ -468,7 +497,8 @@ def build_priority_prompt(
previous_priority: PriorityAssessment | None = None,
) -> str:
"""Build the prompt asking for a priority assessment (only sent when actionable)."""
- schema = json.dumps(PriorityAssessment.model_json_schema(), indent=2)
+ model = PriorityUpdate if previous_priority else PriorityAssessment
+ schema = json.dumps(model.model_json_schema(), indent=2)
previous_priority_context = _render_previous_priority_context(previous_priority)
return f"""Now assess the **priority** of this report based on your research across all {total_signals} signal(s).
@@ -537,6 +567,49 @@ def _enforce_signal_id(finding: SignalFinding, expected_id: str) -> SignalFindin
return finding
+def _resolve_finding_response(
+ response: SignalFinding | SignalFindingUpdate,
+ previous_finding: SignalFinding | None,
+ expected_id: str,
+) -> tuple[SignalFinding, bool]:
+ """Collapse a per-signal research response to (effective finding, is_new)."""
+ if isinstance(response, SignalFindingUpdate):
+ if response.previous_finding_correct and previous_finding is not None:
+ return previous_finding, False
+ if response.finding is None: # unreachable: the model validator requires it
+ raise ValueError("SignalFindingUpdate carried no finding")
+ return _enforce_signal_id(response.finding, expected_id), True
+ return _enforce_signal_id(response, expected_id), True
+
+
+def _resolve_actionability_response(
+ response: ActionabilityAssessment | ActionabilityUpdate,
+ previous: ActionabilityAssessment | None,
+) -> tuple[ActionabilityAssessment, bool]:
+ """Collapse an actionability response to (effective assessment, is_new)."""
+ if isinstance(response, ActionabilityUpdate):
+ if response.previous_assessment_correct and previous is not None:
+ return previous, False
+ if response.assessment is None: # unreachable: the model validator requires it
+ raise ValueError("ActionabilityUpdate carried no assessment")
+ return response.assessment, True
+ return response, True
+
+
+def _resolve_priority_response(
+ response: PriorityAssessment | PriorityUpdate,
+ previous: PriorityAssessment | None,
+) -> tuple[PriorityAssessment, bool]:
+ """Collapse a priority response to (effective assessment, is_new)."""
+ if isinstance(response, PriorityUpdate):
+ if response.previous_assessment_correct and previous is not None:
+ return previous, False
+ if response.assessment is None: # unreachable: the model validator requires it
+ raise ValueError("PriorityUpdate carried no assessment")
+ return response.assessment, True
+ return response, True
+
+
async def run_multi_turn_research(
signals: list[SignalData],
context: CustomPromptSandboxContext,
@@ -560,7 +633,7 @@ async def run_multi_turn_research(
raise ValueError("No signals to investigate")
previous_findings_by_signal_id = (
- {finding.signal_id: finding for finding in previous_report_research.findings}
+ {finding.signal_id: finding for finding in previous_report_research.effective_findings()}
if previous_report_research
else {}
)
@@ -572,19 +645,23 @@ async def run_multi_turn_research(
output_fn(f"Starting multi-turn research: {total} signal(s)")
# Turn 1: initial prompt + signal 1
+ first_previous = previous_findings_by_signal_id.get(signals[0].signal_id)
initial_prompt = build_initial_research_prompt(
signals[0],
total,
title=title,
summary=summary,
previous_report_id=previous_report_id,
- previous_finding=previous_findings_by_signal_id.get(signals[0].signal_id),
+ previous_finding=first_previous,
has_business_knowledge=has_business_knowledge,
)
- session, first_finding = await MultiTurnSession.start(
+ first_schema: type[SignalFinding] | type[SignalFindingUpdate] = (
+ SignalFindingUpdate if first_previous else SignalFinding
+ )
+ session, first_response = await MultiTurnSession.start(
prompt=initial_prompt,
context=context,
- model=SignalFinding,
+ model=first_schema,
branch=branch,
step_name="report_research",
verbose=verbose,
@@ -599,73 +676,108 @@ async def run_multi_turn_research(
# - otherwise an orphaned sandbox can keep running until the workflow inactivity timeout
try:
- # Record the research task relationship immediately after task creation
+ # Record the research task association immediately after task creation — the task_run
+ # artefact IS the task↔report association.
if signal_report_id:
- from products.signals.backend.models import SignalReportTask
+ from products.signals.backend.task_run_artefacts import (
+ SIGNALS_PRODUCT,
+ TASK_RUN_TYPE_RESEARCH,
+ aappend_task_run_artefact,
+ )
- await SignalReportTask.objects.acreate(
+ await aappend_task_run_artefact(
team_id=context.team_id,
report_id=signal_report_id,
+ product=SIGNALS_PRODUCT,
+ type=TASK_RUN_TYPE_RESEARCH,
task_id=str(session.task.id),
- relationship=SignalReportTask.Relationship.RESEARCH,
)
- first_finding = _enforce_signal_id(first_finding, signals[0].signal_id)
- findings: list[SignalFinding] = [first_finding]
+ # Each finding/assessment lands in new_artefacts (produced this run) or old_artefacts
+ # (confirmed unchanged); persistence writes the new list, reusing the old.
+ old_artefacts: list[ResearchArtefactContent] = []
+ new_artefacts: list[ResearchArtefactContent] = []
+
+ first_finding, first_is_new = _resolve_finding_response(first_response, first_previous, signals[0].signal_id)
+ (new_artefacts if first_is_new else old_artefacts).append(first_finding)
if output_fn:
- output_fn(f"Signal 1/{total} done: {first_finding.signal_id}")
+ output_fn(
+ f"Signal 1/{total} done: {first_finding.signal_id}"
+ + ("" if first_is_new else " (previous finding confirmed)")
+ )
# Turns 2..N: one follow-up per remaining signal
for i, signal in enumerate(signals[1:], start=2):
if output_fn:
output_fn(f"Investigating signal {i}/{total}...")
+ previous_finding = previous_findings_by_signal_id.get(signal.signal_id)
followup_prompt = build_signal_investigation_prompt(
signal,
i,
total,
- previous_finding=previous_findings_by_signal_id.get(signal.signal_id),
+ previous_finding=previous_finding,
+ )
+ followup_schema: type[SignalFinding] | type[SignalFindingUpdate] = (
+ SignalFindingUpdate if previous_finding else SignalFinding
)
- finding = await session.send_followup(
+ response = await session.send_followup(
followup_prompt,
- SignalFinding,
+ followup_schema,
label=f"signal_{i}_of_{total}",
)
- finding = _enforce_signal_id(finding, signal.signal_id)
- findings.append(finding)
+ finding, is_new = _resolve_finding_response(response, previous_finding, signal.signal_id)
+ (new_artefacts if is_new else old_artefacts).append(finding)
if output_fn:
- output_fn(f"Signal {i}/{total} done: {finding.signal_id}")
+ output_fn(
+ f"Signal {i}/{total} done: {finding.signal_id}"
+ + ("" if is_new else " (previous finding confirmed)")
+ )
# Actionability assessment
if output_fn:
output_fn("Assessing actionability...")
- actionability_prompt = build_actionability_prompt(
- total,
- previous_actionability=previous_report_research.actionability if previous_report_research else None,
+ previous_actionability = (
+ previous_report_research.effective_actionability() if previous_report_research else None
+ )
+ actionability_prompt = build_actionability_prompt(total, previous_actionability=previous_actionability)
+ actionability_schema: type[ActionabilityAssessment] | type[ActionabilityUpdate] = (
+ ActionabilityUpdate if previous_actionability else ActionabilityAssessment
)
- actionability_result = await session.send_followup(
+ actionability_response = await session.send_followup(
actionability_prompt,
- ActionabilityAssessment,
+ actionability_schema,
label="actionability",
)
+ actionability_result, actionability_is_new = _resolve_actionability_response(
+ actionability_response, previous_actionability
+ )
+ (new_artefacts if actionability_is_new else old_artefacts).append(actionability_result)
if output_fn:
- output_fn(f"Actionability: {actionability_result.actionability.value}")
+ output_fn(
+ f"Actionability: {actionability_result.actionability.value}"
+ + ("" if actionability_is_new else " (unchanged)")
+ )
# Priority assessment (only when actionable)
priority_result: PriorityAssessment | None = None
+ priority_is_new = False
if actionability_result.actionability != ActionabilityChoice.NOT_ACTIONABLE:
if output_fn:
output_fn("Assessing priority...")
- priority_prompt = build_priority_prompt(
- total,
- previous_priority=previous_report_research.priority if previous_report_research else None,
+ previous_priority = previous_report_research.effective_priority() if previous_report_research else None
+ priority_prompt = build_priority_prompt(total, previous_priority=previous_priority)
+ priority_schema: type[PriorityAssessment] | type[PriorityUpdate] = (
+ PriorityUpdate if previous_priority else PriorityAssessment
)
- priority_result = await session.send_followup(
+ priority_response = await session.send_followup(
priority_prompt,
- PriorityAssessment,
+ priority_schema,
label="priority",
)
+ priority_result, priority_is_new = _resolve_priority_response(priority_response, previous_priority)
+ (new_artefacts if priority_is_new else old_artefacts).append(priority_result)
if output_fn:
- output_fn(f"Priority: {priority_result.priority.value}")
+ output_fn(f"Priority: {priority_result.priority.value}" + ("" if priority_is_new else " (unchanged)"))
if output_fn:
output_fn("Generating title and summary...")
@@ -688,11 +800,15 @@ async def run_multi_turn_research(
await asyncio.shield(session.end(status="failed", error=str(e)))
raise
- logger.info("multi_turn_research: completed with %d findings", len(findings))
+ new_finding_count = sum(1 for artefact in new_artefacts if isinstance(artefact, SignalFinding))
+ total_finding_count = new_finding_count + sum(
+ 1 for artefact in old_artefacts if isinstance(artefact, SignalFinding)
+ )
+ logger.info("multi_turn_research: completed with %d findings (%d new)", total_finding_count, new_finding_count)
return ReportResearchOutput(
title=presentation_result.title,
summary=presentation_result.summary,
- findings=findings,
- actionability=actionability_result,
- priority=priority_result,
+ research_task_id=str(session.task.id),
+ old_artefacts=old_artefacts,
+ new_artefacts=new_artefacts,
)
diff --git a/products/signals/backend/routes.py b/products/signals/backend/routes.py
index ed0532cf8a0b..471cb23fc2ba 100644
--- a/products/signals/backend/routes.py
+++ b/products/signals/backend/routes.py
@@ -16,9 +16,6 @@ def register_routes(routers: RouterRegistry) -> None:
signal_reports_router = routers.projects.register(
r"signals/reports", signals.SignalReportViewSet, "environment_signal_reports", ["team_id"]
)
- signal_reports_router.register(
- r"tasks", signals.SignalReportTaskViewSet, "environment_signal_report_tasks", ["team_id", "report_id"]
- )
signal_reports_router.register(
r"artefacts",
signals.SignalReportArtefactViewSet,
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 48f6db52c89e..a322a8f4bd1f 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -9,11 +9,11 @@ from rest_framework import serializers
from posthog.models import User
from posthog.temporal.common.client import sync_connect
+from .artefact_schemas import NON_WRITABLE_ARTEFACT_TYPES
from .models import (
AutonomyPriority,
SignalReport,
SignalReportArtefact,
- SignalReportTask,
SignalSourceConfig,
SignalTeamConfig,
SignalUserAutonomyConfig,
@@ -233,13 +233,6 @@ class SignalUserAutonomyConfigSerializer(serializers.ModelSerializer):
}
-class SignalReportTaskSerializer(serializers.ModelSerializer):
- class Meta:
- model = SignalReportTask
- fields = ["id", "relationship", "task_id", "created_at"]
- read_only_fields = fields
-
-
class SignalUserAutonomyConfigCreateSerializer(serializers.Serializer):
autostart_priority = serializers.ChoiceField(choices=AutonomyPriority.choices, required=False, allow_null=True)
slack_notification_integration_id = serializers.IntegerField(
@@ -412,10 +405,20 @@ class SignalReportSerializer(serializers.ModelSerializer):
class SignalReportArtefactSerializer(serializers.ModelSerializer):
content = serializers.SerializerMethodField()
+ 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.",
+ )
+ 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.",
+ )
class Meta:
model = SignalReportArtefact
- fields = ["id", "type", "content", "created_at"]
+ fields = ["id", "type", "content", "created_at", "updated_at", "created_by", "task_id"]
read_only_fields = fields
def get_content(self, obj: SignalReportArtefact) -> dict | list:
@@ -494,3 +497,97 @@ class SignalReportArtefactWriteSerializer(serializers.Serializer):
if len(value) > self.MAX_ENTRIES:
raise serializers.ValidationError(f"At most {self.MAX_ENTRIES} reviewers may be supplied.")
return value
+
+
+# Writable types only — `video_segment` (and any other NON_WRITABLE type) is read-only and rejected
+# by the write API, so it must not be advertised as an option here.
+_WRITABLE_ARTEFACT_TYPES = sorted(set(SignalReportArtefact.ArtefactType.values) - NON_WRITABLE_ARTEFACT_TYPES)
+
+_ARTEFACT_TYPES_HELP = (
+ "The artefact type. One of: "
+ + ", ".join(_WRITABLE_ARTEFACT_TYPES)
+ + ". Log types accumulate; status types (safety_judgment, actionability_judgment, "
+ "priority_judgment, repo_selection, suggested_reviewers) are latest-wins — appending a new "
+ "version supersedes the previous one as the report's canonical status."
+)
+
+
+def _validate_artefact_content_is_container(value: object) -> dict | list:
+ if not isinstance(value, dict | list):
+ raise serializers.ValidationError("content must be a JSON object or array.")
+ return value
+
+
+class SignalReportArtefactLogCreateSerializer(serializers.Serializer):
+ """Body for appending an artefact to a report.
+
+ Everything is append-only: log artefacts accumulate, status artefacts supersede the previous
+ version (latest-wins). The `content` shape depends on `artefact_type` and is validated
+ against the type's schema (see `products/signals/backend/artefact_schemas.py`).
+ """
+
+ # Plain CharField (not ChoiceField) on purpose: the value is validated against
+ # `ArtefactType.values` in the view, and avoiding a `choices=` enum keeps this off the
+ # collision-prone enum-name path in the generated OpenAPI types.
+ artefact_type = serializers.CharField(help_text=_ARTEFACT_TYPES_HELP)
+ content = serializers.JSONField(
+ help_text="The artefact payload as a JSON object or array; shape depends on artefact_type "
+ "and is validated against its schema.",
+ )
+
+ def validate_content(self, value: object) -> dict | list:
+ # Shape-only here: the view is the schema boundary — it parses the payload into the
+ # type's content model (after normalizing task_run defaults) and 400s on a mismatch.
+ return _validate_artefact_content_is_container(value)
+
+
+class SignalReportArtefactLogUpdateSerializer(serializers.Serializer):
+ """Body for replacing the content of an existing artefact (addressed by id).
+
+ Per-type schema validation happens in the view, which knows the artefact's type.
+ """
+
+ content = serializers.JSONField(
+ help_text="The new artefact payload as a JSON object or array, matching the artefact type's schema."
+ )
+
+ def validate_content(self, value: object) -> dict | list:
+ return _validate_artefact_content_is_container(value)
+
+
+class SignalReportArtefactWriteResponseSerializer(serializers.Serializer):
+ """Response shape for the log-artefact create/update endpoints — echoes the stored row."""
+
+ id = serializers.UUIDField(read_only=True, help_text="The artefact's unique id.")
+ report_id = serializers.UUIDField(read_only=True, help_text="The id of the report this artefact belongs to.")
+ # Plain CharField (no `choices=`) to keep the model's full ArtefactType enum out of the
+ # generated OpenAPI schema; the value is simply echoed back.
+ type = serializers.CharField(read_only=True, help_text="The artefact type.")
+ content = serializers.JSONField(read_only=True, help_text="The artefact payload, parsed from storage.")
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the artefact was created.")
+ updated_at = serializers.DateTimeField(
+ read_only=True,
+ allow_null=True,
+ help_text="When the artefact was last written — set on creation and refreshed on each edit. "
+ "Null only for rows created before this field existed.",
+ )
+ 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 writes.",
+ )
+
+
+class CommitDiffResponseSerializer(serializers.Serializer):
+ """Response for the `commit` artefact diff endpoint — the commit's branch rendered against the
+ repository default branch."""
+
+ diff = serializers.CharField(
+ read_only=True,
+ help_text="Unified diff (patch) text of the branch against the repository default branch, "
+ "from the GitHub compare API.",
+ )
+ truncated = serializers.BooleanField(
+ read_only=True,
+ help_text="True when the diff was too large to return in full and has been truncated.",
+ )
diff --git a/products/signals/backend/task_attribution.py b/products/signals/backend/task_attribution.py
new file mode 100644
index 000000000000..941ea9f803f7
--- /dev/null
+++ b/products/signals/backend/task_attribution.py
@@ -0,0 +1,53 @@
+"""Task attribution for signals API writes, derived from the `X-PostHog-Task-Id` header.
+
+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.
+
+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.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+from rest_framework.exceptions import ValidationError
+from rest_framework.request import Request
+
+from products.signals.backend.models import ArtefactAttribution
+from products.tasks.backend.facade import api as tasks_api
+
+TASK_ID_HEADER = "X-PostHog-Task-Id"
+
+
+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
+ that doesn't exist on this team.
+ """
+ raw = request.headers.get(TASK_ID_HEADER)
+ if not raw or not raw.strip():
+ return None
+ try:
+ task_uuid = uuid.UUID(raw.strip())
+ except ValueError:
+ raise ValidationError({TASK_ID_HEADER: "must be a task UUID."})
+ if not tasks_api.task_exists(task_uuid, team_id):
+ raise ValidationError({TASK_ID_HEADER: "unknown task for this project."})
+ return str(task_uuid)
+
+
+def resolve_request_attribution(request: Request, team_id: int) -> ArtefactAttribution:
+ """Attribution for an API write: the header task when present, else the requesting user."""
+ 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.")
+ return ArtefactAttribution.from_user(user_id)
diff --git a/products/signals/backend/task_run_artefacts.py b/products/signals/backend/task_run_artefacts.py
new file mode 100644
index 000000000000..812ce71fbf2f
--- /dev/null
+++ b/products/signals/backend/task_run_artefacts.py
@@ -0,0 +1,122 @@
+"""Helpers for appending and querying `task_run` log artefacts on a report.
+
+A `task_run` artefact records that a `tasks.Task` ran for a report (research, implementation,
+repo-selection, …) so the run shows up in the report's work-log timeline. The append lives here
+as a single source of truth, shared by the live creation paths and the
+`backfill_task_run_artefacts` management command.
+
+Each artefact carries a `(product, type)` pair following the custom-agent identifier shape: the
+built-in signals pipeline uses `product="signals"` with one of the `TASK_RUN_TYPE_*` constants
+as `type`; custom agents supply their own `identifier()` pair. The pair is also how a task's
+purpose is *derived* — there is no relationship label on the task↔report association itself.
+"""
+
+from __future__ import annotations
+
+from products.signals.backend.artefact_schemas import (
+ SIGNALS_PRODUCT,
+ TASK_RUN_TYPE_IMPLEMENTATION,
+ TASK_RUN_TYPE_REPO_SELECTION,
+ TASK_RUN_TYPE_RESEARCH,
+ TaskRunArtefact,
+)
+from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact, SignalReportTask
+
+# 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
+# working.
+__all__ = [
+ "SIGNALS_PRODUCT",
+ "TASK_RUN_TYPE_IMPLEMENTATION",
+ "TASK_RUN_TYPE_REPO_SELECTION",
+ "TASK_RUN_TYPE_RESEARCH",
+ "aappend_task_run_artefact",
+ "append_task_run_artefact",
+ "record_implementation_task",
+ "signals_task_ids",
+]
+
+
+def _task_run_content(product: str, type: str, task_id: str, run_id: str | None) -> TaskRunArtefact:
+ return TaskRunArtefact(
+ task_id=str(task_id),
+ run_id=str(run_id) if run_id is not None else None,
+ product=product,
+ type=type,
+ )
+
+
+def append_task_run_artefact(
+ *, team_id: int, report_id: str, product: str, type: str, task_id: str, run_id: str | None = None
+) -> SignalReportArtefact:
+ """Append a `task_run` log artefact recording that a task ran for the report (sync).
+
+ Always attributed to the task it records — that task *is* the producer of the entry.
+ """
+ return SignalReportArtefact.add_log(
+ team_id=team_id,
+ report_id=str(report_id),
+ content=_task_run_content(product, type, task_id, run_id),
+ attribution=ArtefactAttribution.from_task(task_id),
+ )
+
+
+async def aappend_task_run_artefact(
+ *, team_id: int, report_id: str, product: str, type: str, task_id: str, run_id: str | None = None
+) -> SignalReportArtefact:
+ """Append a `task_run` log artefact recording that a task ran for the report (async).
+
+ Uses the async ORM directly (not a `database_sync_to_async` hop, which would run on a
+ different connection and not see the caller's uncommitted rows); content validation and
+ task attribution match `append_task_run_artefact`.
+ """
+ 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),
+ )
+
+
+def signals_task_ids(*, report_id: str, type: str) -> list[str]:
+ """Task ids associated with the report by the built-in signals pipeline (product `signals`) for
+ the given `type`, oldest first.
+
+ Thin wrapper over `SignalReport.associated_task_runs`, which unifies the `task_run` artefact log
+ with the legacy `SignalReportTask` gate rows — so this is how a task's *purpose* is derived
+ across both sources during the migration.
+ """
+ return [
+ run.task_id
+ for run in SignalReport.associated_task_runs(report_id=report_id, product=SIGNALS_PRODUCT, type=type)
+ ]
+
+
+def record_implementation_task(
+ *, team_id: int, report_id: str, task_id: str, run_id: str | None = None
+) -> SignalReportArtefact:
+ """Record a started implementation task as BOTH the legacy `SignalReportTask` gate row and the
+ `task_run` work-log artefact.
+
+ `SignalReportTask` (an `implementation` row) is the auto-start idempotency gate — see
+ `auto_start.py` — because the artefact log is freeform and API-mutable and so can't be trusted
+ for a spend-controlling decision. We dual-write the artefact so that, once
+ `backfill_task_run_artefacts` has converted every legacy row, the gate can switch to the
+ artefact log and `SignalReportTask` can be dropped. Call inside the transaction that created
+ the task. Shared by auto-start and the manual start-task API.
+ """
+ SignalReportTask.objects.get_or_create(
+ team_id=team_id,
+ report_id=report_id,
+ task_id=task_id,
+ defaults={"relationship": TASK_RUN_TYPE_IMPLEMENTATION},
+ )
+ return append_task_run_artefact(
+ team_id=team_id,
+ report_id=report_id,
+ product=SIGNALS_PRODUCT,
+ type=TASK_RUN_TYPE_IMPLEMENTATION,
+ task_id=task_id,
+ run_id=run_id,
+ )
diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.py
index 2e207de5c711..be581349edd6 100644
--- a/products/signals/backend/temporal/agentic/report.py
+++ b/products/signals/backend/temporal/agentic/report.py
@@ -1,12 +1,12 @@
-import json
from dataclasses import dataclass
+from typing import TypeVar
from django.db import transaction
import structlog
import temporalio
import posthoganalytics
-from pydantic import ValidationError
+from pydantic import BaseModel, ValidationError
from posthog.models.team.team import Team
from posthog.sync import database_sync_to_async
@@ -15,8 +15,9 @@ from posthog.temporal.common.scoped import scoped_temporal
from posthog.temporal.common.utils import close_db_connections
from products.business_knowledge.backend.logic import is_available_for_team
+from products.signals.backend.artefact_schemas import ArtefactContent, SuggestedReviewers
from products.signals.backend.auto_start import ReviewerContent, maybe_autostart_implementation_task
-from products.signals.backend.models import SignalReport, SignalReportArtefact
+from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact
from products.signals.backend.report_generation.research import (
ActionabilityAssessment,
ActionabilityChoice,
@@ -59,6 +60,24 @@ class RunAgenticReportOutput:
repository: str
+_ArtefactContentT = TypeVar("_ArtefactContentT", bound=BaseModel)
+
+
+def _parse_artefact_content(
+ model_cls: type[_ArtefactContentT], artefact: SignalReportArtefact, report_id: str
+) -> _ArtefactContentT:
+ # These artefacts are written only by this pipeline from the current schemas, so a parse failure
+ # is a bug on our side (corrupt content or an incompatible schema change) — fail loudly rather
+ # than silently dropping prior research and degrading a re-promotion into a fresh run.
+ try:
+ return model_cls.model_validate_json(artefact.content)
+ except ValidationError as error:
+ raise ValueError(
+ f"report {report_id}: {artefact.type} artefact {artefact.id} is incompatible with the "
+ f"current {model_cls.__name__} schema"
+ ) from error
+
+
async def _load_previous_research(report_id: str) -> ReportResearchOutput | None:
"""Reconstruct the previous report state."""
report = await SignalReport.objects.filter(id=report_id).only("title", "summary").afirst()
@@ -80,26 +99,25 @@ async def _load_previous_research(report_id: str) -> ReportResearchOutput | None
],
).order_by("created_at")
- findings: list[SignalFinding] = []
+ # Artefacts are append-only, so there may be several versions of each. Iterating in
+ # ascending `created_at` order means the last value seen wins: judgments collapse to their
+ # latest, and findings are keyed by `signal_id` so a re-researched signal supersedes its
+ # prior version while distinct signals each keep an entry.
+ findings_by_signal: dict[str, SignalFinding] = {}
actionability: ActionabilityAssessment | None = None
priority: PriorityAssessment | None = None
async for artefact in artefacts_qs:
match artefact.type:
case SignalReportArtefact.ArtefactType.SIGNAL_FINDING:
- findings.append(SignalFinding.model_validate_json(artefact.content))
+ finding = _parse_artefact_content(SignalFinding, artefact, report_id)
+ findings_by_signal[finding.signal_id] = finding
case SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT:
- try:
- actionability = ActionabilityAssessment.model_validate_json(artefact.content)
- except ValidationError:
- logger.warning(
- "Ignoring actionability artefact with incompatible schema (likely written by the legacy path)",
- report_id=report_id,
- artefact_id=artefact.id,
- )
+ actionability = _parse_artefact_content(ActionabilityAssessment, artefact, report_id)
case SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT:
- priority = PriorityAssessment.model_validate_json(artefact.content)
+ priority = _parse_artefact_content(PriorityAssessment, artefact, report_id)
+ findings = list(findings_by_signal.values())
if not findings or actionability is None:
logger.info(
"load previous research: missing artefacts, treating as first run",
@@ -112,9 +130,9 @@ async def _load_previous_research(report_id: str) -> ReportResearchOutput | None
return ReportResearchOutput(
title=report.title,
summary=report.summary,
- findings=findings,
- actionability=actionability,
- priority=priority,
+ # Reconstructed from already-persisted artefacts, so everything is "old" — a re-research that
+ # reuses these writes nothing; only what it changes lands in new_artefacts.
+ old_artefacts=[*findings, actionability, *([priority] if priority else [])],
)
@@ -127,6 +145,15 @@ _AGENTIC_ARTEFACT_TYPES = [
]
+@dataclass(frozen=True)
+class ArtefactDraft:
+ """An artefact pending append: its typed content (the row's type derives from the model
+ class) and who produced it."""
+
+ content: ArtefactContent
+ attribution: ArtefactAttribution
+
+
def _build_reviewers_content(
team_id: int,
repository: str,
@@ -173,76 +200,74 @@ def _build_reviewers_content(
return reviewers_content
-def _replace_agentic_report_artefacts(
- team_id: int,
- report_id: str,
- artefacts: list[SignalReportArtefact],
-) -> None:
+def _append_agentic_report_artefacts(*, team_id: int, report_id: str, artefacts: list[ArtefactDraft]) -> None:
+ # Append-only: each (re-promotion) run adds a new version of its artefacts rather than
+ # replacing the previous ones. The report's current judgments / repo selection / reviewers are
+ # the latest row of each type; findings are keyed by `signal_id` (latest per signal wins).
+ # Prior versions are intentionally retained as report-log history. `_AGENTIC_ARTEFACT_TYPES`
+ # is kept as the documented set these versions belong to (and is asserted disjoint from the
+ # log types in tests). Written through `SignalReportArtefact.append` (the single artefact
+ # write path, routing each type to its append semantics) in one transaction; the caller
+ # orchestrates auto-start explicitly, so appends opt out of the model's auto-start
+ # re-evaluation hook.
with transaction.atomic():
- # Delete artefacts from previous agentic runs (re-promotion) before writing new ones.
- # Only deletes types owned by this path — safety_judgment is created by the safety judge
- # activity and left untouched.
- SignalReportArtefact.objects.filter(
- team_id=team_id, report_id=report_id, type__in=_AGENTIC_ARTEFACT_TYPES
- ).delete()
- SignalReportArtefact.objects.bulk_create(artefacts)
+ for draft in artefacts:
+ SignalReportArtefact.append(
+ team_id=team_id,
+ report_id=report_id,
+ content=draft.content,
+ attribution=draft.attribution,
+ reevaluate_autostart=False,
+ )
async def _persist_agentic_report_artefacts(
team_id: int, report_id: str, result: ReportResearchOutput, repo_selection: RepoSelectionResult
) -> None:
- artefacts: list[SignalReportArtefact] = [
- SignalReportArtefact(
- team_id=team_id,
- report_id=report_id,
- type=SignalReportArtefact.ArtefactType.REPO_SELECTION,
- content=repo_selection.model_dump_json(),
- ),
- ]
- artefacts.extend(
- SignalReportArtefact(
- team_id=team_id,
- report_id=report_id,
- type=SignalReportArtefact.ArtefactType.SIGNAL_FINDING,
- content=finding.model_dump_json(),
- )
- for finding in result.findings
- )
- artefacts.append(
- SignalReportArtefact(
- team_id=team_id,
- report_id=report_id,
- type=SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT,
- content=result.actionability.model_dump_json(),
- )
- )
- if result.priority:
- artefacts.append(
- SignalReportArtefact(
- team_id=team_id,
- report_id=report_id,
- type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,
- content=result.priority.model_dump_json(),
- )
- )
-
- # Resolve suggested reviewers from commit hashes
+ # Resolve suggested reviewers from commit hashes (always, from the effective findings —
+ # auto-start below needs them even when nothing is persisted this run)
reviewers_content = await database_sync_to_async(_build_reviewers_content, thread_sensitive=False)(
team_id=team_id,
repository=repo_selection.repository or "",
- findings=result.findings,
+ findings=result.effective_findings(),
+ )
+
+ # Persist only what's new this run; values the agent confirmed unchanged keep their latest
+ # persisted row. Reviewers are derived purely from findings, so they're only re-persisted
+ # when at least one finding changed.
+ #
+ # Attribution: the research findings / judgments / reviewers were produced by the research
+ # sandbox agent, so they're attributed to its task. Repo selection has its own task when a
+ # selection agent ran (N candidates); the 0/1-candidate shortcuts and reused selections fall
+ # back to system. These activities run on the Temporal worker but only *persist* what the
+ # sandbox agents produced.
+ research_attribution = (
+ ArtefactAttribution.from_task(result.research_task_id)
+ if result.research_task_id
+ else ArtefactAttribution.system()
+ )
+ repo_selection_attribution = (
+ ArtefactAttribution.from_task(repo_selection.task_id)
+ if repo_selection.task_id
+ else ArtefactAttribution.system()
)
- if reviewers_content:
+ # Everything the run flagged as new gets persisted; the artefact type derives from each content
+ # model. Reviewers are derived from findings, so they're only re-persisted when a finding changed.
+ has_new_finding = any(isinstance(content, SignalFinding) for content in result.new_artefacts)
+
+ artefacts = [
+ ArtefactDraft(content=repo_selection, attribution=repo_selection_attribution),
+ *(ArtefactDraft(content=content, attribution=research_attribution) for content in result.new_artefacts),
+ ]
+ if reviewers_content and has_new_finding:
artefacts.append(
- SignalReportArtefact(
- team_id=team_id,
- report_id=report_id,
- type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
- content=json.dumps(reviewers_content),
+ ArtefactDraft(
+ content=SuggestedReviewers.model_validate(list(reviewers_content)),
+ attribution=research_attribution,
)
)
- await database_sync_to_async(_replace_agentic_report_artefacts, thread_sensitive=False)(
+ await database_sync_to_async(_append_agentic_report_artefacts, thread_sensitive=False)(
team_id=team_id,
report_id=report_id,
artefacts=artefacts,
@@ -255,8 +280,8 @@ async def _persist_agentic_report_artefacts(
repository=repo_selection.repository or "",
title=result.title,
summary=result.summary,
- actionability=result.actionability,
- priority=result.priority,
+ actionability=result.effective_actionability(),
+ priority=result.effective_priority(),
reviewers_content=reviewers_content,
)
except Exception as error:
@@ -303,7 +328,10 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti
user_id=user_id,
repository=repository,
sandbox_environment_id=sandbox_env_id,
- posthog_mcp_scopes="read_only", # Needs only read (queries, insights)
+ # Reads only: the research agent queries data/insights and can list the report's
+ # artefacts, but never writes artefacts itself — the pipeline persists its
+ # structured outputs after the session.
+ posthog_mcp_scopes="read_only",
)
has_bk = await database_sync_to_async(_team_has_business_knowledge, thread_sensitive=False)(input.team_id)
# 2. Load previous research if this is a re-promoted report
@@ -324,20 +352,22 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti
result,
input.repo_selection,
)
+ actionability = result.effective_actionability()
+ priority = result.effective_priority()
logger.info(
"signals agentic report completed",
report_id=input.report_id,
signal_count=len(input.signals),
- choice=result.actionability.actionability.value,
+ choice=actionability.actionability.value,
repository=repository,
)
return RunAgenticReportOutput(
title=result.title,
summary=result.summary,
- choice=result.actionability.actionability,
- priority=result.priority.priority if result.priority else None,
- explanation=result.actionability.explanation,
- already_addressed=result.actionability.already_addressed,
+ choice=actionability.actionability,
+ priority=priority.priority if priority else None,
+ explanation=actionability.explanation,
+ already_addressed=actionability.already_addressed,
repository=repository,
)
except Exception as error:
diff --git a/products/signals/backend/temporal/inbox_notification.py b/products/signals/backend/temporal/inbox_notification.py
index 4429d0306f94..f6ececd324dc 100644
--- a/products/signals/backend/temporal/inbox_notification.py
+++ b/products/signals/backend/temporal/inbox_notification.py
@@ -23,7 +23,8 @@ from posthog.sync import database_sync_to_async
from posthog.temporal.common.scoped import scoped_temporal
from products.signals.backend.implementation_pr import fetch_implementation_pr_urls_for_reports
-from products.signals.backend.models import SignalReport, SignalReportTask
+from products.signals.backend.models import SignalReport
+from products.signals.backend.task_run_artefacts import SIGNALS_PRODUCT, TASK_RUN_TYPE_IMPLEMENTATION
from products.signals.backend.temporal.signal_queries import fetch_signals_for_report_sync
from products.tasks.backend.facade import api as tasks_facade
@@ -44,13 +45,12 @@ class InboxNotificationState:
def _compute_inbox_notification_state(team_id: int, report_id: str) -> InboxNotificationState:
- impl_task_ids = list(
- SignalReportTask.objects.filter(
- team_id=team_id,
- report_id=report_id,
- relationship=SignalReportTask.Relationship.IMPLEMENTATION,
- ).values_list("task_id", flat=True)
- )
+ impl_task_ids = [
+ run.task_id
+ for run in SignalReport.associated_task_runs(
+ report_id=report_id, team_id=team_id, product=SIGNALS_PRODUCT, type=TASK_RUN_TYPE_IMPLEMENTATION
+ )
+ ]
if not impl_task_ids:
return InboxNotificationState(has_implementation_task=False, pr_available=False, task_terminal=False)
diff --git a/products/signals/backend/temporal/report_safety_judge.py b/products/signals/backend/temporal/report_safety_judge.py
index 08b3f5e7bdc3..a10aa82cf57b 100644
--- a/products/signals/backend/temporal/report_safety_judge.py
+++ b/products/signals/backend/temporal/report_safety_judge.py
@@ -6,10 +6,12 @@ import structlog
import temporalio
from pydantic import BaseModel, Field, model_validator
+from posthog.sync import database_sync_to_async
from posthog.temporal.common.scoped import scoped_temporal
from posthog.temporal.common.utils import close_db_connections
-from products.signals.backend.models import SignalReportArtefact
+from products.signals.backend.artefact_schemas import SafetyJudgment
+from products.signals.backend.models import ArtefactAttribution, SignalReportArtefact
from products.signals.backend.temporal.llm import call_llm
from products.signals.backend.temporal.types import SignalData, render_signals_to_text
@@ -124,16 +126,14 @@ async def report_safety_judge_activity(input: SafetyJudgeInput) -> SafetyJudgeOu
signals=input.signals,
)
- await SignalReportArtefact.objects.acreate(
+ # Append-only: each safety assessment is a point-in-time entry in the report log. The
+ # report's current safety status is the latest safety_judgment row. System-attributed:
+ # the judge is a plain LLM call on the worker — no user or sandbox task is in scope.
+ await database_sync_to_async(SignalReportArtefact.append_status, thread_sensitive=False)(
team_id=input.team_id,
report_id=input.report_id,
- type=SignalReportArtefact.ArtefactType.SAFETY_JUDGMENT,
- content=json.dumps(
- {
- "choice": result.choice,
- "explanation": result.explanation,
- }
- ),
+ content=SafetyJudgment(choice=result.choice, explanation=result.explanation),
+ attribution=ArtefactAttribution.system(),
)
logger.debug(
diff --git a/products/signals/backend/test/test_agentic_report_activity.py b/products/signals/backend/test/test_agentic_report_activity.py
index bf8d5269353d..fffc6d88457f 100644
--- a/products/signals/backend/test/test_agentic_report_activity.py
+++ b/products/signals/backend/test/test_agentic_report_activity.py
@@ -17,14 +17,22 @@ from products.signals.backend.models import SignalReport, SignalReportArtefact
from products.signals.backend.report_generation.research import (
ActionabilityAssessment,
ActionabilityChoice,
+ ActionabilityUpdate,
Priority,
PriorityAssessment,
+ PriorityUpdate,
ReportResearchOutput,
SignalFinding,
+ _resolve_actionability_response,
+ _resolve_priority_response,
run_multi_turn_research,
)
from products.signals.backend.report_generation.select_repo import RepoSelectionResult
-from products.signals.backend.temporal.agentic.report import RunAgenticReportInput, run_agentic_report_activity
+from products.signals.backend.temporal.agentic.report import (
+ RunAgenticReportInput,
+ _parse_artefact_content,
+ run_agentic_report_activity,
+)
from products.signals.backend.temporal.agentic.select_repository import (
SelectRepositoryInput,
select_repository_activity,
@@ -57,10 +65,11 @@ async def ateam(aorganization):
def _build_research_output() -> ReportResearchOutput:
+ # A first run: every finding and assessment is new.
return ReportResearchOutput(
title="Onboarding funnel completion tracking may be regressing",
summary="Signals point to a likely regression around onboarding completion event tracking.",
- findings=[
+ new_artefacts=[
SignalFinding(
signal_id="sig-1",
relevant_code_paths=["frontend/src/scenes/onboarding/OnboardingFlow.tsx"],
@@ -73,17 +82,17 @@ def _build_research_output() -> ReportResearchOutput:
data_queried="Compared pageview and user_signed_up volumes; those remained stable.",
verified=True,
),
+ ActionabilityAssessment(
+ explanation="The issue has a clear code path and supporting event-volume evidence.",
+ actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE,
+ already_addressed=False,
+ ),
+ PriorityAssessment(
+ explanation="The regression affects a core onboarding flow and should be addressed quickly.",
+ priority=Priority.P1,
+ dollar_value=5000.0,
+ ),
],
- actionability=ActionabilityAssessment(
- explanation="The issue has a clear code path and supporting event-volume evidence.",
- actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE,
- already_addressed=False,
- ),
- priority=PriorityAssessment(
- explanation="The regression affects a core onboarding flow and should be addressed quickly.",
- priority=Priority.P1,
- dollar_value=5000.0,
- ),
)
@@ -311,6 +320,7 @@ async def test_run_agentic_report_activity_persists_artefacts(monkeypatch, ateam
assert repo_selection_content == {
"repository": "posthog/posthog",
"reason": "Single repository connected: posthog/posthog",
+ "task_id": None,
}
finding_contents = [json.loads(artefact.content) for artefact in artefacts[3:]]
@@ -375,3 +385,75 @@ async def test_run_multi_turn_research_ends_session_when_followup_fails():
session.end.assert_awaited_once()
assert session.end.await_args.kwargs["status"] == "failed"
+
+
+def test_parse_artefact_content_parses_valid_content():
+ actionability = ActionabilityAssessment(
+ explanation="e", actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE, already_addressed=False
+ )
+ artefact = SignalReportArtefact(
+ type=SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT, content=actionability.model_dump_json()
+ )
+ assert _parse_artefact_content(ActionabilityAssessment, artefact, "report-1") == actionability
+
+
+def test_parse_artefact_content_raises_on_incompatible_schema():
+ # No legacy path writes these artefacts, so a parse failure is our bug — fail loudly, don't skip.
+ artefact = SignalReportArtefact(
+ type=SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT, content='{"unexpected": "shape"}'
+ )
+ with pytest.raises(ValueError, match="incompatible with the current ActionabilityAssessment schema"):
+ _parse_artefact_content(ActionabilityAssessment, artefact, "report-1")
+
+
+def _actionability(explanation: str) -> ActionabilityAssessment:
+ return ActionabilityAssessment(
+ explanation=explanation,
+ actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE,
+ already_addressed=False,
+ )
+
+
+def _priority(explanation: str) -> PriorityAssessment:
+ return PriorityAssessment(explanation=explanation, priority=Priority.P1)
+
+
+ ("response", "previous", "expected_explanation", "expected_is_new"),
+ [
+ # First run: a bare assessment is always new.
+ (_actionability("fresh"), None, "fresh", True),
+ # Update confirmed: the previous assessment is reused unchanged.
+ (ActionabilityUpdate(previous_assessment_correct=True), _actionability("kept"), "kept", False),
+ # Update replaced: the agent's new assessment supersedes the previous one.
+ (
+ ActionabilityUpdate(previous_assessment_correct=False, assessment=_actionability("new")),
+ _actionability("old"),
+ "new",
+ True,
+ ),
+ ],
+)
+def test_resolve_actionability_response(response, previous, expected_explanation, expected_is_new):
+ result, is_new = _resolve_actionability_response(response, previous)
+ assert is_new is expected_is_new
+ assert result.explanation == expected_explanation
+
+
+ ("response", "previous", "expected_explanation", "expected_is_new"),
+ [
+ (_priority("fresh"), None, "fresh", True),
+ (PriorityUpdate(previous_assessment_correct=True), _priority("kept"), "kept", False),
+ (
+ PriorityUpdate(previous_assessment_correct=False, assessment=_priority("new")),
+ _priority("old"),
+ "new",
+ True,
+ ),
+ ],
+)
+def test_resolve_priority_response(response, previous, expected_explanation, expected_is_new):
+ result, is_new = _resolve_priority_response(response, previous)
+ assert is_new is expected_is_new
+ assert result.explanation == expected_explanation
diff --git a/products/signals/backend/test/test_artefact_schemas.py b/products/signals/backend/test/test_artefact_schemas.py
new file mode 100644
index 000000000000..6d35763d6008
--- /dev/null
+++ b/products/signals/backend/test/test_artefact_schemas.py
@@ -0,0 +1,157 @@
+import json
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from pydantic import BaseModel, ValidationError
+
+from products.signals.backend.artefact_schemas import (
+ ARTEFACT_CONTENT_SCHEMAS,
+ ArtefactContentValidationError,
+ CodeReference,
+ Commit,
+ NoteArtefact,
+ TaskRunArtefact,
+ artefact_type_for,
+ parse_artefact_content,
+)
+from products.signals.backend.models import SignalReportArtefact
+
+
+class TestArtefactSchemas(SimpleTestCase):
+ def test_registry_covers_every_artefact_type_exactly(self):
+ assert set(ARTEFACT_CONTENT_SCHEMAS.keys()) == set(SignalReportArtefact.ArtefactType.values)
+
+ def test_code_reference_round_trips(self):
+ ref = CodeReference(file_path="a.py", start_line=1, end_line=3, contents="x", relevance_note="why")
+ assert ref.model_dump()["end_line"] == 3
+
+ def test_code_reference_rejects_end_before_start(self):
+ with self.assertRaises(ValidationError):
+ CodeReference(file_path="a.py", start_line=5, end_line=2, contents="x", relevance_note="why")
+
+ @parameterized.expand([("file_path",), ("contents",), ("relevance_note",)])
+ def test_code_reference_rejects_blank_strings(self, field):
+ kwargs = {"file_path": "a.py", "start_line": 1, "end_line": 2, "contents": "x", "relevance_note": "why"}
+ kwargs[field] = " "
+ with self.assertRaises(ValidationError):
+ CodeReference(**kwargs)
+
+ @parameterized.expand(
+ [
+ ("line_too_long", {"contents": "x" * 1001}),
+ ("too_many_lines", {"contents": "\n".join(["x"] * 21), "end_line": 21}),
+ ("span_too_wide", {"end_line": 22}),
+ ]
+ )
+ def test_code_reference_rejects_unbounded_contents(self, _name, overrides):
+ kwargs = {"file_path": "a.py", "start_line": 1, "end_line": 2, "contents": "x\ny", "relevance_note": "why"}
+ kwargs.update(overrides)
+ with self.assertRaises(ValidationError):
+ CodeReference(**kwargs)
+
+ def test_code_reference_accepts_bounded_contents(self):
+ ref = CodeReference(
+ file_path="a.py",
+ start_line=1,
+ end_line=20,
+ contents="\n".join(["x" * 1000] * 20),
+ relevance_note="why",
+ )
+ assert ref.end_line == 20
+
+ def test_commit_defaults_note_to_none(self):
+ commit = Commit(repository="PostHog/posthog", branch="fix/foo", commit_sha="abc123f", message="fix: foo")
+ assert commit.note is None
+
+ @parameterized.expand([("repository",), ("branch",), ("commit_sha",), ("message",)])
+ def test_commit_rejects_blank_strings(self, field):
+ kwargs = {"repository": "PostHog/posthog", "branch": "fix/foo", "commit_sha": "abc123f", "message": "m"}
+ kwargs[field] = " "
+ with self.assertRaises(ValidationError):
+ Commit(**kwargs)
+
+ def test_task_run_carries_product_and_type(self):
+ artefact = TaskRunArtefact(task_id="abc", product="signals", type="research")
+ assert artefact.product == "signals"
+ assert artefact.type == "research"
+
+ @parameterized.expand([("product",), ("type",)])
+ def test_task_run_rejects_non_routing_safe_identifier(self, field):
+ kwargs = {"task_id": "abc", "product": "signals", "type": "research"}
+ kwargs[field] = "Not Safe!"
+ with self.assertRaises(ValidationError):
+ TaskRunArtefact(**kwargs)
+
+ def test_note_rejects_blank(self):
+ assert NoteArtefact(note="hello").note == "hello"
+ with self.assertRaises(ValidationError):
+ NoteArtefact(note=" ")
+
+
+class TestValidateArtefactContent(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("safety_judgment", {"choice": True, "explanation": None}),
+ (
+ "actionability_judgment",
+ {"explanation": "Looked at it.", "actionability": "not_actionable", "already_addressed": False},
+ ),
+ ("priority_judgment", {"explanation": "It is bad.", "priority": "P1"}),
+ (
+ "signal_finding",
+ {"signal_id": "s1", "relevant_code_paths": ["a.py"], "data_queried": "none", "verified": True},
+ ),
+ ("repo_selection", {"repository": None, "reason": "no candidates"}),
+ ("suggested_reviewers", [{"github_login": "octocat", "github_name": None, "relevant_commits": []}]),
+ ("dismissal", {"reason": "not_a_bug", "note": None, "user_id": 1, "user_uuid": None}),
+ ("video_segment", {"anything": "goes"}),
+ ("note", {"note": "hello"}),
+ (
+ "commit",
+ {"repository": "PostHog/posthog", "branch": "b", "commit_sha": "abc123f", "message": "fix: x"},
+ ),
+ ("task_run", {"task_id": "t1", "run_id": None, "product": "signals", "type": "implementation"}),
+ ]
+ )
+ def test_accepts_valid_content_for_type(self, artefact_type, content):
+ parsed = parse_artefact_content(artefact_type, content)
+ assert artefact_type_for(parsed) == artefact_type
+ # The typed model round-trips through its stored JSON representation.
+ assert parse_artefact_content(artefact_type, parsed.model_dump_json()) == parsed
+
+ @parameterized.expand(
+ [
+ ("safety_judgment", {"choice": "definitely"}),
+ ("actionability_judgment", {"explanation": "", "actionability": "nope", "already_addressed": False}),
+ ("priority_judgment", {"explanation": "x", "priority": "P9"}),
+ ("signal_finding", {"signal_id": "s1"}),
+ ("repo_selection", {"reason": 5}),
+ ("suggested_reviewers", [{"github_name": "no login"}]),
+ ("note", {"note": " "}),
+ ("commit", {"repository": "PostHog/posthog", "branch": "b", "commit_sha": " ", "message": "m"}),
+ ("task_run", {"task_id": "t1", "product": "Not Safe!", "type": "research"}),
+ ]
+ )
+ def test_rejects_invalid_content_for_type(self, artefact_type, content):
+ with self.assertRaises(ArtefactContentValidationError):
+ parse_artefact_content(artefact_type, content)
+
+ def test_parsing_normalizes_to_the_schema(self):
+ # Parsing into the typed model is the boundary: unknown keys are not persisted, and
+ # omitted optional fields are stored with their defaults.
+ parsed = parse_artefact_content("note", json.dumps({"note": "hello", "future_field": 42}))
+ assert json.loads(parsed.model_dump_json()) == {"note": "hello", "author": None}
+
+ def test_rejects_unknown_type_and_malformed_json(self):
+ with self.assertRaises(ArtefactContentValidationError):
+ parse_artefact_content("pushed_branch", {"repository": "a/b", "branch": "c"})
+ with self.assertRaises(ArtefactContentValidationError):
+ parse_artefact_content("note", "{not json")
+
+ def test_artefact_type_for_rejects_non_content_models(self):
+ class NotAnArtefact(BaseModel):
+ x: int = 1
+
+ with self.assertRaises(ArtefactContentValidationError):
+ artefact_type_for(NotAnArtefact())
diff --git a/products/signals/backend/test/test_auto_start.py b/products/signals/backend/test/test_auto_start.py
index 3e2c346fe783..d8474ee9a4f3 100644
--- a/products/signals/backend/test/test_auto_start.py
+++ b/products/signals/backend/test/test_auto_start.py
@@ -1,8 +1,9 @@
-import uuid
from types import SimpleNamespace
import pytest
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import patch
+
+from django.apps import apps
from social_django.models import UserSocialAuth
@@ -11,16 +12,17 @@ from posthog.models.organization import OrganizationMembership
from products.signals.backend.auto_start import (
ReviewerContent,
+ _create_implementation_task_if_absent,
_resolve_autostart_assignee,
- maybe_autostart_implementation_task,
)
-from products.signals.backend.models import SignalReportTask, SignalUserAutonomyConfig
-from products.signals.backend.report_generation.research import (
- ActionabilityAssessment,
- ActionabilityChoice,
- Priority,
- PriorityAssessment,
+from products.signals.backend.models import (
+ SignalReport,
+ SignalReportArtefact,
+ SignalReportTask,
+ SignalUserAutonomyConfig,
)
+from products.signals.backend.report_generation.research import Priority
+from products.signals.backend.task_run_artefacts import TASK_RUN_TYPE_IMPLEMENTATION, signals_task_ids
from products.tasks.backend.facade import api as tasks_facade
@@ -73,36 +75,57 @@ def test_resolve_autostart_assignee(organization, team, autostart_priority, repo
assert assignee is None
@pytest.mark.django_db
-async def test_autostart_tags_implementation_ai_stage(ateam):
- """The autostart implementation run is tagged ai_stage="implementation" so its
- $ai_generation traces are attributed instead of landing in the "(none)" bucket."""
- assignee = SimpleNamespace(id=123)
- created = SimpleNamespace(task_id=uuid.uuid4(), team_id=ateam.id, latest_run=object())
- create_and_run_task = MagicMock(return_value=created)
-
- with (
- patch.object(tasks_facade, "create_and_run_task", create_and_run_task),
- patch("products.signals.backend.auto_start._resolve_autostart_assignee", return_value=assignee),
- patch.object(SignalReportTask.objects, "acreate", AsyncMock()),
- ):
- await maybe_autostart_implementation_task(
- team_id=ateam.id,
- report_id=str(uuid.uuid4()),
- repository="PostHog/posthog",
- title="Fix the thing",
- summary="A short summary",
- actionability=ActionabilityAssessment(
- explanation="Clearly actionable.",
- actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE,
- already_addressed=False,
- ),
- reviewers_content=[_reviewer("octocat")],
- priority=PriorityAssessment(explanation="High impact.", priority=Priority.P0),
- )
+def test_create_implementation_task_if_absent_is_idempotent(organization, team):
+ # The locked create guards against duplicate auto-start tasks: a second evaluation that
+ # observes the link row must no-op rather than spawn another Task / draft PR. It also asserts
+ # the facade is invoked with the SIGNAL_REPORT origin and ai_stage="implementation" so the
+ # run's $ai_generation traces are attributed rather than landing in the "(none)" bucket.
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
+ user = _create_org_member_with_github("[email protected]", organization, "OctoCat")
+ report = SignalReport.objects.create(
+ team=team, status=SignalReport.Status.READY, title="t", summary="s", signal_count=0, total_weight=0.0
+ )
- create_and_run_task.assert_called_once()
- kwargs = create_and_run_task.call_args.kwargs
- assert kwargs["origin_product"] == tasks_facade.TaskOriginProduct.SIGNAL_REPORT
- assert kwargs["ai_stage"] == "implementation"
+ created_tasks = []
+
+ def _fake_create_and_run_task(**kwargs):
+ task = Task.objects.create(
+ team=team,
+ title=kwargs["title"],
+ description=kwargs["description"],
+ created_by=user,
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ )
+ run = TaskRun.objects.create(task=task, team=team)
+ created_tasks.append(task)
+ return SimpleNamespace(task_id=task.id, team_id=team.id, latest_run=SimpleNamespace(id=run.id))
+
+ kwargs = {
+ "team_id": team.id,
+ "report_id": str(report.id),
+ "title": "t",
+ "description": "d",
+ "user_id": user.id,
+ "repository": "owner/repo",
+ "base_branch": None,
+ }
+ with patch.object(tasks_facade, "create_and_run_task", side_effect=_fake_create_and_run_task) as mock_create:
+ first = _create_implementation_task_if_absent(**kwargs)
+ second = _create_implementation_task_if_absent(**kwargs)
+
+ assert first is True
+ assert second is False
+ assert mock_create.call_count == 1
+ call_kwargs = mock_create.call_args.kwargs
+ assert call_kwargs["origin_product"] == tasks_facade.TaskOriginProduct.SIGNAL_REPORT
+ assert call_kwargs["ai_stage"] == "implementation"
+ # The gate the second evaluation observed is the legacy SignalReportTask implementation link,
+ # written in the same transaction as the task; the task_run artefact is the work-log entry
+ # alongside.
+ assert SignalReportTask.objects.filter(report=report, relationship=TASK_RUN_TYPE_IMPLEMENTATION).count() == 1
+ assert (
+ SignalReportArtefact.objects.filter(report=report, type=SignalReportArtefact.ArtefactType.TASK_RUN).count() == 1
+ )
+ assert signals_task_ids(report_id=str(report.id), type=TASK_RUN_TYPE_IMPLEMENTATION) == [str(created_tasks[0].id)]
diff --git a/products/signals/backend/test/test_backfill_task_run_artefacts.py b/products/signals/backend/test/test_backfill_task_run_artefacts.py
new file mode 100644
index 000000000000..30093dad603e
--- /dev/null
+++ b/products/signals/backend/test/test_backfill_task_run_artefacts.py
@@ -0,0 +1,138 @@
+import json
+
+from posthog.test.base import BaseTest
+
+from django.core.management import call_command
+
+from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportTask
+from products.signals.backend.task_run_artefacts import (
+ TASK_RUN_TYPE_IMPLEMENTATION,
+ TASK_RUN_TYPE_REPO_SELECTION,
+ TASK_RUN_TYPE_RESEARCH,
+ append_task_run_artefact,
+)
+
+# Task ORM model needed to build cross-product fixtures; the tasks facade exposes DTOs only.
+from products.tasks.backend.models import Task # tach-ignore
+
+
+class TestBackfillTaskRunArtefacts(BaseTest):
+ def _report(self) -> SignalReport:
+ return SignalReport.objects.create(
+ team=self.team,
+ status=SignalReport.Status.READY,
+ title="t",
+ summary="s",
+ signal_count=1,
+ total_weight=1.0,
+ )
+
+ def _task(self) -> Task:
+ return Task.objects.create(
+ team=self.team,
+ title="task",
+ description="desc",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ )
+
+ def _link(self, report: SignalReport, relationship: str) -> SignalReportTask:
+ return SignalReportTask.objects.create(
+ team=self.team,
+ report=report,
+ task=self._task(),
+ relationship=relationship,
+ )
+
+ def _task_run_artefacts(self, report: SignalReport) -> list[SignalReportArtefact]:
+ return list(SignalReportArtefact.objects.filter(report=report, type=SignalReportArtefact.ArtefactType.TASK_RUN))
+
+ def test_backfills_and_maps_relationships(self):
+ report = self._report()
+ research = self._link(report, TASK_RUN_TYPE_RESEARCH)
+ implementation = self._link(report, TASK_RUN_TYPE_IMPLEMENTATION)
+ repo_selection = self._link(report, TASK_RUN_TYPE_REPO_SELECTION)
+
+ call_command("backfill_task_run_artefacts")
+
+ artefacts = {json.loads(a.content)["task_id"]: json.loads(a.content) for a in self._task_run_artefacts(report)}
+ assert all(c["product"] == "signals" for c in artefacts.values())
+ assert artefacts[str(research.task_id)]["type"] == "research"
+ assert artefacts[str(implementation.task_id)]["type"] == "implementation"
+ assert artefacts[str(repo_selection.task_id)]["type"] == "repo_selection"
+
+ def test_backdates_created_at_to_task_run(self):
+ report = self._report()
+ link = self._link(report, TASK_RUN_TYPE_RESEARCH)
+
+ call_command("backfill_task_run_artefacts")
+
+ artefact = self._task_run_artefacts(report)[0]
+ assert artefact.created_at == link.created_at
+
+ def test_is_idempotent(self):
+ report = self._report()
+ self._link(report, TASK_RUN_TYPE_RESEARCH)
+
+ call_command("backfill_task_run_artefacts")
+ call_command("backfill_task_run_artefacts")
+
+ assert len(self._task_run_artefacts(report)) == 1
+
+ def test_dry_run_writes_nothing(self):
+ report = self._report()
+ self._link(report, TASK_RUN_TYPE_RESEARCH)
+
+ call_command("backfill_task_run_artefacts", "--dry-run")
+
+ assert self._task_run_artefacts(report) == []
+
+ def test_team_id_scopes_backfill(self):
+ report = self._report()
+ self._link(report, TASK_RUN_TYPE_RESEARCH)
+
+ other_team_command_team_id = self.team.id + 99999
+ call_command("backfill_task_run_artefacts", "--team-id", str(other_team_command_team_id))
+
+ # Nothing for our team's report, since we scoped to a different (non-existent) team.
+ assert self._task_run_artefacts(report) == []
+
+ def test_unlabelled_rows_get_default_identifiers(self):
+ # Artefacts are the sole source of association now, so unlabelled rows missing a
+ # task_run artefact get one with the generic default identifiers.
+ report = self._report()
+ task = self._task()
+ SignalReportTask.objects.create(team=self.team, report=report, task=task)
+
+ call_command("backfill_task_run_artefacts")
+
+ artefacts = self._task_run_artefacts(report)
+ assert len(artefacts) == 1
+ content = json.loads(artefacts[0].content)
+ assert content["task_id"] == str(task.id)
+ assert content["product"] == "tasks"
+ assert content["type"] == "agent_run"
+
+ def test_unlabelled_row_with_existing_artefact_is_skipped(self):
+ report = self._report()
+ task = self._task()
+ SignalReportTask.objects.create(team=self.team, report=report, task=task)
+ append_task_run_artefact(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ product="tasks",
+ type="agent_run",
+ task_id=str(task.id),
+ )
+
+ call_command("backfill_task_run_artefacts")
+
+ assert len(self._task_run_artefacts(report)) == 1
+
+ def test_backfilled_artefacts_are_attributed_to_the_task(self):
+ report = self._report()
+ link = self._link(report, TASK_RUN_TYPE_RESEARCH)
+
+ call_command("backfill_task_run_artefacts")
+
+ artefact = self._task_run_artefacts(report)[0]
+ assert str(artefact.task_id) == str(link.task_id)
diff --git a/products/signals/backend/test/test_billing.py b/products/signals/backend/test/test_billing.py
index e75ddf7878f1..b5d02653454c 100644
--- a/products/signals/backend/test/test_billing.py
+++ b/products/signals/backend/test/test_billing.py
@@ -9,6 +9,7 @@ from parameterized import parameterized
from posthog.models import Team
+from products.signals.backend.artefact_schemas import TASK_RUN_TYPE_IMPLEMENTATION, TASK_RUN_TYPE_RESEARCH
from products.signals.backend.billing import SIGNALS_CREDITS_PER_REPORT_WITH_PR, get_signals_billing_credits_by_team
from products.signals.backend.models import SignalReport, SignalReportTask
@@ -51,7 +52,7 @@ class TestSignalsBilling(BaseTest):
created_at: datetime,
pr_url: str | None = "https://github.com/x/y/pull/1",
team: Team | None = None,
- relationship: str = SignalReportTask.Relationship.IMPLEMENTATION,
+ relationship: str = TASK_RUN_TYPE_IMPLEMENTATION,
output: object = _UNSET,
) -> "TaskRunModel":
team = team or self.team
@@ -127,9 +128,7 @@ class TestSignalsBilling(BaseTest):
task = Task.objects.create(
team=self.team, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
)
- SignalReportTask.objects.create(
- team=other, report=report, task=task, relationship=SignalReportTask.Relationship.IMPLEMENTATION
- )
+ SignalReportTask.objects.create(team=other, report=report, task=task, relationship=TASK_RUN_TYPE_IMPLEMENTATION)
TaskRun.objects.create(
team=self.team, task=task, output={"pr_url": "https://github.com/x/y/pull/1"}, created_at=_at(10)
)
@@ -144,7 +143,7 @@ class TestSignalsBilling(BaseTest):
team=self.team, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
)
SignalReportTask.objects.create(
- team=self.team, report=report, task=task, relationship=SignalReportTask.Relationship.IMPLEMENTATION
+ team=self.team, report=report, task=task, relationship=TASK_RUN_TYPE_IMPLEMENTATION
)
TaskRun.objects.create(
team=other, task=task, output={"pr_url": "https://github.com/x/y/pull/1"}, created_at=_at(10)
@@ -161,7 +160,7 @@ class TestSignalsBilling(BaseTest):
team=other, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
)
SignalReportTask.objects.create(
- team=self.team, report=report, task=task, relationship=SignalReportTask.Relationship.IMPLEMENTATION
+ team=self.team, report=report, task=task, relationship=TASK_RUN_TYPE_IMPLEMENTATION
)
TaskRun.objects.create(
team=self.team, task=task, output={"pr_url": "https://github.com/x/y/pull/1"}, created_at=_at(10)
@@ -178,7 +177,7 @@ class TestSignalsBilling(BaseTest):
team=self.team, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
)
SignalReportTask.objects.create(
- team=self.team, report=report, task=task, relationship=SignalReportTask.Relationship.IMPLEMENTATION
+ team=self.team, report=report, task=task, relationship=TASK_RUN_TYPE_IMPLEMENTATION
)
TaskRun.objects.create(
team=self.team, task=task, output={"pr_url": "https://github.com/x/y/pull/1"}, created_at=_at(10)
@@ -236,7 +235,7 @@ class TestSignalsBilling(BaseTest):
def test_pr_on_non_implementation_task_not_billed(self) -> None:
report = self._report()
- self._pr_run(report, created_at=_at(19), relationship=SignalReportTask.Relationship.RESEARCH)
+ self._pr_run(report, created_at=_at(19), relationship=TASK_RUN_TYPE_RESEARCH)
self.assertEqual(self._credits(), {})
@parameterized.expand(
diff --git a/products/signals/backend/test/test_custom_agent_log_artefacts.py b/products/signals/backend/test/test_custom_agent_log_artefacts.py
new file mode 100644
index 000000000000..a23abf8964f2
--- /dev/null
+++ b/products/signals/backend/test/test_custom_agent_log_artefacts.py
@@ -0,0 +1,181 @@
+import json
+import uuid
+
+from posthog.test.base import BaseTest
+from unittest.mock import AsyncMock, patch
+
+from asgiref.sync import async_to_sync
+from pydantic import BaseModel
+
+from products.signals.backend.artefact_schemas import ArtefactContentValidationError, CodeReference, NoteArtefact
+from products.signals.backend.custom_agent.base import NO_REPO, CustomSignalAgent
+from products.signals.backend.custom_agent.persistence import (
+ PersistedCustomAgentReport,
+ create_custom_agent_ready_report,
+)
+from products.signals.backend.custom_agent.schemas import CustomAgentFinalReport
+from products.signals.backend.models import SignalReportArtefact
+from products.signals.backend.report_generation.research import (
+ ActionabilityAssessment,
+ ActionabilityChoice,
+ Priority,
+ PriorityAssessment,
+)
+from products.signals.backend.report_generation.select_repo import RepoSelectionResult
+
+# Task ORM model needed to build cross-product fixtures; the tasks facade exposes DTOs only.
+from products.tasks.backend.models import Task # tach-ignore
+
+
+class _StubAgent(CustomSignalAgent):
+ @classmethod
+ def identifier(cls) -> tuple[str, str]:
+ return ("billing", "anomaly_scan")
+
+ async def run(self) -> bool:
+ return False
+
+
+class TestCustomAgentLogArtefacts(BaseTest):
+ def _agent(self) -> CustomSignalAgent:
+ return _StubAgent(team=self.team, initial_prompt="investigate", repository=NO_REPO)
+
+ def _task(self) -> Task:
+ return Task.objects.create(
+ team=self.team,
+ title="task",
+ description="desc",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ )
+
+ def _final_report(self) -> CustomAgentFinalReport:
+ return CustomAgentFinalReport(
+ title="title",
+ description="description",
+ actionability=ActionabilityAssessment(
+ explanation="e",
+ actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE,
+ already_addressed=False,
+ ),
+ assignees=[],
+ priority=PriorityAssessment(explanation="e", priority=Priority.P1),
+ )
+
+ def test_register_artefact_queues_any_content_model(self):
+ agent = self._agent()
+
+ agent.register_artefact(NoteArtefact(note="hello", author="agent"))
+ agent.register_artefact(
+ CodeReference(file_path="src/a.py", start_line=1, end_line=2, contents="x=1\ny=2", relevance_note="r")
+ )
+ # Status types are registerable too — they route through latest-wins on persistence.
+ agent.register_artefact(PriorityAssessment(explanation="e", priority=Priority.P1))
+
+ assert [type(a).__name__ for a in agent._registered_artefacts] == [
+ "NoteArtefact",
+ "CodeReference",
+ "PriorityAssessment",
+ ]
+
+ def test_register_artefact_rejects_non_content_models(self):
+ agent = self._agent()
+
+ class NotAContentModel(BaseModel):
+ value: str
+
+ with self.assertRaises(ArtefactContentValidationError):
+ agent.register_artefact(NotAContentModel(value="not a content schema")) # type: ignore[arg-type]
+
+ assert agent._registered_artefacts == []
+
+ def test_report_and_continue_persists_queue_and_clears_it(self):
+ agent = self._agent()
+ agent._resolved_repository = RepoSelectionResult(repository=None, reason="caller")
+ agent.register_title("t")
+ agent.register_description("d")
+ agent.register_actionability(
+ ActionabilityAssessment(
+ explanation="e",
+ actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE,
+ already_addressed=False,
+ )
+ )
+ agent.register_priority(PriorityAssessment(explanation="e", priority=Priority.P1))
+ agent.register_assignees([])
+ agent.register_artefact(NoteArtefact(note="first"))
+
+ with (
+ patch(
+ "products.signals.backend.custom_agent.base.create_custom_agent_ready_report",
+ return_value=PersistedCustomAgentReport(report_id=str(uuid.uuid4()), task_id=None),
+ ) as create_mock,
+ patch(
+ "products.signals.backend.custom_agent.base.maybe_autostart_from_report_artefacts",
+ new=AsyncMock(),
+ ),
+ ):
+ async_to_sync(agent.report_and_continue)()
+
+ assert create_mock.call_args.kwargs["registered_artefacts"] == [NoteArtefact(note="first")]
+ assert agent._registered_artefacts == []
+
+ def test_create_report_writes_registered_artefacts_attributed_to_the_task(self):
+ task = self._task()
+ code_reference = CodeReference(
+ file_path="src/a.py", start_line=1, end_line=1, contents="x = 1", relevance_note="r"
+ )
+
+ persisted = create_custom_agent_ready_report(
+ team_id=self.team.id,
+ final_report=self._final_report(),
+ repo_selection=RepoSelectionResult(repository="acme/repo", reason="r"),
+ task_id=str(task.id),
+ agent_identifier=("billing", "anomaly_scan"),
+ registered_artefacts=[NoteArtefact(note="hello"), code_reference],
+ )
+
+ rows = SignalReportArtefact.objects.filter(
+ report_id=persisted.report_id,
+ type__in=[SignalReportArtefact.ArtefactType.NOTE, SignalReportArtefact.ArtefactType.CODE_REFERENCE],
+ )
+ assert rows.count() == 2
+ for row in rows:
+ assert str(row.task_id) == str(task.id)
+ assert row.created_by_id is None
+
+ def test_create_report_without_task_writes_system_attributed_artefacts(self):
+ persisted = create_custom_agent_ready_report(
+ team_id=self.team.id,
+ final_report=self._final_report(),
+ repo_selection=RepoSelectionResult(repository="acme/repo", reason="r"),
+ task_id=None,
+ agent_identifier=("billing", "anomaly_scan"),
+ registered_artefacts=[NoteArtefact(note="hello")],
+ )
+
+ row = SignalReportArtefact.objects.get(
+ report_id=persisted.report_id, type=SignalReportArtefact.ArtefactType.NOTE
+ )
+ assert json.loads(row.content) == {"note": "hello", "author": None}
+ assert row.task_id is None
+ assert row.created_by_id is None
+
+ def test_create_report_routes_registered_status_artefacts_latest_wins(self):
+ # A registered status artefact appends a new version on top of the one the final report
+ # itself writes — the registered (later) row is the report's current status.
+ persisted = create_custom_agent_ready_report(
+ team_id=self.team.id,
+ final_report=self._final_report(),
+ repo_selection=RepoSelectionResult(repository="acme/repo", reason="r"),
+ task_id=None,
+ agent_identifier=("billing", "anomaly_scan"),
+ registered_artefacts=[PriorityAssessment(explanation="raised", priority=Priority.P0)],
+ )
+
+ rows = list(
+ SignalReportArtefact.objects.filter(
+ report_id=persisted.report_id, type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT
+ ).order_by("created_at")
+ )
+ assert len(rows) == 2
+ assert json.loads(rows[-1].content)["priority"] == "P0"
diff --git a/products/signals/backend/test/test_inbox_notification_workflow.py b/products/signals/backend/test/test_inbox_notification_workflow.py
index 1669f44d956c..4a5a0ae82d7f 100644
--- a/products/signals/backend/test/test_inbox_notification_workflow.py
+++ b/products/signals/backend/test/test_inbox_notification_workflow.py
@@ -13,6 +13,7 @@ from temporalio.worker import UnsandboxedWorkflowRunner, Worker
from posthog.models import Organization, Team
from products.signals.backend.models import SignalReport, SignalReportTask
+from products.signals.backend.task_run_artefacts import TASK_RUN_TYPE_IMPLEMENTATION
from products.signals.backend.temporal.inbox_notification import (
InboxNotificationInput,
InboxNotificationState,
@@ -36,9 +37,7 @@ def _link_implementation_task(team: Team, report: SignalReport, *, pr_url: str |
task = Task.objects.create(
team=team, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
)
- SignalReportTask.objects.create(
- team=team, report=report, task=task, relationship=SignalReportTask.Relationship.IMPLEMENTATION
- )
+ SignalReportTask.objects.create(team=team, report=report, task=task, relationship=TASK_RUN_TYPE_IMPLEMENTATION)
TaskRun.objects.create(team=team, task=task, status=run_status, output={"pr_url": pr_url})
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index b81ac759db35..92496c389306 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -20,6 +20,7 @@ from posthog.models.team.team import Team
from products.signals.backend.implementation_pr import fetch_implementation_pr_urls_for_reports
from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportTask
+from products.signals.backend.task_run_artefacts import append_task_run_artefact, record_implementation_task
if TYPE_CHECKING:
from products.tasks.backend.models import Task, TaskRun
@@ -506,6 +507,37 @@ class TestSignalReportListAPI(APIBaseTest):
row = next(r for r in response.json()["results"] if r["id"] == str(report.id))
assert row["is_suggested_reviewer"] is True
+ def test_is_suggested_reviewer_uses_latest_reviewers_row(self):
+ # suggested_reviewers is append-only: an older row listing the user must not keep them
+ # flagged after a newer row drops them (latest-wins).
+ UserSocialAuth.objects.create(
+ user=self.user,
+ provider="github",
+ uid="github-test-latest-wins",
+ extra_data={"login": "suggestedgh"},
+ )
+ report = self._create_report()
+ self._actionability_artefact(report, actionability="immediately_actionable")
+ old = SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=json.dumps([{"github_login": "suggestedgh"}]),
+ )
+ SignalReportArtefact.objects.filter(pk=old.pk).update(created_at=timezone.now() - timedelta(hours=1))
+ # Newer row no longer includes the user — the live reviewer set.
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=json.dumps([{"github_login": "someoneelse"}]),
+ )
+
+ response = self.client.get(self._list_url(status="ready"))
+ 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["is_suggested_reviewer"] is False
+
# --- implementation_pr_url ---
def _create_implementation_task_with_run(
@@ -519,11 +551,10 @@ class TestSignalReportListAPI(APIBaseTest):
description="Fix the bug",
origin_product=Task.OriginProduct.SIGNAL_REPORT,
)
- SignalReportTask.objects.create(
- team=self.team,
- report=report,
- task=task,
- relationship=SignalReportTask.Relationship.IMPLEMENTATION,
+ record_implementation_task(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ task_id=str(task.id),
)
run_output = output if output is not None else ({"pr_url": pr_url} if pr_url else None)
run = TaskRun.objects.create(
@@ -552,6 +583,35 @@ class TestSignalReportListAPI(APIBaseTest):
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('"')
+ 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.
+ 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),
+ )
+ 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"},
+ )
+
+ 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"
+
def test_implementation_pr_url_null_when_no_implementation_task(self):
report = self._create_report()
@@ -588,11 +648,10 @@ class TestSignalReportListAPI(APIBaseTest):
description="Fix the bug",
origin_product=Task.OriginProduct.SIGNAL_REPORT,
)
- SignalReportTask.objects.create(
- team=self.team,
- report=report,
- task=task,
- relationship=SignalReportTask.Relationship.IMPLEMENTATION,
+ 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,
@@ -1439,3 +1498,143 @@ class TestSignalReportBulkStateAPI(APIBaseTest):
def test_bulk_rejects_invalid_requests(self, _name, body):
response = self._post(body)
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+
+
+class TestSignalReportTaskAssociationViaArtefacts(APIBaseTest):
+ """task_run artefacts ARE the task↔report association: associate-me defaults + the reports task_id filter."""
+
+ def _artefacts_url(self, report_id: str) -> str:
+ return f"/api/projects/{self.team.id}/signals/reports/{report_id}/artefacts/"
+
+ def _create_report(self, team=None) -> SignalReport:
+ return SignalReport.objects.create(
+ team=team or self.team,
+ status=SignalReport.Status.READY,
+ title="Report",
+ summary="Summary",
+ signal_count=1,
+ total_weight=1.0,
+ )
+
+ def _create_task(self, team=None) -> "Task":
+ Task = apps.get_model("tasks", "Task")
+ return Task.objects.create(
+ team=team or self.team,
+ title="task",
+ description="desc",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ )
+
+ def _associate(self, report: SignalReport, content: dict, **extra):
+ return self.client.post(
+ self._artefacts_url(str(report.id)),
+ data=json.dumps({"artefact_type": "task_run", "content": content}),
+ content_type="application/json",
+ **extra,
+ )
+
+ def test_associate_task_by_body(self):
+ report = self._create_report()
+ task = self._create_task()
+
+ response = self._associate(report, {"task_id": str(task.id)})
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ body = response.json()
+ assert body["content"]["task_id"] == str(task.id)
+ # product/type default to the generic agent-run identifiers.
+ assert body["content"]["product"] == "tasks"
+ assert body["content"]["type"] == "agent_run"
+ artefact = SignalReportArtefact.objects.get(id=body["id"])
+ # The entry is attributed to the task it records.
+ assert str(artefact.task_id) == str(task.id)
+
+ def test_associate_is_idempotent(self):
+ report = self._create_report()
+ task = self._create_task()
+
+ first = self._associate(report, {"task_id": str(task.id)})
+ second = self._associate(report, {"task_id": str(task.id)})
+ assert first.status_code == status.HTTP_201_CREATED
+ assert second.status_code == status.HTTP_200_OK
+ assert second.json()["id"] == first.json()["id"]
+ assert (
+ SignalReportArtefact.objects.filter(report=report, type=SignalReportArtefact.ArtefactType.TASK_RUN).count()
+ == 1
+ )
+
+ def test_associate_with_custom_product_and_type(self):
+ report = self._create_report()
+ task = self._create_task()
+
+ response = self._associate(report, {"task_id": str(task.id), "product": "billing", "type": "anomaly_scan"})
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ artefact = SignalReportArtefact.objects.get(report=report, type=SignalReportArtefact.ArtefactType.TASK_RUN)
+ content = json.loads(artefact.content)
+ assert content["product"] == "billing"
+ assert content["type"] == "anomaly_scan"
+
+ def test_associate_with_invalid_product_returns_400(self):
+ report = self._create_report()
+ task = self._create_task()
+
+ response = self._associate(report, {"task_id": str(task.id), "product": "Not Valid!"})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert not SignalReportArtefact.objects.filter(
+ report=report, type=SignalReportArtefact.ArtefactType.TASK_RUN
+ ).exists()
+
+ def test_associate_defaults_to_header_task(self):
+ # "Associate me with this report" — empty content, the agent's own task comes from the header.
+ report = self._create_report()
+ task = self._create_task()
+
+ response = self._associate(report, {}, headers={"X-PostHog-Task-Id": str(task.id)})
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ artefact = SignalReportArtefact.objects.get(report=report, type=SignalReportArtefact.ArtefactType.TASK_RUN)
+ assert json.loads(artefact.content)["task_id"] == str(task.id)
+ assert str(artefact.task_id) == str(task.id)
+
+ def test_associate_without_task_returns_400(self):
+ report = self._create_report()
+ response = self._associate(report, {})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_associate_foreign_team_task_returns_400(self):
+ report = self._create_report()
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ foreign_task = self._create_task(team=other_team)
+
+ response = self._associate(report, {"task_id": str(foreign_task.id)})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert not SignalReportArtefact.objects.filter(report=report).exists()
+
+ def test_associate_on_deleted_report_returns_404(self):
+ report = self._create_report()
+ report.status = SignalReport.Status.DELETED
+ report.save(update_fields=["status"])
+ task = self._create_task()
+
+ response = self._associate(report, {"task_id": str(task.id)})
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_reports_list_filters_by_task_id(self):
+ report = self._create_report()
+ other_report = self._create_report()
+ task = self._create_task()
+ append_task_run_artefact(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ product="tasks",
+ type="agent_run",
+ task_id=str(task.id),
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/?task_id={task.id}")
+ assert response.status_code == status.HTTP_200_OK
+ ids = {r["id"] for r in response.json()["results"]}
+ assert ids == {str(report.id)}
+ assert str(other_report.id) not in ids
+
+ def test_reports_list_rejects_malformed_task_id(self):
+ response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/?task_id=not-a-uuid")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
diff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.py
index 43fd7a19b2dd..475243a0c866 100644
--- a/products/signals/backend/test/test_signal_report_artefact_api.py
+++ b/products/signals/backend/test/test_signal_report_artefact_api.py
@@ -2,6 +2,7 @@ import json
import uuid
from posthog.test.base import APIBaseTest
+from unittest.mock import AsyncMock, patch
from parameterized import parameterized
from rest_framework import status
@@ -11,7 +12,17 @@ from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
-from products.signals.backend.models import SignalReport, SignalReportArtefact
+from products.signals.backend.artefact_schemas import (
+ CodeReference,
+ NoteArtefact,
+ Priority,
+ PriorityAssessment,
+ TaskRunArtefact,
+)
+from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact
+
+# Task ORM model needed to build cross-product fixtures; the tasks facade exposes DTOs only.
+from products.tasks.backend.models import Task # tach-ignore
def _attach_github_login(user: User, login: str, *, uid: str | None = None) -> None:
@@ -63,6 +74,22 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
_attach_github_login(user, github_login, uid=f"gh-{email}")
return user
+ def _latest_reviewers(self, report: SignalReport) -> list:
+ # suggested_reviewers is append-only: the current reviewers are the latest row's content.
+ artefact = (
+ SignalReportArtefact.objects.filter(
+ report=report, type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS
+ )
+ .order_by("-created_at")
+ .first()
+ )
+ return json.loads(artefact.content) if artefact else []
+
+ def _reviewers_count(self, report: SignalReport) -> int:
+ return SignalReportArtefact.objects.filter(
+ report=report, type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS
+ ).count()
+
# --- GET list ---
def test_list_returns_results_envelope(self):
@@ -144,7 +171,7 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
# --- PUT (update) ---
- def test_put_replaces_full_list(self):
+ def test_put_sets_full_list(self):
report = self._create_report()
artefact = self._create_artefact(
report,
@@ -158,11 +185,94 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
)
assert response.status_code == status.HTTP_200_OK, response.json()
- artefact.refresh_from_db()
- stored = json.loads(artefact.content)
+ stored = self._latest_reviewers(report)
assert [r["github_login"] for r in stored] == ["bob", "carol"]
assert all(r["relevant_commits"] == [] for r in stored)
+ def test_put_appends_new_status_row_keeping_history(self):
+ report = self._create_report()
+ original = self._create_artefact(
+ report,
+ content=[{"github_login": "alice", "github_name": "Alice", "relevant_commits": []}],
+ )
+
+ response = self.client.put(
+ self._detail_url(str(report.id), str(original.id)),
+ data=json.dumps({"content": [{"github_login": "bob"}]}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ # A new status row is appended; the original is preserved untouched (the log keeps history).
+ assert self._reviewers_count(report) == 2
+ original.refresh_from_db()
+ assert [r["github_login"] for r in json.loads(original.content)] == ["alice"]
+
+ new_id = response.json()["id"]
+ assert new_id != str(original.id)
+ new_row = SignalReportArtefact.objects.get(id=new_id)
+ assert [r["github_login"] for r in json.loads(new_row.content)] == ["bob"]
+ assert [r["github_login"] for r in self._latest_reviewers(report)] == ["bob"]
+
+ def test_put_reviewers_re_evaluates_autostart(self):
+ # Appending a reviewers status re-runs the (idempotent) auto-start evaluation on commit.
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[{"github_login": "alice"}])
+
+ with patch(
+ "products.signals.backend.auto_start.maybe_autostart_from_report_artefacts",
+ new_callable=AsyncMock,
+ ) as mock_autostart:
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": [{"github_login": "alice"}, {"github_login": "bob"}]}),
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ mock_autostart.assert_awaited_once()
+ assert mock_autostart.call_args.kwargs["report_id"] == str(report.id)
+ assert mock_autostart.call_args.kwargs["team_id"] == self.team.id
+
+ def test_put_reviewers_autostart_delegates_when_report_complete(self):
+ # With actionability + repo + priority + reviewers all present, the reconstruction reaches
+ # the actual autostart decision (delegated to maybe_autostart_implementation_task).
+ report = self._create_report()
+ self._create_artefact(
+ report,
+ artefact_type=SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT,
+ content={"explanation": "e", "actionability": "immediately_actionable", "already_addressed": False},
+ )
+ self._create_artefact(
+ report,
+ artefact_type=SignalReportArtefact.ArtefactType.REPO_SELECTION,
+ content={"repository": "acme/repo", "reason": "r"},
+ )
+ self._create_artefact(
+ report,
+ artefact_type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,
+ content={"explanation": "e", "priority": "P1"},
+ )
+ artefact = self._create_artefact(report, content=[{"github_login": "alice"}])
+
+ with patch(
+ "products.signals.backend.auto_start.maybe_autostart_implementation_task",
+ new_callable=AsyncMock,
+ ) as mock_impl:
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": [{"github_login": "alice"}, {"github_login": "bob"}]}),
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ mock_impl.assert_awaited_once()
+ kwargs = mock_impl.call_args.kwargs
+ assert kwargs["repository"] == "acme/repo"
+ assert {r["github_login"] for r in kwargs["reviewers_content"]} == {"alice", "bob"}
+
def test_put_empty_list_clears_content(self):
report = self._create_report()
artefact = self._create_artefact(report, content=[{"github_login": "alice"}])
@@ -173,8 +283,7 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
content_type="application/json",
)
assert response.status_code == status.HTTP_200_OK
- artefact.refresh_from_db()
- assert json.loads(artefact.content) == []
+ assert self._latest_reviewers(report) == []
def test_put_preserves_relevant_commits_for_kept_entries(self):
report = self._create_report()
@@ -202,8 +311,7 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
)
assert response.status_code == status.HTTP_200_OK
- artefact.refresh_from_db()
- stored = {r["github_login"]: r for r in json.loads(artefact.content)}
+ stored = {r["github_login"]: r for r in self._latest_reviewers(report)}
assert stored["alice"]["relevant_commits"] == [{"sha": "abc123", "url": "u", "reason": "r"}]
assert stored["alice"]["github_name"] == "Alice A." # carried over from prior
assert stored["dave"]["relevant_commits"] == []
@@ -220,8 +328,7 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
content_type="application/json",
)
assert response.status_code == status.HTTP_200_OK
- artefact.refresh_from_db()
- stored = json.loads(artefact.content)
+ stored = self._latest_reviewers(report)
assert len(stored) == 1
assert stored[0]["github_login"] == "alicecase"
@@ -237,8 +344,7 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
content_type="application/json",
)
assert response.status_code == status.HTTP_200_OK
- artefact.refresh_from_db()
- stored = json.loads(artefact.content)
+ stored = self._latest_reviewers(report)
assert stored[0]["github_login"] == "alicecase"
def test_put_user_uuid_without_github_login_returns_400(self):
@@ -307,11 +413,12 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
content_type="application/json",
)
assert response.status_code == status.HTTP_200_OK
- artefact.refresh_from_db()
- stored = json.loads(artefact.content)
+ stored = self._latest_reviewers(report)
assert [r["github_login"] for r in stored] == ["alice", "bob"]
- def test_put_is_idempotent(self):
+ def test_put_repeated_yields_same_current_reviewers(self):
+ # Each PUT appends a new status row (the log grows), but identical bodies leave the
+ # *current* reviewers (latest row) unchanged.
report = self._create_report()
artefact = self._create_artefact(report, content=[])
body = json.dumps({"content": [{"github_login": "alice"}, {"github_login": "bob"}]})
@@ -322,8 +429,7 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
content_type="application/json",
)
assert first.status_code == status.HTTP_200_OK
- artefact.refresh_from_db()
- first_content = artefact.content
+ first_current = self._latest_reviewers(report)
second = self.client.put(
self._detail_url(str(report.id), str(artefact.id)),
@@ -331,8 +437,9 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
content_type="application/json",
)
assert second.status_code == status.HTTP_200_OK
- artefact.refresh_from_db()
- assert artefact.content == first_content
+ assert self._latest_reviewers(report) == first_current
+ # Original + two appended rows.
+ assert self._reviewers_count(report) == 3
def test_put_response_is_enriched_with_user(self):
member = self._create_org_member("[email protected]", github_login="alice")
@@ -357,6 +464,10 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
("signal_finding", SignalReportArtefact.ArtefactType.SIGNAL_FINDING),
("repo_selection", SignalReportArtefact.ArtefactType.REPO_SELECTION),
("dismissal", SignalReportArtefact.ArtefactType.DISMISSAL),
+ ("code_reference", SignalReportArtefact.ArtefactType.CODE_REFERENCE),
+ ("commit", SignalReportArtefact.ArtefactType.COMMIT),
+ ("task_run", SignalReportArtefact.ArtefactType.TASK_RUN),
+ ("note", SignalReportArtefact.ArtefactType.NOTE),
]
)
def test_put_rejects_non_suggested_reviewers_types(self, _name, artefact_type):
@@ -395,32 +506,6 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
- def test_patch_not_allowed(self):
- report = self._create_report()
- artefact = self._create_artefact(report, content=[])
-
- response = self.client.patch(
- self._detail_url(str(report.id), str(artefact.id)),
- data=json.dumps({"content": []}),
- content_type="application/json",
- )
- assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
-
- def test_post_not_allowed(self):
- report = self._create_report()
- response = self.client.post(
- self._list_url(str(report.id)),
- data=json.dumps({"content": []}),
- content_type="application/json",
- )
- assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
-
- def test_delete_not_allowed(self):
- report = self._create_report()
- artefact = self._create_artefact(report, content=[])
- response = self.client.delete(self._detail_url(str(report.id), str(artefact.id)))
- assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
-
def test_list_excludes_artefacts_when_parent_report_deleted(self):
report = self._create_report()
self._create_artefact(report, content=[{"github_login": "alice"}])
@@ -458,8 +543,7 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
content_type="application/json",
)
assert response.status_code == status.HTTP_200_OK
- artefact.refresh_from_db()
- stored = json.loads(artefact.content)
+ stored = self._latest_reviewers(report)
assert stored[0]["github_name"] == ""
def test_put_omitted_github_name_carries_over_prior_value(self):
@@ -476,8 +560,7 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
content_type="application/json",
)
assert response.status_code == status.HTTP_200_OK
- artefact.refresh_from_db()
- stored = json.loads(artefact.content)
+ stored = self._latest_reviewers(report)
assert stored[0]["github_name"] == "Alice A."
def test_put_after_update_preserves_filter_jsonb_containment(self):
@@ -502,3 +585,627 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
assert list_response.status_code == status.HTTP_200_OK
ids = {r["id"] for r in list_response.json()["results"]}
assert str(report.id) in ids
+
+ def test_diff_with_non_dict_content_returns_400_not_500(self):
+ # Log content is stored as arbitrary JSON; a non-object commit payload must not 500.
+ report = self._create_report()
+ artefact = self._create_artefact(
+ report,
+ artefact_type=SignalReportArtefact.ArtefactType.COMMIT,
+ content=[1, 2, 3],
+ )
+
+ response = self.client.get(self._detail_url(str(report.id), str(artefact.id)) + "diff/")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+
+_CODE_REFERENCE_CONTENT = {
+ "file_path": "products/signals/backend/models.py",
+ "start_line": 10,
+ "end_line": 12,
+ "contents": "class Foo:\n pass\n",
+ "relevance_note": "where it lives",
+}
+
+
+class TestSignalReportArtefactLogWriteViewSet(APIBaseTest):
+ """The generic log-artefact write surface (POST / PATCH / DELETE).
+
+ Distinct from the bespoke `suggested_reviewers` PUT path covered above.
+ """
+
+ def _list_url(self, report_id: str) -> str:
+ return f"/api/projects/{self.team.id}/signals/reports/{report_id}/artefacts/"
+
+ def _detail_url(self, report_id: str, artefact_id: str) -> str:
+ return f"/api/projects/{self.team.id}/signals/reports/{report_id}/artefacts/{artefact_id}/"
+
+ def _create_report(self, team: Team | None = None) -> SignalReport:
+ return SignalReport.objects.create(
+ team=team or self.team,
+ status=SignalReport.Status.READY,
+ title="Test report",
+ summary="Test summary",
+ signal_count=1,
+ total_weight=1.0,
+ )
+
+ # --- POST (create log artefact) ---
+
+ def test_post_creates_log_artefact_and_returns_id(self):
+ report = self._create_report()
+
+ response = self.client.post(
+ self._list_url(str(report.id)),
+ data=json.dumps({"artefact_type": "code_reference", "content": _CODE_REFERENCE_CONTENT}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ body = response.json()
+ assert body["type"] == "code_reference"
+ assert body["content"] == _CODE_REFERENCE_CONTENT
+ assert body["created_at"] is not None
+
+ artefact = SignalReportArtefact.objects.get(id=body["id"])
+ assert artefact.report_id == report.id
+ assert artefact.team_id == self.team.id
+ assert json.loads(artefact.content) == _CODE_REFERENCE_CONTENT
+
+ @parameterized.expand(
+ [
+ ("code_reference", _CODE_REFERENCE_CONTENT),
+ (
+ "commit",
+ {"repository": "PostHog/posthog", "branch": "fix/foo", "commit_sha": "abc123f", "message": "fix"},
+ ),
+ ("note", {"note": "a free-form note"}),
+ ]
+ )
+ def test_post_accepts_each_log_type(self, artefact_type, content):
+ report = self._create_report()
+ response = self.client.post(
+ self._list_url(str(report.id)),
+ data=json.dumps({"artefact_type": artefact_type, "content": content}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ assert response.json()["type"] == artefact_type
+
+ def test_post_log_artefacts_accumulate(self):
+ report = self._create_report()
+ for _ in range(3):
+ response = self.client.post(
+ self._list_url(str(report.id)),
+ data=json.dumps({"artefact_type": "note", "content": {"note": "tick"}}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED
+
+ assert (
+ SignalReportArtefact.objects.filter(report=report, type=SignalReportArtefact.ArtefactType.NOTE).count() == 3
+ )
+
+ @parameterized.expand(
+ [
+ ("safety_judgment", {"choice": True}),
+ (
+ "actionability_judgment",
+ {"explanation": "clear fix", "actionability": "immediately_actionable", "already_addressed": False},
+ ),
+ ("priority_judgment", {"explanation": "core flow broken", "priority": "P1"}),
+ ("repo_selection", {"repository": "posthog/posthog", "reason": "where the code lives"}),
+ (
+ "signal_finding",
+ {
+ "signal_id": "sig-1",
+ "relevant_code_paths": [],
+ "relevant_commit_hashes": {},
+ "data_queried": "events",
+ "verified": True,
+ },
+ ),
+ ]
+ )
+ def test_post_accepts_status_and_finding_types(self, artefact_type, content):
+ report = self._create_report()
+ response = self.client.post(
+ self._list_url(str(report.id)),
+ data=json.dumps({"artefact_type": artefact_type, "content": content}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ assert response.json()["type"] == artefact_type
+
+ def test_post_status_type_is_latest_wins(self):
+ report = self._create_report()
+ SignalReportArtefact.append_status(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=PriorityAssessment(explanation="initial", priority=Priority.P3),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ response = self.client.post(
+ self._list_url(str(report.id)),
+ data=json.dumps(
+ {
+ "artefact_type": "priority_judgment",
+ "content": {"explanation": "worse than thought", "priority": "P1"},
+ }
+ ),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+
+ # Both rows survive (append-only); the newest is canonical on the report read.
+ rows = SignalReportArtefact.objects.filter(
+ report=report, type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT
+ )
+ assert rows.count() == 2
+ report_response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/")
+ assert report_response.status_code == status.HTTP_200_OK
+ assert report_response.json()["priority"] == "P1"
+
+ def test_post_status_type_with_invalid_content_returns_400(self):
+ report = self._create_report()
+ response = self.client.post(
+ self._list_url(str(report.id)),
+ data=json.dumps({"artefact_type": "priority_judgment", "content": {"priority": "P9"}}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_post_rejects_unknown_type(self):
+ report = self._create_report()
+ response = self.client.post(
+ self._list_url(str(report.id)),
+ data=json.dumps({"artefact_type": "not_a_real_type", "content": {}}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ @parameterized.expand([("empty", {}), ("populated", {"start": 1, "end": 2})])
+ def test_post_rejects_read_only_video_segment_type(self, _name, content):
+ # video_segment is a legacy permissive type with no real content validation (even {} passes),
+ # so the write API must refuse it outright rather than persist an unvalidated payload.
+ report = self._create_report()
+ response = self.client.post(
+ self._list_url(str(report.id)),
+ data=json.dumps({"artefact_type": "video_segment", "content": content}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert not SignalReportArtefact.objects.filter(report=report).exists()
+
+ def test_post_rejects_scalar_content(self):
+ report = self._create_report()
+ response = self.client.post(
+ self._list_url(str(report.id)),
+ data=json.dumps({"artefact_type": "note", "content": "not-an-object"}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_post_on_deleted_report_returns_404(self):
+ report = self._create_report()
+ report.status = SignalReport.Status.DELETED
+ report.save(update_fields=["status"])
+
+ response = self.client.post(
+ self._list_url(str(report.id)),
+ data=json.dumps({"artefact_type": "note", "content": {"note": "x"}}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_post_on_other_team_report_returns_404(self):
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ other_report = self._create_report(team=other_team)
+
+ response = self.client.post(
+ self._list_url(str(other_report.id)),
+ data=json.dumps({"artefact_type": "note", "content": {"note": "x"}}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ assert not SignalReportArtefact.objects.filter(report=other_report).exists()
+
+ # --- PATCH (update log artefact content) ---
+
+ def test_patch_updates_log_artefact_content(self):
+ report = self._create_report()
+ artefact = SignalReportArtefact.add_log(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=NoteArtefact(note="before"),
+ attribution=ArtefactAttribution.from_user(self.user.id),
+ )
+
+ response = self.client.patch(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": {"note": "after"}}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["content"] == {"note": "after", "author": None}
+
+ artefact.refresh_from_db()
+ assert json.loads(artefact.content) == {"note": "after", "author": None}
+ assert artefact.updated_at is not None
+
+ def test_patch_rejects_read_only_video_segment_type(self):
+ # A legacy video_segment row stays readable, but the read-only type can't be edited via the API.
+ report = self._create_report()
+ legacy = SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.VIDEO_SEGMENT,
+ content=json.dumps({"start": 1, "end": 2}),
+ )
+
+ response = self.client.patch(
+ self._detail_url(str(report.id), str(legacy.id)),
+ data=json.dumps({"content": {"start": 9, "end": 9}}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+
+ legacy.refresh_from_db()
+ assert json.loads(legacy.content) == {"start": 1, "end": 2}
+
+ def test_patch_updates_status_artefact_validated_against_its_type(self):
+ report = self._create_report()
+ artefact = SignalReportArtefact.append_status(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=PriorityAssessment(explanation="initial", priority=Priority.P3),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ # Content not matching the row's type schema is rejected…
+ response = self.client.patch(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": {"note": "x"}}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ # …while a valid edit lands and changes the canonical status (it's the latest row).
+ response = self.client.patch(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": {"explanation": "re-judged", "priority": "P0"}}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ report_response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/")
+ assert report_response.json()["priority"] == "P0"
+
+ def test_patch_task_run_cannot_drift_task_id_from_the_fk(self):
+ report = self._create_report()
+ task = Task.objects.create(
+ team=self.team, title="t", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
+ )
+ other_task = Task.objects.create(
+ team=self.team, title="o", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
+ )
+ artefact = SignalReportArtefact.append(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=TaskRunArtefact(task_id=str(task.id), product="signals", type="research"),
+ attribution=ArtefactAttribution.from_task(str(task.id)),
+ )
+
+ # Editing content.task_id to a different task is rejected — the `task` FK is the association.
+ drift = self.client.patch(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": {"task_id": str(other_task.id), "product": "signals", "type": "research"}}),
+ content_type="application/json",
+ )
+ assert drift.status_code == status.HTTP_400_BAD_REQUEST
+
+ # Editing other fields while keeping the same task_id is fine.
+ ok = self.client.patch(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": {"task_id": str(task.id), "product": "signals", "type": "implementation"}}),
+ content_type="application/json",
+ )
+ assert ok.status_code == status.HTTP_200_OK, ok.json()
+ artefact.refresh_from_db()
+ assert json.loads(artefact.content)["type"] == "implementation"
+ assert str(artefact.task_id) == str(task.id)
+
+ def test_patch_other_team_returns_404(self):
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ other_report = self._create_report(team=other_team)
+ artefact = SignalReportArtefact.add_log(
+ team_id=other_team.id,
+ report_id=str(other_report.id),
+ content=NoteArtefact(note="x"),
+ attribution=ArtefactAttribution.from_user(self.user.id),
+ )
+
+ response = self.client.patch(
+ self._detail_url(str(other_report.id), str(artefact.id)),
+ data=json.dumps({"content": {"note": "y"}}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ # --- DELETE (remove log artefact) ---
+
+ def test_delete_removes_log_artefact(self):
+ report = self._create_report()
+ artefact = SignalReportArtefact.add_log(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=CodeReference(file_path="a.py", start_line=1, end_line=1, contents="x", relevance_note="r"),
+ attribution=ArtefactAttribution.from_user(self.user.id),
+ )
+
+ response = self.client.delete(self._detail_url(str(report.id), str(artefact.id)))
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not SignalReportArtefact.objects.filter(id=artefact.id).exists()
+
+ def test_delete_latest_status_artefact_reverts_canonical_to_previous(self):
+ report = self._create_report()
+ for priority, explanation in (("P3", "initial"), ("P1", "escalated")):
+ SignalReportArtefact.append_status(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=PriorityAssessment(explanation=explanation, priority=Priority(priority)),
+ attribution=ArtefactAttribution.system(),
+ )
+ latest = SignalReportArtefact.objects.filter(
+ report=report, type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT
+ ).order_by("-created_at")[0]
+
+ response = self.client.delete(self._detail_url(str(report.id), str(latest.id)))
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not SignalReportArtefact.objects.filter(id=latest.id).exists()
+
+ report_response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/")
+ assert report_response.status_code == status.HTTP_200_OK
+ assert report_response.json()["priority"] == "P3"
+
+ def test_delete_other_team_returns_404(self):
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ other_report = self._create_report(team=other_team)
+ artefact = SignalReportArtefact.add_log(
+ team_id=other_team.id,
+ report_id=str(other_report.id),
+ content=NoteArtefact(note="x"),
+ attribution=ArtefactAttribution.from_user(self.user.id),
+ )
+
+ response = self.client.delete(self._detail_url(str(other_report.id), str(artefact.id)))
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ assert SignalReportArtefact.objects.filter(id=artefact.id).exists()
+
+ def test_post_rejects_missing_artefact_type(self):
+ report = self._create_report()
+ response = self.client.post(
+ self._list_url(str(report.id)),
+ data=json.dumps({"content": []}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+
+class TestSignalReportArtefactAttribution(APIBaseTest):
+ """Attribution of API writes: X-PostHog-Task-Id header → task, otherwise the requesting user."""
+
+ def _list_url(self, report_id: str) -> str:
+ return f"/api/projects/{self.team.id}/signals/reports/{report_id}/artefacts/"
+
+ def _create_report(self, team: Team | None = None) -> SignalReport:
+ return SignalReport.objects.create(
+ team=team or self.team,
+ status=SignalReport.Status.READY,
+ title="Test report",
+ summary="Test summary",
+ signal_count=1,
+ total_weight=1.0,
+ )
+
+ def _create_task(self, team: Team | None = None) -> Task:
+ return Task.objects.create(
+ team=team or self.team,
+ title="task",
+ description="desc",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ )
+
+ def _post_note(self, report: SignalReport, **extra):
+ return self.client.post(
+ self._list_url(str(report.id)),
+ data=json.dumps({"artefact_type": "note", "content": {"note": "hello"}}),
+ content_type="application/json",
+ **extra,
+ )
+
+ def test_post_without_header_attributes_to_user(self):
+ report = self._create_report()
+ response = self._post_note(report)
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ artefact = SignalReportArtefact.objects.get(id=response.json()["id"])
+ assert artefact.created_by_id == self.user.id
+ assert artefact.task_id is None
+ assert response.json()["task_id"] is None
+
+ def test_post_with_header_attributes_to_task(self):
+ report = self._create_report()
+ task = self._create_task()
+ response = self._post_note(report, headers={"X-PostHog-Task-Id": str(task.id)})
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ artefact = SignalReportArtefact.objects.get(id=response.json()["id"])
+ assert str(artefact.task_id) == str(task.id)
+ assert artefact.created_by_id is None
+ assert response.json()["task_id"] == str(task.id)
+
+ def test_post_with_foreign_team_task_header_returns_400(self):
+ report = self._create_report()
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ foreign_task = self._create_task(team=other_team)
+ response = self._post_note(report, headers={"X-PostHog-Task-Id": str(foreign_task.id)})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert not SignalReportArtefact.objects.filter(report=report).exists()
+
+ @parameterized.expand([("not-a-uuid",), ("0000",)])
+ def test_post_with_malformed_task_header_returns_400(self, header_value):
+ report = self._create_report()
+ response = self._post_note(report, headers={"X-PostHog-Task-Id": header_value})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_post_with_unknown_task_header_returns_400(self):
+ report = self._create_report()
+ response = self._post_note(report, headers={"X-PostHog-Task-Id": str(uuid.uuid4())})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_list_exposes_created_by_and_task_id(self):
+ report = self._create_report()
+ assert self._post_note(report).status_code == status.HTTP_201_CREATED
+ task = self._create_task()
+ assert (
+ self._post_note(report, headers={"X-PostHog-Task-Id": str(task.id)}).status_code == status.HTTP_201_CREATED
+ )
+
+ response = self.client.get(self._list_url(str(report.id)))
+ assert response.status_code == status.HTTP_200_OK
+ by_task = {row["task_id"]: row for row in response.json()["results"]}
+ user_row = by_task[None]
+ task_row = by_task[str(task.id)]
+ assert user_row["created_by"]["id"] == self.user.id
+ assert task_row["created_by"] is None
+
+ def test_dismissal_via_state_action_is_attributed(self):
+ report = self._create_report()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/signals/reports/{report.id}/state/",
+ data=json.dumps({"state": "suppressed", "dismissal_reason": "analysis_wrong"}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ dismissal = SignalReportArtefact.objects.get(report=report, type=SignalReportArtefact.ArtefactType.DISMISSAL)
+ assert dismissal.created_by_id == self.user.id
+
+ def test_post_rejects_content_not_matching_type_schema(self):
+ report = self._create_report()
+ response = self.client.post(
+ self._list_url(str(report.id)),
+ data=json.dumps({"artefact_type": "commit", "content": {"repository": "a/b"}}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_patch_rejects_content_not_matching_type_schema(self):
+ report = self._create_report()
+ artefact = SignalReportArtefact.add_log(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=NoteArtefact(note="before"),
+ attribution=ArtefactAttribution.from_user(self.user.id),
+ )
+ response = self.client.patch(
+ f"{self._list_url(str(report.id))}{artefact.id}/",
+ data=json.dumps({"content": {"note": " "}}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ artefact.refresh_from_db()
+ assert json.loads(artefact.content) == {"note": "before", "author": None}
+
+
+_COMMIT_CONTENT = {
+ "repository": "PostHog/posthog",
+ "branch": "posthog-code/fix-foo",
+ "commit_sha": "abc123f",
+ "message": "fix: foo",
+}
+
+
+class TestSignalReportCommitDiff(APIBaseTest):
+ """The commit artefact `diff` action — status-code contract the UI relies on."""
+
+ def _diff_url(self, report_id: str, artefact_id: str) -> str:
+ return f"/api/projects/{self.team.id}/signals/reports/{report_id}/artefacts/{artefact_id}/diff/"
+
+ def _create_report(self) -> SignalReport:
+ return SignalReport.objects.create(
+ team=self.team,
+ status=SignalReport.Status.READY,
+ title="Test report",
+ summary="Test summary",
+ signal_count=1,
+ total_weight=1.0,
+ )
+
+ def _create_commit_artefact(self, report: SignalReport, content: dict | list | None = None) -> SignalReportArtefact:
+ return SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.COMMIT,
+ content=json.dumps(content if content is not None else _COMMIT_CONTENT),
+ )
+
+ def test_diff_rejects_non_commit_artefact(self):
+ report = self._create_report()
+ artefact = SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.NOTE,
+ content=json.dumps({"note": "x"}),
+ )
+ response = self.client.get(self._diff_url(str(report.id), str(artefact.id)))
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "commit artefacts" in response.json()["error"]
+
+ @parameterized.expand(
+ [
+ ("missing_repository", {"branch": "b", "commit_sha": "abc123f", "message": "m"}),
+ ("missing_branch", {"repository": "PostHog/posthog", "commit_sha": "abc123f", "message": "m"}),
+ ]
+ )
+ def test_diff_rejects_incomplete_content(self, _name, content):
+ report = self._create_report()
+ artefact = self._create_commit_artefact(report, content)
+ response = self.client.get(self._diff_url(str(report.id), str(artefact.id)))
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_diff_returns_404_when_no_integration_can_access_repo(self):
+ report = self._create_report()
+ artefact = self._create_commit_artefact(report)
+ with patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository", return_value=None):
+ response = self.client.get(self._diff_url(str(report.id), str(artefact.id)))
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def _mock_github(self, result: dict):
+ github = patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository").start()
+ self.addCleanup(patch.stopall)
+ github.return_value.get_default_branch.return_value = "master"
+ github.return_value.get_diff.return_value = result
+ return github
+
+ def test_diff_success_returns_diff_and_truncated(self):
+ report = self._create_report()
+ artefact = self._create_commit_artefact(report)
+ self._mock_github({"success": True, "diff": "diff --git a b", "truncated": False})
+
+ response = self.client.get(self._diff_url(str(report.id), str(artefact.id)))
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"diff": "diff --git a b", "truncated": False}
+
+ def test_diff_maps_upstream_404(self):
+ report = self._create_report()
+ artefact = self._create_commit_artefact(report)
+ self._mock_github({"success": False, "error": "Not Found", "status_code": 404})
+
+ response = self.client.get(self._diff_url(str(report.id), str(artefact.id)))
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_diff_maps_upstream_failure_to_502(self):
+ report = self._create_report()
+ artefact = self._create_commit_artefact(report)
+ self._mock_github({"success": False, "error": "boom", "status_code": 500})
+
+ response = self.client.get(self._diff_url(str(report.id), str(artefact.id)))
+ assert response.status_code == status.HTTP_502_BAD_GATEWAY
diff --git a/products/signals/backend/test/test_signal_report_artefact_model.py b/products/signals/backend/test/test_signal_report_artefact_model.py
new file mode 100644
index 000000000000..3351937e0123
--- /dev/null
+++ b/products/signals/backend/test/test_signal_report_artefact_model.py
@@ -0,0 +1,227 @@
+import json
+
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+from products.signals.backend.artefact_schemas import (
+ ArtefactContentValidationError,
+ Dismissal,
+ NoteArtefact,
+ Priority,
+ PriorityAssessment,
+ SignalFinding,
+)
+from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact
+from products.signals.backend.temporal.agentic.report import _AGENTIC_ARTEFACT_TYPES
+
+# Task ORM model needed to build cross-product fixtures; the tasks facade exposes DTOs only.
+from products.tasks.backend.models import Task # tach-ignore
+
+
+class TestSignalReportArtefactHelpers(BaseTest):
+ def _report(self) -> SignalReport:
+ return SignalReport.objects.create(
+ team=self.team,
+ status=SignalReport.Status.READY,
+ title="t",
+ summary="s",
+ signal_count=1,
+ total_weight=1.0,
+ )
+
+ def _task(self) -> Task:
+ return Task.objects.create(
+ team=self.team,
+ title="task",
+ description="desc",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ )
+
+ def _add_log(self, report: SignalReport, note: str = "x") -> SignalReportArtefact:
+ return SignalReportArtefact.add_log(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=NoteArtefact(note=note),
+ attribution=ArtefactAttribution.from_user(self.user.id),
+ )
+
+ def _append_priority(self, report: SignalReport, priority: str) -> SignalReportArtefact:
+ return SignalReportArtefact.append_status(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=PriorityAssessment(priority=Priority(priority), explanation="because"),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ @staticmethod
+ def _finding(signal_id: str) -> SignalFinding:
+ return SignalFinding(signal_id=signal_id, relevant_code_paths=["a.py"], data_queried="none", verified=True)
+
+ # --- classification ---
+
+ def test_status_and_log_types_are_disjoint(self):
+ assert SignalReportArtefact.STATUS_ARTEFACT_TYPES.isdisjoint(SignalReportArtefact.LOG_ARTEFACT_TYPES)
+
+ def test_agentic_set_never_touches_log_types(self):
+ # The agentic pipeline appends _AGENTIC_ARTEFACT_TYPES versions on every run. The set must
+ # stay disjoint from the log types so the two write paths never collide on a type.
+ assert set(_AGENTIC_ARTEFACT_TYPES).isdisjoint(SignalReportArtefact.LOG_ARTEFACT_TYPES)
+
+ # --- attribution ---
+
+ @parameterized.expand(
+ [
+ ("user_missing_id", {"kind": "user"}),
+ ("user_with_task", {"kind": "user", "user_id": 1, "task_id": "t"}),
+ ("task_missing_id", {"kind": "task"}),
+ ("task_with_user", {"kind": "task", "task_id": "t", "user_id": 1}),
+ ("system_with_user", {"kind": "system", "user_id": 1}),
+ ("system_with_task", {"kind": "system", "task_id": "t"}),
+ ]
+ )
+ def test_attribution_rejects_mismatched_fields(self, _name, kwargs):
+ with self.assertRaises(ValueError):
+ ArtefactAttribution(**kwargs)
+
+ def test_user_attribution_persists_created_by(self):
+ artefact = self._add_log(self._report())
+ assert artefact.created_by_id == self.user.id
+ assert artefact.task_id is None
+
+ def test_task_attribution_persists_task(self):
+ report = self._report()
+ task = self._task()
+ artefact = SignalReportArtefact.add_log(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=NoteArtefact(note="from an agent"),
+ attribution=ArtefactAttribution.from_task(str(task.id)),
+ )
+ assert str(artefact.task_id) == str(task.id)
+ assert artefact.created_by_id is None
+
+ def test_system_attribution_persists_nulls(self):
+ artefact = self._append_priority(self._report(), "P1")
+ assert artefact.created_by_id is None
+ assert artefact.task_id is None
+
+ # --- add_log ---
+
+ def test_add_log_appends(self):
+ report = self._report()
+ first = self._add_log(report, "one")
+ second = self._add_log(report, "two")
+
+ assert first.id != second.id
+ assert first.type == SignalReportArtefact.ArtefactType.NOTE # derived from the content model
+ notes = list(
+ SignalReportArtefact.objects.filter(report=report, type=SignalReportArtefact.ArtefactType.NOTE).order_by(
+ "created_at"
+ )
+ )
+ assert [json.loads(n.content)["note"] for n in notes] == ["one", "two"]
+
+ def test_add_log_rejects_status_content(self):
+ report = self._report()
+ with self.assertRaises(ValueError):
+ SignalReportArtefact.add_log(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=PriorityAssessment(priority=Priority.P1, explanation="x"), # type: ignore[arg-type]
+ attribution=ArtefactAttribution.system(),
+ )
+
+ # --- append_status ---
+
+ def test_append_status_appends_each_version(self):
+ report = self._report()
+ first = self._append_priority(report, "P2")
+ second = self._append_priority(report, "P0")
+
+ # Distinct rows — the prior version is retained as history, not overwritten.
+ assert first.id != second.id
+ rows = SignalReportArtefact.objects.filter(
+ report=report, type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT
+ ).order_by("created_at")
+ assert rows.count() == 2
+ # Current status is the latest row.
+ assert json.loads(rows[1].content)["priority"] == "P0"
+
+ def test_append_status_rejects_log_content(self):
+ report = self._report()
+ with self.assertRaises(ValueError):
+ SignalReportArtefact.append_status(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=NoteArtefact(note="x"), # type: ignore[arg-type]
+ attribution=ArtefactAttribution.system(),
+ )
+
+ # --- append_finding ---
+
+ def test_append_finding_appends_signal_finding(self):
+ report = self._report()
+ first = SignalReportArtefact.append_finding(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=self._finding("s1"),
+ attribution=ArtefactAttribution.system(),
+ )
+ second = SignalReportArtefact.append_finding(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=self._finding("s2"),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ assert first.type == SignalReportArtefact.ArtefactType.SIGNAL_FINDING
+ assert first.id != second.id
+ assert (
+ SignalReportArtefact.objects.filter(
+ report=report, type=SignalReportArtefact.ArtefactType.SIGNAL_FINDING
+ ).count()
+ == 2
+ )
+
+ # --- append_dismissal ---
+
+ def test_append_dismissal_stacks_and_attributes(self):
+ report = self._report()
+ first = SignalReportArtefact.append_dismissal(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=Dismissal(reason="not_a_bug", user_id=self.user.id),
+ attribution=ArtefactAttribution.from_user(self.user.id),
+ )
+ second = SignalReportArtefact.append_dismissal(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=Dismissal(reason="wont_fix", note="later"),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ assert first.id != second.id
+ assert first.created_by_id == self.user.id
+ assert second.created_by_id is None
+ assert (
+ SignalReportArtefact.objects.filter(report=report, type=SignalReportArtefact.ArtefactType.DISMISSAL).count()
+ == 2
+ )
+
+ # --- update_content ---
+
+ def test_update_content_replaces_and_stamps_updated_at(self):
+ report = self._report()
+ artefact = self._add_log(report, "before")
+ artefact.update_content(json.dumps({"note": "after"}))
+
+ artefact.refresh_from_db()
+ assert json.loads(artefact.content) == {"note": "after", "author": None}
+ assert artefact.updated_at is not None
+
+ def test_update_content_validates_against_row_type(self):
+ report = self._report()
+ artefact = self._add_log(report, "before")
+ with self.assertRaises(ArtefactContentValidationError):
+ artefact.update_content({"note": " "})
diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.py
index 2acaf0ec7618..6fefa8ce50bb 100644
--- a/products/signals/backend/test/test_slack_inbox_notifications.py
+++ b/products/signals/backend/test/test_slack_inbox_notifications.py
@@ -16,7 +16,6 @@ from products.signals.backend.models import (
AutonomyPriority,
SignalReport,
SignalReportArtefact,
- SignalReportTask,
SignalTeamConfig,
SignalUserAutonomyConfig,
)
@@ -31,6 +30,7 @@ from products.signals.backend.slack_inbox_notifications import (
_summary_excerpt,
dispatch_inbox_item_notifications,
)
+from products.signals.backend.task_run_artefacts import record_implementation_task
@pytest.mark.parametrize(
@@ -361,11 +361,10 @@ def _create_implementation_task_with_run(
description="Fix the bug",
origin_product=Task.OriginProduct.SIGNAL_REPORT,
)
- SignalReportTask.objects.create(
- team=team,
- report=report,
- task=task,
- relationship=SignalReportTask.Relationship.IMPLEMENTATION,
+ record_implementation_task(
+ team_id=team.id,
+ report_id=str(report.id),
+ task_id=str(task.id),
)
TaskRun.objects.create(
team=team,
diff --git a/products/signals/backend/test/test_task_run_artefacts.py b/products/signals/backend/test/test_task_run_artefacts.py
new file mode 100644
index 000000000000..4f505a298474
--- /dev/null
+++ b/products/signals/backend/test/test_task_run_artefacts.py
@@ -0,0 +1,348 @@
+import json
+
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+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.report_generation.research import (
+ ActionabilityAssessment,
+ ActionabilityChoice,
+ Priority,
+ PriorityAssessment,
+)
+from products.signals.backend.task_run_artefacts import (
+ SIGNALS_PRODUCT,
+ TASK_RUN_TYPE_IMPLEMENTATION,
+ TASK_RUN_TYPE_REPO_SELECTION,
+ TASK_RUN_TYPE_RESEARCH,
+ aappend_task_run_artefact,
+ append_task_run_artefact,
+ record_implementation_task,
+ signals_task_ids,
+)
+from products.tasks.backend.facade.repo_selection_types import RepoSelectionResult
+
+# Task/TaskRun ORM models needed to build cross-product fixtures; the tasks facade exposes DTOs only.
+from products.tasks.backend.models import Task, TaskRun # tach-ignore
+
+
+class TestTaskRunArtefacts(BaseTest):
+ def _report(self) -> SignalReport:
+ return SignalReport.objects.create(
+ team=self.team,
+ status=SignalReport.Status.READY,
+ title="t",
+ summary="s",
+ signal_count=1,
+ total_weight=1.0,
+ )
+
+ def _task(self) -> Task:
+ return Task.objects.create(
+ team=self.team,
+ title="task",
+ description="desc",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ )
+
+ def _task_run_artefacts(self, report: SignalReport) -> list[SignalReportArtefact]:
+ return list(SignalReportArtefact.objects.filter(report=report, type=SignalReportArtefact.ArtefactType.TASK_RUN))
+
+ @parameterized.expand(
+ [
+ (TASK_RUN_TYPE_RESEARCH,),
+ (TASK_RUN_TYPE_IMPLEMENTATION,),
+ (TASK_RUN_TYPE_REPO_SELECTION,),
+ ]
+ )
+ def test_append_records_signals_product_and_type(self, task_type):
+ report = self._report()
+ task = self._task()
+
+ artefact = append_task_run_artefact(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ product=SIGNALS_PRODUCT,
+ type=task_type,
+ task_id=str(task.id),
+ )
+
+ content = json.loads(artefact.content)
+ assert artefact.type == SignalReportArtefact.ArtefactType.TASK_RUN
+ assert content["task_id"] == str(task.id)
+ assert content["product"] == "signals"
+ assert content["type"] == task_type
+ assert content["run_id"] is None
+
+ def test_append_attributes_artefact_to_the_task(self):
+ report = self._report()
+ task = self._task()
+
+ artefact = append_task_run_artefact(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ product=SIGNALS_PRODUCT,
+ type=TASK_RUN_TYPE_RESEARCH,
+ task_id=str(task.id),
+ )
+
+ assert str(artefact.task_id) == str(task.id)
+ assert artefact.created_by_id is None
+
+ async def test_aappend_carries_run_id(self):
+ report = await SignalReport.objects.acreate(
+ team=self.team,
+ status=SignalReport.Status.READY,
+ title="t",
+ summary="s",
+ signal_count=1,
+ total_weight=1.0,
+ )
+ task = await Task.objects.acreate(
+ team=self.team,
+ title="task",
+ description="desc",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ )
+
+ artefact = await aappend_task_run_artefact(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ product=SIGNALS_PRODUCT,
+ type=TASK_RUN_TYPE_IMPLEMENTATION,
+ task_id=str(task.id),
+ run_id="run-789",
+ )
+
+ content = json.loads(artefact.content)
+ assert content["task_id"] == str(task.id)
+ assert content["run_id"] == "run-789"
+ assert content["product"] == "signals"
+ assert content["type"] == "implementation"
+
+ def test_signals_task_ids_filters_by_product_and_type(self):
+ report = self._report()
+ task = self._task()
+ append_task_run_artefact(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ product=SIGNALS_PRODUCT,
+ type=TASK_RUN_TYPE_RESEARCH,
+ task_id=str(task.id),
+ )
+ other_task = self._task()
+ append_task_run_artefact(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ product="billing",
+ type=TASK_RUN_TYPE_IMPLEMENTATION,
+ task_id=str(other_task.id),
+ )
+
+ assert signals_task_ids(report_id=str(report.id), type=TASK_RUN_TYPE_RESEARCH) == [str(task.id)]
+ # The custom product's "implementation" row doesn't count as a signals implementation.
+ assert signals_task_ids(report_id=str(report.id), type=TASK_RUN_TYPE_IMPLEMENTATION) == []
+
+ def test_record_implementation_task_writes_gate_row_and_artefact(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))
+
+ # Both the legacy SignalReportTask gate row and the task_run work-log artefact are written.
+ assert SignalReportTask.objects.filter(
+ 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)]
+
+ # 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 _final_report(self) -> CustomAgentFinalReport:
+ return CustomAgentFinalReport(
+ title="title",
+ description="description",
+ actionability=ActionabilityAssessment(
+ explanation="e",
+ actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE,
+ already_addressed=False,
+ ),
+ assignees=[],
+ priority=PriorityAssessment(explanation="e", priority=Priority.P1),
+ )
+
+ def test_custom_agent_report_with_task_uses_agent_identifier(self):
+ task = self._task()
+
+ persisted = create_custom_agent_ready_report(
+ team_id=self.team.id,
+ final_report=self._final_report(),
+ repo_selection=RepoSelectionResult(repository="acme/repo", reason="r"),
+ task_id=str(task.id),
+ agent_identifier=("billing", "anomaly_scan"),
+ )
+
+ report = SignalReport.objects.get(id=persisted.report_id)
+ artefacts = self._task_run_artefacts(report)
+ assert len(artefacts) == 1
+ content = json.loads(artefacts[0].content)
+ assert content["task_id"] == str(task.id)
+ assert content["product"] == "billing"
+ assert content["type"] == "anomaly_scan"
+ # Everything the custom agent produced is attributed to its task.
+ for artefact in SignalReportArtefact.objects.filter(report=report):
+ assert str(artefact.task_id) == str(task.id)
+
+ def test_custom_agent_report_without_task_appends_nothing(self):
+ persisted = create_custom_agent_ready_report(
+ team_id=self.team.id,
+ final_report=self._final_report(),
+ repo_selection=RepoSelectionResult(repository="acme/repo", reason="r"),
+ task_id=None,
+ agent_identifier=("billing", "anomaly_scan"),
+ )
+
+ report = SignalReport.objects.get(id=persisted.report_id)
+ assert self._task_run_artefacts(report) == []
+ # No task in scope — system attribution (both columns null).
+ for artefact in SignalReportArtefact.objects.filter(report=report):
+ assert artefact.task_id is None
+ assert artefact.created_by_id is None
+
+
+class TestAssociatedTaskRunsFilter(BaseTest):
+ """`SignalReport.associated_task_runs_filter` matches a TaskRun whose task is associated with
+ the report via either source (task_run artefact or legacy SignalReportTask)."""
+
+ def _report(self) -> SignalReport:
+ return SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.READY, title="t", summary="s", signal_count=1, total_weight=1.0
+ )
+
+ def _task_with_run(self) -> tuple[Task, TaskRun]:
+ task = Task.objects.create(
+ team=self.team, title="task", description="desc", origin_product=Task.OriginProduct.SIGNAL_REPORT
+ )
+ return task, TaskRun.objects.create(team=self.team, task=task, status=TaskRun.Status.COMPLETED)
+
+ def _matched_task_ids(self, report: SignalReport) -> set[str]:
+ return {
+ str(task_id)
+ for task_id in TaskRun.objects.filter(SignalReport.associated_task_runs_filter(report.id)).values_list(
+ "task_id", flat=True
+ )
+ }
+
+ def test_matches_task_associated_via_artefact_only(self):
+ report = self._report()
+ task, _run = self._task_with_run()
+ append_task_run_artefact(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ product=SIGNALS_PRODUCT,
+ type=TASK_RUN_TYPE_IMPLEMENTATION,
+ task_id=str(task.id),
+ )
+ assert not SignalReportTask.objects.filter(report=report).exists()
+ assert self._matched_task_ids(report) == {str(task.id)}
+
+ def test_matches_task_associated_via_signal_report_task_only(self):
+ report = self._report()
+ task, _run = self._task_with_run()
+ SignalReportTask.objects.create(
+ team=self.team, report=report, task=task, relationship=TASK_RUN_TYPE_IMPLEMENTATION
+ )
+ assert not SignalReportArtefact.objects.filter(report=report).exists()
+ 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()
+ # Dual-writes both the gate row and the artefact for the same task.
+ record_implementation_task(team_id=self.team.id, report_id=str(report.id), task_id=str(task.id))
+ # OR of two task_id__in subqueries must not double-count the run.
+ assert TaskRun.objects.filter(SignalReport.associated_task_runs_filter(report.id)).count() == 1
+ assert self._matched_task_ids(report) == {str(task.id)}
+
+ def test_excludes_tasks_associated_with_a_different_report(self):
+ report = self._report()
+ other_report = self._report()
+ other_task, _run = self._task_with_run()
+ append_task_run_artefact(
+ team_id=self.team.id,
+ report_id=str(other_report.id),
+ product=SIGNALS_PRODUCT,
+ type=TASK_RUN_TYPE_IMPLEMENTATION,
+ task_id=str(other_task.id),
+ )
+ assert self._matched_task_ids(report) == set()
+ assert self._matched_task_ids(other_report) == {str(other_task.id)}
+
+
+class TestReportsForTaskFilter(BaseTest):
+ """`SignalReport.reports_for_task_filter` matches the reports a task is associated with via
+ either source (task_run artefact or legacy SignalReportTask)."""
+
+ def _report(self) -> SignalReport:
+ return SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.READY, title="t", summary="s", signal_count=1, total_weight=1.0
+ )
+
+ def _task(self) -> Task:
+ return Task.objects.create(
+ team=self.team, title="task", description="desc", origin_product=Task.OriginProduct.SIGNAL_REPORT
+ )
+
+ def _matched_report_ids(self, task: Task) -> set[str]:
+ return {
+ str(report_id)
+ for report_id in SignalReport.objects.filter(SignalReport.reports_for_task_filter(task.id)).values_list(
+ "id", flat=True
+ )
+ }
+
+ def test_matches_report_associated_via_artefact_only(self):
+ report = self._report()
+ task = self._task()
+ append_task_run_artefact(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ product=SIGNALS_PRODUCT,
+ type=TASK_RUN_TYPE_IMPLEMENTATION,
+ task_id=str(task.id),
+ )
+ assert not SignalReportTask.objects.filter(task=task).exists()
+ assert self._matched_report_ids(task) == {str(report.id)}
+
+ def test_matches_report_associated_via_signal_report_task_only(self):
+ report = self._report()
+ task = self._task()
+ SignalReportTask.objects.create(
+ team=self.team, report=report, task=task, relationship=TASK_RUN_TYPE_IMPLEMENTATION
+ )
+ assert not SignalReportArtefact.objects.filter(task=task).exists()
+ assert self._matched_report_ids(task) == {str(report.id)}
+
+ def test_unions_both_sources_without_duplicate_rows(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))
+ assert SignalReport.objects.filter(SignalReport.reports_for_task_filter(task.id)).count() == 1
+ assert self._matched_report_ids(task) == {str(report.id)}
+
+ def test_excludes_reports_not_associated_with_the_task(self):
+ report = self._report()
+ task = self._task()
+ other_task = self._task()
+ append_task_run_artefact(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ product=SIGNALS_PRODUCT,
+ type=TASK_RUN_TYPE_IMPLEMENTATION,
+ task_id=str(task.id),
+ )
+ assert self._matched_report_ids(other_task) == set()
+ assert self._matched_report_ids(task) == {str(report.id)}
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 4d95a77354cc..c5562fe8bfa2 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -27,9 +27,8 @@ from django.db.models.functions import Cast, Coalesce
import structlog
from asgiref.sync import async_to_sync
-from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_view
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_view
from opentelemetry import trace
from rest_framework import exceptions, mixins, serializers, status, viewsets
from rest_framework.authentication import SessionAuthentication
@@ -42,25 +41,33 @@ from rest_framework.views import APIView
from temporalio.common import RetryPolicy, WorkflowIDConflictPolicy, WorkflowIDReusePolicy
from temporalio.exceptions import WorkflowAlreadyStartedError
+from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.auth import InternalAPIAuthentication, OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
from posthog.exceptions_capture import capture_exception
from posthog.models import Team, User
-from posthog.models.integration import Integration
+from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.permissions import APIScopePermission
from posthog.temporal.common.client import sync_connect
from posthog.user_permissions import UserPermissions
from products.data_warehouse.backend.data_load.service import trigger_external_data_workflow
+from products.signals.backend.artefact_schemas import (
+ NON_WRITABLE_ARTEFACT_TYPES,
+ ArtefactContentValidationError,
+ Dismissal,
+ SuggestedReviewers,
+ parse_artefact_content,
+)
from products.signals.backend.facade.api import emit_signal
from products.signals.backend.implementation_pr import fetch_implementation_pr_urls_for_reports
from products.signals.backend.models import (
+ ArtefactAttribution,
AutonomyPriority,
InvalidStatusTransition,
SignalReport,
SignalReportArtefact,
- SignalReportTask,
SignalSourceConfig,
SignalTeamConfig,
SignalUserAutonomyConfig,
@@ -73,15 +80,23 @@ from products.signals.backend.report_generation.resolve_reviewers import (
resolve_org_github_login_to_users,
)
from products.signals.backend.serializers import (
+ CommitDiffResponseSerializer,
+ SignalReportArtefactLogCreateSerializer,
+ SignalReportArtefactLogUpdateSerializer,
SignalReportArtefactSerializer,
+ SignalReportArtefactWriteResponseSerializer,
SignalReportArtefactWriteSerializer,
SignalReportSerializer,
- SignalReportTaskSerializer,
SignalSourceConfigSerializer,
SignalTeamConfigSerializer,
SignalUserAutonomyConfigCreateSerializer,
SignalUserAutonomyConfigSerializer,
)
+from products.signals.backend.task_attribution import (
+ TASK_ID_HEADER,
+ resolve_request_attribution,
+ resolve_task_id_from_header,
+)
from products.signals.backend.temporal.backfill_error_tracking import (
BackfillErrorTrackingInput,
BackfillErrorTrackingWorkflow,
@@ -533,6 +548,7 @@ class SignalReportViewSet(
qs = self._apply_signal_report_source_product_filter(qs)
qs = self._apply_signal_report_implementation_pr_filter(qs)
qs = self._apply_signal_report_suggested_reviewer_filter(qs)
+ qs = self._apply_signal_report_task_filter(qs)
qs = self._annotate_latest_actionability_value(qs)
qs = self._apply_signal_report_actionability_filter(qs)
qs = self._annotate_signal_report_status_rank(qs)
@@ -623,14 +639,33 @@ class SignalReportViewSet(
report_ids_with_source = fetch_report_ids_for_source_products(self.team, source_products)
return queryset.filter(id__in=report_ids_with_source)
+ def _latest_suggested_reviewers_qs(self):
+ """`suggested_reviewers` rows that are the *current* (latest) version for the correlated
+ outer report (`OuterRef("id")`).
+
+ suggested_reviewers is append-only, so only the newest row is the live reviewer set —
+ older versions remain as history and must not match. A row is current iff no newer row of
+ the same type exists for its report.
+ """
+ has_newer = Exists(
+ SignalReportArtefact.objects.filter(
+ report_id=OuterRef("report_id"),
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ created_at__gt=OuterRef("created_at"),
+ )
+ )
+ return SignalReportArtefact.objects.filter(
+ report_id=OuterRef("id"),
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ ).filter(~has_newer)
+
def _implementation_pr_exists_subquery(self):
# EXISTS over the latest implementation TaskRun that carries a non-empty
# `pr_url`. Mirrors `_annotate_implementation_pr_url`, but as a boolean
# EXISTS so it can be used as a filter (and counted) without the
# per-row PR-url annotation, which the list action skips for performance.
return tasks_facade.task_run_pr_url_exists_subquery(
- task__signal_report_tasks__report_id=OuterRef("id"),
- task__signal_report_tasks__relationship=SignalReportTask.Relationship.IMPLEMENTATION,
+ SignalReport.associated_task_runs_filter(OuterRef(OuterRef("id"))),
)
def _apply_signal_report_implementation_pr_filter(self, queryset):
@@ -678,16 +713,27 @@ class SignalReportViewSet(
return queryset.filter(
Exists(
# nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (parameterized via params)
- SignalReportArtefact.objects.filter(
- report_id=OuterRef("id"),
- type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
- ).extra(
+ self._latest_suggested_reviewers_qs().extra(
where=[reviewer_where],
params=reviewer_json_filters,
)
)
)
+ def _apply_signal_report_task_filter(self, queryset):
+ # Reports a given task is associated with — used by running agents ("which reports am I
+ # working against?") and by the agent harness to fan commit artefacts out to them. Uses the
+ # unified association (task_run artefacts + legacy SignalReportTask); the team-scoped outer
+ # queryset keeps the result within the project.
+ task_filter = self.request.query_params.get("task_id")
+ if not task_filter:
+ return queryset
+ try:
+ task_uuid = uuid.UUID(task_filter.strip())
+ except (ValueError, AttributeError) as e:
+ raise serializers.ValidationError({"task_id": f"Invalid task UUID: {e}"})
+ return queryset.filter(SignalReport.reports_for_task_filter(task_uuid))
+
def _apply_signal_report_priority_filter(self, queryset):
# Filters on the `priority_rank` annotation, which must be applied first.
# Reports without a priority artefact (coalesced to "~") are excluded when this filter is set.
@@ -845,10 +891,7 @@ class SignalReportViewSet(
# github_login comes from our own UserSocialAuth DB, not user input.
suggested_exists = Exists(
# nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (parameterized via params)
- SignalReportArtefact.objects.filter(
- report_id=OuterRef("id"),
- type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
- ).extra(
+ self._latest_suggested_reviewers_qs().extra(
where=["content::jsonb @> %s::jsonb"],
params=[json.dumps([{"github_login": github_login}])],
)
@@ -863,11 +906,12 @@ class SignalReportViewSet(
)
def _annotate_implementation_pr_url(self, queryset):
- # Find the latest TaskRun output->pr_url for the implementation task linked to each report.
- # Path: SignalReportTask(relationship=implementation) -> Task -> TaskRun(latest) -> output->'pr_url'
+ # 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).
+ # Only implementation runs carry a pr_url, so the non-empty-pr_url filter inside the facade
+ # subquery makes "any associated task" resolve to the implementation PR.
latest_impl_pr_url = tasks_facade.latest_task_run_pr_url_subquery(
- task__signal_report_tasks__report_id=OuterRef("id"),
- task__signal_report_tasks__relationship=SignalReportTask.Relationship.IMPLEMENTATION,
+ SignalReport.associated_task_runs_filter(OuterRef(OuterRef("id"))),
)
return queryset.annotate(implementation_pr_url=latest_impl_pr_url)
@@ -1003,6 +1047,13 @@ class SignalReportViewSet(
"priority, created_at, updated_at, id. Defaults to '-is_suggested_reviewer,status,-updated_at'."
),
),
+ OpenApiParameter(
+ name="task_id",
+ type=OpenApiTypes.UUID,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Only reports associated with this task (via the report's task associations).",
+ ),
OpenApiParameter(
name="has_implementation_pr",
type=OpenApiTypes.BOOL,
@@ -1237,19 +1288,17 @@ class SignalReportViewSet(
if target in ("suppressed", "potential") and (dismissal_reason or dismissal_note):
user = self.request.user
is_authenticated = getattr(user, "is_authenticated", False)
- # getattr (not direct attribute access) so the AnonymousUser branch type-checks.
user_uuid = getattr(user, "uuid", None) if is_authenticated else None
- artefact_content = {
- "reason": dismissal_reason,
- "note": dismissal_note,
- "user_id": getattr(user, "id", None) if is_authenticated else None,
- "user_uuid": str(user_uuid) if user_uuid else None,
- }
- SignalReportArtefact.objects.create(
- team=self.team,
- report=report,
- type=SignalReportArtefact.ArtefactType.DISMISSAL,
- content=json.dumps(artefact_content),
+ SignalReportArtefact.append_dismissal(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=Dismissal(
+ reason=dismissal_reason,
+ note=dismissal_note,
+ user_id=getattr(user, "id", None) if is_authenticated else None,
+ user_uuid=str(user_uuid) if user_uuid else None,
+ ),
+ attribution=resolve_request_attribution(self.request, self.team.id),
)
# The dismissal prefetch may have been evaluated before this artefact
# existed; drop the stale cache so a follow-up serializer re-reads the
@@ -1364,27 +1413,61 @@ class SignalReportViewSet(
@extend_schema_view(
- list=extend_schema(exclude=True),
- retrieve=extend_schema(exclude=True),
+ list=extend_schema(
+ summary="List a report's artefacts",
+ description=(
+ "List every artefact on a report — the full work log: signal findings (the evidence "
+ "behind the report), status judgments (safety / actionability / priority, repo "
+ "selection, suggested reviewers — the newest row of each status type is canonical), "
+ "and log entries (code references, commits, task runs, notes). "
+ "`suggested_reviewers` content is enriched with PostHog user info at read time."
+ ),
+ responses={200: SignalReportArtefactSerializer(many=True)},
+ operation_id="signals_report_artefacts_list",
+ ),
+ retrieve=extend_schema(
+ summary="Get a single artefact",
+ description="Get one artefact by id, content parsed (and reviewers enriched) the same way as the list.",
+ responses={200: SignalReportArtefactSerializer},
+ operation_id="signals_report_artefacts_retrieve",
+ ),
+ # The bespoke reviewers PUT stays app-only: agents append suggested_reviewers via POST instead.
update=extend_schema(exclude=True),
)
class SignalReportArtefactViewSet(
TeamAndOrgViewSetMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
+ mixins.CreateModelMixin,
mixins.UpdateModelMixin,
+ mixins.DestroyModelMixin,
viewsets.GenericViewSet,
):
- """Artefacts attached to a signal report. PUT replaces the content of a
- `suggested_reviewers` artefact; other types return 400."""
+ """Artefacts attached to a signal report.
+
+ Two write surfaces, both gated by the `task:write` scope (already held by the agent tokens):
+
+ - PUT edits a report's suggested reviewers: it appends a new `suggested_reviewers` status
+ artefact (latest-wins, so the new row becomes current) with bespoke reviewer enrichment,
+ merging commits/names forward from the current reviewers. Other types return 400.
+ - POST / PATCH / DELETE manage artefacts of *any* type — no type is writer-restricted.
+ Log entries accumulate; status types (judgments, repo selection, suggested reviewers)
+ are latest-wins, so appending a new version supersedes the previous one as the report's
+ canonical status. Content is validated against the type's schema. Team scoping is
+ enforced by `safely_get_queryset`, so an artefact id from another team / a deleted
+ report 404s.
+
+ Writes are attributed: to the task named by the `X-PostHog-Task-Id` header (set automatically
+ for sandbox agents) when present, else to the requesting user.
+ """
serializer_class = SignalReportArtefactSerializer
authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
permission_classes = [IsAuthenticated, APIScopePermission]
scope_object = "task"
- queryset = SignalReportArtefact.objects.all().order_by("-created_at")
- # No POST / PATCH / DELETE
- http_method_names = ["get", "put", "head", "options"]
+ # select_related: the read serializer renders `created_by` inline.
+ queryset = SignalReportArtefact.objects.select_related("created_by").order_by("-created_at")
+ http_method_names = ["get", "post", "put", "patch", "delete", "head", "options"]
def safely_get_queryset(self, queryset):
# Mirror SignalReportViewSet: a deleted parent report is unreachable, so
@@ -1432,6 +1515,9 @@ class SignalReportArtefactViewSet(
write_serializer.is_valid(raise_exception=True)
entries = write_serializer.validated_data["content"]
+ # Resolved before the locked transaction below — header validation must not hold the lock.
+ attribution = resolve_request_attribution(request, self.team.id)
+
# Resolve any user_uuid → canonical github_login via team org membership.
uuids_to_resolve = [str(e["user_uuid"]) for e in entries if e.get("user_uuid")]
uuid_to_login: dict[str, str] = (
@@ -1472,52 +1558,74 @@ class SignalReportArtefactViewSet(
github_name = entry.get("github_name") if explicit_name else None
resolved_entries.append((login_lc, github_name, explicit_name))
- # Preserve relevant_commits for entries that survive the replace, keyed by login.
- try:
- prior_content = json.loads(artefact.content)
- except (json.JSONDecodeError, ValueError):
- prior_content = []
- prior_commits_by_login: dict[str, list] = {}
- prior_name_by_login: dict[str, str | None] = {}
- if isinstance(prior_content, list):
- for prior in prior_content:
- if not isinstance(prior, dict):
- continue
- login = (prior.get("github_login") or "").strip().lower()
- if not login:
- continue
- commits = prior.get("relevant_commits")
- if isinstance(commits, list):
- prior_commits_by_login[login] = commits
- prior_name = prior.get("github_name")
- if isinstance(prior_name, str):
- prior_name_by_login[login] = prior_name
-
- # Dedupe by canonical login, preserve first-seen order.
+ # Lock the report for the read-merge-append so concurrent reviewer edits serialize — each
+ # PUT reads the current (latest) reviewers and appends a new row, so without the lock two
+ # simultaneous edits would both read the same row and one would be silently lost.
seen: set[str] = set()
- new_content: list[dict] = []
- for login_lc, github_name, explicit_name in resolved_entries:
- if login_lc in seen:
- continue
- seen.add(login_lc)
- # If the client supplied github_name (incl. ""), honour it. Otherwise
- # carry over the prior one so kept reviewers don't lose their name.
- effective_name = github_name if explicit_name else prior_name_by_login.get(login_lc)
- new_content.append(
- {
- "github_login": login_lc,
- "github_name": effective_name,
- "relevant_commits": prior_commits_by_login.get(login_lc, []),
- }
+ with transaction.atomic():
+ SignalReport.objects.select_for_update().filter(id=artefact.report_id, team_id=self.team_id).first()
+
+ # Merge commits/names forward from the *current* reviewers (the latest status row), not
+ # necessarily the addressed one — `suggested_reviewers` is append-only and latest-wins.
+ current = (
+ SignalReportArtefact.objects.filter(
+ report_id=artefact.report_id,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ )
+ .order_by("-created_at")
+ .first()
)
+ try:
+ prior_content = json.loads((current or artefact).content)
+ except (json.JSONDecodeError, ValueError):
+ prior_content = []
+ prior_commits_by_login: dict[str, list] = {}
+ prior_name_by_login: dict[str, str | None] = {}
+ if isinstance(prior_content, list):
+ for prior in prior_content:
+ if not isinstance(prior, dict):
+ continue
+ login = (prior.get("github_login") or "").strip().lower()
+ if not login:
+ continue
+ commits = prior.get("relevant_commits")
+ if isinstance(commits, list):
+ prior_commits_by_login[login] = commits
+ prior_name = prior.get("github_name")
+ if isinstance(prior_name, str):
+ prior_name_by_login[login] = prior_name
+
+ # Dedupe by canonical login, preserve first-seen order.
+ new_content: list[dict] = []
+ for login_lc, github_name, explicit_name in resolved_entries:
+ if login_lc in seen:
+ continue
+ seen.add(login_lc)
+ # If the client supplied github_name (incl. ""), honour it. Otherwise
+ # carry over the prior one so kept reviewers don't lose their name.
+ effective_name = github_name if explicit_name else prior_name_by_login.get(login_lc)
+ new_content.append(
+ {
+ "github_login": login_lc,
+ "github_name": effective_name,
+ "relevant_commits": prior_commits_by_login.get(login_lc, []),
+ }
+ )
- artefact.content = json.dumps(new_content)
- artefact.save(update_fields=["content"])
+ # Append a new status row rather than mutating in place: a human reviewer edit becomes a
+ # point-in-time entry in the work log, and latest-wins keeps it current. Appending a
+ # reviewers status also re-evaluates auto-start (handled in `append_status`, on commit).
+ new_artefact = SignalReportArtefact.append_status(
+ team_id=self.team.id,
+ report_id=str(artefact.report_id),
+ content=SuggestedReviewers.model_validate(new_content),
+ attribution=attribution,
+ )
# Return the read-shape (enriched) so the client sees the canonical result.
login_map = resolve_org_github_login_to_users(self.team.id, list(seen)) if seen else {}
read_serializer = SignalReportArtefactSerializer(
- artefact,
+ new_artefact,
context={
**self.get_serializer_context(),
"signals_github_login_to_user_map": login_map,
@@ -1525,25 +1633,286 @@ class SignalReportArtefactViewSet(
)
return Response(read_serializer.data)
+ @staticmethod
+ def _write_response_data(artefact: SignalReportArtefact) -> dict:
+ """Build the create/update response payload, parsing stored JSON content for the echo."""
+ try:
+ parsed_content: dict | list = json.loads(artefact.content)
+ except (json.JSONDecodeError, ValueError):
+ parsed_content = {}
+ return SignalReportArtefactWriteResponseSerializer(
+ {
+ "id": artefact.id,
+ "report_id": artefact.report_id,
+ "type": artefact.type,
+ "content": parsed_content,
+ "created_at": artefact.created_at,
+ "updated_at": artefact.updated_at,
+ "task_id": artefact.task_id,
+ }
+ ).data
+
+ @validated_request(
+ request_serializer=SignalReportArtefactLogCreateSerializer,
+ responses={
+ 201: OpenApiResponse(response=SignalReportArtefactWriteResponseSerializer, description="Artefact created."),
+ 400: OpenApiResponse(
+ description="Unknown artefact type, content not matching the type's schema, "
+ "or an invalid X-PostHog-Task-Id header."
+ ),
+ 404: OpenApiResponse(description="Report not found for this project."),
+ },
+ parameters=[
+ OpenApiParameter(
+ name=TASK_ID_HEADER,
+ type=OpenApiTypes.UUID,
+ location=OpenApiParameter.HEADER,
+ required=False,
+ description=(
+ "Task to attribute the artefact to (must belong to this project). Set automatically "
+ "for sandbox agents; when absent the artefact is attributed to the requesting user."
+ ),
+ ),
+ ],
+ summary="Append an artefact to a report",
+ description=(
+ "Append an artefact to a report (see artefact_type for the writable types). Everything "
+ "is append-only: log entries (code reference, commit, task run, note) accumulate, while "
+ "status types (safety / actionability / priority judgments, repo selection, suggested "
+ "reviewers) are latest-wins — appending a new version supersedes the previous one as the "
+ "report's canonical status. Content is validated against the type's schema."
+ ),
+ operation_id="signals_report_artefacts_create",
+ )
+ def create(self, request: ValidatedRequest, *args, **kwargs) -> Response:
+ report_id = self.parents_query_dict["report_id"]
+ # A deleted / foreign report is unreachable — don't let a known report_id attach
+ # artefacts to it. Mirrors the team-scoped filter in `safely_get_queryset`.
+ report_exists = (
+ SignalReport.objects.filter(id=report_id, team=self.team)
+ .exclude(status=SignalReport.Status.DELETED)
+ .exists()
+ )
+ if not report_exists:
+ raise NotFound()
+ artefact_type = request.validated_data["artefact_type"]
+ writable_types = sorted(set(SignalReportArtefact.ArtefactType.values) - NON_WRITABLE_ARTEFACT_TYPES)
+ if artefact_type not in SignalReportArtefact.ArtefactType.values:
+ return Response(
+ {"error": f"Unknown artefact type '{artefact_type}'. Valid types: {', '.join(writable_types)}."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ if artefact_type in NON_WRITABLE_ARTEFACT_TYPES:
+ # Legacy permissive types (e.g. video_segment) have no real content validation, so the
+ # write API refuses them — they stay readable for existing rows but can't be created.
+ return Response(
+ {"error": f"Artefact type '{artefact_type}' is read-only and cannot be created through the API."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ content = request.validated_data["content"]
+ attribution = resolve_request_attribution(request, self.team.id)
+ if artefact_type == SignalReportArtefact.ArtefactType.TASK_RUN:
+ # task_run artefacts are the task↔report association itself, so they get
+ # associate-me ergonomics: content.task_id defaults to the calling agent's task
+ # (the header), product/type default to a generic agent-run label, the named task
+ # must belong to this project, attribution is always the recorded task, and
+ # re-associating an already-linked task is idempotent (returns the existing entry).
+ if not isinstance(content, dict):
+ return Response(
+ {"error": "task_run content must be a JSON object."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ task_id = content.get("task_id") or resolve_task_id_from_header(request, self.team.id)
+ if not task_id:
+ return Response(
+ {"error": "Provide content.task_id, or call with an X-PostHog-Task-Id header."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ if not tasks_facade.task_exists(task_id, self.team.id):
+ return Response(
+ {"error": "Unknown task for this project."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ content = {**content, "task_id": str(task_id)}
+ content.setdefault("product", "tasks")
+ content.setdefault("type", "agent_run")
+ existing = (
+ SignalReportArtefact.objects.filter(
+ team=self.team,
+ report_id=report_id,
+ type=SignalReportArtefact.ArtefactType.TASK_RUN,
+ task_id=task_id,
+ )
+ .order_by("created_at")
+ .first()
+ )
+ if existing is not None:
+ return Response(self._write_response_data(existing), status=status.HTTP_200_OK)
+ attribution = ArtefactAttribution.from_task(str(task_id))
+ # The write boundary: parse the raw payload into the type's content model once; the
+ # typed model is what flows into the append helpers.
+ try:
+ parsed_content = parse_artefact_content(artefact_type, content)
+ except ArtefactContentValidationError as e:
+ return Response(
+ {"error": f"content does not match the '{artefact_type}' schema: {e}"},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ artefact = SignalReportArtefact.append(
+ team_id=self.team.id,
+ report_id=report_id,
+ content=parsed_content,
+ attribution=attribution,
+ )
+ return Response(self._write_response_data(artefact), status=status.HTTP_201_CREATED)
+
+ @validated_request(
+ request_serializer=SignalReportArtefactLogUpdateSerializer,
+ responses={
+ 200: OpenApiResponse(response=SignalReportArtefactWriteResponseSerializer, description="Artefact updated."),
+ 400: OpenApiResponse(description="Content does not match the artefact type's schema."),
+ 404: OpenApiResponse(description="Artefact not found for this report / project."),
+ },
+ summary="Replace an artefact's content",
+ description=(
+ "Replace the content of an existing artefact, addressed by id. The new content is "
+ "validated against the artefact's type schema. Editing the latest row of a status type "
+ "changes the report's canonical status (latest-wins); to re-assess while keeping history, "
+ "append a new artefact instead. Attribution is creation-time only — edits don't reassign it."
+ ),
+ operation_id="signals_report_artefacts_partial_update",
+ )
+ def partial_update(self, request: ValidatedRequest, *args, **kwargs) -> Response:
+ artefact = cast(SignalReportArtefact, self.get_object())
+ if artefact.type in NON_WRITABLE_ARTEFACT_TYPES:
+ # Legacy read-only types (e.g. video_segment) can't be created via the API, so they
+ # can't be edited through it either.
+ return Response(
+ {"error": f"Artefact type '{artefact.type}' is read-only and cannot be edited through the API."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ try:
+ artefact.update_content(request.validated_data["content"])
+ except ArtefactContentValidationError as e:
+ return Response(
+ {"error": f"content does not match the '{artefact.type}' schema: {e}"},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ return Response(self._write_response_data(artefact))
-@extend_schema_view(list=extend_schema(exclude=True))
-class SignalReportTaskViewSet(
- TeamAndOrgViewSetMixin,
- mixins.ListModelMixin,
- viewsets.GenericViewSet,
-):
- """Read-only list of tasks associated with a signal report."""
+ @extend_schema(
+ responses={
+ 204: OpenApiResponse(description="Artefact deleted."),
+ 404: OpenApiResponse(description="Artefact not found for this report / project."),
+ },
+ summary="Delete an artefact",
+ description=(
+ "Delete an artefact, addressed by id. Deleting the latest row of a status type reverts "
+ "the report's canonical status to the previous version (latest-wins over what remains)."
+ ),
+ operation_id="signals_report_artefacts_destroy",
+ )
+ def destroy(self, request, *args, **kwargs) -> Response:
+ artefact = cast(SignalReportArtefact, self.get_object())
+ artefact.delete()
+ return Response(status=status.HTTP_204_NO_CONTENT)
- serializer_class = SignalReportTaskSerializer
- authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
- permission_classes = [IsAuthenticated, APIScopePermission]
- scope_object = "task"
- queryset = SignalReportTask.objects.all().order_by("-created_at")
- filter_backends = [DjangoFilterBackend]
- filterset_fields = ["relationship", "task_id", "created_at"]
+ @extend_schema(
+ responses={
+ 200: OpenApiResponse(
+ response=CommitDiffResponseSerializer,
+ description="The branch's unified diff against the repository default branch.",
+ ),
+ 400: OpenApiResponse(description="Artefact is not a commit, or is missing repository/branch."),
+ 404: OpenApiResponse(description="Artefact not found, or no GitHub integration can access the repository."),
+ 502: OpenApiResponse(description="GitHub could not produce the diff (branch not found, fetch failed)."),
+ },
+ summary="Fetch the diff for a commit artefact",
+ description=(
+ "Fetch the unified diff of a `commit` artefact's branch against the repository default "
+ "branch via the team's GitHub integration — using the branch's current tip so the diff "
+ "reflects the latest state of the work, not just the single recorded commit."
+ ),
+ operation_id="signals_report_artefacts_diff",
+ )
+ @action(detail=True, methods=["get"], url_path="diff", required_scopes=["task:read"])
+ def diff(self, request: Request, *args, **kwargs) -> Response:
+ artefact = cast(SignalReportArtefact, self.get_object())
+ if artefact.type != SignalReportArtefact.ArtefactType.COMMIT:
+ return Response(
+ {"error": f"Diffs are only available for commit artefacts, not '{artefact.type}'."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ try:
+ content = json.loads(artefact.content)
+ except (json.JSONDecodeError, ValueError):
+ content = {}
+ if not isinstance(content, dict):
+ # Log artefacts store arbitrary JSON; a non-object payload has no repository/commit.
+ content = {}
+ repository = content.get("repository")
+ branch = content.get("branch")
+ if not repository or not branch:
+ return Response(
+ {"error": "Artefact is missing a repository or branch."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
- def safely_get_queryset(self, queryset):
- return queryset.filter(report_id=self.parents_query_dict["report_id"], team=self.team)
+ # The diff is deliberately bounded to repos the team's GitHub installation can access
+ # (`first_for_team_repository` returns None otherwise) rather than to a single per-report
+ # repository: a report's work legitimately spans multiple repos (cross-repo fixes, stacked
+ # PRs). That connection boundary is the intended scope — any `task:write` holder can already
+ # run agents against those same repos — and the repo/ref values are validated in `get_diff`.
+ github = GitHubIntegration.first_for_team_repository(self.team.id, repository)
+ if github is None:
+ return Response(
+ {"error": f"No GitHub integration can access '{repository}'."},
+ status=status.HTTP_404_NOT_FOUND,
+ )
+ try:
+ # Diff the commit's branch against the repo default branch, using each branch's current
+ # tip (no SHA pinning) so the diff stays useful as the branch keeps moving after the
+ # commit was recorded — e.g. after PR babysitting or customer tweaks.
+ base_branch = github.get_default_branch(repository)
+ result = github.get_diff(repository, target_branch=str(branch), base_branch=base_branch)
+ except Exception: # noqa: BLE001 — never let an upstream GitHub failure 500 this endpoint
+ logger.warning(
+ "signals branch diff fetch errored",
+ repository=repository,
+ branch=branch,
+ )
+ return Response(
+ {"error": "GitHub could not produce the diff for this branch."},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ if not result.get("success"):
+ # Surface a clean message rather than the raw GitHub error body. A 404 from the
+ # compare API means the branch (or repo) isn't on the remote — most often a branch
+ # that was merged-and-deleted or force-rewritten away.
+ if result.get("status_code") == 404:
+ return Response(
+ {
+ "error": f"Branch '{branch}' or repository '{repository}' was not found on GitHub — "
+ "the branch may have been deleted or merged away."
+ },
+ status=status.HTTP_404_NOT_FOUND,
+ )
+ logger.warning(
+ "signals branch diff fetch failed",
+ repository=repository,
+ branch=branch,
+ status_code=result.get("status_code"),
+ )
+ return Response(
+ {"error": "GitHub could not produce the diff for this branch."},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ return Response(
+ {
+ "diff": result["diff"],
+ "truncated": result.get("truncated", False),
+ }
+ )
class SignalUserAutonomyConfigView(APIView):
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 779165a32492..9ad7a03cfe2c 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -176,6 +176,134 @@ export interface SignalReportStateRequestApi {
snooze_for?: number
}
+/**
+ * * `video_segment` - Video Segment
+ * * `safety_judgment` - Safety Judgment
+ * * `actionability_judgment` - Actionability Judgment
+ * * `priority_judgment` - Priority Judgment
+ * * `signal_finding` - Signal Finding
+ * * `repo_selection` - Repo Selection
+ * * `suggested_reviewers` - Suggested Reviewers
+ * * `dismissal` - Dismissal
+ * * `code_reference` - Code Reference
+ * * `commit` - Commit
+ * * `task_run` - Task Run
+ * * `note` - Note
+ */
+export type SignalReportArtefactTypeEnumApi =
+ (typeof SignalReportArtefactTypeEnumApi)[keyof typeof SignalReportArtefactTypeEnumApi]
+
+export const SignalReportArtefactTypeEnumApi = {
+ VideoSegment: 'video_segment',
+ SafetyJudgment: 'safety_judgment',
+ ActionabilityJudgment: 'actionability_judgment',
+ PriorityJudgment: 'priority_judgment',
+ SignalFinding: 'signal_finding',
+ RepoSelection: 'repo_selection',
+ SuggestedReviewers: 'suggested_reviewers',
+ Dismissal: 'dismissal',
+ CodeReference: 'code_reference',
+ Commit: 'commit',
+ TaskRun: 'task_run',
+ Note: 'note',
+} 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 {
+ readonly id: string
+ readonly type: SignalReportArtefactTypeEnumApi
+ readonly content: SignalReportArtefactApiContent
+ 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. */
+ readonly created_by: _UserApi | null
+ /**
+ * Task the artefact is attributed to, when an agent produced it. Null for user/system writes.
+ * @nullable
+ */
+ readonly task_id: string | null
+}
+
+export interface PaginatedSignalReportArtefactListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: SignalReportArtefactApi[]
+}
+
+/**
+ * Body for appending an artefact to a report.
+ *
+ * Everything is append-only: log artefacts accumulate, status artefacts supersede the previous
+ * version (latest-wins). The `content` shape depends on `artefact_type` and is validated
+ * against the type's schema (see `products/signals/backend/artefact_schemas.py`).
+ */
+export interface SignalReportArtefactLogCreateApi {
+ /** The artefact type. One of: actionability_judgment, code_reference, commit, dismissal, note, priority_judgment, repo_selection, safety_judgment, signal_finding, suggested_reviewers, task_run. Log types accumulate; status types (safety_judgment, actionability_judgment, priority_judgment, repo_selection, suggested_reviewers) are latest-wins — appending a new version supersedes the previous one as the report's canonical status. */
+ artefact_type: string
+ /** The artefact payload as a JSON object or array; shape depends on artefact_type and is validated against its schema. */
+ content: unknown
+}
+
+/**
+ * Response shape for the log-artefact create/update endpoints — echoes the stored row.
+ */
+export interface SignalReportArtefactWriteResponseApi {
+ /** The artefact's unique id. */
+ readonly id: string
+ /** The id of the report this artefact belongs to. */
+ readonly report_id: string
+ /** The artefact type. */
+ readonly type: string
+ /** The artefact payload, parsed from storage. */
+ readonly content: unknown
+ /** When the artefact was created. */
+ readonly created_at: string
+ /**
+ * When the artefact was last written — set on creation and refreshed on each edit. Null only for rows created before this field existed.
+ * @nullable
+ */
+ readonly updated_at: string | null
+ /**
+ * Task the artefact is attributed to, when an agent produced it. Null for user writes.
+ * @nullable
+ */
+ readonly task_id: string | null
+}
+
+/**
+ * Body for replacing the content of an existing artefact (addressed by id).
+ *
+ * Per-type schema validation happens in the view, which knows the artefact's type.
+ */
+export interface PatchedSignalReportArtefactLogUpdateApi {
+ /** The new artefact payload as a JSON object or array, matching the artefact type's schema. */
+ content?: unknown
+}
+
+/**
+ * Response for the `commit` artefact diff endpoint — the commit's branch rendered against the
+ * repository default branch.
+ */
+export interface CommitDiffResponseApi {
+ /** Unified diff (patch) text of the branch against the repository default branch, from the GitHub compare API. */
+ readonly diff: string
+ /** True when the diff was too large to return in full and has been truncated. */
+ readonly truncated: boolean
+}
+
export interface SignalReportBulkStateRequestApi {
/** Target state for the report. Use 'suppressed' to dismiss the report from the inbox, or 'potential' to snooze/reopen it for later review.
*
@@ -1379,14 +1507,6 @@ export interface PatchedSignalSourceConfigApi {
readonly status?: string | null
}
-export interface _UserApi {
- readonly id: number
- readonly uuid: string
- readonly first_name: string
- readonly last_name: string
- readonly email: string
-}
-
export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]
export const BlankEnumApi = {
@@ -1468,6 +1588,21 @@ export type SignalsReportsListParams = {
* Comma-separated list of PostHog user UUIDs. Reports are kept if their suggested reviewers include any of the given users.
*/
suggested_reviewers?: string
+ /**
+ * Only reports associated with this task (via the report's task associations).
+ */
+ task_id?: string
+}
+
+export type SignalsReportArtefactsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
}
export type SignalsScoutProjectProfileGetParams = {
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 4fb09f635e87..6c82c21698f7 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -9,13 +9,16 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ CommitDiffResponseApi,
EmitFindingRequestApi,
EmitFindingResponseApi,
ForgetRequestApi,
ForgetResponseApi,
PaginatedPauseStateResponseListApi,
+ PaginatedSignalReportArtefactListApi,
PaginatedSignalReportListApi,
PaginatedSignalSourceConfigListApi,
+ PatchedSignalReportArtefactLogUpdateApi,
PatchedSignalScoutConfigApi,
PatchedSignalSourceConfigApi,
PauseResponseApi,
@@ -26,6 +29,9 @@ import type {
ScoutMetadataApi,
ScratchpadEntryApi,
SignalReportApi,
+ SignalReportArtefactApi,
+ SignalReportArtefactLogCreateApi,
+ SignalReportArtefactWriteResponseApi,
SignalReportBulkStateRequestApi,
SignalReportBulkStateResponseApi,
SignalReportStateRequestApi,
@@ -37,6 +43,7 @@ import type {
SignalSourceConfigApi,
SignalUserAutonomyConfigApi,
SignalsProcessingListParams,
+ SignalsReportArtefactsListParams,
SignalsReportsListParams,
SignalsScoutProjectProfileGetParams,
SignalsScoutRunsListParams,
@@ -205,6 +212,153 @@ export const signalsReportsStateCreate = async (
})
}
+export const getSignalsReportArtefactsListUrl = (
+ projectId: string,
+ reportId: string,
+ params?: SignalsReportArtefactsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/signals/reports/${reportId}/artefacts/?${stringifiedParams}`
+ : `/api/projects/${projectId}/signals/reports/${reportId}/artefacts/`
+}
+
+/**
+ * List every artefact on a report — the full work log: signal findings (the evidence behind the report), status judgments (safety / actionability / priority, repo selection, suggested reviewers — the newest row of each status type is canonical), and log entries (code references, commits, task runs, notes). `suggested_reviewers` content is enriched with PostHog user info at read time.
+ * @summary List a report's artefacts
+ */
+export const signalsReportArtefactsList = async (
+ projectId: string,
+ reportId: string,
+ params?: SignalsReportArtefactsListParams,
+ options?: RequestInit
+): Promise<PaginatedSignalReportArtefactListApi> => {
+ return apiMutator<PaginatedSignalReportArtefactListApi>(
+ getSignalsReportArtefactsListUrl(projectId, reportId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getSignalsReportArtefactsCreateUrl = (projectId: string, reportId: string) => {
+ return `/api/projects/${projectId}/signals/reports/${reportId}/artefacts/`
+}
+
+/**
+ * Append an artefact to a report (see artefact_type for the writable types). Everything is append-only: log entries (code reference, commit, task run, note) accumulate, while status types (safety / actionability / priority judgments, repo selection, suggested reviewers) are latest-wins — appending a new version supersedes the previous one as the report's canonical status. Content is validated against the type's schema.
+ * @summary Append an artefact to a report
+ */
+export const signalsReportArtefactsCreate = async (
+ projectId: string,
+ reportId: string,
+ signalReportArtefactLogCreateApi: SignalReportArtefactLogCreateApi,
+ options?: RequestInit
+): Promise<SignalReportArtefactWriteResponseApi> => {
+ return apiMutator<SignalReportArtefactWriteResponseApi>(getSignalsReportArtefactsCreateUrl(projectId, reportId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(signalReportArtefactLogCreateApi),
+ })
+}
+
+export const getSignalsReportArtefactsRetrieveUrl = (projectId: string, reportId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/reports/${reportId}/artefacts/${id}/`
+}
+
+/**
+ * Get one artefact by id, content parsed (and reviewers enriched) the same way as the list.
+ * @summary Get a single artefact
+ */
+export const signalsReportArtefactsRetrieve = async (
+ projectId: string,
+ reportId: string,
+ id: string,
+ options?: RequestInit
+): Promise<SignalReportArtefactApi> => {
+ return apiMutator<SignalReportArtefactApi>(getSignalsReportArtefactsRetrieveUrl(projectId, reportId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getSignalsReportArtefactsPartialUpdateUrl = (projectId: string, reportId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/reports/${reportId}/artefacts/${id}/`
+}
+
+/**
+ * Replace the content of an existing artefact, addressed by id. The new content is validated against the artefact's type schema. Editing the latest row of a status type changes the report's canonical status (latest-wins); to re-assess while keeping history, append a new artefact instead. Attribution is creation-time only — edits don't reassign it.
+ * @summary Replace an artefact's content
+ */
+export const signalsReportArtefactsPartialUpdate = async (
+ projectId: string,
+ reportId: string,
+ id: string,
+ patchedSignalReportArtefactLogUpdateApi?: PatchedSignalReportArtefactLogUpdateApi,
+ options?: RequestInit
+): Promise<SignalReportArtefactWriteResponseApi> => {
+ return apiMutator<SignalReportArtefactWriteResponseApi>(
+ getSignalsReportArtefactsPartialUpdateUrl(projectId, reportId, id),
+ {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedSignalReportArtefactLogUpdateApi),
+ }
+ )
+}
+
+export const getSignalsReportArtefactsDestroyUrl = (projectId: string, reportId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/reports/${reportId}/artefacts/${id}/`
+}
+
+/**
+ * Delete an artefact, addressed by id. Deleting the latest row of a status type reverts the report's canonical status to the previous version (latest-wins over what remains).
+ * @summary Delete an artefact
+ */
+export const signalsReportArtefactsDestroy = async (
+ projectId: string,
+ reportId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getSignalsReportArtefactsDestroyUrl(projectId, reportId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getSignalsReportArtefactsDiffUrl = (projectId: string, reportId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/reports/${reportId}/artefacts/${id}/diff/`
+}
+
+/**
+ * Fetch the unified diff of a `commit` artefact's branch against the repository default branch via the team's GitHub integration — using the branch's current tip so the diff reflects the latest state of the work, not just the single recorded commit.
+ * @summary Fetch the diff for a commit artefact
+ */
+export const signalsReportArtefactsDiff = async (
+ projectId: string,
+ reportId: string,
+ id: string,
+ options?: RequestInit
+): Promise<CommitDiffResponseApi> => {
+ return apiMutator<CommitDiffResponseApi>(getSignalsReportArtefactsDiffUrl(projectId, reportId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getSignalsReportsBulkStateCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/signals/reports/bulk-state/`
}
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index fab55994f2ff..3e15de448d63 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -77,6 +77,42 @@ export const SignalsReportsStateCreateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Append an artefact to a report (see artefact_type for the writable types). Everything is append-only: log entries (code reference, commit, task run, note) accumulate, while status types (safety / actionability / priority judgments, repo selection, suggested reviewers) are latest-wins — appending a new version supersedes the previous one as the report's canonical status. Content is validated against the type's schema.
+ * @summary Append an artefact to a report
+ */
+export const SignalsReportArtefactsCreateBody = /* @__PURE__ */ zod
+ .object({
+ artefact_type: zod
+ .string()
+ .describe(
+ "The artefact type. One of: actionability_judgment, code_reference, commit, dismissal, note, priority_judgment, repo_selection, safety_judgment, signal_finding, suggested_reviewers, task_run. Log types accumulate; status types (safety_judgment, actionability_judgment, priority_judgment, repo_selection, suggested_reviewers) are latest-wins — appending a new version supersedes the previous one as the report's canonical status."
+ ),
+ content: zod
+ .unknown()
+ .describe(
+ 'The artefact payload as a JSON object or array; shape depends on artefact_type and is validated against its schema.'
+ ),
+ })
+ .describe(
+ "Body for appending an artefact to a report.\n\nEverything is append-only: log artefacts accumulate, status artefacts supersede the previous\nversion (latest-wins). The `content` shape depends on `artefact_type` and is validated\nagainst the type's schema (see `products\/signals\/backend\/artefact_schemas.py`)."
+ )
+
+/**
+ * Replace the content of an existing artefact, addressed by id. The new content is validated against the artefact's type schema. Editing the latest row of a status type changes the report's canonical status (latest-wins); to re-assess while keeping history, append a new artefact instead. Attribution is creation-time only — edits don't reassign it.
+ * @summary Replace an artefact's content
+ */
+export const SignalsReportArtefactsPartialUpdateBody = /* @__PURE__ */ zod
+ .object({
+ content: zod
+ .unknown()
+ .optional()
+ .describe("The new artefact payload as a JSON object or array, matching the artefact type's schema."),
+ })
+ .describe(
+ "Body for replacing the content of an existing artefact (addressed by id).\n\nPer-type schema validation happens in the view, which knows the artefact's type."
+ )
+
/**
* Transition many reports to a new state in one call.
*
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index e4a9d33d923d..075ee82ad11a 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -18,6 +18,93 @@ tools:
inbox-processing-pause-update:
operation: signals_processing_pause_update
enabled: false
+ inbox-report-artefacts-create:
+ operation: signals_report_artefacts_create
+ enabled: true
+ scopes:
+ - task:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ enrich_url: '{report_id}'
+ title: Append an artefact to a report
+ description: >
+ Append an artefact to a signal report so it reads as a living document. Everything is append-only. Log types
+ accumulate — `code_reference` (a contiguous span of source lines, at most 20: file_path, start_line,
+ end_line, contents, relevance_note; a single line is just start_line == end_line), `commit` (one commit that
+ has already been pushed to a remote branch: repository, branch, commit_sha, message — usually recorded
+ automatically when you push via git_signed_commit. Only create one yourself for a commit pushed to a remote
+ by other means; never record a commit that is not on a remote branch — an unpushed or local-only commit is
+ always a mistake), `task_run` (associates a tasks.Task with the report — this IS the task↔report
+ association: content.task_id defaults to your own task, product/type label the run and default to
+ tasks/agent_run, and re-associating an already-linked task is idempotent, returning the existing entry),
+ `note` (free-form: note). Status types are latest-wins — appending a new version supersedes the previous one
+ as the report's canonical status: `priority_judgment` (explanation, priority P0–P4),
+ `actionability_judgment` (explanation, actionability, already_addressed), `safety_judgment` (choice),
+ `repo_selection` (repository, reason), `suggested_reviewers` (a list of {github_login}). Status judgments
+ are consequential, not advisory: the canonical priority/actionability steer what humans and agents pick up
+ next, and PostHog's automation uses them when deciding which reports to act on. `content` is a JSON object
+ matching the chosen type and is validated against its schema. Writes are attributed to your task
+ automatically. Returns the created artefact including its id.
+ inbox-report-artefacts-delete:
+ operation: signals_report_artefacts_destroy
+ enabled: true
+ scopes:
+ - task:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Delete an artefact
+ description: >
+ Delete an artefact by its id when it is no longer correct or relevant. Deleting the latest row of a status
+ type (e.g. priority_judgment) reverts the report's canonical status to the previous version.
+ inbox-report-artefacts-list:
+ operation: signals_report_artefacts_list
+ enabled: true
+ scopes:
+ - task:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List a report's artefacts
+ description: >
+ List every artefact on a signal report — the full picture of why it exists and what has been done about it:
+ `signal_finding` entries (the evidence behind the report), status judgments (safety / actionability /
+ priority, repo_selection, suggested_reviewers — the newest row of each status type is the canonical status),
+ and work-log entries (code references, commits, task runs, notes). Read this before re-judging a status or
+ adding to the log.
+ inbox-report-artefacts-retrieve:
+ operation: signals_report_artefacts_retrieve
+ enabled: true
+ scopes:
+ - task:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ enrich_url: '{params.report_id}'
+ title: Get a single artefact
+ description: >
+ Get one artefact by id. Content is parsed (and suggested_reviewers enriched with PostHog user info) the same
+ way as inbox-report-artefacts-list.
+ inbox-report-artefacts-update:
+ operation: signals_report_artefacts_partial_update
+ enabled: true
+ scopes:
+ - task:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Replace an artefact's content
+ description: >
+ Replace the `content` of an existing artefact, addressed by its id, when new information supersedes it. The
+ new content is validated against the artefact type's schema. Editing the latest row of a status type changes
+ the report's canonical status; to re-assess while keeping history, append a new artefact instead.
inbox-reports-bulk-set-state:
operation: signals_reports_bulk_state_create
enabled: true
@@ -53,9 +140,22 @@ 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), and
- suggested_reviewers (PostHog user UUIDs). Results are paginated and ordered by
+ 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). 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.
+ 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."
response:
include:
- id
@@ -88,8 +188,25 @@ tools:
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. To inspect the underlying signals or judgment artefacts, follow up with a HogQL
- query (see the 'signals' skill) — those endpoints are not yet exposed via MCP.
+ 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."
inbox-reports-set-state:
operation: signals_reports_state_create
enabled: true
@@ -204,6 +321,9 @@ tools:
required; `enabled` and `config` are optional and keep their current values if omitted). Prefer
`inbox-source-configs-partial-update` when you only need to flip `enabled` or tweak `config`. Enabling the
session_analysis_cluster source requires the organization to have approved AI data processing.
+ signals-report-artefacts-diff:
+ operation: signals_report_artefacts_diff
+ enabled: false
signals-scout-config-create:
operation: signals_scout_config_create
enabled: true
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 01af3089a832..2726200c6fa7 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -2994,7 +2994,8 @@ def _handle_signals_dismiss_report(payload: dict) -> HttpResponse:
slack_user_id = payload.get("user", {}).get("id", "")
# Only PostHog org members may dismiss — a non-member in a shared channel must not suppress reports.
- if _is_org_member(integration, slack_user_id) is None:
+ org_member = _is_org_member(integration, slack_user_id)
+ if org_member is None:
logger.warning(
"signals_dismiss_report_not_org_member",
integration_id=integration.id,
@@ -3002,7 +3003,9 @@ def _handle_signals_dismiss_report(payload: dict) -> HttpResponse:
)
return HttpResponse(status=200)
- suppressed = dismiss_report_from_slack(report_team_id, str(report_id), slack_user_id=slack_user_id)
+ suppressed = dismiss_report_from_slack(
+ report_team_id, str(report_id), slack_user_id=slack_user_id, user_id=org_member.id
+ )
_post_signals_dismiss_feedback(payload, dismissed=suppressed, slack_user_id=slack_user_id)
return HttpResponse(status=200)
diff --git a/products/slack_app/backend/tests/test_posthog_code_interactivity.py b/products/slack_app/backend/tests/test_posthog_code_interactivity.py
index ade48a77aca6..10b2004d7726 100644
--- a/products/slack_app/backend/tests/test_posthog_code_interactivity.py
+++ b/products/slack_app/backend/tests/test_posthog_code_interactivity.py
@@ -768,6 +768,8 @@ class TestSignalsDismissReport(TestCase):
self.organization = Organization.objects.create(name="Dismiss Org")
self.team = Team.objects.create(organization=self.organization, name="Dismiss Team")
+ self.user = User.objects.create(email="[email protected]", distinct_id="dismiss-user-1")
+ OrganizationMembership.objects.create(user=self.user, organization=self.organization)
self.integration = Integration.objects.create(
team=self.team,
kind="slack",
@@ -826,7 +828,7 @@ class TestSignalsDismissReport(TestCase):
from products.signals.backend.models import SignalReport, SignalReportArtefact
mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
- mock_is_org_member.return_value = MagicMock() # clicker resolves to an org member
+ mock_is_org_member.return_value = self.user # clicker resolves to this org member
report = self._make_ready_report()
response = self._post_interactivity(self._dismiss_payload(str(report.id)))
@@ -834,9 +836,9 @@ class TestSignalsDismissReport(TestCase):
assert response.status_code == 200
report.refresh_from_db()
assert report.status == SignalReport.Status.SUPPRESSED
- assert SignalReportArtefact.objects.filter(
- report=report, type=SignalReportArtefact.ArtefactType.DISMISSAL
- ).exists()
+ dismissal = SignalReportArtefact.objects.get(report=report, type=SignalReportArtefact.ArtefactType.DISMISSAL)
+ # Attributed to the resolved PostHog user, not system.
+ assert dismissal.created_by_id == self.user.id
# The original message is replaced with a dismissed acknowledgement.
assert mock_requests_post.call_args.kwargs["json"]["replace_original"] is True
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index d25345f8c099..14654b6ffdb8 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -455,21 +455,25 @@ def get_latest_pr_url_by_task(task_ids: Iterable[str | UUID]) -> dict[str, str]:
return {str(row["task_id"]): row["output_pr_url_text"] for row in rows if row["output_pr_url_text"]}
-def task_run_pr_url_exists_subquery(**task_run_filter) -> Exists:
- """``Exists`` over runs matching ``task_run_filter`` that produced a non-empty output.pr_url.
-
- The caller supplies the correlation filter (e.g. ``task__signal_report_tasks__report_id=
- OuterRef("id")`` plus its own relationship value). Returns a query expression to embed in
- the caller's queryset — no ORM instances cross the boundary, and the tasks facade stays
- free of the caller's domain.
+def task_run_pr_url_exists_subquery(*conditions: Q, **task_run_filter) -> Exists:
+ """``Exists`` over runs matching the supplied correlation that produced a non-empty output.pr_url.
+
+ The caller supplies the report→run correlation as keyword lookups (e.g.
+ ``task__signal_report_tasks__report_id=OuterRef("id")``) and/or positional ``Q`` objects (e.g.
+ an ``OR`` of two ``task_id__in`` subqueries the caller builds). Returns a query expression to
+ embed in the caller's queryset — no ORM instances cross the boundary, and the tasks facade
+ stays free of the caller's domain.
"""
- return Exists(TaskRun.objects.filter(**task_run_filter, output__pr_url__isnull=False).exclude(output__pr_url=""))
+ return Exists(
+ TaskRun.objects.filter(*conditions, output__pr_url__isnull=False, **task_run_filter).exclude(output__pr_url="")
+ )
-def latest_task_run_pr_url_subquery(**task_run_filter) -> Subquery:
- """``Subquery`` of the latest non-empty output.pr_url for runs matching ``task_run_filter``."""
+def latest_task_run_pr_url_subquery(*conditions: Q, **task_run_filter) -> Subquery:
+ """``Subquery`` of the latest non-empty output.pr_url for runs matching the supplied correlation
+ (keyword lookups and/or positional ``Q`` objects — see ``task_run_pr_url_exists_subquery``)."""
return Subquery(
- TaskRun.objects.filter(**task_run_filter, output__pr_url__isnull=False)
+ TaskRun.objects.filter(*conditions, output__pr_url__isnull=False, **task_run_filter)
.exclude(output__pr_url="")
.order_by("-created_at")
.annotate(output_pr_url_text=KeyTextTransform("pr_url", "output"))
@@ -2066,7 +2070,9 @@ def _trigger_task_processing_workflow(
parse_run_state,
)
- full_mcp_run_sources = frozenset({None, RunSource.MANUAL})
+ # SIGNAL_REPORT: implementation runs log their work on the report (notes, code references)
+ # via the task:write artefact tools.
+ full_mcp_run_sources = frozenset({None, RunSource.MANUAL, RunSource.SIGNAL_REPORT})
run_source = parse_run_state(run.state).run_source
posthog_mcp_scopes: Literal["read_only", "full"] = "full" if run_source in full_mcp_run_sources else "read_only"
try:
@@ -2509,8 +2515,8 @@ def create_task(team_id: int, user_id: int | None, *, validated_data: dict) -> c
"""
from posthog.models import Team # noqa: PLC0415
- from products.signals.backend.models import ( # noqa: PLC0415 — cross-product write kept off the api import path
- SignalReportTask,
+ from products.signals.backend.task_run_artefacts import ( # noqa: PLC0415 — cross-product write kept off the api import path
+ record_implementation_task,
)
from products.tasks.backend.logic.services.title_generator import generate_task_title # noqa: PLC0415
from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path
@@ -2525,10 +2531,9 @@ def create_task(team_id: int, user_id: int | None, *, validated_data: dict) -> c
if user_id is not None:
validated_data["created_by"] = User.objects.get(id=user_id)
- link_relationship = validated_data.pop(
- "signal_report_task_relationship",
- SignalReportTask.Relationship.IMPLEMENTATION,
- )
+ # Only IMPLEMENTATION is accepted; pop it so it isn't forwarded to the model. The link itself
+ # is recorded by record_implementation_task below.
+ validated_data.pop("signal_report_task_relationship", None)
if not validated_data.get("github_integration"):
default_integration = Integration.objects.filter(team=team, kind="github").first()
@@ -2562,11 +2567,12 @@ def create_task(team_id: int, user_id: int | None, *, validated_data: dict) -> c
with transaction.atomic():
task = Task.objects.create(**validated_data)
if task.signal_report_id and task.origin_product == Task.OriginProduct.SIGNAL_REPORT:
- SignalReportTask.objects.create(
+ # Dual-write the implementation gate row + task_run work-log artefact (see
+ # record_implementation_task) so a manually-started task matches autostarted ones.
+ record_implementation_task(
team_id=task.team_id,
- report_id=task.signal_report_id,
- task=task,
- relationship=link_relationship,
+ report_id=str(task.signal_report_id),
+ task_id=str(task.id),
)
return _task_detail_to_dto(_task_detail_queryset().get(pk=task.pk))
diff --git a/products/tasks/backend/facade/repo_selection_types.py b/products/tasks/backend/facade/repo_selection_types.py
new file mode 100644
index 000000000000..f85638722ff8
--- /dev/null
+++ b/products/tasks/backend/facade/repo_selection_types.py
@@ -0,0 +1,11 @@
+"""Lightweight facade re-export of the repo-selection result type.
+
+Kept separate from ``facade.repo_selection`` so callers that only need the framework-free
+``RepoSelectionResult`` model don't pull in the repo-selection agent/sandbox/LLM runtime that
+``select_repository`` drags in. This matters for modules on the ``django.setup()`` import path
+(e.g. signals' ``artefact_schemas``), which must stay dependency-light.
+"""
+
+from products.tasks.backend.logic.repo_selection.types import RepoSelectionResult
+
+__all__ = ["RepoSelectionResult"]
diff --git a/products/tasks/backend/logic/repo_selection/__init__.py b/products/tasks/backend/logic/repo_selection/__init__.py
index 144ed43099a6..30205bd0e641 100644
--- a/products/tasks/backend/logic/repo_selection/__init__.py
+++ b/products/tasks/backend/logic/repo_selection/__init__.py
@@ -1,12 +1,19 @@
-from products.tasks.backend.logic.repo_selection.agent import (
- REPO_SELECTION_DUMMY_REPOSITORY,
- RepoSelectionRejectedError,
- RepoSelectionResult,
- RepoSelectionUnavailableError,
- resolve_team_github_integration,
- select_repository,
-)
-from products.tasks.backend.logic.repo_selection.cascade import select_repository_for_message
+from typing import TYPE_CHECKING
+
+from products.tasks.backend.logic.repo_selection.types import RepoSelectionResult
+
+if TYPE_CHECKING:
+ # Visible to type checkers (so re-exports keep their real types, e.g. the exception classes
+ # used in `except` clauses) without triggering the heavy runtime import — `__getattr__` below
+ # loads them lazily at runtime.
+ from products.tasks.backend.logic.repo_selection.agent import (
+ REPO_SELECTION_DUMMY_REPOSITORY,
+ RepoSelectionRejectedError,
+ RepoSelectionUnavailableError,
+ resolve_team_github_integration,
+ select_repository,
+ )
+ from products.tasks.backend.logic.repo_selection.cascade import select_repository_for_message
__all__ = [
"REPO_SELECTION_DUMMY_REPOSITORY",
@@ -17,3 +24,29 @@ __all__ = [
"select_repository",
"select_repository_for_message",
]
+
+# Everything except the leaf `RepoSelectionResult` DTO lives in `agent.py` / `cascade.py`, which
+# pull in the sandbox/LLM runtime on import. Load those lazily so importing this package just for
+# the DTO (e.g. from the dependency-light Signals artefact schemas) stays cheap and cycle-free.
+_LAZY_FROM_AGENT = frozenset(
+ {
+ "REPO_SELECTION_DUMMY_REPOSITORY",
+ "RepoSelectionRejectedError",
+ "RepoSelectionUnavailableError",
+ "resolve_team_github_integration",
+ "select_repository",
+ }
+)
+_LAZY_FROM_CASCADE = frozenset({"select_repository_for_message"})
+
+
+def __getattr__(name: str) -> object:
+ if name in _LAZY_FROM_AGENT:
+ from products.tasks.backend.logic.repo_selection import agent
+
+ return getattr(agent, name)
+ if name in _LAZY_FROM_CASCADE:
+ from products.tasks.backend.logic.repo_selection import cascade
+
+ return getattr(cascade, name)
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/products/tasks/backend/logic/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.py
index 4c1f23d699ea..3055e821fa7a 100644
--- a/products/tasks/backend/logic/repo_selection/agent.py
+++ b/products/tasks/backend/logic/repo_selection/agent.py
@@ -5,8 +5,6 @@ import logging
from collections.abc import Callable
from typing import TYPE_CHECKING
-from pydantic import BaseModel, Field
-
from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.integration_repository_cache import GitHubRepositoryFullCache
@@ -14,6 +12,7 @@ from posthog.models.team.team import Team
from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
from posthog.sync import database_sync_to_async
+from products.tasks.backend.logic.repo_selection.types import RepoSelectionResult
from products.tasks.backend.logic.services.custom_prompt_internals import CustomPromptSandboxContext
from products.tasks.backend.logic.services.custom_prompt_multi_turn_runner import MultiTurnSession
from products.tasks.backend.logic.services.sandbox import SandboxResources
@@ -31,20 +30,6 @@ REPO_SELECTION_DUMMY_REPOSITORY = "PostHog/.github"
_MAX_GITHUB_REPOS = 1000
-class RepoSelectionResult(BaseModel):
- repository: str | None = Field(
- description="Selected repository in 'owner/repo' format, or null if none of the candidates are relevant."
- )
- reason: str = Field(
- description=(
- "Why this repository was selected (or why none matched). When cache queries were made, "
- "cite the specific path matches, README excerpts, or description content that drove the "
- "decision. When no query was made, justify why the choice was unambiguous from the "
- "context and repo names alone."
- )
- )
-
-
class RepoSelectionRejectedError(Exception):
"""Raised when the LLM returns a repository not in the candidate list (hallucination).
@@ -138,7 +123,10 @@ def _build_repo_selection_prompt(context_block: str, candidate_repos: list[str])
rendered to text, or a Slack thread serialized as `user: text` lines. The caller is
responsible for rendering domain-specific data structures into a string before calling.
"""
- schema_json = json.dumps(RepoSelectionResult.model_json_schema(), indent=2)
+ schema = RepoSelectionResult.model_json_schema()
+ # `task_id` is system-set after the run — keep it out of the agent's output contract.
+ schema.get("properties", {}).pop("task_id", None)
+ schema_json = json.dumps(schema, indent=2)
repo_list = "\n".join(f"{i + 1}. `{repo}`" for i, repo in enumerate(candidate_repos))
return f"""You are a repository selection agent. Decide which GitHub repository in the candidate list
@@ -392,6 +380,9 @@ async def select_repository(
# Track repo discovery execution (for example, for Slack)
if on_research_session is not None:
on_research_session(str(session.task.id), str(session.task_run.id))
+ # Stamp the producing task onto the result (overwriting anything the LLM may have emitted)
+ # so downstream persistence can attribute the selection to it.
+ result.task_id = str(session.task.id)
try:
if result.repository is not None:
result.repository = result.repository.strip().lower()
diff --git a/products/tasks/backend/logic/repo_selection/types.py b/products/tasks/backend/logic/repo_selection/types.py
new file mode 100644
index 000000000000..3860ff39acf2
--- /dev/null
+++ b/products/tasks/backend/logic/repo_selection/types.py
@@ -0,0 +1,31 @@
+from __future__ import annotations
+
+from pydantic import BaseModel, Field
+
+
+class RepoSelectionResult(BaseModel):
+ """Outcome of repository selection: the chosen repo (or none) and why.
+
+ Lives in this leaf module (pydantic only) so it can be shared by dependency-light consumers
+ — notably the Signals artefact schema registry — without pulling in the sandbox/LLM runtime
+ that `agent.py` imports.
+ """
+
+ repository: str | None = Field(
+ description="Selected repository in 'owner/repo' format, or null if none of the candidates are relevant."
+ )
+ reason: str = Field(
+ description=(
+ "Why this repository was selected (or why none matched). When cache queries were made, "
+ "cite the specific path matches, README excerpts, or description content that drove the "
+ "decision. When no query was made, justify why the choice was unambiguous from the "
+ "context and repo names alone."
+ )
+ )
+ # Set by `select_repository` after the sandbox session, never by the LLM (it is stripped from
+ # the prompt's JSON schema). Optional with a default so persisted results and in-flight
+ # Temporal payloads from before the field existed still validate.
+ task_id: str | None = Field(
+ default=None,
+ description="UUID of the sandbox task that performed the selection, when an agent ran.",
+ )
diff --git a/products/tasks/backend/management/commands/demo_mts_example.py b/products/tasks/backend/management/commands/demo_mts_example.py
index 4cd7271d7582..20fd07e6ec9e 100644
--- a/products/tasks/backend/management/commands/demo_mts_example.py
+++ b/products/tasks/backend/management/commands/demo_mts_example.py
@@ -87,19 +87,21 @@ class Command(BaseCommand):
self.stdout.write(self.style.SUCCESS(f"Title: {result.title}"))
self.stdout.write(f"Summary: {result.summary}")
self.stdout.write("")
+ actionability = result.effective_actionability()
self.stdout.write(
- f"Actionability: {result.actionability.actionability.value} "
- f"(already_addressed={result.actionability.already_addressed})"
+ f"Actionability: {actionability.actionability.value} (already_addressed={actionability.already_addressed})"
)
- self.stdout.write(f" Reason: {result.actionability.explanation}")
- if result.priority:
- self.stdout.write(f"Priority: {result.priority.priority.value}")
- self.stdout.write(f" Reason: {result.priority.explanation}")
+ self.stdout.write(f" Reason: {actionability.explanation}")
+ priority = result.effective_priority()
+ if priority:
+ self.stdout.write(f"Priority: {priority.priority.value}")
+ self.stdout.write(f" Reason: {priority.explanation}")
else:
self.stdout.write("Priority: N/A (not actionable)")
self.stdout.write("")
- for i, finding in enumerate(result.findings, start=1):
- self.stdout.write(self.style.WARNING(f"--- Finding {i}/{len(result.findings)} ({finding.signal_id}) ---"))
+ findings = result.effective_findings()
+ for i, finding in enumerate(findings, start=1):
+ self.stdout.write(self.style.WARNING(f"--- Finding {i}/{len(findings)} ({finding.signal_id}) ---"))
self.stdout.write(f" Paths: {', '.join(finding.relevant_code_paths) or '(none)'}")
self.stdout.write(f" Verified: {finding.verified}")
for sha, reason in finding.relevant_commit_hashes.items():
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 01611bdf1a26..282b0fee16ec 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -202,8 +202,8 @@ class TaskRunDetailSerializer(DataclassSerializer):
# Only implementation is supported when linking a task to a report from the public task API
# (e.g. PostHog Code inbox); research/repo-selection links are created by server-side flows.
-# The value/label mirror `signals` `SignalReportTask.Relationship.IMPLEMENTATION` — kept inline
-# so presentation never imports the other product's models.
+# Mirrors `signals` `task_run_artefacts.TASK_RUN_TYPE_IMPLEMENTATION` — kept inline
+# so presentation never imports the other product's internals.
SIGNAL_REPORT_TASK_RELATIONSHIP_IMPLEMENTATION = "implementation"
diff --git a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
index dac2a26f8917..b808b931c8ef 100644
--- a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
@@ -142,6 +142,7 @@ def _refresh_sandbox_mcp(
project_id=task_run.team_id,
scopes=scopes,
interaction_origin=(task_run.state or {}).get("interaction_origin"),
+ task_id=str(task_run.task_id),
)
if task.created_by_id:
user_mcp_configs = get_user_mcp_server_configs(
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index 6865d1d3597a..57180ff67b51 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -158,6 +158,7 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
project_id=ctx.team_id,
scopes=scopes,
interaction_origin=ctx.interaction_origin,
+ task_id=str(ctx.task_id),
)
if task.created_by_id:
user_mcp_configs = get_user_mcp_server_configs(
diff --git a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
index 471fb3f60f3e..c0b48330b34f 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
@@ -44,6 +44,7 @@ def _make_task_run_mock(team_id: int = 7, created_by_id: int | None = 42, state:
task_run.id = "run-1"
task_run.team_id = team_id
task_run.task = task
+ task_run.task_id = "task-1"
# Default to None so `(task_run.state or {}).get(...)` returns None cleanly.
# MagicMock auto-attributes would otherwise return further MagicMock objects
# and leak into kwargs passed to `get_sandbox_ph_mcp_configs`.
@@ -71,7 +72,7 @@ class TestRefreshSandboxMcp:
mock_oauth.assert_called_once_with(task_run.task, scopes="read_only")
mock_ph_configs.assert_called_once_with(
- token="fresh-token", project_id=7, scopes="read_only", interaction_origin=None
+ token="fresh-token", project_id=7, scopes="read_only", interaction_origin=None, task_id="task-1"
)
mock_user_configs.assert_called_once_with(token="fresh-token", team_id=7, user_id=42, interaction_origin=None)
mock_send_refresh.assert_called_once()
@@ -207,7 +208,7 @@ class TestRefreshSandboxMcp:
mock_oauth.assert_called_once_with(mock_oauth.call_args.args[0], scopes="full")
mock_ph_configs.assert_called_once_with(
- token="fresh-token", project_id=7, scopes="full", interaction_origin=None
+ token="fresh-token", project_id=7, scopes="full", interaction_origin=None, task_id="task-1"
)
diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.py
index acaadc7e0097..493b895a3caf 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py
@@ -148,6 +148,23 @@ class TestGetSandboxMcpConfigs(TestCase):
mock_settings.SITE_URL = ""
assert get_sandbox_ph_mcp_configs(self.TOKEN, self.PROJECT_ID) == []
+ def test_task_id_adds_attribution_header(self) -> None:
+ with patch("products.tasks.backend.temporal.process_task.utils.settings") as mock_settings:
+ mock_settings.SANDBOX_MCP_URL = None
+ mock_settings.SITE_URL = "https://app.posthog.com"
+ configs = get_sandbox_ph_mcp_configs(self.TOKEN, self.PROJECT_ID, task_id="task-uuid-123")
+ assert configs[0].headers == [
+ *self._expected_headers(),
+ {"name": "X-PostHog-Task-Id", "value": "task-uuid-123"},
+ ]
+
+ def test_no_task_id_omits_attribution_header(self) -> None:
+ with patch("products.tasks.backend.temporal.process_task.utils.settings") as mock_settings:
+ mock_settings.SANDBOX_MCP_URL = None
+ mock_settings.SITE_URL = "https://app.posthog.com"
+ configs = get_sandbox_ph_mcp_configs(self.TOKEN, self.PROJECT_ID)
+ assert all(h["name"] != "X-PostHog-Task-Id" for h in configs[0].headers)
+
@parameterized.expand(
[
(None, "posthog-code"),
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 0753e8b209f3..8aebfa275aeb 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -328,9 +328,14 @@ def get_sandbox_ph_mcp_configs(
*,
scopes: PosthogMcpScopes = "read_only",
interaction_origin: str | None = None,
+ task_id: str | None = None,
) -> list[McpServerConfig]:
"""Return PostHog MCP server configurations for sandbox agents.
+ `task_id` is baked into an `X-PostHog-Task-Id` header so the MCP server (and through it the
+ PostHog API) can deterministically attribute the agent's writes to its task — the LLM never
+ handles its own task id.
+
Uses SANDBOX_MCP_URL if explicitly set, otherwise derives it from SITE_URL:
- app.posthog.com / us.posthog.com → https://mcp.posthog.com/mcp
- eu.posthog.com → https://mcp-eu.posthog.com/mcp
@@ -348,6 +353,8 @@ def get_sandbox_ph_mcp_configs(
{"name": "x-posthog-read-only", "value": str(read_only).lower()},
{"name": "x-posthog-mcp-consumer", "value": _resolve_mcp_consumer(interaction_origin)},
]
+ if task_id:
+ headers.append({"name": "X-PostHog-Task-Id", "value": str(task_id)})
return [McpServerConfig(type="http", name="posthog", url=url, headers=headers)]
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 429653a62b7b..8572a1920ddc 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -967,6 +967,7 @@ class TestTaskAPI(BaseTaskAPITest):
def test_create_task_with_signal_report_same_team(self):
from products.signals.backend.models import SignalReport, SignalReportTask
+ from products.signals.backend.task_run_artefacts import TASK_RUN_TYPE_IMPLEMENTATION, signals_task_ids
report = SignalReport.objects.create(team=self.team)
response = self.client.post(
@@ -976,18 +977,23 @@ class TestTaskAPI(BaseTaskAPITest):
"description": "From a signal report",
"origin_product": "signal_report",
"signal_report": str(report.id),
- "signal_report_task_relationship": SignalReportTask.Relationship.IMPLEMENTATION.value,
+ # Legacy field old clients still send — accepted and ignored.
+ "signal_report_task_relationship": "implementation",
},
format="json",
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
data = response.json()
self.assertEqual(data["signal_report"], str(report.id))
- link = SignalReportTask.objects.get(
- report=report,
- relationship=SignalReportTask.Relationship.IMPLEMENTATION,
+ # A manual "start implementation" records the implementation task_run artefact (the
+ # task↔report association and work-log entry) and writes the legacy SignalReportTask gate
+ # row that blocks the auto-start pipeline from double-starting.
+ self.assertEqual(signals_task_ids(report_id=str(report.id), type=TASK_RUN_TYPE_IMPLEMENTATION), [data["id"]])
+ self.assertTrue(
+ SignalReportTask.objects.filter(
+ report=report, task_id=data["id"], relationship=TASK_RUN_TYPE_IMPLEMENTATION
+ ).exists()
)
- self.assertEqual(str(link.task_id), data["id"])
def test_create_task_with_signal_report_different_team_rejected(self):
from products.signals.backend.models import SignalReport
@@ -1194,7 +1200,8 @@ class TestTaskAPI(BaseTaskAPITest):
[
("run_source_omitted", None, "full"),
("manual", {"run_source": "manual"}, "full"),
- ("signal_report", {"run_source": "signal_report"}, "read_only"),
+ # signal_report implementation runs log their work as report artefacts (task:write tools).
+ ("signal_report", {"run_source": "signal_report"}, "full"),
]
)
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.py
index f661531cd659..e847f0a54728 100644
--- a/products/tasks/backend/tests/test_webhooks.py
+++ b/products/tasks/backend/tests/test_webhooks.py
@@ -15,7 +15,8 @@ from posthog.models.organization import Organization
from posthog.models.team.team import Team
from posthog.models.user import User
-from products.signals.backend.models import SignalReport, SignalReportTask
+from products.signals.backend.models import SignalReport
+from products.signals.backend.task_run_artefacts import append_task_run_artefact
from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.webhooks import find_task_run
@@ -391,11 +392,12 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
title="Test report",
summary="Test summary",
)
- SignalReportTask.objects.create(
- team=self.team,
- report=self.report,
- task=self.task,
- relationship=SignalReportTask.Relationship.IMPLEMENTATION,
+ 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),
)
def _post_pr_webhook(self, action: str, merged: bool):
@@ -461,7 +463,9 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_merge_on_task_without_linked_report_is_a_noop(self, _mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
- SignalReportTask.objects.filter(task=self.task).delete()
+ from products.signals.backend.models import SignalReportArtefact
+
+ SignalReportArtefact.objects.filter(task=self.task).delete()
response = self._post_pr_webhook(action="closed", merged=True)
diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.py
index 2e56e5b013da..5a91b09dc285 100644
--- a/products/tasks/backend/webhooks.py
+++ b/products/tasks/backend/webhooks.py
@@ -239,7 +239,7 @@ def _resolve_signal_reports_for_task(task_id: uuid.UUID, pr_url: str) -> None:
since GitHub retries 5xx responses and we've already acknowledged the PR event.
"""
reports = (
- SignalReport.objects.filter(report_tasks__task_id=task_id)
+ SignalReport.objects.filter(SignalReport.reports_for_task_filter(task_id))
.exclude(
status__in=[
SignalReport.Status.RESOLVED,
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 99593628aa9b..bb74e9a1c102 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -3658,6 +3658,76 @@
},
"feature_flag": "heatmaps-mcp"
},
+ "inbox-report-artefacts-create": {
+ "description": "Append an artefact to a signal report so it reads as a living document. Everything is append-only. Log types accumulate — `code_reference` (a contiguous span of source lines, at most 20: file_path, start_line, end_line, contents, relevance_note; a single line is just start_line == end_line), `commit` (one commit that has already been pushed to a remote branch: repository, branch, commit_sha, message — usually recorded automatically when you push via git_signed_commit. Only create one yourself for a commit pushed to a remote by other means; never record a commit that is not on a remote branch — an unpushed or local-only commit is always a mistake), `task_run` (associates a tasks.Task with the report — this IS the task↔report association: content.task_id defaults to your own task, product/type label the run and default to tasks/agent_run, and re-associating an already-linked task is idempotent, returning the existing entry), `note` (free-form: note). Status types are latest-wins — appending a new version supersedes the previous one as the report's canonical status: `priority_judgment` (explanation, priority P0–P4), `actionability_judgment` (explanation, actionability, already_addressed), `safety_judgment` (choice), `repo_selection` (repository, reason), `suggested_reviewers` (a list of {github_login}). Status judgments are consequential, not advisory: the canonical priority/actionability steer what humans and agents pick up next, and PostHog's automation uses them when deciding which reports to act on. `content` is a JSON object matching the chosen type and is validated against its schema. Writes are attributed to your task automatically. Returns the created artefact including its id.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Append an artefact to a report",
+ "title": "Append an artefact to a report",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "inbox-report-artefacts-delete": {
+ "description": "Delete an artefact by its id when it is no longer correct or relevant. Deleting the latest row of a status type (e.g. priority_judgment) reverts the report's canonical status to the previous version.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Delete an artefact",
+ "title": "Delete an artefact",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "inbox-report-artefacts-list": {
+ "description": "List every artefact on a signal report — the full picture of why it exists and what has been done about it: `signal_finding` entries (the evidence behind the report), status judgments (safety / actionability / priority, repo_selection, suggested_reviewers — the newest row of each status type is the canonical status), and work-log entries (code references, commits, task runs, notes). Read this before re-judging a status or adding to the log.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "List a report's artefacts",
+ "title": "List a report's artefacts",
+ "required_scopes": ["task:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "inbox-report-artefacts-retrieve": {
+ "description": "Get one artefact by id. Content is parsed (and suggested_reviewers enriched with PostHog user info) the same way as inbox-report-artefacts-list.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Get a single artefact",
+ "title": "Get a single artefact",
+ "required_scopes": ["task:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "inbox-report-artefacts-update": {
+ "description": "Replace the `content` of an existing artefact, addressed by its id, when new information supersedes it. The new content is validated against the artefact type's schema. Editing the latest row of a status type changes the report's canonical status; to re-assess while keeping history, append a new artefact instead.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Replace an artefact's content",
+ "title": "Replace an artefact's content",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"inbox-reports-bulk-set-state": {
"description": "Transition many signal reports to the same state in one call — the bulk form of `inbox-reports-set-state`, for clearing or snoozing a batch of inbox reports without one request per report. Pass `ids` (1–100 report ids) and a `state` ('suppressed' to dismiss, 'potential' to snooze/restore); the optional `dismissal_reason` (same canonical codes as the single-report tool), `dismissal_note`, and `snooze_for` apply to every id. Each id is processed independently, so the whole call returns 200 even on partial failure: inspect `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.",
"category": "Signals",
@@ -3673,7 +3743,7 @@
}
},
"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), and suggested_reviewers (PostHog user UUIDs). Results are paginated and ordered by '-is_suggested_reviewer,status,-updated_at' by default.",
+ "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). 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.",
"category": "Signals",
"feature": "signals",
"summary": "List signal reports",
@@ -3687,7 +3757,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. To inspect the underlying signals or judgment artefacts, follow up with a HogQL query (see the 'signals' skill) — those endpoints are not yet exposed via MCP.",
+ "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.",
"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 cd6133e42059..4d6c152b0b67 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3926,6 +3926,76 @@
},
"feature_flag": "heatmaps-mcp"
},
+ "inbox-report-artefacts-create": {
+ "description": "Append an artefact to a signal report so it reads as a living document. Everything is append-only. Log types accumulate — `code_reference` (a contiguous span of source lines, at most 20: file_path, start_line, end_line, contents, relevance_note; a single line is just start_line == end_line), `commit` (one commit that has already been pushed to a remote branch: repository, branch, commit_sha, message — usually recorded automatically when you push via git_signed_commit. Only create one yourself for a commit pushed to a remote by other means; never record a commit that is not on a remote branch — an unpushed or local-only commit is always a mistake), `task_run` (associates a tasks.Task with the report — this IS the task↔report association: content.task_id defaults to your own task, product/type label the run and default to tasks/agent_run, and re-associating an already-linked task is idempotent, returning the existing entry), `note` (free-form: note). Status types are latest-wins — appending a new version supersedes the previous one as the report's canonical status: `priority_judgment` (explanation, priority P0–P4), `actionability_judgment` (explanation, actionability, already_addressed), `safety_judgment` (choice), `repo_selection` (repository, reason), `suggested_reviewers` (a list of {github_login}). Status judgments are consequential, not advisory: the canonical priority/actionability steer what humans and agents pick up next, and PostHog's automation uses them when deciding which reports to act on. `content` is a JSON object matching the chosen type and is validated against its schema. Writes are attributed to your task automatically. Returns the created artefact including its id.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Append an artefact to a report",
+ "title": "Append an artefact to a report",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "inbox-report-artefacts-delete": {
+ "description": "Delete an artefact by its id when it is no longer correct or relevant. Deleting the latest row of a status type (e.g. priority_judgment) reverts the report's canonical status to the previous version.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Delete an artefact",
+ "title": "Delete an artefact",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "inbox-report-artefacts-list": {
+ "description": "List every artefact on a signal report — the full picture of why it exists and what has been done about it: `signal_finding` entries (the evidence behind the report), status judgments (safety / actionability / priority, repo_selection, suggested_reviewers — the newest row of each status type is the canonical status), and work-log entries (code references, commits, task runs, notes). Read this before re-judging a status or adding to the log.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "List a report's artefacts",
+ "title": "List a report's artefacts",
+ "required_scopes": ["task:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "inbox-report-artefacts-retrieve": {
+ "description": "Get one artefact by id. Content is parsed (and suggested_reviewers enriched with PostHog user info) the same way as inbox-report-artefacts-list.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Get a single artefact",
+ "title": "Get a single artefact",
+ "required_scopes": ["task:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "inbox-report-artefacts-update": {
+ "description": "Replace the `content` of an existing artefact, addressed by its id, when new information supersedes it. The new content is validated against the artefact type's schema. Editing the latest row of a status type changes the report's canonical status; to re-assess while keeping history, append a new artefact instead.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Replace an artefact's content",
+ "title": "Replace an artefact's content",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"inbox-reports-bulk-set-state": {
"description": "Transition many signal reports to the same state in one call — the bulk form of `inbox-reports-set-state`, for clearing or snoozing a batch of inbox reports without one request per report. Pass `ids` (1–100 report ids) and a `state` ('suppressed' to dismiss, 'potential' to snooze/restore); the optional `dismissal_reason` (same canonical codes as the single-report tool), `dismissal_note`, and `snooze_for` apply to every id. Each id is processed independently, so the whole call returns 200 even on partial failure: inspect `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.",
"category": "Signals",
@@ -3941,7 +4011,7 @@
}
},
"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), and suggested_reviewers (PostHog user UUIDs). Results are paginated and ordered by '-is_suggested_reviewer,status,-updated_at' by default.",
+ "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). 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.",
"category": "Signals",
"feature": "signals",
"summary": "List signal reports",
@@ -3955,7 +4025,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. To inspect the underlying signals or judgment artefacts, follow up with a HogQL query (see the 'signals' skill) — those endpoints are not yet exposed via MCP.",
+ "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.",
"category": "Signals",
"feature": "signals",
"summary": "Get signal report",
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index f6a3b4f3050f..15ed54394448 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -878,6 +878,10 @@ function buildResponseFilter(config: ToolConfig): {
function buildEnrichment(config: ToolConfig, category: CategoryConfig, resultVar = 'result'): string {
const baseUrl = config.url_prefix ?? category.url_prefix
+ // agent_note wraps the final returned expression so the note rides the same object the
+ // agent reads — point-of-use guidance without growing the tool description.
+ const noteLiteral = config.agent_note ? JSON.stringify(config.agent_note) : null
+ const noted = (expr: string): string => (noteLiteral ? `withAgentNote(${expr}, ${noteLiteral})` : expr)
if (config.list && config.enrich_url) {
const { prefix, field, suffix, source } = parseEnrichUrl(config.enrich_url)
@@ -888,27 +892,27 @@ function buildEnrichment(config: ToolConfig, category: CategoryConfig, resultVar
`enrich_url '{params.${field}}' is not supported on list tools — list items are enriched from the response array`
)
}
- return [
- ` return await withPostHogUrl(context, {`,
+ const enriched = [
+ `await withPostHogUrl(context, {`,
` ...${resultVar},`,
` results: await Promise.all((${resultVar}.results ?? []).map((item) => withPostHogUrl(context, item, \`${baseUrl}/${prefix}\${item.${field}}${suffix}\`))),`,
` }, '${baseUrl}')`,
- ``,
].join('\n')
+ return ` return ${noted(enriched)}\n`
}
if (config.list) {
- return ` return await withPostHogUrl(context, ${resultVar}, '${baseUrl}')\n`
+ return ` return ${noted(`await withPostHogUrl(context, ${resultVar}, '${baseUrl}')`)}\n`
}
if (config.enrich_url) {
const { prefix, field, suffix, source } = parseEnrichUrl(config.enrich_url)
const sourceExpr = source === 'params' ? `params.${field}` : `${resultVar}.${field}`
- return ` return await withPostHogUrl(context, ${resultVar}, \`${baseUrl}/${prefix}\${${sourceExpr}}${suffix}\`)\n`
+ return ` return ${noted(`await withPostHogUrl(context, ${resultVar}, \`${baseUrl}/${prefix}\${${sourceExpr}}${suffix}\`)`)}\n`
}
- return ` return ${resultVar}\n`
+ return ` return ${noted(resultVar)}\n`
}
// ------------------------------------------------------------------
@@ -932,6 +936,8 @@ function generateToolCode(
responseType: string | undefined
needsWithPostHogUrl: boolean
hasEnrichment: boolean
+ needsWithAgentNote: boolean
+ hasAgentNote: boolean
responseFilterImport: 'pickResponseFields' | 'omitResponseFields' | null
} {
const schemaName = `${toPascalCase(toolName)}Schema`
@@ -1094,6 +1100,13 @@ function generateToolCode(
resultType = responseType ?? 'unknown'
}
+ // agent_note wraps whatever the enrichment produced (or the bare result).
+ const hasAgentNote = !!config.agent_note
+ const needsWithAgentNote = hasAgentNote && !!responseType
+ if (needsWithAgentNote) {
+ resultType = `WithAgentNote<${resultType}>`
+ }
+
const appKey = config.ui_app ?? null
const enrichUsesParams = !!config.enrich_url && parseEnrichUrl(config.enrich_url).source === 'params'
@@ -1126,6 +1139,8 @@ function generateToolCode(
responseType,
needsWithPostHogUrl,
hasEnrichment,
+ needsWithAgentNote,
+ hasAgentNote,
responseFilterImport: responseFilter.helperImport,
}
}
@@ -1154,6 +1169,8 @@ const ${factoryName} = (): ToolBase<typeof ${schemaName}, ${resultType}> => ${fa
responseType,
needsWithPostHogUrl,
hasEnrichment,
+ needsWithAgentNote,
+ hasAgentNote,
responseFilterImport: responseFilter.helperImport,
}
}
@@ -1272,6 +1289,8 @@ function generateCustomSchemaToolCode(
responseType: string | undefined
needsWithPostHogUrl: boolean
hasEnrichment: boolean
+ needsWithAgentNote: boolean
+ hasAgentNote: boolean
responseFilterImport: 'pickResponseFields' | 'omitResponseFields' | null
} {
const pathParamNames = extractPathParams(resolved.path)
@@ -1335,10 +1354,14 @@ function generateCustomSchemaToolCode(
}
}
+ const hasAgentNote = !!config.agent_note
+ const needsWithAgentNote = hasAgentNote && !!responseType
+ const customResultType = needsWithAgentNote ? `WithAgentNote<${responseType}>` : (responseType ?? 'unknown')
+
const code = `
const ${schemaName} = ${baseSchemaExpr}
-const ${factoryName} = (): ToolBase<typeof ${schemaName}, ${responseType ?? 'unknown'}> => ({
+const ${factoryName} = (): ToolBase<typeof ${schemaName}, ${customResultType}> => ({
name: '${toolName}',
schema: ${schemaName},
handler: async (context: Context, params: z.infer<typeof ${schemaName}>) => {
@@ -1355,6 +1378,8 @@ ${handlerBody} },
responseType,
needsWithPostHogUrl: false,
hasEnrichment: false,
+ needsWithAgentNote,
+ hasAgentNote,
responseFilterImport: responseFilter.helperImport,
}
}
@@ -1436,6 +1461,9 @@ function generateCategoryFile(
let hasEnrichment = false
+ let hasWithAgentNote = false
+ let hasAgentNote = false
+
const responseFilterImports = new Set<string>()
for (const [name, config, resolved] of enabledTools) {
@@ -1470,6 +1498,12 @@ function generateCategoryFile(
if (result.hasEnrichment) {
hasEnrichment = true
}
+ if (result.needsWithAgentNote) {
+ hasWithAgentNote = true
+ }
+ if (result.hasAgentNote) {
+ hasAgentNote = true
+ }
if (result.responseFilterImport) {
responseFilterImports.add(result.responseFilterImport)
}
@@ -1601,9 +1635,15 @@ function generateCategoryFile(
if (hasWithPostHogUrl) {
toolUtilsTypeImports.push('WithPostHogUrl')
}
+ if (hasWithAgentNote) {
+ toolUtilsTypeImports.push('WithAgentNote')
+ }
if (hasEnrichment) {
toolUtilsValueImports.push('withPostHogUrl')
}
+ if (hasAgentNote) {
+ toolUtilsValueImports.push('withAgentNote')
+ }
for (const imp of responseFilterImports) {
toolUtilsValueImports.push(imp)
}
diff --git a/services/mcp/scripts/yaml-config-schema.ts b/services/mcp/scripts/yaml-config-schema.ts
index fd9a9d5d8323..a893487ed053 100644
--- a/services/mcp/scripts/yaml-config-schema.ts
+++ b/services/mcp/scripts/yaml-config-schema.ts
@@ -36,6 +36,13 @@ export const ToolConfigSchema = z
* Example: "Time series, aggregations, formulas, comparisons"
*/
system_prompt_hint: z.string().optional(),
+ /**
+ * Brief work-protocol guidance appended to the tool's *response* as `_agentNote`,
+ * so the agent sees it at point of use instead of it growing the always-loaded tool
+ * description. Keep it to a sentence or two and defer details to the referenced
+ * tools' own descriptions.
+ */
+ agent_note: z.string().optional(),
exclude_params: z.array(z.string()).optional(),
include_params: z.array(z.string()).optional(),
/**
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index 3c2c78c8c741..9cadd88a7585 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -119,6 +119,12 @@ export interface ApiConfig {
oauthClientName?: string | undefined
mcpSessionId?: string | undefined
mcpConversationId?: string | undefined
+ /**
+ * Sandbox-provisioned task id (from the inbound `x-posthog-task-id` MCP header). Forwarded
+ * to the PostHog API as `X-PostHog-Task-Id` on every call so writes can be attributed to
+ * the agent's task; the API validates it against the token's team.
+ */
+ taskId?: string | undefined
}
type Endpoint = Record<string, any>
@@ -173,6 +179,8 @@ export class ApiClient {
...(this.config.mcpConversationId
? { 'x-posthog-mcp-conversation-id': this.config.mcpConversationId }
: {}),
+ // Forward the sandbox task id so API writes are attributed to the agent's task.
+ ...(this.config.taskId ? { 'X-PostHog-Task-Id': this.config.taskId } : {}),
'X-PostHog-Client': 'mcp',
}
if (options?.body) {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index fd77bc2e30f6..3d7f21768ca6 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13007,6 +13007,17 @@ export namespace Schemas {
source_comment?: string | null;
}
+ /**
+ * Response for the `commit` artefact diff endpoint — the commit's branch rendered against the
+ * repository default branch.
+ */
+ export interface CommitDiffResponse {
+ /** Unified diff (patch) text of the branch against the repository default branch, from the GitHub compare API. */
+ readonly diff: string;
+ /** True when the diff was too large to return in full and has been truncated. */
+ readonly truncated: boolean;
+ }
+
export interface CompareItem {
label: string;
value: string;
@@ -31498,6 +31509,73 @@ export namespace Schemas {
results: SessionRecordingPlaylist[];
}
+ /**
+ * * `video_segment` - Video Segment
+ * * `safety_judgment` - Safety Judgment
+ * * `actionability_judgment` - Actionability Judgment
+ * * `priority_judgment` - Priority Judgment
+ * * `signal_finding` - Signal Finding
+ * * `repo_selection` - Repo Selection
+ * * `suggested_reviewers` - Suggested Reviewers
+ * * `dismissal` - Dismissal
+ * * `code_reference` - Code Reference
+ * * `commit` - Commit
+ * * `task_run` - Task Run
+ * * `note` - Note
+ */
+ export type SignalReportArtefactTypeEnum = typeof SignalReportArtefactTypeEnum[keyof typeof SignalReportArtefactTypeEnum];
+
+
+ export const SignalReportArtefactTypeEnum = {
+ VideoSegment: 'video_segment',
+ SafetyJudgment: 'safety_judgment',
+ ActionabilityJudgment: 'actionability_judgment',
+ PriorityJudgment: 'priority_judgment',
+ SignalFinding: 'signal_finding',
+ RepoSelection: 'repo_selection',
+ SuggestedReviewers: 'suggested_reviewers',
+ Dismissal: 'dismissal',
+ CodeReference: 'code_reference',
+ Commit: 'commit',
+ TaskRun: 'task_run',
+ Note: 'note',
+ } as const;
+
+ export interface _User {
+ readonly id: number;
+ readonly uuid: string;
+ readonly first_name: string;
+ readonly last_name: string;
+ readonly email: string;
+ }
+
+ export type SignalReportArtefactContent = { [key: string]: unknown } | unknown[];
+
+ export interface SignalReportArtefact {
+ readonly id: string;
+ readonly type: SignalReportArtefactTypeEnum;
+ readonly content: SignalReportArtefactContent;
+ 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. */
+ readonly created_by: _User | null;
+ /**
+ * Task the artefact is attributed to, when an agent produced it. Null for user/system writes.
+ * @nullable
+ */
+ readonly task_id: string | null;
+ }
+
+ export interface PaginatedSignalReportArtefactList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: SignalReportArtefact[];
+ }
+
/**
* * `potential` - Potential
* * `candidate` - Candidate
@@ -38665,6 +38743,16 @@ export namespace Schemas {
custom_tags?: PatchedSessionSummariesConfigCustomTags;
}
+ /**
+ * Body for replacing the content of an existing artefact (addressed by id).
+ *
+ * Per-type schema validation happens in the view, which knows the artefact's type.
+ */
+ export interface PatchedSignalReportArtefactLogUpdate {
+ /** The new artefact payload as a JSON object or array, matching the artefact type's schema. */
+ content?: unknown;
+ }
+
export type ScoutOriginEnum = typeof ScoutOriginEnum[keyof typeof ScoutOriginEnum];
@@ -45614,6 +45702,46 @@ export namespace Schemas {
release_to_everyone?: boolean;
}
+ /**
+ * Body for appending an artefact to a report.
+ *
+ * Everything is append-only: log artefacts accumulate, status artefacts supersede the previous
+ * version (latest-wins). The `content` shape depends on `artefact_type` and is validated
+ * against the type's schema (see `products/signals/backend/artefact_schemas.py`).
+ */
+ export interface SignalReportArtefactLogCreate {
+ /** The artefact type. One of: actionability_judgment, code_reference, commit, dismissal, note, priority_judgment, repo_selection, safety_judgment, signal_finding, suggested_reviewers, task_run. Log types accumulate; status types (safety_judgment, actionability_judgment, priority_judgment, repo_selection, suggested_reviewers) are latest-wins — appending a new version supersedes the previous one as the report's canonical status. */
+ artefact_type: string;
+ /** The artefact payload as a JSON object or array; shape depends on artefact_type and is validated against its schema. */
+ content: unknown;
+ }
+
+ /**
+ * Response shape for the log-artefact create/update endpoints — echoes the stored row.
+ */
+ export interface SignalReportArtefactWriteResponse {
+ /** The artefact's unique id. */
+ readonly id: string;
+ /** The id of the report this artefact belongs to. */
+ readonly report_id: string;
+ /** The artefact type. */
+ readonly type: string;
+ /** The artefact payload, parsed from storage. */
+ readonly content: unknown;
+ /** When the artefact was created. */
+ readonly created_at: string;
+ /**
+ * When the artefact was last written — set on creation and refreshed on each edit. Null only for rows created before this field existed.
+ * @nullable
+ */
+ readonly updated_at: string | null;
+ /**
+ * Task the artefact is attributed to, when an agent produced it. Null for user writes.
+ * @nullable
+ */
+ readonly task_id: string | null;
+ }
+
/**
* * `suppressed` - suppressed
* * `potential` - potential
@@ -45927,14 +46055,6 @@ export namespace Schemas {
emitted_finding_ids: string[];
}
- export interface _User {
- readonly id: number;
- readonly uuid: string;
- readonly first_name: string;
- readonly last_name: string;
- readonly email: string;
- }
-
export interface SignalUserAutonomyConfig {
readonly id: string;
readonly user: _User;
@@ -61637,6 +61757,21 @@ export namespace Schemas {
* Comma-separated list of PostHog user UUIDs. Reports are kept if their suggested reviewers include any of the given users.
*/
suggested_reviewers?: string;
+ /**
+ * Only reports associated with this task (via the report's task associations).
+ */
+ task_id?: string;
+ };
+
+ export type SignalsReportArtefactsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
};
export type SignalsScoutProjectProfileGetParams = {
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 6a958fa9ddb8..e2a39fab44c9 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 22 enabled ops
+ * PostHog API - MCP 27 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -56,6 +56,10 @@ export const SignalsReportsListQueryParams = /* @__PURE__ */ zod.object({
.describe(
'Comma-separated list of PostHog user UUIDs. Reports are kept if their suggested reviewers include any of the given users.'
),
+ task_id: zod
+ .string()
+ .optional()
+ .describe("Only reports associated with this task (via the report's task associations)."),
})
export const SignalsReportsRetrieveParams = /* @__PURE__ */ zod.object({
@@ -135,6 +139,116 @@ export const SignalsReportsStateCreateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * List every artefact on a report — the full work log: signal findings (the evidence behind the report), status judgments (safety / actionability / priority, repo selection, suggested reviewers — the newest row of each status type is canonical), and log entries (code references, commits, task runs, notes). `suggested_reviewers` content is enriched with PostHog user info at read time.
+ * @summary List a report's artefacts
+ */
+export const SignalsReportArtefactsListParams = /* @__PURE__ */ zod.object({
+ 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/."
+ ),
+ report_id: zod.string(),
+})
+
+export const SignalsReportArtefactsListQueryParams = /* @__PURE__ */ zod.object({
+ limit: zod.number().optional().describe('Number of results to return per page.'),
+ offset: zod.number().optional().describe('The initial index from which to return the results.'),
+})
+
+/**
+ * Append an artefact to a report (see artefact_type for the writable types). Everything is append-only: log entries (code reference, commit, task run, note) accumulate, while status types (safety / actionability / priority judgments, repo selection, suggested reviewers) are latest-wins — appending a new version supersedes the previous one as the report's canonical status. Content is validated against the type's schema.
+ * @summary Append an artefact to a report
+ */
+export const SignalsReportArtefactsCreateParams = /* @__PURE__ */ zod.object({
+ 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/."
+ ),
+ report_id: zod.string(),
+})
+
+export const SignalsReportArtefactsCreateHeader = /* @__PURE__ */ zod.object({
+ 'X-PostHog-Task-Id': zod
+ .string()
+ .optional()
+ .describe(
+ 'Task to attribute the artefact to (must belong to this project). Set automatically for sandbox agents; when absent the artefact is attributed to the requesting user.'
+ ),
+})
+
+export const SignalsReportArtefactsCreateBody = /* @__PURE__ */ zod
+ .object({
+ artefact_type: zod
+ .string()
+ .describe(
+ "The artefact type. One of: actionability_judgment, code_reference, commit, dismissal, note, priority_judgment, repo_selection, safety_judgment, signal_finding, suggested_reviewers, task_run. Log types accumulate; status types (safety_judgment, actionability_judgment, priority_judgment, repo_selection, suggested_reviewers) are latest-wins — appending a new version supersedes the previous one as the report's canonical status."
+ ),
+ content: zod
+ .unknown()
+ .describe(
+ 'The artefact payload as a JSON object or array; shape depends on artefact_type and is validated against its schema.'
+ ),
+ })
+ .describe(
+ "Body for appending an artefact to a report.\n\nEverything is append-only: log artefacts accumulate, status artefacts supersede the previous\nversion (latest-wins). The `content` shape depends on `artefact_type` and is validated\nagainst the type's schema (see `products/signals/backend/artefact_schemas.py`)."
+ )
+
+/**
+ * Get one artefact by id, content parsed (and reviewers enriched) the same way as the list.
+ * @summary Get a single artefact
+ */
+export const SignalsReportArtefactsRetrieveParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this signal report artefact.'),
+ 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/."
+ ),
+ report_id: zod.string(),
+})
+
+/**
+ * Replace the content of an existing artefact, addressed by id. The new content is validated against the artefact's type schema. Editing the latest row of a status type changes the report's canonical status (latest-wins); to re-assess while keeping history, append a new artefact instead. Attribution is creation-time only — edits don't reassign it.
+ * @summary Replace an artefact's content
+ */
+export const SignalsReportArtefactsPartialUpdateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this signal report artefact.'),
+ 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/."
+ ),
+ report_id: zod.string(),
+})
+
+export const SignalsReportArtefactsPartialUpdateBody = /* @__PURE__ */ zod
+ .object({
+ content: zod
+ .unknown()
+ .optional()
+ .describe("The new artefact payload as a JSON object or array, matching the artefact type's schema."),
+ })
+ .describe(
+ "Body for replacing the content of an existing artefact (addressed by id).\n\nPer-type schema validation happens in the view, which knows the artefact's type."
+ )
+
+/**
+ * Delete an artefact, addressed by id. Deleting the latest row of a status type reverts the report's canonical status to the previous version (latest-wins over what remains).
+ * @summary Delete an artefact
+ */
+export const SignalsReportArtefactsDestroyParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this signal report artefact.'),
+ 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/."
+ ),
+ report_id: zod.string(),
+})
+
/**
* Transition many reports to a new state in one call.
*
diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.ts
index 03ea48254476..b21dd4a05914 100644
--- a/services/mcp/src/hono/request-context.ts
+++ b/services/mcp/src/hono/request-context.ts
@@ -101,6 +101,7 @@ export class RequestContext {
mcpClientVersion: this.props.mcpClientVersion,
mcpProtocolVersion: this.props.mcpProtocolVersion,
mcpConsumer: this.props.mcpConsumer,
+ taskId: this.props.taskId,
})
}
return this.apiInstance
diff --git a/services/mcp/src/lib/request-properties.ts b/services/mcp/src/lib/request-properties.ts
index d210df5fe01d..af9b29161ed7 100644
--- a/services/mcp/src/lib/request-properties.ts
+++ b/services/mcp/src/lib/request-properties.ts
@@ -27,6 +27,9 @@ export type RequestProperties = {
mcpConversationId?: string | undefined
viaSseRedirect?: boolean | undefined
requestStartTime?: number | undefined
+ // Sandbox-provisioned task id: forwarded to the PostHog API as `X-PostHog-Task-Id` on every
+ // call so writes can be attributed to the agent's task (validated server-side per team).
+ taskId?: string | undefined
// Dev/test-only per-request feature-flag overrides — a JSON object string from
// `?flag_overrides=` or the `x-posthog-flag-overrides` header. Parsed and gated
// to NODE_ENV development/test (fail-closed) in `resolveFeatureFlagOverrides`.
@@ -81,6 +84,7 @@ export function parseRequestProperties(
mcpProtocolVersion: clientInfo.protocolVersion,
mcpVendorClient: sanitizeHeaderValue(header(request, 'x-anthropic-client')),
mode: parseMcpMode(header(request, 'x-posthog-mcp-mode') || params.get('mode')),
+ taskId: sanitizeHeaderValue(header(request, 'x-posthog-task-id')),
transport,
requestStartTime: Date.now(),
featureFlagOverrides: header(request, 'x-posthog-flag-overrides') || params.get('flag_overrides') || undefined,
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 76c0cc9815d5..e67444872fd1 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -3,6 +3,14 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import {
+ SignalsReportArtefactsCreateBody,
+ SignalsReportArtefactsCreateParams,
+ SignalsReportArtefactsDestroyParams,
+ SignalsReportArtefactsListParams,
+ SignalsReportArtefactsListQueryParams,
+ SignalsReportArtefactsPartialUpdateBody,
+ SignalsReportArtefactsPartialUpdateParams,
+ SignalsReportArtefactsRetrieveParams,
SignalsReportsBulkStateCreateBody,
SignalsReportsListQueryParams,
SignalsReportsRetrieveParams,
@@ -29,9 +37,125 @@ import {
SignalsSourceConfigsUpdateBody,
SignalsSourceConfigsUpdateParams,
} from '@/generated/signals/api'
-import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
+import {
+ withPostHogUrl,
+ withAgentNote,
+ pickResponseFields,
+ type WithPostHogUrl,
+ type WithAgentNote,
+} from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+const InboxReportArtefactsCreateSchema = SignalsReportArtefactsCreateParams.omit({ project_id: true }).extend(
+ SignalsReportArtefactsCreateBody.shape
+)
+
+const inboxReportArtefactsCreate = (): ToolBase<
+ typeof InboxReportArtefactsCreateSchema,
+ WithPostHogUrl<Schemas.SignalReportArtefactWriteResponse>
+> => ({
+ name: 'inbox-report-artefacts-create',
+ schema: InboxReportArtefactsCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof InboxReportArtefactsCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.artefact_type !== undefined) {
+ body['artefact_type'] = params.artefact_type
+ }
+ if (params.content !== undefined) {
+ body['content'] = params.content
+ }
+ const result = await context.api.request<Schemas.SignalReportArtefactWriteResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/reports/${encodeURIComponent(String(params.report_id))}/artefacts/`,
+ body,
+ })
+ return await withPostHogUrl(context, result, `/inbox/${result.report_id}`)
+ },
+})
+
+const InboxReportArtefactsDeleteSchema = SignalsReportArtefactsDestroyParams.omit({ project_id: true })
+
+const inboxReportArtefactsDelete = (): ToolBase<typeof InboxReportArtefactsDeleteSchema, unknown> => ({
+ name: 'inbox-report-artefacts-delete',
+ schema: InboxReportArtefactsDeleteSchema,
+ handler: async (context: Context, params: z.infer<typeof InboxReportArtefactsDeleteSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<unknown>({
+ method: 'DELETE',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/reports/${encodeURIComponent(String(params.report_id))}/artefacts/${encodeURIComponent(String(params.id))}/`,
+ })
+ return result
+ },
+})
+
+const InboxReportArtefactsListSchema = SignalsReportArtefactsListParams.omit({ project_id: true }).extend(
+ SignalsReportArtefactsListQueryParams.shape
+)
+
+const inboxReportArtefactsList = (): ToolBase<
+ typeof InboxReportArtefactsListSchema,
+ WithPostHogUrl<Schemas.PaginatedSignalReportArtefactList>
+> => ({
+ name: 'inbox-report-artefacts-list',
+ schema: InboxReportArtefactsListSchema,
+ handler: async (context: Context, params: z.infer<typeof InboxReportArtefactsListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedSignalReportArtefactList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/reports/${encodeURIComponent(String(params.report_id))}/artefacts/`,
+ query: {
+ limit: params.limit,
+ offset: params.offset,
+ },
+ })
+ return await withPostHogUrl(context, result, '/inbox')
+ },
+})
+
+const InboxReportArtefactsRetrieveSchema = SignalsReportArtefactsRetrieveParams.omit({ project_id: true })
+
+const inboxReportArtefactsRetrieve = (): ToolBase<
+ typeof InboxReportArtefactsRetrieveSchema,
+ WithPostHogUrl<Schemas.SignalReportArtefact>
+> => ({
+ name: 'inbox-report-artefacts-retrieve',
+ schema: InboxReportArtefactsRetrieveSchema,
+ handler: async (context: Context, params: z.infer<typeof InboxReportArtefactsRetrieveSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.SignalReportArtefact>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/reports/${encodeURIComponent(String(params.report_id))}/artefacts/${encodeURIComponent(String(params.id))}/`,
+ })
+ return await withPostHogUrl(context, result, `/inbox/${params.report_id}`)
+ },
+})
+
+const InboxReportArtefactsUpdateSchema = SignalsReportArtefactsPartialUpdateParams.omit({ project_id: true }).extend(
+ SignalsReportArtefactsPartialUpdateBody.shape
+)
+
+const inboxReportArtefactsUpdate = (): ToolBase<
+ typeof InboxReportArtefactsUpdateSchema,
+ Schemas.SignalReportArtefactWriteResponse
+> => ({
+ name: 'inbox-report-artefacts-update',
+ schema: InboxReportArtefactsUpdateSchema,
+ handler: async (context: Context, params: z.infer<typeof InboxReportArtefactsUpdateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.content !== undefined) {
+ body['content'] = params.content
+ }
+ const result = await context.api.request<Schemas.SignalReportArtefactWriteResponse>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/reports/${encodeURIComponent(String(params.report_id))}/artefacts/${encodeURIComponent(String(params.id))}/`,
+ body,
+ })
+ return result
+ },
+})
+
const InboxReportsBulkSetStateSchema = SignalsReportsBulkStateCreateBody
const inboxReportsBulkSetState = (): ToolBase<
@@ -71,7 +195,7 @@ const InboxReportsListSchema = SignalsReportsListQueryParams
const inboxReportsList = (): ToolBase<
typeof InboxReportsListSchema,
- WithPostHogUrl<Schemas.PaginatedSignalReportList>
+ WithAgentNote<WithPostHogUrl<Schemas.PaginatedSignalReportList>>
> => ({
name: 'inbox-reports-list',
schema: InboxReportsListSchema,
@@ -90,6 +214,7 @@ const inboxReportsList = (): ToolBase<
source_product: params.source_product,
status: params.status,
suggested_reviewers: params.suggested_reviewers,
+ task_id: params.task_id,
},
})
const filtered = {
@@ -115,22 +240,28 @@ const inboxReportsList = (): ToolBase<
])
),
} as typeof result
- return await withPostHogUrl(
- context,
- {
- ...filtered,
- results: await Promise.all(
- (filtered.results ?? []).map((item) => withPostHogUrl(context, item, `/inbox/${item.id}`))
- ),
- },
- '/inbox'
+ return withAgentNote(
+ await withPostHogUrl(
+ context,
+ {
+ ...filtered,
+ results: await Promise.all(
+ (filtered.results ?? []).map((item) => withPostHogUrl(context, item, `/inbox/${item.id}`))
+ ),
+ },
+ '/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."
)
},
})
const InboxReportsRetrieveSchema = SignalsReportsRetrieveParams.omit({ project_id: true })
-const inboxReportsRetrieve = (): ToolBase<typeof InboxReportsRetrieveSchema, WithPostHogUrl<Schemas.SignalReport>> => ({
+const inboxReportsRetrieve = (): ToolBase<
+ typeof InboxReportsRetrieveSchema,
+ WithAgentNote<WithPostHogUrl<Schemas.SignalReport>>
+> => ({
name: 'inbox-reports-retrieve',
schema: InboxReportsRetrieveSchema,
handler: async (context: Context, params: z.infer<typeof InboxReportsRetrieveSchema>) => {
@@ -139,7 +270,10 @@ const inboxReportsRetrieve = (): ToolBase<typeof InboxReportsRetrieveSchema, Wit
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/reports/${encodeURIComponent(String(params.id))}/`,
})
- return await withPostHogUrl(context, result, `/inbox/${result.id}`)
+ 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."
+ )
},
})
@@ -645,6 +779,11 @@ const signalsScoutScratchpadSearch = (): ToolBase<
})
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'inbox-report-artefacts-create': inboxReportArtefactsCreate,
+ 'inbox-report-artefacts-delete': inboxReportArtefactsDelete,
+ 'inbox-report-artefacts-list': inboxReportArtefactsList,
+ 'inbox-report-artefacts-retrieve': inboxReportArtefactsRetrieve,
+ 'inbox-report-artefacts-update': inboxReportArtefactsUpdate,
'inbox-reports-bulk-set-state': inboxReportsBulkSetState,
'inbox-reports-list': inboxReportsList,
'inbox-reports-retrieve': inboxReportsRetrieve,
diff --git a/services/mcp/src/tools/tool-utils.ts b/services/mcp/src/tools/tool-utils.ts
index bda2ffa6e50a..9e2a810a301f 100644
--- a/services/mcp/src/tools/tool-utils.ts
+++ b/services/mcp/src/tools/tool-utils.ts
@@ -23,6 +23,23 @@ export async function withPostHogUrl<T>(context: Context, result: T, path: strin
return { ...result, _posthogUrl: fullUrl } as WithPostHogUrl<T>
}
+/**
+ * Adds an `_agentNote` field carrying brief point-of-use guidance for the calling agent
+ * (configured per tool via `agent_note` in the YAML definition). For raw array results the
+ * array is wrapped as `{ results, _agentNote }`, mirroring `withPostHogUrl`.
+ */
+export type WithAgentNote<T = unknown> = T extends readonly (infer U)[]
+ ? { results: U[]; _agentNote: string }
+ : T & { _agentNote: string }
+
+/** Adds `_agentNote` to a result. Wraps raw arrays in `{ results, _agentNote }` (see type above). */
+export function withAgentNote<T>(result: T, note: string): WithAgentNote<T> {
+ if (Array.isArray(result)) {
+ return { results: result, _agentNote: note } as unknown as WithAgentNote<T>
+ }
+ return { ...result, _agentNote: note } as WithAgentNote<T>
+}
+
/**
* Pick only fields matching the given dot-path patterns.
* Supports wildcards: `'groups.*.key'` iterates all array items / object keys.
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-create.json
new file mode 100644
index 000000000000..43b77622abd5
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-create.json
@@ -0,0 +1,17 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "artefact_type": {
+ "description": "The artefact type. One of: actionability_judgment, code_reference, commit, dismissal, note, priority_judgment, repo_selection, safety_judgment, signal_finding, suggested_reviewers, task_run. Log types accumulate; status types (safety_judgment, actionability_judgment, priority_judgment, repo_selection, suggested_reviewers) are latest-wins — appending a new version supersedes the previous one as the report's canonical status.",
+ "type": "string"
+ },
+ "content": {
+ "description": "The artefact payload as a JSON object or array; shape depends on artefact_type and is validated against its schema."
+ },
+ "report_id": {
+ "type": "string"
+ }
+ },
+ "required": ["report_id", "artefact_type", "content"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-delete.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-delete.json
new file mode 100644
index 000000000000..976e15c62a4c
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-delete.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this signal report artefact.",
+ "type": "string"
+ },
+ "report_id": {
+ "type": "string"
+ }
+ },
+ "required": ["id", "report_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-list.json
new file mode 100644
index 000000000000..a1e43f676b10
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-list.json
@@ -0,0 +1,18 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "limit": {
+ "description": "Number of results to return per page.",
+ "type": "number"
+ },
+ "offset": {
+ "description": "The initial index from which to return the results.",
+ "type": "number"
+ },
+ "report_id": {
+ "type": "string"
+ }
+ },
+ "required": ["report_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-retrieve.json
new file mode 100644
index 000000000000..976e15c62a4c
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-retrieve.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this signal report artefact.",
+ "type": "string"
+ },
+ "report_id": {
+ "type": "string"
+ }
+ },
+ "required": ["id", "report_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-update.json
new file mode 100644
index 000000000000..fd4447c9ec9a
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-update.json
@@ -0,0 +1,17 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "content": {
+ "description": "The new artefact payload as a JSON object or array, matching the artefact type's schema."
+ },
+ "id": {
+ "description": "A UUID string identifying this signal report artefact.",
+ "type": "string"
+ },
+ "report_id": {
+ "type": "string"
+ }
+ },
+ "required": ["id", "report_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 8ed07d3d816d..8cc2f7ec6012 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
@@ -36,6 +36,10 @@
"suggested_reviewers": {
"description": "Comma-separated list of PostHog user UUIDs. Reports are kept if their suggested reviewers include any of the given users.",
"type": "string"
+ },
+ "task_id": {
+ "description": "Only reports associated with this task (via the report's task associations).",
+ "type": "string"
}
},
"type": "object"