Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(autoresearch): add the suggestion endpoints (18/22) (#89153)

Andrew Maguire25d6a2be251c
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.py
index 901e9c32c264..e13f85ea2f58 100644
--- a/products/autoresearch/backend/facade/api.py
+++ b/products/autoresearch/backend/facade/api.py
@@ -16,7 +16,7 @@ from typing import Any
from uuid import UUID, uuid4
from django.db import transaction
-from django.db.models import F, Q
+from django.db.models import F, Prefetch, Q
from django.utils import timezone as django_timezone
from posthog.models.team import Team
@@ -65,6 +65,8 @@ from .contracts import (
ResolvedTemplate,
Run,
StoredArtifact,
+ Suggestion,
+ SuggestionNotFound as SuggestionNotFound,
TemplateInfo,
TrainingRun,
TrainingRunHistory,
@@ -228,6 +230,22 @@ def _iteration_to_contract(row: AutoresearchIteration) -> Iteration:
)
+def _suggestion_to_contract(row: AutoresearchSuggestion) -> Suggestion:
+ return Suggestion(
+ id=row.id,
+ pipeline=row.pipeline_id,
+ prompt=row.prompt,
+ priority=row.priority,
+ status=row.status,
+ source=row.source,
+ agent_response=row.agent_response,
+ created_by=row.created_by,
+ linked_iteration_ids=[iteration.id for iteration in row.iterations.all()],
+ created_at=row.created_at,
+ updated_at=row.updated_at,
+ )
+
+
def _run_to_contract(row: AutoresearchRun) -> Run:
return Run(
id=row.id,
@@ -662,6 +680,8 @@ def _parent_suggestion_row(
)
if suggestion is None:
raise AutoresearchConflict("parent_suggestion not found on this pipeline.")
+ if suggestion.status == AutoresearchSuggestion.Status.DISMISSED:
+ raise AutoresearchConflict("parent_suggestion was dismissed, so an iteration cannot act on it.")
return suggestion
@@ -1015,6 +1035,116 @@ def delete_artifact(
return ArtifactDeleteResult(path=normalized, deleted=deleted)
+# ── Suggestions ────────────────────────────────────────────────────────────
+
+
+def list_suggestions(
+ team_id: int, *, pipeline_id: str | UUID | None, offset: int, limit: int
+) -> tuple[list[Suggestion], int]:
+ qs = _suggestion_rows(team_id, pipeline_id=pipeline_id).order_by("-created_at")
+ count = qs.count()
+ return [_suggestion_to_contract(row) for row in qs[offset : offset + limit]], count
+
+
+def _suggestion_rows(team_id: int, *, pipeline_id: str | UUID | None) -> Any:
+ """Suggestions in this team, and under ``pipeline_id`` when the route names one.
+
+ The contract lists the linked iteration ids, so they are prefetched here instead of read
+ once per row when a page is serialized.
+ """
+ qs = (
+ AutoresearchSuggestion.objects.for_team(team_id)
+ .select_related("pipeline", "created_by")
+ .prefetch_related(
+ Prefetch(
+ "iterations",
+ queryset=AutoresearchIteration.objects.for_team(team_id).only("id", "parent_suggestion_id"),
+ )
+ )
+ )
+ if pipeline_id:
+ qs = qs.filter(pipeline_id=_as_uuid(pipeline_id))
+ return qs
+
+
+def get_suggestion(
+ team_id: int, suggestion_id: str | UUID, *, pipeline_id: str | UUID | None = None
+) -> Suggestion | None:
+ suggestion_uuid = _as_uuid(suggestion_id)
+ if suggestion_uuid is None:
+ return None
+ row = _suggestion_rows(team_id, pipeline_id=pipeline_id).filter(pk=suggestion_uuid).first()
+ return _suggestion_to_contract(row) if row else None
+
+
+def create_suggestion(
+ team_id: int, pipeline_id: str | UUID, *, prompt: str, priority: str, created_by: Any
+) -> Suggestion:
+ pipeline = _pipeline_row(team_id, pipeline_id)
+ if pipeline.status == AutoresearchPipeline.Status.ARCHIVED:
+ raise AutoresearchConflict("Cannot submit suggestions to an archived pipeline.")
+ row = AutoresearchSuggestion.objects.create(
+ pipeline=pipeline,
+ created_by=created_by,
+ prompt=prompt,
+ priority=priority,
+ source=AutoresearchSuggestion.Source.USER,
+ )
+ return _suggestion_to_contract(row)
+
+
+def respond_to_suggestion(
+ team_id: int,
+ suggestion_id: str | UUID,
+ *,
+ status: str,
+ agent_response: str | None = None,
+ pipeline_id: str | UUID | None = None,
+) -> Suggestion:
+ """Record how the agent handled a suggestion.
+
+ A suggestion only moves forward: queued, then picked up, then acted on or dismissed. A
+ retried or delayed response therefore cannot undo the ``acted_on`` that recording an
+ iteration set, and ``acted_on`` itself is refused until an iteration is linked, because
+ that is what the status promises the reader. The same status again only updates the note.
+ """
+ suggestion_uuid = _as_uuid(suggestion_id)
+ if suggestion_uuid is None:
+ raise SuggestionNotFound("Suggestion not found.")
+ with transaction.atomic():
+ row = (
+ _suggestion_rows(team_id, pipeline_id=pipeline_id)
+ .select_for_update(of=("self",))
+ .filter(pk=suggestion_uuid)
+ .first()
+ )
+ if row is None:
+ raise SuggestionNotFound("Suggestion not found.")
+ if row.pipeline.status == AutoresearchPipeline.Status.ARCHIVED:
+ raise AutoresearchConflict("This pipeline is archived, so its suggestions can no longer be answered.")
+ if status != row.status and _SUGGESTION_RANK[status] <= _SUGGESTION_RANK[row.status]:
+ raise AutoresearchConflict(f"A suggestion cannot move from '{row.status}' to '{status}'.")
+ if status == AutoresearchSuggestion.Status.ACTED_ON and not row.iterations.all():
+ raise AutoresearchConflict(
+ "Record an iteration with parent_suggestion set before marking a suggestion acted_on."
+ )
+ note = row.agent_response if agent_response is None else agent_response
+ if status == AutoresearchSuggestion.Status.DISMISSED and not note.strip():
+ raise AutoresearchConflict("Explain why the suggestion was dismissed in agent_response.")
+ row.status = status
+ row.agent_response = note
+ row.save(update_fields=["status", "agent_response", "updated_at"])
+ return _suggestion_to_contract(row)
+
+
+_SUGGESTION_RANK: dict[str, int] = {
+ AutoresearchSuggestion.Status.QUEUED: 0,
+ AutoresearchSuggestion.Status.PICKED_UP: 1,
+ AutoresearchSuggestion.Status.ACTED_ON: 2,
+ AutoresearchSuggestion.Status.DISMISSED: 2,
+}
+
+
# ── Recipe validation surface for the presentation layer ───────────────────
# The semantic population kinds the labeler can compile. Presentation validates a submitted
@@ -1047,5 +1177,8 @@ VALIDATION_WARNING_CODES = [code.value for code in _ValidationWarningCode]
MODEL_ROLE_CHOICES = AutoresearchModel.Role.choices
TRAINING_RUN_STATUS_CHOICES = AutoresearchTrainingRun.Status.choices
ITERATION_STATUS_CHOICES = AutoresearchIteration.Status.choices
+SUGGESTION_PRIORITY_CHOICES = AutoresearchSuggestion.Priority.choices
+SUGGESTION_STATUS_CHOICES = AutoresearchSuggestion.Status.choices
+SUGGESTION_SOURCE_CHOICES = AutoresearchSuggestion.Source.choices
RUN_TYPE_CHOICES = AutoresearchRun.RunType.choices
RUN_STATUS_CHOICES = AutoresearchRun.Status.choices
diff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.py
index 1b5a5fc5304a..85e3b5b7277b 100644
--- a/products/autoresearch/backend/facade/contracts.py
+++ b/products/autoresearch/backend/facade/contracts.py
@@ -34,6 +34,10 @@ class TrainingRunNotFound(LookupError):
"""No training run with that id in this team."""
+class SuggestionNotFound(LookupError):
+ """No suggestion with that id on this pipeline."""
+
+
class AutoresearchConflict(ValueError):
"""The request is well-formed but the pipeline or run is in the wrong state for it.
@@ -202,6 +206,23 @@ class Iteration:
created_at: datetime
+@dataclass(frozen=True, config={"arbitrary_types_allowed": True})
+class Suggestion:
+ """A free-text hypothesis injected into a running pipeline by a user or agent."""
+
+ id: UUID
+ pipeline: UUID
+ prompt: str
+ priority: str
+ status: str
+ source: str
+ agent_response: str
+ created_by: Any
+ linked_iteration_ids: list[UUID]
+ created_at: datetime
+ updated_at: datetime
+
+
@dataclass(frozen=True)
class Run:
"""Generic operational run: inference or validation."""
diff --git a/products/autoresearch/backend/presentation/AGENTS.md b/products/autoresearch/backend/presentation/AGENTS.md
index d0b24b019786..8994e6e9e746 100644
--- a/products/autoresearch/backend/presentation/AGENTS.md
+++ b/products/autoresearch/backend/presentation/AGENTS.md
@@ -5,15 +5,16 @@ The HTTP surface — and, because of how PostHog's codegen works, considerably m
These serializers are the source of truth for three downstream artifacts: the REST API itself, the generated frontend TypeScript types, and the 29 `autoresearch-*` MCP tools that the sandbox agent uses to drive its own training run.
A vague `help_text` here becomes a vague tool description that a model has to guess at. Treat serializer annotations as agent-facing documentation, because they are.
-This package lands one endpoint group at a time. Pipeline CRUD, the pre-create helpers, the read-only model and run viewsets, and the whole training-run agent surface are here; the lifecycle actions and suggestions arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464). The MCP tools arrive at the end of it.
+The pipeline lifecycle actions (`train`, `score`, `validate-online`, `archive`, `pause`, `resume`) arrive with the last API piece of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), and the MCP tools at its end.
## What lives here
- `views/views.py`
- Four viewsets, registered in `../routes.py` under `project_autoresearch_*` basenames and nested pipeline-first.
+ Five viewsets, registered in `../routes.py` under `project_autoresearch_*` basenames and nested pipeline-first.
- `AutoresearchPipelineViewSet` — full CRUD plus the pre-create helpers `templates`, `resolve-template`, `validate`.
- `AutoresearchTrainingRunViewSet` — read plus create, and **the agent's entire write surface**: `iterations`, `materialize-features`, `complete`, `artifacts`, `artifacts/upload`, `artifacts/get`, `artifacts/delete`, plus `history`.
- `AutoresearchModelViewSet`, `AutoresearchRunViewSet` — read-only.
+ - `AutoresearchSuggestionViewSet` — human or agent hypotheses, plus `respond`.
- `views/serializers.py`
Request and response shapes, plus `resolve_target()`, which turns a pipeline's `target_event` or `target_definition` (an action reference) into the resolved target the rest of the product uses.
It refuses the product's own `autoresearch_prediction` event, and an action with a step that can match it, because the labeler and online validation exclude that event from every scan.
@@ -43,12 +44,13 @@ Consequences worth internalizing:
- **The write surface closes when the run does.** `iterations`, `materialize-features`, `complete`, `artifacts/upload`, and `artifacts/delete` all require the run to be RUNNING (or PENDING for `complete`), so a finished run's artifact bundle is frozen — scoring reads it, nothing rewrites it. Artifact reads stay open. Recording, uploading and deleting take the run row lock that completion takes, so the status check and the write see one state: an iteration cannot land on a completed run, and a bundle file cannot change after completion validated the bundle. Recording also refuses a new `iteration_number` once the run's `iteration_budget` is used.
- **Nested writes are bound to the pipeline in the URL.** A run id under another pipeline's route is a 404, the same as the nested reads.
- **`complete` does not accept a champion.** It triggers `complete_training_run()` in `../training/promotion.py`, which picks the champion server-side from the recorded iterations. The agent cannot promote itself.
+- **A suggestion only moves forward.** `respond` refuses a status below the current one (queued, picked up, then acted on or dismissed), refuses `acted_on` until an iteration is linked, and requires a reason to dismiss; recording an iteration with `parent_suggestion` is what advances a suggestion to `acted_on`. The same status again only updates the note.
- **`materialize-features` is sandbox-scoped.** It verifies the sandbox belongs to this training run before writing anything into it, resolves the sandbox provider from the persisted sandbox id, and writes each request's parquet into its own directory so overlapping requests cannot read each other's files. It runs caller-authored HogQL, so it needs `query:read` on a scoped token and takes the ClickHouse throttles, like the pipeline viewset's query-backed actions.
- If the agent cannot reach these tools, a run burns its full budget doing nothing and fails with `"Agent recorded no iterations before the run ended."` That symptom is almost always MCP connectivity, not the model.
## Where the rest of the system meets this package
-- **Routing** — `../routes.py` (`register_routes`), nested pipeline → models / runs / training_runs.
+- **Routing** — `../routes.py` (`register_routes`), nested pipeline → models / runs / training_runs / suggestions.
- **Frontend types** — generated into `../../frontend/generated/` via drf-spectacular + Orval. Never hand-edit those; change the serializer and regenerate with `hogli build:openapi`.
- **Calls into** — `../training/` (complete), `../dataset/` (validate, templates, `resolve_target`).
diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.py
index b9e9cb3e86d4..13efa79cdb64 100644
--- a/products/autoresearch/backend/presentation/views/serializers.py
+++ b/products/autoresearch/backend/presentation/views/serializers.py
@@ -22,6 +22,7 @@ from products.autoresearch.backend.facade.contracts import (
Pipeline,
PipelineWrite,
Run,
+ Suggestion,
TrainingRun,
)
@@ -37,6 +38,9 @@ RUN_STATUS_CHOICES = api.RUN_STATUS_CHOICES
RUN_TYPE_CHOICES = api.RUN_TYPE_CHOICES
TRAINING_RUN_STATUS_CHOICES = api.TRAINING_RUN_STATUS_CHOICES
ITERATION_STATUS_CHOICES = api.ITERATION_STATUS_CHOICES
+SUGGESTION_PRIORITY_CHOICES = api.SUGGESTION_PRIORITY_CHOICES
+SUGGESTION_STATUS_CHOICES = api.SUGGESTION_STATUS_CHOICES
+SUGGESTION_SOURCE_CHOICES = api.SUGGESTION_SOURCE_CHOICES
TARGET_EVENT_MAX_LENGTH = 255
AGENT_DESCRIPTION_MAX_LENGTH = 2000
@@ -1355,6 +1359,28 @@ class RecordIterationSerializer(serializers.Serializer):
return data
+class RespondToSuggestionSerializer(serializers.Serializer):
+ """Input for the agent to record how it interpreted a steering suggestion."""
+
+ status = serializers.ChoiceField(
+ choices=["picked_up", "acted_on", "dismissed"],
+ help_text=(
+ "How the agent handled the suggestion: 'picked_up' (applied as a search constraint), "
+ "'acted_on' (spawned one or more iterations), or 'dismissed' (rejected — explain why in agent_response)."
+ ),
+ )
+ agent_response = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ max_length=2000,
+ help_text=(
+ "Plain-English note on how the suggestion was interpreted and acted upon. A dismissal needs a "
+ "note, sent now or recorded earlier. Omit it to keep the note already recorded; send an empty "
+ "string to clear it."
+ ),
+ )
+
+
class CompleteTrainingRunSerializer(serializers.Serializer):
"""Input for finalizing a training run. The backend selects/promotes the champion."""
@@ -1497,6 +1523,76 @@ class ArtifactDeleteResultSerializer(serializers.Serializer):
deleted = serializers.BooleanField(help_text="True if a file existed and was removed; False if nothing was there.")
+# ── Suggestion serializers ─────────────────────────────────────────────────
+
+
+@extend_schema_serializer(component_name="AutoresearchSuggestion")
+class AutoresearchSuggestionSerializer(DataclassSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique UUID of this suggestion.")
+ pipeline = serializers.UUIDField(help_text="Pipeline this suggestion targets.")
+ prompt = serializers.CharField(help_text="Free-text hypothesis or direction for the agent to explore.")
+ priority = serializers.ChoiceField(
+ choices=SUGGESTION_PRIORITY_CHOICES,
+ required=False,
+ help_text="'try_next' instructs the agent to act on this before other iterations; 'consider' is advisory.",
+ )
+ status = serializers.ChoiceField(
+ choices=SUGGESTION_STATUS_CHOICES,
+ read_only=True,
+ help_text="Lifecycle status: 'queued' (awaiting pickup), 'picked_up' (agent is applying as a constraint), 'acted_on' (agent spawned iterations), 'dismissed' (agent rejected with rationale).",
+ )
+ # Named `source` to keep the field the API already exposes; it shadows DRF's own
+ # Field.source attribute, which is a typing conflict only.
+ source = serializers.ChoiceField( # type: ignore[assignment]
+ choices=SUGGESTION_SOURCE_CHOICES,
+ read_only=True,
+ help_text="'user' for human-submitted suggestions; 'agent' for agent-generated hypotheses.",
+ )
+ agent_response = serializers.CharField(
+ read_only=True,
+ allow_blank=True,
+ help_text="Agent's note on how the suggestion was interpreted and acted upon. Populated after pickup.",
+ )
+ created_by = UserBasicSerializer(
+ read_only=True, allow_null=True, help_text="The user who submitted it; null for an agent-authored suggestion."
+ )
+ linked_iteration_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ read_only=True,
+ help_text="UUIDs of iterations spawned from this suggestion.",
+ )
+ created_at = serializers.DateTimeField(read_only=True)
+ updated_at = serializers.DateTimeField(read_only=True)
+
+ class Meta:
+ dataclass = Suggestion
+ fields = [
+ "id",
+ "pipeline",
+ "prompt",
+ "priority",
+ "status",
+ "source",
+ "agent_response",
+ "created_by",
+ "linked_iteration_ids",
+ "created_at",
+ "updated_at",
+ ]
+
+
+class CreateSuggestionSerializer(serializers.Serializer):
+ prompt = serializers.CharField(
+ max_length=2000,
+ help_text="Free-text hypothesis or direction for the agent to explore, e.g. 'try a tree-based model' or 'remove recency features, I suspect leakage'.",
+ )
+ priority = serializers.ChoiceField(
+ choices=["try_next", "consider"],
+ default="consider",
+ help_text="'try_next' asks the agent to act on this before other autonomous iterations; 'consider' is advisory context.",
+ )
+
+
# ── Template serializers ───────────────────────────────────────────────────────
diff --git a/products/autoresearch/backend/presentation/views/views.py b/products/autoresearch/backend/presentation/views/views.py
index 56ac4e3e30c1..e5c945f53291 100644
--- a/products/autoresearch/backend/presentation/views/views.py
+++ b/products/autoresearch/backend/presentation/views/views.py
@@ -38,6 +38,7 @@ from products.autoresearch.backend.facade.contracts import (
AutoresearchConflict,
InvalidArtifactPath,
PipelineNotFound,
+ SuggestionNotFound,
TrainingRunNotFound,
)
@@ -52,14 +53,17 @@ from .serializers import (
AutoresearchPipelineCreateSerializer,
AutoresearchPipelineSerializer,
AutoresearchRunSerializer,
+ AutoresearchSuggestionSerializer,
AutoresearchTrainingRunSerializer,
CompleteTrainingRunSerializer,
+ CreateSuggestionSerializer,
MaterializeFeaturesRequestSerializer,
MaterializeFeaturesResponseSerializer,
OpenTrainingRunSerializer,
RecordIterationSerializer,
ResolvedTemplateSerializer,
ResolveTemplateRequestSerializer,
+ RespondToSuggestionSerializer,
StoredArtifactSerializer,
TemplateInfoSerializer,
TrainingRunHistoryQuerySerializer,
@@ -788,3 +792,133 @@ class AutoresearchTrainingRunViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMi
except ArtifactStorageUnavailable as exc:
raise ArtifactStorageUnavailableError(str(exc)) from exc
return Response(ArtifactDeleteResultSerializer(instance=result).data)
+
+
+@extend_schema(tags=["autoresearch"])
+class AutoresearchSuggestionViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin, viewsets.GenericViewSet):
+ """
+ Submit and list steering suggestions for a running pipeline.
+
+ A suggestion is a free-text hypothesis or direction injected by a user or agent.
+ At the start of the next training batch the sandbox agent reads pending suggestions
+ and decides whether to translate each into a concrete iteration, apply it as a
+ search constraint, or dismiss it with rationale.
+ """
+
+ schema = FacadePathParamSchema()
+ uuid_path_parameters = {"id": "A UUID string identifying this autoresearch suggestion.", "pipeline_id": None}
+ scope_object = "autoresearch"
+ scope_object_read_actions = ["list", "retrieve"]
+ scope_object_write_actions = ["create", "respond"]
+ permission_classes = [AutoresearchAccessPermission]
+ serializer_class = AutoresearchSuggestionSerializer
+ queryset = None # data is reached through the facade; declared for router/schema only
+
+ def _should_skip_parents_filter(self) -> bool:
+ return True
+
+ @extend_schema(
+ responses={200: AutoresearchSuggestionSerializer(many=True)},
+ summary="List suggestions",
+ description=(
+ "List steering suggestions for a pipeline, ordered most recent first. "
+ "Check 'status' to see which have been picked up or acted on by the agent."
+ ),
+ )
+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ return self._paginate_via_facade(
+ request,
+ lambda offset, limit: api.list_suggestions(
+ self.team_id, pipeline_id=_parent_pipeline_id(self), offset=offset, limit=limit
+ ),
+ AutoresearchSuggestionSerializer,
+ )
+
+ @extend_schema(
+ responses={200: AutoresearchSuggestionSerializer},
+ summary="Get suggestion",
+ description="Get details for a specific suggestion including its status and agent_response.",
+ )
+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ suggestion = api.get_suggestion(self.team_id, self.kwargs["pk"], pipeline_id=_parent_pipeline_id(self))
+ if suggestion is None:
+ raise NotFound("Suggestion not found.")
+ return Response(AutoresearchSuggestionSerializer(instance=suggestion).data)
+
+ @validated_request(
+ request_serializer=CreateSuggestionSerializer,
+ responses={
+ 201: OpenApiResponse(
+ response=AutoresearchSuggestionSerializer,
+ description="The created suggestion. The agent will pick it up at the start of the next training batch.",
+ ),
+ },
+ summary="Submit a suggestion",
+ description=(
+ "Inject a free-text hypothesis or direction into a running pipeline. "
+ "The sandbox agent reads queued suggestions at the start of each iteration batch and decides: "
+ "translate into a concrete iteration ('acted_on'), apply as a search constraint ('picked_up'), "
+ "or reject with rationale ('dismissed'). "
+ "Use priority='try_next' to instruct the agent to act on this before autonomous iterations; "
+ "'consider' is advisory. "
+ "Check 'agent_response' after the next training run to see how the suggestion was interpreted."
+ ),
+ )
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ data = request.validated_data
+ try:
+ suggestion = api.create_suggestion(
+ self.team_id,
+ _require_parent_pipeline_id(self),
+ prompt=data["prompt"],
+ priority=data.get("priority", "consider"),
+ # The permission class rejects anonymous callers, so this is always a real user.
+ created_by=cast(User, request.user),
+ )
+ except PipelineNotFound as exc:
+ raise NotFound(str(exc)) from exc
+ except AutoresearchConflict as exc:
+ raise ValidationError(str(exc)) from exc
+ return Response(AutoresearchSuggestionSerializer(instance=suggestion).data, status=201)
+
+ @validated_request(
+ request_serializer=RespondToSuggestionSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=AutoresearchSuggestionSerializer,
+ description="The updated suggestion with its new status and agent_response.",
+ ),
+ 400: OpenApiResponse(
+ description=(
+ "The status would move the suggestion backwards, acted_on has no linked iteration, "
+ "a dismissal has no explanation, or the pipeline is archived."
+ )
+ ),
+ },
+ summary="Respond to a suggestion",
+ description=(
+ "Record how the agent handled a steering suggestion: set status to 'picked_up' (applied as a "
+ "search constraint), 'acted_on' (spawned iterations), or 'dismissed' (rejected — explain in "
+ "agent_response), and write the agent_response note the human will read. Call this from the "
+ "training loop after deciding what to do with a pending suggestion. Recording an iteration with "
+ "parent_suggestion set already advances a suggestion to 'acted_on'; use this to add the narrative "
+ "or to mark a suggestion picked_up/dismissed without spawning an iteration. A suggestion only "
+ "moves forward (queued, picked_up, then acted_on or dismissed); the same status again updates the note."
+ ),
+ )
+ @action(detail=True, methods=["post"], url_path="respond")
+ def respond(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ data = request.validated_data
+ try:
+ suggestion = api.respond_to_suggestion(
+ self.team_id,
+ self.kwargs["pk"],
+ status=data["status"],
+ agent_response=data.get("agent_response"),
+ pipeline_id=_parent_pipeline_id(self),
+ )
+ except SuggestionNotFound:
+ raise NotFound("Suggestion not found.")
+ except AutoresearchConflict as exc:
+ raise ValidationError(str(exc)) from exc
+ return Response(AutoresearchSuggestionSerializer(instance=suggestion).data)
diff --git a/products/autoresearch/backend/routes.py b/products/autoresearch/backend/routes.py
index b08168e5ea1a..c4bfadcd7512 100644
--- a/products/autoresearch/backend/routes.py
+++ b/products/autoresearch/backend/routes.py
@@ -28,3 +28,9 @@ def register_routes(routers: RouterRegistry) -> None:
"project_autoresearch_training_runs",
["project_id", "pipeline_id"],
)
+ autoresearch_router.register(
+ r"suggestions",
+ autoresearch.AutoresearchSuggestionViewSet,
+ "project_autoresearch_suggestions",
+ ["project_id", "pipeline_id"],
+ )
diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.py
index 700112a08ce7..f4b0ec05c92e 100644
--- a/products/autoresearch/backend/tests/test_api.py
+++ b/products/autoresearch/backend/tests/test_api.py
@@ -24,6 +24,7 @@ from products.autoresearch.backend.models import (
AutoresearchModel,
AutoresearchPipeline,
AutoresearchRun,
+ AutoresearchSuggestion,
AutoresearchTrainingRun,
)
from products.autoresearch.backend.presentation.views.serializers import (
@@ -572,6 +573,311 @@ class TestValidationWarningSerializer(SimpleTestCase):
assert all(f"'{code}'" in help_text for code in VALIDATION_WARNING_CODES)
+class TestAutoresearchSuggestionAPI(TeamScopedTestMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.base_url = f"/api/projects/{self.team.pk}/autoresearch"
+ self._flag_patcher = patch(
+ "products.autoresearch.backend.access.posthoganalytics.feature_enabled",
+ return_value=True,
+ )
+ self._flag_patcher.start()
+ self.addCleanup(self._flag_patcher.stop)
+
+ def _make_pipeline(self, **kwargs) -> AutoresearchPipeline:
+ defaults = {
+ "team": self.team,
+ "created_by": self.user,
+ "name": "Test Pipeline",
+ "target_event": "$pageview",
+ "horizon_days": 7,
+ "iteration_budget": 50,
+ "iteration_budget_remaining": 50,
+ }
+ defaults.update(kwargs)
+ return AutoresearchPipeline.objects.create(**defaults)
+
+ def _suggestions_url(self, pipeline_id: object) -> str:
+ return f"{self.base_url}/{pipeline_id}/suggestions/"
+
+ # ──────────────────────────────────────────── create ──────────────────────────────────────────
+
+ def test_create_suggestion(self):
+ pipeline = self._make_pipeline()
+ resp = self.client.post(
+ self._suggestions_url(pipeline.id),
+ {"prompt": "try a gradient boosting model", "priority": "consider"},
+ format="json",
+ )
+ assert resp.status_code == status.HTTP_201_CREATED
+ data = resp.json()
+ assert data["prompt"] == "try a gradient boosting model"
+ assert data["priority"] == "consider"
+ assert data["status"] == "queued"
+ assert data["source"] == "user"
+ assert AutoresearchSuggestion.objects.filter(pipeline=pipeline).count() == 1
+
+ def test_create_suggestion_try_next_priority(self):
+ pipeline = self._make_pipeline()
+ resp = self.client.post(
+ self._suggestions_url(pipeline.id),
+ {"prompt": "remove recency features", "priority": "try_next"},
+ format="json",
+ )
+ assert resp.status_code == status.HTTP_201_CREATED
+ assert resp.json()["priority"] == "try_next"
+
+ def test_create_suggestion_default_priority_is_consider(self):
+ pipeline = self._make_pipeline()
+ resp = self.client.post(
+ self._suggestions_url(pipeline.id),
+ {"prompt": "try a different model"},
+ format="json",
+ )
+ assert resp.status_code == status.HTTP_201_CREATED
+ assert resp.json()["priority"] == "consider"
+
+ def test_create_suggestion_archived_pipeline_returns_400(self):
+ pipeline = self._make_pipeline(status=AutoresearchPipeline.Status.ARCHIVED)
+ # Archived pipelines are excluded from the queryset; suggestions endpoint
+ # does its own lookup and returns 400 (not 404) so the error is clear.
+ resp = self.client.post(
+ self._suggestions_url(pipeline.id),
+ {"prompt": "try XGBoost"},
+ format="json",
+ )
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_create_suggestion_on_a_missing_pipeline_returns_404(self):
+ resp = self.client.post(self._suggestions_url(uuid.uuid4()), {"prompt": "try XGBoost"}, format="json")
+ assert resp.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_create_suggestion_missing_prompt_returns_400(self):
+ pipeline = self._make_pipeline()
+ resp = self.client.post(self._suggestions_url(pipeline.id), {}, format="json")
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+
+ # ──────────────────────────────────────────── list ────────────────────────────────────────────
+
+ def test_list_suggestions(self):
+ pipeline = self._make_pipeline()
+ AutoresearchSuggestion.objects.create(
+ pipeline=pipeline,
+ created_by=self.user,
+ prompt="first suggestion",
+ priority=AutoresearchSuggestion.Priority.CONSIDER,
+ source=AutoresearchSuggestion.Source.USER,
+ )
+ AutoresearchSuggestion.objects.create(
+ pipeline=pipeline,
+ created_by=self.user,
+ prompt="second suggestion",
+ priority=AutoresearchSuggestion.Priority.TRY_NEXT,
+ source=AutoresearchSuggestion.Source.USER,
+ )
+ resp = self.client.get(self._suggestions_url(pipeline.id))
+ assert resp.status_code == status.HTTP_200_OK
+ assert resp.json()["count"] == 2
+
+ def test_suggestions_not_leaked_across_pipelines(self):
+ pipeline_a = self._make_pipeline(name="Pipeline A")
+ pipeline_b = self._make_pipeline(name="Pipeline B")
+ AutoresearchSuggestion.objects.create(
+ pipeline=pipeline_a,
+ created_by=self.user,
+ prompt="only for A",
+ source=AutoresearchSuggestion.Source.USER,
+ )
+ resp = self.client.get(self._suggestions_url(pipeline_b.id))
+ assert resp.status_code == status.HTTP_200_OK
+ assert resp.json()["count"] == 0
+
+ # ──────────────────────────────────────────── retrieve ────────────────────────────────────────
+
+ def test_retrieve_suggestion(self):
+ pipeline = self._make_pipeline()
+ suggestion = AutoresearchSuggestion.objects.create(
+ pipeline=pipeline,
+ created_by=self.user,
+ prompt="use day-of-week features",
+ priority=AutoresearchSuggestion.Priority.TRY_NEXT,
+ status=AutoresearchSuggestion.Status.QUEUED,
+ source=AutoresearchSuggestion.Source.USER,
+ )
+ resp = self.client.get(f"{self._suggestions_url(pipeline.id)}{suggestion.id}/")
+ assert resp.status_code == status.HTTP_200_OK
+ data = resp.json()
+ assert data["id"] == str(suggestion.id)
+ assert data["prompt"] == "use day-of-week features"
+ assert data["status"] == "queued"
+
+ def test_retrieve_suggestion_wrong_pipeline_returns_404(self):
+ pipeline_a = self._make_pipeline(name="Pipeline A")
+ pipeline_b = self._make_pipeline(name="Pipeline B")
+ suggestion = AutoresearchSuggestion.objects.create(
+ pipeline=pipeline_a,
+ created_by=self.user,
+ prompt="belongs to A",
+ source=AutoresearchSuggestion.Source.USER,
+ )
+ resp = self.client.get(f"{self._suggestions_url(pipeline_b.id)}{suggestion.id}/")
+ assert resp.status_code == status.HTTP_404_NOT_FOUND
+
+ # ──────────────────────────────────────────── respond ─────────────────────────────────────────
+
+ def _make_suggestion(self, pipeline: AutoresearchPipeline, status_value: str = "queued") -> AutoresearchSuggestion:
+ return AutoresearchSuggestion.objects.create(
+ pipeline=pipeline,
+ created_by=self.user,
+ prompt="try a calibrated logistic regression",
+ priority=AutoresearchSuggestion.Priority.TRY_NEXT,
+ source=AutoresearchSuggestion.Source.USER,
+ status=status_value,
+ )
+
+ def _link_iteration(self, suggestion: AutoresearchSuggestion) -> AutoresearchIteration:
+ run = AutoresearchTrainingRun.objects.create(pipeline=suggestion.pipeline, status="running")
+ return AutoresearchIteration.objects.create(
+ pipeline=suggestion.pipeline,
+ training_run=run,
+ parent_suggestion=suggestion,
+ iteration_number=0,
+ recipe_hash="abc",
+ recipe_snapshot={"feature_sql": "SELECT 1"},
+ model_spec={"model_class": "m"},
+ status="kept",
+ )
+
+ def _respond(self, suggestion: AutoresearchSuggestion, body: dict):
+ return self.client.post(
+ f"{self._suggestions_url(suggestion.pipeline_id)}{suggestion.id}/respond/", body, format="json"
+ )
+
+ def test_respond_sets_status_and_agent_response(self):
+ pipeline = self._make_pipeline()
+ suggestion = self._make_suggestion(pipeline)
+ iteration = self._link_iteration(suggestion)
+ resp = self._respond(
+ suggestion, {"status": "acted_on", "agent_response": "Spawned iter 2 with LR + calibration."}
+ )
+ assert resp.status_code == status.HTTP_200_OK, resp.json()
+ data = resp.json()
+ assert data["status"] == "acted_on"
+ assert data["agent_response"] == "Spawned iter 2 with LR + calibration."
+ assert data["linked_iteration_ids"] == [str(iteration.id)]
+ suggestion.refresh_from_db()
+ assert suggestion.status == "acted_on"
+
+ def test_respond_acted_on_needs_a_linked_iteration(self):
+ suggestion = self._make_suggestion(self._make_pipeline())
+ resp = self._respond(suggestion, {"status": "acted_on", "agent_response": "done"})
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert "parent_suggestion" in str(resp.json())
+
+ @parameterized.expand(
+ [
+ ("acted_on_back_to_picked_up", "acted_on", "picked_up"),
+ ("acted_on_to_dismissed", "acted_on", "dismissed"),
+ ("dismissed_back_to_picked_up", "dismissed", "picked_up"),
+ ]
+ )
+ def test_respond_refuses_a_backward_transition(self, _name: str, current: str, requested: str):
+ suggestion = self._make_suggestion(self._make_pipeline(), status_value=current)
+ resp = self._respond(suggestion, {"status": requested, "agent_response": "changed my mind"})
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ suggestion.refresh_from_db()
+ assert suggestion.status == current
+
+ def test_respond_same_status_updates_the_note_and_blank_clears_it(self):
+ suggestion = self._make_suggestion(self._make_pipeline())
+ assert self._respond(suggestion, {"status": "picked_up", "agent_response": "first"}).status_code == 200
+ resp = self._respond(suggestion, {"status": "picked_up"})
+ assert resp.json()["agent_response"] == "first"
+ resp = self._respond(suggestion, {"status": "picked_up", "agent_response": ""})
+ assert resp.json()["agent_response"] == ""
+
+ def test_respond_dismissed_without_a_reason_returns_400(self):
+ suggestion = self._make_suggestion(self._make_pipeline())
+ resp = self._respond(suggestion, {"status": "dismissed"})
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert "agent_response" in str(resp.json())
+ # A reason recorded earlier satisfies a repeated dismissal that omits the note.
+ assert self._respond(suggestion, {"status": "dismissed", "agent_response": "dead end"}).status_code == 200
+ resp = self._respond(suggestion, {"status": "dismissed"})
+ assert resp.status_code == status.HTTP_200_OK
+ assert resp.json()["agent_response"] == "dead end"
+
+ def test_respond_after_pipeline_archived_returns_400(self):
+ pipeline = self._make_pipeline()
+ suggestion = self._make_suggestion(pipeline)
+ pipeline.status = AutoresearchPipeline.Status.ARCHIVED
+ pipeline.save(update_fields=["status"])
+ resp = self._respond(suggestion, {"status": "picked_up"})
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert "archived" in str(resp.json())
+
+ @parameterized.expand([("retrieve",), ("respond",)])
+ def test_non_uuid_suggestion_id_returns_404(self, action: str):
+ pipeline = self._make_pipeline()
+ url = f"{self._suggestions_url(pipeline.id)}not-a-uuid/"
+ if action == "retrieve":
+ resp = self.client.get(url)
+ else:
+ resp = self.client.post(f"{url}respond/", {"status": "picked_up"}, format="json")
+ assert resp.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_list_reads_linked_iterations_in_one_query(self):
+ pipeline = self._make_pipeline()
+ for _ in range(3):
+ self._link_iteration(self._make_suggestion(pipeline))
+ with CaptureQueriesContext(connection) as queries:
+ resp = self.client.get(self._suggestions_url(pipeline.id))
+ assert resp.status_code == status.HTTP_200_OK
+ assert all(len(row["linked_iteration_ids"]) == 1 for row in resp.json()["results"])
+ assert sum("autoresearchiteration" in q["sql"].lower() for q in queries.captured_queries) == 1
+
+ def test_agent_authored_suggestion_has_no_creator(self):
+ pipeline = self._make_pipeline()
+ suggestion = AutoresearchSuggestion.objects.create(
+ pipeline=pipeline, prompt="from the agent", source=AutoresearchSuggestion.Source.AGENT
+ )
+ resp = self.client.get(f"{self._suggestions_url(pipeline.id)}{suggestion.id}/")
+ assert resp.status_code == status.HTTP_200_OK
+ assert resp.json()["created_by"] is None
+
+ def test_respond_dismissed(self):
+ pipeline = self._make_pipeline()
+ suggestion = self._make_suggestion(pipeline)
+ resp = self.client.post(
+ f"{self._suggestions_url(pipeline.id)}{suggestion.id}/respond/",
+ {"status": "dismissed", "agent_response": "Already a dead-end in a prior run."},
+ format="json",
+ )
+ assert resp.status_code == status.HTTP_200_OK
+ assert resp.json()["status"] == "dismissed"
+
+ def test_respond_invalid_status_returns_400(self):
+ pipeline = self._make_pipeline()
+ suggestion = self._make_suggestion(pipeline)
+ resp = self.client.post(
+ f"{self._suggestions_url(pipeline.id)}{suggestion.id}/respond/",
+ {"status": "queued"},
+ format="json",
+ )
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_respond_wrong_pipeline_returns_404(self):
+ pipeline_a = self._make_pipeline(name="Pipeline A")
+ pipeline_b = self._make_pipeline(name="Pipeline B")
+ suggestion = self._make_suggestion(pipeline_a)
+ resp = self.client.post(
+ f"{self._suggestions_url(pipeline_b.id)}{suggestion.id}/respond/",
+ {"status": "acted_on"},
+ format="json",
+ )
+ assert resp.status_code == status.HTTP_404_NOT_FOUND
+
+
class _InMemoryStorage:
def __init__(self) -> None:
self.store: dict[str, bytes] = {}
diff --git a/products/autoresearch/backend/training/test_agent_recorded_training.py b/products/autoresearch/backend/training/test_agent_recorded_training.py
index 80f69889c2b1..d97a550cf4f6 100644
--- a/products/autoresearch/backend/training/test_agent_recorded_training.py
+++ b/products/autoresearch/backend/training/test_agent_recorded_training.py
@@ -154,12 +154,19 @@ class TestAgentRecordedTraining(TeamScopedTestMixin, APIBaseTest):
iteration.refresh_from_db()
assert iteration.parent_suggestion_id is None
- def test_record_iteration_rejects_foreign_parent_suggestion(self):
- other_pipeline = AutoresearchPipeline.objects.create(
- team=self.team, created_by=self.user, name="Other", target_event="$pageview", horizon_days=7
- )
+ @parameterized.expand([("foreign",), ("dismissed",)])
+ def test_record_iteration_rejects_an_unusable_parent_suggestion(self, case: str):
+ pipeline = self.pipeline
+ if case == "foreign":
+ pipeline = AutoresearchPipeline.objects.create(
+ team=self.team, created_by=self.user, name="Other", target_event="$pageview", horizon_days=7
+ )
foreign = AutoresearchSuggestion.objects.create(
- pipeline=other_pipeline, created_by=self.user, prompt="foreign", source=AutoresearchSuggestion.Source.USER
+ pipeline=pipeline,
+ created_by=self.user,
+ prompt="foreign",
+ source=AutoresearchSuggestion.Source.USER,
+ status="dismissed" if case == "dismissed" else "queued",
)
run_id = self._open_run()
resp = self.client.post(
diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.ts
index 9ed49fafee00..3a2040ec2c98 100644
--- a/products/autoresearch/frontend/generated/api.schemas.ts
+++ b/products/autoresearch/frontend/generated/api.schemas.ts
@@ -493,6 +493,145 @@ export interface PaginatedAutoresearchRunListApi {
results: AutoresearchRunApi[]
}
+/**
+ * * `try_next` - Try next
+ * * `consider` - Consider
+ */
+export type AutoresearchSuggestionPriorityEnumApi =
+ (typeof AutoresearchSuggestionPriorityEnumApi)[keyof typeof AutoresearchSuggestionPriorityEnumApi]
+
+export const AutoresearchSuggestionPriorityEnumApi = {
+ TryNext: 'try_next',
+ Consider: 'consider',
+} as const
+
+/**
+ * * `queued` - Queued
+ * * `picked_up` - Picked up
+ * * `acted_on` - Acted on
+ * * `dismissed` - Dismissed
+ */
+export type AutoresearchSuggestionStatusEnumApi =
+ (typeof AutoresearchSuggestionStatusEnumApi)[keyof typeof AutoresearchSuggestionStatusEnumApi]
+
+export const AutoresearchSuggestionStatusEnumApi = {
+ Queued: 'queued',
+ PickedUp: 'picked_up',
+ ActedOn: 'acted_on',
+ Dismissed: 'dismissed',
+} as const
+
+/**
+ * * `user` - User
+ * * `agent` - Agent
+ */
+export type AutoresearchSuggestionSourceEnumApi =
+ (typeof AutoresearchSuggestionSourceEnumApi)[keyof typeof AutoresearchSuggestionSourceEnumApi]
+
+export const AutoresearchSuggestionSourceEnumApi = {
+ User: 'user',
+ Agent: 'agent',
+} as const
+
+export interface AutoresearchSuggestionApi {
+ /** Unique UUID of this suggestion. */
+ readonly id: string
+ /** Pipeline this suggestion targets. */
+ pipeline: string
+ /** Free-text hypothesis or direction for the agent to explore. */
+ prompt: string
+ /** 'try_next' instructs the agent to act on this before other iterations; 'consider' is advisory.
+ *
+ * * `try_next` - Try next
+ * * `consider` - Consider */
+ priority?: AutoresearchSuggestionPriorityEnumApi
+ /** Lifecycle status: 'queued' (awaiting pickup), 'picked_up' (agent is applying as a constraint), 'acted_on' (agent spawned iterations), 'dismissed' (agent rejected with rationale).
+ *
+ * * `queued` - Queued
+ * * `picked_up` - Picked up
+ * * `acted_on` - Acted on
+ * * `dismissed` - Dismissed */
+ readonly status: AutoresearchSuggestionStatusEnumApi
+ /** 'user' for human-submitted suggestions; 'agent' for agent-generated hypotheses.
+ *
+ * * `user` - User
+ * * `agent` - Agent */
+ readonly source: AutoresearchSuggestionSourceEnumApi
+ /** Agent's note on how the suggestion was interpreted and acted upon. Populated after pickup. */
+ readonly agent_response: string
+ /** The user who submitted it; null for an agent-authored suggestion. */
+ readonly created_by: UserBasicApi | null
+ /** UUIDs of iterations spawned from this suggestion. */
+ readonly linked_iteration_ids: readonly string[]
+ readonly created_at: string
+ readonly updated_at: string
+}
+
+export interface PaginatedAutoresearchSuggestionListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: AutoresearchSuggestionApi[]
+}
+
+/**
+ * * `try_next` - try_next
+ * * `consider` - consider
+ */
+export type CreateSuggestionPriorityEnumApi =
+ (typeof CreateSuggestionPriorityEnumApi)[keyof typeof CreateSuggestionPriorityEnumApi]
+
+export const CreateSuggestionPriorityEnumApi = {
+ TryNext: 'try_next',
+ Consider: 'consider',
+} as const
+
+export interface CreateSuggestionApi {
+ /**
+ * Free-text hypothesis or direction for the agent to explore, e.g. 'try a tree-based model' or 'remove recency features, I suspect leakage'.
+ * @maxLength 2000
+ */
+ prompt: string
+ /** 'try_next' asks the agent to act on this before other autonomous iterations; 'consider' is advisory context.
+ *
+ * * `try_next` - try_next
+ * * `consider` - consider */
+ priority?: CreateSuggestionPriorityEnumApi
+}
+
+/**
+ * * `picked_up` - picked_up
+ * * `acted_on` - acted_on
+ * * `dismissed` - dismissed
+ */
+export type RespondToSuggestionStatusEnumApi =
+ (typeof RespondToSuggestionStatusEnumApi)[keyof typeof RespondToSuggestionStatusEnumApi]
+
+export const RespondToSuggestionStatusEnumApi = {
+ PickedUp: 'picked_up',
+ ActedOn: 'acted_on',
+ Dismissed: 'dismissed',
+} as const
+
+/**
+ * Input for the agent to record how it interpreted a steering suggestion.
+ */
+export interface RespondToSuggestionApi {
+ /** How the agent handled the suggestion: 'picked_up' (applied as a search constraint), 'acted_on' (spawned one or more iterations), or 'dismissed' (rejected — explain why in agent_response).
+ *
+ * * `picked_up` - picked_up
+ * * `acted_on` - acted_on
+ * * `dismissed` - dismissed */
+ status: RespondToSuggestionStatusEnumApi
+ /**
+ * Plain-English note on how the suggestion was interpreted and acted upon. A dismissal needs a note, sent now or recorded earlier. Omit it to keep the note already recorded; send an empty string to clear it.
+ * @maxLength 2000
+ */
+ agent_response?: string
+}
+
/**
* One iteration referenced from a run summary's ladder or dead-ends list.
*/
@@ -1431,6 +1570,17 @@ export type AutoresearchRunsListParams = {
offset?: number
}
+export type AutoresearchSuggestionsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type AutoresearchTrainingRunsListParams = {
/**
* Number of results to return per page.
diff --git a/products/autoresearch/frontend/generated/api.ts b/products/autoresearch/frontend/generated/api.ts
index b9070d20929e..1882febde97b 100644
--- a/products/autoresearch/frontend/generated/api.ts
+++ b/products/autoresearch/frontend/generated/api.ts
@@ -22,21 +22,26 @@ import type {
AutoresearchPipelineCreateApi,
AutoresearchRunApi,
AutoresearchRunsListParams,
+ AutoresearchSuggestionApi,
+ AutoresearchSuggestionsListParams,
AutoresearchTrainingRunApi,
AutoresearchTrainingRunsHistoryRetrieveParams,
AutoresearchTrainingRunsListParams,
CompleteTrainingRunApi,
+ CreateSuggestionApi,
MaterializeFeaturesRequestApi,
MaterializeFeaturesResponseApi,
OpenTrainingRunApi,
PaginatedAutoresearchModelListApi,
PaginatedAutoresearchPipelineListApi,
PaginatedAutoresearchRunListApi,
+ PaginatedAutoresearchSuggestionListApi,
PaginatedAutoresearchTrainingRunListApi,
PatchedAutoresearchPipelineCreateApi,
RecordIterationApi,
ResolveTemplateRequestApi,
ResolvedTemplateApi,
+ RespondToSuggestionApi,
StoredArtifactApi,
TemplateInfoApi,
TrainingRunHistoryApi,
@@ -218,6 +223,113 @@ export const autoresearchRunsRetrieve = async (
})
}
+export const getAutoresearchSuggestionsListUrl = (
+ projectId: string,
+ pipelineId: string,
+ params?: AutoresearchSuggestionsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/autoresearch/${pipelineId}/suggestions/?${stringifiedParams}`
+ : `/api/projects/${projectId}/autoresearch/${pipelineId}/suggestions/`
+}
+
+/**
+ * List steering suggestions for a pipeline, ordered most recent first. Check 'status' to see which have been picked up or acted on by the agent.
+ * @summary List suggestions
+ */
+export const autoresearchSuggestionsList = async (
+ projectId: string,
+ pipelineId: string,
+ params?: AutoresearchSuggestionsListParams,
+ options?: RequestInit
+): Promise<PaginatedAutoresearchSuggestionListApi> => {
+ return apiMutator<PaginatedAutoresearchSuggestionListApi>(
+ getAutoresearchSuggestionsListUrl(projectId, pipelineId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getAutoresearchSuggestionsCreateUrl = (projectId: string, pipelineId: string) => {
+ return `/api/projects/${projectId}/autoresearch/${pipelineId}/suggestions/`
+}
+
+/**
+ * Inject a free-text hypothesis or direction into a running pipeline. The sandbox agent reads queued suggestions at the start of each iteration batch and decides: translate into a concrete iteration ('acted_on'), apply as a search constraint ('picked_up'), or reject with rationale ('dismissed'). Use priority='try_next' to instruct the agent to act on this before autonomous iterations; 'consider' is advisory. Check 'agent_response' after the next training run to see how the suggestion was interpreted.
+ * @summary Submit a suggestion
+ */
+export const autoresearchSuggestionsCreate = async (
+ projectId: string,
+ pipelineId: string,
+ createSuggestionApi: CreateSuggestionApi,
+ options?: RequestInit
+): Promise<AutoresearchSuggestionApi> => {
+ return apiMutator<AutoresearchSuggestionApi>(getAutoresearchSuggestionsCreateUrl(projectId, pipelineId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(createSuggestionApi),
+ })
+}
+
+export const getAutoresearchSuggestionsRetrieveUrl = (projectId: string, pipelineId: string, id: string) => {
+ return `/api/projects/${projectId}/autoresearch/${pipelineId}/suggestions/${id}/`
+}
+
+/**
+ * Get details for a specific suggestion including its status and agent_response.
+ * @summary Get suggestion
+ */
+export const autoresearchSuggestionsRetrieve = async (
+ projectId: string,
+ pipelineId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AutoresearchSuggestionApi> => {
+ return apiMutator<AutoresearchSuggestionApi>(getAutoresearchSuggestionsRetrieveUrl(projectId, pipelineId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAutoresearchSuggestionsRespondCreateUrl = (projectId: string, pipelineId: string, id: string) => {
+ return `/api/projects/${projectId}/autoresearch/${pipelineId}/suggestions/${id}/respond/`
+}
+
+/**
+ * Record how the agent handled a steering suggestion: set status to 'picked_up' (applied as a search constraint), 'acted_on' (spawned iterations), or 'dismissed' (rejected — explain in agent_response), and write the agent_response note the human will read. Call this from the training loop after deciding what to do with a pending suggestion. Recording an iteration with parent_suggestion set already advances a suggestion to 'acted_on'; use this to add the narrative or to mark a suggestion picked_up/dismissed without spawning an iteration. A suggestion only moves forward (queued, picked_up, then acted_on or dismissed); the same status again updates the note.
+ * @summary Respond to a suggestion
+ */
+export const autoresearchSuggestionsRespondCreate = async (
+ projectId: string,
+ pipelineId: string,
+ id: string,
+ respondToSuggestionApi: RespondToSuggestionApi,
+ options?: RequestInit
+): Promise<AutoresearchSuggestionApi> => {
+ return apiMutator<AutoresearchSuggestionApi>(
+ getAutoresearchSuggestionsRespondCreateUrl(projectId, pipelineId, id),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(respondToSuggestionApi),
+ }
+ )
+}
+
export const getAutoresearchTrainingRunsListUrl = (
projectId: string,
pipelineId: string,
diff --git a/products/autoresearch/frontend/generated/api.zod.ts b/products/autoresearch/frontend/generated/api.zod.ts
index 8b584b5a206c..10cd271427bb 100644
--- a/products/autoresearch/frontend/generated/api.zod.ts
+++ b/products/autoresearch/frontend/generated/api.zod.ts
@@ -121,6 +121,54 @@ export const AutoresearchCreateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Inject a free-text hypothesis or direction into a running pipeline. The sandbox agent reads queued suggestions at the start of each iteration batch and decides: translate into a concrete iteration ('acted_on'), apply as a search constraint ('picked_up'), or reject with rationale ('dismissed'). Use priority='try_next' to instruct the agent to act on this before autonomous iterations; 'consider' is advisory. Check 'agent_response' after the next training run to see how the suggestion was interpreted.
+ * @summary Submit a suggestion
+ */
+export const autoresearchSuggestionsCreateBodyPromptMax = 2000
+
+export const autoresearchSuggestionsCreateBodyPriorityDefault = `consider`
+
+export const AutoresearchSuggestionsCreateBody = /* @__PURE__ */ zod.object({
+ prompt: zod
+ .string()
+ .max(autoresearchSuggestionsCreateBodyPromptMax)
+ .describe(
+ "Free-text hypothesis or direction for the agent to explore, e.g. 'try a tree-based model' or 'remove recency features, I suspect leakage'."
+ ),
+ priority: zod
+ .enum(['try_next', 'consider'])
+ .describe('\* `try_next` - try_next\n\* `consider` - consider')
+ .default(autoresearchSuggestionsCreateBodyPriorityDefault)
+ .describe(
+ "'try_next' asks the agent to act on this before other autonomous iterations; 'consider' is advisory context.\n\n\* `try_next` - try_next\n\* `consider` - consider"
+ ),
+})
+
+/**
+ * Record how the agent handled a steering suggestion: set status to 'picked_up' (applied as a search constraint), 'acted_on' (spawned iterations), or 'dismissed' (rejected — explain in agent_response), and write the agent_response note the human will read. Call this from the training loop after deciding what to do with a pending suggestion. Recording an iteration with parent_suggestion set already advances a suggestion to 'acted_on'; use this to add the narrative or to mark a suggestion picked_up/dismissed without spawning an iteration. A suggestion only moves forward (queued, picked_up, then acted_on or dismissed); the same status again updates the note.
+ * @summary Respond to a suggestion
+ */
+export const autoresearchSuggestionsRespondCreateBodyAgentResponseMax = 2000
+
+export const AutoresearchSuggestionsRespondCreateBody = /* @__PURE__ */ zod
+ .object({
+ status: zod
+ .enum(['picked_up', 'acted_on', 'dismissed'])
+ .describe('\* `picked_up` - picked_up\n\* `acted_on` - acted_on\n\* `dismissed` - dismissed')
+ .describe(
+ "How the agent handled the suggestion: 'picked_up' (applied as a search constraint), 'acted_on' (spawned one or more iterations), or 'dismissed' (rejected — explain why in agent_response).\n\n\* `picked_up` - picked_up\n\* `acted_on` - acted_on\n\* `dismissed` - dismissed"
+ ),
+ agent_response: zod
+ .string()
+ .max(autoresearchSuggestionsRespondCreateBodyAgentResponseMax)
+ .optional()
+ .describe(
+ 'Plain-English note on how the suggestion was interpreted and acted upon. A dismissal needs a note, sent now or recorded earlier. Omit it to keep the note already recorded; send an empty string to clear it.'
+ ),
+ })
+ .describe('Input for the agent to record how it interpreted a steering suggestion.')
+
/**
* Open a new training run for a pipeline and return its id. An agent — the in-house sandbox, an external bring-your-own agent, or a scheduled job — then records iterations against this run and finalizes it with the complete endpoint. The run starts in 'running'.
* @summary Open a training run
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8a985f13870b..f922aa695a6b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -11937,6 +11937,80 @@ export namespace Schemas {
readonly created_at: string;
}
+ /**
+ * * `try_next` - Try next
+ * * `consider` - Consider
+ */
+ export type AutoresearchSuggestionPriorityEnum = typeof AutoresearchSuggestionPriorityEnum[keyof typeof AutoresearchSuggestionPriorityEnum];
+
+
+ export const AutoresearchSuggestionPriorityEnum = {
+ TryNext: 'try_next',
+ Consider: 'consider',
+ } as const;
+
+ /**
+ * * `queued` - Queued
+ * * `picked_up` - Picked up
+ * * `acted_on` - Acted on
+ * * `dismissed` - Dismissed
+ */
+ export type AutoresearchSuggestionStatusEnum = typeof AutoresearchSuggestionStatusEnum[keyof typeof AutoresearchSuggestionStatusEnum];
+
+
+ export const AutoresearchSuggestionStatusEnum = {
+ Queued: 'queued',
+ PickedUp: 'picked_up',
+ ActedOn: 'acted_on',
+ Dismissed: 'dismissed',
+ } as const;
+
+ /**
+ * * `user` - User
+ * * `agent` - Agent
+ */
+ export type AutoresearchSuggestionSourceEnum = typeof AutoresearchSuggestionSourceEnum[keyof typeof AutoresearchSuggestionSourceEnum];
+
+
+ export const AutoresearchSuggestionSourceEnum = {
+ User: 'user',
+ Agent: 'agent',
+ } as const;
+
+ export interface AutoresearchSuggestion {
+ /** Unique UUID of this suggestion. */
+ readonly id: string;
+ /** Pipeline this suggestion targets. */
+ pipeline: string;
+ /** Free-text hypothesis or direction for the agent to explore. */
+ prompt: string;
+ /** 'try_next' instructs the agent to act on this before other iterations; 'consider' is advisory.
+ *
+ * * `try_next` - Try next
+ * * `consider` - Consider */
+ priority?: AutoresearchSuggestionPriorityEnum;
+ /** Lifecycle status: 'queued' (awaiting pickup), 'picked_up' (agent is applying as a constraint), 'acted_on' (agent spawned iterations), 'dismissed' (agent rejected with rationale).
+ *
+ * * `queued` - Queued
+ * * `picked_up` - Picked up
+ * * `acted_on` - Acted on
+ * * `dismissed` - Dismissed */
+ readonly status: AutoresearchSuggestionStatusEnum;
+ /** 'user' for human-submitted suggestions; 'agent' for agent-generated hypotheses.
+ *
+ * * `user` - User
+ * * `agent` - Agent */
+ readonly source: AutoresearchSuggestionSourceEnum;
+ /** Agent's note on how the suggestion was interpreted and acted upon. Populated after pickup. */
+ readonly agent_response: string;
+ /** The user who submitted it; null for an agent-authored suggestion. */
+ readonly created_by: UserBasic | null;
+ /** UUIDs of iterations spawned from this suggestion. */
+ readonly linked_iteration_ids: readonly string[];
+ readonly created_at: string;
+ readonly updated_at: string;
+ }
+
/**
* One iteration referenced from a run summary's ladder or dead-ends list.
*/
@@ -22044,6 +22118,31 @@ export namespace Schemas {
uploads: UploadTarget[];
}
+ /**
+ * * `try_next` - try_next
+ * * `consider` - consider
+ */
+ export type CreateSuggestionPriorityEnum = typeof CreateSuggestionPriorityEnum[keyof typeof CreateSuggestionPriorityEnum];
+
+
+ export const CreateSuggestionPriorityEnum = {
+ TryNext: 'try_next',
+ Consider: 'consider',
+ } as const;
+
+ export interface CreateSuggestion {
+ /**
+ * Free-text hypothesis or direction for the agent to explore, e.g. 'try a tree-based model' or 'remove recency features, I suspect leakage'.
+ * @maxLength 2000
+ */
+ prompt: string;
+ /** 'try_next' asks the agent to act on this before other autonomous iterations; 'consider' is advisory context.
+ *
+ * * `try_next` - try_next
+ * * `consider` - consider */
+ priority?: CreateSuggestionPriorityEnum;
+ }
+
/**
* * `csv` - csv
* * `json` - json
@@ -60676,6 +60775,15 @@ export namespace Schemas {
results: AutoresearchRun[];
}
+ export interface PaginatedAutoresearchSuggestionList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: AutoresearchSuggestion[];
+ }
+
export interface PaginatedAutoresearchTrainingRunList {
count: number;
/** @nullable */
@@ -83835,6 +83943,37 @@ export namespace Schemas {
notes: string;
}
+ /**
+ * * `picked_up` - picked_up
+ * * `acted_on` - acted_on
+ * * `dismissed` - dismissed
+ */
+ export type RespondToSuggestionStatusEnum = typeof RespondToSuggestionStatusEnum[keyof typeof RespondToSuggestionStatusEnum];
+
+
+ export const RespondToSuggestionStatusEnum = {
+ PickedUp: 'picked_up',
+ ActedOn: 'acted_on',
+ Dismissed: 'dismissed',
+ } as const;
+
+ /**
+ * Input for the agent to record how it interpreted a steering suggestion.
+ */
+ export interface RespondToSuggestion {
+ /** How the agent handled the suggestion: 'picked_up' (applied as a search constraint), 'acted_on' (spawned one or more iterations), or 'dismissed' (rejected — explain why in agent_response).
+ *
+ * * `picked_up` - picked_up
+ * * `acted_on` - acted_on
+ * * `dismissed` - dismissed */
+ status: RespondToSuggestionStatusEnum;
+ /**
+ * Plain-English note on how the suggestion was interpreted and acted upon. A dismissal needs a note, sent now or recorded earlier. Omit it to keep the note already recorded; send an empty string to clear it.
+ * @maxLength 2000
+ */
+ agent_response?: string;
+ }
+
/**
* * `accepted` - accepted
* * `target_finished` - target_finished
@@ -102443,6 +102582,17 @@ export namespace Schemas {
offset?: number;
};
+ export type AutoresearchSuggestionsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type AutoresearchTrainingRunsListParams = {
/**
* Number of results to return per page.