The platform for continuously improving AI agents.
Evaluations and Data Workshop: pinned judges, drafted eval sets, XLSX and column sets (#369)
Freyam Mehtac219261ec7fd
diff --git a/.agents/skills/backend-architecture/references/assistant.md b/.agents/skills/backend-architecture/references/assistant.mdindex a2eb2e30..8d94d57e 100644--- a/.agents/skills/backend-architecture/references/assistant.md+++ b/.agents/skills/backend-architecture/references/assistant.md@@ -17,7 +17,7 @@ The Console's assistant is a second author beside a customer's coding agent, and## 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 (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.+- 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. `draft_eval_set` checks criteria with `services/eval_sets.py` and ends the turn with a review card; it saves nothing and is refused in a turn no person started. The person edits it and saves a new set through the eval-sets API (an amended set stays unchanged) or rejects it, and that answer is their reply.- 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"}`.diff --git a/.agents/skills/backend-architecture/references/data-first.md b/.agents/skills/backend-architecture/references/data-first.mdindex d7afc6d1..ef2b21d4 100644--- a/.agents/skills/backend-architecture/references/data-first.md+++ b/.agents/skills/backend-architecture/references/data-first.md@@ -18,7 +18,7 @@ Data-first projects start from uploaded data and the original task brief (`Datas- Partitions keep exact content, declared groups, synthetic lineage and duplicate observations together. Calibration and final members have eval intent. Group and content checks report exact overlap only; they do not prove absence of paraphrase or pretraining contamination.- Final and calibration data never select a recipe. Full experiments need audit, baseline and sanity reports but no pilot. Optional pilot selection needs a measured task metric from a matching settled pilot with a verified checkpoint.- Experiments prepare a configuration-bound forecast before launch and may enforce user-defined planning constraints. Unmeasured or over-budget quotes do not recommend launch. Constraints are not an invoice cap.-- Native comparisons save a draft, prepare immutable suites in the background and launch explicitly. Calibration is a barrier: it is fitted (global, then per kind, by local L-BFGS-B) before final predictions, and stays separate from final scoring. References stay local and never enter a worker.+- Native comparisons save a draft, prepare immutable suites in the background and launch explicitly. A participant's `instructions` (at most 8000 characters) go before each decision question, locally and for System One; they are part of its preparation group, and a preparation receipt with other instructions is refused. Purpose `final` reads an evaluation dataset; `development` also reads decision training rows. Calibration is a barrier: it is fitted (global, then per kind, by local L-BFGS-B) before final predictions, and stays separate from final scoring. References stay local and never enter a worker.- Every paid call is journaled. Unacknowledged native submissions and bare external intents are never replayed; a paused native collector resumes only with its exact recorded `call_id`. Explicit resume of a local stage (`verify_inputs`, `fit_calibration`, `score`) fences the interrupted lease and reuses saved inputs without provider calls. Pause stops new claims; it does not cancel remote work.- Transient stage failures retry with 15/30-second backoff, at most three attempts. Explicit 429/5xx responses retry only rejected rows. External timeouts retain `submission_unknown` without replay; uncertain costs stay in the attempt ledger.- Exhausted collection scores the verified predictions that exist. Results report `completion.status`, per-suite coverage and issues; partial results are `completed_with_issues`, never silent success or zero-filled scores.diff --git a/.agents/skills/backend-architecture/references/evaluation.md b/.agents/skills/backend-architecture/references/evaluation.mdindex d251dcb4..9a217a6e 100644--- a/.agents/skills/backend-architecture/references/evaluation.md+++ b/.agents/skills/backend-architecture/references/evaluation.md@@ -5,15 +5,16 @@An `EvalRun` scores one target (`mode` `recorded` or `generate`) over one pinned dataset cell with a frozen `matrix` (`runs.freeze_matrix`: the eval set's rows, else every enabled row for the capability). Creating several `targets` makes one run per target under a shared `group`; REST creation allows at most one `is_baseline`. Training groups can mark several baselines, and `baseline_of` takes the newest completed one. Startup commits the running state and the complete row inventory atomically before admission; model warm-up stays outside that transaction.- `innermind/runs.py` owns the lifecycle (create, launch, generate, score, aggregate, finish, cancel, relaunch, reap). `generation.py` and `replay.py` produce outputs.-- `dataset.DatasetRowProcessor` scores rows with the live span evaluators and saves each `EvalScore(source_type=dataset_row)` as it is written, only while the run's `scoring_task_id` is the scorer's own. The scorer beats `updated_at` every 30 s; `runs.reap_stalled` hands a silent one to a new scorer that skips saved rows (up to `SCORING_ATTEMPTS`), sends a pending run's start again after 10 minutes and fails it after 60.+- `create_run` pins `EvalRun.judge_context`: the Jev decision model, the explanation chain (the run's `judge_model` first) and the capability description as the fallback intent. Scoring reads only these; a relaunch keeps them.+- `dataset.DatasetRowProcessor` scores rows with the live span evaluators and saves each `EvalScore(source_type=dataset_row)` as it is written, only while the run's `scoring_task_id` is the scorer's own. A run has one score per row (`uniq_eval_score_run_row`). A generation failure is `EvalRunRow.error`; a scoring failure is `score_error`, and the next scorer scores that row again. The scorer beats `updated_at` every 30 s; `runs.reap_stalled` hands a silent one to a new scorer that skips saved rows (up to `SCORING_ATTEMPTS`), sends a pending run's start again after 10 minutes and fails it after 60.- A row stands for the capability's answer: it takes every frozen row whose `span_type` is blank or `llm_call`, whatever its `span_name`. `tool_call`, `retrieval` and `workflow` rows stay live-only.- A training job reuses its first run's matrix for its later evaluations.-- `comparison.compare` pairs the latest score per row that both runs scored into wins, losses and ties (`EPSILON` 0.005), and labels per-metric and overall means improved, regressed or unchanged; a metric or the overall score with no row scored in both runs, including a metric only one run has, is unmeasured. It also reports trust.+- `comparison.compare` pairs the score of each row that both runs scored into wins, losses and ties (`EPSILON` 0.005), and labels per-metric and overall means improved, regressed or unchanged; a metric or the overall score with no row scored in both runs, including a metric only one run has, is unmeasured. It also reports trust.- Replayed rows snapshot the runner's initial request (`replay.RunResult.request`). A token-limited generation keeps its partial answer and usage, is marked degraded, and is excluded from trusted scores rather than scored as zero.## Judges and context estimates-- `EvalRun.judge_model` freezes the explanation judge; blank uses the `EVAL_EXPLANATION` registry default. It never changes Jev. Existing runs reject judge changes. Training's `eval_judge_model` overrides it for that job's runs, and baseline sharing requires the same judge selection.+- `EvalRun.judge_model` chooses the explanation judge, pinned first in `judge_context`; blank uses the `EVAL_EXPLANATION` registry chain. It never changes Jev. Existing runs reject judge changes. Training's `eval_judge_model` overrides it for that job's runs, and baseline sharing requires the same judge selection.- `innermind/context.py` supplies advisory context estimates for generate targets and the judge, including reserved output (REST `POST /api/eval-runs/context-check/`, run detail, MCP readiness). Warnings never change `ready`, gate launch or remove a candidate. Unknown limits stay unverified; unknown prices are null.- The Console creates standalone runs (`CreateRunDialog`, with judge model and context preview), relaunches and deletes runs, and creates and deletes matrix rows. Training setup carries its own judge selector and advisory warnings: selectors are tinted only for estimated overflows, undersized options stay selectable, and Start opens a short risk summary with Start anyway. Unverified and pending checks stay neutral. Nothing blocks launch or changes a model automatically.diff --git a/.agents/skills/backend-architecture/references/experiments.md b/.agents/skills/backend-architecture/references/experiments.mdindex 8e3d7f38..0b43b565 100644--- a/.agents/skills/backend-architecture/references/experiments.md+++ b/.agents/skills/backend-architecture/references/experiments.md@@ -12,8 +12,10 @@ An experiment is a saved flow of stages with its own conversation. The Console,## Runs- `runs.plan` resolves parameters and gives each stage an action: `reference` (an input stage), `decide` (a control stage), `reuse` (unchanged since the run named by `reuse_run`, by stage identity: kind, resolved settings and upstream identities) or `execute`. Its fingerprint pins `runs.start`: a changed plan is refused. A run's deadline is 24 hours unless set (1–168).+- A Model stage's candidate settings (`catalog.CANDIDATE`: system prompt, generation strategy, max steps, reasoning effort) ride on its model port: Evaluate passes them as the target's `params` and labels the run with the stage title; Qualify gives the system prompt to its participant as `instructions` and measures with purpose `final`.- A stage is one call to an MCP catalog tool, made in process for the run's starter (`stages.START`), then the records it started read through `get_job` until they end (`stages.FINISH`). Input and control stages decide at once. Variants, subflow and iterate run another experiment as child runs under their step. `ExperimentStep` holds each attempt's inputs, outputs, receipts and calls.- `runs.advance` (task `experiments.advance_run`, io queue) holds a cache lock, never a transaction across tool calls. It starts every stage whose inputs arrived, reads running ones, skips a branch a condition did not take, and ends the run `completed` or `unmet`. The `experiments.reconcile` beat task (control, 15 s) advances every active run not checked in 30 s: that is the polling interval and the recovery from a lost task.+- A stage's calls run as the `overmind experiment` client, credited to the experiment, never to a coding agent. A top-level run is one activity row from start to end.- `stop` marks the run `stopping`; the next advance cancels each running stage's work through the cancel tool of its record's kind (`stages.CANCEL`) and names on the step what it could not stop. `retry` adds an attempt for each failed or cancelled stage.## The experiment's agentdiff --git a/.agents/skills/data-workshop/SKILL.md b/.agents/skills/data-workshop/SKILL.mdindex 73a919e9..1a127056 100644--- a/.agents/skills/data-workshop/SKILL.md+++ b/.agents/skills/data-workshop/SKILL.md@@ -26,7 +26,9 @@ A customer's coding agent over MCP and the Console assistant own interpretation,- A dataset may start from a written `brief` with no source or capability. Intent is explicit (`train` with `train_format` `sft` or `decision`, or `eval`) and otherwise stays pending; when no capability is given, REST and MCP landing assign the top-ranked capability if its score is above zero; CLI transfers never infer one.- The first source attaches to the draft; later uploads append versions. Original bytes, extraction metadata and row evidence are retained.-- CLI uploads use `DatasetTransfer`: a project request key binds SHA-256, byte count and destination. Up to 100 ordered files and 2 GiB per transfer; file order is part of identity; one batch becomes one source cell or one version. Repeat the identical command after an interruption. `get_job(kind=dataset_transfer)` reads byte and publication state; `dataset_run` reports landing. An explicit `--json-rows-field` selects a top-level JSON row array and is recorded.+- CLI uploads use `DatasetTransfer`: a project request key binds SHA-256, byte count and destination. Up to 100 ordered files and 2 GiB per transfer; file order is part of identity; one batch becomes one source cell or one version.+- A new dataset from several files lands one dataset per set of column names (`land._group`: ignoring case and order; value types do not split a set), the first set in the named dataset and the others in datasets saved at publication (`imports._column_groups`). Every landed dataset's `source_spec.column_groups` lists them; Home adds each as its own Data stage. A split or an added batch needs one set of columns.+- XLSX (`spreadsheets.py`, openpyxl read-only) lands one dataset per sheet. The first nonempty row is the header; formulas stay source text, dates become ISO text, durations seconds; `_overmind_evidence` names the sheet, row and typed cells. 100 MiB per workbook and 512 MiB expanded; `.xlsx.gz` is refused. Repeat the identical command after an interruption. `get_job(kind=dataset_transfer)` reads byte and publication state; `dataset_run` reports landing. An explicit `--json-rows-field` selects a top-level JSON row array and is recorded.- Local upload, export and checkpoint download authenticate separately from MCP. Without an explicit or repository key they use the address-bound account connection at `$XDG_CONFIG_HOME/overmind/connection.toml` (mode `0600`); repository keys are endpoint-bound too. `overmind connection check --project-id PROJECT --json` verifies MCP and transfer access from the invoking environment; MCP connectivity alone is not readiness. Verify the installed CLI from the workspace and from a repository-free directory.- Confirmed permission denial uses the host's scoped approval. Missing credentials and transfer errors never authorize a browser fallback or an automatic sandbox-policy change.- Landing admission is one import per project, least-recent-project first, up to the observed landing capacity (backend-architecture `references/celery.md`). A started import whose worker or document parser stopped is retried by `admission.reconcile` under a new owner, up to `imports.MAX_ATTEMPTS` in total; other failures need explicit `resume_dataset_import`.@@ -75,6 +77,7 @@ External results arrive inline (at most 2,000 rows or 4 MiB) or as a project-sco- Preserve probability targets, option order, weights, duplicates, blank states and declared groups. Never argmax soft targets or invent distributions from means. Decision recipes publish a typed `decision` with tied maxima and supervision metadata.- The native agent declares target meaning per family from evidence in retained code and output metadata; unknown meaning stays unknown. Analytics keep declared supervision metadata.- Publication measures analytics on the full rows, bound to the exact fingerprint and rule version. They are advisory; `explore_dataset` backfills older cells, and reads never scan.+- Two leakage checks are warnings that never block publication: one JSON input field gives the observed label on 99% of the rows that share its value with at least four others, when those rows are half the family (`leakage.input_determines_label`; an input with more than 1,000 distinct values is not assessed), and an input's text holds a word of the row's own label and none of another's on 98% of at least 50 rows (`leakage.label_in_input`).- Raw tables have no inferred feature or target mapping; column names such as `label` or `score` never select columns.- Column contracts use `object` for a nested decision. A final step's `consumer` (`decision_train`, `decision_eval`, `chat_train`, `model_eval`) validates targets in preview and publication.- `use.check` verifies technical fit; `use.use` and `use.freeze` pin exact cells inside the consumer transaction.@@ -82,7 +85,7 @@ External results arrive inline (at most 2,000 rows or 4 MiB) or as a project-sco## Console canvas-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 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`). A terminal version's Checks section shows warning and error chips, then the findings, the passed and the not-checked checks (`notebook/cell-checks.tsx`); the active version's footer holds Intent and the Capability switch, ranked by `capability_rank`. 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/skills/mcp/SKILL.md b/.agents/skills/mcp/SKILL.mdindex ba9bf0f8..134326c0 100644--- a/.agents/skills/mcp/SKILL.md+++ b/.agents/skills/mcp/SKILL.md@@ -47,7 +47,12 @@ for one UUID run_id against the current SDK’s ten stages. These progress receistay out of the notification feed; the landing page renders their roadmap.The Console subscribes to `/api/activity/events/` for project-scoped snapshotsand invalidates asset queries without page reloads. Task status changes-update the original activity ID; transformation publication reuses that task record.+update the original activity ID. A dataset's preparation is one row (`task_kind`+`dataset_preparation`, `task_id` the dataset) from its first saved script or run to its+publication; previews add no row, a failed full run marks it failed, and the next change+after a publication opens the next row. A top-level experiment run is one row+(`experiment_run`) that `runs.start` writes and `runs._end` closes. The platform's own+clients (`overmind assistant`, `overmind experiment`, `overmind-transfer`) connect no agent.Only newly observed changes trigger the brief asset highlight. Reconnects reconcilethe durable snapshot; onboarding receipts also advance the stream revision.Reads and status polls never create action notifications or mark@@ -140,7 +145,6 @@ Follow the testing policy in AGENTS.md and the run-tests skill. A tool's happy p- [ ] `CONTRACT_VERSION`, the catalog, prompts, resources, the user-facing skills in `overmind/skills/` and the MCP tests change together. Regenerate the API client when the REST contract changed.Activity `sequence_key` identifies a project-scoped dataset preparation workflow:-creation, upload, import, saved transformations, previews and publication. Pipeline-runs resolve their dataset from the retained run record. Other edits and consumers+creation, upload, import and the preparation row. Other edits and consumersremain separate. The Console connects adjacent matching events without declaringwhole-task completion.diff --git a/.agents/skills/run-tests/SKILL.md b/.agents/skills/run-tests/SKILL.mdindex e4f5c549..3530ca75 100644--- a/.agents/skills/run-tests/SKILL.md+++ b/.agents/skills/run-tests/SKILL.md@@ -93,7 +93,9 @@ Tests run inside a rolled-back transaction by default. Call MCP tools with `mcp_## Gotchas- Backend tests need the compose `postgres` service on `localhost:5432`- (`TEST_POSTGRES_HOST`/`TEST_POSTGRES_PORT` override it).+ (`TEST_POSTGRES_HOST`/`TEST_POSTGRES_PORT` override it). A second checkout running+ suites at the same time sets its own `POSTGRES_DB` and, for journeys, its own+ `TEST_REDIS_URL` database: otherwise the runs share and drop one test database.- `uv add`/`uv remove` resync the venv WITHOUT dev/test groups — pytestvanishes. Restore with `uv sync --group dev --group test`.- Compose workers restart through watchmedo on `.py` changes under `overbae/`; API containers hot-reload. A non-Python edit under `overbae/` (for example `overbae/modal/models.json`) needs `docker compose restart <worker>`. Recreate a worker after a dependency change (AGENTS.md Gotchas).diff --git a/DESIGN.md b/DESIGN.mdindex e95f1827..24d7fc08 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -801,11 +801,12 @@ extraction commentary stay out of this cell summary; retained provenance remainsavailable through MCP.The footer has a 32px minimum height and wraps at narrow widths. First an **Active** indicator (`success` chip-with a tick). Then a contract chip that names the first failure (**Not a-train table**, **Does not match Research Agent**, **Intent pending**, else-**Fits**). Its hover card gives each contract as Needs / Columns / Found / Fix-and allows direct intent/capability changes where the dataset is not frozen. There-is no automatic repair action; transformations are authored by the native coding agent. Then the+with a tick). Then the **Intent** field, with a one-click **Use for …** per fitting use+while the intent can change, and the **Capability** field: the capability's name, or+**Does not match Research Agent** in the warning tone. Its menu switches to another+capability, ranked by how well the rows match it, or removes it. A terminal version's+**Checks** section header carries its warning and error chips, **+N** and **N not+checked**. There is no automatic repair action; transformations are authored by the native coding agent. Then theconsumers in the primary tint on the right: a train table offers **Train amodel**; an eval table offers **Use in a trainingjob** (the eval dataset that scores the job); each opens the wizard on itsdiff --git a/frontend/src/components/activity-links.tsx b/frontend/src/components/activity-links.tsxindex bc2f2d89..afa22f51 100644--- a/frontend/src/components/activity-links.tsx+++ b/frontend/src/components/activity-links.tsx@@ -41,6 +41,18 @@ export function ActivityAssetLink({const link = { ...props, id: asset.id };if (asset.kind === "training_job") return toTraining(link, asset.label);if (asset.kind === "dataset") return toDataset(link, asset.label);+ if (asset.kind === "experiment")+ return (+ <Link+ className={className}+ onClick={props.onClick}+ params={{ experimentId: asset.id }}+ search={{ projectId: props.projectId }}+ to="/experiments/$experimentId"+ >+ {asset.label}+ </Link>+ );if (asset.kind === "capability")return (<Linkdiff --git a/frontend/src/components/assistant/assistant-result.tsx b/frontend/src/components/assistant/assistant-result.tsxindex 83c7e11a..7b448c17 100644--- a/frontend/src/components/assistant/assistant-result.tsx+++ b/frontend/src/components/assistant/assistant-result.tsx@@ -23,9 +23,11 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltipimport { useTableSort } from "@/hooks/use-table-sort";import { sessionStore } from "@/lib/storage";import { cn } from "@/lib/utils";+import { EvalSetDraftReview } from "./eval-set-draft";import type {ChartNode,ChoicesNode,+ EvalSetDraftNode,Interaction,Presentation,QuestionNode,@@ -329,6 +331,18 @@ function ResultImage({ node }: { node: Extract<ResultNode, { type: "Image" }> }));}+function Draft({ node }: { node: EvalSetDraftNode }) {+ const { actions, call } = useResult();+ return (+ <EvalSetDraftReview+ answered={actions.answered.has(answerKey(call, node.id))}+ node={node}+ onAnswer={(text, values) => actions.onAnswer(text, { call, id: node.id, values })}+ sending={actions.sending}+ />+ );+}+function draftOf(key: string): Record<string, unknown> {try {return JSON.parse(sessionStore.get(key) ?? "{}");@@ -608,6 +622,8 @@ function Node({ node }: { node: ResultNode }): ReactNode {case "Question":case "Choices":return <Question node={node} />;+ case "EvalSetDraft":+ return <Draft node={node} />;default:return <p className="text-xs text-muted-foreground">This part cannot be displayed.</p>;}diff --git a/frontend/src/components/assistant/eval-set-draft.test.tsx b/frontend/src/components/assistant/eval-set-draft.test.tsxnew file mode 100644index 00000000..a40ea2ad--- /dev/null+++ b/frontend/src/components/assistant/eval-set-draft.test.tsx@@ -0,0 +1,71 @@+// @vitest-environment jsdom+// covers: console-logic+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";++import { NEW_CRITERION } from "@/components/evaluations/criteria-card";+import { draftChanges, EvalSetDraftReview } from "./eval-set-draft";+import type { EvalSetDraftNode } from "./types";++const created = vi.fn();+vi.mock("@/client", () => ({+ default: {+ evalSets: {+ evalSetsCreate: (request: unknown) => {+ created(request);+ return Promise.resolve({ id: "new-set", name: "Replies v2" });+ },+ },+ },+}));++afterEach(cleanup);++const tone = { ...NEW_CRITERION.llm, name: "Tone", source: "Is it polite?" };+const brief = { ...NEW_CRITERION.llm, name: "Brief", source: "Is it short?" };+const node: EvalSetDraftNode = {+ amends: { criteria: [tone], id: "old-set", name: "Replies" },+ capability: "capability",+ criteria: [{ ...tone, source: "Is it kind?" }, brief],+ description: "",+ id: "eval_set",+ name: "Replies v2",+ project: "project",+ type: "EvalSetDraft",+};++it("names what a draft adds, changes and removes by criterion", () => {+ expect(draftChanges([tone, brief], [{ ...tone, source: "Kind?" }])).toEqual({+ added: [],+ changed: ["Tone"],+ removed: ["Brief"],+ });+});++it("saves the reviewed draft as a new set and answers with its id", async () => {+ const onAnswer = vi.fn();+ render(+ <QueryClientProvider client={new QueryClient()}>+ <EvalSetDraftReview answered={false} node={node} onAnswer={onAnswer} sending={false} />+ </QueryClientProvider>+ );+ expect(screen.getByText("Added: Brief")).toBeTruthy();+ expect(screen.getByText("Changed: Tone")).toBeTruthy();++ fireEvent.click(screen.getByRole("button", { name: "Save eval set" }));++ await waitFor(() =>+ expect(onAnswer).toHaveBeenCalledWith("Saved eval set Replies v2.", {+ name: "Replies v2",+ saved: "new-set",+ })+ );+ expect(created).toHaveBeenCalledWith({+ evalSetRequest: expect.objectContaining({+ capability: "capability",+ name: "Replies v2",+ project: "project",+ }),+ });+});diff --git a/frontend/src/components/assistant/eval-set-draft.tsx b/frontend/src/components/assistant/eval-set-draft.tsxnew file mode 100644index 00000000..97c253e0--- /dev/null+++ b/frontend/src/components/assistant/eval-set-draft.tsx@@ -0,0 +1,134 @@+import { useState } from "react";++import { useMutation, useQueryClient } from "@tanstack/react-query";++import apiClient from "@/client";+import { CriteriaCard, type Criterion, saveBlocker } from "@/components/evaluations/criteria-card";+import { Button } from "@/components/ui/button";+import { errorMessage } from "@/lib/notify";+import type { EvalSet } from "@/openapi";+import type { EvalSetDraftNode } from "./types";++const LABELS = { added: "Added", changed: "Changed", removed: "Removed" };++/** What a draft changes in the set it amends, by criterion name. */+export function draftChanges(before: Criterion[], after: Criterion[]) {+ const old = new Map(before.map((criterion) => [criterion.name, criterion]));+ const names = new Set(after.map((criterion) => criterion.name));+ return {+ added: after.filter((c) => !old.has(c.name)).map((c) => c.name),+ changed: after+ .filter((c) => old.has(c.name) && JSON.stringify(old.get(c.name)) !== JSON.stringify(c))+ .map((c) => c.name),+ removed: before.filter((c) => !names.has(c.name)).map((c) => c.name),+ };+}++function Changes({+ before,+ after,+ name,+}: {+ before: Criterion[];+ after: Criterion[];+ name: string;+}) {+ const changes = draftChanges(before, after);+ const lines = (["added", "changed", "removed"] as const).filter((kind) => changes[kind].length);+ return (+ <div className="space-y-0.5 text-xs text-muted-foreground">+ <p>Changes to {name}</p>+ {lines.length ? (+ lines.map((kind) => (+ <p key={kind}>+ {LABELS[kind]}: {changes[kind].join(", ")}+ </p>+ ))+ ) : (+ <p>No criterion changed</p>+ )}+ </div>+ );+}++/** The agent's drafted eval set: the person edits it, then saves it as a new set or rejects+ * it. Either answer reaches the agent as the person's reply. */+export function EvalSetDraftReview({+ answered,+ node,+ onAnswer,+ sending,+}: {+ answered: boolean;+ node: EvalSetDraftNode;+ onAnswer: (text: string, values: Record<string, unknown>) => void;+ sending: boolean;+}) {+ const queryClient = useQueryClient();+ const [name, setName] = useState(node.name);+ const [criteria, setCriteria] = useState<Criterion[]>(node.criteria);+ // A saved set whose reply did not send is sent again, never saved twice.+ const [saved, setSaved] = useState<EvalSet | null>(null);+ const reply = (set: EvalSet) =>+ onAnswer(`Saved eval set ${set.name}.`, { name: set.name, saved: set.id });+ const save = useMutation({+ mutationFn: () =>+ apiClient.evalSets.evalSetsCreate({+ evalSetRequest: {+ capability: node.capability,+ criteria: criteria.map((c) => ({ ...c, name: c.name.trim() })),+ description: node.description,+ name: name.trim(),+ project: node.project,+ },+ }),+ onSuccess: async (set) => {+ setSaved(set);+ reply(set);+ await queryClient.invalidateQueries({ queryKey: ["eval-sets"] });+ },+ });+ const editable = !answered && !saved;+ const blocker = saveBlocker(name, criteria);+ const busy = answered || sending || save.isPending;+ return (+ <div className="space-y-3">+ {node.amends && (+ <Changes after={criteria} before={node.amends.criteria} name={node.amends.name} />+ )}+ <CriteriaCard+ criteria={criteria}+ description={node.description || undefined}+ name={name}+ onChange={editable ? setCriteria : undefined}+ onNameChange={editable ? setName : undefined}+ />+ <div className="flex items-center gap-2">+ <p aria-live="polite" className="mr-auto text-xs text-muted-foreground">+ {answered+ ? "Response sent"+ : save.error+ ? errorMessage(save.error, "Could not save the eval set.")+ : saved+ ? `Saved ${saved.name}`+ : blocker}+ </p>+ <Button+ disabled={busy || !!saved}+ onClick={() => onAnswer("Rejected the drafted eval set.", { rejected: true })}+ size="xs"+ variant="secondary"+ >+ Reject+ </Button>+ <Button+ disabled={busy || (!saved && !!blocker)}+ onClick={() => (saved ? reply(saved) : save.mutate())}+ size="xs"+ >+ {save.isPending ? "Saving…" : "Save eval set"}+ </Button>+ </div>+ </div>+ );+}diff --git a/frontend/src/components/assistant/types.ts b/frontend/src/components/assistant/types.tsindex d2f67946..12489d56 100644--- a/frontend/src/components/assistant/types.ts+++ b/frontend/src/components/assistant/types.ts@@ -1,3 +1,5 @@+import type { Criterion } from "@/components/evaluations/criteria-card";+export interface ToolCall {id: string;name: string;@@ -103,6 +105,18 @@ export type ChartNode = {y_label: string;};export type TableNode = { type: "Table"; title: string; data: string; columns: string[] };+/** Built by the `draft_eval_set` tool; saving it is the person's own request. */+export type EvalSetDraftNode = {+ type: "EvalSetDraft";+ id: string;+ project: string;+ name: string;+ description: string;+ criteria: Criterion[];+ capability: string | null;+ /** The set this draft changes; saving makes a new set beside it. */+ amends: { id: string; name: string; criteria: Criterion[] } | null;+};/** The components the backend validates in `services/assistant/presentation.py`. */export type ResultNode =@@ -111,6 +125,7 @@ export type ResultNode =| ChartNode| ChoicesNode| { type: "Code"; code: string; language: string }+ | EvalSetDraftNode| { type: "Details"; title: string; children: ResultNode[] }| { type: "Heading"; text: string }| { type: "Image"; title: string; image: string }diff --git a/frontend/src/components/datasets/attachment.test.tsx b/frontend/src/components/datasets/attachment.test.tsxnew file mode 100644index 00000000..5036b09e--- /dev/null+++ b/frontend/src/components/datasets/attachment.test.tsx@@ -0,0 +1,58 @@+// @vitest-environment jsdom+// covers: console-logic+import { cleanup, render } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";++import type { DatasetUpload } from "@/hooks/use-uploads";+import { Attachment } from "./attachment";++const pdf = vi.hoisted(() => ({ destroy: vi.fn(), started: vi.fn() }));++vi.mock("pdfjs-dist", () => ({+ GlobalWorkerOptions: {},+ getDocument: () => {+ pdf.started();+ // A document still parsing when the tile goes away.+ return { destroy: pdf.destroy, promise: new Promise(() => {}) };+ },+}));+vi.mock("pdfjs-dist/build/pdf.worker.min.mjs?url", () => ({ default: "worker.js" }));++afterEach(cleanup);++const upload = (name: string, status: DatasetUpload["status"]) =>+ ({+ file: Object.assign(new File(["%PDF"], name), {+ arrayBuffer: () => Promise.resolve(new ArrayBuffer(4)),+ }),+ id: name,+ percent: 40,+ status,+ }) as DatasetUpload;++const tile = (entry: DatasetUpload) =>+ render(+ <ul>+ <Attachment compact disabled={false} entry={entry} onRemove={vi.fn()} onRetry={vi.fn()} />+ </ul>+ );++it("draws the upload state in the tile until the file is ready", () => {+ const spinning = (status: DatasetUpload["status"]) => {+ const { container } = tile(upload("rows.csv", status));+ const found = !!container.querySelector('button [data-slot="spinner"]');+ cleanup();+ return found;+ };+ expect(spinning("uploading")).toBe(true);+ expect(spinning("counting")).toBe(true);+ expect(spinning("ready")).toBe(false);+});++it("stops drawing a PDF preview when the tile goes away", async () => {+ const { unmount } = tile(upload("report.pdf", "ready"));+ await vi.waitFor(() => expect(pdf.started).toHaveBeenCalled());+ expect(pdf.destroy).not.toHaveBeenCalled();+ unmount();+ expect(pdf.destroy).toHaveBeenCalled();+});diff --git a/frontend/src/components/datasets/attachment.tsx b/frontend/src/components/datasets/attachment.tsxindex f6af3dba..2ff4f2cb 100644--- a/frontend/src/components/datasets/attachment.tsx+++ b/frontend/src/components/datasets/attachment.tsx@@ -1,5 +1,7 @@import { useEffect, useId, useState } from "react";+import { motion, useReducedMotion } from "motion/react";+import { FileTypeIcon, fileTypeAppearance } from "@/components/file-type-icon";import { Button } from "@/components/ui/button";import { Icon } from "@/components/ui/icons";@@ -36,10 +38,12 @@ export function Attachment({const isImage = /\.(png|jpe?g|webp)$/i.test(entry.file.name);const [preview, setPreview] = useState<string | null>(null);const isPdf = /\.pdf$/i.test(entry.file.name);+ const reduce = useReducedMotion();useEffect(() => {if (!isImage && !isPdf) return;let url: string | undefined;let gone = false;+ const drawing = new AbortController();const show = (made: string) => {if (gone) URL.revokeObjectURL(made);else {@@ -49,9 +53,10 @@ export function Attachment({};if (isImage) show(URL.createObjectURL(entry.file));// A PDF that cannot be drawn keeps the file icon.- else void pdfThumbnail(entry.file).then(show, () => undefined);+ else void pdfThumbnail(entry.file, drawing.signal).then(show, () => undefined);return () => {gone = true;+ drawing.abort();if (url) URL.revokeObjectURL(url);};}, [entry.file, isImage, isPdf]);@@ -66,7 +71,8 @@ export function Attachment({const appearance = fileTypeAppearance(entry.file.name);const type = entry.file.name.replace(/\.gz$/i, "").split(".").at(-1)?.toUpperCase();return (- <li+ <motion.li+ animate={{ opacity: 1, x: 0 }}className={cn("flex h-8 min-w-0 max-w-full items-center rounded-sm bg-control pr-1 sm:max-w-72",detailed && "h-auto w-full gap-2 border border-border bg-muted py-1.5 sm:max-w-none",@@ -74,6 +80,10 @@ export function Attachment({"assistant-attachment relative h-9 w-44 max-w-44 shrink-0 rounded-md border border-border bg-card pr-1 sm:max-w-44",entry.status === "error" && "border-destructive/40 bg-destructive/10 text-destructive")}+ exit={{ opacity: 0, scale: reduce ? 1 : 0.92 }}+ initial={{ opacity: 0, x: reduce ? 0 : 10 }}+ layout={!reduce}+ transition={{ duration: reduce ? 0 : 0.2, ease: [0.4, 0, 0.2, 1] }}><Popover><PopoverTrigger@@ -97,9 +107,7 @@ export function Attachment({])}>- {compact && !preview ? (- <appearance.icon className="size-3.5" />- ) : working ? (+ {working ? (<Spinner className="size-3.5" />) : entry.status === "error" ? (<Icon.warning className="size-3.5 text-destructive" />@@ -116,6 +124,8 @@ export function Attachment({onError={() => setPreview(null)}src={preview}/>+ ) : compact ? (+ <appearance.icon className="size-3.5" />) : (<FileTypeIcon className="size-3.5" filename={entry.file.name} />)}@@ -222,6 +232,6 @@ export function Attachment({><Icon.close /></Button>- </li>+ </motion.li>);}diff --git a/frontend/src/components/datasets/dataset-file-upload.tsx b/frontend/src/components/datasets/dataset-file-upload.tsxindex 517f727f..1e4f67fe 100644--- a/frontend/src/components/datasets/dataset-file-upload.tsx+++ b/frontend/src/components/datasets/dataset-file-upload.tsx@@ -1,5 +1,7 @@import { useRef, useState } from "react";+import { AnimatePresence } from "motion/react";+import { Attachment } from "@/components/datasets/attachment";import { Button } from "@/components/ui/button";import { Icon } from "@/components/ui/icons";@@ -50,16 +52,18 @@ export function DatasetFileUpload({>{upload.files.length > 0 && (<ul aria-label="Selected files" className="flex flex-wrap gap-2">- {upload.files.map((entry) => (- <Attachment- detailed- disabled={busy}- entry={entry}- key={entry.id}- onRemove={() => upload.remove(entry.id)}- onRetry={() => upload.retry(entry)}- />- ))}+ <AnimatePresence initial={false}>+ {upload.files.map((entry) => (+ <Attachment+ detailed+ disabled={busy}+ entry={entry}+ key={entry.id}+ onRemove={() => upload.remove(entry.id)}+ onRetry={() => upload.retry(entry)}+ />+ ))}+ </AnimatePresence></ul>)}<div className="flex flex-wrap items-center justify-between gap-3">@@ -72,7 +76,7 @@ export function DatasetFileUpload({</p></div><input- accept=".csv,.tsv,.json,.jsonl,.ndjson,.parquet,.gz,.pdf,.docx,.md,.txt,.png,.jpg,.jpeg,.webp"+ accept=".csv,.tsv,.json,.jsonl,.ndjson,.parquet,.xlsx,.gz,.pdf,.docx,.md,.txt,.png,.jpg,.jpeg,.webp"aria-label="Choose dataset files"className="hidden"disabled={busy}diff --git a/frontend/src/components/datasets/new-dataset-dialog.test.tsx b/frontend/src/components/datasets/new-dataset-dialog.test.tsxindex 9a7bc637..3f382abb 100644--- a/frontend/src/components/datasets/new-dataset-dialog.test.tsx+++ b/frontend/src/components/datasets/new-dataset-dialog.test.tsx@@ -125,7 +125,8 @@ describe("dataset file dialog", () => {expect(within(list).getByText("2 B")).toBeTruthy();fireEvent.change(screen.getByLabelText("Dataset name"), { target: { value: "Support data" } });fireEvent.click(screen.getByRole("button", { name: "Remove first.csv" }));- expect(within(list).queryByText("first.csv")).toBeNull();+ // The tile leaves through its exit animation.+ await waitFor(() => expect(within(list).queryByText("first.csv")).toBeNull());expect((screen.getByLabelText("Dataset name") as HTMLInputElement).value).toBe("Support data");choose("Capability", "Support");choose("Intent", "Eval");diff --git a/frontend/src/components/datasets/notebook/cell-checks.test.tsx b/frontend/src/components/datasets/notebook/cell-checks.test.tsxnew file mode 100644index 00000000..16cb17ea--- /dev/null+++ b/frontend/src/components/datasets/notebook/cell-checks.test.tsx@@ -0,0 +1,91 @@+// @vitest-environment jsdom+// covers: measured-facts+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";++import type { Cell, DatasetAnalytics } from "@/openapi";+import { CapabilityField, CellChecks, CheckChips } from "./cell-checks";++afterEach(cleanup);++const check = (id: string, status: string, title = id) => ({+ id,+ metrics: id === "targets.class_balance" ? { families: ["fraud"] } : {},+ status,+ summary: `${title} summary`,+ title,+});++const report = {+ checks: [+ check("targets.class_balance", "warning", "Class imbalance"),+ check("leakage.label_in_input", "warning", "Label named in the input"),+ check("targets.validity", "error", "Target validity"),+ check("inputs.missing", "pass", "Missing input values"),+ check("leakage.cross_split", "not_checked", "Duplicates and split leakage"),+ check("inputs.availability", "not_checked", "Feature availability"),+ ],+ families: [+ {+ counts: [1000, 1],+ id: "fraud",+ labels: ["No", "Yes"],+ majorityBaseline: 1000 / 1001,+ question: "Fraud?",+ rows: 1001,+ },+ ],+ fingerprint: "abc",+ rowsScanned: 1001,+ status: "completed",+ version: 3,+} as unknown as DatasetAnalytics;++it("shows errors first, folds the rest into a count and counts what was not checked", () => {+ render(<CheckChips report={report} />);+ const chips = screen.getAllByText(/Target validity|Class imbalance|\+1|not checked/);+ expect(chips.map((chip) => chip.textContent)).toEqual([+ "Target validity",+ "Class imbalance",+ "+1",+ "2 not checked",+ ]);+});++it("names what always answering the majority label scores, and lists the other checks", () => {+ render(<CellChecks report={report} />);+ expect(screen.getByText("Accuracy alone is misleading here")).toBeTruthy();+ expect(screen.getByText(/scores 99\.90% accuracy and misses all 1 “Yes” row\./)).toBeTruthy();+ expect(screen.getByText("Label named in the input summary")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: /2 not checked/ }));+ expect(screen.getByText("Feature availability summary")).toBeTruthy();+ expect(screen.getByRole("button", { name: /1 passed/ }).getAttribute("aria-expanded")).toBe(+ "false"+ );+});++it("offers the other capabilities in rank order, and removal", () => {+ const onChange = vi.fn();+ render(+ <CapabilityField+ cell={{ capabilityReport: { ok: false, reason: "No tool calls match" } } as unknown as Cell}+ current="triage"+ name="Triage"+ onChange={onChange}+ ranked={[+ { capability_id: "refunds", name: "Refunds", score: 0.9 },+ { capability_id: "triage", name: "Triage", score: 0.4 },+ { capability_id: "billing", name: "Billing", score: 0.1 },+ ]}+ />+ );+ expect(screen.getByText("Does not match Triage")).toBeTruthy();+ fireEvent.pointerDown(screen.getByRole("button", { name: "Change capability" }), {+ button: 0,+ ctrlKey: false,+ });+ const items = screen.getAllByRole("menuitem").map((item) => item.textContent);+ expect(items).toEqual(["Refunds90%", "Billing10%", "Remove capability"]);+ fireEvent.click(screen.getByRole("menuitem", { name: "Remove capability" }));+ expect(onChange).toHaveBeenCalledWith(null);+});diff --git a/frontend/src/components/datasets/notebook/cell-checks.tsx b/frontend/src/components/datasets/notebook/cell-checks.tsxnew file mode 100644index 00000000..31237c53--- /dev/null+++ b/frontend/src/components/datasets/notebook/cell-checks.tsx@@ -0,0 +1,230 @@+import { useState } from "react";++import { Badge } from "@/components/ui/badge";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Icon } from "@/components/ui/icons";+import { cn } from "@/lib/utils";+import type { Cell, DatasetAnalytics, DatasetAnalyticsCheck } from "@/openapi";+import { Field } from "./field";++const alerting = (check: DatasetAnalyticsCheck) =>+ check.status === "error" || check.status === "warning";++function alertsOf(report: DatasetAnalytics) {+ return report.checks+ .filter(alerting)+ .sort((a, b) => Number(b.status === "error") - Number(a.status === "error"));+}++/** The version's warnings and errors, then how many checks did not run. */+export function CheckChips({ report }: { report: DatasetAnalytics }) {+ const alerts = alertsOf(report);+ const unchecked = report.checks.filter((check) => check.status === "not_checked").length;+ return (+ <span className="flex min-w-0 flex-wrap items-center gap-1">+ {alerts.slice(0, 2).map((check) => (+ <Badge+ key={check.id}+ size="chip"+ title={check.summary}+ variant={check.status === "error" ? "error" : "warning"}+ >+ {check.title}+ </Badge>+ ))}+ {alerts.length > 2 && (+ <Badge size="chip" variant="warning">+ +{alerts.length - 2}+ </Badge>+ )}+ {unchecked > 0 && (+ <Badge size="chip" variant="neutral">+ {unchecked} not checked+ </Badge>+ )}+ </span>+ );+}++/** For each imbalanced question: what always answering its majority label scores. */+function Imbalance({ check, report }: { check: DatasetAnalyticsCheck; report: DatasetAnalytics }) {+ const ids = (check.metrics as { families?: string[] } | null)?.families ?? [];+ const families = report.families.filter(+ (family) =>+ ids.includes(family.id) &&+ family.majorityBaseline != null &&+ family.counts?.length === family.labels.length+ );+ return families.map((family) => {+ const counts = family.counts!;+ const majority = counts.indexOf(Math.max(...counts));+ const minority = counts.indexOf(Math.min(...counts));+ return (+ <p className="leading-relaxed" key={family.id}>+ <span className="text-foreground">{family.question}</span> Predicting “+ {family.labels[majority]}” for every row scores{" "}+ {(family.majorityBaseline! * 100).toFixed(2)}% accuracy and misses all{" "}+ {counts[minority].toLocaleString()} “{family.labels[minority]}”{" "}+ {counts[minority] === 1 ? "row" : "rows"}.+ </p>+ );+ });+}++function CheckList({ title, checks }: { title: string; checks: DatasetAnalyticsCheck[] }) {+ const [open, setOpen] = useState(false);+ if (!checks.length) return null;+ return (+ <section>+ <button+ aria-expanded={open}+ className="flex items-center gap-1 text-muted-foreground hover:text-foreground"+ onClick={() => setOpen(!open)}+ type="button"+ >+ <Icon.chevronRight className={cn("size-3", open && "rotate-90")} />+ {checks.length} {title}+ </button>+ {open && (+ <dl className="mt-1 divide-y divide-border/60 border-y border-border/60">+ {checks.map((check) => (+ <div className="grid gap-1 py-1.5 sm:grid-cols-[11rem_minmax(0,1fr)]" key={check.id}>+ <dt className="text-foreground">{check.title}</dt>+ <dd className="break-words text-muted-foreground">{check.summary}</dd>+ </div>+ ))}+ </dl>+ )}+ </section>+ );+}++/** Every check measured on the version: findings first, then what passed and what did not run. */+export function CellChecks({ report }: { report: DatasetAnalytics }) {+ const alerts = alertsOf(report);+ return (+ <div aria-label="Checks" className="nodrag nowheel space-y-3 px-3 pb-3 text-xs">+ {alerts.map((check) => (+ <section className="space-y-1" key={check.id}>+ <h3+ className={cn(+ "flex items-center gap-1.5",+ check.status === "error" ? "text-destructive" : "text-warning"+ )}+ >+ <Icon.warning className="size-3 shrink-0" />+ {check.id === "targets.class_balance"+ ? "Accuracy alone is misleading here"+ : check.title}+ </h3>+ {check.id === "targets.class_balance" ? (+ <Imbalance check={check} report={report} />+ ) : (+ <p className="break-words leading-relaxed">{check.summary}</p>+ )}+ </section>+ ))}+ <CheckList checks={report.checks.filter((check) => check.status === "pass")} title="passed" />+ <CheckList+ checks={report.checks.filter((check) => check.status === "not_checked")}+ title="not checked"+ />+ <p className="text-muted-foreground" title={report.fingerprint}>+ {report.rowsScanned?.toLocaleString()} rows scanned · checks v{report.version}+ </p>+ </div>+ );+}++export interface CapabilityChoice {+ capability_id: string;+ name: string;+ score: number;+}++/** The dataset's capability, a warning when the version's rows do not match it, and a+ * switch to another capability, ranked by how well the rows match it. */+export function CapabilityField({+ cell,+ current,+ name,+ ranked,+ onChange,+}: {+ cell: Cell;+ current: string | null;+ name: string;+ ranked: CapabilityChoice[];+ /** Absent while the dataset is busy or frozen. */+ onChange?: (capability: string | null) => void;+}) {+ const report = (cell.capabilityReport ?? {}) as { ok?: boolean; reason?: string };+ const mismatch = !!current && report.ok === false;+ const others = ranked.filter((choice) => choice.capability_id !== current);+ const value = (+ <>+ {mismatch && <Icon.warning className="size-3 shrink-0" />}+ <span className="truncate">+ {current ? (mismatch ? `Does not match ${name}` : name) : "None"}+ </span>+ </>+ );+ if (!onChange || (!current && !others.length))+ return (+ <Field+ label="Capability"+ title={mismatch ? report.reason : undefined}+ tone={mismatch ? "text-warning" : current ? "text-foreground" : "text-muted-foreground"}+ >+ {value}+ </Field>+ );+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ aria-label="Change capability"+ className="nodrag inline-flex rounded-sm focus-visible:outline focus-visible:outline-ring"+ title={mismatch ? report.reason : undefined}+ type="button"+ >+ <Field+ label="Capability"+ tone={mismatch ? "text-warning" : current ? "text-foreground" : "text-muted-foreground"}+ >+ {value}+ <Icon.chevronDown className="size-3 shrink-0 text-muted-foreground" />+ </Field>+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-64">+ {others.map((choice) => (+ <DropdownMenuItem+ key={choice.capability_id}+ onSelect={() => onChange(choice.capability_id)}+ >+ <span className="min-w-0 flex-1 truncate">{choice.name}</span>+ <span className="font-mono text-muted-foreground tabular-nums">+ {Math.round(choice.score * 100)}%+ </span>+ </DropdownMenuItem>+ ))}+ {current && (+ <>+ {others.length > 0 && <DropdownMenuSeparator />}+ <DropdownMenuItem onSelect={() => onChange(null)}>+ <Icon.capabilityOff className="size-4" />+ Remove capability+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/frontend/src/components/datasets/notebook/cell.tsx b/frontend/src/components/datasets/notebook/cell.tsxindex 06a74d20..1827b343 100644--- a/frontend/src/components/datasets/notebook/cell.tsx+++ b/frontend/src/components/datasets/notebook/cell.tsx@@ -3,6 +3,12 @@ import { type ReactNode, useEffect, useState } from "react";import { Link } from "@tanstack/react-router";import { Handle, Position, useNodeConnections } from "@xyflow/react";+import {+ type CapabilityChoice,+ CapabilityField,+ CellChecks,+ CheckChips,+} from "@/components/datasets/notebook/cell-checks";import { CellLabels } from "@/components/datasets/notebook/cell-labels";import { CellScript } from "@/components/datasets/notebook/cell-script";import { Field } from "@/components/datasets/notebook/field";@@ -30,6 +36,7 @@ export interface CellActions {onUse: (purpose: UsePurpose) => void;onExport: (fmt: "jsonl" | "csv") => void;onIntent: (intent: "train" | "eval", trainFormat?: "sft" | "decision") => void;+ onCapability: (capability: string | null) => void;}function ExportDialog({@@ -87,11 +94,13 @@ function ExportDialog({function SectionHeader({label,meta,+ badges,open,onToggle,}: {label: string;meta?: string;+ badges?: ReactNode;open: boolean;onToggle: () => void;}) {@@ -109,6 +118,7 @@ function SectionHeader({className={cn("size-3 transition-transform duration-150", open && "rotate-90")}/><span className="pixel-label whitespace-nowrap">{label}</span>+ {badges}<span className="flex-1" />{meta && <span className="truncate font-mono tabular-nums">{meta}</span>}</button>@@ -214,24 +224,14 @@ function IntentFields({);}-/** Shown only when the rows do not match the bound capability. */-function CapabilityMismatch({ cell, name }: { cell: Cell; name: string }) {- const report = (cell.capabilityReport ?? {}) as { ok?: boolean; reason?: string };- if (!name || report.ok !== false) return null;- return (- <Field label="Capability" title={report.reason} tone="text-warning">- <Icon.warning className="size-3 shrink-0" />- <span className="truncate">Does not match {name}</span>- </Field>- );-}-export function NotebookCell({datasetId,cell,intent,trainFormat,capabilityName,+ capabilityId,+ capabilityRank,active,member,intentLocked,@@ -248,6 +248,9 @@ export function NotebookCell({intent: string;trainFormat: string;capabilityName: string;+ capabilityId: string | null;+ /** Capabilities ranked by how well the dataset's rows match them. */+ capabilityRank: CapabilityChoice[];active: boolean;/** The cell's part of a training split, named for the reader. *//** A cell of another dataset, such as a partition member: its name links there. */@@ -273,6 +276,7 @@ export function NotebookCell({// Intermediate versions start folded so the end of the flow stays in view.const [tableChoice, setTableOpen] = useState<boolean | null>(null);const [labelsOpen, setLabelsOpen] = useState(false);+ const [checksOpen, setChecksOpen] = useState(false);const terminal = outgoing.length === 0 || active;const tableOpen = tableChoice ?? (terminal || selected);// A table that selection opened stays open, with its filters, when selection moves on.@@ -462,6 +466,17 @@ export function NotebookCell({{labelsOpen && <CellLabels cell={cell} />}</div>)}+ {terminal && cell.analytics?.status === "completed" && (+ <div className="border-t border-border/70">+ <SectionHeader+ badges={<CheckChips report={cell.analytics} />}+ label="Checks"+ onToggle={() => setChecksOpen((open) => !open)}+ open={checksOpen}+ />+ {checksOpen && <CellChecks report={cell.analytics} />}+ </div>+ )}{active && (<footer className="flex min-h-10 flex-wrap items-center gap-2 border-t border-border/70 px-2.5 py-2"><IntentFields@@ -471,7 +486,13 @@ export function NotebookCell({onIntent={editable && !intentLocked ? actions.onIntent : undefined}trainFormat={trainFormat}/>- <CapabilityMismatch cell={cell} name={capabilityName} />+ <CapabilityField+ cell={cell}+ current={capabilityId}+ name={capabilityName}+ onChange={editable && !intentLocked ? actions.onCapability : undefined}+ ranked={capabilityRank}+ />{splitReport}<span className="flex-1" />{intent === "train" && (diff --git a/frontend/src/components/datasets/notebook/notebook-page.tsx b/frontend/src/components/datasets/notebook/notebook-page.tsxindex 431a9e78..505ff311 100644--- a/frontend/src/components/datasets/notebook/notebook-page.tsx+++ b/frontend/src/components/datasets/notebook/notebook-page.tsx@@ -224,6 +224,7 @@ export function DatasetNotebook({<div><NotebookCellactions={{+ onCapability: guard((capability: string | null) => patch.mutate({ capability })),onExport: (fmt) =>void downloadExport(owner,@@ -237,7 +238,9 @@ export function DatasetNotebook({onUse: guard(handOff),}}active={cell.id === active?.id}+ capabilityId={dataset.capability ?? null}capabilityName={dataset.capabilityName ?? ""}+ capabilityRank={Array.isArray(dataset.capabilityRank) ? dataset.capabilityRank : []}cell={cell}datasetId={owner}editable={editable && local}diff --git a/frontend/src/components/datasets/notebook/source.tsx b/frontend/src/components/datasets/notebook/source.tsxindex ee120bcb..bf333f13 100644--- a/frontend/src/components/datasets/notebook/source.tsx+++ b/frontend/src/components/datasets/notebook/source.tsx@@ -1,5 +1,7 @@import { type ReactNode, useRef, useState } from "react";+import { AnimatePresence } from "motion/react";+import apiClient from "@/client";import { Attachment } from "@/components/datasets/attachment";import { SOURCE_KIND_LABEL } from "@/components/datasets/badges";@@ -195,19 +197,21 @@ export function SourceLanding({</p>{upload.files.length > 0 && (<ul aria-label="Selected files" className="flex flex-wrap gap-2">- {upload.files.map((file) => (- <Attachment- disabled={attach.isPending}- entry={file}- key={file.id}- onRemove={() => upload.remove(file.id)}- onRetry={() => upload.retry(file)}- />- ))}+ <AnimatePresence initial={false}>+ {upload.files.map((file) => (+ <Attachment+ disabled={attach.isPending}+ entry={file}+ key={file.id}+ onRemove={() => upload.remove(file.id)}+ onRetry={() => upload.retry(file)}+ />+ ))}+ </AnimatePresence></ul>)}<input- accept=".csv,.tsv,.json,.jsonl,.ndjson,.parquet,.gz,.pdf,.docx,.md,.txt,.png,.jpg,.jpeg,.webp"+ accept=".csv,.tsv,.json,.jsonl,.ndjson,.parquet,.xlsx,.gz,.pdf,.docx,.md,.txt,.png,.jpg,.jpeg,.webp"aria-label="Attach source files"className="hidden"multiplediff --git a/frontend/src/components/evaluations/criteria-card.test.tsx b/frontend/src/components/evaluations/criteria-card.test.tsxnew file mode 100644index 00000000..3e8818b7--- /dev/null+++ b/frontend/src/components/evaluations/criteria-card.test.tsx@@ -0,0 +1,55 @@+// @vitest-environment jsdom+// covers: console-logic+import { useState } from "react";++import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";++import { CriteriaCard, type Criterion, NEW_CRITERION } from "./criteria-card";++vi.mock("@/client", () => ({+ default: { evalSets: { evalSetsValidatePythonCreate: () => new Promise(() => {}) } },+}));++afterEach(cleanup);++const tone: Criterion = { ...NEW_CRITERION.llm, name: "Tone", source: "Is it polite?" };+const brief: Criterion = { ...NEW_CRITERION.llm, name: "Brief", source: "Is it short?" };++function Editor() {+ const [criteria, setCriteria] = useState([tone, brief]);+ return (+ <QueryClientProvider client={new QueryClient()}>+ <CriteriaCard criteria={criteria} name="Replies" onChange={setCriteria} />+ </QueryClientProvider>+ );+}++const names = () =>+ [...document.querySelectorAll("[data-row]")].map(+ (row) => row.querySelector("span span")?.textContent+ );++it("undoes a removal in place and hands focus to the next control", () => {+ render(<Editor />);+ fireEvent.click(screen.getByText("Tone"));+ expect(document.activeElement).toBe(screen.getByLabelText("Criterion name"));++ fireEvent.click(screen.getByRole("button", { name: "Preview" }));+ expect(screen.getByText(/Yes: 1\s+No: 0/)).toBeTruthy();++ fireEvent.click(screen.getByRole("button", { name: "Remove" }));+ expect(names()).toEqual(["Brief"]);+ const undo = screen.getByRole("button", { name: "Undo" });+ expect(document.activeElement).toBe(undo);++ fireEvent.click(undo);+ expect(screen.getByLabelText<HTMLInputElement>("Criterion name").value).toBe("Tone");+ fireEvent.click(screen.getByRole("button", { name: "Done" }));+ expect(names()).toEqual(["Tone", "Brief"]);+ expect(document.activeElement?.textContent).toContain("Tone");++ fireEvent.click(screen.getByRole("button", { name: "Python criterion" }));+ expect(document.activeElement).toBe(screen.getByLabelText("Criterion name"));+});diff --git a/frontend/src/components/evaluations/criteria-card.tsx b/frontend/src/components/evaluations/criteria-card.tsxindex 5ba6d9c9..80526bb4 100644--- a/frontend/src/components/evaluations/criteria-card.tsx+++ b/frontend/src/components/evaluations/criteria-card.tsx@@ -1,6 +1,7 @@-import { type ReactNode, useState } from "react";+import { type ReactNode, useEffect, useRef, useState } from "react";import { useQuery } from "@tanstack/react-query";+import { AnimatePresence, motion, useReducedMotion } from "motion/react";import apiClient from "@/client";import { Button } from "@/components/ui/button";@@ -235,6 +236,21 @@ function CriterionBody({);}+// Criteria carry no ids: a row keeps its key across moves, removals and an undo.+let lastKey = 0;+const newKey = () => `criterion-${++lastKey}`;++function Preview({ criterion }: { criterion: Criterion }) {+ return (+ <pre className="whitespace-pre-wrap rounded-sm bg-muted p-2 text-xs leading-relaxed">+ {[+ criterion.source,+ ...(criterion.options ?? []).map((option) => `${option.label}: ${option.score}`),+ ].join("\n")}+ </pre>+ );+}+/** A benchmark's criteria as an accordion; editable when `onChange` is given. */export function CriteriaCard({actions,@@ -255,21 +271,72 @@ export function CriteriaCard({onNameChange?: (name: string) => void;summary?: RunSummary;}) {+ const reduce = useReducedMotion();+ const root = useRef<HTMLDivElement>(null);+ // A change that moves focus names its target; the render after it focuses it.+ const focusNext = useRef<string | null>(null);+ useEffect(() => {+ if (!focusNext.current) return;+ root.current?.querySelector<HTMLElement>(focusNext.current)?.focus({ preventScroll: true });+ focusNext.current = null;+ });const [open, setOpen] = useState<number | null>(null);+ const [preview, setPreview] = useState(false);+ const [removed, setRemoved] = useState<{+ criterion: Criterion;+ index: number;+ key: string;+ } | null>(null);+ const [keys, setKeys] = useState(() => criteria.map(newKey));+ // A parent that replaces the criteria (a dialog that loads a set) starts the keys again.+ if (keys.length !== criteria.length) setKeys(criteria.map(newKey));++ const expand = (index: number) => {+ setOpen(index);+ setPreview(false);+ if (onChange) focusNext.current = `[data-title="${index}"]`;+ };const update = (index: number, next: Criterion) =>onChange?.(criteria.map((c, i) => (i === index ? next : c)));const move = (index: number, by: number) => {- const next = [...criteria];- [next[index], next[index + by]] = [next[index + by], next[index]];- onChange?.(next);+ const swap = <T,>(items: T[]) => {+ const next = [...items];+ [next[index], next[index + by]] = [next[index + by], next[index]];+ return next;+ };+ setKeys(swap(keys));+ onChange?.(swap(criteria));setOpen(index + by);};+ const remove = (index: number) => {+ setRemoved({ criterion: criteria[index], index, key: keys[index] });+ setKeys(keys.filter((_, i) => i !== index));+ onChange?.(criteria.filter((_, i) => i !== index));+ setOpen(null);+ focusNext.current = "[data-undo]";+ };+ const undo = () => {+ if (!removed) return;+ const at = Math.min(removed.index, criteria.length);+ setKeys([...keys.slice(0, at), removed.key, ...keys.slice(at)]);+ onChange?.([...criteria.slice(0, at), removed.criterion, ...criteria.slice(at)]);+ setRemoved(null);+ expand(at);+ };+ const add = (type: "llm" | "deterministic") => {+ setKeys([...keys, newKey()]);+ onChange?.([...criteria, NEW_CRITERION[type]]);+ setRemoved(null);+ expand(criteria.length);+ };+return (<CardclassName={cn("flex min-h-0 flex-col gap-0 overflow-hidden p-0 transition-colors hover:border-muted-foreground",className)}+ ref={root}><div className="flex min-h-8 shrink-0 items-center gap-2 p-3"><span className="rounded-sm bg-muted p-1">@@ -294,111 +361,154 @@ export function CriteriaCard({{!criteria.length && (<li className="px-3 py-1.5 text-xs text-muted-foreground">No criteria</li>)}- {criteria.map((criterion, index) =>- open === index ? (- <li className="mx-2 space-y-3 rounded-sm bg-wash-subtle p-2" key={index}>- <div className="flex items-center gap-2">- {onChange ? (- <Input- aria-label="Criterion name"- onChange={(e) => update(index, { ...criterion, name: e.target.value })}- placeholder="Criterion name"- size="xs"- value={criterion.name}- />- ) : (- <span className="min-w-0 flex-1 truncate text-sm font-medium">- {criterion.name}+ {criteria.map((criterion, index) => {+ const expanded = open === index;+ return (+ <li+ className={cn(expanded && "mx-2 rounded-sm bg-wash-subtle")}+ key={keys[index] ?? index}+ >+ {expanded ? (+ <div className="flex items-center gap-2 p-2">+ {onChange ? (+ <Input+ aria-label="Criterion name"+ data-title={index}+ onChange={(e) => update(index, { ...criterion, name: e.target.value })}+ placeholder="Criterion name"+ size="xs"+ value={criterion.name}+ />+ ) : (+ <span className="min-w-0 flex-1 truncate text-sm font-medium">+ {criterion.name}+ </span>+ )}+ <span className="shrink-0 text-xs text-muted-foreground">+ {criterionKind(criterion)}</span>- )}- <span className="shrink-0 text-xs text-muted-foreground">- {criterionKind(criterion)}- </span>- <Button onClick={() => setOpen(null)} size="xs" variant="secondary">- Done- </Button>- </div>- <CriterionBody- criterion={criterion}- onChange={onChange && ((next) => update(index, next))}- />- {onChange && (- <div className="flex gap-1">- <Button- aria-label="Move up"- disabled={index === 0}- onClick={() => move(index, -1)}- size="icon-xs"- variant="ghost"- >- <Icon.arrowUp />- </Button><Button- aria-label="Move down"- disabled={index === criteria.length - 1}- onClick={() => move(index, 1)}- size="icon-xs"- variant="ghost"- >- <Icon.arrowDown />- </Button>- <Button- className="ml-auto text-destructive"+ aria-expandedonClick={() => {- onChange(criteria.filter((_, i) => i !== index));setOpen(null);+ focusNext.current = `[data-row="${index}"]`;}}size="xs"variant="secondary">- <Icon.delete />- Remove+ Done</Button></div>- )}- </li>- ) : (- <li key={index}>- <button- aria-expanded={false}- className="flex w-full items-center gap-3 px-3 py-1.5 text-left hover:bg-wash-subtle focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"- onClick={() => setOpen(index)}- type="button"- >- <span className="min-w-0 flex-1">- {/* A one-criterion card already shows this name as its title. */}- {criterion.name !== name && (- <span className="mb-0.5 block truncate text-sm font-medium">- {criterion.name || "Untitled criterion"}+ ) : (+ <button+ aria-expanded={false}+ className="flex w-full items-center gap-3 px-3 py-1.5 text-left hover:bg-wash-subtle focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"+ data-row={index}+ onClick={() => expand(index)}+ type="button"+ >+ <span className="min-w-0 flex-1">+ {/* A one-criterion card already shows this name as its title. */}+ {criterion.name !== name && (+ <span className="mb-0.5 block truncate text-sm font-medium">+ {criterion.name || "Untitled criterion"}+ </span>+ )}+ <span className="block truncate text-xs text-muted-foreground">+ {criterion.type === "deterministic"+ ? "evaluate(span)"+ : criterion.source || "No question"}</span>- )}- <span className="block truncate text-xs text-muted-foreground">- {criterion.type === "deterministic"- ? "evaluate(span)"- : criterion.source || "No question"}</span>- </span>- {summary && <ScoreChip value={summary.metrics?.[criterion.name]?.mean} />}- <span className="shrink-0 text-xs text-muted-foreground">- {criterionKind(criterion)}- </span>- </button>+ {summary && <ScoreChip value={summary.metrics?.[criterion.name]?.mean} />}+ <span className="shrink-0 text-xs text-muted-foreground">+ {criterionKind(criterion)}+ </span>+ </button>+ )}+ <AnimatePresence initial={false}>+ {expanded && (+ <motion.div+ animate={{ height: "auto", opacity: 1 }}+ className="overflow-hidden"+ exit={{ height: 0, opacity: 0 }}+ initial={{ height: 0, opacity: 0 }}+ transition={{ duration: reduce ? 0 : 0.2, ease: [0.25, 1, 0.5, 1] }}+ >+ <div className="space-y-3 px-2 pb-2">+ <CriterionBody+ criterion={criterion}+ onChange={onChange && ((next) => update(index, next))}+ />+ {preview && <Preview criterion={criterion} />}+ {onChange && (+ <div className="flex gap-1">+ <Button+ aria-label="Move up"+ disabled={index === 0}+ onClick={() => move(index, -1)}+ size="icon-xs"+ variant="ghost"+ >+ <Icon.arrowUp />+ </Button>+ <Button+ aria-label="Move down"+ disabled={index === criteria.length - 1}+ onClick={() => move(index, 1)}+ size="icon-xs"+ variant="ghost"+ >+ <Icon.arrowDown />+ </Button>+ {criterion.type === "llm" && (+ <Button+ aria-expanded={preview}+ className="ml-auto"+ onClick={() => setPreview(!preview)}+ size="xs"+ variant="secondary"+ >+ Preview+ </Button>+ )}+ <Button+ className={cn(+ "text-destructive",+ criterion.type !== "llm" && "ml-auto"+ )}+ onClick={() => remove(index)}+ size="xs"+ variant="secondary"+ >+ <Icon.delete />+ Remove+ </Button>+ </div>+ )}+ </div>+ </motion.div>+ )}+ </AnimatePresence></li>- )- )}+ );+ })}</ul>+ {removed && onChange && (+ <div+ className="flex items-center justify-end gap-2 px-3 pb-2 text-xs text-muted-foreground"+ role="status"+ >+ Removed {removed.criterion.name || "criterion"}+ <Button data-undo onClick={undo} size="xs" variant="secondary">+ Undo+ </Button>+ </div>+ )}{onChange && (<div className="flex gap-2 border-t border-border/70 p-2">{(["llm", "deterministic"] as const).map((type) => (- <Button- key={type}- onClick={() => {- onChange([...criteria, NEW_CRITERION[type]]);- setOpen(criteria.length);- }}- size="xs"- variant="secondary"- >+ <Button key={type} onClick={() => add(type)} size="xs" variant="secondary"><Icon.add />{type === "llm" ? "Judge criterion" : "Python criterion"}</Button>diff --git a/frontend/src/components/evaluations/generated-run-results.tsx b/frontend/src/components/evaluations/generated-run-results.tsxindex a8d3ffef..2187b180 100644--- a/frontend/src/components/evaluations/generated-run-results.tsx+++ b/frontend/src/components/evaluations/generated-run-results.tsx@@ -91,10 +91,10 @@ export function matchesDatapoint(: [point.samples[participant]].filter(Boolean);if (!samples.length) return false;const matching = samples.filter((sample) => {- if (outcome === "errored") return !!sample.error || sample.degraded;- if (outcome === "failing")- return !sample.error && !sample.degraded && sample.score != null && sample.score < 0.5;- if (outcome === "unscored") return sample.score == null && !sample.error && !sample.degraded;+ const errored = !!sample.error || !!sample.scoreError || sample.degraded;+ if (outcome === "errored") return errored;+ if (outcome === "failing") return !errored && sample.score != null && sample.score < 0.5;+ if (outcome === "unscored") return sample.score == null && !errored;return true;});const query = search.trim().toLowerCase();@@ -107,6 +107,7 @@ export function matchesDatapoint(sample.output,sample.reference,sample.error,+ sample.scoreError,sample.metrics,].some((value) => JSON.stringify(value)?.toLowerCase().includes(query)));@@ -456,6 +457,9 @@ export function GeneratedRunResults({ runs }: { runs: EvalRun[] }) {{sample.error && (<p className="text-sm text-muted-foreground">{sample.error}</p>)}+ {sample.scoreError && (+ <p className="text-sm text-warning">{sample.scoreError}</p>+ )}{sample.degraded && (<p className="text-sm text-warning">{sample.degradedReason || "Degraded result"}diff --git a/frontend/src/components/quickstart/home-quickstart.tsx b/frontend/src/components/quickstart/home-quickstart.tsxindex 99ea31cb..285ffd14 100644--- a/frontend/src/components/quickstart/home-quickstart.tsx+++ b/frontend/src/components/quickstart/home-quickstart.tsx@@ -43,6 +43,7 @@ export function recentPrompts(activity: Pick<Activity, "assets">[]) {capability: `Help me test and improve “${name}”.`,dataset: `Explore “${name}” and suggest how to use it for training.`,evaluation: `Review “${name}” and explain what I should improve next.`,+ experiment: `Review how “${name}” went and suggest what to try next.`,training_job: `Review “${name}” and help me choose the next training experiment.`,}[asset.kind]: undefined;diff --git a/frontend/src/components/workspace/home-composer.tsx b/frontend/src/components/workspace/home-composer.tsxindex 42ab3349..1fb29f55 100644--- a/frontend/src/components/workspace/home-composer.tsx+++ b/frontend/src/components/workspace/home-composer.tsx@@ -1,6 +1,7 @@import { type Ref, useEffect, useImperativeHandle, useRef, useState } from "react";import { useMutation, useQueryClient } from "@tanstack/react-query";+import { AnimatePresence } from "motion/react";import apiClient from "@/client";import { MentionTextarea } from "@/components/assistant/mention-textarea";@@ -28,7 +29,7 @@ import { errorMessage } from "@/lib/notify";import type { Dataset } from "@/openapi";const ACCEPT =- ".csv,.tsv,.json,.jsonl,.ndjson,.parquet,.gz,.pdf,.docx,.md,.txt,.png,.jpg,.jpeg,.webp";+ ".csv,.tsv,.json,.jsonl,.ndjson,.parquet,.xlsx,.gz,.pdf,.docx,.md,.txt,.png,.jpg,.jpeg,.webp";// The API takes 20 dataset versions with a message.const MAX_DATASETS = 20;// An attached file lands before the experiment starts with it; past this the send fails.@@ -237,6 +238,14 @@ export function HomeComposer({const ids = [...new Set([step.dataset, ...datasets.map((dataset) => dataset.id)].filter(Boolean)),];+ const readyCell = (dataset: Dataset) => {+ const cell = activeCellOf(dataset);+ if (dataset.state === "error" || !cell)+ throw new Error(+ "The attached data has no ready version. Check its import before sending."+ );+ return cell.id;+ };const cells = await Promise.all(ids.map(async (id) => {const deadline = Date.now() + LANDING_SECONDS * 1000;@@ -251,14 +260,23 @@ export function HomeComposer({signal.throwIfAborted();dataset = await apiClient.datasets.datasetsRetrieve({ id: id! }, { signal });}- const cell = activeCellOf(dataset);- if (dataset.state === "error" || !cell)- throw new Error(- "The attached data has no ready version. Check its import before sending."- );- return cell.id;+ if (id !== step.dataset) return [readyCell(dataset)];+ // Files with other columns, and each workbook sheet, landed as datasets of their+ // own in the same publication; each becomes its own Data stage.+ const groups =+ (dataset.sourceSpec as { column_groups?: { dataset: string }[] }).column_groups ?? [];+ const others = await Promise.all(+ groups+ .filter((group) => group.dataset !== id)+ .map(async (group) =>+ readyCell(+ await apiClient.datasets.datasetsRetrieve({ id: group.dataset }, { signal })+ )+ )+ );+ return [readyCell(dataset), ...others];})- );+ ).then((found) => found.flat());setLanding("");const experiment = await apiClient.experiments.experimentsCreate({experimentCreateRequest: { cells, message, name, project: projectId, requestKey: step.key },@@ -356,16 +374,18 @@ export function HomeComposer({</Button></li>))}- {upload.files.map((entry) => (- <Attachment- compact- disabled={locked}- entry={entry}- key={entry.id}- onRemove={() => upload.remove(entry.id)}- onRetry={() => upload.retry(entry)}- />- ))}+ <AnimatePresence initial={false}>+ {upload.files.map((entry) => (+ <Attachment+ compact+ disabled={locked}+ entry={entry}+ key={entry.id}+ onRemove={() => upload.remove(entry.id)}+ onRetry={() => upload.retry(entry)}+ />+ ))}+ </AnimatePresence></ul>)}<div className="grid min-w-0 grid-cols-[auto_minmax(0,1fr)_auto] items-end gap-2 p-2">diff --git a/frontend/src/lib/pdf-thumbnail.ts b/frontend/src/lib/pdf-thumbnail.tsindex 3d28f20a..d2b993f3 100644--- a/frontend/src/lib/pdf-thumbnail.ts+++ b/frontend/src/lib/pdf-thumbnail.ts@@ -3,11 +3,14 @@ import workerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url";const WIDTH = 384;/** The first page of a PDF as an image URL the caller must revoke. pdf.js loads on first- * use, so it stays out of the initial bundle. */-export async function pdfThumbnail(file: File): Promise<string> {+ * use, so it stays out of the initial bundle. An abort stops the parse and the drawing. */+export async function pdfThumbnail(file: File, signal?: AbortSignal): Promise<string> {const pdfjs = await import("pdfjs-dist");+ signal?.throwIfAborted();pdfjs.GlobalWorkerOptions.workerSrc = workerUrl;const task = pdfjs.getDocument({ data: await file.arrayBuffer() });+ const stop = () => void task.destroy();+ signal?.addEventListener("abort", stop, { once: true });try {const page = await (await task.promise).getPage(1);const viewport = page.getViewport({ scale: 1 });@@ -17,9 +20,11 @@ export async function pdfThumbnail(file: File): Promise<string> {canvas.height = scaled.height;await page.render({ canvas, viewport: scaled }).promise;const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, "image/png"));+ signal?.throwIfAborted();if (!blob) throw new Error("The page could not be drawn.");return URL.createObjectURL(blob);} finally {+ signal?.removeEventListener("abort", stop);void task.destroy();}}diff --git a/frontend/src/openapi/.openapi-generator/FILES b/frontend/src/openapi/.openapi-generator/FILESindex 92229644..bb0f29e0 100644--- a/frontend/src/openapi/.openapi-generator/FILES+++ b/frontend/src/openapi/.openapi-generator/FILES@@ -401,6 +401,7 @@ models/PublicModelMarketing.tsmodels/PublicModelPricing.tsmodels/PublicTokenRefresh.tsmodels/PublicTokenRefreshRequest.ts+models/PurposeEnum.tsmodels/PythonCheck.tsmodels/PythonSourceRequest.tsmodels/QuantizationEnum.tsdiff --git a/frontend/src/openapi/models/ActivityAssetKindEnum.ts b/frontend/src/openapi/models/ActivityAssetKindEnum.tsindex d62e22a9..6f49d233 100644--- a/frontend/src/openapi/models/ActivityAssetKindEnum.ts+++ b/frontend/src/openapi/models/ActivityAssetKindEnum.ts@@ -18,13 +18,15 @@* * `capability` - capability* * `evaluation` - evaluation* * `training_job` - training_job+ * * `experiment` - experiment* @export*/export const ActivityAssetKindEnum = {dataset: 'dataset',capability: 'capability',evaluation: 'evaluation',- training_job: 'training_job'+ training_job: 'training_job',+ experiment: 'experiment'} as const;export type ActivityAssetKindEnum = typeof ActivityAssetKindEnum[keyof typeof ActivityAssetKindEnum];diff --git a/frontend/src/openapi/models/DecisionComparisonRequestRequest.ts b/frontend/src/openapi/models/DecisionComparisonRequestRequest.tsindex c9348f4a..41237c23 100644--- a/frontend/src/openapi/models/DecisionComparisonRequestRequest.ts+++ b/frontend/src/openapi/models/DecisionComparisonRequestRequest.ts@@ -20,6 +20,13 @@ import {DecisionParticipantRequestToJSON,DecisionParticipantRequestToJSONTyped,} from './DecisionParticipantRequest';+import type { PurposeEnum } from './PurposeEnum';+import {+ PurposeEnumFromJSON,+ PurposeEnumFromJSONTyped,+ PurposeEnumToJSON,+ PurposeEnumToJSONTyped,+} from './PurposeEnum';/***@@ -87,8 +94,16 @@ export interface DecisionComparisonRequestRequest {* @memberof DecisionComparisonRequestRequest*/inference?: any | null;+ /**+ *+ * @type {PurposeEnum}+ * @memberof DecisionComparisonRequestRequest+ */+ purpose?: PurposeEnum;}++/*** Check if a given object implements the DecisionComparisonRequestRequest interface.*/@@ -122,6 +137,7 @@ export function DecisionComparisonRequestRequestFromJSONTyped(json: any, ignoreD'bootstrapSamples': json['bootstrap_samples'] == null ? undefined : json['bootstrap_samples'],'seed': json['seed'] == null ? undefined : json['seed'],'inference': json['inference'] == null ? undefined : json['inference'],+ 'purpose': json['purpose'] == null ? undefined : PurposeEnumFromJSON(json['purpose']),};}@@ -146,5 +162,6 @@ export function DecisionComparisonRequestRequestToJSONTyped(value?: DecisionComp'bootstrap_samples': value['bootstrapSamples'],'seed': value['seed'],'inference': value['inference'],+ 'purpose': PurposeEnumToJSON(value['purpose']),};}diff --git a/frontend/src/openapi/models/DecisionParticipantRequest.ts b/frontend/src/openapi/models/DecisionParticipantRequest.tsindex 24ac89a4..6dd0577d 100644--- a/frontend/src/openapi/models/DecisionParticipantRequest.ts+++ b/frontend/src/openapi/models/DecisionParticipantRequest.ts@@ -63,6 +63,12 @@ export interface DecisionParticipantRequest {* @memberof DecisionParticipantRequest*/servedModel?: string;+ /**+ *+ * @type {string}+ * @memberof DecisionParticipantRequest+ */+ instructions?: string;}@@ -93,6 +99,7 @@ export function DecisionParticipantRequestFromJSONTyped(json: any, ignoreDiscrim'job': json['job'] == null ? undefined : json['job'],'model': json['model'] == null ? undefined : json['model'],'servedModel': json['served_model'] == null ? undefined : json['served_model'],+ 'instructions': json['instructions'] == null ? undefined : json['instructions'],};}@@ -113,5 +120,6 @@ export function DecisionParticipantRequestToJSONTyped(value?: DecisionParticipan'job': value['job'],'model': value['model'],'served_model': value['servedModel'],+ 'instructions': value['instructions'],};}diff --git a/frontend/src/openapi/models/EvalRunRow.ts b/frontend/src/openapi/models/EvalRunRow.tsindex aad7fb85..ace5721e 100644--- a/frontend/src/openapi/models/EvalRunRow.ts+++ b/frontend/src/openapi/models/EvalRunRow.ts@@ -22,7 +22,7 @@ import {} from './EvalRunRowStateEnum';/**- * ``score`` and ``metrics`` are the row's newest score, passed in by the view.+ * ``score`` and ``metrics`` are the row's score, passed in by the view.* @export* @interface EvalRunRow*/@@ -81,6 +81,12 @@ export interface EvalRunRow {* @memberof EvalRunRow*/readonly error: string;+ /**+ *+ * @type {string}+ * @memberof EvalRunRow+ */+ readonly scoreError: string;/**** @type {boolean}@@ -134,6 +140,7 @@ export function instanceOfEvalRunRow(value: object): value is EvalRunRow {if (!('reference' in value) || value['reference'] === undefined) return false;if (!('metadata' in value) || value['metadata'] === undefined) return false;if (!('error' in value) || value['error'] === undefined) return false;+ if (!('scoreError' in value) || value['scoreError'] === undefined) return false;if (!('degraded' in value) || value['degraded'] === undefined) return false;if (!('degradedReason' in value) || value['degradedReason'] === undefined) return false;if (!('state' in value) || value['state'] === undefined) return false;@@ -162,6 +169,7 @@ export function EvalRunRowFromJSONTyped(json: any, ignoreDiscriminator: boolean)'reference': json['reference'],'metadata': json['metadata'],'error': json['error'],+ 'scoreError': json['score_error'],'degraded': json['degraded'],'degradedReason': json['degraded_reason'],'state': EvalRunRowStateEnumFromJSON(json['state']),@@ -175,7 +183,7 @@ export function EvalRunRowToJSON(json: any): EvalRunRow {return EvalRunRowToJSONTyped(json, false);}-export function EvalRunRowToJSONTyped(value?: Omit<EvalRunRow, 'id'|'run'|'row_index'|'source_trace_id'|'input'|'output'|'reference'|'metadata'|'error'|'degraded'|'degraded_reason'|'state'|'score'|'metrics'|'finished_at'> | null, ignoreDiscriminator: boolean = false): any {+export function EvalRunRowToJSONTyped(value?: Omit<EvalRunRow, 'id'|'run'|'row_index'|'source_trace_id'|'input'|'output'|'reference'|'metadata'|'error'|'score_error'|'degraded'|'degraded_reason'|'state'|'score'|'metrics'|'finished_at'> | null, ignoreDiscriminator: boolean = false): any {if (value == null) {return value;}diff --git a/frontend/src/openapi/models/EvalRunRowDetail.ts b/frontend/src/openapi/models/EvalRunRowDetail.tsindex 13040fc8..c040ccc7 100644--- a/frontend/src/openapi/models/EvalRunRowDetail.ts+++ b/frontend/src/openapi/models/EvalRunRowDetail.ts@@ -81,6 +81,12 @@ export interface EvalRunRowDetail {* @memberof EvalRunRowDetail*/readonly error: string;+ /**+ *+ * @type {string}+ * @memberof EvalRunRowDetail+ */+ readonly scoreError: string;/**** @type {boolean}@@ -134,6 +140,7 @@ export function instanceOfEvalRunRowDetail(value: object): value is EvalRunRowDeif (!('reference' in value) || value['reference'] === undefined) return false;if (!('metadata' in value) || value['metadata'] === undefined) return false;if (!('error' in value) || value['error'] === undefined) return false;+ if (!('scoreError' in value) || value['scoreError'] === undefined) return false;if (!('degraded' in value) || value['degraded'] === undefined) return false;if (!('degradedReason' in value) || value['degradedReason'] === undefined) return false;if (!('state' in value) || value['state'] === undefined) return false;@@ -162,6 +169,7 @@ export function EvalRunRowDetailFromJSONTyped(json: any, ignoreDiscriminator: bo'reference': json['reference'],'metadata': json['metadata'],'error': json['error'],+ 'scoreError': json['score_error'],'degraded': json['degraded'],'degradedReason': json['degraded_reason'],'state': EvalRunRowStateEnumFromJSON(json['state']),@@ -175,7 +183,7 @@ export function EvalRunRowDetailToJSON(json: any): EvalRunRowDetail {return EvalRunRowDetailToJSONTyped(json, false);}-export function EvalRunRowDetailToJSONTyped(value?: Omit<EvalRunRowDetail, 'id'|'run'|'row_index'|'source_trace_id'|'input'|'output'|'reference'|'metadata'|'error'|'degraded'|'degraded_reason'|'state'|'score'|'metrics'|'finished_at'> | null, ignoreDiscriminator: boolean = false): any {+export function EvalRunRowDetailToJSONTyped(value?: Omit<EvalRunRowDetail, 'id'|'run'|'row_index'|'source_trace_id'|'input'|'output'|'reference'|'metadata'|'error'|'score_error'|'degraded'|'degraded_reason'|'state'|'score'|'metrics'|'finished_at'> | null, ignoreDiscriminator: boolean = false): any {if (value == null) {return value;}diff --git a/frontend/src/openapi/models/PurposeEnum.ts b/frontend/src/openapi/models/PurposeEnum.tsnew file mode 100644index 00000000..aad2fb42--- /dev/null+++ b/frontend/src/openapi/models/PurposeEnum.ts@@ -0,0 +1,53 @@+/* 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.+ */+++/**+ * * `development` - development+ * * `final` - final+ * @export+ */+export const PurposeEnum = {+ development: 'development',+ final: 'final'+} as const;+export type PurposeEnum = typeof PurposeEnum[keyof typeof PurposeEnum];+++export function instanceOfPurposeEnum(value: any): boolean {+ for (const key in PurposeEnum) {+ if (Object.prototype.hasOwnProperty.call(PurposeEnum, key)) {+ if (PurposeEnum[key as keyof typeof PurposeEnum] === value) {+ return true;+ }+ }+ }+ return false;+}++export function PurposeEnumFromJSON(json: any): PurposeEnum {+ return PurposeEnumFromJSONTyped(json, false);+}++export function PurposeEnumFromJSONTyped(json: any, ignoreDiscriminator: boolean): PurposeEnum {+ return json as PurposeEnum;+}++export function PurposeEnumToJSON(value?: PurposeEnum | null): any {+ return value as any;+}++export function PurposeEnumToJSONTyped(value: any, ignoreDiscriminator: boolean): PurposeEnum {+ return value as PurposeEnum;+}diff --git a/frontend/src/openapi/models/index.ts b/frontend/src/openapi/models/index.tsindex 32756edb..b4e908d2 100644--- a/frontend/src/openapi/models/index.ts+++ b/frontend/src/openapi/models/index.ts@@ -356,6 +356,7 @@ export * from './PublicModelMarketing';export * from './PublicModelPricing';export * from './PublicTokenRefresh';export * from './PublicTokenRefreshRequest';+export * from './PurposeEnum';export * from './PythonCheck';export * from './PythonSourceRequest';export * from './QuantizationEnum';diff --git a/frontend/src/styles.css b/frontend/src/styles.cssindex a31ff6a2..ab7a9545 100644--- a/frontend/src/styles.css+++ b/frontend/src/styles.css@@ -1044,10 +1044,6 @@ body:has(scrollbar-width: thin;}- .assistant-attachment {- animation: assistant-attachment-in 220ms ease-out both;- }-@media (hover: hover) and (pointer: fine) {.assistant-attachment-remove {opacity: 0;@@ -1058,23 +1054,6 @@ body:has(}}- @keyframes assistant-attachment-in {- from {- opacity: 0;- transform: translateX(10px);- }- to {- opacity: 1;- transform: translateX(0);- }- }-- @media (prefers-reduced-motion: reduce) {- .assistant-attachment {- animation: none;- }- }-.assistant-composer {transition: border-color 150ms;}diff --git a/modal_shared/decision_inference.py b/modal_shared/decision_inference.pyindex b38776c6..1ba52b41 100644--- a/modal_shared/decision_inference.py+++ b/modal_shared/decision_inference.py@@ -11,7 +11,9 @@ def input_digest(request):).hexdigest()-def prepare_requests(records, output, failures, tokenizer, context_length, encode_record):+def prepare_requests(+ records, output, failures, tokenizer, context_length, encode_record, *, instructions=""+):encoder = DecisionEncoder(tokenizer, encode_record)keys = set()report = {"ready_decisions": 0, "failed_decisions": 0, "tokens": 0, "max_tokens": 0}@@ -27,6 +29,9 @@ def prepare_requests(records, output, failures, tokenizer, context_length, encodif digest != record["input_sha256"]:raise ValueError("Benchmark input checksum differs")identity = {"key": key, "input_sha256": digest}+ if instructions:+ # The input keeps its own identity, so prompt variants pair on the same rows.+ request = {**request, "question": f"{instructions}\n\n{request['question']}"}try:prepared = encoder.request(request)except ValueError as exc:diff --git a/overbae/api/activity.py b/overbae/api/activity.pyindex 234f9a82..e7820c23 100644--- a/overbae/api/activity.py+++ b/overbae/api/activity.py@@ -22,7 +22,9 @@ STREAM_SECONDS = 300class ActivityAssetSerializer(serializers.Serializer):- kind = serializers.ChoiceField(choices=["dataset", "capability", "evaluation", "training_job"])+ kind = serializers.ChoiceField(+ choices=["dataset", "capability", "evaluation", "training_job", "experiment"]+ )id = serializers.UUIDField()label = serializers.CharField()diff --git a/overbae/api/eval_serializers.py b/overbae/api/eval_serializers.pyindex 9770183f..8c604fb8 100644--- a/overbae/api/eval_serializers.py+++ b/overbae/api/eval_serializers.py@@ -8,6 +8,7 @@ from rest_framework import serializersfrom rest_framework.exceptions import PermissionDeniedfrom overbae.api.scoping import project_ids_for+from overbae.core.errors import InputValidationErrorfrom overbae.core.model_registry import judge_picker_modelsfrom overbae.innermind import context, deterministic, generation, runsfrom overbae.innermind.definitions import DefinitionSource, definition_source@@ -22,14 +23,15 @@ from overbae.models import (ModelRef,Project,)+from overbae.services import eval_setsfrom overbae.services.activity import asset, recordfrom overbae.services.datasets import rows as row_storefrom overbae.services.datasets import usefrom overbae.services.datasets.lifecycle import DatasetError+from overbae.services.eval_sets import EXPECTATION_MAX_CHARSfrom overbae.services.model_catalog import is_model_availableMAX_TARGETS = 6-EXPECTATION_MAX_CHARS = 1_000def require_membership(serializer, project):@@ -126,24 +128,10 @@ class EvalCriterionSerializer(serializers.Serializer):options = JudgeOptionSerializer(many=True, required=False)def validate(self, attrs):- if attrs["type"] == EvalMatrix.Type.DETERMINISTIC:- if problem := deterministic.audit(attrs["source"]):- raise serializers.ValidationError({"source": problem})- attrs.pop("options", None)- attrs.pop("output", None)- return attrs- if len(attrs["source"]) > EXPECTATION_MAX_CHARS:- raise serializers.ValidationError(- {"source": f"Question exceeds {EXPECTATION_MAX_CHARS} characters."}- )- if "output" not in attrs:- raise serializers.ValidationError({"output": "Choose yes/no or multiple choice."})- labels = [option["label"].strip() for option in attrs.get("options", [])]- if not 2 <= len(set(labels)) == len(labels) <= 20 or not all(labels):- raise serializers.ValidationError({"options": "Provide 2–20 distinct answers."})- if attrs["output"] == "yes_no" and labels != ["Yes", "No"]:- raise serializers.ValidationError({"options": "Yes/no answers are Yes and No."})- return attrs+ try:+ return eval_sets.clean_criterion(attrs)+ except InputValidationError as exc:+ raise serializers.ValidationError(exc.detail) from Noneclass PythonSourceSerializer(serializers.Serializer):@@ -213,9 +201,10 @@ class EvalSetSerializer(serializers.ModelSerializer):"give it its own criteria."})- names = [criterion["name"] for criterion in attrs.get("criteria") or []]- if len(set(names)) != len(names):- raise serializers.ValidationError({"criteria": "Criterion names must be unique."})+ try:+ eval_sets.check_names(attrs.get("criteria") or [])+ except InputValidationError as exc:+ raise serializers.ValidationError({"criteria": exc.detail}) from Nonereturn attrs@@ -430,9 +419,9 @@ class EvalRunProgressSerializer(serializers.Serializer):def run_progress(run: EvalRun) -> dict:counts = dict.fromkeys(EvalRunRow.State.values, 0)errored = 0- for state, error in run.rows.values_list("state", "error"):+ for state, error, score_error in run.rows.values_list("state", "error", "score_error"):counts[state] += 1- errored += bool(error)+ errored += bool(error or score_error)rows = sum(counts.values())unfinished = sum(counts[state] for state in generation.UNFINISHED)phase = (@@ -546,7 +535,7 @@ class EvalScoreSerializer(serializers.ModelSerializer):class EvalRunRowSerializer(serializers.ModelSerializer):- """``score`` and ``metrics`` are the row's newest score, passed in by the view."""+ """``score`` and ``metrics`` are the row's score, passed in by the view."""score = serializers.SerializerMethodField()metrics = serializers.SerializerMethodField()@@ -565,6 +554,7 @@ class EvalRunRowSerializer(serializers.ModelSerializer):"reference","metadata","error",+ "score_error","degraded","degraded_reason","state",@@ -574,16 +564,16 @@ class EvalRunRowSerializer(serializers.ModelSerializer):]read_only_fields = fields- def latest(self, obj) -> EvalScore | None:+ def row_score(self, obj) -> EvalScore | None:return self.context.get("scores", {}).get(f"{obj.run.cell_id}:{obj.row_index}")def get_score(self, obj) -> float | None:- found = self.latest(obj)+ found = self.row_score(obj)return found.score if found else None@extend_schema_field(serializers.DictField())def get_metrics(self, obj) -> dict:- found = self.latest(obj)+ found = self.row_score(obj)return found.metrics if found else {}@staticmethoddiff --git a/overbae/api/eval_views.py b/overbae/api/eval_views.pyindex a6c98f33..b7589b05 100644--- a/overbae/api/eval_views.py+++ b/overbae/api/eval_views.py@@ -421,7 +421,7 @@ class EvalRunRowViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewse),pk=run_id,)- ctx["scores"] = comparison.latest_scores(run)+ ctx["scores"] = comparison.scores_by_row(run)return ctxdiff --git a/overbae/api/native_evaluation.py b/overbae/api/native_evaluation.pyindex 87d04733..2756fc04 100644--- a/overbae/api/native_evaluation.py+++ b/overbae/api/native_evaluation.py@@ -105,6 +105,7 @@ class DecisionParticipantSerializer(serializers.Serializer):job = serializers.UUIDField(required=False)model = serializers.CharField(max_length=255, required=False)served_model = serializers.CharField(max_length=255, required=False, allow_blank=True)+ instructions = serializers.CharField(max_length=8000, required=False, allow_blank=True)class DecisionComparisonRequestSerializer(serializers.Serializer):@@ -118,6 +119,7 @@ class DecisionComparisonRequestSerializer(serializers.Serializer):bootstrap_samples = serializers.IntegerField(min_value=2, max_value=10000, default=1000)seed = serializers.IntegerField(min_value=0, max_value=4294967295, default=73491)inference = serializers.JSONField(required=False)+ purpose = serializers.ChoiceField(choices=["development", "final"], default="final")class EvaluationResumeSerializer(serializers.Serializer):diff --git a/overbae/innermind/comparison.py b/overbae/innermind/comparison.pyindex 2d8d3a8a..61e6099a 100644--- a/overbae/innermind/comparison.py+++ b/overbae/innermind/comparison.py@@ -39,17 +39,13 @@ def classify(baseline: float | None, candidate: float | None) -> tuple[float | Nreturn delta, UNCHANGED-def latest_scores(run: EvalRun) -> dict[str, EvalScore]:- """The newest score per row; a re-scored row appends rather than replaces."""- latest: dict[str, EvalScore] = {}- for score in run.scores.order_by("source_id", "-created_at"):- latest.setdefault(score.source_id, score)- return latest+def scores_by_row(run: EvalRun) -> dict[str, EvalScore]:+ return {score.source_id: score for score in run.scores.all()}def compare(baseline: EvalRun, candidate: EvalRun) -> dict:"""Scores only rows both runs scored, so a row one run skipped never moves the delta."""- base_rows, cand_rows = latest_scores(baseline), latest_scores(candidate)+ base_rows, cand_rows = scores_by_row(baseline), scores_by_row(candidate)paired = sorted(set(base_rows) & set(cand_rows))scored_pairs = [k for k in paired if base_rows[k].score is not None and cand_rows[k].score is not Nonediff --git a/overbae/innermind/dataset.py b/overbae/innermind/dataset.pyindex d47ecff1..b7616e9c 100644--- a/overbae/innermind/dataset.py+++ b/overbae/innermind/dataset.py@@ -32,7 +32,7 @@ class DatasetRowProcessor(SpanProcessor):span_name = "dataset_row"def __init__(self, run: EvalRun):- super().__init__(run.project_id, run.judge_model)+ super().__init__(run.project_id, run.judge_context)self.run = runself.capability_id = run.dataset.capability_id if run.dataset_id else None@@ -66,7 +66,7 @@ class DatasetRowProcessor(SpanProcessor):def scoreable(run: EvalRun) -> list[tuple[row_store.DatasetRow, EvalRunRow]]:- """Rows a previous scorer already saved are skipped."""+ """Rows a previous scorer already saved are skipped; rows it failed to score are not."""scored = set(run.scores.values_list("source_id", flat=True))run_rows = [row@@ -97,27 +97,26 @@ def _hold(run_id, task_id) -> None:@transaction.atomic-def _save(score: EvalScore, task_id: str) -> None:+def _save(score: EvalScore, run_row: EvalRunRow, task_id: str) -> None:"""Each score is saved as soon as it exists."""_hold(score.run_id, task_id)score.save()+ EvalRunRow.objects.filter(pk=run_row.pk).exclude(score_error="").update(score_error="")@transaction.atomicdef _row_failed(run_row: EvalRunRow, task_id: str, error: str) -> None:_hold(run_row.run_id, task_id)- EvalRunRow.objects.filter(pk=run_row.pk).update(error=error)+ EvalRunRow.objects.filter(pk=run_row.pk).update(score_error=error)async def score_rows(run: EvalRun, task_id: str) -> int:- """Appends one EvalScore per scoreable row and returns how many were written. The- run must arrive with ``dataset__capability`` and ``cell`` loaded."""+ """Saves one EvalScore per scoreable row and returns how many were written. The+ run must arrive with ``dataset`` and ``cell`` loaded."""pairs = await sync_to_async(scoreable)(run)processor = DatasetRowProcessor(run)matrix = [EvalMatrix.from_snapshot(data) for data in run.matrix]- fallback = (- run.dataset.capability.description if run.dataset_id and run.dataset.capability_id else ""- )+ fallback = run.judge_context["intent"]slots = asyncio.Semaphore(MAX_CONCURRENT_ROWS)async def score(row: row_store.DatasetRow, run_row: EvalRunRow) -> EvalScore | None:@@ -142,7 +141,7 @@ async def score_rows(run: EvalRun, task_id: str) -> int:score=span.eval_attributes["score"],metrics=span.eval_attributes["metrics"],)- await sync_to_async(_save)(saved, task_id)+ await sync_to_async(_save)(saved, run_row, task_id)return savedresults = await asyncio.gather(*(score(row, run_row) for row, run_row in pairs))diff --git a/overbae/innermind/evals.py b/overbae/innermind/evals.pyindex dd83bf27..d986eacf 100644--- a/overbae/innermind/evals.py+++ b/overbae/innermind/evals.py@@ -8,7 +8,7 @@ from abc import ABC, abstractmethodfrom overbae.core.decisions import ChoiceQuestion, DecisionError, decidefrom overbae.core.llms import call_llm-from overbae.core.model_registry import TaskType, model_chain, resolve_model+from overbae.core.model_registry import TaskType, decision_model, model_chainfrom overbae.innermind import deterministic, evidencefrom overbae.innermind.metrics import REASON_BELOW, Metricfrom overbae.models import EvalMatrix, Span@@ -69,6 +69,15 @@ def expectation_rows(span: Span) -> list[EvalMatrix]:]+def judges(judge_model: str = "") -> dict:+ """The models a score is made with. A run pins them when it is created."""+ chain = model_chain(TaskType.EVAL_EXPLANATION)+ return {+ "decision_model": decision_model().slug,+ "explanation_models": list(dict.fromkeys([judge_model, *chain] if judge_model else chain)),+ }++def fit(state: dict, limit: int = JEV_STATE_LIMIT) -> dict:"""Halve the longest text field, keeping its head and tail, until the state fits."""state = dict(state)@@ -127,9 +136,9 @@ class JevEvaluator(Evaluator):)values = {"yes": 1.0, "partial": 0.5, "no": 0.0}- def __init__(self, project_id: str, explain_model: str = ""):+ def __init__(self, project_id: str, pinned: dict | None = None):self.project_id = str(project_id)- self.explain_model = explain_model+ self.judges = pinned or judges()async def score(self, row: EvalMatrix, span: Span, trace: list[Span]) -> Metric:if not row.judge_options:@@ -187,6 +196,7 @@ class JevEvaluator(Evaluator):project_id=self.project_id,workload=self.workload,contract=self.contract,+ model=self.judges["decision_model"],)except DecisionError as exc:if exc.reason in RETRYABLE or exc.reason.startswith("provider_http_5"):@@ -204,13 +214,14 @@ class JevEvaluator(Evaluator):"Name what is missing or wrong; do not restate the expectation.\n\n"+ json.dumps(fit(state), ensure_ascii=False, indent=1))+ first, *fallbacks = self.judges["explanation_models"]try:text, _ = await asyncio.to_thread(throttled,call_llm,prompt,- model=self.explain_model or resolve_model(TaskType.EVAL_EXPLANATION),- fallback_models=model_chain(TaskType.EVAL_EXPLANATION),+ model=first,+ fallback_models=fallbacks,max_tokens=EXPLAIN_MAX_TOKENS,max_attempts=LLM_ATTEMPTS,)@@ -221,9 +232,11 @@ class JevEvaluator(Evaluator):class EvaluatorFactory:- def get_evaluator(self, row: EvalMatrix, project_id: str, explain_model: str = "") -> Evaluator:+ def get_evaluator(+ self, row: EvalMatrix, project_id: str, pinned: dict | None = None+ ) -> Evaluator:if row.type == EvalMatrix.Type.LLM:- return JevEvaluator(project_id, explain_model)+ return JevEvaluator(project_id, pinned)if row.type == EvalMatrix.Type.DETERMINISTIC:return OvermindEvaluator()raise ValueError(f"Unknown eval matrix type: {row.type}")diff --git a/overbae/innermind/runs.py b/overbae/innermind/runs.pyindex 6303c92d..12dddfd5 100644--- a/overbae/innermind/runs.py+++ b/overbae/innermind/runs.py@@ -16,7 +16,7 @@ from django.db.models import Qfrom django.utils import timezonefrom overbae.core import async_loop, telemetry-from overbae.innermind import classes, comparison, dataset, generation+from overbae.innermind import classes, comparison, dataset, evals, generationfrom overbae.innermind.metrics import FAIL_BELOWfrom overbae.models import EvalMatrix, EvalRun, EvalRunRow, EvalSet, FinetuningJobfrom overbae.services.activity import update_task@@ -70,6 +70,10 @@ def create_run(*, cell, mode: str, matrix: list[dict], **fields: Any) -> EvalRunfields.setdefault("dataset", cell.dataset)params = dict(fields.pop("params", None) or {})capability = fields["dataset"].capability if fields["dataset"] else None+ fields["judge_context"] = {+ **evals.judges(fields.get("judge_model", "")),+ "intent": capability.description if capability else "",+ }if mode == EvalRun.Mode.GENERATE and "system_prompt" not in params and capability:params["system_prompt"] = system_prompt(capability)return EvalRun.objects.create(cell=cell, mode=mode, matrix=matrix, params=params, **fields)@@ -174,7 +178,7 @@ def hand_to_scoring(run_id) -> str:def score(run_id, task_id) -> bool:if not generation.begin_scoring(run_id, task_id):return False- run = EvalRun.objects.select_related("dataset__capability", "cell", "model_ref").get(pk=run_id)+ run = EvalRun.objects.select_related("dataset", "cell", "model_ref").get(pk=run_id)held = Q(scoring_task_id=task_id)beat = heartbeat.start(@@ -197,8 +201,8 @@ def score(run_id, task_id) -> bool:def aggregate(run: EvalRun) -> dict:- rows = list(run.rows.values("row_index", "error", "degraded"))- scores = comparison.latest_scores(run).values()+ rows = list(run.rows.values("row_index", "error", "score_error", "degraded"))+ scores = comparison.scores_by_row(run).values()by_metric: dict[str, list[dict]] = defaultdict(list)for row_score in scores:for name, metric in row_score.metrics.items():@@ -214,7 +218,7 @@ def aggregate(run: EvalRun) -> dict:"errors": sum(bool(m.get("error")) for m in results),}row_scores = [s.score for s in scores if s.score is not None]- errored = sum(bool(row["error"]) for row in rows)+ errored = sum(bool(row["error"] or row["score_error"]) for row in rows)degraded = sum(row["degraded"] for row in rows)return {"score": mean(row_scores) if row_scores else None,@@ -312,7 +316,7 @@ def cancel(run: EvalRun) -> int:def row_scores(run: EvalRun) -> dict[int, float | None]:return {int(source_id.rsplit(":", 1)[1]): row_score.score- for source_id, row_score in comparison.latest_scores(run).items()+ for source_id, row_score in comparison.scores_by_row(run).items()}diff --git a/overbae/innermind/span_processor.py b/overbae/innermind/span_processor.pyindex 75f789b0..a93017bf 100644--- a/overbae/innermind/span_processor.py+++ b/overbae/innermind/span_processor.py@@ -32,9 +32,9 @@ SWEEP_GRACE = timedelta(seconds=90)class SpanProcessor:"""Scores one span against the matching matrix rows and its own expectations."""- def __init__(self, project_id: str, explain_model: str = ""):+ def __init__(self, project_id: str, pinned: dict | None = None):self.project_id = str(project_id)- self.explain_model = explain_model+ self.pinned = pinneddef takes_unscoped_expectations(self, span: Span, trace: dict[str, Span]) -> bool:"""Unscoped llm rows describe the capability's answer."""@@ -100,7 +100,7 @@ class SpanProcessor:)outcomes = await asyncio.gather(*(- evaluator_factory.get_evaluator(row, self.project_id, self.explain_model).score(+ evaluator_factory.get_evaluator(row, self.project_id, self.pinned).score(row, span, nodes)for row in distinctdiff --git a/overbae/management/commands/seed_demo.py b/overbae/management/commands/seed_demo.pyindex 180f710f..f63831de 100644--- a/overbae/management/commands/seed_demo.py+++ b/overbae/management/commands/seed_demo.py@@ -35,7 +35,7 @@ from django.db import connectionfrom django.db.models import Qfrom django.utils import timezone-from overbae.innermind import comparison+from overbae.innermind import comparison, evalsfrom overbae.innermind import runs as innermind_runsfrom overbae.innermind import signals as innermind_signalsfrom overbae.models import (@@ -2941,6 +2941,10 @@ class Command(BaseCommand):name=f"{name} · {label}" if len(targets) > 1 else name,description=description,judge_model=JUDGE,+ judge_context={+ **evals.judges(JUDGE),+ "intent": dataset.capability.description if dataset.capability else "",+ },dataset=dataset,cell=version,max_items=n_samples,diff --git a/overbae/migrations/0074_eval_judge_context_and_one_score_per_row.py b/overbae/migrations/0074_eval_judge_context_and_one_score_per_row.pynew file mode 100644index 00000000..44cf07c8--- /dev/null+++ b/overbae/migrations/0074_eval_judge_context_and_one_score_per_row.py@@ -0,0 +1,65 @@+from django.db import migrations, models+from django.db.models import F, OuterRef, Subquery++# The registry's values when runs began pinning them; existing runs scored with these.+DECISION_MODEL = "typesafe/jev-1.13"+EXPLANATION_MODELS = ["gpt-5-mini", "claude-haiku-4-5", "gemini-3.8-flash"]+SCORING_FAILED = "scoring failed: "+++def pin_and_split(apps, schema_editor):+ """Pins each run's judges, moves scoring failures off the generation error, and keeps+ the newest score of a row scored more than once."""+ EvalRun = apps.get_model("overbae", "EvalRun")+ EvalRunRow = apps.get_model("overbae", "EvalRunRow")+ EvalScore = apps.get_model("overbae", "EvalScore")+ for run in EvalRun.objects.select_related("dataset__capability").iterator():+ capability = run.dataset.capability if run.dataset_id else None+ chain = [run.judge_model, *EXPLANATION_MODELS] if run.judge_model else EXPLANATION_MODELS+ run.judge_context = {+ "decision_model": DECISION_MODEL,+ "explanation_models": list(dict.fromkeys(chain)),+ "intent": capability.description if capability else "",+ }+ run.save(update_fields=["judge_context"])+ EvalRunRow.objects.filter(error__startswith=SCORING_FAILED).update(+ score_error=F("error"), error=""+ )+ newest = EvalScore.objects.filter(+ run_id=OuterRef("run_id"), source_id=OuterRef("source_id")+ ).order_by("-created_at", "-pk")+ EvalScore.objects.filter(run__isnull=False).exclude(+ pk=Subquery(newest.values("pk")[:1])+ ).delete()+++class Migration(migrations.Migration):+ dependencies = [+ ("overbae", "0073_one_agent"),+ ]++ operations = [+ migrations.RemoveIndex(+ model_name="evalscore",+ name="eval_score_run_id_5cea0d_idx",+ ),+ migrations.AddField(+ model_name="evalrun",+ name="judge_context",+ field=models.JSONField(blank=True, default=dict),+ ),+ migrations.AddField(+ model_name="evalrunrow",+ name="score_error",+ field=models.TextField(blank=True, default=""),+ ),+ migrations.RunPython(pin_and_split, migrations.RunPython.noop),+ migrations.AddConstraint(+ model_name="evalscore",+ constraint=models.UniqueConstraint(+ condition=models.Q(("run__isnull", False)),+ fields=("run", "source_id"),+ name="uniq_eval_score_run_row",+ ),+ ),+ ]diff --git a/overbae/modal/modal_decision_evaluation.py b/overbae/modal/modal_decision_evaluation.pyindex 2a99c4e8..cdf75029 100644--- a/overbae/modal/modal_decision_evaluation.py+++ b/overbae/modal/modal_decision_evaluation.py@@ -84,6 +84,7 @@ def prepare(evaluation_id, model_run, input_sha256, *, foundation=None, inferencelse:artifact = read_artifact(model / "final")request = {"artifact_identity": artifact["identity"], "input_sha256": input_sha256}+ request["instructions"] = (inference or {}).get("instructions", "")atomic_json(directory / "request.json", request)with (directory / "prepare.log").open("a") as log:subprocess.run(diff --git a/overbae/models/innermind.py b/overbae/models/innermind.pyindex 946b6760..91828c07 100644--- a/overbae/models/innermind.py+++ b/overbae/models/innermind.py@@ -220,6 +220,8 @@ class EvalRun(models.Model):name = models.CharField(max_length=255)description = models.TextField(blank=True, default="")judge_model = models.CharField(max_length=255, blank=True, default="")+ # Pinned at creation and kept on relaunch: decision_model, explanation_models, intent.+ judge_context = models.JSONField(default=dict, blank=True)dataset = models.ForeignKey("overbae.Dataset",@@ -333,7 +335,10 @@ class EvalRunRow(models.Model):output = models.JSONField(null=True, blank=True)# model, cost, tokens, finish_reasons, truncated, generation_strategy.metadata = models.JSONField(default=dict, blank=True)+ # Generation failed; the row has no output to score.error = models.TextField(blank=True, default="")+ # Scoring failed; a later scoring attempt scores the row again.+ score_error = models.TextField(blank=True, default="")# Degraded rows stay out of aggregates: a pipeline-caused 0 is not a model failure.degraded = models.BooleanField(default=False)degraded_reason = models.CharField(max_length=255, blank=True, default="")@@ -366,7 +371,7 @@ class EvalGenerationScheduler(models.Model):class EvalScore(models.Model):- """Append-only: every scoring pass adds a row, so history is never rewritten."""+ """Append-only for spans and trajectories; a run scores each of its rows once."""class SourceType(models.TextChoices):SPAN = "span"@@ -391,9 +396,15 @@ class EvalScore(models.Model):class Meta:db_table = "eval_score"ordering = ["-created_at"]+ constraints = [+ models.UniqueConstraint(+ fields=["run", "source_id"],+ condition=models.Q(run__isnull=False),+ name="uniq_eval_score_run_row",+ )+ ]indexes = [models.Index(fields=["source_type", "source_id", "-created_at"]),- models.Index(fields=["run", "source_id"]),models.Index(fields=["project", "-created_at"]),]diff --git a/overbae/services/activity.py b/overbae/services/activity.pyindex 0bafa5a6..8ebef516 100644--- a/overbae/services/activity.py+++ b/overbae/services/activity.py@@ -13,7 +13,6 @@ from overbae.models import (ActivityClient,ActivityRead,Capability,- DatasetPipelineRun,FinetuningJob,)from overbae.services.datasets import events@@ -27,6 +26,7 @@ AGENTS = ((re.compile(r"^gemini[- ]cli\b"), "gemini", "Gemini CLI"),(re.compile(r"^opencode\b"), "opencode", "OpenCode"),(re.compile(r"^overmind assistant$"), "overmind", "Overmind assistant"),+ (re.compile(r"^overmind experiment$"), "overmind", "Experiment"),)@@ -55,7 +55,7 @@ def connection_actor(context):def connected(context):# The platform's own clients connect nothing: no agent was set up.- if context.client_name in ("overmind-transfer", "overmind assistant"):+ if context.client_name == "overmind-transfer" or actor(context.client_name)[0] == "overmind":returnactor_kind, actor_name = connection_actor(context)ActivityClient.objects.get_or_create(@@ -291,6 +291,14 @@ def mcp_succeeded(name, definition, output, context):**attribution,)return+ if name in {"save_dataset_pipeline", "run_dataset_pipeline"}:+ datasets = [item for item in output_assets(output) if item["kind"] == "dataset"]+ if len(datasets) == 1:+ assets = datasets+ if context.experiment is not None:+ assets.append(asset("experiment", context.experiment.pk, context.experiment.name))+ preparing(project_id, datasets[0]["id"], assets, **attribution)+ returnif name == "cancel_finetune":event = Activity.objects.filter(key=f"cancel-training:{output['id']}", project_id=project_id@@ -342,12 +350,6 @@ def mcp_succeeded(name, definition, output, context):action = "Started training run"elif name == "prepare_training_data":action = "Requested training data preparation for"- if name == "run_dataset_pipeline":- action = (- "Requested a transformation preview for"- if (output.get("run") or {}).get("mode") == "preview"- else "Requested a transformation of"- )record(key=f"mcp-{'cancel' if cancelling else 'task'}:{project_id}:{job['kind']}:{job['id']}",project_id=project_id,@@ -385,9 +387,7 @@ def mcp_succeeded(name, definition, output, context):key=f"mcp-change:{project_id}:{name}:{digest}",project_id=project_id,kind="asset_changed",- action="Saved a transformation for"- if name == "save_dataset_pipeline"- else action_label(name),+ action=action_label(name),assets=output_assets(output),**attribution,)@@ -503,6 +503,82 @@ def repository_synced(project, snapshot, capabilities):)+def _preparation_key(project_id, dataset_id):+ # A dataset's preparations follow one another: the next one opens once the last published.+ published = Activity.objects.filter(+ project_id=project_id,+ task_kind="dataset_preparation",+ task_id=str(dataset_id),+ status="completed",+ ).count()+ return f"preparation:{dataset_id}:{published}"+++def preparing(project_id, dataset_id, assets, **attribution):+ """One row for a dataset's preparation, from its first saved script or run to its+ publication: later scripts, previews and runs move the same row."""+ record(+ key=_preparation_key(project_id, dataset_id),+ project_id=project_id,+ kind="task_requested",+ action="Preparing",+ task_kind="dataset_preparation",+ task_id=dataset_id,+ status="running",+ assets=assets,+ **attribution,+ )+ update_task(project_id, "dataset_preparation", dataset_id, "running")+++def prepared(dataset):+ """A publication completes the preparation's row, or records one when none was open."""+ event = record(+ key=_preparation_key(dataset.project_id, dataset.pk),+ project_id=dataset.project_id,+ kind="preparation_published",+ action="Published dataset preparation",+ task_kind="dataset_preparation",+ task_id=dataset.pk,+ assets=[asset("dataset", dataset.pk, dataset.name)],+ )+ if (+ Activity.objects.filter(pk=event.pk)+ .exclude(kind="preparation_published", status="completed")+ .update(+ kind="preparation_published",+ action="Published dataset preparation",+ status="completed",+ updated_at=timezone.now(),+ )+ ):+ changed(dataset.project_id)+++def experiment_run_started(run, user):+ actor_kind, actor_name = (+ actor("overmind assistant")+ if run.origin == "assistant"+ else ("overmind", "Trigger")+ if run.origin == "trigger"+ else ("overmind", "Overmind")+ )+ # The key MCP's start_experiment_run records under, so a coding agent's start relabels it.+ record(+ key=f"mcp-task:{run.experiment.project_id}:experiment_run:{run.pk}",+ project_id=run.experiment.project_id,+ user_id=getattr(user, "pk", None),+ kind="task_requested",+ action="Started a run of",+ task_kind="experiment_run",+ task_id=run.pk,+ status="running",+ assets=[asset("experiment", run.experiment.pk, run.experiment.name)],+ actor_kind=actor_kind,+ actor_name=actor_name,+ )++def source_ready(dataset, cell_id, user=None):record(key=f"source-ready:{cell_id}",@@ -523,25 +599,11 @@ def feed(query, *, offset=0, limit=25):query = feed_events(query, observed_at)count = query.count()events = list(query[offset : offset + limit])- runs = dict(- DatasetPipelineRun.objects.filter(- pk__in=[event.task_id for event in events if event.task_kind == "dataset_pipeline"],- ).values_list("pk", "dataset_id")- )sequences = {}for event in events:- dataset_id = (- runs.get(UUID(event.task_id)) if event.task_kind == "dataset_pipeline" else None- )- if (- event.kind in {"source_uploaded", "source_ready"}- or event.action- in {- "Saved a transformation for",- "Saved dataset pipeline",- "Published dataset preparation",- }- or event.key.startswith("dataset-created:")+ dataset_id = event.task_id if event.task_kind == "dataset_preparation" else None+ if event.kind in {"source_uploaded", "source_ready"} or event.key.startswith(+ "dataset-created:"):dataset_ids = [item["id"] for item in event.assets if item["kind"] == "dataset"]if len(dataset_ids) == 1:diff --git a/overbae/services/assistant/presentation.py b/overbae/services/assistant/presentation.pyindex b9d658a0..d9012c86 100644--- a/overbae/services/assistant/presentation.py+++ b/overbae/services/assistant/presentation.py@@ -260,12 +260,17 @@ def _image(name: str, raw: bytes) -> str:return f"{hashlib.sha256(raw).hexdigest()}.{kind}"+# Components that end the turn until the person answers; the review card of a drafted eval+# set is built by `draft_eval_set`, never written by the model.+ASKS = ("Question", "Choices", "EvalSetDraft")++def asks(document: dict) -> bool:"""Whether a stored document puts a question to the user."""def found(node) -> bool:if isinstance(node, dict):- return node.get("type") in ("Question", "Choices") or any(map(found, node.values()))+ return node.get("type") in ASKS or any(map(found, node.values()))return isinstance(node, list) and any(map(found, node))return found(document["root"])diff --git a/overbae/services/assistant/prompt.py b/overbae/services/assistant/prompt.pyindex 3cd04145..8cf8c2c8 100644--- a/overbae/services/assistant/prompt.py+++ b/overbae/services/assistant/prompt.py@@ -123,6 +123,9 @@ needs (`problems`) and the newest runs with each stage's state.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.+- A Suite stage scores with an eval set. When the experiment needs criteria, draft them with+ `draft_eval_set`; a person edits and saves it. Saving makes a new set, so a run before it+ stays comparable: bind the id their reply names. You never save a set yourself.- The final holdout of a Partition stage is read once, by a Qualify stage that nothing trainsor selects after. Every other tool refuses its rows.- Runs start training, evaluation, inference and data jobs that cost credits. Start one whendiff --git a/overbae/services/assistant/tools.py b/overbae/services/assistant/tools.pyindex 4747b620..68eb2576 100644--- a/overbae/services/assistant/tools.py+++ b/overbae/services/assistant/tools.py@@ -7,6 +7,7 @@ import ioimport jsonimport reimport time+import uuidimport zipfilefrom collections.abc import Callablefrom copy import deepcopy@@ -17,16 +18,26 @@ from pathlib import Pathfrom asgiref.sync import async_to_syncfrom django.conf import settingsfrom django.db.models import Q+from pydantic import BaseModel, ConfigDict, Field, ValidationErrorfrom overbae.core.errors import InputValidationError-from overbae.models import AssistantThread, Cell, DatasetPipeline, DatasetPipelineRun-from overbae.services import workspaces+from overbae.models import (+ AssistantEvent,+ AssistantInput,+ AssistantThread,+ Cell,+ DatasetPipeline,+ DatasetPipelineRun,+ EvalSet,+)+from overbae.services import eval_sets, workspacesfrom overbae.services.assistant import presentationfrom overbae.services.assistant.threads import data_namefrom 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+from overbae.services.mcp.contracts.evaluations import EvalCriterionContractCATALOG_TOOLS = ("list_datasets",@@ -125,6 +136,20 @@ OWN_TOOLS = {}+class EvalSetDraft(BaseModel):+ """Draft an eval set for the person to review. Nothing is saved: they edit the criteria,+ then save or reject it, and their reply says which, with the new set's id. To change a+ set, pass its id as `eval_set`: saving makes a new set, so earlier runs stay comparable.+ Draft only in reply to a person's message."""++ model_config = ConfigDict(extra="forbid")++ name: str = Field(min_length=1, max_length=255)+ description: str = Field(default="", max_length=2000)+ criteria: list[EvalCriterionContract] = Field(min_length=1, max_length=200)+ eval_set: uuid.UUID | None = None++@dataclass(frozen=True)class Outcome:ok: bool@@ -153,6 +178,9 @@ def specifications() -> list[dict]:schema["required"] = [key for key in schema.get("required", []) if key not in supplied]specs.append(_function(name, definition.description, schema))specs += [_function(name, text, schema) for name, (text, schema) in OWN_TOOLS.items()]+ specs.append(+ _function("draft_eval_set", EvalSetDraft.__doc__, EvalSetDraft.model_json_schema())+ )specs.append(_function("present",@@ -224,6 +252,7 @@ def _invoke(turn: Turn, name, arguments):token=PlatformCredential(thread.project_id),project=thread.project,client_name=ASSISTANT,+ experiment=thread.experiment,)return async_to_sync(CATALOG.invoke)(name, arguments, context)@@ -448,7 +477,63 @@ def _present(turn: Turn, arguments) -> Outcome:return Outcome(True, {"shown": True}, presentation=document, asks=asks)-_OWN = {"run_python": _run_python, "run_pipeline": _run_pipeline, "present": _present}+def _draft_eval_set(turn: Turn, arguments) -> Outcome:+ thread = turn.thread+ origin = (+ thread.events.filter(kind=AssistantEvent.Kind.USER)+ .order_by("-sequence")+ .values_list("payload__origin", flat=True)+ .first()+ )+ if origin != AssistantInput.Origin.USER:+ raise InputValidationError(+ "A person reviews a drafted eval set: draft one in reply to a person's message."+ )+ try:+ draft = EvalSetDraft.model_validate(arguments)+ except ValidationError as exc:+ raise InputValidationError(str(exc)) from None+ criteria = eval_sets.clean_criteria([c.model_dump(exclude_none=True) for c in draft.criteria])+ amends = None+ if draft.eval_set is not None:+ amends = EvalSet.objects.filter(project=thread.project, pk=draft.eval_set).first()+ if amends is None:+ raise InputValidationError("The eval set to change is not in this project.")+ capability = amends.capability_id if amends else None+ if EvalSet.objects.filter(+ project=thread.project, capability_id=capability, name=draft.name+ ).exists():+ raise InputValidationError(f"An eval set named {draft.name} exists: choose another name.")+ document = {+ "root": {+ "type": "EvalSetDraft",+ "id": "eval_set",+ "project": str(thread.project_id),+ "name": draft.name,+ "description": draft.description,+ "criteria": criteria,+ "capability": str(capability) if capability else None,+ "amends": {+ "id": str(amends.pk),+ "name": amends.name,+ "criteria": amends.matrix_snapshot(),+ }+ if amends+ else None,+ },+ "data": {},+ "images": {},+ "cells": {},+ }+ return Outcome(True, {"shown": True}, presentation=document, asks=True)+++_OWN = {+ "run_python": _run_python,+ "run_pipeline": _run_pipeline,+ "present": _present,+ "draft_eval_set": _draft_eval_set,+}def _compact(value):diff --git a/overbae/services/datasets/analytics.py b/overbae/services/datasets/analytics.pyindex 7840eb3a..845ce46b 100644--- a/overbae/services/datasets/analytics.py+++ b/overbae/services/datasets/analytics.py@@ -1,15 +1,29 @@import hashlibimport jsonimport math+import re+from collections import Counterfrom django.utils import timezonefrom overbae.services.datasets.examples import decode, missing-VERSION = 2+VERSION = 3FAMILY_LIMIT = 8OPTION_LIMIT = 32FIELD_LIMIT = 100+# An input value is evidence about the label once five rows share it; one input that gives+# the label on 99% of those rows, when they are half the family, nearly determines it.+SHARED_ROWS = 5+DETERMINED_SHARE = 0.99+COVERED_SHARE = 0.5+# Distinct values counted per input and family; an input with more is not assessed.+VALUE_LIMIT = 1_000+# An input names the label when, on 98% of at least 50 judged rows, its text holds a word+# of the row's own option and none of another option's.+NAMED_SHARE = 0.98+NAMED_ROWS = 50+WORD = re.compile(r"[a-z]{4,}")def digest(value):@@ -25,6 +39,7 @@ class Analytics:self.structured_input_rows = self.weighted_rows = 0self.families = {}self.keys = {}+ self.leaks = {}def observe(self, decision, *, valid):self.rows += 1@@ -89,7 +104,79 @@ class Analytics:for index, probability in enumerate(probabilities):family["target_mass"][index] += weight * probabilityif family["counts"] is not None:- family["counts"][probabilities.index(1)] += 1+ label = probabilities.index(1)+ family["counts"][label] += 1+ self._observe_leaks(key, family, label, state)++ def _observe_leaks(self, key, family, label, state):+ leak = self.leaks.get(key)+ if leak is None:+ words = [set(WORD.findall(option.lower())) for option in family["labels"]]+ shared = {w for w, uses in Counter(w for f in words for w in f).items() if uses > 1}+ words = [found - shared for found in words]+ leak = self.leaks[key] = {+ "own": words,+ "others": [set().union(*words[:i], *words[i + 1 :]) for i in range(len(words))],+ "judged": 0,+ "judged_labels": set(),+ "named": Counter(),+ "values": {},+ "overflow": set(),+ }+ values = state if isinstance(state, dict) else {"state": state}+ own, others = leak["own"][label], leak["others"][label]+ if own:+ leak["judged"] += 1+ leak["judged_labels"].add(label)+ for name, value in values.items():+ if isinstance(value, str):+ found = set(WORD.findall(value.lower()))+ if found & own and not found & others:+ leak["named"][str(name)] += 1+ if not isinstance(state, dict):+ return+ for name, value in state.items():+ name = str(name)+ if missing(value) or name in leak["overflow"] or name not in self.fields:+ continue+ counted = leak["values"].setdefault(name, {})+ text = json.dumps(value, sort_keys=True, default=str)+ identity = text if len(text) <= 64 else hashlib.sha256(text.encode()).hexdigest()+ if identity not in counted and len(counted) >= VALUE_LIMIT:+ leak["overflow"].add(name)+ del leak["values"][name]+ continue+ counted.setdefault(identity, Counter())[label] += 1++ def _leak_findings(self):+ determined, named, overflow = [], [], set()+ assessed = judged = False+ for key, leak in self.leaks.items():+ family = self.families[key]+ if sum(1 for count in family["counts"] if count) < 2:+ continue+ overflow |= leak["overflow"]+ for name, counted in leak["values"].items():+ assessed = True+ shared = [labels for labels in counted.values() if labels.total() >= SHARED_ROWS]+ covered = sum(labels.total() for labels in shared)+ agreeing = sum(max(labels.values()) for labels in shared)+ if (+ covered >= COVERED_SHARE * family["rows"]+ and agreeing >= DETERMINED_SHARE * covered+ ):+ determined.append(+ {"family": key, "field": name[:120], "rows": covered, "agreeing": agreeing}+ )+ if leak["judged"] < NAMED_ROWS or len(leak["judged_labels"]) < 2:+ continue+ judged = True+ for name, count in sorted(leak["named"].items()):+ if count >= NAMED_SHARE * leak["judged"]:+ named.append(+ {"family": key, "field": name[:120], "rows": leak["judged"], "named": count}+ )+ return determined, named, sorted(overflow), assessed, judgeddef report(self):families = [dict(family) for family in self.families.values()]@@ -122,6 +209,15 @@ class Analytics:if "first" in field and not field["varies"]:constants.append(name[:120])+ determined, named, overflow, assessed, judged = self._leak_findings()+ labelled = any(sum(1 for count in f["counts"] if count) > 1 for f in gold)+ unassessed = (+ f" {len(overflow):,} inputs with more than {VALUE_LIMIT:,} distinct values were not "+ "assessed."+ if overflow+ else ""+ )+def check(identifier, title, status, summary, metrics=None):return {"id": identifier,@@ -273,6 +369,64 @@ class Analytics:"field_limit": FIELD_LIMIT,},),+ check(+ "leakage.input_determines_label",+ "Label given by one input",+ "warning"+ if determined+ else "pass"+ if assessed+ else "not_checked"+ if labelled+ else "not_applicable",+ " ".join(+ f"{item['field']} alone gives the label on {item['agreeing']:,} of the "+ f"{item['rows']:,} rows that share its value with at least "+ f"{SHARED_ROWS - 1} others."+ for item in determined[:3]+ )+ + (f" And {len(determined) - 3} more inputs." if len(determined) > 3 else "")+ + unassessed+ if determined+ else "No single input gives the label on 99% of the rows that share its value "+ f"with at least {SHARED_ROWS - 1} others.{unassessed}"+ if assessed+ else "No JSON input fields were available to compare with the labels."+ if labelled+ else "Needs at least two observed labels.",+ {+ "shared_rows": SHARED_ROWS,+ "determined_share": DETERMINED_SHARE,+ "covered_share": COVERED_SHARE,+ "findings": determined[:20],+ "unassessed_fields": overflow[:20],+ },+ ),+ check(+ "leakage.label_in_input",+ "Label named in the input",+ "warning"+ if named+ else "pass"+ if judged+ else "not_checked"+ if labelled+ else "not_applicable",+ " ".join(+ f"{item['field']} names the row's own label on {item['named']:,} of "+ f"{item['rows']:,} rows."+ for item in named[:3]+ )+ + (f" And {len(named) - 3} more inputs." if len(named) > 3 else "")+ if named+ else "No input names the row's own label on 98% of the rows."+ if judged+ else f"Fewer than {NAMED_ROWS} rows have a label with a word of 4 or more letters "+ "that no other label shares, so inputs were not searched for labels."+ if labelled+ else "Needs at least two observed labels.",+ {"named_share": NAMED_SHARE, "minimum_rows": NAMED_ROWS, "findings": named[:20]},+ ),check("leakage.cross_split","Duplicates and split leakage",diff --git a/overbae/services/datasets/files.py b/overbae/services/datasets/files.pyindex dcf39ff1..bd27d92a 100644--- a/overbae/services/datasets/files.py+++ b/overbae/services/datasets/files.py@@ -26,17 +26,26 @@ import pyarrow as paimport pyarrow.parquet as pqfrom overbae.core.errors import InputValidationError-from overbae.services.datasets import documents+from overbae.services.datasets import documents, spreadsheetslogger = logging.getLogger(__name__)-ALLOWED_SUFFIXES = (".csv", ".tsv", ".json", ".jsonl", ".ndjson", ".parquet", *documents.SUFFIXES)+ALLOWED_SUFFIXES = (+ ".csv",+ ".tsv",+ ".json",+ ".jsonl",+ ".ndjson",+ ".parquet",+ ".xlsx",+ *documents.SUFFIXES,+)CHUNK_BYTES = 8 * 1024 * 1024MAX_UPLOAD_BYTES = 2 * 1024 * 1024 * 1024JSON_ARRAY_MAX_BYTES = 256 * 1024 * 1024_SAFE_NAME = re.compile(r"[^A-Za-z0-9._-]+")UNSUPPORTED = (- "Use a CSV, TSV, JSON, JSONL, Parquet, PDF, DOCX, Markdown, text, PNG, JPEG or WebP file."+ "Use a CSV, TSV, JSON, JSONL, Parquet, XLSX, PDF, DOCX, Markdown, text, PNG, JPEG or WebP file.")# A transcript cell is far longer than the csv module's 128 KB default.@@ -104,7 +113,7 @@ def _iter_delimited(fh: io.TextIOBase, delimiter: str) -> Iterator[dict[str, Anyheader = next(reader, None)if not header:raise FileError("The file has no header row.")- header = _clean_names(header)+ header = clean_names(header)for cells in reader:if not cells:continue@@ -118,7 +127,7 @@ def _iter_delimited(fh: io.TextIOBase, delimiter: str) -> Iterator[dict[str, Anyraise FileError(f"Row {reader.line_num} is not valid delimited text.") from exc-def _clean_names(names: list[Any]) -> list[str]:+def clean_names(names: list[Any]) -> list[str]:"""Names are stripped, a blank name becomes ``column_N``, and two namesthat differ only by case are refused: the frame store matches namescase-insensitively, so one of them would be lost."""@@ -133,7 +142,7 @@ def _clean_names(names: list[Any]) -> list[str]:def _normalise_names(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:raw = list(dict.fromkeys(name for row in rows for name in row))- names = dict(zip(raw, _clean_names(raw), strict=True))+ names = dict(zip(raw, clean_names(raw), strict=True))if all(k == v for k, v in names.items()):return rowsreturn [{names[k]: v for k, v in row.items()} for row in rows]@@ -199,9 +208,16 @@ def _text_rows(fh: io.TextIOBase, name: str) -> list[dict[str, Any]]:def iter_file_rows(- path: Path, *, filename: str, json_rows_field: str | None = None+ path: Path, *, filename: str, json_rows_field: str | None = None, sheet: str | None = None) -> Iterator[dict[str, Any]]:+ """``sheet`` names the one sheet of a workbook to read."""name = (filename or "").lower()+ if name.endswith(".xlsx"):+ try:+ yield from spreadsheets.rows(path, sheet or "")+ return+ except spreadsheets.SpreadsheetError as exc:+ raise FileError(exc.detail) from excif name.endswith(documents.SUFFIXES):try:return documents.extract(path, filename=filename)[0]@@ -230,20 +246,29 @@ def iter_file_rows(class FileRows:- def __init__(self, path: Path, *, filename: str, json_rows_field: str | None = None):- self.path, self.filename = path, filename+ def __init__(+ self,+ path: Path,+ *,+ filename: str,+ json_rows_field: str | None = None,+ sheet: str | None = None,+ ):+ self.path, self.filename, self.sheet = path, filename, sheetself.json_rows_field = json_rows_fieldself.count = 0names = {}numeric = {}delimited = filename.lower().removesuffix(".gz").endswith((".csv", ".tsv"))- for row in iter_file_rows(path, filename=filename, json_rows_field=json_rows_field):+ for row in iter_file_rows(+ path, filename=filename, json_rows_field=json_rows_field, sheet=sheet+ ):self.count += 1for key, value in row.items():names.setdefault(key, None)if delimited and value not in (None, ""):numeric.setdefault(key, set()).add(type(_number(value)))- self.names = dict(zip(names, _clean_names(list(names)), strict=True))+ self.names = dict(zip(names, clean_names(list(names)), strict=True))self.numeric = {k for k, types in numeric.items() if types in ({int}, {float})}def __len__(self):@@ -251,7 +276,10 @@ class FileRows:def __iter__(self):for row in iter_file_rows(- self.path, filename=self.filename, json_rows_field=self.json_rows_field+ self.path,+ filename=self.filename,+ json_rows_field=self.json_rows_field,+ sheet=self.sheet,):yield {self.names[key]: (_number(value) if value not in (None, "") else None)@@ -278,7 +306,11 @@ def inspect_upload(_inspection_path(upload_id).write_text(json.dumps(record), encoding="utf-8")return {"filename": filename, "bytes": size, "rows": None}try:- if bare.endswith(".parquet"):+ if bare.endswith(".xlsx"):+ rows = sum(+ 1 for sheet in spreadsheets.sheets(path) for _ in spreadsheets.rows(path, sheet)+ )+ elif bare.endswith(".parquet"):rows = pq.ParquetFile(path).metadata.num_rowselse:if bare.endswith(".json") and size > JSON_ARRAY_MAX_BYTES:@@ -292,6 +324,8 @@ def inspect_upload()except FileError:raise+ except spreadsheets.SpreadsheetError as exc:+ raise FileError(exc.detail) from excexcept UnicodeDecodeError as exc:raise FileError("The file is not UTF-8. Save it as UTF-8 and upload it again.") from excexcept (gzip.BadGzipFile, EOFError) as exc:@@ -359,8 +393,8 @@ def safe_filename(name: str) -> str:def begin_upload(filename: str, *, upload_id=None, managed=False) -> tuple[str, str]:safe = safe_filename(filename)lowered = safe.lower()- if lowered.endswith(".parquet.gz"):- raise FileError("Parquet is already compressed. Upload the .parquet file.")+ if lowered.endswith((".parquet.gz", ".xlsx.gz")):+ raise FileError("Parquet and XLSX are already compressed. Upload them without gzip.")if lowered.endswith(".gz") and lowered.removesuffix(".gz").endswith(documents.SUFFIXES):raise FileError("Upload documents without gzip compression.")if not lowered.removesuffix(".gz").endswith(ALLOWED_SUFFIXES):@@ -409,6 +443,8 @@ def upload_received(upload_id: Any) -> int:def upload_byte_limit(filename: str) -> int:+ if filename.lower().endswith(".xlsx"):+ return spreadsheets.MAX_BYTESreturn (documents.MAX_BYTES if filename.lower().endswith(documents.SUFFIXES) else MAX_UPLOAD_BYTES)diff --git a/overbae/services/datasets/imports.py b/overbae/services/datasets/imports.pyindex 65b6f6b1..5e2f0ae6 100644--- a/overbae/services/datasets/imports.py+++ b/overbae/services/datasets/imports.py@@ -566,11 +566,11 @@ def _read_parts(run, targets, progress):"ocr_languages": source.get("ocr_languages", []),}if source.get("uploads"):- read = landing.read_uploads(source["uploads"], on_progress=progress, **extraction)+ groups = landing.read_uploads(source["uploads"], on_progress=progress, **extraction)if source.get("pasted"):- read = replace(read, spec={"pasted": True})+ groups = [replace(landing.single(groups), spec={"pasted": True})]elif source.get("upload_id"):- read = landing.read_file(+ groups = landing.read_file(files.upload_data_path(source["upload_id"]),filename=source.get("filename") or files.upload_filename(source["upload_id"]),json_rows_field=source.get("json_rows_field"),@@ -578,18 +578,20 @@ def _read_parts(run, targets, progress):**extraction,)elif source.get("traces") is not None:- read = landing.read_traces(- run.dataset.project_id,- source["traces"],- on_progress=lambda done: events.publish(- run.dataset_id,- {- "dataset_id": str(run.dataset_id),- "type": "land_progress",- "traces": done,- },- ),- )+ groups = [+ landing.read_traces(+ run.dataset.project_id,+ source["traces"],+ on_progress=lambda done: events.publish(+ run.dataset_id,+ {+ "dataset_id": str(run.dataset_id),+ "type": "land_progress",+ "traces": done,+ },+ ),+ )+ ]elif source.get("llm_calls") is not None:read = llm_calls.read(run.dataset.project_id,@@ -638,7 +640,8 @@ def _read_parts(run, targets, progress):else:raise landing.LandError("No saved source is available.")if not split:- return [(targets[0], read)], Dataset.State.IDLE+ return _column_groups(run, targets[0], groups), Dataset.State.IDLE+ read = landing.single(groups)cut = {"eval_percent": int(split["eval_percent"]),"position": split["position"],@@ -661,6 +664,38 @@ def _read_parts(run, targets, progress):], Dataset.State.IDLE+def _column_groups(run, primary, groups):+ """The first set of columns lands in ``primary``; each other set lands in a dataset of+ its own, saved only when the landing publishes. Every landed dataset lists them all."""+ if len(groups) == 1:+ return [(primary, groups[0])]+ targets = [primary]+ for index, group in enumerate(groups[1:], start=1):+ first = group.spec["files"][0]+ name = first["filename"].removesuffix(".gz").rsplit(".", 1)[0] or "Untitled dataset"+ targets.append(+ Dataset(+ id=uuid.uuid5(run.pk, f"columns:{index}"),+ project_id=primary.project_id,+ name=(f"{name} · {first['sheet']}" if "sheet" in first else name)[:255],+ capability_id=primary.capability_id,+ intent=primary.intent,+ train_format=primary.train_format,+ ocr_languages=primary.ocr_languages,+ created_by_id=primary.created_by_id,+ state=Dataset.State.LANDING,+ )+ )+ listed = [+ {"dataset": str(target.pk), "files": group.spec["files"]}+ for target, group in zip(targets, groups, strict=True)+ ]+ return [+ (target, replace(group, spec={**group.spec, "column_groups": listed}))+ for target, group in zip(targets, groups, strict=True)+ ]++def execute(task_id, inputs):dataset = Dataset.objects.filter(pk=inputs["dataset_id"]).first()if dataset is None:@@ -705,6 +740,7 @@ def execute(task_id, inputs):events.publish(target.pk, {"type": "land_started", "dataset_id": str(target.pk)})progress = _landing_progress(run, targets)parts, state = _read_parts(run, targets, progress)+ saved = {target.pk for target in targets}prepared = [(target,@@ -731,6 +767,8 @@ def execute(task_id, inputs):with publication(claimed) as locked:rows = 0for target, result in prepared:+ if target.pk not in saved:+ target.save(force_insert=True)landing.publish(target, result, user=user)source_ready(target, result.cell_id, user)rows += result.cell_fields["rows"]diff --git a/overbae/services/datasets/land.py b/overbae/services/datasets/land.pyindex 76dc4084..2bcc9b65 100644--- a/overbae/services/datasets/land.py+++ b/overbae/services/datasets/land.py@@ -35,6 +35,7 @@ from overbae.services.datasets import (operations,paths,selection,+ spreadsheets,store,)from overbae.services.datasets.partition import split_rows@@ -142,7 +143,8 @@ def prepare(dataset.project_id, pd.DataFrame.from_records(store.head(path, 500))),}- measured = Dataset.objects.select_related("capability").get(pk=dataset.pk)+ # A dataset a landing splits off by columns is saved only when it publishes.+ measured = Dataset.objects.select_related("capability").filter(pk=dataset.pk).first() or datasetif infer_capability and measured.capability_id is None and fields["capability_rank"]:best = fields["capability_rank"][0]if best["score"] > 0:@@ -234,8 +236,19 @@ def commit(dataset, landing, *, user=None, state=Dataset.State.IDLE, infer_capabreturn dataset-def read_file(path: Path, **options) -> Landing:- return _require_rows(_read_one(path, **options))+def read_file(path: Path, **options) -> list[Landing]:+ """The file's rows, one landing per sheet of a workbook, else one."""+ return [_require_rows(group) for group in _group(_read_one(path, **options))]+++def single(groups: list[Landing]) -> Landing:+ """The one column set a split or an added batch needs."""+ if len(groups) > 1:+ raise LandError(+ f"These files hold {len(groups)} different sets of columns. "+ "Add files that share one set of columns."+ )+ return groups[0]def _require_rows(landing: Landing) -> Landing:@@ -259,7 +272,8 @@ def _read_one(json_rows_field: str | None = None,project_id=None,ocr_languages=None,-) -> Landing:+) -> list[Landing]:+ """The file's rows: one part per sheet of a workbook, else one part."""spool = Nonedef progress(detail):@@ -283,7 +297,12 @@ def _read_one(with cached.open("w") as output:for row in extracted:output.write(json.dumps(row) + "\n")- rows = files.FileRows(cached, filename="extracted.jsonl")+ parts = [(files.FileRows(cached, filename="extracted.jsonl"), extraction)]+ elif filename.lower().endswith(".xlsx"):+ parts = [+ (files.FileRows(path, filename=filename, sheet=sheet), {"sheet": sheet})+ for sheet in spreadsheets.sheets(path)+ ]else:rows = files.FileRows(path, filename=filename, json_rows_field=json_rows_field)extraction = (@@ -291,25 +310,36 @@ def _read_one(if json_rows_fieldelse {})- except (files.FileError, documents.DocumentError) as exc:+ parts = [(rows, extraction)]+ except (files.FileError, documents.DocumentError, spreadsheets.SpreadsheetError) as exc:progress({"stage": "failed"})raise LandError(str(exc), code=getattr(exc, "code", "import_failed")) from exc- if not rows and extraction.get("status") != "no_text":+ if not any(len(rows) for rows, _ in parts) and not any(+ extraction.get("status") == "no_text" for _, extraction in parts+ ):raise LandError("The file has no rows.")identity = store.file_sha256(path)- artifact = {- "id": identity,- "sha256": identity,- "filename": filename,- "bytes": files.stored_stat(path).st_size,- "rows": len(rows),- "extraction": extraction,- "staged_path": str(path),- }- return Landing(- SourceRows(rows, spool),- spec={"filename": filename, "sources": [artifact]},- )+ size = files.stored_stat(path).st_size+ return [+ Landing(+ SourceRows(rows, spool),+ spec={+ "filename": filename,+ "sources": [+ {+ "id": identity,+ "sha256": identity,+ "filename": filename,+ "bytes": size,+ "rows": len(rows),+ "extraction": extraction,+ "staged_path": str(path),+ }+ ],+ },+ )+ for rows, extraction in parts+ ]@dataclass@@ -325,6 +355,10 @@ class SourceRows:def __iter__(self):return iter(self.source)+ @property+ def columns(self) -> frozenset[str]:+ return frozenset(name.lower() for name in self.source.names.values())+@dataclassclass UploadRows:@@ -338,15 +372,60 @@ class UploadRows:yield from source+def _group(parts: list[Landing]) -> list[Landing]:+ """Parts with the same column names land together, in the order they came; each sheet+ of a workbook lands alone. Names compare as the store does, ignoring case; types do not+ split a group, so a column of integers in one file and decimals in another stays one. A+ document with no text has no columns: its source is recorded with the first group."""+ groups: dict[Any, list[Landing]] = {}+ empty = []+ for index, part in enumerate(parts):+ if not len(part.rows):+ empty.append(part)+ continue+ sheet = part.spec["sources"][0]["extraction"].get("sheet")+ key = ("sheet", index) if sheet is not None else part.rows.columns+ groups.setdefault(key, []).append(part)+ if empty:+ first = next(iter(groups.values()), None)+ if first is None:+ groups[None] = empty+ else:+ first.extend(empty)+ landings = []+ for members in groups.values():+ sources = [source for part in members for source in part.spec["sources"]]+ landings.append(+ Landing(+ UploadRows([part.rows for part in members]),+ spec={+ "sources": sources,+ "files": [+ {+ **{k: item[k] for k in ("filename", "bytes", "rows")},+ **(+ {"sheet": item["extraction"]["sheet"]}+ if "sheet" in item["extraction"]+ else {}+ ),+ }+ for item in sources+ ],+ },+ )+ )+ return landings++def read_uploads(upload_ids: list[str],*,on_progress: Callable[[dict], None] | None = None,project_id=None,ocr_languages=None,-) -> Landing:+) -> list[Landing]:+ """The uploads' rows, one landing per set of columns (``_group``)."""parts = []- sources = []for index, upload_id in enumerate(upload_ids):filename = files.upload_filename(upload_id)path = files.upload_data_path(upload_id)@@ -357,27 +436,19 @@ def read_uploads(if on_progress:on_progress({"completed": index, "total": len(upload_ids), **detail})- part = _read_one(- path,- filename=filename,- on_progress=progress,- project_id=project_id,- ocr_languages=ocr_languages,- json_rows_field=(files.inspection(upload_id) or {}).get("json_rows_field"),+ parts.extend(+ _read_one(+ path,+ filename=filename,+ on_progress=progress,+ project_id=project_id,+ ocr_languages=ocr_languages,+ json_rows_field=(files.inspection(upload_id) or {}).get("json_rows_field"),+ ))- sources.extend(part.spec["sources"])- parts.append(part.rows)if on_progress:on_progress({"completed": len(upload_ids), "total": len(upload_ids), "stage": "merging"})- return _require_rows(- Landing(- UploadRows(parts),- spec={- "sources": sources,- "files": [{k: item[k] for k in ("filename", "bytes", "rows")} for item in sources],- },- )- )+ return [_require_rows(group) for group in _group(parts)]def read_rows(rows: list[dict[str, Any]], *, spec: dict[str, Any] | None = None) -> Landing:diff --git a/overbae/services/datasets/list_activity.py b/overbae/services/datasets/list_activity.pyindex db790fc5..2afa99d3 100644--- a/overbae/services/datasets/list_activity.py+++ b/overbae/services/datasets/list_activity.py@@ -48,18 +48,21 @@ def current_work(datasets):dataset_id__in=ids, state__in=["queued", "running"]).order_by("created_at"))+ # Oldest first, so each dataset keeps its newest preparation's actor.actors = dict(Activity.objects.filter(project_id__in={dataset.project_id for dataset in datasets},- task_kind="dataset_pipeline",- task_id__in=[str(run.pk) for run in runs],- ).values_list("task_id", "actor_kind")+ task_kind="dataset_preparation",+ task_id__in=[str(run.dataset_id) for run in runs],+ )+ .order_by("created_at")+ .values_list("task_id", "actor_kind"))for run in runs:work[str(run.dataset_id)] = {**run_progress(run),"status": run.state,- "actor_kind": actors.get(str(run.pk)),+ "actor_kind": actors.get(str(run.dataset_id)),}for dataset in datasets:landing = (dataset.source_spec or {}).get("landing_progress") or {}diff --git a/overbae/services/datasets/spreadsheets.py b/overbae/services/datasets/spreadsheets.pynew file mode 100644index 00000000..5798f23c--- /dev/null+++ b/overbae/services/datasets/spreadsheets.py@@ -0,0 +1,118 @@+"""XLSX workbooks → rows, one sheet at a time.++The first row of a sheet is its header. Formulas stay their source text, never a computed+value; dates become ISO text and durations seconds. Each row's ``_overmind_evidence``+names its sheet and row and the cells whose stored value is a formula, an error, a date or+a duration.+"""++from __future__ import annotations++import datetime as dt+from collections.abc import Iterator+from contextlib import contextmanager+from pathlib import Path+from typing import Any+from zipfile import BadZipFile, ZipFile++from openpyxl import load_workbook+from openpyxl.utils.exceptions import InvalidFileException++from overbae.core.errors import InputValidationError+from overbae.services.datasets.store import EVIDENCE++MAX_BYTES = 100 * 1024**2+MAX_EXPANDED_BYTES = 512 * 1024**2+_NONLITERAL = {"f": "formula", "e": "error"}+++class SpreadsheetError(InputValidationError):+ pass+++@contextmanager+def _workbook(path: Path):+ try:+ with ZipFile(path) as archive:+ if sum(member.file_size for member in archive.infolist()) > MAX_EXPANDED_BYTES:+ raise SpreadsheetError("The workbook expands to more than 512 MiB.")+ # Staged uploads have no extension, which load_workbook needs for a path.+ with path.open("rb") as stream:+ workbook = load_workbook(stream, read_only=True, data_only=False, keep_links=False)+ try:+ yield workbook+ finally:+ workbook.close()+ except SpreadsheetError:+ raise+ except (BadZipFile, InvalidFileException, OSError, ValueError, KeyError, SyntaxError) as exc:+ raise SpreadsheetError("The file is not a readable XLSX workbook.") from exc+++def _header(sheet: str, cells) -> list[str]:+ from overbae.services.datasets.files import (+ FileError,+ clean_names,+ ) # lazy: files imports this module++ values = [cell.value for cell in cells]+ while values and values[-1] is None:+ values.pop()+ if any(cell.data_type in _NONLITERAL for cell in cells[: len(values)]):+ raise SpreadsheetError(f"Sheet {sheet!r} has a formula or error in its header row.")+ names = ["" if value is None else str(value) for value in values]+ if any(name.strip().lower() == EVIDENCE for name in names):+ raise SpreadsheetError(f"Sheet {sheet!r} has a column named {EVIDENCE}. Rename it.")+ try:+ return clean_names(names)+ except FileError as exc:+ raise SpreadsheetError(f"Sheet {sheet!r}: {exc.detail}") from exc+++def _rows(worksheet) -> Iterator[tuple[int, tuple]]:+ worksheet.reset_dimensions()+ for number, cells in enumerate(worksheet.iter_rows(), start=1):+ if any(cell.value is not None for cell in cells):+ yield number, cells+++def sheets(path: Path) -> list[str]:+ """The sheets that hold a header and at least one row, in workbook order."""+ found = []+ with _workbook(path) as workbook:+ for worksheet in workbook:+ rows = _rows(worksheet)+ if next(rows, None) is not None and next(rows, None) is not None:+ found.append(worksheet.title)+ return found+++def rows(path: Path, sheet: str) -> Iterator[dict[str, Any]]:+ with _workbook(path) as workbook:+ if sheet not in workbook.sheetnames:+ raise SpreadsheetError(f"The workbook has no sheet {sheet!r}.")+ numbered = _rows(workbook[sheet])+ first = next(numbered, None)+ if first is None:+ return+ header = _header(sheet, first[1])+ for number, cells in numbered:+ if any(cell.value is not None for cell in cells[len(header) :]):+ raise SpreadsheetError(+ f"Sheet {sheet!r} row {number} has a value right of its last header cell."+ )+ record: dict[str, Any] = dict.fromkeys(header)+ kinds = {}+ for name, cell in zip(header, cells, strict=False):+ value = cell.value+ if isinstance(value, dt.timedelta):+ kinds[name] = "duration_seconds"+ value = value.total_seconds()+ elif isinstance(value, (dt.datetime, dt.date, dt.time)):+ kinds[name] = type(value).__name__+ value = value.isoformat()+ elif cell.data_type in _NONLITERAL:+ kinds[name] = _NONLITERAL[cell.data_type]+ record[name] = value+ record[EVIDENCE] = {"sheet": sheet, "row": number, "cells": kinds}+ yield recorddiff --git a/overbae/services/datasets/workbench.py b/overbae/services/datasets/workbench.pyindex df0db84d..e15e1d9b 100644--- a/overbae/services/datasets/workbench.py+++ b/overbae/services/datasets/workbench.py@@ -823,16 +823,7 @@ def execute(run_id, *, script_executor=None):updated_at=timezone.now(),**declared_intent(dataset, steps[-1].get("consumer")),)- activity.record(- key=f"mcp-task:{dataset.project_id}:dataset_pipeline:{run.pk}",- task_kind="dataset_pipeline",- task_id=run.pk,- project_id=dataset.project_id,- kind="preparation_published",- action="Published dataset preparation",- assets=[activity.asset("dataset", dataset.pk, dataset.name)],- )- activity.update_task(dataset.project_id, "dataset_pipeline", run.pk, "completed")+ activity.prepared(dataset)if binding:binding.checkpoint = run.specification["binding_checkpoint"]binding.error = ""@@ -972,6 +963,10 @@ def fail(run_id, error, *, expired_before=None, attempt=None):Dataset.objects.filter(pk=run.dataset_id).update(state=Dataset.State.IDLE, error="", updated_at=timezone.now())+ if run.mode != "preview":+ activity.update_task(+ run.dataset.project_id, "dataset_preparation", run.dataset_id, "failed"+ )transaction.on_commit(lambda: events.publish(run.dataset_id, {"type": "dataset_changed"}))diff --git a/overbae/services/decision_providers.py b/overbae/services/decision_providers.pyindex 057c8a63..cf4f4b41 100644--- a/overbae/services/decision_providers.py+++ b/overbae/services/decision_providers.py@@ -24,6 +24,8 @@ from overbae.models import BillingService, DecisionProviderRequest, FinetuningJofrom overbae.services import evaluation_inputsfrom overbae.services.billing_ledger import charge_llm_usage+MAX_INSTRUCTIONS = 8000+class SubmissionUnknownError(RuntimeError):pass@@ -96,8 +98,14 @@ def qualify_participants(project, selected):"job","model","served_model",+ "instructions",}:raise InputValidationError("Unknown participant fields")+ instructions = participant.get("instructions", "")+ if not isinstance(instructions, str) or len(instructions) > MAX_INSTRUCTIONS:+ raise InputValidationError(+ f"Participant instructions are text of at most {MAX_INSTRUCTIONS} characters"+ )key = participant.get("key", "")if (not isinstance(key, str)@@ -115,7 +123,10 @@ def qualify_participants(project, selected):or kind not in {"foundation", "trained", "external"}):raise InputValidationError("Choose a named foundation, trained or external participant")+ # A prompt variant is its own participant: the instructions are part of its identity.reference = {"key": key, "name": name, "kind": kind}+ if instructions:+ reference["instructions"] = instructionsif kind == "external":model = participant.get("model")served = participant.get("served_model", "")@@ -161,10 +172,11 @@ def qualify_participants(project, selected):return result-def question(request):+def question(request, instructions=""):decision_request(request)kind, options = request["kind"], request["options"]- result = {"type": kind, "instructions": request["question"]}+ text = f"{instructions}\n\n{request['question']}" if instructions else request["question"]+ result = {"type": kind, "instructions": text}if kind == "score":if len(options) > 10:raise InputValidationError(@@ -378,7 +390,7 @@ def external_step(plan, role, participant):body = {"model": participant.get("served_model") or participant["model"],"state": request["state"],- "questions": {"decision": question(request)},+ "questions": {"decision": question(request, participant.get("instructions", ""))},}futures[executor.submit(decisions.request_once, body)] = (record, request)errors = []diff --git a/overbae/services/eval_sets.py b/overbae/services/eval_sets.pynew file mode 100644index 00000000..eab2cacc--- /dev/null+++ b/overbae/services/eval_sets.py@@ -0,0 +1,46 @@+"""The rules a benchmark's own criteria follow, for REST, MCP and the assistant's draft."""++from overbae.core.errors import InputValidationError+from overbae.innermind import deterministic+from overbae.models import EvalMatrix++EXPECTATION_MAX_CHARS = 1_000+++def clean_criterion(criterion: dict) -> dict:+ """The criterion as stored; Python criteria keep no judge fields. The caller checks+ each field's type and length."""+ if criterion["type"] == EvalMatrix.Type.DETERMINISTIC:+ if problem := deterministic.audit(criterion["source"]):+ raise InputValidationError(problem)+ return {k: v for k, v in criterion.items() if k not in ("options", "output")}+ if len(criterion["source"]) > EXPECTATION_MAX_CHARS:+ raise InputValidationError(f"Question exceeds {EXPECTATION_MAX_CHARS} characters.")+ if "output" not in criterion:+ raise InputValidationError("Choose yes/no or multiple choice.")+ labels = [option["label"].strip() for option in criterion.get("options") or []]+ if not 2 <= len(set(labels)) == len(labels) <= 20 or not all(labels):+ raise InputValidationError("Provide 2–20 distinct answers.")+ if criterion["output"] == "yes_no" and labels != ["Yes", "No"]:+ raise InputValidationError("Yes/no answers are Yes and No.")+ return criterion+++def check_names(criteria: list[dict]) -> None:+ names = [criterion["name"] for criterion in criteria]+ if len(set(names)) != len(names):+ raise InputValidationError("Criterion names must be unique.")+++def clean_criteria(criteria: list[dict]) -> list[dict]:+ """Every rule at once, naming the criterion that breaks one."""+ if not criteria:+ raise InputValidationError("Add at least one criterion.")+ check_names(criteria)+ cleaned = []+ for criterion in criteria:+ try:+ cleaned.append(clean_criterion(criterion))+ except InputValidationError as exc:+ raise InputValidationError(f"{criterion['name']}: {exc.detail}") from None+ return cleaneddiff --git a/overbae/services/experiments/catalog.py b/overbae/services/experiments/catalog.pyindex fc8b4a08..c689b548 100644--- a/overbae/services/experiments/catalog.py+++ b/overbae/services/experiments/catalog.py@@ -67,6 +67,22 @@ def _text(title, default=None, description="", enum=None):return schema+# How a model answers when Evaluate generates with it; Qualify reads only the system prompt.+CANDIDATE = {+ "system_prompt": _text(+ "System prompt",+ description="Evaluate replaces the dataset's system prompt with it; Qualify puts it "+ "before each decision question.",+ ),+ "generation_strategy": _text(+ "Generation",+ enum=("replay", "single_completion"),+ description="Replay runs the recorded tool loop; single completion answers once.",+ ),+ "max_steps": _number("Steps, at most", None, 1, 100, "integer"),+ "reasoning_effort": _text("Reasoning effort", enum=("low", "medium", "high")),+}+PREDICATE = {"metric": _text("Metric", description="A metric the scores report, such as accuracy."),"op": _text("Comparison", ">=", enum=(">=", ">", "<=", "<", "==")),@@ -106,6 +122,7 @@ KINDS = {settings={"base_model": _text("Base model", description="A training catalogue model id."),"finetune": _uuid("Trained model", "A training job of this project."),+ **CANDIDATE,},),Kind(diff --git a/overbae/services/experiments/runs.py b/overbae/services/experiments/runs.pyindex 64d5b4ed..e0214092 100644--- a/overbae/services/experiments/runs.py+++ b/overbae/services/experiments/runs.py@@ -27,6 +27,7 @@ from overbae.models import (ExperimentRun,ExperimentStep,)+from overbae.services import activityfrom overbae.services.experiments import describe, records, stagesfrom overbae.services.experiments import document as flowfrom overbae.services.experiments.catalog import FLOWS, KINDS@@ -44,7 +45,6 @@ AGENT_RUNS = 3FAILED_JOBS = frozenset({"failed", "cancelled", "deleted", "submission_unknown"})INPUTS = frozenset({"data", "model", "suite"})CONTROL = frozenset({"condition", "join", "compare"})-EXPERIMENT_CLIENT = "overmind experiment"def _settings(project, document: dict, parameters: dict) -> dict[str, dict]:@@ -268,6 +268,7 @@ def start({"run": run.number, "origin": origin, "revision": reviewed["revision"]},run=run,)+ activity.experiment_run_started(run, user)wake(run)return run@@ -333,6 +334,7 @@ def retry(run: ExperimentRun, user) -> ExperimentRun:held.deadline = max(held.deadline, timezone.now() + timedelta(hours=DEFAULT_HOURS))held.result = {key: value for key, value in held.result.items() if key == "plan"}held.save(update_fields=["state", "ended_at", "deadline", "result"])+ activity.update_task(held.experiment.project_id, "experiment_run", held.pk, "running")records.log(held.experiment,"run_retried",@@ -377,7 +379,11 @@ def advance(run_id) -> None:def _context(run):- from overbae.services.mcp.context import MCPContext, PlatformCredential # lazy: MCP stack+ from overbae.services.mcp.context import ( # lazy: MCP stack+ EXPERIMENT,+ MCPContext,+ PlatformCredential,+ )project = run.experiment.projectif not project.memberships.filter(user=run.created_by).exists():@@ -386,7 +392,8 @@ def _context(run):user=run.created_by,token=PlatformCredential(project.pk),project=project,- client_name=EXPERIMENT_CLIENT,+ client_name=EXPERIMENT,+ experiment=run.experiment,)@@ -889,6 +896,13 @@ def _end(run, state: str, reason: str, current) -> None:)if run.origin == ExperimentRun.Origin.ASSISTANT:_stop_deployments(run)+ if not run.parent_id:+ activity.update_task(+ run.experiment.project_id,+ "experiment_run",+ run.pk,+ {State.COMPLETED: "completed", State.UNMET: "failed"}.get(state, "cancelled"),+ )if run.parent_id:wake(run.parent.run)returndiff --git a/overbae/services/experiments/stages.py b/overbae/services/experiments/stages.pyindex 39c92d23..dcf0683c 100644--- a/overbae/services/experiments/stages.py+++ b/overbae/services/experiments/stages.py@@ -4,7 +4,8 @@ get_job until it ends. Input and control stages are decided here, at once.Values on ports, by type:data {"cell"}- model {"base_model"} | {"finetune", "model_id"?}+ model ({"base_model"} | {"finetune", "model_id"?}) + {"params", "label"}? when the+ Model stage sets candidate settingssuite {"eval_set"}traces {"connector"}scores {"source": {"kind", "id"}, "candidates": [{"label", "model", "metrics"}],@@ -40,6 +41,7 @@ from overbae.models import ()from overbae.services.datasets import rows as row_storefrom overbae.services.datasets import store+from overbae.services.experiments.catalog import CANDIDATE# A check reads every row it vouches for; above this it refuses rather than sample.CHECK_ROWS = 100_000@@ -152,8 +154,15 @@ def _model_stage(stage: Stage):job = FinetuningJob.objects.filter(project=stage.project, pk=finetune).first()if job is None:raise StageFailedError("The trained model is not a training job of this project.")- return Done({"model": {"finetune": str(job.pk), **_served(job)}})- return Done({"model": _model(stage.settings.get("base_model"))})+ model = {"finetune": str(job.pk), **_served(job)}+ else:+ model = _model(stage.settings.get("base_model"))+ params = {key: stage.settings[key] for key in CANDIDATE if stage.settings.get(key) is not None}+ if params:+ # Two Model stages of one model differ by their settings, so each keeps its own title.+ name = model.get("model_id") or model.get("base_model") or "Trained model"+ model |= {"params": params, "label": f"{name} · {stage.node['title']}"}+ return Done({"model": model})def _served(job: FinetuningJob) -> dict:@@ -321,8 +330,12 @@ def _target(model: dict) -> dict:raise StageFailedError("A trained model is evaluated once deployed: add a Deploy stage.")- return {"label": model["model_id"][:255], "model_name": model["model_id"]}- return {"label": model["base_model"][:255], "model_name": model["base_model"]}+ name = model.get("model_id") or model["base_model"]+ return {+ "label": (model.get("label") or name)[:255],+ "model_name": name,+ **({"params": model["params"]} if model.get("params") else {}),+ }def _evaluate(stage: Stage):@@ -361,18 +374,22 @@ def _system(stage: Stage):def _participant(index: int, model: dict) -> dict:model = _model(model)+ instructions = (model.get("params") or {}).get("system_prompt", "")+ variant = {"instructions": instructions} if instructions else {}if model.get("finetune"):return {"key": f"candidate-{index}",- "name": f"Trained {index}",+ "name": (model.get("label") or f"Trained {index}")[:255],"kind": "trained","job": model["finetune"],+ **variant,}return {"key": f"candidate-{index}",- "name": model["base_model"][:255],+ "name": (model.get("label") or model["base_model"])[:255],"kind": "foundation","model": model["base_model"],+ **variant,}@@ -393,6 +410,7 @@ def _qualify(stage: Stage):"participants": participants,"baseline": "baseline","bootstrap_samples": stage.settings.get("bootstrap_samples") or 1000,+ "purpose": "final",},)evaluation = str(created["workflow"]["id"])diff --git a/overbae/services/mcp/__init__.py b/overbae/services/mcp/__init__.pyindex f7d563f3..eaa74a32 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.4.0"+CONTRACT_VERSION = "12.5.0"diff --git a/overbae/services/mcp/context.py b/overbae/services/mcp/context.pyindex abe6eeff..ab7b9b7a 100644--- a/overbae/services/mcp/context.py+++ b/overbae/services/mcp/context.py@@ -8,10 +8,11 @@ from contextvars import ContextVar, Tokenfrom dataclasses import dataclass, replacefrom uuid import UUID-from overbae.models import APIToken, MCPOAuthToken, Project, User+from overbae.models import APIToken, Experiment, MCPOAuthToken, Project, Userfrom overbae.services.mcp.errors import MCPErrorASSISTANT = "overmind assistant"+EXPERIMENT = "overmind experiment"@dataclass(frozen=True)@@ -35,6 +36,8 @@ class MCPContext:client_ip: str | None = Noneinference_base_url: str = ""client_name: str = ""+ # The experiment whose agent or run makes the call.+ experiment: Experiment | None = None# Request headers the client sends on every call; reported back only in friction reports.user_agent: str = ""protocol_version: str = ""diff --git a/overbae/services/mcp/contracts/activity.py b/overbae/services/mcp/contracts/activity.pyindex 65a7897f..15834def 100644--- a/overbae/services/mcp/contracts/activity.py+++ b/overbae/services/mcp/contracts/activity.py@@ -14,7 +14,7 @@ class InspectActivityInput(MCPModel):class ActivityAsset(MCPModel):- kind: Literal["dataset", "capability", "evaluation", "training_job"]+ kind: Literal["dataset", "capability", "evaluation", "training_job", "experiment"]id: UUIDlabel: strdiff --git a/overbae/services/mcp/contracts/model_workflows.py b/overbae/services/mcp/contracts/model_workflows.pyindex 97749509..e8f76d28 100644--- a/overbae/services/mcp/contracts/model_workflows.py+++ b/overbae/services/mcp/contracts/model_workflows.py@@ -67,6 +67,7 @@ class ParticipantInput(MCPModel):model: str | None = Nonejob: UUID | None = Noneserved_model: str | None = None+ instructions: str = Field(default="", max_length=8000)class CreateComparisonInput(MCPModel):@@ -79,6 +80,7 @@ class CreateComparisonInput(MCPModel):bootstrap_samples: int = Field(default=1000, ge=2, le=10000)seed: int = Field(default=73491, ge=0, le=4294967295)inference: InferenceSettings | None = None+ purpose: Literal["development", "final"] = "final"class ResumeComparisonInput(MCPModel):diff --git a/overbae/services/mcp/resources.py b/overbae/services/mcp/resources.pyindex 93b491ee..dfa1cf9b 100644--- a/overbae/services/mcp/resources.py+++ b/overbae/services/mcp/resources.py@@ -242,7 +242,7 @@ def pipeline_package_guide() -> dict:def _dataset_upload_resource(uri: str) -> dict:- from overbae.services.datasets import documents, files+ from overbae.services.datasets import documents, files, spreadsheetsreturn {"uri": uri,@@ -265,8 +265,12 @@ def _dataset_upload_resource(uri: str) -> dict:f"CSV, TSV, JSON, JSONL, NDJSON, and Parquet uploads are capped at "f"{files.MAX_UPLOAD_BYTES // 1024**3} GiB. "f"Monolithic JSON arrays are capped at {files.JSON_ARRAY_MAX_BYTES // 1024**2} MiB "- "because the parser reads them whole."+ "because the parser reads them whole. "+ f"XLSX workbooks are capped at {spreadsheets.MAX_BYTES // 1024**2} MiB and "+ f"{spreadsheets.MAX_EXPANDED_BYTES // 1024**2} MiB expanded."),+ "spreadsheets": "Each XLSX sheet with a header row and data lands as its own dataset. The first nonempty row is the header; formulas keep their source text and are not evaluated, dates become ISO text and durations seconds. Each row's _overmind_evidence names its sheet, row and the cells that held a formula, an error, a date or a duration. Ambiguous headers and values right of the header are refused.",+ "column_sets": "A new dataset from several files lands each set of column names (compared ignoring case and order; value types do not split a set) as its own dataset; the first set stays the named dataset. Every landed dataset's source_spec.column_groups lists all of them. A split or an upload into an existing dataset needs files with one set of columns.","chunk_bytes": files.CHUNK_BYTES,"command": "overmind dataset upload FILE --project-id PROJECT --json","pipeline_packages": {@@ -924,7 +928,7 @@ def _eval_run_resource(project, value: str, uri: str) -> dict:if run is None:raise _not_found("eval run", value)run = EvalRun.objects.select_related("dataset", "cell", "model_ref").get(pk=run.pk)- scores = comparison.latest_scores(run)+ scores = comparison.scores_by_row(run)rows = list(run.rows.order_by("row_index")[:5])baseline = comparison.baseline_of(run.group)return {@@ -947,6 +951,7 @@ def _eval_run_resource(project, value: str, uri: str) -> dict:"summary": safe_json(run.summary or {}),"context_checks": safe_json(eval_context.run_context_checks(run)),"judge_model": run.judge_model,+ "judge_context": safe_json(run.judge_context),"matrix": [{"name": row.get("name"), "type": row.get("type")} for row in run.matrix[:_MAX_LIST]],@@ -958,6 +963,7 @@ def _eval_run_resource(project, value: str, uri: str) -> dict:"state": row.state,"output": safe_json(row.output),"error": row.error[:_ERROR_CAP],+ "score_error": row.score_error[:_ERROR_CAP],"degraded": row.degraded,"degraded_reason": row.degraded_reason,"score": found.scorediff --git a/overbae/services/mcp/tools_model_workflows.py b/overbae/services/mcp/tools_model_workflows.pyindex 8de24dec..89085cd3 100644--- a/overbae/services/mcp/tools_model_workflows.py+++ b/overbae/services/mcp/tools_model_workflows.py@@ -510,7 +510,7 @@ def register_model_workflow_tools(catalog):("create_native_evaluation","Compare decision models",- "Save an immutable comparison draft without submitting provider work. Use launch_native_evaluation to run: frozen input-only suites, foundations, trained artifacts or external probability models, optional calibration, paired scoring and durable receipts.",+ "Save an immutable comparison draft; launch_native_evaluation runs it. Frozen input-only suites; foundation, trained or external probability models; instructions make a prompt variant; paired scoring. A development purpose also reads decision training rows.",CreateComparisonInput,WorkflowOutput,create_comparison,diff --git a/overbae/services/native_evaluation.py b/overbae/services/native_evaluation.pyindex 9ca20d9c..1d7a2c61 100644--- a/overbae/services/native_evaluation.py+++ b/overbae/services/native_evaluation.py@@ -32,6 +32,7 @@ from overbae.models import ()from overbae.services.compute_costs import estimate_usagefrom overbae.services.datasets import heartbeat, paths, rows, use+from overbae.services.datasets.examples import prepare_native_recordfrom overbae.services.decision_benchmark_scoring import compare_suite, recordsfrom overbae.services.decision_calibration import fit_decision_calibrationfrom overbae.services.decision_providers import (@@ -46,6 +47,7 @@ from overbae.services.training_release import currentlogger = logging.getLogger(__name__)+PURPOSES = ("development", "final")TEMPERATURES = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0]@@ -136,6 +138,40 @@ def runtime():}+def training_decisions(cell) -> bool:+ report = (cell.intent_report or {}).get("train") or {}+ return bool(report.get("ok")) and report.get("format") == "decision"+++def check_suite(cell, purpose):+ """A final measurement reads a readable evaluation dataset of native decisions; a+ development one also reads decision training rows, whose targets are the references."""+ if purpose == "development" and training_decisions(cell):+ return+ if purpose == "final" and cell.dataset.intent != "eval":+ raise InputValidationError("A final evaluation reads an evaluation dataset")+ if not cell.fits("eval")[0]:+ raise InputValidationError("Select a technically readable evaluation version")+ evaluation = (cell.intent_report or {}).get("eval", {})+ if evaluation.get("input_type") != "decision" or any(+ k != "decision" and v for k, v in evaluation.get("input_types", {}).items()+ ):+ raise InputValidationError(+ "Evaluation suites must contain native decision inputs and separate references."+ )+++def suite_example(row):+ """A row's decision request and its reference, from evaluation or training rows."""+ if isinstance(row.input, dict) and "decision" in row.input:+ return row.input["decision"], row.expected_output+ decision = row.extra.get("decision")+ if not isinstance(decision, dict):+ return None, row.expected_output+ example = prepare_native_record({}, dict(decision), "eval")+ return example["input"]["decision"], example["expected_output"]++@transaction.atomicdef create_plan(project,@@ -151,24 +187,19 @@ def create_plan(inference=None,job=None,triggered_by=None,+ purpose="final",):if calibration_cell is not None and calibration_cell.id == final_cell.id:raise InputValidationError("Calibration and final suites must be separate frozen cells.")suites = {"final": final_cell}if calibration_cell is not None:suites = {"calibration": calibration_cell, **suites}+ if purpose not in PURPOSES:+ raise InputValidationError("Choose a development or final evaluation")for cell in suites.values():if cell.dataset.project_id != project.pk:raise InputValidationError("Evaluation suites must belong to this project.")- if cell.dataset.intent != "eval" or not cell.fits("eval")[0]:- raise InputValidationError("Select a technically readable evaluation version")- evaluation = (cell.intent_report or {}).get("eval", {})- if evaluation.get("input_type") != "decision" or any(- k != "decision" and v for k, v in evaluation.get("input_types", {}).items()- ):- raise InputValidationError(- "Evaluation suites must contain native decision inputs and separate references."- )+ check_suite(cell, purpose)if (type(bootstrap_samples) is not intor not 2 <= bootstrap_samples <= 10000@@ -201,6 +232,7 @@ def create_plan(if baseline not in {p["key"] for p in selected}:raise InputValidationError("Choose one of the participants as the baseline")config = {+ "purpose": purpose,"runtime": existing.config["runtime"]if existingelse runtime()@@ -320,12 +352,17 @@ def participants(plan):return plan.config["participants"]+def preparation_identity(participant):+ """Participants share prepared inputs when they run one model with one prompt."""+ return participant.get("job") or participant["key"], participant.get("instructions", "")++def preparation_groups(plan):groups = {}for participant in participants(plan):if participant["kind"] == "external" or participant["key"] in plan.config.get("reuse", {}):continue- identity = participant.get("job") or participant["key"]+ identity = preparation_identity(participant)if identity not in groups:key = "prepare" if not groups else "prepare_" + participant["key"]groups[identity] = (key, participant)@@ -339,7 +376,7 @@ def provider_stage(plan, stage):if key == action:return role, participant, True, actionparticipant = next(p for p in participants(plan) if p["key"] == key)- group = groups.get(participant.get("job") or key)+ group = groups.get(preparation_identity(participant))return role, participant, False, group[0] if group else None@@ -376,7 +413,7 @@ def write_suite(plan, role):(staging / "failures.jsonl").open("w") as failures,):for row in rows.iter_rows(cell):- request = row.input.get("decision") if isinstance(row.input, dict) else None+ request, reference = suite_example(row)benchmark = str(row.extra.get("benchmark") or row.extra.get("source") or cell.dataset.name)@@ -385,7 +422,7 @@ def write_suite(plan, role):n = len(request["options"])score_decision(request,- row.expected_output,+ reference,{"probabilities": [1 / n] * n, "log_probabilities": [-math.log(n)] * n},)identity = {"key": str(row.index), "input_sha256": input_digest(request)}@@ -397,7 +434,7 @@ def write_suite(plan, role):"decisions": 1,"source_row": row.index,"input": request,- "reference": row.expected_output,+ "reference": reference,"error": str(exc),})@@ -419,7 +456,7 @@ def write_suite(plan, role):"query": str(row.extra.get("query") or request.get("question") or "decision"),- "reference": row.expected_output,+ "reference": reference,"metadata": row.extra.get("metadata") or {},})@@ -614,7 +651,10 @@ def submit(plan, stage):model_run,digest_file(source),foundation=None if model else participant,- inference=plan.config["inference"],+ inference={+ **plan.config["inference"],+ "instructions": participant.get("instructions", ""),+ },).object_idfunction = modal.Function.from_name(selected["app"], "predict", environment_name=selected["environment"]@@ -629,6 +669,8 @@ def submit(plan, stage):def collect(plan, stage, receipt):role, participant, preparing, group = provider_stage(plan, stage)+ if preparing and receipt.get("instructions", "") != participant.get("instructions", ""):+ raise InputValidationError("Prepared instructions differ from the frozen participant")native_label = "base" if participant["kind"] == "foundation" else "candidate"filename = "failures.jsonl" if preparing else f"{native_label}.jsonl"checksum = receipt["failures_sha256" if preparing else "predictions_sha256"]@@ -649,7 +691,7 @@ def collect(plan, stage, receipt):for arm in participants(plan):if (arm["kind"] != "external"- and preparation_groups(plan)[arm.get("job") or arm["key"]][0] == group+ and preparation_groups(plan)[preparation_identity(arm)][0] == group):with replacing(directory(plan, role) / f"{arm['key']}.failures.jsonl") as copy:shutil.copyfile(target, copy)diff --git a/overbae/services/sft_assets/prepare_decisions.py b/overbae/services/sft_assets/prepare_decisions.pyindex da333fbb..6f6d0d8e 100644--- a/overbae/services/sft_assets/prepare_decisions.py+++ b/overbae/services/sft_assets/prepare_decisions.py@@ -59,6 +59,7 @@ def main(directory, model_directory):tokenizer,prepared["context_length"],encode_record,+ instructions=request["instructions"],)atomic_json(directory / "preparation.json",diff --git a/overbae/tasks/datasets.py b/overbae/tasks/datasets.pyindex cec952f2..55d1cbca 100644--- a/overbae/tasks/datasets.py+++ b/overbae/tasks/datasets.py@@ -305,18 +305,24 @@ def _execute_landing(upload_ids = source.get("uploads") or []try:if upload_ids:- read = landing.read_uploads(upload_ids, on_progress=file_progress, **extraction)+ read = landing.single(+ landing.read_uploads(upload_ids, on_progress=file_progress, **extraction)+ )elif upload_id:filename = source.get("filename") or files.upload_filename(upload_id) or "upload"path = files.upload_data_path(upload_id)if not path.exists():raise landing.LandError("The upload has expired. Start it again.")- read = landing.read_file(- path,- json_rows_field=source.get("json_rows_field"),- filename=filename,- on_progress=lambda detail: file_progress({"completed": 0, "total": 1, **detail}),- **extraction,+ read = landing.single(+ landing.read_file(+ path,+ json_rows_field=source.get("json_rows_field"),+ filename=filename,+ on_progress=lambda detail: file_progress(+ {"completed": 0, "total": 1, **detail}+ ),+ **extraction,+ ))elif source.get("rows") is not None:read = landing.read_rows(list(source["rows"]), spec={"pasted": True})diff --git a/overmind/overmind/__init__.py b/overmind/overmind/__init__.pyindex b1c269b1..f103d09e 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.133"+__version__ = "0.1.134"from .client import Client, ModelDeleted, OvermindInferenceErrordiff --git a/overmind/pyproject.toml b/overmind/pyproject.tomlindex 068bd783..0c5daa21 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.133"+version = "0.1.134"[project.urls]"Agent setup" = "https://console.overmindlab.ai/setup.md"diff --git a/overmind/skills/overmind-training/SKILL.md b/overmind/skills/overmind-training/SKILL.mdindex 78afc039..a5d86e48 100644--- a/overmind/skills/overmind-training/SKILL.md+++ b/overmind/skills/overmind-training/SKILL.md@@ -387,7 +387,7 @@ The native coding agent owns interpretation. Save target meaning as a hypothesisUse `create_data_partition` with `source_cell`, `name`, `request_key`, and a recipe containing `seed`, `fractions` keyed by train/development/calibration/final, `group_by`, optional `stratify_by`, and optional `holdouts` (`field`, `values`, `role`). Inspect `get_job(kind="data_partition")` for counts, grouping, assignment hashes and member cells. Prepare each member for its consumer. Retry a failed saved partition with `retry_data_partition`.-`list_decision_models` returns eligible foundations, ready native artifacts and supported external participants. Eligibility is not proof of hardware fit or quality. `create_native_evaluation` freezes `final_cell`, optional `calibration_cell`, `participants` and the `baseline` key. `create_native_evaluation` saves a draft without inference. `prepare_native_evaluation` verifies immutable suites in background; `launch_native_evaluation` authorizes the saved participants and suites once. A participant has a key, name, kind and model ID, or a trained job UUID. Input references stay separate; one global temperature is fitted on the calibration suite before final scoring. Mean-only suites omit probability temperature calibration. Inspect `get_job(kind="native_evaluation")` and the returned resource for every benchmark, denominator, failure, raw/calibrated metric and paired interval. Calibration scores are in-sample; overlap and pretraining independence limitations remain explicit.+`list_decision_models` returns eligible foundations, ready native artifacts and supported external participants. Eligibility is not proof of hardware fit or quality. `create_native_evaluation` freezes `final_cell`, optional `calibration_cell`, `participants` and the `baseline` key. `create_native_evaluation` saves a draft without inference. `prepare_native_evaluation` verifies immutable suites in background; `launch_native_evaluation` authorizes the saved participants and suites once. A participant has a key, name, kind and model ID, or a trained job UUID, and optional `instructions` (up to 8000 characters) put before each decision question: two participants of one model with different instructions compare prompt variants. `purpose` is `final` (the default; an evaluation dataset) or `development`, which also reads decision training rows. Input references stay separate; one global temperature is fitted on the calibration suite before final scoring. Mean-only suites omit probability temperature calibration. Inspect `get_job(kind="native_evaluation")` and the returned resource for every benchmark, denominator, failure, raw/calibrated metric and paired interval. Calibration scores are in-sample; overlap and pretraining independence limitations remain explicit.`create_training_experiment` saves a name, purpose, request key, explicit variants and optional evaluation protocol UUID. Each variant declares `base_model`, train `cell`, optional `development_cell`, and `hyperparameters` (for example `n_epochs`, `learning_rate`, `lora_r`, `seed`). A `checkpoint_policy` declares fractions ending at 1 and selection `last` or `development_loss`. Final scores never choose a checkpoint. Run `prepare_training_experiment` to verify sources and obtain a forecast bound to the frozen configuration. Inspect it before `launch_training_experiment`; pass its quote ID when user constraints require it. An optional `constraints.max_training_run_usd` and explicit `unpriced_allowance_usd` enforce the user's planning policy; there is no default spend cap or claim of provider all-in enforcement. Unknown costs stay unknown. `create_training_profile` saves one bounded candidate (1–128 steps, 60–3600 seconds per provider attempt, no automatic provider retries), then uses the same preparation and launch path. Native profiles sample representative length quantiles, retain labels and record their measurement scope; profile weights are not quality evidence. Requested/effective conditions and seed variation are recorded separately from evaluation uncertainty.diff --git a/overmind/uv.lock b/overmind/uv.lockindex 01a29fe2..a0fb5975 100644--- a/overmind/uv.lock+++ b/overmind/uv.lock@@ -923,7 +923,7 @@ wheels = [[[package]]name = "overmind"-version = "0.1.133"+version = "0.1.134"source = { editable = "." }dependencies = [{ name = "packaging" },diff --git a/pyproject.toml b/pyproject.tomlindex f465a170..439f6288 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -75,6 +75,7 @@ dependencies = ["pypdfium2>=5.0,<6","matplotlib>=3.11.2","orjson>=3.13.0",+ "openpyxl>=3.1.5",]description = "Overbae — unified Django API for the Overclaw / Overmind platform"license = { text = "AGPL-3.0" }diff --git a/tests/fakes/modal.py b/tests/fakes/modal.pyindex bba78da8..45ee3f50 100644--- a/tests/fakes/modal.py+++ b/tests/fakes/modal.py@@ -693,6 +693,7 @@ class DecisionBackend:"input_sha256": input_sha256,"ready_decisions": len(rows),"failures_sha256": hashlib.sha256(b"").hexdigest(),+ "instructions": (inference or {}).get("instructions", ""),}def _predict(self, evaluation_id, model_run, *, base_only, inference=None):diff --git a/tests/journeys/browser.py b/tests/journeys/browser.pyindex 96c2b7fb..e84cd2f1 100644--- a/tests/journeys/browser.py+++ b/tests/journeys/browser.py@@ -143,8 +143,8 @@ class Console:def sees(self, text: str, *, exact: bool = True) -> None:self._browser.call(lambda: self._page.get_by_text(text, exact=exact).first.wait_for())- def upload(self, selector: str, path: Path) -> None:- self._browser.call(self._page.set_input_files, selector, str(path))+ def upload(self, selector: str, *paths: Path) -> None:+ self._browser.call(self._page.set_input_files, selector, [str(path) for path in paths])def signed_in(self) -> bool:return bool(self._browser.call(self._page.evaluate, "localStorage.getItem('jwt_access')"))diff --git a/tests/journeys/test_data.py b/tests/journeys/test_data.pyindex 5ce6e059..34a1c216 100644--- a/tests/journeys/test_data.py+++ b/tests/journeys/test_data.py@@ -119,9 +119,12 @@ def hand_uploaded_data_to_the_coding_agent(console, tmp_path):def use_freezes_an_uploaded_eval_source(console, workshop, project, worker, tmp_path):- # A file dropped on Home with no message lands in a new experiment, with no agent turn.+ # Files dropped on Home with no message land in a new experiment, with no agent turn;+ # files with other columns land as a dataset of their own, in a Data stage of their own.+ labels = tmp_path / "labels.csv"+ labels.write_text("text,label\nhello,greeting\n")console.goto(f"/?projectId={project}")- console.upload('input[aria-label="Attach dataset files"]', tickets(tmp_path))+ console.upload('input[aria-label="Attach dataset files"]', tickets(tmp_path), labels)console.press("Send")def landed():@@ -133,6 +136,14 @@ def use_freezes_an_uploaded_eval_source(console, workshop, project, worker, tmp_inspected = settle(worker, landed)dataset = inspected["id"]+ console.wait_until("() => location.pathname.startsWith('/experiments/')")+ experiment = console._browser.call(+ lambda: console._page.evaluate("() => location.pathname.split('/')[2]")+ )+ nodes = workshop.call("inspect_experiment", {"experiment": experiment})["flow"]["nodes"]+ assert [node["kind"] for node in nodes] == ["data", "data"], nodes+ names = [item["name"] for item in workshop.call("list_datasets", {})["datasets"]]+ assert "labels" in names, namesworkshop.call("update_dataset", {"dataset": dataset, "intent": "eval"})inspected = workshop.call("inspect_dataset", {"dataset": dataset})assert inspected["active"]["rows"] == 3diff --git a/tests/settings.py b/tests/settings.pyindex 1a10533b..0fc91c32 100644--- a/tests/settings.py+++ b/tests/settings.py@@ -32,7 +32,8 @@ WORKSPACE_PROVIDER = "native"DATABASES = {"default": {"ENGINE": "django.db.backends.postgresql",- "NAME": "overbae",+ # A worktree sets its own name, so parallel suites never share or drop one database.+ "NAME": os.environ.get("POSTGRES_DB", "overbae"),"USER": os.environ.get("POSTGRES_USER", "overbae"),"PASSWORD": os.environ.get("POSTGRES_PASSWORD", "overbae"),"HOST": os.environ.get("TEST_POSTGRES_HOST", "localhost"),diff --git a/tests/test_assistant_eval_set_draft.py b/tests/test_assistant_eval_set_draft.pynew file mode 100644index 00000000..ec4ed171--- /dev/null+++ b/tests/test_assistant_eval_set_draft.py@@ -0,0 +1,85 @@+"""The experiment's agent drafts an eval set and stops for a person: nothing is saved, the+draft is checked by the eval-set rules, and a turn no person started cannot draft."""++import pytest+from factories import make_capability, make_project, make_user+from fakes.llm import tool_call++from overbae.models import AssistantInput, EvalSet+from overbae.services.assistant import threads, turn+from overbae.services.experiments import records+from overbae.tasks.assistant import run_turn++pytestmark = [pytest.mark.django_db, pytest.mark.covers("assistant-results")]++POLITE = {+ "name": "Polite",+ "type": "llm",+ "source": "Is the reply polite?",+ "output": "yes_no",+ "options": [{"label": "Yes", "score": 1}, {"label": "No", "score": 0}],+}+SHORT = {+ "name": "Short",+ "type": "deterministic",+ "source": "def evaluate(span):\n return 1.0",+ "output": "yes_no",+}+++def draft(**arguments):+ return tool_call("draft_eval_set", {"summary": "Drafting criteria", **arguments})+++def thread(monkeypatch):+ monkeypatch.setattr(run_turn, "delay", lambda *a: None)+ user = make_user()+ project = make_project(member=user)+ return records.create(project, user, name="E").assistant_thread, user+++def test_a_draft_waits_for_the_person_and_saves_nothing(fake_llm, thread):+ thread, user = thread+ capability = make_capability(thread.project)+ current = EvalSet.objects.create(+ project=thread.project, capability=capability, name="Replies", criteria=[POLITE]+ )+ wrong = {**POLITE, "options": [{"label": "Sure", "score": 1}, {"label": "No", "score": 0}]}+ fake_llm.stream_rounds(+ [+ ([draft(name="Replies v2", criteria=[wrong], eval_set=str(current.pk))], ""),+ ([draft(name="Replies", criteria=[POLITE], eval_set=str(current.pk))], ""),+ ([draft(name="Replies v2", criteria=[POLITE, SHORT], eval_set=str(current.pk))], ""),+ ([], "Never reached."),+ ]+ )+ threads.send(thread, user, request_key="m", text="Add a length check to the suite.")++ turn.run(thread.pk)++ refused, taken, shown = thread.events.filter(kind="tool_result")+ assert refused.payload["content"]["error"] == "Polite: Yes/no answers are Yes and No."+ assert "exists" in taken.payload["content"]["error"]+ card = shown.presentation["root"]+ assert card["type"] == "EvalSetDraft"+ assert card["criteria"] == [POLITE, {k: v for k, v in SHORT.items() if k != "output"}]+ assert card["capability"] == str(capability.pk)+ assert card["amends"] == {"id": str(current.pk), "name": "Replies", "criteria": [POLITE]}+ assert not thread.events.filter(kind="assistant", payload__text="Never reached.").exists()+ assert list(EvalSet.objects.values_list("name", flat=True)) == ["Replies"]+++def test_a_turn_no_person_started_cannot_draft(fake_llm, thread):+ thread, user = thread+ fake_llm.stream_rounds([([draft(name="Checks", criteria=[POLITE])], ""), ([], "Noted.")])+ threads.send(+ thread, user, request_key="n", text="Run 3 ended.", origin=AssistantInput.Origin.RUN+ )++ turn.run(thread.pk)++ (result,) = thread.events.filter(kind="tool_result")+ assert not result.payload["ok"]+ assert "a person's message" in result.payload["content"]["error"]+ assert result.presentation is Nonediff --git a/tests/test_dataset_column_groups.py b/tests/test_dataset_column_groups.pynew file mode 100644index 00000000..8acf447b--- /dev/null+++ b/tests/test_dataset_column_groups.py@@ -0,0 +1,104 @@+"""Dropped files land one dataset per set of columns, and one per workbook sheet."""++import io+import json++import pytest+from openpyxl import Workbook+from rest_framework.test import APIClient++from overbae.models import Dataset, Project, ProjectMembership, User+from overbae.services.datasets import files++pytestmark = pytest.mark.covers("data-logic")+++def _upload(name, content):+ upload_id, _ = files.begin_upload(name)+ files.append_chunk(upload_id, 0, content)+ files.inspect_upload(upload_id, size=len(content))+ return upload_id+++def _workbook():+ workbook = Workbook()+ workbook.active.title = "orders"+ workbook.active.append(["order", "total"])+ workbook.active.append(["A1", 3])+ refunds = workbook.create_sheet("refunds")+ refunds.append(["order", "total"])+ refunds.append(["A1", -3])+ refunds.append(["A2", -1])+ stream = io.BytesIO()+ workbook.save(stream)+ return stream.getvalue()+++def client_project(db):+ user = User.objects.create_user(email="[email protected]", password="pw", clerk_user_id="groups")+ project = Project.objects.create(name="Groups", slug="groups")+ ProjectMembership.objects.create(user=user, project=project)+ client = APIClient()+ client.force_authenticate(user)+ return client, project++[email protected]_db(transaction=True)+def test_each_set_of_columns_and_each_sheet_lands_as_its_own_dataset(client_project):+ client, project = client_project+ ids = [+ _upload("questions.csv", b"input,output\nq1,a1\n"),+ _upload("labels.csv", b"text,label\nhello,greeting\n"),+ _upload("book.xlsx", _workbook()),+ # Same names in another order and case, and integers where the first file has text.+ _upload("more.jsonl", json.dumps({"Output": 2, "input": "q2"}).encode() + b"\n"),+ ]+ response = client.post(+ "/api/datasets/",+ {"project": str(project.id), "name": "Dropped", "source": {"uploads": ids}},+ format="json",+ )+ assert response.status_code == 201, response.data+ primary = Dataset.objects.get(pk=response.data["id"])+ listed = primary.source_spec["column_groups"]+ assert listed[0]["dataset"] == str(primary.pk)+ landed = [Dataset.objects.get(pk=item["dataset"]) for item in listed]+ assert [(d.name, d.state, d.source.rows) for d in landed] == [+ ("Dropped", Dataset.State.IDLE, 2),+ ("labels", Dataset.State.IDLE, 1),+ ("book · orders", Dataset.State.IDLE, 1),+ ("book · refunds", Dataset.State.IDLE, 2),+ ]+ assert [[f["filename"] for f in item["files"]] for item in listed] == [+ ["questions.csv", "more.jsonl"],+ ["labels.csv"],+ ["book.xlsx"],+ ["book.xlsx"],+ ]+ assert listed[3]["files"][0]["sheet"] == "refunds"+ assert all(d.source_spec["column_groups"] == listed for d in landed)+ assert {d.project_id for d in landed} == {project.id}+ assert all(not files.upload_data_path(upload_id).exists() for upload_id in ids)++[email protected]_db(transaction=True)+def test_a_split_of_files_with_different_columns_is_refused(client_project):+ client, project = client_project+ ids = [_upload("a.csv", b"input\none\ntwo\n"), _upload("b.csv", b"text\none\ntwo\n")]+ response = client.post(+ "/api/datasets/split/",+ {+ "project": str(project.id),+ "name": "Mixed",+ "source": {"uploads": ids},+ "eval_percent": 50,+ "position": "tail",+ },+ format="json",+ )+ assert response.status_code == 201, response.data+ train = Dataset.objects.get(pk=response.data["train"]["id"])+ assert train.state == Dataset.State.ERROR+ assert "2 different sets of columns" in train.error+ assert Dataset.objects.filter(project=project).count() == 2diff --git a/tests/test_dataset_files.py b/tests/test_dataset_files.pyindex 45a00275..3698b361 100644--- a/tests/test_dataset_files.py+++ b/tests/test_dataset_files.py@@ -88,7 +88,9 @@ def test_upload_names_are_checked_before_any_byte_is_stored(settings, tmp_path):settings.MEDIA_ROOT = tmp_pathwith pytest.raises(files.FileError, match="already compressed"):files.begin_upload("rows.parquet.gz")+ with pytest.raises(files.FileError, match="already compressed"):+ files.begin_upload("rows.xlsx.gz")with pytest.raises(files.FileError, match="Use a CSV"):- files.begin_upload("rows.xlsx")+ files.begin_upload("rows.exe")upload_id, name = files.begin_upload("rows.jsonl.gz")assert name == "rows.jsonl.gz" and files.upload_received(upload_id) == 0diff --git a/tests/test_dataset_label_leakage.py b/tests/test_dataset_label_leakage.pynew file mode 100644index 00000000..c3694dee--- /dev/null+++ b/tests/test_dataset_label_leakage.py@@ -0,0 +1,87 @@+"""Analytics warn when one input gives away the label, or the input names it."""++import json++import pytest++from overbae.services.datasets.profile import profile_records++pytestmark = pytest.mark.covers("data-logic")++OPTIONS = ["refund", "replacement"]+++def row(label, state):+ return {+ "decision": {+ "state": json.dumps(state) if isinstance(state, dict) else state,+ "question": "Which resolution?",+ "kind": "choice",+ "options": OPTIONS,+ "target_probabilities": [1, 0] if label == "refund" else [0, 1],+ "target_semantics": "categorical_gold",+ }+ }+++def checks(records):+ report = profile_records(records)["analytics"]+ return {item["id"]: item for item in report["checks"]}+++def test_an_input_that_gives_the_label_on_shared_values_is_flagged():+ records = [+ row(label, {"queue": f"{label}-desk", "order": index, "note": "customer wrote in"})+ for index, label in enumerate(["refund", "replacement"] * 60)+ ]+ found = checks(records)+ determined = found["leakage.input_determines_label"]+ assert determined["status"] == "warning"+ assert [item["field"] for item in determined["metrics"]["findings"]] == ["queue"]+ assert "queue alone gives the label on 120 of the 120 rows" in determined["summary"]+ # Distinct per row, so no value is shared by five rows: no evidence either way.+ assert "order" not in determined["summary"]+ assert found["leakage.label_in_input"]["status"] == "warning"+ assert found["leakage.label_in_input"]["metrics"]["findings"][0]["field"] == "queue"+++def test_inputs_that_only_correlate_or_name_shared_words_pass():+ records = [+ row(label, {"channel": "email" if index % 3 else "phone", "text": "please help"})+ for index, label in enumerate(["refund", "replacement"] * 60)+ ]+ found = checks(records)+ assert found["leakage.input_determines_label"]["status"] == "pass"+ assert found["leakage.label_in_input"]["status"] == "pass"+++def test_text_states_are_searched_for_their_label_but_never_block():+ records = [+ row(label, f"Ticket: the customer wants a {label} for order {index}")+ for index, label in enumerate(["refund", "replacement"] * 30)+ ]+ found = checks(records)+ assert found["leakage.label_in_input"]["status"] == "warning"+ assert found["leakage.label_in_input"]["summary"] == (+ "state names the row's own label on 60 of 60 rows."+ )+ assert found["leakage.input_determines_label"]["status"] == "not_checked"+ assert not any(item["status"] == "error" for item in found.values())+++def test_labels_without_distinct_words_are_not_searched():+ records = [+ {+ "decision": {+ **row("refund", {"a": 1})["decision"],+ "options": ["Yes", "No"],+ "target_probabilities": [1, 0] if index % 2 else [0, 1],+ }+ }+ for index in range(60)+ ]+ found = checks(records)+ assert found["leakage.label_in_input"]["status"] == "not_checked"+ single = checks([row("refund", {"a": 1}) for _ in range(60)])+ assert single["leakage.label_in_input"]["status"] == "not_applicable"+ assert single["leakage.input_determines_label"]["status"] == "not_applicable"diff --git a/tests/test_dataset_preparation_activity.py b/tests/test_dataset_preparation_activity.pynew file mode 100644index 00000000..822870dd--- /dev/null+++ b/tests/test_dataset_preparation_activity.py@@ -0,0 +1,109 @@+"""The feed shows one row per dataset preparation and per experiment run, credited to who+acted; the platform's own experiment runs connect no coding agent."""++import pytest+from conftest import frozen_dataset+from mcp_fixtures import call_tool, mcp_context++from overbae.models import Activity, ActivityClient, ExperimentRun+from overbae.services import activity+from overbae.services.experiments import records, runs+from overbae.services.mcp.catalog import CATALOG+from overbae.services.mcp.context import EXPERIMENT, MCPContext, PlatformCredential+from overbae.services.mcp.resources import resource_link++pytestmark = [pytest.mark.django_db, pytest.mark.covers("live-console")]++ROWS = [{"input": "hi", "expected_output": "hello"}, {"input": "bye", "expected_output": "ciao"}]+++def test_an_experiment_s_tool_calls_are_its_own_and_connect_no_agent():+ person = mcp_context(["read", "write"])+ experiment = records.create(person.project, person.user, name="Replies")+ context = MCPContext(+ user=person.user,+ token=PlatformCredential(person.project.pk),+ project=person.project,+ client_name=EXPERIMENT,+ experiment=experiment,+ )+ dataset = frozen_dataset(person.project, ROWS)+ assert not call_tool("list_datasets", {}, context).isError+ renamed = call_tool("update_dataset", {"dataset": str(dataset.pk), "name": "tickets"}, context)+ assert not renamed.isError+ assert not Activity.objects.filter(kind="agent_connected").exists()+ assert not ActivityClient.objects.exists()+ updated = Activity.objects.get(action="Updated dataset")+ assert (updated.actor_kind, updated.actor_name) == ("overmind", "Experiment")+++def _succeeded(context, tool, dataset, **output):+ links = [resource_link("datasets", str(dataset.pk), dataset.name)]+ activity.mcp_succeeded(+ tool,+ CATALOG.get(tool).definition,+ {"dataset": str(dataset.pk), "resource_links": links, **output},+ context,+ )+++def test_a_preparation_is_one_row_from_its_first_script_to_its_publication():+ context = mcp_context(["read", "write"], client_name="codex")+ dataset = frozen_dataset(context.project, ROWS, name="tickets")+ job = {"kind": "dataset_pipeline", "id": "run", "status": "queued"}+ _succeeded(context, "save_dataset_pipeline", dataset)+ _succeeded(context, "run_dataset_pipeline", dataset, run={"mode": "preview"}, job=job)+ _succeeded(context, "run_dataset_pipeline", dataset, run={"mode": "publish"}, job=job)+ rows = Activity.objects.filter(project=context.project).exclude(+ kind__in=["agent_connected", "source_ready"]+ )+ [row] = rows+ assert (row.action, row.status, row.actor_name) == ("Preparing", "running", "Codex")+ assert row.assets == [{"kind": "dataset", "id": str(dataset.pk), "label": "tickets"}]++ activity.update_task(context.project.pk, "dataset_preparation", dataset.pk, "failed")+ _succeeded(context, "run_dataset_pipeline", dataset, run={"mode": "publish"}, job=job)+ activity.prepared(dataset)+ [row] = rows.all()+ assert (row.kind, row.status, row.actor_name) == ("preparation_published", "completed", "Codex")+ project = context.project.pk+ feed = activity.feed(activity.visible(context.user, [project], project))+ assert feed["results"][0]["sequence_key"].endswith(str(dataset.pk))++ # The next change to the recipe is the next preparation.+ _succeeded(context, "save_dataset_pipeline", dataset)+ assert list(rows.order_by("created_at").values_list("status", flat=True)) == [+ "completed",+ "running",+ ]+++def test_an_experiment_run_is_one_row_that_ends_with_the_run(eager, monkeypatch):+ from overbae.tasks.assistant import run_turn++ monkeypatch.setattr(run_turn, "delay", lambda *args: None)+ context = mcp_context(["read", "write"])+ cell = frozen_dataset(context.project, ROWS).active_cell+ node = {"id": "data", "kind": "data", "settings": {"cell": str(cell.pk)}}+ check = {+ "id": "check",+ "kind": "check_data",+ "inputs": {"data": ["data.data"]},+ "settings": {"schema": {"type": "object", "required": ["missing"]}},+ }+ document = {"nodes": [node, check], "outputs": [{"node": "check", "port": "report"}]}+ experiment = records.create(context.project, context.user, name="Replies", document=document)+ run = runs.start(experiment, context.user, origin="assistant")+ run.refresh_from_db()+ assert run.state == ExperimentRun.State.UNMET+ row = Activity.objects.get(task_kind="experiment_run")+ assert (row.action, row.status, row.actor_name) == (+ "Started a run of",+ "failed",+ "Overmind assistant",+ )+ assert row.assets == [{"kind": "experiment", "id": str(experiment.pk), "label": "Replies"}]+ runs.retry(run, context.user)+ row.refresh_from_db()+ assert row.status == "failed"+ assert Activity.objects.filter(task_kind="experiment_run").count() == 1diff --git a/tests/test_dataset_scale.py b/tests/test_dataset_scale.pyindex 7d776916..34f02ffe 100644--- a/tests/test_dataset_scale.py+++ b/tests/test_dataset_scale.py@@ -94,7 +94,10 @@ def test_three_hundred_thousand_orders_land_and_publish_a_batched_script_within_stream.write(json.dumps(order) + "\n")project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")dataset = Dataset.objects.create(project=project, name="orders")- _timed(60, lambda: land.commit(dataset, land.read_file(source, filename="orders.jsonl")))+ _timed(+ 60,+ lambda: land.commit(dataset, land.single(land.read_file(source, filename="orders.jsonl"))),+ )dataset.refresh_from_db()original = dataset.sourcemanifest = {diff --git a/tests/test_dataset_spreadsheets.py b/tests/test_dataset_spreadsheets.pynew file mode 100644index 00000000..ca96722c--- /dev/null+++ b/tests/test_dataset_spreadsheets.py@@ -0,0 +1,113 @@+"""A workbook lands sheet by sheet, values as stored, or is refused with a message."""++from __future__ import annotations++import datetime as dt+from zipfile import ZIP_DEFLATED, ZipFile++import pytest+from openpyxl import Workbook++from overbae.services.datasets import files, spreadsheets++pytestmark = pytest.mark.covers("data-logic")+++def _save(tmp_path, *sheets, name="book.xlsx"):+ workbook = Workbook()+ workbook.remove(workbook.active)+ for title, rows in sheets:+ sheet = workbook.create_sheet(title)+ for row in rows:+ sheet.append(row)+ path = tmp_path / name+ workbook.save(path)+ return path+++def test_each_sheet_reads_its_values_as_stored(settings, tmp_path):+ settings.MEDIA_ROOT = tmp_path / "media"+ path = _save(+ tmp_path,+ (+ "orders",+ [+ ["id", "amount", "paid", "placed", "took", "double", None],+ [+ "007",+ 1.5,+ False,+ dt.datetime(2024, 2, 3, 4, 5),+ dt.timedelta(minutes=2),+ "=B2*2",+ ],+ [],+ ["008", None, True, dt.date(2024, 2, 4), None, "#N/A"],+ ],+ ),+ ("empty", []),+ ("notes", [["note"], ["first"]]),+ )+ assert spreadsheets.sheets(path) == ["orders", "notes"]+ upload_id, _ = files.begin_upload(path.name)+ payload = path.read_bytes()+ files.append_chunk(upload_id, 0, payload)+ assert files.inspect_upload(upload_id, size=len(payload))["rows"] == 3++ rows = list(files.FileRows(path, filename=path.name, sheet="orders"))+ assert rows[0] == {+ "id": "007",+ "amount": 1.5,+ "paid": False,+ "placed": "2024-02-03T04:05:00",+ "took": 120.0,+ "double": "=B2*2",+ "_overmind_evidence": {+ "sheet": "orders",+ "row": 2,+ "cells": {"placed": "datetime", "took": "duration_seconds", "double": "formula"},+ },+ }+ assert rows[1]["_overmind_evidence"] == {+ "sheet": "orders",+ "row": 4,+ "cells": {"placed": "datetime", "double": "error"},+ }+ assert rows[1]["placed"] == "2024-02-04T00:00:00" and rows[1]["amount"] is None+ assert list(files.FileRows(path, filename=path.name, sheet="notes"))[0]["note"] == "first"+++ ("rows", "message"),+ [+ ([["a", "A"], [1, 2]], "appears twice"),+ ([["a", "_overmind_evidence"], [1, 2]], "Rename it"),+ ([["a", "=1+1"], [1, 2]], "formula or error in its header"),+ ([["a"], [1, None, 3]], "row 2 has a value right of its last header cell"),+ ],+)+def test_ambiguous_sheets_are_refused(tmp_path, rows, message):+ path = _save(tmp_path, ("data", rows))+ with pytest.raises(files.FileError, match=message):+ list(files.FileRows(path, filename=path.name, sheet="data"))+++def test_unreadable_or_oversized_workbooks_are_refused(tmp_path):+ broken = tmp_path / "broken.xlsx"+ source = _save(tmp_path, ("data", [["a"], [1]]))+ with ZipFile(source) as original, ZipFile(broken, "w") as rewritten:+ for member in original.infolist():+ body = original.read(member)+ rewritten.writestr(+ member, b"<broken>" if member.filename == "xl/workbook.xml" else body+ )+ with pytest.raises(spreadsheets.SpreadsheetError, match="not a readable XLSX"):+ spreadsheets.sheets(broken)++ bomb = tmp_path / "bomb.xlsx"+ with ZipFile(bomb, "w", ZIP_DEFLATED) as archive, archive.open("filler", "w") as filler:+ block = bytes(16 * 1024**2)+ for _ in range(spreadsheets.MAX_EXPANDED_BYTES // len(block) + 1):+ filler.write(block)+ with pytest.raises(spreadsheets.SpreadsheetError, match="expands to more than"):+ spreadsheets.sheets(bomb)diff --git a/tests/test_dataset_store.py b/tests/test_dataset_store.pyindex 0211cfad..1ff4ce18 100644--- a/tests/test_dataset_store.py+++ b/tests/test_dataset_store.py@@ -187,7 +187,7 @@ def test_paste_detects_shape():def test_stream_rows_rejects_unknown_extension():with pytest.raises(files.FileError, match="Use a CSV"):- list(files.iter_stream_rows(io.StringIO("x"), filename="rows.xlsx"))+ list(files.iter_stream_rows(io.StringIO("x"), filename="rows.exe"))def test_query_exposes_declared_nested_columns_as_json(tmp_path):diff --git a/tests/test_dataset_streaming.py b/tests/test_dataset_streaming.pyindex 75b07718..b1cdf657 100644--- a/tests/test_dataset_streaming.py+++ b/tests/test_dataset_streaming.py@@ -75,7 +75,7 @@ def test_landing_measures_every_row_without_full_frame_reads(tmp_path, settings,monkeypatch.setattr(store, "read_frame", forbid)project = Project.objects.create(name="Streaming", slug="streaming")dataset = Dataset.objects.create(project=project, name="Native", intent="train")- landing = land.read_file(path, filename=path.name)+ landing = land.single(land.read_file(path, filename=path.name))land.commit(dataset, landing, infer_capability=False)source = dataset.sourceassert source.rows == 20_003diff --git a/tests/test_dataset_work.py b/tests/test_dataset_work.pyindex fa9aa7bb..abb5c1ad 100644--- a/tests/test_dataset_work.py+++ b/tests/test_dataset_work.py@@ -65,7 +65,7 @@ def test_landing_reports_rows_written_then_measuring(tmp_path):reported = []land.prepare(dataset,- land.read_file(source, filename="rows.jsonl"),+ land.single(land.read_file(source, filename="rows.jsonl")),path=tmp_path / "out.parquet",on_progress=reported.append,)diff --git a/tests/test_decision_prediction.py b/tests/test_decision_prediction.pyindex b82910a9..99517711 100644--- a/tests/test_decision_prediction.py+++ b/tests/test_decision_prediction.py@@ -30,19 +30,23 @@ def record():return {"key": "row", "decision": request, "input_sha256": digest_json(request)}-def prepare(records, context=1024):+def prepare(records, context=1024, instructions=""):output, failures = io.StringIO(), io.StringIO()result = prepare_requests(- records,- output,- failures,- None,- context,- encode_record,+ records, output, failures, None, context, encode_record, instructions=instructions)return result, output.getvalue(), failures.getvalue()+def test_instructions_precede_the_question_and_keep_the_input_identity():+ _, plain, _ = prepare(iter([record()]))+ _, variant, _ = prepare(iter([record()]), instructions="Be brief.")+ plain, variant = json.loads(plain), json.loads(variant)+ assert variant["input_sha256"] == plain["input_sha256"] == record()["input_sha256"]+ assert variant["input_ids"] != plain["input_ids"]+ assert "Be brief." in bytes(variant["input_ids"]).decode()++def test_native_prediction_preparation_keeps_identity_without_supervision():report, output, failures = prepare(iter([record()]))row = json.loads(output)diff --git a/tests/test_eval_judge_context_migration.py b/tests/test_eval_judge_context_migration.pynew file mode 100644index 00000000..8d704495--- /dev/null+++ b/tests/test_eval_judge_context_migration.py@@ -0,0 +1,56 @@+from datetime import timedelta++import pytest+from django.db.migrations.executor import MigrationExecutor+from django.utils import timezone+from migration_replay import scratch_database++pytestmark = pytest.mark.covers("migrations")+++def test_runs_pin_their_judges_and_keep_one_score_per_row(django_db_blocker):+ before = [("overbae", "0073_one_agent")]+ after = [("overbae", "0074_eval_judge_context_and_one_score_per_row")]+ with scratch_database(django_db_blocker) as database:+ executor = MigrationExecutor(database)+ executor.migrate(before)+ apps = executor.loader.project_state(before).apps+ project = apps.get_model("overbae", "Project").objects.create(name="P", slug="p")+ capability = apps.get_model("overbae", "Capability").objects.create(+ project=project, name="Support", description="Answer billing questions."+ )+ dataset = apps.get_model("overbae", "Dataset").objects.create(+ project=project, name="Tickets", capability=capability+ )+ runs = apps.get_model("overbae", "EvalRun").objects+ judged = runs.create(project=project, name="judged", dataset=dataset, judge_model="m-1")+ plain = runs.create(project=project, name="plain")+ rows = apps.get_model("overbae", "EvalRunRow").objects+ failed = rows.create(run=judged, row_index=0, error="scoring failed: Jev provider_timeout")+ lost = rows.create(run=judged, row_index=1, error="generation failed: timeout")+ scores = apps.get_model("overbae", "EvalScore").objects+ older = scores.create(project=project, run=judged, source_id="c:1", score=0.1)+ newer = scores.create(project=project, run=judged, source_id="c:1", score=0.9)+ scores.filter(pk=older.pk).update(created_at=timezone.now() - timedelta(hours=1))+ live = [scores.create(project=project, source_id="span", score=s) for s in (0.2, 0.3)]++ executor = MigrationExecutor(database)+ executor.migrate(after)+ apps = executor.loader.project_state(after).apps+ runs = apps.get_model("overbae", "EvalRun").objects+ rows = apps.get_model("overbae", "EvalRunRow").objects+ scores = apps.get_model("overbae", "EvalScore").objects++ assert runs.get(pk=judged.pk).judge_context == {+ "decision_model": "typesafe/jev-1.13",+ "explanation_models": ["m-1", "gpt-5-mini", "claude-haiku-4-5", "gemini-3.8-flash"],+ "intent": "Answer billing questions.",+ }+ assert runs.get(pk=plain.pk).judge_context["intent"] == ""+ assert rows.filter(pk=failed.pk).values_list("error", "score_error").get() == (+ "",+ "scoring failed: Jev provider_timeout",+ )+ assert rows.get(pk=lost.pk).error == "generation failed: timeout"+ assert list(scores.filter(run_id=judged.pk).values_list("pk", flat=True)) == [newer.pk]+ assert scores.filter(pk__in=[score.pk for score in live]).count() == 2diff --git a/tests/test_eval_judge_pinning.py b/tests/test_eval_judge_pinning.pynew file mode 100644index 00000000..6bd69241--- /dev/null+++ b/tests/test_eval_judge_pinning.py@@ -0,0 +1,56 @@+"""A run scores with the judges and intent pinned when it was created, also after a relaunch."""++import os++import pytest+from conftest import frozen_dataset+from factories import make_capability, make_matrix_row, make_project++from overbae.innermind import generation, runs+from overbae.models import EvalRun++pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("metrics-math")]+++def test_relaunched_run_scores_with_the_judges_and_intent_it_was_created_with(+ fake_llm, settings, monkeypatch+):+ monkeypatch.setenv("OPENROUTER_API_KEY", "pinning-test-key")+ settings.CACHES = {+ "default": {+ "BACKEND": "django.core.cache.backends.redis.RedisCache",+ "LOCATION": os.environ.get("TEST_REDIS_URL", "redis://localhost:6379/15"),+ }+ }+ project = make_project()+ capability = make_capability(project, description="Answer billing questions.")+ dataset = frozen_dataset(+ project, [{"input": "q", "expected_output": "a"}], capability=capability+ )+ run = runs.create_run(+ project=project,+ name="pinned",+ cell=dataset.active_cell,+ mode=EvalRun.Mode.RECORDED,+ matrix=[make_matrix_row(project).snapshot()],+ judge_model="claude-haiku-4-5",+ )+ # A registry change after creation: the run keeps the models it pinned.+ EvalRun.objects.filter(pk=run.pk).update(+ judge_context={**run.judge_context, "decision_model": "typesafe/jev-1.14"},+ status=EvalRun.Status.COMPLETED,+ )+ capability.description = "Something else entirely."+ capability.save()+ fake_llm.decide = lambda *_: "no"++ assert runs.relaunch(run)+ assert runs.start(run.pk) == "score"+ published = []+ generation.dispatch(lambda *_: None, lambda run_id, token: published.append(token))+ assert runs.score(run.pk, published[-1])++ decision = fake_llm.decisions[-1]+ assert decision["model"] == "typesafe/jev-1.14"+ assert "haiku" in fake_llm.requests[-1].body["model"]+ assert EvalRun.objects.get(pk=run.pk).judge_context["intent"] == "Answer billing questions."diff --git a/tests/test_eval_recovery.py b/tests/test_eval_recovery.pyindex 5f6d0b6e..609fb464 100644--- a/tests/test_eval_recovery.py+++ b/tests/test_eval_recovery.py@@ -7,6 +7,7 @@ from types import SimpleNamespaceimport pytestfrom conftest import frozen_dataset+from django.db import IntegrityErrorfrom django.utils import timezonefrom factories import make_matrix_row, make_project@@ -56,6 +57,7 @@ def test_a_lost_scorer_is_replaced_and_keeps_the_scores_it_saved():first = run.rows.order_by("row_index").first()dataset._save(EvalScore(project=run.project, run=run, source_id=f"{run.cell_id}:{first.row_index}"),+ first,lost,)silence(run)@@ -63,7 +65,7 @@ def test_a_lost_scorer_is_replaced_and_keeps_the_scores_it_saved():runs.reap_stalled()with pytest.raises(dataset.ScoringLostError):- dataset._save(EvalScore(project=run.project, run=run, source_id="late"), lost)+ dataset._save(EvalScore(project=run.project, run=run, source_id="late"), first, lost)with pytest.raises(dataset.ScoringLostError):dataset._row_failed(first, lost, "late judge error")replacement = handed(run)@@ -77,6 +79,28 @@ def test_a_lost_scorer_is_replaced_and_keeps_the_scores_it_saved():)+def test_a_row_that_failed_scoring_is_scored_by_the_next_scorer():+ run = scored_run()+ lost = handed(run)+ assert generation.begin_scoring(run.pk, lost)+ first = run.rows.order_by("row_index").first()+ dataset._row_failed(first, lost, "scoring failed: Jev provider_timeout")+ silence(run)+ runs.reap_stalled()++ assert runs.score(run.pk, handed(run))++ run.refresh_from_db()+ first.refresh_from_db()+ assert (first.error, first.score_error) == ("", "")+ assert run.summary["errored"] == 0+ assert run.scores.count() == len(ROWS)+ with pytest.raises(IntegrityError):+ EvalScore.objects.create(+ project=run.project, run=run, source_id=f"{run.cell_id}:{first.row_index}"+ )++def test_a_hand_off_that_waited_in_the_queue_starts_with_a_fresh_heartbeat():run = scored_run()token = handed(run)diff --git a/tests/test_experiments.py b/tests/test_experiments.pyindex e90ee191..f538af5e 100644--- a/tests/test_experiments.py+++ b/tests/test_experiments.py@@ -653,6 +653,49 @@ def test_an_evaluation_names_why_it_was_refused_or_scored_no_row(setup, monkeypaassert run.state == ExperimentRun.State.UNMET+def test_model_stages_of_one_model_are_evaluated_with_their_own_settings(setup, monkeypatch):+ from types import SimpleNamespace++ from overbae.tasks.innermind import run_eval_run++ context, cell = setup+ monkeypatch.setattr(run_eval_run, "delay", lambda **kwargs: SimpleNamespace(id="t"))+ make_matrix_row(context.project)+ concise = {+ "base_model": "openai/gpt-5-mini",+ "system_prompt": "Answer in one sentence.",+ "generation_strategy": "single_completion",+ "max_steps": 3,+ }+ experiment = records.create(+ context.project,+ context.user,+ document={+ "nodes": [+ {"id": "data", "kind": "data", "settings": {"cell": str(cell.pk)}},+ {"id": "plain", "kind": "model", "settings": {"base_model": "openai/gpt-5-mini"}},+ {"id": "concise", "kind": "model", "title": "Concise", "settings": concise},+ {+ "id": "eval",+ "kind": "evaluate",+ "inputs": {"data": ["data.data"], "model": ["plain.model", "concise.model"]},+ },+ ]+ },+ )+ run = runs.start(experiment, context.user, origin="console")+ runs.advance(run.pk)++ evaluated = {r.label: r.params for r in EvalRun.objects.filter(project=context.project)}+ assert "system_prompt" not in evaluated["openai/gpt-5-mini"]+ assert evaluated["openai/gpt-5-mini · Concise"] == {+ "label": "openai/gpt-5-mini · Concise",+ "system_prompt": "Answer in one sentence.",+ "generation_strategy": "single_completion",+ "max_steps": 3,+ }++def test_a_request_key_returns_its_run_only_for_the_same_request(setup):context, cell = setupexperiment = records.create(context.project, context.user, document=flow(cell.pk))diff --git a/tests/test_mcp_resources.py b/tests/test_mcp_resources.pyindex f54fb977..51883851 100644--- a/tests/test_mcp_resources.py+++ b/tests/test_mcp_resources.py@@ -180,6 +180,7 @@ def test_dataset_upload_resource_describes_cli_flow_and_server_limits():".jsonl",".ndjson",".parquet",+ ".xlsx",".pdf",".docx",".md",diff --git a/tests/test_native_evaluation_variants.py b/tests/test_native_evaluation_variants.pynew file mode 100644index 00000000..b054aba5--- /dev/null+++ b/tests/test_native_evaluation_variants.py@@ -0,0 +1,105 @@+"""A native evaluation compares prompt variants of one model, and a development measurement+also reads decision training rows; a final one reads only an evaluation dataset."""++import json++import pytest++from overbae.core.errors import InputValidationError+from overbae.models import Dataset, FinetuningJob, Project+from overbae.services import native_evaluation+from overbae.services.datasets import land+from overbae.services.decision_providers import question++pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]++REQUEST = {"state": "Evidence", "question": "Choose", "kind": "choice", "options": ["yes", "no"]}+++def suite(project, intent, row):+ dataset = Dataset.objects.create(project=project, name=intent, intent=intent)+ land.land_rows(dataset, [row(i) for i in range(3)])+ dataset.refresh_from_db()+ return dataset.active_cell+++def evaluation_row(i):+ return {+ "input": {"decision": {**REQUEST, "state": f"Evidence {i}"}},+ "expected_output": {"probabilities": [1, 0]},+ }+++def training_row(i):+ return {"decision": {**REQUEST, "state": f"Evidence {i}", "target_probabilities": [1, 0]}}+++def job():+ project = Project.objects.create(name="Variants", slug="variants")+ train = Dataset.objects.create(project=project, name="Train", intent="train")+ return FinetuningJob.objects.create(+ project=project,+ dataset=train,+ base_model="fixture",+ hyperparameters={"objective": "decision_cross_entropy"},+ status="running",+ )+++def plan(job, final_cell, *, purpose="final", instructions="Answer as a cautious reviewer."):+ return native_evaluation.create_plan(+ job.project,+ name="Prompts",+ request_key=f"{purpose}-{len(instructions)}",+ final_cell=final_cell,+ participants=[+ {"key": "plain", "name": "Plain", "kind": "trained", "job": str(job.pk)},+ {+ "key": "careful",+ "name": "Careful",+ "kind": "trained",+ "job": str(job.pk),+ "instructions": instructions,+ },+ ],+ baseline="plain",+ purpose=purpose,+ )+++def test_a_prompt_variant_is_prepared_on_its_own_and_its_receipt_must_match(job):+ variants = plan(job, suite(job.project, "eval", evaluation_row))++ assert variants.config["participants"][1]["instructions"] == "Answer as a cautious reviewer."+ assert "instructions" not in variants.config["participants"][0]+ assert native_evaluation.stage_sequence(variants)[1:5] == [+ "final_prepare",+ "final_prepare_careful",+ "final_plain",+ "final_careful",+ ]+ with pytest.raises(InputValidationError, match="instructions differ"):+ native_evaluation.collect(variants, "final_prepare_careful", {"instructions": ""})+ # System One reads the same instructions before the question.+ assert question(REQUEST, "Be brief.")["instructions"] == "Be brief.\n\nChoose"+ with pytest.raises(InputValidationError, match="at most 8000"):+ plan(job, variants.final_cell, instructions="x" * 8001)+++def test_development_reads_training_decisions_and_final_refuses_them(job, tmp_path, settings):+ settings.MEDIA_ROOT = tmp_path+ training = suite(job.project, "train", training_row)++ with pytest.raises(InputValidationError, match="evaluation dataset"):+ plan(job, training)+ development = plan(job, training, purpose="development")++ assert development.config["purpose"] == "development"+ inputs = native_evaluation.seal_suite(development, "final")+ references = [json.loads(line) for line in (inputs.parent / "references.jsonl").open()]+ assert [json.loads(line)["decision"] for line in inputs.open()][0] == {+ **REQUEST,+ "state": "Evidence 0",+ }+ assert [row["reference"] for row in references] == [{"probabilities": [1, 0]}] * 3diff --git a/uv.lock b/uv.lockindex eb8f5166..3f63bded 100644--- a/uv.lock+++ b/uv.lock@@ -271,6 +271,7 @@ dependencies = [{ name = "newrelic" },{ name = "numpy" },{ name = "openai" },+ { name = "openpyxl" },{ name = "opentelemetry-proto" },{ name = "orjson" },{ name = "overmind" },@@ -369,6 +370,7 @@ requires-dist = [{ name = "newrelic", specifier = ">=13.4.0" },{ name = "numpy", specifier = ">=2.0" },{ name = "openai", specifier = ">=1.0.0" },+ { name = "openpyxl", specifier = ">=3.1.5" },{ name = "opentelemetry-proto" },{ name = "orjson", specifier = ">=3.13.0" },{ name = "overmind", specifier = ">=0.1.97" },@@ -1232,6 +1234,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/fd/8a/75e3177f374877b19dd3112820b071836ad1100f9f58424630b4783519bc/emoji-2.16.0-py3-none-any.whl", hash = "sha256:c4230d80640def9071599ff56b1b5950fe13a2a94c0da98c5deab12431b24330", size = 610912, upload-time = "2026-09-16T19:47:55.507Z" },]+[[package]]+name = "et-xmlfile"+version = "2.0.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/d3/38/af70d7ab1ae9d4da450eeec1fa3918940a5fafb9055e934af8d6eb0c2313/et_xmlfile-2.0.0.tar.gz", hash = "sha256:dab3f4764309081ce75662649be815c4c9081e88f0837825f90fd28317d4da54", size = 17234, upload-time = "2024-10-25T17:25:40.039Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/c1/8b/5fe2cc11fee489817272089c4203e679c63b570a5aaeb18d852ae3cbba6a/et_xmlfile-2.0.0-py3-none-any.whl", hash = "sha256:7a91720bc756843502c3b7504c77b8fe44217c85c537d85037f0f536151b2caa", size = 18059, upload-time = "2024-10-25T17:25:39.051Z" },+]+[[package]]name = "execnet"version = "2.1.2"@@ -2673,6 +2684,18 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/9a/19/54eec742c937c0ed0de2b9d1ee679d7a502934e31bbd1ff4772322df0e62/openinference_semantic_conventions-0.1.39-py3-none-any.whl", hash = "sha256:2c98d7b9d2ce8b19fbd97d6a496a781fd32d7f31ea63575f1c0cbf8f349b29fa", size = 11701, upload-time = "2026-09-24T03:52:37.413Z" },]+[[package]]+name = "openpyxl"+version = "3.1.5"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "et-xmlfile" },+]+sdist = { url = "https://files.pythonhosted.org/packages/3d/f9/88d94a75de065ea32619465d2f77b29a0469500e99012523b91cc4141cd1/openpyxl-3.1.5.tar.gz", hash = "sha256:cf0e3cf56142039133628b5acffe8ef0c12bc902d2aadd3e0fe5878dc08d1050", size = 186464, upload-time = "2024-06-28T14:03:44.161Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/c0/da/977ded879c29cbd04de313843e76868e6e13408a94ed6b987245dc7c8506/openpyxl-3.1.5-py2.py3-none-any.whl", hash = "sha256:5282c12b107bffeef825f4617dc029afaf41d0ea60823bbb665ef3079dc79de2", size = 250910, upload-time = "2024-06-28T14:03:41.161Z" },+]+[[package]]name = "opentelemetry-api"version = "1.45.2"