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 data model and the access gate (2/22) (#88740)

Andrew Maguire912c944dcc9b
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index d93a21804640..8f877c7d69a5 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -80,6 +80,12 @@ rules:
|Announcement
|AnnouncementDelivery
|ApprovalPolicy
+ |AutoresearchIteration
+ |AutoresearchModel
+ |AutoresearchPipeline
+ |AutoresearchRun
+ |AutoresearchSuggestion
+ |AutoresearchTrainingRun
|BatchExport
|BatchExportBackfill
|BatchExportFileDownload
@@ -476,6 +482,12 @@ rules:
|Announcement
|AnnouncementDelivery
|ApprovalPolicy
+ |AutoresearchIteration
+ |AutoresearchModel
+ |AutoresearchPipeline
+ |AutoresearchRun
+ |AutoresearchSuggestion
+ |AutoresearchTrainingRun
|BatchExport
|BatchExportBackfill
|BatchExportFileDownload
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
index 58c3d6976a28..b0d5ffd13ee7 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
@@ -395,6 +395,7 @@ export interface accessControlsLogicActions {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -566,6 +567,7 @@ export interface accessControlsLogicMeta {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -714,6 +716,7 @@ export interface accessControlsLogicMeta {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -834,6 +837,7 @@ export interface accessControlsLogicMeta {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
index 407f1a660715..f7a88bc8ce7b 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
@@ -220,6 +220,7 @@ export interface accessDetailLogicActions {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts
index 3aa0d97ed245..7a646595ff71 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts
@@ -66,6 +66,7 @@ export interface addObjectOverrideModalLogicActions {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -184,6 +185,7 @@ export interface addObjectOverrideModalLogicActions {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -323,6 +325,7 @@ export interface addObjectOverrideModalLogicActions {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -446,6 +449,7 @@ export interface addObjectOverrideModalLogicActions {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -568,6 +572,7 @@ export interface addObjectOverrideModalLogicActions {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -711,6 +716,7 @@ export interface addObjectOverrideModalLogicMeta {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts
index edace2635944..1c22e64c8d09 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts
@@ -29,6 +29,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -153,6 +154,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -269,6 +271,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -398,6 +401,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -532,6 +536,7 @@ export interface groupedAccessControlRuleModalLogicActions {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -668,6 +673,7 @@ export interface groupedAccessControlRuleModalLogicActions {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -784,6 +790,7 @@ export interface groupedAccessControlRuleModalLogicActions {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -939,6 +946,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -1057,6 +1065,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -1174,6 +1183,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -1291,6 +1301,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -1409,6 +1420,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -1526,6 +1538,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -1654,6 +1667,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -1771,6 +1785,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
index 3a65a6413c0a..386fdbfcd659 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
@@ -320,6 +320,7 @@ export interface accessControlLogicMeta {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -540,6 +541,7 @@ export interface accessControlLogicMeta {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
@@ -657,6 +659,7 @@ export interface accessControlLogicMeta {
| 'alert'
| 'annotation'
| 'approvals'
+ | 'autoresearch'
| 'batch_export'
| 'batch_import'
| 'batch_import_support'
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 20ecff526c78..8077bddab093 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -61,6 +61,7 @@ export const API_SCOPES: APIScope[] = [
{ key: 'alert', objectName: 'Alert', objectPlural: 'alerts' },
{ key: 'annotation', objectName: 'Annotation', objectPlural: 'annotations' },
{ key: 'approvals', objectName: 'Approvals', objectPlural: 'approvals' },
+ { key: 'autoresearch', objectName: 'Autoresearch', objectPlural: 'autoresearch pipelines' },
{ key: 'batch_export', objectName: 'Batch export', objectPlural: 'batch exports' },
{ key: 'billing', objectName: 'Billing', objectPlural: 'billing' },
{ key: 'business_knowledge', objectName: 'Business knowledge', objectPlural: 'business knowledge' },
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 0f1d2e52b078..13e532711959 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5848,6 +5848,7 @@ export const API_SCOPE_OBJECTS = [
'alert',
'annotation',
'approvals',
+ 'autoresearch',
'batch_export',
'batch_import',
'batch_import_support',
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 8ff9ed191a28..05d812ee4292 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -22,6 +22,7 @@ APIScopeObject = Literal[
"alert",
"annotation",
"approvals",
+ "autoresearch",
"batch_export",
"batch_import",
"batch_import_support",
diff --git a/products/autoresearch/AGENTS.md b/products/autoresearch/AGENTS.md
new file mode 100644
index 000000000000..88fd2f6c6ff6
--- /dev/null
+++ b/products/autoresearch/AGENTS.md
@@ -0,0 +1,54 @@
+# Autoresearch
+
+Agent-driven predictive modeling.
+A user names a **target event**, a **population**, and a **horizon** ("who will download a file in the next 30 days?").
+An agent then searches for the best model for that question, and once it finds one, the product scores the population on a cadence and writes the result back into PostHog as `autoresearch_prediction` events.
+
+The framing is Karpathy's `autoresearch` prompt pattern: an agent edits one thing, runs a fixed eval, keeps the change if a single metric improved, reverts otherwise, and loops until a stop rule fires.
+Here the "one thing" is a feature set plus a model spec, the fixed eval is holdout AUC on a labeled training population, and the loop runs inside a Tasks sandbox.
+
+This directory currently holds the data model and the access gate only.
+The training loop, inference, evaluation, the API, the MCP tools, and the frontend land in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464).
+
+## Data model in one pass
+
+```text
+AutoresearchPipeline the standing question (target, population, horizon, cadence)
+ ├─ AutoresearchTrainingRun one attempt to find a better model
+ │ └─ AutoresearchIteration one experiment inside that attempt (kept / discarded)
+ ├─ AutoresearchModel a trained model, role = champion | challenger | archived
+ ├─ AutoresearchRun one execution of inference or validation
+ └─ AutoresearchSuggestion a human- or agent-authored hypothesis for the next run to explore
+```
+
+`AutoresearchModel.artifact_prefix` points at the model's artifact bundle in object storage.
+When it is empty the model carries only `model_recipe`, which the in-process scoring path reads.
+
+Every model carries its own `team` foreign key and sits on `TeamScopedRootMixin`, so reads outside a team scope raise rather than crossing tenants.
+Read through `Model.objects.for_team(team_id)` or inside a `team_scope(team_id)` block.
+The five pipeline-owned models inherit `PipelineScopedModel`, whose `save()` derives `team` from the parent pipeline unconditionally (an explicit mismatched value is overwritten) and rejects related rows that belong to another pipeline, so a create only has to pass `pipeline`.
+
+Every AUC and confidence column (`success_auc`, `holdout_score`, `realized_score`, `best_holdout_score`, `train_score`, `agent_confidence`) is NULL until measured and otherwise held to `[0, 1]` by a CHECK constraint.
+A writer that produces a raw score has to normalize it before it saves.
+The counters carry CHECK constraints too: `iteration_budget` is at least 1, `iteration_count`, `rows_scored` and `iteration_budget_remaining` are at least 0, and `trained_on_start` is no later than `trained_on_end`.
+
+## Feature flag and access
+
+Gated by the `autoresearch` feature flag (`backend/access.py`).
+Rollout is configured on the flag, and code only asks whether it is on.
+
+The real-agent training path additionally needs Tasks access, because it runs in a Tasks sandbox.
+
+## Invariants that cross package boundaries
+
+These are the ones that have actually broken things.
+
+- **Everything is keyed on `person_id`, one row per person.**
+ Agent-authored `feature_sql` must be a read-only `SELECT` keyed on `person_id`, and the label and population queries key on it too.
+ A mismatch here does not raise, it silently produces all-zero labels and a degenerate model.
+ **A uniform score distribution is an identifier mismatch until proven otherwise, not a bad model.**
+- **The agent proposes, the backend disposes.**
+ Iterations are recorded by the agent, but champion selection happens server-side.
+ Never let agent output pick the champion directly.
+- **Autoresearch trains on identified users only.**
+ On demo-style datasets that are largely anonymous, raw event counts wildly overstate how much training data exists.
diff --git a/products/autoresearch/CLAUDE.md b/products/autoresearch/CLAUDE.md
new file mode 120000
index 000000000000..47dc3e3d863c
--- /dev/null
+++ b/products/autoresearch/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/products/autoresearch/backend/access.py b/products/autoresearch/backend/access.py
new file mode 100644
index 000000000000..bddd66024ca1
--- /dev/null
+++ b/products/autoresearch/backend/access.py
@@ -0,0 +1,81 @@
+"""Feature-flag gate for the autoresearch product.
+
+Access is controlled by the `autoresearch` feature flag. Rollout is configured
+on the flag in PostHog, so code only asks whether it's enabled for this user/team.
+"""
+
+from django.conf import settings
+from django.contrib.auth.models import AbstractBaseUser, AnonymousUser
+
+import posthoganalytics
+
+from posthog.models.team import Team
+from posthog.permissions import posthog_feature_flag_value
+
+from products.feature_flags.backend.facade import api as feature_flags_facade
+
+AUTORESEARCH_FLAG = "autoresearch"
+
+
+def has_autoresearch_access(
+ user: AbstractBaseUser | AnonymousUser | None,
+ *,
+ team_id: int | None = None,
+ organization_id: str | None = None,
+) -> bool:
+ if not user or not user.is_authenticated:
+ return False
+ distinct_id = getattr(user, "distinct_id", None)
+ if not distinct_id:
+ return False
+
+ # In local dev the analytics SDK is disabled; fall back to a direct ORM check.
+ # DEBUG only: a production instance that disables the SDK (OPT_OUT_CAPTURE) must
+ # fail closed rather than grant access on any active flag row.
+ # Don't apply this in TEST mode, because tests mock feature_enabled directly.
+ if settings.DEBUG and not getattr(settings, "TEST", False):
+ return _local_flag_enabled(team_id=team_id)
+
+ if team_id is not None and organization_id is None:
+ organization_id = _organization_id_for_team(team_id)
+
+ # An organization-targeted rollout reaches the in-app flag evaluation, which sends the
+ # organization group. The shared helper sends it too, or the product renders and every
+ # request 403s. It also honors POSTHOG_FEATURE_FLAGS_FORCE_ENABLED, which a direct SDK
+ # call would skip.
+ if organization_id is not None:
+ return bool(
+ posthog_feature_flag_value(
+ AUTORESEARCH_FLAG,
+ distinct_id,
+ organization_id=organization_id,
+ team_id=team_id,
+ )
+ )
+
+ # No resolvable organization: evaluate with whatever group context exists.
+ groups: dict[str, str] = {}
+ group_properties: dict[str, dict[str, str]] = {}
+ if team_id is not None:
+ groups["project"] = str(team_id)
+ group_properties["project"] = {"id": str(team_id)}
+
+ return bool(
+ posthoganalytics.feature_enabled(
+ AUTORESEARCH_FLAG,
+ distinct_id,
+ groups=groups,
+ group_properties=group_properties,
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+
+
+def _organization_id_for_team(team_id: int) -> str | None:
+ organization_id = Team.objects.filter(pk=team_id).values_list("organization_id", flat=True).first()
+ return str(organization_id) if organization_id else None
+
+
+def _local_flag_enabled(*, team_id: int | None) -> bool:
+ return feature_flags_facade.flag_is_active(AUTORESEARCH_FLAG, team_id=team_id)
diff --git a/products/autoresearch/backend/admin.py b/products/autoresearch/backend/admin.py
new file mode 100644
index 000000000000..b839b786afd8
--- /dev/null
+++ b/products/autoresearch/backend/admin.py
@@ -0,0 +1,232 @@
+from typing import Any
+
+from django import forms
+from django.contrib import admin
+from django.db import models
+from django.http import HttpRequest
+
+from .models import (
+ AutoresearchIteration,
+ AutoresearchModel,
+ AutoresearchPipeline,
+ AutoresearchRun,
+ AutoresearchSuggestion,
+ AutoresearchTrainingRun,
+)
+
+
+class PipelineBoundRelationsForm(forms.ModelForm):
+ """Reports a cross-pipeline relation as a field error.
+
+ `PipelineScopedModel.save()` raises `ValueError` for a relation that belongs to another
+ pipeline. Admin does not turn a save-time exception into form feedback, so without this
+ the staff user gets a 500 instead of a message about the field they picked.
+ """
+
+ def clean(self) -> dict[str, Any]:
+ super().clean()
+ cleaned_data = self.cleaned_data
+ # `pipeline` is read-only on a saved row, so it reaches clean() only on the add form.
+ pipeline = cleaned_data.get("pipeline") or getattr(self.instance, "pipeline", None)
+ if pipeline is None:
+ return cleaned_data
+ for relation_name in self.instance._pipeline_bound_relations:
+ related = cleaned_data.get(relation_name)
+ if related is not None and related.pipeline_id != pipeline.pk:
+ self.add_error(relation_name, "Pick a row that belongs to the same pipeline.")
+ return cleaned_data
+
+
+class PipelineLockedAdminMixin(admin.ModelAdmin):
+ """Makes `pipeline` read-only once the row exists.
+
+ Rows that reference this one check same-pipeline consistency only on their own save,
+ so moving a saved row to another pipeline would strand its referencing rows under the
+ old pipeline and team.
+ """
+
+ form = PipelineBoundRelationsForm
+
+ def get_readonly_fields(self, request: HttpRequest, obj: models.Model | None = None) -> tuple[str, ...]:
+ readonly = super().get_readonly_fields(request, obj)
+ if obj is not None:
+ return (*readonly, "pipeline")
+ return tuple(readonly)
+
+
+class AutoresearchModelInline(admin.TabularInline):
+ model = AutoresearchModel
+ extra = 0
+ can_delete = False
+ show_change_link = True
+ fields = ("id", "role", "holdout_score", "realized_score", "is_preliminary", "created_at")
+ readonly_fields = ("id", "role", "holdout_score", "realized_score", "is_preliminary", "created_at")
+
+
+class AutoresearchTrainingRunInline(admin.TabularInline):
+ model = AutoresearchTrainingRun
+ extra = 0
+ can_delete = False
+ show_change_link = True
+ fields = ("id", "status", "iteration_count", "best_holdout_score", "created_at")
+ readonly_fields = ("id", "status", "iteration_count", "best_holdout_score", "created_at")
+
+
[email protected](AutoresearchPipeline)
+class AutoresearchPipelineAdmin(admin.ModelAdmin):
+ list_display = (
+ "name",
+ "team",
+ "target_event",
+ "horizon_days",
+ "status",
+ "created_by",
+ "created_at",
+ )
+ list_filter = ("status", "created_at")
+ search_fields = ("name", "target_event", "team__name")
+ readonly_fields = ("id", "created_at", "updated_at", "last_scored_at")
+ autocomplete_fields = ("team", "created_by")
+ inlines = [AutoresearchModelInline, AutoresearchTrainingRunInline]
+
+ fieldsets = (
+ (None, {"fields": ("id", "name", "description", "status")}),
+ ("Team & Owner", {"fields": ("team", "created_by")}),
+ (
+ "Prediction target",
+ {"fields": ("target_event", "target_definition", "horizon_days", "training_lookback_days")},
+ ),
+ ("Population", {"fields": ("training_population", "inference_population")}),
+ ("Output", {"fields": ("output_person_property",)}),
+ ("Budget & schedule", {"fields": ("iteration_budget", "iteration_budget_remaining", "cadence_days")}),
+ ("Stop criteria", {"fields": ("success_auc", "plateau_iterations")}),
+ ("Dates", {"fields": ("created_at", "updated_at", "last_scored_at")}),
+ )
+
+ def get_readonly_fields(self, request: HttpRequest, obj: AutoresearchPipeline | None = None) -> tuple[str, ...]:
+ # Every child row copies team_id from the pipeline at save time. Moving a saved
+ # pipeline to another team would strand those copies under the old tenant.
+ if obj is not None:
+ return (*self.readonly_fields, "team")
+ return self.readonly_fields
+
+
+class AutoresearchIterationInline(admin.TabularInline):
+ model = AutoresearchIteration
+ extra = 0
+ can_delete = False
+ show_change_link = True
+ fields = ("iteration_number", "status", "holdout_score", "train_score", "agent_confidence", "created_at")
+ readonly_fields = ("iteration_number", "status", "holdout_score", "train_score", "agent_confidence", "created_at")
+
+
[email protected](AutoresearchTrainingRun)
+class AutoresearchTrainingRunAdmin(PipelineLockedAdminMixin):
+ list_display = ("id", "pipeline", "status", "iteration_count", "best_holdout_score", "task_run_id", "created_at")
+ list_filter = ("status", "created_at")
+ search_fields = ("pipeline__name",)
+ readonly_fields = ("id", "created_at", "started_at", "completed_at")
+ raw_id_fields = ("pipeline",)
+ inlines = [AutoresearchIterationInline]
+
+ fieldsets = (
+ (None, {"fields": ("id", "pipeline", "status")}),
+ ("Task sandbox", {"fields": ("task_run_id",)}),
+ ("Progress", {"fields": ("iteration_budget", "iteration_count", "best_holdout_score")}),
+ ("Error", {"fields": ("error",)}),
+ ("Dates", {"fields": ("created_at", "started_at", "completed_at")}),
+ )
+
+
[email protected](AutoresearchModel)
+class AutoresearchModelAdmin(PipelineLockedAdminMixin):
+ list_display = (
+ "id",
+ "pipeline",
+ "role",
+ "holdout_score",
+ "realized_score",
+ "is_preliminary",
+ "recipe_hash",
+ "created_at",
+ )
+ list_filter = ("role", "is_preliminary", "created_at")
+ search_fields = ("pipeline__name", "recipe_hash", "agent_description")
+ # model_recipe is readonly because recipe_hash is its SHA-256; an admin edit to one
+ # without the other would break hash-based dedup and provenance.
+ readonly_fields = (
+ "id",
+ "recipe_hash",
+ "model_recipe",
+ "artifact_prefix",
+ "created_at",
+ "updated_at",
+ "promoted_at",
+ "archived_at",
+ )
+ raw_id_fields = ("pipeline", "source_training_run")
+
+ def has_add_permission(self, request: HttpRequest) -> bool:
+ # Models are created by the training loop and promotion. The add form excludes the
+ # read-only model_recipe, so a hand-created row would fail its NOT NULL constraint.
+ return False
+
+ fieldsets = (
+ (None, {"fields": ("id", "pipeline", "role", "is_preliminary")}),
+ ("Recipe", {"fields": ("recipe_hash", "model_recipe", "artifact_prefix", "model_explanation")}),
+ ("Performance", {"fields": ("holdout_score", "realized_score", "calibration_error", "metrics")}),
+ ("Provenance", {"fields": ("source_training_run", "agent_description", "trained_on_start", "trained_on_end")}),
+ ("Dates", {"fields": ("created_at", "updated_at", "promoted_at", "archived_at")}),
+ )
+
+
[email protected](AutoresearchIteration)
+class AutoresearchIterationAdmin(admin.ModelAdmin):
+ """Read-only detail view behind the training-run inline's change links."""
+
+ list_display = ("id", "training_run", "iteration_number", "status", "holdout_score", "created_at")
+ list_filter = ("status", "created_at")
+ search_fields = ("pipeline__name", "recipe_hash")
+ raw_id_fields = ("pipeline", "training_run", "parent_suggestion")
+
+ def has_add_permission(self, request: HttpRequest) -> bool:
+ return False
+
+ def has_change_permission(self, request: HttpRequest, obj: AutoresearchIteration | None = None) -> bool:
+ return False
+
+ def has_delete_permission(self, request: HttpRequest, obj: AutoresearchIteration | None = None) -> bool:
+ return False
+
+
[email protected](AutoresearchRun)
+class AutoresearchRunAdmin(admin.ModelAdmin):
+ form = PipelineBoundRelationsForm
+ list_display = ("id", "pipeline", "run_type", "status", "rows_scored", "created_at")
+ list_filter = ("run_type", "status", "created_at")
+ search_fields = ("pipeline__name",)
+ readonly_fields = ("id", "created_at", "started_at", "completed_at")
+ raw_id_fields = ("pipeline", "model")
+
+ fieldsets = (
+ (None, {"fields": ("id", "pipeline", "model", "run_type", "status")}),
+ ("Results", {"fields": ("rows_scored", "metrics")}),
+ ("Error", {"fields": ("error",)}),
+ ("Dates", {"fields": ("created_at", "started_at", "completed_at")}),
+ )
+
+
[email protected](AutoresearchSuggestion)
+class AutoresearchSuggestionAdmin(PipelineLockedAdminMixin):
+ list_display = ("id", "pipeline", "priority", "status", "source", "created_by", "created_at")
+ list_filter = ("priority", "status", "source", "created_at")
+ search_fields = ("pipeline__name", "prompt")
+ readonly_fields = ("id", "created_at", "updated_at")
+ raw_id_fields = ("pipeline", "created_by")
+
+ fieldsets = (
+ (None, {"fields": ("id", "pipeline", "created_by", "source")}),
+ ("Content", {"fields": ("prompt", "priority", "status")}),
+ ("Agent response", {"fields": ("agent_response",)}),
+ ("Dates", {"fields": ("created_at", "updated_at")}),
+ )
diff --git a/products/autoresearch/backend/facade/access.py b/products/autoresearch/backend/facade/access.py
new file mode 100644
index 000000000000..f6005433e909
--- /dev/null
+++ b/products/autoresearch/backend/facade/access.py
@@ -0,0 +1,6 @@
+"""Access-gate re-export — the flag check the presentation layer reaches for."""
+
+from ..access import (
+ AUTORESEARCH_FLAG as AUTORESEARCH_FLAG,
+ has_autoresearch_access as has_autoresearch_access,
+)
diff --git a/products/autoresearch/backend/migrations/0001_initial.py b/products/autoresearch/backend/migrations/0001_initial.py
new file mode 100644
index 000000000000..670c411e8e02
--- /dev/null
+++ b/products/autoresearch/backend/migrations/0001_initial.py
@@ -0,0 +1,877 @@
+# Generated by Django 5.2.17 on 2026-08-31 11:36
+
+import django.core.validators
+import django.db.models.manager
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = [
+ # Anchored below posthog.1316: pulling that rename into a fresh-DB plan ahead of
+ # ee.0058 breaks its backfill, which still queries the pre-rename field name.
+ ("posthog", "1310_provisioning_rate_limit_overrides"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="AutoresearchPipeline",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("name", models.CharField(max_length=255)),
+ ("description", models.TextField(blank=True, default="")),
+ (
+ "target_event",
+ models.CharField(
+ help_text="Event name to predict, e.g. '$pageview'",
+ max_length=255,
+ ),
+ ),
+ (
+ "target_definition",
+ models.JSONField(
+ default=dict,
+ help_text="Full target definition including filters and positive-label logic",
+ ),
+ ),
+ (
+ "horizon_days",
+ models.IntegerField(
+ default=7,
+ help_text="Predict whether the target occurs within N days",
+ validators=[django.core.validators.MinValueValidator(1)],
+ ),
+ ),
+ (
+ "training_lookback_days",
+ models.IntegerField(
+ default=180,
+ help_text="How far back to look for training examples. Larger windows give more data but may include stale behavior.",
+ validators=[django.core.validators.MinValueValidator(1)],
+ ),
+ ),
+ (
+ "training_population",
+ models.JSONField(
+ default=dict,
+ help_text="HogQL cohort or filter defining the training population",
+ ),
+ ),
+ (
+ "inference_population",
+ models.JSONField(
+ default=dict,
+ help_text="HogQL cohort or filter defining the daily scoring population",
+ ),
+ ),
+ (
+ "cadence_days",
+ models.IntegerField(
+ default=1,
+ help_text="Re-score every N days",
+ validators=[django.core.validators.MinValueValidator(1)],
+ ),
+ ),
+ (
+ "iteration_budget",
+ models.IntegerField(
+ default=50,
+ help_text="Max training iterations for the autoresearch loop",
+ validators=[django.core.validators.MinValueValidator(1)],
+ ),
+ ),
+ (
+ "iteration_budget_remaining",
+ models.IntegerField(
+ blank=True,
+ default=None,
+ null=True,
+ validators=[django.core.validators.MinValueValidator(0)],
+ ),
+ ),
+ (
+ "success_auc",
+ models.FloatField(
+ blank=True,
+ help_text="Stop when holdout AUC reaches this threshold",
+ null=True,
+ validators=[
+ django.core.validators.MinValueValidator(0.0),
+ django.core.validators.MaxValueValidator(1.0),
+ ],
+ ),
+ ),
+ (
+ "plateau_iterations",
+ models.IntegerField(
+ default=10,
+ help_text="Stop if no improvement after this many consecutive iterations",
+ validators=[django.core.validators.MinValueValidator(1)],
+ ),
+ ),
+ (
+ "output_person_property",
+ models.CharField(
+ blank=True,
+ default="",
+ help_text="Person property name for champion scores, e.g. 'predicted_p_pageview'",
+ max_length=255,
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("draft", "Draft"),
+ ("bootstrapping", "Bootstrapping"),
+ ("running", "Running"),
+ ("converged", "Converged"),
+ ("paused", "Paused"),
+ ("archived", "Archived"),
+ ],
+ default="draft",
+ max_length=20,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ("last_scored_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ["-created_at"],
+ "default_manager_name": "all_teams",
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.CreateModel(
+ name="AutoresearchModel",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "role",
+ models.CharField(
+ choices=[
+ ("champion", "Champion"),
+ ("challenger", "Challenger"),
+ ("archived", "Archived"),
+ ],
+ default="challenger",
+ max_length=20,
+ ),
+ ),
+ (
+ "recipe_hash",
+ models.CharField(help_text="SHA-256 of the serialized recipe JSON", max_length=64),
+ ),
+ (
+ "model_recipe",
+ models.JSONField(
+ help_text="Portable recipe: feature_sql, feature_transforms, model_class, model_params, etc."
+ ),
+ ),
+ (
+ "artifact_prefix",
+ models.CharField(blank=True, default="", max_length=500),
+ ),
+ (
+ "model_explanation",
+ models.JSONField(
+ default=dict,
+ help_text="Global feature importance, directionality, stability, leakage warnings",
+ ),
+ ),
+ (
+ "holdout_score",
+ models.FloatField(
+ blank=True,
+ help_text="Offline holdout AUC",
+ null=True,
+ validators=[
+ django.core.validators.MinValueValidator(0.0),
+ django.core.validators.MaxValueValidator(1.0),
+ ],
+ ),
+ ),
+ (
+ "realized_score",
+ models.FloatField(
+ blank=True,
+ help_text="Online realized AUC once labels mature",
+ null=True,
+ validators=[
+ django.core.validators.MinValueValidator(0.0),
+ django.core.validators.MaxValueValidator(1.0),
+ ],
+ ),
+ ),
+ ("calibration_error", models.FloatField(blank=True, null=True)),
+ (
+ "metrics",
+ models.JSONField(
+ default=dict,
+ help_text="Full metrics bundle (train/holdout/realized)",
+ ),
+ ),
+ ("agent_description", models.TextField(blank=True, default="")),
+ ("trained_on_start", models.DateField(blank=True, null=True)),
+ ("trained_on_end", models.DateField(blank=True, null=True)),
+ (
+ "is_preliminary",
+ models.BooleanField(
+ default=True,
+ help_text="True until at least one realized validation cycle completes",
+ ),
+ ),
+ ("promoted_at", models.DateTimeField(blank=True, null=True)),
+ ("archived_at", models.DateTimeField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ (
+ "pipeline",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="models",
+ to="autoresearch.autoresearchpipeline",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ["-created_at"],
+ "default_manager_name": "all_teams",
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.CreateModel(
+ name="AutoresearchRun",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "run_type",
+ models.CharField(
+ choices=[
+ ("inference", "Inference"),
+ ("validation", "Validation"),
+ ],
+ max_length=20,
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("pending", "Pending"),
+ ("running", "Running"),
+ ("completed", "Completed"),
+ ("failed", "Failed"),
+ ],
+ default="pending",
+ max_length=20,
+ ),
+ ),
+ (
+ "rows_scored",
+ models.IntegerField(
+ blank=True,
+ null=True,
+ validators=[django.core.validators.MinValueValidator(0)],
+ ),
+ ),
+ ("metrics", models.JSONField(default=dict)),
+ ("error", models.TextField(blank=True, default="")),
+ ("started_at", models.DateTimeField(blank=True, null=True)),
+ ("completed_at", models.DateTimeField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "model",
+ models.ForeignKey(
+ blank=True,
+ help_text="Champion model used for this run",
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="runs",
+ to="autoresearch.autoresearchmodel",
+ ),
+ ),
+ (
+ "pipeline",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="runs",
+ to="autoresearch.autoresearchpipeline",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ["-created_at"],
+ "default_manager_name": "all_teams",
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.CreateModel(
+ name="AutoresearchSuggestion",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "prompt",
+ models.TextField(help_text="Free-text hypothesis or direction for the agent to explore"),
+ ),
+ (
+ "priority",
+ models.CharField(
+ choices=[("try_next", "Try next"), ("consider", "Consider")],
+ default="consider",
+ help_text="'try_next' instructs the agent to act on this before other iterations; 'consider' is advisory",
+ max_length=20,
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("queued", "Queued"),
+ ("picked_up", "Picked up"),
+ ("acted_on", "Acted on"),
+ ("dismissed", "Dismissed"),
+ ],
+ default="queued",
+ max_length=20,
+ ),
+ ),
+ (
+ "source",
+ models.CharField(
+ choices=[("user", "User"), ("agent", "Agent")],
+ default="user",
+ help_text="Whether the suggestion came from a human user or an agent",
+ max_length=20,
+ ),
+ ),
+ (
+ "agent_response",
+ models.TextField(
+ blank=True,
+ default="",
+ help_text="Agent's note on how the suggestion was interpreted and acted upon",
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "pipeline",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="suggestions",
+ to="autoresearch.autoresearchpipeline",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ["-created_at"],
+ "default_manager_name": "all_teams",
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.CreateModel(
+ name="AutoresearchTrainingRun",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "task_id",
+ models.UUIDField(
+ blank=True,
+ help_text="Parent Task ID in the tasks product sandbox",
+ null=True,
+ ),
+ ),
+ (
+ "task_run_id",
+ models.UUIDField(
+ blank=True,
+ help_text="TaskRun ID in the tasks product sandbox",
+ null=True,
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("pending", "Pending"),
+ ("running", "Running"),
+ ("completed", "Completed"),
+ ("failed", "Failed"),
+ ],
+ default="pending",
+ max_length=20,
+ ),
+ ),
+ (
+ "iteration_budget",
+ models.IntegerField(
+ default=50,
+ validators=[django.core.validators.MinValueValidator(1)],
+ ),
+ ),
+ (
+ "iteration_count",
+ models.IntegerField(
+ default=0,
+ validators=[django.core.validators.MinValueValidator(0)],
+ ),
+ ),
+ (
+ "best_holdout_score",
+ models.FloatField(
+ blank=True,
+ null=True,
+ validators=[
+ django.core.validators.MinValueValidator(0.0),
+ django.core.validators.MaxValueValidator(1.0),
+ ],
+ ),
+ ),
+ ("error", models.TextField(blank=True, default="")),
+ ("summary", models.JSONField(blank=True, default=dict)),
+ ("started_at", models.DateTimeField(blank=True, null=True)),
+ ("completed_at", models.DateTimeField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "pipeline",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="training_runs",
+ to="autoresearch.autoresearchpipeline",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ["-created_at"],
+ "default_manager_name": "all_teams",
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.AddField(
+ model_name="autoresearchmodel",
+ name="source_training_run",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="candidate_models",
+ to="autoresearch.autoresearchtrainingrun",
+ ),
+ ),
+ migrations.CreateModel(
+ name="AutoresearchIteration",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("iteration_number", models.IntegerField()),
+ ("recipe_hash", models.CharField(max_length=64)),
+ (
+ "recipe_snapshot",
+ models.JSONField(help_text="Compact recipe at time of iteration; full artifact in model row"),
+ ),
+ (
+ "model_spec",
+ models.JSONField(
+ default=dict,
+ help_text="model_class + hyperparams tried this iteration",
+ ),
+ ),
+ (
+ "train_score",
+ models.FloatField(
+ blank=True,
+ null=True,
+ validators=[
+ django.core.validators.MinValueValidator(0.0),
+ django.core.validators.MaxValueValidator(1.0),
+ ],
+ ),
+ ),
+ (
+ "holdout_score",
+ models.FloatField(
+ blank=True,
+ null=True,
+ validators=[
+ django.core.validators.MinValueValidator(0.0),
+ django.core.validators.MaxValueValidator(1.0),
+ ],
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("kept", "Kept"),
+ ("discarded", "Discarded"),
+ ("crashed", "Crashed"),
+ ],
+ max_length=20,
+ ),
+ ),
+ ("agent_description", models.TextField(blank=True, default="")),
+ (
+ "agent_confidence",
+ models.FloatField(
+ blank=True,
+ help_text="Agent's self-assessed confidence 0–1",
+ null=True,
+ validators=[
+ django.core.validators.MinValueValidator(0.0),
+ django.core.validators.MaxValueValidator(1.0),
+ ],
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ (
+ "pipeline",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="iterations",
+ to="autoresearch.autoresearchpipeline",
+ ),
+ ),
+ (
+ "parent_suggestion",
+ models.ForeignKey(
+ blank=True,
+ help_text="Suggestion that spawned this iteration, if any",
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="iterations",
+ to="autoresearch.autoresearchsuggestion",
+ ),
+ ),
+ (
+ "training_run",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="iterations",
+ to="autoresearch.autoresearchtrainingrun",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ["iteration_number"],
+ "default_manager_name": "all_teams",
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchpipeline",
+ constraint=models.CheckConstraint(
+ condition=models.Q(("horizon_days__gte", 1)),
+ name="autoresearch_horizon_days_positive",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchpipeline",
+ constraint=models.CheckConstraint(
+ condition=models.Q(("training_lookback_days__gte", 1)),
+ name="autoresearch_lookback_days_positive",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchpipeline",
+ constraint=models.CheckConstraint(
+ condition=models.Q(("cadence_days__gte", 1)),
+ name="autoresearch_cadence_days_positive",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchpipeline",
+ constraint=models.CheckConstraint(
+ condition=models.Q(("iteration_budget__gte", 1)),
+ name="autoresearch_iteration_budget_positive",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchpipeline",
+ constraint=models.CheckConstraint(
+ condition=models.Q(("plateau_iterations__gte", 1)),
+ name="autoresearch_plateau_iterations_positive",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchpipeline",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ ("success_auc__isnull", True),
+ models.Q(("success_auc__gte", 0.0), ("success_auc__lte", 1.0)),
+ _connector="OR",
+ ),
+ name="autoresearch_success_auc_in_unit_range",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchmodel",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("role", "champion")),
+ fields=("pipeline",),
+ name="autoresearch_one_champion_per_pipeline",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchmodel",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ ("holdout_score__isnull", True),
+ models.Q(("holdout_score__gte", 0.0), ("holdout_score__lte", 1.0)),
+ _connector="OR",
+ ),
+ name="autoresearch_model_holdout_score_in_unit_range",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchmodel",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ ("realized_score__isnull", True),
+ models.Q(("realized_score__gte", 0.0), ("realized_score__lte", 1.0)),
+ _connector="OR",
+ ),
+ name="autoresearch_model_realized_score_in_unit_range",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchtrainingrun",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ ("best_holdout_score__isnull", True),
+ models.Q(("best_holdout_score__gte", 0.0), ("best_holdout_score__lte", 1.0)),
+ _connector="OR",
+ ),
+ name="autoresearch_training_run_best_holdout_score_in_unit_range",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchiteration",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ ("train_score__isnull", True),
+ models.Q(("train_score__gte", 0.0), ("train_score__lte", 1.0)),
+ _connector="OR",
+ ),
+ name="autoresearch_iteration_train_score_in_unit_range",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchiteration",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ ("holdout_score__isnull", True),
+ models.Q(("holdout_score__gte", 0.0), ("holdout_score__lte", 1.0)),
+ _connector="OR",
+ ),
+ name="autoresearch_iteration_holdout_score_in_unit_range",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchiteration",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ ("agent_confidence__isnull", True),
+ models.Q(("agent_confidence__gte", 0.0), ("agent_confidence__lte", 1.0)),
+ _connector="OR",
+ ),
+ name="autoresearch_iteration_agent_confidence_in_unit_range",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchpipeline",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ ("iteration_budget_remaining__isnull", True),
+ ("iteration_budget_remaining__gte", 0),
+ _connector="OR",
+ ),
+ name="autoresearch_budget_remaining_nonnegative",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchmodel",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ ("trained_on_start__isnull", True),
+ ("trained_on_end__isnull", True),
+ ("trained_on_start__lte", models.F("trained_on_end")),
+ _connector="OR",
+ ),
+ name="autoresearch_model_trained_on_range_ordered",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchtrainingrun",
+ constraint=models.CheckConstraint(
+ condition=models.Q(("iteration_budget__gte", 1)),
+ name="autoresearch_training_run_iteration_budget_positive",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchtrainingrun",
+ constraint=models.CheckConstraint(
+ condition=models.Q(("iteration_count__gte", 0)),
+ name="autoresearch_training_run_iteration_count_nonnegative",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="autoresearchrun",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ ("rows_scored__isnull", True),
+ ("rows_scored__gte", 0),
+ _connector="OR",
+ ),
+ name="autoresearch_run_rows_scored_nonnegative",
+ ),
+ ),
+ migrations.AlterUniqueTogether(
+ name="autoresearchiteration",
+ unique_together={("training_run", "iteration_number")},
+ ),
+ ]
diff --git a/products/autoresearch/backend/migrations/__init__.py b/products/autoresearch/backend/migrations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/autoresearch/backend/migrations/max_migration.txt b/products/autoresearch/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..cbab66dde92a
--- /dev/null
+++ b/products/autoresearch/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_initial
diff --git a/products/autoresearch/backend/models.py b/products/autoresearch/backend/models.py
new file mode 100644
index 000000000000..06a3d41a40ed
--- /dev/null
+++ b/products/autoresearch/backend/models.py
@@ -0,0 +1,475 @@
+from typing import TYPE_CHECKING, Any, ClassVar
+
+if TYPE_CHECKING:
+ import uuid
+
+from django.core.validators import MaxValueValidator, MinValueValidator
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel, uuid7
+
+# AUC and confidence scores are probabilities: NULL until measured, otherwise in [0, 1].
+# An out-of-range score corrupts model comparison, so the database rejects it too.
+UNIT_INTERVAL_VALIDATORS = [MinValueValidator(0.0), MaxValueValidator(1.0)]
+
+
+def unit_interval_constraint(field: str, name: str) -> models.CheckConstraint:
+ return models.CheckConstraint(
+ check=models.Q(**{f"{field}__isnull": True}) | models.Q(**{f"{field}__gte": 0.0, f"{field}__lte": 1.0}),
+ name=name,
+ )
+
+
+def min_value_constraint(field: str, minimum: int, name: str, *, nullable: bool = False) -> models.CheckConstraint:
+ at_least = models.Q(**{f"{field}__gte": minimum})
+ if nullable:
+ at_least = models.Q(**{f"{field}__isnull": True}) | at_least
+ return models.CheckConstraint(check=at_least, name=name)
+
+
+class AutoresearchPipeline(TeamScopedRootMixin, UUIDModel):
+ # Framework internals (admin querysets, FK form fields, raw-id widget lookups) read
+ # `_default_manager` with no team context, where the fail-closed `objects` would raise.
+ # Route them through this unscoped sibling via `Meta.default_manager_name`, mirroring
+ # `ProductTeamModel`; scoped reads stay on `objects`.
+ all_teams = models.Manager()
+
+ class Status(models.TextChoices):
+ DRAFT = "draft", "Draft"
+ BOOTSTRAPPING = "bootstrapping", "Bootstrapping"
+ RUNNING = "running", "Running"
+ CONVERGED = "converged", "Converged"
+ PAUSED = "paused", "Paused"
+ ARCHIVED = "archived", "Archived"
+
+ id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
+ # db_constraint=False on team/user FKs: creating a real constraint takes a
+ # SHARE ROW EXCLUSIVE lock on the hot parent table (see /django-migrations).
+ # related_name="+" on every relation into core: a reverse accessor on Team or User is a
+ # boundary crossing no import linter can see, and nothing needs to read autoresearch rows
+ # off a team. Callers go through the facade.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ created_by = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_index=False,
+ db_constraint=False,
+ related_name="+",
+ )
+ name = models.CharField(max_length=255)
+ description = models.TextField(blank=True, default="")
+
+ # Prediction target
+ target_event = models.CharField(max_length=255, help_text="Event name to predict, e.g. '$pageview'")
+ target_definition = models.JSONField(
+ default=dict, help_text="Full target definition including filters and positive-label logic"
+ )
+ horizon_days = models.IntegerField(
+ default=7, validators=[MinValueValidator(1)], help_text="Predict whether the target occurs within N days"
+ )
+ training_lookback_days = models.IntegerField(
+ default=180,
+ validators=[MinValueValidator(1)],
+ help_text="How far back to look for training examples. Larger windows give more data but may include stale behavior.",
+ )
+
+ # Population
+ training_population = models.JSONField(
+ default=dict, help_text="HogQL cohort or filter defining the training population"
+ )
+ inference_population = models.JSONField(
+ default=dict, help_text="HogQL cohort or filter defining the daily scoring population"
+ )
+
+ # Schedule and budget
+ cadence_days = models.IntegerField(default=1, validators=[MinValueValidator(1)], help_text="Re-score every N days")
+ iteration_budget = models.IntegerField(
+ default=50, validators=[MinValueValidator(1)], help_text="Max training iterations for the autoresearch loop"
+ )
+ # Nullable so save() can tell "not supplied" from an explicit value; filled from
+ # iteration_budget on first save.
+ iteration_budget_remaining = models.IntegerField(
+ null=True, blank=True, default=None, validators=[MinValueValidator(0)]
+ )
+
+ # Stop criteria
+ success_auc = models.FloatField(
+ null=True,
+ blank=True,
+ validators=UNIT_INTERVAL_VALIDATORS,
+ help_text="Stop when holdout AUC reaches this threshold",
+ )
+ plateau_iterations = models.IntegerField(
+ default=10,
+ validators=[MinValueValidator(1)],
+ help_text="Stop if no improvement after this many consecutive iterations",
+ )
+
+ # Outputs
+ output_person_property = models.CharField(
+ max_length=255,
+ blank=True,
+ default="",
+ help_text="Person property name for champion scores, e.g. 'predicted_p_pageview'",
+ )
+
+ status = models.CharField(max_length=20, choices=Status.choices, default=Status.DRAFT)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+ last_scored_at = models.DateTimeField(null=True, blank=True)
+
+ class Meta:
+ ordering = ["-created_at"]
+ default_manager_name = "all_teams"
+ constraints = [
+ min_value_constraint("horizon_days", 1, "autoresearch_horizon_days_positive"),
+ min_value_constraint("training_lookback_days", 1, "autoresearch_lookback_days_positive"),
+ min_value_constraint("cadence_days", 1, "autoresearch_cadence_days_positive"),
+ min_value_constraint("iteration_budget", 1, "autoresearch_iteration_budget_positive"),
+ min_value_constraint("plateau_iterations", 1, "autoresearch_plateau_iterations_positive"),
+ min_value_constraint(
+ "iteration_budget_remaining", 0, "autoresearch_budget_remaining_nonnegative", nullable=True
+ ),
+ unit_interval_constraint("success_auc", "autoresearch_success_auc_in_unit_range"),
+ ]
+
+ def save(self, *args: Any, **kwargs: Any) -> None:
+ # Fill only at creation: a later save must not silently refund an exhausted budget.
+ if self._state.adding and self.iteration_budget_remaining is None:
+ self.iteration_budget_remaining = self.iteration_budget
+ super().save(*args, **kwargs)
+
+ def __str__(self) -> str:
+ return f"{self.name} ({self.team_id})"
+
+
+class PipelineScopedModel(TeamScopedRootMixin, UUIDModel):
+ """A row owned by one pipeline. Subclasses declare their own `pipeline` foreign key.
+
+ The row carries team rather than reaching it through pipeline, because
+ TeamScopedManager filters on a team column the model itself declares, and save()
+ derives it from the parent so a caller cannot file a row under the wrong tenant.
+ """
+
+ id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
+ # See AutoresearchPipeline.team: no reverse accessor on the core model.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+
+ # See AutoresearchPipeline.all_teams: framework internals need an unscoped
+ # `_default_manager`; concrete subclasses set `Meta.default_manager_name = "all_teams"`.
+ all_teams = models.Manager()
+
+ # Relations that must belong to the same pipeline as this row. save() rejects a
+ # mismatch, so a row cannot mix parents across pipelines.
+ _pipeline_bound_relations: ClassVar[tuple[str, ...]] = ()
+
+ if TYPE_CHECKING:
+ # Subclasses declare the pipeline FK; this names its attname for the shared save().
+ pipeline_id: "uuid.UUID"
+
+ class Meta:
+ abstract = True
+
+ def save(self, *args: Any, **kwargs: Any) -> None:
+ # RelatedObjectDoesNotExist subclasses AttributeError, so an unset pipeline reads as None.
+ pipeline = getattr(self, "pipeline", None)
+ if pipeline is not None:
+ # Overwrite unconditionally: an explicit team_id that disagrees with the
+ # pipeline's would file the row under the wrong tenant.
+ self.team_id = pipeline.team_id
+ # A partial save that writes the pipeline must write the derived team with it,
+ # or the row keeps its old tenant while pointing at the new pipeline.
+ update_fields = kwargs.get("update_fields")
+ if update_fields is not None and not {"pipeline", "pipeline_id"}.isdisjoint(update_fields):
+ kwargs["update_fields"] = {*update_fields, "team"}
+ for relation_name in self._pipeline_bound_relations:
+ related = getattr(self, relation_name, None)
+ if related is not None and related.pipeline_id != self.pipeline_id:
+ raise ValueError(
+ f"{type(self).__name__}.{relation_name} belongs to pipeline {related.pipeline_id}, "
+ f"not this row's pipeline {self.pipeline_id}"
+ )
+ super().save(*args, **kwargs)
+
+
+class AutoresearchModel(PipelineScopedModel):
+ """A persisted, versioned champion or challenger recipe."""
+
+ class Role(models.TextChoices):
+ CHAMPION = "champion", "Champion"
+ CHALLENGER = "challenger", "Challenger"
+ ARCHIVED = "archived", "Archived"
+
+ pipeline = models.ForeignKey(AutoresearchPipeline, on_delete=models.CASCADE, related_name="models")
+
+ role = models.CharField(max_length=20, choices=Role.choices, default=Role.CHALLENGER)
+
+ _pipeline_bound_relations = ("source_training_run",)
+
+ # Portable recipe, the load-bearing artifact
+ recipe_hash = models.CharField(max_length=64, help_text="SHA-256 of the serialized recipe JSON")
+ model_recipe = models.JSONField(
+ help_text="Portable recipe: feature_sql, feature_transforms, model_class, model_params, etc."
+ )
+ # Object-storage key prefix for the artifact bundle (train.py, predict.py, features.sql).
+ # When set, inference runs the bundle in a sandbox instead of the in-process recipe path.
+ # Empty for legacy recipe-only models.
+ artifact_prefix = models.CharField(max_length=500, blank=True, default="")
+ model_explanation = models.JSONField(
+ default=dict,
+ help_text="Global feature importance, directionality, stability, leakage warnings",
+ )
+
+ # Performance
+ holdout_score = models.FloatField(
+ null=True, blank=True, validators=UNIT_INTERVAL_VALIDATORS, help_text="Offline holdout AUC"
+ )
+ realized_score = models.FloatField(
+ null=True,
+ blank=True,
+ validators=UNIT_INTERVAL_VALIDATORS,
+ help_text="Online realized AUC once labels mature",
+ )
+ calibration_error = models.FloatField(null=True, blank=True)
+ metrics = models.JSONField(default=dict, help_text="Full metrics bundle (train/holdout/realized)")
+
+ # Provenance
+ source_training_run = models.ForeignKey(
+ "autoresearch.AutoresearchTrainingRun",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="candidate_models",
+ )
+ agent_description = models.TextField(blank=True, default="")
+ trained_on_start = models.DateField(null=True, blank=True)
+ trained_on_end = models.DateField(null=True, blank=True)
+ is_preliminary = models.BooleanField(
+ default=True, help_text="True until at least one realized validation cycle completes"
+ )
+
+ promoted_at = models.DateTimeField(null=True, blank=True)
+ archived_at = models.DateTimeField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ ordering = ["-created_at"]
+ default_manager_name = "all_teams"
+ constraints = [
+ # Inference and scoring read "the champion" as a single row; two champions
+ # would make that read ambiguous, so the database rejects the second.
+ models.UniqueConstraint(
+ fields=["pipeline"],
+ condition=models.Q(role="champion"),
+ name="autoresearch_one_champion_per_pipeline",
+ ),
+ unit_interval_constraint("holdout_score", "autoresearch_model_holdout_score_in_unit_range"),
+ unit_interval_constraint("realized_score", "autoresearch_model_realized_score_in_unit_range"),
+ models.CheckConstraint(
+ check=models.Q(trained_on_start__isnull=True)
+ | models.Q(trained_on_end__isnull=True)
+ | models.Q(trained_on_start__lte=models.F("trained_on_end")),
+ name="autoresearch_model_trained_on_range_ordered",
+ ),
+ ]
+
+ def __str__(self) -> str:
+ return f"{self.role} model for pipeline {self.pipeline_id}"
+
+
+class AutoresearchTrainingRun(PipelineScopedModel):
+ """One bounded training/bootstrap session backed by a Task/TaskRun."""
+
+ class Status(models.TextChoices):
+ PENDING = "pending", "Pending"
+ RUNNING = "running", "Running"
+ COMPLETED = "completed", "Completed"
+ FAILED = "failed", "Failed"
+
+ pipeline = models.ForeignKey(AutoresearchPipeline, on_delete=models.CASCADE, related_name="training_runs")
+
+ # Link to the Task/TaskRun sandbox (nullable for stubs).
+ # task_id is the parent Task, which the /tasks/:taskId detail UI needs.
+ # task_run_id is the specific TaskRun, kept for log lookups.
+ task_id = models.UUIDField(null=True, blank=True, help_text="Parent Task ID in the tasks product sandbox")
+ task_run_id = models.UUIDField(null=True, blank=True, help_text="TaskRun ID in the tasks product sandbox")
+
+ status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)
+ iteration_budget = models.IntegerField(default=50, validators=[MinValueValidator(1)])
+ iteration_count = models.IntegerField(default=0, validators=[MinValueValidator(0)])
+ best_holdout_score = models.FloatField(null=True, blank=True, validators=UNIT_INTERVAL_VALIDATORS)
+ error = models.TextField(blank=True, default="")
+ # Tier-1 cross-run learning memory: a distilled, structured summary of this run written on
+ # completion. Backend derives the structural fields (champion, kept ladder, dead-ends) from the
+ # recorded iterations; the agent enriches recommended_next + distillation via the complete tool.
+ # Read back by a new run via the training_runs/history endpoint to orient before iterating.
+ summary = models.JSONField(default=dict, blank=True)
+
+ started_at = models.DateTimeField(null=True, blank=True)
+ completed_at = models.DateTimeField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ ordering = ["-created_at"]
+ default_manager_name = "all_teams"
+ constraints = [
+ unit_interval_constraint(
+ "best_holdout_score", "autoresearch_training_run_best_holdout_score_in_unit_range"
+ ),
+ min_value_constraint("iteration_budget", 1, "autoresearch_training_run_iteration_budget_positive"),
+ min_value_constraint("iteration_count", 0, "autoresearch_training_run_iteration_count_nonnegative"),
+ ]
+
+
+class AutoresearchIteration(PipelineScopedModel):
+ """One recipe attempt within a training run."""
+
+ class Status(models.TextChoices):
+ KEPT = "kept", "Kept"
+ DISCARDED = "discarded", "Discarded"
+ CRASHED = "crashed", "Crashed"
+
+ pipeline = models.ForeignKey(AutoresearchPipeline, on_delete=models.CASCADE, related_name="iterations")
+ training_run = models.ForeignKey(AutoresearchTrainingRun, on_delete=models.CASCADE, related_name="iterations")
+
+ _pipeline_bound_relations = ("training_run", "parent_suggestion")
+
+ iteration_number = models.IntegerField()
+ recipe_hash = models.CharField(max_length=64)
+ recipe_snapshot = models.JSONField(help_text="Compact recipe at time of iteration; full artifact in model row")
+ model_spec = models.JSONField(default=dict, help_text="model_class + hyperparams tried this iteration")
+
+ train_score = models.FloatField(null=True, blank=True, validators=UNIT_INTERVAL_VALIDATORS)
+ holdout_score = models.FloatField(null=True, blank=True, validators=UNIT_INTERVAL_VALIDATORS)
+ status = models.CharField(max_length=20, choices=Status.choices)
+ agent_description = models.TextField(blank=True, default="")
+ agent_confidence = models.FloatField(
+ null=True, blank=True, validators=UNIT_INTERVAL_VALIDATORS, help_text="Agent's self-assessed confidence 0–1"
+ )
+ parent_suggestion = models.ForeignKey(
+ "autoresearch.AutoresearchSuggestion",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="iterations",
+ help_text="Suggestion that spawned this iteration, if any",
+ )
+
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ ordering = ["iteration_number"]
+ default_manager_name = "all_teams"
+ unique_together = [("training_run", "iteration_number")]
+ constraints = [
+ unit_interval_constraint("train_score", "autoresearch_iteration_train_score_in_unit_range"),
+ unit_interval_constraint("holdout_score", "autoresearch_iteration_holdout_score_in_unit_range"),
+ unit_interval_constraint("agent_confidence", "autoresearch_iteration_agent_confidence_in_unit_range"),
+ ]
+
+
+class AutoresearchSuggestion(PipelineScopedModel):
+ """A free-text hypothesis or direction injected into a running pipeline by a user or agent."""
+
+ class Priority(models.TextChoices):
+ TRY_NEXT = "try_next", "Try next"
+ CONSIDER = "consider", "Consider"
+
+ class Status(models.TextChoices):
+ QUEUED = "queued", "Queued"
+ PICKED_UP = "picked_up", "Picked up"
+ ACTED_ON = "acted_on", "Acted on"
+ DISMISSED = "dismissed", "Dismissed"
+
+ class Source(models.TextChoices):
+ USER = "user", "User"
+ AGENT = "agent", "Agent"
+
+ pipeline = models.ForeignKey(AutoresearchPipeline, on_delete=models.CASCADE, related_name="suggestions")
+ created_by = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_index=False,
+ db_constraint=False,
+ related_name="+",
+ )
+
+ prompt = models.TextField(help_text="Free-text hypothesis or direction for the agent to explore")
+ priority = models.CharField(
+ max_length=20,
+ choices=Priority.choices,
+ default=Priority.CONSIDER,
+ help_text="'try_next' instructs the agent to act on this before other iterations; 'consider' is advisory",
+ )
+ status = models.CharField(max_length=20, choices=Status.choices, default=Status.QUEUED)
+ source = models.CharField(
+ max_length=20,
+ choices=Source.choices,
+ default=Source.USER,
+ help_text="Whether the suggestion came from a human user or an agent",
+ )
+ agent_response = models.TextField(
+ blank=True,
+ default="",
+ help_text="Agent's note on how the suggestion was interpreted and acted upon",
+ )
+
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ ordering = ["-created_at"]
+ default_manager_name = "all_teams"
+
+ def __str__(self) -> str:
+ return f"[{self.priority}] {self.prompt[:60]} ({self.status})"
+
+
+class AutoresearchRun(PipelineScopedModel):
+ """Generic operational run: inference or validation."""
+
+ class RunType(models.TextChoices):
+ INFERENCE = "inference", "Inference"
+ VALIDATION = "validation", "Validation"
+
+ class Status(models.TextChoices):
+ PENDING = "pending", "Pending"
+ RUNNING = "running", "Running"
+ COMPLETED = "completed", "Completed"
+ FAILED = "failed", "Failed"
+
+ pipeline = models.ForeignKey(AutoresearchPipeline, on_delete=models.CASCADE, related_name="runs")
+
+ _pipeline_bound_relations = ("model",)
+
+ model = models.ForeignKey(
+ AutoresearchModel,
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="runs",
+ help_text="Champion model used for this run",
+ )
+ run_type = models.CharField(max_length=20, choices=RunType.choices)
+ status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)
+
+ rows_scored = models.IntegerField(null=True, blank=True, validators=[MinValueValidator(0)])
+ metrics = models.JSONField(default=dict)
+ error = models.TextField(blank=True, default="")
+
+ started_at = models.DateTimeField(null=True, blank=True)
+ completed_at = models.DateTimeField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ ordering = ["-created_at"]
+ default_manager_name = "all_teams"
+ constraints = [
+ min_value_constraint("rows_scored", 0, "autoresearch_run_rows_scored_nonnegative", nullable=True),
+ ]
diff --git a/products/autoresearch/backend/tests/test_access.py b/products/autoresearch/backend/tests/test_access.py
new file mode 100644
index 000000000000..3cf4edebbad4
--- /dev/null
+++ b/products/autoresearch/backend/tests/test_access.py
@@ -0,0 +1,33 @@
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from products.autoresearch.backend.access import has_autoresearch_access
+
+
+class TestAutoresearchAccess(BaseTest):
+ @patch("products.autoresearch.backend.access.posthoganalytics.feature_enabled", return_value=True)
+ def test_sends_both_organization_and_project_groups(self, feature_enabled: object) -> None:
+ assert has_autoresearch_access(self.user, team_id=self.team.pk) is True
+
+ _, kwargs = feature_enabled.call_args # type: ignore[attr-defined]
+ assert kwargs["groups"] == {
+ "project": str(self.team.pk),
+ "organization": str(self.team.organization_id),
+ }
+ assert kwargs["group_properties"] == {
+ "project": {"id": str(self.team.pk)},
+ "organization": {"id": str(self.team.organization_id)},
+ }
+
+ @patch("products.autoresearch.backend.access.posthoganalytics.feature_enabled", return_value=True)
+ def test_uses_the_supplied_organization_without_a_team_lookup(self, feature_enabled: object) -> None:
+ with self.assertNumQueries(0):
+ assert has_autoresearch_access(self.user, team_id=self.team.pk, organization_id="abc") is True
+
+ _, kwargs = feature_enabled.call_args # type: ignore[attr-defined]
+ assert kwargs["groups"]["organization"] == "abc"
+
+ @patch("posthog.permissions._FORCE_ENABLED_FLAGS", frozenset({"autoresearch"}))
+ @patch("products.autoresearch.backend.access.posthoganalytics.feature_enabled", return_value=False)
+ def test_honors_the_force_enabled_override(self, feature_enabled: object) -> None:
+ assert has_autoresearch_access(self.user, team_id=self.team.pk) is True
diff --git a/products/autoresearch/backend/tests/test_models.py b/products/autoresearch/backend/tests/test_models.py
new file mode 100644
index 000000000000..7458ad1fdbb0
--- /dev/null
+++ b/products/autoresearch/backend/tests/test_models.py
@@ -0,0 +1,176 @@
+from datetime import date
+from typing import Any
+
+from posthog.test.base import BaseTest
+
+from django.contrib import admin as django_admin
+from django.db import IntegrityError, transaction
+from django.test import RequestFactory
+
+from parameterized import parameterized
+
+from posthog.models.organization import Organization
+from posthog.models.team import Team
+
+from products.autoresearch.backend import admin as admin_module
+from products.autoresearch.backend.models import (
+ AutoresearchIteration,
+ AutoresearchModel,
+ AutoresearchPipeline,
+ AutoresearchRun,
+ AutoresearchSuggestion,
+ AutoresearchTrainingRun,
+)
+
+
+class TestAutoresearchModels(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.pipeline = AutoresearchPipeline.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, name="p1", target_event="$pageview"
+ )
+
+ def _other_team_pipeline(self) -> AutoresearchPipeline:
+ other_org = Organization.objects.create(name="other")
+ other_team = Team.objects.create(organization=other_org, name="other")
+ return AutoresearchPipeline.objects.for_team(other_team.pk).create(
+ team_id=other_team.pk, name="p2", target_event="$pageview"
+ )
+
+ def test_save_overwrites_a_mismatched_team_with_the_pipelines(self) -> None:
+ other = self._other_team_pipeline()
+ run = AutoresearchTrainingRun(pipeline=other, team_id=self.team.pk)
+ run.save()
+ assert run.team_id == other.team_id
+
+ def test_partial_save_of_the_pipeline_persists_the_derived_team(self) -> None:
+ other = self._other_team_pipeline()
+ run = AutoresearchTrainingRun.objects.for_team(self.team.pk).create(pipeline=self.pipeline)
+ run.pipeline = other
+ run.save(update_fields=["pipeline"])
+ run.refresh_from_db()
+ assert run.team_id == other.team_id
+
+ def _create(self, model_cls: type[Any], **fields: Any) -> Any:
+ if model_cls is AutoresearchPipeline:
+ return AutoresearchPipeline.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, name="p4", target_event="$pageview", **fields
+ )
+ if model_cls is AutoresearchModel:
+ fields = {"recipe_hash": "a", "model_recipe": {}, **fields}
+ elif model_cls is AutoresearchRun:
+ fields = {"run_type": AutoresearchRun.RunType.INFERENCE, **fields}
+ elif model_cls is AutoresearchIteration:
+ fields = {
+ "training_run": AutoresearchTrainingRun.objects.for_team(self.team.pk).create(pipeline=self.pipeline),
+ "iteration_number": 1,
+ "recipe_hash": "a",
+ "recipe_snapshot": {},
+ "status": AutoresearchIteration.Status.KEPT,
+ **fields,
+ }
+ return model_cls.objects.for_team(self.team.pk).create(pipeline=self.pipeline, **fields)
+
+ def test_save_rejects_a_relation_from_another_pipeline(self) -> None:
+ other = self._other_team_pipeline()
+ foreign_run = AutoresearchTrainingRun.objects.for_team(other.team_id).create(pipeline=other)
+ with self.assertRaisesRegex(ValueError, "training_run"):
+ AutoresearchIteration(
+ pipeline=self.pipeline,
+ training_run=foreign_run,
+ iteration_number=1,
+ recipe_snapshot={},
+ status=AutoresearchIteration.Status.KEPT,
+ ).save()
+
+ def test_only_one_champion_per_pipeline(self) -> None:
+ AutoresearchModel.objects.for_team(self.team.pk).create(
+ pipeline=self.pipeline, role=AutoresearchModel.Role.CHAMPION, recipe_hash="a", model_recipe={}
+ )
+ with self.assertRaises(IntegrityError), transaction.atomic():
+ AutoresearchModel.objects.for_team(self.team.pk).create(
+ pipeline=self.pipeline, role=AutoresearchModel.Role.CHAMPION, recipe_hash="b", model_recipe={}
+ )
+
+ def test_iteration_budget_remaining_fills_from_the_budget_only_at_creation(self) -> None:
+ pipeline = AutoresearchPipeline.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, name="p3", target_event="$pageview", iteration_budget=10
+ )
+ assert pipeline.iteration_budget_remaining == 10
+
+ pipeline.iteration_budget_remaining = None
+ pipeline.save()
+ pipeline.refresh_from_db()
+ assert pipeline.iteration_budget_remaining is None
+
+ @parameterized.expand(
+ [
+ (AutoresearchModel, {"holdout_score": 2.0}),
+ (AutoresearchModel, {"realized_score": -1.0}),
+ (AutoresearchModel, {"trained_on_start": date(2026, 2, 1), "trained_on_end": date(2026, 1, 1)}),
+ (AutoresearchTrainingRun, {"best_holdout_score": 1.5}),
+ (AutoresearchTrainingRun, {"iteration_budget": 0}),
+ (AutoresearchTrainingRun, {"iteration_count": -1}),
+ (AutoresearchIteration, {"holdout_score": 2.0}),
+ (AutoresearchIteration, {"agent_confidence": -0.5}),
+ (AutoresearchRun, {"rows_scored": -1}),
+ (AutoresearchPipeline, {"iteration_budget_remaining": -1}),
+ ]
+ )
+ def test_out_of_range_values_are_rejected(self, model_cls: type[Any], fields: dict[str, Any]) -> None:
+ with self.assertRaises(IntegrityError), transaction.atomic():
+ self._create(model_cls, **fields)
+
+ def test_admin_form_rejects_a_relation_from_another_pipeline(self) -> None:
+ other = self._other_team_pipeline()
+ foreign_model = AutoresearchModel.objects.for_team(other.team_id).create(
+ pipeline=other, recipe_hash="a", model_recipe={}
+ )
+ request = RequestFactory().get("/admin/")
+ request.user = self.user
+ model_admin = admin_module.AutoresearchRunAdmin(AutoresearchRun, django_admin.site)
+ form = model_admin.get_form(request)(
+ data={
+ "pipeline": str(self.pipeline.pk),
+ "model": str(foreign_model.pk),
+ "run_type": AutoresearchRun.RunType.INFERENCE,
+ "status": AutoresearchRun.Status.PENDING,
+ "metrics": "{}",
+ }
+ )
+ assert not form.is_valid()
+ assert "model" in form.errors
+
+ def test_admin_works_without_team_context(self) -> None:
+ AutoresearchRun.objects.for_team(self.team.pk).create(
+ pipeline=self.pipeline, run_type=AutoresearchRun.RunType.INFERENCE
+ )
+ request = RequestFactory().get("/admin/")
+ request.user = self.user
+ admins = (
+ (AutoresearchPipeline, admin_module.AutoresearchPipelineAdmin),
+ (AutoresearchTrainingRun, admin_module.AutoresearchTrainingRunAdmin),
+ (AutoresearchModel, admin_module.AutoresearchModelAdmin),
+ (AutoresearchRun, admin_module.AutoresearchRunAdmin),
+ )
+ for model, admin_class in admins:
+ model_admin = admin_class(model, django_admin.site)
+ list(model_admin.get_queryset(request))
+ model_admin.get_form(request)()
+
+ def test_admin_locks_child_rows_to_their_pipeline(self) -> None:
+ request = RequestFactory().get("/admin/")
+ request.user = self.user
+ run = AutoresearchTrainingRun.objects.for_team(self.team.pk).create(pipeline=self.pipeline)
+ admins = (
+ (AutoresearchTrainingRun, admin_module.AutoresearchTrainingRunAdmin),
+ (AutoresearchModel, admin_module.AutoresearchModelAdmin),
+ (AutoresearchSuggestion, admin_module.AutoresearchSuggestionAdmin),
+ )
+ for model, admin_class in admins:
+ model_admin = admin_class(model, django_admin.site)
+ assert "pipeline" not in model_admin.get_readonly_fields(request)
+ assert "pipeline" in model_admin.get_readonly_fields(request, run)
+
+ model_admin = admin_module.AutoresearchModelAdmin(AutoresearchModel, django_admin.site)
+ assert model_admin.has_add_permission(request) is False
diff --git a/products/feature_flags/backend/facade/api.py b/products/feature_flags/backend/facade/api.py
index 28f3ebbb688a..3d15d7e74f36 100644
--- a/products/feature_flags/backend/facade/api.py
+++ b/products/feature_flags/backend/facade/api.py
@@ -292,3 +292,16 @@ def serialize_flags(flags: Any, *, context: dict) -> Any:
access-control-derived fields, so it can only be built for a real request.
"""
return FeatureFlagSerializer(flags, many=True, context=context).data
+
+
+def flag_is_active(key: str, *, team_id: int | None = None) -> bool:
+ """Whether an active flag with this key exists, optionally narrowed to one team.
+
+ A direct row read, not an evaluation: it ignores rollout percentages and release
+ conditions. Callers use it as a local-development fallback for when the analytics SDK
+ is disabled and ``posthoganalytics.feature_enabled`` cannot answer.
+ """
+ qs = FeatureFlag.objects.filter(key=key, active=True)
+ if team_id is not None:
+ qs = qs.filter(team_id=team_id)
+ return qs.exists()
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index c2feca2c8aaa..b033cefc1185 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -25,6 +25,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'annotation:write',
'approvals:read',
'approvals:write',
+ 'autoresearch:read',
+ 'autoresearch:write',
'batch_export:read',
'batch_export:write',
'batch_import:read',
diff --git a/tach.toml b/tach.toml
index 1d316b37ea6d..a76de4954cd1 100644
--- a/tach.toml
+++ b/tach.toml
@@ -189,7 +189,10 @@ layer = "modules"
[[modules]]
path = "products.autoresearch"
-depends_on = []
+depends_on = [
+ "posthog",
+ "products.feature_flags",
+]
layer = "modules"
[[modules]]