: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): cap per-report signal tasks and interactive run duration (#84510)
Georgiy Tarasov115c7a9bde5b
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 935aabe5194c..6d0cb8c6a48b 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -115,6 +115,15 @@ TASKS_INACTIVITY_TIMEOUT_SECONDS: int = get_from_env("TASKS_INACTIVITY_TIMEOUT_S# matching TASKS_INACTIVITY_TIMEOUT_SECONDS above.TASKS_MAX_RUN_DURATION_SECONDS: int = get_from_env("TASKS_MAX_RUN_DURATION_SECONDS", 3 * 60 * 60, type_cast=int)+# Wall-clock cap for *interactive* signals-origin runs (Inbox "Create PR" / "Discuss", scout+# chat), which are exempt from TASKS_MAX_RUN_DURATION_SECONDS above. Their inference is unbilled,+# so without this their only time bound is the heartbeat-reset inactivity timer. Defaults to the+# sandbox TTL: it never ends a conversation the sandbox wouldn't have ended anyway, but it does+# bound snapshot-resume chains and wedged-but-heartbeating agents. 0 or negative disables.+TASKS_INTERACTIVE_SIGNALS_MAX_RUN_DURATION_SECONDS: int = get_from_env(+ "TASKS_INTERACTIVE_SIGNALS_MAX_RUN_DURATION_SECONDS", 6 * 60 * 60, type_cast=int+)+# Override the delay before the first in-sandbox credential refresh (default 20# minutes). Set this low (e.g. 30) for local testing so the refresh loop fires# quickly instead of waiting out the GitHub token's lifetime.diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.pyindex e4e6a6f39b62..1f4345037dac 100644--- a/products/signals/backend/facade/api.py+++ b/products/signals/backend/facade/api.py@@ -23,6 +23,9 @@ from products.signals.backend.contracts import SIGNAL_VARIANT_LOOKUP, SignalRemefrom products.signals.backend.models import SignalReport, SignalSourceConfigfrom products.signals.backend.signal_metadata import fetch_signal_stats_for_source_slice+# Re-exported for external products (tasks presentation catches it around facade create_task).+from products.signals.backend.task_run_artefacts import ReportTaskCapExceeded as ReportTaskCapExceeded+if TYPE_CHECKING:from products.tasks.backend.facade.repo_selection import RepoSelectionResultdiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 3dbc902b38eb..7ae6ddc58c7a 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -1062,10 +1062,22 @@ class SignalReportArtefact(UUIDModel):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"- )+ if isinstance(parsed, TaskRunArtefact):+ if 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"+ )+ # (product, type) is the run's purpose and feeds the per-report task cap, which counts+ # non-pipeline signals runs; letting an edit relabel a discussion as pipeline work+ # would free its slot in the count.+ existing = parse_artefact_content(self.type, self.content)+ if isinstance(existing, TaskRunArtefact) and (parsed.product, parsed.type) != (+ existing.product,+ existing.type,+ ):+ raise ArtefactContentValidationError(+ "task_run content.product and content.type record what ran and cannot be changed by editing"+ )self.content = parsed.model_dump_json()self.save(update_fields=["content", "updated_at"])if self.type == SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS:diff --git a/products/signals/backend/task_run_artefacts.py b/products/signals/backend/task_run_artefacts.pyindex c9b734ba2463..ede3cf1a2d18 100644--- a/products/signals/backend/task_run_artefacts.py+++ b/products/signals/backend/task_run_artefacts.py@@ -23,6 +23,7 @@ from products.signals.backend.artefact_schemas import (TASK_RUN_TYPE_IMPLEMENTATION,TASK_RUN_TYPE_REPO_SELECTION,TASK_RUN_TYPE_RESEARCH,+ TASK_RUN_TYPE_SCOUT,NoteArtefact,TaskRunArtefact,)@@ -33,19 +34,47 @@ from products.signals.backend.models import ArtefactAttribution, SignalReport, S# without a cycle); re-exported here so existing `from task_run_artefacts import …` callers keep# working.__all__ = [+ "MAX_DISCUSSION_TASKS_PER_REPORT","SIGNALS_PRODUCT","TASK_RUN_TYPE_DISCUSSION","TASK_RUN_TYPE_IMPLEMENTATION","TASK_RUN_TYPE_REPO_SELECTION","TASK_RUN_TYPE_RESEARCH",+ "ReportTaskCapExceeded","aappend_task_run_artefact","append_task_run_artefact",+ "enforce_report_task_cap","record_implementation_task","record_report_task","release_quota_cancelled_implementation","signals_task_ids",]+# One report funds at most this many user-started discussion tasks, on top of one live+# implementation. Inference on these tasks is unbilled (per-PR pricing), so without a cap a+# single report is an unlimited font of free agent runs; the number only needs to cover honest+# "ask a follow-up in a fresh task" use, since conversation *within* a task is unlimited.+MAX_DISCUSSION_TASKS_PER_REPORT = 3++# `scout` excluded too: it labels the scout run that authored the report, is server-written, and+# is rejected as a client-asserted relationship by the tasks write serializer.+_PIPELINE_TASK_RUN_TYPES = frozenset(+ {TASK_RUN_TYPE_IMPLEMENTATION, TASK_RUN_TYPE_RESEARCH, TASK_RUN_TYPE_REPO_SELECTION, TASK_RUN_TYPE_SCOUT}+)++_TERMINAL_NO_PR_RUN_STATUSES = frozenset({"failed", "cancelled"})++_GITHUB_PR_URL_PREFIX = "https://github.com/"+++class ReportTaskCapExceeded(Exception):+ """A signal report already has its allowance of user-started tasks."""++ def __init__(self, kind: str, detail: str) -> None:+ super().__init__(detail)+ self.kind = kind+ self.detail = detail+def _task_run_content(product: str, type: str, task_id: str, run_id: str | None) -> TaskRunArtefact:return TaskRunArtefact(@@ -103,6 +132,78 @@ def signals_task_ids(*, report_id: str, type: str) -> list[str]:]+def _live_implementation_exists(*, team_id: int, report_id: str) -> bool:+ """Whether the report has an implementation task that still claims its one slot.++ Reads the `SignalReportTask` gate rows (not the API-mutable artefact log) and traverses+ to runs via the FK, staying behind the tasks public interface like `billing`. A task+ releases the slot only when it is deleted or every one of its runs ended failed/cancelled+ without shipping a GitHub PR — a task with no runs yet still claims it, and a shipped PR+ claims it permanently (the report is implemented). Quota-cancelled implementations delete+ their gate rows (`release_quota_cancelled_implementation`), so they never count.+ """+ rows = (+ SignalReportTask.objects.filter(team_id=team_id, report_id=report_id, relationship=TASK_RUN_TYPE_IMPLEMENTATION)+ .exclude(task__deleted=True)+ .values_list("task_id", "task__runs__status", "task__runs__output__pr_url")+ )+ runs_by_task: dict[str, list[tuple[str | None, object]]] = {}+ for task_id, status, pr_url in rows:+ runs_by_task.setdefault(str(task_id), []).append((status, pr_url))+ for runs in runs_by_task.values():+ has_runs = any(run_status is not None for run_status, _run_pr_url in runs)+ if not has_runs:+ return True+ for run_status, run_pr_url in runs:+ if run_status is None:+ continue+ if run_status not in _TERMINAL_NO_PR_RUN_STATUSES:+ return True+ if isinstance(run_pr_url, str) and run_pr_url.startswith(_GITHUB_PR_URL_PREFIX):+ return True+ return False+++def enforce_report_task_cap(*, team_id: int, report_id: str, relationship: str | None) -> None:+ """Cap the tasks a single report can spawn; raises `ReportTaskCapExceeded` at the limit.++ Inference on report-started tasks is unbilled (the customer pays per PR), so the report is+ the resource being spent and the cap belongs on it: one live implementation, and at most+ `MAX_DISCUSSION_TASKS_PER_REPORT` tasks with any other relationship. This is defense in depth+ over the gateway's `signals_interactive` per-user budget and per-task spend ceiling.++ Must be called inside an open transaction: it locks the report row — the same lock+ auto-start's `_create_implementation_task_if_absent` takes — so concurrent creates+ serialize instead of both passing the count check.+ """+ if not transaction.get_connection().in_atomic_block:+ raise RuntimeError("enforce_report_task_cap must run inside a transaction; it locks the report row")+ report = SignalReport.objects.select_for_update().filter(id=report_id, team_id=team_id).first()+ if report is None:+ # The serializer already team-scoped the report; behave as the create path would without a cap.+ return+ if relationship is None or relationship == TASK_RUN_TYPE_IMPLEMENTATION:+ if _live_implementation_exists(team_id=team_id, report_id=report_id):+ raise ReportTaskCapExceeded(+ kind=TASK_RUN_TYPE_IMPLEMENTATION,+ detail="A PR task already exists for this report. Open the existing task to continue.",+ )+ return+ # Any non-implementation label is a discussion for cap purposes; server-only pipeline labels+ # can't reach here (the write serializer rejects them) and are excluded from the count.+ # Counting is status-independent: a discussion that ended still consumed inference.+ discussions = [+ run+ for run in SignalReport.associated_task_runs(report_id=report_id, team_id=team_id, product=SIGNALS_PRODUCT)+ if run.type not in _PIPELINE_TASK_RUN_TYPES+ ]+ if len(discussions) >= MAX_DISCUSSION_TASKS_PER_REPORT:+ raise ReportTaskCapExceeded(+ kind=TASK_RUN_TYPE_DISCUSSION,+ detail="This report has reached its limit of AI discussions. Open an existing discussion task to continue.",+ )++def record_implementation_task(*, team_id: int, report_id: str, task_id: str, run_id: str | None = None, billing_exempt_reason: str | None = None) -> SignalReportArtefact:diff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.pyindex cdb281fea191..5ba6f582ab90 100644--- a/products/signals/backend/test/test_signal_report_artefact_api.py+++ b/products/signals/backend/test/test_signal_report_artefact_api.py@@ -1133,15 +1133,32 @@ class TestSignalReportArtefactLogWriteViewSet(APIBaseTest):)assert drift.status_code == status.HTTP_400_BAD_REQUEST- # Editing other fields while keeping the same task_id is fine.+ # Relabeling the run's purpose is rejected too — the (product, type) pair feeds the+ # per-report task cap, so an edit relabeling a discussion as pipeline work would free+ # its slot in the count.+ for relabel in (+ {"task_id": str(task.id), "product": "signals", "type": "implementation"},+ {"task_id": str(task.id), "product": "tasks", "type": "research"},+ ):+ response = self.client.patch(+ self._detail_url(str(report.id), str(artefact.id)),+ data=json.dumps({"content": relabel}),+ content_type="application/json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()++ # Editing other fields while keeping the association and purpose is fine.+ run_id = str(uuid.uuid4())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"}}),+ data=json.dumps(+ {"content": {"task_id": str(task.id), "product": "signals", "type": "research", "run_id": run_id}}+ ),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 json.loads(artefact.content)["run_id"] == run_idassert str(artefact.task_id) == str(task.id)def test_patch_other_team_returns_404(self):@@ -1176,6 +1193,24 @@ class TestSignalReportArtefactLogWriteViewSet(APIBaseTest):assert response.status_code == status.HTTP_204_NO_CONTENTassert not SignalReportArtefact.objects.filter(id=artefact.id).exists()+ def test_delete_task_run_artefact_is_rejected(self):+ # The work log is what the per-report task cap counts; a deletable log would let a+ # client at the cap free its own slots.+ report = self._create_report()+ task = Task.objects.create(+ team=self.team, title="t", 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="discussion"),+ attribution=ArtefactAttribution.from_task(str(task.id)),+ )++ response = self.client.delete(self._detail_url(str(report.id), str(artefact.id)))+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert 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")):diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 93052b22f14f..cd148dd20eb5 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -3512,18 +3512,27 @@ class SignalReportArtefactViewSet(@extend_schema(responses={204: OpenApiResponse(description="Artefact deleted."),+ 400: OpenApiResponse(description="Artefact type cannot be deleted through the API."),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)."+ "the report's canonical status to the previous version (latest-wins over what remains). "+ "`task_run` artefacts are an append-only work log and cannot be deleted."),parameters=[_REPORT_ID_PARAMETER],operation_id="signals_report_artefacts_destroy",)def destroy(self, request, *args, **kwargs) -> Response:artefact = cast(SignalReportArtefact, self.get_object())+ if artefact.type == SignalReportArtefact.ArtefactType.TASK_RUN:+ # The work log is also what the per-report task cap counts; a deletable log would let+ # a client at the cap free its own slots.+ return Response(+ {"error": "task_run artefacts are an append-only work log and cannot be deleted."},+ status=status.HTTP_400_BAD_REQUEST,+ )was_reviewers = artefact.type == SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERSreport_id = str(artefact.report_id)artefact.delete()diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 17ae5bb0d7b7..6c482495dec0 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -621,7 +621,7 @@ export const getSignalsReportArtefactsDestroyUrl = (projectId: string, reportId:}/**- * 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).+ * 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). `task_run` artefacts are an append-only work log and cannot be deleted.* @summary Delete an artefact*/export const signalsReportArtefactsDestroy = async (diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.tsindex a78a2abcc516..8d0ede8ba782 100644--- a/products/signals/frontend/inbox/inboxAnalytics.ts+++ b/products/signals/frontend/inbox/inboxAnalytics.ts@@ -82,9 +82,10 @@ export type InboxReportActionType =/*** Whether a task-kickoff action (`discuss` / `create_pr`) actually produced a task. The press itself* is already an {@link captureInboxReportAction} event; without the outcome the two are- * indistinguishable, so an attempted PR counts the same as a created one.+ * indistinguishable, so an attempted PR counts the same as a created one. `limited` is a server+ * limit (the per-report task cap or the per-user creation throttle) refusing an issued request.*/-export type InboxReportActionOutcome = 'success' | 'failure' | 'blocked'+export type InboxReportActionOutcome = 'success' | 'failure' | 'blocked' | 'limited'/** Panels that replace the report list and so never fire `Inbox viewed`. */export type InboxPanelName = 'runs' | 'config' | 'scratchpad' | 'findings'@@ -460,7 +461,8 @@ export function captureSignalSourceSteeringChanged(params: {/*** Outcome of a task-kickoff action, fired once the request settles. Pairs with the press event on* `report_id` + `action_type`. `blocked` means we never issued the request (no AI consent), which is- * a product problem rather than a failure — hence its own bucket.+ * a product problem rather than a failure — hence its own bucket. `limited` means the server+ * refused the request with a limit 429; `limit_code` says which limit.*/export function captureInboxReportActionCompleted(params: {report: SignalReport@@ -468,12 +470,15 @@ export function captureInboxReportActionCompleted(params: {outcome: InboxReportActionOutcome/** Only set for `blocked`, and only ever our own consent copy — never a server error body. */blockedReason?: string | null+ /** Only set for `limited`: the server's error code (`signal_report_task_cap` or `throttled`). */+ limitCode?: string | null}): void {captureInboxEvent(INBOX_EVENTS.REPORT_ACTION_COMPLETED, {...baseReportProperties(params.report),action_type: params.actionType,outcome: params.outcome,...(params.blockedReason ? { blocked_reason: params.blockedReason } : {}),+ ...(params.limitCode ? { limit_code: params.limitCode } : {}),})}diff --git a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts b/products/signals/frontend/inbox/inboxTaskKickoffLogic.tsindex 04ae1e2ce623..5fc3e0afdd03 100644--- a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts+++ b/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts@@ -16,7 +16,7 @@ import {TaskExecutionModeEnumApi,} from 'products/tasks/frontend/generated/api.schemas'-import { captureInboxReportActionCompleted } from './inboxAnalytics'+import { InboxReportActionType, captureInboxReportActionCompleted } from './inboxAnalytics'import {SIGNAL_REPORT_TASK_DISCUSSION_RELATIONSHIP,SIGNAL_REPORT_TASK_IMPLEMENTATION_RELATIONSHIP,@@ -68,6 +68,40 @@ function buildDiscussReportPrompt(reportUrl: string, question: string): string {return `Answer this question about the PostHog Inbox report at ${reportUrl}:\n\n${question.trim()}`}+// The per-report cap 429 carries code `signal_report_task_cap` with its message under `error`+// (TaskRunErrorResponseSerializer); the per-user creation throttle is DRF's `throttled` 429 with+// `detail`. Both are user-facing copy the server owns. Matching on code, not status: other 429s+// (e.g. the compute-quota gate) are not task limits and belong on the generic failure path.+function taskLimitMessage(error: any): string | null {+ if (error?.code === 'signal_report_task_cap' || error?.code === 'throttled') {+ return error?.data?.error || error?.detail || 'Task limit reached for this report. Try again later.'+ }+ return null+}++// Shared error tail of both kickoff listeners: a recognized task-limit 429 gets the server's copy+// and a `limited` outcome; anything else is a plain failure.+function handleKickoffError(+ error: any,+ report: SignalReport,+ actionType: InboxReportActionType,+ fallbackMessage: string+): void {+ const limitMessage = taskLimitMessage(error)+ if (limitMessage) {+ lemonToast.error(limitMessage)+ captureInboxReportActionCompleted({+ report,+ actionType,+ outcome: 'limited',+ limitCode: error?.code ?? null,+ })+ return+ }+ lemonToast.error(error?.detail || error?.message || fallbackMessage)+ captureInboxReportActionCompleted({ report, actionType, outcome: 'failure' })+}+async function createReportTask(report: SignalReport,relationship: SignalReportTaskRelationship,@@ -228,8 +262,7 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([captureInboxReportActionCompleted({ report, actionType: 'discuss', outcome: 'success' })actions.discussReportSuccess()} catch (error: any) {- lemonToast.error(error?.detail || error?.message || "Couldn't ask AI about this report. Try again.")- captureInboxReportActionCompleted({ report, actionType: 'discuss', outcome: 'failure' })+ handleKickoffError(error, report, 'discuss', "Couldn't ask AI about this report. Try again.")actions.discussReportFailure()}},@@ -256,8 +289,7 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([captureInboxReportActionCompleted({ report, actionType: 'create_pr', outcome: 'success' })actions.createPrSuccess()} catch (error: any) {- lemonToast.error(error?.detail || error?.message || 'Failed to start PR task')- captureInboxReportActionCompleted({ report, actionType: 'create_pr', outcome: 'failure' })+ handleKickoffError(error, report, 'create_pr', "Couldn't start the PR task. Try again.")actions.createPrFailure()}},diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex 7f023ec77c55..c9eaa9b97fc3 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -59,7 +59,8 @@ tools:title: Delete an artefactdescription: >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.+ type (e.g. priority_judgment) reverts the report's canonical status to the previous version. `task_run`+ artefacts are an append-only work log and cannot be deleted.inbox-report-artefacts-list:operation: signals_report_artefacts_listenabled: truediff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 849a6c68e994..21eed230b6e5 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -4702,6 +4702,7 @@ def create_task(from posthog.models import Team # noqa: PLC0415from products.signals.backend.task_run_artefacts import ( # noqa: PLC0415 — cross-product write kept off the api import path+ enforce_report_task_cap,record_report_task,)from products.tasks.backend.logic.services.title_generator import generate_task_title # noqa: PLC0415@@ -4911,11 +4912,24 @@ def create_task(# Gated regardless of the relationship label: the label is client-selected and manually# created tasks run PR-capable by default, so a "discussion" label must not dodge the limit.report_ref = validated_data.get("signal_report") or validated_data.get("signal_report_id")- if report_ref and validated_data.get("origin_product") == Task.OriginProduct.SIGNAL_REPORT:- enforce_self_driving_pr_quota(team, report_id=str(getattr(report_ref, "id", report_ref)))+ signal_report_id = (+ str(getattr(report_ref, "id", report_ref))+ if report_ref and validated_data.get("origin_product") == Task.OriginProduct.SIGNAL_REPORT+ else None+ )+ if signal_report_id:+ enforce_self_driving_pr_quota(team, report_id=signal_report_id)logger.info("Creating task with data: %s", validated_data)with transaction.atomic():+ if signal_report_id:+ # Locks the report row until commit, so concurrent creates (and auto-start, which+ # takes the same lock) serialize instead of both passing the count check.+ enforce_report_task_cap(+ team_id=team_id,+ report_id=signal_report_id,+ relationship=signal_report_task_relationship,+ )task = Task.objects.create(**validated_data)if task.signal_report_id and task.origin_product == Task.OriginProduct.SIGNAL_REPORT:# Record the task↔report association + work-log artefact for the asserted relationshipdiff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 521c6887780c..b5960e31ee38 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -401,6 +401,9 @@ class WizardCloudRunSerializer(DataclassSerializer):# Mirrors the routing-safe identifier rule in `signals` `artefact_schemas` (_IDENTIFIER_PART_RE),# kept inline so presentation never imports the other product's internals._SIGNAL_REPORT_TASK_RELATIONSHIP_RE = re.compile(r"^[a-z0-9][a-z0-9_-]*$")+# String literals rather than an import: presentation must not import signals internals, and the+# vocabulary (products/signals/backend/artefact_schemas.py TASK_RUN_TYPE_*) is stable.+_SERVER_ONLY_SIGNAL_REPORT_TASK_RELATIONSHIPS = frozenset({"research", "repo_selection", "scout"})class TaskSerializer(DataclassSerializer):@@ -526,10 +529,11 @@ class TaskWriteSerializer(serializers.Serializer):write_only=True,max_length=200,help_text=(- "How the created task relates to the signal report (e.g. 'implementation', 'discussion', "- "'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens "- "the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, "- "'_', '-') is accepted."+ "How the created task relates to the signal report (e.g. 'implementation', 'discussion'). "+ "Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start "+ "spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted "+ "except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). "+ "Non-implementation labels count toward the report's discussion task limit."),)json_schema = serializers.JSONField(@@ -537,10 +541,10 @@ class TaskWriteSerializer(serializers.Serializer):allow_null=True,help_text="JSON schema used to validate the output of the task.",)- internal = serializers.BooleanField(- required=False,- help_text="If true, this task is for internal use and should not be exposed to end users.",- )+ # `internal` is deliberately not writable here: only server-side creators (auto-start,+ # research, loops) set it via the facade. A client-set `internal=True` on a signals-origin+ # task would drop the token's interactive-run marker and with it the `signals_interactive`+ # budget and per-task spend ceiling (see is_interactive_signals_task in temporal/oauth.py).archived = serializers.BooleanField(required=False,help_text="If true, the task is hidden from default list responses.",@@ -721,6 +725,11 @@ class TaskWriteSerializer(serializers.Serializer):"Must contain only lowercase letters, numbers, underscores, or hyphens, ""and start with a lowercase letter or number.")+ # Labels the signals pipeline writes itself. Client-asserted, they would misrepresent a+ # user-started task as pipeline work — and dodge the per-report cap, which counts every+ # non-implementation label as a discussion except these server-only ones.+ if normalized in _SERVER_ONLY_SIGNAL_REPORT_TASK_RELATIONSHIPS:+ raise serializers.ValidationError(f"Relationship '{normalized}' is reserved for server-created tasks.")return normalizeddef validate(self, attrs: dict[str, Any]) -> dict[str, Any]:@@ -803,6 +812,18 @@ class TaskCreateSerializer(TaskWriteSerializer):help_text="Agent protocol and harness used for this task's runs. Defaults to ACP when omitted.",)+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ attrs = super().validate(attrs)+ # Mirror image of the signal_report_task_relationship check: a report-less signal_report+ # task still mints under the Signals OAuth app with the interactive run scope, but skips+ # the per-report cap entirely. Require the report so the cap and interactive budget always+ # see the run. Create-only, since origin_product is not writable on update.+ if attrs.get("origin_product") == tasks_facade.TaskOriginProduct.SIGNAL_REPORT and not attrs.get(+ "signal_report"+ ):+ raise serializers.ValidationError({"signal_report": "Requires signal_report when set."})+ return attrs+class TaskRunSetOutputRequestSerializer(serializers.Serializer):output = serializers.JSONField(diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 052ef7ed60c9..7a184ed3bc06 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -32,7 +32,10 @@ from rest_framework.exceptions import (from rest_framework.pagination import LimitOffsetPaginationfrom rest_framework.parsers import BaseParserfrom rest_framework.permissions import IsAuthenticated+from rest_framework.request import Requestfrom rest_framework.response import Response+from rest_framework.throttling import BaseThrottle, UserRateThrottle+from rest_framework.views import APIViewfrom posthog.schema import QuerySchemaRoot@@ -287,6 +290,31 @@ class TaskUsageUpstreamUnavailable(APIException):default_code = "task_usage_upstream_unavailable"+class _SignalReportTaskCreateThrottle(UserRateThrottle):+ """Rate-limits only signal-report task creation on the shared create endpoint.++ Report-started tasks run unbilled inference (the customer pays per PR), so their creation+ rate needs a per-user bound the generic create path doesn't; the per-report cap alone still+ allows sweeping every report on a team. Reading `request.data` here is safe — DRF caches it.+ """++ def allow_request(self, request: Request, view: APIView) -> bool:+ data = request.data+ if not isinstance(data, dict) or data.get("origin_product") != "signal_report":+ return True+ return super().allow_request(request, view)+++class SignalReportTaskCreateBurstThrottle(_SignalReportTaskCreateThrottle):+ scope = "signal_report_task_create_burst"+ rate = "10/hour"+++class SignalReportTaskCreateSustainedThrottle(_SignalReportTaskCreateThrottle):+ scope = "signal_report_task_create_day"+ rate = "30/day"++@extend_schema(tags=["tasks"])class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"""@@ -305,6 +333,12 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# request/response schema via @validated_request / @extend_schema.serializer_class = TaskSerializer+ def get_throttles(self) -> list[BaseThrottle]:+ throttles = super().get_throttles()+ if getattr(self, "action", None) == "create":+ throttles += [SignalReportTaskCreateBurstThrottle(), SignalReportTaskCreateSustainedThrottle()]+ return throttles+def _user_id(self) -> int | None:return getattr(self.request.user, "id", None)@@ -499,7 +533,10 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):201: TaskSerializer,429: OpenApiResponse(response=TaskRunErrorResponseSerializer,- description="Organization reached its PostHog Desktop usage limit",+ description=(+ "Organization reached its PostHog Desktop usage limit, the signal report reached its "+ "task limit (code `signal_report_task_cap`), or the per-user creation rate limit fired"+ ),),},)@@ -507,6 +544,10 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):serializer = self._write_serializer(request.data, serializer_class=TaskCreateSerializer)# Read before create_task, which pops the relationship out of the dict it's handed.relationship = serializer.validated_data.get("signal_report_task_relationship")+ from products.signals.backend.facade.api import ( # noqa: PLC0415 — keeps the signals stack off this module's import path+ ReportTaskCapExceeded,+ )+try:task = tasks_facade.create_task(self.team_id,@@ -516,6 +557,14 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)except ComputeBillingLimitExceeded as error:return compute_quota_limit_response(error.reason)+ except ReportTaskCapExceeded as error:+ # `code` distinguishes this from the compute-quota 429 for frontend handling.+ return Response(+ TaskRunErrorResponseSerializer(+ {"type": "rate_limit", "code": "signal_report_task_cap", "error": error.detail}+ ).data,+ status=status.HTTP_429_TOO_MANY_REQUESTS,+ )self._forward_signals_discussion_note(request, task, relationship)return Response(TaskSerializer(task).data, status=status.HTTP_201_CREATED)diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.pyindex 8f0270e18784..f013ad565e34 100644--- a/products/tasks/backend/temporal/oauth.py+++ b/products/tasks/backend/temporal/oauth.py@@ -76,7 +76,7 @@ def _oauth_application_for_task(task: Task) -> SandboxOAuthApplication:return "array"-def _is_interactive_signals_task(task: Task) -> bool:+def is_interactive_signals_task(task: Task) -> bool:"""Whether this run exists because a person pressed something, not because we scheduled it."""return task.origin_product in INTERACTIVE_SIGNALS_ORIGIN_PRODUCTS and not task.internal@@ -124,7 +124,7 @@ def create_oauth_access_token(# task needs a member-capable token, or every member-proxy call it was# just granted would 403.token_options["include_mcp_builtin_agent_scope"] = True- if _is_interactive_signals_task(task):+ if is_interactive_signals_task(task):token_options["include_interactive_run_scope"] = Truereturn create_oauth_access_token_for_user(actor, task.team_id, **token_options)diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.pyindex 1c219b0137d7..3dfaa91a258d 100644--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py@@ -46,6 +46,7 @@ from products.tasks.backend.logic.services.sandbox_config import ()from products.tasks.backend.models import SandboxCustomImage, SandboxEnvironment, Task, TaskRunfrom products.tasks.backend.temporal.constants import resolve_inactivity_timeout, resolve_max_run_duration+from products.tasks.backend.temporal.oauth import is_interactive_signals_taskfrom products.tasks.backend.temporal.observability import emit_agent_log, log_with_activity_contextfrom products.tasks.backend.temporal.process_task.utils import (format_allowed_domains_for_log,@@ -124,6 +125,10 @@ class TaskProcessingContext:# Captured at workflow start so the continue_as_new trigger is deterministic across replay.continue_as_new_enabled: bool = Falsecontinue_as_new_history_threshold: int = 0+ # Wall-clock cap for interactive signals-origin runs, resolved activity-side. The None+ # default is what pre-existing run histories decode, so replays schedule no new timer+ # (see .claude/rules/temporal-workflow-versioning.md, pattern 2).+ interactive_max_run_duration_seconds: int | None = None@propertydef mode(self) -> str:@@ -239,10 +244,14 @@ class TaskProcessingContext:Unlike the inactivity timeout, this is not reset by heartbeats, so it stops awedged-but-heartbeating agent that would otherwise run forever. User-driven- sessions can legitimately run for hours, so they are uncapped. Autonomous runs- get the cap as a safety net unless the setting disables it deployment-wide.+ sessions can legitimately run for hours, so they are uncapped — except interactive+ signals-origin runs, whose inference is unbilled and which therefore get their own+ (longer) ceiling, resolved activity-side into the field below. Autonomous runs get+ the cap as a safety net unless the setting disables it deployment-wide."""if self.mode == "interactive" or self._is_user_origin():+ if self.interactive_max_run_duration_seconds:+ return timedelta(seconds=self.interactive_max_run_duration_seconds)return Nonereturn resolve_max_run_duration()@@ -1030,6 +1039,17 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro"debug",f"rtk_enabled: {rtk_enabled} for this task run",)+ # The same test that mints the token's interactive-run marker: user-started signals runs get+ # a finite wall-clock ceiling because their inference is unbilled and the generic interactive+ # exemption would leave them bounded only by the inactivity timer.+ interactive_max_run_duration_seconds = None+ if (+ (state or {}).get("mode") == "interactive"+ and is_interactive_signals_task(task)+ and settings.TASKS_INTERACTIVE_SIGNALS_MAX_RUN_DURATION_SECONDS > 0+ ):+ interactive_max_run_duration_seconds = settings.TASKS_INTERACTIVE_SIGNALS_MAX_RUN_DURATION_SECONDS+pr_authorship_mode = get_pr_authorship_mode(task, state)user_github_integration_id = Noneif not (is_slack_interaction_state(state) and pr_authorship_mode.value == "user"):@@ -1092,4 +1112,5 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskProrun_id=run_id,),continue_as_new_history_threshold=settings.TASKS_CONTINUE_AS_NEW_HISTORY_THRESHOLD,+ interactive_max_run_duration_seconds=interactive_max_run_duration_seconds,)diff --git a/products/tasks/backend/temporal/process_task/tests/test_max_run_duration.py b/products/tasks/backend/temporal/process_task/tests/test_max_run_duration.pyindex cfc3ecba5524..026df9802bd5 100644--- a/products/tasks/backend/temporal/process_task/tests/test_max_run_duration.py+++ b/products/tasks/backend/temporal/process_task/tests/test_max_run_duration.py@@ -79,3 +79,12 @@ class TestMaxRunDuration:@override_settings(TASKS_MAX_RUN_DURATION_SECONDS=-1)def test_negative_disables_the_cap(self):assert resolve_max_run_duration() is None++ def test_interactive_signals_cap_applies_when_the_activity_resolved_one(self):+ # User-started signals runs (unbilled inference) get a finite ceiling via the field the+ # activity resolves; other interactive runs keep the exemption. None is also what+ # pre-existing run histories decode, so replays schedule no timer.+ context = _context({"mode": "interactive"}, origin_product=Task.OriginProduct.SIGNAL_REPORT.value)+ assert context.max_run_duration() is None+ context.interactive_max_run_duration_seconds = 6 * 60 * 60+ assert context.max_run_duration() == timedelta(seconds=6 * 60 * 60)diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 8bf92880170f..03cef551d9e2 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -13,6 +13,7 @@ from urllib.parse import quotefrom unittest.mock import ANY, AsyncMock, MagicMock, call, patchfrom django.conf import settings+from django.core.cache import cachefrom django.db import connectionfrom django.http import StreamingHttpResponsefrom django.test import SimpleTestCase, TestCase, override_settings@@ -183,6 +184,10 @@ class BaseTaskAPITest(TestCase):self.client = APIClient()self.client.force_authenticate(self.user)+ # DRF throttle history lives in the default cache keyed by user pk; without this it+ # accumulates across tests (APIBaseTest clears it in setUp for the same reason).+ cache.clear()+# Enable tasks feature flag by defaultself.set_tasks_feature_flag(True)@@ -1631,6 +1636,22 @@ class TestTaskAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ def test_create_signal_report_origin_requires_report(self):+ # A report-less signal_report origin would mint an interactive Signals run that skips the+ # per-report cap; the serializer must reject it (mirror of the internal/reserved bypasses).+ response = self.client.post(+ "/api/projects/@current/tasks/",+ {+ "title": "New Task",+ "description": "New Description",+ "origin_product": "signal_report",+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "signal_report")+def test_create_task_with_github_user_integration(self):user_integration = _grant_user_github_access(self.user)@@ -1802,12 +1823,12 @@ class TestTaskAPI(BaseTaskAPITest):self.assertEqual(signals_task_ids(report_id=str(report.id), type=TASK_RUN_TYPE_IMPLEMENTATION), [])self.assertFalse(SignalReportTask.objects.filter(report=report, task_id=data["id"]).exists())- @parameterized.expand([("discussion", True), ("implementation", False), ("research", False)])+ @parameterized.expand([("discussion", True), ("implementation", False), ("triage", False)])def test_signal_report_task_forwards_discussion_question_as_scout_note(self, relationship, should_forward):# Wiring guard: a "Discuss" kickoff (and only a discussion relationship) forwards the user's# question to the report's scout as a REPORT_DISCUSSION note. Guards the facade hook firing for- # discussion but not for implementation/research (which would spam a note on every PR kickoff),- # and the URL-prefix strip end to end.+ # discussion but not for implementation or free-form labels (which would spam a note on every+ # PR kickoff), and the URL-prefix strip end to end.from products.signals.backend.models import SignalReport, SignalScoutNotereport = SignalReport.objects.create(team=self.team, title="Checkout errors spiked")@@ -1966,25 +1987,205 @@ class TestTaskAPI(BaseTaskAPITest):from products.signals.backend.models import SignalReport, SignalReportTaskfrom products.signals.backend.task_run_artefacts import signals_task_ids- # The relationship is a free-form task_run label — no value is reserved. A non-implementation- # relationship records only the work-log artefact (no SignalReportTask gate row).+ # The relationship is a free-form task_run label (bar the reserved pipeline labels). A+ # non-implementation relationship records only the work-log artefact (no SignalReportTask+ # gate row).report = SignalReport.objects.create(team=self.team)response = self.client.post("/api/projects/@current/tasks/",{- "title": "Research",+ "title": "Triage","description": "From a signal report","origin_product": "signal_report","signal_report": str(report.id),- "signal_report_task_relationship": "research",+ "signal_report_task_relationship": "triage",},format="json",)self.assertEqual(response.status_code, status.HTTP_201_CREATED)data = response.json()- self.assertEqual(signals_task_ids(report_id=str(report.id), type="research"), [data["id"]])+ self.assertEqual(signals_task_ids(report_id=str(report.id), type="triage"), [data["id"]])self.assertFalse(SignalReportTask.objects.filter(report=report, task_id=data["id"]).exists())+ def _post_signal_report_task(self, report_id, relationship, title="Report task"):+ return self.client.post(+ "/api/projects/@current/tasks/",+ {+ "title": title,+ "description": "From a signal report",+ "origin_product": "signal_report",+ "signal_report": str(report_id),+ "signal_report_task_relationship": relationship,+ },+ format="json",+ )++ def _create_implementation_task_with_runs(self, report, run_specs, deleted=False):+ from products.signals.backend.models import SignalReportTask++ task = Task.objects.create(+ team=self.team,+ title="Prior implementation",+ description="Prior",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ signal_report=report,+ deleted=deleted,+ )+ SignalReportTask.objects.create(team=self.team, report=report, task=task, relationship="implementation")+ for run_status, pr_url in run_specs:+ TaskRun.objects.create(+ task=task, team=self.team, status=run_status, output={"pr_url": pr_url} if pr_url else None+ )+ return task++ @parameterized.expand([("research",), ("repo_selection",), ("scout",)])+ def test_reserved_signal_report_task_relationships_rejected(self, relationship):+ # These labels mark server-side pipeline work; a client asserting one would misrepresent a+ # user-started task and dodge the per-report discussion cap (which exempts pipeline labels).+ from products.signals.backend.models import SignalReport++ report = SignalReport.objects.create(team=self.team)+ response = self._post_signal_report_task(report.id, relationship)+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "signal_report_task_relationship")++ def test_reserved_relationships_match_signals_pipeline_vocabulary(self):+ # The serializer's reserved set is a string-literal copy (presentation must not import+ # signals internals). If signals grows a pipeline label the serializer doesn't reserve,+ # clients can assert it and the label is also exempt from the per-report discussion+ # count — uncapped report-started runs.+ from products.signals.backend.artefact_schemas import TASK_RUN_TYPE_IMPLEMENTATION+ from products.signals.backend.task_run_artefacts import _PIPELINE_TASK_RUN_TYPES+ from products.tasks.backend.presentation.serializers import _SERVER_ONLY_SIGNAL_REPORT_TASK_RELATIONSHIPS++ # `implementation` is the one pipeline label clients may assert (it opens the auto-start+ # spend gate and is capped by the one-live-implementation rule instead).+ self.assertEqual(+ _SERVER_ONLY_SIGNAL_REPORT_TASK_RELATIONSHIPS, _PIPELINE_TASK_RUN_TYPES - {TASK_RUN_TYPE_IMPLEMENTATION}+ )++ @parameterized.expand(+ [+ # a live implementation claims the report's one slot+ ("created_never_run", [], False, status.HTTP_429_TOO_MANY_REQUESTS),+ ("run_in_progress", [("in_progress", None)], False, status.HTTP_429_TOO_MANY_REQUESTS),+ ("run_completed", [("completed", None)], False, status.HTTP_429_TOO_MANY_REQUESTS),+ (+ "failed_but_pr_shipped",+ [("failed", "https://github.com/acme/web/pull/1")],+ False,+ status.HTTP_429_TOO_MANY_REQUESTS,+ ),+ # only a fully dead prior implementation (or a deleted task) releases the slot+ ("all_runs_failed", [("failed", None), ("failed", None)], False, status.HTTP_201_CREATED),+ ("run_cancelled_no_pr", [("cancelled", None)], False, status.HTTP_201_CREATED),+ ("prior_task_deleted", [("in_progress", None)], True, status.HTTP_201_CREATED),+ ]+ )+ def test_second_implementation_task_per_report_gated_on_prior_state(+ self, _name, run_specs, prior_deleted, expected_status+ ):+ from products.signals.backend.models import SignalReport++ report = SignalReport.objects.create(team=self.team)+ self._create_implementation_task_with_runs(report, run_specs, deleted=prior_deleted)++ response = self._post_signal_report_task(report.id, "implementation")++ self.assertEqual(response.status_code, expected_status)+ if expected_status == status.HTTP_429_TOO_MANY_REQUESTS:+ self.assertEqual(response.json()["code"], "signal_report_task_cap")+ self.assertFalse(Task.objects.filter(title="Report task").exists())++ def test_discussion_task_cap_per_report_counts_free_form_labels(self):+ from products.signals.backend.models import SignalReport+ from products.signals.backend.task_run_artefacts import MAX_DISCUSSION_TASKS_PER_REPORT++ report = SignalReport.objects.create(team=self.team)+ # Free-form labels share the discussion bucket — otherwise a made-up label resets the cap.+ labels = ["discussion", "brainstorm", "discussion"]+ self.assertEqual(len(labels), MAX_DISCUSSION_TASKS_PER_REPORT)+ for label in labels:+ self.assertEqual(self._post_signal_report_task(report.id, label).status_code, status.HTTP_201_CREATED)++ response = self._post_signal_report_task(report.id, "discussion")++ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)+ self.assertEqual(response.json()["code"], "signal_report_task_cap")+ # An exhausted discussion cap must not consume the implementation slot, and vice versa.+ self.assertEqual(+ self._post_signal_report_task(report.id, "implementation").status_code, status.HTTP_201_CREATED+ )++ def test_report_task_cap_counts_tasks_across_team_members(self):+ from products.signals.backend.models import SignalReport++ report = SignalReport.objects.create(team=self.team)+ self.assertEqual(+ self._post_signal_report_task(report.id, "implementation").status_code, status.HTTP_201_CREATED+ )++ other_user = self.create_organization_user()+ self.client.force_login(other_user)+ response = self._post_signal_report_task(report.id, "implementation")++ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)+ self.assertEqual(response.json()["code"], "signal_report_task_cap")++ def test_create_task_ignores_client_internal_flag(self):+ # A client-set internal=True on a signals-origin task would drop the interactive-run budget+ # marker at the gateway; the field is server-only, so the key is silently ignored.+ from products.signals.backend.models import SignalReport++ report = SignalReport.objects.create(team=self.team)+ response = self.client.post(+ "/api/projects/@current/tasks/",+ {+ "title": "Report task",+ "description": "From a signal report",+ "origin_product": "signal_report",+ "signal_report": str(report.id),+ "signal_report_task_relationship": "discussion",+ "internal": True,+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertFalse(Task.objects.get(id=response.json()["id"]).internal)++ def test_update_task_ignores_client_internal_flag(self):+ task = self.create_task("Mine")+ response = self.client.patch(+ f"/api/projects/@current/tasks/{task.id}/",+ {"internal": True},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ task.refresh_from_db()+ self.assertFalse(task.internal)++ def test_signal_report_create_throttle_skips_other_origins(self):+ from products.signals.backend.models import SignalReport+ from products.tasks.backend.presentation.views.api import SignalReportTaskCreateBurstThrottle++ report = SignalReport.objects.create(team=self.team)+ other_report = SignalReport.objects.create(team=self.team)+ with patch.object(SignalReportTaskCreateBurstThrottle, "rate", "1/day"):+ self.assertEqual(+ self._post_signal_report_task(report.id, "discussion").status_code, status.HTTP_201_CREATED+ )+ self.assertEqual(+ self._post_signal_report_task(other_report.id, "discussion").status_code,+ status.HTTP_429_TOO_MANY_REQUESTS,+ )+ # The throttle is scoped to signal-report creates; the shared endpoint stays open.+ response = self.client.post(+ "/api/projects/@current/tasks/",+ {"title": "Plain task", "description": "Unrelated", "origin_product": "user_created"},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+def test_create_task_with_signal_report_different_team_rejected(self):from products.signals.backend.models import SignalReport@@ -4572,15 +4773,6 @@ class TestTaskInternalFilterAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertTrue(response.json()["internal"])- def test_internal_field_is_settable_on_create(self):- response = self.client.post(- "/api/projects/@current/tasks/",- {"title": "Internal Task via API", "description": "Created as internal", "internal": True},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_201_CREATED)- self.assertTrue(response.json()["internal"])-def test_internal_field_defaults_to_false_on_create(self):response = self.client.post("/api/projects/@current/tasks/",diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex ecc3b4c3aa09..381d27676e31 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -1640,14 +1640,12 @@ export interface TaskCreateApi {*/signal_report?: string | null/**- * How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted.+ * How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit.* @maxLength 200*/signal_report_task_relationship?: string/** JSON schema used to validate the output of the task. */json_schema?: unknown- /** If true, this task is for internal use and should not be exposed to end users. */- internal?: boolean/** If true, the task is hidden from default list responses. */archived?: boolean/**@@ -1783,14 +1781,12 @@ export interface TaskWriteApi {*/signal_report?: string | null/**- * How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted.+ * How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit.* @maxLength 200*/signal_report_task_relationship?: string/** JSON schema used to validate the output of the task. */json_schema?: unknown- /** If true, this task is for internal use and should not be exposed to end users. */- internal?: boolean/** If true, the task is hidden from default list responses. */archived?: boolean/**@@ -1911,14 +1907,12 @@ export interface PatchedTaskWriteApi {*/signal_report?: string | null/**- * How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted.+ * How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit.* @maxLength 200*/signal_report_task_relationship?: string/** JSON schema used to validate the output of the task. */json_schema?: unknown- /** If true, this task is for internal use and should not be exposed to end users. */- internal?: boolean/** If true, the task is hidden from default list responses. */archived?: boolean/**diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex 616b6e18cac6..844b87ae03ec 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -1133,13 +1133,9 @@ export const TasksCreateBody = /* @__PURE__ */ zod.max(tasksCreateBodySignalReportTaskRelationshipMax).optional().describe(- "How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted."+ "How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit."),json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),- internal: zod- .boolean()- .optional()- .describe('If true, this task is for internal use and should not be exposed to end users.'),archived: zod.boolean().optional().describe('If true, the task is hidden from default list responses.'),ci_prompt: zod.string()@@ -1297,13 +1293,9 @@ export const TasksUpdateBody = /* @__PURE__ */ zod.max(tasksUpdateBodySignalReportTaskRelationshipMax).optional().describe(- "How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted."+ "How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit."),json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),- internal: zod- .boolean()- .optional()- .describe('If true, this task is for internal use and should not be exposed to end users.'),archived: zod.boolean().optional().describe('If true, the task is hidden from default list responses.'),ci_prompt: zod.string()@@ -1446,13 +1438,9 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod.max(tasksPartialUpdateBodySignalReportTaskRelationshipMax).optional().describe(- "How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted."+ "How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit."),json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),- internal: zod- .boolean()- .optional()- .describe('If true, this task is for internal use and should not be exposed to end users.'),archived: zod.boolean().optional().describe('If true, the task is hidden from default list responses.'),ci_prompt: zod.string()diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 59554da6b9e6..a36a67891b66 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -4958,7 +4958,7 @@}},"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.",+ "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. `task_run` artefacts are an append-only work log and cannot be deleted.","category": "Signals","feature": "signals","summary": "Delete an artefact",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 862c6c4ff8c9..69f5052a834b 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5141,7 +5141,7 @@}},"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.",+ "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. `task_run` artefacts are an append-only work log and cannot be deleted.","category": "Signals","feature": "signals","summary": "Delete an artefact",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d7c760d608b5..434e948ddd74 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -62935,14 +62935,12 @@ export namespace Schemas {*/signal_report?: string | null;/**- * How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted.+ * How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit.* @maxLength 200*/signal_report_task_relationship?: string;/** JSON schema used to validate the output of the task. */json_schema?: unknown;- /** If true, this task is for internal use and should not be exposed to end users. */- internal?: boolean;/** If true, the task is hidden from default list responses. */archived?: boolean;/**@@ -78624,14 +78622,12 @@ export namespace Schemas {*/signal_report?: string | null;/**- * How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted.+ * How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit.* @maxLength 200*/signal_report_task_relationship?: string;/** JSON schema used to validate the output of the task. */json_schema?: unknown;- /** If true, this task is for internal use and should not be exposed to end users. */- internal?: boolean;/** If true, the task is hidden from default list responses. */archived?: boolean;/**@@ -79787,14 +79783,12 @@ export namespace Schemas {*/signal_report?: string | null;/**- * How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted.+ * How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit.* @maxLength 200*/signal_report_task_relationship?: string;/** JSON schema used to validate the output of the task. */json_schema?: unknown;- /** If true, this task is for internal use and should not be exposed to end users. */- internal?: boolean;/** If true, the task is hidden from default list responses. */archived?: boolean;/**diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex f20a1fd0dbb6..f4c1a7b966de 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -314,7 +314,7 @@ export const SignalsReportArtefactsPartialUpdateBody = /* @__PURE__ */ zod)/**- * 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).+ * 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). `task_run` artefacts are an append-only work log and cannot be deleted.* @summary Delete an artefact*/export const SignalsReportArtefactsDestroyParams = /* @__PURE__ */ zod.object({diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex 3bd8a573b0af..1ce0570f3faa 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -1028,13 +1028,9 @@ export const TasksCreateBody = /* @__PURE__ */ zod.max(tasksCreateBodySignalReportTaskRelationshipMax).optional().describe(- "How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted."+ "How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit."),json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),- internal: zod- .boolean()- .optional()- .describe('If true, this task is for internal use and should not be exposed to end users.'),archived: zod.boolean().optional().describe('If true, the task is hidden from default list responses.'),ci_prompt: zod.string()diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.tsindex 40a9dcc56732..9b8a62fe0f49 100644--- a/services/mcp/src/tools/generated/tasks.ts+++ b/services/mcp/src/tools/generated/tasks.ts@@ -457,7 +457,6 @@ const TasksCreateSchema = TasksCreateBody.omit({signal_report: true,signal_report_task_relationship: true,json_schema: true,- internal: true,archived: true,ci_prompt: true,branch: true,