The platform for continuously improving AI agents.
One agent in experiments: runtime, protected settings and Your system (#367)
Freyam Mehta59bf79b7602b
diff --git a/.agents/skills/backend-architecture/references/assistant.md b/.agents/skills/backend-architecture/references/assistant.mdindex 2b60167a..a2eb2e30 100644--- a/.agents/skills/backend-architecture/references/assistant.md+++ b/.agents/skills/backend-architecture/references/assistant.md@@ -1,16 +1,15 @@# Platform assistant and project workspaces-The Console's assistant is a second author beside a customer's coding agent, in the Data Workshop and in each experiment. MCP stays the primary surface; both reach the same domain services.+The Console's assistant is a second author beside a customer's coding agent, and the only agent in the Console: every conversation is an experiment's, including data preparation. MCP stays the primary surface; both reach the same domain services.## Turn-- A dataset or an experiment has at most one `AssistantThread` (`dataset.assistant_thread`, `experiment.assistant_thread`; references/experiments.md) and its append-only `AssistantEvent` log (`user`, `assistant`, `tool_result`, `status`, `summary`). The log is the model context and the transcript. Messages wait in `AssistantInput` until a turn delivers them.+- An experiment has one `AssistantThread` (`experiment.assistant_thread`; references/experiments.md; the `dataset` column is unused and goes in a later migration) and its append-only `AssistantEvent` log (`user`, `assistant`, `tool_result`, `status`, `summary`). The log is the model context and the transcript. Messages wait in `AssistantInput` until a turn delivers them.- A turn that fails before it delivers its message leaves the message queued and does not wake itself: the next message starts the turn.- A turn is one Celery task (`tasks/assistant.run_turn`, queue `assistant`): from the delivered messages to a reply without tool calls, or to a `present` that asks a Question or Choices. `turn.wake` sends it after the commit that queued a message; a second task finds the thread taken and ends. The task starts the next turn itself when messages arrived while it ran.-- A turn takes the thread by raising `AssistantThread.turn` and writes only while it still holds that number (`log.append(..., turn=)` raises `LostTurnError`). `updated_at` is its progress mark, which a heartbeat also moves while the worker lives. The `resume_lost_turns` beat task (control queue, every minute) wakes a running turn whose mark is older than `turn.LEASE` (2 minutes); `run` takes it over under a new number, writes a `resumed` status and continues the reply from the log, where a call left without a result is answered as abandoned and never run again. After `turn.RESUMES` take-overs for one message, or when nothing resumed it for `STALE` (`turn.settle`, called by every read and message), the turn is marked interrupted. A turn ends itself after `TURN_SECONDS`.-- A message for a dataset whose source still lands waits: `_begin` leaves it queued, and the landing task calls `turn.wake_dataset` when it ends.-- A Console dataset made with `prepare` (the dialog sends it when an intent or a brief is given) queues `threads.queue_first_pass` in the create transaction, so its turn starts when the source lands. `turn.ready` holds that message while the dataset has no landed source, so a failed import keeps it queued for the next landing. A split queues one pass on the train half; the brief names the eval half (`split.sibling`), and both halves share the cleaning steps.-- A message is delivered with `threads.brief`: what the dataset holds now: its intent, the linked capability's contract, the split sibling, its pipeline, and for the source and latest versions their `data/<cell>.parquet` path, `fit`, exact `duplicate_rows` and a column profile (`store.frame_profile`, cached per frame). It is attached again only when it changed or a summary replaced the message that carried it.+- A turn takes the thread by raising `AssistantThread.turn` and writes only while it still holds that number (`log.append(..., turn=)` raises `LostTurnError`). `updated_at` is its progress mark, which a heartbeat also moves while the worker lives. The `resume_lost_turns` beat task (control queue, every minute) wakes a running turn whose mark is older than `turn.LEASE` (2 minutes); `run` takes it over under a new number, writes a `resumed` status and continues the reply from the log, where a call left without a result is answered as abandoned and never run again. After `turn.RESUMES` take-overs for one message, or when nothing resumed it for `STALE` (`turn.settle`, called by every read and message), the turn is marked interrupted. A turn takes at least its first message. One that reaches `TURN_SECONDS` queues a `continue` input and ends; `turn.CONTINUES` (8) continues since a person last wrote bound unattended work, then it fails. Turns no person started (run ends, triggers, continues) run at most `turn.UNATTENDED_TURNS` (3) at once per project; a person's message queued anywhere in the thread never waits. A held-back thread logs a `waiting` status; a turn that ends, and `resume_lost_turns`, wake each thread whose newest event is that status (`turn.waiting`), so a thread whose turn failed since waits for a person. A deleted experiment's thread takes no notice and starts no turn.+- Data dropped on Home with no message makes an experiment and no turn. Home waits for the data to land before it sends a message, so no turn waits on a landing.+- A message is delivered with `threads.brief` (`describe.brief`): the flow, the agent's notes, the runs, and for the first versions the flow pins (`describe.BRIEF_DATASETS`) `threads.dataset_brief`: the dataset's intent, the linked capability's contract, the split sibling, its pipeline, the version's `data/<cell>.parquet` path, `fit`, exact `duplicate_rows` and a column profile (`store.frame_profile`, cached per frame). It is attached again only when it changed or a summary replaced the message that carried it.- When a reply's prompt passes `ASSISTANT_COMPACT_TOKENS`, the turn appends a `summary` of all but the last `COMPACT_KEEP` events. A model call reads the newest summary and the events after it; the transcript keeps everything. The cut never separates a tool call from its result.- Stop sets `stop_requested`, drops queued messages and stops the conversation's kernel at once (`tasks/assistant.stop_kernel`), so a cell that runs answers. The turn sees the flag at its next step. Jobs the turn started continue.- Tools run with the project access of the newest message's sender, checked before each model call. The project's `owner` pays (gate and charges): a turn of a project without one fails. A reply and its charge are saved in one transaction; billing details are under Workspaces.@@ -18,7 +17,7 @@ The Console's assistant is a second author beside a customer's coding agent, in## Tools- Catalog tools (`tools.CATALOG_TOOLS`) are MCP tools called in process through `CATALOG.invoke`; validation and receipts are the catalog's own. The turn supplies `project_id`, and `request_key` on mutating tools. A tool that starts a job waits for it in the same call (`tools._wait`).-- Own tools: `run_python` runs a cell in the conversation's kernel; `versions` names the dataset versions it reads, copied into the workspace first. `run_pipeline` retains a package from the model's files, then saves, validates and runs it through the catalog and waits for the run; a publish over more than `tools.SAMPLE_ROWS` rows first runs a preview of that many rows and stops there when it fails, unless the script ran and kept none of those rows; a `pipeline` argument names either id of a saved pipeline. `present` shows a result.+- Own tools: `run_python` runs a cell in the conversation's kernel (an MCP client's `run_python` has its own kernel, `records.kernel`, per experiment and client); `versions` names the dataset versions it reads, copied into the workspace first. `run_pipeline` retains a package from the model's files, then saves, validates and runs it through the catalog and waits for the run; a publish over more than `tools.SAMPLE_ROWS` rows first runs a preview of that many rows and stops there when it fails, unless the script ran and kept none of those rows; a `pipeline` argument names either id of a saved pipeline. `present` shows a result.- Every tool schema starts with a `summary` argument (`tools.SUMMARY`): a few words for the reader. The Console shows it in place of the tool's name, while the call is written and afterwards.- Publication has one path: a retained pipeline package run by the pipeline runner. The kernel is for exploration only. The assistant has no path to the customer's repository or machine.- `present` documents are validated by `services/assistant/presentation.py` and stored in `AssistantEvent.presentation`. Charts, tables and metrics read tables the kernel wrote, and an Image is a PNG, JPEG or WebP file it wrote, retained under `MEDIA_ROOT/assistant/<thread>/` by content name. A Question or Choices answer is `{"call", "id", "values"}`.@@ -33,7 +32,8 @@ The Console's assistant is a second author beside a customer's coding agent, in- `bill` charges each `WorkspaceSandbox` row: Modal's `_experimental_stats().cost` for the window from `billed_until` to 10 minutes ago (usage arrives late), to the project's owner as `workspace`, keyed `modal-sandbox:<id>:<window start>`. An unmeasured window waits; a row finishes once its sandbox ended and a window holds no time. `tasks/assistant.bill_workspaces` runs it every 15 minutes. Model calls charge the owner as `assistant` at OpenRouter's `usage.cost`, keyed `openrouter:<generation>`; a call without a cost, or a stream cut off after it started, is charged by `charge_generation` from `/api/v1/generation`.- `native` runs the workspaces in the `sandbox` service (`sandbox/workspaces.py`) on the `workspaces` volume, under the uid and memory admission of a pipeline run, from the same memory budget. Copies are removed oldest first above `DATA_BUDGET_BYTES` (20 GiB). Its kernels stop after 15 idle minutes.- Native kernels, pipeline package runs and document extraction share one container and one Linux kernel. A uid keeps a run out of another's files, and `kernel.py:confine` closes the rest without any privilege (Fargate cannot grant `CAP_SYS_ADMIN`): Landlock limits the process and its children to its own folders, the libraries and its own `/proc` entry, denies TCP and scopes signals and abstract sockets; a seccomp filter refuses every socket family but `AF_UNIX`. Landlock applies as far as the host's Linux supports it (files 5.13, TCP 6.7, scoping 6.12); `/health` reports its version as `landlock`. A library that cannot reach a file it needs may abort the process instead of raising, so `conformance.LIBRARY_USE` uses every pinned library; a new library or allowed path is checked there.-- A deleted dataset's copies and conversations leave the workspace (`tasks/assistant.forget_workspace_data`), and a deleted project's workspace goes with it (`remove_workspace`); both retry, because the workspace holds customer data. `sweep_idle_workspaces` removes, each day, every workspace whose project had no assistant activity for 7 days.+- A final holdout's version is refused by `run_python`, `query_dataset` and `explore_dataset` (`partition_plans.refuse_sealed`).+- A deleted dataset's copies, and a deleted experiment's conversation and client kernels, leave the workspace (`tasks/assistant.forget_workspace_data`), and a deleted project's workspace goes with it (`remove_workspace`); both retry, because the workspace holds customer data. `sweep_idle_workspaces` removes, each day, every workspace whose project had no assistant activity for 7 days.- `conformance.py` holds the contract checks. The test suite runs them on `native`, and the Modal provider's edge cases on `tests/fakes/modal.py`; `manage.py check_workspaces` runs them on the configured provider. `.github/workflows/workspaces.yml` runs it on Modal in `overmind-dev`, with the `development` environment's Modal token as `deploy-modal.yml` uses it, each night and after a merge to `main` that changes the provider, the kernel or `uv.lock`. A rollout runs it on staging before prod.## Live updatesdiff --git a/.agents/skills/backend-architecture/references/experiments.md b/.agents/skills/backend-architecture/references/experiments.mdindex 2aa9e551..8e3d7f38 100644--- a/.agents/skills/backend-architecture/references/experiments.md+++ b/.agents/skills/backend-architecture/references/experiments.md@@ -18,6 +18,9 @@ An experiment is a saved flow of stages with its own conversation. The Console,## The experiment's agent-- Its conversation is an `AssistantThread` with `experiment` set (a thread has a dataset or an experiment). The brief (`describe.brief`) carries the flow, its problems and the newest runs; the experiment tools are in `tools.CATALOG_TOOLS`, so the assistant and an MCP client call the same tools.-- When a top-level run ends, `operator.run_ended` queues a notice (`AssistantInput.origin=run`) as the run's starter, and the turn reads it as the platform's words. The agent starts at most `runs.AGENT_RUNS` runs (3) since a person last sent a message or started a run.+- Its conversation is the experiment's `AssistantThread`; every conversation is one, and a dataset page has none. `records.dataset_links` gives each dataset the experiment that made it (a stage whose output version appeared during the stage) and those that read it; an experiment that pins a dataset blocks its delete. The brief (`describe.brief`) carries the flow, its problems and the newest runs; the experiment tools are in `tools.CATALOG_TOOLS`, so the assistant and an MCP client call the same tools.+- When a top-level run ends, `operator.run_ended` queues a notice (`AssistantInput.origin=run`) as the run's starter, and the turn reads it as the platform's words. The agent starts at most `runs.AGENT_RUNS` runs (3) per person's message or trigger send, and while no person is in the loop none once a trigger's `max_spend_usd` is reached by `describe.spend` (measured costs only: agent calls, training charges, evaluation answers; workspace time and judging are named as not measured). A run the agent started stops the deployments it made when it ends, unless one became a capability's active model.+- A person's save (Console or MCP) marks the settings it set on each node as `protected`. The agent's save that changes one is refused (`ProtectedSettingError`, MCP `protected_setting`) and logged as a `proposal` event; `records.resolve_proposal` applies it as the person's own revision, or dismisses it.+- `Experiment.notes` holds the agent's notes, written with `revise_experiment` `notes` and shown read-only in the Console.+- Your system (`system` kind, `services/experiments/system.py`): the stage waits on a `system_outputs` receipt; `overmind run` reads `GET /api/experiment-steps/<id>/rows/` and posts `outputs/`, which imports the rows with a `_overmind_output` column into the step's own dataset (`uuid5(step, "outputs")`, so the input's active version stays; provenance: step, label, commit) and replaces the receipt with the import's run. The same outputs again replay that import, also after the stage moved on. A final holdout is refused. Evaluate scores it with a `recorded` target, whose `recorded_output` reads `_overmind_output`.- Triggers (`triggers.py`, beat `experiments.fire_triggers` every minute) send their instruction (`origin=trigger`) every N hours, or when a capability's failing traces within N hours reach a threshold (counted again every 10 minutes), until `max_sends`.diff --git a/.agents/skills/data-workshop/SKILL.md b/.agents/skills/data-workshop/SKILL.mdindex 2616368f..73a919e9 100644--- a/.agents/skills/data-workshop/SKILL.md+++ b/.agents/skills/data-workshop/SKILL.md@@ -5,7 +5,7 @@ description: Data Workshop internals — source landing and OCR, immutable datas# Data Workshop-A customer's coding agent over MCP and the Console assistant own interpretation, code and semantic work (backend-architecture `references/assistant.md`). The platform stores evidence and runs explicit, deterministic operations. Landing never diagnoses, generates examples or starts preparation; a message that waits for the source starts its turn when landing ends. There is no mutable cell or replay endpoint; old conversations and provider receipts are archived in `DatasetHistory`, and historical cell scripts, reviews and frames stay readable.+A customer's coding agent over MCP and the Console assistant own interpretation, code and semantic work (backend-architecture `references/assistant.md`). The platform stores evidence and runs explicit, deterministic operations. Landing never diagnoses, generates examples or starts preparation. Preparation is an experiment's work: the dataset page has no chat. There is no mutable cell or replay endpoint; old conversations and provider receipts are archived in `DatasetHistory`, and historical cell scripts, reviews and frames stay readable.## Map@@ -82,7 +82,7 @@ External results arrive inline (at most 2,000 rows or 4 MiB) or as a project-sco## Console canvas-The landing page opens on the assistant composer (`components/assistant/assistant-composer.tsx`): files or attached datasets plus one sentence start a thread on the working dataset. The project dataset table is a sheet below it; a row opens its cells on a flow canvas. Cells stay full-size at scale 1; zoom and Fit view change only the camera. Steps run downward and sibling branches share a horizontal layer. The layered layout owns every position and reruns when a cell's height changes, so cells are not draggable. The folder button opens project-scoped dataset navigation. The assistant chat is a bar at the bottom of the canvas that opens into a resizable left panel (`components/assistant/`). There is no funding control, cell search or cell-selector strip.+The landing page is the project dataset table; a row opens its cells on a flow canvas. Data comes in on Home, where files with no message land in a new experiment without an agent turn. Cells stay full-size at scale 1; zoom and Fit view change only the camera. Steps run downward and sibling branches share a horizontal layer. The layered layout owns every position and reruns when a cell's height changes, so cells are not draggable. The folder button opens project-scoped dataset navigation. A bar at the bottom of the canvas shows "Made by", "Used in" and "Work on this dataset" (`notebook/dataset-links.tsx`). There is no funding control, cell search or cell-selector strip.The inventory columns are Name, Role, Capability, Datapoints, Source and Updated(`components/datasets/datasets-table.tsx`); every value is one chip shape or an em dash.diff --git a/AGENTS.md b/AGENTS.mdindex 77afbeb8..1069ad00 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -31,7 +31,7 @@ This file is the playbook every task needs; Claude Code, Codex and Cursor read i- OTLP ingest never creates a capability, a scan never deletes one, and `DELETE` is a soft delete. On OTLP spans, wire identity is `overmind.capability.id` alone.- Operator alerts come from New Relic: every `overbae.*` ERROR log becomes a New Relic error grouped by its unformatted message, so pass IDs as log args, never in an f-string. A caught failure with no log calls `telemetry.report_failure` (`overbae/core/telemetry.py`).- Celery routing must agree across `CELERY_TASK_ROUTES`, `make worker`, docker-compose and `docker/worker-topology.json`. Only prefork pools enforce `time_limit`. `tests/test_celery_topology.py` checks compose and `make worker` against the routes.-- Two authors do interpretation, code and semantic work: a customer's coding agent over MCP, and the platform assistant in the Console (`services/assistant/`). Both call the same domain services; deterministic, lineage-bound operations stay in the platform. The assistant's turn runs in a worker, never in a sandbox; a project workspace (`services/workspaces/`) only runs code.+- Two authors do interpretation, code and semantic work: a customer's coding agent over MCP, and the platform assistant in the Console (`services/assistant/`). Both call the same domain services; deterministic, lineage-bound operations stay in the platform. The assistant's turn runs in a worker, never in a sandbox; a project workspace (`services/workspaces/`) only runs code. Every assistant conversation is an experiment's; a setting a person set is protected, and the agent's change to it becomes a proposal.- Work-starting operations take a project-scoped request key: an identical retry returns the same record, and a changed payload conflicts. An unknown provider acknowledgement is reconciled from its saved call ID, never resubmitted.- Measured facts only. Missing usage, progress, scores and telemetry stay unknown; never fill them with a percentage, a zero, an ETA or elapsed time.- Code under `overbae/modal/`, `modal_shared/` and `overbae/services/sft_assets/` reaches Modal only after `modal deploy`; training and serving pin immutable releases.diff --git a/DESIGN.md b/DESIGN.mdindex a65a7684..e95f1827 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -702,9 +702,10 @@ heading and project count. Dataset listings and their empty states have no Newdataset action. Columns show name, intent,active version, row count, source, capability and last update. Intent uses amonochrome outlined chip, not a status tint. Selecting a row-opens the existing cell-based notebook. The Datasets landing opens on the assistant-composer under a "Ready to train" title, over the night sky of the connection pages (`ConnectionBackground`); the dataset-list is a sheet below it that slides up to full height. A checkbox on a row attaches that dataset to the composer.+opens the existing cell-based notebook. Datasets is a library: the table under a page heading, with an+Experiment column (the experiment that made the dataset, else the first that reads it). Work on data starts in an+experiment: the empty state links to Home, and the dataset page has no chat, only "Made by", "Used in" and a+"Work on this dataset" button that starts an experiment reading its active version.Dataset navigation and content share a continuous outer bezel (3px). The 248pxcolumn starts collapsed, including on landing. The notebook folder button revealsdiff --git a/frontend/src/client.ts b/frontend/src/client.tsindex 68ee8a69..62a43291 100644--- a/frontend/src/client.ts+++ b/frontend/src/client.ts@@ -52,6 +52,7 @@ import {McpOauthApi,ModelsApi,NativeEvaluationsApi,+ ProjectSetupApi,ProjectsApi,ResponseError,SessionsApi,@@ -421,6 +422,7 @@ export async function request<T>(path: string, init?: RequestInit): Promise<T> {export class API {mcpOauth: McpOauthApi;agent: AgentApi;+ projectSetup: ProjectSetupApi;capabilities: CapabilitiesApi;auth: AuthApi;billing: BillingApi;@@ -468,6 +470,7 @@ export class API {this.assistantThreads = new AssistantThreadsApi(this.cfg);this.mcpOauth = new McpOauthApi(this.cfg);this.agent = new AgentApi(this.cfg);+ this.projectSetup = new ProjectSetupApi(this.cfg);this.capabilities = new CapabilitiesApi(this.cfg);this.auth = new AuthApi(this.cfg);this.billing = new BillingApi(this.cfg);diff --git a/frontend/src/components/assistant/assistant-composer.tsx b/frontend/src/components/assistant/assistant-composer.tsxdeleted file mode 100644index 333dafae..00000000--- a/frontend/src/components/assistant/assistant-composer.tsx+++ /dev/null@@ -1,280 +0,0 @@-import { useRef, useState } from "react";--import { useMutation, useQueryClient } from "@tanstack/react-query";--import apiClient from "@/client";-import { Attachment } from "@/components/datasets/attachment";-import { Alert } from "@/components/ui/alert";-import { Button } from "@/components/ui/button";-import { Card } from "@/components/ui/card";-import { Icon } from "@/components/ui/icons";-import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";-import { Spinner } from "@/components/ui/spinner";-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";-import { sendToDataset } from "@/hooks/use-assistant-thread";-import { activeCellOf, datasetDisplayName, invalidateDataset } from "@/hooks/use-datasets";-import { useGuestGate } from "@/hooks/use-guest-gate";-import { useDatasetUploads } from "@/hooks/use-uploads";-import { errorMessage } from "@/lib/notify";-import type { Dataset } from "@/openapi";-import { MessageLimit } from "./message-limit";-import { MESSAGE_CHARS } from "./types";--const ACCEPT =- ".csv,.tsv,.json,.jsonl,.ndjson,.parquet,.gz,.pdf,.docx,.md,.txt,.png,.jpg,.jpeg,.webp";-const stripExtension = (name: string) => name.replace(/(\.[a-z0-9]+){1,2}$/i, "");--// The API takes 20 dataset versions with a message.-const MAX_REFERENCES = 20;--/** The goal a user starts from: attached files or datasets, and one sentence. Sending- * creates the working dataset if files were attached, opens its thread and queues the- * message; the assistant starts when the source has landed. A retry of the same request- * repeats nothing; a changed request is a new one. */--export function AssistantComposer({- projectId,- datasets,- onRemoveDataset,- onStarted,-}: {- projectId: string;- /** Datasets attached from the list. Without uploads the first is the working dataset. */- datasets: Dataset[];- onRemoveDataset: (id: string) => void;- onStarted: (datasetId: string) => void;-}) {- const qc = useQueryClient();- const guard = useGuestGate();- const upload = useDatasetUploads();- const fileInput = useRef<HTMLInputElement>(null);- const [text, setText] = useState("");- const [dragging, setDragging] = useState(false);- const progress = useRef<{ request: string; key: string; dataset?: string }>(null);-- const uploading = upload.files.some((file) => file.status !== "ready" && file.status !== "error");- const ready = upload.files.filter((file) => file.status === "ready");- const start = useMutation({- mutationFn: async (message: string) => {- const uploads = ready.map((file) => file.uploadId!);- const request = JSON.stringify([message, uploads, datasets.map((dataset) => dataset.id)]);- if (progress.current?.request !== request)- progress.current = { key: crypto.randomUUID(), request };- const step = progress.current;- if (!step.dataset) {- step.dataset = uploads.length- ? (- await apiClient.datasets.datasetsCreate({- datasetCreateRequest: {- name: stripExtension(ready[0].file.name) || "Untitled dataset",- project: projectId,- source: { uploads },- },- })- ).id- : datasets[0].id;- invalidateDataset(qc);- }- const working = step.dataset;- const references = await Promise.all(- datasets- .filter((dataset) => dataset.id !== working)- .map((dataset) => apiClient.datasets.datasetsRetrieve({ id: dataset.id }))- );- await sendToDataset(qc, working, {- cells: references.flatMap((dataset) => activeCellOf(dataset)?.id ?? []),- requestKey: step.key,- text: message,- });- return working;- },- });-- const locked = start.isPending;- const hasData = ready.length > 0 || datasets.length > 0;- // The message names every attached dataset but the one it works on; the API takes 20.- const tooMany = (ready.length > 0 ? datasets.length : datasets.length - 1) > MAX_REFERENCES;- const sendHint = locked- ? "Starting"- : uploading- ? "Uploading"- : !hasData- ? "No data attached"- : tooMany- ? `At most ${MAX_REFERENCES + (ready.length > 0 ? 0 : 1)} datasets`- : !text.trim()- ? "No message"- : "Send";- const submit = guard(() => {- if (locked || uploading || !hasData || tooMany || !text.trim()) return;- // Called only while this page is mounted: a start that ends later moves nobody.- start.mutate(text.trim(), { onSuccess: onStarted });- });- const addFiles = guard((files: File[]) => upload.add(files));-- return (- <Card- className="assistant-surface assistant-composer w-full p-1.5 data-[dragging=true]:border-ring"- data-dragging={dragging}- >- <form- aria-label="Start with the assistant"- className="assistant-chat-inner overflow-hidden border border-border/70 bg-muted"- onDragLeave={() => setDragging(false)}- onDragOver={(event) => {- event.preventDefault();- setDragging(true);- }}- onDrop={(event) => {- event.preventDefault();- setDragging(false);- addFiles(Array.from(event.dataTransfer.files));- }}- onSubmit={(event) => {- event.preventDefault();- submit();- }}- >- <span aria-hidden="true" className="assistant-prompt-mark">- >- </span>- <textarea- aria-label="What would you like to train?"- className="assistant-chat-input block max-h-56 min-h-28 w-full resize-none border-0 bg-transparent text-sm outline-none"- disabled={locked}- id="assistant-intent"- maxLength={MESSAGE_CHARS}- onChange={(event) => setText(event.target.value)}- onKeyDown={(event) => {- if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {- event.preventDefault();- submit();- }- }}- onPaste={(event) => {- if (event.clipboardData.files.length) {- event.preventDefault();- addFiles(Array.from(event.clipboardData.files));- }- }}- placeholder="What would you like to train?"- value={text}- />- {text.length >= MESSAGE_CHARS && <MessageLimit />}- {start.error && (- <div className="flex items-center gap-2 px-3 pb-2">- <Alert className="w-auto flex-1">- {errorMessage(start.error, "The request could not be started.")}- </Alert>- <Button onClick={submit} size="xs" type="button" variant="secondary">- Retry- </Button>- </div>- )}- <div className="flex min-w-0 items-center gap-2 px-3 pt-1 pb-3">- <input- accept={ACCEPT}- aria-label="Attach dataset files"- className="hidden"- disabled={locked}- multiple- onChange={(event) => {- addFiles(Array.from(event.target.files ?? []));- event.target.value = "";- }}- ref={fileInput}- type="file"- />- <Tooltip>- <TooltipTrigger asChild>- <Button- aria-label="Attach files"- disabled={locked}- onClick={guard(() => fileInput.current?.click())}- size="icon-sm"- type="button"- variant="outline"- >- <Icon.add />- </Button>- </TooltipTrigger>- <TooltipContent>Attach files</TooltipContent>- </Tooltip>- <ul- aria-label="Attached data"- className="assistant-attachments flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto"- >- {datasets.map((dataset, index) => (- <li- className="assistant-attachment flex h-7 max-w-44 shrink-0 items-center gap-1 rounded-sm border border-border/70 bg-card pr-0.5 pl-1.5 text-xs text-muted-foreground"- key={dataset.id}- >- <Popover>- <PopoverTrigger asChild>- <button- aria-label={`Dataset details: ${datasetDisplayName(dataset)}`}- className="flex min-w-0 items-center gap-1.5 rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/60"- type="button"- >- <Icon.dataset className="size-3.5 shrink-0 text-cat-2" />- <span className="truncate">{datasetDisplayName(dataset)}</span>- </button>- </PopoverTrigger>- <PopoverContent align="start" className="w-64 space-y-2 p-3 text-xs" side="top">- <p className="break-words font-medium">{datasetDisplayName(dataset)}</p>- <p className="text-muted-foreground">- {dataset.activeVersion} · {dataset.rows.toLocaleString()} rows- </p>- <p className="text-muted-foreground">- {index === 0 && !upload.files.length- ? "Working dataset"- : "Reference dataset"}- </p>- </PopoverContent>- </Popover>- <Button- aria-label={`Remove ${datasetDisplayName(dataset)} from chat`}- className="assistant-attachment-remove text-muted-foreground transition-opacity"- disabled={locked}- onClick={() => onRemoveDataset(dataset.id)}- size="icon-xs"- type="button"- variant="ghost"- >- <Icon.close />- </Button>- </li>- ))}- {upload.files.map((entry) => (- <Attachment- compact- disabled={locked}- entry={entry}- key={entry.id}- onRemove={() => upload.remove(entry.id)}- onRetry={() => upload.retry(entry)}- />- ))}- </ul>- <Tooltip>- <TooltipTrigger asChild>- <span className="inline-flex shrink-0">- <Button- className="disabled:text-muted-foreground"- disabled={locked || uploading || !hasData || tooMany || !text.trim()}- size="sm"- type="submit"- variant="secondary"- >- {locked || uploading ? <Spinner size="sm" /> : <Icon.send />}- Send- </Button>- </span>- </TooltipTrigger>- <TooltipContent>{sendHint}</TooltipContent>- </Tooltip>- </div>- </form>- </Card>- );-}diff --git a/frontend/src/components/assistant/assistant-dock.tsx b/frontend/src/components/assistant/assistant-dock.tsxindex d6728a33..7cfb591e 100644--- a/frontend/src/components/assistant/assistant-dock.tsx+++ b/frontend/src/components/assistant/assistant-dock.tsx@@ -64,7 +64,7 @@ function statusOf(if (stopping) return "Stopping";const last = assistant.events.at(-1);if (active) {- // A message that waits for the dataset's source to land: no step runs yet.+ // A queued message no turn took yet: no step runs.if (assistant.thread?.state === "idle") return "Queued";return runningLabel(assistant.events) ?? assistant.draft?.steps.at(-1) ?? "Working";}diff --git a/frontend/src/components/assistant/assistant-transcript.tsx b/frontend/src/components/assistant/assistant-transcript.tsxindex 8e228ea0..6195f761 100644--- a/frontend/src/components/assistant/assistant-transcript.tsx+++ b/frontend/src/components/assistant/assistant-transcript.tsx@@ -235,10 +235,12 @@ function ToolGroup({ steps, active }: { steps: Step[]; active: boolean }) {}const STATUS_NOTE = {+ continued: "text-muted-foreground",failed: "text-error",interrupted: "text-warning",resumed: "text-muted-foreground",stopped: "text-muted-foreground",+ waiting: "text-muted-foreground",};// A mention the composer wrote as a markdown link to a Console page.diff --git a/frontend/src/components/capability-detail/next-step-nudge.tsx b/frontend/src/components/capability-detail/next-step-nudge.tsxindex 8ba5d35d..d77c3e79 100644--- a/frontend/src/components/capability-detail/next-step-nudge.tsx+++ b/frontend/src/components/capability-detail/next-step-nudge.tsx@@ -124,7 +124,7 @@ function ctaLink();case "upload":return (- <Link search={{ create: true, ds_capability: capabilityId, projectId }} to="/datasets">+ <Link search={{ projectId }} to="/"><Icon.upload />Upload dataset</Link>diff --git a/frontend/src/components/command-palette.tsx b/frontend/src/components/command-palette.tsxindex 331cd82f..8d5c2a77 100644--- a/frontend/src/components/command-palette.tsx+++ b/frontend/src/components/command-palette.tsx@@ -139,12 +139,11 @@ const NAV_KEYWORDS: Record<string, string[]> = {const ACTIONS: ActionDef[] = [{icon: Icon.datasetAdd,- id: "action:create-dataset",- keywords: ["new dataset", "create dataset", "upload dataset", "import traces", "data workshop"],- label: "New dataset",+ id: "action:new-experiment",+ keywords: ["new experiment", "new dataset", "upload dataset", "data workshop"],+ label: "New experiment",projectScoped: true,- search: { create: "true" },- to: "/datasets",+ to: "/",},{icon: Icon.projectAdd,diff --git a/frontend/src/components/datasets/datasets-table.test.tsx b/frontend/src/components/datasets/datasets-table.test.tsxindex b2d23136..4ef2eb99 100644--- a/frontend/src/components/datasets/datasets-table.test.tsx+++ b/frontend/src/components/datasets/datasets-table.test.tsx@@ -32,6 +32,7 @@ const dataset = (fields: Partial<Dataset>): Dataset =>cells: [],id: crypto.randomUUID(),intent: "pending",+ madeBy: null,name: "rows",roles: [],rows: 10,@@ -40,6 +41,7 @@ const dataset = (fields: Partial<Dataset>): Dataset =>state: "idle",trainFormat: "",updatedAt: "2026-11-18T10:00:00Z",+ usedIn: [],work: null,...fields,}) as unknown as Dataset;@@ -85,8 +87,8 @@ describe("datasets table", () => {expect(row("Tickets").getByText("a.csv")).toBeTruthy();expect(row("Tickets").getByText("+2")).toBeTruthy();expect(row("Calls").getByText("Traces")).toBeTruthy();- // A draft has no role, capability, count or source: each shows the same dash.- expect(row("Draft").getAllByText("—")).toHaveLength(4);+ // A draft has no role, capability, count, source or experiment: each shows the same dash.+ expect(row("Draft").getAllByText("—")).toHaveLength(5);// With no intent, a used dataset shows what it was used for, and rows sent inline say so.expect(row("Split source").getByText("Train + Eval")).toBeTruthy();expect(row("Split source").getByText("Inline rows")).toBeTruthy();diff --git a/frontend/src/components/datasets/datasets-table.tsx b/frontend/src/components/datasets/datasets-table.tsxindex e7b0adcc..a635f811 100644--- a/frontend/src/components/datasets/datasets-table.tsx+++ b/frontend/src/components/datasets/datasets-table.tsx@@ -1,11 +1,10 @@import { createContext, type ReactNode, useContext, useMemo, useState } from "react";-import { useNavigate } from "@tanstack/react-router";-import type { ColumnDef, OnChangeFn, RowSelectionState } from "@tanstack/react-table";+import { Link, useNavigate } from "@tanstack/react-router";+import type { ColumnDef } from "@tanstack/react-table";import { EntityRef } from "@/components/entity-ref";import { FileTypeIcon } from "@/components/file-type-icon";-import { Checkbox } from "@/components/ui/checkbox";import { ConfirmDialog } from "@/components/ui/confirm-dialog";import { DataTable } from "@/components/ui/data-table";import { DateTime } from "@/components/ui/datetime";@@ -480,6 +479,30 @@ function getColumns(opts: {minSize: 140,size: 200,},+ {+ accessorFn: (row) => (row.madeBy ?? row.usedIn[0])?.name ?? "",+ cell: ({ row }) => {+ const link = row.original.madeBy ?? row.original.usedIn[0];+ return link ? (+ <Link+ className="truncate text-sm underline-offset-2 hover:underline"+ onClick={(event) => event.stopPropagation()}+ params={{ experimentId: link.experiment }}+ search={{ projectId: row.original.project }}+ to="/experiments/$experimentId"+ >+ {link.name}+ </Link>+ ) : (+ <Dash />+ );+ },+ header: "Experiment",+ id: "experiment",+ meta: { label: "Experiment" },+ minSize: 140,+ size: 200,+ },{accessorKey: "updatedAt",cell: ({ row }) => (@@ -498,40 +521,6 @@ function getColumns(opts: {return cols;}-const ATTACH_COLUMN: ColumnDef<Dataset> = {- cell: ({ row }) => {- const published = !!row.original.activeVersion;- return (- <Tooltip>- <TooltipTrigger asChild>- <span className="inline-flex">- <Checkbox- aria-label={`Attach ${datasetDisplayName(row.original)} to chat`}- checked={row.getIsSelected()}- disabled={!published}- onCheckedChange={(checked) => row.toggleSelected(checked === true)}- onClick={(event) => event.stopPropagation()}- />- </span>- </TooltipTrigger>- <TooltipContent>- {!published- ? "This dataset has no published data."- : row.getIsSelected()- ? "Remove from chat"- : "Attach to chat"}- </TooltipContent>- </Tooltip>- );- },- enableResizing: false,- enableSorting: false,- header: "",- id: "attach",- meta: { label: "Attach to chat", noTruncate: true },- size: 36,-};-export function DatasetsBrowser({datasets,search,@@ -546,12 +535,7 @@ export function DatasetsBrowser({hideCapabilityColumn,fill = true,rowSearch,- rowSelection,- onRowSelectionChange,}: DatasetsFilterProps & {- /** With both set, each row gets a checkbox that attaches its dataset to the assistant. */- rowSelection?: RowSelectionState;- onRowSelectionChange?: OnChangeFn<RowSelectionState>;isLoading: boolean;error?: unknown;onRetry?: () => unknown;@@ -594,11 +578,10 @@ export function DatasetsBrowser({const pageRows = sorted.slice((currentPage - 1) * pageSize, currentPage * pageSize);const hasActiveFilters = roleFilter !== "all" || capabilityFilter !== "all" || !!search;- const selectable = !!onRowSelectionChange;- const columns = useMemo(() => {- const base = getColumns({ hideCapabilityColumn, nameById });- return selectable ? [ATTACH_COLUMN, ...base] : base;- }, [hideCapabilityColumn, nameById, selectable]);+ const columns = useMemo(+ () => getColumns({ hideCapabilityColumn, nameById }),+ [hideCapabilityColumn, nameById]+ );const [renamingId, setRenamingId] = useState<string | null>(null);const [deleteTarget, setDeleteTarget] = useState<Dataset | null>(null);const patchDataset = usePatchDatasetMutation();@@ -650,7 +633,6 @@ export function DatasetsBrowser({title="No datasets yet"/>}- enableRowSelection={selectable}error={error}getRowId={(row) => row.id}hasActiveFilters={hasActiveFilters}@@ -672,7 +654,6 @@ export function DatasetsBrowser({onRetry={onRetry}onRowClick={(ds) => open(ds)}onRowOpenInTab={(ds) => open(ds, newWorkspaceTab("/datasets"))}- onRowSelectionChange={onRowSelectionChange}ordering={ordering}page={currentPage}pageSize={pageSize}@@ -690,7 +671,6 @@ export function DatasetsBrowser({},]}rowClassName={(row) => (highlights[`dataset:${row.id}`] ? "activity-highlight" : undefined)}- rowSelection={rowSelection}storageKey="datasets-table"/></Renaming.Provider>diff --git a/frontend/src/components/datasets/new-dataset-dialog.test.tsx b/frontend/src/components/datasets/new-dataset-dialog.test.tsxindex f829aa39..9a7bc637 100644--- a/frontend/src/components/datasets/new-dataset-dialog.test.tsx+++ b/frontend/src/components/datasets/new-dataset-dialog.test.tsx@@ -136,7 +136,6 @@ describe("dataset file dialog", () => {capabilityId: "cap",intent: "eval",name: "Support data",- prepare: true,projectId: "project",source: { uploads: ["second.jsonl"] },})@@ -175,7 +174,6 @@ describe("dataset file dialog", () => {evalPercent: 40,name: "first",position: "tail",- prepare: true,projectId: "project",source: { uploads: ["first.csv", "second.jsonl"] },})diff --git a/frontend/src/components/datasets/new-dataset-dialog.tsx b/frontend/src/components/datasets/new-dataset-dialog.tsxindex fd414d5d..afe8f3f5 100644--- a/frontend/src/components/datasets/new-dataset-dialog.tsx+++ b/frontend/src/components/datasets/new-dataset-dialog.tsx@@ -212,8 +212,6 @@ export function NewDatasetDialog({? null: capabilityId,name: name.trim() || suggestedName || "Untitled dataset",- // A stated intent or brief starts the assistant's first pass once the source lands.- prepare: !!ready && (intent !== "pending" || !!brief.trim()),projectId,source: ready ? readiness.source : undefined,};diff --git a/frontend/src/components/datasets/notebook/cell.tsx b/frontend/src/components/datasets/notebook/cell.tsxindex 059d0014..06a74d20 100644--- a/frontend/src/components/datasets/notebook/cell.tsx+++ b/frontend/src/components/datasets/notebook/cell.tsx@@ -240,6 +240,7 @@ export function NotebookCell({onSelect,actions,sourceDetails,+ splitReport,preparationActions,}: {datasetId: string;@@ -258,6 +259,8 @@ export function NotebookCell({onSelect: () => void;actions: CellActions;sourceDetails?: ReactNode;+ /** How the import split the source, beside the active version's intent. */+ splitReport?: ReactNode;preparationActions?: ReactNode;}) {const source = cell.position === 0;@@ -469,6 +472,7 @@ export function NotebookCell({trainFormat={trainFormat}/><CapabilityMismatch cell={cell} name={capabilityName} />+ {splitReport}<span className="flex-1" />{intent === "train" && (<Buttondiff --git a/frontend/src/components/datasets/notebook/dataset-links.tsx b/frontend/src/components/datasets/notebook/dataset-links.tsxnew file mode 100644index 00000000..b4780141--- /dev/null+++ b/frontend/src/components/datasets/notebook/dataset-links.tsx@@ -0,0 +1,101 @@+import { useRef } from "react";++import { useMutation } from "@tanstack/react-query";+import { Link, useNavigate } from "@tanstack/react-router";++import apiClient from "@/client";+import { Button } from "@/components/ui/button";+import { Icon } from "@/components/ui/icons";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { activeCellOf, datasetDisplayName } from "@/hooks/use-datasets";+import { useGuestGate } from "@/hooks/use-guest-gate";+import { notify } from "@/lib/notify";+import type { Dataset, ExperimentLink } from "@/openapi";++function ExperimentName({ link, projectId }: { link: ExperimentLink; projectId: string }) {+ return (+ <Link+ className="block truncate text-foreground underline-offset-2 hover:underline"+ params={{ experimentId: link.experiment }}+ search={{ projectId }}+ to="/experiments/$experimentId"+ >+ {link.name}+ </Link>+ );+}++/** The experiments that made and use the dataset; work on it starts an experiment. */+export function DatasetLinks({ dataset, projectId }: { dataset: Dataset; projectId: string }) {+ const navigate = useNavigate();+ const guard = useGuestGate();+ const active = activeCellOf(dataset);+ // One key per start: a retry after a lost response returns the same experiment.+ const requestKey = useRef(crypto.randomUUID());+ const start = useMutation({+ mutationFn: () =>+ apiClient.experiments.experimentsCreate({+ experimentCreateRequest: {+ cells: [active!.id],+ name: `Work on ${datasetDisplayName(dataset)}`,+ project: projectId,+ requestKey: requestKey.current,+ },+ }),+ onError: (error) => notify.error(error, "The experiment could not be started"),+ onSuccess: (experiment) => {+ requestKey.current = crypto.randomUUID();+ void navigate({+ params: { experimentId: experiment.id },+ search: { projectId },+ to: "/experiments/$experimentId",+ });+ },+ });+ const links = (dataset.madeBy ? 1 : 0) + dataset.usedIn.length;+ return (+ // Beside "Prepare with coding agent": the same work, by the platform's agent.+ <>+ {links > 0 && (+ <Popover>+ <PopoverTrigger asChild>+ <Button size="sm" variant="outline">+ <Icon.history />+ Experiments+ <span className="tabular-nums text-muted-foreground">{links}</span>+ </Button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-72 space-y-3 p-3 text-sm">+ {dataset.madeBy && (+ <div className="space-y-1">+ <p className="text-xs text-muted-foreground">Made by</p>+ <ExperimentName link={dataset.madeBy} projectId={projectId} />+ </div>+ )}+ {dataset.usedIn.length > 0 && (+ <div className="space-y-1">+ <p className="text-xs text-muted-foreground">Used in</p>+ <ul className="space-y-1">+ {dataset.usedIn.map((link) => (+ <li className="flex min-w-0" key={link.experiment}>+ <ExperimentName link={link} projectId={projectId} />+ </li>+ ))}+ </ul>+ </div>+ )}+ </PopoverContent>+ </Popover>+ )}+ <Button+ disabled={!active || start.isPending}+ onClick={guard(() => start.mutate())}+ size="sm"+ title={active ? undefined : "This dataset has no ready version."}+ >+ <Icon.ai />+ Work on this dataset+ </Button>+ </>+ );+}diff --git a/frontend/src/components/datasets/notebook/notebook-page.test.tsx b/frontend/src/components/datasets/notebook/notebook-page.test.tsxindex 76b84a75..b76a9baf 100644--- a/frontend/src/components/datasets/notebook/notebook-page.test.tsx+++ b/frontend/src/components/datasets/notebook/notebook-page.test.tsx@@ -45,12 +45,14 @@ beforeEach(() => {cells: [],error: "The import worker stopped.",id: "dataset",+ made_by: null,name: "titanic",operation: { source_import: { can_resume: true } },project: "project",roles: [],source_spec: {},state: "error",+ used_in: [],work: null,workspace_id: "dataset-1",});diff --git a/frontend/src/components/datasets/notebook/notebook-page.tsx b/frontend/src/components/datasets/notebook/notebook-page.tsxindex e0fa6f34..431a9e78 100644--- a/frontend/src/components/datasets/notebook/notebook-page.tsx+++ b/frontend/src/components/datasets/notebook/notebook-page.tsx@@ -3,11 +3,11 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useQueryClient } from "@tanstack/react-query";import { Link, useNavigate } from "@tanstack/react-router";-import { AssistantDock } from "@/components/assistant/assistant-dock";import { NotebookControls } from "@/components/datasets/notebook/canvas-controls";import { NotebookCell, type UsePurpose } from "@/components/datasets/notebook/cell";import { CellFlow } from "@/components/datasets/notebook/cell-flow";import { useCellMotion } from "@/components/datasets/notebook/cell-motion";+import { DatasetLinks } from "@/components/datasets/notebook/dataset-links";import { ContaminationReport } from "@/components/datasets/notebook/preparation";import { PreparationActions } from "@/components/datasets/notebook/preparation-actions";import {@@ -19,7 +19,6 @@ import { Alert } from "@/components/ui/alert";import { Button } from "@/components/ui/button";import { EmptyState } from "@/components/ui/empty-state";import { LoadingState, Spinner } from "@/components/ui/spinner";-import { useAssistantThread } from "@/hooks/use-assistant-thread";import {activeCellOf,type DatasetEvent,@@ -63,7 +62,6 @@ export function DatasetNotebook({cellParam,dataset?.updatedAt?.getTime());- const assistant = useAssistantThread({ dataset: datasetId });const patch = usePatchDatasetMutation(datasetId);const cancel = useCancelDatasetMutation(datasetId);@@ -100,15 +98,9 @@ export function DatasetNotebook({}, [stamp, read, refresh]);useDatasetEvents(datasetId, (event: DatasetEvent) => {- if (event.type === "assistant" || event.type === "assistant.draft") {- assistant.handle(event);- return;- }if (event.type === "connected") {- // The conversation reads after the events it holds, so every connection catches up- // on it. A dropped connection may have missed dataset changes; a first one only- // those made after the page read the dataset, compared once that read has arrived.- assistant.handle(event);+ // A dropped connection may have missed dataset changes; a first one only those made+ // after the page read the dataset, compared once that read has arrived.if (event.again) {refresh();} else {@@ -209,6 +201,7 @@ export function DatasetNotebook({!busy ? (<div className="nodrag nopan pointer-events-auto"><PreparationActions cell={cell} dataset={dataset} run={latestRun}>+ {cell && <DatasetLinks dataset={dataset} projectId={projectId} />}{dataset.operation?.source_import?.can_resume === true && (<Buttondisabled={resumeImport.isPending}@@ -273,6 +266,7 @@ export function DatasetNotebook({/>) : undefined}+ splitReport={local ? <ContaminationReport spec={dataset.sourceSpec} /> : undefined}trainFormat={node ? node.trainFormat : (dataset.trainFormat ?? "")}/></div>@@ -281,7 +275,7 @@ export function DatasetNotebook({return (<div className="relative flex h-full min-h-0 flex-col">- <div className="assistant-notices pointer-events-none absolute bottom-16 z-10 max-h-48 overflow-y-auto">+ <div className="pointer-events-none absolute bottom-4 left-1/2 z-10 max-h-48 w-[min(48rem,calc(100%-1.5rem))] -translate-x-1/2 overflow-y-auto"><div className="pointer-events-auto space-y-2 rounded-sm bg-card">{/* Mounted while idle too, so the first status is announced. */}<span className="sr-only" role="status">@@ -303,7 +297,6 @@ export function DatasetNotebook({</Button></div>)}- <ContaminationReport spec={dataset.sourceSpec} />{workbenchQuery.isError && (<Alert variant="destructive"><div className="flex flex-wrap items-center gap-2">@@ -364,14 +357,6 @@ export function DatasetNotebook({showMinimap={showMinimap}/>)}- <AssistantDock- assistant={assistant}- cells={cells}- datasetId={datasetId}- onSelectCell={scrollTo}- projectId={projectId}- selectedCell={selectedId}- /></div></div>);diff --git a/frontend/src/components/datasets/notebook/preparation.tsx b/frontend/src/components/datasets/notebook/preparation.tsxindex 959705f8..8eac16b9 100644--- a/frontend/src/components/datasets/notebook/preparation.tsx+++ b/frontend/src/components/datasets/notebook/preparation.tsx@@ -16,7 +16,7 @@ export function ContaminationReport({ spec }: { spec: unknown }) {)?.contamination_report;if (!report) return null;return (- <div aria-label="Data split" className="mb-2 mr-2 flex flex-wrap gap-2">+ <div aria-label="Data split" className="contents" role="group"><Field label="Train">{report.train_rows.toLocaleString()} rows</Field><Field label="Eval">{report.eval_rows.toLocaleString()} rows</Field><Field label="Duplicates removed">{report.duplicates_removed.toLocaleString()}</Field>diff --git a/frontend/src/components/experiments/experiment-panel.tsx b/frontend/src/components/experiments/experiment-panel.tsxnew file mode 100644index 00000000..c033fc46--- /dev/null+++ b/frontend/src/components/experiments/experiment-panel.tsx@@ -0,0 +1,105 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";++import apiClient from "@/client";+import { Button } from "@/components/ui/button";+import { Icon } from "@/components/ui/icons";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { invalidateExperiment } from "@/hooks/use-experiments";+import { notify } from "@/lib/notify";+import type { ExperimentDetail, Proposal } from "@/openapi";++const value = (raw: unknown) =>+ raw === null || raw === undefined+ ? "nothing"+ : typeof raw === "string"+ ? raw+ : JSON.stringify(raw);++/** The agent's change to settings a person chose: nothing changes until they apply it. */+export function ProposalCards({ detail }: { detail: ExperimentDetail }) {+ const qc = useQueryClient();+ const decide = useMutation({+ mutationFn: ({ proposal, apply }: { proposal: Proposal; apply: boolean }) =>+ apiClient.experiments.experimentsProposalsCreate({+ id: detail.id,+ proposalDecisionRequest: { apply },+ sequence: String(proposal.sequence),+ }),+ onError: (error) => notify.error(error, "The proposal could not be resolved"),+ onSettled: () => invalidateExperiment(qc, detail.id),+ });+ if (!detail.proposals.length) return null;+ return (+ <div className="pointer-events-none absolute inset-x-0 top-3 z-10 flex flex-col items-center gap-2 px-14">+ {detail.proposals.map((proposal) => (+ <section+ aria-label="The agent proposes a change"+ className="pointer-events-auto w-full max-w-lg space-y-2 rounded-md border border-border bg-card p-3 text-xs"+ key={proposal.sequence}+ >+ <p className="font-medium">The agent proposes a change to settings you chose</p>+ <ul className="space-y-1 text-muted-foreground">+ {proposal.changes.map((change) => (+ <li key={`${change.node}.${change.key}`}>+ <span className="text-foreground">{change.title}</span> · {change.key}:{" "}+ {change.beforeLabel ?? value(change.before)} →{" "}+ {change.afterLabel ?? value(change.after)}+ </li>+ ))}+ </ul>+ <div className="flex justify-end gap-2">+ <Button+ disabled={decide.isPending}+ onClick={() => decide.mutate({ apply: false, proposal })}+ size="xs"+ variant="secondary"+ >+ Dismiss+ </Button>+ <Button+ disabled={decide.isPending}+ onClick={() => decide.mutate({ apply: true, proposal })}+ size="xs"+ >+ Apply+ </Button>+ </div>+ </section>+ ))}+ </div>+ );+}++/** What the work cost as measured, the parts no record prices, and the agent's notes. */+export function NotesAndSpend({ detail }: { detail: ExperimentDetail }) {+ const { measuredUsd, unknown } = detail.spend;+ return (+ <Popover>+ <PopoverTrigger asChild>+ <Button aria-label="Notes and spend" size="icon-sm" variant="outline">+ <Icon.file />+ </Button>+ </PopoverTrigger>+ <PopoverContent+ align="end"+ className="flex max-h-[70vh] w-96 flex-col gap-3 overflow-y-auto p-3 text-xs"+ >+ <section className="space-y-1">+ <p className="font-medium">Spend</p>+ <p className="tabular-nums">${measuredUsd.toFixed(2)} measured</p>+ {unknown.length > 0 && (+ <p className="text-muted-foreground">Not measured: {unknown.join(", ")}</p>+ )}+ </section>+ <section className="space-y-1">+ <p className="font-medium">Agent notes</p>+ {detail.notes ? (+ <p className="whitespace-pre-wrap text-muted-foreground">{detail.notes}</p>+ ) : (+ <p className="text-muted-foreground">None</p>+ )}+ </section>+ </PopoverContent>+ </Popover>+ );+}diff --git a/frontend/src/components/experiments/flow.ts b/frontend/src/components/experiments/flow.tsindex 8a84089f..f3823166 100644--- a/frontend/src/components/experiments/flow.ts+++ b/frontend/src/components/experiments/flow.ts@@ -57,6 +57,7 @@ export const STAGE_ICONS: Record<string, (typeof Icon)[keyof typeof Icon]> = {stop_deployment: Icon.server,subflow: Icon.folder,suite: Icon.eval,+ system: Icon.terminal,trace_dataset: Icon.dataset,train: Icon.finetuning,transform: Icon.workshop,diff --git a/frontend/src/components/experiments/stage-card.tsx b/frontend/src/components/experiments/stage-card.tsxindex 308e1537..ea57d1c8 100644--- a/frontend/src/components/experiments/stage-card.tsx+++ b/frontend/src/components/experiments/stage-card.tsx@@ -61,6 +61,27 @@ function StatusText({);}+/** Your system waits for outputs: the command that sends them, run where its code lives. */+function SystemCommand({ stepId }: { stepId: string }) {+ const command = `overmind run --step ${stepId} --entry module:function`;+ return (+ <div className="space-y-1">+ <p className="text-muted-foreground">Waiting for your system. Run where its code lives:</p>+ <div className="flex items-start gap-1 rounded-sm bg-background p-1.5">+ <code className="min-w-0 flex-1 font-mono break-all">{command}</code>+ <Button+ aria-label="Copy command"+ onClick={() => void navigator.clipboard?.writeText(command).catch(() => undefined)}+ size="icon-xs"+ variant="ghost"+ >+ <Icon.copy />+ </Button>+ </div>+ </div>+ );+}+export function StageIcon({ node, kind }: { node: FlowNode; kind?: StageKind }) {const Glyph = STAGE_ICONS[node.kind] ?? Icon.code;return (@@ -236,6 +257,10 @@ export function StageCard({{!models.length && !others.length && !shown.length && !ownModel && !dataset && (<p className="text-muted-foreground">{kind?.description}</p>)}+ {(step?.receipts as { kind: string }[] | undefined)?.some(+ (receipt) => receipt.kind === "system_outputs"+ ) &&+ step && <SystemCommand stepId={step.id} />}{node.notes && <Notes text={node.notes} />}{step?.error && (<pdiff --git a/frontend/src/components/experiments/triggers.tsx b/frontend/src/components/experiments/triggers.tsxindex 3fb63099..ab53b7b7 100644--- a/frontend/src/components/experiments/triggers.tsx+++ b/frontend/src/components/experiments/triggers.tsx@@ -42,6 +42,7 @@ export function ExperimentTriggers({const [threshold, setThreshold] = useState(10);const [hours, setHours] = useState(24);const [sends, setSends] = useState(5);+ const [cap, setCap] = useState("");const add = useMutation({mutationFn: () =>apiClient.experiments.experimentsTriggersCreate({@@ -51,6 +52,7 @@ export function ExperimentTriggers({instruction,kind,maxSends: sends,+ maxSpendUsd: cap.trim() ? cap.trim() : undefined,threshold: kind === "failing_traces" ? threshold : null,},id: experimentId,@@ -95,6 +97,7 @@ export function ExperimentTriggers({</span><span className="block text-muted-foreground">{trigger.sends} of {trigger.maxSends} sent+ {trigger.maxSpendUsd && ` · stops at USD ${trigger.maxSpendUsd} measured`}{trigger.sends >= trigger.maxSends? " · ended": trigger.nextAt@@ -193,6 +196,15 @@ export function ExperimentTriggers({value={sends}/></Field>+ <Field label="Measured spend, at most (USD)">+ <Input+ aria-label="Measured spend, at most (USD)"+ inputMode="decimal"+ onChange={(event) => setCap(event.target.value)}+ placeholder="No cap"+ value={cap}+ />+ </Field></div>{failure && (<Alert variant="destructive">diff --git a/frontend/src/components/quickstart/home-quickstart.test.ts b/frontend/src/components/quickstart/home-quickstart.test.tsnew file mode 100644index 00000000..46410310--- /dev/null+++ b/frontend/src/components/quickstart/home-quickstart.test.ts@@ -0,0 +1,31 @@+// covers: home-setup+import { describe, expect, it } from "vitest";++import { quickstartStage } from "./home-quickstart";++const done = { dataset: true, deployed: true, evalSet: true, scanned: true, trained: true };+const loaded = { activityLoading: false, error: false, milestonesLoading: false };++describe("quickstartStage", () => {+ it("shows nothing until the setup answers, then one stage that stays", () => {+ expect(quickstartStage({ ...loaded, setup: undefined })).toBe("pending");+ // A finished setup never passes through the checklist on a reload.+ expect(quickstartStage({ ...loaded, activityLoading: true, setup: done })).toBe("pending");+ expect(quickstartStage({ ...loaded, setup: done })).toBe("suggestions");+ });++ it("shows the checklist while a step is left and the install prompt before a scan", () => {+ expect(quickstartStage({ ...loaded, setup: { ...done, trained: false } })).toBe("guide");+ const unscanned = { ...done, scanned: false };+ expect(quickstartStage({ ...loaded, milestonesLoading: true, setup: unscanned })).toBe(+ "pending"+ );+ expect(quickstartStage({ ...loaded, setup: unscanned })).toBe("install");+ });++ it("says the status is unavailable when the setup read fails", () => {+ expect(quickstartStage({ ...loaded, error: true, setup: undefined })).toBe("error");+ // A failed background poll keeps the stage already shown.+ expect(quickstartStage({ ...loaded, error: true, setup: done })).toBe("suggestions");+ });+});diff --git a/frontend/src/components/quickstart/home-quickstart.tsx b/frontend/src/components/quickstart/home-quickstart.tsxindex d06a6193..99ea31cb 100644--- a/frontend/src/components/quickstart/home-quickstart.tsx+++ b/frontend/src/components/quickstart/home-quickstart.tsx@@ -13,10 +13,9 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltipimport type { ComposerDraft } from "@/components/workspace/home-composer";import { config } from "@/config";import { useOnboardingMilestones } from "@/hooks/use-activity";-import { useProjectDatasetsQuery } from "@/hooks/use-datasets";import { onboardingPrompt } from "@/lib/mcp-setup";import { cn } from "@/lib/utils";-import type { Activity } from "@/openapi";+import type { Activity, ProjectSetup } from "@/openapi";const STEP_PROMPTS: Record<string, string> = {dataset: "Explore the attached data and help me prepare it for model training.",@@ -55,66 +54,35 @@ export function recentPrompts(activity: Pick<Activity, "assets">[]) {return prompts;}-/** Whether the project has at least one record of a kind. */-function useExists(projectId: string, key: string, fetch: () => Promise<{ count: number }>) {- return useQuery({- queryFn: async () => (await fetch()).count > 0,- queryKey: ["setup", key, projectId],- refetchInterval: 30_000,- });-}-function SetupGuide({- projectId,+ setup,onPrompt,}: {- projectId: string;+ setup: ProjectSetup;onPrompt: (draft: ComposerDraft) => void;}) {- const datasets = useProjectDatasetsQuery(projectId);- const evalSets = useExists(projectId, "eval-sets", () =>- apiClient.evalSets.evalSetsList({ pageSize: 1, project: projectId })- );- const training = useExists(projectId, "training", () =>- apiClient.finetuningJobs.finetuningJobsList({- pageSize: 1,- project: projectId,- status: "succeeded",- })- );- const inference = useExists(projectId, "inference", () =>- apiClient.deployedModels.deployedModelsList({- pageSize: 1,- project: projectId,- status: "ready",- })- );const steps = [{description: "Upload data to your project's dataset workspace.",- done: datasets.data?.some((dataset) => dataset.rows > 0),- error: datasets.isError,+ done: setup.dataset,id: "dataset",title: "Upload dataset",},{description: "Add datasets and graders to a saved eval set.",- done: evalSets.data,- error: evalSets.isError,+ done: setup.evalSet,id: "eval",title: "Create eval set",},{description: "Train a model on your dataset.",- done: training.data,- error: training.isError,+ done: setup.trained,id: "train",title: "Train model",},{description: "Deploy a model to an inference endpoint.",- done: inference.data,- error: inference.isError,+ done: setup.deployed,id: "deploy",title: "Deploy to inference",},@@ -122,10 +90,7 @@ function SetupGuide({const [selected, setSelected] = useState<string | null>(null);const [collapsed, setCollapsed] = useState(false);const completed = steps.filter((step) => step.done).length;- const known = steps.every((step) => step.done !== undefined && !step.error);const open = selected ?? steps.find((step) => !step.done)?.id;- if (known && completed === steps.length)- return <Suggestions onPrompt={onPrompt} projectId={projectId} />;return (<Card aria-label="Setup guide" className="p-2" role="region"><button@@ -136,7 +101,7 @@ function SetupGuide({><span>Finish setting up</span><span className="flex items-center gap-2 text-xs text-muted-foreground">- {known ? `${completed} of ${steps.length} complete` : "Checking progress"}+ {completed} of {steps.length} complete<Icon.chevronDownclassName={cn("size-3 transition-transform", !collapsed && "rotate-180")}/>@@ -145,7 +110,7 @@ function SetupGuide({<ProgressclassName="mb-2"label="Setup progress"- percent={known ? (completed / steps.length) * 100 : null}+ percent={(completed / steps.length) * 100}/>{!collapsed && (<ol className="overflow-hidden rounded-sm bg-wash-subtle">@@ -168,15 +133,7 @@ function SetupGuide({<span aria-hidden="true" className="size-4 rounded-sm border border-border" />)}<span className="flex-1">{step.title}</span>- <span className="text-muted-foreground">- {step.error- ? "Status unavailable"- : step.done === undefined- ? "Checking"- : step.done- ? "Complete"- : "To do"}- </span>+ <span className="text-muted-foreground">{step.done ? "Complete" : "To do"}</span></button>{expanded && (<div className="space-y-2 px-3 pb-3 pl-9">@@ -203,21 +160,15 @@ function SetupGuide({}function Suggestions({- projectId,+ activity,onPrompt,}: {- projectId: string;+ activity: Pick<Activity, "assets">[];onPrompt: (draft: ComposerDraft) => void;}) {- const activity = useQuery({- queryFn: () => apiClient.activity.activityList({ limit: ACTIVITY_EVENTS, project: projectId }),- queryKey: ["activity", "suggestions", projectId],- refetchInterval: 30_000,- staleTime: 30_000,- });return (<div aria-label="Suggested prompts" className="grid grid-cols-3 gap-2">- {recentPrompts(activity.data?.results ?? []).map((item) => (+ {recentPrompts(activity).map((item) => (<Tooltip key={item.prompt}><TooltipTrigger asChild><Button@@ -235,8 +186,30 @@ function Suggestions({);}+/** Which quickstart Home shows. Nothing until the setup and the stage's own data have+ * loaded: a stage that a later answer would replace is never shown. */+export function quickstartStage({+ setup,+ error,+ milestonesLoading,+ activityLoading,+}: {+ setup: ProjectSetup | undefined;+ error: boolean;+ milestonesLoading: boolean;+ activityLoading: boolean;+}): "error" | "pending" | "install" | "guide" | "suggestions" {+ // A failed poll keeps the stage the last answer chose.+ if (!setup) return error ? "error" : "pending";+ if (!setup.scanned) return milestonesLoading ? "pending" : "install";+ if (!(setup.dataset && setup.evalSet && setup.trained && setup.deployed)) return "guide";+ return activityLoading ? "pending" : "suggestions";+}+/** Below the Home composer: the install prompt until the repository is scanned, then the- * four-step setup guide, then prompts from recent activity. Each fills the composer. */+ * four-step setup guide, then prompts from recent activity. Each fills the composer.+ * The server decides which in one answer, and a stage shows only once the data it reads+ * has loaded, so a reload never shows a stage that a later answer replaces. */export function HomeQuickstart({projectId,onPrompt,@@ -244,22 +217,33 @@ export function HomeQuickstart({projectId: string;onPrompt: (draft: ComposerDraft) => void;}) {- const graph = useQuery({- queryFn: () => apiClient.agent.agentRetrieve({ project: projectId }),- queryKey: ["agent-graph", projectId],+ const project = useQuery({+ queryFn: () => apiClient.projectSetup.projectSetupRetrieve({ project: projectId }),+ queryKey: ["project-setup", projectId],refetchInterval: 30_000,});+ // Started with the setup, not after it: each stage's data loads in parallel.const milestones = useOnboardingMilestones(projectId, "agent");+ const activity = useQuery({+ queryFn: () => apiClient.activity.activityList({ limit: ACTIVITY_EVENTS, project: projectId }),+ queryKey: ["activity", "suggestions", projectId],+ refetchInterval: 30_000,+ staleTime: 30_000,+ });+ const stage = quickstartStage({+ activityLoading: activity.isLoading,+ error: project.isError,+ milestonesLoading: milestones.isLoading,+ setup: project.data,+ });+ if (stage === "error")+ return <p className="text-xs text-muted-foreground">Setup status unavailable</p>;+ if (stage === "pending") return null;+ if (stage === "guide" && project.data)+ return <SetupGuide onPrompt={onPrompt} setup={project.data} />;+ if (stage === "suggestions")+ return <Suggestions activity={activity.data?.results ?? []} onPrompt={onPrompt} />;const steps = milestones.data;- const scanned =- !!graph.data?.repositorySnapshot ||- !!graph.data?.lastSyncedAt ||- (graph.data?.capabilities.length ?? 0) > 0 ||- !!steps?.some((step) => step.kind === "repository_synced" && step.completedAt);- if (graph.isError)- return <p className="text-xs text-muted-foreground">Installation status unavailable</p>;- if (!graph.data) return null;- if (scanned) return <SetupGuide onPrompt={onPrompt} projectId={projectId} />;const completed = steps?.filter((step) => step.completedAt).length ?? 0;const next = steps?.find((step) => !step.completedAt);const last = steps?.filter((step) => step.completedAt).at(-1);diff --git a/frontend/src/components/workspace/home-composer.tsx b/frontend/src/components/workspace/home-composer.tsxindex 37f31c04..42ab3349 100644--- a/frontend/src/components/workspace/home-composer.tsx+++ b/frontend/src/components/workspace/home-composer.tsx@@ -271,6 +271,8 @@ export function HomeComposer({const locked = start.isPending;const attaching = resolving > 0;const tooMany = datasets.length + (ready.length ? 1 : 0) > MAX_DATASETS;+ // Data with no message lands in a new experiment without an agent turn.+ const empty = !text.trim() && !ready.length && !datasets.length;const sendHint = locked? landing? `Waiting for ${landing} to land`@@ -281,13 +283,17 @@ export function HomeComposer({? "Attaching": tooMany? `At most ${MAX_DATASETS} datasets`- : !text.trim()+ : empty? "No message"- : "Send";+ : text.trim()+ ? "Send"+ : "Add data";const submit = guard(() => {- if (locked || uploading || attaching || tooMany || !text.trim()) return;+ if (locked || uploading || attaching || tooMany || empty) return;// The name reads as typed; the message carries each mention's link.- const name = text.trim().split("\n")[0].slice(0, 120);+ const name =+ text.trim().split("\n")[0].slice(0, 120) ||+ (ready.length ? stripExtension(ready[0].file.name) : datasetDisplayName(datasets[0]));start.mutate({ message: serializeMentions(text, references).trim(), name },{@@ -436,7 +442,7 @@ export function HomeComposer({<span className="inline-flex"><Buttonaria-label="Send"- disabled={locked || uploading || attaching || tooMany || !text.trim()}+ disabled={locked || uploading || attaching || tooMany || empty}size="icon-sm"type="submit"variant="secondary"diff --git a/frontend/src/hooks/use-assistant-thread.test.tsx b/frontend/src/hooks/use-assistant-thread.test.tsxindex 6252fa88..8aa5a37a 100644--- a/frontend/src/hooks/use-assistant-thread.test.tsx+++ b/frontend/src/hooks/use-assistant-thread.test.tsx@@ -22,7 +22,7 @@ vi.mock("@/client", () => ({assistantThreadsEventsList: vi.fn(({ after }: { after: number }) =>Promise.resolve(held.filter((event) => event.sequence > after))),- assistantThreadsList: vi.fn(() => Promise.resolve([{ id: "thread" }])),+ assistantThreadsRetrieve: vi.fn(() => Promise.resolve({ id: "thread" })),},},}));@@ -31,12 +31,12 @@ const api = vi.mocked((await import("@/client")).default.assistantThreads);it("shows each event once when the page opens a conversation it read before", async () => {const client = new QueryClient();- client.setQueryData(["assistant-thread", "dataset"], { id: "thread" });+ client.setQueryData(["assistant-thread", "thread"], { id: "thread" });// Development mounts each effect twice, as a page opened again from the cache does.const wrapper = ({ children }: { children: ReactNode }) => (<QueryClientProvider client={client}>{children}</QueryClientProvider>);- const { result } = renderHook(() => useAssistantThread({ dataset: "dataset" }), {+ const { result } = renderHook(() => useAssistantThread("thread"), {reactStrictMode: true,wrapper,});@@ -47,17 +47,17 @@ it("shows each event once when the page opens a conversation it read before", asit("reads only the events it does not hold when the conversation opens again", async () => {const client = new QueryClient();- client.setQueryData(["assistant-thread", "dataset"], { id: "thread" });+ client.setQueryData(["assistant-thread", "thread"], { id: "thread" });const wrapper = ({ children }: { children: ReactNode }) => (<QueryClientProvider client={client}>{children}</QueryClientProvider>);- const first = renderHook(() => useAssistantThread({ dataset: "dataset" }), { wrapper });+ const first = renderHook(() => useAssistantThread("thread"), { wrapper });await waitFor(() => expect(first.result.current.events).toHaveLength(2));first.unmount();held.push({ kind: "status", payload: { state: "stopped" }, presentation: null, sequence: 3 });api.assistantThreadsEventsList.mockClear();- const again = renderHook(() => useAssistantThread({ dataset: "dataset" }), { wrapper });+ const again = renderHook(() => useAssistantThread("thread"), { wrapper });expect(again.result.current.events.map((event) => event.sequence)).toEqual([1, 2]);await waitFor(() => expect(again.result.current.events).toHaveLength(3));expect(api.assistantThreadsEventsList).toHaveBeenCalledWith({ after: 2, id: "thread" });diff --git a/frontend/src/hooks/use-assistant-thread.ts b/frontend/src/hooks/use-assistant-thread.tsindex 4a110947..a229ba55 100644--- a/frontend/src/hooks/use-assistant-thread.ts+++ b/frontend/src/hooks/use-assistant-thread.ts@@ -1,31 +1,12 @@import { useCallback, useEffect } from "react";-import { type QueryClient, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import apiClient from "@/client";import type { AssistantEvent, Draft } from "@/components/assistant/types";-import type { AssistantThread, ChangeMessageRequest, SendMessageRequest } from "@/openapi";+import type { ChangeMessageRequest, SendMessageRequest } from "@/openapi";-const threadKey = (datasetId: string) => ["assistant-thread", datasetId];--/** Queues one message on the dataset's conversation, which is opened on first use. */-export async function sendToDataset(- qc: QueryClient,- datasetId: string,- message: SendMessageRequest-) {- const key = threadKey(datasetId);- const thread =- qc.getQueryData<AssistantThread | null>(key) ??- (await apiClient.assistantThreads.assistantThreadsCreate({- openThreadRequest: { dataset: datasetId },- }));- qc.setQueryData(key, thread);- await apiClient.assistantThreads.assistantThreadsMessagesCreate({- id: thread.id,- sendMessageRequest: message,- });-}+const threadKey = (threadId: string) => ["assistant-thread", threadId];/** The conversation's events as the page holds them. The log only grows and its sequence* numbers only rise, so adding a read keeps every event once, whatever order or how@@ -37,8 +18,8 @@ export function mergeEvents(held: AssistantEvent[], added: AssistantEvent[]) {}const NO_EVENTS: AssistantEvent[] = [];-const eventsKey = (threadId: string | undefined) => ["assistant-events", threadId];-const draftKey = (threadId: string | undefined) => ["assistant-draft", threadId];+const eventsKey = (threadId: string) => ["assistant-events", threadId];+const draftKey = (threadId: string) => ["assistant-draft", threadId];/** What a conversation's live channel says: the thread changed, or the reply grew. */export type AssistantStreamEvent =@@ -47,38 +28,26 @@ export type AssistantStreamEvent =| { type: "assistant.draft"; added: string; at: number; steps: string[] }| { type: string };-/** A conversation: about a dataset, opened on first use, or an experiment's own thread. */-export type AssistantSubject = { dataset: string } | { thread: string };-/** The conversation: its thread, its events and the reply being written. The page's one* event stream announces changes, and ``handle`` applies them. Events and the reply live in* the query cache under the thread, so a page that opens again, mounts twice or reconnects* reads only what it does not hold. */-export function useAssistantThread(subject: AssistantSubject) {+export function useAssistantThread(threadId: string) {const qc = useQueryClient();- const datasetId = "dataset" in subject ? subject.dataset : undefined;- const subjectKey = datasetId ?? ("thread" in subject ? subject.thread : "");const found = useQuery({- queryFn: async () =>- "thread" in subject- ? await apiClient.assistantThreads.assistantThreadsRetrieve({ id: subject.thread })- : ((- await apiClient.assistantThreads.assistantThreadsList({ dataset: subject.dataset })- )[0] ?? null),- queryKey: threadKey(subjectKey),+ queryFn: () => apiClient.assistantThreads.assistantThreadsRetrieve({ id: threadId }),+ queryKey: threadKey(threadId),});const thread = found.data ?? null;- const threadId = thread?.id;// The cache keeps one read per thread; a signal during a read starts it again from the// newest event held.const log = useQuery({- enabled: !!threadId,queryFn: async () => {const held = qc.getQueryData<AssistantEvent[]>(eventsKey(threadId)) ?? [];const added = (await apiClient.assistantThreads.assistantThreadsEventsList({after: held.at(-1)?.sequence ?? 0,- id: threadId!,+ id: threadId,})) as unknown as AssistantEvent[];// A reply or a status ends the text being written. A first read holds the earlier// replies too; the thread's own state settles the reply in progress then.@@ -95,7 +64,6 @@ export function useAssistantThread(subject: AssistantSubject) {// The server's text of the reply being written; a thread that rests writes none.const written = thread?.state === "running" ? thread.draft || null : null;useEffect(() => {- if (!threadId) return;qc.setQueryData<Draft | null>(draftKey(threadId), (old) =>written === null? null@@ -114,13 +82,12 @@ export function useAssistantThread(subject: AssistantSubject) {const handle = useCallback((event: AssistantStreamEvent) => {if (event.type === "assistant" || event.type === "connected") {- void qc.invalidateQueries({ queryKey: threadKey(subjectKey) });+ void qc.invalidateQueries({ queryKey: threadKey(threadId) });// A read in flight may have missed the change: start another after the newest held.- if (threadId)- void qc- .cancelQueries({ queryKey: eventsKey(threadId) })- .then(() => qc.refetchQueries({ queryKey: eventsKey(threadId) }));- } else if (event.type === "assistant.draft" && "added" in event && threadId) {+ void qc+ .cancelQueries({ queryKey: eventsKey(threadId) })+ .then(() => qc.refetchQueries({ queryKey: eventsKey(threadId) }));+ } else if (event.type === "assistant.draft" && "added" in event) {// A gain names its position in code points, as the server counts: one the text// already holds, as a snapshot read ahead of it may, changes nothing.qc.setQueryData<Draft | null>(draftKey(threadId), (old) => {@@ -132,28 +99,24 @@ export function useAssistantThread(subject: AssistantSubject) {});}},- [qc, subjectKey, threadId]+ [qc, threadId]);- // An experiment's thread is known before its read returns, so a send then still lands.- const sendTo = "thread" in subject ? subject.thread : threadId;const send = useMutation({- mutationFn: async (message: SendMessageRequest) => {- if (datasetId) return sendToDataset(qc, datasetId, message);- await apiClient.assistantThreads.assistantThreadsMessagesCreate({- id: sendTo!,+ mutationFn: (message: SendMessageRequest) =>+ apiClient.assistantThreads.assistantThreadsMessagesCreate({+ id: threadId,sendMessageRequest: message,- });- },+ }),});const stop = useMutation({- mutationFn: () => apiClient.assistantThreads.assistantThreadsStopCreate({ id: sendTo! }),+ mutationFn: () => apiClient.assistantThreads.assistantThreadsStopCreate({ id: threadId }),});const changeQueued = useMutation({mutationFn: (change: ChangeMessageRequest) =>apiClient.assistantThreads.assistantThreadsQueueCreate({changeMessageRequest: change,- id: sendTo!,+ id: threadId,}),});diff --git a/frontend/src/hooks/use-datasets.ts b/frontend/src/hooks/use-datasets.tsindex 479a3fd3..538a9be8 100644--- a/frontend/src/hooks/use-datasets.ts+++ b/frontend/src/hooks/use-datasets.ts@@ -367,8 +367,6 @@ export interface CreateDatasetInput {intent?: Intent;capabilityId?: string | null;source?: SourceRequest;- /** Queue the assistant's first pass, which starts once the source lands. */- prepare?: boolean;}export function useCreateDatasetMutation() {@@ -381,7 +379,6 @@ export function useCreateDatasetMutation() {capability: input.capabilityId,intent: input.intent,name: input.name,- prepare: input.prepare,project: input.projectId,source: input.source,},@@ -403,7 +400,6 @@ export interface CreateDatasetSplitInput {groupBy?: string[];stratifyBy?: string;deduplicate?: boolean;- prepare?: boolean;}/** One source landed as `<name> train` and `<name> eval`. */@@ -420,7 +416,6 @@ export function useCreateDatasetSplitMutation() {groupBy: input.groupBy,name: input.name,position: input.position,- prepare: input.prepare,project: input.projectId,source: input.source,stratifyBy: input.stratifyBy,diff --git a/frontend/src/lib/schemas.test.ts b/frontend/src/lib/schemas.test.tsindex 228def04..f155188d 100644--- a/frontend/src/lib/schemas.test.ts+++ b/frontend/src/lib/schemas.test.ts@@ -120,11 +120,6 @@ describe("schemas", () => {});describe("datasetsSearchSchema", () => {- it("accepts the create deep-link param", () => {- const result = datasetsSearchSchema.parse({ create: true, ds_capability: "capability-1" });- expect(result.create).toBe(true);- expect(result.ds_capability).toBe("capability-1");- });it("round-trips every filter a shared datasets link carries", () => {const result = datasetsSearchSchema.parse({ds_capability: "capability-1",diff --git a/frontend/src/lib/schemas.ts b/frontend/src/lib/schemas.tsindex 3b3a12ef..6b2f6c4b 100644--- a/frontend/src/lib/schemas.ts+++ b/frontend/src/lib/schemas.ts@@ -135,10 +135,6 @@ export type TrainingSearch = z.infer<typeof trainingSearchSchema>;* of the search, `projectId` included.*/export const datasetsSearchSchema = projectIdSearchSchema.extend({- /** Opens the create-dataset dialog on land. The palette sends it as a string. */- create: z- .union([z.boolean(), z.enum(["true", "false"]).transform((v) => v === "true")])- .optional(),/** A capability id, or the `NO_CAPABILITY` sentinel for datasets attached to none. */ds_capability: z.string().optional().default("all"),ds_role: zdiff --git a/frontend/src/openapi/.openapi-generator/FILES b/frontend/src/openapi/.openapi-generator/FILESindex e40bda49..92229644 100644--- a/frontend/src/openapi/.openapi-generator/FILES+++ b/frontend/src/openapi/.openapi-generator/FILES@@ -22,6 +22,7 @@ apis/EvalRunsApi.tsapis/EvalScoresApi.tsapis/EvalSetsApi.tsapis/ExperimentRunsApi.ts+apis/ExperimentStepsApi.tsapis/ExperimentsApi.tsapis/FeedbackApi.tsapis/FinetuningJobsApi.ts@@ -30,6 +31,7 @@ apis/InferenceRequestsApi.tsapis/McpOauthApi.tsapis/ModelsApi.tsapis/NativeEvaluationsApi.ts+apis/ProjectSetupApi.tsapis/ProjectsApi.tsapis/PublicApi.tsapis/SessionsApi.ts@@ -212,6 +214,7 @@ models/ExperimentCandidateRequest.tsmodels/ExperimentCreateRequest.tsmodels/ExperimentDetail.tsmodels/ExperimentLaunchRequest.ts+models/ExperimentLink.tsmodels/ExperimentPlan.tsmodels/ExperimentPlanEntry.tsmodels/ExperimentProblem.ts@@ -309,7 +312,6 @@ models/NativeMonitor.tsmodels/NativeSample.tsmodels/NativeSamplePrediction.tsmodels/OnboardingMilestone.ts-models/OpenThreadRequest.tsmodels/OpenrouterStatusEnum.tsmodels/OutputEnum.tsmodels/OverallComparison.ts@@ -381,7 +383,11 @@ models/ProjectMember.tsmodels/ProjectMembershipCreateRequest.tsmodels/ProjectRequest.tsmodels/ProjectSavePipelineRequest.ts+models/ProjectSetup.tsmodels/Prompt.ts+models/Proposal.ts+models/ProposalChange.ts+models/ProposalDecisionRequest.tsmodels/ProvenanceEnum.tsmodels/ProviderEnum.tsmodels/PublicLibraryFilterOption.ts@@ -422,6 +428,7 @@ models/SignalTypeEnum.tsmodels/SourceEnum.tsmodels/SourceRequest.tsmodels/Span.ts+models/Spend.tsmodels/SplitMethod3daEnum.tsmodels/SplitMethodE87Enum.tsmodels/SplitPositionEnum.ts@@ -433,6 +440,11 @@ models/Stratum.tsmodels/SyncSnapshot.tsmodels/SyncSnapshotRequest.tsmodels/SyncStatusEnum.ts+models/SystemImport.ts+models/SystemOutputRequest.ts+models/SystemOutputsRequest.ts+models/SystemRepositoryRequest.ts+models/SystemRows.tsmodels/TaskTypeSourceEnum.tsmodels/TiersEnum.tsmodels/TokenObtainPair.tsdiff --git a/frontend/src/openapi/apis/AssistantThreadsApi.ts b/frontend/src/openapi/apis/AssistantThreadsApi.tsindex d3af454e..1e03d039 100644--- a/frontend/src/openapi/apis/AssistantThreadsApi.ts+++ b/frontend/src/openapi/apis/AssistantThreadsApi.ts@@ -19,7 +19,6 @@ import type {AssistantInput,AssistantThread,ChangeMessageRequest,- OpenThreadRequest,SendMessageRequest,} from '../models/index';import {@@ -31,16 +30,10 @@ import {AssistantThreadToJSON,ChangeMessageRequestFromJSON,ChangeMessageRequestToJSON,- OpenThreadRequestFromJSON,- OpenThreadRequestToJSON,SendMessageRequestFromJSON,SendMessageRequestToJSON,} from '../models/index';-export interface AssistantThreadsCreateRequest {- openThreadRequest: OpenThreadRequest;-}-export interface AssistantThreadsEventsListRequest {id: string;after?: number;@@ -51,10 +44,6 @@ export interface AssistantThreadsImagesRetrieveRequest {name: string;}-export interface AssistantThreadsListRequest {- dataset: string;-}-export interface AssistantThreadsMessagesCreateRequest {id: string;sendMessageRequest: SendMessageRequest;@@ -78,65 +67,6 @@ export interface AssistantThreadsStopCreateRequest {*/export class AssistantThreadsApi extends runtime.BaseAPI {- /**- * Open the dataset\'s conversation.- */- async assistantThreadsCreateRaw(requestParameters: AssistantThreadsCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<AssistantThread>> {- if (requestParameters['openThreadRequest'] == null) {- throw new runtime.RequiredError(- 'openThreadRequest',- 'Required parameter "openThreadRequest" was null or undefined when calling assistantThreadsCreate().'- );- }-- const queryParameters: any = {};-- const headerParameters: runtime.HTTPHeaders = {};-- headerParameters['Content-Type'] = 'application/json';-- if (this.configuration && this.configuration.accessToken) {- const token = this.configuration.accessToken;- const tokenString = await token("ClerkBearerAuth", []);-- if (tokenString) {- headerParameters["Authorization"] = `Bearer ${tokenString}`;- }- }- if (this.configuration && this.configuration.apiKey) {- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication- }-- if (this.configuration && this.configuration.accessToken) {- const token = this.configuration.accessToken;- const tokenString = await token("BearerAuth", []);-- if (tokenString) {- headerParameters["Authorization"] = `Bearer ${tokenString}`;- }- }-- let urlPath = `/api/assistant-threads/`;-- const response = await this.request({- path: urlPath,- method: 'POST',- headers: headerParameters,- query: queryParameters,- body: OpenThreadRequestToJSON(requestParameters['openThreadRequest']),- }, initOverrides);-- return new runtime.JSONApiResponse(response, (jsonValue) => AssistantThreadFromJSON(jsonValue));- }-- /**- * Open the dataset\'s conversation.- */- async assistantThreadsCreate(requestParameters: AssistantThreadsCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<AssistantThread> {- const response = await this.assistantThreadsCreateRaw(requestParameters, initOverrides);- return await response.value();- }-/*** The events after a cursor, as the Console shows them.*/@@ -264,67 +194,7 @@ export class AssistantThreadsApi extends runtime.BaseAPI {}/**- * The dataset\'s conversation, if it has one.- */- async assistantThreadsListRaw(requestParameters: AssistantThreadsListRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<Array<AssistantThread>>> {- if (requestParameters['dataset'] == null) {- throw new runtime.RequiredError(- 'dataset',- 'Required parameter "dataset" was null or undefined when calling assistantThreadsList().'- );- }-- const queryParameters: any = {};-- if (requestParameters['dataset'] != null) {- queryParameters['dataset'] = requestParameters['dataset'];- }-- const headerParameters: runtime.HTTPHeaders = {};-- if (this.configuration && this.configuration.accessToken) {- const token = this.configuration.accessToken;- const tokenString = await token("ClerkBearerAuth", []);-- if (tokenString) {- headerParameters["Authorization"] = `Bearer ${tokenString}`;- }- }- if (this.configuration && this.configuration.apiKey) {- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication- }-- if (this.configuration && this.configuration.accessToken) {- const token = this.configuration.accessToken;- const tokenString = await token("BearerAuth", []);-- if (tokenString) {- headerParameters["Authorization"] = `Bearer ${tokenString}`;- }- }-- let urlPath = `/api/assistant-threads/`;-- const response = await this.request({- path: urlPath,- method: 'GET',- headers: headerParameters,- query: queryParameters,- }, initOverrides);-- return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(AssistantThreadFromJSON));- }-- /**- * The dataset\'s conversation, if it has one.- */- async assistantThreadsList(requestParameters: AssistantThreadsListRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<Array<AssistantThread>> {- const response = await this.assistantThreadsListRaw(requestParameters, initOverrides);- return await response.value();- }-- /**- * The conversation about a dataset. Changes are announced on the dataset\'s event stream; a page reads them here.+ * An experiment\'s conversation. Changes are announced on the experiment\'s event stream; a page reads them here.*/async assistantThreadsMessagesCreateRaw(requestParameters: AssistantThreadsMessagesCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<AssistantInput>> {if (requestParameters['id'] == null) {@@ -383,7 +253,7 @@ export class AssistantThreadsApi extends runtime.BaseAPI {}/**- * The conversation about a dataset. Changes are announced on the dataset\'s event stream; a page reads them here.+ * An experiment\'s conversation. Changes are announced on the experiment\'s event stream; a page reads them here.*/async assistantThreadsMessagesCreate(requestParameters: AssistantThreadsMessagesCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<AssistantInput> {const response = await this.assistantThreadsMessagesCreateRaw(requestParameters, initOverrides);@@ -458,7 +328,7 @@ export class AssistantThreadsApi extends runtime.BaseAPI {}/**- * The conversation about a dataset. Changes are announced on the dataset\'s event stream; a page reads them here.+ * An experiment\'s conversation. Changes are announced on the experiment\'s event stream; a page reads them here.*/async assistantThreadsRetrieveRaw(requestParameters: AssistantThreadsRetrieveRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<AssistantThread>> {if (requestParameters['id'] == null) {@@ -507,7 +377,7 @@ export class AssistantThreadsApi extends runtime.BaseAPI {}/**- * The conversation about a dataset. Changes are announced on the dataset\'s event stream; a page reads them here.+ * An experiment\'s conversation. Changes are announced on the experiment\'s event stream; a page reads them here.*/async assistantThreadsRetrieve(requestParameters: AssistantThreadsRetrieveRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<AssistantThread> {const response = await this.assistantThreadsRetrieveRaw(requestParameters, initOverrides);@@ -515,7 +385,7 @@ export class AssistantThreadsApi extends runtime.BaseAPI {}/**- * The conversation about a dataset. Changes are announced on the dataset\'s event stream; a page reads them here.+ * An experiment\'s conversation. Changes are announced on the experiment\'s event stream; a page reads them here.*/async assistantThreadsStopCreateRaw(requestParameters: AssistantThreadsStopCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<AssistantThread>> {if (requestParameters['id'] == null) {@@ -564,7 +434,7 @@ export class AssistantThreadsApi extends runtime.BaseAPI {}/**- * The conversation about a dataset. Changes are announced on the dataset\'s event stream; a page reads them here.+ * An experiment\'s conversation. Changes are announced on the experiment\'s event stream; a page reads them here.*/async assistantThreadsStopCreate(requestParameters: AssistantThreadsStopCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<AssistantThread> {const response = await this.assistantThreadsStopCreateRaw(requestParameters, initOverrides);diff --git a/frontend/src/openapi/apis/ExperimentStepsApi.ts b/frontend/src/openapi/apis/ExperimentStepsApi.tsnew file mode 100644index 00000000..61aa35f9--- /dev/null+++ b/frontend/src/openapi/apis/ExperimentStepsApi.ts@@ -0,0 +1,169 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */+++import * as runtime from '../runtime';+import type {+ SystemImport,+ SystemOutputsRequest,+ SystemRows,+} from '../models/index';+import {+ SystemImportFromJSON,+ SystemImportToJSON,+ SystemOutputsRequestFromJSON,+ SystemOutputsRequestToJSON,+ SystemRowsFromJSON,+ SystemRowsToJSON,+} from '../models/index';++export interface ExperimentStepsOutputsCreateRequest {+ id: string;+ systemOutputsRequest: SystemOutputsRequest;+}++export interface ExperimentStepsRowsRetrieveRequest {+ id: string;+}++/**+ *+ */+export class ExperimentStepsApi extends runtime.BaseAPI {++ /**+ * A Your-system stage: its rows for ``overmind run``, and the outputs it returns.+ */+ async experimentStepsOutputsCreateRaw(requestParameters: ExperimentStepsOutputsCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<SystemImport>> {+ if (requestParameters['id'] == null) {+ throw new runtime.RequiredError(+ 'id',+ 'Required parameter "id" was null or undefined when calling experimentStepsOutputsCreate().'+ );+ }++ if (requestParameters['systemOutputsRequest'] == null) {+ throw new runtime.RequiredError(+ 'systemOutputsRequest',+ 'Required parameter "systemOutputsRequest" was null or undefined when calling experimentStepsOutputsCreate().'+ );+ }++ const queryParameters: any = {};++ const headerParameters: runtime.HTTPHeaders = {};++ headerParameters['Content-Type'] = 'application/json';++ if (this.configuration && this.configuration.accessToken) {+ const token = this.configuration.accessToken;+ const tokenString = await token("ClerkBearerAuth", []);++ if (tokenString) {+ headerParameters["Authorization"] = `Bearer ${tokenString}`;+ }+ }+ if (this.configuration && this.configuration.apiKey) {+ headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication+ }++ if (this.configuration && this.configuration.accessToken) {+ const token = this.configuration.accessToken;+ const tokenString = await token("BearerAuth", []);++ if (tokenString) {+ headerParameters["Authorization"] = `Bearer ${tokenString}`;+ }+ }++ let urlPath = `/api/experiment-steps/{id}/outputs/`;+ urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));++ const response = await this.request({+ path: urlPath,+ method: 'POST',+ headers: headerParameters,+ query: queryParameters,+ body: SystemOutputsRequestToJSON(requestParameters['systemOutputsRequest']),+ }, initOverrides);++ return new runtime.JSONApiResponse(response, (jsonValue) => SystemImportFromJSON(jsonValue));+ }++ /**+ * A Your-system stage: its rows for ``overmind run``, and the outputs it returns.+ */+ async experimentStepsOutputsCreate(requestParameters: ExperimentStepsOutputsCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<SystemImport> {+ const response = await this.experimentStepsOutputsCreateRaw(requestParameters, initOverrides);+ return await response.value();+ }++ /**+ * A Your-system stage: its rows for ``overmind run``, and the outputs it returns.+ */+ async experimentStepsRowsRetrieveRaw(requestParameters: ExperimentStepsRowsRetrieveRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<SystemRows>> {+ if (requestParameters['id'] == null) {+ throw new runtime.RequiredError(+ 'id',+ 'Required parameter "id" was null or undefined when calling experimentStepsRowsRetrieve().'+ );+ }++ const queryParameters: any = {};++ const headerParameters: runtime.HTTPHeaders = {};++ if (this.configuration && this.configuration.accessToken) {+ const token = this.configuration.accessToken;+ const tokenString = await token("ClerkBearerAuth", []);++ if (tokenString) {+ headerParameters["Authorization"] = `Bearer ${tokenString}`;+ }+ }+ if (this.configuration && this.configuration.apiKey) {+ headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication+ }++ if (this.configuration && this.configuration.accessToken) {+ const token = this.configuration.accessToken;+ const tokenString = await token("BearerAuth", []);++ if (tokenString) {+ headerParameters["Authorization"] = `Bearer ${tokenString}`;+ }+ }++ let urlPath = `/api/experiment-steps/{id}/rows/`;+ urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));++ const response = await this.request({+ path: urlPath,+ method: 'GET',+ headers: headerParameters,+ query: queryParameters,+ }, initOverrides);++ return new runtime.JSONApiResponse(response, (jsonValue) => SystemRowsFromJSON(jsonValue));+ }++ /**+ * A Your-system stage: its rows for ``overmind run``, and the outputs it returns.+ */+ async experimentStepsRowsRetrieve(requestParameters: ExperimentStepsRowsRetrieveRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<SystemRows> {+ const response = await this.experimentStepsRowsRetrieveRaw(requestParameters, initOverrides);+ return await response.value();+ }++}diff --git a/frontend/src/openapi/apis/ExperimentsApi.ts b/frontend/src/openapi/apis/ExperimentsApi.tsindex 707f83ee..c449fae5 100644--- a/frontend/src/openapi/apis/ExperimentsApi.ts+++ b/frontend/src/openapi/apis/ExperimentsApi.ts@@ -26,6 +26,7 @@ import type {ExperimentTrigger,ExperimentTriggerInputRequest,PatchedExperimentRenameRequest,+ ProposalDecisionRequest,StageKind,} from '../models/index';import {@@ -51,6 +52,8 @@ import {ExperimentTriggerInputRequestToJSON,PatchedExperimentRenameRequestFromJSON,PatchedExperimentRenameRequestToJSON,+ ProposalDecisionRequestFromJSON,+ ProposalDecisionRequestToJSON,StageKindFromJSON,StageKindToJSON,} from '../models/index';@@ -79,6 +82,12 @@ export interface ExperimentsPlanCreateRequest {experimentRunOptionsRequest?: ExperimentRunOptionsRequest;}+export interface ExperimentsProposalsCreateRequest {+ id: string;+ sequence: string;+ proposalDecisionRequest: ProposalDecisionRequest;+}+export interface ExperimentsRetrieveRequest {id: string;revision?: number;@@ -466,6 +475,81 @@ export class ExperimentsApi extends runtime.BaseAPI {return await response.value();}+ /**+ * Apply the agent\'s proposal as your own revision, or dismiss it.+ */+ async experimentsProposalsCreateRaw(requestParameters: ExperimentsProposalsCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<ExperimentDetail>> {+ if (requestParameters['id'] == null) {+ throw new runtime.RequiredError(+ 'id',+ 'Required parameter "id" was null or undefined when calling experimentsProposalsCreate().'+ );+ }++ if (requestParameters['sequence'] == null) {+ throw new runtime.RequiredError(+ 'sequence',+ 'Required parameter "sequence" was null or undefined when calling experimentsProposalsCreate().'+ );+ }++ if (requestParameters['proposalDecisionRequest'] == null) {+ throw new runtime.RequiredError(+ 'proposalDecisionRequest',+ 'Required parameter "proposalDecisionRequest" was null or undefined when calling experimentsProposalsCreate().'+ );+ }++ const queryParameters: any = {};++ const headerParameters: runtime.HTTPHeaders = {};++ headerParameters['Content-Type'] = 'application/json';++ if (this.configuration && this.configuration.accessToken) {+ const token = this.configuration.accessToken;+ const tokenString = await token("ClerkBearerAuth", []);++ if (tokenString) {+ headerParameters["Authorization"] = `Bearer ${tokenString}`;+ }+ }+ if (this.configuration && this.configuration.apiKey) {+ headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication+ }++ if (this.configuration && this.configuration.accessToken) {+ const token = this.configuration.accessToken;+ const tokenString = await token("BearerAuth", []);++ if (tokenString) {+ headerParameters["Authorization"] = `Bearer ${tokenString}`;+ }+ }++ let urlPath = `/api/experiments/{id}/proposals/{sequence}/`;+ urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));+ urlPath = urlPath.replace(`{${"sequence"}}`, encodeURIComponent(String(requestParameters['sequence'])));++ const response = await this.request({+ path: urlPath,+ method: 'POST',+ headers: headerParameters,+ query: queryParameters,+ body: ProposalDecisionRequestToJSON(requestParameters['proposalDecisionRequest']),+ }, initOverrides);++ return new runtime.JSONApiResponse(response, (jsonValue) => ExperimentDetailFromJSON(jsonValue));+ }++ /**+ * Apply the agent\'s proposal as your own revision, or dismiss it.+ */+ async experimentsProposalsCreate(requestParameters: ExperimentsProposalsCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<ExperimentDetail> {+ const response = await this.experimentsProposalsCreateRaw(requestParameters, initOverrides);+ return await response.value();+ }+/*** Experiments: saved flows of stages, their runs, triggers and live channel. The conversation is an assistant thread (``thread``).*/diff --git a/frontend/src/openapi/apis/ProjectSetupApi.ts b/frontend/src/openapi/apis/ProjectSetupApi.tsnew file mode 100644index 00000000..b1ed3a26--- /dev/null+++ b/frontend/src/openapi/apis/ProjectSetupApi.ts@@ -0,0 +1,94 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */+++import * as runtime from '../runtime';+import type {+ ProjectSetup,+} from '../models/index';+import {+ ProjectSetupFromJSON,+ ProjectSetupToJSON,+} from '../models/index';++export interface ProjectSetupRetrieveRequest {+ project: string;+}++/**+ *+ */+export class ProjectSetupApi extends runtime.BaseAPI {++ /**+ * Get the project\'s setup stage for Home+ */+ async projectSetupRetrieveRaw(requestParameters: ProjectSetupRetrieveRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<ProjectSetup>> {+ if (requestParameters['project'] == null) {+ throw new runtime.RequiredError(+ 'project',+ 'Required parameter "project" was null or undefined when calling projectSetupRetrieve().'+ );+ }++ const queryParameters: any = {};++ if (requestParameters['project'] != null) {+ queryParameters['project'] = requestParameters['project'];+ }++ const headerParameters: runtime.HTTPHeaders = {};++ if (this.configuration && this.configuration.accessToken) {+ const token = this.configuration.accessToken;+ const tokenString = await token("ClerkBearerAuth", []);++ if (tokenString) {+ headerParameters["Authorization"] = `Bearer ${tokenString}`;+ }+ }+ if (this.configuration && this.configuration.apiKey) {+ headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication+ }++ if (this.configuration && this.configuration.accessToken) {+ const token = this.configuration.accessToken;+ const tokenString = await token("BearerAuth", []);++ if (tokenString) {+ headerParameters["Authorization"] = `Bearer ${tokenString}`;+ }+ }++ let urlPath = `/api/project-setup/`;++ const response = await this.request({+ path: urlPath,+ method: 'GET',+ headers: headerParameters,+ query: queryParameters,+ }, initOverrides);++ return new runtime.JSONApiResponse(response, (jsonValue) => ProjectSetupFromJSON(jsonValue));+ }++ /**+ * Get the project\'s setup stage for Home+ */+ async projectSetupRetrieve(requestParameters: ProjectSetupRetrieveRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<ProjectSetup> {+ const response = await this.projectSetupRetrieveRaw(requestParameters, initOverrides);+ return await response.value();+ }++}diff --git a/frontend/src/openapi/apis/index.ts b/frontend/src/openapi/apis/index.tsindex 930acb82..bf135178 100644--- a/frontend/src/openapi/apis/index.ts+++ b/frontend/src/openapi/apis/index.ts@@ -24,6 +24,7 @@ export * from './EvalRunsApi';export * from './EvalScoresApi';export * from './EvalSetsApi';export * from './ExperimentRunsApi';+export * from './ExperimentStepsApi';export * from './ExperimentsApi';export * from './FeedbackApi';export * from './FinetuningJobsApi';@@ -32,6 +33,7 @@ export * from './InferenceRequestsApi';export * from './McpOauthApi';export * from './ModelsApi';export * from './NativeEvaluationsApi';+export * from './ProjectSetupApi';export * from './ProjectsApi';export * from './PublicApi';export * from './SessionsApi';diff --git a/frontend/src/openapi/models/AssistantThread.ts b/frontend/src/openapi/models/AssistantThread.tsindex b855deb3..da3e3536 100644--- a/frontend/src/openapi/models/AssistantThread.ts+++ b/frontend/src/openapi/models/AssistantThread.ts@@ -58,7 +58,7 @@ export interface AssistantThread {* @type {string}* @memberof AssistantThread*/- readonly dataset: string | null;+ readonly experiment: string | null;/**** @type {AssistantThreadStateEnum}@@ -99,7 +99,7 @@ export interface AssistantThread {export function instanceOfAssistantThread(value: object): value is AssistantThread {if (!('id' in value) || value['id'] === undefined) return false;if (!('project' in value) || value['project'] === undefined) return false;- if (!('dataset' in value) || value['dataset'] === undefined) return false;+ if (!('experiment' in value) || value['experiment'] === undefined) return false;if (!('state' in value) || value['state'] === undefined) return false;if (!('stopRequested' in value) || value['stopRequested'] === undefined) return false;if (!('queue' in value) || value['queue'] === undefined) return false;@@ -120,7 +120,7 @@ export function AssistantThreadFromJSONTyped(json: any, ignoreDiscriminator: boo'id': json['id'],'project': json['project'],- 'dataset': json['dataset'],+ 'experiment': json['experiment'],'state': AssistantThreadStateEnumFromJSON(json['state']),'stopRequested': json['stop_requested'],'queue': ((json['queue'] as Array<any>).map(AssistantInputFromJSON)),@@ -133,7 +133,7 @@ export function AssistantThreadToJSON(json: any): AssistantThread {return AssistantThreadToJSONTyped(json, false);}-export function AssistantThreadToJSONTyped(value?: Omit<AssistantThread, 'id'|'project'|'dataset'|'state'|'stop_requested'|'queue'|'participants'|'draft'> | null, ignoreDiscriminator: boolean = false): any {+export function AssistantThreadToJSONTyped(value?: Omit<AssistantThread, 'id'|'project'|'experiment'|'state'|'stop_requested'|'queue'|'participants'|'draft'> | null, ignoreDiscriminator: boolean = false): any {if (value == null) {return value;}diff --git a/frontend/src/openapi/models/Dataset.ts b/frontend/src/openapi/models/Dataset.tsindex 09c9d044..935a98b7 100644--- a/frontend/src/openapi/models/Dataset.ts+++ b/frontend/src/openapi/models/Dataset.ts@@ -48,6 +48,13 @@ import {DatasetStateEnumToJSON,DatasetStateEnumToJSONTyped,} from './DatasetStateEnum';+import type { ExperimentLink } from './ExperimentLink';+import {+ ExperimentLinkFromJSON,+ ExperimentLinkFromJSONTyped,+ ExperimentLinkToJSON,+ ExperimentLinkToJSONTyped,+} from './ExperimentLink';import type { Cell } from './Cell';import {CellFromJSON,@@ -176,6 +183,18 @@ export interface Dataset {* @memberof Dataset*/readonly rows: number;+ /**+ *+ * @type {ExperimentLink}+ * @memberof Dataset+ */+ readonly madeBy: ExperimentLink | null;+ /**+ *+ * @type {Array<ExperimentLink>}+ * @memberof Dataset+ */+ readonly usedIn: Array<ExperimentLink>;/**** @type {{ [key: string]: any; }}@@ -250,6 +269,8 @@ export function instanceOfDataset(value: object): value is Dataset {if (!('activeVersion' in value) || value['activeVersion'] === undefined) return false;if (!('activeCell' in value) || value['activeCell'] === undefined) return false;if (!('rows' in value) || value['rows'] === undefined) return false;+ if (!('madeBy' in value) || value['madeBy'] === undefined) return false;+ if (!('usedIn' in value) || value['usedIn'] === undefined) return false;if (!('operation' in value) || value['operation'] === undefined) return false;if (!('state' in value) || value['state'] === undefined) return false;if (!('error' in value) || value['error'] === undefined) return false;@@ -289,6 +310,8 @@ export function DatasetFromJSONTyped(json: any, ignoreDiscriminator: boolean): D'activeVersion': json['active_version'],'activeCell': json['active_cell'],'rows': json['rows'],+ 'madeBy': ExperimentLinkFromJSON(json['made_by']),+ 'usedIn': ((json['used_in'] as Array<any>).map(ExperimentLinkFromJSON)),'operation': json['operation'],'state': DatasetStateEnumFromJSON(json['state']),'error': json['error'],@@ -303,7 +326,7 @@ export function DatasetToJSON(json: any): Dataset {return DatasetToJSONTyped(json, false);}-export function DatasetToJSONTyped(value?: Omit<Dataset, 'work'|'roles'|'workspace_id'|'id'|'project'|'brief'|'source_kind'|'source_spec'|'capability_name'|'capability_rank'|'active_version'|'active_cell'|'rows'|'operation'|'state'|'error'|'cells'|'created_by'|'created_at'|'updated_at'> | null, ignoreDiscriminator: boolean = false): any {+export function DatasetToJSONTyped(value?: Omit<Dataset, 'work'|'roles'|'workspace_id'|'id'|'project'|'brief'|'source_kind'|'source_spec'|'capability_name'|'capability_rank'|'active_version'|'active_cell'|'rows'|'made_by'|'used_in'|'operation'|'state'|'error'|'cells'|'created_by'|'created_at'|'updated_at'> | null, ignoreDiscriminator: boolean = false): any {if (value == null) {return value;}diff --git a/frontend/src/openapi/models/DatasetCreateRequest.ts b/frontend/src/openapi/models/DatasetCreateRequest.tsindex dec9f431..d6f45e40 100644--- a/frontend/src/openapi/models/DatasetCreateRequest.ts+++ b/frontend/src/openapi/models/DatasetCreateRequest.ts@@ -70,12 +70,6 @@ export interface DatasetCreateRequest {* @memberof DatasetCreateRequest*/source?: SourceRequest;- /**- * Queue the assistant's first pass, which starts once the source lands.- * @type {boolean}- * @memberof DatasetCreateRequest- */- prepare?: boolean;}@@ -104,7 +98,6 @@ export function DatasetCreateRequestFromJSONTyped(json: any, ignoreDiscriminator'capability': json['capability'] == null ? undefined : json['capability'],'intent': json['intent'] == null ? undefined : IntentEnumFromJSON(json['intent']),'source': json['source'] == null ? undefined : SourceRequestFromJSON(json['source']),- 'prepare': json['prepare'] == null ? undefined : json['prepare'],};}@@ -125,6 +118,5 @@ export function DatasetCreateRequestToJSONTyped(value?: DatasetCreateRequest | n'capability': value['capability'],'intent': IntentEnumToJSON(value['intent']),'source': SourceRequestToJSON(value['source']),- 'prepare': value['prepare'],};}diff --git a/frontend/src/openapi/models/DatasetSplitCreateRequest.ts b/frontend/src/openapi/models/DatasetSplitCreateRequest.tsindex 85de8706..02c025c5 100644--- a/frontend/src/openapi/models/DatasetSplitCreateRequest.ts+++ b/frontend/src/openapi/models/DatasetSplitCreateRequest.ts@@ -95,12 +95,6 @@ export interface DatasetSplitCreateRequest {* @memberof DatasetSplitCreateRequest*/deduplicate?: boolean;- /**- * Queue the assistant's first pass, which starts once the source lands.- * @type {boolean}- * @memberof DatasetSplitCreateRequest- */- prepare?: boolean;}@@ -137,7 +131,6 @@ export function DatasetSplitCreateRequestFromJSONTyped(json: any, ignoreDiscrimi'groupBy': json['group_by'] == null ? undefined : json['group_by'],'stratifyBy': json['stratify_by'] == null ? undefined : json['stratify_by'],'deduplicate': json['deduplicate'] == null ? undefined : json['deduplicate'],- 'prepare': json['prepare'] == null ? undefined : json['prepare'],};}@@ -162,6 +155,5 @@ export function DatasetSplitCreateRequestToJSONTyped(value?: DatasetSplitCreateR'group_by': value['groupBy'],'stratify_by': value['stratifyBy'],'deduplicate': value['deduplicate'],- 'prepare': value['prepare'],};}diff --git a/frontend/src/openapi/models/ExperimentDetail.ts b/frontend/src/openapi/models/ExperimentDetail.tsindex 7769dc2e..f1048004 100644--- a/frontend/src/openapi/models/ExperimentDetail.ts+++ b/frontend/src/openapi/models/ExperimentDetail.ts@@ -34,6 +34,13 @@ import {ExperimentTriggerToJSON,ExperimentTriggerToJSONTyped,} from './ExperimentTrigger';+import type { Spend } from './Spend';+import {+ SpendFromJSON,+ SpendFromJSONTyped,+ SpendToJSON,+ SpendToJSONTyped,+} from './Spend';import type { ExperimentProblem } from './ExperimentProblem';import {ExperimentProblemFromJSON,@@ -41,6 +48,13 @@ import {ExperimentProblemToJSON,ExperimentProblemToJSONTyped,} from './ExperimentProblem';+import type { Proposal } from './Proposal';+import {+ ProposalFromJSON,+ ProposalFromJSONTyped,+ ProposalToJSON,+ ProposalToJSONTyped,+} from './Proposal';/***@@ -132,6 +146,24 @@ export interface ExperimentDetail {* @memberof ExperimentDetail*/datasets: Array<PinnedDataset>;+ /**+ *+ * @type {string}+ * @memberof ExperimentDetail+ */+ notes: string;+ /**+ *+ * @type {Spend}+ * @memberof ExperimentDetail+ */+ spend: Spend;+ /**+ *+ * @type {Array<Proposal>}+ * @memberof ExperimentDetail+ */+ proposals: Array<Proposal>;/**** @type {Array<ExperimentRunSummary>}@@ -170,6 +202,9 @@ export function instanceOfExperimentDetail(value: object): value is ExperimentDeif (!('document' in value) || value['document'] === undefined) return false;if (!('problems' in value) || value['problems'] === undefined) return false;if (!('datasets' in value) || value['datasets'] === undefined) return false;+ if (!('notes' in value) || value['notes'] === undefined) return false;+ if (!('spend' in value) || value['spend'] === undefined) return false;+ if (!('proposals' in value) || value['proposals'] === undefined) return false;if (!('runList' in value) || value['runList'] === undefined) return false;if (!('triggers' in value) || value['triggers'] === undefined) return false;if (!('thread' in value) || value['thread'] === undefined) return false;@@ -200,6 +235,9 @@ export function ExperimentDetailFromJSONTyped(json: any, ignoreDiscriminator: bo'document': json['document'],'problems': ((json['problems'] as Array<any>).map(ExperimentProblemFromJSON)),'datasets': ((json['datasets'] as Array<any>).map(PinnedDatasetFromJSON)),+ 'notes': json['notes'],+ 'spend': SpendFromJSON(json['spend']),+ 'proposals': ((json['proposals'] as Array<any>).map(ProposalFromJSON)),'runList': ((json['run_list'] as Array<any>).map(ExperimentRunSummaryFromJSON)),'triggers': ((json['triggers'] as Array<any>).map(ExperimentTriggerFromJSON)),'thread': json['thread'],@@ -231,6 +269,9 @@ export function ExperimentDetailToJSONTyped(value?: ExperimentDetail | null, ign'document': value['document'],'problems': ((value['problems'] as Array<any>).map(ExperimentProblemToJSON)),'datasets': ((value['datasets'] as Array<any>).map(PinnedDatasetToJSON)),+ 'notes': value['notes'],+ 'spend': SpendToJSON(value['spend']),+ 'proposals': ((value['proposals'] as Array<any>).map(ProposalToJSON)),'run_list': ((value['runList'] as Array<any>).map(ExperimentRunSummaryToJSON)),'triggers': ((value['triggers'] as Array<any>).map(ExperimentTriggerToJSON)),'thread': value['thread'],diff --git a/frontend/src/openapi/models/ExperimentLink.ts b/frontend/src/openapi/models/ExperimentLink.tsnew file mode 100644index 00000000..97355299--- /dev/null+++ b/frontend/src/openapi/models/ExperimentLink.ts@@ -0,0 +1,74 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */++import { mapValues } from '../runtime';+/**+ *+ * @export+ * @interface ExperimentLink+ */+export interface ExperimentLink {+ /**+ *+ * @type {string}+ * @memberof ExperimentLink+ */+ experiment: string;+ /**+ *+ * @type {string}+ * @memberof ExperimentLink+ */+ name: string;+}++/**+ * Check if a given object implements the ExperimentLink interface.+ */+export function instanceOfExperimentLink(value: object): value is ExperimentLink {+ if (!('experiment' in value) || value['experiment'] === undefined) return false;+ if (!('name' in value) || value['name'] === undefined) return false;+ return true;+}++export function ExperimentLinkFromJSON(json: any): ExperimentLink {+ return ExperimentLinkFromJSONTyped(json, false);+}++export function ExperimentLinkFromJSONTyped(json: any, ignoreDiscriminator: boolean): ExperimentLink {+ if (json == null) {+ return json;+ }+ return {++ 'experiment': json['experiment'],+ 'name': json['name'],+ };+}++export function ExperimentLinkToJSON(json: any): ExperimentLink {+ return ExperimentLinkToJSONTyped(json, false);+}++export function ExperimentLinkToJSONTyped(value?: ExperimentLink | null, ignoreDiscriminator: boolean = false): any {+ if (value == null) {+ return value;+ }++ return {++ 'experiment': value['experiment'],+ 'name': value['name'],+ };+}diff --git a/frontend/src/openapi/models/ExperimentTrigger.ts b/frontend/src/openapi/models/ExperimentTrigger.tsindex d5a6fa70..f61fc974 100644--- a/frontend/src/openapi/models/ExperimentTrigger.ts+++ b/frontend/src/openapi/models/ExperimentTrigger.ts@@ -75,6 +75,12 @@ export interface ExperimentTrigger {* @memberof ExperimentTrigger*/maxSends: number;+ /**+ *+ * @type {string}+ * @memberof ExperimentTrigger+ */+ maxSpendUsd: string | null;/**** @type {Date}@@ -103,6 +109,7 @@ export function instanceOfExperimentTrigger(value: object): value is ExperimentTif (!('threshold' in value) || value['threshold'] === undefined) return false;if (!('sends' in value) || value['sends'] === undefined) return false;if (!('maxSends' in value) || value['maxSends'] === undefined) return false;+ if (!('maxSpendUsd' in value) || value['maxSpendUsd'] === undefined) return false;if (!('nextAt' in value) || value['nextAt'] === undefined) return false;if (!('lastSentAt' in value) || value['lastSentAt'] === undefined) return false;return true;@@ -126,6 +133,7 @@ export function ExperimentTriggerFromJSONTyped(json: any, ignoreDiscriminator: b'threshold': json['threshold'],'sends': json['sends'],'maxSends': json['max_sends'],+ 'maxSpendUsd': json['max_spend_usd'],'nextAt': (json['next_at'] == null ? null : new Date(json['next_at'])),'lastSentAt': (json['last_sent_at'] == null ? null : new Date(json['last_sent_at'])),};@@ -150,6 +158,7 @@ export function ExperimentTriggerToJSONTyped(value?: ExperimentTrigger | null, i'threshold': value['threshold'],'sends': value['sends'],'max_sends': value['maxSends'],+ 'max_spend_usd': value['maxSpendUsd'],'next_at': value['nextAt'] == null ? value['nextAt'] : value['nextAt'].toISOString(),'last_sent_at': value['lastSentAt'] == null ? value['lastSentAt'] : value['lastSentAt'].toISOString(),};diff --git a/frontend/src/openapi/models/ExperimentTriggerInputRequest.ts b/frontend/src/openapi/models/ExperimentTriggerInputRequest.tsindex ae37ee7b..e8409d7e 100644--- a/frontend/src/openapi/models/ExperimentTriggerInputRequest.ts+++ b/frontend/src/openapi/models/ExperimentTriggerInputRequest.ts@@ -51,6 +51,12 @@ export interface ExperimentTriggerInputRequest {* @memberof ExperimentTriggerInputRequest*/maxSends: number;+ /**+ *+ * @type {string}+ * @memberof ExperimentTriggerInputRequest+ */+ maxSpendUsd?: string;/**** @type {string}@@ -92,6 +98,7 @@ export function ExperimentTriggerInputRequestFromJSONTyped(json: any, ignoreDisc'instruction': json['instruction'],'hours': json['hours'],'maxSends': json['max_sends'],+ 'maxSpendUsd': json['max_spend_usd'] == null ? undefined : json['max_spend_usd'],'capability': json['capability'] == null ? undefined : json['capability'],'threshold': json['threshold'] == null ? undefined : json['threshold'],};@@ -112,6 +119,7 @@ export function ExperimentTriggerInputRequestToJSONTyped(value?: ExperimentTrigg'instruction': value['instruction'],'hours': value['hours'],'max_sends': value['maxSends'],+ 'max_spend_usd': value['maxSpendUsd'],'capability': value['capability'],'threshold': value['threshold'],};diff --git a/frontend/src/openapi/models/OpenThreadRequest.ts b/frontend/src/openapi/models/OpenThreadRequest.tsdeleted file mode 100644index 203da57c..00000000--- a/frontend/src/openapi/models/OpenThreadRequest.ts+++ /dev/null@@ -1,65 +0,0 @@-/* tslint:disable */-/* eslint-disable */-/**- * Overbae API- * Backend API for the Overclaw / Overmind platform.- *- * The version of the OpenAPI document: 2.0.0- *- *- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).- * https://openapi-generator.tech- * Do not edit the class manually.- */--import { mapValues } from '../runtime';-/**- *- * @export- * @interface OpenThreadRequest- */-export interface OpenThreadRequest {- /**- *- * @type {string}- * @memberof OpenThreadRequest- */- dataset: string;-}--/**- * Check if a given object implements the OpenThreadRequest interface.- */-export function instanceOfOpenThreadRequest(value: object): value is OpenThreadRequest {- if (!('dataset' in value) || value['dataset'] === undefined) return false;- return true;-}--export function OpenThreadRequestFromJSON(json: any): OpenThreadRequest {- return OpenThreadRequestFromJSONTyped(json, false);-}--export function OpenThreadRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): OpenThreadRequest {- if (json == null) {- return json;- }- return {-- 'dataset': json['dataset'],- };-}--export function OpenThreadRequestToJSON(json: any): OpenThreadRequest {- return OpenThreadRequestToJSONTyped(json, false);-}--export function OpenThreadRequestToJSONTyped(value?: OpenThreadRequest | null, ignoreDiscriminator: boolean = false): any {- if (value == null) {- return value;- }-- return {-- 'dataset': value['dataset'],- };-}diff --git a/frontend/src/openapi/models/ProjectSetup.ts b/frontend/src/openapi/models/ProjectSetup.tsnew file mode 100644index 00000000..bc53be35--- /dev/null+++ b/frontend/src/openapi/models/ProjectSetup.ts@@ -0,0 +1,101 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */++import { mapValues } from '../runtime';+/**+ *+ * @export+ * @interface ProjectSetup+ */+export interface ProjectSetup {+ /**+ *+ * @type {boolean}+ * @memberof ProjectSetup+ */+ scanned: boolean;+ /**+ *+ * @type {boolean}+ * @memberof ProjectSetup+ */+ dataset: boolean;+ /**+ *+ * @type {boolean}+ * @memberof ProjectSetup+ */+ evalSet: boolean;+ /**+ *+ * @type {boolean}+ * @memberof ProjectSetup+ */+ trained: boolean;+ /**+ *+ * @type {boolean}+ * @memberof ProjectSetup+ */+ deployed: boolean;+}++/**+ * Check if a given object implements the ProjectSetup interface.+ */+export function instanceOfProjectSetup(value: object): value is ProjectSetup {+ if (!('scanned' in value) || value['scanned'] === undefined) return false;+ if (!('dataset' in value) || value['dataset'] === undefined) return false;+ if (!('evalSet' in value) || value['evalSet'] === undefined) return false;+ if (!('trained' in value) || value['trained'] === undefined) return false;+ if (!('deployed' in value) || value['deployed'] === undefined) return false;+ return true;+}++export function ProjectSetupFromJSON(json: any): ProjectSetup {+ return ProjectSetupFromJSONTyped(json, false);+}++export function ProjectSetupFromJSONTyped(json: any, ignoreDiscriminator: boolean): ProjectSetup {+ if (json == null) {+ return json;+ }+ return {++ 'scanned': json['scanned'],+ 'dataset': json['dataset'],+ 'evalSet': json['eval_set'],+ 'trained': json['trained'],+ 'deployed': json['deployed'],+ };+}++export function ProjectSetupToJSON(json: any): ProjectSetup {+ return ProjectSetupToJSONTyped(json, false);+}++export function ProjectSetupToJSONTyped(value?: ProjectSetup | null, ignoreDiscriminator: boolean = false): any {+ if (value == null) {+ return value;+ }++ return {++ 'scanned': value['scanned'],+ 'dataset': value['dataset'],+ 'eval_set': value['evalSet'],+ 'trained': value['trained'],+ 'deployed': value['deployed'],+ };+}diff --git a/frontend/src/openapi/models/Proposal.ts b/frontend/src/openapi/models/Proposal.tsnew file mode 100644index 00000000..801d9fa6--- /dev/null+++ b/frontend/src/openapi/models/Proposal.ts@@ -0,0 +1,82 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */++import { mapValues } from '../runtime';+import type { ProposalChange } from './ProposalChange';+import {+ ProposalChangeFromJSON,+ ProposalChangeFromJSONTyped,+ ProposalChangeToJSON,+ ProposalChangeToJSONTyped,+} from './ProposalChange';++/**+ *+ * @export+ * @interface Proposal+ */+export interface Proposal {+ /**+ *+ * @type {number}+ * @memberof Proposal+ */+ sequence: number;+ /**+ *+ * @type {Array<ProposalChange>}+ * @memberof Proposal+ */+ changes: Array<ProposalChange>;+}++/**+ * Check if a given object implements the Proposal interface.+ */+export function instanceOfProposal(value: object): value is Proposal {+ if (!('sequence' in value) || value['sequence'] === undefined) return false;+ if (!('changes' in value) || value['changes'] === undefined) return false;+ return true;+}++export function ProposalFromJSON(json: any): Proposal {+ return ProposalFromJSONTyped(json, false);+}++export function ProposalFromJSONTyped(json: any, ignoreDiscriminator: boolean): Proposal {+ if (json == null) {+ return json;+ }+ return {++ 'sequence': json['sequence'],+ 'changes': ((json['changes'] as Array<any>).map(ProposalChangeFromJSON)),+ };+}++export function ProposalToJSON(json: any): Proposal {+ return ProposalToJSONTyped(json, false);+}++export function ProposalToJSONTyped(value?: Proposal | null, ignoreDiscriminator: boolean = false): any {+ if (value == null) {+ return value;+ }++ return {++ 'sequence': value['sequence'],+ 'changes': ((value['changes'] as Array<any>).map(ProposalChangeToJSON)),+ };+}diff --git a/frontend/src/openapi/models/ProposalChange.ts b/frontend/src/openapi/models/ProposalChange.tsnew file mode 100644index 00000000..6e9c2398--- /dev/null+++ b/frontend/src/openapi/models/ProposalChange.ts@@ -0,0 +1,119 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */++import { mapValues } from '../runtime';+/**+ *+ * @export+ * @interface ProposalChange+ */+export interface ProposalChange {+ /**+ *+ * @type {string}+ * @memberof ProposalChange+ */+ node: string;+ /**+ *+ * @type {string}+ * @memberof ProposalChange+ */+ title: string;+ /**+ *+ * @type {string}+ * @memberof ProposalChange+ */+ key: string;+ /**+ *+ * @type {any}+ * @memberof ProposalChange+ */+ before: any | null;+ /**+ *+ * @type {any}+ * @memberof ProposalChange+ */+ after: any | null;+ /**+ *+ * @type {string}+ * @memberof ProposalChange+ */+ beforeLabel: string | null;+ /**+ *+ * @type {string}+ * @memberof ProposalChange+ */+ afterLabel: string | null;+}++/**+ * Check if a given object implements the ProposalChange interface.+ */+export function instanceOfProposalChange(value: object): value is ProposalChange {+ if (!('node' in value) || value['node'] === undefined) return false;+ if (!('title' in value) || value['title'] === undefined) return false;+ if (!('key' in value) || value['key'] === undefined) return false;+ if (!('before' in value) || value['before'] === undefined) return false;+ if (!('after' in value) || value['after'] === undefined) return false;+ if (!('beforeLabel' in value) || value['beforeLabel'] === undefined) return false;+ if (!('afterLabel' in value) || value['afterLabel'] === undefined) return false;+ return true;+}++export function ProposalChangeFromJSON(json: any): ProposalChange {+ return ProposalChangeFromJSONTyped(json, false);+}++export function ProposalChangeFromJSONTyped(json: any, ignoreDiscriminator: boolean): ProposalChange {+ if (json == null) {+ return json;+ }+ return {++ 'node': json['node'],+ 'title': json['title'],+ 'key': json['key'],+ 'before': json['before'],+ 'after': json['after'],+ 'beforeLabel': json['before_label'],+ 'afterLabel': json['after_label'],+ };+}++export function ProposalChangeToJSON(json: any): ProposalChange {+ return ProposalChangeToJSONTyped(json, false);+}++export function ProposalChangeToJSONTyped(value?: ProposalChange | null, ignoreDiscriminator: boolean = false): any {+ if (value == null) {+ return value;+ }++ return {++ 'node': value['node'],+ 'title': value['title'],+ 'key': value['key'],+ 'before': value['before'],+ 'after': value['after'],+ 'before_label': value['beforeLabel'],+ 'after_label': value['afterLabel'],+ };+}diff --git a/frontend/src/openapi/models/ProposalDecisionRequest.ts b/frontend/src/openapi/models/ProposalDecisionRequest.tsnew file mode 100644index 00000000..3d64768f--- /dev/null+++ b/frontend/src/openapi/models/ProposalDecisionRequest.ts@@ -0,0 +1,65 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */++import { mapValues } from '../runtime';+/**+ *+ * @export+ * @interface ProposalDecisionRequest+ */+export interface ProposalDecisionRequest {+ /**+ *+ * @type {boolean}+ * @memberof ProposalDecisionRequest+ */+ apply: boolean;+}++/**+ * Check if a given object implements the ProposalDecisionRequest interface.+ */+export function instanceOfProposalDecisionRequest(value: object): value is ProposalDecisionRequest {+ if (!('apply' in value) || value['apply'] === undefined) return false;+ return true;+}++export function ProposalDecisionRequestFromJSON(json: any): ProposalDecisionRequest {+ return ProposalDecisionRequestFromJSONTyped(json, false);+}++export function ProposalDecisionRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): ProposalDecisionRequest {+ if (json == null) {+ return json;+ }+ return {++ 'apply': json['apply'],+ };+}++export function ProposalDecisionRequestToJSON(json: any): ProposalDecisionRequest {+ return ProposalDecisionRequestToJSONTyped(json, false);+}++export function ProposalDecisionRequestToJSONTyped(value?: ProposalDecisionRequest | null, ignoreDiscriminator: boolean = false): any {+ if (value == null) {+ return value;+ }++ return {++ 'apply': value['apply'],+ };+}diff --git a/frontend/src/openapi/models/Spend.ts b/frontend/src/openapi/models/Spend.tsnew file mode 100644index 00000000..081bcaeb--- /dev/null+++ b/frontend/src/openapi/models/Spend.ts@@ -0,0 +1,74 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */++import { mapValues } from '../runtime';+/**+ *+ * @export+ * @interface Spend+ */+export interface Spend {+ /**+ *+ * @type {number}+ * @memberof Spend+ */+ measuredUsd: number;+ /**+ *+ * @type {Array<string>}+ * @memberof Spend+ */+ unknown: Array<string>;+}++/**+ * Check if a given object implements the Spend interface.+ */+export function instanceOfSpend(value: object): value is Spend {+ if (!('measuredUsd' in value) || value['measuredUsd'] === undefined) return false;+ if (!('unknown' in value) || value['unknown'] === undefined) return false;+ return true;+}++export function SpendFromJSON(json: any): Spend {+ return SpendFromJSONTyped(json, false);+}++export function SpendFromJSONTyped(json: any, ignoreDiscriminator: boolean): Spend {+ if (json == null) {+ return json;+ }+ return {++ 'measuredUsd': json['measured_usd'],+ 'unknown': json['unknown'],+ };+}++export function SpendToJSON(json: any): Spend {+ return SpendToJSONTyped(json, false);+}++export function SpendToJSONTyped(value?: Spend | null, ignoreDiscriminator: boolean = false): any {+ if (value == null) {+ return value;+ }++ return {++ 'measured_usd': value['measuredUsd'],+ 'unknown': value['unknown'],+ };+}diff --git a/frontend/src/openapi/models/SystemImport.ts b/frontend/src/openapi/models/SystemImport.tsnew file mode 100644index 00000000..c19abba0--- /dev/null+++ b/frontend/src/openapi/models/SystemImport.ts@@ -0,0 +1,65 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */++import { mapValues } from '../runtime';+/**+ *+ * @export+ * @interface SystemImport+ */+export interface SystemImport {+ /**+ * The import that ends the stage's wait.+ * @type {string}+ * @memberof SystemImport+ */+ run: string;+}++/**+ * Check if a given object implements the SystemImport interface.+ */+export function instanceOfSystemImport(value: object): value is SystemImport {+ if (!('run' in value) || value['run'] === undefined) return false;+ return true;+}++export function SystemImportFromJSON(json: any): SystemImport {+ return SystemImportFromJSONTyped(json, false);+}++export function SystemImportFromJSONTyped(json: any, ignoreDiscriminator: boolean): SystemImport {+ if (json == null) {+ return json;+ }+ return {++ 'run': json['run'],+ };+}++export function SystemImportToJSON(json: any): SystemImport {+ return SystemImportToJSONTyped(json, false);+}++export function SystemImportToJSONTyped(value?: SystemImport | null, ignoreDiscriminator: boolean = false): any {+ if (value == null) {+ return value;+ }++ return {++ 'run': value['run'],+ };+}diff --git a/frontend/src/openapi/models/SystemOutputRequest.ts b/frontend/src/openapi/models/SystemOutputRequest.tsnew file mode 100644index 00000000..28f2ecbf--- /dev/null+++ b/frontend/src/openapi/models/SystemOutputRequest.ts@@ -0,0 +1,74 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */++import { mapValues } from '../runtime';+/**+ *+ * @export+ * @interface SystemOutputRequest+ */+export interface SystemOutputRequest {+ /**+ *+ * @type {number}+ * @memberof SystemOutputRequest+ */+ sourceRow: number;+ /**+ *+ * @type {any}+ * @memberof SystemOutputRequest+ */+ output: any | null;+}++/**+ * Check if a given object implements the SystemOutputRequest interface.+ */+export function instanceOfSystemOutputRequest(value: object): value is SystemOutputRequest {+ if (!('sourceRow' in value) || value['sourceRow'] === undefined) return false;+ if (!('output' in value) || value['output'] === undefined) return false;+ return true;+}++export function SystemOutputRequestFromJSON(json: any): SystemOutputRequest {+ return SystemOutputRequestFromJSONTyped(json, false);+}++export function SystemOutputRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): SystemOutputRequest {+ if (json == null) {+ return json;+ }+ return {++ 'sourceRow': json['source_row'],+ 'output': json['output'],+ };+}++export function SystemOutputRequestToJSON(json: any): SystemOutputRequest {+ return SystemOutputRequestToJSONTyped(json, false);+}++export function SystemOutputRequestToJSONTyped(value?: SystemOutputRequest | null, ignoreDiscriminator: boolean = false): any {+ if (value == null) {+ return value;+ }++ return {++ 'source_row': value['sourceRow'],+ 'output': value['output'],+ };+}diff --git a/frontend/src/openapi/models/SystemOutputsRequest.ts b/frontend/src/openapi/models/SystemOutputsRequest.tsnew file mode 100644index 00000000..63f97dde--- /dev/null+++ b/frontend/src/openapi/models/SystemOutputsRequest.ts@@ -0,0 +1,88 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */++import { mapValues } from '../runtime';+import type { SystemRepositoryRequest } from './SystemRepositoryRequest';+import {+ SystemRepositoryRequestFromJSON,+ SystemRepositoryRequestFromJSONTyped,+ SystemRepositoryRequestToJSON,+ SystemRepositoryRequestToJSONTyped,+} from './SystemRepositoryRequest';+import type { SystemOutputRequest } from './SystemOutputRequest';+import {+ SystemOutputRequestFromJSON,+ SystemOutputRequestFromJSONTyped,+ SystemOutputRequestToJSON,+ SystemOutputRequestToJSONTyped,+} from './SystemOutputRequest';++/**+ *+ * @export+ * @interface SystemOutputsRequest+ */+export interface SystemOutputsRequest {+ /**+ *+ * @type {Array<SystemOutputRequest>}+ * @memberof SystemOutputsRequest+ */+ outputs: Array<SystemOutputRequest>;+ /**+ *+ * @type {SystemRepositoryRequest}+ * @memberof SystemOutputsRequest+ */+ repository?: SystemRepositoryRequest;+}++/**+ * Check if a given object implements the SystemOutputsRequest interface.+ */+export function instanceOfSystemOutputsRequest(value: object): value is SystemOutputsRequest {+ if (!('outputs' in value) || value['outputs'] === undefined) return false;+ return true;+}++export function SystemOutputsRequestFromJSON(json: any): SystemOutputsRequest {+ return SystemOutputsRequestFromJSONTyped(json, false);+}++export function SystemOutputsRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): SystemOutputsRequest {+ if (json == null) {+ return json;+ }+ return {++ 'outputs': ((json['outputs'] as Array<any>).map(SystemOutputRequestFromJSON)),+ 'repository': json['repository'] == null ? undefined : SystemRepositoryRequestFromJSON(json['repository']),+ };+}++export function SystemOutputsRequestToJSON(json: any): SystemOutputsRequest {+ return SystemOutputsRequestToJSONTyped(json, false);+}++export function SystemOutputsRequestToJSONTyped(value?: SystemOutputsRequest | null, ignoreDiscriminator: boolean = false): any {+ if (value == null) {+ return value;+ }++ return {++ 'outputs': ((value['outputs'] as Array<any>).map(SystemOutputRequestToJSON)),+ 'repository': SystemRepositoryRequestToJSON(value['repository']),+ };+}diff --git a/frontend/src/openapi/models/SystemRepositoryRequest.ts b/frontend/src/openapi/models/SystemRepositoryRequest.tsnew file mode 100644index 00000000..9e79c219--- /dev/null+++ b/frontend/src/openapi/models/SystemRepositoryRequest.ts@@ -0,0 +1,80 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */++import { mapValues } from '../runtime';+/**+ *+ * @export+ * @interface SystemRepositoryRequest+ */+export interface SystemRepositoryRequest {+ /**+ *+ * @type {string}+ * @memberof SystemRepositoryRequest+ */+ remote?: string;+ /**+ *+ * @type {string}+ * @memberof SystemRepositoryRequest+ */+ commit?: string;+ /**+ *+ * @type {boolean}+ * @memberof SystemRepositoryRequest+ */+ dirty?: boolean;+}++/**+ * Check if a given object implements the SystemRepositoryRequest interface.+ */+export function instanceOfSystemRepositoryRequest(value: object): value is SystemRepositoryRequest {+ return true;+}++export function SystemRepositoryRequestFromJSON(json: any): SystemRepositoryRequest {+ return SystemRepositoryRequestFromJSONTyped(json, false);+}++export function SystemRepositoryRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): SystemRepositoryRequest {+ if (json == null) {+ return json;+ }+ return {++ 'remote': json['remote'] == null ? undefined : json['remote'],+ 'commit': json['commit'] == null ? undefined : json['commit'],+ 'dirty': json['dirty'] == null ? undefined : json['dirty'],+ };+}++export function SystemRepositoryRequestToJSON(json: any): SystemRepositoryRequest {+ return SystemRepositoryRequestToJSONTyped(json, false);+}++export function SystemRepositoryRequestToJSONTyped(value?: SystemRepositoryRequest | null, ignoreDiscriminator: boolean = false): any {+ if (value == null) {+ return value;+ }++ return {++ 'remote': value['remote'],+ 'commit': value['commit'],+ 'dirty': value['dirty'],+ };+}diff --git a/frontend/src/openapi/models/SystemRows.ts b/frontend/src/openapi/models/SystemRows.tsnew file mode 100644index 00000000..258c831d--- /dev/null+++ b/frontend/src/openapi/models/SystemRows.ts@@ -0,0 +1,74 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */++import { mapValues } from '../runtime';+/**+ *+ * @export+ * @interface SystemRows+ */+export interface SystemRows {+ /**+ *+ * @type {string}+ * @memberof SystemRows+ */+ label: string;+ /**+ *+ * @type {Array<any>}+ * @memberof SystemRows+ */+ rows: Array<any>;+}++/**+ * Check if a given object implements the SystemRows interface.+ */+export function instanceOfSystemRows(value: object): value is SystemRows {+ if (!('label' in value) || value['label'] === undefined) return false;+ if (!('rows' in value) || value['rows'] === undefined) return false;+ return true;+}++export function SystemRowsFromJSON(json: any): SystemRows {+ return SystemRowsFromJSONTyped(json, false);+}++export function SystemRowsFromJSONTyped(json: any, ignoreDiscriminator: boolean): SystemRows {+ if (json == null) {+ return json;+ }+ return {++ 'label': json['label'],+ 'rows': json['rows'],+ };+}++export function SystemRowsToJSON(json: any): SystemRows {+ return SystemRowsToJSONTyped(json, false);+}++export function SystemRowsToJSONTyped(value?: SystemRows | null, ignoreDiscriminator: boolean = false): any {+ if (value == null) {+ return value;+ }++ return {++ 'label': value['label'],+ 'rows': value['rows'],+ };+}diff --git a/frontend/src/openapi/models/index.ts b/frontend/src/openapi/models/index.tsindex d0dd6143..32756edb 100644--- a/frontend/src/openapi/models/index.ts+++ b/frontend/src/openapi/models/index.ts@@ -169,6 +169,7 @@ export * from './ExperimentCandidateRequest';export * from './ExperimentCreateRequest';export * from './ExperimentDetail';export * from './ExperimentLaunchRequest';+export * from './ExperimentLink';export * from './ExperimentPlan';export * from './ExperimentPlanEntry';export * from './ExperimentProblem';@@ -266,7 +267,6 @@ export * from './NativeMonitor';export * from './NativeSample';export * from './NativeSamplePrediction';export * from './OnboardingMilestone';-export * from './OpenThreadRequest';export * from './OpenrouterStatusEnum';export * from './OutputEnum';export * from './OverallComparison';@@ -338,7 +338,11 @@ export * from './ProjectMember';export * from './ProjectMembershipCreateRequest';export * from './ProjectRequest';export * from './ProjectSavePipelineRequest';+export * from './ProjectSetup';export * from './Prompt';+export * from './Proposal';+export * from './ProposalChange';+export * from './ProposalDecisionRequest';export * from './ProvenanceEnum';export * from './ProviderEnum';export * from './PublicLibraryFilterOption';@@ -379,6 +383,7 @@ export * from './SignalTypeEnum';export * from './SourceEnum';export * from './SourceRequest';export * from './Span';+export * from './Spend';export * from './SplitMethod3daEnum';export * from './SplitMethodE87Enum';export * from './SplitPositionEnum';@@ -390,6 +395,11 @@ export * from './Stratum';export * from './SyncSnapshot';export * from './SyncSnapshotRequest';export * from './SyncStatusEnum';+export * from './SystemImport';+export * from './SystemOutputRequest';+export * from './SystemOutputsRequest';+export * from './SystemRepositoryRequest';+export * from './SystemRows';export * from './TaskTypeSourceEnum';export * from './TiersEnum';export * from './TokenObtainPair';diff --git a/frontend/src/routes/_auth/datasets.index.tsx b/frontend/src/routes/_auth/datasets.index.tsxindex 9d2a32e6..b34561d8 100644--- a/frontend/src/routes/_auth/datasets.index.tsx+++ b/frontend/src/routes/_auth/datasets.index.tsx@@ -1,27 +1,17 @@-import { useEffect, useState } from "react";+import { createFileRoute, Link, redirect } from "@tanstack/react-router";-import { createFileRoute, redirect } from "@tanstack/react-router";-import type { RowSelectionState } from "@tanstack/react-table";--import { AssistantComposer } from "@/components/assistant/assistant-composer";-import { ConnectionBackground } from "@/components/connection-scene";import { DatasetsBrowser, DatasetsToolbar } from "@/components/datasets/datasets-table";-import { NewDatasetDialog } from "@/components/datasets/new-dataset-dialog";import { ProjectRequiredEmptyState } from "@/components/project-required-empty-state";import { QuickstartEmbed } from "@/components/quickstart/quickstart-embed";import { Button } from "@/components/ui/button";-import { CountChip } from "@/components/ui/count-chip";+import { EmptyState } from "@/components/ui/empty-state";import { Icon } from "@/components/ui/icons";-import { PageHeader } from "@/components/ui/page-header";import { PageShell } from "@/components/ui/page-shell";-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { useProjectDatasetsQuery } from "@/hooks/use-datasets";import { useProjectCapabilitiesQuery } from "@/hooks/use-evaluations";-import { useGuestGate } from "@/hooks/use-guest-gate";import { datasetWorkspaces } from "@/lib/dataset-workspaces";import { featureFlags } from "@/lib/feature-flags";import { datasetsSearchSchema } from "@/lib/schemas";-import { cn } from "@/lib/utils";export const Route = createFileRoute("/_auth/datasets/")({beforeLoad: () => {@@ -50,27 +40,11 @@ function DatasetsIndexPage() {}function ProjectDatasets({ projectId }: { projectId: string }) {- const { create, ds_search, ds_role, ds_capability } = Route.useSearch();+ const { ds_search, ds_role, ds_capability } = Route.useSearch();const navigate = Route.useNavigate();const query = useProjectDatasetsQuery(projectId);const capabilities = useProjectCapabilitiesQuery(projectId);- const [createOpen, setCreateOpen] = useState(false);- const [tableFocused, setTableFocused] = useState(false);- // Selection survives filtering and paging: it is keyed by dataset id.- const [rowSelection, setRowSelection] = useState<RowSelectionState>({});- const guard = useGuestGate();const datasets = datasetWorkspaces(query.data ?? []);- const attached = datasets.filter((dataset) => rowSelection[dataset.id]);-- useEffect(() => {- if (!create) return;- setCreateOpen(true);- void navigate({- replace: true,- resetScroll: false,- search: (prev) => ({ ...prev, create: undefined }),- });- }, [create, navigate]);const filters = {capabilityFilter: ds_capability,@@ -101,101 +75,22 @@ function ProjectDatasets({ projectId }: { projectId: string }) {};return (- <PageShell className="assistant-stage relative isolate gap-0" header={null} variant="full">- <section- aria-hidden={tableFocused}- aria-label="Start with the assistant"- className="absolute inset-0 overflow-hidden"- inert={tableFocused}- >- <ConnectionBackground />- <div className="assistant-hero-content relative flex min-h-0 flex-col items-center justify-center gap-5 px-6 pt-4 pb-6 sm:gap-7 sm:px-8 sm:pb-10">- <PageHeader- className="justify-center [&_h1]:text-4xl [&_h1]:leading-none sm:[&_h1]:text-5xl"- title={- <span className="inline-flex items-center gap-2">- Ready to train- <span aria-hidden="true" className="assistant-cursor bg-foreground" />- </span>- }- />- <div className="w-full max-w-3xl">- <AssistantComposer- datasets={attached}- onRemoveDataset={(id) => setRowSelection(({ [id]: _removed, ...rest }) => rest)}- onStarted={(datasetId) =>- void navigate({- params: { datasetId },- search: { projectId },- to: "/datasets/$datasetId",- viewTransition: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,- })- }- projectId={projectId}- />- </div>- </div>- </section>- <section- aria-label="Available datasets"- className="assistant-datasets absolute inset-x-0 bottom-0 z-10 flex min-h-0 flex-col border-border border-t bg-card"- data-expanded={tableFocused}- id="assistant-datasets"- >- <Tooltip>- <TooltipTrigger asChild>- <Button- aria-controls="assistant-datasets"- aria-expanded={tableFocused}- aria-label={tableFocused ? "Show composer" : "Focus datasets"}- className={cn(- "assistant-dataset-handle absolute left-1/2 z-10 h-5 w-10 border border-border bg-card hover:bg-control",- tableFocused- ? "rounded-t-none rounded-b-sm border-t-0"- : "rounded-t-sm rounded-b-none border-b-0"- )}- onClick={() => setTableFocused((focused) => !focused)}- size="icon-xs"- variant="ghost"- >- <Icon.chevronUp- className={cn(- "size-3 transition-transform duration-300 motion-reduce:transition-none",- tableFocused && "rotate-180"- )}- />+ <PageShell header={null}>+ {query.data && datasets.length === 0 && !query.error ? (+ <EmptyState+ action={+ <Button asChild size="sm">+ <Link search={{ projectId }} to="/">+ Start an experiment+ </Link></Button>- </TooltipTrigger>- <TooltipContent>{tableFocused ? "Show composer" : "Focus datasets"}</TooltipContent>- </Tooltip>- <div className="flex min-h-0 flex-1 flex-col gap-3 px-4 pt-6 pb-4 md:px-6 md:pb-6">- <div className="flex shrink-0 items-center gap-2">- <Icon.dataset className="size-4 text-muted-foreground" />- <h2 className="text-sm font-medium">Datasets</h2>- {query.data && <CountChip count={datasets.length} />}- <div className="ml-auto flex items-center gap-2">- {attached.length > 0 && (- <Button- className="text-muted-foreground"- onClick={() => {- setTableFocused(false);- requestAnimationFrame(() =>- document.getElementById("assistant-intent")?.focus({ preventScroll: true })- );- }}- size="xs"- variant="secondary"- >- {attached.length} attached- <Icon.chevronUp />- </Button>- )}- <Button onClick={guard(() => setCreateOpen(true))} size="xs" variant="secondary">- <Icon.datasetAdd />- New dataset- </Button>- </div>- </div>+ }+ description="Datasets come from experiments."+ icon={Icon.dataset}+ title="No datasets"+ />+ ) : (+ <div className="flex min-h-0 flex-1 flex-col gap-3"><DatasetsToolbar {...filters} /><DatasetsBrowser{...filters}@@ -203,13 +98,10 @@ function ProjectDatasets({ projectId }: { projectId: string }) {isLoading={query.isPending}key={JSON.stringify([ds_search, ds_role, ds_capability])}onRetry={() => query.refetch()}- onRowSelectionChange={setRowSelection}rowSearch={{ projectId }}- rowSelection={rowSelection}/></div>- </section>- <NewDatasetDialog onOpenChange={setCreateOpen} open={createOpen} projectId={projectId} />+ )}</PageShell>);}diff --git a/frontend/src/routes/_auth/experiments.$experimentId.tsx b/frontend/src/routes/_auth/experiments.$experimentId.tsxindex 2b6cdd25..619ab2d8 100644--- a/frontend/src/routes/_auth/experiments.$experimentId.tsx+++ b/frontend/src/routes/_auth/experiments.$experimentId.tsx@@ -6,6 +6,7 @@ import z from "zod";import apiClient from "@/client";import { AssistantDock } from "@/components/assistant/assistant-dock";+import { NotesAndSpend, ProposalCards } from "@/components/experiments/experiment-panel";import {asFlow,attempts,@@ -110,7 +111,7 @@ function ExperimentEditor({ detail }: { detail: ExperimentDetail }) {setBase(detail.version);}, [detail.version, detail.document, dirty, history, base]);- const assistant = useAssistantThread({ thread: detail.thread });+ const assistant = useAssistantThread(detail.thread);const pinned = history === null ? detail.datasets : historyDatasets;const datasetFor = useCallback((cell: unknown) => pinned.find((item) => item.cell === cell),@@ -304,6 +305,7 @@ function ExperimentEditor({ detail }: { detail: ExperimentDetail }) {</Alert>)}<div className="relative flex min-h-0 flex-1">+ <ProposalCards detail={detail} />{draft.nodes.length ? (<StageCanvasbelow={renderBelow}@@ -321,7 +323,8 @@ function ExperimentEditor({ detail }: { detail: ExperimentDetail }) {/>)}</div>- <div className="absolute top-3 right-3 z-10" hidden={!!focusedNode}>+ <div className="absolute top-3 right-3 z-10 flex gap-1.5" hidden={!!focusedNode}>+ <NotesAndSpend detail={detail} /><Popover><PopoverTrigger asChild><Button aria-label="Experiment options" size="icon-sm" variant="outline">diff --git a/frontend/src/styles.css b/frontend/src/styles.cssindex 0dc68e9c..a31ff6a2 100644--- a/frontend/src/styles.css+++ b/frontend/src/styles.css@@ -786,21 +786,6 @@ body:has(transform: translateX(0);}- /* Notices stand in the dock's column, above its bar. */- .assistant-notices {- left: 50%;- width: min(48rem, calc(100% - 1.5rem));- transform: translateX(-50%);- }-- /* The open panel covers the canvas's left edge, so the canvas's notices move right. */- :has(.assistant-dock[data-panel="true"]) > .assistant-notices {- right: 3rem;- left: auto;- width: min(36rem, calc(100% - 1.5rem));- transform: none;- }-.assistant-dock[data-resizing="true"] {user-select: none;transition: none;diff --git a/overbae/api/assistant.py b/overbae/api/assistant.pyindex 33779112..c0c8e8b9 100644--- a/overbae/api/assistant.py+++ b/overbae/api/assistant.py@@ -3,7 +3,6 @@ import mimetypesfrom django.contrib.auth import get_user_modelfrom django.db import transactionfrom django.http import FileResponse-from django.shortcuts import get_object_or_404from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import extend_schema, extend_schema_fieldfrom redis.exceptions import RedisError@@ -12,10 +11,9 @@ from rest_framework.decorators import actionfrom rest_framework.exceptions import NotFound, ValidationErrorfrom rest_framework.response import Response-from overbae.api.scoping import project_ids_forfrom overbae.api.workbench import ProjectPipelineViewSetfrom overbae.core.errors import InputValidationError-from overbae.models import AssistantEvent, AssistantInput, AssistantThread, Cell, Dataset+from overbae.models import AssistantEvent, AssistantInput, AssistantThread, Cellfrom overbae.services.assistant import log, threads, tools, turnfrom overbae.services.datasets import events@@ -65,7 +63,7 @@ class AssistantThreadSerializer(serializers.ModelSerializer):fields = ["id","project",- "dataset",+ "experiment","state","stop_requested","queue",@@ -82,7 +80,7 @@ class AssistantThreadSerializer(serializers.ModelSerializer):@extend_schema_field(ParticipantSerializer(many=True))def get_participants(self, thread):"""Who wrote in the conversation, sent or queued: members share one conversation- about a dataset, and a reader must tell a teammate's message from their own."""+ about an experiment, and a reader must tell a teammate's message from their own."""senders = set(thread.events.filter(kind=AssistantEvent.Kind.USER).values_list("payload__user", flat=True@@ -163,14 +161,6 @@ class AssistantEventSerializer(serializers.ModelSerializer):return payload-class OpenThreadSerializer(serializers.Serializer):- dataset = serializers.UUIDField()---class ThreadQuerySerializer(serializers.Serializer):- dataset = serializers.UUIDField()--class SendMessageSerializer(serializers.Serializer):request_key = serializers.CharField(max_length=128)text = serializers.CharField(max_length=20000, allow_blank=True)@@ -201,44 +191,15 @@ class EventsQuerySerializer(serializers.Serializer):class AssistantThreadViewSet(ProjectPipelineViewSet):- """The conversation about a dataset. Changes are announced on the dataset's event+ """An experiment's conversation. Changes are announced on the experiment's eventstream; a page reads them here."""def _thread(self, pk) -> AssistantThread:- return turn.settle(self.resolve(AssistantThread.objects.select_related("dataset"), pk))+ return turn.settle(self.resolve(AssistantThread.objects.select_related("experiment"), pk))def _show(self, thread):return AssistantThreadSerializer(thread, context={"request": self.request}).data- @extend_schema(- parameters=[ThreadQuerySerializer], responses=AssistantThreadSerializer(many=True)- )- def list(self, request):- """The dataset's conversation, if it has one."""- query = ThreadQuerySerializer(data=request.query_params)- query.is_valid(raise_exception=True)- found = AssistantThread.objects.filter(- project__is_active=True,- project__memberships__user=request.user,- project_id__in=project_ids_for(request.user, request.auth),- dataset_id=query.validated_data["dataset"],- )- return Response([self._show(turn.settle(thread)) for thread in found])-- @extend_schema(request=OpenThreadSerializer, responses=AssistantThreadSerializer)- def create(self, request):- """Open the dataset's conversation."""- body = OpenThreadSerializer(data=request.data)- body.is_valid(raise_exception=True)- dataset = get_object_or_404(- Dataset,- pk=body.validated_data["dataset"],- project__is_active=True,- project__memberships__user=request.user,- project_id__in=project_ids_for(request.user, request.auth),- )- return Response(self._show(threads.open_thread(dataset)))-@extend_schema(responses=AssistantThreadSerializer)def retrieve(self, request, pk=None):return Response(self._show(self._thread(pk)))diff --git a/overbae/api/dataset_serializers.py b/overbae/api/dataset_serializers.pyindex 9a2d3268..edcd0a2a 100644--- a/overbae/api/dataset_serializers.py+++ b/overbae/api/dataset_serializers.py@@ -16,6 +16,7 @@ from overbae.services.datasets import ()from overbae.services.datasets.land import SPLIT_POSITIONSfrom overbae.services.datasets.workspaces import workspace_ids+from overbae.services.experiments import recordsclass FitSerializer(serializers.Serializer):@@ -214,9 +215,17 @@ class DatasetListSerializer(serializers.ListSerializer):self.context["current_work"] = list_activity.current_work(datasets)self.context["dataset_roles"] = dataset_role_service.dataset_roles(datasets)self.context["workspace_ids"] = workspace_ids(datasets)+ self.context["experiment_links"] = {}+ for project in {dataset.project_id for dataset in datasets}:+ self.context["experiment_links"] |= records.dataset_links(project)return super().to_representation(datasets)+class ExperimentLinkSerializer(serializers.Serializer):+ experiment = serializers.UUIDField()+ name = serializers.CharField()++class DatasetSerializer(serializers.ModelSerializer):workspace_id = serializers.SerializerMethodField()roles = serializers.SerializerMethodField()@@ -230,6 +239,8 @@ class DatasetSerializer(serializers.ModelSerializer):active_version = serializers.SerializerMethodField()active_cell = serializers.SerializerMethodField()rows = serializers.SerializerMethodField()+ made_by = serializers.SerializerMethodField()+ used_in = serializers.SerializerMethodField()class Meta:model = Dataset@@ -254,6 +265,8 @@ class DatasetSerializer(serializers.ModelSerializer):"active_version","active_cell","rows",+ "made_by",+ "used_in","operation","state","error",@@ -343,6 +356,22 @@ class DatasetSerializer(serializers.ModelSerializer):cell = self._active(obj)return str(cell.pk) if cell else None+ def _links(self, obj) -> dict:+ found = self.context.get("experiment_links")+ if found is None:+ found = self.context["experiment_links"] = records.dataset_links(obj.project_id)+ return found.get(str(obj.pk)) or {"made_by": None, "used_in": []}++ @extend_schema_field(ExperimentLinkSerializer(allow_null=True))+ def get_made_by(self, obj):+ """The experiment whose run made a version of this dataset."""+ return self._links(obj)["made_by"]++ @extend_schema_field(ExperimentLinkSerializer(many=True))+ def get_used_in(self, obj):+ """Live experiments whose newest revision reads this dataset."""+ return self._links(obj)["used_in"]+def get_rows(self, obj) -> int:cell = self._active(obj)return int(cell.rows) if cell else 0@@ -408,16 +437,10 @@ class DatasetCreateSerializer(serializers.Serializer):)intent = serializers.ChoiceField(choices=Dataset.Intent.choices, required=False)source = SourceSerializer(required=False)- prepare = serializers.BooleanField(- default=False,- help_text="Queue the assistant's first pass, which starts once the source lands.",- )def validate(self, attrs):if not attrs.get("source") and not attrs.get("brief"):raise serializers.ValidationError("Describe what you want to do or add source data.")- if attrs.get("prepare") and not attrs.get("source"):- raise serializers.ValidationError({"prepare": "The first pass needs source data."})if (attrs.get("source") or {}).get("llm_calls") and attrs.get("intent") not in (Dataset.Intent.TRAIN,Dataset.Intent.EVAL,@@ -446,10 +469,6 @@ class DatasetSplitCreateSerializer(serializers.Serializer):max_length=255, required=False, allow_null=True, default=None)deduplicate = serializers.BooleanField(default=True)- prepare = serializers.BooleanField(- default=False,- help_text="Queue the assistant's first pass, which starts once the source lands.",- )class DatasetPairSerializer(serializers.Serializer):diff --git a/overbae/api/datasets.py b/overbae/api/datasets.pyindex 7a79cbdc..0883b44d 100644--- a/overbae/api/datasets.py+++ b/overbae/api/datasets.py@@ -29,7 +29,6 @@ from overbae.api.dataset_serializers import (from overbae.api.scoping import project_ids_forfrom overbae.api.workbench import WorkbenchActionsfrom overbae.models import Capability, Cell, Dataset, DatasetTransfer, Project-from overbae.services.assistant import threadsfrom overbae.services.datasets import diff as diff_svcfrom overbae.services.datasets import (dispatch,@@ -162,8 +161,6 @@ class DatasetViewSet(WorkbenchActions, viewsets.ModelViewSet):capability=capability,infer_capability="capability" not in data,)- if data["prepare"] and source and request.user.is_authenticated:- threads.queue_first_pass(dataset, request.user)except lifecycle.DatasetError as exc:raise ValidationError({"detail": exc.detail, "code": exc.code}) from excreturn Response(DatasetSerializer(dataset).data, status=status.HTTP_201_CREATED)@@ -195,8 +192,6 @@ class DatasetViewSet(WorkbenchActions, viewsets.ModelViewSet):capability=capability,infer_capability="capability" not in data,)- if data["prepare"] and request.user.is_authenticated:- threads.queue_first_pass(train, request.user, split=True)except lifecycle.DatasetError as exc:raise ValidationError({"detail": exc.detail, "code": exc.code}) from excreturn Response(diff --git a/overbae/api/experiments.py b/overbae/api/experiments.pyindex 12f69782..d043773e 100644--- a/overbae/api/experiments.py+++ b/overbae/api/experiments.py@@ -1,5 +1,6 @@import jsonimport logging+from decimal import Decimalfrom django.conf import settingsfrom django.db import connections, transaction@@ -15,9 +16,9 @@ from rest_framework.response import Responsefrom overbae.api.scoping import project_ids_forfrom overbae.api.workbench import ProjectPipelineViewSetfrom overbae.core.errors import InputValidationError-from overbae.models import Experiment, ExperimentRun, ExperimentTrigger+from overbae.models import Experiment, ExperimentRun, ExperimentStep, ExperimentTriggerfrom overbae.services.assistant import threads, turn-from overbae.services.experiments import catalog, describe, records, runs, triggers+from overbae.services.experiments import catalog, describe, records, runs, system, triggersfrom overbae.services.experiments import document as flowlogger = logging.getLogger(__name__)@@ -62,6 +63,7 @@ class ExperimentTriggerSerializer(serializers.Serializer):threshold = serializers.IntegerField(allow_null=True)sends = serializers.IntegerField()max_sends = serializers.IntegerField()+ max_spend_usd = serializers.DecimalField(max_digits=10, decimal_places=2, allow_null=True)next_at = serializers.DateTimeField(allow_null=True)last_sent_at = serializers.DateTimeField(allow_null=True)@@ -73,11 +75,36 @@ class PinnedDatasetSerializer(serializers.Serializer):rows = serializers.IntegerField()+class ProposalChangeSerializer(serializers.Serializer):+ node = serializers.CharField()+ title = serializers.CharField()+ key = serializers.CharField()+ # Any JSON value the stage setting takes; null where the setting is absent.+ before = serializers.JSONField(allow_null=True)+ after = serializers.JSONField(allow_null=True)+ # A dataset version's dataset name, where the value is one.+ before_label = serializers.CharField(allow_null=True)+ after_label = serializers.CharField(allow_null=True)+++class ProposalSerializer(serializers.Serializer):+ sequence = serializers.IntegerField()+ changes = ProposalChangeSerializer(many=True)+++class SpendSerializer(serializers.Serializer):+ measured_usd = serializers.FloatField()+ unknown = serializers.ListField(child=serializers.CharField())++class ExperimentDetailSerializer(ExperimentSerializer):revision = serializers.IntegerField(help_text="The revision shown; 0 before the first save.")document = serializers.JSONField()problems = ExperimentProblemSerializer(many=True)datasets = PinnedDatasetSerializer(many=True, help_text="The dataset versions stages pin.")+ notes = serializers.CharField(allow_blank=True)+ spend = SpendSerializer()+ proposals = ProposalSerializer(many=True)run_list = ExperimentRunSummarySerializer(many=True)triggers = ExperimentTriggerSerializer(many=True)thread = serializers.UUIDField()@@ -198,11 +225,18 @@ class ExperimentStartSerializer(ExperimentRunOptionsSerializer):max_hours = serializers.IntegerField(min_value=1, max_value=168, required=False, default=None)+class ProposalDecisionSerializer(serializers.Serializer):+ apply = serializers.BooleanField()++class ExperimentTriggerInputSerializer(serializers.Serializer):kind = serializers.ChoiceField(ExperimentTrigger.Kind.choices)instruction = serializers.CharField(max_length=8000)hours = serializers.IntegerField(min_value=1, max_value=720)max_sends = serializers.IntegerField(min_value=1, max_value=100)+ max_spend_usd = serializers.DecimalField(+ max_digits=10, decimal_places=2, min_value=Decimal("0.01"), required=False, default=None+ )capability = serializers.UUIDField(required=False, allow_null=True, default=None)threshold = serializers.IntegerField(min_value=1, required=False, allow_null=True, default=None)@@ -251,6 +285,9 @@ class ExperimentViewSet(ProjectPipelineViewSet):"document": document,"problems": flow.problems(document),"datasets": records.pinned_datasets(found.project, document),+ "notes": found.notes,+ "spend": describe.spend(found),+ "proposals": records.proposals(found),"run_list": [describe.summary(run) for run in listed[:PAGE]],"triggers": describe.triggers(found),"thread": found.assistant_thread.pk,@@ -292,12 +329,13 @@ class ExperimentViewSet(ProjectPipelineViewSet):if values["cells"]else None,)- if values["message"].strip() or values["cells"]:+ # Data dropped without a message lands with no agent turn and no cost.+ if values["message"].strip():threads.send(found.assistant_thread,request.user,request_key=f"create:{values['request_key']}",- text=values["message"] or "Start with the attached data.",+ text=values["message"],cells=values["cells"],)turn.wake(found.assistant_thread)@@ -394,6 +432,22 @@ class ExperimentViewSet(ProjectPipelineViewSet):ExperimentTriggerSerializer(describe.triggers(found), many=True).data, status=201)+ @extend_schema(request=ProposalDecisionSerializer, responses=ExperimentDetailSerializer)+ @action(detail=True, methods=["post"], url_path=r"proposals/(?P<sequence>[0-9]+)")+ def proposal(self, request, pk=None, sequence=None):+ """Apply the agent's proposal as your own revision, or dismiss it."""+ found = self._experiment(pk)+ body = ProposalDecisionSerializer(data=request.data)+ body.is_valid(raise_exception=True)+ try:+ records.resolve_proposal(+ found, request.user, int(sequence), apply=body.validated_data["apply"]+ )+ except InputValidationError as exc:+ raise _refused(exc) from None+ found.refresh_from_db()+ return Response(self._detail(found))+@extend_schema(request=None, responses={204: None})@action(detail=True, methods=["delete"], url_path=r"triggers/(?P<trigger>[0-9a-f-]{36})")def remove_trigger(self, request, pk=None, trigger=None):@@ -500,3 +554,63 @@ class ExperimentRunViewSet(ProjectPipelineViewSet):except InputValidationError as exc:raise _refused(exc) from Nonereturn Response(ExperimentRunSerializer(describe.run(retried)).data, status=202)+++class SystemRowsSerializer(serializers.Serializer):+ label = serializers.CharField(allow_blank=True)+ # Each row whole, as its dataset holds it, with ``source_row``.+ rows = serializers.ListField(child=serializers.JSONField())+++class SystemOutputSerializer(serializers.Serializer):+ source_row = serializers.IntegerField(min_value=0)+ output = serializers.JSONField(allow_null=True)+++class SystemRepositorySerializer(serializers.Serializer):+ remote = serializers.CharField(max_length=500, required=False, allow_blank=True)+ commit = serializers.CharField(max_length=64, required=False, allow_blank=True)+ dirty = serializers.BooleanField(required=False)+++class SystemOutputsSerializer(serializers.Serializer):+ outputs = SystemOutputSerializer(many=True, max_length=2000)+ repository = SystemRepositorySerializer(required=False, default=dict)+++class SystemImportSerializer(serializers.Serializer):+ run = serializers.UUIDField(help_text="The import that ends the stage's wait.")+++class ExperimentStepViewSet(ProjectPipelineViewSet):+ """A Your-system stage: its rows for ``overmind run``, and the outputs it returns."""++ def _step(self, pk) -> ExperimentStep:+ return get_object_or_404(+ ExperimentStep.objects.select_related("run__revision", "run__experiment"),+ pk=pk,+ run__experiment__deleted_at=None,+ run__experiment__project__is_active=True,+ run__experiment__project__memberships__user=self.request.user,+ run__experiment__project_id__in=project_ids_for(self.request.user, self.request.auth),+ )++ @extend_schema(responses=SystemRowsSerializer)+ @action(detail=True, methods=["get"])+ def rows(self, request, pk=None):+ try:+ return Response(SystemRowsSerializer(system.rows(self._step(pk))).data)+ except InputValidationError as exc:+ raise _refused(exc) from None++ @extend_schema(request=SystemOutputsSerializer, responses={201: SystemImportSerializer})+ @action(detail=True, methods=["post"])+ def outputs(self, request, pk=None):+ body = SystemOutputsSerializer(data=request.data)+ body.is_valid(raise_exception=True)+ values = body.validated_data+ try:+ run = system.send(self._step(pk), request.user, values["outputs"], values["repository"])+ except InputValidationError as exc:+ raise _refused(exc) from None+ return Response({"run": run}, status=201)diff --git a/overbae/api/project_setup.py b/overbae/api/project_setup.pynew file mode 100644index 00000000..aaf20bc9--- /dev/null+++ b/overbae/api/project_setup.py@@ -0,0 +1,35 @@+from drf_spectacular.utils import OpenApiParameter, extend_schema+from rest_framework import serializers+from rest_framework.exceptions import NotFound+from rest_framework.response import Response+from rest_framework.views import APIView++from overbae.api.scoping import project_ids_for+from overbae.models import Project+from overbae.services import project_setup+++class ProjectSetupSerializer(serializers.Serializer):+ scanned = serializers.BooleanField()+ dataset = serializers.BooleanField()+ eval_set = serializers.BooleanField()+ trained = serializers.BooleanField()+ deployed = serializers.BooleanField()+++class ProjectSetupView(APIView):+ @extend_schema(+ summary="Get the project's setup stage for Home",+ parameters=[+ OpenApiParameter(+ name="project", location=OpenApiParameter.QUERY, type=str, required=True+ )+ ],+ responses={200: ProjectSetupSerializer},+ )+ def get(self, request):+ project_id = str(request.query_params.get("project") or "")+ if project_id not in {str(p) for p in project_ids_for(request.user, request.auth)}:+ raise NotFound+ found = project_setup.setup(Project.objects.get(pk=project_id))+ return Response(ProjectSetupSerializer(found).data)diff --git a/overbae/innermind/generation.py b/overbae/innermind/generation.pyindex 9242129b..1bfc05f4 100644--- a/overbae/innermind/generation.py+++ b/overbae/innermind/generation.py@@ -249,7 +249,13 @@ def reference_of(row: row_store.DatasetRow, mode: str) -> Any:return row.expected_output+SYSTEM_OUTPUT = "_overmind_output"++def recorded_output(row: row_store.DatasetRow) -> Any:+ # What the user's own system answered (experiments' Your system stage).+ if SYSTEM_OUTPUT in (row.extra or {}):+ return row.extra[SYSTEM_OUTPUT]messages = chatml.parse_messages(row.input) or []if messages and messages[-1].get("role") == "assistant":return messages[-1]diff --git a/overbae/migrations/0073_one_agent.py b/overbae/migrations/0073_one_agent.pynew file mode 100644index 00000000..38dbd04b--- /dev/null+++ b/overbae/migrations/0073_one_agent.py@@ -0,0 +1,81 @@+from django.db import migrations, models+++def dataset_threads_to_experiments(apps, schema_editor):+ """Each dataset's conversation becomes an experiment that reads the dataset."""+ Thread = apps.get_model("overbae", "AssistantThread")+ Experiment = apps.get_model("overbae", "Experiment")+ Revision = apps.get_model("overbae", "ExperimentRevision")+ Cell = apps.get_model("overbae", "Cell")+ for thread in Thread.objects.filter(dataset__isnull=False).select_related("dataset"):+ dataset = thread.dataset+ first = thread.inputs.order_by("position").values_list("created_by_id", flat=True).first()+ author = first or dataset.created_by_id+ ready = Cell.objects.filter(dataset=dataset, state="ok").exclude(fingerprint="")+ cell = ready.filter(pk=dataset.active_id).first() or ready.order_by("-position").first()+ experiment = Experiment.objects.create(+ project_id=dataset.project_id,+ name=f"Prepare {dataset.name}"[:255],+ created_by_id=author,+ version=1 if cell else 0,+ )+ if cell is not None:+ Revision.objects.create(+ experiment=experiment,+ number=1,+ created_by_id=author,+ document={+ "parameters": [],+ "outputs": [],+ "nodes": [+ {+ "id": "data_1",+ "kind": "data",+ "title": dataset.name[:120],+ "settings": {"cell": str(cell.pk)},+ "inputs": {},+ "notes": "",+ }+ ],+ },+ )+ Experiment.objects.filter(pk=experiment.pk).update(+ created_at=thread.created_at, updated_at=thread.updated_at+ )+ Thread.objects.filter(pk=thread.pk).update(dataset=None, experiment=experiment)+ # A first pass that waited for its source would run unasked in the experiment.+ thread.inputs.filter(state="queued", request_key__startswith="first-pass:").update(+ state="removed"+ )+++class Migration(migrations.Migration):+ dependencies = [("overbae", "0072_experiment_request_fingerprint")]++ operations = [+ migrations.AddField(+ model_name="experiment",+ name="notes",+ field=models.TextField(blank=True, db_default="", default=""),+ ),+ migrations.AddField(+ model_name="experimenttrigger",+ name="max_spend_usd",+ field=models.DecimalField(blank=True, decimal_places=2, max_digits=10, null=True),+ ),+ migrations.AlterField(+ model_name="assistantinput",+ name="origin",+ field=models.CharField(+ choices=[+ ("user", "User"),+ ("run", "Run"),+ ("trigger", "Trigger"),+ ("continue", "Continue"),+ ],+ default="user",+ max_length=16,+ ),+ ),+ migrations.RunPython(dataset_threads_to_experiments, migrations.RunPython.noop),+ ]diff --git a/overbae/models/assistant.py b/overbae/models/assistant.pyindex 3385549b..d84f535f 100644--- a/overbae/models/assistant.py+++ b/overbae/models/assistant.py@@ -18,8 +18,9 @@ class ThreadQuerySet(models.QuerySet):class AssistantThread(models.Model):- """The conversation about one dataset or one experiment, shared by the project's- members. The event log is the record: no process holds state between turns."""+ """An experiment's conversation, shared by the project's members. The event log is the+ record: no process holds state between turns. ``dataset`` is unused since every+ conversation became an experiment's; a later migration drops it."""class State(models.TextChoices):IDLE = "idle"@@ -96,6 +97,8 @@ class AssistantInput(models.Model):USER = "user"RUN = "run"TRIGGER = "trigger"+ # A turn reached its time limit with work left; this input starts the next one.+ CONTINUE = "continue"id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)thread = models.ForeignKey(diff --git a/overbae/models/experiments.py b/overbae/models/experiments.pyindex 546f97c8..0d533fcd 100644--- a/overbae/models/experiments.py+++ b/overbae/models/experiments.py@@ -13,6 +13,8 @@ class Experiment(models.Model):project = models.ForeignKey("overbae.Project", on_delete=models.CASCADE)name = models.CharField(max_length=255)objective = models.TextField(blank=True, default="")+ # The agent's working notes: plan, findings, open questions. People read them.+ notes = models.TextField(blank=True, default="", db_default="")# The newest revision's number; 0 until the first save.version = models.PositiveIntegerField(default=0)created_by = models.ForeignKey(@@ -189,6 +191,9 @@ class ExperimentTrigger(models.Model):)threshold = models.PositiveIntegerField(null=True, blank=True)max_sends = models.PositiveSmallIntegerField()+ # Unattended work stops once the experiment's measured spend since the trigger was made+ # reaches this; unmeasured parts are not counted.+ max_spend_usd = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)sends = models.PositiveSmallIntegerField(default=0)next_at = models.DateTimeField(null=True, blank=True)last_sent_at = models.DateTimeField(null=True, blank=True)diff --git a/overbae/services/assistant/log.py b/overbae/services/assistant/log.pyindex 0eba4730..6e4ad1b9 100644--- a/overbae/services/assistant/log.py+++ b/overbae/services/assistant/log.py@@ -24,9 +24,7 @@ def draft_key(thread_id) -> str:def _channel(thread: AssistantThread) -> str:- if thread.experiment_id is not None:- return records.channel(thread.experiment_id)- return events.channel(thread.dataset_id)+ return records.channel(thread.experiment_id)def changed(thread: AssistantThread) -> None:diff --git a/overbae/services/assistant/prompt.py b/overbae/services/assistant/prompt.pyindex b6ae2e5d..3cd04145 100644--- a/overbae/services/assistant/prompt.py+++ b/overbae/services/assistant/prompt.py@@ -41,8 +41,8 @@ How you decideWhat you work with- You act through tools. Everything you make is a normal platform record the user can open.-- The first message about a dataset carries what the dataset holds now: its intent, the- linked capability's contract, and its versions. Each version has its `path`, its `fit`+- Each message carries the experiment and, under `datasets`, the versions its stages pin:+ each one's dataset and intent, the linked capability's contract, its `path`, its `fit`(whether its rows already fit sft, decision or eval, and why not), its exact`duplicate_rows`, and for each column the kind, null rate, examples and, from a fixedsample of `profile_sample_rows`, distinct and most common values. Start from these facts@@ -117,34 +117,31 @@ needs (`problems`) and the newest runs with each stage's state.the user changed the flow: read it with `inspect_experiment` and apply your change again ontop of theirs. Their edit stays.- Keep the models, datasets and thresholds a person chose. When one cannot run, say why and- ask; never put another in its place.+ ask; never put another in its place. A save that changes one is refused with+ `protected_setting` and kept as a proposal the person applies: say what you propose and why.+- Keep the experiment's notes current with `revise_experiment` and `notes`: the plan, what you+ measured with its numbers, and open questions. People read them; the brief carries them.- Read the stage catalogue with `inspect_experiment` and `catalog` true before you use a stagekind for the first time. Bind each input to an upstream output of the same type.- The final holdout of a Partition stage is read once, by a Qualify stage that nothing trains- or selects after. Do not try to read it elsewhere.+ or selects after. Every other tool refuses its rows.- Runs start training, evaluation, inference and data jobs that cost credits. Start one whenthe user asked for a run; otherwise review it with `plan_experiment_run`, say in a sentencewhat would run, and ask. A run is watched, not waited for: say it started and end the turn.- A notice that a run ended is the platform's, not the user's. Say in one or two sentenceswhat it measured or why it stopped. When a stage failed for a reason the flow can fix,revise it and run again with `start_experiment_run`, or retry its failed stages with- `control_experiment_run`; you may start three runs before a person asks again. When it- cannot be fixed, say what is needed.+ `control_experiment_run`; you may start three runs per person's message or trigger+ notice, and none past a trigger's spend cap. When it cannot be fixed, say what is needed."""def system(thread: AssistantThread) -> str:# Only what never changes in a thread's life: providers cache the prompt from its start.- if thread.experiment_id is not None:- subject = (- f"Project: {thread.project.name!r}. The conversation is about the experiment "- f"{thread.experiment.name!r} (id {thread.experiment_id}).\n\n{EXPERIMENT}"- )- else:- subject = (- f"Project: {thread.project.name!r}. The conversation is about the dataset "- f"{thread.dataset.name!r} (id {thread.dataset_id})."- )+ subject = (+ f"Project: {thread.project.name!r}. The conversation is about the experiment "+ f"{thread.experiment.name!r} (id {thread.experiment_id}).\n\n{EXPERIMENT}"+ )return "\n\n".join((RULES,diff --git a/overbae/services/assistant/threads.py b/overbae/services/assistant/threads.pyindex 44e7c40d..c5101d56 100644--- a/overbae/services/assistant/threads.py+++ b/overbae/services/assistant/threads.py@@ -29,13 +29,6 @@ CAPABILITY_FIELDS = ()-def open_thread(dataset: Dataset) -> AssistantThread:- """The dataset's conversation, made on first use."""- return AssistantThread.objects.get_or_create(- dataset=dataset, defaults={"project_id": dataset.project_id}- )[0]--def data_name(cell) -> str:"""The file a version has in a workspace's ``data``. A published version never changes,so its id names its rows."""@@ -45,25 +38,15 @@ def data_name(cell) -> str:def brief(thread) -> dict:"""What the conversation is about now, in JSON types: the model reads it with theuser's message, so its first step is work and not a lookup."""- if thread.experiment_id is not None:- from overbae.services.experiments import describe # lazy: experiments import threads+ from overbae.services.experiments import describe # lazy: experiments import threads- return describe.brief(thread.experiment)- dataset = thread.dataset- names = dataset.versions()- source, active = dataset.source, dataset.active_cell+ return describe.brief(thread.experiment)- def version(cell):- return {- "cell": str(cell.pk),- "title": cell.title,- "version": names.get(cell.pk),- "rows": cell.rows,- "path": f"data/{data_name(cell)}",- "fit": cell.fit(),- **_profile(cell),- }+def dataset_brief(cell) -> dict:+ """A pinned version as the model reads it: its dataset, the capability it serves, the+ recipe that made it and its columns' profile."""+ dataset = cell.datasetout = {"dataset": {"id": str(dataset.pk),@@ -71,14 +54,18 @@ def brief(thread) -> dict:"intent": dataset.intent,"train_format": dataset.train_format,},- "versions": len(names),+ "version": {+ "cell": str(cell.pk),+ "title": cell.title,+ "version": dataset.versions().get(cell.pk),+ "rows": cell.rows,+ "path": f"data/{data_name(cell)}",+ "fit": cell.fit(),+ **_profile(cell),+ },}if dataset.capability_id is not None:out["capability"] = capability_contract(dataset.capability)- if source is not None and source.ran:- out["source"] = version(source)- if active is not None and active != source:- out["latest"] = version(active)recipe = dataset.preparation_pipelineif recipe is not None:out["pipeline"] = {"id": str(recipe.family), "name": recipe.name}@@ -164,24 +151,6 @@ def capability_contract(capability) -> dict:return out-FIRST_PASS = {- Dataset.Intent.TRAIN: "Prepare this dataset for training.",- Dataset.Intent.EVAL: "Prepare this dataset for evaluation.",- Dataset.Intent.PENDING: "Prepare this dataset for the use its rows fit best.",-}-SPLIT_PASS = "Prepare this dataset for training and its evaluation split for evaluation."-FIRST_PASS_KEY = "first-pass:"---def queue_first_pass(dataset: Dataset, user, *, split: bool = False) -> AssistantInput:- """The first message of a dataset made with an intent or a brief: its turn starts once- the source lands. A split prepares both halves in one conversation, with one script."""- text = SPLIT_PASS if split else FIRST_PASS[dataset.intent]- if dataset.brief.strip():- text = f"{text}\n\n{dataset.brief.strip()}"- return send(open_thread(dataset), user, request_key=f"{FIRST_PASS_KEY}{dataset.pk}", text=text)--def send(thread,user,diff --git a/overbae/services/assistant/tools.py b/overbae/services/assistant/tools.pyindex b06944f6..4747b620 100644--- a/overbae/services/assistant/tools.py+++ b/overbae/services/assistant/tools.py@@ -23,7 +23,7 @@ from overbae.models import AssistantThread, Cell, DatasetPipeline, DatasetPipelifrom overbae.services import workspacesfrom overbae.services.assistant import presentationfrom overbae.services.assistant.threads import data_name-from overbae.services.datasets import pipeline_packages, rows+from overbae.services.datasets import partition_plans, pipeline_packages, rowsfrom overbae.services.datasets.lifecycle import DatasetErrorfrom overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import ASSISTANT, MCPContext, PlatformCredential@@ -264,21 +264,29 @@ def _platform(turn: Turn, name: str, arguments: dict) -> Outcome:return Outcome(True, content)-def _put_versions(turn: Turn, provider, versions) -> bool:- """False when the user stopped the turn before every version was copied."""+def run_cell(project_id, conversation: str, code: str, versions, timeout: int, alive):+ """Copy the named versions into the project's workspace, then run the cell in the+ conversation's kernel. None when ``alive`` turned false first: a stop ends the kernel,+ and a cell started after it would start another."""if not isinstance(versions, list) or not all(isinstance(v, str) for v in versions):raise InputValidationError("versions lists dataset version ids.")- cells = Cell.objects.filter(dataset__project=turn.thread.project_id, pk__in=versions)+ cells = Cell.objects.filter(dataset__project=project_id, pk__in=versions)if cells.count() != len(set(versions)):raise InputValidationError("A listed dataset version is not in this project.")+ partition_plans.refuse_sealed(cells)+ provider = workspaces.provider()for cell in cells:# A deleted project takes its thread along; a turn that lost it copies nothing# into a workspace its removal already cleared. A stopped turn copies nothing more.- if not turn.alive():- return False+ if not alive():+ return Nonewith open(rows.frame_path(cell), "rb") as frame:- provider.put_data(str(turn.thread.project_id), data_name(cell), frame)- return True+ provider.put_data(str(project_id), data_name(cell), frame)+ if not alive():+ return None+ return provider.run(+ str(project_id), conversation, code, max(1, min(timeout, workspaces.MAX_SECONDS))+ )def _run_python(turn: Turn, arguments) -> Outcome:@@ -288,16 +296,11 @@ def _run_python(turn: Turn, arguments) -> Outcome:raise InputValidationError("code is text and timeout is a whole number of seconds.")if len(code) > MAX_CODE_CHARS:raise InputValidationError(f"code is at most {MAX_CODE_CHARS:,} characters.")- provider = workspaces.provider()- # A stop ends the kernel; a cell started after it would start another.- if not _put_versions(turn, provider, arguments.get("versions") or []) or not turn.alive():+ thread = turn.thread+ versions = arguments.get("versions") or []+ run = run_cell(thread.project_id, thread.pk.hex, code, versions, timeout, turn.alive)+ if run is None:return Outcome(False, {"error": "The user stopped the conversation."})- run = provider.run(- str(turn.thread.project_id),- turn.thread.pk.hex,- code,- max(1, min(timeout, workspaces.MAX_SECONDS)),- )content = {"output": run.output, "error": run.error, "truncated": run.truncated}if run.restarted:content["note"] = run.restarteddiff --git a/overbae/services/assistant/turn.py b/overbae/services/assistant/turn.pyindex 0e768b93..a71c3fd0 100644--- a/overbae/services/assistant/turn.py+++ b/overbae/services/assistant/turn.py@@ -17,6 +17,8 @@ from datetime import timedeltafrom django.conf import settingsfrom django.contrib.auth import get_user_modelfrom django.db import transaction+from django.db.models import OuterRef, Subquery+from django.db.models.fields.json import KTfrom django.utils import timezonefrom overbae.core import telemetry@@ -26,8 +28,7 @@ from overbae.models import (AssistantEvent,AssistantInput,AssistantThread,- Cell,- Dataset,+ Project,)from overbae.models.assistant import STALEfrom overbae.services import workspaces@@ -49,6 +50,11 @@ TURN_SECONDS = 30 * 60# A turn whose heartbeat is this old lost its worker and may be taken over.LEASE = timedelta(minutes=2)RESUMES = 2+# Continued turns since a person last wrote: 8 × 30 min bounds unattended work at 4 h.+CONTINUES = 8+# Turns a project runs at once for work no person started: run ends, triggers, continues.+UNATTENDED_TURNS = 3+WAITING = "waiting"DRAFT_INTERVAL_SECONDS = 0.1ABANDONED = {"error": "This call has no recorded result: the turn stopped or was interrupted. It may "@@ -77,23 +83,27 @@ def wake(thread: AssistantThread) -> None:def ready(thread):- """The queued messages a turn may take. The first pass prepares landed rows: after an- import fails it stays queued for the landing that succeeds."""- queued = thread.inputs.filter(state=Queued)- if thread.dataset_id is None:- return queued- if not Cell.objects.filter(- dataset_id=thread.dataset_id, position=0, state=Cell.State.OK- ).exists():- queued = queued.exclude(request_key__startswith=threads.FIRST_PASS_KEY)- return queued---def wake_dataset(dataset_id) -> None:- """The dataset's source landed: a message that waited for it may start its turn."""- thread = AssistantThread.objects.filter(dataset_id=dataset_id).first()- if thread is not None and ready(thread).exists():- wake(thread)+ """The queued messages a turn may take."""+ return thread.inputs.filter(state=Queued)+++def waiting(project_id=None):+ """Threads the unattended limit held back: their newest event says so. A thread whose+ turn failed since waits for a person's message instead."""+ newest = AssistantEvent.objects.filter(thread=OuterRef("pk")).order_by("-sequence")+ found = (+ AssistantThread.objects.filter(+ state=State.IDLE,+ experiment__deleted_at=None,+ pk__in=AssistantInput.objects.filter(state=Queued).values("thread"),+ )+ .annotate(+ last_kind=Subquery(newest.values("kind")[:1]),+ last_state=Subquery(newest.annotate(state=KT("payload__state")).values("state")[:1]),+ )+ .filter(last_kind=Kind.STATUS, last_state=WAITING)+ )+ return found if project_id is None else found.filter(project=project_id)def settle(thread: AssistantThread) -> AssistantThread:@@ -125,7 +135,8 @@ def _interrupt(held) -> None:def resume_lost() -> int:- """Wake every turn whose worker stopped beating; ``run`` takes each over."""+ """Wake every turn whose worker stopped beating; ``run`` takes each over. Wake threads+ that wait for a turn slot too, for a slot a lost or interrupted turn freed."""from overbae.tasks.assistant import run_turn # lazy: tasks import the API serializerslost = AssistantThread.objects.filter(@@ -134,6 +145,8 @@ def resume_lost() -> int:for thread_id in lost:telemetry.report_failure("Assistant turn lost its worker", thread_id=thread_id)run_turn.delay(str(thread_id))+ for thread_id in waiting().values_list("pk", flat=True):+ run_turn.delay(str(thread_id))return len(lost)@@ -166,20 +179,28 @@ def run(thread_id) -> None:# After a failure the next message starts the turn: the one that failed would fail again.if not failed and ready(thread).exists():wake(thread)+ # A turn slot freed: unattended work that waited for one may start.+ for other in waiting(thread.project_id).exclude(pk=thread.pk)[:UNATTENDED_TURNS]:+ wake(other)def _begin(thread_id) -> tuple[AssistantThread | None, bool]:"""Take the thread for a turn, when a message waits and nothing holds it, or take overa turn whose worker was lost. True with a take-over."""thread = settle(- AssistantThread.objects.select_related("project", "dataset", "experiment").get(pk=thread_id)+ AssistantThread.objects.select_related("project", "experiment").get(pk=thread_id))with transaction.atomic():thread = (AssistantThread.objects.select_for_update(of=("self",))- .select_related("project", "dataset", "experiment")+ .select_related("project", "experiment").get(pk=thread_id))+ if thread.experiment is None or thread.experiment.deleted_at is not None:+ # A deleted experiment's turn ends; a thread without one has no subject.+ if thread.state == State.RUNNING:+ _interrupt(thread)+ return None, Falseresumed = thread.state == State.RUNNINGif resumed:if thread.updated_at >= timezone.now() - LEASE:@@ -192,10 +213,24 @@ def _begin(thread_id) -> tuple[AssistantThread | None, bool]:thread.save(update_fields=["turn", "updated_at"])_status(thread, "resumed", "The reply continues after its worker stopped.")else:- if not ready(thread).exists():+ queued = ready(thread)+ if not queued.exists():return None, False- # A first message on a new dataset waits for its source; landing wakes the thread.- if thread.dataset_id and thread.dataset.state == Dataset.State.LANDING:+ # A person's message never waits; unattended work shares a few turns per project,+ # counted under the project's lock so two admissions never both pass.+ if not queued.filter(origin=AssistantInput.Origin.USER).exists():+ Project.objects.select_for_update().filter(pk=thread.project_id).exists()+ busy = AssistantThread.objects.moving().filter(project=thread.project_id)+ if (+ not queued.filter(origin=AssistantInput.Origin.USER).exists()+ and busy.count() >= UNATTENDED_TURNS+ ):+ if not waiting(thread.project_id).filter(pk=thread.pk).exists():+ log.append(+ thread,+ Kind.STATUS,+ {"state": WAITING, "detail": "Waits for a free turn in this project."},+ )return None, Falsethread.state, thread.stop_requested = State.RUNNING, Falsethread.turn += 1@@ -267,10 +302,13 @@ def _stopped(thread) -> None:def _turn(thread) -> None:deadline = time.monotonic() + TURN_SECONDSmessage = ready(thread).order_by("-urgent", "position").first()- # Past the deadline the rest stay queued: ``run`` starts the next turn for them.- while message is not None and time.monotonic() < deadline:+ # A turn takes at least its first message; past the deadline the rest stay queued and+ # ``run`` starts the next turn for them.+ while message is not None:if _deliver(thread, message):_answer(thread, deadline)+ if time.monotonic() >= deadline:+ breakmessage = ready(thread).order_by("-urgent", "position").first()@@ -281,9 +319,7 @@ def _answer(thread, deadline: float) -> None:if not _alive(thread):raise _StoppedErrorif time.monotonic() > deadline:- _status(- thread, "failed", "The turn reached its time limit. Send a message to continue."- )+ _continue(thread)return# A message sent "now" joins at the next model call.for urgent in ready(thread).filter(urgent=True).order_by("position"):@@ -333,8 +369,8 @@ def _actor(thread):def _deliver(thread, message) -> bool:- # The model reads what the dataset holds with a message, once: again only when it- # changed, or when a summary replaced the message that carried it.+ # The model reads the brief with a message, once: again only when it changed, or when a+ # summary replaced the message that carried it.window = _window(thread)known = next((@@ -344,14 +380,8 @@ def _deliver(thread, message) -> bool:),None,)- # Saving a recipe or a flow revision updates the row, not the record this turn loaded.- # A turn's publish changes these; the brief reads them fresh.- if thread.dataset_id is not None:- thread.dataset.refresh_from_db(- fields=["preparation_pipeline", "intent", "train_format", "capability", "source_spec"]- )- if thread.experiment_id is not None:- thread.experiment.refresh_from_db(fields=["name", "objective", "version"])+ # Saving a flow revision updates the row, not the record this turn loaded.+ thread.experiment.refresh_from_db(fields=["name", "objective", "version", "notes"])now = threads.brief(thread)with transaction.atomic():# The thread first, as every queue change locks it: a stop that came after the@@ -460,7 +490,33 @@ def _compact(thread, payer) -> None:)+def _continue(thread) -> None:+ """The turn ran out of time with work left: queue its next turn, up to a limit since+ a person last wrote, so unattended work stays bounded."""+ since = (+ thread.inputs.filter(origin=AssistantInput.Origin.USER)+ .order_by("-position")+ .values_list("position", flat=True)+ .first()+ )+ done = thread.inputs.filter(origin=AssistantInput.Origin.CONTINUE, position__gt=since or 0)+ user = _actor(thread)+ if done.count() >= CONTINUES or user is None:+ _status(thread, "failed", "The work reached its time limit. Send a message to continue.")+ return+ _status(thread, "continued", "The work continues in a new turn.")+ threads.send(+ thread,+ user,+ request_key=f"continue:{thread.turn}:{done.count()}",+ text="Continue where you stopped.",+ origin=AssistantInput.Origin.CONTINUE,+ )++NOTICES = {+ AssistantInput.Origin.CONTINUE: "Your previous turn reached its time limit with work left. "+ "This is the platform's notice, not the user's words.",AssistantInput.Origin.RUN: "A run of this experiment ended. This is the platform's notice, ""not the user's words.",AssistantInput.Origin.TRIGGER: "A trigger of this experiment fired with this instruction. "@@ -661,7 +717,7 @@ def stop(thread: AssistantThread) -> None:lambda: stop_kernel.delay(str(held.project_id), str(held.pk), held.turn))elif held.inputs.filter(state=Queued).exists():- # Messages that wait for the dataset's source to land.+ # Messages that wait for a turn slot.log.append(held, Kind.STATUS, {"state": "stopped", "detail": "Stopped."})held.inputs.filter(state=Queued).update(state=AssistantInput.State.REMOVED)log.changed(thread)diff --git a/overbae/services/datasets/admission.py b/overbae/services/datasets/admission.pyindex 778cb3ef..9abb9f0d 100644--- a/overbae/services/datasets/admission.py+++ b/overbae/services/datasets/admission.py@@ -390,14 +390,6 @@ def reconcile(publish):lease_until=None,updated_at=now,)- # Lazy: the assistant reaches the MCP catalog, which imports this module.- from overbae.services.assistant.turn import wake_dataset-- # A message sent with the upload waited for its source; landing has ended.- for target in targets:- transaction.on_commit(- lambda dataset_id=target.pk: wake_dataset(dataset_id), robust=True- )DatasetLandingWork.objects.filter(state="waiting").exclude(dataset__state="landing").update(state="cancelled", finished_at=now, updated_at=now)diff --git a/overbae/services/datasets/exploration.py b/overbae/services/datasets/exploration.pyindex b4197fad..bdc4b43b 100644--- a/overbae/services/datasets/exploration.py+++ b/overbae/services/datasets/exploration.py@@ -14,6 +14,7 @@ from overbae.services.datasets import (heartbeat,land,lineage,+ partition_plans,paths,profile,rows,@@ -37,6 +38,7 @@ def request(project, *, source_cell, name, request_key, kind, sampling_request=N"profile_version": PROFILE_VERSION,"sampling": sampling.validate_request(**sampling_request) if sampling_request else None,}+ partition_plans.refuse_sealed([source_cell])Project.objects.select_for_update().get(pk=project.pk)prior = DataExploration.objects.filter(project=project, request_key=request_key).first()if prior:diff --git a/overbae/services/datasets/imports.py b/overbae/services/datasets/imports.pyindex e08db251..65b6f6b1 100644--- a/overbae/services/datasets/imports.py+++ b/overbae/services/datasets/imports.py@@ -237,18 +237,12 @@ def _block(run, code, error):Dataset.objects.filter(pk__in=_target_ids(run), state=Dataset.State.LANDING).update(state=Dataset.State.ERROR, error=run.error, updated_at=timezone.now())- # Lazy: the assistant reaches the MCP catalog, which imports this module.- from overbae.services.assistant.turn import wake_dataset-for dataset_id in _target_ids(run):transaction.on_commit(lambda dataset_id=dataset_id: events.publish(dataset_id, {"dataset_id": str(dataset_id), "type": "land_failed", "error": error}))- # A message sent with the upload waited for this source; it is read once the- # source's error is committed, or a turn could still see it landing.- transaction.on_commit(lambda dataset_id=dataset_id: wake_dataset(dataset_id), robust=True)@transaction.atomic@@ -779,16 +773,8 @@ def execute(task_id, inputs):return {"status": "failed", "error": str(exc)}finally:beat.set()- # Lazy: the assistant reaches the MCP catalog, which imports this module.- from overbae.services.assistant.turn import wake_dataset-try:for target_id in [] if retrying else _target_ids(run):operations.finished(target_id, task_id=str(run.pk))- # A message sent with the upload waited for its source, landed or failed.- try:- wake_dataset(target_id)- except Exception: # noqa: BLE001 - the next message wakes the conversation- logger.exception("assistant not woken for dataset %s", target_id)finally:shutil.rmtree(stage, ignore_errors=True)diff --git a/overbae/services/datasets/lifecycle.py b/overbae/services/datasets/lifecycle.pyindex 4776b1ba..8dad8305 100644--- a/overbae/services/datasets/lifecycle.py+++ b/overbae/services/datasets/lifecycle.py@@ -8,7 +8,7 @@ from typing import Anyfrom django.db import transactionfrom django.utils import timezone-from overbae.models import AssistantThread, Capability, Cell, Dataset+from overbae.models import Capability, Cell, Datasetfrom overbae.services.datasets import measure, paths@@ -137,6 +137,13 @@ def delete_blocked_reason(dataset: Dataset) -> str:return "A transformation is running. Wait for it to finish."if dataset.cells.filter(pipeline_artifacts__isnull=False).exists():return "A version is retained as an external transformation artifact. This dataset cannot be deleted."+ # Lazy: the experiments package imports dataset services.+ from overbae.services.experiments import records++ used_in = (records.dataset_links(dataset.project_id).get(str(dataset.pk)) or {}).get("used_in")+ if used_in:+ names = ", ".join(sorted(link["name"] for link in used_in)[:3])+ return f"The experiment {names} uses this dataset, so it cannot be deleted."used = [c for c in dataset.cells.all() if c.used_at is not None or any(usage(c).values())]if used:versions = dataset.versions()@@ -153,14 +160,10 @@ def delete_dataset(dataset: Dataset) -> None:directory = paths.dataset_dir(dataset.id)project = str(dataset.project_id)copies = [f"{cell}.parquet" for cell in dataset.cells.values_list("pk", flat=True)]- conversations = [- pk.hex- for pk in AssistantThread.objects.filter(dataset=dataset).values_list("pk", flat=True)- ]dataset.delete()shutil.rmtree(directory, ignore_errors=True)# Lazy: the tasks package imports this module.from overbae.tasks.assistant import forget_workspace_data# The assistant's workspace holds copies of the dataset's versions.- transaction.on_commit(lambda: forget_workspace_data.delay(project, copies, conversations))+ transaction.on_commit(lambda: forget_workspace_data.delay(project, copies, []))diff --git a/overbae/services/datasets/list_activity.py b/overbae/services/datasets/list_activity.pyindex 2a26167d..db790fc5 100644--- a/overbae/services/datasets/list_activity.py+++ b/overbae/services/datasets/list_activity.py@@ -1,4 +1,4 @@-from overbae.models import Activity, AssistantThread, DatasetPipelineRun, DatasetTransfer+from overbae.models import Activity, DatasetPipelineRun, DatasetTransferLANDING_STAGES = {"writing": "Writing", "measuring": "Measuring"}RUN_STAGES = {@@ -87,22 +87,4 @@ def current_work(datasets):"total": sum(member["size"] for member in members),"unit": "bytes",}- # A conversation whose turn runs is preparing its dataset, even between jobs; a turn- # lost with its worker is not.- for dataset_id in (- AssistantThread.objects.moving()- .filter(dataset_id__in=ids)- .values_list("dataset_id", flat=True)- ):- work.setdefault(- str(dataset_id),- {- "label": "Preparing",- "status": "running",- "actor_kind": "overmind",- "completed": None,- "total": None,- "unit": "",- },- )return workdiff --git a/overbae/services/datasets/partition_plans.py b/overbae/services/datasets/partition_plans.pyindex 9948f566..e11b7259 100644--- a/overbae/services/datasets/partition_plans.py+++ b/overbae/services/datasets/partition_plans.py@@ -20,6 +20,27 @@ from overbae.services.datasets.partition import GROUP_ALIASESROLES = ("train", "development", "calibration", "final")+class SealedHoldoutError(InputValidationError):+ """A final holdout's rows were asked for outside its one Qualify stage."""+++def sealed(cells):+ """The final holdouts among ``cells``."""+ return DataPartitionMember.objects.filter(role="final", cell__in=list(cells)).values_list(+ "cell_id", flat=True+ )+++def refuse_sealed(cells) -> None:+ """Agents read no final holdout row: neither in a workspace, a query, an exploration nor+ a Your system stage."""+ found = sealed(cells).first()+ if found is not None:+ raise SealedHoldoutError(+ f"Version {found} is a sealed final holdout: only a Qualify stage reads it, once."+ )++def validate_recipe(recipe):if not isinstance(recipe, dict) or set(recipe) - {"seed",diff --git a/overbae/services/experiments/catalog.py b/overbae/services/experiments/catalog.pyindex 8e6a4aaf..fc8b4a08 100644--- a/overbae/services/experiments/catalog.py+++ b/overbae/services/experiments/catalog.py@@ -243,14 +243,26 @@ KINDS = {},required=("experiment", "candidates"),),+ Kind(+ "system",+ "Your system",+ "Evaluation",+ "Your own application answers each row where it runs; `overmind run` sends its outputs",+ inputs=(Port("data", "data", required=True),),+ outputs=(Port("data", "data"),),+ settings={+ "label": _text("Label", description="What the outputs are from, such as a branch."),+ "max_items": _number("Rows, at most", 200, 1, 2000, "integer"),+ },+ ),Kind("evaluate","Evaluate","Evaluation",- "Score models on a dataset version with benchmark criteria",+ "Score models, and outputs of your system, on a dataset version with benchmark criteria",inputs=(Port("data", "data", required=True),- Port("model", "model", required=True, many=True),+ Port("model", "model", many=True),Port("suite", "suite"),),outputs=(Port("scores", "scores"),),diff --git a/overbae/services/experiments/describe.py b/overbae/services/experiments/describe.pyindex a49d53e0..df4b022d 100644--- a/overbae/services/experiments/describe.py+++ b/overbae/services/experiments/describe.py@@ -1,16 +1,28 @@"""An experiment and its runs as the Console, MCP and the experiment's agent read them."""import json+from decimal import Decimalfrom django.db.models import Count, Prefetch-from overbae.models import Experiment, ExperimentRun, ExperimentStep+from overbae.models import (+ Cell,+ EvalRunRow,+ Experiment,+ ExperimentRun,+ ExperimentStep,+ FinetuningJob,+)+from overbae.services.assistant import threads+from overbae.services.datasets import partition_plansfrom overbae.services.experiments import document as flowfrom overbae.services.experiments import recordsACTIVE = (ExperimentRun.State.RUNNING, ExperimentRun.State.STOPPING)# Runs the agent's brief carries; older ones it reads with inspect_experiment.BRIEF_RUNS = 3+# Pinned versions the brief profiles; the rest the agent reads with tools.+BRIEF_DATASETS = 4# A run's state in get_job's terms: an incomplete run failed, a stopped one was cancelled.JOB_STATUS = {ExperimentRun.State.UNMET: "failed", ExperimentRun.State.STOPPED: "cancelled"}@@ -144,6 +156,8 @@ def brief(found: Experiment) -> dict:"version": found.version,},"flow": document,+ "notes": found.notes,+ "datasets": _pinned(found.project, document),"problems": flow.problems(document),"runs": [{**summary(item), "stages": _stage_states(item)} for item in runs[:BRIEF_RUNS]],"triggers": triggers(found),@@ -151,6 +165,60 @@ def brief(found: Experiment) -> dict:return json.loads(json.dumps(out, default=str))+def _pinned(project, document) -> list[dict]:+ """The first versions the flow pins, profiled, so the agent's first step is work. A final+ holdout is never profiled for an agent."""+ cells = {item["cell"] for item in records.pinned_datasets(project, document)}+ found = (+ Cell.objects.select_related("dataset__capability")+ .filter(pk__in=cells)+ .exclude(pk__in=partition_plans.sealed(cells))+ )+ return [+ threads.dataset_brief(cell) for cell in found.order_by("dataset__name")[:BRIEF_DATASETS]+ ]+++def spend(found: Experiment, since=None) -> dict:+ """What the experiment's work cost as measured, in USD, and the parts no record prices:+ an unmeasured part is named, never estimated."""+ unknown, total = set(), Decimal(0)+ events = found.assistant_thread.events.all()+ roots = found.runs.filter(parent=None).values_list("pk", flat=True)+ steps = ExperimentStep.objects.filter(run__in=records.run_tree(roots))+ if since is not None:+ events, steps = events.filter(created_at__gte=since), steps.filter(started_at__gte=since)+ if events.filter(kind="tool_result", payload__name="run_python").exists():+ unknown.add("workspace time")+ for cost in events.filter(kind__in=["assistant", "summary"]).values_list(+ "payload__usage__response_cost", flat=True+ ):+ if isinstance(cost, int | float):+ total += Decimal(str(cost))+ else:+ unknown.add("agent calls priced later")+ receipts = [+ r for found_receipts in steps.values_list("receipts", flat=True) for r in found_receipts+ ]+ jobs = [r["id"] for r in receipts if r.get("kind") == "finetune_job"]+ for cost in FinetuningJob.objects.filter(pk__in=jobs).values_list("cost_usd", flat=True):+ if cost is None:+ unknown.add("training not priced yet")+ else:+ total += cost+ runs = [r["id"] for r in receipts if r.get("kind") == "eval_run"]+ if runs:+ unknown.add("evaluation judging")+ for cost in EvalRunRow.objects.filter(run__in=runs).values_list(+ "metadata__cost", flat=True+ ):+ if isinstance(cost, int | float):+ total += Decimal(str(cost))+ named = {"native_evaluation": "decision evaluation", "deployment": "serving"}+ unknown |= {named[r["kind"]] for r in receipts if r.get("kind") in named}+ return {"measured_usd": float(round(total, 4)), "unknown": sorted(unknown)}++def triggers(found: Experiment) -> list[dict]:return [{@@ -162,6 +230,7 @@ def triggers(found: Experiment) -> list[dict]:"threshold": trigger.threshold,"sends": trigger.sends,"max_sends": trigger.max_sends,+ "max_spend_usd": trigger.max_spend_usd,"next_at": trigger.next_at,"last_sent_at": trigger.last_sent_at,}diff --git a/overbae/services/experiments/document.py b/overbae/services/experiments/document.pyindex b81e8aa5..011d9be4 100644--- a/overbae/services/experiments/document.py+++ b/overbae/services/experiments/document.py@@ -137,6 +137,14 @@ def _node(raw) -> dict:"settings": settings,"inputs": bound,"notes": str(raw.get("notes") or "")[:4000],+ # The settings a person set: the agent proposes changes to them, a person applies.+ "protected": sorted(+ {+ key+ for key in (raw.get("protected") if isinstance(raw.get("protected"), list) else [])+ if isinstance(key, str) and key in settings+ }+ ),}diff --git a/overbae/services/experiments/operator.py b/overbae/services/experiments/operator.pyindex ccd147a8..93aa5210 100644--- a/overbae/services/experiments/operator.py+++ b/overbae/services/experiments/operator.py@@ -15,9 +15,14 @@ ENDED = {def notify(experiment, user, *, origin: str, text: str, request_key: str):"""Queue a notice for the experiment's agent, sent as ``user``: the turn acts with their- access. Nothing is sent for a person who left the project."""+ access. Nothing is sent for a person who left the project, nor to a deleted+ experiment."""thread = getattr(experiment, "assistant_thread", None)- if thread is None or not experiment.project.memberships.filter(user=user).exists():+ if (+ thread is None+ or experiment.deleted_at is not None+ or not experiment.project.memberships.filter(user=user).exists()+ ):return Nonemessage = threads.send(thread, user, request_key=request_key, text=text, origin=origin)turn.wake(thread)diff --git a/overbae/services/experiments/records.py b/overbae/services/experiments/records.pyindex 75ed173e..f76d0498 100644--- a/overbae/services/experiments/records.py+++ b/overbae/services/experiments/records.py@@ -5,7 +5,7 @@ import jsonimport uuidfrom django.db import IntegrityError, transaction-from django.db.models import Max+from django.db.models import F, Maxfrom django.utils import timezonefrom overbae.core.errors import InputValidationError@@ -16,6 +16,7 @@ from overbae.models import (ExperimentEvent,ExperimentRevision,ExperimentRun,+ ExperimentStep,)from overbae.services.datasets import eventsfrom overbae.services.experiments import document as flow@@ -70,14 +71,79 @@ def data_stages(project, cells) -> dict:def pinned_datasets(project, document: dict) -> list[dict]:"""The dataset versions the flow's stages pin, as a data port carries them."""- ids = set()+ ids = set(_cells(document))+ cells = Cell.objects.select_related("dataset").filter(dataset__project=project, pk__in=ids)+ return [data_value(cell) for cell in cells]+++def dataset_links(project_id) -> dict[str, dict]:+ """For each dataset of the project: the experiment whose run made it and the live+ experiments whose newest revision reads it, newest first."""+ live = Experiment.objects.filter(project=project_id, deleted_at=None)+ names = dict(live.values_list("pk", "name"))+ links: dict[str, dict] = {}++ steps = (+ ExperimentStep.objects.filter(+ run__experiment__in=live, state=ExperimentStep.State.COMPLETED+ )+ .order_by("started_at")+ .values_list("outputs", "run__experiment_id", "started_at")+ )+ outputs = [+ (value["cell"], experiment, started)+ for found, experiment, started in steps+ for value in (found or {}).values()+ if isinstance(value, dict) and value.get("cell")+ ]+ cells = {+ str(pk): (dataset, created)+ for pk, dataset, created in Cell.objects.filter(+ pk__in={cell for cell, _, _ in outputs}+ ).values_list("pk", "dataset_id", "created_at")+ }+ for cell, experiment, started in outputs:+ dataset, created = cells.get(cell, (None, None))+ # A stage made the version when it appeared during the stage; a Data stage only reads.+ if dataset is not None and started is not None and created >= started:+ entry = links.setdefault(str(dataset), {"made_by": None, "used_in": []})+ entry["made_by"] = {"experiment": str(experiment), "name": names[experiment]}+ revisions = ExperimentRevision.objects.filter(+ experiment__in=live, number=F("experiment__version")+ ).order_by("-experiment__updated_at")+ pins = [(revision.experiment_id, _cells(revision.document)) for revision in revisions]+ owner = dict(+ Cell.objects.filter(pk__in={c for _, cells in pins for c in cells}).values_list(+ "pk", "dataset_id"+ )+ )+ for experiment, cells in pins:+ for dataset in dict.fromkeys(str(owner[c]) for c in cells if c in owner):+ entry = links.setdefault(dataset, {"made_by": None, "used_in": []})+ entry["used_in"].append({"experiment": str(experiment), "name": names[experiment]})+ return links+++def run_tree(roots) -> list:+ """The runs and every child run their stages started, at any depth: a child run of+ another experiment's flow is still this work's."""+ found, frontier = [], list(roots)+ while frontier:+ found += frontier+ frontier = list(+ ExperimentRun.objects.filter(parent__run__in=frontier).values_list("pk", flat=True)+ )+ return found+++def _cells(document: dict) -> list[uuid.UUID]:+ found = []for node in document.get("nodes") or []:try:- ids.add(uuid.UUID(str((node.get("settings") or {}).get("cell"))))+ found.append(uuid.UUID(str((node.get("settings") or {}).get("cell"))))except ValueError:continue- cells = Cell.objects.select_related("dataset").filter(dataset__project=project, pk__in=ids)- return [data_value(cell) for cell in cells]+ return founddef fingerprint(value) -> str:@@ -86,7 +152,9 @@ def fingerprint(value) -> str:return hashlib.sha256(text.encode()).hexdigest()-def create(project, user, *, name="", objective="", request_key="", document=None) -> Experiment:+def create(+ project, user, *, name="", objective="", request_key="", document=None, agent=False+) -> Experiment:"""A new experiment and its conversation. The same request key with the same requestreturns the first one; with a different request it is refused."""asked = fingerprint({"name": name, "objective": objective, "document": document})@@ -109,7 +177,7 @@ def create(project, user, *, name="", objective="", request_key="", document=Non)AssistantThread.objects.create(project=project, experiment=experiment)if document is not None:- revise(experiment, user, document=document, expected_version=0)+ revise(experiment, user, document=document, expected_version=0, agent=agent)except IntegrityError:return _replayed(Experiment.objects.get(project=project, request_key=request_key), asked)return experiment@@ -131,6 +199,19 @@ def rename(experiment: Experiment, name: str) -> Experiment:return experiment+def kernel(experiment: Experiment) -> str:+ """Coding agents' kernel and folder in the experiment's workspace, apart from its own+ agent's."""+ return uuid.uuid5(experiment.assistant_thread.pk, "mcp").hex+++def write_notes(experiment: Experiment, notes: str) -> Experiment:+ Experiment.objects.filter(pk=experiment.pk).update(notes=notes[:20_000])+ log(experiment, "notes", {"chars": len(notes)})+ experiment.refresh_from_db()+ return experiment++def delete(experiment: Experiment) -> None:"""Soft delete. Runs still moving are stopped first, so nothing works unseen."""from overbae.services.experiments import runs # lazy: runs imports this module@@ -142,21 +223,43 @@ def delete(experiment: Experiment) -> None:runs.stop(run)Experiment.objects.filter(pk=experiment.pk).update(deleted_at=timezone.now())experiment.triggers.filter(deleted_at=None).update(deleted_at=timezone.now())+ # Lazy: the tasks package imports the services.+ from overbae.tasks.assistant import forget_workspace_data++ # The agent's and coding agents' files in the workspace go with the experiment.+ project = str(experiment.project_id)+ conversations = [experiment.assistant_thread.pk.hex, kernel(experiment)]+ transaction.on_commit(lambda: forget_workspace_data.delay(project, [], conversations))+ # Lazy: the assistant imports this module. Its turn stops and its queued notices go.+ from overbae.services.assistant import turn++ turn.stop(experiment.assistant_thread)+++class ProtectedSettingError(InputValidationError):+ """The agent's save changes a setting a person set; it was kept as a proposal."""def revise(- experiment: Experiment, user, *, document, expected_version: int, request_key=""+ experiment: Experiment,+ user,+ *,+ document,+ expected_version: int,+ request_key="",+ agent=False,) -> ExperimentRevision:"""Save the document as the next revision. ``expected_version`` is the revision theeditor started from: a save over a newer one is refused, so neither the user nor the- agent overwrites the other's change unseen."""+ agent overwrites the other's change unseen. A person's save marks the settings they set+ as protected; the agent's save that changes one is kept as a proposal instead."""normalized = flow.normalize(document)with transaction.atomic():held = Experiment.objects.select_for_update().get(pk=experiment.pk)if request_key:prior = held.revisions.filter(request_key=request_key).first()if prior is not None:- if fingerprint(prior.document) != fingerprint(normalized):+ if fingerprint(_unmarked(prior.document)) != fingerprint(_unmarked(normalized)):raise InputValidationError("This request key identifies a different save.")return priorif held.version != expected_version:@@ -164,19 +267,156 @@ def revise(f"Revision {held.version} was saved after revision {expected_version}. ""Load the latest revision and apply the change again.")- revision = ExperimentRevision.objects.create(- experiment=held,- number=held.version + 1,- document=normalized,- created_by=user,- request_key=request_key,+ base = current(held)+ changes = _protect(base, normalized, agent=agent)+ if not changes:+ revision = ExperimentRevision.objects.create(+ experiment=held,+ number=held.version + 1,+ document=normalized,+ created_by=user,+ request_key=request_key,+ )+ Experiment.objects.filter(pk=held.pk).update(version=revision.number)+ log(held, "revision", {"number": revision.number, "user": getattr(user, "pk", None)})+ if changes:+ # A retried refused save is the same proposal, not another one.+ if not any(p.payload["document"] == normalized for p in _open_proposals(held)):+ log(+ experiment,+ "proposal",+ {"base": held.version, "document": normalized, "changes": changes},+ )+ names = ", ".join(f"{c['title']} {c['key']}" for c in changes[:3])+ raise ProtectedSettingError(+ f"A person set {names}. The change is saved as a proposal they can apply: say what "+ "you propose and why, and wait for them.")- Experiment.objects.filter(pk=held.pk).update(version=revision.number)- log(held, "revision", {"number": revision.number, "user": getattr(user, "pk", None)})experiment.refresh_from_db()return revision+def _unmarked(document: dict) -> dict:+ return {+ **document,+ "nodes": [{k: v for k, v in n.items() if k != "protected"} for n in document["nodes"]],+ }+++def _protect(base: dict, document: dict, *, agent: bool) -> list[dict]:+ """Carry each stage's protected settings into ``document``. A person's save protects+ what it set; the agent's save keeps the marks and returns each protected setting it+ changes."""+ before = {node["id"]: node for node in base.get("nodes") or []}+ after = {node["id"] for node in document["nodes"]}+ changes = []+ for node in document["nodes"]:+ old = before.get(node["id"])+ marked = set(old.get("protected") or []) if old else set()+ kept = marked if old and old["kind"] == node["kind"] else set()+ if agent and marked - kept:+ # Another kind under the same id replaces the stage and every setting a person set.+ changes += [_change(old, key, None) for key in sorted(marked)]+ if agent:+ for key in sorted(kept):+ if node["settings"].get(key) != old["settings"].get(key):+ changes.append(_change(old, key, node["settings"].get(key)))+ node["protected"] = sorted(kept & set(node["settings"]))+ else:+ set_now = {+ key+ for key, value in node["settings"].items()+ if old is None or old["settings"].get(key) != value+ }+ node["protected"] = sorted((kept | set_now) & set(node["settings"]))+ if agent:+ for node_id, old in before.items():+ if node_id not in after:+ changes += [_change(old, key, None) for key in old.get("protected") or []]+ return changes+++def _change(node: dict, key: str, value) -> dict:+ return {+ "node": node["id"],+ "title": node["title"],+ "key": key,+ "before": node["settings"].get(key),+ "after": value,+ }+++def _open_proposals(experiment: Experiment) -> list:+ """Proposal events no person applied or dismissed, on the newest revision."""+ events = experiment.events.filter(kind__in=["proposal", "proposal_resolved"])+ resolved = {event.payload["proposal"] for event in events if event.kind == "proposal_resolved"}+ return [+ event+ for event in events+ if event.kind == "proposal"+ and event.sequence not in resolved+ and event.payload["base"] == experiment.version+ ]+++def proposals(experiment: Experiment) -> list[dict]:+ """The agent's proposals a person has not applied or dismissed, on the newest revision."""+ found = _open_proposals(experiment)+ # A dataset version reads as its dataset's name.+ pinned = {+ str(c["after"] if side else c["before"])+ for event in found+ for c in event.payload["changes"]+ if c["key"] == "cell"+ for side in (0, 1)+ }+ names = {+ str(pk): name+ for pk, name in Cell.objects.filter(+ dataset__project=experiment.project_id, pk__in=_uuids(pinned)+ ).values_list("pk", "dataset__name")+ }+ return [+ {+ "sequence": event.sequence,+ "changes": [+ {+ **change,+ "before_label": names.get(str(change["before"])),+ "after_label": names.get(str(change["after"])),+ }+ for change in event.payload["changes"]+ ],+ }+ for event in found+ ]+++def _uuids(values) -> list[uuid.UUID]:+ found = []+ for value in values:+ try:+ found.append(uuid.UUID(value))+ except ValueError:+ continue+ return found+++def resolve_proposal(experiment: Experiment, user, sequence: int, *, apply: bool):+ """Apply the agent's proposal as the person's own save, or dismiss it."""+ event = experiment.events.filter(kind="proposal", sequence=sequence).first()+ if event is None or sequence not in {p["sequence"] for p in proposals(experiment)}:+ raise InputValidationError("This proposal was already resolved or the flow changed.")+ if apply:+ revise(+ experiment,+ user,+ document=event.payload["document"],+ expected_version=event.payload["base"],+ )+ log(experiment, "proposal_resolved", {"proposal": sequence, "applied": apply})++def revision(experiment: Experiment, number: int | None = None) -> ExperimentRevision | None:found = experiment.revisions.all()if number is not None:diff --git a/overbae/services/experiments/runs.py b/overbae/services/experiments/runs.pyindex 49f4f15d..c6a19a78 100644--- a/overbae/services/experiments/runs.py+++ b/overbae/services/experiments/runs.py@@ -8,19 +8,27 @@ moves runs whose task was lost."""import loggingfrom datetime import timedelta+from decimal import Decimalfrom asgiref.sync import async_to_syncfrom django.core.cache import cachefrom django.db import transaction-from django.db.models import Max+from django.db.models import Max, Qfrom django.utils import timezonefrom overbae.core import telemetryfrom overbae.core.errors import InputValidationErrorfrom overbae.core.utils import fingerprint-from overbae.models import AssistantInput, Experiment, ExperimentRun, ExperimentStep+from overbae.models import (+ AssistantInput,+ Capability,+ DeployedModel,+ Experiment,+ ExperimentRun,+ ExperimentStep,+)+from overbae.services.experiments import describe, records, stagesfrom overbae.services.experiments import document as flow-from overbae.services.experiments import records, stagesfrom overbae.services.experiments.catalog import FLOWS, KINDSlogger = logging.getLogger(__name__)@@ -153,22 +161,23 @@ def plan(def _agent_budget(experiment: Experiment) -> None:+ """The agent starts at most AGENT_RUNS runs per person's message or trigger send, and+ none past a trigger's spend cap while no person is in the loop."""thread = getattr(experiment, "assistant_thread", None)- since = (- thread.inputs.filter(origin=AssistantInput.Origin.USER)- .order_by("-created_at")- .values_list("created_at", flat=True)- .first()+ asked = (+ thread.inputs.filter(+ origin__in=[AssistantInput.Origin.USER, AssistantInput.Origin.TRIGGER]+ ).order_by("-created_at")if thread- else None- )+ else AssistantInput.objects.none()+ ).first()person = (experiment.runs.filter(parent=None, origin__in=["console", "mcp"]).order_by("-created_at").values_list("created_at", flat=True).first())- since = max(filter(None, (since, person)), default=None)+ since = max(filter(None, (asked and asked.created_at, person)), default=None)started = experiment.runs.filter(parent=None, origin=ExperimentRun.Origin.ASSISTANT)if since is not None:started = started.filter(created_at__gt=since)@@ -177,6 +186,15 @@ def _agent_budget(experiment: Experiment) -> None:f"The agent started {AGENT_RUNS} runs since a person last asked: ask the user ""before starting another.")+ if asked is not None and asked.origin == AssistantInput.Origin.USER:+ return+ for trigger in experiment.triggers.filter(deleted_at=None, max_spend_usd__isnull=False):+ spent = Decimal(str(describe.spend(experiment, since=trigger.created_at)["measured_usd"]))+ if spent >= trigger.max_spend_usd:+ raise InputValidationError(+ f"The trigger's spend cap of ${trigger.max_spend_usd} is reached "+ f"(${spent:.2f} measured). Ask the user before starting another run."+ )def start(@@ -250,7 +268,7 @@ def start({"run": run.number, "origin": origin, "revision": reviewed["revision"]},run=run,)- _wake(run)+ wake(run)return run@@ -281,7 +299,7 @@ def _next_number(experiment) -> int:return (experiment.runs.aggregate(last=Max("number"))["last"] or 0) + 1-def _wake(run, countdown=None) -> None:+def wake(run, countdown=None) -> None:from overbae.tasks.experiments import advance_run # lazy: tasks import this modulerun_id = str(run.pk)@@ -292,7 +310,7 @@ def stop(run: ExperimentRun) -> ExperimentRun:"""Stop the run and the work its stages started, at its next advance."""if ExperimentRun.objects.filter(pk=run.pk, state=State.RUNNING).update(state=State.STOPPING):records.changed(run.experiment_id, "experiment")- _wake(run)+ wake(run)run.refresh_from_db()return run@@ -321,7 +339,7 @@ def retry(run: ExperimentRun, user) -> ExperimentRun:{"run": held.number, "stages": retried, "user": user.pk},run=held,)- _wake(held)+ wake(held)held.refresh_from_db()return held@@ -601,6 +619,9 @@ def _observe(run, step, node, settings, context) -> bool:if not step.receipts:_dispatch(run, step, node, settings, context)return True+ if any(receipt["kind"] == stages.SYSTEM_OUTPUTS for receipt in step.receipts):+ # Your system has not sent its outputs; their import replaces this receipt.+ return Falsecalls = list(step.calls)invoke = _invoker(context, step, calls)jobs = []@@ -695,7 +716,7 @@ def _child(run, step, target, revision, parameters, label) -> ExperimentRun:deadline=run.deadline,result={"plan": child_plan["entries"], "label": label},)- _wake(child)+ wake(child)return child@@ -863,14 +884,40 @@ def _end(run, state: str, reason: str, current) -> None:records.log(run.experiment, "run_ended", {"run": run.number, "state": state, "reason": reason}, run=run)+ if run.origin == ExperimentRun.Origin.ASSISTANT:+ _stop_deployments(run)if run.parent_id:- _wake(run.parent.run)+ wake(run.parent.run)returnfrom overbae.services.experiments import operator # lazy: the assistant imports runsoperator.run_ended(run)+def _stop_deployments(run) -> None:+ """A deployment the agent's run brought up served its evaluation: it stops with the run,+ child runs included. One that served before the run, or that a capability now uses or+ rolls back to, stays."""+ from overbae.services.inference_client import get_inference_client # lazy: network client++ receipts = ExperimentStep.objects.filter(run__in=records.run_tree([run.pk])).values_list(+ "receipts", flat=True+ )+ named = [r["id"] for found in receipts for r in found if r.get("kind") == "deployment"]+ used = Capability.objects.filter(+ Q(active_model__in=named) | Q(previous_active_model__in=named)+ ).values_list("active_model", "previous_active_model")+ kept = {pk for pair in used for pk in pair if pk}+ started = DeployedModel.objects.filter(pk__in=named).filter(+ Q(created_at__gte=run.created_at) | Q(deployed_at__gte=run.created_at)+ )+ for deployed in started.exclude(pk__in=kept):+ try:+ get_inference_client().delete_model(deployed.model_id)+ except Exception:+ logger.exception("deployment %s of run %s did not stop", deployed.pk, run.pk)++def due() -> list[str]:"""Runs a lost task left moving: the reconciler advances each."""stale = timezone.now() - timedelta(seconds=30)diff --git a/overbae/services/experiments/stages.py b/overbae/services/experiments/stages.pyindex 0083e717..695215dc 100644--- a/overbae/services/experiments/stages.py+++ b/overbae/services/experiments/stages.py@@ -24,6 +24,7 @@ from jsonschema.exceptions import SchemaErrorfrom referencing import Registryfrom referencing.exceptions import Unresolvable+from overbae.innermind.generation import SYSTEM_OUTPUTfrom overbae.models import (Cell,ConnectorCredential,@@ -52,6 +53,8 @@ OPERATORS = {"==": operator.eq,}SUCCEEDED = frozenset({"succeeded", "completed", "complete", "ready"})+# The receipt of a Your-system stage until its outputs arrive.+SYSTEM_OUTPUTS = "system_outputs"class StageFailedError(Exception):@@ -326,6 +329,14 @@ def _evaluate(stage: Stage):cell = _cell(stage)models = stage.inputs.get("model") or []targets = [_target(model) for model in models]+ # Outputs your system returned are scored as they are, after the models' answers.+ system = (_one(stage.inputs.get("data")) or {}).get("system")+ if system is None and any(column.get("name") == SYSTEM_OUTPUT for column in cell.columns or []):+ system = ""+ if system is not None:+ targets.append({"label": (system or "Your system")[:255], "mode": "recorded"})+ if not targets:+ raise StageFailedError("Evaluate scores a model or the outputs of Your system.")arguments = {"dataset": str(cell.dataset_id),"cell": str(cell.pk),@@ -341,6 +352,13 @@ def _evaluate(stage: Stage):return Waiting([{"kind": "eval_run", "id": str(run["id"])} for run in content["runs"]])+def _system(stage: Stage):+ """Your system answers the rows where it runs; ``overmind run`` sends the outputs, and+ the import that names this stage ends the wait."""+ _cell(stage)+ return Waiting([{"kind": SYSTEM_OUTPUTS, "id": stage.step_id, "status": "waiting"}])++def _participant(index: int, model: dict) -> dict:model = _model(model)if model.get("finetune"):@@ -392,6 +410,10 @@ def _deployment(stage: Stage) -> DeployedModel:).first()if deployed is None:raise StageFailedError("Its deployment input is not a deployment of this project.")+ if deployed.status in (DeployedModel.Status.DELETING, DeployedModel.Status.DELETED):+ raise StageFailedError(+ "Its deployment was stopped when its run ended. Retry from the Deploy stage."+ )return deployed@@ -545,6 +567,7 @@ START = {"train": _train,"evaluate": _evaluate,"qualify": _qualify,+ "system": _system,"publish": _publish,"verify_deployment": _inference,"inference": _inference,@@ -580,6 +603,11 @@ def _finished_transform(stage: Stage, jobs):return Done({"data": data_value(run.output)})+def _finished_system(stage: Stage, jobs):+ finished = _finished_transform(stage, jobs).outputs["data"]+ return Done({"data": {**finished, "system": stage.settings.get("label") or ""}})++def _finished_split(stage: Stage, jobs):plan = DataPartitionPlan.objects.get(pk=jobs[0]["id"])return Done(@@ -680,6 +708,7 @@ FINISH = {"ingest": lambda stage, jobs: Done({"traces": {"connector": jobs[0]["id"]}}),"trace_dataset": _finished_dataset,"transform": _finished_transform,+ "system": _finished_system,"split": _finished_split,"train": _finished_train,"evaluate": _finished_evaluate,diff --git a/overbae/services/experiments/system.py b/overbae/services/experiments/system.pynew file mode 100644index 00000000..94298b27--- /dev/null+++ b/overbae/services/experiments/system.py@@ -0,0 +1,129 @@+"""Your system: the user's own application answers a stage's rows where it runs, and+``overmind run`` sends the outputs back with the code identity that made them."""++import json+import uuid++from django.db import transaction++from overbae.core.errors import InputValidationError+from overbae.innermind import generation+from overbae.models import Cell, Dataset, DatasetPipelineRun, ExperimentStep+from overbae.services.datasets import partition_plans, store, workbench+from overbae.services.datasets.lifecycle import DatasetError+from overbae.services.datasets.rows import frame_path+from overbae.services.experiments import records, runs, stages++DEFAULT_ROWS = 200+REPOSITORY_FIELDS = ("remote", "commit", "dirty")+++NOT_WAITING = "This stage is not waiting for outputs of your system."+++def _stage(step: ExperimentStep) -> tuple[dict, Cell]:+ """The Your system stage and the version it sends. No agent and no client reads a+ final holdout's rows."""+ node = next((n for n in step.run.revision.document["nodes"] if n["id"] == step.node), None)+ if node is None or node["kind"] != "system":+ raise InputValidationError(NOT_WAITING)+ value = step.inputs.get("data") or {}+ value = value[0] if isinstance(value, list) else value+ cell = Cell.objects.select_related("dataset").filter(pk=value.get("cell")).first()+ if cell is None:+ raise InputValidationError("The stage's input version no longer exists.")+ partition_plans.refuse_sealed([cell])+ return node, cell+++def _waiting(step: ExperimentStep) -> bool:+ return step.state == ExperimentStep.State.RUNNING and any(+ receipt.get("kind") == stages.SYSTEM_OUTPUTS for receipt in step.receipts+ )+++def rows(step: ExperimentStep) -> dict:+ """The rows your system answers: each one whole, with ``source_row`` naming it."""+ node, cell = _stage(step)+ if not _waiting(step):+ raise InputValidationError(NOT_WAITING)+ return _rows(node, cell)+++def _rows(node: dict, cell: Cell) -> dict:+ limit = int(node["settings"].get("max_items") or DEFAULT_ROWS)+ found = []+ for index, record in enumerate(store.iter_rows(frame_path(cell))):+ if index >= limit:+ break+ found.append({**record, "source_row": index})+ return {"label": node["settings"].get("label") or "", "rows": found}+++def _outputs_dataset(step: ExperimentStep, cell: Cell, label: str, user) -> Dataset:+ """The stage's own dataset: the outputs are a new dataset, and the input's active+ version stays as it was."""+ source = cell.dataset+ found, _ = Dataset.objects.get_or_create(+ pk=uuid.uuid5(step.pk, "outputs"),+ defaults={+ "project_id": source.project_id,+ "name": f"{label} outputs"[:255],+ "intent": source.intent,+ "train_format": source.train_format,+ "capability_id": source.capability_id,+ "state": Dataset.State.IDLE,+ "created_by": user,+ },+ )+ return found+++def send(step: ExperimentStep, user, outputs: list[dict], repository: dict) -> str:+ """Import each row with your system's ``output`` into the stage's own dataset; the+ stage then waits on that import. The same outputs again return the same import, also+ once the stage has moved on."""+ node, cell = _stage(step)+ label = node["settings"].get("label") or "Your system"+ target = _outputs_dataset(step, cell, label, user)+ key = f"system:{step.pk}"+ if (+ not _waiting(step)+ and not DatasetPipelineRun.objects.filter(dataset=target, request_key=key).exists()+ ):+ raise InputValidationError(NOT_WAITING)+ asked = {row["source_row"]: row for row in _rows(node, cell)["rows"]}+ answered = {}+ for item in outputs:+ index = item.get("source_row")+ if index not in asked or index in answered or "output" not in item:+ raise InputValidationError(+ "Each output names one source_row of the stage's rows and carries output."+ )+ answered[index] = {**asked[index], generation.SYSTEM_OUTPUT: item["output"]}+ if not answered:+ raise InputValidationError("Send at least one output.")+ identity = {field: repository.get(field) for field in REPOSITORY_FIELDS if field in repository}+ try:+ run = workbench.submit(+ target,+ user,+ source_cell=cell.pk,+ source_fingerprint=cell.fingerprint,+ request_key=key,+ imported_rows=[answered[index] for index in sorted(answered)],+ name=f"{label} outputs"[:255],+ provenance=json.dumps(+ {"experiment_step": str(step.pk), "system": label, "repository": identity}+ ),+ )+ except DatasetError as exc:+ raise InputValidationError(exc.detail) from None+ with transaction.atomic():+ held = ExperimentStep.objects.select_for_update().get(pk=step.pk)+ if any(r.get("kind") == stages.SYSTEM_OUTPUTS for r in held.receipts):+ held.receipts = [{"kind": "dataset_pipeline", "id": str(run.pk)}]+ held.save(update_fields=["receipts"])+ records.changed(step.run.experiment_id, "experiment")+ runs.wake(step.run)+ return str(run.pk)diff --git a/overbae/services/experiments/triggers.py b/overbae/services/experiments/triggers.pyindex 8ece6d57..e4dd3f12 100644--- a/overbae/services/experiments/triggers.py+++ b/overbae/services/experiments/triggers.py@@ -2,6 +2,7 @@capability's failing traces reach a threshold within a window."""from datetime import timedelta+from decimal import Decimalfrom django.db import transactionfrom django.db.models import F@@ -10,7 +11,7 @@ from django.utils import timezonefrom overbae.core.errors import InputValidationErrorfrom overbae.innermind import healthfrom overbae.models import AssistantInput, Capability, ExperimentTrigger-from overbae.services.experiments import operator, records+from overbae.services.experiments import describe, operator, recordsKind = ExperimentTrigger.KindMAX_HOURS = 720@@ -20,7 +21,16 @@ RECHECK = timedelta(minutes=10)def create(- experiment, user, *, kind, instruction, hours, max_sends, capability=None, threshold=None+ experiment,+ user,+ *,+ kind,+ instruction,+ hours,+ max_sends,+ capability=None,+ threshold=None,+ max_spend_usd=None,) -> ExperimentTrigger:if kind not in Kind.values:raise InputValidationError("A trigger runs on a schedule or on failing traces.")@@ -43,6 +53,7 @@ def create(capability=found,threshold=threshold if found else None,max_sends=max_sends,+ max_spend_usd=max_spend_usd,next_at=now + timedelta(hours=hours) if kind == Kind.SCHEDULE else now,created_by=user,)@@ -56,7 +67,7 @@ def remove(trigger: ExperimentTrigger) -> None:def fire_due() -> int:- """Send every trigger that is due and still has sends left."""+ """Send every trigger that is due, still has sends left and is under its spend cap."""now, sent = timezone.now(), 0due = ExperimentTrigger.objects.filter(deleted_at=None,@@ -75,6 +86,12 @@ def fire_due() -> int:deleted_at=None,experiment__deleted_at=None,)+ cap = trigger.max_spend_usd+ spent = describe.spend(trigger.experiment, trigger.created_at) if cap else None+ if cap is not None and Decimal(str(spent["measured_usd"])) >= cap:+ # Past its spend cap a trigger sends nothing: a send starts paid agent turns.+ observed.update(next_at=now + window)+ continueif trigger.kind == Kind.FAILING_TRACES:failing = len(health.failures(diff --git a/overbae/services/mcp/__init__.py b/overbae/services/mcp/__init__.pyindex 92943938..46e8c3b4 100644--- a/overbae/services/mcp/__init__.py+++ b/overbae/services/mcp/__init__.py@@ -1,3 +1,3 @@"""MCP protocol and catalog services."""-CONTRACT_VERSION = "12.2.0"+CONTRACT_VERSION = "12.3.0"diff --git a/overbae/services/mcp/contracts/experiments.py b/overbae/services/mcp/contracts/experiments.pyindex 9d68a3f2..f2ee4388 100644--- a/overbae/services/mcp/contracts/experiments.py+++ b/overbae/services/mcp/contracts/experiments.py@@ -2,6 +2,7 @@from __future__ import annotations+from decimal import Decimalfrom typing import Any, Literalfrom uuid import UUID@@ -58,6 +59,9 @@ class InspectExperimentOutput(MCPModel):runs: list[dict[str, Any]] = Field(description="The newest 20 runs, newest first.")run: dict[str, Any] | None = Nonetriggers: list[dict[str, Any]]+ notes: str+ spend: dict[str, Any] = Field(description="Measured spend and the parts not measured.")+ proposals: list[dict[str, Any]] = Field(description="Changes awaiting a person.")catalog: list[dict[str, Any]] | None = Noneresource_links: list[ResourceLinkContract]@@ -82,6 +86,9 @@ class ReviseExperimentInput(MCPModel):experiment: UUIDexpected_version: int = Field(ge=0)name: str | None = Field(default=None, min_length=1, max_length=255)+ notes: str | None = Field(+ default=None, max_length=20_000, description="Replaces the working notes people read."+ )flow: dict[str, Any] | None = Field(default=None, description=FLOW)changes: list[StageChange] | None = Field(default=None, max_length=50)request_key: str = Field(min_length=1, max_length=128)@@ -90,8 +97,8 @@ class ReviseExperimentInput(MCPModel):def one_form(self):if self.flow is not None and self.changes is not None:raise ValueError("Give the whole flow or a list of changes, not both.")- if self.flow is None and self.changes is None and self.name is None:- raise ValueError("Give a name, the whole flow or a list of changes.")+ if self.flow is None and self.changes is None and self.name is None and self.notes is None:+ raise ValueError("Give a name, notes, the whole flow or a list of changes.")return self@@ -147,6 +154,9 @@ class ConfigureExperimentTriggerInput(MCPModel):instruction: str = Field(default="", max_length=8000)hours: int = Field(default=24, ge=1, le=720)max_sends: int = Field(default=5, ge=1, le=100)+ max_spend_usd: Decimal | None = Field(+ default=None, gt=0, max_digits=10, decimal_places=2, description="Stops unattended runs."+ )capability: str | None = Field(default=None, max_length=255)threshold: int | None = Field(default=None, ge=1)@@ -157,6 +167,24 @@ class ExperimentTriggerOutput(MCPModel):resource_links: list[ResourceLinkContract]+class RunPythonInput(MCPModel):+ experiment: UUID+ code: str = Field(min_length=1, max_length=64_000)+ versions: list[UUID] = Field(+ default_factory=list, max_length=10, description="Read at data/<cell id>.parquet."+ )+ timeout: int = Field(default=120, ge=1, le=600, description="Seconds.")+++class RunPythonOutput(MCPModel):+ summary: str = Field(min_length=1, max_length=240)+ ok: bool+ output: str+ error: str | None = None+ truncated: bool+ note: str | None = None++class SendExperimentMessageInput(MCPModel):experiment: UUIDtext: str = Field(default="", max_length=20_000)diff --git a/overbae/services/mcp/errors.py b/overbae/services/mcp/errors.pyindex 91871817..715de693 100644--- a/overbae/services/mcp/errors.py+++ b/overbae/services/mcp/errors.py@@ -85,6 +85,9 @@ ErrorCode = Literal["invalid_filter","embedding_unavailable","rate_limited",+ "protected_setting",+ "holdout_sealed",+ "workspace_unavailable","internal_error",]diff --git a/overbae/services/mcp/tools_datasets.py b/overbae/services/mcp/tools_datasets.pyindex 909505ed..17779a7a 100644--- a/overbae/services/mcp/tools_datasets.py+++ b/overbae/services/mcp/tools_datasets.py@@ -13,6 +13,7 @@ from overbae.models import Capability, Datasetfrom overbae.services.datasets import (dispatch,imports,+ partition_plans,paths,store,workbench,@@ -123,6 +124,10 @@ def _query_dataset_sync(payload: QueryDatasetInput, context: MCPContext) -> Querraise MCPError("cell_not_found", "The cell was not found in this dataset.") from excif cell.dataset_id != dataset.id:raise MCPError("cell_not_found", "The cell was not found in this dataset.")+ try:+ partition_plans.refuse_sealed([cell])+ except partition_plans.SealedHoldoutError as exc:+ raise MCPError("holdout_sealed", exc.detail) from Nonelimit = min(payload.limit, 100)phases.append(("admission", time.monotonic()))try:diff --git a/overbae/services/mcp/tools_experiments.py b/overbae/services/mcp/tools_experiments.pyindex 83d54bd6..06008077 100644--- a/overbae/services/mcp/tools_experiments.py+++ b/overbae/services/mcp/tools_experiments.py@@ -8,7 +8,9 @@ from django.db import transactionfrom overbae.core.errors import InputValidationErrorfrom overbae.models import Experiment, ExperimentRun-from overbae.services.assistant import threads, turn+from overbae.services import workspaces+from overbae.services.assistant import threads, tools, turn+from overbae.services.datasets import partition_plansfrom overbae.services.entity_resolution import resolve_capabilityfrom overbae.services.experiments import catalog, describe, records, runs, triggersfrom overbae.services.experiments import document as flow@@ -29,6 +31,8 @@ from overbae.services.mcp.contracts.experiments import (ReviseExperimentInput,ReviseExperimentOutput,RunOptions,+ RunPythonInput,+ RunPythonOutput,SendExperimentMessageInput,SendExperimentMessageOutput,StartExperimentRunInput,@@ -77,6 +81,8 @@ def _origin(context: MCPContext) -> str:def _refused(exc: InputValidationError):+ if isinstance(exc, records.ProtectedSettingError):+ return MCPError("protected_setting", exc.detail)return MCPError("invalid_input", exc.detail)@@ -98,6 +104,7 @@ def _create_sync(payload: CreateExperimentInput, context: MCPContext) -> Experimobjective=payload.objective,request_key=payload.request_key,document=payload.flow,+ agent=_origin(context) == ExperimentRun.Origin.ASSISTANT,)if payload.message.strip():with transaction.atomic():@@ -136,6 +143,9 @@ def _inspect_sync(payload: InspectExperimentInput, context: MCPContext) -> Insperuns=[describe.summary(item) for item in listed],run=describe.run(selected) if selected else None,triggers=describe.triggers(found),+ notes=found.notes,+ spend=describe.spend(found),+ proposals=records.proposals(found),catalog=catalog.describe() if payload.catalog else None,resource_links=_links(found),)@@ -146,10 +156,12 @@ def _revise_sync(payload: ReviseExperimentInput, context: MCPContext) -> ReviseEtry:if payload.name is not None:found = records.rename(found, payload.name)+ if payload.notes is not None:+ found = records.write_notes(found, payload.notes)if payload.flow is None and payload.changes is None:saved = records.revision(found)return ReviseExperimentOutput(- summary=f"Renamed to {found.name[:200]}.",+ summary="Saved the name." if payload.notes is None else "Saved the notes.",experiment=_contract(found),revision=found.version,problems=flow.problems(saved.document if saved else flow.EMPTY),@@ -171,6 +183,7 @@ def _revise_sync(payload: ReviseExperimentInput, context: MCPContext) -> ReviseEdocument=document,expected_version=payload.expected_version,request_key=payload.request_key,+ agent=_origin(context) == ExperimentRun.Origin.ASSISTANT,)except InputValidationError as exc:raise _refused(exc) from None@@ -285,6 +298,7 @@ def _trigger_sync(max_sends=payload.max_sends,capability=capability.pk if capability else None,threshold=payload.threshold,+ max_spend_usd=payload.max_spend_usd,)except InputValidationError as exc:raise _refused(exc) from None@@ -293,6 +307,36 @@ def _trigger_sync()+def _run_python_sync(payload: RunPythonInput, context: MCPContext) -> RunPythonOutput:+ """A coding agent explores the project's data in place: its own kernel in the+ experiment's workspace, offline, with the versions it names copied in read-only."""+ found = _experiment(context, payload.experiment)+ versions = sorted({str(version) for version in payload.versions})+ try:+ run = tools.run_cell(+ context.project.pk,+ records.kernel(found),+ payload.code,+ versions,+ payload.timeout,+ lambda: True,+ )+ except partition_plans.SealedHoldoutError as exc:+ raise MCPError("holdout_sealed", exc.detail) from None+ except InputValidationError as exc:+ raise _refused(exc) from None+ except workspaces.WorkspaceUnavailableError as exc:+ raise MCPError("workspace_unavailable", str(exc)[:300], retryable=True) from None+ return RunPythonOutput(+ summary="The cell ran." if run.ok else "The cell failed.",+ ok=run.ok,+ output=run.output,+ error=run.error or None,+ truncated=run.truncated,+ note=run.restarted or None,+ )++def _send_sync(payload: SendExperimentMessageInput, context: MCPContext) -> SendExperimentMessageOutput:@@ -420,6 +464,18 @@ TOOLS = ("overmind:train","free",),+ (+ "run_python",+ "Run Python",+ "Run Python in your own kernel in the experiment's workspace: offline, state kept "+ "between calls, named dataset versions at data/<cell id>.parquet.",+ RunPythonInput,+ RunPythonOutput,+ _run_python_sync,+ False,+ "overmind:data:write",+ "compute",+ ),("send_experiment_message","Send experiment message",@@ -447,7 +503,7 @@ def register_experiment_tools(catalog_registry) -> None:output_model=outputs,read_only=read_only,destructive=name == "delete_experiment",- idempotent=True,+ idempotent=name != "run_python",open_world=False,required_scopes=frozenset({scope}),cost_class=cost,diff --git a/overbae/services/mcp/tools_workbench.py b/overbae/services/mcp/tools_workbench.pyindex 9afb0818..87b717bd 100644--- a/overbae/services/mcp/tools_workbench.py+++ b/overbae/services/mcp/tools_workbench.py@@ -1,7 +1,7 @@from asgiref.sync import sync_to_asyncfrom overbae.models import Capability-from overbae.services.datasets import lifecycle, pipeline_bindings, workbench+from overbae.services.datasets import lifecycle, partition_plans, pipeline_bindings, workbenchfrom overbae.services.mcp.contracts.common import ResourceLinkContractfrom overbae.services.mcp.contracts.workbench import (BindingInput,@@ -49,6 +49,12 @@ def invoke(name, payload, context):if run:result["run"] = workbench.run_record(run)elif name in {"run_dataset_pipeline", "import_dataset_version"}:+ # A transform or import of a final holdout would carry its rows to another version.+ sources = [args.get("source_cell"), args.get("artifact_cell")]+ try:+ partition_plans.refuse_sealed([cell for cell in sources if cell])+ except partition_plans.SealedHoldoutError as exc:+ raise MCPError("holdout_sealed", exc.detail) from Noneresult["run"] = workbench.run_record(workbench.submit(dataset, context.user, **args))elif name == "update_dataset":if args.get("capability"):diff --git a/overbae/services/project_setup.py b/overbae/services/project_setup.pynew file mode 100644index 00000000..87f118fd--- /dev/null+++ b/overbae/services/project_setup.py@@ -0,0 +1,27 @@+"""Home's setup stage, decided on the server in one answer, so the Console never shows a+stage that a later answer replaces."""++from overbae.models import Activity, Capability, Cell, DeployedModel, EvalSet, FinetuningJob+++def setup(project) -> dict:+ """Whether the repository was scanned, and each first step the project has reached. A+ deployment that stopped later still served; a dataset or eval set counts while it exists."""+ settings = project.settings or {}+ return {+ "scanned": bool(settings.get("repository_snapshot") or settings.get("last_synced_at"))+ or Capability.objects.filter(project=project).current().exists()+ or Activity.objects.filter(+ project=project, kind="repository_synced", status="completed"+ ).exists(),+ "dataset": Cell.objects.filter(+ dataset__project=project, state=Cell.State.OK, rows__gt=0+ ).exists(),+ "eval_set": EvalSet.objects.filter(project=project).exists(),+ "trained": FinetuningJob.objects.filter(+ project=project, status=FinetuningJob.Status.SUCCEEDED+ ).exists(),+ "deployed": DeployedModel.objects.filter(+ project=project, deployed_at__isnull=False+ ).exists(),+ }diff --git a/overbae/urls.py b/overbae/urls.pyindex 1e76764e..22dd5295 100644--- a/overbae/urls.py+++ b/overbae/urls.py@@ -44,7 +44,7 @@ from overbae.api.eval_views import (EvalSetViewSet,ModelCatalogView,)-from overbae.api.experiments import ExperimentRunViewSet, ExperimentViewSet+from overbae.api.experiments import ExperimentRunViewSet, ExperimentStepViewSet, ExperimentViewSetfrom overbae.api.guest import GuestClaimView, GuestStartViewfrom overbae.api.health import health_checkfrom overbae.api.inference_requests import (@@ -56,6 +56,7 @@ from overbae.api.mcp_oauth import MCPConsentViewfrom overbae.api.native_evaluation import NativeEvaluationViewSetfrom overbae.api.otlp import otlp_tracesfrom overbae.api.overwatch_agent import OverwatchQueryView+from overbae.api.project_setup import ProjectSetupViewfrom overbae.api.public_models import PublicModelLibraryDetailView, PublicModelLibraryListViewfrom overbae.api.robots import robots_txtfrom overbae.api.signal_views import SignalEventViewSet, SignalSubscriptionViewSet@@ -85,6 +86,7 @@ router = DefaultRouter()router.register("assistant-threads", AssistantThreadViewSet, basename="assistant-thread")router.register("experiments", ExperimentViewSet, basename="experiment")router.register("experiment-runs", ExperimentRunViewSet, basename="experiment-run")+router.register("experiment-steps", ExperimentStepViewSet, basename="experiment-step")router.register("dataset-transfers", DatasetTransferViewSet, basename="dataset-transfer")router.register("dataset-pipeline-packages", DatasetPipelinePackageViewSet, basename="dataset-pipeline-package"@@ -234,6 +236,7 @@ urlpatterns += [path("api/v1/models/<path:model_id>", model_detail, name="v1-model-detail"),path("api/", include(router.urls)),path("api/agent/", AgentGraphView.as_view(), name="agent-graph"),+ path("api/project-setup/", ProjectSetupView.as_view(), name="project-setup"),path("api/v1/sync", SyncView.as_view(), name="toml-sync"),path("api/models/catalog/", ModelCatalogView.as_view(), name="model-catalog"),# Unauthenticated: powers the marketing site's /library pages.diff --git a/overmind/overmind/__init__.py b/overmind/overmind/__init__.pyindex bcbb004b..2baf1c88 100644--- a/overmind/overmind/__init__.py+++ b/overmind/overmind/__init__.py@@ -9,7 +9,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any-__version__ = "0.1.131"+__version__ = "0.1.132"from .client import Client, ModelDeleted, OvermindInferenceErrordiff --git a/overmind/overmind/__main__.py b/overmind/overmind/__main__.pyindex 3979ed60..2f02ff74 100644--- a/overmind/overmind/__main__.py+++ b/overmind/overmind/__main__.py@@ -30,6 +30,7 @@ try:from overmind.finetune_cmd import finetune as finetune_cmdfrom overmind.init_cmd import init as init_cmdfrom overmind.model_cmd import model_app+ from overmind.run_cmd import run as run_cmdfrom overmind.skills import skills_appfrom overmind.sync import sync as sync_cmdexcept ImportError as exc:@@ -91,6 +92,7 @@ app.command("init")(init_cmd)app.command("sync")(sync_cmd)app.command("chassis")(chassis_cmd)app.command("finetune")(finetune_cmd)+app.command("run")(run_cmd)if __name__ == "__main__":diff --git a/overmind/overmind/run_cmd.py b/overmind/overmind/run_cmd.pynew file mode 100644index 00000000..45dadd1a--- /dev/null+++ b/overmind/overmind/run_cmd.py@@ -0,0 +1,105 @@+"""``overmind run``: your own system answers an experiment's rows where it runs."""++from __future__ import annotations++import importlib+import json+import sys+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from typing import Annotated, Any++import requests+import typer++from overmind.config import DEFAULT_PATH, load+from overmind.repository_snapshot import capture_repository_snapshot+from overmind.transfer_connection import TransferError, request_json, resolve_transfer_connection+++def _entry(spec: str):+ module, _, name = spec.partition(":")+ if not module or not name:+ raise ValueError("Name the function as module:function, for example app.agent:answer.")+ sys.path.insert(0, str(Path.cwd()))+ function = getattr(importlib.import_module(module), name, None)+ if not callable(function):+ raise ValueError(f"{spec} is not a function.")+ return function+++def run(+ step: Annotated[str, typer.Option("--step", help="The Your-system stage attempt to answer.")],+ entry: Annotated[str, typer.Option("--entry", help="module:function called with each row.")],+ concurrency: Annotated[int, typer.Option("--concurrency", min=1, max=32)] = 4,+ api_key: Annotated[str, typer.Option("--api-key", envvar="OVERMIND_API_KEY", show_default=False)] = "",+ api_url: Annotated[str, typer.Option("--api-url", envvar="OVERMIND_API_URL")] = "",+ path: Annotated[Path, typer.Option("--path")] = DEFAULT_PATH,+ as_json: Annotated[bool, typer.Option("--json")] = False,+) -> None:+ """Answer an experiment's rows with your own function and send the outputs.++ The function receives each row as a dict and returns its output. The code stays here;+ Overmind receives the outputs and the commit that made them.+ """+ try:+ config = load(path) if path.exists() else None+ key, url = resolve_transfer_connection(api_key, api_url, config)+ function = _entry(entry)+ client = requests.Session()+ client.headers.update({"X-Api-Key": key})+ base = f"{url.rstrip('/')}/api/experiment-steps/{step}"+ try:+ asked = request_json(client, "GET", f"{base}/rows/", stage="system_rows")+ except TransferError as exc:+ if exc.code == "resource_not_found":+ raise TransferError(+ "No Your-system stage with this id is waiting, or this key cannot read it. "+ "Check the id on the stage card; the server needs MCP contract 12.3.0 or "+ "later.",+ code="server_too_old",+ ) from None+ raise++ def answer(row: dict[str, Any]) -> dict[str, Any] | None:+ try:+ return {"source_row": row["source_row"], "output": function(row)}+ except Exception as exc: # noqa: BLE001 - a failed row stays unmeasured+ typer.echo(f"Row {row['source_row']} failed: {exc}", err=True)+ return None++ with ThreadPoolExecutor(max_workers=concurrency) as pool:+ outputs = [found for found in pool.map(answer, asked["rows"]) if found is not None]+ if not outputs:+ raise TransferError("Every row failed; nothing was sent.", code="no_outputs")+ snapshot = capture_repository_snapshot(Path.cwd()) or {}+ repository = {+ "remote": snapshot.get("repository", ""),+ "commit": snapshot.get("commit", ""),+ "dirty": bool(snapshot.get("dirty")),+ }+ receipt = request_json(+ client,+ "POST",+ f"{base}/outputs/",+ stage="system_outputs",+ json={"outputs": outputs, "repository": repository},+ )+ result = {+ "import": receipt["run"],+ "answered": len(outputs),+ "rows": len(asked["rows"]),+ "commit": repository["commit"],+ "dirty": repository["dirty"],+ }+ typer.echo(+ json.dumps(result)+ if as_json+ else f"Sent {len(outputs)} of {len(asked['rows'])} outputs. The experiment scores them next."+ )+ except (TransferError, OSError, ValueError, ImportError) as exc:+ record = (+ exc.record() if isinstance(exc, TransferError) else {"code": "local_configuration", "message": str(exc)}+ )+ typer.echo(json.dumps({"error": record}) if as_json else record["message"], err=not as_json)+ raise typer.Exit(1) from Nonediff --git a/overmind/pyproject.toml b/overmind/pyproject.tomlindex c908f0c6..dc4e0eb3 100644--- a/overmind/pyproject.toml+++ b/overmind/pyproject.toml@@ -46,7 +46,7 @@ license = { text = "MIT" }name = "overmind"readme = "README.md"requires-python = ">=3.10,<4" # todo; remove the upper bound-version = "0.1.131"+version = "0.1.132"[project.urls]"Agent setup" = "https://console.overmindlab.ai/setup.md"diff --git a/overmind/skills/overmind-experiments/SKILL.md b/overmind/skills/overmind-experiments/SKILL.mdindex d2b1fc90..0df1b492 100644--- a/overmind/skills/overmind-experiments/SKILL.md+++ b/overmind/skills/overmind-experiments/SKILL.md@@ -29,7 +29,25 @@ Start with `list_projects`; pass `project_id` on every call from an account connand its triggers end.The final holdout of a Partition stage is read once, by a Qualify stage that nothing trains-or selects after. The flow refuses any other reader.+or selects after. The flow refuses any other reader, and every read tool refuses its rows.++A setting a person chose is protected: the experiment's Console agent cannot change it; its+change is kept as a proposal the person applies. Your edits count as a person's.++## Evaluate the user's own system++Their application stays where it runs, with its keys. Add a `system` stage ("Your system")+after a Data stage and bind an Evaluate stage's `data` to its output. When a run reaches the+stage, run `overmind run --step <step id> --entry module:function` in the user's repository:+it calls the function on each row (a dict with `source_row`) and sends only the outputs and+the commit that made them. Evaluate scores those outputs on the same criteria as any model+bound to it. `inspect_experiment` with `run` gives the step id.++## Explore data in place++`run_python` runs Python in your own kernel in the experiment's workspace: offline, state+kept between calls, each version you list in `versions` at `data/<cell id>.parquet`. Keep+results as Data Workshop pipelines; the kernel is scratch.## Run@@ -48,8 +66,9 @@ or selects after. The flow refuses any other reader.## Steer- `send_experiment_message` talks to the experiment's Console agent, or answers its question.- It hears when a run ends and may repair the flow and run again, at most three times- before a person asks again.+ It hears when a run ends and may repair the flow and run again, at most three times per+ person's message or trigger notice. It keeps its notes in the experiment; read them with+ `inspect_experiment`, and write your own with `revise_experiment` and `notes`.- `configure_experiment_trigger` sends an instruction to that agent every N hours, or when a- capability's failing traces within N hours reach a threshold, up to `max_sends` times;- `enabled` false ends one.+ capability's failing traces within N hours reach a threshold, up to `max_sends` times, and+ no unattended run past `max_spend_usd` of measured spend; `enabled` false ends one.diff --git a/overmind/tests/test_run_cmd.py b/overmind/tests/test_run_cmd.pynew file mode 100644index 00000000..79411a5e--- /dev/null+++ b/overmind/tests/test_run_cmd.py@@ -0,0 +1,72 @@+from __future__ import annotations++import json+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++import pytest+from typer.testing import CliRunner++from overmind.__main__ import app++pytestmark = pytest.mark.covers("cli-contract")++ROWS = [{"source_row": 0, "input": "hi"}, {"source_row": 1, "input": "boom"}]+++def server():+ received: list[dict] = []++ class Handler(BaseHTTPRequestHandler):+ def _reply(self, status, body):+ data = json.dumps(body).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def do_GET(self):+ if self.path == "/api/experiment-steps/step/rows/":+ return self._reply(200, {"label": "main", "rows": ROWS})+ return self._reply(404, {})++ def do_POST(self):+ length = int(self.headers["Content-Length"])+ received.append({"key": self.headers["X-Api-Key"], **json.loads(self.rfile.read(length))})+ return self._reply(201, {"run": "import-1"})++ def log_message(self, *args):+ pass++ httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ threading.Thread(target=httpd.serve_forever, daemon=True).start()+ yield f"http://127.0.0.1:{httpd.server_address[1]}", received+ httpd.shutdown()+++def test_run_answers_each_row_where_the_code_lives_and_sends_only_outputs(server, tmp_path, monkeypatch):+ url, received = server+ (tmp_path / "agent.py").write_text(+ "def answer(row):\n if row['input'] == 'boom':\n raise RuntimeError('no')\n return row['input'] + '!'\n"+ )+ monkeypatch.chdir(tmp_path)+ args = ["run", "--step", "step", "--entry", "agent:answer", "--api-url", url, "--api-key", "k", "--json"]+ result = CliRunner().invoke(app, args)+ assert result.exit_code == 0, result.output+ assert json.loads(result.stdout.splitlines()[-1])["answered"] == 1+ (sent,) = received+ # The failed row stays unmeasured; no code or file leaves the machine.+ assert sent["key"] == "k" and sent["outputs"] == [{"source_row": 0, "output": "hi!"}]+ assert set(sent["repository"]) == {"remote", "commit", "dirty"}+++def test_run_names_an_older_server_instead_of_failing_unclearly(server, tmp_path, monkeypatch):+ url, _ = server+ (tmp_path / "agent.py").write_text("def answer(row):\n return 1\n")+ monkeypatch.chdir(tmp_path)+ args = ["run", "--step", "gone", "--entry", "agent:answer", "--api-url", url, "--api-key", "k"]+ result = CliRunner().invoke(app, args)+ assert result.exit_code == 1+ assert "12.3.0" in result.outputdiff --git a/overmind/uv.lock b/overmind/uv.lockindex 1d54caa8..1f4d557a 100644--- a/overmind/uv.lock+++ b/overmind/uv.lock@@ -923,7 +923,7 @@ wheels = [[[package]]name = "overmind"-version = "0.1.131"+version = "0.1.132"source = { editable = "." }dependencies = [{ name = "packaging" },diff --git a/tests/coverage_map.py b/tests/coverage_map.pyindex ff4ceeb6..65d61f3c 100644--- a/tests/coverage_map.py+++ b/tests/coverage_map.py@@ -300,6 +300,13 @@ COVERAGE_MAP: dict[str, Entry] = {LOGIC,"Hyperparameters, context budgets, batching, eval schedules and monitoring plans.",),+ "home-setup": Entry(+ S4,+ LOGIC,+ "Home shows one setup stage the server decides: the install prompt until the "+ "repository is scanned, the checklist while a first step is left, then prompts. A "+ "stopped deployment still counts as deployed, and no stage shows before its data loads.",+ ),"experiments": Entry(S2,INVARIANT,diff --git a/tests/journeys/stack.py b/tests/journeys/stack.pyindex ade492eb..20377a82 100644--- a/tests/journeys/stack.py+++ b/tests/journeys/stack.py@@ -157,6 +157,21 @@ def drain_scoring(ledger: TaskLedger, timeout: float = 120) -> None:raise TimeoutError("Live scoring work still waits after 10 admissions")+def drain_run(ledger: TaskLedger, run_id: str, timeout: float = 120) -> None:+ """Drain, then advance the experiment run as the reconciler would, until it ends: the+ run reads its stages' records on that tick, which no beat runs in journeys."""+ from overbae.celery import app+ from overbae.models import ExperimentRun++ def ended():+ if ExperimentRun.objects.filter(pk=run_id, state__in=["running", "stopping"]).exists():+ app.send_task("overbae.tasks.experiments.advance_run", args=[run_id])+ return False+ return True++ settle(ledger, ended, timeout)++def settle(ledger: TaskLedger, condition, timeout: float = 60):"""Drain until ``condition()`` holds. A browser action returns before its requestcommits, so the work it publishes may not exist yet when a single drain runs."""diff --git a/tests/journeys/test_data.py b/tests/journeys/test_data.pyindex 7a05c811..5ce6e059 100644--- a/tests/journeys/test_data.py+++ b/tests/journeys/test_data.py@@ -119,23 +119,22 @@ def hand_uploaded_data_to_the_coding_agent(console, tmp_path):def use_freezes_an_uploaded_eval_source(console, workshop, project, worker, tmp_path):- console.goto(f"/datasets?projectId={project}")- console.command("New dataset")- console.fill("#dataset-name", "Console upload")- console.upload('[role="dialog"] input[type="file"]', tickets(tmp_path))- console.sees("3 rows")- console.choose("#dataset-intent", "Eval")- console.press("Create dataset")+ # A file dropped on Home with no message lands in a new experiment, with no agent turn.+ console.goto(f"/?projectId={project}")+ console.upload('input[aria-label="Attach dataset files"]', tickets(tmp_path))+ console.press("Send")def landed():for dataset in workshop.call("list_datasets", {})["datasets"]:- if dataset["name"] == "Console upload":+ if dataset["name"] == "tickets":inspected = workshop.call("inspect_dataset", {"dataset": dataset["id"]})return inspected if inspected["active"] else Nonereturn Noneinspected = settle(worker, landed)dataset = inspected["id"]+ workshop.call("update_dataset", {"dataset": dataset, "intent": "eval"})+ inspected = workshop.call("inspect_dataset", {"dataset": dataset})assert inspected["active"]["rows"] == 3assert inspected["intent"] == "eval"assert inspected["active"]["fits"]["ok"] is True@@ -203,23 +202,9 @@ def keep_the_brief_when_the_cli_attaches_data(console, workshop, cli, sample_agent, project, worker, tmp_path):brief = "Classify refund requests; retain uncertain labels for review."- console.goto(f"/datasets?projectId={project}")- console.command("New dataset")- console.fill("#dataset-name", "Brief before data")- console.fill("#dataset-brief", brief)- console.press("Create dataset")-- def draft():- return next(- (- row- for row in workshop.call("list_datasets", {})["datasets"]- if row["name"] == "Brief before data"- ),- None,- )-- dataset = settle(worker, draft)["id"]+ dataset = workshop.call("start_dataset", {"name": "Brief before data", "brief": brief})[+ "dataset"+ ]["id"]before = workshop.call("inspect_dataset", {"dataset": dataset})assert before["brief"] == brief and before["active"] is Noneassert upload(cli, sample_agent, tickets(tmp_path), "--dataset", dataset) == datasetdiff --git a/tests/journeys/test_evaluate.py b/tests/journeys/test_evaluate.pyindex eb9077be..0c7d0883 100644--- a/tests/journeys/test_evaluate.py+++ b/tests/journeys/test_evaluate.py@@ -1,7 +1,9 @@+import json+import pytestfrom .datasets import JUDGE, tickets, upload-from .stack import drain+from .stack import drain, drain_runpytestmark = pytest.mark.covers("evaluate")@@ -50,6 +52,49 @@ def test_evaluate(workshop, cli, sample_agent, worker, tmp_path, fake_llm, consoassert compared["weak"]["overall"]["status"] == "regressed"assert compared["weak"]["losses"] == 3+ # The user's own system answers the same rows where its code lives; only the outputs+ # and the commit come back, and the experiment scores them.+ cell = workshop.call("inspect_dataset", {"dataset": dataset})["active"]["id"]+ flow = {+ "nodes": [+ {"id": "data", "kind": "data", "settings": {"cell": cell}},+ {+ "id": "mine",+ "kind": "system",+ "inputs": {"data": ["data.data"]},+ "settings": {"label": "main"},+ },+ {+ "id": "eval",+ "kind": "evaluate",+ "inputs": {"data": ["mine.data"]},+ "settings": {"judge_model": JUDGE},+ },+ ]+ }+ created = workshop.call(+ "create_experiment", {"name": "Mine", "flow": flow, "request_key": "mine"}+ )["experiment"]+ started = workshop.call(+ "start_experiment_run", {"experiment": created["id"], "request_key": "mine-run"}+ )["run"]+ drain(worker)+ run = workshop.call("inspect_experiment", {"experiment": created["id"], "run": started["id"]})+ (step,) = [s for s in run["run"]["steps"] if s["node"] == "mine"]++ (sample_agent.repo / "mine.py").write_text("def answer(row):\n return 'Refund issued.'\n")+ sent = cli.run(+ "run", "--step", step["id"], "--entry", "mine:answer", "--json", cwd=sample_agent.repo+ )+ assert json.loads(sent.splitlines()[-1])["answered"] == 3+ drain_run(worker, started["id"])+ ended = workshop.call("get_job", {"kind": "experiment_run", "id": started["id"]})+ assert ended["status"] == "completed", ended+ run = workshop.call("inspect_experiment", {"experiment": created["id"], "run": started["id"]})+ (scored,) = [s for s in run["run"]["steps"] if s["node"] == "eval"]+ (candidate,) = scored["outputs"]["scores"]["candidates"]+ assert candidate["label"] == "main" and candidate["metrics"]["score"] is not None+project = workshop.project()["id"]console.goto(f"/evaluations?projectId={project}")for label in ("recorded", "candidate", "weak"):diff --git a/tests/journeys/test_tenancy.py b/tests/journeys/test_tenancy.pyindex ea47bc18..bb477214 100644--- a/tests/journeys/test_tenancy.py+++ b/tests/journeys/test_tenancy.py@@ -39,7 +39,10 @@ def outsider_project_key():def list_routes() -> list[str]:- return sorted({f"/api/{prefix}/" for prefix, _, _ in router.registry})+ """Every registered collection that lists; a viewset of detail actions only has none."""+ return sorted(+ {f"/api/{prefix}/" for prefix, viewset, _ in router.registry if hasattr(viewset, "list")}+ )def test_no_list_endpoint_answers_without_credentials(secrets, live_api):diff --git a/tests/mcp_fixtures.py b/tests/mcp_fixtures.pyindex 803e7077..def11313 100644--- a/tests/mcp_fixtures.py+++ b/tests/mcp_fixtures.py@@ -27,6 +27,7 @@ EXPECTED_TOOL_NAMES = {"control_experiment_run","configure_experiment_trigger","send_experiment_message",+ "run_python","search_objects","inspect_dependencies","revise_eval_matrix_row",diff --git a/tests/test_assistant_api.py b/tests/test_assistant_api.pyindex 0360a0b2..695569e7 100644--- a/tests/test_assistant_api.py+++ b/tests/test_assistant_api.py@@ -1,10 +1,10 @@import pytest-from conftest import frozen_datasetfrom factories import auth_client, make_member, make_project, make_userfrom overbae.models import AssistantThreadfrom overbae.services import workspacesfrom overbae.services.assistant import log+from overbae.services.experiments import recordsfrom overbae.tasks.assistant import run_turn, stop_kernelpytestmark = [pytest.mark.django_db, pytest.mark.covers("assistant-api")]@@ -17,21 +17,25 @@ def woken(monkeypatch):return started-def opened(user, dataset):- return auth_client(user).post("/api/assistant-threads/", {"dataset": dataset.pk}, format="json")+def opened(user, project):+ body = {"project": str(project.pk), "request_key": f"open-{user.pk}"}+ return auth_client(user).post("/api/experiments/", body, format="json")-def test_a_member_opens_the_datasets_conversation_sends_and_reads_after_a_cursor(+def experiment_thread(project, user, **fields):+ thread = records.create(project, user, name="E").assistant_thread+ AssistantThread.objects.filter(pk=thread.pk).update(**fields)+ thread.refresh_from_db()+ return thread+++def test_a_member_opens_an_experiments_conversation_sends_and_reads_after_a_cursor(woken, django_capture_on_commit_callbacks):user = make_user()project = make_project(member=user)- dataset = frozen_dataset(project, user=user)client = auth_client(user)- thread_id = opened(user, dataset).data["id"]- assert opened(user, dataset).data["id"] == thread_id- listed = client.get("/api/assistant-threads/", {"dataset": dataset.pk}).data- assert [t["id"] for t in listed] == [thread_id]+ thread_id = str(opened(user, project).data["thread"])body = {"request_key": "first", "text": "Prepare this."}with django_capture_on_commit_callbacks(execute=True):@@ -51,9 +55,7 @@ def test_a_member_opens_the_datasets_conversation_sends_and_reads_after_a_cursordef test_a_tool_result_shows_only_its_output_and_error():user = make_user()- thread = AssistantThread.objects.create(- project=(project := make_project(member=user)), dataset=frozen_dataset(project, user=user)- )+ thread = experiment_thread(make_project(member=user), user)content = {"output": "2\n", "rows": [{"secret": 1}] * 50, "error": {"message": "late"}}log.append(thread, "tool_result", {"call": "c", "name": "n", "ok": False, "content": content})(event,) = auth_client(user).get(f"/api/assistant-threads/{thread.pk}/events/").data@@ -64,7 +66,7 @@ def test_each_member_of_a_shared_conversation_is_told_which_messages_are_theirs(first, second = make_user(), make_user()project = make_project(member=first)make_member(second, project)- url = f"/api/assistant-threads/{opened(first, frozen_dataset(project, user=first)).data['id']}"+ url = f"/api/assistant-threads/{opened(first, project).data['thread']}"for user, key in ((first, "a"), (second, "b")):message = {"request_key": key, "text": "Hello"}assert auth_client(user).post(f"{url}/messages/", message, format="json").status_code == 202@@ -93,9 +95,7 @@ def test_stop_during_a_turn_ends_the_kernel_at_once(monkeypatch.setattr(stop_kernel, "delay", lambda *a: ended.append(a))user = make_user()project = make_project(member=user)- thread = AssistantThread.objects.create(- project=project, dataset=frozen_dataset(project, user=user), state="running"- )+ thread = experiment_thread(project, user, state="running")with django_capture_on_commit_callbacks(execute=True):stopped = auth_client(user).post(f"/api/assistant-threads/{thread.pk}/stop/")assert stopped.status_code == 202 and stopped.data["stop_requested"]@@ -115,8 +115,7 @@ def test_stop_during_a_turn_ends_the_kernel_at_once(def test_another_project_and_a_guest_cannot_use_a_conversation(woken):owner = make_user()project = make_project(member=owner)- dataset = frozen_dataset(project, user=owner)- thread = AssistantThread.objects.create(project=project, dataset=dataset)+ thread = experiment_thread(project, owner)url = f"/api/assistant-threads/{thread.pk}"body = {"request_key": "k", "text": "Hello."}@@ -126,7 +125,7 @@ def test_another_project_and_a_guest_cannot_use_a_conversation(woken):assert client.get(f"{url}/events/").status_code == 404assert client.post(f"{url}/messages/", body, format="json").status_code == 404assert client.post(f"{url}/stop/").status_code == 404- assert opened(outsider, dataset).status_code == 404+ assert opened(outsider, project).status_code == 404guest = make_user(is_guest=True)make_member(guest, project)diff --git a/tests/test_assistant_results.py b/tests/test_assistant_results.pyindex 1c71abd4..0cd9d444 100644--- a/tests/test_assistant_results.py+++ b/tests/test_assistant_results.py@@ -1,10 +1,10 @@import pytest-from conftest import frozen_datasetfrom factories import auth_client, make_project, make_userfrom fakes.llm import tool_callfrom overbae.services import workspacesfrom overbae.services.assistant import threads, turn+from overbae.services.experiments import recordsfrom overbae.tasks.assistant import run_turnpytestmark = [pytest.mark.django_db, pytest.mark.covers("assistant-results")]@@ -50,7 +50,7 @@ def test_a_result_carries_the_kernels_rows_and_image_and_refuses_a_file_that_is_monkeypatch.setattr(run_turn, "delay", lambda *a: None)user = make_user()project = make_project(member=user)- thread = threads.open_thread(frozen_dataset(project, user=user))+ thread = records.create(project, user, name="E").assistant_threadfake_llm.stream_rounds([([tool_call("run_python", {"summary": "Computing", "code": COMPUTE})], ""),diff --git a/tests/test_assistant_turn.py b/tests/test_assistant_turn.pyindex 828af8a7..240b2a8a 100644--- a/tests/test_assistant_turn.py+++ b/tests/test_assistant_turn.py@@ -6,7 +6,7 @@ from decimal import Decimalimport pytestfrom conftest import frozen_datasetfrom django.utils import timezone-from factories import auth_client, make_capability, make_project, make_user+from factories import make_capability, make_project, make_userfrom fakes.llm import tool_callfrom overbae.core.llms import stream_llm_tools@@ -21,7 +21,8 @@ from overbae.models import ()from overbae.services import workspacesfrom overbae.services.assistant import log, threads, tools, turn-from overbae.services.datasets import land, lifecycle, list_activity+from overbae.services.datasets import lifecycle+from overbae.services.experiments import recordsfrom overbae.services.workspaces.modal_sandbox import ModalProviderfrom overbae.tasks import assistant as assistant_tasks@@ -41,10 +42,23 @@ def user():return make_user()+def experiment_thread(project, user, dataset):+ """The conversation of an experiment that reads the dataset's active version."""+ cells = [dataset.active_cell.pk] if dataset.active_cell else []+ document = records.data_stages(project, cells) if cells else None+ return records.create(project, user, name="Prepare", document=document).assistant_thread+++def dataset_of(thread) -> Dataset:+ """The dataset the conversation's experiment reads."""+ (node,) = records.current(thread.experiment)["nodes"]+ return Dataset.objects.get(cells__pk=node["settings"]["cell"])++@pytest.fixturedef thread(user):project = make_project(member=user)- return threads.open_thread(frozen_dataset(project, user=user))+ return experiment_thread(project, user, frozen_dataset(project, user=user))def say(thread, user, text, key=None, **extra):@@ -76,7 +90,7 @@ def python(code, versions=(), **extra):def test_a_turn_runs_code_on_the_datasets_version_and_charges_each_model_call(fake_llm, user, thread):- source = thread.dataset.source+ source = dataset_of(thread).sourcecount = f"import pandas\nlen(pandas.read_parquet('data/{source.pk}.parquet'))"fake_llm.stream_rounds([([python(count, [str(source.pk)])], "Counting the rows."), ([], "It has 2 rows.")]@@ -146,7 +160,8 @@ def test_a_turn_starts_the_modal_workspace_while_the_model_replies(fake_llm, faksettings.WORKSPACE_PROVIDER, settings.MODAL_WORKSPACE_REGION = "modal", ""ModalProvider._sandboxes.clear()user = make_user()- thread = threads.open_thread(frozen_dataset(make_project(member=user), user=user))+ project = make_project(member=user)+ thread = experiment_thread(project, user, frozen_dataset(project, user=user))fake_llm.stream_rounds([([], "Hello.")])say(thread, user, "Hi.")deadline = time.monotonic() + 5@@ -157,7 +172,7 @@ def test_a_turn_starts_the_modal_workspace_while_the_model_replies(fake_llm, fakdef test_the_summary_of_a_call_is_for_the_reader_and_no_tool_receives_it(fake_llm, user, thread):- query = {"summary": "Counting", "dataset": str(thread.dataset_id), "sql": "select 1 as one"}+ query = {"summary": "Counting", "dataset": str(dataset_of(thread).pk), "sql": "select 1 as one"}fake_llm.stream_rounds([([tool_call("query_dataset", query)], ""), ([], "One.")])say(thread, user, "Count.")(counted,) = results(thread)@@ -179,23 +194,6 @@ def test_a_question_ends_the_turn_and_the_answer_continues_it(fake_llm, user, thassert kinds(thread)[3:] == ["user", "assistant"]-def test_a_message_waits_for_its_source_and_landing_starts_the_turn(- user, woken, django_capture_on_commit_callbacks-):- project = make_project(member=user)- dataset = Dataset.objects.create(project=project, name="new", state=Dataset.State.LANDING)- thread = threads.open_thread(dataset)- threads.send(thread, user, request_key="k", text="Prepare it.")- turn.run(thread.pk)- thread.refresh_from_db()- assert thread.state == AssistantThread.State.IDLE and not thread.events.exists()-- Dataset.objects.filter(pk=dataset.pk).update(state=Dataset.State.IDLE)- with django_capture_on_commit_callbacks(execute=True):- turn.wake_dataset(dataset.pk)- assert woken == [str(thread.pk)]--def test_stop_ends_the_turn_at_its_next_step_and_drops_the_queue(fake_llm, user, thread, woken):def reply(_request):# The user stops while the model writes a call, and the reply streams on past the@@ -203,7 +201,7 @@ def test_stop_ends_the_turn_at_its_next_step_and_drops_the_queue(fake_llm, user,AssistantThread.objects.filter(pk=thread.pk).update(stop_requested=True)threads.send(thread, user, request_key="later", text="And then?")time.sleep(turn.DRAFT_INTERVAL_SECONDS * 2)- query = {"summary": "Counting", "dataset": str(thread.dataset_id), "sql": "select 1"}+ query = {"summary": "Counting", "dataset": str(dataset_of(thread).pk), "sql": "select 1"}return {"content": None, "tool_calls": [tool_call("query_dataset", query)], "usage": {}}fake_llm.on(lambda request: bool(request.body.get("stream")), reply)@@ -222,11 +220,8 @@ def test_a_turn_that_stopped_moving_is_interrupted_and_writes_nothing_more(threads.send(thread, user, request_key="k", text="Prepare it.")stale = timezone.now() - turn.STALE - timedelta(minutes=1)AssistantThread.objects.filter(pk=thread.pk).update(state="running", turn=4)- assert str(thread.dataset_id) in list_activity.current_work([thread.dataset])AssistantThread.objects.filter(pk=thread.pk).update(updated_at=stale)thread.refresh_from_db()- # The dataset list does not show a lost turn as current work.- assert str(thread.dataset_id) not in list_activity.current_work([thread.dataset])with django_capture_on_commit_callbacks(execute=True):settled = turn.settle(thread)@@ -338,7 +333,11 @@ def test_one_call_retains_a_pipeline_and_runs_it_and_a_correction_is_its_next_re):manifest = {"version": 1, "steps": [{"name": "Keep", "entrypoint": "keep.py"}]}files = {"manifest.json": json.dumps(manifest), "keep.py": KEEP}- run = {"summary": "Publishing", "source_cell": str(thread.dataset.source.pk), "mode": "publish"}+ run = {+ "summary": "Publishing",+ "source_cell": str(dataset_of(thread).source.pk),+ "mode": "publish",+ }first = tool_call("run_pipeline", {**run, "name": "Keep", "files": files})fake_llm.stream_rounds([([first], ""), ([], "Published.")])say(thread, user, "Prepare it.")@@ -364,8 +363,8 @@ def test_a_publish_runs_a_sample_first_and_a_failing_sample_publishes_nothing():project = make_project(member=user)rows = [{"input": f"q{i}", "expected_output": "a"} for i in range(tools.SAMPLE_ROWS + 1)]- thread = threads.open_thread(frozen_dataset(project, rows, user=user))- source = thread.dataset.source+ thread = experiment_thread(project, user, frozen_dataset(project, rows, user=user))+ source = dataset_of(thread).sourcemanifest = {"version": 1, "steps": [{"name": "Break", "entrypoint": "break.py"}]}files = {"manifest.json": json.dumps(manifest), "break.py": "raise SystemExit('broken')\n"}call = {"summary": "Publishing", "source_cell": str(source.pk), "mode": "publish"}@@ -378,11 +377,13 @@ def test_a_publish_runs_a_sample_first_and_a_failing_sample_publishes_nothing(assert not failed["ok"] and failed["content"]["sample"] and failed["content"]["error"](run,) = DatasetPipeline.objects.get().datasetpipelinerun_set.all()assert (run.mode, run.state) == ("preview", "failed")- thread.dataset.refresh_from_db()- assert thread.dataset.active_cell == source+ dataset_of(thread).refresh_from_db()+ assert dataset_of(thread).active_cell == source-def test_the_first_message_carries_each_versions_fit_profile_and_the_capability_contract(user):+def test_each_message_carries_each_pinned_versions_fit_profile_and_the_capability_contract(+ user,+):project = make_project(member=user)capability = make_capability(project,@@ -394,60 +395,16 @@ def test_the_first_message_carries_each_versions_fit_profile_and_the_capability_{"messages": reply[:1] + [{"role": "assistant", "content": "Bye"}], "queue": "tech"}]dataset = frozen_dataset(project, rows, user=user, capability=capability)- brief = threads.brief(threads.open_thread(dataset))+ (pinned,) = threads.brief(experiment_thread(project, user, dataset))["datasets"]- assert brief["capability"]["system_prompt"] == "Answer tickets."- source = brief["source"]+ assert pinned["capability"]["system_prompt"] == "Answer tickets."+ source = pinned["version"]assert source["fit"]["sft"]["ok"] and not source["fit"]["decision"]["ok"]assert source["duplicate_rows"] == 1queue = next(column for column in source["columns"] if column["name"] == "queue")assert queue["distinct"] == 2 and queue["top"][0] == {"value": "billing", "count": 2}-def test_a_dataset_made_with_an_intent_queues_one_first_pass_and_a_split_one_for_both(user):- project = make_project(member=user)- client = auth_client(user)- body = {- "project": str(project.pk),- "name": "Tickets",- "brief": "Keep the tone.",- "prepare": True,- "source": {"rows": [{"text": f"t{i}"} for i in range(4)]},- }- made = client.post("/api/datasets/", {**body, "intent": "train"}, format="json").data- (message,) = AssistantInput.objects.filter(thread__dataset_id=made["id"])- assert message.text == f"{threads.FIRST_PASS['train']}\n\nKeep the tone."- assert message.state == AssistantInput.State.QUEUED-- plain = client.post("/api/datasets/", {**body, "prepare": False}, format="json").data- assert not AssistantThread.objects.filter(dataset_id=plain["id"]).exists()-- split = {**body, "name": "Pair", "eval_percent": 50, "position": "tail"}- pair = client.post("/api/datasets/split/", split, format="json").data- (first,) = AssistantInput.objects.filter(thread__dataset_id=pair["train"]["id"])- assert first.text.startswith(threads.SPLIT_PASS)- assert not AssistantThread.objects.filter(dataset_id=pair["eval"]["id"]).exists()---def test_a_first_pass_waits_through_a_failed_import_for_a_landed_source(- user, woken, django_capture_on_commit_callbacks-):- project = make_project(member=user)- dataset = Dataset.objects.create(- project=project, name="t", intent="train", state=Dataset.State.ERROR- )- message = threads.queue_first_pass(dataset, user)- thread = message.thread- turn.run(thread.pk)- message.refresh_from_db()- assert message.state == AssistantInput.State.QUEUED and not thread.events.exists()-- land.land_rows(dataset, [{"text": "a"}])- with django_capture_on_commit_callbacks(execute=True):- turn.wake_dataset(dataset.pk)- assert woken == [str(thread.pk)]--def test_a_kernel_that_restarted_is_told_to_the_model(fake_llm, user, thread):provider = workspaces.provider()project, conversation = str(thread.project_id), thread.pk.hex@@ -468,7 +425,7 @@ def test_a_long_conversation_is_summarized_and_no_call_loses_its_result(fake_llm, user, thread, settings):settings.ASSISTANT_COMPACT_TOKENS = 0- query = {"summary": "Counting", "dataset": str(thread.dataset_id), "sql": "select 1"}+ query = {"summary": "Counting", "dataset": str(dataset_of(thread).pk), "sql": "select 1"}fake_llm.on_json(lambda r: not r.body.get("stream"), lambda _r: {})fake_llm.on(lambda r: not r.body.get("stream"), {"content": "Earlier: counted.", "usage": {}})rounds = []@@ -485,7 +442,7 @@ def test_a_long_conversation_is_summarized_and_no_call_loses_its_result(def test_a_reply_with_tool_calls_returns_its_reasoning_to_the_model(fake_llm, user, thread):- query = {"summary": "Counting", "dataset": str(thread.dataset_id), "sql": "select 1"}+ query = {"summary": "Counting", "dataset": str(dataset_of(thread).pk), "sql": "select 1"}fake_llm.stream_rounds([([tool_call("query_dataset", query)], ""), ([], "Done.")], reasoning="why")@@ -524,14 +481,56 @@ def test_the_log_stores_what_a_kernel_prints_that_jsonb_refuses(thread):assert event.payload == {"content": {"output": "a�b", "n": None}}-def test_deleting_a_dataset_deletes_its_copies_in_the_workspace(+def test_a_pinned_dataset_stays_and_deleting_its_experiment_then_it_deletes_their_files(user, thread, monkeypatch, django_capture_on_commit_callbacks):forgotten = []monkeypatch.setattr(assistant_tasks.forget_workspace_data, "delay", lambda *a: forgotten.append(a))- source = thread.dataset.source+ dataset = dataset_of(thread)+ source = dataset.source+ with pytest.raises(lifecycle.DatasetError, match="Prepare"):+ lifecycle.delete_dataset(dataset)with django_capture_on_commit_callbacks(execute=True):- lifecycle.delete_dataset(thread.dataset)- assert forgotten == [(str(thread.project_id), [f"{source.pk}.parquet"], [thread.pk.hex])]+ records.delete(thread.experiment)+ lifecycle.delete_dataset(dataset)+ project = str(thread.project_id)+ assert forgotten == [+ (project, [], [thread.pk.hex, records.kernel(thread.experiment)]),+ (project, [f"{source.pk}.parquet"], []),+ ]+++def test_a_turn_out_of_time_continues_in_the_next_until_its_limit(user, thread, woken):+ threads.send(thread, user, request_key="k", text="Work for long.")+ with pytest.MonkeyPatch.context() as patch:+ patch.setattr(turn, "TURN_SECONDS", -1)+ for _ in range(turn.CONTINUES + 1):+ turn.run(thread.pk)+ continued = thread.inputs.filter(origin=AssistantInput.Origin.CONTINUE)+ assert continued.count() == turn.CONTINUES+ states = [e.payload["state"] for e in thread.events.filter(kind="status")]+ assert states == ["continued"] * turn.CONTINUES + ["failed"]+++def test_unattended_work_waits_for_a_free_turn_and_a_persons_message_never_does(+ user, thread, woken+):+ project = thread.project+ busy = [+ experiment_thread(project, user, frozen_dataset(project, user=user))+ for _ in range(turn.UNATTENDED_TURNS)+ ]+ AssistantThread.objects.filter(pk__in=[t.pk for t in busy]).update(state="running")+ notice = {"request_key": "n", "text": "A run ended.", "origin": AssistantInput.Origin.RUN}+ threads.send(thread, user, **notice)+ assert turn._begin(thread.pk) == (None, False)+ assert list(turn.waiting(project.pk).values_list("pk", flat=True)) == [thread.pk]+ # A turn that failed since waits for a person, not for another turn's end.+ log.append(thread, "status", {"state": "failed", "detail": "The turn failed."})+ assert not turn.waiting(project.pk).exists()+ # A person's message queued behind the notice starts the turn at once.+ threads.send(thread, user, request_key="p", text="Now, please.")+ started, _ = turn._begin(thread.pk)+ assert started is not Nonediff --git a/tests/test_dataset_import_receipts.py b/tests/test_dataset_import_receipts.pyindex 247abbf5..9b297d96 100644--- a/tests/test_dataset_import_receipts.py+++ b/tests/test_dataset_import_receipts.py@@ -17,14 +17,11 @@ from datetime import timedeltaimport pytestfrom django.db import close_old_connections, connectionfrom django.utils import timezone-from factories import make_userfrom overbae.models import Cell, Dataset, DatasetImport, DatasetPipelineRun, Project-from overbae.services.assistant import threadsfrom overbae.services.datasets import dispatch, files, imports, workbenchfrom overbae.services.datasets.lifecycle import DatasetErrorfrom overbae.tasks import datasets as dataset_tasks-from overbae.tasks.assistant import run_turnfrom overbae.tasks.cleanup_tmp import cleanup_uploadspytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("work-once")]@@ -172,10 +169,6 @@ def test_an_import_that_keeps_losing_its_worker_is_blocked_with_its_source(from overbae.services.datasets import importsdataset, run = create_import(imported_source)- started = []- monkeypatch.setattr(run_turn, "delay", started.append)- conversation = threads.open_thread(dataset)- threads.send(conversation, make_user(), request_key="sent", text="Prepare it.")for _ in range(imports.MAX_ATTEMPTS):assert imports.claim(run.pk) is not NoneDatasetImport.objects.filter(pk=run.pk).update(@@ -187,8 +180,6 @@ def test_an_import_that_keeps_losing_its_worker_is_blocked_with_its_source(assert run.state == "blocked" and run.failure_code == "worker_timeout"assert dataset.state == "error"assert files.upload_data_path(imported_source[1]).exists()- # The message sent with the upload no longer waits for a source that will not land.- assert started == [str(conversation.pk)]def test_stale_import_cannot_write_or_publish_landing_progress(imported_source, monkeypatch):diff --git a/tests/test_dataset_thread_migration.py b/tests/test_dataset_thread_migration.pynew file mode 100644index 00000000..e7775259--- /dev/null+++ b/tests/test_dataset_thread_migration.py@@ -0,0 +1,46 @@+import pytest+from django.db.migrations.executor import MigrationExecutor+from migration_replay import scratch_database++pytestmark = pytest.mark.covers("migrations")+++def test_each_dataset_conversation_becomes_an_experiment_that_reads_the_dataset(+ django_db_blocker,+):+ before = [("overbae", "0072_experiment_request_fingerprint")]+ after = [("overbae", "0073_one_agent")]+ with scratch_database(django_db_blocker) as database:+ executor = MigrationExecutor(database)+ executor.migrate(before)+ state = executor.loader.project_state(before).apps+ user = state.get_model("overbae", "User").objects.create(email="[email protected]")+ project = state.get_model("overbae", "Project").objects.create(name="P", slug="p")+ datasets = state.get_model("overbae", "Dataset").objects+ cells = state.get_model("overbae", "Cell").objects+ threads = state.get_model("overbae", "AssistantThread").objects+ inputs = state.get_model("overbae", "AssistantInput").objects+ ready = datasets.create(project=project, name="Tickets", created_by=user)+ source = cells.create(dataset=ready, position=0, state="ok", fingerprint="f0")+ landing = datasets.create(project=project, name="Upload", state="landing")+ talked = threads.create(project=project, dataset=ready)+ inputs.create(thread=talked, created_by=user, request_key="k", text="Clean it", position=1)+ waiting = threads.create(project=project, dataset=landing)+ first = {"thread": waiting, "created_by": user, "text": "Prepare it", "position": 1}+ inputs.create(**first, request_key=f"first-pass:{landing.pk}")++ executor = MigrationExecutor(database)+ executor.migrate(after)+ state = executor.loader.project_state(after).apps+ threads = state.get_model("overbae", "AssistantThread").objects+ moved = threads.select_related("experiment").get(pk=talked.pk)+ empty = threads.select_related("experiment").get(pk=waiting.pk)+ revision = moved.experiment.revisions.get()++ assert (moved.dataset_id, moved.experiment.name) == (None, "Prepare Tickets")+ assert moved.experiment.created_by_id == user.pk+ assert revision.document["nodes"][0]["settings"] == {"cell": str(source.pk)}+ assert moved.inputs.get().text == "Clean it"+ assert (empty.experiment.name, empty.experiment.version) == ("Prepare Upload", 0)+ # The first pass that waited for its source would run unasked in the experiment.+ assert empty.inputs.get().state == "removed"diff --git a/tests/test_experiments.py b/tests/test_experiments.pyindex 4b01728e..4815e3ac 100644--- a/tests/test_experiments.py+++ b/tests/test_experiments.py@@ -1,5 +1,7 @@"""Experiments: the flow document's rules, a run's lifecycle and the surfaces that drive it."""+import dataclasses+import uuidfrom datetime import timedeltaimport pytest@@ -11,6 +13,7 @@ from mcp_fixtures import call_tool, mcp_contextfrom overbae.core.errors import InputValidationErrorfrom overbae.models import (AssistantInput,+ Cell,ConnectorCredential,EvalRun,EvalRunRow,@@ -54,6 +57,8 @@ def setup(eager, monkeypatch):def test_flow_refuses_type_mismatches_loops_and_early_holdout_reads():split = {"id": "split", "kind": "split", "inputs": {"data": ["data.data"]}}data = {"id": "data", "kind": "data", "settings": {"cell": "x"}}+ # A malformed protected mark is dropped, not a server error.+ assert document.normalize({"nodes": [{**data, "protected": 1}]})["nodes"][0]["protected"] == []with pytest.raises(InputValidationError, match="takes data, not model"):document.normalize({@@ -491,6 +496,15 @@ def test_a_run_past_its_deadline_and_a_deleted_experiment_stop_their_work(setup)records.delete(experiment)run.refresh_from_db()assert run.state == ExperimentRun.State.STOPPED+ # A deleted experiment's agent takes no notice and starts no turn.+ from overbae.services.assistant import threads, turn++ experiment.refresh_from_db()+ thread = experiment.assistant_thread+ late = {"origin": "run", "text": "Run 2 ended.", "request_key": "late"}+ assert operator.notify(experiment, context.user, **late) is None+ threads.send(thread, context.user, request_key="m", text="Go on.")+ assert turn._begin(thread.pk) == (None, False)def test_the_experiment_agent_edits_and_runs_the_flow_with_the_mcp_tools(setup, fake_llm):@@ -583,6 +597,8 @@ def test_a_partition_stage_runs_the_platform_partition_and_seals_the_final_holdoassert [call["tool"] for call in split.calls] == ["create_data_partition"]assert run.steps.get(node="check").outputs["report"]["rows"] < 40assert run.state == ExperimentRun.State.COMPLETED+ made = records.dataset_links(context.project.pk)[split.outputs["train"]["dataset"]]+ assert made["made_by"]["experiment"] == str(experiment.pk)def test_an_evaluation_names_why_it_was_refused_or_scored_no_row(setup, monkeypatch):@@ -891,3 +907,308 @@ def test_mcp_run_control_and_triggers_replay_a_request_key_once(setup):call_tool("configure_experiment_trigger", trigger, context)call_tool("configure_experiment_trigger", trigger, context)assert experiment.triggers.filter(deleted_at=None).count() == 1+++def test_data_dropped_without_a_message_lands_in_an_experiment_that_names_and_keeps_it(setup):+ from factories import auth_client++ from overbae.services.datasets import lifecycle++ context, cell = setup+ client = auth_client(context.user)+ body = {"project": str(context.project.pk), "cells": [str(cell.pk)], "request_key": "drop"}+ created = client.post("/api/experiments/", body, format="json").data+ assert not experiment_thread(created["id"]).inputs.exists()++ shown = client.get(f"/api/datasets/{cell.dataset_id}/").data+ used = {"experiment": created["id"], "name": created["name"]}+ assert (shown["made_by"], shown["used_in"]) == (None, [used])+ with pytest.raises(lifecycle.DatasetError, match=created["name"]):+ lifecycle.delete_dataset(cell.dataset)++ reader = records.create(context.project, context.user, document=flow(cell.pk))+ runs.advance(runs.start(reader, context.user, origin="console").pk)+ listed = client.get(f"/api/datasets/?project={context.project.pk}").data["results"]+ (row,) = [row for row in listed if row["id"] == str(cell.dataset_id)]+ # A Data stage reads a version; only a stage that wrote one made it.+ assert row["made_by"] is None and len(row["used_in"]) == 2+++def test_a_setting_a_person_chose_changes_only_when_they_apply_the_agents_proposal(setup):+ from factories import auth_client++ from overbae.services.mcp.context import ASSISTANT++ context, cell = setup+ other = frozen_dataset(context.project, ROWS, name="other").active_cell+ experiment = records.create(context.project, context.user, document=flow(cell.pk))+ agent = dataclasses.replace(context, client_name=ASSISTANT)+ swap = {"set": {"id": "data", "settings": {"cell": str(other.pk)}}}+ edit = {"experiment": str(experiment.pk), "expected_version": 1, "request_key": "swap"}+ refused = call_tool("revise_experiment", {**edit, "changes": [swap]}, agent)+ assert refused.structuredContent["error"]["code"] == "protected_setting"+ experiment.refresh_from_db()+ assert experiment.version == 1+ # Another kind under the same id replaces every setting a person set.+ retyped = {"set": {"id": "data", "kind": "trace_dataset", "settings": {"name": "T"}}}+ kind = call_tool("revise_experiment", {**edit, "request_key": "k", "changes": [retyped]}, agent)+ assert kind.structuredContent["error"]["code"] == "protected_setting", kind.structuredContent++ # Everything else stays the agent's to change.+ title = {"set": {"id": "check", "title": "Rows check"}}+ saved = call_tool("revise_experiment", {**edit, "request_key": "t", "changes": [title]}, agent)+ assert not saved.isError, saved.structuredContent++ client = auth_client(context.user)+ url = f"/api/experiments/{experiment.pk}"+ experiment.refresh_from_db()+ # The agent's later save moved the flow past the first proposal's base.+ assert records.proposals(experiment) == []+ again = call_tool(+ "revise_experiment", {**edit, "expected_version": 2, "changes": [swap]}, agent+ )+ assert again.structuredContent["error"]["code"] == "protected_setting"+ retried = call_tool(+ "revise_experiment", {**edit, "expected_version": 2, "changes": [swap]}, agent+ )+ assert retried.structuredContent["error"]["code"] == "protected_setting"+ (proposal,) = client.get(f"{url}/").data["proposals"]+ assert proposal["changes"][0] == {+ "node": "data",+ "title": "Data",+ "key": "cell",+ "before": str(cell.pk),+ "after": str(other.pk),+ "before_label": cell.dataset.name,+ "after_label": "other",+ }+ applied = client.post(+ f"{url}/proposals/{proposal['sequence']}/", {"apply": True}, format="json"+ )+ assert applied.status_code == 200, applied.data+ assert applied.data["document"]["nodes"][0]["settings"]["cell"] == str(other.pk)+ assert applied.data["proposals"] == []+++def test_notes_are_written_with_a_save_and_read_back_with_the_spend(setup):+ context, cell = setup+ experiment = records.create(context.project, context.user, document=flow(cell.pk))+ noted = call_tool(+ "revise_experiment",+ {+ "experiment": str(experiment.pk),+ "expected_version": 1,+ "notes": "Plan: check rows.",+ "request_key": "n",+ },+ context,+ )+ assert not noted.isError, noted.structuredContent+ read = call_tool("inspect_experiment", {"experiment": str(experiment.pk)}, context)+ assert read.structuredContent["notes"] == "Plan: check rows."+ assert read.structuredContent["spend"] == {"measured_usd": 0.0, "unknown": []}+ from overbae.services.experiments import describe++ experiment.refresh_from_db()+ assert describe.brief(experiment)["notes"] == "Plan: check rows."+++def test_agents_read_no_row_of_a_final_holdout(setup):+ context, _ = setup+ rows = [{"input": f"q{i}", "expected_output": f"a{i}"} for i in range(40)]+ cell = frozen_dataset(context.project, rows, name="many").active_cell+ experiment = records.create(+ context.project,+ context.user,+ document={+ "nodes": [+ {"id": "data", "kind": "data", "settings": {"cell": str(cell.pk)}},+ {+ "id": "split",+ "kind": "split",+ "inputs": {"data": ["data.data"]},+ "settings": {"train": 0.7, "development": 0.15, "final": 0.15, "seed": 7},+ },+ ]+ },+ )+ run = runs.start(experiment, context.user, origin="console")+ runs.advance(run.pk)+ final = run.steps.get(node="split").outputs["final"]+ query = {"dataset": final["dataset"], "sql": "select count(*) from t"}+ assert call_tool("query_dataset", query, context).structuredContent["error"]["code"] == (+ "holdout_sealed"+ )+ code = {"experiment": str(experiment.pk), "code": "1", "versions": [final["cell"]]}+ assert call_tool("run_python", code, context).structuredContent["error"]["code"] == (+ "holdout_sealed"+ )+ sealed = Cell.objects.get(pk=final["cell"])+ transform = {+ "dataset": final["dataset"],+ "source_cell": final["cell"],+ "source_fingerprint": sealed.fingerprint,+ "pipeline": str(uuid.uuid4()),+ "request_key": "leak",+ }+ refused = call_tool("run_dataset_pipeline", transform, context).structuredContent+ assert refused["error"]["code"] == "holdout_sealed"+ from overbae.services.experiments import describe++ pinned = {"nodes": [{"id": "data", "kind": "data", "settings": {"cell": final["cell"]}}]}+ reading = records.create(context.project, context.user, document=pinned)+ assert describe.brief(reading)["datasets"] == []+++def test_a_coding_agent_has_its_own_kernel_that_a_delete_forgets(setup, monkeypatch):+ from overbae.services import workspaces+ from overbae.tasks.assistant import forget_workspace_data++ context, cell = setup+ experiment = records.create(context.project, context.user, document=flow(cell.pk))+ cells = {"experiment": str(experiment.pk), "versions": [str(cell.pk)]}+ project = str(context.project.pk)+ try:+ first = call_tool("run_python", {**cells, "code": "x = 41"}, context)+ assert first.structuredContent["ok"], first.structuredContent+ read = call_tool("run_python", {**cells, "code": "x + 1"}, context)+ assert read.structuredContent["output"].strip() == "42"+ forgotten = []+ monkeypatch.setattr(forget_workspace_data, "delay", lambda *a: forgotten.append(a))+ records.delete(experiment)+ (_, _, conversations) = forgotten[0]+ assert len(conversations) == 2 and experiment.assistant_thread.pk.hex in conversations+ finally:+ workspaces.provider().remove(project)+++def test_unattended_runs_stop_at_a_triggers_spend_cap_and_a_person_starts_them_again(setup):+ from decimal import Decimal++ from overbae.services.assistant import log, threads++ context, cell = setup+ experiment = records.create(context.project, context.user, document=flow(cell.pk))+ triggers.create(+ experiment,+ context.user,+ kind="schedule",+ instruction="Improve it.",+ hours=24,+ max_sends=4,+ max_spend_usd=Decimal("0.30"),+ )+ thread = experiment.assistant_thread+ # Exactly the cap: 0.3 as a float is below Decimal("0.30"), and must not slip under it.+ log.append(thread, "assistant", {"text": "", "calls": [], "usage": {"response_cost": 0.3}})+ notice = {"request_key": "t", "text": "Improve it.", "origin": AssistantInput.Origin.TRIGGER}+ threads.send(thread, context.user, **notice)+ with pytest.raises(InputValidationError, match="spend cap of \\$0.30"):+ runs.start(experiment, context.user, origin=ExperimentRun.Origin.ASSISTANT)+ # Past its cap the trigger sends nothing: a send starts paid agent turns.+ ExperimentTrigger.objects.filter(experiment=experiment).update(next_at=timezone.now())+ assert triggers.fire_due() == 0+ threads.send(thread, context.user, request_key="p", text="Run it.")+ assert runs.start(experiment, context.user, origin=ExperimentRun.Origin.ASSISTANT)+++def test_a_deployment_the_agents_run_started_stops_with_the_run(setup, scripted):+ from django.conf import settings++ from overbae.models import DeployedModel++ context, cell = setup+ gateway = scripted(settings.INFERENCE_API_URL).reply(json_body={})+ experiment = records.create(context.project, context.user, document=flow(cell.pk))+ run = runs.start(experiment, context.user, origin=ExperimentRun.Origin.ASSISTANT)+ deployed = DeployedModel.objects.create(+ project=context.project, model_id="ft-eval", status=DeployedModel.Status.READY+ )+ # One that served before the run, as deploying a trained model again returns it, stays.+ served = DeployedModel.objects.create(+ project=context.project, model_id="ft-mine", status=DeployedModel.Status.READY+ )+ DeployedModel.objects.filter(pk=served.pk).update(created_at=run.created_at - timedelta(1))+ # A failed attempt that had served deployments; its retry ends the run again.+ receipts = [{"kind": "deployment", "id": str(d.pk)} for d in (deployed, served)]+ ExperimentStep.objects.filter(run=run, node="check").update(+ state=ExperimentStep.State.FAILED, receipts=receipts+ )+ ExperimentRun.objects.filter(pk=run.pk).update(state=ExperimentRun.State.UNMET)+ run.refresh_from_db()+ runs.retry(run, context.user)+ deployed.refresh_from_db()+ served.refresh_from_db()+ assert deployed.status == DeployedModel.Status.DELETED and gateway.calls+ assert served.status == DeployedModel.Status.READY+++def test_your_system_answers_where_it_runs_and_its_outputs_are_scored_as_recorded(+ setup, monkeypatch+):+ from types import SimpleNamespace++ from factories import auth_client++ from overbae.innermind import generation+ from overbae.services.datasets.rows import row_from_record+ from overbae.tasks.innermind import run_eval_run++ context, cell = setup+ make_matrix_row(context.project)+ monkeypatch.setattr(run_eval_run, "delay", lambda **kwargs: SimpleNamespace(id="t"))+ experiment = records.create(+ context.project,+ context.user,+ document={+ "nodes": [+ {"id": "data", "kind": "data", "settings": {"cell": str(cell.pk)}},+ {+ "id": "mine",+ "kind": "system",+ "inputs": {"data": ["data.data"]},+ "settings": {"label": "main"},+ },+ # A stage that keeps the rows keeps them your system's outputs.+ {+ "id": "check",+ "kind": "check_data",+ "inputs": {"data": ["mine.data"]},+ "settings": {"schema": {"type": "object", "required": ["input"]}},+ },+ {"id": "eval", "kind": "evaluate", "inputs": {"data": ["check.data"]}},+ ]+ },+ )+ run = runs.start(experiment, context.user, origin="console")+ runs.advance(run.pk)+ step = run.steps.get(node="mine")+ client = auth_client(context.user)+ asked = client.get(f"/api/experiment-steps/{step.pk}/rows/").data+ assert asked["label"] == "main" and [r["source_row"] for r in asked["rows"]] == [0, 1]++ outputs = [{"source_row": r["source_row"], "output": "ciao"} for r in asked["rows"]]+ body = {"outputs": outputs, "repository": {"commit": "abc123", "dirty": False}}+ sent = client.post(f"/api/experiment-steps/{step.pk}/outputs/", body, format="json")+ assert sent.status_code == 201, sent.data+ runs.advance(run.pk)+ step.refresh_from_db()+ assert step.state == ExperimentStep.State.COMPLETED, step.error+ assert step.outputs["data"]["system"] == "main"+ # The outputs are a dataset of their own; the input's active version stays.+ cell.dataset.refresh_from_db()+ assert cell.dataset.active_cell.pk == cell.pk+ assert step.outputs["data"]["dataset"] != str(cell.dataset_id)+ # A retry after a lost response returns the same import.+ again = client.post(f"/api/experiment-steps/{step.pk}/outputs/", body, format="json")+ assert (again.status_code, again.data) == (201, sent.data)+ evaluated = run.steps.get(node="eval")+ (call,) = [c for c in evaluated.calls if c.get("tool") == "run_evaluation"]+ assert call["ok"], call+ assert evaluated.receipts[0]["kind"] == "eval_run"+ # Recorded mode scores the system's answer against the dataset's reference.+ row = {"input": "hi", "expected_output": "hello", "_overmind_output": "ciao"}+ assert generation.recorded_output(row_from_record(0, row)) == "ciao"+ # A dataset's own output column keeps its meaning.+ plain = {"input": "hi", "expected_output": "hello", "output": "ciao"}+ assert generation.recorded_output(row_from_record(0, plain)) == "hello"diff --git a/tests/test_landing_admission.py b/tests/test_landing_admission.pyindex 3b62b6d0..aabd71af 100644--- a/tests/test_landing_admission.py+++ b/tests/test_landing_admission.py@@ -245,19 +245,11 @@ def lapse(run):def test_a_lost_upload_retries_under_a_new_owner_until_its_attempt_limit(monkeypatch):- from factories import make_user-- from overbae.services.assistant import threadsfrom overbae.services.datasets import files, imports- from overbae.tasks.assistant import run_turndataset, run, upload_id = admitted_upload(monkeypatch, "passengers.csv", b"passenger_id,survived\n1,0\n2,1\n")- woken = []- monkeypatch.setattr(run_turn, "delay", woken.append)- conversation = threads.open_thread(dataset)- threads.send(conversation, make_user(), request_key="sent", text="Prepare it.")messages = []admission.dispatch(lambda **message: messages.append(message))owners = []@@ -278,8 +270,6 @@ def test_a_lost_upload_retries_under_a_new_owner_until_its_attempt_limit(monkeypassert dataset.state == "error"assert DatasetLandingWork.objects.get(pk=run.pk).state == "failed"assert files.upload_data_path(upload_id).exists()- # The message sent with the upload no longer waits for a source that will not land.- assert woken == [str(conversation.pk)]stale = land.apply(kwargs=messages[0]["kwargs"], task_id=str(run.pk), headers={admission.HEADER: owners[0]})diff --git a/tests/test_project_setup.py b/tests/test_project_setup.pynew file mode 100644index 00000000..23deaca0--- /dev/null+++ b/tests/test_project_setup.py@@ -0,0 +1,41 @@+import pytest+from conftest import frozen_dataset+from django.utils import timezone+from factories import auth_client, make_capability, make_project, make_user++from overbae.models import DeployedModel++pytestmark = [pytest.mark.django_db, pytest.mark.covers("home-setup")]+++def test_home_setup_is_decided_once_and_a_reached_step_stays_done():+ user = make_user()+ project = make_project(member=user)+ client = auth_client(user)++ def setup():+ return client.get(f"/api/project-setup/?project={project.pk}").data++ assert setup() == {+ "scanned": False,+ "dataset": False,+ "eval_set": False,+ "trained": False,+ "deployed": False,+ }+ make_capability(project, "Support")+ frozen_dataset(project, user=user)+ served = DeployedModel.objects.create(+ project=project, model_id="ft-a", status="ready", deployed_at=timezone.now()+ )+ # A deployment that stopped since still served: the checklist does not come back.+ DeployedModel.objects.filter(pk=served.pk).update(status="deleted")+ assert setup() == {+ "scanned": True,+ "dataset": True,+ "eval_set": False,+ "trained": False,+ "deployed": True,+ }+ outsider = auth_client(make_user()).get(f"/api/project-setup/?project={project.pk}")+ assert outsider.status_code == 404diff --git a/tests/test_workspaces.py b/tests/test_workspaces.pyindex ad4b61fa..98cfd986 100644--- a/tests/test_workspaces.py+++ b/tests/test_workspaces.py@@ -7,13 +7,12 @@ from datetime import timedeltafrom decimal import Decimalimport pytest-from conftest import frozen_datasetfrom django.utils import timezonefrom factories import make_project, make_userfrom starlette.testclient import TestClientfrom overbae.models import AssistantThread, BillingService, BillingTelemetry, WorkspaceSandbox-from overbae.services.assistant import threads+from overbae.services.experiments import recordsfrom overbae.services.workspaces import WorkspaceUnavailableError, conformancefrom overbae.services.workspaces.modal_sandbox import ModalProviderfrom overbae.services.workspaces.native import NativeProvider@@ -242,7 +241,7 @@ def test_a_modal_sandbox_of_no_project_is_never_charged(modal_workspaces, fake_mdef test_a_workspace_its_project_has_not_used_for_a_week_is_removed(db, provider):user = make_user()recent, old = (- threads.open_thread(frozen_dataset(make_project(member=user), user=user)) for _ in range(2)+ records.create(make_project(member=user), user, name="E").assistant_thread for _ in range(2))AssistantThread.objects.filter(pk=old.pk).update(updated_at=timezone.now() - timedelta(days=8))unused = str(uuid.uuid4())