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): have the training agent build a report notebook (#110415)

posthog[bot]ea7facfff1a4
diff --git a/products/autoresearch/backend/access.py b/products/autoresearch/backend/access.py
index bddd66024ca1..0bc5ba1fff1b 100644
--- a/products/autoresearch/backend/access.py
+++ b/products/autoresearch/backend/access.py
@@ -1,7 +1,8 @@
-"""Feature-flag gate for the autoresearch product.
+"""Feature-flag gates 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.
+Access is controlled by the `autoresearch` feature flag. The `autoresearch-report-notebook`
+flag gates the report notebook that a training run builds. Rollout is configured on each
+flag in PostHog, so code only asks whether it's enabled for this user/team.
"""
from django.conf import settings
@@ -15,6 +16,7 @@ from posthog.permissions import posthog_feature_flag_value
from products.feature_flags.backend.facade import api as feature_flags_facade
AUTORESEARCH_FLAG = "autoresearch"
+REPORT_NOTEBOOK_FLAG = "autoresearch-report-notebook"
def has_autoresearch_access(
@@ -22,6 +24,25 @@ def has_autoresearch_access(
*,
team_id: int | None = None,
organization_id: str | None = None,
+) -> bool:
+ return _flag_enabled(AUTORESEARCH_FLAG, user, team_id=team_id, organization_id=organization_id)
+
+
+def has_report_notebook_access(
+ user: AbstractBaseUser | AnonymousUser | None,
+ *,
+ team_id: int | None = None,
+ organization_id: str | None = None,
+) -> bool:
+ return _flag_enabled(REPORT_NOTEBOOK_FLAG, user, team_id=team_id, organization_id=organization_id)
+
+
+def _flag_enabled(
+ flag: str,
+ user: AbstractBaseUser | AnonymousUser | None,
+ *,
+ team_id: int | None,
+ organization_id: str | None,
) -> bool:
if not user or not user.is_authenticated:
return False
@@ -34,7 +55,7 @@ def has_autoresearch_access(
# 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)
+ return _local_flag_enabled(flag, team_id=team_id)
if team_id is not None and organization_id is None:
organization_id = _organization_id_for_team(team_id)
@@ -46,7 +67,7 @@ def has_autoresearch_access(
if organization_id is not None:
return bool(
posthog_feature_flag_value(
- AUTORESEARCH_FLAG,
+ flag,
distinct_id,
organization_id=organization_id,
team_id=team_id,
@@ -62,7 +83,7 @@ def has_autoresearch_access(
return bool(
posthoganalytics.feature_enabled(
- AUTORESEARCH_FLAG,
+ flag,
distinct_id,
groups=groups,
group_properties=group_properties,
@@ -77,5 +98,5 @@ def _organization_id_for_team(team_id: int) -> str | None:
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)
+def _local_flag_enabled(flag: str, *, team_id: int | None) -> bool:
+ return feature_flags_facade.flag_is_active(flag, team_id=team_id)
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.py
index 9305770ec29a..5a656ee37baf 100644
--- a/products/autoresearch/backend/facade/api.py
+++ b/products/autoresearch/backend/facade/api.py
@@ -1059,6 +1059,7 @@ def complete_run(
model_explanation: dict[str, Any] | None = None,
recommended_next: str = "",
distillation: str = "",
+ report_notebook_short_id: str = "",
) -> TrainingRun:
"""Finalize a run. Promotion is server-side, so an agent cannot set the champion."""
# Promotion imports the inference sandbox, and with it pandas and pyarrow; the router imports
@@ -1078,6 +1079,7 @@ def complete_run(
model_explanation=model_explanation or {},
recommended_next=recommended_next or "",
distillation=distillation or "",
+ report_notebook_short_id=report_notebook_short_id or "",
)
except PromotionError as exc:
raise AutoresearchConflict(str(exc)) from exc
diff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.py
index 85e3b5b7277b..e2bd5e7b4c34 100644
--- a/products/autoresearch/backend/facade/contracts.py
+++ b/products/autoresearch/backend/facade/contracts.py
@@ -163,6 +163,7 @@ class TrainingRunSummary:
dead_ends: list[TrainingRunSummaryLadderItem]
recommended_next: str
distillation: str
+ report_notebook_short_id: str
@dataclass(frozen=True)
diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.py
index 712deb36ba27..9f406fa81749 100644
--- a/products/autoresearch/backend/presentation/views/serializers.py
+++ b/products/autoresearch/backend/presentation/views/serializers.py
@@ -893,6 +893,12 @@ class TrainingRunSummarySerializer(serializers.Serializer):
distillation = serializers.CharField(
allow_blank=True, help_text="Agent's 1–2 sentence distillation of what this run learned. Empty if not provided."
)
+ report_notebook_short_id = serializers.CharField(
+ required=False,
+ default="",
+ allow_blank=True,
+ help_text="Short id of the report notebook the agent built for this run. Empty if there is none.",
+ )
@extend_schema_serializer(component_name="IterationTrail")
@@ -1424,6 +1430,15 @@ class CompleteTrainingRunSerializer(serializers.Serializer):
"dead-ends. Stored in the run summary as the cheapest thing the next run reads. Max 2000 characters."
),
)
+ report_notebook_short_id = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ default="",
+ help_text=(
+ "Short id of the report notebook you built for this run. Stored in the run summary only if the "
+ "notebook exists in this project; an unknown id is dropped and does not fail the completion."
+ ),
+ )
# ── Feature materialization serializers ─────────────────────────────────────
diff --git a/products/autoresearch/backend/presentation/views/views.py b/products/autoresearch/backend/presentation/views/views.py
index 5149ef8bf31a..d70ba38d9a58 100644
--- a/products/autoresearch/backend/presentation/views/views.py
+++ b/products/autoresearch/backend/presentation/views/views.py
@@ -942,6 +942,7 @@ class AutoresearchTrainingRunViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMi
model_explanation=data.get("model_explanation") or {},
recommended_next=data.get("recommended_next") or "",
distillation=data.get("distillation") or "",
+ report_notebook_short_id=data.get("report_notebook_short_id") or "",
)
except TrainingRunNotFound:
raise NotFound("Training run not found.")
diff --git a/products/autoresearch/backend/training/AGENTS.md b/products/autoresearch/backend/training/AGENTS.md
index 703e0d3790de..5cc60d1bcac7 100644
--- a/products/autoresearch/backend/training/AGENTS.md
+++ b/products/autoresearch/backend/training/AGENTS.md
@@ -13,6 +13,7 @@ The other half is `../inference/`, which consumes what this package produces and
The real path. `run_training()` creates the `AutoresearchTrainingRun` (status `RUNNING`) and fires `Task.create_and_run()` with `internal=True` and no repository, so the run shows up as an internal Task rather than in the normal Tasks list.
The brief carries user-authored text, so the sandbox token holds only `TRAINING_MCP_SCOPES` (the `execute-sql` reads, the autoresearch scopes, and `user:read`, which the PostHog MCP server needs to start a session), and an empty connector allowlist keeps the team's shared MCP connectors out of the sandbox.
`build_agent_description()` assembles the agent's brief — the target, the horizon, the population, and the contract for the bundle it must author.
+ When the `autoresearch-report-notebook` flag is on for the launching user, the token also holds `REPORT_NOTEBOOK_MCP_SCOPES` and the brief adds a Finalize step: the agent builds one report notebook from the `system.autoresearch_*` tables and passes its `short_id` to complete. `report.md` stays required either way.
The agent drives the rest _itself_ through the `autoresearch-*` MCP tools: it records each iteration, uploads the bundle, and calls complete. Nothing polls it.
- `stub.py`
`run_stub_training()` — a hand-authored champion recipe with universal engagement features (event counts, distinct event types, days since first seen) that apply to any team and any target.
@@ -27,6 +28,7 @@ The other half is `../inference/`, which consumes what this package produces and
`_detect_uploaded_bundle()` decides whether the new model gets an `artifact_prefix` (bundle path) or only a recorded recipe (legacy path).
The bundle is written once per run, so a losing iteration can overwrite it: the uploaded `features.sql` must match the `feature_sql` recorded by the selected iteration, whitespace aside, or promotion raises rather than publishing a champion whose recipe and score describe other code.
`complete_training_run()` reads the bundle and enters the run's `team_scope()` before it opens the transaction, because the `TaskRun` safety net calls it from a worker thread with no request scope, and object-storage calls must not run under the row lock.
+ The agent's `report_notebook_short_id` goes into the run summary only if that notebook exists in the run's team. A bad id or a failed check stores an empty value and never fails completion.
Only a promoted model is fitted. A challenger's `model.pkl` would never be read, because inference serves the champion and no path promotes a challenger row later.
- `artifacts.py`
Object storage for the bundle: `features.sql`, `train.py`, `predict.py`, plus the fitted `model.pkl` written at completion.
diff --git a/products/autoresearch/backend/training/promotion.py b/products/autoresearch/backend/training/promotion.py
index cf43c70feed5..e83a065b2f90 100644
--- a/products/autoresearch/backend/training/promotion.py
+++ b/products/autoresearch/backend/training/promotion.py
@@ -39,6 +39,7 @@ from products.autoresearch.backend.models import (
)
from products.autoresearch.backend.training import artifacts
from products.autoresearch.backend.training.recipe_validation import RecipeValidationError, validate_model_class
+from products.notebooks.backend.facade import api as notebooks_facade
logger = structlog.get_logger(__name__)
@@ -166,6 +167,7 @@ def _build_run_summary(
champion_model_class: str,
recommended_next: str,
distillation: str,
+ report_notebook_short_id: str,
) -> dict[str, Any]:
"""Tier-1 cross-run memory: backend derives the structural facts; the agent supplies the two
judgment fields (recommended_next, distillation). Read back by a new run before it iterates."""
@@ -186,6 +188,7 @@ def _build_run_summary(
"dead_ends": [_summary_item(it) for it in dead_ends],
"recommended_next": recommended_next or "",
"distillation": distillation or "",
+ "report_notebook_short_id": report_notebook_short_id,
}
@@ -305,6 +308,7 @@ def complete_training_run(
model_explanation: dict[str, Any] | None = None,
recommended_next: str = "",
distillation: str = "",
+ report_notebook_short_id: str = "",
) -> dict[str, Any]:
"""Finalize a run: pick the best iteration, decide champion vs challenger, persist the model."""
# The TaskRun safety net calls this from a worker thread, where no request has set a
@@ -323,9 +327,28 @@ def complete_training_run(
model_explanation=model_explanation,
recommended_next=recommended_next,
distillation=distillation,
+ report_notebook_short_id=_verified_report_notebook(current, report_notebook_short_id),
)
+def _verified_report_notebook(training_run: AutoresearchTrainingRun, short_id: str) -> str:
+ """
+ The agent's notebook short id if that notebook exists in the run's team, else "".
+ The model result matters more than the report, so a bad id or a failed check never fails completion.
+ """
+ short_id = (short_id or "").strip()
+ if not short_id:
+ return ""
+ try:
+ if notebooks_facade.notebook_exists(training_run.team_id, short_id, include_deleted=False):
+ return short_id
+ except Exception:
+ logger.exception("autoresearch_report_notebook_check_failed", training_run_id=str(training_run.pk))
+ return ""
+ logger.warning("autoresearch_report_notebook_not_found", training_run_id=str(training_run.pk))
+ return ""
+
+
def _activate_pipeline(pipeline: AutoresearchPipeline) -> None:
"""A pipeline with its first champion goes live: flip Draft/Bootstrapping -> Running so the
daily coordinator starts scoring it. Mirrors the stub path (stub_training); pause/resume
@@ -371,6 +394,7 @@ def _finalize_under_lock(
model_explanation: dict[str, Any] | None,
recommended_next: str,
distillation: str,
+ report_notebook_short_id: str,
) -> dict[str, Any]:
# Re-fetch under lock and re-check status inside the transaction. Both callers (the
# complete API action and the TaskRun post_save safety net) guard on status outside
@@ -468,6 +492,7 @@ def _finalize_under_lock(
champion_model_class=_serving_model_class(promoted=promoted, model=model, incumbent=current),
recommended_next=recommended_next,
distillation=distillation,
+ report_notebook_short_id=report_notebook_short_id,
)
training_run.save(update_fields=["status", "iteration_count", "best_holdout_score", "summary", "completed_at"])
diff --git a/products/autoresearch/backend/training/runner.py b/products/autoresearch/backend/training/runner.py
index ba4293bcf27f..02f64872bdea 100644
--- a/products/autoresearch/backend/training/runner.py
+++ b/products/autoresearch/backend/training/runner.py
@@ -33,8 +33,10 @@ import structlog
from posthog.hogql.property import action_to_expr
from posthog.dataclasses import frozen
+from posthog.models.user import User
from products.actions.backend.models.action import Action
+from products.autoresearch.backend.access import has_report_notebook_access
from products.autoresearch.backend.dataset.labeling import TrainingSample, build_target_condition
from products.autoresearch.backend.inference.sandbox import _resolve_acting_user, measure_training_sample
from products.autoresearch.backend.models import AutoresearchPipeline, AutoresearchSuggestion, AutoresearchTrainingRun
@@ -73,6 +75,11 @@ MAX_PENDING_SUGGESTIONS = 10
# The brief carries user-authored text, so the token grants nothing beyond that.
TRAINING_MCP_SCOPES = ["query:read", "insight:read", "user:read", "autoresearch:read", "autoresearch:write"]
+# Added only when the report notebook flag is on for the user who starts the run.
+# notebook:write also exposes notebooks-partial-update and notebooks-destroy, so the brief
+# limits the agent to the notebook it creates in this run.
+REPORT_NOTEBOOK_MCP_SCOPES = ["notebook:read", "notebook:write"]
+
# Task.title is a 255-character column, and a pipeline name and target event can each
# take all of it.
_TASK_TITLE_MAX_CHARS = 255
@@ -141,12 +148,62 @@ def _describe_training_sample(sample: TrainingSample | None) -> str:
return clause
+def _report_notebook_step(pipeline: AutoresearchPipeline, *, training_run_id: str, today_iso: str) -> str:
+ """The Finalize step that builds the report notebook, indented to sit inside the brief."""
+ step = textwrap.dedent(f"""
+ 3. **Build the report notebook** — a live copy of the report whose numbers come from SQL
+ cells, so a reader can check them and re-run them after scoring. `report.md` stays the
+ fallback: write it first, whatever happens in this step.
+
+ Do this step only if `notebooks-create-markdown` and `notebooks-add-cell` are in your
+ tool list. If they are not, skip to the next step.
+
+ Create exactly ONE notebook with `notebooks-create-markdown`. Title it
+ `<pipeline name> · model report · {today_iso}`, where the pipeline name is
+ {_wrap_untrusted(pipeline.name)}. Change and run only this notebook. Never update,
+ delete, or run any other notebook.
+
+ Build it in this order, with markdown prose between the cells:
+ - **TL;DR** and **What it predicts** — the same content as `report.md`.
+ - **How training went** — a SQL cell over `system.autoresearch_iterations` where
+ `training_run_id = '{training_run_id}'`, then a Python cell that plots holdout AUC by
+ iteration and marks kept and discarded iterations.
+ - **How well it works** — a SQL cell over `system.autoresearch_models` where
+ `pipeline_id = '{pipeline.pk}'`: role, holdout AUC, realized AUC, calibration error,
+ and lift@10/@20 from `metrics` when present. Explain them in plain words.
+ - **What drives it** — a Python cell that charts the feature importances and direction
+ in `model_explanation` of this run's model row
+ (`source_training_run_id = '{training_run_id}'`), then prose on the intuition behind
+ each top feature.
+ - **Live performance** — a SQL cell over `events` where
+ `event = 'autoresearch_prediction'` and
+ `properties.$autoresearch_pipeline_id = '{pipeline.pk}'`, then Python cells for the
+ score histogram and the realized vs predicted rate by decile. A new model has no
+ predictions yet, so these cells must handle an empty result: print a clear message
+ such as "No predictions yet. Re-run after the first scoring run." and do not fail.
+ - **How it was built** and **Caveats and recommended use** — prose.
+
+ Rules for every cell:
+ - Every number comes from a SQL cell. Do not type metrics into Python or prose tables.
+ - Python cells work only on the dataframes of earlier cells. No network access: no
+ `requests`, `urllib`, `http`, `socket`, or `subprocess`. No file reads or writes,
+ and no package installs.
+ - One figure per Python cell. The kernel keeps at most 8 figures and about 3 MB of
+ images per cell.
+ - Do not call `notebooks-configure-compute`. Use the default kernel.
+ - Run each cell. If a cell fails, fix it or delete it. Never leave a failed cell.
+
+ Keep the notebook's `short_id` for the next step.""")
+ return textwrap.indent(step, " " * 8)
+
+
def build_agent_description(
pipeline: AutoresearchPipeline,
iteration_budget: int,
training_run_id: str,
pending_suggestions: list[AutoresearchSuggestion] | None = None,
training_sample: TrainingSample | None = None,
+ report_notebook: bool = False,
) -> str:
"""Build the Claude Code agent prompt for the autoresearch training loop."""
pop_clause = ""
@@ -174,6 +231,16 @@ def build_agent_description(
today_iso = date.today().isoformat()
min_iters = min(3, iteration_budget)
target = _describe_target(pipeline)
+ complete_step = 3
+ notebook_step = ""
+ notebook_field = ""
+ if report_notebook:
+ complete_step = 4
+ notebook_step = _report_notebook_step(pipeline, training_run_id=training_run_id, today_iso=today_iso)
+ notebook_field = (
+ "\n - `report_notebook_short_id`: the `short_id` of the notebook from step 3. Omit it\n"
+ " if you skipped step 3 or the notebook does not exist."
+ )
prompt = textwrap.dedent(f"""
# PostHog Autoresearch Agent
@@ -530,14 +597,14 @@ def build_agent_description(
Add a calibration line (predicted vs realized rate) if it aids the story. Where a chart
would be overkill (or mermaid can't express it), fall back to compact ASCII/unicode bar
charts inline — they render in any Markdown surface. Use plain GFM tables for the metrics
- block. If a user suggestion asks for a particular audience or emphasis, honor it.
- 3. Call `autoresearch-training-runs-complete-create` with `pipeline_id = "{pipeline.pk}"`
+ block. If a user suggestion asks for a particular audience or emphasis, honor it.{notebook_step}
+ {complete_step}. Call `autoresearch-training-runs-complete-create` with `pipeline_id = "{pipeline.pk}"`
and `id = "{training_run_id}"`. The backend picks the best iteration, decides
champion vs challenger, and attaches your uploaded bundle as the model's artifact.
Also pass two short fields that become this run's learning memory for the NEXT run:
- `distillation`: 1–2 sentences on what this run learned — the winning signal, the
key transform, the dead-ends. This is the cheapest thing the next run reads.
- - `recommended_next`: concretely what a future run should try next given what you found.
+ - `recommended_next`: concretely what a future run should try next given what you found.{notebook_field}
The backend derives the rest of the summary (the kept ladder and dead-ends) from your
recorded iterations, so keep these two fields to judgment only — do not restate the ladder.
@@ -604,6 +671,16 @@ def _training_sample_for_brief(pipeline: AutoresearchPipeline) -> TrainingSample
return None
+def _report_notebook_enabled(pipeline: AutoresearchPipeline, *, user_id: int) -> bool:
+ """A flag check that fails leaves the notebook out rather than failing the launch."""
+ try:
+ user = User.objects.filter(pk=user_id).first()
+ return has_report_notebook_access(user, team_id=pipeline.team_id)
+ except Exception:
+ logger.warning("autoresearch_report_notebook_flag_check_failed", pipeline_id=str(pipeline.pk), exc_info=True)
+ return False
+
+
def run_training(
pipeline: AutoresearchPipeline,
iteration_budget: int,
@@ -625,6 +702,9 @@ def run_training(
# Completion fits the champion as the pipeline's creator, so a creator who has left
# would consume the paid run and leave a champion that no scoring run can load.
_resolve_acting_user(team=pipeline.team, pipeline=pipeline, user=None)
+ # The MCP token belongs to user_id, so the flag is evaluated for the same user.
+ report_notebook = _report_notebook_enabled(pipeline, user_id=user_id)
+ mcp_scopes = TRAINING_MCP_SCOPES + REPORT_NOTEBOOK_MCP_SCOPES if report_notebook else TRAINING_MCP_SCOPES
# Every materialization labels through this condition, so a target it refuses (a deleted
# action, or one with no steps) would fail the whole paid run.
build_target_condition(
@@ -662,6 +742,7 @@ def run_training(
training_run_id=str(training_run.id),
pending_suggestions=pending_suggestions or None,
training_sample=_training_sample_for_brief(pipeline),
+ report_notebook=report_notebook,
)
title = f"[autoresearch] {pipeline.name}: learn to predict '{pipeline.target_event}'"
@@ -675,7 +756,7 @@ def run_training(
create_pr=False,
mode="background",
internal=True,
- posthog_mcp_scopes=TRAINING_MCP_SCOPES,
+ posthog_mcp_scopes=mcp_scopes,
# The autoresearch image is the agent-capable base plus pandas/numpy/
# scikit-learn/pyarrow at system site. The base image lacks the ML libs; the
# notebook image has the libs but cannot host the agent server — only this
diff --git a/products/autoresearch/backend/training/test_promotion.py b/products/autoresearch/backend/training/test_promotion.py
index a0542590d9ca..aee4e2399ec0 100644
--- a/products/autoresearch/backend/training/test_promotion.py
+++ b/products/autoresearch/backend/training/test_promotion.py
@@ -11,6 +11,7 @@ from django.utils import timezone as django_timezone
from parameterized import parameterized
from posthog.models.scoping import unscoped
+from posthog.models.team import Team
from posthog.storage.object_storage import ObjectStorageError
from products.autoresearch.backend.models import (
@@ -23,6 +24,7 @@ from products.autoresearch.backend.testing import TeamScopedTestMixin
from products.autoresearch.backend.training.artifacts import ArtifactBundle, InvalidArtifactContent, PartialBundle
from products.autoresearch.backend.training.promotion import PromotionError, complete_training_run
from products.autoresearch.backend.training.stub import run_stub_training
+from products.notebooks.backend.facade import api as notebooks_facade
ANCHORED_FEATURE_SQL = "SELECT a.person_id AS distinct_id, count() AS c FROM {anchors} a GROUP BY a.person_id"
_DEFAULT_PARAMS = object()
@@ -328,6 +330,23 @@ class TestCompleteTrainingRun(TeamScopedTestMixin, BaseTest):
assert not AutoresearchModel.objects.filter(pipeline=self.pipeline).exists()
+ @parameterized.expand([("own_team", "own", True), ("other_team", "other", False), ("missing", "none", False)])
+ def test_report_notebook_is_linked_only_when_it_exists_in_the_run_team(self, _name, owner, linked):
+ if owner == "none":
+ short_id = "doesnotexist"
+ else:
+ team_id = self.team.pk if owner == "own" else Team.objects.create(organization=self.organization).pk
+ short_id = notebooks_facade.create_notebook(team_id, title="Report", content=None).short_id
+ run = self._run()
+ self._iteration(run, number=0, holdout=0.8)
+
+ result = complete_training_run(run, report_notebook_short_id=short_id)
+
+ assert result["promoted"] is True
+ run.refresh_from_db()
+ assert run.status == AutoresearchTrainingRun.Status.COMPLETED
+ assert run.summary["report_notebook_short_id"] == (short_id if linked else "")
+
def test_completion_runs_without_an_ambient_team_scope(self):
# The TaskRun safety net finalizes a run from a worker thread, where no request has
# set a scope. Every read in promotion goes through a fail-closed manager.
diff --git a/products/autoresearch/backend/training/test_training.py b/products/autoresearch/backend/training/test_training.py
index 3434935ddc89..775b0ac6cb31 100644
--- a/products/autoresearch/backend/training/test_training.py
+++ b/products/autoresearch/backend/training/test_training.py
@@ -15,6 +15,7 @@ from products.autoresearch.backend.inference.sandbox import SandboxInferenceErro
from products.autoresearch.backend.models import AutoresearchPipeline, AutoresearchSuggestion, AutoresearchTrainingRun
from products.autoresearch.backend.testing import TeamScopedTestMixin
from products.autoresearch.backend.training.runner import (
+ REPORT_NOTEBOOK_MCP_SCOPES,
TRAINING_MCP_SCOPES,
UNTRUSTED_DATA_TAG,
build_agent_description,
@@ -35,9 +36,12 @@ class TestBuildAgentDescription(TeamScopedTestMixin, BaseTest):
iteration_budget_remaining=10,
)
- def test_prompt_renders_without_unresolved_placeholders(self) -> None:
+ @parameterized.expand([("without_notebook", False), ("with_notebook", True)])
+ def test_prompt_renders_without_unresolved_placeholders(self, _name: str, report_notebook: bool) -> None:
pipeline = self._make_pipeline()
- prompt = build_agent_description(pipeline=pipeline, iteration_budget=5, training_run_id="run-123")
+ prompt = build_agent_description(
+ pipeline=pipeline, iteration_budget=5, training_run_id="run-123", report_notebook=report_notebook
+ )
# `{anchors}` and `{lookback_days}` are intentional — they are documented
# placeholders the agent is taught to use inside its own SQL, and `{init}`
# is the literal mermaid `%%{init}%%` directive the report section forbids.
@@ -96,13 +100,19 @@ class TestBuildAgentDescription(TeamScopedTestMixin, BaseTest):
assert "set_output/" not in prompt
assert "recipe.json" not in prompt
- def test_prompt_instructs_report_md(self) -> None:
+ @parameterized.expand([("without_notebook", False), ("with_notebook", True)])
+ def test_prompt_instructs_report_md(self, _name: str, report_notebook: bool) -> None:
pipeline = self._make_pipeline()
- prompt = build_agent_description(pipeline=pipeline, iteration_budget=5, training_run_id="run-123")
+ prompt = build_agent_description(
+ pipeline=pipeline, iteration_budget=5, training_run_id="run-123", report_notebook=report_notebook
+ )
# The agent must author a portable report.md, uploaded like the bundle files, with charts.
assert "report.md" in prompt
assert "mermaid" in prompt
assert "autoresearch-training-runs-artifacts-upload-create" in prompt
+ assert ("notebooks-create-markdown" in prompt) is report_notebook
+ assert ("report_notebook_short_id" in prompt) is report_notebook
+ assert prompt.index("report.md") < prompt.index("autoresearch-training-runs-complete-create")
def test_prompt_excludes_autoresearch_feedback_events(self) -> None:
pipeline = self._make_pipeline()
@@ -172,13 +182,26 @@ class TestRunTraining(TeamScopedTestMixin, BaseTest):
facade.create_and_run_task.return_value = MagicMock(task_id=uuid.uuid4(), latest_run=MagicMock(id=uuid.uuid4()))
facade.task_run_is_terminal.return_value = False
- def test_dispatch_grants_only_training_scopes_and_stamps_the_run(self, facade: MagicMock) -> None:
+ @parameterized.expand(
+ [
+ ("flag_off", False, TRAINING_MCP_SCOPES),
+ ("flag_on", True, TRAINING_MCP_SCOPES + REPORT_NOTEBOOK_MCP_SCOPES),
+ ]
+ )
+ def test_dispatch_grants_only_training_scopes_and_stamps_the_run(
+ self, facade: MagicMock, _name: str, flag_on: bool, expected_scopes: list[str]
+ ) -> None:
self._dispatched(facade)
- training_run = run_training(self.pipeline, iteration_budget=5, user_id=self.user.id)
+ with patch(
+ "products.autoresearch.backend.training.runner.has_report_notebook_access", return_value=flag_on
+ ) as flag:
+ training_run = run_training(self.pipeline, iteration_budget=5, user_id=self.user.id)
+ assert flag.call_args.args[0] == self.user
kwargs = facade.create_and_run_task.call_args.kwargs
- assert kwargs["posthog_mcp_scopes"] == TRAINING_MCP_SCOPES
+ assert kwargs["posthog_mcp_scopes"] == expected_scopes
+ assert ("notebooks-create-markdown" in kwargs["description"]) is flag_on
assert "user:read" in kwargs["posthog_mcp_scopes"]
assert kwargs["extra_run_state"] == {
"autoresearch_training_run_id": str(training_run.id),
diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.ts
index 2f4645ea3176..368ca65827e3 100644
--- a/products/autoresearch/frontend/generated/api.schemas.ts
+++ b/products/autoresearch/frontend/generated/api.schemas.ts
@@ -674,6 +674,8 @@ export interface TrainingRunSummaryApi {
recommended_next: string
/** Agent's 1–2 sentence distillation of what this run learned. Empty if not provided. */
distillation: string
+ /** Short id of the report notebook the agent built for this run. Empty if there is none. */
+ report_notebook_short_id?: string
}
/**
@@ -917,6 +919,8 @@ export interface CompleteTrainingRunApi {
* @maxLength 2000
*/
distillation?: string
+ /** Short id of the report notebook you built for this run. Stored in the run summary only if the notebook exists in this project; an unknown id is dropped and does not fail the completion. */
+ report_notebook_short_id?: string
}
export type RecordIterationApiRecipeSnapshotFeatureTransformsItem = { [key: string]: unknown }
diff --git a/products/autoresearch/frontend/generated/api.zod.ts b/products/autoresearch/frontend/generated/api.zod.ts
index 1d4df754342f..751f48e3d8b3 100644
--- a/products/autoresearch/frontend/generated/api.zod.ts
+++ b/products/autoresearch/frontend/generated/api.zod.ts
@@ -248,6 +248,8 @@ export const autoresearchTrainingRunsCompleteCreateBodyRecommendedNextMax = 2000
export const autoresearchTrainingRunsCompleteCreateBodyDistillationDefault = ``
export const autoresearchTrainingRunsCompleteCreateBodyDistillationMax = 2000
+export const autoresearchTrainingRunsCompleteCreateBodyReportNotebookShortIdDefault = ``
+
export const AutoresearchTrainingRunsCompleteCreateBody = /* @__PURE__ */ zod
.object({
best_iteration_id: zod
@@ -274,6 +276,12 @@ export const AutoresearchTrainingRunsCompleteCreateBody = /* @__PURE__ */ zod
.describe(
'A 1–2 sentence distillation of what this run learned — the winning signal, the key transform, the dead-ends. Stored in the run summary as the cheapest thing the next run reads. Max 2000 characters.'
),
+ report_notebook_short_id: zod
+ .string()
+ .default(autoresearchTrainingRunsCompleteCreateBodyReportNotebookShortIdDefault)
+ .describe(
+ 'Short id of the report notebook you built for this run. Stored in the run summary only if the notebook exists in this project; an unknown id is dropped and does not fail the completion.'
+ ),
})
.describe('Input for finalizing a training run. The backend selects\/promotes the champion.')
diff --git a/products/autoresearch/mcp/tools.yaml b/products/autoresearch/mcp/tools.yaml
index 21a898760612..87c83c366bc2 100644
--- a/products/autoresearch/mcp/tools.yaml
+++ b/products/autoresearch/mcp/tools.yaml
@@ -507,7 +507,7 @@ tools:
model card. Also pass distillation (1–2 sentences on what this run learned) and recommended_next (what a
future run should try next) — these are stored in the run summary and read back by the next run during
orientation; the backend derives the rest of the summary (kept ladder, dead-ends) from your recorded
- iterations.
+ iterations. If you built a report notebook for this run, pass its short_id as report_notebook_short_id.
feature_flag: autoresearch
response:
include:
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 1d307b61e5c8..a909666dff33 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1330,7 +1330,7 @@
"feature_flag": "autoresearch"
},
"autoresearch-training-runs-complete-create": {
- "description": "Finalize a training run. The backend selects the kept iteration with the highest holdout_score. best_iteration_id only breaks a tie at that top score and never overrides the ranking, so upload the bundle of the highest-scoring iteration. The backend then decides champion vs challenger via the promotion ladder (cold-start preliminary, anti-thrash margin for an existing champion), and persists the model. Agents cannot set the champion directly — promotion is server-only. Call autoresearch-models-list afterwards to see the resulting champion/challenger. Optionally pass model_explanation (top features and directionality) for the model card. Also pass distillation (1–2 sentences on what this run learned) and recommended_next (what a future run should try next) — these are stored in the run summary and read back by the next run during orientation; the backend derives the rest of the summary (kept ladder, dead-ends) from your recorded iterations.",
+ "description": "Finalize a training run. The backend selects the kept iteration with the highest holdout_score. best_iteration_id only breaks a tie at that top score and never overrides the ranking, so upload the bundle of the highest-scoring iteration. The backend then decides champion vs challenger via the promotion ladder (cold-start preliminary, anti-thrash margin for an existing champion), and persists the model. Agents cannot set the champion directly — promotion is server-only. Call autoresearch-models-list afterwards to see the resulting champion/challenger. Optionally pass model_explanation (top features and directionality) for the model card. Also pass distillation (1–2 sentences on what this run learned) and recommended_next (what a future run should try next) — these are stored in the run summary and read back by the next run during orientation; the backend derives the rest of the summary (kept ladder, dead-ends) from your recorded iterations. If you built a report notebook for this run, pass its short_id as report_notebook_short_id.",
"category": "Autoresearch",
"feature": "autoresearch",
"summary": "Complete a training run",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 84e0e43c6bdf..18989909f8be 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1345,7 +1345,7 @@
"feature_flag": "autoresearch"
},
"autoresearch-training-runs-complete-create": {
- "description": "Finalize a training run. The backend selects the kept iteration with the highest holdout_score. best_iteration_id only breaks a tie at that top score and never overrides the ranking, so upload the bundle of the highest-scoring iteration. The backend then decides champion vs challenger via the promotion ladder (cold-start preliminary, anti-thrash margin for an existing champion), and persists the model. Agents cannot set the champion directly — promotion is server-only. Call autoresearch-models-list afterwards to see the resulting champion/challenger. Optionally pass model_explanation (top features and directionality) for the model card. Also pass distillation (1–2 sentences on what this run learned) and recommended_next (what a future run should try next) — these are stored in the run summary and read back by the next run during orientation; the backend derives the rest of the summary (kept ladder, dead-ends) from your recorded iterations.",
+ "description": "Finalize a training run. The backend selects the kept iteration with the highest holdout_score. best_iteration_id only breaks a tie at that top score and never overrides the ranking, so upload the bundle of the highest-scoring iteration. The backend then decides champion vs challenger via the promotion ladder (cold-start preliminary, anti-thrash margin for an existing champion), and persists the model. Agents cannot set the champion directly — promotion is server-only. Call autoresearch-models-list afterwards to see the resulting champion/challenger. Optionally pass model_explanation (top features and directionality) for the model card. Also pass distillation (1–2 sentences on what this run learned) and recommended_next (what a future run should try next) — these are stored in the run summary and read back by the next run during orientation; the backend derives the rest of the summary (kept ladder, dead-ends) from your recorded iterations. If you built a report notebook for this run, pass its short_id as report_notebook_short_id.",
"category": "Autoresearch",
"feature": "autoresearch",
"summary": "Complete a training run",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5ce7fe119156..c6d9cd79d106 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13686,6 +13686,8 @@ export namespace Schemas {
recommended_next: string;
/** Agent's 1–2 sentence distillation of what this run learned. Empty if not provided. */
distillation: string;
+ /** Short id of the report notebook the agent built for this run. Empty if there is none. */
+ report_notebook_short_id?: string;
}
/**
@@ -23555,6 +23557,8 @@ export namespace Schemas {
* @maxLength 2000
*/
distillation?: string;
+ /** Short id of the report notebook you built for this run. Stored in the run summary only if the notebook exists in this project; an unknown id is dropped and does not fail the completion. */
+ report_notebook_short_id?: string;
}
export interface ComposeTicket {
diff --git a/services/mcp/src/generated/autoresearch/api.ts b/services/mcp/src/generated/autoresearch/api.ts
index 4a88cc4ce81c..9b46d1673d11 100644
--- a/services/mcp/src/generated/autoresearch/api.ts
+++ b/services/mcp/src/generated/autoresearch/api.ts
@@ -425,6 +425,8 @@ export const autoresearchTrainingRunsCompleteCreateBodyRecommendedNextMax = 2000
export const autoresearchTrainingRunsCompleteCreateBodyDistillationDefault = ``
export const autoresearchTrainingRunsCompleteCreateBodyDistillationMax = 2000
+export const autoresearchTrainingRunsCompleteCreateBodyReportNotebookShortIdDefault = ``
+
export const AutoresearchTrainingRunsCompleteCreateBody = () => zod
.object({
best_iteration_id: zod
@@ -451,6 +453,12 @@ export const AutoresearchTrainingRunsCompleteCreateBody = () => zod
.describe(
'A 1–2 sentence distillation of what this run learned — the winning signal, the key transform, the dead-ends. Stored in the run summary as the cheapest thing the next run reads. Max 2000 characters.'
),
+ report_notebook_short_id: zod
+ .string()
+ .default(autoresearchTrainingRunsCompleteCreateBodyReportNotebookShortIdDefault)
+ .describe(
+ 'Short id of the report notebook you built for this run. Stored in the run summary only if the notebook exists in this project; an unknown id is dropped and does not fail the completion.'
+ ),
})
.describe('Input for finalizing a training run. The backend selects\/promotes the champion.')
diff --git a/services/mcp/src/tools/generated/autoresearch.ts b/services/mcp/src/tools/generated/autoresearch.ts
index ec707d4725a6..8b6198728d1c 100644
--- a/services/mcp/src/tools/generated/autoresearch.ts
+++ b/services/mcp/src/tools/generated/autoresearch.ts
@@ -595,6 +595,9 @@ const autoresearchTrainingRunsCompleteCreate = (): ToolBase<
if (params.distillation !== undefined) {
body['distillation'] = params.distillation
}
+ if (params.report_notebook_short_id !== undefined) {
+ body['report_notebook_short_id'] = params.report_notebook_short_id
+ }
const result = await context.api.request<Schemas.AutoresearchTrainingRun>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/training_runs/${encodeURIComponent(String(params.id))}/complete/`,
diff --git a/tach.toml b/tach.toml
index dd749ec1b356..814cea3f3f90 100644
--- a/tach.toml
+++ b/tach.toml
@@ -235,6 +235,7 @@ depends_on = [
"posthog",
"products.actions",
"products.feature_flags",
+ "products.notebooks",
"products.tasks",
]
layer = "modules"