: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): mark monitored drafts ready after agent fixes (#100448)
posthog[bot]02a97db5de2e
diff --git a/docs/internal/task-pr-review-handover.md b/docs/internal/task-pr-review-handover.mdnew file mode 100644index 000000000000..805972176031--- /dev/null+++ b/docs/internal/task-pr-review-handover.md@@ -0,0 +1,29 @@+# Automatic review handover for task PRs++Task PRs open as drafts. The snapshot-based PR monitor can make a draft ready after the agent finishes a successful turn and addresses CI failures and review comments. This requests review through the repository's review rules. It never approves or merges a PR.++## Enable the transition++Enable `tasks-pr-auto-ready` for selected users or organizations in PostHog. The flag is off by default and is checked before each attempt. The task must also use the PR loop and `tasks-pr-babysit-snapshot`. Its GitHub integration needs permission to write pull requests. The task-management monitor and local runs do not use this transition.++To keep a PR in draft, add the `keep-draft` label. Create this label in each repository before you enable the flag. The `no-ci` label also prevents the transition. A task run with `state.keep_draft: true` stays in draft. A PR that someone has already made ready or returned to draft is left alone. An explicit preference to open a report PR ready is independent of this transition and can make the PR ready earlier.++## Transition rules++- The latest agent turn must end with `end_turn`. A timeout, cancellation, error, or missing completion result is not success.+- The agent must be inactive, with no queued follow-up message.+- All reported draft checks must pass. Missing, pending, failed, or unknown checks prevent the transition.+- GitHub must confirm that the PR has no merge conflict. No unresolved review thread or changes-requested review can remain.+- GitHub must return the complete list of review threads. A list that GitHub truncates prevents the transition, because the monitor cannot then prove that no thread is unresolved.+- The activity reads the PR again. Its state, commit, and feedback must match the monitor's snapshot, and its repository must match the task run. The branch must match the stored task branch. If no task branch was stored, it must match the branch in the monitor's snapshot.+- The GitHub helper checks the commit, labels, and draft history again before the ready mutation. Repeated attempts do not repeat a completed transition.++GitHub does not provide an atomic ready mutation conditional on a commit. A change can arrive between the final read and mutation. Required checks and human approval apply to the final commit.++Checks that start only after the ready transition do not block that transition. The monitor handles those checks and new review feedback, within its time and iteration limits.++## Observe and stop++The task shows `PR ready for review` after a successful transition. Structured logs record `task_pr_auto_ready_evaluated`, `task_pr_auto_ready_skipped`, `task_pr_auto_ready_rejected`, and `task_pr_auto_ready_failed`. A GitHub or flag-service failure does not stop CI monitoring. A transport failure can occur after GitHub accepts the mutation; the next attempt reads the draft history instead of repeating the mutation.++To measure the rollout, check completed runs left in draft, the time from a successful iteration to a review request, the failures, and the PRs that people return to draft. Disable `tasks-pr-auto-ready` to stop further automatic transitions. Do not change a PR that is already ready during rollback.diff --git a/ee/hogai/sandbox/__init__.py b/ee/hogai/sandbox/__init__.pyindex 34ef0d4f39de..a46515b5f01b 100644--- a/ee/hogai/sandbox/__init__.py+++ b/ee/hogai/sandbox/__init__.py@@ -7,6 +7,7 @@ from ee.hogai.sandbox.types import (is_turn_complete,pi_turn_error,turn_complete_trace_id,+ turn_completed_successfully,)__all__ = [@@ -18,4 +19,5 @@ __all__ = ["is_turn_complete","pi_turn_error","turn_complete_trace_id",+ "turn_completed_successfully",]diff --git a/ee/hogai/sandbox/test_turn_event_contract.py b/ee/hogai/sandbox/test_turn_event_contract.pyindex 2e7a44251160..87c58c20fb8d 100644--- a/ee/hogai/sandbox/test_turn_event_contract.py+++ b/ee/hogai/sandbox/test_turn_event_contract.py@@ -3,7 +3,12 @@ from pathlib import Pathimport pytest-from ee.hogai.sandbox.types import is_idle_resume_turn_complete, is_turn_complete, pi_turn_error+from ee.hogai.sandbox.types import (+ is_idle_resume_turn_complete,+ is_turn_complete,+ pi_turn_error,+ turn_completed_successfully,+)@pytest.mark.parametrize(@@ -18,4 +23,5 @@ def test_turn_event_contract(event: dict[str, object], expected: dict[str, bool]"turn_complete": is_turn_complete(event),"idle_resume": is_idle_resume_turn_complete(event),"pi_error": pi_turn_error(event),- } == {key: expected[key] for key in ("turn_complete", "idle_resume", "pi_error")}+ "successful": turn_completed_successfully(event),+ } == {key: expected[key] for key in ("turn_complete", "idle_resume", "pi_error", "successful")}diff --git a/ee/hogai/sandbox/turn_event_contract.json b/ee/hogai/sandbox/turn_event_contract.jsonindex 51f4f3b7f4a2..4ff0a345c4cd 100644--- a/ee/hogai/sandbox/turn_event_contract.json+++ b/ee/hogai/sandbox/turn_event_contract.json@@ -11,7 +11,8 @@"turn_complete": true,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -29,7 +30,8 @@"turn_complete": true,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": true}},{@@ -47,7 +49,8 @@"turn_complete": true,"idle_resume": true,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -65,7 +68,8 @@"turn_complete": true,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -81,7 +85,8 @@"turn_complete": true,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -97,7 +102,8 @@"turn_complete": true,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -115,7 +121,8 @@"turn_complete": true,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -132,7 +139,8 @@"turn_complete": true,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": true}},{@@ -149,7 +157,8 @@"turn_complete": false,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -166,7 +175,8 @@"turn_complete": false,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -181,7 +191,8 @@"turn_complete": true,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -197,7 +208,8 @@"turn_complete": true,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": true}},{@@ -213,7 +225,8 @@"turn_complete": true,"idle_resume": false,"pi_error": true,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -229,7 +242,8 @@"turn_complete": false,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -241,7 +255,8 @@"turn_complete": false,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -254,7 +269,8 @@"turn_complete": false,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -272,7 +288,8 @@"turn_complete": false,"idle_resume": false,"pi_error": false,- "session_update": true+ "session_update": true,+ "successful": false}},{@@ -290,7 +307,8 @@"turn_complete": false,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -302,7 +320,8 @@"turn_complete": false,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -315,7 +334,8 @@"turn_complete": false,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -328,7 +348,8 @@"turn_complete": false,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -341,7 +362,8 @@"turn_complete": false,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}},{@@ -351,7 +373,8 @@"turn_complete": false,"idle_resume": false,"pi_error": false,- "session_update": false+ "session_update": false,+ "successful": false}}]diff --git a/ee/hogai/sandbox/types.py b/ee/hogai/sandbox/types.pyindex b6e12960b1ba..5a28f1491382 100644--- a/ee/hogai/sandbox/types.py+++ b/ee/hogai/sandbox/types.py@@ -73,6 +73,30 @@ def pi_turn_error(event: dict) -> bool:return pi_event.get("stopReason") == PI_STOP_REASON_ERROR+def turn_completed_successfully(event: Mapping[str, object]) -> bool:+ """True when a turn-closing event reports ``end_turn`` as its stop reason.++ `is_turn_complete` answers "the turn is over". This answers "the turn is over and the+ agent finished its work", which a caller needs before it acts on the turn's result. The+ stop reason sits in a different place in each of the three envelopes.+ """+ if event.get("type") == PI_EVENT_TYPE:+ pi_event = event.get("event")+ if not isinstance(pi_event, dict) or pi_event.get("type") != PI_TURN_COMPLETED_TYPE:+ return False+ return pi_event.get("stopReason") == STOP_REASON_END_TURN+ if event.get("type") != ACP_NOTIFICATION_TYPE:+ return False+ notification = event.get("notification")+ if not isinstance(notification, dict):+ return False+ if notification.get("method") == TURN_COMPLETE_METHOD:+ params = notification.get("params")+ return isinstance(params, dict) and params.get("stopReason") == STOP_REASON_END_TURN+ result = notification.get("result")+ return isinstance(result, dict) and result.get("stopReason") == STOP_REASON_END_TURN++def turn_complete_trace_id(event: Mapping[str, object]) -> str | None:"""The finished turn's gateway trace id, when the agent reported one.diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex f16138b9366b..38259ac5eabf 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -1950,6 +1950,7 @@ class GitHubIntegrationBase:idisDraftstate+ headRefOidlabels(first: 100) { nodes { name } }timelineItems(itemTypes: [READY_FOR_REVIEW_EVENT, CONVERT_TO_DRAFT_EVENT], first: 1) {nodes { __typename }@@ -1968,7 +1969,12 @@ class GitHubIntegrationBase:"""def mark_pull_request_ready_for_review(- self, repository: str, pr_number: int, *, skip_labels: Collection[str] = ()+ self,+ repository: str,+ pr_number: int,+ *,+ skip_labels: Collection[str] = (),+ expected_head_sha: str | None = None,) -> dict[str, Any]:"""Take a draft pull request out of draft. ``repository`` is ``owner/repo`` or a bare repo.@@ -2003,6 +2009,8 @@ class GitHubIntegrationBase:return {"success": True, "changed": False, "reason": "closed"}if not pr.get("isDraft"):return {"success": True, "changed": False, "reason": "not_draft"}+ if expected_head_sha is not None and pr.get("headRefOid") != expected_head_sha:+ return {"success": True, "changed": False, "reason": "head_changed"}# Somebody already moved this pull request between draft and ready, so its current draft# state is a decision rather than the state it opened in. Reading the timeline is what makes# that durable: a caller that queues this work cannot otherwise tell a pull request that was@@ -2097,9 +2105,10 @@ class GitHubIntegrationBase:query($owner: String!, $repo: String!, $number: Int!) {repository(owner: $owner, name: $repo) {pullRequest(number: $number) {- url state isDraft mergeable headRefOid+ url state isDraft mergeable headRefOid headRefName reviewDecisionauthor { login }reviewThreads(first: 100) {+ pageInfo { hasNextPage }nodes {id isResolved pathcomments(last: 1) {@@ -2233,13 +2242,20 @@ class GitHubIntegrationBase:failing_checks = self._extract_failing_checks(rollup)if not failing_checks and (rollup or {}).get("state") in self._FAILING_ROLLUP_STATES:failing_checks.append({"key": self._ROLLUP_FAILING_CHECK_KEY, "details_url": f"{html_url}/checks"})+ mergeable = self._map_mergeable(pr.get("mergeable"))return {"success": True,"url": html_url,"state": self._map_pr_state(pr.get("state"), bool(pr.get("isDraft"))),"head_sha": pr.get("headRefOid") or "",- "has_conflict": self._map_mergeable(pr.get("mergeable")) is False,+ "has_conflict": mergeable is False,+ "mergeable": mergeable is True,+ "ci_status": self._map_ci_status((rollup or {}).get("state")),+ "review_decision": pr.get("reviewDecision"),+ "review_threads_complete": ((pr.get("reviewThreads") or {}).get("pageInfo") or {}).get("hasNextPage")+ is False,+ "head_ref": pr.get("headRefName"),"author_login": author_login,"failing_checks": failing_checks,"unresolved_threads": unresolved_threads,diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.pyindex 47e1ca7c1d5e..8015fc759237 100644--- a/products/tasks/backend/logic/stream/event_ingest.py+++ b/products/tasks/backend/logic/stream/event_ingest.py@@ -34,7 +34,13 @@ from products.tasks.backend.metrics import observe_stream_write_skippedfrom products.tasks.backend.models import TaskRunfrom products.tasks.backend.push_dispatcher import dispatch_task_run_turn_completed-from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE, is_idle_resume_turn_complete, is_turn_complete, pi_turn_error+from ee.hogai.sandbox import (+ PI_RUNTIME_ERROR_MESSAGE,+ is_idle_resume_turn_complete,+ is_turn_complete,+ pi_turn_error,+ turn_completed_successfully,+)logger = structlog.get_logger(__name__)@@ -483,7 +489,11 @@ async def _heartbeat_workflow_if_needed(redis_stream: TaskRunRedisStream, run_idif pi_turn_error(event):await _dispatch_turn_failed(run_id)else:- await _dispatch_turn_completed(run_id, turn_completed=not is_idle_resume_turn_complete(event))+ await _dispatch_turn_completed(+ run_id,+ succeeded=turn_completed_successfully(event),+ turn_completed=not is_idle_resume_turn_complete(event),+ )returnif _is_session_update(event):@@ -534,11 +544,13 @@ def _signal_agent_boot_milestone(return task_run.signal_agent_boot_milestone(milestone)-async def _dispatch_turn_completed(run_id: str, *, turn_completed: bool = True) -> None:- await sync_to_async(_dispatch_turn_completed_sync, thread_sensitive=True)(run_id, turn_completed=turn_completed)+async def _dispatch_turn_completed(run_id: str, *, succeeded: bool = False, turn_completed: bool = True) -> None:+ await sync_to_async(_dispatch_turn_completed_sync, thread_sensitive=True)(+ run_id, succeeded=succeeded, turn_completed=turn_completed+ )-def _dispatch_turn_completed_sync(run_id: str, *, turn_completed: bool = True) -> None:+def _dispatch_turn_completed_sync(run_id: str, *, succeeded: bool = False, turn_completed: bool = True) -> None:if not settings.TEST:close_old_connections()@@ -548,7 +560,7 @@ def _dispatch_turn_completed_sync(run_id: str, *, turn_completed: bool = True) -logger.warning("task_run_event_ingest_turn_completed_run_missing", run_id=run_id)return- task_run.signal_agent_turn_completed()+ task_run.signal_agent_turn_completed(succeeded=succeeded)dispatch_task_run_turn_completed(task_run, turn_completed=turn_completed)diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex eb8983797271..2488e93c9263 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -2603,7 +2603,7 @@ class TaskRun(models.Model):except Exception as e:logger.warning("task_run.heartbeat_failed", task_run_id=str(self.id), error=str(e))- def signal_agent_turn_completed(self) -> None:+ def signal_agent_turn_completed(self, *, succeeded: bool = False) -> None:import asynciofrom posthog.temporal.common.client import sync_connect@@ -2613,7 +2613,12 @@ class TaskRun(models.Model):try:client = sync_connect()handle = client.get_workflow_handle(self.workflow_id)- asyncio.run(handle.signal(ProcessTaskWorkflow.agent_state_changed, arg=False))++ async def signal_completion() -> None:+ await handle.signal(ProcessTaskWorkflow.agent_state_changed, arg=False)+ await handle.signal(ProcessTaskWorkflow.agent_turn_completed, arg=succeeded)++ asyncio.run(signal_completion())except Exception as e:logger.warning("task_run.turn_completed_signal_failed", task_run_id=str(self.id), error=str(e))@@ -2781,6 +2786,15 @@ class TaskRun(models.Model):error=str(e),)+ @property+ def has_pending_followup_messages(self) -> bool:+ """The persisted view of the workflow's in-memory follow-up queue.++ A caller outside the workflow reads this to tell that a user queued more work which+ the agent has not picked up yet.+ """+ return bool(_read_pending_followup_messages(self.state))+def record_pending_followup_message(self, message_id: str, content: str, *, accepted_at: datetime) -> None:record = {"id": message_id[:MAX_PENDING_FOLLOWUP_MESSAGE_ID_CHARS],diff --git a/products/tasks/backend/temporal/__init__.py b/products/tasks/backend/temporal/__init__.pyindex 326b284763cb..4c4db9363fa5 100644--- a/products/tasks/backend/temporal/__init__.py+++ b/products/tasks/backend/temporal/__init__.py@@ -55,6 +55,7 @@ from .process_task.activities import (from .process_task.activities.feature_flags import is_slack_app_agent_design_enabled_for_task_activityfrom .process_task.activities.get_pr_babysit_snapshot import get_pr_babysit_snapshotfrom .process_task.activities.get_pr_context import get_pr_context+from .process_task.activities.mark_pr_ready import mark_pr_readyfrom .process_task.activities.slack_agent_design import (append_slack_agent_design_steps,start_slack_agent_design_stream,@@ -116,6 +117,7 @@ ACTIVITIES = [update_task_run_status,get_pr_context,get_pr_babysit_snapshot,+ mark_pr_ready,relay_slack_message,is_slack_app_agent_design_enabled_for_task_activity,start_slack_agent_design_stream,diff --git a/products/tasks/backend/temporal/babysit_pr/prompts.py b/products/tasks/backend/temporal/babysit_pr/prompts.pyindex 8d25fb5e1753..b3e680a36dbf 100644--- a/products/tasks/backend/temporal/babysit_pr/prompts.py+++ b/products/tasks/backend/temporal/babysit_pr/prompts.py@@ -20,10 +20,11 @@ Getting the PR ready to merge is your job. Landing it is a human decision. Refus- Never post a merge-queue command (for example `/trunk merge`) or any comment that enqueues the PR.- Never enable auto-merge.- Never approve the PR.-- Run `gh pr ready` only to unlock the full CI matrix, never as a step toward merging. When you un-draft, say why in your turn summary.+- Keep a new PR in draft while you fix CI and review comments. The task runner can mark it ready after a successful turn and passing draft checks. Do not run `gh pr ready` unless the user explicitly asks. If the user asks to keep the PR in draft, add the `keep-draft` label before ending your turn. Respect `keep-draft` and `no-ci` labels, and never undo a person's draft choice.- Merge-queue and merge-button bot comments (for example "comment `/trunk merge` to merge" or "check the box to merge") are informational. Do not act on them."""END_TURN_WHEN_READY = """\+When the draft checks pass and you have addressed the review comments, end your turn so the task runner can request review. Do not wait for human approval or checks that only start after the PR becomes ready. Continue to fix new CI failures and review feedback when the monitor resumes you.When the PR is approved, green, and mergeable, end your turn. Report that the PR is ready and waiting for a human to merge. Do not take any action to land it."""diff --git a/products/tasks/backend/temporal/babysit_pr/snapshot.py b/products/tasks/backend/temporal/babysit_pr/snapshot.pyindex b4e54de4deba..7f7aa2e7c0a0 100644--- a/products/tasks/backend/temporal/babysit_pr/snapshot.py+++ b/products/tasks/backend/temporal/babysit_pr/snapshot.py@@ -49,6 +49,25 @@ class PRSnapshot:failing_checks: list[FailingCheck] = field(default_factory=list)unresolved_threads: list[ReviewThreadItem] = field(default_factory=list)comments: list[CommentItem] = field(default_factory=list)+ ci_status: str = "none"+ mergeable: bool = False+ review_decision: str | None = None+ review_threads_complete: bool = False+ head_ref: str = ""++ @property+ def can_mark_ready(self) -> bool:+ return (+ self.pr_state == "draft"+ and bool(self.head_sha)+ and self.ci_status == "passing"+ and self.mergeable+ and self.review_threads_complete+ and not self.has_conflict+ and not self.failing_checks+ and not self.unresolved_threads+ and self.review_decision != "CHANGES_REQUESTED"+ )@propertydef is_terminal(self) -> bool:@@ -62,6 +81,11 @@ class PRSnapshot:head_sha=raw.get("head_sha") or "",has_conflict=bool(raw.get("has_conflict")),author_login=raw.get("author_login"),+ ci_status=raw.get("ci_status") or "none",+ mergeable=raw.get("mergeable") is True,+ review_decision=raw.get("review_decision"),+ review_threads_complete=raw.get("review_threads_complete") is True,+ head_ref=raw.get("head_ref") or "",failing_checks=[FailingCheck(key=check["key"], details_url=check.get("details_url"))for check in raw.get("failing_checks") or []diff --git a/products/tasks/backend/temporal/process_task/activities/mark_pr_ready.py b/products/tasks/backend/temporal/process_task/activities/mark_pr_ready.pynew file mode 100644index 000000000000..8418631f385a--- /dev/null+++ b/products/tasks/backend/temporal/process_task/activities/mark_pr_ready.py@@ -0,0 +1,112 @@+import posthoganalytics+from temporalio import activity++from posthog.dataclasses import frozen+from posthog.models.integration import GitHubIntegration+from posthog.temporal.common.utils import close_db_connections++from products.tasks.backend.models import TaskRun+from products.tasks.backend.temporal.babysit_pr.snapshot import PRSnapshot+from products.tasks.backend.temporal.observability import log_activity_execution+from products.tasks.backend.temporal.process_task.activities.get_pr_context import (+ get_github_integration,+ get_user_github_integration,+)+from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext++AUTO_READY_FEATURE_FLAG = "tasks-pr-auto-ready"+KEEP_DRAFT_LABELS = frozenset({"keep-draft", "no-ci"})+++@frozen+class MarkPrReadyInput:+ context: TaskProcessingContext+ snapshot: PRSnapshot+++def _run_still_wants_review(run: TaskRun, pr_url: str) -> bool:+ return (+ run.status == TaskRun.Status.IN_PROGRESS+ and (run.output or {}).get("pr_url") == pr_url+ and (run.state or {}).get("keep_draft") is not True+ and not run.has_pending_followup_messages+ )+++@close_db_connections+def mark_pr_ready(input: MarkPrReadyInput) -> bool:+ context = input.context+ with log_activity_execution("mark_pr_ready", **context.to_log_context()):+ try:+ if not context.has_github_credentials or not input.snapshot.can_mark_ready:+ return False++ run = TaskRun.objects.filter(id=context.run_id, team_id=context.team_id).first()+ if run is None or not _run_still_wants_review(run, input.snapshot.pr_url):+ return False++ parsed = GitHubIntegration.parse_pull_request_url(input.snapshot.pr_url)+ if parsed is None or parsed.repository.casefold() != (context.repository or "").casefold():+ return False++ enabled = posthoganalytics.feature_enabled(+ AUTO_READY_FEATURE_FLAG,+ distinct_id=context.distinct_id,+ groups={"organization": context.organization_id},+ group_properties={"organization": {"id": context.organization_id}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ if enabled is not True:+ return False++ github = (+ get_github_integration(context.github_integration_id)+ if context.github_integration_id+ else get_user_github_integration(str(context.github_user_integration_id))+ )+ raw = github.get_pull_request_babysit_snapshot(input.snapshot.pr_url)+ current = PRSnapshot.from_raw(raw, input.snapshot.pr_url)+ expected_branch = run.branch or context.branch or input.snapshot.head_ref+ if (+ not raw.get("success")+ or not expected_branch+ or current.head_ref != expected_branch+ or current != input.snapshot+ or not current.can_mark_ready+ ):+ activity.logger.info(+ "task_pr_auto_ready_skipped", extra={"reason": "pr_changed", "run_id": context.run_id}+ )+ return False++ # The workflow checked its follow-up queue before it started this activity, and a+ # message the user sent since then only reached the run row. Read that row again here,+ # next to the mutation, so new work queued while the GitHub calls above were in flight+ # keeps the pull request in draft.+ fresh = TaskRun.objects.filter(id=context.run_id, team_id=context.team_id).first()+ if fresh is None or not _run_still_wants_review(fresh, input.snapshot.pr_url):+ activity.logger.info(+ "task_pr_auto_ready_skipped", extra={"reason": "run_changed", "run_id": context.run_id}+ )+ return False++ result = github.mark_pull_request_ready_for_review(+ parsed.repository,+ parsed.number,+ skip_labels=KEEP_DRAFT_LABELS,+ expected_head_sha=current.head_sha,+ )+ if result.get("success") is not True:+ activity.logger.warning("task_pr_auto_ready_rejected", extra={"run_id": context.run_id})+ return False+ changed = result.get("changed") is True+ activity.logger.info(+ "task_pr_auto_ready_evaluated",+ extra={"run_id": context.run_id, "changed": changed, "reason": result.get("reason")},+ )+ return changed+ except Exception:+ activity.logger.exception("task_pr_auto_ready_failed", extra={"run_id": context.run_id})+ return Falsediff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.pyindex 07b81d36d619..02865e808192 100644--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py@@ -53,6 +53,7 @@ from ee.hogai.sandbox import (is_turn_complete,pi_turn_error,turn_complete_trace_id,+ turn_completed_successfully,)logger = structlog.get_logger(__name__)@@ -545,6 +546,11 @@ async def _relay_loop()else:await _signal_safely(workflow_handle, "agent_state_changed", arg=False)+ await _signal_safely(+ workflow_handle,+ "agent_turn_completed",+ arg=turn_completed_successfully(event_data),+ )if sandbox_id and background_logs_enabled:asyncio.create_task(_emit_agentsh_events(sandbox_id, run_id, last_audit_ts_ns))if not turn_failed and task_run is not None and task_run.mode == "interactive":diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_mark_pr_ready.py b/products/tasks/backend/temporal/process_task/activities/tests/test_mark_pr_ready.pynew file mode 100644index 000000000000..39d8e5fb2ae2--- /dev/null+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_mark_pr_ready.py@@ -0,0 +1,137 @@+from dataclasses import replace+from types import SimpleNamespace++import pytest+from unittest.mock import MagicMock, patch++from posthog.models.integration import GitHubIntegration++from products.tasks.backend.temporal.babysit_pr.snapshot import PRSnapshot+from products.tasks.backend.temporal.process_task.activities import mark_pr_ready as ready_module+from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext+from products.tasks.backend.temporal.process_task.activities.mark_pr_ready import MarkPrReadyInput, mark_pr_ready++from ee.hogai.sandbox import turn_completed_successfully+++ "change,requested",+ [+ ("none", True),+ ("disabled", False),+ ("failed_run", False),+ ("keep_draft", False),+ ("queued_followup", False),+ ("followup_queued_mid_flight", False),+ ("different_pr", False),+ ("different_repository", False),+ ("different_branch", False),+ ("unset_branch", True),+ ("unset_branch_changed", False),+ ("new_commit", False),+ ("new_feedback", False),+ ("github_failure", False),+ ],+)+def test_activity_rechecks_run_and_pr_before_requesting_review(monkeypatch, change, requested):+ context = TaskProcessingContext(+ task_id="task-1",+ run_id="run-1",+ team_id=1,+ team_uuid="team-1",+ organization_id="org-1",+ github_integration_id=1,+ repository="example/widgets",+ distinct_id="user-1",+ )+ pr_url = "https://github.com/example/widgets/pull/7"+ raw = {+ "success": True,+ "url": pr_url,+ "state": "draft",+ "head_sha": "head1",+ "head_ref": "posthog/change",+ "ci_status": "passing",+ "mergeable": True,+ "review_threads_complete": True,+ }+ snapshot = PRSnapshot.from_raw(raw, pr_url)+ run = SimpleNamespace(+ status="in_progress",+ branch=raw["head_ref"],+ output={"pr_url": raw["url"]},+ state={},+ has_pending_followup_messages=False,+ )+ late_run = SimpleNamespace(**vars(run))+ github = MagicMock()+ github.mark_pull_request_ready_for_review.return_value = {"success": True, "changed": True}+ if change == "failed_run":+ run.status = "failed"+ elif change == "keep_draft":+ run.state["keep_draft"] = True+ elif change == "queued_followup":+ run.has_pending_followup_messages = True+ elif change == "followup_queued_mid_flight":+ late_run.has_pending_followup_messages = True+ elif change == "different_pr":+ run.output["pr_url"] = "https://github.com/example/widgets/pull/8"+ elif change == "different_repository":+ context = replace(context, repository="example/other")+ elif change == "different_branch":+ raw["head_ref"] = "other"+ elif change in ("unset_branch", "unset_branch_changed"):+ run.branch = None+ if change == "unset_branch_changed":+ raw["head_ref"] = "other"+ elif change == "new_commit":+ raw["head_sha"] = "head2"+ elif change == "new_feedback":+ raw["comments"] = [{"id": "comment-1", "body": "Please change the name"}]+ elif change == "github_failure":+ github.get_pull_request_babysit_snapshot.side_effect = RuntimeError("unavailable")+ github.get_pull_request_babysit_snapshot.return_value = raw+ monkeypatch.setattr(ready_module.posthoganalytics, "feature_enabled", lambda *args, **kwargs: change != "disabled")+ monkeypatch.setattr(ready_module, "get_github_integration", lambda _: github)+ with patch.object(ready_module.TaskRun.objects, "filter") as find_run:+ find_run.return_value.first.side_effect = [run, late_run]+ assert mark_pr_ready(MarkPrReadyInput(context=context, snapshot=snapshot)) is requested+ assert github.mark_pull_request_ready_for_review.called is requested+ if requested:+ github.mark_pull_request_ready_for_review.assert_called_once_with(+ "example/widgets", 7, skip_labels=frozenset({"keep-draft", "no-ci"}), expected_head_sha="head1"+ )++[email protected]("reason", ["end_turn", "cancelled", "error", "refusal", None])+def test_only_successful_completion_enables_handover(reason):+ for event in (+ {"type": "notification", "notification": {"result": {"stopReason": reason}}},+ {+ "type": "notification",+ "notification": {"method": "_posthog/turn_complete", "params": {"stopReason": reason}},+ },+ {"type": "pi_event", "event": {"type": "turn_completed", "stopReason": reason}},+ ):+ assert turn_completed_successfully(event) is (reason == "end_turn")+++ "state,expected_reason",+ [+ ({"headRefOid": "head2"}, "head_changed"),+ ({"labels": {"nodes": [{"name": "Keep-Draft"}]}}, "label"),+ ({"timelineItems": {"nodes": [{"__typename": "ConvertToDraftEvent"}]}}, "draft_state_decided"),+ ({"isDraft": False}, "not_draft"),+ ({"state": "CLOSED"}, "closed"),+ ],+)+def test_final_github_read_preserves_new_commits_and_manual_choices(state, expected_reason):+ github = object.__new__(GitHubIntegration)+ pr = {"id": "PR_1", "state": "OPEN", "isDraft": True, "headRefOid": "head1", **state}+ with patch.object(github, "_gh_graphql", return_value={"repository": {"pullRequest": pr}}) as graphql:+ result = github.mark_pull_request_ready_for_review(+ "example/widgets", 7, expected_head_sha="head1", skip_labels={"keep-draft"}+ )+ assert result == {"success": True, "changed": False, "reason": expected_reason}+ graphql.assert_called_once()diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.pyindex 7f37c19150bd..ca19a756ca2d 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py@@ -863,13 +863,14 @@ class TestRelaySandboxEventsErrorHandling:assert redis_stream.claim_first_agent_activity.await_count == 2@pytest.mark.parametrize(- ("event", "turn_failed", "turn_completed"),+ ("event", "turn_failed", "turn_completed", "turn_succeeded"),[- ({"type": "pi_event", "event": {"type": "turn_completed", "stopReason": "error"}}, True, False),+ ({"type": "pi_event", "event": {"type": "turn_completed", "stopReason": "error"}}, True, False, False),({"type": "notification", "notification": {"method": TURN_COMPLETE_METHOD}},False,True,+ False,),({@@ -878,6 +879,7 @@ class TestRelaySandboxEventsErrorHandling:},False,True,+ True,),({@@ -886,11 +888,17 @@ class TestRelaySandboxEventsErrorHandling:},False,False,+ False,),],)async def test_relay_handles_turn_completion(- self, monkeypatch: pytest.MonkeyPatch, event: dict[str, object], turn_failed: bool, turn_completed: bool+ self,+ monkeypatch: pytest.MonkeyPatch,+ event: dict[str, object],+ turn_failed: bool,+ turn_completed: bool,+ turn_succeeded: bool,) -> None:redis_stream = SimpleNamespace(write_event=AsyncMock(),@@ -960,7 +968,10 @@ class TestRelaySandboxEventsErrorHandling:handle.signal.assert_awaited_once_with("complete_task", args=["failed", PI_RUNTIME_ERROR_MESSAGE])else:await asyncio.wait_for(dispatch_done.wait(), timeout=5)- handle.signal.assert_awaited_once_with("agent_state_changed", arg=False)+ assert handle.signal.await_args_list == [+ call("agent_state_changed", arg=False),+ call("agent_turn_completed", arg=turn_succeeded),+ ]if turn_completed:notify.assert_called_once_with(task_run)else:diff --git a/products/tasks/backend/temporal/process_task/tests/test_ci_follow_up_decision.py b/products/tasks/backend/temporal/process_task/tests/test_ci_follow_up_decision.pyindex e434c38ab341..10a376953064 100644--- a/products/tasks/backend/temporal/process_task/tests/test_ci_follow_up_decision.py+++ b/products/tasks/backend/temporal/process_task/tests/test_ci_follow_up_decision.py@@ -15,8 +15,10 @@ from products.tasks.backend.temporal.process_task import workflow as process_tasfrom products.tasks.backend.temporal.process_task.activities.get_pr_babysit_snapshot import get_pr_babysit_snapshotfrom products.tasks.backend.temporal.process_task.activities.get_pr_context import GetPrContextOutput, get_pr_contextfrom products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext+from products.tasks.backend.temporal.process_task.activities.mark_pr_ready import mark_pr_readyfrom products.tasks.backend.temporal.process_task.workflow import (CIFollowUpDecision,+ PendingFollowup,ProcessTaskInput,ProcessTaskWorkflow,ResumedSandboxState,@@ -212,6 +214,54 @@ def _capture_dispatched_messages(monkeypatch) -> list[str]:class TestBabysitFollowUpDecision:+ @pytest.mark.parametrize(+ "succeeded,active,queued,overrides,expected",+ [+ (True, False, False, {}, True),+ (False, False, False, {}, False),+ (True, True, False, {}, False),+ (True, False, True, {}, False),+ (True, False, False, {"ci_status": "pending"}, False),+ (True, False, False, {"ci_status": "none"}, False),+ (True, False, False, {"failing_checks": [BABYSIT_CHECK]}, False),+ (True, False, False, {"unresolved_threads": [BABYSIT_THREAD]}, False),+ (True, False, False, {"review_threads_complete": False}, False),+ (True, False, False, {"review_decision": "CHANGES_REQUESTED"}, False),+ (True, False, False, {"mergeable": False}, False),+ ],+ )+ async def test_ready_handover_requires_a_successful_idle_turn_and_safe_snapshot(+ self, monkeypatch, succeeded, active, queued, overrides, expected+ ):+ wf = _babysit_workflow()+ wf._last_turn_succeeded = succeeded+ wf._agent_active = active+ wf._end_of_turn_received = not active+ if queued:+ wf._pending_followups.append(PendingFollowup(message="More work", artifact_ids=[]))+ snapshot = _babysit_snapshot(+ **{+ "pr_state": "draft",+ "ci_status": "passing",+ "mergeable": True,+ "review_threads_complete": True,+ **overrides,+ }+ )+ executed = []++ async def execute(activity_fn, *args, **kwargs):+ executed.append(activity_fn)+ return snapshot if activity_fn is get_pr_babysit_snapshot else False++ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", execute)+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", lambda _: True)+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())++ await wf._should_run_ci_follow_up()++ assert (mark_pr_ready in executed) is expected+@pytest.mark.parametrize("pr_babysit_enabled,expected_activity",[@@ -297,11 +347,13 @@ class TestBabysitFollowUpDecision:assert await wf._should_run_ci_follow_up() is CIFollowUpDecision.FIREawait wf._dispatch_ci_follow_up()wf._chain_started_at = datetime(2026, 8, 18, tzinfo=UTC)+ wf._last_turn_succeeded = Trueresumed = wf._build_resumed_input(ProcessTaskInput(run_id="run-1"), "sandbox-1").resumed_sandboxassert resumed is not Nonecontinuation = _babysit_workflow()continuation._restore_resumed_state(resumed)+ assert continuation._last_turn_succeeded is Trueassert await continuation._should_run_ci_follow_up() is CIFollowUpDecision.SKIPassert len(sent) == 1diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex d5c6e3f55cbf..2c8fd5513d13 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -38,6 +38,7 @@ from products.tasks.backend.temporal.process_task.activities.get_pr_context impoget_pr_context,is_pr_actionable,)+from products.tasks.backend.temporal.process_task.activities.mark_pr_ready import MarkPrReadyInput, mark_pr_readyfrom .activities.cleanup_sandbox import (CleanupSandboxInput,@@ -207,6 +208,7 @@ class ResumedSandboxState:chain_started_at: Optional[str] = Noneagent_active: Optional[bool] = Noneend_of_turn_received: Optional[bool] = None+ last_turn_succeeded: bool = Falselast_agent_heartbeat_at: Optional[str] = Nonesandbox_ttl_expires_at: Optional[str] = Nonesandbox_ttl_snapshot_taken: bool = False@@ -496,6 +498,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._client_activity_received: bool = Falseself._agent_active: Optional[bool] = Noneself._end_of_turn_received: Optional[bool] = None+ self._last_turn_succeeded = Falseself._turn_ended_received = Falseself._last_agent_heartbeat_at: Optional[datetime] = Noneself._prewarmed: bool = False@@ -1102,6 +1105,30 @@ class ProcessTaskWorkflow(PostHogWorkflow):return CIFollowUpDecision.TERMINALattention = self._babysit_journal.attention(snapshot)if attention.is_empty:+ if (+ self._last_turn_succeeded+ and self._end_of_turn_received is True+ and self._agent_active is False+ and self._pending_followup is None+ and not self._pending_followups+ and not self._task_completed+ and snapshot.can_mark_ready+ and workflow.patched("tasks-pr-auto-ready-v1")+ ):+ try:+ changed = await workflow.execute_activity(+ mark_pr_ready,+ MarkPrReadyInput(context=self.context, snapshot=snapshot),+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ except temporalio.exceptions.ActivityError:+ workflow.logger.exception(+ "task_pr_auto_ready_activity_failed", extra={"run_id": self.context.run_id}+ )+ changed = False+ if changed:+ await self._emit_progress("pr", "completed", "PR ready for review", "setup", detail=snapshot.pr_url)workflow.logger.info("PR has nothing needing attention, skipping CI follow-up",extra={@@ -1882,6 +1909,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):chain_started_at=self._chain_start_time().isoformat(),agent_active=self._agent_active,end_of_turn_received=self._end_of_turn_received,+ last_turn_succeeded=self._last_turn_succeeded,last_agent_heartbeat_at=(self._last_agent_heartbeat_at.isoformat() if self._last_agent_heartbeat_at else None),@@ -1923,6 +1951,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._last_active_time = datetime.fromisoformat(resumed.last_active_time) if resumed.last_active_time else Noneself._agent_active = resumed.agent_activeself._end_of_turn_received = resumed.end_of_turn_received+ self._last_turn_succeeded = resumed.last_turn_succeededself._last_agent_heartbeat_at = (datetime.fromisoformat(resumed.last_agent_heartbeat_at) if resumed.last_agent_heartbeat_at else None)@@ -3312,9 +3341,14 @@ class ProcessTaskWorkflow(PostHogWorkflow):async def agent_state_changed(self, agent_active: bool) -> None:self._agent_active = agent_activeself._end_of_turn_received = not agent_active+ self._last_turn_succeeded = Falseif not agent_active and _turn_opens_on_dispatch():self._turn_ended_received = True+ @temporalio.workflow.signal+ async def agent_turn_completed(self, succeeded: bool = False) -> None:+ self._last_turn_succeeded = self._agent_active is False and succeeded+@temporalio.workflow.signalasync def agent_command_dispatched(self) -> None:self._record_first_command_dispatched()diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.pyindex 86a8320f8412..b3d25bf2d6fb 100644--- a/products/tasks/backend/tests/test_event_ingest.py+++ b/products/tasks/backend/tests/test_event_ingest.py@@ -532,19 +532,30 @@ class TestTaskRunEventIngest(TestCase):@parameterized.expand([- ("acp", {"type": "notification", "notification": {"method": "_posthog/turn_complete"}}),- ("pi", {"type": "pi_event", "event": {"type": "turn_completed"}}),+ (runtime, reason, reason == "end_turn")+ for runtime in ("acp", "pi")+ for reason in ("end_turn", "cancelled", None)])@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)- def test_turn_complete_ingest_signals_the_workflow_for_a_background_run(self, _name: str, event: dict) -> None:+ def test_turn_complete_ingest_signals_the_workflow_for_a_background_run(+ self, runtime: str, reason: str | None, succeeded: bool+ ) -> None:token = self._create_token()+ event = (+ {"type": "pi_event", "event": {"type": "turn_completed", "stopReason": reason}}+ if runtime == "pi"+ else {+ "type": "notification",+ "notification": {"method": "_posthog/turn_complete", "params": {"stopReason": reason}},+ }+ )with patch.object(TaskRun, "signal_agent_turn_completed") as signal_turn_completed:status, _ = self._call_ingest(token, [{"seq": 1, "event": event}])self.assertEqual(status, 200)- signal_turn_completed.assert_called_once()+ signal_turn_completed.assert_called_once_with(succeeded=succeeded)@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)def test_pi_turn_completed_with_a_runtime_error_fails_the_run_instead_of_completing_it(self) -> None:diff --git a/services/agent-proxy/tests/lib/side-effects.test.ts b/services/agent-proxy/tests/lib/side-effects.test.tsindex 4d6625c680fe..a3d22a1d1dce 100644--- a/services/agent-proxy/tests/lib/side-effects.test.ts+++ b/services/agent-proxy/tests/lib/side-effects.test.ts@@ -8,16 +8,19 @@ const cases = JSON.parse() as {name: stringevent: Record<string, unknown>- expect: { turn_complete: boolean; idle_resume: boolean; pi_error: boolean; session_update: boolean }+ expect: Record<string, boolean>}[]+// The fixture also carries expectations for predicates only the Python side has, so+// each side compares the keys it implements.describe('turn event contract', () => {it.each(cases)('$name', ({ event, expect: expected }) => {- expect({+ const actual = {turn_complete: isTurnComplete(event),idle_resume: isIdleResumeTurnComplete(event),pi_error: isPiTurnError(event),session_update: isSessionUpdate(event),- }).toEqual(expected)+ }+ expect(actual).toEqual(Object.fromEntries(Object.keys(actual).map((key) => [key, expected[key]])))})})