Skip to content

The platform for continuously improving AI agents.

Remove the optimiser and backtesting (#355)

Freyam Mehta8135c7bfcbac
diff --git a/.agents/skills/api-endpoints/SKILL.md b/.agents/skills/api-endpoints/SKILL.md
index a4e8f4a0..51a5f408 100644
--- a/.agents/skills/api-endpoints/SKILL.md
+++ b/.agents/skills/api-endpoints/SKILL.md
@@ -9,7 +9,7 @@ The frontend consumes the backend exclusively through the generated typescript-f
## 1. Serializer and view go in the surface's own module
-`overbae/api/` is one module per surface — `eval_views.py`/`eval_serializers.py`, `datasets.py`/`dataset_serializers.py`, `optimizer.py`, `billing.py`, `otlp.py`, and so on. `views.py` and `serializers.py` are the legacy monoliths; a new surface gets its own module rather than growing them.
+`overbae/api/` is one module per surface — `eval_views.py`/`eval_serializers.py`, `datasets.py`/`dataset_serializers.py`, `billing.py`, `otlp.py`, and so on. `views.py` and `serializers.py` are the legacy monoliths; a new surface gets its own module rather than growing them.
Never return a raw dict from a view — request and response shapes are serializers. Keep business logic in `services/` or on the model; annotate with `@extend_schema` where drf-spectacular needs help.
diff --git a/.agents/skills/backend-architecture/SKILL.md b/.agents/skills/backend-architecture/SKILL.md
index ead7c7f8..978932c9 100644
--- a/.agents/skills/backend-architecture/SKILL.md
+++ b/.agents/skills/backend-architecture/SKILL.md
@@ -9,7 +9,7 @@ Single Django app `overbae`, project-scoped tenancy.
## Layout
-- `api/` — DRF views and serializers, one module per surface (`eval_views.py`, `datasets.py`, `optimizer.py`, `otlp.py`, `billing.py`, `mcp.py`, …). `views.py` and `serializers.py` are legacy monoliths; a new surface gets its own module. The global exception handler (`api/exception_handler.py`) flattens list errors to `{detail}`, adds `code`, maps `IntegrityError` to 409 `conflict`, and returns `{detail, code: internal_error, error_id}` for unhandled errors.
+- `api/` — DRF views and serializers, one module per surface (`eval_views.py`, `datasets.py`, `otlp.py`, `billing.py`, `mcp.py`, …). `views.py` and `serializers.py` are legacy monoliths; a new surface gets its own module. The global exception handler (`api/exception_handler.py`) flattens list errors to `{detail}`, adds `code`, maps `IntegrityError` to 409 `conflict`, and returns `{detail, code: internal_error, error_id}` for unhandled errors.
- `models/` — split by domain (`iam.py`, `capabilities.py`, `traces.py`, `innermind.py`, `finetuning.py`, `datasets.py`, `dataset_pipeline.py`, `operations.py`, `billing.py`, …).
- `innermind/` — the eval matrix evaluators, live span and trajectory scoring, deterministic checks, evaluation runs, the Default eval set, health and signals.
- `services/` — business logic. Largest subtrees: `datasets/` (Data Workshop; data-workshop skill), `mcp/` (mcp skill), `connectors/`, `sft_assets/` (training code baked into the Modal image), `codebase/`.
diff --git a/.agents/skills/backend-architecture/references/evaluation.md b/.agents/skills/backend-architecture/references/evaluation.md
index 18cafcc0..db610d17 100644
--- a/.agents/skills/backend-architecture/references/evaluation.md
+++ b/.agents/skills/backend-architecture/references/evaluation.md
@@ -2,12 +2,12 @@
## Runs
-An `EvalRun` scores one target (`mode` `recorded`, `generate` or `provided`) 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.
+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. A `provided` run cannot relaunch.
+- `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.
- 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.
-- An optimiser experiment reuses its first run's matrix for later candidates; a training job does the same for its evaluations.
+- 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; added and removed mark a metric present in only one run. 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.
diff --git a/.agents/skills/backend-architecture/references/serving.md b/.agents/skills/backend-architecture/references/serving.md
index 7689a6ba..e093f406 100644
--- a/.agents/skills/backend-architecture/references/serving.md
+++ b/.agents/skills/backend-architecture/references/serving.md
@@ -25,7 +25,7 @@ A ready `DeployedModel` has at most one live `DedicatedDeployment` on the privat
## Activation
-`services/model_activation.py` makes a ready deployment live. REST `active_model` and MCP `set_active_model` persist a per-capability `ModelActivation`; the deployment reconciler wakes and verifies through `pre_warm`, then switches the alias atomically. The previous target serves until verification succeeds and stays saved for switch-back. Only successful application API-key calls to the alias advance the connection timestamps; probes, pinned calls and optimiser traffic never do.
+`services/model_activation.py` makes a ready deployment live. REST `active_model` and MCP `set_active_model` persist a per-capability `ModelActivation`; the deployment reconciler wakes and verifies through `pre_warm`, then switches the alias atomically. The previous target serves until verification succeeds and stays saved for switch-back. Only successful application API-key calls to the alias advance the connection timestamps; probes and pinned calls never do.
## Inference requests
diff --git a/.agents/skills/seed-demo-data/SKILL.md b/.agents/skills/seed-demo-data/SKILL.md
index 304b7f47..37769b20 100644
--- a/.agents/skills/seed-demo-data/SKILL.md
+++ b/.agents/skills/seed-demo-data/SKILL.md
@@ -10,7 +10,7 @@ company — with thirty days of traffic across three capabilities (ticket triage
KB answering, dispute resolution) and every downstream surface filled: an eval
matrix and eval sets, live span and trajectory scores with `EvalScore` history,
signal subscriptions and events, sessions, datasets with immutable cell chains,
-grouped eval runs, optimiser runs (harness, model comparison), training jobs
+grouped eval runs, training jobs
with judge evals and class metrics, deployed models with inference traffic, and
the credits ledger.
@@ -35,7 +35,7 @@ labelled Demo; they never imply that a real coding agent performed the seeded wo
Celery beat + reconcilers stay running against the seeded DB. Violations cause
workers to re-drive seeded rows against **real providers** and spend credits:
-- Every `EvalRun` / `FinetuningJob` / `OptimizerExperiment` / dataset `Cell`
+- Every `EvalRun` / `FinetuningJob` / dataset `Cell`
is TERMINAL (reconcilers re-drive non-terminal rows within 10–60s).
- The span sweep re-scores any span whose `eval_attributes` lacks a `score`
key, and the trajectory sweep any root from the last day with a `score` but
diff --git a/AGENTS.md b/AGENTS.md
index da4547d2..6c529e71 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -34,7 +34,7 @@ This file is the playbook every task needs; Claude Code, Codex and Cursor read i
- Work-starting operations take a project-scoped request key: an identical retry returns the same record, and a changed payload conflicts. An unknown provider acknowledgement is reconciled from its saved call ID, never resubmitted.
- Measured facts only. Missing usage, progress, scores and telemetry stay unknown; never fill them with a percentage, a zero, an ETA or elapsed time.
- Code under `overbae/modal/`, `modal_shared/` and `overbae/services/sft_assets/` reaches Modal only after `modal deploy`; training and serving pin immutable releases.
-- Naming: UI "Optimiser" is backend `optimizer`; UI "Training" is backend `finetuning`; UI "Capability" is the `Capability` model, and the sidebar's "Agent" is the project graph.
+- Naming: UI "Training" is backend `finetuning`; UI "Capability" is the `Capability` model, and the sidebar's "Agent" is the project graph.
- Overwatch (`/api/internal/overwatch/*`, app in `sales-dashboard/`) only reads product records and runs no user authentication. Its tokens, caches and Slack boundary are in backend-architecture `references/auth-and-billing.md`.
- `DESIGN.md` carries a fixed YAML frontmatter schema that tooling reads. Extend the values; don't restructure the document.
diff --git a/DESIGN.md b/DESIGN.md
index e176fc48..30cf028f 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -272,7 +272,7 @@ colour across every chart.
An entity's icon carries the accent of its type (`ENTITY_META` in
`components/entity-ref/shell.tsx`): trace `cat-1`, dataset `cat-2`, capability and
-eval run `cat-3`, model `cat-4`, optimisation and training run `cat-5`, project
+eval run `cat-3`, model `cat-4`, training run `cat-5`, project
`cat-6`. The label stays neutral. The accent is the type, never a status: a green
dataset icon does not mean success. `FileTypeIcon` gives a file the accent of what
it holds. Provider logos use the full-colour mark where `@lobehub/icons` has one.
@@ -655,12 +655,12 @@ tones get away with a 1.65:1 border because their hue does the work.
### Navigation
-- **Sidebar:** 16rem expanded, 3rem icon-collapsed, 18rem mobile. Labels in
- NeueBit at 1.46em with +0.05em tracking. Transparent border and accent; the
- separation comes from background tone alone.
+- **Sidebar:** One flat list of first-level items. 16rem expanded, 3rem
+ icon-collapsed, 18rem mobile. Labels in NeueBit at 1.46em with +0.05em
+ tracking. Transparent border and accent; the separation comes from background
+ tone alone.
- **Active row:** 8% foreground tint, a genuine 700 bitmap cut, foreground-tinted
icon, 2px radius.
-- **Sub-items:** Connected by the stepped pixel elbow described in Shapes.
- **Breadcrumbs:** Chevron-separated, NeueBit, active crumb bold, inactive
`text-muted-foreground hover:text-foreground`.
@@ -808,7 +808,7 @@ train table**, **Does not match Research Agent**, **Intent pending**, else
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
consumers in the primary tint on the right: a train table offers **Train a
-model**; an eval table offers **Run the optimiser** and **Use in a training
+model**; an eval table offers **Use in a training
job** (the eval dataset that scores the job); each opens the wizard on its
page with the current published dataset selected, without changing its active cell.
Other cells have no activation control or empty action footer. The Console cannot
@@ -877,7 +877,7 @@ deletion with an actionable error. Both formats include a run-details card with
Probability runs show participants, the baseline, exact dataset versions and row
counts, optional calibration data, timestamps and status. Completion time comes
from the recorded scoring observation; missing credit usage remains unmeasured.
-Evaluation details have no Optimise action. Probability metrics appear above the shared-style
+Probability metrics appear above the shared-style
comparison table, with models as rows and measured metrics as columns. The baseline
appears once. Model comparison uses the same DataTable, compact model/baseline
badges and resizable columns as other Console lists, with benchmark group rows
diff --git a/README.md b/README.md
index a02bceb1..01e967b9 100644
--- a/README.md
+++ b/README.md
@@ -29,7 +29,6 @@ Available from the [Console](https://console.overmindlab.ai/?utm_source=github&u
<tr><td><b><a href="https://docs.overmindlab.ai/how-to/investigate">Observability</a></b></td><td>OpenTelemetry traces, scored as they arrive and matched to the capability that produced them.</td></tr>
<tr><td><b><a href="https://docs.overmindlab.ai/how-to/prepare-data">Datasets</a></b></td><td>Production traces or uploaded files become versioned eval and training datasets.</td></tr>
<tr><td><b><a href="https://docs.overmindlab.ai/how-to/evaluate">Eval</a></b></td><td>What "good" means per capability, measured on live traces and in batch.</td></tr>
-<tr><td><b><a href="https://docs.overmindlab.ai/how-to/optimise">Optimisers</a></b></td><td>Prompt, tool, and control-flow experiments in your repo; the winner is a git diff.</td></tr>
<tr><td><b><a href="https://docs.overmindlab.ai/how-to/train">Models</a></b></td><td>Fine-tunes you own, trained on your data and benchmarked against production.</td></tr>
<tr><td><b><a href="https://docs.overmindlab.ai/how-to/serve">Inference</a></b></td><td>Trained and frontier models on one OpenAI-compatible API.</td></tr>
</table>
@@ -46,13 +45,13 @@ Available from the [Console](https://console.overmindlab.ai/?utm_source=github&u
Sign up at [console.overmindlab.ai](https://console.overmindlab.ai/?utm_source=github&utm_medium=readme&utm_campaign=always-on&utm_content=readme-get-started), copy the onboarding prompt from **Get started**, and paste it into your coding agent (Cursor, Claude Code, OpenCode or Codex) with your agent's repo root open. The **Data** tab starts from an uploaded dataset instead. It installs `overmind`, runs `overmind init` and `overmind sync`, and maps the agent's capabilities. From then on everything is a `/overmind` command in the same chat:
-| Command | What it does |
-| -------------------------- | --------------------------------------------- |
-| `/overmind ensure-tracing` | Inspect traces and instrument the agent |
-| `/overmind dataset` | Build, clean, upload or export a dataset |
-| `/overmind finetune` | Fine-tune, deploy and smoke-test a model |
-| `/overmind optimise` | Run prompt and code optimisation |
-| `/overmind backtest` | Compare models against the agent's own traces |
+| Command | What it does |
+| -------------------------- | ---------------------------------------- |
+| `/overmind ensure-tracing` | Inspect traces and instrument the agent |
+| `/overmind dataset` | Build, clean, upload or export a dataset |
+| `/overmind finetune` | Fine-tune, deploy and smoke-test a model |
+| `/overmind improve` | Change a prompt or code and measure it |
+| `/overmind compare-models` | Score other models on recorded calls |
### Run it yourself
@@ -75,7 +74,7 @@ The API refuses to start until every required key is set, and the error names ea
| Required | Used for |
| --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
-| `OPENROUTER_API_KEY` | Judges, evals, trace scoring, optimiser scoring. Frontier chat proxy only when `OPENROUTER_PROXY_ENABLED=1` |
+| `OPENROUTER_API_KEY` | Judges, evals and trace scoring. Frontier chat proxy only when `OPENROUTER_PROXY_ENABLED=1` |
| `MODAL_TOKEN_ID`, `MODAL_TOKEN_SECRET` | Modal training and serving workers (set `MODAL_ENVIRONMENT` explicitly) |
| `INFERENCE_API_URL`, `INFERENCE_API_KEY` | Serving trained models — the endpoint printed by `modal deploy` and its shared secret |
| `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_BUCKET_NAME` | The fine-tuning checkpoint archive |
@@ -204,7 +203,6 @@ http_headers = { "X-Api-Key" = "ovr_…" }
| Evaluations | `check_evaluation_readiness`, `create_eval_set`, `create_eval_matrix_row`, `delete_eval_matrix_row`, `run_evaluation`, `compare_evaluations` |
| Training | `check_finetune_readiness`, `prepare_training_data`, `estimate_finetune`, `start_finetune`, `inspect_training_progress`, `cancel_finetune`, `deploy_finetune`, `retry_deployment`, `set_active_model`, `run_inference`, `get_model_swap_prompt` |
| Decision models | `list_decision_models`, `start_decision_job`, `create_native_evaluation`, `inspect_native_evaluation`, `create_training_experiment`, `measure_decision_performance` |
-| Optimiser | `check_optimizer_readiness`, `start_optimizer`, `inspect_optimizer_result` |
| Connectors | `inspect_connectors`, `configure_connector`, `sync_connector` |
| Instrumentation | `get_instrumentation_plan`, `verify_instrumentation` |
| Catalog | `get_model_catalog`, `list_model_workflows` |
diff --git a/frontend/public/setup.md b/frontend/public/setup.md
index c0de66d3..15e7a183 100644
--- a/frontend/public/setup.md
+++ b/frontend/public/setup.md
@@ -55,16 +55,14 @@ ______________________________________________________________________
Overmind has the following features
-| Feature | Reference |
-| ----------------- | --------------------------------------------------------------------- |
-| Agent Scanning | [Code scanning and eval authoring](#code-scanning-and-eval-authoring) |
-| Observability | [Telemetry](#telemetry) |
-| Dataset | [Datasets](#datasets) |
-| Evaluations | [Evals](#evals) |
-| Finetuning | [Finetuning](#finetuning) |
-| Optimiser | [Optimiser](#optimiser) |
-| Model Backtesting | [Backtesting](#backtesting) |
-| Inference | [Inference](#inference) |
+| Feature | Reference |
+| -------------- | --------------------------------------------------------------------- |
+| Agent Scanning | [Code scanning and eval authoring](#code-scanning-and-eval-authoring) |
+| Observability | [Telemetry](#telemetry) |
+| Dataset | [Datasets](#datasets) |
+| Evaluations | [Evals](#evals) |
+| Finetuning | [Finetuning](#finetuning) |
+| Inference | [Inference](#inference) |
## Code scanning and eval authoring
@@ -123,23 +121,6 @@ Overmind has the following features
- Split by group before fitting, measure a baseline, and never select on final-role data.
- Use the skill `/overmind-training` to run finetuning operations
-## Optimiser
-
-> Runs an agent in your infrastructure to experiment with different prompts and models and find which works best. All results are backed by evaluations
-
-- Needs an `eval` dataset cell.
-- Flow: `check_optimizer_readiness`, `start_optimizer`, then run `overmind optimise start -e EXPERIMENT && overmind optimise next` in the repo and do each returned action.
-- Stop at `COMPLETE`. Apply the winning diff only when authorised.
-- Use the skill `/overmind-optimiser` to run optimiser operations
-
-## Backtesting
-
-> Tries different models and replays your LLM spans to see which model works best
-
-- Use the `compare-models` prompt: `check_optimizer_readiness` and `start_optimizer` with `mode=model_comparison` and 1-5 model ids, then `inspect_optimizer_result`.
-- Or replay stored LLM spans: `overmind backtest --models a,b --since 7d`.
-- Use the skill `/overmind-optimiser` to run backtesting operations
-
## Inference
> Runs inference on the finetuned model through Overmind.
diff --git a/frontend/scripts/check-controls.mjs b/frontend/scripts/check-controls.mjs
index 8b460208..87565349 100644
--- a/frontend/scripts/check-controls.mjs
+++ b/frontend/scripts/check-controls.mjs
@@ -131,11 +131,9 @@ const ACRONYMS =
const PRODUCT_TERMS = [
"ChatGPT",
"Data Workshop",
- "Agent Testing",
"Model Training",
"Context Graph",
"Overmind",
- "Optimiser",
"Observability",
"Console",
"Datasets",
diff --git a/frontend/src/client.ts b/frontend/src/client.ts
index dd828785..e2180d82 100644
--- a/frontend/src/client.ts
+++ b/frontend/src/client.ts
@@ -51,7 +51,6 @@ import {
McpOauthApi,
ModelsApi,
NativeEvaluationsApi,
- OptimizerExperimentsApi,
ProjectsApi,
ResponseError,
SessionsApi,
@@ -324,20 +323,13 @@ const PRESERVE_VALUE_KEYS = new Set([
"outputData",
"evaluationCriteria",
"improvementMetadata",
- "capabilityDescription",
- "backtestModelSuggestions",
"scores",
"feedbackScores",
"feedbackScore",
"inputSchema",
"outputFields",
"toolConfig",
- "dimensionScores",
- "backtestResults",
"settings",
- "consistencyRules",
- "optimizableElements",
- "fixedElements",
"input",
"expectedOutput",
"manifest",
@@ -461,7 +453,6 @@ export class API {
decisionJobs: DecisionJobsApi;
decisionModels: DecisionModelsApi;
decisionPerformance: DecisionPerformanceApi;
- optimizerExperiments: OptimizerExperimentsApi;
/** OTLP trace ingestion (`POST /api/v1/traces`). */
projects: ProjectsApi;
/** Traces grouped by `conversation.id`. */
@@ -507,7 +498,6 @@ export class API {
this.decisionJobs = new DecisionJobsApi(this.cfg);
this.decisionModels = new DecisionModelsApi(this.cfg);
this.decisionPerformance = new DecisionPerformanceApi(this.cfg);
- this.optimizerExperiments = new OptimizerExperimentsApi(this.cfg);
this.projects = new ProjectsApi(this.cfg);
this.sessions = new SessionsApi(this.cfg);
this.traces = new TracesApi(this.cfg);
diff --git a/frontend/src/components/activity-links.tsx b/frontend/src/components/activity-links.tsx
index 517cf288..6b03620b 100644
--- a/frontend/src/components/activity-links.tsx
+++ b/frontend/src/components/activity-links.tsx
@@ -105,18 +105,6 @@ export function ActivityTaskChip({
Evaluation task
</Link>
);
- if (kind === "optimizer_experiment")
- return (
- <Link
- className={chipClass}
- params={{ experimentId: id }}
- search={{ projectId }}
- to="/optimiser/$experimentId"
- >
- <Icon.optimiser className="size-3" />
- Optimiser task
- </Link>
- );
return (
<Badge className="gap-1.5" size="chip" variant="neutral">
<Icon.listBox className="size-3" />
diff --git a/frontend/src/components/app-sidebar.tsx b/frontend/src/components/app-sidebar.tsx
index 01e250bd..c2fc29f5 100644
--- a/frontend/src/components/app-sidebar.tsx
+++ b/frontend/src/components/app-sidebar.tsx
@@ -1,4 +1,4 @@
-import { type ComponentType, type CSSProperties, type SVGProps, useEffect, useState } from "react";
+import { type ComponentType, type SVGProps, useEffect, useState } from "react";
import { Link, useRouterState, useSearch } from "@tanstack/react-router";
@@ -10,7 +10,6 @@ import {
JobNotificationBadge,
type JobNotificationBadgeTone,
} from "@/components/job-notification-badge";
-import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Icon } from "@/components/ui/icons";
import {
Sidebar,
@@ -22,16 +21,12 @@ import {
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
- SidebarMenuSub,
- SidebarMenuSubButton,
- SidebarMenuSubItem,
useSidebar,
} from "@/components/ui/sidebar";
import { useAuthContext } from "@/contexts/auth-context";
import { useAllEvalRunsQuery } from "@/hooks/use-evaluations";
import { useFinetuningJobsQuery } from "@/hooks/use-finetuning";
import { useGuestGate } from "@/hooks/use-guest-gate";
-import { useOptimizerExperimentsQuery } from "@/hooks/use-optimizer";
import { useOnboardingStatus } from "@/hooks/use-query";
import { useUnseenSignalCountQuery } from "@/hooks/use-signals";
import { featureFlags } from "@/lib/feature-flags";
@@ -43,7 +38,6 @@ import {
kindsForPathname,
useUnseenCompletions,
} from "@/lib/unseen-job-completions";
-import { cn } from "@/lib/utils";
type IconType = ComponentType<SVGProps<SVGSVGElement>>;
type Flag = keyof typeof featureFlags;
@@ -55,37 +49,15 @@ interface NavLeaf {
to: string;
}
-interface NavGroup {
- icon: IconType;
- label: string;
- items: NavLeaf[];
-}
-
-type NavEntry = NavLeaf | NavGroup;
-
-const isGroup = (entry: NavEntry): entry is NavGroup => "items" in entry;
const flagOn = (flag: Flag | null): boolean => flag === null || featureFlags[flag];
-const platformNavTree: NavEntry[] = [
+const platformNavTree: NavLeaf[] = [
{ flag: null, icon: Icon.agent, label: "Agent", to: "/" },
{ flag: null, icon: Icon.observability, label: "Observability", to: "/observability" },
{ flag: "datasets", icon: Icon.dataset, label: "Datasets", to: "/datasets" },
- {
- icon: Icon.agentTesting,
- items: [
- { flag: "evaluations", icon: Icon.eval, label: "Evaluations", to: "/evaluations" },
- { flag: "evaluations", icon: Icon.optimiser, label: "Optimiser", to: "/optimiser" },
- ],
- label: "Agent Testing",
- },
- {
- icon: Icon.models,
- items: [
- { flag: "finetuning", icon: Icon.training, label: "Training", to: "/training" },
- { flag: "inference", icon: Icon.inference, label: "Inference", to: "/inference" },
- ],
- label: "Models",
- },
+ { flag: "evaluations", icon: Icon.eval, label: "Evaluations", to: "/evaluations" },
+ { flag: "finetuning", icon: Icon.training, label: "Training", to: "/training" },
+ { flag: "inference", icon: Icon.inference, label: "Inference", to: "/inference" },
];
// Not rendered in the sidebar — Settings is the top-bar gear and Projects sits
@@ -96,20 +68,10 @@ const configNavTree: NavLeaf[] = [
{ flag: null, icon: Icon.integrations, label: "Integrations", to: "/observability/integrations" },
];
-const filterNav = (tree: NavEntry[]): NavEntry[] =>
- tree
- .map((entry) =>
- isGroup(entry) ? { ...entry, items: entry.items.filter((i) => flagOn(i.flag)) } : entry
- )
- .filter((entry) => (isGroup(entry) ? entry.items.length > 0 : flagOn(entry.flag)));
-
-const platformNav: NavEntry[] = filterNav(platformNavTree);
+const platformNav: NavLeaf[] = platformNavTree.filter((leaf) => flagOn(leaf.flag));
const configNav: NavLeaf[] = configNavTree.filter((leaf) => flagOn(leaf.flag));
-export const navLinks: NavLeaf[] = [
- ...platformNav.flatMap((entry) => (isGroup(entry) ? entry.items : [entry])),
- ...configNav,
-];
+export const navLinks: NavLeaf[] = [...platformNav, ...configNav];
const externalLinks = [
{ href: "https://docs.overmindlab.ai", icon: Icon.docs, label: "Docs" },
@@ -122,7 +84,6 @@ const isLeafActive = (pathname: string, to: string): boolean =>
const JOB_KIND_ROUTE: Record<RunningJobKind, string> = {
eval: "/evaluations",
finetuning: "/training",
- optimizer: "/optimiser",
};
type NavJobBadge = { count: number; tone: JobNotificationBadgeTone };
@@ -132,7 +93,6 @@ function useNavJobBadges(): Record<string, NavJobBadge> {
const { projectId } = useSearch({ from: "/_auth" });
const ftQuery = useFinetuningJobsQuery(projectId);
const evalQuery = useAllEvalRunsQuery(projectId);
- const optimizerQuery = useOptimizerExperimentsQuery(projectId);
const unseen = useUnseenCompletions();
const unseenSignals =
useUnseenSignalCountQuery(featureFlags.signals ? projectId : undefined).data ?? 0;
@@ -140,7 +100,6 @@ function useNavJobBadges(): Record<string, NavJobBadge> {
const running = buildRunningJobs({
evalRuns: evalQuery.data?.results,
finetuning: ftQuery.data?.results,
- optimizerExperiments: optimizerQuery.data?.results,
});
const runningByRoute: Record<string, number> = {};
@@ -213,105 +172,6 @@ function NavLink({
);
}
-// The trigger deliberately takes no `tooltip` prop: `CollapsibleTrigger asChild`
-// and the tooltip wrapper clash over the ref and swallow the toggle click.
-function NavGroupItem({
- group,
- pathname,
- badges,
-}: {
- group: NavGroup;
- pathname: string;
- badges: Record<string, NavJobBadge>;
-}) {
- const { icon: IconCmp, items, label } = group;
- const guard = useGuestGate();
- const hasActiveChild = items.some((item) => isLeafActive(pathname, item.to));
- return (
- <Collapsible asChild className="group/collapsible" defaultOpen>
- <SidebarMenuItem>
- <CollapsibleTrigger asChild>
- <SidebarMenuButton className="!py-2.5" isActive={hasActiveChild}>
- <IconCmp className="!size-[17px]" />
- <span className="sidebar-label flex-1">{label}</span>
- <Icon.chevronRight className="ml-auto !size-4 shrink-0 text-muted-foreground transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
- </SidebarMenuButton>
- </CollapsibleTrigger>
- <CollapsibleContent>
- {/* border-l-0 drops the primitive's 1px trunk; each item draws its own. */}
- <SidebarMenuSub className="mr-0 border-l-0 pr-0">
- {items.map((item, index) => {
- const ItemIcon = item.icon;
- const active = isLeafActive(pathname, item.to);
- return (
- <SidebarMenuSubItem
- // `.sidebar-elbow::before` (styles.css) draws each item's own
- // connector. Every trunk starts at one shared point 0.75rem
- // above the FIRST row's centre and ends at its own row's
- // centre — hence the row pitch (2rem) times index. The active
- // line is raised above the muted ones, and its colour must
- // stay on the sidebar's semantic palette.
- className={cn("sidebar-elbow", active && "z-10")}
- key={item.to}
- style={
- {
- "--elbow-h": `calc(${index} * 2rem + 0.75rem)`,
- ...(active && { "--elbow-color": "var(--sidebar-foreground)" }),
- } as CSSProperties
- }
- >
- <SidebarMenuSubButton asChild isActive={active}>
- <Link
- onClick={item.to === "/" ? undefined : guard()}
- search={(e) => ({ projectId: e.projectId })}
- to={item.to}
- >
- <ItemIcon className="!size-[15px]" />
- <span className="sidebar-label">{item.label}</span>
- {badges[item.to] ? <NavJobCountBadge badge={badges[item.to]} /> : null}
- </Link>
- </SidebarMenuSubButton>
- </SidebarMenuSubItem>
- );
- })}
- </SidebarMenuSub>
- </CollapsibleContent>
- </SidebarMenuItem>
- </Collapsible>
- );
-}
-
-function NavSection({
- entries,
- iconOnly,
- pathname,
- badges = {},
-}: {
- entries: NavEntry[];
- iconOnly: boolean;
- pathname: string;
- badges?: Record<string, NavJobBadge>;
-}) {
- return (
- <>
- {entries.map((entry) => {
- if (!isGroup(entry)) {
- return (
- <NavLink badge={badges[entry.to]} key={entry.to} leaf={entry} pathname={pathname} />
- );
- }
- return iconOnly ? (
- entry.items.map((leaf) => (
- <NavLink badge={badges[leaf.to]} key={leaf.to} leaf={leaf} pathname={pathname} />
- ))
- ) : (
- <NavGroupItem badges={badges} group={entry} key={entry.label} pathname={pathname} />
- );
- })}
- </>
- );
-}
-
function ExternalNavLink({ href, icon: Icon, label }: (typeof externalLinks)[number]) {
return (
<SidebarMenuItem>
@@ -406,12 +266,14 @@ export function AppSidebar({ collapsible = "icon", onSearchOpen }: AppSidebarPro
</SidebarMenuButton>
</SidebarMenuItem>
)}
- <NavSection
- badges={navJobBadges}
- entries={platformNav}
- iconOnly={iconOnly}
- pathname={location.pathname}
- />
+ {platformNav.map((leaf) => (
+ <NavLink
+ badge={navJobBadges[leaf.to]}
+ key={leaf.to}
+ leaf={leaf}
+ pathname={location.pathname}
+ />
+ ))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
diff --git a/frontend/src/components/capability-detail/EvalMatrixTab.tsx b/frontend/src/components/capability-detail/EvalMatrixTab.tsx
deleted file mode 100644
index d6f036f6..00000000
--- a/frontend/src/components/capability-detail/EvalMatrixTab.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { useState } from "react";
-
-import { EvalMatrixTable } from "@/components/evaluations/eval-matrix-table";
-import { RunLocallyDialog } from "@/components/optimiser/run-locally-dialog";
-import { Button } from "@/components/ui/button";
-import { Icon } from "@/components/ui/icons";
-import { useGuestGate } from "@/hooks/use-guest-gate";
-import type { Capability } from "@/openapi";
-
-export function EvalMatrixTab({
- capabilityId,
- capability,
- projectId,
-}: {
- capabilityId: string;
- capability: Capability;
- projectId: string;
-}) {
- const guard = useGuestGate();
- const [optimiseOpen, setOptimiseOpen] = useState(false);
-
- return (
- <>
- <EvalMatrixTable
- actions={
- <Button onClick={guard(() => setOptimiseOpen(true))} size="sm" variant="secondary">
- <Icon.optimiser />
- Optimise
- </Button>
- }
- capability={capability}
- capabilityId={capabilityId}
- projectId={projectId}
- />
- <RunLocallyDialog
- capabilityId={capabilityId}
- onOpenChange={setOptimiseOpen}
- open={optimiseOpen}
- projectId={projectId}
- />
- </>
- );
-}
diff --git a/frontend/src/components/capability-detail/next-step-nudge.tsx b/frontend/src/components/capability-detail/next-step-nudge.tsx
index 6c40c689..8ba5d35d 100644
--- a/frontend/src/components/capability-detail/next-step-nudge.tsx
+++ b/frontend/src/components/capability-detail/next-step-nudge.tsx
@@ -41,17 +41,6 @@ export function CapabilityNextStepNudge({
queryKey: ["finetuning-jobs", projectId, "capability", capabilityId],
staleTime: 30_000,
});
- const experimentsQuery = useQuery({
- enabled: featureFlags.evaluations && enabled,
- queryFn: () =>
- apiClient.optimizerExperiments.optimizerExperimentsList({
- capability: capabilityId,
- pageSize: 1,
- }),
- queryKey: ["capability-experiments-count", capabilityId],
- staleTime: 30_000,
- });
-
const datasets = (datasetsQuery.data?.results ?? []).map((d) => ({
contract: d.activeVersion ? (d.intent ?? null) : null,
}));
@@ -61,11 +50,9 @@ export function CapabilityNextStepNudge({
finetuningJobs: jobsQuery.data?.results ?? [],
flags: {
datasets: featureFlags.datasets,
- evaluations: featureFlags.evaluations,
finetuning: featureFlags.finetuning,
inference: featureFlags.inference,
},
- optimiserExperimentCount: experimentsQuery.data?.count ?? 0,
});
const dismissKey = nudge ? DISMISS_KEY(nudge.kind, capabilityId) : "";
@@ -100,11 +87,6 @@ const COPY = {
Icon: Icon.finetuning,
title: "Fine-tune a model",
},
- optimise: {
- description: "An eval dataset is ready",
- Icon: Icon.optimiser,
- title: "Optimise your agent",
- },
upload: {
description: "No datasets attached to this capability",
Icon: Icon.upload,
@@ -140,13 +122,6 @@ function ctaLink(
Fine-tune
</Link>
);
- case "optimise":
- return (
- <Link search={{ capabilityId, optimize: true, projectId }} to="/optimiser">
- <Icon.optimiser />
- Optimise
- </Link>
- );
case "upload":
return (
<Link search={{ create: true, ds_capability: capabilityId, projectId }} to="/datasets">
diff --git a/frontend/src/components/capability-detail/pick-capability-nudge.test.ts b/frontend/src/components/capability-detail/pick-capability-nudge.test.ts
index cc8b1d10..edece3aa 100644
--- a/frontend/src/components/capability-detail/pick-capability-nudge.test.ts
+++ b/frontend/src/components/capability-detail/pick-capability-nudge.test.ts
@@ -5,7 +5,6 @@ import { pickCapabilityNudge } from "./pick-capability-nudge";
const ALL_FLAGS = {
datasets: true,
- evaluations: true,
finetuning: true,
inference: true,
};
@@ -18,23 +17,10 @@ describe("pickCapabilityNudge", () => {
deployedModels: [],
finetuningJobs: [],
flags: ALL_FLAGS,
- optimiserExperimentCount: 0,
})
).toEqual({ kind: "upload" });
});
- it("returns optimise when an eval dataset exists and no experiments", () => {
- expect(
- pickCapabilityNudge({
- datasets: [{ contract: "eval" }],
- deployedModels: [],
- finetuningJobs: [],
- flags: ALL_FLAGS,
- optimiserExperimentCount: 0,
- })
- ).toEqual({ kind: "optimise" });
- });
-
it("returns finetune when an ft dataset exists and no jobs", () => {
expect(
pickCapabilityNudge({
@@ -42,19 +28,17 @@ describe("pickCapabilityNudge", () => {
deployedModels: [],
finetuningJobs: [],
flags: ALL_FLAGS,
- optimiserExperimentCount: 0,
})
).toEqual({ kind: "finetune" });
});
- it("prefers finetune over optimise when both datasets exist", () => {
+ it("returns finetune when eval and training datasets both exist", () => {
expect(
pickCapabilityNudge({
datasets: [{ contract: "eval" }, { contract: "train" }],
deployedModels: [],
finetuningJobs: [],
flags: ALL_FLAGS,
- optimiserExperimentCount: 0,
})?.kind
).toBe("finetune");
});
@@ -66,7 +50,6 @@ describe("pickCapabilityNudge", () => {
deployedModels: [{ finetuningJobId: "j1", id: "m1", status: "failed" }],
finetuningJobs: [{ createdAt: "2024-01-02", id: "j1", status: "succeeded" }],
flags: ALL_FLAGS,
- optimiserExperimentCount: 1,
})
).toEqual({ jobId: "j1", kind: "deploy", modelId: "m1" });
});
@@ -78,7 +61,6 @@ describe("pickCapabilityNudge", () => {
deployedModels: [{ finetuningJobId: "j1", id: "m1", status: "ready" }],
finetuningJobs: [{ createdAt: "2024-01-02", id: "j1", status: "succeeded" }],
flags: ALL_FLAGS,
- optimiserExperimentCount: 1,
})
).toBeNull();
});
@@ -90,7 +72,6 @@ describe("pickCapabilityNudge", () => {
deployedModels: [],
finetuningJobs: [{ id: "j1", status: "running" }],
flags: ALL_FLAGS,
- optimiserExperimentCount: 0,
})
).toBeNull();
});
@@ -102,7 +83,6 @@ describe("pickCapabilityNudge", () => {
deployedModels: [],
finetuningJobs: [],
flags: { ...ALL_FLAGS, datasets: false },
- optimiserExperimentCount: 0,
})
).toBeNull();
});
diff --git a/frontend/src/components/capability-detail/pick-capability-nudge.ts b/frontend/src/components/capability-detail/pick-capability-nudge.ts
index 4ad823e0..012d5e75 100644
--- a/frontend/src/components/capability-detail/pick-capability-nudge.ts
+++ b/frontend/src/components/capability-detail/pick-capability-nudge.ts
@@ -1,7 +1,7 @@
/** Live serving statuses — anything still in the deploy pipeline or ready. */
const LIVE_DEPLOY_STATUSES = new Set(["queued", "deploying", "warming", "ready"]);
-type CapabilityNudgeKind = "deploy" | "finetune" | "optimise" | "upload";
+type CapabilityNudgeKind = "deploy" | "finetune" | "upload";
export type CapabilityNudge = {
kind: CapabilityNudgeKind;
@@ -21,16 +21,13 @@ export function pickCapabilityNudge({
datasets,
finetuningJobs,
deployedModels,
- optimiserExperimentCount,
flags,
}: {
datasets: DatasetLike[];
finetuningJobs: JobLike[];
deployedModels: ModelLike[];
- optimiserExperimentCount: number;
flags: {
datasets: boolean;
- evaluations: boolean;
finetuning: boolean;
inference: boolean;
};
@@ -51,11 +48,6 @@ export function pickCapabilityNudge({
return { kind: "finetune" };
}
- const hasEvalDataset = datasets.some((d) => d.contract === "eval");
- if (flags.evaluations && hasEvalDataset && optimiserExperimentCount === 0) {
- return { kind: "optimise" };
- }
-
if (flags.datasets && datasets.length === 0) {
return { kind: "upload" };
}
diff --git a/frontend/src/components/capability-grid.tsx b/frontend/src/components/capability-grid.tsx
index 1b18a451..1e7be0ad 100644
--- a/frontend/src/components/capability-grid.tsx
+++ b/frontend/src/components/capability-grid.tsx
@@ -113,15 +113,6 @@ function CapabilityCard({ capability }: { capability: CapabilityList }) {
</span>
</MetricRow>
)}
- {capability.analyzerModel && (
- <MetricRow icon={<Icon.ai className="size-3" />} label="Analyser">
- <ModelProviderChip
- className="ml-auto min-w-0 text-xs"
- compact
- model={capability.analyzerModel}
- />
- </MetricRow>
- )}
{toolNames.length > 0 && (
<MetricRow
icon={<Icon.tool className="size-3" />}
diff --git a/frontend/src/components/command-palette.tsx b/frontend/src/components/command-palette.tsx
index 53168928..eb6a4965 100644
--- a/frontend/src/components/command-palette.tsx
+++ b/frontend/src/components/command-palette.tsx
@@ -107,15 +107,6 @@ const NAV_KEYWORDS: Record<string, string[]> = {
"delete connector",
"remove connector",
],
- "/optimiser": [
- "optimiser",
- "optimizer",
- "optimize",
- "optimisation",
- "model comparison",
- "delete experiment",
- "remove experiment",
- ],
"/projects": ["projects", "create project", "new project", "delete project", "remove project"],
"/settings": [
"settings",
@@ -272,19 +263,6 @@ const ACTIONS: ActionDef[] = [
projectScoped: true,
to: "/training",
},
- {
- icon: Icon.optimiser,
- id: "action:delete-experiment",
- keywords: [
- "delete experiment",
- "remove experiment",
- "delete optimizer experiment",
- "delete optimisation",
- ],
- label: "Delete experiment",
- projectScoped: true,
- to: "/optimiser",
- },
];
const RESOURCES: ResourceDef[] = navLinks.map((leaf) => ({
diff --git a/frontend/src/components/connectors/setup-wizard.tsx b/frontend/src/components/connectors/setup-wizard.tsx
index 7c2c6d75..95e4da69 100644
--- a/frontend/src/components/connectors/setup-wizard.tsx
+++ b/frontend/src/components/connectors/setup-wizard.tsx
@@ -1,6 +1,6 @@
/**
* One-page connector setup — credentials → project → range → capabilities →
- * destination, stacked like the optimiser wizard. Scroll vertically; no steps.
+ * destination, stacked in one column. Scroll vertically; no steps.
*/
import { type ReactNode, useEffect, useMemo, useReducer, useRef, useState } from "react";
diff --git a/frontend/src/components/datasets/notebook/cell.tsx b/frontend/src/components/datasets/notebook/cell.tsx
index 6e0d31be..059d0014 100644
--- a/frontend/src/components/datasets/notebook/cell.tsx
+++ b/frontend/src/components/datasets/notebook/cell.tsx
@@ -24,7 +24,7 @@ import { cn } from "@/lib/utils";
import type { Cell } from "@/openapi";
/** `train_eval`: the eval dataset that scores a training job. */
-export type UsePurpose = "train" | "train_eval" | "optimise";
+export type UsePurpose = "train" | "train_eval";
export interface CellActions {
onUse: (purpose: UsePurpose) => void;
@@ -485,28 +485,16 @@ export function NotebookCell({
</Button>
)}
{intent === "eval" && (
- <>
- <Button
- className="border-primary/40 bg-primary/10 text-primary hover:bg-primary/20"
- disabled={!fit.ok}
- onClick={() => actions.onUse("optimise")}
- size="xs"
- variant="outline"
- >
- <Icon.optimiser />
- Run the optimiser
- </Button>
- <Button
- className="border-primary/40 bg-primary/10 text-primary hover:bg-primary/20"
- disabled={!fit.ok}
- onClick={() => actions.onUse("train_eval")}
- size="xs"
- variant="outline"
- >
- <Icon.training />
- Use in a training job
- </Button>
- </>
+ <Button
+ className="border-primary/40 bg-primary/10 text-primary hover:bg-primary/20"
+ disabled={!fit.ok}
+ onClick={() => actions.onUse("train_eval")}
+ size="xs"
+ variant="outline"
+ >
+ <Icon.training />
+ Use in a training job
+ </Button>
)}
</footer>
)}
diff --git a/frontend/src/components/datasets/notebook/notebook-page.tsx b/frontend/src/components/datasets/notebook/notebook-page.tsx
index 57d1d698..4d5c1e7f 100644
--- a/frontend/src/components/datasets/notebook/notebook-page.tsx
+++ b/frontend/src/components/datasets/notebook/notebook-page.tsx
@@ -167,16 +167,11 @@ export function DatasetNotebook({
search: { capabilityId, datasetId, projectId, train: true },
to: "/training",
});
- } else if (purpose === "train_eval") {
+ } else {
void navigate({
search: { capabilityId, evalDatasetId: datasetId, projectId, train: true },
to: "/training",
});
- } else {
- void navigate({
- search: { capabilityId, datasetId, optimize: true, projectId },
- to: "/optimiser",
- });
}
},
[dataset?.capability, datasetId, navigate, projectId]
diff --git a/frontend/src/components/entity-ref/cards.tsx b/frontend/src/components/entity-ref/cards.tsx
index 95700d62..06c898fc 100644
--- a/frontend/src/components/entity-ref/cards.tsx
+++ b/frontend/src/components/entity-ref/cards.tsx
@@ -28,10 +28,6 @@ function livePoll(status: unknown) {
return typeof status === "string" && TERMINAL.has(status) ? (false as const) : 5_000;
}
-function pct(value: number | null | undefined) {
- return value == null ? null : `${Math.round(value)}%`;
-}
-
function isTerminal(status: unknown) {
return typeof status === "string" && TERMINAL.has(status);
}
@@ -275,39 +271,6 @@ export function ModelCard({ id, name }: { id: string; name: string }) {
);
}
-export function ExperimentCard({ id, name }: { id: string; name: string }) {
- const { data, isPending } = useQuery({
- queryFn: () => apiClient.optimizerExperiments.optimizerExperimentsRetrieve({ id }),
- queryKey: ["optimizer-experiment", id],
- refetchInterval: (q) => livePoll((q.state.data as { status?: string } | undefined)?.status),
- });
- if (isPending) return <EntityCardSkeleton kind="experiment" name={name} />;
- if (!data) return <EntityCardMissing kind="experiment" name={name} />;
-
- const scores = (data.scores ?? {}) as Record<string, unknown>;
- const best = typeof scores.best === "number" ? scores.best : null;
-
- return (
- <EntityCardShell
- footer={
- <>
- <StatusBadge fallback="pending" status={data.status} />
- <span className="text-xs tabular-nums text-muted-foreground">
- Iteration {data.currentIteration ?? 0}/{data.numIterations ?? 0}
- </span>
- </>
- }
- kind="experiment"
- name={data.capabilityName || name}
- >
- <Row label="Dataset">{data.datasetName}</Row>
- <Row label="Eval set">{data.evalSetName}</Row>
- <Row label="Best score">{pct(best)}</Row>
- <Row label="Started">{data.createdAt ? <DateTime value={data.createdAt} /> : null}</Row>
- </EntityCardShell>
- );
-}
-
export function ProjectCard({ id, name }: { id: string; name: string }) {
const { data, isPending } = useQuery({
queryFn: () => apiClient.projects.projectsRetrieve({ id }),
diff --git a/frontend/src/components/entity-ref/index.tsx b/frontend/src/components/entity-ref/index.tsx
index 6b20c919..88c27576 100644
--- a/frontend/src/components/entity-ref/index.tsx
+++ b/frontend/src/components/entity-ref/index.tsx
@@ -6,7 +6,6 @@ import {
CapabilityCard,
DatasetCard,
EvalRunCard,
- ExperimentCard,
JobCard,
ModelCard,
ProjectCard,
@@ -83,18 +82,6 @@ export function EntityLink({
{children}
</Link>
);
- case "experiment":
- return (
- <Link
- className={className}
- onClick={onClick}
- params={{ experimentId: id }}
- to="/optimiser/$experimentId"
- {...rest}
- >
- {children}
- </Link>
- );
case "model":
return (
<Link
@@ -159,7 +146,6 @@ const CARDS: Record<
capability: CapabilityCard,
dataset: DatasetCard,
evalRun: EvalRunCard,
- experiment: ExperimentCard,
job: JobCard,
model: ModelCard,
project: ProjectCard,
diff --git a/frontend/src/components/entity-ref/shell.tsx b/frontend/src/components/entity-ref/shell.tsx
index 0c248632..24ce5e7d 100644
--- a/frontend/src/components/entity-ref/shell.tsx
+++ b/frontend/src/components/entity-ref/shell.tsx
@@ -8,7 +8,6 @@ export type EntityKind =
| "capability"
| "dataset"
| "evalRun"
- | "experiment"
| "job"
| "model"
| "project"
@@ -23,7 +22,6 @@ export const ENTITY_META: Record<
capability: { accent: "text-cat-3", icon: Icon.agent, label: "Capability" },
dataset: { accent: "text-cat-2", icon: Icon.dataset, label: "Dataset" },
evalRun: { accent: "text-cat-3", icon: Icon.eval, label: "Eval run" },
- experiment: { accent: "text-cat-5", icon: Icon.optimiser, label: "Optimisation" },
job: { accent: "text-cat-5", icon: Icon.training, label: "Training run" },
model: { accent: "text-cat-4", icon: Icon.inference, label: "Model" },
project: { accent: "text-cat-6", icon: Icon.project, label: "Project" },
diff --git a/frontend/src/components/evaluations/eval-matrix-table.tsx b/frontend/src/components/evaluations/eval-matrix-table.tsx
index 0e049298..cd97ffc8 100644
--- a/frontend/src/components/evaluations/eval-matrix-table.tsx
+++ b/frontend/src/components/evaluations/eval-matrix-table.tsx
@@ -1,4 +1,4 @@
-import { Fragment, type ReactNode, useState } from "react";
+import { Fragment, useState } from "react";
import { useQueries } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
@@ -144,12 +144,10 @@ export function EvalMatrixTable({
projectId,
capabilityId,
capability,
- actions,
}: {
projectId: string;
capabilityId?: string;
capability?: Capability;
- actions?: ReactNode;
}) {
const highlights = useActivityHighlights();
const matrix = useEvalMatrixQuery(projectId, capabilityId);
@@ -309,13 +307,10 @@ export function EvalMatrixTable({
hasActiveFilters={hasActiveFilters}
onClearFilters={clearFilters}
primary={
- <>
- {actions}
- <Button onClick={guard(() => setCreating(true))}>
- <Icon.add />
- Add evaluation
- </Button>
- </>
+ <Button onClick={guard(() => setCreating(true))}>
+ <Icon.add />
+ Add evaluation
+ </Button>
}
search={
<SearchInput
diff --git a/frontend/src/components/evaluations/eval-set-empty-wizard-state.tsx b/frontend/src/components/evaluations/eval-set-empty-wizard-state.tsx
index c9c7248d..1ebb2197 100644
--- a/frontend/src/components/evaluations/eval-set-empty-wizard-state.tsx
+++ b/frontend/src/components/evaluations/eval-set-empty-wizard-state.tsx
@@ -167,7 +167,7 @@ export function EvalSetEmptyWizardState({
</Button>
}
className="rounded-md border border-dashed border-border"
- description="After code scan, create an eval set on the capability's Evaluations tab — the active set grades optimiser candidates."
+ description="After code scan, create an eval set on the capability's Evaluations tab."
icon={Icon.listBox}
size="section"
title="No eval set yet"
diff --git a/frontend/src/components/feedback-dialog.tsx b/frontend/src/components/feedback-dialog.tsx
index 423bbe11..23221843 100644
--- a/frontend/src/components/feedback-dialog.tsx
+++ b/frontend/src/components/feedback-dialog.tsx
@@ -75,7 +75,6 @@ const AREAS: { value: FeedbackAreaEnum; label: string; path?: RegExp }[] = [
{ label: "Observability", path: /^\/observability/, value: FeedbackAreaEnum.observability },
{ label: "Datasets", path: /^\/datasets/, value: FeedbackAreaEnum.datasets },
{ label: "Evaluation", path: /^\/evaluations/, value: FeedbackAreaEnum.evaluation },
- { label: "Optimiser", path: /^\/optimiser/, value: FeedbackAreaEnum.optimizer },
{ label: "Training", path: /^\/training/, value: FeedbackAreaEnum.training },
{ label: "Serving", path: /^\/inference/, value: FeedbackAreaEnum.serving },
{ label: "Billing", path: /^\/settings/, value: FeedbackAreaEnum.billing },
diff --git a/frontend/src/components/onboarding/shell.tsx b/frontend/src/components/onboarding/shell.tsx
index fe6c0597..f8479f74 100644
--- a/frontend/src/components/onboarding/shell.tsx
+++ b/frontend/src/components/onboarding/shell.tsx
@@ -16,7 +16,7 @@ const PILLARS = [
{
description: "Catch regressions before your users do",
icon: Icon.eval,
- name: "Evaluate & Optimise",
+ name: "Evaluate",
},
{ description: "Own your intelligence", icon: Icon.training, name: "Train & Serve" },
] as const;
diff --git a/frontend/src/components/optimiser/experiment-status.test.ts b/frontend/src/components/optimiser/experiment-status.test.ts
deleted file mode 100644
index dc77de90..00000000
--- a/frontend/src/components/optimiser/experiment-status.test.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-// covers: console-logic
-import { describe, expect, it } from "vitest";
-
-import type { OptimizerExperiment } from "@/openapi";
-import { optimizerModelIds } from "./experiment-status";
-
-const experiment = (overrides: Partial<OptimizerExperiment> = {}) =>
- ({ mode: "optimize", modelIds: null, ...overrides }) as OptimizerExperiment;
-
-describe("optimiser run type", () => {
- it("keeps only valid model ids for counts and search", () => {
- expect(optimizerModelIds(experiment({ modelIds: ["openai/gpt-4o", 7, null] }))).toEqual([
- "openai/gpt-4o",
- ]);
- });
-});
diff --git a/frontend/src/components/optimiser/experiment-status.tsx b/frontend/src/components/optimiser/experiment-status.tsx
deleted file mode 100644
index ecdebd50..00000000
--- a/frontend/src/components/optimiser/experiment-status.tsx
+++ /dev/null
@@ -1,142 +0,0 @@
-import { Badge } from "@/components/ui/badge";
-import { ResolvedStatusBadge, resolveStatus } from "@/lib/job-status";
-import { humanizeKey } from "@/lib/label-case";
-import type { ModeCd6Enum, OptimizerExperiment } from "@/openapi";
-
-// Keys mirror overbae/models/optimizer.py OptimizerExperiment.Status.
-export const EXPERIMENT_STATUS_LABELS: Record<string, string> = {
- baseline: "Running baseline",
- cancelled: "Cancelled",
- completed: "Completed",
- evaluated_baseline_outputs: "Baseline evaluated",
- evaluated_candidate_outputs: "Candidates evaluated",
- evaluating_baseline_outputs: "Evaluating baseline",
- evaluating_candidate_outputs: "Evaluating candidates",
- failed: "Failed",
- iterating: "Iterating",
- paused: "Paused",
- scheduled: "Scheduled",
-};
-
-export function prettyStatus(status: string): string {
- return EXPERIMENT_STATUS_LABELS[status] ?? humanizeKey(status);
-}
-
-const OPTIMIZER_RUN_TYPE_META: Record<
- ModeCd6Enum,
- {
- description: string;
- label: string;
- variant: "info" | "secondary";
- }
-> = {
- hybrid: {
- description: "Tests prompt and code changes with each selected model.",
- label: "Code + model optimisation",
- variant: "info",
- },
- model_comparison: {
- description: "Compares the current model with selected models on the same dataset.",
- label: "Model comparison",
- variant: "info",
- },
- optimize: {
- description: "Varies prompts, tools, and code across iterations.",
- label: "Prompt & code optimisation",
- variant: "secondary",
- },
-};
-
-export function optimizerRunType(experiment: OptimizerExperiment): ModeCd6Enum {
- return experiment.mode === "model_comparison" || experiment.mode === "hybrid"
- ? experiment.mode
- : "optimize";
-}
-
-export function optimizerRunTypeMeta(type: ModeCd6Enum) {
- return OPTIMIZER_RUN_TYPE_META[type];
-}
-
-export function optimizerModelIds(experiment: OptimizerExperiment): string[] {
- return Array.isArray(experiment.modelIds)
- ? experiment.modelIds.filter((modelId): modelId is string => typeof modelId === "string")
- : [];
-}
-
-export function OptimizerRunTypeBadge({
- experiment,
- showModelCount = false,
- size = "default",
-}: {
- experiment: OptimizerExperiment;
- showModelCount?: boolean;
- size?: "chip" | "default";
-}) {
- const type = optimizerRunType(experiment);
- const meta = optimizerRunTypeMeta(type);
- const modelCount = optimizerModelIds(experiment).length;
-
- return (
- <Badge
- aria-label={modelCount > 0 ? `${meta.label}, ${modelCount} selected models` : meta.label}
- className="max-w-full"
- size={size}
- title={meta.description}
- variant={meta.variant}
- >
- <span className="truncate">{meta.label}</span>
- {showModelCount && modelCount > 0 && (
- <span className="ml-1 shrink-0 font-mono text-xs font-normal opacity-80">
- · {modelCount} model{modelCount === 1 ? "" : "s"}
- </span>
- )}
- </Badge>
- );
-}
-
-/** Tone comes from the shared job-status registry; only the label stays
- * optimiser-specific. */
-export function ExperimentStatusChip({
- status,
- progress,
-}: {
- status: string;
- progress?: number | null;
-}) {
- const key =
- status === "completed" || status === "failed" || status === "cancelled"
- ? status
- : status === "scheduled"
- ? "queued"
- : status === "paused"
- ? "paused"
- : "running";
- const cfg = resolveStatus(key, "queued");
- return <ResolvedStatusBadge cfg={{ ...cfg, label: prettyStatus(status) }} progress={progress} />;
-}
-
-const TERMINAL = new Set(["completed", "failed", "cancelled"]);
-
-export function isExperimentLive(status: string): boolean {
- return !TERMINAL.has(status) && !status.startsWith("failed") && status !== "paused";
-}
-
-export function asNumber(value: unknown): number | null {
- return typeof value === "number" && Number.isFinite(value) ? value : null;
-}
-
-/** Scores are 0–100. */
-export function experimentScores(experiment: OptimizerExperiment): {
- baseline: number | null;
- best: number | null;
- delta: number | null;
-} {
- const scores = (experiment.scores ?? {}) as Record<string, unknown>;
- const baseline = asNumber(scores.baseline);
- const best = asNumber(scores.best);
- return {
- baseline,
- best,
- delta: baseline != null && best != null ? best - baseline : null,
- };
-}
diff --git a/frontend/src/components/optimiser/experiment-winner.test.ts b/frontend/src/components/optimiser/experiment-winner.test.ts
deleted file mode 100644
index 4b5efa7d..00000000
--- a/frontend/src/components/optimiser/experiment-winner.test.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-// covers: measured-facts
-import { describe, expect, it } from "vitest";
-
-import type { WinnerCandidate } from "./experiment-winner";
-import { deriveWinner } from "./experiment-winner";
-
-function candidate(partial: Partial<WinnerCandidate> = {}): WinnerCandidate {
- return {
- candidateIndex: 0,
- id: "c-1",
- isBaseline: false,
- score: 90,
- status: "evaluated",
- targetModel: "openai/gpt-5",
- ...partial,
- };
-}
-
-function iteration(order: number, candidates: WinnerCandidate[]) {
- return { candidates, id: `it-${order}`, order };
-}
-
-const tie = [
- iteration(1, [candidate({ id: "early", score: 90, targetModel: "model/a" })]),
- iteration(2, [candidate({ id: "late", score: 90, targetModel: "model/b" })]),
-];
-
-describe("deriveWinner", () => {
- it("crowns the backend's recorded comparison winner, even on a tie", () => {
- expect(deriveWinner(tie, { best: 90, comparison: true, winnerModel: "model/b" })?.id).toBe(
- "late"
- );
- });
-
- it("while running, a comparison tie crowns the earliest model (backend max())", () => {
- expect(deriveWinner(tie, { best: 90, comparison: true, winnerModel: null })?.id).toBe("early");
- });
-
- it("an optimize tie crowns the latest iteration (backend -iteration__order)", () => {
- expect(deriveWinner(tie, { best: 90, comparison: false, winnerModel: null })?.id).toBe("late");
- });
-
- it("returns null before anything is scored", () => {
- expect(deriveWinner(tie, { best: null, comparison: true, winnerModel: null })).toBeNull();
- });
-
- it("never crowns the baseline", () => {
- const baselineTie = [
- iteration(0, [candidate({ id: "base", isBaseline: true, score: 95 })]),
- iteration(1, [candidate({ id: "model", score: 95 })]),
- ];
- expect(deriveWinner(baselineTie, { best: 95, comparison: true, winnerModel: null })?.id).toBe(
- "model"
- );
- });
-});
diff --git a/frontend/src/components/optimiser/experiment-winner.ts b/frontend/src/components/optimiser/experiment-winner.ts
deleted file mode 100644
index 10ea9d14..00000000
--- a/frontend/src/components/optimiser/experiment-winner.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-export type WinnerCandidate = {
- id: string;
- candidateIndex: number;
- targetModel: string;
- isBaseline: boolean;
- status: string;
- score: number;
-};
-
-export type WinnerIteration = { id: string; order: number; candidates: WinnerCandidate[] };
-
-type WinnerOptions = {
- comparison: boolean;
- /** Backend `state.model_comparison.selected_winner`, once the run reports. */
- winnerModel: string | null;
- best: number | null;
-};
-
-function isScored(candidate: WinnerCandidate): boolean {
- return (
- !candidate.isBaseline &&
- candidate.status === "evaluated" &&
- typeof candidate.score === "number" &&
- Number.isFinite(candidate.score)
- );
-}
-
-/** Tie-breaks mirror the backend: comparison takes the earliest candidate
- * (`max()`), optimize/hybrid the latest (`-score, -iteration__order`). */
-export function deriveWinner(
- iterations: WinnerIteration[],
- { comparison, winnerModel, best }: WinnerOptions
-): WinnerCandidate | null {
- const orderOf = new Map<string, number>();
- for (const iteration of iterations) {
- for (const candidate of iteration.candidates ?? []) orderOf.set(candidate.id, iteration.order);
- }
-
- const evaluated = iterations.flatMap((it) => it.candidates ?? []).filter(isScored);
- if (winnerModel != null) {
- return evaluated.find((c) => c.targetModel === winnerModel) ?? null;
- }
- if (best == null) return null;
-
- const ties = evaluated.filter((c) => c.score === best);
- ties.sort(
- comparison
- ? (a, b) =>
- (orderOf.get(a.id) ?? -1) - (orderOf.get(b.id) ?? -1) ||
- a.candidateIndex - b.candidateIndex
- : (a, b) =>
- (orderOf.get(b.id) ?? -1) - (orderOf.get(a.id) ?? -1) ||
- a.candidateIndex - b.candidateIndex
- );
- return ties[0] ?? null;
-}
diff --git a/frontend/src/components/optimiser/experiments-table.test.tsx b/frontend/src/components/optimiser/experiments-table.test.tsx
deleted file mode 100644
index 7817331f..00000000
--- a/frontend/src/components/optimiser/experiments-table.test.tsx
+++ /dev/null
@@ -1,167 +0,0 @@
-// @vitest-environment jsdom
-// covers: live-console
-import { cleanup, render, screen } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import type { OptimizerExperiment } from "@/openapi";
-
-const mocks = vi.hoisted(() => ({ navigate: vi.fn(), rows: vi.fn() }));
-
-// Radix Select needs a layout engine jsdom lacks.
-vi.mock("@/components/ui/select", () => ({
- Select: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- SelectContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- SelectItem: ({ children, value }: { children: React.ReactNode; value: string }) => (
- <div data-value={value}>{children}</div>
- ),
- SelectTrigger: () => null,
- SelectValue: () => null,
-}));
-
-// The real `DataTable` calls `onRowClick` from a row's `onClick`, so a button
-// standing in for the row exercises the same handler.
-vi.mock("@/components/ui/data-table", () => ({
- DataTable: ({
- data,
- onRowClick,
- toolbar,
- }: {
- data: { results: OptimizerExperiment[] };
- onRowClick?: (row: OptimizerExperiment) => void;
- toolbar: React.ReactNode;
- }) => {
- mocks.rows(data.results.map((e) => e.id));
- return (
- <div>
- {toolbar}
- <button onClick={() => onRowClick?.(data.results[0])} type="button">
- open row
- </button>
- </div>
- );
- },
-}));
-
-// `Link` is only here so the EntityRef import chain resolves.
-vi.mock("@tanstack/react-router", () => ({
- Link: () => null,
- useNavigate: () => mocks.navigate,
-}));
-
-// `useDebouncedValue` is deliberately NOT mocked: the mount guard below holds
-// only because the real hook seeds with the incoming value.
-
-vi.mock("@/hooks/use-optimizer", () => {
- const make = (id: string, capability: string, capabilityName: string) =>
- ({
- capability,
- capabilityName,
- createdAt: new Date("2026-01-01T00:00:00Z"),
- currentIteration: 1,
- datasetName: "ds",
- evalSetName: "es",
- id,
- numIterations: 3,
- scores: null,
- status: "completed",
- }) as unknown as OptimizerExperiment;
- return {
- useOptimizerExperimentsQuery: () => ({
- data: {
- results: [
- make("exp-a", "capability-1", "Billing Capability"),
- make("exp-b", "capability-2", "Billing Capability"),
- make("exp-c", "capability-3", ""),
- ],
- },
- isFetched: true,
- }),
- };
-});
-
-import { ExperimentsTable } from "./experiments-table";
-
-afterEach(() => {
- cleanup();
- mocks.navigate.mockClear();
-});
-
-function renderTable(runCapability: string) {
- render(
- <ExperimentsTable
- filters={{ run_capability: runCapability, run_search: "", run_status: "all" }}
- onSearchChange={vi.fn()}
- page={1}
- pageSize={25}
- projectId="proj-1"
- />
- );
- return mocks.rows.mock.calls.at(-1)?.[0] as string[];
-}
-
-// The stubbed trigger carries no label, so capability options are picked out by the
-// fixture id prefix; no status value starts with "capability-".
-const capabilityOptionValues = () =>
- [...document.querySelectorAll("[data-value^='capability-']")].map((el) =>
- el.getAttribute("data-value")
- );
-
-describe("ExperimentsTable capability filter", () => {
- it("gives two same-named capabilities their own option and filters by id", () => {
- const rows = renderTable("capability-2");
-
- expect(capabilityOptionValues()).toEqual(["capability-1", "capability-2", "capability-3"]);
- expect(rows).toEqual(["exp-b"]);
- });
-
- it("keeps a nameless capability selectable under a fallback label", () => {
- renderTable("all");
-
- expect(capabilityOptionValues()).toContain("capability-3");
- expect(screen.getByText("Unnamed capability")).toBeTruthy();
- });
-
- it("surfaces an unknown incoming id instead of a blank select", () => {
- const rows = renderTable("capability-gone");
-
- expect(capabilityOptionValues()).toContain("capability-gone");
- expect(screen.getByText("Unknown capability")).toBeTruthy();
- expect(rows).toEqual([]);
- });
-});
-
-// The URL is the source of truth for the search box, so publishing the settled
-// value must be a no-op until the user types.
-describe("ExperimentsTable deep link", () => {
- it("doesn't rewrite a deep-linked page + search on mount", () => {
- const onSearchChange = vi.fn();
-
- // Two rows match "billing" at one per page, so page 2 needs no clamping.
- render(
- <ExperimentsTable
- filters={{ run_capability: "all", run_search: "billing", run_status: "all" }}
- onSearchChange={onSearchChange}
- page={2}
- pageSize={1}
- projectId="proj-1"
- />
- );
-
- expect(onSearchChange).not.toHaveBeenCalled();
- });
-});
-
-// A literal `search: { projectId }` overwrites the search instead of extending
-// it, and "Back to optimiser" rebuilds the list URL from what survives.
-describe("ExperimentsTable row click", () => {
- it("carries the whole search into the experiment, not just projectId", () => {
- renderTable("all");
-
- screen.getByRole("button", { name: "open row" }).click();
-
- const { search, to } = mocks.navigate.mock.calls[0][0];
- const url = { page: 2, projectId: "proj-1", run_search: "billing" };
- expect(to).toBe("/optimiser/$experimentId");
- expect(typeof search === "function" ? search(url) : search).toEqual(url);
- });
-});
diff --git a/frontend/src/components/optimiser/experiments-table.tsx b/frontend/src/components/optimiser/experiments-table.tsx
deleted file mode 100644
index c0806128..00000000
--- a/frontend/src/components/optimiser/experiments-table.tsx
+++ /dev/null
@@ -1,386 +0,0 @@
-import { type ReactNode, useEffect, useMemo, useState } from "react";
-
-import { useNavigate } from "@tanstack/react-router";
-import type { ColumnDef } from "@tanstack/react-table";
-
-import { EntityRef } from "@/components/entity-ref";
-import {
- EXPERIMENT_STATUS_LABELS,
- ExperimentStatusChip,
- experimentScores,
- OptimizerRunTypeBadge,
- optimizerModelIds,
- optimizerRunType,
- optimizerRunTypeMeta,
- prettyStatus,
-} from "@/components/optimiser/experiment-status";
-import { DataTable } from "@/components/ui/data-table";
-import { DateTime } from "@/components/ui/datetime";
-import { DeltaChip } from "@/components/ui/delta-chip";
-import { EmptyState } from "@/components/ui/empty-state";
-import { Icon } from "@/components/ui/icons";
-import { ListToolbar } from "@/components/ui/list-toolbar";
-import { SearchInput } from "@/components/ui/search-input";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import { useDebouncedValue } from "@/hooks/use-debounced-value";
-import { useOptimizerExperimentsQuery } from "@/hooks/use-optimizer";
-import { usePersistedState } from "@/hooks/use-persisted-state";
-import { parseDrfOrdering } from "@/lib/drf-ordering";
-import type { OptimiserSearch } from "@/lib/schemas";
-import { clearUnseenCompletion, useUnseenCompletionKeys } from "@/lib/unseen-job-completions";
-import type { OptimizerExperiment } from "@/openapi";
-import { OptimizerExperimentStatusEnum } from "@/openapi";
-
-type SortKey = "type" | "capability" | "status" | "dataset" | "score" | "created";
-
-function ScoreCell({
- baseline,
- best,
- delta,
-}: {
- baseline: number | null;
- best: number | null;
- delta: number | null;
-}) {
- if (best == null && baseline == null) return <span className="text-muted-foreground">—</span>;
- return (
- <span className="inline-flex items-center gap-1.5 tabular-nums text-foreground">
- <span>{best != null ? best.toFixed(1) : "—"}</span>
- {delta != null && <DeltaChip value={delta} />}
- </span>
- );
-}
-
-type ExperimentFilters = Pick<OptimiserSearch, "run_capability" | "run_search" | "run_status">;
-
-interface ExperimentsTableProps {
- projectId: string;
- action?: ReactNode;
- page: number;
- pageSize: number;
- filters: ExperimentFilters;
- onSearchChange: (
- updates: Partial<ExperimentFilters> & { page?: number; page_size?: number }
- ) => void;
-}
-
-export function ExperimentsTable({
- projectId,
- action,
- page,
- pageSize,
- filters,
- onSearchChange,
-}: ExperimentsTableProps) {
- const navigate = useNavigate();
- const unseenKeys = useUnseenCompletionKeys();
- const { data, isFetched, error, refetch } = useOptimizerExperimentsQuery(projectId);
- const {
- run_capability: capabilityFilter,
- run_search: searchParam,
- run_status: statusFilter,
- } = filters;
- // Local so typing doesn't write a URL entry per keystroke.
- const [search, setSearch] = useState(searchParam);
- const debouncedSearch = useDebouncedValue(search, 400);
- // Client-side sort, encoded as a DRF ordering string for DataTable headers.
- const [ordering, setOrdering] = usePersistedState<string>(
- "optimiser:experimentOrdering",
- "-created"
- );
-
- const allExperiments = data?.results ?? [];
-
- const resetToFirstPage = () => {
- if (page !== 1) onSearchChange({ page: 1 });
- };
-
- // The guard matters: the debounce seeds with the incoming value, so an
- // unguarded effect would reset a deep-linked `?page=` on mount.
- useEffect(() => {
- if (debouncedSearch !== searchParam) onSearchChange({ page: 1, run_search: debouncedSearch });
- }, [debouncedSearch, searchParam, onSearchChange]);
-
- // Keyed on the capability id, not the name: two capabilities can share a display name, and
- // a nameless one still has to be selectable.
- const capabilityOptions = useMemo(() => {
- const byId = new Map<string, string>();
- for (const e of allExperiments) {
- if (e.capability) byId.set(e.capability, e.capabilityName || "Unnamed capability");
- }
- // A `run_capability` no experiment carries (stale link, deleted capability) would
- // leave the trigger blank and the empty table unexplained.
- if (capabilityFilter !== "all" && !byId.has(capabilityFilter))
- byId.set(capabilityFilter, "Unknown capability");
- return [...byId]
- .map(([id, name]) => ({ id, name }))
- .sort((a, b) => a.name.localeCompare(b.name));
- }, [allExperiments, capabilityFilter]);
-
- const hasActiveFilters =
- statusFilter !== "all" || capabilityFilter !== "all" || search.trim() !== "";
-
- const experiments = useMemo(() => {
- const q = searchParam.trim().toLowerCase();
- const filtered = allExperiments.filter((e) => {
- if (statusFilter !== "all" && e.status !== statusFilter) return false;
- if (capabilityFilter !== "all" && e.capability !== capabilityFilter) return false;
- if (q) {
- const runType = optimizerRunType(e);
- const haystack =
- `${e.capabilityName} ${e.datasetName} ${e.evalSetName} ${e.status} ${optimizerRunTypeMeta(runType).label} ${optimizerRunTypeMeta(runType).description} ${optimizerModelIds(e).join(" ")}`.toLowerCase();
- if (!haystack.includes(q)) return false;
- }
- return true;
- });
-
- const sort = parseDrfOrdering(ordering || undefined);
- const requestedKey = sort?.field;
- const key: SortKey =
- requestedKey === "type" ||
- requestedKey === "capability" ||
- requestedKey === "status" ||
- requestedKey === "dataset" ||
- requestedKey === "score" ||
- requestedKey === "created"
- ? requestedKey
- : "created";
- const dir = sort?.dir === "asc" ? 1 : -1;
- return [...filtered].sort((a, b) => {
- let cmp = 0;
- switch (key) {
- case "type":
- cmp = optimizerRunTypeMeta(optimizerRunType(a)).label.localeCompare(
- optimizerRunTypeMeta(optimizerRunType(b)).label
- );
- break;
- case "capability":
- cmp = a.capabilityName.localeCompare(b.capabilityName);
- break;
- case "status":
- cmp = a.status.localeCompare(b.status);
- break;
- case "dataset":
- cmp = (a.datasetName || "").localeCompare(b.datasetName || "");
- break;
- case "score": {
- const aBest = experimentScores(a).best ?? -Infinity;
- const bBest = experimentScores(b).best ?? -Infinity;
- cmp = aBest - bBest;
- break;
- }
- case "created":
- cmp = new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
- break;
- }
- return cmp * dir;
- });
- }, [allExperiments, searchParam, statusFilter, capabilityFilter, ordering]);
-
- const totalPages = Math.max(1, Math.ceil(experiments.length / pageSize));
- const safePage = Math.min(page, totalPages);
- // Clamping waits for the fetch: an empty first render would otherwise rewrite
- // a deep-linked `?page=` to 1.
- useEffect(() => {
- if (isFetched && page !== safePage) onSearchChange({ page: safePage });
- }, [isFetched, page, safePage, onSearchChange]);
- const pageRows = experiments.slice((safePage - 1) * pageSize, safePage * pageSize);
-
- const clearFilters = () => {
- setSearch("");
- onSearchChange({ page: 1, run_capability: "all", run_search: "", run_status: "all" });
- };
-
- const columns: ColumnDef<OptimizerExperiment>[] = [
- {
- accessorKey: "capabilityName",
- cell: ({ row }) => {
- const e = row.original;
- return e.capability ? (
- <EntityRef id={e.capability} kind="capability" name={e.capabilityName} />
- ) : (
- <span className="text-muted-foreground">—</span>
- );
- },
- header: "Capability",
- meta: { noTruncate: true, orderingField: "capability" },
- minSize: 140,
- size: 200,
- },
- {
- cell: ({ row }) => (
- <OptimizerRunTypeBadge experiment={row.original} showModelCount size="chip" />
- ),
- header: "Run type",
- id: "mode",
- meta: { noTruncate: true, orderingField: "type" },
- minSize: 130,
- size: 148,
- },
- {
- accessorKey: "status",
- cell: ({ row }) => {
- const experiment = row.original;
- const progress =
- experiment.status === "iterating" && experiment.numIterations > 0
- ? (experiment.currentIteration / experiment.numIterations) * 100
- : null;
- return <ExperimentStatusChip progress={progress} status={experiment.status} />;
- },
- header: "Status",
- meta: { noTruncate: true, orderingField: "status" },
- minSize: 120,
- size: 140,
- },
- {
- accessorKey: "datasetName",
- cell: ({ row }) => {
- const e = row.original;
- return e.dataset ? (
- <EntityRef id={e.dataset} kind="dataset" name={e.datasetName} projectId={projectId} />
- ) : (
- <span className="text-muted-foreground">—</span>
- );
- },
- header: "Dataset",
- meta: { noTruncate: true, orderingField: "dataset" },
- minSize: 120,
- size: 144,
- },
- {
- cell: ({ row }) => {
- const { baseline, best, delta } = experimentScores(row.original);
- return <ScoreCell baseline={baseline} best={best} delta={delta} />;
- },
- header: "Best score",
- id: "score",
- meta: { noTruncate: true, orderingField: "score" },
- minSize: 110,
- size: 130,
- },
- {
- accessorKey: "createdAt",
- cell: ({ row }) => (
- <span className="text-muted-foreground">
- <DateTime value={row.original.createdAt} />
- </span>
- ),
- header: "Created",
- meta: { orderingField: "created" },
- minSize: 120,
- size: 136,
- },
- ];
-
- const toolbar = (
- <ListToolbar
- filters={
- <>
- <Select
- onValueChange={(v) => onSearchChange({ page: 1, run_status: v })}
- value={statusFilter}
- >
- <SelectTrigger aria-label="Filter by status" className="w-[180px]" size="default">
- <SelectValue placeholder="Status" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">All statuses</SelectItem>
- {Object.values(OptimizerExperimentStatusEnum).map((s) => (
- <SelectItem key={s} value={s}>
- {EXPERIMENT_STATUS_LABELS[s] ?? prettyStatus(s)}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
-
- {capabilityOptions.length > 0 && (
- <Select
- onValueChange={(v) => onSearchChange({ page: 1, run_capability: v })}
- value={capabilityFilter}
- >
- <SelectTrigger aria-label="Filter by capability" className="w-[160px]" size="default">
- <SelectValue placeholder="Capability" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">All capabilities</SelectItem>
- {capabilityOptions.map((a) => (
- <SelectItem key={a.id} value={a.id}>
- {a.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- </>
- }
- hasActiveFilters={hasActiveFilters}
- onClearFilters={clearFilters}
- primary={action}
- search={
- <SearchInput
- className="min-w-[200px] flex-1"
- label="Search experiments"
- onChange={(e) => setSearch(e.target.value)}
- onClear={() => {
- setSearch("");
- onSearchChange({ page: 1, run_search: "" });
- }}
- placeholder="Search experiments…"
- value={search}
- />
- }
- />
- );
-
- return (
- <DataTable
- columns={columns}
- data={{ count: experiments.length, results: pageRows }}
- emptyState={
- <EmptyState
- className="flex-1"
- description="Runs appear after /overmind optimise or /overmind backtest."
- icon={Icon.optimiser}
- size="section"
- title="No runs yet"
- />
- }
- error={error}
- getRowId={(row) => row.id}
- hasActiveFilters={hasActiveFilters}
- // `data` is synthesized client-side here, so `unsettled` can't infer
- // settledness from it — pass the query's own `isFetched`.
- isLoading={!isFetched}
- onClearFilters={clearFilters}
- onOrderingChange={(o) => {
- setOrdering(o ?? "");
- resetToFirstPage();
- }}
- onPageChange={(p) => onSearchChange({ page: p })}
- onPageSizeChange={(s) => onSearchChange({ page: 1, page_size: s })}
- onRetry={() => refetch()}
- // Carry the whole search, not just `projectId` — see the runs table.
- onRowClick={(e) =>
- navigate({
- params: { experimentId: e.id },
- resetScroll: false,
- search: (prev) => prev,
- to: "/optimiser/$experimentId",
- })
- }
- onRowMouseEnter={(e) => clearUnseenCompletion(`optimizer:${e.id}`)}
- ordering={ordering || undefined}
- page={safePage}
- pageSize={pageSize}
- rowClassName={(e) => (unseenKeys.has(`optimizer:${e.id}`) ? "bg-wash-subtle" : undefined)}
- storageKey="optimiser:experiments-cols"
- toolbar={toolbar}
- />
- );
-}
diff --git a/frontend/src/components/optimiser/finetuning-suggestion.tsx b/frontend/src/components/optimiser/finetuning-suggestion.tsx
deleted file mode 100644
index ab459429..00000000
--- a/frontend/src/components/optimiser/finetuning-suggestion.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { Link } from "@tanstack/react-router";
-
-import apiClient from "@/client";
-import { asNumber } from "@/components/optimiser/experiment-status";
-import { isCrossExperimentPlateau } from "@/components/optimiser/plateau";
-import { Button } from "@/components/ui/button";
-import { FloatingNudge } from "@/components/ui/floating-nudge";
-import { Icon } from "@/components/ui/icons";
-import { useNudgeDismissalCount } from "@/hooks/use-nudge-dismissal";
-import { featureFlags } from "@/lib/feature-flags";
-
-const DISMISS_KEY = (capabilityId: string) =>
- `optimizer-finetune-suggest-dismissed:${capabilityId}`;
-
-/** Re-appears after a dismiss only once another experiment completes. */
-export function FinetuningSuggestion({
- capabilityId,
- projectId,
- currentImproved = false,
-}: {
- capabilityId: string;
- projectId?: string;
- currentImproved?: boolean;
-}) {
- const { data } = useQuery({
- enabled: featureFlags.finetuning && !!projectId && !currentImproved,
- queryFn: () =>
- apiClient.optimizerExperiments.optimizerExperimentsList({
- capability: capabilityId,
- pageSize: 100,
- }),
- queryKey: ["capability-experiments", capabilityId],
- staleTime: 30_000,
- });
- const experiments = data?.results ?? [];
-
- const completedWithScore = experiments.filter(
- (e) =>
- e.status === "completed" &&
- asNumber((e.scores as Record<string, unknown> | null)?.best) != null
- ).length;
-
- const { dismissed, dismiss } = useNudgeDismissalCount(
- DISMISS_KEY(capabilityId),
- completedWithScore
- );
-
- const show =
- featureFlags.finetuning &&
- projectId != null &&
- !currentImproved &&
- isCrossExperimentPlateau(experiments) &&
- !dismissed;
-
- if (!show) return null;
-
- return (
- <FloatingNudge
- cta={
- <Button asChild size="sm">
- <Link search={{ capabilityId, projectId, train: true }} to="/training">
- <Icon.finetuning />
- Try fine-tuning
- </Link>
- </Button>
- }
- description="Optimisation has plateaued — fine-tuning a model may help"
- icon={<Icon.ai className="size-5" />}
- onDismiss={dismiss}
- title="Scores aren't improving"
- />
- );
-}
diff --git a/frontend/src/components/optimiser/plateau.test.ts b/frontend/src/components/optimiser/plateau.test.ts
deleted file mode 100644
index c9d83d97..00000000
--- a/frontend/src/components/optimiser/plateau.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-// covers: console-logic
-import { describe, expect, it } from "vitest";
-
-import type { OptimizerExperiment } from "@/openapi";
-import { isCrossExperimentPlateau } from "./plateau";
-
-function makeExp(best: number | null, offset: number): OptimizerExperiment {
- return {
- createdAt: new Date(1_000_000 + offset * 1000).toISOString(),
- id: String(offset),
- scores: best != null ? { best } : null,
- status: "completed",
- } as unknown as OptimizerExperiment;
-}
-
-describe("isCrossExperimentPlateau", () => {
- it("returns false with fewer than 2 completed scored experiments", () => {
- expect(isCrossExperimentPlateau([])).toBe(false);
- expect(isCrossExperimentPlateau([makeExp(50, 0)])).toBe(false);
- });
-
- it("returns false when a later experiment beats the first", () => {
- expect(isCrossExperimentPlateau([makeExp(40, 0), makeExp(50, 1)])).toBe(false);
- });
-
- it("returns true when the second score equals the first", () => {
- expect(isCrossExperimentPlateau([makeExp(50, 0), makeExp(50, 1)])).toBe(true);
- });
-
- it("returns true when the second score is worse than the first", () => {
- expect(isCrossExperimentPlateau([makeExp(50, 0), makeExp(40, 1)])).toBe(true);
- });
-
- it("returns false when a middle experiment sets a new high", () => {
- expect(isCrossExperimentPlateau([makeExp(40, 0), makeExp(55, 1), makeExp(48, 2)])).toBe(false);
- });
-
- it("ignores experiments without a numeric best score", () => {
- expect(isCrossExperimentPlateau([makeExp(50, 0), makeExp(null, 1)])).toBe(false);
- });
-
- it("ignores non-completed experiments", () => {
- const running = { ...makeExp(30, 1), status: "running" } as unknown as OptimizerExperiment;
- expect(isCrossExperimentPlateau([makeExp(50, 0), running])).toBe(false);
- });
-
- it("sorts chronologically when the API returns newest-first ISO timestamps", () => {
- expect(isCrossExperimentPlateau([makeExp(50, 1), makeExp(40, 0)])).toBe(false);
- });
-});
diff --git a/frontend/src/components/optimiser/plateau.ts b/frontend/src/components/optimiser/plateau.ts
deleted file mode 100644
index d6fd440c..00000000
--- a/frontend/src/components/optimiser/plateau.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { asNumber } from "@/components/optimiser/experiment-status";
-import type { OptimizerExperiment } from "@/openapi";
-
-type ScoredExperiment = {
- at: number;
- best: number;
-};
-
-function createdAtMs(value: Date | string | undefined): number {
- const ms = value instanceof Date ? +value : Date.parse(String(value ?? ""));
- return Number.isFinite(ms) ? ms : 0;
-}
-
-/** Baseline is the first completed experiment: nothing after it may set a new best. */
-export function isCrossExperimentPlateau(experiments: OptimizerExperiment[]): boolean {
- const completed = experiments
- .filter((e) => e.status === "completed")
- .map((e) => ({
- at: createdAtMs(e.createdAt),
- best: asNumber((e.scores as Record<string, unknown> | null)?.best),
- }))
- .filter((e): e is ScoredExperiment => e.best != null)
- .sort((a, b) => a.at - b.at);
- if (completed.length < 2) return false;
- let peak = completed[0].best;
- for (let i = 1; i < completed.length; i++) {
- if (completed[i].best > peak) return false;
- peak = Math.max(peak, completed[i].best);
- }
- return true;
-}
diff --git a/frontend/src/components/optimiser/run-locally-dialog.test.tsx b/frontend/src/components/optimiser/run-locally-dialog.test.tsx
deleted file mode 100644
index 0c08db4b..00000000
--- a/frontend/src/components/optimiser/run-locally-dialog.test.tsx
+++ /dev/null
@@ -1,371 +0,0 @@
-// @vitest-environment jsdom
-// covers: console-logic
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-const mocks = vi.hoisted(() => ({
- capabilities: vi.fn(),
- catalog: vi.fn(),
- datasets: vi.fn(),
- deployed: vi.fn(),
- writeText: vi.fn(),
-}));
-
-vi.mock("@/hooks/use-evaluations", () => ({
- useModelCatalogQuery: () =>
- mocks.catalog() ?? {
- data: {
- defaults: {
- backtestModels: ["openai/gpt-5-mini", "anthropic/claude-sonnet-4"],
- judgeModel: "openai/gpt-5-mini",
- judgeModels: ["openai/gpt-5-mini"],
- },
- models: [
- {
- contextLength: null,
- id: "openai/gpt-5-mini",
- name: "GPT-5 Mini",
- provider: "openai",
- },
- {
- contextLength: null,
- id: "anthropic/claude-sonnet-4",
- name: "Claude Sonnet 4",
- provider: "anthropic",
- },
- {
- contextLength: null,
- id: "google/gemini-2.5-pro",
- name: "Gemini 2.5 Pro",
- provider: "google",
- },
- {
- contextLength: null,
- id: "xai/grok-4",
- name: "Grok 4",
- provider: "xai",
- },
- {
- contextLength: null,
- id: "deepseek/deepseek-chat",
- name: "DeepSeek Chat",
- provider: "deepseek",
- },
- {
- contextLength: null,
- id: "qwen/qwen3-32b",
- name: "Qwen3 32B",
- provider: "qwen",
- },
- {
- contextLength: null,
- id: "openai/gpt-5-mini:batch",
- name: "GPT-5 Mini (batch)",
- provider: "openai",
- },
- {
- contextLength: null,
- id: "anthropic/claude-sonnet-4:batch",
- name: "Claude Sonnet 4 (batch)",
- provider: "anthropic",
- },
- ],
- },
- error: null,
- isLoading: false,
- refetch: vi.fn(),
- },
- useProjectCapabilitiesQuery: (projectId: string | undefined) =>
- mocks.capabilities(projectId) ?? { data: { results: [] } },
- useProjectDatasetsForEvalQuery: () =>
- mocks.datasets() ?? { data: { results: [] }, error: null, isLoading: false, refetch: vi.fn() },
-}));
-
-vi.mock("@/hooks/use-inference", () => ({
- useDeployedModelsQuery: () =>
- mocks.deployed() ?? { data: { results: [] }, error: null, isLoading: false },
-}));
-
-vi.mock("@/components/model-provider-chip", () => ({
- getProviderIcon: () => undefined,
- ModelProviderChip: ({ children, model }: { children?: React.ReactNode; model: string }) => (
- <span>
- {model}
- {children}
- </span>
- ),
- ProviderLogo: () => null,
-}));
-
-vi.mock("@/components/ui/select", () => ({
- Select: ({
- children,
- onValueChange,
- value,
- }: {
- children: React.ReactNode;
- onValueChange?: (value: string) => void;
- value?: string;
- }) => (
- <div
- data-select-value={value}
- onClick={(event) => {
- const item = (event.target as HTMLElement).closest("[data-select-item]");
- const next = item?.getAttribute("data-value");
- if (next) onValueChange?.(next);
- }}
- onKeyDown={(event) => {
- if (event.key !== "Enter" && event.key !== " ") return;
- const item = (event.target as HTMLElement).closest("[data-select-item]");
- const next = item?.getAttribute("data-value");
- if (next) onValueChange?.(next);
- }}
- >
- {children}
- </div>
- ),
- SelectContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- SelectItem: ({ children, value }: { children: React.ReactNode; value: string }) => (
- <button data-select-item data-value={value} type="button">
- {children}
- </button>
- ),
- SelectTrigger: ({ children, ...props }: { children: React.ReactNode; "aria-label"?: string }) => (
- <button type="button" {...props}>
- {children}
- </button>
- ),
- SelectValue: ({ placeholder }: { placeholder?: string }) => <span>{placeholder}</span>,
-}));
-
-import {
- buildBacktestPrompt,
- buildOptimisePrompt,
- isComparisonOptionDisabled,
- MAX_COMPARISON_MODELS,
- RunLocallyDialog,
- toggleComparisonModel,
-} from "./run-locally-dialog";
-
-afterEach(() => {
- cleanup();
- mocks.capabilities.mockReset();
- mocks.datasets.mockReset();
- mocks.deployed.mockReset();
- mocks.writeText.mockReset();
-});
-
-describe("toggleComparisonModel", () => {
- it("adds and removes models and refuses a sixth selection", () => {
- const five = ["a", "b", "c", "d", "e"];
- expect(toggleComparisonModel(five, "f")).toEqual(five);
- expect(toggleComparisonModel(five, "c")).toEqual(["a", "b", "d", "e"]);
- expect(toggleComparisonModel([], "a")).toEqual(["a"]);
- expect(toggleComparisonModel(["only"], "only")).toEqual([]);
- expect(MAX_COMPARISON_MODELS).toBe(5);
- });
-
- it("refuses mixing batch and standard models", () => {
- expect(toggleComparisonModel(["openai/gpt-5-mini"], "openai/gpt-5-mini:batch")).toEqual([
- "openai/gpt-5-mini",
- ]);
- expect(toggleComparisonModel(["openai/gpt-5-mini:batch"], "anthropic/claude-sonnet-4")).toEqual(
- ["openai/gpt-5-mini:batch"]
- );
- expect(
- toggleComparisonModel(["openai/gpt-5-mini:batch"], "google/gemini-2.5-pro:batch")
- ).toEqual(["openai/gpt-5-mini:batch", "google/gemini-2.5-pro:batch"]);
- });
-});
-
-describe("isComparisonOptionDisabled", () => {
- it("disables the other lane and a sixth selection", () => {
- expect(isComparisonOptionDisabled(["openai/gpt-5-mini"], "openai/gpt-5-mini:batch")).toBe(true);
- expect(isComparisonOptionDisabled(["openai/gpt-5-mini:batch"], "openai/gpt-5-mini")).toBe(true);
- expect(isComparisonOptionDisabled(["openai/gpt-5-mini"], "anthropic/claude-sonnet-4")).toBe(
- false
- );
- expect(isComparisonOptionDisabled([], "openai/gpt-5-mini:batch")).toBe(false);
- expect(isComparisonOptionDisabled(["a", "b", "c", "d", "e"], "f")).toBe(true);
- });
-});
-
-describe("buildOptimisePrompt", () => {
- it("copies the skill prompt with capability and dataset", () => {
- expect(buildOptimisePrompt("invoice-extract", "ds-1")).toBe(
- `/overmind optimise
-capability: invoice-extract
-dataset: ds-1`
- );
- });
-});
-
-describe("buildBacktestPrompt", () => {
- it("uses the selected model list", () => {
- const prompt = buildBacktestPrompt("invoice-extract", "ds-1", [
- "google/gemini-2.5-pro",
- "xai/grok-4",
- ]);
- expect(prompt).toBe(
- `/overmind backtest
-capability: invoice-extract
-dataset: ds-1
-models: google/gemini-2.5-pro, xai/grok-4`
- );
- });
-});
-
-describe("RunLocallyDialog", () => {
- function openModelComparison() {
- fireEvent.mouseDown(screen.getByRole("tab", { name: "Compare models" }));
- }
-
- it("explains both run types and switches to the model comparison prompt", () => {
- mocks.capabilities.mockReturnValue({
- data: {
- results: [{ activeModel: null, id: "cap-1", name: "Invoice", slug: "invoice-extract" }],
- },
- });
-
- render(
- <RunLocallyDialog
- capabilityId="cap-1"
- datasetId="ds-99"
- onOpenChange={vi.fn()}
- open
- projectId="proj-1"
- />
- );
-
- expect(screen.getByRole("heading", { name: "New optimisation run" })).toBeTruthy();
- const improve = screen.getByRole("tab", { name: "Improve prompts & code" });
- expect(improve.getAttribute("aria-selected")).toBe("true");
- expect(
- document.getElementById(improve.getAttribute("aria-describedby")!)?.textContent
- ).toContain("prompts, tool definitions and application logic");
- const compare = screen.getByRole("tab", { name: "Compare models" });
- expect(
- document.getElementById(compare.getAttribute("aria-describedby")!)?.textContent
- ).toContain("Keep prompts and logic fixed");
- expect(screen.getByText(/records the winning diff for review/)).toBeTruthy();
- expect(
- screen.getByText(/Execution runs locally; scores and progress appear in Overmind/)
- ).toBeTruthy();
- expect(screen.getByText(/Copying does not start a run/)).toBeTruthy();
- expect(screen.getByRole("button", { name: "Copy prompt" })).toBeTruthy();
- expect(screen.getByText(/capability: invoice-extract/)).toBeTruthy();
- expect(screen.getByText(/dataset: ds-99/)).toBeTruthy();
- expect(screen.queryByText(/models: openai\/gpt-5-mini, anthropic\/claude-sonnet-4/)).toBeNull();
-
- openModelComparison();
- expect(compare.getAttribute("aria-selected")).toBe("true");
- expect(screen.getByText(/without fine-tuning or changing prompts/)).toBeTruthy();
- expect(screen.queryByText(/records the winning diff for review/)).toBeNull();
- expect(screen.getByText(/capability: invoice-extract/)).toBeTruthy();
- expect(screen.getByText(/dataset: ds-99/)).toBeTruthy();
- expect(screen.getByText(/models: openai\/gpt-5-mini, anthropic\/claude-sonnet-4/)).toBeTruthy();
-
- fireEvent.click(screen.getByRole("checkbox", { name: "Select google/gemini-2.5-pro" }));
- expect(
- screen.getByText(
- /models: openai\/gpt-5-mini, anthropic\/claude-sonnet-4, google\/gemini-2\.5-pro/
- )
- ).toBeTruthy();
-
- fireEvent.click(screen.getByRole("checkbox", { name: "Select openai/gpt-5-mini" }));
- expect(
- screen.getByText(/models: anthropic\/claude-sonnet-4, google\/gemini-2\.5-pro/)
- ).toBeTruthy();
-
- expect(screen.getByText(/Batch and standard models can't be mixed/)).toBeTruthy();
- expect(
- (
- screen.getByRole("checkbox", {
- name: "Select openai/gpt-5-mini:batch",
- }) as HTMLButtonElement
- ).disabled
- ).toBe(true);
- });
-
- it("allows unselecting the last remaining model", () => {
- mocks.capabilities.mockReturnValue({
- data: {
- results: [{ activeModel: null, id: "cap-1", name: "Invoice", slug: "invoice-extract" }],
- },
- });
-
- render(
- <RunLocallyDialog
- capabilityId="cap-1"
- datasetId="ds-99"
- onOpenChange={vi.fn()}
- open
- projectId="proj-1"
- />
- );
-
- openModelComparison();
- fireEvent.click(screen.getByRole("checkbox", { name: "Select openai/gpt-5-mini" }));
- fireEvent.click(screen.getByRole("checkbox", { name: "Select anthropic/claude-sonnet-4" }));
- expect(screen.getByText(/models: <model>/)).toBeTruthy();
- expect(
- (
- screen.getByRole("checkbox", {
- name: "Select openai/gpt-5-mini:batch",
- }) as HTMLButtonElement
- ).disabled
- ).toBe(false);
- });
-
- it("falls back to placeholders when capability/dataset are unknown", () => {
- mocks.capabilities.mockReturnValue({ data: { results: [] } });
- render(<RunLocallyDialog onOpenChange={vi.fn()} open projectId="proj-1" />);
- expect(screen.getByText("No capabilities.")).toBeTruthy();
- expect(screen.getByText("No eval datasets.")).toBeTruthy();
- expect(screen.getByText(/capability: <slug>/)).toBeTruthy();
- expect(screen.getByText(/dataset: <dataset-id>/)).toBeTruthy();
- expect(screen.queryByLabelText("Local file")).toBeNull();
- });
-
- it("updates commands when a capability is picked", () => {
- mocks.capabilities.mockReturnValue({
- data: {
- results: [
- { activeModel: null, id: "cap-1", name: "Invoice", slug: "invoice-extract" },
- { activeModel: null, id: "cap-2", name: "Receipt", slug: "receipt-parse" },
- ],
- },
- });
- render(<RunLocallyDialog onOpenChange={vi.fn()} open projectId="proj-1" />);
- expect(screen.getByRole("button", { name: "Capability" })).toBeTruthy();
- expect(screen.getByText(/capability: <slug>/)).toBeTruthy();
- fireEvent.click(screen.getByRole("button", { name: "Receipt" }));
- expect(screen.getByText(/capability: receipt-parse/)).toBeTruthy();
- openModelComparison();
- expect(screen.getByText(/capability: receipt-parse/)).toBeTruthy();
- });
-
- it("uses a picked eval dataset in the prompt", () => {
- mocks.capabilities.mockReturnValue({
- data: {
- results: [{ activeModel: null, id: "cap-1", name: "Invoice", slug: "invoice-extract" }],
- },
- });
- mocks.datasets.mockReturnValue({
- data: {
- results: [
- { capability: "cap-1", id: "ds-1", name: "Eval invoices" },
- { capability: "cap-1", id: "ds-2", name: "Eval receipts" },
- ],
- },
- error: null,
- isLoading: false,
- refetch: vi.fn(),
- });
- render(<RunLocallyDialog onOpenChange={vi.fn()} open projectId="proj-1" />);
- expect(screen.getByRole("button", { name: "Eval dataset" })).toBeTruthy();
- expect(screen.getByText(/dataset: <dataset-id>/)).toBeTruthy();
- fireEvent.click(screen.getByRole("button", { name: "Eval receipts" }));
- expect(screen.getByText(/dataset: ds-2/)).toBeTruthy();
- });
-});
diff --git a/frontend/src/components/optimiser/run-locally-dialog.tsx b/frontend/src/components/optimiser/run-locally-dialog.tsx
deleted file mode 100644
index 8d20f14a..00000000
--- a/frontend/src/components/optimiser/run-locally-dialog.tsx
+++ /dev/null
@@ -1,619 +0,0 @@
-import { useEffect, useMemo, useState } from "react";
-
-import { ModelOptionLabel } from "@/components/model-option-label";
-import type { ProviderId } from "@/components/model-provider";
-import { getModelProviderInfo, getProviderInfoById } from "@/components/model-provider";
-import { getProviderIcon, ProviderLogo } from "@/components/model-provider-chip";
-import { Badge } from "@/components/ui/badge";
-import { useCopy } from "@/components/ui/block-actions";
-import { Button } from "@/components/ui/button";
-import { Checkbox } from "@/components/ui/checkbox";
-import {
- Dialog,
- DialogBody,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { Icon } from "@/components/ui/icons";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { QueryError } from "@/components/ui/query-error";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import { Skeleton } from "@/components/ui/skeleton";
-import { LoadingState } from "@/components/ui/spinner";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import {
- useModelCatalogQuery,
- useProjectCapabilitiesQuery,
- useProjectDatasetsForEvalQuery,
-} from "@/hooks/use-evaluations";
-import { useDeployedModelsQuery } from "@/hooks/use-inference";
-import { PROSE } from "@/lib/typography";
-import { cn } from "@/lib/utils";
-import { type CatalogModel, DeployedModelsListStatusEnum } from "@/openapi";
-
-export const MAX_COMPARISON_MODELS = 5;
-
-type ComparisonModelLane = "batch" | "standard";
-
-/** OpenRouter batch slugs carry a `:batch` suffix (e.g. `openai/gpt-5-mini:batch`). */
-export function isBatchModel(modelId: string): boolean {
- return modelId.includes(":batch");
-}
-
-function comparisonModelLane(selected: string[]): ComparisonModelLane | null {
- if (selected.length === 0) return null;
- return selected.some(isBatchModel) ? "batch" : "standard";
-}
-
-/** Chips only — every other provider stays reachable through the browse list. */
-const POPULAR_PROVIDERS: ProviderId[] = [
- "openai",
- "anthropic",
- "google",
- "xai",
- "deepseek",
- "qwen",
- "kimi",
- "zhipu",
- "minimax",
- "bytedance",
-];
-
-export function toggleComparisonModel(selected: string[], modelId: string): string[] {
- if (selected.includes(modelId)) return selected.filter((id) => id !== modelId);
- if (selected.length >= MAX_COMPARISON_MODELS) return selected;
- const lane = comparisonModelLane(selected);
- if (lane && comparisonModelLane([modelId]) !== lane) return selected;
- return [...selected, modelId];
-}
-
-export function isComparisonOptionDisabled(selected: string[], modelId: string): boolean {
- if (selected.includes(modelId)) return false;
- if (selected.length >= MAX_COMPARISON_MODELS) return true;
- const lane = comparisonModelLane(selected);
- return lane !== null && comparisonModelLane([modelId]) !== lane;
-}
-
-/** An empty selection keeps every provider. */
-function filterModelsByProvider(models: CatalogModel[], providers: ProviderId[]): CatalogModel[] {
- if (providers.length === 0) return models;
- const wanted = new Set(providers);
- return models.filter((model) => wanted.has(getModelProviderInfo(model.id).id));
-}
-
-export const DATASET_REF_PLACEHOLDER = "<dataset-id>";
-
-export function buildOptimisePrompt(capabilitySlug: string, datasetRef: string): string {
- return `/overmind optimise
-capability: ${capabilitySlug}
-dataset: ${datasetRef}`;
-}
-
-export function buildBacktestPrompt(
- capabilitySlug: string,
- datasetRef: string,
- modelIds: string[]
-): string {
- const models = (modelIds.length > 0 ? modelIds : ["<model>"]).join(", ");
- return `/overmind backtest
-capability: ${capabilitySlug}
-dataset: ${datasetRef}
-models: ${models}`;
-}
-
-interface RunLocallyDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- projectId: string;
- capabilityId?: string;
- datasetId?: string;
-}
-
-export function RunLocallyDialog({
- open,
- onOpenChange,
- projectId,
- capabilityId,
- datasetId,
-}: RunLocallyDialogProps) {
- return (
- <Dialog onOpenChange={onOpenChange} open={open}>
- <DialogContent size="lg">
- {open ? (
- <RunLocallyBody
- capabilityId={capabilityId}
- datasetId={datasetId}
- onOpenChange={onOpenChange}
- projectId={projectId}
- />
- ) : null}
- </DialogContent>
- </Dialog>
- );
-}
-
-function RunLocallyBody({
- onOpenChange,
- projectId,
- capabilityId,
- datasetId,
-}: Omit<RunLocallyDialogProps, "open">) {
- const [chosenModelIds, setChosenModelIds] = useState<string[] | null>(null);
- const [selectedCapabilityId, setSelectedCapabilityId] = useState(capabilityId ?? "");
- const [selectedDatasetId, setSelectedDatasetId] = useState(datasetId ?? "");
- const [selectedTab, setSelectedTab] = useState("optimize");
- const defaultModelIds = useModelCatalogQuery().data?.defaults.backtestModels ?? [];
- const modelIds = chosenModelIds ?? defaultModelIds;
-
- const capabilitiesQuery = useProjectCapabilitiesQuery(projectId);
- const capabilities = capabilitiesQuery.data?.results ?? [];
- useEffect(() => {
- if (selectedCapabilityId) return;
- if (capabilityId && capabilities.some((row) => row.id === capabilityId)) {
- setSelectedCapabilityId(capabilityId);
- return;
- }
- if (capabilities.length === 1) setSelectedCapabilityId(capabilities[0].id);
- }, [capabilities, capabilityId, selectedCapabilityId]);
- const capability = capabilities.find((row) => row.id === selectedCapabilityId);
- const capabilitySlug = capability?.slug ?? "<slug>";
- const incumbentModel = capability?.activeModel ?? null;
-
- const datasetsQuery = useProjectDatasetsForEvalQuery(projectId);
- const datasets = datasetsQuery.data?.results ?? [];
- useEffect(() => {
- if (selectedDatasetId) return;
- if (datasetId && datasets.some((row) => row.id === datasetId)) {
- setSelectedDatasetId(datasetId);
- return;
- }
- if (datasets.length === 1) setSelectedDatasetId(datasets[0].id);
- }, [datasetId, datasets, selectedDatasetId]);
-
- const datasetRef = selectedDatasetId.trim() || DATASET_REF_PLACEHOLDER;
- const optimisePrompt = buildOptimisePrompt(capabilitySlug, datasetRef);
- const backtestPrompt = buildBacktestPrompt(capabilitySlug, datasetRef, modelIds);
-
- return (
- <>
- <DialogHeader>
- <DialogTitle>New optimisation run</DialogTitle>
- <DialogDescription>
- Improve a capability's prompts and code, or compare the models running it.
- </DialogDescription>
- </DialogHeader>
-
- <DialogBody className="min-w-0 space-y-5">
- <Tabs onValueChange={setSelectedTab} value={selectedTab}>
- <TabsList
- aria-label="Run type"
- className="grid h-auto grid-cols-1 items-stretch gap-3 bg-transparent p-0 sm:grid-cols-2"
- >
- <TabsTrigger
- aria-describedby="optimise-mode-description"
- aria-labelledby="optimise-mode-label"
- className="items-start flex-col gap-1.5 whitespace-normal border border-border bg-card p-3 text-left data-[state=active]:border-primary data-[state=active]:bg-accent data-[state=active]:text-foreground data-[state=active]:hover:text-foreground"
- value="optimize"
- >
- <span id="optimise-mode-label">Improve prompts &amp; code</span>
- <span className="text-xs text-muted-foreground" id="optimise-mode-description">
- Test changes to prompts, tool definitions and application logic.
- </span>
- </TabsTrigger>
- <TabsTrigger
- aria-describedby="compare-mode-description"
- aria-labelledby="compare-mode-label"
- className="items-start flex-col gap-1.5 whitespace-normal border border-border bg-card p-3 text-left data-[state=active]:border-primary data-[state=active]:bg-accent data-[state=active]:text-foreground data-[state=active]:hover:text-foreground"
- value="model_comparison"
- >
- <span id="compare-mode-label">Compare models</span>
- <span className="text-xs text-muted-foreground" id="compare-mode-description">
- Keep prompts and logic fixed; evaluate different models on the same tasks.
- </span>
- </TabsTrigger>
- </TabsList>
-
- <div className="mt-5 grid grid-cols-1 gap-4 sm:grid-cols-2">
- <div className="min-w-0 space-y-1.5">
- <Label className="text-xs text-muted-foreground">Capability</Label>
- <EntitySelect
- ariaLabel="Capability"
- empty="No capabilities."
- error={capabilitiesQuery.error}
- errorFallback="Couldn't load capabilities."
- isLoading={capabilitiesQuery.isLoading}
- loadingLabel="Loading capabilities…"
- onRetry={capabilitiesQuery.refetch}
- onValueChange={setSelectedCapabilityId}
- options={capabilities.map((row) => ({ id: row.id, name: row.name }))}
- placeholder="Select a capability"
- value={selectedCapabilityId}
- />
- </div>
-
- <div className="min-w-0 space-y-1.5">
- <Label className="text-xs text-muted-foreground">Eval dataset</Label>
- <EntitySelect
- ariaLabel="Eval dataset"
- empty="No eval datasets."
- error={datasetsQuery.error}
- errorFallback="Couldn't load datasets."
- isLoading={datasetsQuery.isLoading}
- loadingLabel="Loading datasets…"
- onRetry={datasetsQuery.refetch}
- onValueChange={setSelectedDatasetId}
- options={datasets.map((row) => ({ id: row.id, name: row.name || row.id }))}
- placeholder="Select a dataset"
- value={selectedDatasetId}
- />
- </div>
- </div>
-
- <TabsContent className="mt-4 space-y-4" value="optimize">
- <p className={cn(PROSE, "text-sm text-muted-foreground")}>
- Your coding agent proposes code changes and tests each against the current version
- using this dataset. Overmind scores the results and records the winning diff for
- review.
- </p>
- <CommandBlock commands={optimisePrompt} />
- </TabsContent>
- <TabsContent className="mt-4 space-y-4" value="model_comparison">
- <p className={cn(PROSE, "text-sm text-muted-foreground")}>
- Run up to {MAX_COMPARISON_MODELS} models on the same examples. Compare evaluation
- scores with the current model, without fine-tuning or changing prompts.
- </p>
- <BacktestModelPicker
- incumbentModel={incumbentModel}
- modelIds={modelIds}
- onModelIdsChange={setChosenModelIds}
- projectId={projectId}
- />
- <CommandBlock commands={backtestPrompt} />
- </TabsContent>
- </Tabs>
- </DialogBody>
-
- <DialogFooter>
- <Button onClick={() => onOpenChange(false)} type="button" variant="secondary">
- Close
- </Button>
- </DialogFooter>
- </>
- );
-}
-
-function BacktestModelPicker({
- modelIds,
- onModelIdsChange,
- incumbentModel,
- projectId,
-}: {
- modelIds: string[];
- onModelIdsChange: (modelIds: string[]) => void;
- incumbentModel: string | null;
- projectId: string;
-}) {
- const catalogQuery = useModelCatalogQuery();
- const deployedQuery = useDeployedModelsQuery({
- projectId,
- status: DeployedModelsListStatusEnum.ready,
- });
- const [search, setSearch] = useState("");
- const [providerFilter, setProviderFilter] = useState<ProviderId[]>([]);
-
- const allModels = catalogQuery.data?.models ?? [];
- const providerCounts = useMemo(() => {
- const counts = new Map<ProviderId, number>();
- for (const model of allModels) {
- const provider = getModelProviderInfo(model.id).id;
- counts.set(provider, (counts.get(provider) ?? 0) + 1);
- }
- return counts;
- }, [allModels]);
- const providerChips = POPULAR_PROVIDERS.filter(
- (provider) => (providerCounts.get(provider) ?? 0) > 0
- );
- const deployedPicks = useMemo(
- () =>
- (deployedQuery.data?.results ?? []).map((deployed) => ({
- baseModelId: deployed.baseModelId,
- id: deployed.modelId,
- label: deployed.capabilityName
- ? `${deployed.capabilityName} · ${deployed.baseModelId.split("/").pop() ?? deployed.modelId}`
- : deployed.modelId,
- })),
- [deployedQuery.data?.results]
- );
- const selected = new Set(modelIds);
- const models = useMemo(() => {
- const q = search.trim().toLowerCase();
- return filterModelsByProvider(allModels, providerFilter)
- .filter(
- (model) =>
- !q ||
- model.id.toLowerCase().includes(q) ||
- model.name.toLowerCase().includes(q) ||
- model.provider.toLowerCase().includes(q)
- )
- .sort((a, b) => a.id.localeCompare(b.id));
- }, [allModels, providerFilter, search]);
-
- if (catalogQuery.isLoading) {
- return <LoadingState label="Loading OpenRouter models" />;
- }
-
- if (catalogQuery.error) {
- return (
- <QueryError
- error={catalogQuery.error}
- fallback="Couldn't load the OpenRouter model catalogue."
- onRetry={catalogQuery.refetch}
- />
- );
- }
-
- return (
- <div className="space-y-3">
- {providerChips.length > 0 && (
- <div className="space-y-1.5">
- <div className="flex items-center gap-1 text-xs text-muted-foreground">
- <p className="font-medium">Popular providers</p>
- <span className="mx-1 text-muted-foreground/50">|</span>
- <p className={cn(PROSE)}>Pick up to {MAX_COMPARISON_MODELS} models</p>
- </div>
- <div aria-label="Filter by provider" className="flex flex-wrap gap-1.5">
- {providerChips.map((providerId) => {
- const active = providerFilter.includes(providerId);
- const info = getProviderInfoById(providerId);
- return (
- <button
- aria-label={`${active ? "Remove" : "Add"} ${info.providerLabel} filter`}
- aria-pressed={active}
- className={cn(
- "inline-flex max-w-full items-center gap-1.5 rounded-md border px-2 py-1 text-xs font-medium transition-colors",
- active
- ? "border-primary/40 bg-primary/10 text-foreground"
- : "border-border/70 bg-wash-raised text-muted-foreground hover:border-border hover:text-foreground"
- )}
- key={providerId}
- onClick={() =>
- setProviderFilter((current) =>
- active ? current.filter((id) => id !== providerId) : [...current, providerId]
- )
- }
- type="button"
- >
- <ProviderLogo
- Icon={getProviderIcon(providerId)}
- providerLabel={info.providerLabel}
- providerSlug={info.providerSlug}
- />
- <span className="truncate">{info.providerLabel}</span>
- <span className="shrink-0 font-mono text-xs tabular-nums opacity-70">
- {providerCounts.get(providerId)}
- </span>
- </button>
- );
- })}
- </div>
- </div>
- )}
-
- {deployedPicks.length > 0 && (
- <div className="space-y-1.5">
- <p className="px-1 text-xs font-medium text-muted-foreground">Your fine-tuned models</p>
- <div aria-label="Fine-tuned OpenRouter models" className="flex flex-wrap gap-1.5">
- {deployedPicks.map((pick) => {
- const checked = selected.has(pick.id);
- const disabled = isComparisonOptionDisabled(modelIds, pick.id);
- return (
- <button
- aria-label={`Select ${pick.id}`}
- aria-pressed={checked}
- className={cn(
- "inline-flex max-w-full items-center gap-2 rounded-sm border px-2 py-1.5 text-sm transition-colors",
- checked
- ? "border-success/40 bg-success/10 text-foreground"
- : "border-border/70 bg-wash-raised text-muted-foreground hover:border-border hover:text-foreground",
- disabled && "cursor-not-allowed opacity-50"
- )}
- disabled={disabled}
- key={pick.id}
- onClick={() => onModelIdsChange(toggleComparisonModel(modelIds, pick.id))}
- type="button"
- >
- <ModelOptionLabel model={pick.baseModelId} name={pick.label} />
- {checked && <Icon.success className="size-3 shrink-0 text-success" />}
- </button>
- );
- })}
- </div>
- </div>
- )}
-
- <div className="relative">
- <Icon.search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
- <Input
- aria-label="Search OpenRouter models"
- className="pl-8"
- onChange={(event) => setSearch(event.target.value)}
- placeholder="Search model name, provider, or slug…"
- value={search}
- />
- </div>
-
- {modelIds.length > 0 && (
- <div aria-label="Selected OpenRouter models" className="flex flex-wrap gap-1.5">
- {modelIds.map((modelId) => (
- <Badge className="max-w-full gap-2" key={modelId} variant="outline">
- <ModelOptionLabel model={modelId} />
- {isBatchModel(modelId) && (
- <span className="font-normal text-muted-foreground">· batch</span>
- )}
- {modelId === incumbentModel && (
- <span className="font-normal text-muted-foreground">· current model</span>
- )}
- <button
- aria-label={`Remove ${modelId}`}
- className="rounded-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60"
- onClick={() => onModelIdsChange(modelIds.filter((id) => id !== modelId))}
- type="button"
- >
- <Icon.close className="size-3" />
- </button>
- </Badge>
- ))}
- </div>
- )}
-
- <div className="flex items-center justify-between gap-3 px-1 text-xs font-medium text-muted-foreground">
- <span>
- Browse all models
- {modelIds.length > 0 && (
- <span className="tabular-nums">
- {" "}
- · {modelIds.length} of {MAX_COMPARISON_MODELS} selected
- </span>
- )}
- </span>
- </div>
-
- <div className="max-h-60 overflow-y-auto rounded-md border border-border/70">
- {models.length === 0 ? (
- <p className="px-3 py-6 text-center text-sm text-muted-foreground">No matching models.</p>
- ) : (
- models.map((model) => {
- const checked = selected.has(model.id);
- const disabled = isComparisonOptionDisabled(modelIds, model.id);
- const batch = isBatchModel(model.id);
- return (
- <label
- className={cn(
- "flex cursor-pointer items-start gap-2.5 border-b border-border/60 px-3 py-2 last:border-b-0 hover:bg-wash-raised",
- disabled && "cursor-not-allowed opacity-50"
- )}
- key={model.id}
- >
- <Checkbox
- aria-label={`Select ${model.id}`}
- checked={checked}
- disabled={disabled}
- onCheckedChange={() =>
- onModelIdsChange(toggleComparisonModel(modelIds, model.id))
- }
- />
- <span className="min-w-0 flex-1">
- <ModelOptionLabel className="text-sm" model={model.id} name={model.name}>
- {batch && (
- <Badge className="shrink-0" size="chip" variant="neutral">
- Batch
- </Badge>
- )}
- </ModelOptionLabel>
- <span className="block truncate pl-5.5 font-mono text-xs text-muted-foreground">
- {model.id}
- </span>
- </span>
- </label>
- );
- })
- )}
- </div>
-
- <p className={cn(PROSE, "text-xs text-muted-foreground")}>
- Select 1–{MAX_COMPARISON_MODELS} models. Batch and standard models can't be mixed. The
- prompt below uses this list.
- </p>
- </div>
- );
-}
-
-function EntitySelect({
- ariaLabel,
- empty,
- error,
- errorFallback,
- isLoading,
- loadingLabel,
- onRetry,
- onValueChange,
- options,
- placeholder,
- value,
-}: {
- ariaLabel: string;
- empty: string;
- error: unknown;
- errorFallback: string;
- isLoading: boolean;
- loadingLabel: string;
- onRetry: () => Promise<unknown> | unknown;
- onValueChange: (value: string) => void;
- options: { id: string; name: string }[];
- placeholder: string;
- value: string;
-}) {
- if (isLoading) {
- return (
- <div aria-busy="true" aria-label={loadingLabel} role="status">
- <span className="sr-only">{loadingLabel}</span>
- <Skeleton aria-hidden="true" className="h-8 w-full" />
- </div>
- );
- }
- if (error) {
- return <QueryError error={error} fallback={errorFallback} onRetry={onRetry} />;
- }
- if (options.length === 0) {
- return <p className={cn(PROSE, "text-sm text-muted-foreground")}>{empty}</p>;
- }
- return (
- <Select onValueChange={onValueChange} value={value || undefined}>
- <SelectTrigger aria-label={ariaLabel} className="w-full">
- <SelectValue placeholder={placeholder} />
- </SelectTrigger>
- <SelectContent>
- {options.map((row) => (
- <SelectItem key={row.id} value={row.id}>
- {row.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- );
-}
-
-function CommandBlock({ commands }: { commands: string }) {
- const { copied, copy } = useCopy(commands);
-
- return (
- <div className="space-y-2">
- <p className={cn(PROSE, "text-xs text-muted-foreground")}>
- Paste this prompt into your coding agent in the capability's repository. Execution runs
- locally; scores and progress appear in Overmind. Copying does not start a run.
- </p>
- <div className="overflow-hidden rounded-md border border-border/70 bg-wash-subtle">
- <div className="flex items-center justify-between gap-3 border-b border-border/70 bg-wash-raised px-3 py-1.5">
- <span className="text-xs text-muted-foreground">Coding agent prompt</span>
- <Button onClick={copy} size="xs" type="button" variant="secondary">
- {copied ? <Icon.success /> : <Icon.copy />}
- {copied ? "Copied" : "Copy prompt"}
- </Button>
- </div>
- <pre className="overflow-x-auto whitespace-pre p-3 font-mono text-xs leading-relaxed text-foreground">
- {commands}
- </pre>
- </div>
- </div>
- );
-}
diff --git a/frontend/src/components/optimiser/score-chart.tsx b/frontend/src/components/optimiser/score-chart.tsx
deleted file mode 100644
index 0a4cb1a1..00000000
--- a/frontend/src/components/optimiser/score-chart.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import {
- CartesianGrid,
- Line,
- LineChart,
- Tooltip as RechartsTooltip,
- ReferenceLine,
- ResponsiveContainer,
- XAxis,
- YAxis,
-} from "recharts";
-
-import { GraphTooltip } from "@/components/ui/graph-tooltip";
-
-export interface ScorePoint {
- iteration: number;
- /** 0–100, null while unscored. */
- best: number | null;
-}
-
-export function OptimizerScoreChart({
- points,
- baseline,
-}: {
- points: ScorePoint[];
- baseline: number | null;
-}) {
- return (
- <div
- aria-label="Line chart of best candidate score per iteration"
- className="cursor-default select-none [&_*]:outline-none"
- role="img"
- >
- <ResponsiveContainer height={220} width="100%">
- <LineChart data={points} margin={{ bottom: 4, left: -18, right: 12, top: 8 }}>
- <CartesianGrid className="stroke-border/60" strokeDasharray="3 3" />
- <XAxis
- allowDecimals={false}
- dataKey="iteration"
- tick={{ fontSize: 10 }}
- tickLine={false}
- />
- <YAxis domain={[0, 100]} tick={{ fontSize: 10 }} tickLine={false} width={40} />
- <RechartsTooltip
- content={({ active, payload, label }) => (
- <GraphTooltip
- active={active}
- label={label === 0 ? "Baseline" : `Iteration ${label}`}
- payload={payload}
- valueFormatter={(value) => value.toFixed(1)}
- />
- )}
- cursor={{ stroke: "var(--muted-foreground)", strokeOpacity: 0.3 }}
- />
- {baseline != null && (
- <ReferenceLine
- label={{ fill: "var(--muted-foreground)", fontSize: 10, value: "baseline" }}
- stroke="var(--chart-2)"
- strokeDasharray="4 4"
- y={baseline}
- />
- )}
- <Line
- connectNulls
- dataKey="best"
- dot={{ r: 3 }}
- isAnimationActive={false}
- name="Best score"
- stroke="var(--chart-1)"
- strokeWidth={1.5}
- type="monotone"
- />
- </LineChart>
- </ResponsiveContainer>
- </div>
- );
-}
diff --git a/frontend/src/components/running-jobs-button.tsx b/frontend/src/components/running-jobs-button.tsx
index f7e189ff..3dfca7dc 100644
--- a/frontend/src/components/running-jobs-button.tsx
+++ b/frontend/src/components/running-jobs-button.tsx
@@ -18,9 +18,7 @@ import { displayJobStatus, type RunningJobItem } from "@/lib/running-jobs";
import { cn } from "@/lib/utils";
function kindLabel(kind: RunningJobItem["kind"]): string {
- if (kind === "finetuning") return "Fine-tuning";
- if (kind === "optimizer") return "Optimiser";
- return "Eval";
+ return kind === "finetuning" ? "Fine-tuning" : "Eval";
}
function JobRow({
@@ -66,13 +64,7 @@ function JobTaskLink({ job }: { job: RunningJobItem }) {
<span>
<ActivityTaskChip
id={job.id}
- kind={
- job.kind === "finetuning"
- ? "finetune_job"
- : job.kind === "eval"
- ? "eval_run"
- : "optimizer_experiment"
- }
+ kind={job.kind === "finetuning" ? "finetune_job" : "eval_run"}
projectId={projectId}
/>
{job.datasetId && (
diff --git a/frontend/src/components/traces/SpanDetailView.tsx b/frontend/src/components/traces/SpanDetailView.tsx
index f02d8f04..bc2f7e46 100644
--- a/frontend/src/components/traces/SpanDetailView.tsx
+++ b/frontend/src/components/traces/SpanDetailView.tsx
@@ -116,10 +116,6 @@ function KeyValueRows({ entries }: { entries: Array<[string, unknown]> }) {
const OVERMIND_GROUPS: Array<{ prefix: string; title: string }> = [
{ prefix: "overmind.capability.", title: "Capability" },
- { prefix: "overmind.optimize.", title: "Optimise" },
- { prefix: "overmind.setup.", title: "Setup" },
- { prefix: "overmind.run.", title: "Run" },
- { prefix: "overmind.init.", title: "Initialise" },
];
// Mirrors the SDK attribute contract (overmind/docs/tracing-attributes.md,
diff --git a/frontend/src/components/ui/icons/index.ts b/frontend/src/components/ui/icons/index.ts
index 4643e5d9..13459751 100644
--- a/frontend/src/components/ui/icons/index.ts
+++ b/frontend/src/components/ui/icons/index.ts
@@ -20,8 +20,7 @@ export const Icon = {
add: glyph("plus"),
addUser: glyph("user-plus"),
agent: glyph("robot-body"),
- agentTesting: glyph("test-tubes"),
- ai: glyph("sparkle"), // the "optimise / AI / magic" affordance (not Sparkles)
+ ai: glyph("sparkle"), // the "AI / magic" affordance (not Sparkles)
algorithm: glyph("algorithm"),
analytics: glyph("analytics"),
arrowDown: glyph("arrow-down"),
@@ -93,12 +92,9 @@ export const Icon = {
menu: glyph("menu"),
minimap: glyph("map"),
model: glyph("cpu"),
- models: glyph("neural-network-2"),
notify: glyph("bell"),
observability: glyph("eye"),
observabilityTitle: Eyeball,
- optimiser: glyph("speed-fast"),
- optimiserTitle: TitleChart,
overmind: OvermindEyeMono,
panelLeftClose: glyph("arrow-bar-left"),
panelLeftOpen: glyph("arrow-bar-right"),
diff --git a/frontend/src/hooks/use-optimizer.ts b/frontend/src/hooks/use-optimizer.ts
deleted file mode 100644
index c42d2999..00000000
--- a/frontend/src/hooks/use-optimizer.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-
-import apiClient from "@/client";
-import { isExperimentLive } from "@/components/optimiser/experiment-status";
-
-export const useOptimizerExperimentsQuery = (projectId: string | undefined) =>
- useQuery({
- enabled: !!projectId,
- queryFn: async ({ signal }) => {
- const results = [];
- for (let page = 1; ; page++) {
- const data = await apiClient.optimizerExperiments.optimizerExperimentsList(
- { page, pageSize: 100, project: projectId },
- { signal }
- );
- results.push(...data.results);
- if (!data.next) return { ...data, next: null, previous: null, results };
- }
- },
- queryKey: ["optimizer-experiments", projectId],
- refetchInterval: (query) => {
- const rows = query.state.data?.results ?? [];
- return rows.some((e) => e.project === projectId && isExperimentLive(e.status))
- ? 5_000
- : false;
- },
- select: (data) => ({
- ...data,
- results: (data.results ?? []).filter((e) => e.project === projectId),
- }),
- });
diff --git a/frontend/src/hooks/use-running-jobs.ts b/frontend/src/hooks/use-running-jobs.ts
index b740d4d3..ff881746 100644
--- a/frontend/src/hooks/use-running-jobs.ts
+++ b/frontend/src/hooks/use-running-jobs.ts
@@ -5,7 +5,6 @@ import { useNavigate } from "@tanstack/react-router";
import { showJobCompletionToast } from "@/components/job-completion-toast";
import { useAllEvalRunsQuery } from "@/hooks/use-evaluations";
import { useFinetuningJobsQuery } from "@/hooks/use-finetuning";
-import { useOptimizerExperimentsQuery } from "@/hooks/use-optimizer";
import {
buildRunningJobs,
completionToastCopy,
@@ -37,14 +36,6 @@ export function navigateToJob(
});
return;
}
- if (job.kind === "optimizer") {
- void navigate({
- params: { experimentId: job.id },
- search: (prev) => ({ ...prev, projectId }),
- to: "/optimiser/$experimentId",
- });
- return;
- }
void navigate({
params: { runId: job.id },
search: (prev) => ({ ...prev, projectId }),
@@ -56,16 +47,13 @@ export function useRunningJobs(projectId: string | undefined) {
const navigate = useNavigate();
const ftQuery = useFinetuningJobsQuery(projectId);
const evalQuery = useAllEvalRunsQuery(projectId);
- const optimizerQuery = useOptimizerExperimentsQuery(projectId);
const ftResults = ftQuery.data?.results;
const evalResults = evalQuery.data?.results;
- const optimizerResults = optimizerQuery.data?.results;
const running = buildRunningJobs({
evalRuns: evalResults,
finetuning: ftResults,
- optimizerExperiments: optimizerResults,
});
const unseenCompletions = useUnseenCompletions();
@@ -87,12 +75,10 @@ export function useRunningJobs(projectId: string | undefined) {
const current = buildRunningJobs({
evalRuns: evalResults,
finetuning: ftResults,
- optimizerExperiments: optimizerResults,
});
const latest = {
evalRuns: evalResults,
finetuning: ftResults,
- optimizerExperiments: optimizerResults,
};
if (hydratedForProject.current !== projectId) {
@@ -116,15 +102,7 @@ export function useRunningJobs(projectId: string | undefined) {
title: message,
});
}
- }, [
- projectId,
- ftResults,
- evalResults,
- optimizerResults,
- ftQuery.isFetched,
- evalQuery.isFetched,
- navigate,
- ]);
+ }, [projectId, ftResults, evalResults, ftQuery.isFetched, evalQuery.isFetched, navigate]);
return {
clearUnseenCompletions,
diff --git a/frontend/src/lib/credits.ts b/frontend/src/lib/credits.ts
index a6e17321..fccfdf4a 100644
--- a/frontend/src/lib/credits.ts
+++ b/frontend/src/lib/credits.ts
@@ -88,7 +88,6 @@ const PATH_ACTIONS: ReadonlyArray<readonly [string, string]> = [
["/finetuning-jobs", "start this training run"],
["/deployed-models", "deploy this model"],
["/eval-runs", "run this evaluation"],
- ["/optimizer-experiments", "start this optimisation"],
["/chat/completions", "run this model"],
["/jobs", "run this job"],
];
diff --git a/frontend/src/lib/running-jobs.test.ts b/frontend/src/lib/running-jobs.test.ts
index b5937906..a6315405 100644
--- a/frontend/src/lib/running-jobs.test.ts
+++ b/frontend/src/lib/running-jobs.test.ts
@@ -25,13 +25,6 @@ describe("buildRunningJobs", () => {
name: "Done",
status: "completed",
},
- {
- createdAt: new Date("2026-07-20T10:30:00.000Z"),
- id: "e3",
- name: "Optimizer · bot · candidate 1",
- origin: "optimizer",
- status: "running",
- },
],
finetuning: [
{
@@ -112,44 +105,6 @@ describe("buildRunningJobs", () => {
});
});
- it("rolls optimizer eval runs into a single experiment row", () => {
- const items = buildRunningJobs({
- evalRuns: [
- {
- createdAt: new Date("2026-07-20T10:00:00.000Z"),
- id: "e1",
- name: "Optimizer · bot · baseline",
- origin: "optimizer",
- status: "running",
- },
- {
- createdAt: new Date("2026-07-20T10:01:00.000Z"),
- id: "e2",
- name: "Optimizer · bot · candidate 1",
- origin: "optimizer",
- status: "pending",
- },
- ],
- optimizerExperiments: [
- {
- capabilityName: "bot",
- createdAt: new Date("2026-07-20T09:55:00.000Z"),
- currentIteration: 2,
- id: "x1",
- numIterations: 5,
- status: "iterating",
- },
- ],
- });
-
- expect(items.map((i) => i.key)).toEqual(["optimizer:x1"]);
- expect(items[0]).toMatchObject({
- kind: "optimizer",
- status: "running",
- title: "Optimizer · bot · iteration 2/5",
- });
- });
-
it("includes terminal jobs when activeOnly is false (all-jobs page)", () => {
const items = buildRunningJobs(
{
@@ -256,68 +211,10 @@ describe("detectCompletedJobs", () => {
expect(completed).toHaveLength(0);
});
-
- it("emits optimizer experiment completions with dedicated toast copy", () => {
- const prev = new Map<string, RunningJobItem>([
- [
- "optimizer:x1",
- {
- id: "x1",
- key: "optimizer:x1",
- kind: "optimizer",
- startedAt: "2026-07-20T09:55:00.000Z",
- status: "running",
- title: "Optimizer · bot · iteration 2/5",
- },
- ],
- ]);
-
- const completed = detectCompletedJobs(prev, [], {
- optimizerExperiments: [
- {
- capabilityName: "bot",
- currentIteration: 5,
- id: "x1",
- numIterations: 5,
- status: "completed",
- },
- ],
- });
-
- expect(completed).toHaveLength(1);
- expect(completed[0]?.status).toBe("completed");
- expect(completionToastCopy(completed[0]!)).toEqual({
- description: "Optimizer · bot · iteration 5/5",
- message: "Optimization finished",
- });
- });
-
- it("ignores optimizer experiments that are paused rather than finished", () => {
- const prev = new Map<string, RunningJobItem>([
- [
- "optimizer:x1",
- {
- id: "x1",
- key: "optimizer:x1",
- kind: "optimizer",
- startedAt: "2026-07-20T09:55:00.000Z",
- status: "running",
- title: "Optimizer · bot · iteration 2/5",
- },
- ],
- ]);
-
- const completed = detectCompletedJobs(prev, [], {
- optimizerExperiments: [{ id: "x1", status: "paused" }],
- });
-
- expect(completed).toHaveLength(0);
- });
});
it.each([
"finetuning",
- "optimizer",
"eval",
] as const)("does not infer %s completion from an absent list row", (kind) => {
const previous: RunningJobItem = {
diff --git a/frontend/src/lib/running-jobs.ts b/frontend/src/lib/running-jobs.ts
index f2030d77..0b49a486 100644
--- a/frontend/src/lib/running-jobs.ts
+++ b/frontend/src/lib/running-jobs.ts
@@ -2,7 +2,7 @@
import { userFacingJobError } from "@/components/finetuning/train/model-config";
-export type RunningJobKind = "finetuning" | "eval" | "optimizer";
+export type RunningJobKind = "finetuning" | "eval";
export interface RunningJobItem {
/** Stable across polls. */
@@ -27,10 +27,6 @@ const FT_ACTIVE = new Set(["queued", "preparing", "running", "deploying", "valid
const FT_TERMINAL = new Set(["succeeded", "failed", "cancelled"]);
const EVAL_ACTIVE = new Set(["pending", "running"]);
const EVAL_TERMINAL = new Set(["completed", "failed", "cancelled"]);
-// overbae/models/optimizer.py OptimizerExperiment.Status — every non-terminal
-// status counts as in-flight.
-const OPTIMIZER_TERMINAL = new Set(["completed", "failed", "cancelled"]);
-
function isActiveFinetuningStatus(status: string | undefined): boolean {
return !!status && FT_ACTIVE.has(status);
}
@@ -39,10 +35,6 @@ function isActiveEvalStatus(status: string | undefined): boolean {
return !!status && EVAL_ACTIVE.has(status);
}
-function isActiveOptimizerStatus(status: string | undefined): boolean {
- return !!status && !OPTIMIZER_TERMINAL.has(status) && status !== "paused";
-}
-
export function isTerminalFinetuningStatus(status: string | undefined): boolean {
return !!status && FT_TERMINAL.has(status);
}
@@ -51,37 +43,6 @@ function isTerminalEvalStatus(status: string | undefined): boolean {
return !!status && EVAL_TERMINAL.has(status);
}
-function isTerminalOptimizerStatus(status: string | undefined): boolean {
- return !!status && OPTIMIZER_TERMINAL.has(status);
-}
-
-function foldOptimizerStatus(status: string): string {
- if (OPTIMIZER_TERMINAL.has(status) || status === "paused") return status;
- if (status === "scheduled") return "pending";
- return "running";
-}
-
-type OptimizerExperimentRow = {
- id: string;
- capability?: string | null;
- dataset?: string | null;
- datasetName?: string;
- capabilityName?: string | null;
- status: string;
- failureReason?: string | null;
- currentIteration?: number;
- numIterations?: number;
- createdAt?: Date | string;
-};
-
-function optimizerTitle(exp: OptimizerExperimentRow): string {
- const capability = exp.capabilityName?.trim();
- const base = capability ? `Optimizer · ${capability}` : "Optimizer experiment";
- if (!exp.numIterations) return base;
- const current = Math.min(exp.currentIteration ?? 0, exp.numIterations);
- return `${base} · iteration ${current}/${exp.numIterations}`;
-}
-
export function displayJobStatus(status: string): string {
if (status === "finished") return "completed";
return status;
@@ -151,10 +112,7 @@ export function buildRunningJobs(
error?: string | null;
status: string;
createdAt: Date | string;
- /** "manual" / "optimizer". */
- origin?: string | null;
}>;
- optimizerExperiments?: OptimizerExperimentRow[];
},
opts?: { activeOnly?: boolean }
): RunningJobItem[] {
@@ -201,8 +159,6 @@ export function buildRunningJobs(
}
for (const run of input.evalRuns ?? []) {
- // Candidate runs are internals; the experiment itself is the progress row.
- if (run.origin === "optimizer") continue;
if (activeOnly && !isActiveEvalStatus(run.status)) continue;
const capability = run.capabilityName?.trim();
items.push({
@@ -220,23 +176,6 @@ export function buildRunningJobs(
});
}
- for (const exp of input.optimizerExperiments ?? []) {
- if (activeOnly && !isActiveOptimizerStatus(exp.status)) continue;
- items.push({
- error: exp.failureReason?.trim() || undefined,
- id: exp.id,
- key: `optimizer:${exp.id}`,
- kind: "optimizer",
- startedAt: toIso(exp.createdAt),
- status: foldOptimizerStatus(exp.status),
- title: optimizerTitle(exp),
- ...(exp.dataset ? { datasetId: exp.dataset, datasetName: exp.datasetName } : {}),
- ...(exp.capability
- ? { capabilityId: exp.capability, capabilityName: exp.capabilityName ?? undefined }
- : {}),
- });
- }
-
items.sort((a, b) => (a.startedAt < b.startedAt ? 1 : a.startedAt > b.startedAt ? -1 : 0));
return items;
}
@@ -259,7 +198,6 @@ export function detectCompletedJobs(
status: string;
datasetName?: string | null;
}>;
- optimizerExperiments?: OptimizerExperimentRow[];
}
): RunningJobItem[] {
const activeKeys = new Set(currentlyActive.map((j) => j.key));
@@ -288,17 +226,6 @@ export function detectCompletedJobs(
continue;
}
- if (prev.kind === "optimizer") {
- const row = latest.optimizerExperiments?.find((e) => e.id === prev.id);
- if (!row || !isTerminalOptimizerStatus(row.status)) continue;
- completed.push({
- ...prev,
- status: foldOptimizerStatus(row.status),
- title: optimizerTitle(row),
- });
- continue;
- }
-
if (prev.kind === "eval") {
const row = latest.evalRuns?.find((j) => j.id === prev.id);
if (!row || !isTerminalEvalStatus(row.status)) continue;
@@ -320,8 +247,7 @@ export function completionToastCopy(job: RunningJobItem): { message: string; des
: job.status === "cancelled"
? "was cancelled"
: "failed";
- const kind =
- job.kind === "finetuning" ? "Fine-tuning" : job.kind === "eval" ? "Eval run" : "Optimization";
+ const kind = job.kind === "finetuning" ? "Fine-tuning" : "Eval run";
return {
description: job.title,
message: `${kind} ${ok}`,
diff --git a/frontend/src/lib/schemas.test.ts b/frontend/src/lib/schemas.test.ts
index 6ef23cff..228def04 100644
--- a/frontend/src/lib/schemas.test.ts
+++ b/frontend/src/lib/schemas.test.ts
@@ -4,7 +4,6 @@ import { describe, expect, it } from "vitest";
import {
datasetsSearchSchema,
evaluationsSearchSchema,
- optimiserSearchSchema,
tracesSearchSchema,
trainingSearchSchema,
} from "./schemas";
@@ -90,29 +89,6 @@ describe("schemas", () => {
});
});
- describe("optimiserSearchSchema", () => {
- it("round-trips a deep link carrying both a page and filters", () => {
- const result = optimiserSearchSchema.parse({
- page: "2",
- run_capability: "capability-1",
- run_search: "gpt",
- run_status: "running",
- });
- expect(result.page).toBe(2);
- expect(result.run_capability).toBe("capability-1");
- expect(result.run_search).toBe("gpt");
- expect(result.run_status).toBe("running");
- });
- it("accepts optimize + capability deep-link params", () => {
- const result = optimiserSearchSchema.parse({
- capabilityId: "capability-1",
- optimize: true,
- });
- expect(result.optimize).toBe(true);
- expect(result.capabilityId).toBe("capability-1");
- });
- });
-
describe("trainingSearchSchema", () => {
it("round-trips a page, the history filters and an open run together", () => {
const result = trainingSearchSchema.parse({
diff --git a/frontend/src/lib/schemas.ts b/frontend/src/lib/schemas.ts
index 65c23a94..6c340611 100644
--- a/frontend/src/lib/schemas.ts
+++ b/frontend/src/lib/schemas.ts
@@ -76,21 +76,13 @@ export const tracesSearchSchema = z.object({
view: z.enum(["roots", "sessions", "signals"]).optional().catch("roots").default("roots"),
});
-/**
- * Shared by the Evaluations and Optimiser lists. "all" means no filter.
- * `run_status` stays free-form because each list has its own status vocabulary.
- */
-const runFilterShape = {
- run_capability: z.string().optional().default("all"),
- run_search: z.string().optional().default(""),
- run_status: z.string().optional().default("all"),
-};
-
export const evaluationsSearchSchema = projectIdSearchSchema.extend({
page: z.coerce.number().min(1).optional().default(1),
page_size: z.coerce.number().min(5).max(100).optional().default(25),
- ...runFilterShape,
+ // "all" means no filter.
+ run_capability: z.string().optional().default("all"),
run_dataset: z.string().optional().default("all"),
+ run_search: z.string().optional().default(""),
run_status: z
.enum(["all", ...Object.values(EvalRunsActivityListStatusEnum)])
.optional()
@@ -101,19 +93,6 @@ export const evaluationsSearchSchema = projectIdSearchSchema.extend({
export type EvaluationsSearch = z.infer<typeof evaluationsSearchSchema>;
-/** `optimize` (and legacy `wizard`) open the run-locally instructions dialog;
- * `capabilityId` / `datasetId` prefill the example commands. */
-export const optimiserSearchSchema = projectIdSearchSchema.extend({
- capabilityId: z.string().optional(),
- datasetId: z.string().optional(),
- optimize: z.boolean().optional(),
- page: z.coerce.number().min(1).optional().default(1),
- page_size: z.coerce.number().min(5).max(100).optional().default(25),
- ...runFilterShape,
-});
-
-export type OptimiserSearch = z.infer<typeof optimiserSearchSchema>;
-
// `ft_*` rather than the shared `run_*`: `ft_status` is a closed set, `run_status` is
// free-form, and a `search: (prev) => …` navigation carries every route's params.
export const trainingSearchSchema = projectIdSearchSchema.extend({
diff --git a/frontend/src/lib/unseen-job-completions.ts b/frontend/src/lib/unseen-job-completions.ts
index 7598a87e..c5dfa3df 100644
--- a/frontend/src/lib/unseen-job-completions.ts
+++ b/frontend/src/lib/unseen-job-completions.ts
@@ -55,7 +55,6 @@ const ROUTE_UNSEEN_KINDS: ReadonlyArray<{
}> = [
{ kinds: ["finetuning"], prefix: "/training" },
{ kinds: ["eval"], prefix: "/evaluations" },
- { kinds: ["optimizer"], prefix: "/optimiser" },
];
export function kindsForPathname(pathname: string): readonly RunningJobKind[] | null {
diff --git a/frontend/src/openapi/.openapi-generator/FILES b/frontend/src/openapi/.openapi-generator/FILES
index eb1f00ec..068adaff 100644
--- a/frontend/src/openapi/.openapi-generator/FILES
+++ b/frontend/src/openapi/.openapi-generator/FILES
@@ -28,8 +28,6 @@ apis/InferenceRequestsApi.ts
apis/McpOauthApi.ts
apis/ModelsApi.ts
apis/NativeEvaluationsApi.ts
-apis/OptimizerCandidatesApi.ts
-apis/OptimizerExperimentsApi.ts
apis/ProjectsApi.ts
apis/PublicApi.ts
apis/SessionsApi.ts
@@ -69,7 +67,6 @@ models/Binding.ts
models/BindingStateRequest.ts
models/BlankEnum.ts
models/CancelWork.ts
-models/CandidateInputRequest.ts
models/Capability.ts
models/CapabilityFlow.ts
models/CapabilityFlowExpectedOutput.ts
@@ -99,7 +96,6 @@ models/ChangeMessageRequest.ts
models/CheckoutSessionResponse.ts
models/CheckpointFile.ts
models/ColumnStat.ts
-models/CommandResultInputRequest.ts
models/ComparisonCoverage.ts
models/ConfidenceEnum.ts
models/ConnectorActiveConfig.ts
@@ -130,7 +126,6 @@ models/ConnectorVerifyResponse.ts
models/ConsentDecisionRequest.ts
models/ConsentDetails.ts
models/ConsentRedirect.ts
-models/CreateIterationRequest.ts
models/CreditTopUpRequestRequest.ts
models/Dataset.ts
models/DatasetAnalytics.ts
@@ -193,8 +188,6 @@ models/EvalScore.ts
models/EvalScoreSourceTypeEnum.ts
models/EvalSet.ts
models/EvalSetRequest.ts
-models/EvalSpecResponse.ts
-models/EvaluateIterationRequest.ts
models/EvaluationActivity.ts
models/EvaluationActivityDataset.ts
models/EvaluationActivityKindEnum.ts
@@ -269,7 +262,6 @@ models/JudgeModelEnum.ts
models/Kind703Enum.ts
models/LocalSessionRequest.ts
models/MetricComparison.ts
-models/ModeCd6Enum.ts
models/ModelActivation.ts
models/ModelActivationStageEnum.ts
models/ModelCatalogResponse.ts
@@ -292,18 +284,7 @@ models/NativeSample.ts
models/NativeSamplePrediction.ts
models/OnboardingMilestone.ts
models/OpenThreadRequest.ts
-models/OpenrouterKeySourceEnum.ts
models/OpenrouterStatusEnum.ts
-models/OptimizerCandidate.ts
-models/OptimizerCandidateStatusEnum.ts
-models/OptimizerCommand.ts
-models/OptimizerCommandStatusEnum.ts
-models/OptimizerExperiment.ts
-models/OptimizerExperimentCreateRequest.ts
-models/OptimizerExperimentStatusEnum.ts
-models/OptimizerExperimentsResultsCreate200Response.ts
-models/OptimizerIteration.ts
-models/OptimizerIterationStatusEnum.ts
models/OverallComparison.ts
models/Package.ts
models/PackageFile.ts
@@ -329,10 +310,6 @@ models/PaginatedFinetuningJobEventList.ts
models/PaginatedFinetuningJobListList.ts
models/PaginatedFinetuningJobRunList.ts
models/PaginatedNativeEvaluationList.ts
-models/PaginatedOptimizerCandidateList.ts
-models/PaginatedOptimizerCommandList.ts
-models/PaginatedOptimizerExperimentList.ts
-models/PaginatedOptimizerIterationList.ts
models/PaginatedPartitionPlanList.ts
models/PaginatedProjectInviteList.ts
models/PaginatedProjectList.ts
@@ -368,7 +345,6 @@ models/PlanEnum.ts
models/PlanUsage.ts
models/PlanUsageUnit.ts
models/PositionEnum.ts
-models/PostResultsRequest.ts
models/PreparationEdge.ts
models/PreparationEdgeKindEnum.ts
models/PreparationNode.ts
@@ -408,7 +384,6 @@ models/ScopeEnum.ts
models/SendMessageRequest.ts
models/ServingContextPlan.ts
models/Session.ts
-models/SetCommandTemplateRequest.ts
models/SignalCatalogEntry.ts
models/SignalEvent.ts
models/SignalEventSeenRequest.ts
diff --git a/frontend/src/openapi/apis/CapabilitiesApi.ts b/frontend/src/openapi/apis/CapabilitiesApi.ts
index 9a1e68cb..f766b84b 100644
--- a/frontend/src/openapi/apis/CapabilitiesApi.ts
+++ b/frontend/src/openapi/apis/CapabilitiesApi.ts
@@ -17,7 +17,6 @@ import * as runtime from '../runtime';
import type {
Capability,
CapabilityRequest,
- EvalSpecResponse,
PaginatedCapabilityListList,
PaginatedPromptList,
PatchedCapabilityRequest,
@@ -27,8 +26,6 @@ import {
CapabilityToJSON,
CapabilityRequestFromJSON,
CapabilityRequestToJSON,
- EvalSpecResponseFromJSON,
- EvalSpecResponseToJSON,
PaginatedCapabilityListListFromJSON,
PaginatedCapabilityListListToJSON,
PaginatedPromptListFromJSON,
@@ -45,10 +42,6 @@ export interface CapabilitiesDestroyRequest {
id: string;
}
-export interface CapabilitiesEvalSpecRetrieveRequest {
- id: string;
-}
-
export interface CapabilitiesListRequest {
model?: string;
name?: string;
@@ -205,63 +198,6 @@ export class CapabilitiesApi extends runtime.BaseAPI {
await this.capabilitiesDestroyRaw(requestParameters, initOverrides);
}
- /**
- * Get capability eval spec
- */
- async capabilitiesEvalSpecRetrieveRaw(requestParameters: CapabilitiesEvalSpecRetrieveRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<EvalSpecResponse>> {
- if (requestParameters['id'] == null) {
- throw new runtime.RequiredError(
- 'id',
- 'Required parameter "id" was null or undefined when calling capabilitiesEvalSpecRetrieve().'
- );
- }
-
- const queryParameters: any = {};
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/capabilities/{id}/eval_spec/`;
- urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));
-
- const response = await this.request({
- path: urlPath,
- method: 'GET',
- headers: headerParameters,
- query: queryParameters,
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => EvalSpecResponseFromJSON(jsonValue));
- }
-
- /**
- * Get capability eval spec
- */
- async capabilitiesEvalSpecRetrieve(requestParameters: CapabilitiesEvalSpecRetrieveRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<EvalSpecResponse> {
- const response = await this.capabilitiesEvalSpecRetrieveRaw(requestParameters, initOverrides);
- return await response.value();
- }
-
/**
* Current capabilities by default; pass `status=leftover` for rows the latest scan did not reproduce.
* List capabilities
diff --git a/frontend/src/openapi/apis/EvalRunsApi.ts b/frontend/src/openapi/apis/EvalRunsApi.ts
index f22a83ea..886ddd89 100644
--- a/frontend/src/openapi/apis/EvalRunsApi.ts
+++ b/frontend/src/openapi/apis/EvalRunsApi.ts
@@ -934,7 +934,6 @@ export type EvalRunsActivityListStatusEnum = typeof EvalRunsActivityListStatusEn
*/
export const EvalRunsListModeEnum = {
generate: 'generate',
- provided: 'provided',
recorded: 'recorded'
} as const;
export type EvalRunsListModeEnum = typeof EvalRunsListModeEnum[keyof typeof EvalRunsListModeEnum];
diff --git a/frontend/src/openapi/apis/EvalSetsApi.ts b/frontend/src/openapi/apis/EvalSetsApi.ts
index 4c11c0e7..5fd49fe1 100644
--- a/frontend/src/openapi/apis/EvalSetsApi.ts
+++ b/frontend/src/openapi/apis/EvalSetsApi.ts
@@ -65,7 +65,7 @@ export interface EvalSetsRetrieveRequest {
export class EvalSetsApi extends runtime.BaseAPI {
/**
- * A named selection of matrix rows. The capability\'s active set drives the optimizer, backtests and training evaluations.
+ * A named selection of matrix rows. The capability\'s active set drives live scoring, eval runs and training evaluations.
* Activate this set on its capability
*/
async evalSetsActivateCreateRaw(requestParameters: EvalSetsActivateCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<EvalSet>> {
@@ -115,7 +115,7 @@ export class EvalSetsApi extends runtime.BaseAPI {
}
/**
- * A named selection of matrix rows. The capability\'s active set drives the optimizer, backtests and training evaluations.
+ * A named selection of matrix rows. The capability\'s active set drives live scoring, eval runs and training evaluations.
* Activate this set on its capability
*/
async evalSetsActivateCreate(requestParameters: EvalSetsActivateCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<EvalSet> {
@@ -124,7 +124,7 @@ export class EvalSetsApi extends runtime.BaseAPI {
}
/**
- * A named selection of matrix rows. The capability\'s active set drives the optimizer, backtests and training evaluations.
+ * A named selection of matrix rows. The capability\'s active set drives live scoring, eval runs and training evaluations.
* Create an eval set
*/
async evalSetsCreateRaw(requestParameters: EvalSetsCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<EvalSet>> {
@@ -176,7 +176,7 @@ export class EvalSetsApi extends runtime.BaseAPI {
}
/**
- * A named selection of matrix rows. The capability\'s active set drives the optimizer, backtests and training evaluations.
+ * A named selection of matrix rows. The capability\'s active set drives live scoring, eval runs and training evaluations.
* Create an eval set
*/
async evalSetsCreate(requestParameters: EvalSetsCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<EvalSet> {
@@ -185,7 +185,7 @@ export class EvalSetsApi extends runtime.BaseAPI {
}
/**
- * A named selection of matrix rows. The capability\'s active set drives the optimizer, backtests and training evaluations.
+ * A named selection of matrix rows. The capability\'s active set drives live scoring, eval runs and training evaluations.
* Delete an eval set
*/
async evalSetsDestroyRaw(requestParameters: EvalSetsDestroyRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<void>> {
@@ -235,7 +235,7 @@ export class EvalSetsApi extends runtime.BaseAPI {
}
/**
- * A named selection of matrix rows. The capability\'s active set drives the optimizer, backtests and training evaluations.
+ * A named selection of matrix rows. The capability\'s active set drives live scoring, eval runs and training evaluations.
* Delete an eval set
*/
async evalSetsDestroy(requestParameters: EvalSetsDestroyRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<void> {
@@ -243,7 +243,7 @@ export class EvalSetsApi extends runtime.BaseAPI {
}
/**
- * A named selection of matrix rows. The capability\'s active set drives the optimizer, backtests and training evaluations.
+ * A named selection of matrix rows. The capability\'s active set drives live scoring, eval runs and training evaluations.
* List eval sets
*/
async evalSetsListRaw(requestParameters: EvalSetsListRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<PaginatedEvalSetList>> {
@@ -301,7 +301,7 @@ export class EvalSetsApi extends runtime.BaseAPI {
}
/**
- * A named selection of matrix rows. The capability\'s active set drives the optimizer, backtests and training evaluations.
+ * A named selection of matrix rows. The capability\'s active set drives live scoring, eval runs and training evaluations.
* List eval sets
*/
async evalSetsList(requestParameters: EvalSetsListRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<PaginatedEvalSetList> {
@@ -310,7 +310,7 @@ export class EvalSetsApi extends runtime.BaseAPI {
}
/**
- * A named selection of matrix rows. The capability\'s active set drives the optimizer, backtests and training evaluations.
+ * A named selection of matrix rows. The capability\'s active set drives live scoring, eval runs and training evaluations.
* Update an eval set\'s name or rows
*/
async evalSetsPartialUpdateRaw(requestParameters: EvalSetsPartialUpdateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<EvalSet>> {
@@ -363,7 +363,7 @@ export class EvalSetsApi extends runtime.BaseAPI {
}
/**
- * A named selection of matrix rows. The capability\'s active set drives the optimizer, backtests and training evaluations.
+ * A named selection of matrix rows. The capability\'s active set drives live scoring, eval runs and training evaluations.
* Update an eval set\'s name or rows
*/
async evalSetsPartialUpdate(requestParameters: EvalSetsPartialUpdateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<EvalSet> {
@@ -372,7 +372,7 @@ export class EvalSetsApi extends runtime.BaseAPI {
}
/**
- * A named selection of matrix rows. The capability\'s active set drives the optimizer, backtests and training evaluations.
+ * A named selection of matrix rows. The capability\'s active set drives live scoring, eval runs and training evaluations.
* Get an eval set
*/
async evalSetsRetrieveRaw(requestParameters: EvalSetsRetrieveRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<EvalSet>> {
@@ -422,7 +422,7 @@ export class EvalSetsApi extends runtime.BaseAPI {
}
/**
- * A named selection of matrix rows. The capability\'s active set drives the optimizer, backtests and training evaluations.
+ * A named selection of matrix rows. The capability\'s active set drives live scoring, eval runs and training evaluations.
* Get an eval set
*/
async evalSetsRetrieve(requestParameters: EvalSetsRetrieveRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<EvalSet> {
diff --git a/frontend/src/openapi/apis/OptimizerCandidatesApi.ts b/frontend/src/openapi/apis/OptimizerCandidatesApi.ts
deleted file mode 100644
index 57178421..00000000
--- a/frontend/src/openapi/apis/OptimizerCandidatesApi.ts
+++ /dev/null
@@ -1,162 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-
-import * as runtime from '../runtime';
-import type {
- OptimizerCandidate,
- PaginatedOptimizerCandidateList,
-} from '../models/index';
-import {
- OptimizerCandidateFromJSON,
- OptimizerCandidateToJSON,
- PaginatedOptimizerCandidateListFromJSON,
- PaginatedOptimizerCandidateListToJSON,
-} from '../models/index';
-
-export interface OptimizerCandidatesListRequest {
- ordering?: string;
- page?: number;
- pageSize?: number;
- search?: string;
-}
-
-export interface OptimizerCandidatesRetrieveRequest {
- id: string;
-}
-
-/**
- *
- */
-export class OptimizerCandidatesApi extends runtime.BaseAPI {
-
- /**
- */
- async optimizerCandidatesListRaw(requestParameters: OptimizerCandidatesListRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<PaginatedOptimizerCandidateList>> {
- const queryParameters: any = {};
-
- if (requestParameters['ordering'] != null) {
- queryParameters['ordering'] = requestParameters['ordering'];
- }
-
- if (requestParameters['page'] != null) {
- queryParameters['page'] = requestParameters['page'];
- }
-
- if (requestParameters['pageSize'] != null) {
- queryParameters['page_size'] = requestParameters['pageSize'];
- }
-
- if (requestParameters['search'] != null) {
- queryParameters['search'] = requestParameters['search'];
- }
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/optimizer-candidates/`;
-
- const response = await this.request({
- path: urlPath,
- method: 'GET',
- headers: headerParameters,
- query: queryParameters,
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => PaginatedOptimizerCandidateListFromJSON(jsonValue));
- }
-
- /**
- */
- async optimizerCandidatesList(requestParameters: OptimizerCandidatesListRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<PaginatedOptimizerCandidateList> {
- const response = await this.optimizerCandidatesListRaw(requestParameters, initOverrides);
- return await response.value();
- }
-
- /**
- */
- async optimizerCandidatesRetrieveRaw(requestParameters: OptimizerCandidatesRetrieveRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<OptimizerCandidate>> {
- if (requestParameters['id'] == null) {
- throw new runtime.RequiredError(
- 'id',
- 'Required parameter "id" was null or undefined when calling optimizerCandidatesRetrieve().'
- );
- }
-
- const queryParameters: any = {};
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/optimizer-candidates/{id}/`;
- urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));
-
- const response = await this.request({
- path: urlPath,
- method: 'GET',
- headers: headerParameters,
- query: queryParameters,
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => OptimizerCandidateFromJSON(jsonValue));
- }
-
- /**
- */
- async optimizerCandidatesRetrieve(requestParameters: OptimizerCandidatesRetrieveRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<OptimizerCandidate> {
- const response = await this.optimizerCandidatesRetrieveRaw(requestParameters, initOverrides);
- return await response.value();
- }
-
-}
diff --git a/frontend/src/openapi/apis/OptimizerExperimentsApi.ts b/frontend/src/openapi/apis/OptimizerExperimentsApi.ts
deleted file mode 100644
index 24c4f4fa..00000000
--- a/frontend/src/openapi/apis/OptimizerExperimentsApi.ts
+++ /dev/null
@@ -1,879 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-
-import * as runtime from '../runtime';
-import type {
- CreateIterationRequest,
- EvaluateIterationRequest,
- OptimizerExperiment,
- OptimizerExperimentCreateRequest,
- OptimizerExperimentsResultsCreate200Response,
- OptimizerIteration,
- PaginatedOptimizerCommandList,
- PaginatedOptimizerExperimentList,
- PaginatedOptimizerIterationList,
- PostResultsRequest,
- SetCommandTemplateRequest,
-} from '../models/index';
-import {
- CreateIterationRequestFromJSON,
- CreateIterationRequestToJSON,
- EvaluateIterationRequestFromJSON,
- EvaluateIterationRequestToJSON,
- OptimizerExperimentFromJSON,
- OptimizerExperimentToJSON,
- OptimizerExperimentCreateRequestFromJSON,
- OptimizerExperimentCreateRequestToJSON,
- OptimizerExperimentsResultsCreate200ResponseFromJSON,
- OptimizerExperimentsResultsCreate200ResponseToJSON,
- OptimizerIterationFromJSON,
- OptimizerIterationToJSON,
- PaginatedOptimizerCommandListFromJSON,
- PaginatedOptimizerCommandListToJSON,
- PaginatedOptimizerExperimentListFromJSON,
- PaginatedOptimizerExperimentListToJSON,
- PaginatedOptimizerIterationListFromJSON,
- PaginatedOptimizerIterationListToJSON,
- PostResultsRequestFromJSON,
- PostResultsRequestToJSON,
- SetCommandTemplateRequestFromJSON,
- SetCommandTemplateRequestToJSON,
-} from '../models/index';
-
-export interface OptimizerExperimentsAddIterationCreateRequest {
- id: string;
- createIterationRequest: CreateIterationRequest;
-}
-
-export interface OptimizerExperimentsCancelCreateRequest {
- id: string;
-}
-
-export interface OptimizerExperimentsCommandsListRequest {
- id: string;
- ordering?: string;
- page?: number;
- pageSize?: number;
- search?: string;
- status?: string;
-}
-
-export interface OptimizerExperimentsCompleteCreateRequest {
- id: string;
-}
-
-export interface OptimizerExperimentsCreateRequest {
- optimizerExperimentCreateRequest: OptimizerExperimentCreateRequest;
-}
-
-export interface OptimizerExperimentsDestroyRequest {
- id: string;
-}
-
-export interface OptimizerExperimentsEvaluateCreateRequest {
- id: string;
- evaluateIterationRequest: EvaluateIterationRequest;
-}
-
-export interface OptimizerExperimentsIterationsListRequest {
- id: string;
- ordering?: string;
- page?: number;
- pageSize?: number;
- search?: string;
-}
-
-export interface OptimizerExperimentsListRequest {
- capability?: string;
- ordering?: string;
- page?: number;
- pageSize?: number;
- project?: string;
- search?: string;
-}
-
-export interface OptimizerExperimentsResultsCreateRequest {
- id: string;
- postResultsRequest: PostResultsRequest;
-}
-
-export interface OptimizerExperimentsRetrieveRequest {
- id: string;
-}
-
-export interface OptimizerExperimentsTemplateCreateRequest {
- id: string;
- setCommandTemplateRequest: SetCommandTemplateRequest;
-}
-
-/**
- *
- */
-export class OptimizerExperimentsApi extends runtime.BaseAPI {
-
- /**
- */
- async optimizerExperimentsAddIterationCreateRaw(requestParameters: OptimizerExperimentsAddIterationCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<OptimizerIteration>> {
- if (requestParameters['id'] == null) {
- throw new runtime.RequiredError(
- 'id',
- 'Required parameter "id" was null or undefined when calling optimizerExperimentsAddIterationCreate().'
- );
- }
-
- if (requestParameters['createIterationRequest'] == null) {
- throw new runtime.RequiredError(
- 'createIterationRequest',
- 'Required parameter "createIterationRequest" was null or undefined when calling optimizerExperimentsAddIterationCreate().'
- );
- }
-
- const queryParameters: any = {};
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- headerParameters['Content-Type'] = 'application/json';
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/optimizer-experiments/{id}/add-iteration/`;
- urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));
-
- const response = await this.request({
- path: urlPath,
- method: 'POST',
- headers: headerParameters,
- query: queryParameters,
- body: CreateIterationRequestToJSON(requestParameters['createIterationRequest']),
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => OptimizerIterationFromJSON(jsonValue));
- }
-
- /**
- */
- async optimizerExperimentsAddIterationCreate(requestParameters: OptimizerExperimentsAddIterationCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<OptimizerIteration> {
- const response = await this.optimizerExperimentsAddIterationCreateRaw(requestParameters, initOverrides);
- return await response.value();
- }
-
- /**
- */
- async optimizerExperimentsCancelCreateRaw(requestParameters: OptimizerExperimentsCancelCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<OptimizerExperiment>> {
- if (requestParameters['id'] == null) {
- throw new runtime.RequiredError(
- 'id',
- 'Required parameter "id" was null or undefined when calling optimizerExperimentsCancelCreate().'
- );
- }
-
- const queryParameters: any = {};
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/optimizer-experiments/{id}/cancel/`;
- urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));
-
- const response = await this.request({
- path: urlPath,
- method: 'POST',
- headers: headerParameters,
- query: queryParameters,
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => OptimizerExperimentFromJSON(jsonValue));
- }
-
- /**
- */
- async optimizerExperimentsCancelCreate(requestParameters: OptimizerExperimentsCancelCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<OptimizerExperiment> {
- const response = await this.optimizerExperimentsCancelCreateRaw(requestParameters, initOverrides);
- return await response.value();
- }
-
- /**
- */
- async optimizerExperimentsCommandsListRaw(requestParameters: OptimizerExperimentsCommandsListRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<PaginatedOptimizerCommandList>> {
- if (requestParameters['id'] == null) {
- throw new runtime.RequiredError(
- 'id',
- 'Required parameter "id" was null or undefined when calling optimizerExperimentsCommandsList().'
- );
- }
-
- const queryParameters: any = {};
-
- if (requestParameters['ordering'] != null) {
- queryParameters['ordering'] = requestParameters['ordering'];
- }
-
- if (requestParameters['page'] != null) {
- queryParameters['page'] = requestParameters['page'];
- }
-
- if (requestParameters['pageSize'] != null) {
- queryParameters['page_size'] = requestParameters['pageSize'];
- }
-
- if (requestParameters['search'] != null) {
- queryParameters['search'] = requestParameters['search'];
- }
-
- if (requestParameters['status'] != null) {
- queryParameters['status'] = requestParameters['status'];
- }
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/optimizer-experiments/{id}/commands/`;
- urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));
-
- const response = await this.request({
- path: urlPath,
- method: 'GET',
- headers: headerParameters,
- query: queryParameters,
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => PaginatedOptimizerCommandListFromJSON(jsonValue));
- }
-
- /**
- */
- async optimizerExperimentsCommandsList(requestParameters: OptimizerExperimentsCommandsListRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<PaginatedOptimizerCommandList> {
- const response = await this.optimizerExperimentsCommandsListRaw(requestParameters, initOverrides);
- return await response.value();
- }
-
- /**
- */
- async optimizerExperimentsCompleteCreateRaw(requestParameters: OptimizerExperimentsCompleteCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<OptimizerExperiment>> {
- if (requestParameters['id'] == null) {
- throw new runtime.RequiredError(
- 'id',
- 'Required parameter "id" was null or undefined when calling optimizerExperimentsCompleteCreate().'
- );
- }
-
- const queryParameters: any = {};
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/optimizer-experiments/{id}/complete/`;
- urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));
-
- const response = await this.request({
- path: urlPath,
- method: 'POST',
- headers: headerParameters,
- query: queryParameters,
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => OptimizerExperimentFromJSON(jsonValue));
- }
-
- /**
- */
- async optimizerExperimentsCompleteCreate(requestParameters: OptimizerExperimentsCompleteCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<OptimizerExperiment> {
- const response = await this.optimizerExperimentsCompleteCreateRaw(requestParameters, initOverrides);
- return await response.value();
- }
-
- /**
- */
- async optimizerExperimentsCreateRaw(requestParameters: OptimizerExperimentsCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<OptimizerExperiment>> {
- if (requestParameters['optimizerExperimentCreateRequest'] == null) {
- throw new runtime.RequiredError(
- 'optimizerExperimentCreateRequest',
- 'Required parameter "optimizerExperimentCreateRequest" was null or undefined when calling optimizerExperimentsCreate().'
- );
- }
-
- const queryParameters: any = {};
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- headerParameters['Content-Type'] = 'application/json';
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/optimizer-experiments/`;
-
- const response = await this.request({
- path: urlPath,
- method: 'POST',
- headers: headerParameters,
- query: queryParameters,
- body: OptimizerExperimentCreateRequestToJSON(requestParameters['optimizerExperimentCreateRequest']),
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => OptimizerExperimentFromJSON(jsonValue));
- }
-
- /**
- */
- async optimizerExperimentsCreate(requestParameters: OptimizerExperimentsCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<OptimizerExperiment> {
- const response = await this.optimizerExperimentsCreateRaw(requestParameters, initOverrides);
- return await response.value();
- }
-
- /**
- */
- async optimizerExperimentsDestroyRaw(requestParameters: OptimizerExperimentsDestroyRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<void>> {
- if (requestParameters['id'] == null) {
- throw new runtime.RequiredError(
- 'id',
- 'Required parameter "id" was null or undefined when calling optimizerExperimentsDestroy().'
- );
- }
-
- const queryParameters: any = {};
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/optimizer-experiments/{id}/`;
- urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));
-
- const response = await this.request({
- path: urlPath,
- method: 'DELETE',
- headers: headerParameters,
- query: queryParameters,
- }, initOverrides);
-
- return new runtime.VoidApiResponse(response);
- }
-
- /**
- */
- async optimizerExperimentsDestroy(requestParameters: OptimizerExperimentsDestroyRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<void> {
- await this.optimizerExperimentsDestroyRaw(requestParameters, initOverrides);
- }
-
- /**
- */
- async optimizerExperimentsEvaluateCreateRaw(requestParameters: OptimizerExperimentsEvaluateCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<OptimizerExperiment>> {
- if (requestParameters['id'] == null) {
- throw new runtime.RequiredError(
- 'id',
- 'Required parameter "id" was null or undefined when calling optimizerExperimentsEvaluateCreate().'
- );
- }
-
- if (requestParameters['evaluateIterationRequest'] == null) {
- throw new runtime.RequiredError(
- 'evaluateIterationRequest',
- 'Required parameter "evaluateIterationRequest" was null or undefined when calling optimizerExperimentsEvaluateCreate().'
- );
- }
-
- const queryParameters: any = {};
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- headerParameters['Content-Type'] = 'application/json';
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/optimizer-experiments/{id}/evaluate/`;
- urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));
-
- const response = await this.request({
- path: urlPath,
- method: 'POST',
- headers: headerParameters,
- query: queryParameters,
- body: EvaluateIterationRequestToJSON(requestParameters['evaluateIterationRequest']),
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => OptimizerExperimentFromJSON(jsonValue));
- }
-
- /**
- */
- async optimizerExperimentsEvaluateCreate(requestParameters: OptimizerExperimentsEvaluateCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<OptimizerExperiment> {
- const response = await this.optimizerExperimentsEvaluateCreateRaw(requestParameters, initOverrides);
- return await response.value();
- }
-
- /**
- */
- async optimizerExperimentsIterationsListRaw(requestParameters: OptimizerExperimentsIterationsListRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<PaginatedOptimizerIterationList>> {
- if (requestParameters['id'] == null) {
- throw new runtime.RequiredError(
- 'id',
- 'Required parameter "id" was null or undefined when calling optimizerExperimentsIterationsList().'
- );
- }
-
- const queryParameters: any = {};
-
- if (requestParameters['ordering'] != null) {
- queryParameters['ordering'] = requestParameters['ordering'];
- }
-
- if (requestParameters['page'] != null) {
- queryParameters['page'] = requestParameters['page'];
- }
-
- if (requestParameters['pageSize'] != null) {
- queryParameters['page_size'] = requestParameters['pageSize'];
- }
-
- if (requestParameters['search'] != null) {
- queryParameters['search'] = requestParameters['search'];
- }
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/optimizer-experiments/{id}/iterations/`;
- urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));
-
- const response = await this.request({
- path: urlPath,
- method: 'GET',
- headers: headerParameters,
- query: queryParameters,
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => PaginatedOptimizerIterationListFromJSON(jsonValue));
- }
-
- /**
- */
- async optimizerExperimentsIterationsList(requestParameters: OptimizerExperimentsIterationsListRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<PaginatedOptimizerIterationList> {
- const response = await this.optimizerExperimentsIterationsListRaw(requestParameters, initOverrides);
- return await response.value();
- }
-
- /**
- */
- async optimizerExperimentsListRaw(requestParameters: OptimizerExperimentsListRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<PaginatedOptimizerExperimentList>> {
- const queryParameters: any = {};
-
- if (requestParameters['capability'] != null) {
- queryParameters['capability'] = requestParameters['capability'];
- }
-
- if (requestParameters['ordering'] != null) {
- queryParameters['ordering'] = requestParameters['ordering'];
- }
-
- if (requestParameters['page'] != null) {
- queryParameters['page'] = requestParameters['page'];
- }
-
- if (requestParameters['pageSize'] != null) {
- queryParameters['page_size'] = requestParameters['pageSize'];
- }
-
- if (requestParameters['project'] != null) {
- queryParameters['project'] = requestParameters['project'];
- }
-
- if (requestParameters['search'] != null) {
- queryParameters['search'] = requestParameters['search'];
- }
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/optimizer-experiments/`;
-
- const response = await this.request({
- path: urlPath,
- method: 'GET',
- headers: headerParameters,
- query: queryParameters,
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => PaginatedOptimizerExperimentListFromJSON(jsonValue));
- }
-
- /**
- */
- async optimizerExperimentsList(requestParameters: OptimizerExperimentsListRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<PaginatedOptimizerExperimentList> {
- const response = await this.optimizerExperimentsListRaw(requestParameters, initOverrides);
- return await response.value();
- }
-
- /**
- */
- async optimizerExperimentsResultsCreateRaw(requestParameters: OptimizerExperimentsResultsCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<OptimizerExperimentsResultsCreate200Response>> {
- if (requestParameters['id'] == null) {
- throw new runtime.RequiredError(
- 'id',
- 'Required parameter "id" was null or undefined when calling optimizerExperimentsResultsCreate().'
- );
- }
-
- if (requestParameters['postResultsRequest'] == null) {
- throw new runtime.RequiredError(
- 'postResultsRequest',
- 'Required parameter "postResultsRequest" was null or undefined when calling optimizerExperimentsResultsCreate().'
- );
- }
-
- const queryParameters: any = {};
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- headerParameters['Content-Type'] = 'application/json';
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/optimizer-experiments/{id}/results/`;
- urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));
-
- const response = await this.request({
- path: urlPath,
- method: 'POST',
- headers: headerParameters,
- query: queryParameters,
- body: PostResultsRequestToJSON(requestParameters['postResultsRequest']),
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => OptimizerExperimentsResultsCreate200ResponseFromJSON(jsonValue));
- }
-
- /**
- */
- async optimizerExperimentsResultsCreate(requestParameters: OptimizerExperimentsResultsCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<OptimizerExperimentsResultsCreate200Response> {
- const response = await this.optimizerExperimentsResultsCreateRaw(requestParameters, initOverrides);
- return await response.value();
- }
-
- /**
- */
- async optimizerExperimentsRetrieveRaw(requestParameters: OptimizerExperimentsRetrieveRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<OptimizerExperiment>> {
- if (requestParameters['id'] == null) {
- throw new runtime.RequiredError(
- 'id',
- 'Required parameter "id" was null or undefined when calling optimizerExperimentsRetrieve().'
- );
- }
-
- const queryParameters: any = {};
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/optimizer-experiments/{id}/`;
- urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));
-
- const response = await this.request({
- path: urlPath,
- method: 'GET',
- headers: headerParameters,
- query: queryParameters,
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => OptimizerExperimentFromJSON(jsonValue));
- }
-
- /**
- */
- async optimizerExperimentsRetrieve(requestParameters: OptimizerExperimentsRetrieveRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<OptimizerExperiment> {
- const response = await this.optimizerExperimentsRetrieveRaw(requestParameters, initOverrides);
- return await response.value();
- }
-
- /**
- */
- async optimizerExperimentsTemplateCreateRaw(requestParameters: OptimizerExperimentsTemplateCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<OptimizerExperiment>> {
- if (requestParameters['id'] == null) {
- throw new runtime.RequiredError(
- 'id',
- 'Required parameter "id" was null or undefined when calling optimizerExperimentsTemplateCreate().'
- );
- }
-
- if (requestParameters['setCommandTemplateRequest'] == null) {
- throw new runtime.RequiredError(
- 'setCommandTemplateRequest',
- 'Required parameter "setCommandTemplateRequest" was null or undefined when calling optimizerExperimentsTemplateCreate().'
- );
- }
-
- const queryParameters: any = {};
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- headerParameters['Content-Type'] = 'application/json';
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/optimizer-experiments/{id}/template/`;
- urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));
-
- const response = await this.request({
- path: urlPath,
- method: 'POST',
- headers: headerParameters,
- query: queryParameters,
- body: SetCommandTemplateRequestToJSON(requestParameters['setCommandTemplateRequest']),
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => OptimizerExperimentFromJSON(jsonValue));
- }
-
- /**
- */
- async optimizerExperimentsTemplateCreate(requestParameters: OptimizerExperimentsTemplateCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<OptimizerExperiment> {
- const response = await this.optimizerExperimentsTemplateCreateRaw(requestParameters, initOverrides);
- return await response.value();
- }
-
-}
diff --git a/frontend/src/openapi/apis/index.ts b/frontend/src/openapi/apis/index.ts
index d3782d14..081542b9 100644
--- a/frontend/src/openapi/apis/index.ts
+++ b/frontend/src/openapi/apis/index.ts
@@ -30,8 +30,6 @@ export * from './InferenceRequestsApi';
export * from './McpOauthApi';
export * from './ModelsApi';
export * from './NativeEvaluationsApi';
-export * from './OptimizerCandidatesApi';
-export * from './OptimizerExperimentsApi';
export * from './ProjectsApi';
export * from './PublicApi';
export * from './SessionsApi';
diff --git a/frontend/src/openapi/models/CandidateInputRequest.ts b/frontend/src/openapi/models/CandidateInputRequest.ts
deleted file mode 100644
index 1acef3a2..00000000
--- a/frontend/src/openapi/models/CandidateInputRequest.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-/**
- *
- * @export
- * @interface CandidateInputRequest
- */
-export interface CandidateInputRequest {
- /**
- *
- * @type {number}
- * @memberof CandidateInputRequest
- */
- candidateIndex: number;
- /**
- *
- * @type {string}
- * @memberof CandidateInputRequest
- */
- codePath?: string;
- /**
- *
- * @type {string}
- * @memberof CandidateInputRequest
- */
- patch?: string;
- /**
- *
- * @type {string}
- * @memberof CandidateInputRequest
- */
- targetModel?: string;
- /**
- *
- * @type {boolean}
- * @memberof CandidateInputRequest
- */
- isBaseline?: boolean;
-}
-
-/**
- * Check if a given object implements the CandidateInputRequest interface.
- */
-export function instanceOfCandidateInputRequest(value: object): value is CandidateInputRequest {
- if (!('candidateIndex' in value) || value['candidateIndex'] === undefined) return false;
- return true;
-}
-
-export function CandidateInputRequestFromJSON(json: any): CandidateInputRequest {
- return CandidateInputRequestFromJSONTyped(json, false);
-}
-
-export function CandidateInputRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): CandidateInputRequest {
- if (json == null) {
- return json;
- }
- return {
-
- 'candidateIndex': json['candidate_index'],
- 'codePath': json['code_path'] == null ? undefined : json['code_path'],
- 'patch': json['patch'] == null ? undefined : json['patch'],
- 'targetModel': json['target_model'] == null ? undefined : json['target_model'],
- 'isBaseline': json['is_baseline'] == null ? undefined : json['is_baseline'],
- };
-}
-
-export function CandidateInputRequestToJSON(json: any): CandidateInputRequest {
- return CandidateInputRequestToJSONTyped(json, false);
-}
-
-export function CandidateInputRequestToJSONTyped(value?: CandidateInputRequest | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'candidate_index': value['candidateIndex'],
- 'code_path': value['codePath'],
- 'patch': value['patch'],
- 'target_model': value['targetModel'],
- 'is_baseline': value['isBaseline'],
- };
-}
diff --git a/frontend/src/openapi/models/Capability.ts b/frontend/src/openapi/models/Capability.ts
index 3f588a8d..dc60ee4f 100644
--- a/frontend/src/openapi/models/Capability.ts
+++ b/frontend/src/openapi/models/Capability.ts
@@ -59,24 +59,6 @@ export interface Capability {
* @memberof Capability
*/
toolConfig?: any | null;
- /**
- *
- * @type {any}
- * @memberof Capability
- */
- consistencyRules?: any | null;
- /**
- *
- * @type {any}
- * @memberof Capability
- */
- optimizableElements?: any | null;
- /**
- *
- * @type {any}
- * @memberof Capability
- */
- fixedElements?: any | null;
/**
*
* @type {number}
@@ -125,12 +107,6 @@ export interface Capability {
* @memberof Capability
*/
model?: string;
- /**
- *
- * @type {string}
- * @memberof Capability
- */
- analyzerModel?: string;
/**
*
* @type {string}
@@ -173,24 +149,6 @@ export interface Capability {
* @memberof Capability
*/
outputSchema?: any | null;
- /**
- *
- * @type {number}
- * @memberof Capability
- */
- structureWeight?: number;
- /**
- *
- * @type {number}
- * @memberof Capability
- */
- totalPoints?: number;
- /**
- *
- * @type {number}
- * @memberof Capability
- */
- toolUsageWeight?: number;
/**
*
* @type {string}
@@ -324,9 +282,6 @@ export function CapabilityFromJSONTyped(json: any, ignoreDiscriminator: boolean)
'id': json['id'],
'activation': ModelActivationFromJSON(json['activation']),
'toolConfig': json['tool_config'] == null ? undefined : json['tool_config'],
- 'consistencyRules': json['consistency_rules'] == null ? undefined : json['consistency_rules'],
- 'optimizableElements': json['optimizable_elements'] == null ? undefined : json['optimizable_elements'],
- 'fixedElements': json['fixed_elements'] == null ? undefined : json['fixed_elements'],
'datasetSize': json['dataset_size'],
'flow': CapabilityFlowFromJSON(json['flow']),
'name': json['name'],
@@ -335,7 +290,6 @@ export function CapabilityFromJSONTyped(json: any, ignoreDiscriminator: boolean)
'sourcePath': json['source_path'] == null ? undefined : json['source_path'],
'entrypointFn': json['entrypoint_fn'] == null ? undefined : json['entrypoint_fn'],
'model': json['model'] == null ? undefined : json['model'],
- 'analyzerModel': json['analyzer_model'] == null ? undefined : json['analyzer_model'],
'cliVersion': json['cli_version'] == null ? undefined : json['cli_version'],
'status': json['status'] == null ? undefined : CapabilityStatusEnumFromJSON(json['status']),
'observed': json['observed'] == null ? undefined : json['observed'],
@@ -343,9 +297,6 @@ export function CapabilityFromJSONTyped(json: any, ignoreDiscriminator: boolean)
'inputSchema': json['input_schema'] == null ? undefined : json['input_schema'],
'outputFields': json['output_fields'] == null ? undefined : json['output_fields'],
'outputSchema': json['output_schema'] == null ? undefined : json['output_schema'],
- 'structureWeight': json['structure_weight'] == null ? undefined : json['structure_weight'],
- 'totalPoints': json['total_points'] == null ? undefined : json['total_points'],
- 'toolUsageWeight': json['tool_usage_weight'] == null ? undefined : json['tool_usage_weight'],
'policyMarkdown': json['policy_markdown'] == null ? undefined : json['policy_markdown'],
'toolsSummary': json['tools_summary'] == null ? undefined : json['tools_summary'],
'decisionLogic': json['decision_logic'] == null ? undefined : json['decision_logic'],
@@ -377,15 +328,11 @@ export function CapabilityToJSONTyped(value?: Omit<Capability, 'id'|'activation'
return {
'tool_config': value['toolConfig'],
- 'consistency_rules': value['consistencyRules'],
- 'optimizable_elements': value['optimizableElements'],
- 'fixed_elements': value['fixedElements'],
'name': value['name'],
'description': value['description'],
'source_path': value['sourcePath'],
'entrypoint_fn': value['entrypointFn'],
'model': value['model'],
- 'analyzer_model': value['analyzerModel'],
'cli_version': value['cliVersion'],
'status': CapabilityStatusEnumToJSON(value['status']),
'observed': value['observed'],
@@ -393,9 +340,6 @@ export function CapabilityToJSONTyped(value?: Omit<Capability, 'id'|'activation'
'input_schema': value['inputSchema'],
'output_fields': value['outputFields'],
'output_schema': value['outputSchema'],
- 'structure_weight': value['structureWeight'],
- 'total_points': value['totalPoints'],
- 'tool_usage_weight': value['toolUsageWeight'],
'policy_markdown': value['policyMarkdown'],
'tools_summary': value['toolsSummary'],
'decision_logic': value['decisionLogic'],
diff --git a/frontend/src/openapi/models/CapabilityList.ts b/frontend/src/openapi/models/CapabilityList.ts
index a74aa68f..fabbaaa8 100644
--- a/frontend/src/openapi/models/CapabilityList.ts
+++ b/frontend/src/openapi/models/CapabilityList.ts
@@ -81,24 +81,6 @@ export interface CapabilityList {
* @memberof CapabilityList
*/
benchmarkModel?: string | null;
- /**
- *
- * @type {number}
- * @memberof CapabilityList
- */
- structureWeight?: number;
- /**
- *
- * @type {number}
- * @memberof CapabilityList
- */
- totalPoints?: number;
- /**
- *
- * @type {number}
- * @memberof CapabilityList
- */
- toolUsageWeight?: number;
/**
*
* @type {CapabilityStatusEnum}
@@ -123,12 +105,6 @@ export interface CapabilityList {
* @memberof CapabilityList
*/
entrypointFn?: string;
- /**
- *
- * @type {string}
- * @memberof CapabilityList
- */
- analyzerModel?: string;
/**
*
* @type {number}
@@ -232,14 +208,10 @@ export function CapabilityListFromJSONTyped(json: any, ignoreDiscriminator: bool
'model': json['model'] == null ? undefined : json['model'],
'activeModel': json['active_model'] == null ? undefined : json['active_model'],
'benchmarkModel': json['benchmark_model'] == null ? undefined : json['benchmark_model'],
- 'structureWeight': json['structure_weight'] == null ? undefined : json['structure_weight'],
- 'totalPoints': json['total_points'] == null ? undefined : json['total_points'],
- 'toolUsageWeight': json['tool_usage_weight'] == null ? undefined : json['tool_usage_weight'],
'status': json['status'] == null ? undefined : CapabilityStatusEnumFromJSON(json['status']),
'observed': json['observed'] == null ? undefined : json['observed'],
'suggestedName': json['suggested_name'],
'entrypointFn': json['entrypoint_fn'] == null ? undefined : json['entrypoint_fn'],
- 'analyzerModel': json['analyzer_model'] == null ? undefined : json['analyzer_model'],
'datasetSize': json['dataset_size'],
'datasetHasExpectedOutput': json['dataset_has_expected_output'],
'datasetInputKeys': json['dataset_input_keys'],
@@ -272,13 +244,9 @@ export function CapabilityListToJSONTyped(value?: Omit<CapabilityList, 'id'|'sug
'model': value['model'],
'active_model': value['activeModel'],
'benchmark_model': value['benchmarkModel'],
- 'structure_weight': value['structureWeight'],
- 'total_points': value['totalPoints'],
- 'tool_usage_weight': value['toolUsageWeight'],
'status': CapabilityStatusEnumToJSON(value['status']),
'observed': value['observed'],
'entrypoint_fn': value['entrypointFn'],
- 'analyzer_model': value['analyzerModel'],
'cli_version': value['cliVersion'],
'last_activity_at': value['lastActivityAt'] == null ? value['lastActivityAt'] : value['lastActivityAt'].toISOString(),
};
diff --git a/frontend/src/openapi/models/CapabilityRequest.ts b/frontend/src/openapi/models/CapabilityRequest.ts
index ff653bdd..72edee26 100644
--- a/frontend/src/openapi/models/CapabilityRequest.ts
+++ b/frontend/src/openapi/models/CapabilityRequest.ts
@@ -33,24 +33,6 @@ export interface CapabilityRequest {
* @memberof CapabilityRequest
*/
toolConfig?: any | null;
- /**
- *
- * @type {any}
- * @memberof CapabilityRequest
- */
- consistencyRules?: any | null;
- /**
- *
- * @type {any}
- * @memberof CapabilityRequest
- */
- optimizableElements?: any | null;
- /**
- *
- * @type {any}
- * @memberof CapabilityRequest
- */
- fixedElements?: any | null;
/**
*
* @type {string}
@@ -81,12 +63,6 @@ export interface CapabilityRequest {
* @memberof CapabilityRequest
*/
model?: string;
- /**
- *
- * @type {string}
- * @memberof CapabilityRequest
- */
- analyzerModel?: string;
/**
*
* @type {string}
@@ -129,24 +105,6 @@ export interface CapabilityRequest {
* @memberof CapabilityRequest
*/
outputSchema?: any | null;
- /**
- *
- * @type {number}
- * @memberof CapabilityRequest
- */
- structureWeight?: number;
- /**
- *
- * @type {number}
- * @memberof CapabilityRequest
- */
- totalPoints?: number;
- /**
- *
- * @type {number}
- * @memberof CapabilityRequest
- */
- toolUsageWeight?: number;
/**
*
* @type {string}
@@ -231,15 +189,11 @@ export function CapabilityRequestFromJSONTyped(json: any, ignoreDiscriminator: b
return {
'toolConfig': json['tool_config'] == null ? undefined : json['tool_config'],
- 'consistencyRules': json['consistency_rules'] == null ? undefined : json['consistency_rules'],
- 'optimizableElements': json['optimizable_elements'] == null ? undefined : json['optimizable_elements'],
- 'fixedElements': json['fixed_elements'] == null ? undefined : json['fixed_elements'],
'name': json['name'],
'description': json['description'] == null ? undefined : json['description'],
'sourcePath': json['source_path'] == null ? undefined : json['source_path'],
'entrypointFn': json['entrypoint_fn'] == null ? undefined : json['entrypoint_fn'],
'model': json['model'] == null ? undefined : json['model'],
- 'analyzerModel': json['analyzer_model'] == null ? undefined : json['analyzer_model'],
'cliVersion': json['cli_version'] == null ? undefined : json['cli_version'],
'status': json['status'] == null ? undefined : CapabilityStatusEnumFromJSON(json['status']),
'observed': json['observed'] == null ? undefined : json['observed'],
@@ -247,9 +201,6 @@ export function CapabilityRequestFromJSONTyped(json: any, ignoreDiscriminator: b
'inputSchema': json['input_schema'] == null ? undefined : json['input_schema'],
'outputFields': json['output_fields'] == null ? undefined : json['output_fields'],
'outputSchema': json['output_schema'] == null ? undefined : json['output_schema'],
- 'structureWeight': json['structure_weight'] == null ? undefined : json['structure_weight'],
- 'totalPoints': json['total_points'] == null ? undefined : json['total_points'],
- 'toolUsageWeight': json['tool_usage_weight'] == null ? undefined : json['tool_usage_weight'],
'policyMarkdown': json['policy_markdown'] == null ? undefined : json['policy_markdown'],
'toolsSummary': json['tools_summary'] == null ? undefined : json['tools_summary'],
'decisionLogic': json['decision_logic'] == null ? undefined : json['decision_logic'],
@@ -275,15 +226,11 @@ export function CapabilityRequestToJSONTyped(value?: CapabilityRequest | null, i
return {
'tool_config': value['toolConfig'],
- 'consistency_rules': value['consistencyRules'],
- 'optimizable_elements': value['optimizableElements'],
- 'fixed_elements': value['fixedElements'],
'name': value['name'],
'description': value['description'],
'source_path': value['sourcePath'],
'entrypoint_fn': value['entrypointFn'],
'model': value['model'],
- 'analyzer_model': value['analyzerModel'],
'cli_version': value['cliVersion'],
'status': CapabilityStatusEnumToJSON(value['status']),
'observed': value['observed'],
@@ -291,9 +238,6 @@ export function CapabilityRequestToJSONTyped(value?: CapabilityRequest | null, i
'input_schema': value['inputSchema'],
'output_fields': value['outputFields'],
'output_schema': value['outputSchema'],
- 'structure_weight': value['structureWeight'],
- 'total_points': value['totalPoints'],
- 'tool_usage_weight': value['toolUsageWeight'],
'policy_markdown': value['policyMarkdown'],
'tools_summary': value['toolsSummary'],
'decision_logic': value['decisionLogic'],
diff --git a/frontend/src/openapi/models/CommandResultInputRequest.ts b/frontend/src/openapi/models/CommandResultInputRequest.ts
deleted file mode 100644
index 39e3e493..00000000
--- a/frontend/src/openapi/models/CommandResultInputRequest.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-/**
- *
- * @export
- * @interface CommandResultInputRequest
- */
-export interface CommandResultInputRequest {
- /**
- *
- * @type {string}
- * @memberof CommandResultInputRequest
- */
- candidateId: string;
- /**
- *
- * @type {number}
- * @memberof CommandResultInputRequest
- */
- datapointIndex: number;
- /**
- *
- * @type {boolean}
- * @memberof CommandResultInputRequest
- */
- success?: boolean;
- /**
- *
- * @type {string}
- * @memberof CommandResultInputRequest
- */
- output?: string;
- /**
- *
- * @type {string}
- * @memberof CommandResultInputRequest
- */
- error?: string;
- /**
- *
- * @type {string}
- * @memberof CommandResultInputRequest
- */
- traceId?: string;
- /**
- *
- * @type {any}
- * @memberof CommandResultInputRequest
- */
- input?: any | null;
-}
-
-/**
- * Check if a given object implements the CommandResultInputRequest interface.
- */
-export function instanceOfCommandResultInputRequest(value: object): value is CommandResultInputRequest {
- if (!('candidateId' in value) || value['candidateId'] === undefined) return false;
- if (!('datapointIndex' in value) || value['datapointIndex'] === undefined) return false;
- return true;
-}
-
-export function CommandResultInputRequestFromJSON(json: any): CommandResultInputRequest {
- return CommandResultInputRequestFromJSONTyped(json, false);
-}
-
-export function CommandResultInputRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): CommandResultInputRequest {
- if (json == null) {
- return json;
- }
- return {
-
- 'candidateId': json['candidate_id'],
- 'datapointIndex': json['datapoint_index'],
- 'success': json['success'] == null ? undefined : json['success'],
- 'output': json['output'] == null ? undefined : json['output'],
- 'error': json['error'] == null ? undefined : json['error'],
- 'traceId': json['trace_id'] == null ? undefined : json['trace_id'],
- 'input': json['input'] == null ? undefined : json['input'],
- };
-}
-
-export function CommandResultInputRequestToJSON(json: any): CommandResultInputRequest {
- return CommandResultInputRequestToJSONTyped(json, false);
-}
-
-export function CommandResultInputRequestToJSONTyped(value?: CommandResultInputRequest | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'candidate_id': value['candidateId'],
- 'datapoint_index': value['datapointIndex'],
- 'success': value['success'],
- 'output': value['output'],
- 'error': value['error'],
- 'trace_id': value['traceId'],
- 'input': value['input'],
- };
-}
diff --git a/frontend/src/openapi/models/CreateIterationRequest.ts b/frontend/src/openapi/models/CreateIterationRequest.ts
deleted file mode 100644
index 5b1e5793..00000000
--- a/frontend/src/openapi/models/CreateIterationRequest.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-import type { CandidateInputRequest } from './CandidateInputRequest';
-import {
- CandidateInputRequestFromJSON,
- CandidateInputRequestFromJSONTyped,
- CandidateInputRequestToJSON,
- CandidateInputRequestToJSONTyped,
-} from './CandidateInputRequest';
-
-/**
- *
- * @export
- * @interface CreateIterationRequest
- */
-export interface CreateIterationRequest {
- /**
- *
- * @type {number}
- * @memberof CreateIterationRequest
- */
- order: number;
- /**
- *
- * @type {string}
- * @memberof CreateIterationRequest
- */
- name?: string;
- /**
- *
- * @type {Array<CandidateInputRequest>}
- * @memberof CreateIterationRequest
- */
- candidates: Array<CandidateInputRequest>;
-}
-
-/**
- * Check if a given object implements the CreateIterationRequest interface.
- */
-export function instanceOfCreateIterationRequest(value: object): value is CreateIterationRequest {
- if (!('order' in value) || value['order'] === undefined) return false;
- if (!('candidates' in value) || value['candidates'] === undefined) return false;
- return true;
-}
-
-export function CreateIterationRequestFromJSON(json: any): CreateIterationRequest {
- return CreateIterationRequestFromJSONTyped(json, false);
-}
-
-export function CreateIterationRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): CreateIterationRequest {
- if (json == null) {
- return json;
- }
- return {
-
- 'order': json['order'],
- 'name': json['name'] == null ? undefined : json['name'],
- 'candidates': ((json['candidates'] as Array<any>).map(CandidateInputRequestFromJSON)),
- };
-}
-
-export function CreateIterationRequestToJSON(json: any): CreateIterationRequest {
- return CreateIterationRequestToJSONTyped(json, false);
-}
-
-export function CreateIterationRequestToJSONTyped(value?: CreateIterationRequest | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'order': value['order'],
- 'name': value['name'],
- 'candidates': ((value['candidates'] as Array<any>).map(CandidateInputRequestToJSON)),
- };
-}
diff --git a/frontend/src/openapi/models/EvalRun.ts b/frontend/src/openapi/models/EvalRun.ts
index 186eec6c..ad7dea7a 100644
--- a/frontend/src/openapi/models/EvalRun.ts
+++ b/frontend/src/openapi/models/EvalRun.ts
@@ -209,12 +209,6 @@ export interface EvalRun {
* @memberof EvalRun
*/
readonly origin: string;
- /**
- *
- * @type {string}
- * @memberof EvalRun
- */
- readonly optimizerExperiment: string | null;
/**
*
* @type {number}
@@ -275,7 +269,6 @@ export function instanceOfEvalRun(value: object): value is EvalRun {
if (!('summary' in value) || value['summary'] === undefined) return false;
if (!('progress' in value) || value['progress'] === undefined) return false;
if (!('origin' in value) || value['origin'] === undefined) return false;
- if (!('optimizerExperiment' in value) || value['optimizerExperiment'] === undefined) return false;
if (!('triggeredBy' in value) || value['triggeredBy'] === undefined) return false;
if (!('createdAt' in value) || value['createdAt'] === undefined) return false;
if (!('updatedAt' in value) || value['updatedAt'] === undefined) return false;
@@ -321,7 +314,6 @@ export function EvalRunFromJSONTyped(json: any, ignoreDiscriminator: boolean): E
'summary': json['summary'],
'progress': EvalRunProgressFromJSON(json['progress']),
'origin': json['origin'],
- 'optimizerExperiment': json['optimizer_experiment'],
'triggeredBy': json['triggered_by'],
'createdAt': (new Date(json['created_at'])),
'updatedAt': (new Date(json['updated_at'])),
@@ -333,7 +325,7 @@ export function EvalRunToJSON(json: any): EvalRun {
return EvalRunToJSONTyped(json, false);
}
-export function EvalRunToJSONTyped(value?: Omit<EvalRun, 'id'|'project'|'name'|'description'|'label'|'dataset'|'dataset_name'|'capability_id'|'capability_name'|'cell'|'cell_info'|'max_items'|'sampling'|'eval_set'|'matrix'|'mode'|'model_ref'|'model_name'|'resolved_model'|'params'|'group'|'is_baseline'|'judge_model'|'status'|'error'|'summary'|'progress'|'origin'|'optimizer_experiment'|'triggered_by'|'created_at'|'updated_at'|'completed_at'> | null, ignoreDiscriminator: boolean = false): any {
+export function EvalRunToJSONTyped(value?: Omit<EvalRun, 'id'|'project'|'name'|'description'|'label'|'dataset'|'dataset_name'|'capability_id'|'capability_name'|'cell'|'cell_info'|'max_items'|'sampling'|'eval_set'|'matrix'|'mode'|'model_ref'|'model_name'|'resolved_model'|'params'|'group'|'is_baseline'|'judge_model'|'status'|'error'|'summary'|'progress'|'origin'|'triggered_by'|'created_at'|'updated_at'|'completed_at'> | null, ignoreDiscriminator: boolean = false): any {
if (value == null) {
return value;
}
diff --git a/frontend/src/openapi/models/EvalRunDetail.ts b/frontend/src/openapi/models/EvalRunDetail.ts
index 7250aca2..d1a39f0f 100644
--- a/frontend/src/openapi/models/EvalRunDetail.ts
+++ b/frontend/src/openapi/models/EvalRunDetail.ts
@@ -216,12 +216,6 @@ export interface EvalRunDetail {
* @memberof EvalRunDetail
*/
readonly origin: string;
- /**
- *
- * @type {string}
- * @memberof EvalRunDetail
- */
- readonly optimizerExperiment: string | null;
/**
*
* @type {number}
@@ -288,7 +282,6 @@ export function instanceOfEvalRunDetail(value: object): value is EvalRunDetail {
if (!('summary' in value) || value['summary'] === undefined) return false;
if (!('progress' in value) || value['progress'] === undefined) return false;
if (!('origin' in value) || value['origin'] === undefined) return false;
- if (!('optimizerExperiment' in value) || value['optimizerExperiment'] === undefined) return false;
if (!('triggeredBy' in value) || value['triggeredBy'] === undefined) return false;
if (!('createdAt' in value) || value['createdAt'] === undefined) return false;
if (!('updatedAt' in value) || value['updatedAt'] === undefined) return false;
@@ -335,7 +328,6 @@ export function EvalRunDetailFromJSONTyped(json: any, ignoreDiscriminator: boole
'summary': json['summary'],
'progress': EvalRunProgressFromJSON(json['progress']),
'origin': json['origin'],
- 'optimizerExperiment': json['optimizer_experiment'],
'triggeredBy': json['triggered_by'],
'createdAt': (new Date(json['created_at'])),
'updatedAt': (new Date(json['updated_at'])),
@@ -348,7 +340,7 @@ export function EvalRunDetailToJSON(json: any): EvalRunDetail {
return EvalRunDetailToJSONTyped(json, false);
}
-export function EvalRunDetailToJSONTyped(value?: Omit<EvalRunDetail, 'id'|'project'|'name'|'description'|'label'|'dataset'|'dataset_name'|'capability_id'|'capability_name'|'cell'|'cell_info'|'max_items'|'sampling'|'eval_set'|'matrix'|'mode'|'model_ref'|'model_name'|'resolved_model'|'params'|'group'|'is_baseline'|'judge_model'|'status'|'error'|'summary'|'progress'|'origin'|'optimizer_experiment'|'triggered_by'|'created_at'|'updated_at'|'completed_at'|'context_checks'> | null, ignoreDiscriminator: boolean = false): any {
+export function EvalRunDetailToJSONTyped(value?: Omit<EvalRunDetail, 'id'|'project'|'name'|'description'|'label'|'dataset'|'dataset_name'|'capability_id'|'capability_name'|'cell'|'cell_info'|'max_items'|'sampling'|'eval_set'|'matrix'|'mode'|'model_ref'|'model_name'|'resolved_model'|'params'|'group'|'is_baseline'|'judge_model'|'status'|'error'|'summary'|'progress'|'origin'|'triggered_by'|'created_at'|'updated_at'|'completed_at'|'context_checks'> | null, ignoreDiscriminator: boolean = false): any {
if (value == null) {
return value;
}
diff --git a/frontend/src/openapi/models/EvalRunModeEnum.ts b/frontend/src/openapi/models/EvalRunModeEnum.ts
index 2172124f..2b737f57 100644
--- a/frontend/src/openapi/models/EvalRunModeEnum.ts
+++ b/frontend/src/openapi/models/EvalRunModeEnum.ts
@@ -16,13 +16,11 @@
/**
* * `recorded` - Recorded
* * `generate` - Generate
- * * `provided` - Provided
* @export
*/
export const EvalRunModeEnum = {
recorded: 'recorded',
- generate: 'generate',
- provided: 'provided'
+ generate: 'generate'
} as const;
export type EvalRunModeEnum = typeof EvalRunModeEnum[keyof typeof EvalRunModeEnum];
diff --git a/frontend/src/openapi/models/EvalSpecResponse.ts b/frontend/src/openapi/models/EvalSpecResponse.ts
deleted file mode 100644
index 8f55c3d7..00000000
--- a/frontend/src/openapi/models/EvalSpecResponse.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-/**
- *
- * @export
- * @interface EvalSpecResponse
- */
-export interface EvalSpecResponse {
- /**
- *
- * @type {string}
- * @memberof EvalSpecResponse
- */
- capabilityDescription: string;
- /**
- *
- * @type {string}
- * @memberof EvalSpecResponse
- */
- sourcePath: string;
- /**
- *
- * @type {any}
- * @memberof EvalSpecResponse
- */
- inputSchema: any | null;
- /**
- *
- * @type {any}
- * @memberof EvalSpecResponse
- */
- outputFields: any | null;
- /**
- *
- * @type {number}
- * @memberof EvalSpecResponse
- */
- structureWeight: number;
- /**
- *
- * @type {number}
- * @memberof EvalSpecResponse
- */
- totalPoints: number;
- /**
- *
- * @type {any}
- * @memberof EvalSpecResponse
- */
- toolConfig: any | null;
- /**
- *
- * @type {number}
- * @memberof EvalSpecResponse
- */
- toolUsageWeight: number;
- /**
- *
- * @type {any}
- * @memberof EvalSpecResponse
- */
- consistencyRules: any | null;
- /**
- *
- * @type {any}
- * @memberof EvalSpecResponse
- */
- optimizableElements: any | null;
- /**
- *
- * @type {any}
- * @memberof EvalSpecResponse
- */
- fixedElements: any | null;
-}
-
-/**
- * Check if a given object implements the EvalSpecResponse interface.
- */
-export function instanceOfEvalSpecResponse(value: object): value is EvalSpecResponse {
- if (!('capabilityDescription' in value) || value['capabilityDescription'] === undefined) return false;
- if (!('sourcePath' in value) || value['sourcePath'] === undefined) return false;
- if (!('inputSchema' in value) || value['inputSchema'] === undefined) return false;
- if (!('outputFields' in value) || value['outputFields'] === undefined) return false;
- if (!('structureWeight' in value) || value['structureWeight'] === undefined) return false;
- if (!('totalPoints' in value) || value['totalPoints'] === undefined) return false;
- if (!('toolConfig' in value) || value['toolConfig'] === undefined) return false;
- if (!('toolUsageWeight' in value) || value['toolUsageWeight'] === undefined) return false;
- if (!('consistencyRules' in value) || value['consistencyRules'] === undefined) return false;
- if (!('optimizableElements' in value) || value['optimizableElements'] === undefined) return false;
- if (!('fixedElements' in value) || value['fixedElements'] === undefined) return false;
- return true;
-}
-
-export function EvalSpecResponseFromJSON(json: any): EvalSpecResponse {
- return EvalSpecResponseFromJSONTyped(json, false);
-}
-
-export function EvalSpecResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): EvalSpecResponse {
- if (json == null) {
- return json;
- }
- return {
-
- 'capabilityDescription': json['capability_description'],
- 'sourcePath': json['source_path'],
- 'inputSchema': json['input_schema'],
- 'outputFields': json['output_fields'],
- 'structureWeight': json['structure_weight'],
- 'totalPoints': json['total_points'],
- 'toolConfig': json['tool_config'],
- 'toolUsageWeight': json['tool_usage_weight'],
- 'consistencyRules': json['consistency_rules'],
- 'optimizableElements': json['optimizable_elements'],
- 'fixedElements': json['fixed_elements'],
- };
-}
-
-export function EvalSpecResponseToJSON(json: any): EvalSpecResponse {
- return EvalSpecResponseToJSONTyped(json, false);
-}
-
-export function EvalSpecResponseToJSONTyped(value?: EvalSpecResponse | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'capability_description': value['capabilityDescription'],
- 'source_path': value['sourcePath'],
- 'input_schema': value['inputSchema'],
- 'output_fields': value['outputFields'],
- 'structure_weight': value['structureWeight'],
- 'total_points': value['totalPoints'],
- 'tool_config': value['toolConfig'],
- 'tool_usage_weight': value['toolUsageWeight'],
- 'consistency_rules': value['consistencyRules'],
- 'optimizable_elements': value['optimizableElements'],
- 'fixed_elements': value['fixedElements'],
- };
-}
diff --git a/frontend/src/openapi/models/EvaluateIterationRequest.ts b/frontend/src/openapi/models/EvaluateIterationRequest.ts
deleted file mode 100644
index 7893447c..00000000
--- a/frontend/src/openapi/models/EvaluateIterationRequest.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-/**
- *
- * @export
- * @interface EvaluateIterationRequest
- */
-export interface EvaluateIterationRequest {
- /**
- *
- * @type {number}
- * @memberof EvaluateIterationRequest
- */
- order: number;
-}
-
-/**
- * Check if a given object implements the EvaluateIterationRequest interface.
- */
-export function instanceOfEvaluateIterationRequest(value: object): value is EvaluateIterationRequest {
- if (!('order' in value) || value['order'] === undefined) return false;
- return true;
-}
-
-export function EvaluateIterationRequestFromJSON(json: any): EvaluateIterationRequest {
- return EvaluateIterationRequestFromJSONTyped(json, false);
-}
-
-export function EvaluateIterationRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): EvaluateIterationRequest {
- if (json == null) {
- return json;
- }
- return {
-
- 'order': json['order'],
- };
-}
-
-export function EvaluateIterationRequestToJSON(json: any): EvaluateIterationRequest {
- return EvaluateIterationRequestToJSONTyped(json, false);
-}
-
-export function EvaluateIterationRequestToJSONTyped(value?: EvaluateIterationRequest | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'order': value['order'],
- };
-}
diff --git a/frontend/src/openapi/models/FeedbackAreaEnum.ts b/frontend/src/openapi/models/FeedbackAreaEnum.ts
index 0130ba9d..606c796f 100644
--- a/frontend/src/openapi/models/FeedbackAreaEnum.ts
+++ b/frontend/src/openapi/models/FeedbackAreaEnum.ts
@@ -18,7 +18,6 @@
* * `observability` - Observability
* * `datasets` - Datasets
* * `evaluation` - Evaluation
- * * `optimizer` - Optimiser
* * `training` - Training
* * `serving` - Serving
* * `billing` - Billing
@@ -30,7 +29,6 @@ export const FeedbackAreaEnum = {
observability: 'observability',
datasets: 'datasets',
evaluation: 'evaluation',
- optimizer: 'optimizer',
training: 'training',
serving: 'serving',
billing: 'billing',
diff --git a/frontend/src/openapi/models/ModeCd6Enum.ts b/frontend/src/openapi/models/ModeCd6Enum.ts
deleted file mode 100644
index bdce1bb3..00000000
--- a/frontend/src/openapi/models/ModeCd6Enum.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-
-/**
- * * `optimize` - Optimize
- * * `model_comparison` - Model Comparison
- * * `hybrid` - Harness + Models
- * @export
- */
-export const ModeCd6Enum = {
- optimize: 'optimize',
- model_comparison: 'model_comparison',
- hybrid: 'hybrid'
-} as const;
-export type ModeCd6Enum = typeof ModeCd6Enum[keyof typeof ModeCd6Enum];
-
-
-export function instanceOfModeCd6Enum(value: any): boolean {
- for (const key in ModeCd6Enum) {
- if (Object.prototype.hasOwnProperty.call(ModeCd6Enum, key)) {
- if (ModeCd6Enum[key as keyof typeof ModeCd6Enum] === value) {
- return true;
- }
- }
- }
- return false;
-}
-
-export function ModeCd6EnumFromJSON(json: any): ModeCd6Enum {
- return ModeCd6EnumFromJSONTyped(json, false);
-}
-
-export function ModeCd6EnumFromJSONTyped(json: any, ignoreDiscriminator: boolean): ModeCd6Enum {
- return json as ModeCd6Enum;
-}
-
-export function ModeCd6EnumToJSON(value?: ModeCd6Enum | null): any {
- return value as any;
-}
-
-export function ModeCd6EnumToJSONTyped(value: any, ignoreDiscriminator: boolean): ModeCd6Enum {
- return value as ModeCd6Enum;
-}
diff --git a/frontend/src/openapi/models/ModelDefaults.ts b/frontend/src/openapi/models/ModelDefaults.ts
index d5800718..5f9e7e5d 100644
--- a/frontend/src/openapi/models/ModelDefaults.ts
+++ b/frontend/src/openapi/models/ModelDefaults.ts
@@ -31,12 +31,6 @@ export interface ModelDefaults {
* @memberof ModelDefaults
*/
judgeModels: Array<string>;
- /**
- *
- * @type {Array<string>}
- * @memberof ModelDefaults
- */
- backtestModels: Array<string>;
}
/**
@@ -45,7 +39,6 @@ export interface ModelDefaults {
export function instanceOfModelDefaults(value: object): value is ModelDefaults {
if (!('judgeModel' in value) || value['judgeModel'] === undefined) return false;
if (!('judgeModels' in value) || value['judgeModels'] === undefined) return false;
- if (!('backtestModels' in value) || value['backtestModels'] === undefined) return false;
return true;
}
@@ -61,7 +54,6 @@ export function ModelDefaultsFromJSONTyped(json: any, ignoreDiscriminator: boole
'judgeModel': json['judge_model'],
'judgeModels': json['judge_models'],
- 'backtestModels': json['backtest_models'],
};
}
@@ -78,6 +70,5 @@ export function ModelDefaultsToJSONTyped(value?: ModelDefaults | null, ignoreDis
'judge_model': value['judgeModel'],
'judge_models': value['judgeModels'],
- 'backtest_models': value['backtestModels'],
};
}
diff --git a/frontend/src/openapi/models/OpenrouterKeySourceEnum.ts b/frontend/src/openapi/models/OpenrouterKeySourceEnum.ts
deleted file mode 100644
index e845751c..00000000
--- a/frontend/src/openapi/models/OpenrouterKeySourceEnum.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-
-/**
- * * `platform` - Overmind credits
- * * `local` - Local .env
- * @export
- */
-export const OpenrouterKeySourceEnum = {
- platform: 'platform',
- local: 'local'
-} as const;
-export type OpenrouterKeySourceEnum = typeof OpenrouterKeySourceEnum[keyof typeof OpenrouterKeySourceEnum];
-
-
-export function instanceOfOpenrouterKeySourceEnum(value: any): boolean {
- for (const key in OpenrouterKeySourceEnum) {
- if (Object.prototype.hasOwnProperty.call(OpenrouterKeySourceEnum, key)) {
- if (OpenrouterKeySourceEnum[key as keyof typeof OpenrouterKeySourceEnum] === value) {
- return true;
- }
- }
- }
- return false;
-}
-
-export function OpenrouterKeySourceEnumFromJSON(json: any): OpenrouterKeySourceEnum {
- return OpenrouterKeySourceEnumFromJSONTyped(json, false);
-}
-
-export function OpenrouterKeySourceEnumFromJSONTyped(json: any, ignoreDiscriminator: boolean): OpenrouterKeySourceEnum {
- return json as OpenrouterKeySourceEnum;
-}
-
-export function OpenrouterKeySourceEnumToJSON(value?: OpenrouterKeySourceEnum | null): any {
- return value as any;
-}
-
-export function OpenrouterKeySourceEnumToJSONTyped(value: any, ignoreDiscriminator: boolean): OpenrouterKeySourceEnum {
- return value as OpenrouterKeySourceEnum;
-}
diff --git a/frontend/src/openapi/models/OptimizerCandidate.ts b/frontend/src/openapi/models/OptimizerCandidate.ts
deleted file mode 100644
index 4d2b5bb8..00000000
--- a/frontend/src/openapi/models/OptimizerCandidate.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-import type { OptimizerCandidateStatusEnum } from './OptimizerCandidateStatusEnum';
-import {
- OptimizerCandidateStatusEnumFromJSON,
- OptimizerCandidateStatusEnumFromJSONTyped,
- OptimizerCandidateStatusEnumToJSON,
- OptimizerCandidateStatusEnumToJSONTyped,
-} from './OptimizerCandidateStatusEnum';
-
-/**
- *
- * @export
- * @interface OptimizerCandidate
- */
-export interface OptimizerCandidate {
- /**
- *
- * @type {string}
- * @memberof OptimizerCandidate
- */
- readonly id: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerCandidate
- */
- readonly experiment: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerCandidate
- */
- readonly iteration: string;
- /**
- *
- * @type {number}
- * @memberof OptimizerCandidate
- */
- readonly candidateIndex: number;
- /**
- *
- * @type {string}
- * @memberof OptimizerCandidate
- */
- readonly targetModel: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerCandidate
- */
- readonly modelName: string;
- /**
- *
- * @type {boolean}
- * @memberof OptimizerCandidate
- */
- readonly isBaseline: boolean;
- /**
- *
- * @type {number}
- * @memberof OptimizerCandidate
- */
- readonly score: number;
- /**
- *
- * @type {any}
- * @memberof OptimizerCandidate
- */
- readonly scores: any | null;
- /**
- *
- * @type {OptimizerCandidateStatusEnum}
- * @memberof OptimizerCandidate
- */
- readonly status: OptimizerCandidateStatusEnum;
- /**
- *
- * @type {string}
- * @memberof OptimizerCandidate
- */
- readonly codePath: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerCandidate
- */
- readonly evalRun: string | null;
- /**
- *
- * @type {Date}
- * @memberof OptimizerCandidate
- */
- readonly createdAt: Date;
-}
-
-
-
-/**
- * Check if a given object implements the OptimizerCandidate interface.
- */
-export function instanceOfOptimizerCandidate(value: object): value is OptimizerCandidate {
- if (!('id' in value) || value['id'] === undefined) return false;
- if (!('experiment' in value) || value['experiment'] === undefined) return false;
- if (!('iteration' in value) || value['iteration'] === undefined) return false;
- if (!('candidateIndex' in value) || value['candidateIndex'] === undefined) return false;
- if (!('targetModel' in value) || value['targetModel'] === undefined) return false;
- if (!('modelName' in value) || value['modelName'] === undefined) return false;
- if (!('isBaseline' in value) || value['isBaseline'] === undefined) return false;
- if (!('score' in value) || value['score'] === undefined) return false;
- if (!('scores' in value) || value['scores'] === undefined) return false;
- if (!('status' in value) || value['status'] === undefined) return false;
- if (!('codePath' in value) || value['codePath'] === undefined) return false;
- if (!('evalRun' in value) || value['evalRun'] === undefined) return false;
- if (!('createdAt' in value) || value['createdAt'] === undefined) return false;
- return true;
-}
-
-export function OptimizerCandidateFromJSON(json: any): OptimizerCandidate {
- return OptimizerCandidateFromJSONTyped(json, false);
-}
-
-export function OptimizerCandidateFromJSONTyped(json: any, ignoreDiscriminator: boolean): OptimizerCandidate {
- if (json == null) {
- return json;
- }
- return {
-
- 'id': json['id'],
- 'experiment': json['experiment'],
- 'iteration': json['iteration'],
- 'candidateIndex': json['candidate_index'],
- 'targetModel': json['target_model'],
- 'modelName': json['model_name'],
- 'isBaseline': json['is_baseline'],
- 'score': json['score'],
- 'scores': json['scores'],
- 'status': OptimizerCandidateStatusEnumFromJSON(json['status']),
- 'codePath': json['code_path'],
- 'evalRun': json['eval_run'],
- 'createdAt': (new Date(json['created_at'])),
- };
-}
-
-export function OptimizerCandidateToJSON(json: any): OptimizerCandidate {
- return OptimizerCandidateToJSONTyped(json, false);
-}
-
-export function OptimizerCandidateToJSONTyped(value?: Omit<OptimizerCandidate, 'id'|'experiment'|'iteration'|'candidate_index'|'target_model'|'model_name'|'is_baseline'|'score'|'scores'|'status'|'code_path'|'eval_run'|'created_at'> | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- };
-}
diff --git a/frontend/src/openapi/models/OptimizerCandidateStatusEnum.ts b/frontend/src/openapi/models/OptimizerCandidateStatusEnum.ts
deleted file mode 100644
index 18c06dc5..00000000
--- a/frontend/src/openapi/models/OptimizerCandidateStatusEnum.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-
-/**
- * * `pending` - Pending
- * * `running_commands` - Running Commands
- * * `commands_done` - Commands Done
- * * `evaluating` - Evaluating
- * * `evaluated` - Evaluated
- * * `failed` - Failed
- * @export
- */
-export const OptimizerCandidateStatusEnum = {
- pending: 'pending',
- running_commands: 'running_commands',
- commands_done: 'commands_done',
- evaluating: 'evaluating',
- evaluated: 'evaluated',
- failed: 'failed'
-} as const;
-export type OptimizerCandidateStatusEnum = typeof OptimizerCandidateStatusEnum[keyof typeof OptimizerCandidateStatusEnum];
-
-
-export function instanceOfOptimizerCandidateStatusEnum(value: any): boolean {
- for (const key in OptimizerCandidateStatusEnum) {
- if (Object.prototype.hasOwnProperty.call(OptimizerCandidateStatusEnum, key)) {
- if (OptimizerCandidateStatusEnum[key as keyof typeof OptimizerCandidateStatusEnum] === value) {
- return true;
- }
- }
- }
- return false;
-}
-
-export function OptimizerCandidateStatusEnumFromJSON(json: any): OptimizerCandidateStatusEnum {
- return OptimizerCandidateStatusEnumFromJSONTyped(json, false);
-}
-
-export function OptimizerCandidateStatusEnumFromJSONTyped(json: any, ignoreDiscriminator: boolean): OptimizerCandidateStatusEnum {
- return json as OptimizerCandidateStatusEnum;
-}
-
-export function OptimizerCandidateStatusEnumToJSON(value?: OptimizerCandidateStatusEnum | null): any {
- return value as any;
-}
-
-export function OptimizerCandidateStatusEnumToJSONTyped(value: any, ignoreDiscriminator: boolean): OptimizerCandidateStatusEnum {
- return value as OptimizerCandidateStatusEnum;
-}
diff --git a/frontend/src/openapi/models/OptimizerCommand.ts b/frontend/src/openapi/models/OptimizerCommand.ts
deleted file mode 100644
index f17d892d..00000000
--- a/frontend/src/openapi/models/OptimizerCommand.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-import type { OptimizerCommandStatusEnum } from './OptimizerCommandStatusEnum';
-import {
- OptimizerCommandStatusEnumFromJSON,
- OptimizerCommandStatusEnumFromJSONTyped,
- OptimizerCommandStatusEnumToJSON,
- OptimizerCommandStatusEnumToJSONTyped,
-} from './OptimizerCommandStatusEnum';
-
-/**
- *
- * @export
- * @interface OptimizerCommand
- */
-export interface OptimizerCommand {
- /**
- *
- * @type {string}
- * @memberof OptimizerCommand
- */
- readonly id: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerCommand
- */
- readonly experiment: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerCommand
- */
- readonly candidate: string | null;
- /**
- *
- * @type {string}
- * @memberof OptimizerCommand
- */
- readonly iteration: string | null;
- /**
- *
- * @type {number}
- * @memberof OptimizerCommand
- */
- readonly datapointIndex: number;
- /**
- *
- * @type {string}
- * @memberof OptimizerCommand
- */
- readonly command: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerCommand
- */
- readonly codePath: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerCommand
- */
- readonly output: string;
- /**
- *
- * @type {any}
- * @memberof OptimizerCommand
- */
- readonly result: any | null;
- /**
- *
- * @type {number}
- * @memberof OptimizerCommand
- */
- readonly score: number;
- /**
- *
- * @type {string}
- * @memberof OptimizerCommand
- */
- readonly traceType: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerCommand
- */
- readonly originalTraceId: string;
- /**
- *
- * @type {OptimizerCommandStatusEnum}
- * @memberof OptimizerCommand
- */
- readonly status: OptimizerCommandStatusEnum;
- /**
- *
- * @type {number}
- * @memberof OptimizerCommand
- */
- readonly timeout: number;
- /**
- *
- * @type {string}
- * @memberof OptimizerCommand
- */
- readonly error: string;
- /**
- *
- * @type {Date}
- * @memberof OptimizerCommand
- */
- readonly createdAt: Date;
-}
-
-
-
-/**
- * Check if a given object implements the OptimizerCommand interface.
- */
-export function instanceOfOptimizerCommand(value: object): value is OptimizerCommand {
- if (!('id' in value) || value['id'] === undefined) return false;
- if (!('experiment' in value) || value['experiment'] === undefined) return false;
- if (!('candidate' in value) || value['candidate'] === undefined) return false;
- if (!('iteration' in value) || value['iteration'] === undefined) return false;
- if (!('datapointIndex' in value) || value['datapointIndex'] === undefined) return false;
- if (!('command' in value) || value['command'] === undefined) return false;
- if (!('codePath' in value) || value['codePath'] === undefined) return false;
- if (!('output' in value) || value['output'] === undefined) return false;
- if (!('result' in value) || value['result'] === undefined) return false;
- if (!('score' in value) || value['score'] === undefined) return false;
- if (!('traceType' in value) || value['traceType'] === undefined) return false;
- if (!('originalTraceId' in value) || value['originalTraceId'] === undefined) return false;
- if (!('status' in value) || value['status'] === undefined) return false;
- if (!('timeout' in value) || value['timeout'] === undefined) return false;
- if (!('error' in value) || value['error'] === undefined) return false;
- if (!('createdAt' in value) || value['createdAt'] === undefined) return false;
- return true;
-}
-
-export function OptimizerCommandFromJSON(json: any): OptimizerCommand {
- return OptimizerCommandFromJSONTyped(json, false);
-}
-
-export function OptimizerCommandFromJSONTyped(json: any, ignoreDiscriminator: boolean): OptimizerCommand {
- if (json == null) {
- return json;
- }
- return {
-
- 'id': json['id'],
- 'experiment': json['experiment'],
- 'candidate': json['candidate'],
- 'iteration': json['iteration'],
- 'datapointIndex': json['datapoint_index'],
- 'command': json['command'],
- 'codePath': json['code_path'],
- 'output': json['output'],
- 'result': json['result'],
- 'score': json['score'],
- 'traceType': json['trace_type'],
- 'originalTraceId': json['original_trace_id'],
- 'status': OptimizerCommandStatusEnumFromJSON(json['status']),
- 'timeout': json['timeout'],
- 'error': json['error'],
- 'createdAt': (new Date(json['created_at'])),
- };
-}
-
-export function OptimizerCommandToJSON(json: any): OptimizerCommand {
- return OptimizerCommandToJSONTyped(json, false);
-}
-
-export function OptimizerCommandToJSONTyped(value?: Omit<OptimizerCommand, 'id'|'experiment'|'candidate'|'iteration'|'datapoint_index'|'command'|'code_path'|'output'|'result'|'score'|'trace_type'|'original_trace_id'|'status'|'timeout'|'error'|'created_at'> | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- };
-}
diff --git a/frontend/src/openapi/models/OptimizerCommandStatusEnum.ts b/frontend/src/openapi/models/OptimizerCommandStatusEnum.ts
deleted file mode 100644
index 1801d24a..00000000
--- a/frontend/src/openapi/models/OptimizerCommandStatusEnum.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-
-/**
- * * `pending` - Pending
- * * `running` - Running
- * * `ran` - Ran
- * * `passed` - Passed
- * * `evaluated` - Evaluated
- * * `failed` - Failed
- * @export
- */
-export const OptimizerCommandStatusEnum = {
- pending: 'pending',
- running: 'running',
- ran: 'ran',
- passed: 'passed',
- evaluated: 'evaluated',
- failed: 'failed'
-} as const;
-export type OptimizerCommandStatusEnum = typeof OptimizerCommandStatusEnum[keyof typeof OptimizerCommandStatusEnum];
-
-
-export function instanceOfOptimizerCommandStatusEnum(value: any): boolean {
- for (const key in OptimizerCommandStatusEnum) {
- if (Object.prototype.hasOwnProperty.call(OptimizerCommandStatusEnum, key)) {
- if (OptimizerCommandStatusEnum[key as keyof typeof OptimizerCommandStatusEnum] === value) {
- return true;
- }
- }
- }
- return false;
-}
-
-export function OptimizerCommandStatusEnumFromJSON(json: any): OptimizerCommandStatusEnum {
- return OptimizerCommandStatusEnumFromJSONTyped(json, false);
-}
-
-export function OptimizerCommandStatusEnumFromJSONTyped(json: any, ignoreDiscriminator: boolean): OptimizerCommandStatusEnum {
- return json as OptimizerCommandStatusEnum;
-}
-
-export function OptimizerCommandStatusEnumToJSON(value?: OptimizerCommandStatusEnum | null): any {
- return value as any;
-}
-
-export function OptimizerCommandStatusEnumToJSONTyped(value: any, ignoreDiscriminator: boolean): OptimizerCommandStatusEnum {
- return value as OptimizerCommandStatusEnum;
-}
diff --git a/frontend/src/openapi/models/OptimizerExperiment.ts b/frontend/src/openapi/models/OptimizerExperiment.ts
deleted file mode 100644
index 014f441e..00000000
--- a/frontend/src/openapi/models/OptimizerExperiment.ts
+++ /dev/null
@@ -1,304 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-import type { ModeCd6Enum } from './ModeCd6Enum';
-import {
- ModeCd6EnumFromJSON,
- ModeCd6EnumFromJSONTyped,
- ModeCd6EnumToJSON,
- ModeCd6EnumToJSONTyped,
-} from './ModeCd6Enum';
-import type { OptimizerExperimentStatusEnum } from './OptimizerExperimentStatusEnum';
-import {
- OptimizerExperimentStatusEnumFromJSON,
- OptimizerExperimentStatusEnumFromJSONTyped,
- OptimizerExperimentStatusEnumToJSON,
- OptimizerExperimentStatusEnumToJSONTyped,
-} from './OptimizerExperimentStatusEnum';
-import type { OpenrouterKeySourceEnum } from './OpenrouterKeySourceEnum';
-import {
- OpenrouterKeySourceEnumFromJSON,
- OpenrouterKeySourceEnumFromJSONTyped,
- OpenrouterKeySourceEnumToJSON,
- OpenrouterKeySourceEnumToJSONTyped,
-} from './OpenrouterKeySourceEnum';
-
-/**
- *
- * @export
- * @interface OptimizerExperiment
- */
-export interface OptimizerExperiment {
- /**
- *
- * @type {string}
- * @memberof OptimizerExperiment
- */
- readonly id: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperiment
- */
- readonly project: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperiment
- */
- readonly capability: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperiment
- */
- readonly capabilityName: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperiment
- */
- readonly datasetName: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperiment
- */
- readonly evalSetName: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperiment
- */
- readonly dataset: string | null;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperiment
- */
- readonly cell: string | null;
- /**
- *
- * @type {{ [key: string]: any; }}
- * @memberof OptimizerExperiment
- */
- readonly cellInfo: { [key: string]: any; } | null;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperiment
- */
- readonly evalSet: string | null;
- /**
- *
- * @type {number}
- * @memberof OptimizerExperiment
- */
- readonly triggeredBy: number | null;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperiment
- */
- readonly entrypoint: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperiment
- */
- readonly codeTrigger: string;
- /**
- *
- * @type {ModeCd6Enum}
- * @memberof OptimizerExperiment
- */
- readonly mode: ModeCd6Enum;
- /**
- *
- * @type {any}
- * @memberof OptimizerExperiment
- */
- readonly modelIds: any | null;
- /**
- *
- * @type {OpenrouterKeySourceEnum}
- * @memberof OptimizerExperiment
- */
- readonly openrouterKeySource: OpenrouterKeySourceEnum;
- /**
- *
- * @type {OptimizerExperimentStatusEnum}
- * @memberof OptimizerExperiment
- */
- readonly status: OptimizerExperimentStatusEnum;
- /**
- *
- * @type {number}
- * @memberof OptimizerExperiment
- */
- readonly currentIteration: number;
- /**
- *
- * @type {number}
- * @memberof OptimizerExperiment
- */
- readonly numIterations: number;
- /**
- *
- * @type {number}
- * @memberof OptimizerExperiment
- */
- readonly numCandidatesPerIteration: number;
- /**
- *
- * @type {number}
- * @memberof OptimizerExperiment
- */
- readonly maxIterationsWithoutImprovement: number;
- /**
- *
- * @type {number}
- * @memberof OptimizerExperiment
- */
- readonly stalledIterations: number;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperiment
- */
- readonly commandTemplate: string;
- /**
- *
- * @type {any}
- * @memberof OptimizerExperiment
- */
- readonly scores: any | null;
- /**
- *
- * @type {any}
- * @memberof OptimizerExperiment
- */
- readonly state: any | null;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperiment
- */
- readonly failureReason: string;
- /**
- *
- * @type {Date}
- * @memberof OptimizerExperiment
- */
- readonly createdAt: Date;
- /**
- *
- * @type {Date}
- * @memberof OptimizerExperiment
- */
- readonly updatedAt: Date;
-}
-
-
-
-/**
- * Check if a given object implements the OptimizerExperiment interface.
- */
-export function instanceOfOptimizerExperiment(value: object): value is OptimizerExperiment {
- if (!('id' in value) || value['id'] === undefined) return false;
- if (!('project' in value) || value['project'] === undefined) return false;
- if (!('capability' in value) || value['capability'] === undefined) return false;
- if (!('capabilityName' in value) || value['capabilityName'] === undefined) return false;
- if (!('datasetName' in value) || value['datasetName'] === undefined) return false;
- if (!('evalSetName' in value) || value['evalSetName'] === undefined) return false;
- if (!('dataset' in value) || value['dataset'] === undefined) return false;
- if (!('cell' in value) || value['cell'] === undefined) return false;
- if (!('cellInfo' in value) || value['cellInfo'] === undefined) return false;
- if (!('evalSet' in value) || value['evalSet'] === undefined) return false;
- if (!('triggeredBy' in value) || value['triggeredBy'] === undefined) return false;
- if (!('entrypoint' in value) || value['entrypoint'] === undefined) return false;
- if (!('codeTrigger' in value) || value['codeTrigger'] === undefined) return false;
- if (!('mode' in value) || value['mode'] === undefined) return false;
- if (!('modelIds' in value) || value['modelIds'] === undefined) return false;
- if (!('openrouterKeySource' in value) || value['openrouterKeySource'] === undefined) return false;
- if (!('status' in value) || value['status'] === undefined) return false;
- if (!('currentIteration' in value) || value['currentIteration'] === undefined) return false;
- if (!('numIterations' in value) || value['numIterations'] === undefined) return false;
- if (!('numCandidatesPerIteration' in value) || value['numCandidatesPerIteration'] === undefined) return false;
- if (!('maxIterationsWithoutImprovement' in value) || value['maxIterationsWithoutImprovement'] === undefined) return false;
- if (!('stalledIterations' in value) || value['stalledIterations'] === undefined) return false;
- if (!('commandTemplate' in value) || value['commandTemplate'] === undefined) return false;
- if (!('scores' in value) || value['scores'] === undefined) return false;
- if (!('state' in value) || value['state'] === undefined) return false;
- if (!('failureReason' in value) || value['failureReason'] === undefined) return false;
- if (!('createdAt' in value) || value['createdAt'] === undefined) return false;
- if (!('updatedAt' in value) || value['updatedAt'] === undefined) return false;
- return true;
-}
-
-export function OptimizerExperimentFromJSON(json: any): OptimizerExperiment {
- return OptimizerExperimentFromJSONTyped(json, false);
-}
-
-export function OptimizerExperimentFromJSONTyped(json: any, ignoreDiscriminator: boolean): OptimizerExperiment {
- if (json == null) {
- return json;
- }
- return {
-
- 'id': json['id'],
- 'project': json['project'],
- 'capability': json['capability'],
- 'capabilityName': json['capability_name'],
- 'datasetName': json['dataset_name'],
- 'evalSetName': json['eval_set_name'],
- 'dataset': json['dataset'],
- 'cell': json['cell'],
- 'cellInfo': json['cell_info'],
- 'evalSet': json['eval_set'],
- 'triggeredBy': json['triggered_by'],
- 'entrypoint': json['entrypoint'],
- 'codeTrigger': json['code_trigger'],
- 'mode': ModeCd6EnumFromJSON(json['mode']),
- 'modelIds': json['model_ids'],
- 'openrouterKeySource': OpenrouterKeySourceEnumFromJSON(json['openrouter_key_source']),
- 'status': OptimizerExperimentStatusEnumFromJSON(json['status']),
- 'currentIteration': json['current_iteration'],
- 'numIterations': json['num_iterations'],
- 'numCandidatesPerIteration': json['num_candidates_per_iteration'],
- 'maxIterationsWithoutImprovement': json['max_iterations_without_improvement'],
- 'stalledIterations': json['stalled_iterations'],
- 'commandTemplate': json['command_template'],
- 'scores': json['scores'],
- 'state': json['state'],
- 'failureReason': json['failure_reason'],
- 'createdAt': (new Date(json['created_at'])),
- 'updatedAt': (new Date(json['updated_at'])),
- };
-}
-
-export function OptimizerExperimentToJSON(json: any): OptimizerExperiment {
- return OptimizerExperimentToJSONTyped(json, false);
-}
-
-export function OptimizerExperimentToJSONTyped(value?: Omit<OptimizerExperiment, 'id'|'project'|'capability'|'capability_name'|'dataset_name'|'eval_set_name'|'dataset'|'cell'|'cell_info'|'eval_set'|'triggered_by'|'entrypoint'|'code_trigger'|'mode'|'model_ids'|'openrouter_key_source'|'status'|'current_iteration'|'num_iterations'|'num_candidates_per_iteration'|'max_iterations_without_improvement'|'stalled_iterations'|'command_template'|'scores'|'state'|'failure_reason'|'created_at'|'updated_at'> | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- };
-}
diff --git a/frontend/src/openapi/models/OptimizerExperimentCreateRequest.ts b/frontend/src/openapi/models/OptimizerExperimentCreateRequest.ts
deleted file mode 100644
index b81da5d5..00000000
--- a/frontend/src/openapi/models/OptimizerExperimentCreateRequest.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-import type { ModeCd6Enum } from './ModeCd6Enum';
-import {
- ModeCd6EnumFromJSON,
- ModeCd6EnumFromJSONTyped,
- ModeCd6EnumToJSON,
- ModeCd6EnumToJSONTyped,
-} from './ModeCd6Enum';
-import type { OpenrouterKeySourceEnum } from './OpenrouterKeySourceEnum';
-import {
- OpenrouterKeySourceEnumFromJSON,
- OpenrouterKeySourceEnumFromJSONTyped,
- OpenrouterKeySourceEnumToJSON,
- OpenrouterKeySourceEnumToJSONTyped,
-} from './OpenrouterKeySourceEnum';
-
-/**
- * ``perform_create`` fills ``eval_set``/``entrypoint`` from the capability;
- * ``dataset`` must be supplied.
- * @export
- * @interface OptimizerExperimentCreateRequest
- */
-export interface OptimizerExperimentCreateRequest {
- /**
- *
- * @type {string}
- * @memberof OptimizerExperimentCreateRequest
- */
- capability: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperimentCreateRequest
- */
- dataset?: string | null;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperimentCreateRequest
- */
- cell?: string | null;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperimentCreateRequest
- */
- evalSet?: string | null;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperimentCreateRequest
- */
- entrypoint?: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerExperimentCreateRequest
- */
- codeTrigger?: string;
- /**
- *
- * @type {ModeCd6Enum}
- * @memberof OptimizerExperimentCreateRequest
- */
- mode?: ModeCd6Enum;
- /**
- *
- * @type {any}
- * @memberof OptimizerExperimentCreateRequest
- */
- modelIds?: any | null;
- /**
- *
- * @type {OpenrouterKeySourceEnum}
- * @memberof OptimizerExperimentCreateRequest
- */
- openrouterKeySource?: OpenrouterKeySourceEnum;
- /**
- *
- * @type {number}
- * @memberof OptimizerExperimentCreateRequest
- */
- numIterations?: number;
- /**
- *
- * @type {number}
- * @memberof OptimizerExperimentCreateRequest
- */
- numCandidatesPerIteration?: number;
- /**
- *
- * @type {number}
- * @memberof OptimizerExperimentCreateRequest
- */
- maxIterationsWithoutImprovement?: number;
-}
-
-
-
-/**
- * Check if a given object implements the OptimizerExperimentCreateRequest interface.
- */
-export function instanceOfOptimizerExperimentCreateRequest(value: object): value is OptimizerExperimentCreateRequest {
- if (!('capability' in value) || value['capability'] === undefined) return false;
- return true;
-}
-
-export function OptimizerExperimentCreateRequestFromJSON(json: any): OptimizerExperimentCreateRequest {
- return OptimizerExperimentCreateRequestFromJSONTyped(json, false);
-}
-
-export function OptimizerExperimentCreateRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): OptimizerExperimentCreateRequest {
- if (json == null) {
- return json;
- }
- return {
-
- 'capability': json['capability'],
- 'dataset': json['dataset'] == null ? undefined : json['dataset'],
- 'cell': json['cell'] == null ? undefined : json['cell'],
- 'evalSet': json['eval_set'] == null ? undefined : json['eval_set'],
- 'entrypoint': json['entrypoint'] == null ? undefined : json['entrypoint'],
- 'codeTrigger': json['code_trigger'] == null ? undefined : json['code_trigger'],
- 'mode': json['mode'] == null ? undefined : ModeCd6EnumFromJSON(json['mode']),
- 'modelIds': json['model_ids'] == null ? undefined : json['model_ids'],
- 'openrouterKeySource': json['openrouter_key_source'] == null ? undefined : OpenrouterKeySourceEnumFromJSON(json['openrouter_key_source']),
- 'numIterations': json['num_iterations'] == null ? undefined : json['num_iterations'],
- 'numCandidatesPerIteration': json['num_candidates_per_iteration'] == null ? undefined : json['num_candidates_per_iteration'],
- 'maxIterationsWithoutImprovement': json['max_iterations_without_improvement'] == null ? undefined : json['max_iterations_without_improvement'],
- };
-}
-
-export function OptimizerExperimentCreateRequestToJSON(json: any): OptimizerExperimentCreateRequest {
- return OptimizerExperimentCreateRequestToJSONTyped(json, false);
-}
-
-export function OptimizerExperimentCreateRequestToJSONTyped(value?: OptimizerExperimentCreateRequest | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'capability': value['capability'],
- 'dataset': value['dataset'],
- 'cell': value['cell'],
- 'eval_set': value['evalSet'],
- 'entrypoint': value['entrypoint'],
- 'code_trigger': value['codeTrigger'],
- 'mode': ModeCd6EnumToJSON(value['mode']),
- 'model_ids': value['modelIds'],
- 'openrouter_key_source': OpenrouterKeySourceEnumToJSON(value['openrouterKeySource']),
- 'num_iterations': value['numIterations'],
- 'num_candidates_per_iteration': value['numCandidatesPerIteration'],
- 'max_iterations_without_improvement': value['maxIterationsWithoutImprovement'],
- };
-}
diff --git a/frontend/src/openapi/models/OptimizerExperimentStatusEnum.ts b/frontend/src/openapi/models/OptimizerExperimentStatusEnum.ts
deleted file mode 100644
index fba73b9e..00000000
--- a/frontend/src/openapi/models/OptimizerExperimentStatusEnum.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-
-/**
- * * `scheduled` - Scheduled
- * * `baseline` - Baseline
- * * `evaluating_baseline_outputs` - Evaluating Baseline Outputs
- * * `evaluated_baseline_outputs` - Evaluated Baseline Outputs
- * * `iterating` - Iterating
- * * `evaluating_candidate_outputs` - Evaluating Candidate Outputs
- * * `evaluated_candidate_outputs` - Evaluated Candidate Outputs
- * * `completed` - Completed
- * * `failed` - Failed
- * * `cancelled` - Cancelled
- * * `paused` - Paused
- * @export
- */
-export const OptimizerExperimentStatusEnum = {
- scheduled: 'scheduled',
- baseline: 'baseline',
- evaluating_baseline_outputs: 'evaluating_baseline_outputs',
- evaluated_baseline_outputs: 'evaluated_baseline_outputs',
- iterating: 'iterating',
- evaluating_candidate_outputs: 'evaluating_candidate_outputs',
- evaluated_candidate_outputs: 'evaluated_candidate_outputs',
- completed: 'completed',
- failed: 'failed',
- cancelled: 'cancelled',
- paused: 'paused'
-} as const;
-export type OptimizerExperimentStatusEnum = typeof OptimizerExperimentStatusEnum[keyof typeof OptimizerExperimentStatusEnum];
-
-
-export function instanceOfOptimizerExperimentStatusEnum(value: any): boolean {
- for (const key in OptimizerExperimentStatusEnum) {
- if (Object.prototype.hasOwnProperty.call(OptimizerExperimentStatusEnum, key)) {
- if (OptimizerExperimentStatusEnum[key as keyof typeof OptimizerExperimentStatusEnum] === value) {
- return true;
- }
- }
- }
- return false;
-}
-
-export function OptimizerExperimentStatusEnumFromJSON(json: any): OptimizerExperimentStatusEnum {
- return OptimizerExperimentStatusEnumFromJSONTyped(json, false);
-}
-
-export function OptimizerExperimentStatusEnumFromJSONTyped(json: any, ignoreDiscriminator: boolean): OptimizerExperimentStatusEnum {
- return json as OptimizerExperimentStatusEnum;
-}
-
-export function OptimizerExperimentStatusEnumToJSON(value?: OptimizerExperimentStatusEnum | null): any {
- return value as any;
-}
-
-export function OptimizerExperimentStatusEnumToJSONTyped(value: any, ignoreDiscriminator: boolean): OptimizerExperimentStatusEnum {
- return value as OptimizerExperimentStatusEnum;
-}
diff --git a/frontend/src/openapi/models/OptimizerExperimentsResultsCreate200Response.ts b/frontend/src/openapi/models/OptimizerExperimentsResultsCreate200Response.ts
deleted file mode 100644
index 7ee7eea6..00000000
--- a/frontend/src/openapi/models/OptimizerExperimentsResultsCreate200Response.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-/**
- *
- * @export
- * @interface OptimizerExperimentsResultsCreate200Response
- */
-export interface OptimizerExperimentsResultsCreate200Response {
- /**
- *
- * @type {number}
- * @memberof OptimizerExperimentsResultsCreate200Response
- */
- upserted?: number;
-}
-
-/**
- * Check if a given object implements the OptimizerExperimentsResultsCreate200Response interface.
- */
-export function instanceOfOptimizerExperimentsResultsCreate200Response(value: object): value is OptimizerExperimentsResultsCreate200Response {
- return true;
-}
-
-export function OptimizerExperimentsResultsCreate200ResponseFromJSON(json: any): OptimizerExperimentsResultsCreate200Response {
- return OptimizerExperimentsResultsCreate200ResponseFromJSONTyped(json, false);
-}
-
-export function OptimizerExperimentsResultsCreate200ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): OptimizerExperimentsResultsCreate200Response {
- if (json == null) {
- return json;
- }
- return {
-
- 'upserted': json['upserted'] == null ? undefined : json['upserted'],
- };
-}
-
-export function OptimizerExperimentsResultsCreate200ResponseToJSON(json: any): OptimizerExperimentsResultsCreate200Response {
- return OptimizerExperimentsResultsCreate200ResponseToJSONTyped(json, false);
-}
-
-export function OptimizerExperimentsResultsCreate200ResponseToJSONTyped(value?: OptimizerExperimentsResultsCreate200Response | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'upserted': value['upserted'],
- };
-}
diff --git a/frontend/src/openapi/models/OptimizerIteration.ts b/frontend/src/openapi/models/OptimizerIteration.ts
deleted file mode 100644
index 3fb85950..00000000
--- a/frontend/src/openapi/models/OptimizerIteration.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-import type { OptimizerCandidate } from './OptimizerCandidate';
-import {
- OptimizerCandidateFromJSON,
- OptimizerCandidateFromJSONTyped,
- OptimizerCandidateToJSON,
- OptimizerCandidateToJSONTyped,
-} from './OptimizerCandidate';
-import type { OptimizerIterationStatusEnum } from './OptimizerIterationStatusEnum';
-import {
- OptimizerIterationStatusEnumFromJSON,
- OptimizerIterationStatusEnumFromJSONTyped,
- OptimizerIterationStatusEnumToJSON,
- OptimizerIterationStatusEnumToJSONTyped,
-} from './OptimizerIterationStatusEnum';
-
-/**
- *
- * @export
- * @interface OptimizerIteration
- */
-export interface OptimizerIteration {
- /**
- *
- * @type {string}
- * @memberof OptimizerIteration
- */
- readonly id: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerIteration
- */
- readonly experiment: string;
- /**
- *
- * @type {number}
- * @memberof OptimizerIteration
- */
- readonly order: number;
- /**
- *
- * @type {string}
- * @memberof OptimizerIteration
- */
- readonly name: string;
- /**
- *
- * @type {OptimizerIterationStatusEnum}
- * @memberof OptimizerIteration
- */
- readonly status: OptimizerIterationStatusEnum;
- /**
- *
- * @type {any}
- * @memberof OptimizerIteration
- */
- readonly scores: any | null;
- /**
- *
- * @type {string}
- * @memberof OptimizerIteration
- */
- readonly patch: string;
- /**
- *
- * @type {string}
- * @memberof OptimizerIteration
- */
- readonly evalRun: string | null;
- /**
- *
- * @type {Array<OptimizerCandidate>}
- * @memberof OptimizerIteration
- */
- readonly candidates: Array<OptimizerCandidate>;
- /**
- *
- * @type {Date}
- * @memberof OptimizerIteration
- */
- readonly createdAt: Date;
-}
-
-
-
-/**
- * Check if a given object implements the OptimizerIteration interface.
- */
-export function instanceOfOptimizerIteration(value: object): value is OptimizerIteration {
- if (!('id' in value) || value['id'] === undefined) return false;
- if (!('experiment' in value) || value['experiment'] === undefined) return false;
- if (!('order' in value) || value['order'] === undefined) return false;
- if (!('name' in value) || value['name'] === undefined) return false;
- if (!('status' in value) || value['status'] === undefined) return false;
- if (!('scores' in value) || value['scores'] === undefined) return false;
- if (!('patch' in value) || value['patch'] === undefined) return false;
- if (!('evalRun' in value) || value['evalRun'] === undefined) return false;
- if (!('candidates' in value) || value['candidates'] === undefined) return false;
- if (!('createdAt' in value) || value['createdAt'] === undefined) return false;
- return true;
-}
-
-export function OptimizerIterationFromJSON(json: any): OptimizerIteration {
- return OptimizerIterationFromJSONTyped(json, false);
-}
-
-export function OptimizerIterationFromJSONTyped(json: any, ignoreDiscriminator: boolean): OptimizerIteration {
- if (json == null) {
- return json;
- }
- return {
-
- 'id': json['id'],
- 'experiment': json['experiment'],
- 'order': json['order'],
- 'name': json['name'],
- 'status': OptimizerIterationStatusEnumFromJSON(json['status']),
- 'scores': json['scores'],
- 'patch': json['patch'],
- 'evalRun': json['eval_run'],
- 'candidates': ((json['candidates'] as Array<any>).map(OptimizerCandidateFromJSON)),
- 'createdAt': (new Date(json['created_at'])),
- };
-}
-
-export function OptimizerIterationToJSON(json: any): OptimizerIteration {
- return OptimizerIterationToJSONTyped(json, false);
-}
-
-export function OptimizerIterationToJSONTyped(value?: Omit<OptimizerIteration, 'id'|'experiment'|'order'|'name'|'status'|'scores'|'patch'|'eval_run'|'candidates'|'created_at'> | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- };
-}
diff --git a/frontend/src/openapi/models/OptimizerIterationStatusEnum.ts b/frontend/src/openapi/models/OptimizerIterationStatusEnum.ts
deleted file mode 100644
index b3a2a1ac..00000000
--- a/frontend/src/openapi/models/OptimizerIterationStatusEnum.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-
-/**
- * * `pending` - Pending
- * * `generating_candidates` - Generating Candidates
- * * `generated_candidates` - Generated Candidates
- * * `running_commands` - Running Commands
- * * `evaluating` - Evaluating
- * * `evaluated` - Evaluated
- * * `completed` - Completed
- * * `failed` - Failed
- * @export
- */
-export const OptimizerIterationStatusEnum = {
- pending: 'pending',
- generating_candidates: 'generating_candidates',
- generated_candidates: 'generated_candidates',
- running_commands: 'running_commands',
- evaluating: 'evaluating',
- evaluated: 'evaluated',
- completed: 'completed',
- failed: 'failed'
-} as const;
-export type OptimizerIterationStatusEnum = typeof OptimizerIterationStatusEnum[keyof typeof OptimizerIterationStatusEnum];
-
-
-export function instanceOfOptimizerIterationStatusEnum(value: any): boolean {
- for (const key in OptimizerIterationStatusEnum) {
- if (Object.prototype.hasOwnProperty.call(OptimizerIterationStatusEnum, key)) {
- if (OptimizerIterationStatusEnum[key as keyof typeof OptimizerIterationStatusEnum] === value) {
- return true;
- }
- }
- }
- return false;
-}
-
-export function OptimizerIterationStatusEnumFromJSON(json: any): OptimizerIterationStatusEnum {
- return OptimizerIterationStatusEnumFromJSONTyped(json, false);
-}
-
-export function OptimizerIterationStatusEnumFromJSONTyped(json: any, ignoreDiscriminator: boolean): OptimizerIterationStatusEnum {
- return json as OptimizerIterationStatusEnum;
-}
-
-export function OptimizerIterationStatusEnumToJSON(value?: OptimizerIterationStatusEnum | null): any {
- return value as any;
-}
-
-export function OptimizerIterationStatusEnumToJSONTyped(value: any, ignoreDiscriminator: boolean): OptimizerIterationStatusEnum {
- return value as OptimizerIterationStatusEnum;
-}
diff --git a/frontend/src/openapi/models/PaginatedOptimizerCandidateList.ts b/frontend/src/openapi/models/PaginatedOptimizerCandidateList.ts
deleted file mode 100644
index 58f5d72d..00000000
--- a/frontend/src/openapi/models/PaginatedOptimizerCandidateList.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-import type { OptimizerCandidate } from './OptimizerCandidate';
-import {
- OptimizerCandidateFromJSON,
- OptimizerCandidateFromJSONTyped,
- OptimizerCandidateToJSON,
- OptimizerCandidateToJSONTyped,
-} from './OptimizerCandidate';
-
-/**
- *
- * @export
- * @interface PaginatedOptimizerCandidateList
- */
-export interface PaginatedOptimizerCandidateList {
- /**
- *
- * @type {number}
- * @memberof PaginatedOptimizerCandidateList
- */
- count: number;
- /**
- *
- * @type {string}
- * @memberof PaginatedOptimizerCandidateList
- */
- next?: string | null;
- /**
- *
- * @type {string}
- * @memberof PaginatedOptimizerCandidateList
- */
- previous?: string | null;
- /**
- *
- * @type {Array<OptimizerCandidate>}
- * @memberof PaginatedOptimizerCandidateList
- */
- results: Array<OptimizerCandidate>;
-}
-
-/**
- * Check if a given object implements the PaginatedOptimizerCandidateList interface.
- */
-export function instanceOfPaginatedOptimizerCandidateList(value: object): value is PaginatedOptimizerCandidateList {
- if (!('count' in value) || value['count'] === undefined) return false;
- if (!('results' in value) || value['results'] === undefined) return false;
- return true;
-}
-
-export function PaginatedOptimizerCandidateListFromJSON(json: any): PaginatedOptimizerCandidateList {
- return PaginatedOptimizerCandidateListFromJSONTyped(json, false);
-}
-
-export function PaginatedOptimizerCandidateListFromJSONTyped(json: any, ignoreDiscriminator: boolean): PaginatedOptimizerCandidateList {
- if (json == null) {
- return json;
- }
- return {
-
- 'count': json['count'],
- 'next': json['next'] == null ? undefined : json['next'],
- 'previous': json['previous'] == null ? undefined : json['previous'],
- 'results': ((json['results'] as Array<any>).map(OptimizerCandidateFromJSON)),
- };
-}
-
-export function PaginatedOptimizerCandidateListToJSON(json: any): PaginatedOptimizerCandidateList {
- return PaginatedOptimizerCandidateListToJSONTyped(json, false);
-}
-
-export function PaginatedOptimizerCandidateListToJSONTyped(value?: PaginatedOptimizerCandidateList | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'count': value['count'],
- 'next': value['next'],
- 'previous': value['previous'],
- 'results': ((value['results'] as Array<any>).map(OptimizerCandidateToJSON)),
- };
-}
diff --git a/frontend/src/openapi/models/PaginatedOptimizerCommandList.ts b/frontend/src/openapi/models/PaginatedOptimizerCommandList.ts
deleted file mode 100644
index cda044c8..00000000
--- a/frontend/src/openapi/models/PaginatedOptimizerCommandList.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-import type { OptimizerCommand } from './OptimizerCommand';
-import {
- OptimizerCommandFromJSON,
- OptimizerCommandFromJSONTyped,
- OptimizerCommandToJSON,
- OptimizerCommandToJSONTyped,
-} from './OptimizerCommand';
-
-/**
- *
- * @export
- * @interface PaginatedOptimizerCommandList
- */
-export interface PaginatedOptimizerCommandList {
- /**
- *
- * @type {number}
- * @memberof PaginatedOptimizerCommandList
- */
- count: number;
- /**
- *
- * @type {string}
- * @memberof PaginatedOptimizerCommandList
- */
- next?: string | null;
- /**
- *
- * @type {string}
- * @memberof PaginatedOptimizerCommandList
- */
- previous?: string | null;
- /**
- *
- * @type {Array<OptimizerCommand>}
- * @memberof PaginatedOptimizerCommandList
- */
- results: Array<OptimizerCommand>;
-}
-
-/**
- * Check if a given object implements the PaginatedOptimizerCommandList interface.
- */
-export function instanceOfPaginatedOptimizerCommandList(value: object): value is PaginatedOptimizerCommandList {
- if (!('count' in value) || value['count'] === undefined) return false;
- if (!('results' in value) || value['results'] === undefined) return false;
- return true;
-}
-
-export function PaginatedOptimizerCommandListFromJSON(json: any): PaginatedOptimizerCommandList {
- return PaginatedOptimizerCommandListFromJSONTyped(json, false);
-}
-
-export function PaginatedOptimizerCommandListFromJSONTyped(json: any, ignoreDiscriminator: boolean): PaginatedOptimizerCommandList {
- if (json == null) {
- return json;
- }
- return {
-
- 'count': json['count'],
- 'next': json['next'] == null ? undefined : json['next'],
- 'previous': json['previous'] == null ? undefined : json['previous'],
- 'results': ((json['results'] as Array<any>).map(OptimizerCommandFromJSON)),
- };
-}
-
-export function PaginatedOptimizerCommandListToJSON(json: any): PaginatedOptimizerCommandList {
- return PaginatedOptimizerCommandListToJSONTyped(json, false);
-}
-
-export function PaginatedOptimizerCommandListToJSONTyped(value?: PaginatedOptimizerCommandList | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'count': value['count'],
- 'next': value['next'],
- 'previous': value['previous'],
- 'results': ((value['results'] as Array<any>).map(OptimizerCommandToJSON)),
- };
-}
diff --git a/frontend/src/openapi/models/PaginatedOptimizerExperimentList.ts b/frontend/src/openapi/models/PaginatedOptimizerExperimentList.ts
deleted file mode 100644
index cfac9886..00000000
--- a/frontend/src/openapi/models/PaginatedOptimizerExperimentList.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-import type { OptimizerExperiment } from './OptimizerExperiment';
-import {
- OptimizerExperimentFromJSON,
- OptimizerExperimentFromJSONTyped,
- OptimizerExperimentToJSON,
- OptimizerExperimentToJSONTyped,
-} from './OptimizerExperiment';
-
-/**
- *
- * @export
- * @interface PaginatedOptimizerExperimentList
- */
-export interface PaginatedOptimizerExperimentList {
- /**
- *
- * @type {number}
- * @memberof PaginatedOptimizerExperimentList
- */
- count: number;
- /**
- *
- * @type {string}
- * @memberof PaginatedOptimizerExperimentList
- */
- next?: string | null;
- /**
- *
- * @type {string}
- * @memberof PaginatedOptimizerExperimentList
- */
- previous?: string | null;
- /**
- *
- * @type {Array<OptimizerExperiment>}
- * @memberof PaginatedOptimizerExperimentList
- */
- results: Array<OptimizerExperiment>;
-}
-
-/**
- * Check if a given object implements the PaginatedOptimizerExperimentList interface.
- */
-export function instanceOfPaginatedOptimizerExperimentList(value: object): value is PaginatedOptimizerExperimentList {
- if (!('count' in value) || value['count'] === undefined) return false;
- if (!('results' in value) || value['results'] === undefined) return false;
- return true;
-}
-
-export function PaginatedOptimizerExperimentListFromJSON(json: any): PaginatedOptimizerExperimentList {
- return PaginatedOptimizerExperimentListFromJSONTyped(json, false);
-}
-
-export function PaginatedOptimizerExperimentListFromJSONTyped(json: any, ignoreDiscriminator: boolean): PaginatedOptimizerExperimentList {
- if (json == null) {
- return json;
- }
- return {
-
- 'count': json['count'],
- 'next': json['next'] == null ? undefined : json['next'],
- 'previous': json['previous'] == null ? undefined : json['previous'],
- 'results': ((json['results'] as Array<any>).map(OptimizerExperimentFromJSON)),
- };
-}
-
-export function PaginatedOptimizerExperimentListToJSON(json: any): PaginatedOptimizerExperimentList {
- return PaginatedOptimizerExperimentListToJSONTyped(json, false);
-}
-
-export function PaginatedOptimizerExperimentListToJSONTyped(value?: PaginatedOptimizerExperimentList | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'count': value['count'],
- 'next': value['next'],
- 'previous': value['previous'],
- 'results': ((value['results'] as Array<any>).map(OptimizerExperimentToJSON)),
- };
-}
diff --git a/frontend/src/openapi/models/PaginatedOptimizerIterationList.ts b/frontend/src/openapi/models/PaginatedOptimizerIterationList.ts
deleted file mode 100644
index 3d681c03..00000000
--- a/frontend/src/openapi/models/PaginatedOptimizerIterationList.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-import type { OptimizerIteration } from './OptimizerIteration';
-import {
- OptimizerIterationFromJSON,
- OptimizerIterationFromJSONTyped,
- OptimizerIterationToJSON,
- OptimizerIterationToJSONTyped,
-} from './OptimizerIteration';
-
-/**
- *
- * @export
- * @interface PaginatedOptimizerIterationList
- */
-export interface PaginatedOptimizerIterationList {
- /**
- *
- * @type {number}
- * @memberof PaginatedOptimizerIterationList
- */
- count: number;
- /**
- *
- * @type {string}
- * @memberof PaginatedOptimizerIterationList
- */
- next?: string | null;
- /**
- *
- * @type {string}
- * @memberof PaginatedOptimizerIterationList
- */
- previous?: string | null;
- /**
- *
- * @type {Array<OptimizerIteration>}
- * @memberof PaginatedOptimizerIterationList
- */
- results: Array<OptimizerIteration>;
-}
-
-/**
- * Check if a given object implements the PaginatedOptimizerIterationList interface.
- */
-export function instanceOfPaginatedOptimizerIterationList(value: object): value is PaginatedOptimizerIterationList {
- if (!('count' in value) || value['count'] === undefined) return false;
- if (!('results' in value) || value['results'] === undefined) return false;
- return true;
-}
-
-export function PaginatedOptimizerIterationListFromJSON(json: any): PaginatedOptimizerIterationList {
- return PaginatedOptimizerIterationListFromJSONTyped(json, false);
-}
-
-export function PaginatedOptimizerIterationListFromJSONTyped(json: any, ignoreDiscriminator: boolean): PaginatedOptimizerIterationList {
- if (json == null) {
- return json;
- }
- return {
-
- 'count': json['count'],
- 'next': json['next'] == null ? undefined : json['next'],
- 'previous': json['previous'] == null ? undefined : json['previous'],
- 'results': ((json['results'] as Array<any>).map(OptimizerIterationFromJSON)),
- };
-}
-
-export function PaginatedOptimizerIterationListToJSON(json: any): PaginatedOptimizerIterationList {
- return PaginatedOptimizerIterationListToJSONTyped(json, false);
-}
-
-export function PaginatedOptimizerIterationListToJSONTyped(value?: PaginatedOptimizerIterationList | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'count': value['count'],
- 'next': value['next'],
- 'previous': value['previous'],
- 'results': ((value['results'] as Array<any>).map(OptimizerIterationToJSON)),
- };
-}
diff --git a/frontend/src/openapi/models/PatchedCapabilityRequest.ts b/frontend/src/openapi/models/PatchedCapabilityRequest.ts
index dbf7711f..7f3fc888 100644
--- a/frontend/src/openapi/models/PatchedCapabilityRequest.ts
+++ b/frontend/src/openapi/models/PatchedCapabilityRequest.ts
@@ -33,24 +33,6 @@ export interface PatchedCapabilityRequest {
* @memberof PatchedCapabilityRequest
*/
toolConfig?: any | null;
- /**
- *
- * @type {any}
- * @memberof PatchedCapabilityRequest
- */
- consistencyRules?: any | null;
- /**
- *
- * @type {any}
- * @memberof PatchedCapabilityRequest
- */
- optimizableElements?: any | null;
- /**
- *
- * @type {any}
- * @memberof PatchedCapabilityRequest
- */
- fixedElements?: any | null;
/**
*
* @type {string}
@@ -81,12 +63,6 @@ export interface PatchedCapabilityRequest {
* @memberof PatchedCapabilityRequest
*/
model?: string;
- /**
- *
- * @type {string}
- * @memberof PatchedCapabilityRequest
- */
- analyzerModel?: string;
/**
*
* @type {string}
@@ -129,24 +105,6 @@ export interface PatchedCapabilityRequest {
* @memberof PatchedCapabilityRequest
*/
outputSchema?: any | null;
- /**
- *
- * @type {number}
- * @memberof PatchedCapabilityRequest
- */
- structureWeight?: number;
- /**
- *
- * @type {number}
- * @memberof PatchedCapabilityRequest
- */
- totalPoints?: number;
- /**
- *
- * @type {number}
- * @memberof PatchedCapabilityRequest
- */
- toolUsageWeight?: number;
/**
*
* @type {string}
@@ -229,15 +187,11 @@ export function PatchedCapabilityRequestFromJSONTyped(json: any, ignoreDiscrimin
return {
'toolConfig': json['tool_config'] == null ? undefined : json['tool_config'],
- 'consistencyRules': json['consistency_rules'] == null ? undefined : json['consistency_rules'],
- 'optimizableElements': json['optimizable_elements'] == null ? undefined : json['optimizable_elements'],
- 'fixedElements': json['fixed_elements'] == null ? undefined : json['fixed_elements'],
'name': json['name'] == null ? undefined : json['name'],
'description': json['description'] == null ? undefined : json['description'],
'sourcePath': json['source_path'] == null ? undefined : json['source_path'],
'entrypointFn': json['entrypoint_fn'] == null ? undefined : json['entrypoint_fn'],
'model': json['model'] == null ? undefined : json['model'],
- 'analyzerModel': json['analyzer_model'] == null ? undefined : json['analyzer_model'],
'cliVersion': json['cli_version'] == null ? undefined : json['cli_version'],
'status': json['status'] == null ? undefined : CapabilityStatusEnumFromJSON(json['status']),
'observed': json['observed'] == null ? undefined : json['observed'],
@@ -245,9 +199,6 @@ export function PatchedCapabilityRequestFromJSONTyped(json: any, ignoreDiscrimin
'inputSchema': json['input_schema'] == null ? undefined : json['input_schema'],
'outputFields': json['output_fields'] == null ? undefined : json['output_fields'],
'outputSchema': json['output_schema'] == null ? undefined : json['output_schema'],
- 'structureWeight': json['structure_weight'] == null ? undefined : json['structure_weight'],
- 'totalPoints': json['total_points'] == null ? undefined : json['total_points'],
- 'toolUsageWeight': json['tool_usage_weight'] == null ? undefined : json['tool_usage_weight'],
'policyMarkdown': json['policy_markdown'] == null ? undefined : json['policy_markdown'],
'toolsSummary': json['tools_summary'] == null ? undefined : json['tools_summary'],
'decisionLogic': json['decision_logic'] == null ? undefined : json['decision_logic'],
@@ -273,15 +224,11 @@ export function PatchedCapabilityRequestToJSONTyped(value?: PatchedCapabilityReq
return {
'tool_config': value['toolConfig'],
- 'consistency_rules': value['consistencyRules'],
- 'optimizable_elements': value['optimizableElements'],
- 'fixed_elements': value['fixedElements'],
'name': value['name'],
'description': value['description'],
'source_path': value['sourcePath'],
'entrypoint_fn': value['entrypointFn'],
'model': value['model'],
- 'analyzer_model': value['analyzerModel'],
'cli_version': value['cliVersion'],
'status': CapabilityStatusEnumToJSON(value['status']),
'observed': value['observed'],
@@ -289,9 +236,6 @@ export function PatchedCapabilityRequestToJSONTyped(value?: PatchedCapabilityReq
'input_schema': value['inputSchema'],
'output_fields': value['outputFields'],
'output_schema': value['outputSchema'],
- 'structure_weight': value['structureWeight'],
- 'total_points': value['totalPoints'],
- 'tool_usage_weight': value['toolUsageWeight'],
'policy_markdown': value['policyMarkdown'],
'tools_summary': value['toolsSummary'],
'decision_logic': value['decisionLogic'],
diff --git a/frontend/src/openapi/models/PostResultsRequest.ts b/frontend/src/openapi/models/PostResultsRequest.ts
deleted file mode 100644
index 9d917184..00000000
--- a/frontend/src/openapi/models/PostResultsRequest.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-import type { CommandResultInputRequest } from './CommandResultInputRequest';
-import {
- CommandResultInputRequestFromJSON,
- CommandResultInputRequestFromJSONTyped,
- CommandResultInputRequestToJSON,
- CommandResultInputRequestToJSONTyped,
-} from './CommandResultInputRequest';
-
-/**
- *
- * @export
- * @interface PostResultsRequest
- */
-export interface PostResultsRequest {
- /**
- *
- * @type {Array<CommandResultInputRequest>}
- * @memberof PostResultsRequest
- */
- results: Array<CommandResultInputRequest>;
-}
-
-/**
- * Check if a given object implements the PostResultsRequest interface.
- */
-export function instanceOfPostResultsRequest(value: object): value is PostResultsRequest {
- if (!('results' in value) || value['results'] === undefined) return false;
- return true;
-}
-
-export function PostResultsRequestFromJSON(json: any): PostResultsRequest {
- return PostResultsRequestFromJSONTyped(json, false);
-}
-
-export function PostResultsRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): PostResultsRequest {
- if (json == null) {
- return json;
- }
- return {
-
- 'results': ((json['results'] as Array<any>).map(CommandResultInputRequestFromJSON)),
- };
-}
-
-export function PostResultsRequestToJSON(json: any): PostResultsRequest {
- return PostResultsRequestToJSONTyped(json, false);
-}
-
-export function PostResultsRequestToJSONTyped(value?: PostResultsRequest | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'results': ((value['results'] as Array<any>).map(CommandResultInputRequestToJSON)),
- };
-}
diff --git a/frontend/src/openapi/models/SetCommandTemplateRequest.ts b/frontend/src/openapi/models/SetCommandTemplateRequest.ts
deleted file mode 100644
index 1d701452..00000000
--- a/frontend/src/openapi/models/SetCommandTemplateRequest.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-/**
- *
- * @export
- * @interface SetCommandTemplateRequest
- */
-export interface SetCommandTemplateRequest {
- /**
- *
- * @type {string}
- * @memberof SetCommandTemplateRequest
- */
- template: string;
-}
-
-/**
- * Check if a given object implements the SetCommandTemplateRequest interface.
- */
-export function instanceOfSetCommandTemplateRequest(value: object): value is SetCommandTemplateRequest {
- if (!('template' in value) || value['template'] === undefined) return false;
- return true;
-}
-
-export function SetCommandTemplateRequestFromJSON(json: any): SetCommandTemplateRequest {
- return SetCommandTemplateRequestFromJSONTyped(json, false);
-}
-
-export function SetCommandTemplateRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): SetCommandTemplateRequest {
- if (json == null) {
- return json;
- }
- return {
-
- 'template': json['template'],
- };
-}
-
-export function SetCommandTemplateRequestToJSON(json: any): SetCommandTemplateRequest {
- return SetCommandTemplateRequestToJSONTyped(json, false);
-}
-
-export function SetCommandTemplateRequestToJSONTyped(value?: SetCommandTemplateRequest | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'template': value['template'],
- };
-}
diff --git a/frontend/src/openapi/models/index.ts b/frontend/src/openapi/models/index.ts
index a97cb17f..d4b31e9b 100644
--- a/frontend/src/openapi/models/index.ts
+++ b/frontend/src/openapi/models/index.ts
@@ -26,7 +26,6 @@ export * from './Binding';
export * from './BindingStateRequest';
export * from './BlankEnum';
export * from './CancelWork';
-export * from './CandidateInputRequest';
export * from './Capability';
export * from './CapabilityFlow';
export * from './CapabilityFlowExpectedOutput';
@@ -56,7 +55,6 @@ export * from './ChangeMessageRequest';
export * from './CheckoutSessionResponse';
export * from './CheckpointFile';
export * from './ColumnStat';
-export * from './CommandResultInputRequest';
export * from './ComparisonCoverage';
export * from './ConfidenceEnum';
export * from './ConnectorActiveConfig';
@@ -87,7 +85,6 @@ export * from './ConnectorVerifyResponse';
export * from './ConsentDecisionRequest';
export * from './ConsentDetails';
export * from './ConsentRedirect';
-export * from './CreateIterationRequest';
export * from './CreditTopUpRequestRequest';
export * from './Dataset';
export * from './DatasetAnalytics';
@@ -150,8 +147,6 @@ export * from './EvalScore';
export * from './EvalScoreSourceTypeEnum';
export * from './EvalSet';
export * from './EvalSetRequest';
-export * from './EvalSpecResponse';
-export * from './EvaluateIterationRequest';
export * from './EvaluationActivity';
export * from './EvaluationActivityDataset';
export * from './EvaluationActivityKindEnum';
@@ -226,7 +221,6 @@ export * from './JudgeModelEnum';
export * from './Kind703Enum';
export * from './LocalSessionRequest';
export * from './MetricComparison';
-export * from './ModeCd6Enum';
export * from './ModelActivation';
export * from './ModelActivationStageEnum';
export * from './ModelCatalogResponse';
@@ -249,18 +243,7 @@ export * from './NativeSample';
export * from './NativeSamplePrediction';
export * from './OnboardingMilestone';
export * from './OpenThreadRequest';
-export * from './OpenrouterKeySourceEnum';
export * from './OpenrouterStatusEnum';
-export * from './OptimizerCandidate';
-export * from './OptimizerCandidateStatusEnum';
-export * from './OptimizerCommand';
-export * from './OptimizerCommandStatusEnum';
-export * from './OptimizerExperiment';
-export * from './OptimizerExperimentCreateRequest';
-export * from './OptimizerExperimentStatusEnum';
-export * from './OptimizerExperimentsResultsCreate200Response';
-export * from './OptimizerIteration';
-export * from './OptimizerIterationStatusEnum';
export * from './OverallComparison';
export * from './Package';
export * from './PackageFile';
@@ -286,10 +269,6 @@ export * from './PaginatedFinetuningJobEventList';
export * from './PaginatedFinetuningJobListList';
export * from './PaginatedFinetuningJobRunList';
export * from './PaginatedNativeEvaluationList';
-export * from './PaginatedOptimizerCandidateList';
-export * from './PaginatedOptimizerCommandList';
-export * from './PaginatedOptimizerExperimentList';
-export * from './PaginatedOptimizerIterationList';
export * from './PaginatedPartitionPlanList';
export * from './PaginatedProjectInviteList';
export * from './PaginatedProjectList';
@@ -325,7 +304,6 @@ export * from './PlanEnum';
export * from './PlanUsage';
export * from './PlanUsageUnit';
export * from './PositionEnum';
-export * from './PostResultsRequest';
export * from './PreparationEdge';
export * from './PreparationEdgeKindEnum';
export * from './PreparationNode';
@@ -365,7 +343,6 @@ export * from './ScopeEnum';
export * from './SendMessageRequest';
export * from './ServingContextPlan';
export * from './Session';
-export * from './SetCommandTemplateRequest';
export * from './SignalCatalogEntry';
export * from './SignalEvent';
export * from './SignalEventSeenRequest';
diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.ts
index 2f3297a3..efd0dc7b 100644
--- a/frontend/src/routeTree.gen.ts
+++ b/frontend/src/routeTree.gen.ts
@@ -20,11 +20,9 @@ import { Route as AuthSettingsRouteImport } from './routes/_auth/settings'
import { Route as AuthObservabilityRouteImport } from './routes/_auth/observability'
import { Route as AuthInferenceRouteImport } from './routes/_auth/inference'
import { Route as AuthProjectsIndexRouteImport } from './routes/_auth/projects.index'
-import { Route as AuthOptimiserIndexRouteImport } from './routes/_auth/optimiser.index'
import { Route as AuthEvaluationsIndexRouteImport } from './routes/_auth/evaluations.index'
import { Route as AuthDatasetsIndexRouteImport } from './routes/_auth/datasets.index'
import { Route as AuthCapabilitiesIndexRouteImport } from './routes/_auth/capabilities.index'
-import { Route as AuthOptimiserExperimentIdRouteImport } from './routes/_auth/optimiser.$experimentId'
import { Route as AuthObservabilityIntegrationsRouteImport } from './routes/_auth/observability_.integrations'
import { Route as AuthObservabilityTraceIdRouteImport } from './routes/_auth/observability.$traceId'
import { Route as AuthInferenceModelIdRouteImport } from './routes/_auth/inference_.$modelId'
@@ -87,11 +85,6 @@ const AuthProjectsIndexRoute = AuthProjectsIndexRouteImport.update({
path: '/projects/',
getParentRoute: () => AuthRoute,
} as any)
-const AuthOptimiserIndexRoute = AuthOptimiserIndexRouteImport.update({
- id: '/optimiser/',
- path: '/optimiser/',
- getParentRoute: () => AuthRoute,
-} as any)
const AuthEvaluationsIndexRoute = AuthEvaluationsIndexRouteImport.update({
id: '/evaluations/',
path: '/evaluations/',
@@ -107,12 +100,6 @@ const AuthCapabilitiesIndexRoute = AuthCapabilitiesIndexRouteImport.update({
path: '/capabilities/',
getParentRoute: () => AuthRoute,
} as any)
-const AuthOptimiserExperimentIdRoute =
- AuthOptimiserExperimentIdRouteImport.update({
- id: '/optimiser/$experimentId',
- path: '/optimiser/$experimentId',
- getParentRoute: () => AuthRoute,
- } as any)
const AuthObservabilityIntegrationsRoute =
AuthObservabilityIntegrationsRouteImport.update({
id: '/observability_/integrations',
@@ -169,11 +156,9 @@ export interface FileRoutesByFullPath {
'/inference/$modelId': typeof AuthInferenceModelIdRoute
'/observability/$traceId': typeof AuthObservabilityTraceIdRoute
'/observability/integrations': typeof AuthObservabilityIntegrationsRoute
- '/optimiser/$experimentId': typeof AuthOptimiserExperimentIdRoute
'/capabilities/': typeof AuthCapabilitiesIndexRoute
'/datasets/': typeof AuthDatasetsIndexRoute
'/evaluations/': typeof AuthEvaluationsIndexRoute
- '/optimiser/': typeof AuthOptimiserIndexRoute
'/projects/': typeof AuthProjectsIndexRoute
'/evaluations/runs/$runId': typeof AuthEvaluationsRunsRunIdRoute
'/datasets/$datasetId/': typeof AuthDatasetsDatasetIdIndexRoute
@@ -193,11 +178,9 @@ export interface FileRoutesByTo {
'/inference/$modelId': typeof AuthInferenceModelIdRoute
'/observability/$traceId': typeof AuthObservabilityTraceIdRoute
'/observability/integrations': typeof AuthObservabilityIntegrationsRoute
- '/optimiser/$experimentId': typeof AuthOptimiserExperimentIdRoute
'/capabilities': typeof AuthCapabilitiesIndexRoute
'/datasets': typeof AuthDatasetsIndexRoute
'/evaluations': typeof AuthEvaluationsIndexRoute
- '/optimiser': typeof AuthOptimiserIndexRoute
'/projects': typeof AuthProjectsIndexRoute
'/evaluations/runs/$runId': typeof AuthEvaluationsRunsRunIdRoute
'/datasets/$datasetId': typeof AuthDatasetsDatasetIdIndexRoute
@@ -219,11 +202,9 @@ export interface FileRoutesById {
'/_auth/inference_/$modelId': typeof AuthInferenceModelIdRoute
'/_auth/observability/$traceId': typeof AuthObservabilityTraceIdRoute
'/_auth/observability_/integrations': typeof AuthObservabilityIntegrationsRoute
- '/_auth/optimiser/$experimentId': typeof AuthOptimiserExperimentIdRoute
'/_auth/capabilities/': typeof AuthCapabilitiesIndexRoute
'/_auth/datasets/': typeof AuthDatasetsIndexRoute
'/_auth/evaluations/': typeof AuthEvaluationsIndexRoute
- '/_auth/optimiser/': typeof AuthOptimiserIndexRoute
'/_auth/projects/': typeof AuthProjectsIndexRoute
'/_auth/evaluations/runs/$runId': typeof AuthEvaluationsRunsRunIdRoute
'/_auth/datasets/$datasetId/': typeof AuthDatasetsDatasetIdIndexRoute
@@ -245,11 +226,9 @@ export interface FileRouteTypes {
| '/inference/$modelId'
| '/observability/$traceId'
| '/observability/integrations'
- | '/optimiser/$experimentId'
| '/capabilities/'
| '/datasets/'
| '/evaluations/'
- | '/optimiser/'
| '/projects/'
| '/evaluations/runs/$runId'
| '/datasets/$datasetId/'
@@ -269,11 +248,9 @@ export interface FileRouteTypes {
| '/inference/$modelId'
| '/observability/$traceId'
| '/observability/integrations'
- | '/optimiser/$experimentId'
| '/capabilities'
| '/datasets'
| '/evaluations'
- | '/optimiser'
| '/projects'
| '/evaluations/runs/$runId'
| '/datasets/$datasetId'
@@ -294,11 +271,9 @@ export interface FileRouteTypes {
| '/_auth/inference_/$modelId'
| '/_auth/observability/$traceId'
| '/_auth/observability_/integrations'
- | '/_auth/optimiser/$experimentId'
| '/_auth/capabilities/'
| '/_auth/datasets/'
| '/_auth/evaluations/'
- | '/_auth/optimiser/'
| '/_auth/projects/'
| '/_auth/evaluations/runs/$runId'
| '/_auth/datasets/$datasetId/'
@@ -392,13 +367,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthProjectsIndexRouteImport
parentRoute: typeof AuthRoute
}
- '/_auth/optimiser/': {
- id: '/_auth/optimiser/'
- path: '/optimiser'
- fullPath: '/optimiser/'
- preLoaderRoute: typeof AuthOptimiserIndexRouteImport
- parentRoute: typeof AuthRoute
- }
'/_auth/evaluations/': {
id: '/_auth/evaluations/'
path: '/evaluations'
@@ -420,13 +388,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthCapabilitiesIndexRouteImport
parentRoute: typeof AuthRoute
}
- '/_auth/optimiser/$experimentId': {
- id: '/_auth/optimiser/$experimentId'
- path: '/optimiser/$experimentId'
- fullPath: '/optimiser/$experimentId'
- preLoaderRoute: typeof AuthOptimiserExperimentIdRouteImport
- parentRoute: typeof AuthRoute
- }
'/_auth/observability_/integrations': {
id: '/_auth/observability_/integrations'
path: '/observability/integrations'
@@ -499,11 +460,9 @@ interface AuthRouteChildren {
AuthCapabilitiesCapabilityIdRoute: typeof AuthCapabilitiesCapabilityIdRoute
AuthInferenceModelIdRoute: typeof AuthInferenceModelIdRoute
AuthObservabilityIntegrationsRoute: typeof AuthObservabilityIntegrationsRoute
- AuthOptimiserExperimentIdRoute: typeof AuthOptimiserExperimentIdRoute
AuthCapabilitiesIndexRoute: typeof AuthCapabilitiesIndexRoute
AuthDatasetsIndexRoute: typeof AuthDatasetsIndexRoute
AuthEvaluationsIndexRoute: typeof AuthEvaluationsIndexRoute
- AuthOptimiserIndexRoute: typeof AuthOptimiserIndexRoute
AuthProjectsIndexRoute: typeof AuthProjectsIndexRoute
AuthEvaluationsRunsRunIdRoute: typeof AuthEvaluationsRunsRunIdRoute
AuthDatasetsDatasetIdIndexRoute: typeof AuthDatasetsDatasetIdIndexRoute
@@ -519,11 +478,9 @@ const AuthRouteChildren: AuthRouteChildren = {
AuthCapabilitiesCapabilityIdRoute: AuthCapabilitiesCapabilityIdRoute,
AuthInferenceModelIdRoute: AuthInferenceModelIdRoute,
AuthObservabilityIntegrationsRoute: AuthObservabilityIntegrationsRoute,
- AuthOptimiserExperimentIdRoute: AuthOptimiserExperimentIdRoute,
AuthCapabilitiesIndexRoute: AuthCapabilitiesIndexRoute,
AuthDatasetsIndexRoute: AuthDatasetsIndexRoute,
AuthEvaluationsIndexRoute: AuthEvaluationsIndexRoute,
- AuthOptimiserIndexRoute: AuthOptimiserIndexRoute,
AuthProjectsIndexRoute: AuthProjectsIndexRoute,
AuthEvaluationsRunsRunIdRoute: AuthEvaluationsRunsRunIdRoute,
AuthDatasetsDatasetIdIndexRoute: AuthDatasetsDatasetIdIndexRoute,
diff --git a/frontend/src/routes/_auth.tsx b/frontend/src/routes/_auth.tsx
index 533f70d2..db05c956 100644
--- a/frontend/src/routes/_auth.tsx
+++ b/frontend/src/routes/_auth.tsx
@@ -63,7 +63,6 @@ const DYNAMIC_PARENTS = new Set([
"jobs",
"observability",
"datasets",
- "optimiser",
"inference",
]);
@@ -114,14 +113,6 @@ function useCachedName(
select: (dataset) => dataset.name?.trim() || `Dataset ${dataset.id.slice(0, 8)}`,
});
- const experimentNameQuery = useQuery({
- enabled: kind === "optimiser" && !!slug,
- queryFn: () => apiClient.optimizerExperiments.optimizerExperimentsRetrieve({ id: slug ?? "" }),
- // Same key as the run page so the label rides the existing cache.
- queryKey: ["optimizer-experiment", slug],
- select: (experiment) => `${experiment.capabilityName || "Run"} · ${experiment.id.slice(0, 8)}`,
- });
-
const deployedModelNameQuery = useQuery({
enabled: kind === "inference" && !!slug,
queryFn: () => apiClient.deployedModels.deployedModelsRetrieve({ id: slug ?? "" }),
@@ -153,7 +144,6 @@ function useCachedName(
if (kind === "capabilities") return capabilityNameQuery.data;
if (kind === "projects") return projectNameQuery.data;
if (kind === "datasets") return datasetNameQuery.data;
- if (kind === "optimiser") return experimentNameQuery.data;
if (kind === "inference") return deployedModelNameQuery.data;
return undefined;
}
diff --git a/frontend/src/routes/_auth/-inference.filter.test.tsx b/frontend/src/routes/_auth/-inference.filter.test.tsx
index 313b6de3..30ae5da6 100644
--- a/frontend/src/routes/_auth/-inference.filter.test.tsx
+++ b/frontend/src/routes/_auth/-inference.filter.test.tsx
@@ -140,7 +140,7 @@ describe("Inference search request scope", () => {
expect(routeState.navigate).not.toHaveBeenCalled();
});
- // 400ms, matching the training, evaluations, optimiser and datasets lists.
+ // 400ms, matching the training, evaluations and datasets lists.
it("publishes the settled term to the url, back on page 1", () => {
vi.useFakeTimers();
renderPage({ page: 3 });
diff --git a/frontend/src/routes/_auth/capabilities.$capabilityId.tsx b/frontend/src/routes/_auth/capabilities.$capabilityId.tsx
index e0b119f7..e3d1f1e6 100644
--- a/frontend/src/routes/_auth/capabilities.$capabilityId.tsx
+++ b/frontend/src/routes/_auth/capabilities.$capabilityId.tsx
@@ -7,11 +7,11 @@ import z from "zod";
import apiClient from "@/client";
import { CapabilityNameEditor } from "@/components/capability-detail/CapabilityNameEditor";
import { DatasetTab } from "@/components/capability-detail/DatasetTab";
-import { EvalMatrixTab } from "@/components/capability-detail/EvalMatrixTab";
import { ModelsTab } from "@/components/capability-detail/ModelsTab";
import { CapabilityNextStepNudge } from "@/components/capability-detail/next-step-nudge";
import { CapabilityFactsBar } from "@/components/capability-overview/CapabilityFactsBar";
import { CapabilityPromptCard } from "@/components/capability-overview/CapabilityPromptCard";
+import { EvalMatrixTable } from "@/components/evaluations/eval-matrix-table";
import { Alert } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { useCopy } from "@/components/ui/block-actions";
@@ -261,7 +261,7 @@ function CapabilityDetailPage() {
<h2 className={TITLE.section} id="capability-evaluators-heading">
Evaluations
</h2>
- <EvalMatrixTab
+ <EvalMatrixTable
capability={capability}
capabilityId={capabilityId}
projectId={projectId}
diff --git a/frontend/src/routes/_auth/evaluations.runs.$runId.tsx b/frontend/src/routes/_auth/evaluations.runs.$runId.tsx
index d9744f0e..bf2ade25 100644
--- a/frontend/src/routes/_auth/evaluations.runs.$runId.tsx
+++ b/frontend/src/routes/_auth/evaluations.runs.$runId.tsx
@@ -46,7 +46,6 @@ export const Route = createFileRoute("/_auth/evaluations/runs/$runId")({
const MODE_LABEL: Record<string, string> = {
generate: "Generated",
- provided: "Provided",
recorded: "Recorded",
};
@@ -298,22 +297,6 @@ function RunHeaderCard({
<RunElapsed run={actionRun} />
<div className="ml-auto flex shrink-0 items-center gap-2">
<RelaunchButton runId={actionRun.id} visible={!active} />
- {actionRun.status === "completed" && (
- <Button asChild size="sm">
- <Link
- search={{
- optimize: true,
- projectId,
- ...(actionRun.capabilityId ? { capabilityId: actionRun.capabilityId } : {}),
- ...(actionRun.dataset ? { datasetId: actionRun.dataset } : {}),
- }}
- to="/optimiser"
- >
- <Icon.optimiser />
- Optimise
- </Link>
- </Button>
- )}
</div>
</div>
</Card>
diff --git a/frontend/src/routes/_auth/optimiser.$experimentId.tsx b/frontend/src/routes/_auth/optimiser.$experimentId.tsx
deleted file mode 100644
index f2bcf4b5..00000000
--- a/frontend/src/routes/_auth/optimiser.$experimentId.tsx
+++ /dev/null
@@ -1,1236 +0,0 @@
-import { type ReactNode, useState } from "react";
-
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { createFileRoute, redirect } from "@tanstack/react-router";
-
-import apiClient from "@/client";
-import { EntityRef } from "@/components/entity-ref";
-import { ModelProviderChip } from "@/components/model-provider-chip";
-import {
- ExperimentStatusChip,
- experimentScores,
- isExperimentLive,
- OptimizerRunTypeBadge,
- optimizerModelIds,
- optimizerRunType,
- optimizerRunTypeMeta,
- prettyStatus,
-} from "@/components/optimiser/experiment-status";
-import { deriveWinner } from "@/components/optimiser/experiment-winner";
-import { FinetuningSuggestion } from "@/components/optimiser/finetuning-suggestion";
-import { DetailErrorState } from "@/components/route-error";
-import { Alert } from "@/components/ui/alert";
-import { Badge } from "@/components/ui/badge";
-import { useCopy } from "@/components/ui/block-actions";
-import { Button } from "@/components/ui/button";
-import { Card } from "@/components/ui/card";
-import { ConfirmDialog } from "@/components/ui/confirm-dialog";
-import { CountChip } from "@/components/ui/count-chip";
-import { DateTime } from "@/components/ui/datetime";
-import { DeltaChip } from "@/components/ui/delta-chip";
-import { Icon } from "@/components/ui/icons";
-import { lazyChart } from "@/components/ui/lazy-chart";
-import { PageHeader } from "@/components/ui/page-header";
-import { PageShell } from "@/components/ui/page-shell";
-import { QueryError } from "@/components/ui/query-error";
-import { SortableHeader } from "@/components/ui/sortable-header";
-import { LoadingState } from "@/components/ui/spinner";
-import { Table, TableBody, TableCell, TableHeader, TableRow } from "@/components/ui/table";
-import { useElapsedSeconds } from "@/hooks/use-elapsed-seconds";
-import { useTableSort } from "@/hooks/use-table-sort";
-import { scoreTextClass } from "@/lib/colors";
-import { featureFlags } from "@/lib/feature-flags";
-import { formatElapsed } from "@/lib/formatters";
-import { resolveStatus } from "@/lib/job-status";
-import { notify } from "@/lib/notify";
-import { projectIdSearchSchema } from "@/lib/schemas";
-import { PROSE, TITLE } from "@/lib/typography";
-import { cn } from "@/lib/utils";
-import type {
- ModeCd6Enum,
- OptimizerCandidate,
- OptimizerCommand,
- OptimizerExperiment,
- OptimizerIteration,
-} from "@/openapi";
-
-// Lazy so recharts stays out of the initial bundle.
-const OptimizerScoreChart = lazyChart(
- () =>
- import("@/components/optimiser/score-chart").then((m) => ({
- default: m.OptimizerScoreChart,
- })),
- { minHeight: 220 }
-);
-
-export const Route = createFileRoute("/_auth/optimiser/$experimentId")({
- beforeLoad: () => {
- if (!featureFlags.evaluations) throw redirect({ replace: true, to: "/" });
- },
- component: OptimiserRunPage,
- validateSearch: projectIdSearchSchema,
-});
-
-const LIVE_CANDIDATE_STATUSES = new Set([
- "pending",
- "running_commands",
- "commands_done",
- "evaluating",
-]);
-
-function iterationChipKey(status: string): string {
- if (status === "completed" || status === "evaluated") return "completed";
- if (status === "failed") return "failed";
- if (status === "pending") return "queued";
- return "running";
-}
-
-function ChildStatusChip({ status, chipKey }: { status: string; chipKey: string }) {
- const cfg = resolveStatus(chipKey, "queued");
- return (
- <Badge className="gap-1" size="chip" variant={cfg.variant}>
- {cfg.icon}
- {prettyStatus(status)}
- </Badge>
- );
-}
-
-/** Terminal runs measure to `updatedAt` — it is bumped on the terminal transition. */
-function RunElapsed({ experiment }: { experiment: OptimizerExperiment }) {
- const live = isExperimentLive(experiment.status);
- const ticking = useElapsedSeconds(live ? experiment.createdAt : undefined);
-
- if (live) {
- if (ticking == null) return null;
- return (
- <span
- aria-label={`Running for ${formatElapsed(ticking)}`}
- className="tabular-nums text-xs text-muted-foreground"
- role="timer"
- >
- {formatElapsed(ticking)}
- </span>
- );
- }
-
- const totalSeconds = Math.floor(
- (experiment.updatedAt.getTime() - experiment.createdAt.getTime()) / 1000
- );
- if (totalSeconds <= 0) return null;
- return (
- <span
- aria-label={`Ran for ${formatElapsed(totalSeconds)}`}
- className="tabular-nums text-xs text-muted-foreground"
- role="img"
- >
- {formatElapsed(totalSeconds)}
- </span>
- );
-}
-
-function iterationBest(iteration: OptimizerIteration): number | null {
- return (iteration.candidates ?? []).reduce<number | null>((acc, c) => {
- if (c.status !== "evaluated") return acc;
- const s = typeof c.score === "number" && Number.isFinite(c.score) ? c.score : null;
- return s != null && (acc == null || s > acc) ? s : acc;
- }, null);
-}
-
-function iterationLabel(iteration: OptimizerIteration): string {
- if (iteration.order === 0) return "Baseline";
- return iteration.name || `Iteration ${iteration.order}`;
-}
-
-function comparisonIterationLabel(iteration: OptimizerIteration, comparedModels: string[]): string {
- const models = [...(iteration.candidates ?? [])]
- .sort((a, b) => a.candidateIndex - b.candidateIndex)
- .map((candidate) => candidate.modelName || candidate.targetModel)
- .filter(Boolean)
- .join(", ");
- return models || comparedModels[iteration.order - 1] || "Selected models";
-}
-
-type CandidateCoverage = {
- errors?: string[];
- excluded_commands?: number;
-};
-
-function candidateCoverage(candidate: OptimizerCandidate): CandidateCoverage {
- const scores = candidate.scores as { coverage?: CandidateCoverage } | null | undefined;
- return scores?.coverage ?? {};
-}
-
-type ModelComparisonReport = {
- incumbentWins: boolean | null;
- overallWinner: string | null;
- selectedWinner: string | null;
-};
-
-/** Candidates are ordered with models cycling fastest. */
-function harnessNumber(candidateIndex: number, modelCount: number): number {
- return modelCount > 0 ? Math.floor(candidateIndex / modelCount) + 1 : 1;
-}
-
-function highestScore(...scores: (number | null | undefined)[]): number | null {
- const known = scores.filter((s): s is number => typeof s === "number" && Number.isFinite(s));
- return known.length > 0 ? Math.max(...known) : null;
-}
-
-function modelComparisonReport(experiment: OptimizerExperiment): ModelComparisonReport {
- const state = experiment.state as Record<string, unknown> | null;
- const report = state?.model_comparison as Record<string, unknown> | undefined;
- return {
- incumbentWins: typeof report?.incumbent_wins === "boolean" ? report.incumbent_wins : null,
- overallWinner: typeof report?.overall_winner === "string" ? report.overall_winner : null,
- selectedWinner: typeof report?.selected_winner === "string" ? report.selected_winner : null,
- };
-}
-
-/** `state.model_optimization.overall_winner` — a model slug, or "incumbent". */
-function hybridWinnerOf(experiment: OptimizerExperiment): string | null {
- const state = experiment.state as Record<string, unknown> | null;
- const winner = (state?.model_optimization as Record<string, unknown> | undefined)?.overall_winner;
- return typeof winner === "string" ? winner : null;
-}
-
-/** A command with neither candidate nor iteration is the smoke test. */
-function commandPhase(command: OptimizerCommand): string {
- if (command.candidate == null && command.iteration == null) return "Smoke test";
- return `dp #${command.datapointIndex}`;
-}
-
-function HeaderStat({
- label,
- primary = false,
- children,
-}: {
- label: string;
- primary?: boolean;
- children: ReactNode;
-}) {
- return (
- <div className="flex flex-col gap-1.5">
- <span className="text-xs font-medium text-muted-foreground">{label}</span>
- <div
- className={cn(
- "flex items-center gap-1.5 font-mono tabular-nums leading-none",
- primary ? "text-xl font-semibold" : "text-sm font-medium"
- )}
- >
- {children}
- </div>
- </div>
- );
-}
-
-/** Hidden from the rendered diff, but kept in the copy/download text. */
-const GIT_META_LINE =
- /^(index |--- |\+\+\+ |old mode |new mode |new file mode |deleted file mode |similarity index |dissimilarity index |rename from |rename to |copy from |copy to |Binary files )/;
-
-function diffDisplayLines(lines: string[]): ({ path: string } | { line: string })[] {
- const out: ({ path: string } | { line: string })[] = [];
- for (const line of lines) {
- const fileHeader = line.match(/^diff --git a\/.* b\/(.*)$/);
- if (fileHeader) out.push({ path: fileHeader[1] });
- else if (!GIT_META_LINE.test(line)) out.push({ line });
- }
- return out;
-}
-
-function DiffViewer({ patch, filename }: { patch: string; filename: string }) {
- // git apply expects a trailing newline — normalise once for copy + download.
- const text = patch.endsWith("\n") ? patch : `${patch}\n`;
- const { copied, copy } = useCopy(text);
-
- const lines = patch.split("\n");
- if (lines.at(-1) === "") lines.pop();
- const added = lines.filter((l) => l.startsWith("+") && !l.startsWith("+++")).length;
- const removed = lines.filter((l) => l.startsWith("-") && !l.startsWith("---")).length;
-
- function download() {
- const url = URL.createObjectURL(new Blob([text], { type: "text/x-patch" }));
- const a = document.createElement("a");
- a.href = url;
- a.download = filename;
- a.click();
- URL.revokeObjectURL(url);
- }
-
- const actionClass =
- "rounded-sm p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60";
-
- return (
- <div className="overflow-hidden rounded-md border border-border/60">
- <div className="flex items-center gap-2 border-b border-border/70 bg-wash-raised px-3 py-1.5">
- <Icon.diff className="size-3 shrink-0 text-muted-foreground" />
- <span className="min-w-0 truncate font-mono text-xs text-muted-foreground">{filename}</span>
- <span className="font-mono text-xs tabular-nums text-success">+{added}</span>
- <span className="font-mono text-xs tabular-nums text-destructive">−{removed}</span>
- <span className="flex-1" />
- <button
- aria-label="Copy patch to clipboard"
- className={actionClass}
- onClick={copy}
- title={copied ? "Copied!" : "Copy patch"}
- type="button"
- >
- {copied ? (
- <Icon.success className="size-3 text-success" />
- ) : (
- <Icon.clipboard className="size-3" />
- )}
- </button>
- <button
- aria-label={`Download ${filename}`}
- className={actionClass}
- onClick={download}
- title="Download patch"
- type="button"
- >
- <Icon.download className="size-3" />
- </button>
- </div>
- <div className="max-h-96 overflow-auto bg-wash-subtle">
- <pre className="pb-2 font-mono text-xs leading-relaxed">
- {diffDisplayLines(lines).map((item, i) => {
- if ("path" in item) {
- return (
- <span
- className="mb-1 flex items-center gap-1.5 border-b border-border/60 bg-wash-raised px-3 py-1.5 font-medium text-foreground/90 [&:not(:first-child)]:mt-2 [&:not(:first-child)]:border-t"
- key={i}
- >
- <Icon.file className="size-3 shrink-0 text-muted-foreground" />
- {item.path}
- </span>
- );
- }
- const { line } = item;
- const isAdd = line.startsWith("+");
- const isDel = line.startsWith("-");
- const isHunk = line.startsWith("@@");
- return (
- <span
- className={cn(
- "block px-3",
- isAdd && "bg-success/10 text-success",
- isDel && "bg-destructive/10 text-destructive",
- isHunk && "text-primary/70",
- !isAdd && !isDel && !isHunk && "text-foreground/80"
- )}
- key={i}
- >
- {line || "\u00a0"}
- </span>
- );
- })}
- </pre>
- </div>
- </div>
- );
-}
-
-function CandidateRow({
- candidate,
- hybrid,
- modelCount,
- isBest,
- failedCommands,
-}: {
- candidate: OptimizerCandidate;
- hybrid: boolean;
- modelCount: number;
- isBest: boolean;
- failedCommands: OptimizerCommand[];
-}) {
- const { experimentId } = Route.useParams();
- const [showPatch, setShowPatch] = useState(false);
- const { modelName, targetModel } = candidate;
- const harnessIndex = harnessNumber(candidate.candidateIndex, modelCount);
- const label = candidate.isBaseline
- ? "Baseline"
- : hybrid
- ? `Code version ${harnessIndex}`
- : targetModel || `Candidate ${candidate.candidateIndex + 1}`;
- const patchLabel = candidate.isBaseline ? "base" : `c${candidate.candidateIndex + 1}`;
- const running = LIVE_CANDIDATE_STATUSES.has(candidate.status);
- const chipKey =
- candidate.status === "evaluated"
- ? "completed"
- : candidate.status === "failed"
- ? "failed"
- : running
- ? "running"
- : "queued";
-
- const score = candidate.status === "evaluated" ? candidate.score : null;
- const coverage = candidateCoverage(candidate);
- const excludedOutputs = coverage.excluded_commands ?? failedCommands.length;
-
- const actions = candidate.evalRun || candidate.codePath;
-
- return (
- <div className="flex flex-col gap-2 border-b border-border/60 px-4 py-2.5 last:border-b-0">
- <div
- className={cn(
- "grid items-start gap-x-2.5 gap-y-2",
- candidate.codePath ? "grid-cols-[minmax(0,1fr)_auto]" : "grid-cols-1"
- )}
- >
- <div className="flex min-w-0 items-center gap-2.5">
- <span
- className={cn(
- "inline-flex max-w-64 shrink-0 justify-center truncate rounded-sm border px-1.5 py-0.5 font-mono text-xs",
- candidate.isBaseline && "border-warning/40 bg-warning/10 text-warning",
- !candidate.isBaseline && isBest && "border-success/40 bg-success/10 text-success",
- !candidate.isBaseline &&
- !isBest &&
- "border-border/60 bg-wash-raised text-muted-foreground"
- )}
- >
- {label}
- </span>
- <ModelProviderChip
- compact
- model={
- modelName ||
- targetModel ||
- (candidate.isBaseline ? "Incumbent model" : "Capability model")
- }
- />
- <ChildStatusChip chipKey={chipKey} status={candidate.status} />
- {isBest && !candidate.isBaseline && (
- <Badge className="gap-1" size="chip" variant="success">
- <Icon.zap className="size-2.5" />
- Best
- </Badge>
- )}
- {score != null && (
- <span className={cn("font-mono text-xs tabular-nums", scoreTextClass(score))}>
- {score.toFixed(1)}%
- </span>
- )}
- {excludedOutputs > 0 && (
- <span className="text-xs text-destructive">
- {excludedOutputs} output{excludedOutputs === 1 ? "" : "s"} excluded from score
- </span>
- )}
- {actions && <span className="flex-1" />}
- {candidate.evalRun && (
- <div
- className={cn("shrink-0", candidate.codePath && "border-r border-border/70 pr-2.5")}
- >
- <EntityRef id={candidate.evalRun} kind="evalRun" name="Eval run" />
- </div>
- )}
- </div>
-
- {candidate.codePath && (
- <button
- aria-expanded={showPatch}
- className="inline-flex items-center gap-1 px-2.5 text-xs text-muted-foreground/60 transition-colors hover:text-foreground"
- onClick={() => setShowPatch((v) => !v)}
- type="button"
- >
- <Icon.diff className="size-3 text-muted-foreground" />
- {showPatch ? "Hide patch" : "View patch"}
- </button>
- )}
-
- {showPatch && candidate.codePath && (
- <DiffViewer filename={`${experimentId}-${patchLabel}.patch`} patch={candidate.codePath} />
- )}
- </div>
-
- {failedCommands.map((command) => (
- <div className="overflow-hidden rounded-md border border-border" key={command.id}>
- <div className="flex items-center gap-2 px-3 py-1.5 text-xs font-medium text-muted-foreground">
- <Icon.failed className="size-3.5 shrink-0" />
- {commandPhase(command)} failed
- </div>
- <pre className="max-h-40 overflow-auto whitespace-pre-wrap border-t border-border/60 px-3 py-2 font-mono text-xs text-muted-foreground">
- {command.error?.trim() || command.output?.trim() || "(no error output captured)"}
- </pre>
- </div>
- ))}
- {failedCommands.length === 0 && coverage.errors && coverage.errors.length > 0 && (
- <Alert className="flex-col px-3 py-2 text-xs" variant="destructive">
- <p className="font-medium">Excluded output errors</p>
- <ul className="mt-1 list-disc space-y-0.5 pl-4 font-mono">
- {coverage.errors.map((error) => (
- <li key={error}>{error}</li>
- ))}
- </ul>
- </Alert>
- )}
- {candidate.status === "failed" && failedCommands.length === 0 && (
- <Alert className="px-3 py-2 text-xs" variant="destructive">
- This candidate failed before producing a score. Its outputs were excluded from ranking.
- </Alert>
- )}
- </div>
- );
-}
-
-function IterationRow({
- comparison,
- iteration,
- baseline,
- hybrid,
- modelCount,
- comparedModels,
- showWinnerBadge,
- winnerCandidateId,
- failedCommands,
-}: {
- comparison: boolean;
- iteration: OptimizerIteration;
- baseline: number | null;
- hybrid: boolean;
- modelCount: number;
- comparedModels: string[];
- showWinnerBadge: boolean;
- winnerCandidateId: string | null;
- failedCommands: OptimizerCommand[];
-}) {
- const [expanded, setExpanded] = useState(false);
- const candidates = [...(iteration.candidates ?? [])].sort(
- (a, b) => a.candidateIndex - b.candidateIndex
- );
- const best = iterationBest(iteration);
- const delta = best != null && baseline != null && iteration.order > 0 ? best - baseline : null;
- // Comparison rows name their model even before its candidate exists: order i
- // maps 1:1 onto the i-th selected model.
- const rowLabel = comparison
- ? comparisonIterationLabel(iteration, comparedModels)
- : iterationLabel(iteration);
-
- return (
- <>
- <TableRow
- className={cn("cursor-pointer", showWinnerBadge && "bg-success/[0.04]")}
- onClick={() => setExpanded((v) => !v)}
- >
- <TableCell className="px-4">
- <span className="flex items-center gap-2">
- <Button
- aria-expanded={expanded}
- aria-label={expanded ? "Hide candidates" : "Show candidates"}
- onClick={(e) => {
- e.stopPropagation();
- setExpanded((v) => !v);
- }}
- size="icon-sm"
- variant="ghost"
- >
- <Icon.chevronDown
- className={cn("size-3.5 transition-transform", !expanded && "-rotate-90")}
- />
- </Button>
- {!comparison && (
- <span className="w-6 shrink-0 font-mono text-xs text-muted-foreground">
- #{iteration.order}
- </span>
- )}
- <span className="min-w-0 truncate text-sm font-medium">{rowLabel}</span>
- {showWinnerBadge && (
- <Badge className="shrink-0 gap-1" size="chip" variant="success">
- <Icon.trophy className="size-2.5" />
- Winner
- </Badge>
- )}
- </span>
- </TableCell>
- <TableCell className="px-4 text-center">
- <ChildStatusChip chipKey={iterationChipKey(iteration.status)} status={iteration.status} />
- </TableCell>
- <TableCell className="px-4 text-center font-mono text-xs tabular-nums text-muted-foreground">
- {candidates.length}
- </TableCell>
- <TableCell className="px-4 text-center font-mono text-xs tabular-nums">
- {best == null ? (
- <span className="text-muted-foreground/40">—</span>
- ) : (
- <span className="inline-flex items-center justify-center gap-1.5 text-foreground">
- <span>{best.toFixed(1)}%</span>
- {delta != null && <DeltaChip value={delta} />}
- </span>
- )}
- </TableCell>
- <TableCell className="px-4 text-center font-mono text-xs tabular-nums text-muted-foreground">
- <DateTime value={iteration.createdAt} />
- </TableCell>
- </TableRow>
- {expanded && (
- <TableRow className="bg-wash-subtle hover:bg-wash-subtle">
- <TableCell className="p-0" colSpan={5}>
- {candidates.length === 0 ? (
- <p className={cn(PROSE, "px-4 py-3 text-sm italic text-muted-foreground")}>
- {comparison
- ? "Scores appear here once the selected models are evaluated."
- : "Candidates appear here once the optimiser proposes them."}
- </p>
- ) : (
- <div className="flex flex-col">
- {candidates.map((c) => (
- <CandidateRow
- candidate={c}
- failedCommands={failedCommands.filter((cmd) => cmd.candidate === c.id)}
- hybrid={hybrid}
- isBest={winnerCandidateId != null && c.id === winnerCandidateId}
- key={c.id}
- modelCount={modelCount}
- />
- ))}
- </div>
- )}
- </TableCell>
- </TableRow>
- )}
- </>
- );
-}
-
-const COMMAND_STATUS_TEXT: Record<string, string> = {
- evaluated: "evaluated",
- failed: "failed",
- passed: "passed",
- pending: "queued",
- ran: "ran",
- running: "running",
-};
-
-function RunActivity({
- experiment,
- commands,
- onCancel,
- cancelPending,
- commandsError,
- onCommandsRetry,
- runType,
- hybridWinner,
- best,
- delta,
-}: {
- experiment: OptimizerExperiment;
- commands: OptimizerCommand[];
- commandsError?: unknown;
- onCommandsRetry?: () => Promise<unknown> | unknown;
- onCancel: () => void;
- cancelPending: boolean;
- runType: ModeCd6Enum;
- hybridWinner: string | null;
- best: number | null;
- delta: number | null;
-}) {
- const [expanded, setExpanded] = useState(false);
- const live = isExperimentLive(experiment.status);
- const runTypeLabel = optimizerRunTypeMeta(runType).label;
-
- const running = commands.filter((c) => c.status === "running").length;
- const pending = commands.filter((c) => c.status === "pending").length;
- const failed = commands.filter((c) => c.status === "failed").length;
-
- let statusLine: string;
- if (experiment.status === "failed") {
- statusLine = experiment.failureReason || "Experiment failed";
- } else if (experiment.status === "cancelled") {
- statusLine = "Experiment cancelled";
- } else if (experiment.status === "completed") {
- if (runType === "model_comparison") {
- const report = modelComparisonReport(experiment);
- statusLine = report.overallWinner
- ? `${runTypeLabel} completed — ${report.overallWinner === "incumbent" ? "incumbent" : report.overallWinner} won`
- : `${runTypeLabel} completed`;
- } else if (runType === "hybrid") {
- const { baseline } = experimentScores(experiment);
- const winnerScore = hybridWinner === "incumbent" ? baseline : best;
- statusLine = hybridWinner
- ? `${runTypeLabel} completed — ${hybridWinner} won${winnerScore != null ? ` at ${winnerScore.toFixed(1)}` : ""}`
- : `${runTypeLabel} completed`;
- } else {
- statusLine =
- best != null
- ? `${runTypeLabel} completed — best score ${best.toFixed(1)}${delta != null ? ` (${delta >= 0 ? "up" : "down"} ${Math.abs(delta).toFixed(1)} vs baseline)` : ""}`
- : `${runTypeLabel} completed`;
- }
- } else {
- const parts = [prettyStatus(experiment.status)];
- if (running > 0 || pending > 0) {
- parts.push(`${running} command${running === 1 ? "" : "s"} running · ${pending} queued`);
- } else {
- parts.push("waiting for `/overmind optimise`");
- }
- if (failed > 0) parts.push(`${failed} failed`);
- statusLine = parts.join(" — ");
- }
-
- const feed = [...commands].sort((a, b) => +b.createdAt - +a.createdAt);
-
- return (
- <Card className="flex flex-col gap-1.5 p-4">
- <div className="flex h-7 items-center gap-2.5">
- <ExperimentStatusChip status={experiment.status} />
- {live && (
- <span aria-hidden className="size-1.5 shrink-0 animate-pulse rounded-xs bg-primary" />
- )}
- <p
- className="min-w-0 flex-1 truncate font-mono text-xs leading-none tabular-nums text-muted-foreground"
- title={statusLine}
- >
- {statusLine}
- </p>
- <div className="flex h-7 shrink-0 items-center gap-2">
- {live && (
- <ConfirmDialog
- cancelLabel="Keep running"
- confirmLabel="Cancel run"
- description="Stops this optimisation run."
- destructive
- isPending={cancelPending}
- onConfirm={onCancel}
- title="Cancel this run?"
- trigger={
- <Button size="sm" variant="secondary">
- <Icon.close />
- Cancel
- </Button>
- }
- />
- )}
- {feed.length > 0 && (
- <Button
- aria-expanded={expanded}
- aria-label={expanded ? "Hide command log" : "Show command log"}
- onClick={() => setExpanded((v) => !v)}
- size="icon-sm"
- variant="ghost"
- >
- <Icon.chevronDown
- className={cn("size-3.5 transition-transform", expanded && "rotate-180")}
- />
- </Button>
- )}
- </div>
- </div>
- {expanded && feed.length > 0 && (
- <div
- aria-live="polite"
- className="flex max-h-56 flex-col overflow-y-auto rounded-md bg-wash-subtle px-2.5 py-1.5"
- role="log"
- >
- {feed.map((command) => {
- const detail =
- command.status === "failed"
- ? command.error?.trim() || command.output?.trim() || ""
- : (command.output ?? "").trim();
- return (
- <p
- className="shrink-0 truncate font-mono text-xs leading-5 text-muted-foreground"
- key={command.id}
- title={detail || command.command}
- >
- <span className="text-muted-foreground">
- {new Date(command.createdAt).toLocaleTimeString()}{" "}
- </span>
- <span className="font-medium">{commandPhase(command)}</span>
- <span
- className={cn(
- "ml-1.5",
- command.status === "failed" && "text-destructive",
- (command.status === "evaluated" || command.status === "passed") &&
- "text-success"
- )}
- >
- {COMMAND_STATUS_TEXT[command.status] ?? command.status}
- </span>
- {typeof command.score === "number" && command.status === "evaluated" && (
- <span className="ml-1.5 tabular-nums">{command.score.toFixed(1)}</span>
- )}
- {detail && <span className="ml-1.5 text-muted-foreground/70">{detail}</span>}
- </p>
- );
- })}
- </div>
- )}
- {commandsError != null && (
- <QueryError
- error={commandsError}
- fallback="Couldn't load command activity."
- onRetry={onCommandsRetry}
- />
- )}
- </Card>
- );
-}
-
-function OptimiserRunPage() {
- const { sort, onSort, sortRows } = useTableSort<
- "order" | "status" | "candidates" | "score" | "created"
- >();
- const { experimentId } = Route.useParams();
- const { projectId } = Route.useSearch();
- const queryClient = useQueryClient();
-
- const experimentQuery = useQuery({
- queryFn: () =>
- apiClient.optimizerExperiments.optimizerExperimentsRetrieve({ id: experimentId }),
- queryKey: ["optimizer-experiment", experimentId],
- refetchInterval: (query) => {
- const status = query.state.data?.status;
- return status && isExperimentLive(status) ? 2_500 : false;
- },
- refetchOnWindowFocus: true,
- });
- const experiment = experimentQuery.data;
- const live = experiment ? isExperimentLive(experiment.status) : false;
-
- const header = (
- <PageHeader
- icon={
- <Icon.optimiserTitle
- aria-hidden
- className="size-6 shrink-0 [image-rendering:pixelated] invert"
- />
- }
- title={experiment?.capabilityName ?? "Experiment"}
- />
- );
-
- const iterationsQuery = useQuery({
- enabled: !!experiment,
- queryFn: () =>
- apiClient.optimizerExperiments.optimizerExperimentsIterationsList({
- id: experimentId,
- pageSize: 100,
- }),
- queryKey: ["experiment-iterations", experimentId],
- refetchInterval: live ? 3_000 : false,
- staleTime: live ? 0 : 30_000,
- });
-
- const commandsQuery = useQuery({
- enabled: !!experiment,
- queryFn: () =>
- apiClient.optimizerExperiments.optimizerExperimentsCommandsList({
- id: experimentId,
- pageSize: 100,
- }),
- queryKey: ["experiment-commands", experimentId],
- refetchInterval: live ? 3_000 : false,
- staleTime: live ? 0 : 30_000,
- });
-
- const cancelMutation = useMutation({
- mutationFn: () =>
- apiClient.optimizerExperiments.optimizerExperimentsCancelCreate({ id: experimentId }),
- onError: (e) => notify.error(e, "Couldn't cancel the experiment"),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ["optimizer-experiment", experimentId] });
- queryClient.invalidateQueries({ queryKey: ["experiment-iterations", experimentId] });
- queryClient.invalidateQueries({ queryKey: ["experiment-commands", experimentId] });
- },
- });
-
- if (experimentQuery.error && !experiment) {
- return (
- <PageShell header={header}>
- <DetailErrorState error={experimentQuery.error} fallback="Couldn't load this experiment." />
- </PageShell>
- );
- }
-
- if (experimentQuery.isLoading || !experiment) {
- return (
- <PageShell header={header}>
- <LoadingState fullPage label="Loading experiment" />
- </PageShell>
- );
- }
-
- const iterations = [...(iterationsQuery.data?.results ?? [])].sort((a, b) => a.order - b.order);
- const commands = commandsQuery.data?.results ?? [];
- const failedCommands = commands.filter((c) => c.status === "failed");
-
- const runType = optimizerRunType(experiment);
- const comparison = runType === "model_comparison";
- const hybrid = runType === "hybrid";
- const recordedScores = experimentScores(experiment);
- const baseline = recordedScores.baseline;
- const comparedModels = optimizerModelIds(experiment);
- const comparisonReport = modelComparisonReport(experiment);
- const comparisonWinner =
- comparisonReport.overallWinner ??
- (comparisonReport.incumbentWins === true
- ? "incumbent"
- : (comparisonReport.selectedWinner ?? null));
- const hybridWinner = hybridWinnerOf(experiment);
-
- const allCandidates = iterations.flatMap((it) => it.candidates ?? []);
- const candidateIterationOrder = new Map(
- iterations.flatMap((it) => (it.candidates ?? []).map((c) => [c.id, it.order]))
- );
- const iterationOrderOf = (candidate: { id: string }): number =>
- candidateIterationOrder.get(candidate.id) ?? -1;
- const highestCandidate = allCandidates
- .filter(
- (candidate) =>
- !candidate.isBaseline &&
- candidate.status === "evaluated" &&
- typeof candidate.score === "number" &&
- Number.isFinite(candidate.score)
- )
- .sort((a, b) => b.score - a.score)[0];
- const best =
- comparison || hybrid
- ? (highestCandidate?.score ?? recordedScores.best)
- : highestScore(recordedScores.best, baseline, highestCandidate?.score);
- const delta = baseline != null && best != null ? best - baseline : recordedScores.delta;
- const improved = delta != null && delta > 0;
-
- // Tie-breaks mirror the backend: comparison crowns the earliest candidate
- // (``max()``), optimize/hybrid the latest iteration (``-score, -iteration__order``).
- const winner = deriveWinner(iterations, {
- best,
- comparison,
- winnerModel: comparison ? comparisonReport.selectedWinner : null,
- });
- const winnerIterationOrder = winner != null ? iterationOrderOf(winner) : null;
- // An incumbent win crowns no model row — the header's "Overall winner" says so.
- const showWinnerBadge =
- winnerIterationOrder != null && !(comparison && comparisonReport.incumbentWins === true);
-
- const chartPoints = iterations.map((it) => ({
- best: it.order === 0 ? (iterationBest(it) ?? baseline) : iterationBest(it),
- iteration: it.order,
- }));
-
- const evaluatedCandidates = allCandidates.filter((c) => c.status === "evaluated").length;
- const winningHarness =
- highestCandidate && comparedModels.length > 0
- ? harnessNumber(highestCandidate.candidateIndex, comparedModels.length)
- : null;
-
- return (
- <PageShell header={header}>
- {experiment.failureReason && (
- <Alert className="flex-col px-3 py-2" variant="destructive">
- <p className="mb-1 inline-flex items-center gap-1.5 text-xs font-semibold text-muted-foreground">
- <Icon.failed className="size-3" />
- Failure reason
- </p>
- <pre className="max-h-48 w-full overflow-auto whitespace-pre-wrap font-mono text-xs text-muted-foreground">
- {experiment.failureReason}
- </pre>
- </Alert>
- )}
-
- <Card className="flex flex-col gap-4 p-4">
- <div className="flex min-w-0 flex-wrap items-center gap-2">
- <EntityRef
- id={experiment.capability}
- kind="capability"
- name={experiment.capabilityName}
- />
- {experiment.dataset && (
- <EntityRef
- id={experiment.dataset}
- kind="dataset"
- name={experiment.datasetName}
- projectId={projectId}
- />
- )}
- {experiment.evalSetName && (
- <Badge
- className="inline-flex max-w-56 gap-1 font-mono text-xs font-medium"
- variant="secondary"
- >
- <Icon.listBox className="size-3 shrink-0 text-muted-foreground" />
- <span className="truncate">{experiment.evalSetName}</span>
- </Badge>
- )}
- <OptimizerRunTypeBadge experiment={experiment} showModelCount />
- </div>
-
- {(comparison || hybrid) && comparedModels.length > 0 && (
- <section className="-mx-4 flex flex-col gap-2 border-t border-border/70 px-4 pt-3">
- <h3 className="text-xs text-muted-foreground">Selected models</h3>
- <div className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-4">
- {comparedModels.map((modelId) => (
- <ModelProviderChip className="w-full" key={modelId} model={modelId} />
- ))}
- </div>
- </section>
- )}
-
- <div className="grid grid-cols-2 gap-x-6 gap-y-4 sm:grid-cols-3 lg:grid-cols-5">
- <HeaderStat label="Baseline score">
- {baseline != null ? baseline.toFixed(1) : "—"}
- </HeaderStat>
- <HeaderStat
- label={
- comparison ? "Best selected model" : hybrid ? "Best tested combination" : "Best score"
- }
- primary
- >
- <span className="inline-flex items-center gap-1.5">
- <span>{best != null ? best.toFixed(1) : "—"}</span>
- {delta != null && <DeltaChip value={delta} />}
- </span>
- </HeaderStat>
- {hybrid && (
- <>
- <HeaderStat label="Best tested model">
- <ModelProviderChip
- compact
- model={highestCandidate?.modelName || highestCandidate?.targetModel || "—"}
- />
- </HeaderStat>
- <HeaderStat label="Best tested code version">
- {winningHarness != null ? `Code version ${winningHarness}` : "—"}
- </HeaderStat>
- <HeaderStat label="Overall winner">
- {hybridWinner === "incumbent"
- ? `Incumbent${baseline != null ? ` (${baseline.toFixed(1)})` : ""}`
- : (hybridWinner ?? "—")}
- </HeaderStat>
- </>
- )}
- {comparison ? (
- <>
- <HeaderStat label="Selected-model winner">
- <span className="max-w-64 truncate font-mono">
- {comparisonReport.selectedWinner ?? "—"}
- </span>
- </HeaderStat>
- <HeaderStat label="Overall winner">
- <span className="max-w-64 truncate font-mono">
- {comparisonWinner === "incumbent" ? "Incumbent" : (comparisonWinner ?? "—")}
- </span>
- </HeaderStat>
- </>
- ) : (
- <HeaderStat label="Iterations">
- {experiment.currentIteration}/{experiment.numIterations}
- </HeaderStat>
- )}
- <HeaderStat label="Candidates evaluated">
- {evaluatedCandidates}/{allCandidates.length || "—"}
- </HeaderStat>
- </div>
- <div
- aria-label="Iteration progress"
- aria-valuemax={100}
- aria-valuemin={0}
- aria-valuenow={
- experiment.numIterations > 0
- ? Math.round((experiment.currentIteration / experiment.numIterations) * 100)
- : 0
- }
- className="h-1.5 overflow-hidden rounded-xs bg-muted"
- role="progressbar"
- >
- <div
- className={cn(
- "h-full rounded-xs transition-all duration-500 motion-reduce:transition-none",
- live ? "bg-primary" : "bg-success"
- )}
- style={{
- width: `${
- experiment.numIterations > 0
- ? Math.min(100, (experiment.currentIteration / experiment.numIterations) * 100)
- : 0
- }%`,
- }}
- />
- </div>
-
- <div className="-mx-4 flex flex-col gap-3 border-t border-border/70 px-4 pt-3">
- <div className="flex items-center gap-2">
- <Icon.chart className="size-4 shrink-0 text-muted-foreground" />
- <h3 className="text-xs leading-none">
- {comparison
- ? "Comparison scores"
- : hybrid
- ? "Code + model scores"
- : "Score over iterations"}
- </h3>
- <span className="truncate text-xs leading-none text-muted-foreground">
- {comparison
- ? "incumbent and best selected model · 0–100"
- : hybrid
- ? "best code + model combination · 0–100"
- : "best candidate per iteration · 0–100"}
- </span>
- </div>
- {chartPoints.some((p) => p.best != null) ? (
- <OptimizerScoreChart baseline={baseline} points={chartPoints} />
- ) : (
- <div className="flex items-center justify-center py-8 text-sm text-muted-foreground">
- No scores yet.
- </div>
- )}
- </div>
-
- <dl className="-mx-4 grid grid-cols-2 gap-x-8 gap-y-3 border-t border-border/70 px-4 pt-3 sm:grid-cols-3 lg:grid-cols-5">
- {!comparison && !hybrid && (
- <>
- <div className="flex flex-col gap-1">
- <dt className="text-xs leading-none text-muted-foreground">
- Candidates / iteration
- </dt>
- <dd className="font-mono text-xs font-medium leading-none tabular-nums">
- {experiment.numCandidatesPerIteration}
- </dd>
- </div>
- <div className="flex flex-col gap-1">
- <dt className="text-xs leading-none text-muted-foreground">Patience</dt>
- <dd className="font-mono text-xs font-medium leading-none tabular-nums">
- {experiment.maxIterationsWithoutImprovement} stalled iterations
- </dd>
- </div>
- </>
- )}
- <div className="flex flex-col gap-1">
- <dt className="text-xs leading-none text-muted-foreground">Time elapsed</dt>
- <dd className="font-mono text-xs font-medium leading-none tabular-nums">
- <RunElapsed experiment={experiment} />
- </dd>
- </div>
- <div className="flex flex-col gap-1">
- <dt className="text-xs leading-none text-muted-foreground">Started</dt>
- <dd className="font-mono text-xs font-medium leading-none tabular-nums">
- <DateTime value={experiment.createdAt} />
- </dd>
- </div>
- {experiment.entrypoint && (
- <div className="flex min-w-0 flex-col gap-1">
- <dt className="text-xs leading-none text-muted-foreground">Entrypoint</dt>
- <dd className="truncate font-mono text-xs font-medium leading-none">
- {experiment.entrypoint}
- </dd>
- </div>
- )}
- </dl>
- </Card>
-
- <section className="flex flex-col gap-3">
- <h3 className={TITLE.section}>Activity</h3>
- {live && <p className="font-mono text-xs text-muted-foreground">/overmind optimise</p>}
- <RunActivity
- best={best}
- cancelPending={cancelMutation.isPending}
- commands={commands}
- commandsError={commandsQuery.error}
- delta={delta}
- experiment={experiment}
- hybridWinner={hybridWinner}
- onCancel={() => cancelMutation.mutate()}
- onCommandsRetry={commandsQuery.refetch}
- runType={runType}
- />
- </section>
-
- <section className="flex flex-col gap-3">
- <h3 className={cn(TITLE.section, "inline-flex items-center gap-1.5")}>
- {comparison ? "Model candidates" : hybrid ? "Code + model candidates" : "Iterations"}
- <CountChip count={iterations.length} />
- </h3>
- {iterationsQuery.isError ? (
- <QueryError
- error={iterationsQuery.error}
- fallback="Couldn't load iterations."
- onRetry={iterationsQuery.refetch}
- />
- ) : iterationsQuery.isLoading && iterations.length === 0 ? (
- <LoadingState />
- ) : iterations.length === 0 ? (
- <div className="flex flex-col items-center justify-center rounded-md border border-dashed border-border py-12">
- <Icon.ai className="mb-3 size-10 text-muted-foreground/50" />
- <p className={cn(PROSE, "max-w-sm text-center text-sm text-muted-foreground")}>
- No iterations yet. <code className="font-mono">/overmind optimise</code> in the
- capability repo.
- </p>
- </div>
- ) : (
- <div className="overflow-auto rounded-md border border-border">
- <Table>
- <TableHeader>
- <TableRow>
- <SortableHeader
- className="px-4"
- label={comparison ? "Models" : "Iteration"}
- onSort={onSort}
- sort={sort}
- sortKey="order"
- />
- <SortableHeader
- className="w-34 px-4 text-center"
- label="Status"
- onSort={onSort}
- sort={sort}
- sortKey="status"
- />
- <SortableHeader
- className="w-26 px-4 text-center"
- label={comparison ? "Models tested" : "Candidates"}
- onSort={onSort}
- sort={sort}
- sortKey="candidates"
- />
- <SortableHeader
- className="w-30 px-4 text-center"
- label="Score"
- onSort={onSort}
- sort={sort}
- sortKey="score"
- />
- <SortableHeader
- className="w-38 px-4 text-center"
- label="Created"
- onSort={onSort}
- sort={sort}
- sortKey="created"
- />
- </TableRow>
- </TableHeader>
- <TableBody>
- {sortRows(iterations, (it, key) =>
- key === "order"
- ? comparison
- ? comparisonIterationLabel(it, comparedModels)
- : it.order
- : key === "status"
- ? it.status
- : key === "candidates"
- ? (it.candidates?.length ?? 0)
- : key === "score"
- ? iterationBest(it)
- : it.createdAt?.getTime()
- ).map((it) => (
- <IterationRow
- baseline={baseline}
- comparedModels={comparedModels}
- comparison={comparison}
- failedCommands={failedCommands}
- hybrid={hybrid}
- iteration={it}
- key={it.id}
- modelCount={comparedModels.length}
- showWinnerBadge={showWinnerBadge && it.order === winnerIterationOrder}
- winnerCandidateId={winner?.id ?? null}
- />
- ))}
- </TableBody>
- </Table>
- </div>
- )}
- </section>
-
- <FinetuningSuggestion
- capabilityId={experiment.capability}
- currentImproved={improved}
- projectId={projectId}
- />
- </PageShell>
- );
-}
diff --git a/frontend/src/routes/_auth/optimiser.index.tsx b/frontend/src/routes/_auth/optimiser.index.tsx
deleted file mode 100644
index 805f0739..00000000
--- a/frontend/src/routes/_auth/optimiser.index.tsx
+++ /dev/null
@@ -1,121 +0,0 @@
-import { createFileRoute, redirect } from "@tanstack/react-router";
-
-import { ExperimentsTable } from "@/components/optimiser/experiments-table";
-import { RunLocallyDialog } from "@/components/optimiser/run-locally-dialog";
-import { ProjectRequiredEmptyState } from "@/components/project-required-empty-state";
-import { Button } from "@/components/ui/button";
-import { Icon } from "@/components/ui/icons";
-import { PageHeader } from "@/components/ui/page-header";
-import { PageShell } from "@/components/ui/page-shell";
-import { featureFlags } from "@/lib/feature-flags";
-import { type OptimiserSearch, optimiserSearchSchema } from "@/lib/schemas";
-
-export const Route = createFileRoute("/_auth/optimiser/")({
- beforeLoad: () => {
- if (!featureFlags.evaluations) throw redirect({ replace: true, to: "/" });
- },
- component: OptimiserPage,
- validateSearch: optimiserSearchSchema,
-});
-
-function OptimiserPage() {
- const search = Route.useSearch();
- const {
- projectId,
- page,
- page_size: pageSize,
- optimize: optimizeParam,
- capabilityId,
- datasetId,
- } = search;
- const navigate = Route.useNavigate();
- // URL state, not local: deep-linked from the workshop rail / capability nudge.
- const dialogOpen = optimizeParam === true;
-
- const clearDialogSearch = () =>
- navigate({
- search: (prev) => ({
- ...prev,
- capabilityId: undefined,
- datasetId: undefined,
- optimize: undefined,
- }),
- });
-
- const openDialog = () =>
- navigate({
- search: (prev) => ({ ...prev, optimize: true }),
- });
-
- const patchSearch = (updates: Partial<OptimiserSearch>) =>
- navigate({
- replace: true,
- resetScroll: false,
- search: (prev) => ({ ...prev, ...updates }),
- });
-
- if (!projectId) {
- return (
- <PageShell
- header={
- <PageHeader
- description="Improve your agent against datasets and evals."
- icon={
- <Icon.optimiserTitle
- aria-hidden
- className="size-6 shrink-0 [image-rendering:pixelated] invert"
- />
- }
- title="Optimiser"
- />
- }
- variant="full"
- >
- <ProjectRequiredEmptyState />
- </PageShell>
- );
- }
-
- return (
- <PageShell
- header={
- <PageHeader
- description="Improve your agent against datasets and evals."
- icon={
- <Icon.optimiserTitle
- aria-hidden
- className="size-6 shrink-0 [image-rendering:pixelated] invert"
- />
- }
- title="Optimiser"
- />
- }
- variant="full"
- >
- <div className="flex min-h-0 flex-1 flex-col">
- <ExperimentsTable
- action={
- <Button onClick={openDialog}>
- <Icon.optimiser /> New run
- </Button>
- }
- filters={search}
- onSearchChange={patchSearch}
- page={page}
- pageSize={pageSize}
- projectId={projectId}
- />
- </div>
-
- <RunLocallyDialog
- capabilityId={capabilityId}
- datasetId={datasetId}
- onOpenChange={(open) => {
- if (!open) clearDialogSearch();
- }}
- open={dialogOpen}
- projectId={projectId}
- />
- </PageShell>
- );
-}
diff --git a/frontend/src/styles.css b/frontend/src/styles.css
index 82f2d934..3208583c 100644
--- a/frontend/src/styles.css
+++ b/frontend/src/styles.css
@@ -157,8 +157,7 @@ code {
/* One masked box with two mask layers, so a single background-color drives
both segments (active rows override --elbow-color). The vertical layer
stops 12px short so the corner reads as pixel steps, not a filled square.
- Shared by sidebar sub-nav (fixed --elbow-h pitch math) and trace details
- (live-measured row centers). */
+ Used by the activity feed and trace details (live-measured row centers). */
.sidebar-elbow::before {
position: absolute;
bottom: 50%;
diff --git a/overbae/admin.py b/overbae/admin.py
index 0b06e2bf..7ed6ebfd 100644
--- a/overbae/admin.py
+++ b/overbae/admin.py
@@ -13,10 +13,6 @@ from overbae.models import (
EvalSet,
Feedback,
ModelRef,
- OptimizerCandidate,
- OptimizerCommand,
- OptimizerExperiment,
- OptimizerIteration,
Project,
ProjectMembership,
SignalEvent,
@@ -33,141 +29,6 @@ from overbae.models import (
class DatasetAdmin(admin.ModelAdmin): ...
[email protected](OptimizerExperiment)
-class OptimizerExperimentAdmin(admin.ModelAdmin):
- list_display = [
- "id",
- "capability",
- "status",
- "current_iteration",
- "num_iterations",
- "created_at",
- ]
- list_filter = ["status"]
- search_fields = ["id", "capability__name"]
- readonly_fields = ["id", "created_at", "updated_at"]
-
-
[email protected](OptimizerIteration)
-class OptimizerIterationAdmin(admin.ModelAdmin):
- list_display = ["id", "experiment", "order", "name", "status", "created_at"]
- list_filter = ["status"]
- search_fields = ["id", "experiment__id"]
- readonly_fields = ["id", "created_at"]
-
-
[email protected](OptimizerCandidate)
-class OptimizerCandidateAdmin(admin.ModelAdmin):
- list_display = [
- "id",
- "iteration",
- "candidate_index",
- "is_baseline",
- "score",
- "status",
- "created_at",
- ]
- list_filter = ["status", "is_baseline"]
- search_fields = ["id", "iteration__id"]
- readonly_fields = ["id", "created_at"]
- actions = ["mark_evaluated"]
-
- @admin.action(description="Mark candidates as evaluated.")
- def mark_evaluated(self, request, queryset):
- updated = queryset.update(status=OptimizerCandidate.Status.EVALUATED)
- self.message_user(request, f"{updated} candidate(s) set to evaluated.")
-
-
[email protected](OptimizerCommand)
-class OptimizerCommandAdmin(admin.ModelAdmin):
- actions = ["mark_pending"]
- list_display = [
- "id",
- "iteration",
- "datapoint_index",
- "status",
- "score",
- "created_at",
- ]
- search_fields = [
- "id",
- "experiment__id",
- "candidate__id",
- "iteration__id",
- "original_trace_id",
- "command",
- "code_path",
- "error",
- ]
- list_filter = [
- "experiment",
- "candidate",
- "iteration",
- "status",
- "trace_type",
- "timeout",
- "created_at",
- ]
- readonly_fields = [
- "id",
- "created_at",
- "updated_at",
- ]
- fieldsets = (
- (
- "Identifiers",
- {
- "fields": [
- "id",
- "experiment",
- "candidate",
- "iteration",
- "datapoint_index",
- ]
- },
- ),
- (
- "Command Details",
- {
- "fields": [
- "command",
- "code_path",
- "trace_type",
- "original_trace_id",
- "timeout",
- "status",
- ]
- },
- ),
- (
- "Results",
- {
- "fields": [
- "input",
- "output",
- "result",
- "score",
- "error",
- ]
- },
- ),
- (
- "Timestamps",
- {
- "fields": [
- "created_at",
- "updated_at",
- ]
- },
- ),
- )
-
- @admin.action(description="Change the status of all selected commands to pending.")
- def mark_pending(self, request, queryset):
- updated = queryset.update(status=OptimizerCommand.Status.PENDING)
- self.message_user(request, f"{updated} command(s) set to pending.")
-
-
@admin.register(User)
class UserAdmin(DjangoUserAdmin):
ordering = ("email",)
@@ -302,22 +163,16 @@ class CapabilityAdmin(admin.ModelAdmin):
),
(
"Source",
- {"fields": ("source_path", "entrypoint_fn", "model", "analyzer_model", "footprint")},
+ {"fields": ("source_path", "entrypoint_fn", "model", "footprint")},
),
(
- "Eval Spec",
+ "Contract",
{
"fields": (
"input_schema",
"output_fields",
"output_schema",
- "structure_weight",
- "total_points",
"tool_config",
- "tool_usage_weight",
- "consistency_rules",
- "optimizable_elements",
- "fixed_elements",
"policy_markdown",
)
},
diff --git a/overbae/api/capabilities.py b/overbae/api/capabilities.py
index 6b4de621..16952698 100644
--- a/overbae/api/capabilities.py
+++ b/overbae/api/capabilities.py
@@ -28,20 +28,6 @@ from overbae.services.capabilities import graph, identity
from overbae.services.capability_prompts import sync_capability_prompts
-class EvalSpecResponseSerializer(serializers.Serializer):
- capability_description = serializers.CharField()
- source_path = serializers.CharField()
- input_schema = serializers.JSONField()
- output_fields = serializers.JSONField()
- structure_weight = serializers.FloatField()
- total_points = serializers.FloatField()
- tool_config = serializers.JSONField()
- tool_usage_weight = serializers.FloatField()
- consistency_rules = serializers.JSONField()
- optimizable_elements = serializers.JSONField()
- fixed_elements = serializers.JSONField()
-
-
class GraphEdgeSerializer(serializers.Serializer):
kind = serializers.ChoiceField(choices=["invokes", "shares_tool"])
source = serializers.CharField()
@@ -99,7 +85,7 @@ class CapabilityViewSet(
queryset = Capability.objects.all()
filterset_class = CapabilityFilter
search_fields = ["name", "slug", "description", "source_path"]
- ordering_fields = ["name", "created_at", "total_points"]
+ ordering_fields = ["name", "created_at"]
lookup_field = "id"
http_method_names = ["get", "post", "patch", "delete", "head", "options"]
@@ -133,28 +119,6 @@ class CapabilityViewSet(
def perform_destroy(self, instance):
instance.set_status(Capability.Status.DELETED)
- @extend_schema(summary="Get capability eval spec", responses={200: EvalSpecResponseSerializer})
- @action(detail=True, methods=["get"])
- def eval_spec(self, request, id=None):
- capability = self.get_object()
- return Response(
- EvalSpecResponseSerializer(
- {
- "capability_description": capability.description,
- "source_path": capability.source_path,
- "input_schema": capability.input_schema,
- "output_fields": capability.output_fields,
- "structure_weight": capability.structure_weight,
- "total_points": capability.total_points,
- "tool_config": capability.tool_config,
- "tool_usage_weight": capability.tool_usage_weight,
- "consistency_rules": capability.consistency_rules,
- "optimizable_elements": capability.optimizable_elements,
- "fixed_elements": capability.fixed_elements,
- }
- ).data
- )
-
@extend_schema(
summary="List the capability's selectable system prompts",
description=(
diff --git a/overbae/api/completions.py b/overbae/api/completions.py
index 441e8be4..cee4ff9b 100644
--- a/overbae/api/completions.py
+++ b/overbae/api/completions.py
@@ -52,7 +52,7 @@ from overbae.services.inference_client import (
InferenceClientError,
get_inference_client,
)
-from overbae.services.model_catalog import estimate_cost, resolve_bare_openrouter_slug
+from overbae.services.model_catalog import estimate_cost
logger = logging.getLogger(__name__)
@@ -147,9 +147,6 @@ def _process_stream_chunk(raw: str, captured: dict[str, Any], include_usage: boo
OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
_OPENROUTER_TIMEOUT = 120
-# Model-comparison runs send this header to reach ANY OpenRouter-served slug;
-OPTIMISER_ROUTING_HEADER = "X-Overmind-Optimiser"
-
def _openrouter_headers() -> dict:
return {
@@ -446,27 +443,7 @@ def chat_completions(request: Request) -> Response | StreamingHttpResponse:
# vLLM knows only the concrete served name, never the caller's alias.
model_id = deployed.model_id
- is_optimiser_run = (
- isinstance(request.auth, APIToken)
- and request.headers.get(OPTIMISER_ROUTING_HEADER, "") == "1"
- )
- routed = model_id
- if deployed is None and is_optimiser_run and settings.OPENROUTER_PROXY_ENABLED:
- if "/" not in routed:
- # A patched capability may send the bare slug it had hardcoded; the routing
- # branch below requires a ``provider/model`` form. Re-attach the provider
- # so the request routes instead of 404ing. Unresolvable names keep the
- # existing DeployedModel lookup / 404 path.
- routed = resolve_bare_openrouter_slug(routed) or routed
- # The ``openrouter/`` namespace is a platform-side alias, not an id
- # OpenRouter serves — strip it so the slug routes upstream.
- routed = routed.removeprefix("openrouter/")
- if (
- deployed is None
- and settings.OPENROUTER_PROXY_ENABLED
- and (is_inference_model(routed) or (is_optimiser_run and "/" in routed))
- ):
- model_id = routed
+ if deployed is None and settings.OPENROUTER_PROXY_ENABLED and is_inference_model(model_id):
if not getattr(settings, "OPENROUTER_API_KEY", None):
return Response(
{
@@ -574,9 +551,7 @@ def chat_completions(request: Request) -> Response | StreamingHttpResponse:
request_id = uuid.uuid4()
call_context = {
"request_id": request_id,
- "source": "application"
- if isinstance(request.auth, APIToken) and not is_optimiser_run
- else "internal",
+ "source": "application" if isinstance(request.auth, APIToken) else "internal",
"requested_model": requested_model,
"started_at": started_at,
}
diff --git a/overbae/api/eval_serializers.py b/overbae/api/eval_serializers.py
index 213e4b4c..9371477d 100644
--- a/overbae/api/eval_serializers.py
+++ b/overbae/api/eval_serializers.py
@@ -398,7 +398,6 @@ class EvalRunSerializer(serializers.ModelSerializer):
cell_info = serializers.SerializerMethodField()
progress = serializers.SerializerMethodField()
origin = serializers.CharField(read_only=True, default="manual")
- optimizer_experiment = serializers.UUIDField(read_only=True, default=None, allow_null=True)
class Meta:
model = EvalRun
@@ -431,7 +430,6 @@ class EvalRunSerializer(serializers.ModelSerializer):
"summary",
"progress",
"origin",
- "optimizer_experiment",
"triggered_by",
"created_at",
"updated_at",
diff --git a/overbae/api/eval_views.py b/overbae/api/eval_views.py
index 8c747d97..b64e1499 100644
--- a/overbae/api/eval_views.py
+++ b/overbae/api/eval_views.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from django.db.models import Case, CharField, Exists, OuterRef, Q, Subquery, Value, When
+from django.db.models import Case, CharField, Exists, OuterRef, Q, Value, When
from django.shortcuts import get_object_or_404
from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_view
from rest_framework import mixins, status, viewsets
@@ -47,7 +47,6 @@ from overbae.models import (
EvalScore,
EvalSet,
FinetuningJobEval,
- OptimizerCandidate,
)
from overbae.services.datasets import rows as row_store
from overbae.services.evaluation_activity import (
@@ -115,8 +114,8 @@ class EvalMatrixViewSet(viewsets.ModelViewSet):
destroy=extend_schema(summary="Delete an eval set"),
)
class EvalSetViewSet(viewsets.ModelViewSet):
- """A named selection of matrix rows. The capability's active set drives the
- optimizer, backtests and training evaluations."""
+ """A named selection of matrix rows. The capability's active set drives live
+ scoring, eval runs and training evaluations."""
serializer_class = EvalSetSerializer
search_fields = ["name", "description"]
@@ -196,9 +195,7 @@ class EvalRunViewSet(
def get_queryset(self):
if getattr(self, "swagger_fake_view", False):
return EvalRun.objects.none()
- candidate = OptimizerCandidate.objects.filter(eval_run=OuterRef("pk"))
origin = Case(
- When(Exists(candidate), then=Value("optimizer")),
When(
Exists(FinetuningJobEval.objects.filter(eval_run=OuterRef("pk"))),
then=Value("finetuning"),
@@ -211,10 +208,7 @@ class EvalRunViewSet(
project_id__in=project_ids_for(self.request.user, self.request.auth)
)
.select_related("dataset__capability", "cell", "model_ref")
- .annotate(
- origin=origin,
- optimizer_experiment=Subquery(candidate.values("experiment_id")[:1]),
- )
+ .annotate(origin=origin)
)
@extend_schema(
diff --git a/overbae/api/optimizer.py b/overbae/api/optimizer.py
deleted file mode 100644
index 2fc915e4..00000000
--- a/overbae/api/optimizer.py
+++ /dev/null
@@ -1,416 +0,0 @@
-from __future__ import annotations
-
-import logging
-
-from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_view
-from rest_framework import serializers, status, viewsets
-from rest_framework.decorators import action
-from rest_framework.exceptions import PermissionDenied
-from rest_framework.response import Response
-
-from overbae.api.scoping import project_ids_for
-from overbae.models import (
- Cell,
- OptimizerCandidate,
- OptimizerCommand,
- OptimizerExperiment,
- OptimizerIteration,
-)
-from overbae.services.datasets import use
-from overbae.services.optimizer_create import create_optimizer_experiment
-
-logger = logging.getLogger(__name__)
-
-
-class OptimizerCommandSerializer(serializers.ModelSerializer):
- class Meta:
- model = OptimizerCommand
- fields = [
- "id",
- "experiment",
- "candidate",
- "iteration",
- "datapoint_index",
- "command",
- "code_path",
- "output",
- "result",
- "score",
- "trace_type",
- "original_trace_id",
- "status",
- "timeout",
- "error",
- "created_at",
- ]
- read_only_fields = fields
-
-
-class OptimizerCandidateSerializer(serializers.ModelSerializer):
- model_name = serializers.SerializerMethodField()
-
- def get_model_name(self, obj) -> str:
- return obj.target_model or obj.experiment._incumbent_model_name()
-
- class Meta:
- model = OptimizerCandidate
- fields = [
- "id",
- "experiment",
- "iteration",
- "candidate_index",
- "target_model",
- "model_name",
- "is_baseline",
- "score",
- "scores",
- "status",
- "code_path",
- "eval_run",
- "created_at",
- ]
- read_only_fields = fields
-
-
-class OptimizerIterationSerializer(serializers.ModelSerializer):
- # Nested so the ``iterations`` action returns the whole tree in one call.
- candidates = OptimizerCandidateSerializer(many=True, read_only=True)
-
- class Meta:
- model = OptimizerIteration
- fields = [
- "id",
- "experiment",
- "order",
- "name",
- "status",
- "scores",
- "patch",
- "eval_run",
- "candidates",
- "created_at",
- ]
- read_only_fields = [
- "id",
- "experiment",
- "order",
- "name",
- "status",
- "scores",
- "patch",
- "eval_run",
- "created_at",
- ]
-
-
-class OptimizerExperimentSerializer(serializers.ModelSerializer):
- # Denormalised labels so the run page needs no per-entity fetch.
- capability_name = serializers.SerializerMethodField()
- dataset_name = serializers.CharField(source="dataset.name", read_only=True, default="")
- eval_set_name = serializers.CharField(source="eval_set.name", read_only=True, default="")
- cell_info = serializers.SerializerMethodField()
-
- def get_capability_name(self, obj) -> str:
- return obj.capability.name if obj.capability_id else ""
-
- def get_cell_info(self, obj) -> dict | None:
- return use.describe(obj.cell if obj.cell_id else None)
-
- class Meta:
- model = OptimizerExperiment
- fields = [
- "id",
- "project",
- "capability",
- "capability_name",
- "dataset_name",
- "eval_set_name",
- "dataset",
- "cell",
- "cell_info",
- "eval_set",
- "triggered_by",
- "entrypoint",
- "code_trigger",
- "mode",
- "model_ids",
- "openrouter_key_source",
- "status",
- "current_iteration",
- "num_iterations",
- "num_candidates_per_iteration",
- "max_iterations_without_improvement",
- "stalled_iterations",
- "command_template",
- "scores",
- "state",
- "failure_reason",
- "created_at",
- "updated_at",
- ]
- read_only_fields = fields
-
-
-class SetCommandTemplateSerializer(serializers.Serializer):
- template = serializers.CharField()
-
-
-class CandidateInputSerializer(serializers.Serializer):
- candidate_index = serializers.IntegerField(min_value=0)
- code_path = serializers.CharField(required=False, default="", allow_blank=True)
- patch = serializers.CharField(required=False, default="", allow_blank=True)
- target_model = serializers.CharField(required=False, default="", allow_blank=True)
- is_baseline = serializers.BooleanField(required=False, default=False)
-
-
-class CreateIterationSerializer(serializers.Serializer):
- order = serializers.IntegerField(min_value=0)
- name = serializers.CharField(required=False, default="", allow_blank=True)
- candidates = CandidateInputSerializer(many=True)
-
-
-class CommandResultInputSerializer(serializers.Serializer):
- candidate_id = serializers.UUIDField()
- datapoint_index = serializers.IntegerField(min_value=0)
- success = serializers.BooleanField(default=True)
- output = serializers.CharField(required=False, default="", allow_blank=True)
- error = serializers.CharField(required=False, default="", allow_blank=True)
- trace_id = serializers.CharField(required=False, default="", allow_blank=True)
- input = serializers.JSONField(required=False, default=None, allow_null=True)
-
-
-class PostResultsSerializer(serializers.Serializer):
- results = CommandResultInputSerializer(many=True)
-
-
-class EvaluateIterationSerializer(serializers.Serializer):
- order = serializers.IntegerField(min_value=0)
-
-
-class OptimizerExperimentCreateSerializer(serializers.ModelSerializer):
- """``perform_create`` fills ``eval_set``/``entrypoint`` from the capability;
- ``dataset`` must be supplied.
- """
-
- cell = serializers.PrimaryKeyRelatedField(
- queryset=Cell.objects.all(), required=False, allow_null=True
- )
-
- class Meta:
- model = OptimizerExperiment
- fields = [
- "capability",
- "dataset",
- "cell",
- "eval_set",
- "entrypoint",
- "code_trigger",
- "mode",
- "model_ids",
- "openrouter_key_source",
- "num_iterations",
- "num_candidates_per_iteration",
- "max_iterations_without_improvement",
- ]
-
-
-@extend_schema_view(
- list=extend_schema(
- parameters=[
- OpenApiParameter(
- name="capability",
- type=OpenApiTypes.UUID,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Only return experiments for this capability.",
- ),
- OpenApiParameter(
- name="project", type=OpenApiTypes.UUID, location=OpenApiParameter.QUERY
- ),
- ]
- )
-)
-class OptimizerExperimentViewSet(viewsets.ModelViewSet):
- serializer_class = OptimizerExperimentSerializer
- lookup_field = "id"
- lookup_value_regex = "[0-9a-f-]{36}"
- http_method_names = ["get", "post", "delete", "head", "options"]
-
- def get_queryset(self):
- if getattr(self, "swagger_fake_view", False):
- return OptimizerExperiment.objects.none()
- qs = OptimizerExperiment.objects.filter(
- project_id__in=project_ids_for(self.request.user, self.request.auth)
- ).select_related("capability", "dataset", "cell", "eval_set")
- project_id = self.request.query_params.get("project")
- if project_id:
- qs = qs.filter(project_id=project_id)
- capability_id = self.request.query_params.get("capability")
- if capability_id:
- qs = qs.filter(capability_id=capability_id)
- return qs
-
- def get_serializer_class(self):
- if self.action == "create":
- return OptimizerExperimentCreateSerializer
- return OptimizerExperimentSerializer
-
- def perform_create(self, serializer):
- capability = serializer.validated_data["capability"]
- allowed_projects = project_ids_for(self.request.user, self.request.auth)
- if str(capability.project_id) not in [str(pid) for pid in allowed_projects]:
- raise PermissionDenied("You do not belong to this capability's project.")
-
- validated = serializer.validated_data
- serializer.instance = create_optimizer_experiment(
- user=self.request.user,
- capability=capability,
- dataset=validated.get("dataset"),
- cell=validated.get("cell"),
- eval_set=validated.get("eval_set"),
- entrypoint=validated.get("entrypoint", ""),
- code_trigger=validated.get("code_trigger", ""),
- mode=validated.get("mode", OptimizerExperiment.Mode.OPTIMIZE),
- model_ids=validated.get("model_ids", []),
- openrouter_key_source=validated.get(
- "openrouter_key_source", OptimizerExperiment.OpenRouterKeySource.PLATFORM
- ),
- num_iterations=validated.get("num_iterations", 5),
- num_candidates_per_iteration=validated.get("num_candidates_per_iteration", 3),
- max_iterations_without_improvement=validated.get(
- "max_iterations_without_improvement", 3
- ),
- )
-
- @extend_schema(responses=OptimizerExperimentSerializer)
- def create(self, request, *args, **kwargs):
- create_serializer = self.get_serializer(data=request.data)
- create_serializer.is_valid(raise_exception=True)
- self.perform_create(create_serializer)
- output = OptimizerExperimentSerializer(
- create_serializer.instance, context=self.get_serializer_context()
- )
- return Response(output.data, status=status.HTTP_201_CREATED)
-
- def _paginated(self, qs, serializer_cls):
- """The generated client expects a ``Paginated*List`` envelope from every
- list-shaped action, so custom actions must paginate too."""
- page = self.paginate_queryset(qs)
- if page is not None:
- return self.get_paginated_response(serializer_cls(page, many=True).data)
- return Response(serializer_cls(qs, many=True).data)
-
- @extend_schema(
- parameters=[
- OpenApiParameter(
- name="status",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Filter commands by status (e.g. 'failed').",
- )
- ],
- responses=OptimizerCommandSerializer(many=True),
- )
- @action(detail=True, methods=["get"])
- def commands(self, request, id=None):
- experiment = self.get_object()
- qs = experiment.commands.all().order_by("created_at")
- status_filter = request.query_params.get("status")
- if status_filter:
- qs = qs.filter(status=status_filter)
- return self._paginated(qs, OptimizerCommandSerializer)
-
- @extend_schema(responses=OptimizerIterationSerializer(many=True))
- @action(detail=True, methods=["get"])
- def iterations(self, request, id=None):
- experiment = self.get_object()
- qs = experiment.iterations.prefetch_related("candidates").order_by("order")
- return self._paginated(qs, OptimizerIterationSerializer)
-
- @extend_schema(responses=OptimizerExperimentSerializer)
- @action(detail=True, methods=["post"])
- def cancel(self, request, id=None):
- experiment = self.get_object()
- experiment.cancel()
- return Response(OptimizerExperimentSerializer(experiment).data)
-
- @extend_schema(request=SetCommandTemplateSerializer, responses=OptimizerExperimentSerializer)
- @action(detail=True, methods=["post"])
- def template(self, request, id=None):
- from overbae.services.optimizer_ledger import set_command_template
-
- experiment = self.get_object()
- ser = SetCommandTemplateSerializer(data=request.data)
- ser.is_valid(raise_exception=True)
- experiment = set_command_template(experiment, ser.validated_data["template"])
- return Response(OptimizerExperimentSerializer(experiment).data)
-
- @extend_schema(request=CreateIterationSerializer, responses=OptimizerIterationSerializer)
- @action(detail=True, methods=["post"], url_path="add-iteration")
- def add_iteration(self, request, id=None):
- from overbae.services.optimizer_ledger import create_iteration
-
- experiment = self.get_object()
- ser = CreateIterationSerializer(data=request.data)
- ser.is_valid(raise_exception=True)
- v = ser.validated_data
- iteration = create_iteration(
- experiment,
- order=v["order"],
- name=v.get("name", ""),
- candidates=v["candidates"],
- )
- return Response(
- OptimizerIterationSerializer(iteration).data,
- status=status.HTTP_201_CREATED,
- )
-
- @extend_schema(
- request=PostResultsSerializer,
- responses={"200": {"type": "object", "properties": {"upserted": {"type": "integer"}}}},
- )
- @action(detail=True, methods=["post"])
- def results(self, request, id=None):
- from overbae.services.optimizer_ledger import post_results
-
- experiment = self.get_object()
- ser = PostResultsSerializer(data=request.data)
- ser.is_valid(raise_exception=True)
- summary = post_results(experiment, [dict(r) for r in ser.validated_data["results"]])
- return Response(summary)
-
- @extend_schema(request=EvaluateIterationSerializer, responses=OptimizerExperimentSerializer)
- @action(detail=True, methods=["post"])
- def evaluate(self, request, id=None):
- from overbae.services.optimizer_ledger import evaluate_iteration
-
- experiment = self.get_object()
- ser = EvaluateIterationSerializer(data=request.data)
- ser.is_valid(raise_exception=True)
- experiment = evaluate_iteration(experiment, ser.validated_data["order"])
- return Response(OptimizerExperimentSerializer(experiment).data)
-
- @extend_schema(responses=OptimizerExperimentSerializer)
- @action(detail=True, methods=["post"])
- def complete(self, request, id=None):
- from overbae.services.optimizer_ledger import complete_experiment
-
- experiment = self.get_object()
- experiment = complete_experiment(experiment)
- return Response(OptimizerExperimentSerializer(experiment).data)
-
-
-class OptimizerCandidateViewSet(viewsets.ReadOnlyModelViewSet):
- serializer_class = OptimizerCandidateSerializer
- lookup_field = "id"
- lookup_value_regex = "[0-9a-f-]{36}"
- http_method_names = ["get", "head", "options"]
-
- def get_queryset(self):
- if getattr(self, "swagger_fake_view", False):
- return OptimizerCandidate.objects.none()
- return OptimizerCandidate.objects.filter(
- experiment__project_id__in=project_ids_for(self.request.user, self.request.auth)
- ).select_related("iteration", "eval_run", "experiment")
diff --git a/overbae/api/otlp.py b/overbae/api/otlp.py
index 30572c83..d8cf3460 100644
--- a/overbae/api/otlp.py
+++ b/overbae/api/otlp.py
@@ -25,7 +25,7 @@ from rest_framework.permissions import IsAuthenticated
from overbae.api import overmind_attrs as oc_attrs
from overbae.api.scoping import project_ids_for
-from overbae.core.utils import safe_float, safe_int, safe_json, safe_json_or_default
+from overbae.core.utils import safe_float, safe_int, safe_json
from overbae.innermind import evidence
from overbae.models import (
APIToken,
@@ -63,10 +63,6 @@ def _get_attr(mapping: dict[str, Any] | None, primary: str, *legacy: str) -> Any
_EMPTY_PARENT_SPAN_ID = b"\x00" * 8
-# Recognises optimize spans that carry no ``overmind.command``; only the root
-# CLI span has that tag.
-
-
def _any_value_to_python(value) -> Any:
kind = value.WhichOneof("value")
match kind:
@@ -344,14 +340,6 @@ def _overmind_tags_from_span(span: Span) -> dict[str, Any]:
return tags
-def _first(tags: dict[str, Any], *keys: str) -> Any:
- for key in keys:
- val = tags.get(key)
- if val:
- return val
- return None
-
-
def _find_existing_capability_for_trace(trace_id: str, project: Project) -> Capability | None:
"""Subprocess-spawned spans inherit W3C ``TRACEPARENT`` but not OTel baggage, so
they carry no capability identity. Reuse is only safe when the trace maps to
@@ -425,148 +413,14 @@ def _resolve_conversation(
return conversation
-def _assign(capability: Capability, field: str, value: Any, *, force: bool) -> bool:
- """Sets *field* only when empty, unless *force*."""
- if value is None or value == "":
+def _record_cli_version(capability: Capability, version: str) -> bool:
+ """The latest span wins, so the Console can flag a capability whose most recent run
+ used an outdated CLI."""
+ version = (version or "")[:20]
+ if not version or capability.cli_version == version:
return False
- cur = getattr(capability, field)
- if (force or not cur) and cur != value:
- setattr(capability, field, value)
- return True
- return False
-
-
-# ``cast`` applies to non-empty values only — an empty container must never
-# overwrite populated state.
-_EVAL_FIELD_TYPES: dict[str, tuple[type, Any]] = {
- "input_schema": (dict, {}),
- "output_fields": (dict, {}),
- "structure_weight": (float, 20.0),
- "total_points": (float, 100.0),
- "tool_config": (dict, {}),
- "tool_usage_weight": (float, 10.0),
- "consistency_rules": (list, []),
- "optimizable_elements": (list, []),
- "fixed_elements": (list, []),
-}
-
-
-def _merge_eval_spec(capability: Capability, spec: dict[str, Any], *, force: bool) -> bool:
- """Apply an ``eval_spec.json``-shaped dict onto Capability columns."""
- dirty = False
-
- for field, (cast, _default) in _EVAL_FIELD_TYPES.items():
- new_val = spec.get(field)
- if new_val is None:
- continue
- current = getattr(capability, field)
-
- # Never wipe populated structured state with an empty container.
- if cast in (dict, list) and current and not new_val:
- continue
- # Without ``force`` we only fill empty fields.
- if not force and cast in (dict, list) and current:
- continue
-
- if cast is float:
- new_val = safe_float(new_val, _default)
- setattr(capability, field, new_val)
- dirty = True
-
- # The SDK's eval_spec.json key is frozen wire format: ``agent_description``.
- desc = spec.get("agent_description") or spec.get("description")
- if isinstance(desc, dict):
- desc = desc.get("purpose") or desc.get("description") or ""
- if isinstance(desc, str) and desc.strip():
- dirty |= _assign(capability, "description", desc.strip(), force=force)
-
- out_schema = spec.get("output_schema")
- if isinstance(out_schema, dict) and out_schema and (force or not capability.output_schema):
- capability.output_schema = out_schema
- dirty = True
-
- return dirty
-
-
-def _apply_overmind_fields(capability: Capability, overmind_tags: dict[str, Any]) -> bool:
- command = overmind_tags.get(oc_attrs.COMMAND)
- # setup/optimize spans carry authoritative spec data — overwrite freely.
- force_eval = command in ("optimize", "setup")
- force_path = force_eval
-
- dirty = False
-
- fn_name = _first(overmind_tags, oc_attrs.SETUP_ENTRYPOINT_FN, oc_attrs.OPTIMIZE_ENTRYPOINT_FN)
-
- if fn_name:
- dirty |= _assign(capability, "entrypoint_fn", fn_name, force=force_path)
-
- # Always overwritten: the latest span wins, so the UI can flag a capability whose
- # most recent run used an outdated CLI.
- cli_version = overmind_tags.get(oc_attrs.CLI_VERSION)
- if cli_version and isinstance(cli_version, str):
- dirty |= _assign(capability, "cli_version", cli_version[:20], force=True)
-
- dirty |= _assign(capability, "model", overmind_tags.get(oc_attrs.SETUP_MODEL), force=force_eval)
- dirty |= _assign(
- capability,
- "analyzer_model",
- _first(overmind_tags, oc_attrs.SETUP_ANALYZER_MODEL, oc_attrs.OPTIMIZE_ANALYZER_MODEL),
- force=force_eval,
- )
-
- eval_raw = _first(overmind_tags, oc_attrs.OPTIMIZE_EVAL_SPEC, oc_attrs.SETUP_EVAL_SPEC)
- if eval_raw:
- spec = safe_json_or_default(eval_raw, {})
- if spec:
- dirty |= _merge_eval_spec(capability, spec, force=force_eval)
-
- policy_md = _first(overmind_tags, oc_attrs.SETUP_POLICY_MARKDOWN)
- if policy_md:
- dirty |= _assign(capability, "policy_markdown", policy_md, force=force_eval)
-
- out_schema = safe_json_or_default(overmind_tags.get(oc_attrs.SETUP_OUTPUT_SCHEMA), None)
- if out_schema and (force_eval or out_schema != capability.output_schema):
- capability.output_schema = out_schema
- dirty = True
-
- in_schema = safe_json_or_default(overmind_tags.get(oc_attrs.SETUP_INPUT_SCHEMA), None)
- if isinstance(in_schema, dict) and in_schema and (force_eval or not capability.input_schema):
- capability.input_schema = in_schema
- dirty = True
-
- consistency = safe_json_or_default(overmind_tags.get(oc_attrs.SETUP_CONSISTENCY_RULES), None)
- if (
- isinstance(consistency, list)
- and consistency
- and (force_eval or not capability.consistency_rules)
- ):
- capability.consistency_rules = consistency
- dirty = True
-
- optimizable = safe_json_or_default(overmind_tags.get(oc_attrs.SETUP_OPTIMIZABLE_ELEMENTS), None)
- if (
- isinstance(optimizable, list)
- and optimizable
- and (force_eval or not capability.optimizable_elements)
- ):
- capability.optimizable_elements = optimizable
- dirty = True
-
- fixed = safe_json_or_default(overmind_tags.get(oc_attrs.SETUP_FIXED_ELEMENTS), None)
- if isinstance(fixed, list) and fixed and (force_eval or not capability.fixed_elements):
- capability.fixed_elements = fixed
- dirty = True
-
- tools_summary = overmind_tags.get(oc_attrs.SETUP_TOOLS_SUMMARY)
- if isinstance(tools_summary, str) and tools_summary.strip():
- dirty |= _assign(capability, "tools_summary", tools_summary, force=force_eval)
-
- decision_logic = overmind_tags.get(oc_attrs.SETUP_DECISION_LOGIC)
- if isinstance(decision_logic, str) and decision_logic.strip():
- dirty |= _assign(capability, "decision_logic", decision_logic, force=force_eval)
-
- return dirty
+ capability.cli_version = version
+ return True
_TOTAL_TOKEN_KEYS = (
@@ -685,8 +539,7 @@ def process_span(span_id: str, project_id: str | None = None):
if capability is None:
capability = _find_existing_capability_for_trace(span.trace_id, project)
if capability is not None:
- overmind_tags[oc_attrs.CLI_VERSION] = span.scope_version
- dirty = _apply_overmind_fields(capability, overmind_tags)
+ dirty = _record_cli_version(capability, span.scope_version)
dirty |= _apply_runtime_summaries(capability, span, overmind_tags)
if dirty:
capability.save()
diff --git a/overbae/api/overmind_attrs.py b/overbae/api/overmind_attrs.py
index 01352e1e..9385b79d 100644
--- a/overbae/api/overmind_attrs.py
+++ b/overbae/api/overmind_attrs.py
@@ -6,10 +6,6 @@ interprets must be added there first and copied here verbatim.
from __future__ import annotations
-COMMAND = "overmind.command"
-CLI_VERSION = "overmind.cli.version"
-
-
STATUS = "overmind.status" # "running" | "success" | "failed" | "cancelled"
ERROR_TYPE = "overmind.error.type"
ERROR_MESSAGE = "overmind.error.message"
@@ -25,120 +21,9 @@ CONVERSATION_ID_LEGACY = "overmind.conversation.id"
CAPABILITY_ID = "overmind.capability.id"
PROJECT_ID = "overmind.project.id"
JOB_ID = "overmind.job.id"
-ITERATION_ID = "overmind.iteration.id"
-EXPERIMENT_ID = "overmind.experiment.id"
CAPABILITY_NAME = "overmind.capability.name"
-INIT_ENV_PATH = "overmind.init.env_path"
-INIT_HAS_OPENAI_KEY = "overmind.init.has_openai_key"
-INIT_HAS_ANTHROPIC_KEY = "overmind.init.has_anthropic_key"
-INIT_HAS_OVERMIND_TOKEN = "overmind.init.has_overmind_token"
-INIT_ANALYZER_MODEL = "overmind.init.analyzer_model"
-INIT_HAS_SYNTHETIC_DATAGEN_MODEL = "overmind.init.has_synthetic_datagen_model"
-
-
-SETUP_FAST = "overmind.setup.fast"
-SETUP_MODEL = "overmind.setup.model"
-SETUP_HAS_POLICY = "overmind.setup.has_policy"
-SETUP_HAS_SEED_DATA = "overmind.setup.has_seed_data"
-SETUP_POLICY_PATH = "overmind.setup.policy_path"
-SETUP_DATA_PATH = "overmind.setup.data_path"
-SETUP_STORAGE_BACKEND = "overmind.setup.storage_backend"
-SETUP_ENTRYPOINT_FN = "overmind.setup.entrypoint_fn"
-SETUP_ANALYZER_MODEL = "overmind.setup.analyzer_model"
-SETUP_PHASE = "overmind.setup.phase"
-SETUP_EVAL_SPEC_FIELD_COUNT = "overmind.setup.eval_spec_field_count"
-SETUP_EVAL_SPEC_HAS_TOOLS = "overmind.setup.eval_spec_has_tools"
-SETUP_EVAL_SPEC_HAS_JUDGE = "overmind.setup.eval_spec_has_judge"
-SETUP_EVAL_SPEC_HAS_POLICY = "overmind.setup.eval_spec_has_policy"
-SETUP_EVAL_SPEC_STRUCTURE_WEIGHT = "overmind.setup.eval_spec_structure_weight"
-SETUP_EVAL_SPEC_TOOL_COUNT = "overmind.setup.eval_spec_tool_count"
-SETUP_EVAL_SPEC_CONSISTENCY_RULE_COUNT = "overmind.setup.eval_spec_consistency_rule_count"
-SETUP_CRITERIA_SOURCE = "overmind.setup.criteria_source"
-SETUP_POLICY_SOURCE = "overmind.setup.policy_source"
-# Newer flows prefer these over the agent_policy_* keys above.
-SETUP_POLICY_MARKDOWN = "overmind.setup.policy_markdown"
-SETUP_EVAL_SPEC = "overmind.setup.eval_spec" # JSON string
-SETUP_PROPOSED_CRITERIA = "overmind.setup.proposed_criteria"
-SETUP_TOOL_ANALYSIS = "overmind.setup.tool_analysis"
-SETUP_INPUT_SCHEMA = "overmind.setup.input_schema"
-SETUP_OUTPUT_SCHEMA = "overmind.setup.output_schema"
-SETUP_CONSISTENCY_RULES = "overmind.setup.consistency_rules"
-SETUP_TOOLS_SUMMARY = "overmind.setup.tools_summary"
-SETUP_DECISION_LOGIC = "overmind.setup.decision_logic"
-SETUP_SCOPE = "overmind.setup.scope"
-SETUP_OPTIMIZABLE_ELEMENTS = "overmind.setup.optimizable_elements"
-SETUP_FIXED_ELEMENTS = "overmind.setup.fixed_elements"
-
-OPTIMIZE_FAST = "overmind.optimize.fast"
-OPTIMIZE_ENTRYPOINT_FN = "overmind.optimize.entrypoint_fn"
-OPTIMIZE_STORAGE_BACKEND = "overmind.optimize.storage_backend"
-OPTIMIZE_ANALYZER_MODEL = "overmind.optimize.analyzer_model"
-OPTIMIZE_LLM_JUDGE_MODEL = "overmind.optimize.llm_judge_model"
-OPTIMIZE_ITERATIONS = "overmind.optimize.iterations"
-OPTIMIZE_CANDIDATES_PER_ITERATION = "overmind.optimize.candidates_per_iteration"
-OPTIMIZE_PARALLEL = "overmind.optimize.parallel"
-OPTIMIZE_MAX_WORKERS = "overmind.optimize.max_workers"
-OPTIMIZE_RUNS_PER_EVAL = "overmind.optimize.runs_per_eval"
-OPTIMIZE_REGRESSION_THRESHOLD = "overmind.optimize.regression_threshold"
-OPTIMIZE_HOLDOUT_RATIO = "overmind.optimize.holdout_ratio"
-OPTIMIZE_HOLDOUT_ENFORCEMENT = "overmind.optimize.holdout_enforcement"
-OPTIMIZE_EARLY_STOPPING_PATIENCE = "overmind.optimize.early_stopping_patience"
-OPTIMIZE_CROSS_RUN_PERSISTENCE = "overmind.optimize.cross_run_persistence"
-OPTIMIZE_FAILURE_CLUSTERING = "overmind.optimize.failure_clustering"
-OPTIMIZE_ADAPTIVE_FOCUS = "overmind.optimize.adaptive_focus"
-OPTIMIZE_MODEL_BACKTESTING = "overmind.optimize.model_backtesting"
-OPTIMIZE_BACKTEST_MODELS = "overmind.optimize.backtest_models"
-OPTIMIZE_EVAL_SPEC_PATH = "overmind.optimize.eval_spec_path"
-OPTIMIZE_DATA_PATH = "overmind.optimize.data_path"
-OPTIMIZE_EVAL_SPEC = "overmind.optimize.eval_spec" # JSON string; refreshes Capability eval fields
-
-OPTIMIZE_PHASE = "overmind.optimize.phase"
-OPTIMIZE_DATASET_TOTAL = "overmind.optimize.dataset_total"
-OPTIMIZE_DATASET_TRAIN = "overmind.optimize.dataset_train"
-OPTIMIZE_DATASET_HOLDOUT = "overmind.optimize.dataset_holdout"
-OPTIMIZE_BASELINE_SCORE = "overmind.optimize.baseline_score"
-OPTIMIZE_ITERATION = "overmind.optimize.iteration"
-OPTIMIZE_TOTAL_ITERATIONS = "overmind.optimize.total_iterations"
-OPTIMIZE_BEST_SCORE_BEFORE = "overmind.optimize.best_score_before"
-OPTIMIZE_STALL_COUNT = "overmind.optimize.stall_count"
-OPTIMIZE_TEMPERATURE = "overmind.optimize.temperature"
-OPTIMIZE_N_CANDIDATES_GENERATED = "overmind.optimize.n_candidates_generated"
-OPTIMIZE_N_CANDIDATES_VALID = "overmind.optimize.n_candidates_valid"
-OPTIMIZE_CANDIDATE_INDEX = "overmind.optimize.candidate_index"
-OPTIMIZE_CANDIDATE_METHOD = "overmind.optimize.candidate_method"
-OPTIMIZE_CANDIDATE_SCORE = "overmind.optimize.candidate_score"
-OPTIMIZE_CANDIDATE_ADJUSTED_SCORE = "overmind.optimize.candidate_adjusted_score"
-OPTIMIZE_COMPLEXITY_PENALTY = "overmind.optimize.complexity_penalty"
-OPTIMIZE_ITERATION_DECISION = "overmind.optimize.iteration_decision"
-OPTIMIZE_ITERATION_SCORE = "overmind.optimize.iteration_score"
-OPTIMIZE_ITERATION_IMPROVEMENT = "overmind.optimize.iteration_improvement"
-OPTIMIZE_ITERATION_REASON = "overmind.optimize.iteration_reason"
-OPTIMIZE_STEP = "overmind.optimize.step"
-OPTIMIZE_RUN_STATUS = "overmind.optimize.run_status"
-# JSON — OTel attributes cannot carry nested dicts.
-OPTIMIZE_ITERATION_DIMENSION_SCORES = "overmind.optimize.iteration_dimension_scores"
-# → JobIteration.agent_code
-OPTIMIZE_ITERATION_AGENT_CODE = "overmind.optimize.iteration_agent_code"
-# JSON list of change summaries → JobIteration.description
-OPTIMIZE_ITERATION_SUGGESTIONS = "overmind.optimize.iteration_suggestions"
-OPTIMIZE_ACCEPTED = "overmind.optimize.accepted"
-OPTIMIZE_FINAL_BEST_SCORE = "overmind.optimize.final_best_score"
-OPTIMIZE_REPORT_MARKDOWN = "overmind.optimize.report_markdown" # → Job.report_markdown
-OPTIMIZE_BEST_AGENT_CODE = "overmind.optimize.best_agent_code" # → Job.best_agent_code
-OPTIMIZE_HOLDOUT_SCORE = "overmind.optimize.holdout_score"
-OPTIMIZE_HOLDOUT_BASELINE_SCORE = "overmind.optimize.holdout_baseline_score"
-OPTIMIZE_HOLDOUT_IMPROVEMENT = "overmind.optimize.holdout_improvement"
-OPTIMIZE_BLENDED_IMPROVEMENT = "overmind.optimize.blended_improvement"
-OPTIMIZE_HOLDOUT_REVERTED = "overmind.optimize.holdout_reverted"
-OPTIMIZE_OVERFIT_GAP = "overmind.optimize.overfit_gap"
-OPTIMIZE_TOTAL_ACCEPTED = "overmind.optimize.total_accepted"
-OPTIMIZE_TOTAL_REJECTED = "overmind.optimize.total_rejected"
-OPTIMIZE_REPORT_IMPROVEMENT = "overmind.optimize.report_improvement"
-OPTIMIZE_BACKTEST_MODEL = "overmind.optimize.backtest_model"
-OPTIMIZE_BACKTEST_SCORE = "overmind.optimize.backtest_score"
-
# Span EVENT names / event-attribute keys, not span attributes; payloads are JSON strings.
EVAL_SCHEMA_VERSION = "overmind.eval.schema_version"
EVAL_PAYLOAD = "overmind.eval.payload"
@@ -152,88 +37,6 @@ EVAL_EVENT_INTENT = "overmind.eval.intent"
PROMPT_TEMPLATE = "overmind.prompt.template"
PROMPT_KWARGS = "overmind.prompt.kwargs" # JSON string
-EVAL_BATCH_SIZE = "overmind.eval.batch_size"
-EVAL_AVG_TOTAL = "overmind.eval.avg_total"
-EVAL_USED_LLM_JUDGE = "overmind.eval.used_llm_judge"
-EVAL_JUDGE_NEEDS_COUNT = "overmind.eval.judge_needs_count"
-EVAL_JUDGE_FAIL_COUNT = "overmind.eval.judge_fail_count"
-EVAL_JUDGE_FAIL_PCT = "overmind.eval.judge_fail_pct"
-EVAL_AVG_CONFIDENCE = "overmind.eval.avg_confidence"
-EVAL_SOURCE_SUMMARY = "overmind.eval.source_summary"
-RUN_AGENT_RUN_NAME = "overmind.run.run_name"
-RUN_AGENT_AGENT_PATH = "overmind.run.agent_path"
-RUN_AGENT_CASES_TOTAL = "overmind.run.cases_total"
-RUN_AGENT_CASES_SUCCEEDED = "overmind.run.cases_succeeded"
-RUN_AGENT_CASES_FAILED = "overmind.run.cases_failed"
-RUN_AGENT_CASES_WITH_PROVENANCE = "overmind.run.cases_with_provenance"
-RUN_AGENT_PARALLEL = "overmind.run.parallel"
-RUN_AGENT_MAX_WORKERS = "overmind.run.max_workers"
-RUN_AGENT_BACKENDS = "overmind.run.backends"
-RUN_AGENT_BACKEND_USED = "overmind.run.backend_used"
-RUN_AGENT_AVG_SCORE = "overmind.run.avg_score"
-RUN_AGENT_DIMENSION_SCORES = "overmind.run.dimension_scores"
-RUN_AGENT_PASS_RATE = "overmind.run.pass_rate"
-RUN_AGENT_DURATION_SECONDS = "overmind.run.duration_seconds"
-RUN_AGENT_PER_CASE_SCORES = "overmind.run.per_case_scores"
-
-RUN_CASE_RUN_NAME = "overmind.run.case.run_name"
-RUN_CASE_INDEX = "overmind.run.case.index"
-RUN_CASE_INPUT_KEYS = "overmind.run.case.input_keys"
-RUN_CASE_INPUT_CHARS = "overmind.run.case.input_chars"
-RUN_CASE_BACKEND_ATTEMPTS = "overmind.run.case.backend_attempts"
-RUN_CASE_BACKENDS_TRIED = "overmind.run.case.backends_tried"
-RUN_CASE_BACKEND_USED = "overmind.run.case.backend_used"
-RUN_CASE_SUCCESS = "overmind.run.case.success"
-RUN_CASE_RETURNCODE = "overmind.run.case.returncode"
-RUN_CASE_ERROR = "overmind.run.case.error"
-RUN_CASE_OUTPUT_CHARS = "overmind.run.case.output_chars"
-RUN_CASE_DURATION_SECONDS = "overmind.run.case.duration_seconds"
-RUN_CASE_PROVENANCE_COUNT = "overmind.run.case.provenance_count"
-RUN_CASE_CONFIDENCE = "overmind.run.case.confidence"
-
-OPTIMIZE_WORKTREE_RUN_NAME = "overmind.optimize.worktree.run_name"
-OPTIMIZE_WORKTREE_ENTRY_PATH = "overmind.optimize.worktree.entry_path"
-OPTIMIZE_WORKTREE_CASES_TOTAL = "overmind.optimize.worktree.cases_total"
-OPTIMIZE_WORKTREE_AVG_SCORE = "overmind.optimize.worktree.avg_score"
-OPTIMIZE_WORKTREE_DIMENSION_SCORES = "overmind.optimize.worktree.dimension_scores"
-OPTIMIZE_WORKTREE_PASS_RATE = "overmind.optimize.worktree.pass_rate"
-OPTIMIZE_WORKTREE_DURATION_SECONDS = "overmind.optimize.worktree.duration_seconds"
-
-RUN_STATE_TOTAL_RUNS = "overmind.run_state.total_runs"
-RUN_STATE_REGRESSION_CASES = "overmind.run_state.regression_cases"
-RUN_STATE_FAILURE_CLUSTERS = "overmind.run_state.failure_clusters"
-RUN_STATE_LATEST_BASELINE = "overmind.run_state.latest_baseline"
-RUN_STATE_LATEST_FINAL = "overmind.run_state.latest_final"
-RUN_STATE_LATEST_ACCEPTED = "overmind.run_state.latest_accepted"
-RUN_STATE_LATEST_REJECTED = "overmind.run_state.latest_rejected"
-
-CANDIDATES_REQUESTED = "overmind.candidates.requested"
-CANDIDATES_PRODUCED = "overmind.candidates.produced"
-CANDIDATES_METHODS = "overmind.candidates.methods"
-CANDIDATES_HAS_DIAGNOSIS = "overmind.candidates.has_diagnosis"
-CANDIDATES_USE_BUNDLE = "overmind.candidates.use_bundle"
-CANDIDATES_HAS_ROOT_CAUSE = "overmind.candidates.has_root_cause"
-CANDIDATES_FALLBACK = "overmind.candidates.fallback"
-
-SEED_VALIDATION_TOTAL_CASES = "overmind.seed_validation.total_cases"
-SEED_VALIDATION_VALID_COUNT = "overmind.seed_validation.valid_count"
-SEED_VALIDATION_INVALID_COUNT = "overmind.seed_validation.invalid_count"
-SEED_COVERAGE_QUALITY_SCORE = "overmind.seed_coverage.quality_score"
-SEED_COVERAGE_CASE_COUNT = "overmind.seed_coverage.case_count"
-SEED_COVERAGE_GAP_COUNT = "overmind.seed_coverage.gap_count"
-SEED_COVERAGE_UNCOVERED_RULE_COUNT = "overmind.seed_coverage.uncovered_rule_count"
-SEED_COVERAGE_SUGGESTED_ADDITIONAL_CASES = "overmind.seed_coverage.suggested_additional_cases"
-
-CODING_AGENT_MODEL = "overmind.coding_agent.model"
-CODING_AGENT_INPUT_FILE_COUNT = "overmind.coding_agent.input_file_count"
-CODING_AGENT_MODIFIED_FILE_COUNT = "overmind.coding_agent.modified_file_count"
-CODING_AGENT_STEPS_TAKEN = "overmind.coding_agent.steps_taken"
-CODING_AGENT_MAX_STEPS = "overmind.coding_agent.max_steps"
-CODING_AGENT_TOKENS_IN = "overmind.coding_agent.tokens_in"
-CODING_AGENT_TOKENS_OUT = "overmind.coding_agent.tokens_out"
-CODING_AGENT_LOOP_STEPS = "overmind.coding_agent.loop_steps"
-CODING_AGENT_EXIT_REASON = "overmind.coding_agent.exit_reason"
-
LLM_MODEL = "genai.model"
LLM_RESPONSE_MODEL = "genai.response.model"
LLM_PROVIDER = "genai.provider"
diff --git a/overbae/api/overwatch_dashboard.py b/overbae/api/overwatch_dashboard.py
index 7d79c450..fcb6d9d3 100644
--- a/overbae/api/overwatch_dashboard.py
+++ b/overbae/api/overwatch_dashboard.py
@@ -196,7 +196,6 @@ class UserActivitySerializer(serializers.Serializer):
traces = TraceActivitySerializer()
inference = InferenceActivitySerializer()
datasets = DatasetActivitySerializer()
- optimizer = WorkflowActivitySerializer()
evaluations = WorkflowActivitySerializer()
diff --git a/overbae/api/serializers.py b/overbae/api/serializers.py
index c22eb599..c3d51a95 100644
--- a/overbae/api/serializers.py
+++ b/overbae/api/serializers.py
@@ -462,14 +462,10 @@ class CapabilityListSerializer(serializers.ModelSerializer):
"model",
"active_model",
"benchmark_model",
- "structure_weight",
- "total_points",
- "tool_usage_weight",
"status",
"observed",
"suggested_name",
"entrypoint_fn",
- "analyzer_model",
"dataset_size",
"dataset_has_expected_output",
"dataset_input_keys",
@@ -676,17 +672,13 @@ class CapabilityFlowSerializer(serializers.Serializer):
class CapabilitySerializer(serializers.ModelSerializer):
activation = ModelActivationSerializer(read_only=True, allow_null=True)
tool_config = serializers.JSONField(required=False, allow_null=True)
- consistency_rules = serializers.JSONField(required=False, allow_null=True)
- optimizable_elements = serializers.JSONField(required=False, allow_null=True)
- fixed_elements = serializers.JSONField(required=False, allow_null=True)
dataset_size = serializers.SerializerMethodField()
flow = serializers.SerializerMethodField()
class Meta:
model = Capability
fields = "__all__"
- # ``slug`` stays immutable: OTLP ingest, optimizer runs and external
- # references resolve by it.
+ # ``slug`` stays immutable: OTLP ingest and external references resolve by it.
read_only_fields = [
"id",
"slug",
@@ -770,17 +762,8 @@ class CapabilitySerializer(serializers.ModelSerializer):
attrs = super().validate(attrs)
# Back-filling defaults on a partial update would clobber JSONB columns
# (a PATCH of ``policy_markdown`` alone would wipe ``tool_config``).
- if self.partial:
- return attrs
- defaults = {
- "tool_config": {},
- "consistency_rules": [],
- "optimizable_elements": [],
- "fixed_elements": [],
- }
- for key, default in defaults.items():
- if attrs.get(key) is None:
- attrs[key] = default.copy() if isinstance(default, (dict, list)) else default
+ if not self.partial and attrs.get("tool_config") is None:
+ attrs["tool_config"] = {}
return attrs
@@ -2517,7 +2500,6 @@ class CatalogModelSerializer(serializers.Serializer):
class ModelDefaultsSerializer(serializers.Serializer):
judge_model = serializers.CharField()
judge_models = serializers.ListField(child=serializers.CharField())
- backtest_models = serializers.ListField(child=serializers.CharField())
class ModelCatalogResponseSerializer(serializers.Serializer):
diff --git a/overbae/core/model_registry.py b/overbae/core/model_registry.py
index ce7ed953..24adadbb 100644
--- a/overbae/core/model_registry.py
+++ b/overbae/core/model_registry.py
@@ -419,14 +419,9 @@ def model_defaults() -> dict[str, object]:
return {
"judge_model": default_judge_model(),
"judge_models": judge_picker_models(),
- "backtest_models": default_backtest_models(),
}
-def default_backtest_models() -> list[str]:
- return [OPENROUTER_MODEL_SLUGS[name] for name in model_chain(TaskType.DEFAULT)[:2]]
-
-
@dataclass(frozen=True)
class Provider:
name: str
diff --git a/overbae/innermind/runs.py b/overbae/innermind/runs.py
index 5414dc82..de01341c 100644
--- a/overbae/innermind/runs.py
+++ b/overbae/innermind/runs.py
@@ -75,30 +75,6 @@ def create_run(*, cell, mode: str, matrix: list[dict], **fields: Any) -> EvalRun
return EvalRun.objects.create(cell=cell, mode=mode, matrix=matrix, params=params, **fields)
-def provide_outputs(run: EvalRun, outputs: dict[int, tuple[Any, str]]) -> None:
- """Posts a ``provided`` run's outputs, ``{row_index: (output, source_trace_id)}``.
- A missing output stays visible as a degraded row."""
- now = timezone.now()
- EvalRunRow.objects.bulk_create(
- [
- EvalRunRow(
- run=run,
- row_index=index,
- source_trace_id=trace_id or "",
- output=output,
- degraded=output is None,
- degraded_reason="no_output: the caller provided no output"
- if output is None
- else "",
- state=EvalRunRow.State.DONE,
- finished_at=now,
- )
- for index, (output, trace_id) in sorted(outputs.items())
- ],
- batch_size=ROW_BATCH,
- )
-
-
def launch(run: EvalRun) -> None:
# tasks.innermind imports this module.
from overbae.tasks.innermind import run_eval_run # noqa: PLC0415
@@ -117,9 +93,7 @@ def launch(run: EvalRun) -> None:
def relaunch(run: EvalRun) -> bool:
- """Re-runs a terminal run from its frozen inputs; a provided run keeps its outputs."""
- if run.mode == EvalRun.Mode.PROVIDED:
- raise RunError("A run with provided outputs cannot be re-launched.")
+ """Re-runs a terminal run from its frozen inputs."""
with transaction.atomic():
if not EvalRun.objects.filter(pk=run.pk, status__in=EvalRun.TERMINAL).update(
status=EvalRun.Status.PENDING,
@@ -143,9 +117,7 @@ def selected_rows(run: EvalRun) -> list[row_store.DatasetRow]:
def seed_rows(run: EvalRun) -> int:
"""Creates the run's rows: recorded outputs are done at once, generated ones wait
- for admission, and provided ones already exist."""
- if run.mode == EvalRun.Mode.PROVIDED:
- return run.rows.count()
+ for admission."""
run.rows.all().delete()
run.scores.all().delete()
now = timezone.now()
@@ -283,15 +255,13 @@ def finish(run: EvalRun, *, where: Q = Q()) -> None:
def on_terminal(run: EvalRun) -> None:
update_task(run.project_id, "eval_run", run.pk, run.status)
- # Both consumers import this module to create their runs.
- from overbae.models.optimizer import on_candidate_eval_finished # noqa: PLC0415
+ # finetuning_eval imports this module to create its runs.
from overbae.services.finetuning_eval import sync_eval_scores # noqa: PLC0415
if run.status == EvalRun.Status.COMPLETED:
comparison.baseline_comparison(run)
for job in FinetuningJob.objects.filter(job_evals__eval_run_id=run.pk).distinct():
sync_eval_scores(job)
- on_candidate_eval_finished(run)
def fail(run_id, reason: str, *, where: Q = Q()) -> bool:
diff --git a/overbae/management/commands/seed_demo.py b/overbae/management/commands/seed_demo.py
index 774954c5..6a29abfa 100644
--- a/overbae/management/commands/seed_demo.py
+++ b/overbae/management/commands/seed_demo.py
@@ -3,7 +3,7 @@
One demo project — Support Copilot at Ledgerline, a fictional payments company — with
thirty days of traffic across three capabilities and every downstream surface filled:
live span and trajectory scores, signal events, datasets with versions and chats, eval
-runs, optimiser runs, training jobs, served models and the credits ledger.
+runs, training jobs, served models and the credits ledger.
Deterministic (seeded RNG, stable ids, timestamps anchored to NOW) and idempotent: a re-run
deletes the project (and the retired Undermind demo, if present) before it seeds. The
@@ -64,10 +64,6 @@ from overbae.models import (
ModelActivation,
ModelRef,
NativeEvaluationPlan,
- OptimizerCandidate,
- OptimizerCommand,
- OptimizerExperiment,
- OptimizerIteration,
Project,
ProjectMembership,
SignalEvent,
@@ -388,63 +384,6 @@ _JUDGE_REASONS = {
"Asks for 'more information' without naming a class.",
],
}
-_COMMAND_TEMPLATE = """uv run python - <<'EOF'
-from support.triage.capability import run_triage
-self.stdout.write(run_triage(**__DATAPOINT_INPUT__))
-EOF
-"""
-_TRIAGE_DIFFS = [
- """diff --git a/support/triage/prompts.py b/support/triage/prompts.py
-index 4c1f2ab..8e9d310 100644
---- a/support/triage/prompts.py
-+++ b/support/triage/prompts.py
-@@ -1,12 +1,18 @@
- SYSTEM_PROMPT = \"\"\"You are Ledgerline's support triage capability.
--Classify the ticket and return strict JSON with urgency, category,
--team and a one-line summary.
-+Process:
-+1. Identify the failure surface (API, dashboard, payouts, billing, fraud).
-+2. Call lookup_merchant; enterprise merchants are never `low` urgency.
-+3. Payment-disruption reports route to oncall-payments; suspected fraud
-+ to risk-ops.
-+4. Summaries never quote card numbers.
-+
-+Return strict JSON matching the schema. Urgency reflects merchant
-+impact, not sentiment.
- \"\"\"
-""",
- """diff --git a/support/triage/prompts.py b/support/triage/prompts.py
-index 4c1f2ab..2b7a914 100644
---- a/support/triage/prompts.py
-+++ b/support/triage/prompts.py
-@@ -1,8 +1,13 @@
- SYSTEM_PROMPT = \"\"\"You are Ledgerline's support triage capability.
--Classify the ticket and return strict JSON with urgency, category,
--team and a one-line summary.
-+Think through the routing before answering:
-+- Which team owns this failure surface?
-+- Does the merchant plan floor the urgency?
-+Return strict JSON with urgency, category, team and a one-line summary.
- \"\"\"
-+
-+FEW_SHOT = [
-+ {"ticket": "Payouts stuck since Monday", "team": "oncall-payments"},
-+]
-""",
- """diff --git a/support/triage/capability.py b/support/triage/capability.py
-index 91c0d44..d02f871 100644
---- a/support/triage/capability.py
-+++ b/support/triage/capability.py
-@@ -41,7 +41,10 @@ def run_triage(ticket_text, merchant_plan="growth", previous_tickets=0):
- merchant = lookup_merchant(merchant_name=extract_merchant(ticket_text))
-- result = llm.chat(SYSTEM_PROMPT, ticket_text)
-+ context = f"plan={merchant_plan} incidents={merchant.open_incidents}"
-+ result = llm.chat(SYSTEM_PROMPT, f"{context}\\n\\n{ticket_text}")
-+ if merchant_plan == "enterprise" and result["urgency"] == "low":
-+ result["urgency"] = "medium"
- return validate(result)
-""",
-]
TRIAGE_GROUP = uuid.uuid5(uuid.NAMESPACE_URL, "seed/ft/group/triage")
MODAL_URL = (
"https://ledgerline--overmind-inference-{worker}-web.modal.run?model={model}&max_model_len=8192"
@@ -712,7 +651,6 @@ class Command(BaseCommand):
):
model.objects.filter(project__slug__in=slugs).delete()
FinetuningJob.objects.filter(project__slug__in=slugs).delete()
- OptimizerExperiment.objects.filter(project__slug__in=slugs).delete()
EvalRun.objects.filter(project__slug__in=slugs).delete()
Project.objects.filter(slug__in=slugs).delete()
for dataset_id in doomed_datasets:
@@ -1468,7 +1406,6 @@ class Command(BaseCommand):
for cap in capabilities:
Capability.objects.filter(pk=cap.pk).update(
cli_version="0.1.55",
- analyzer_model="anthropic/claude-sonnet-5",
created_at=days_ago(DAYS),
updated_at=days_ago(0.2),
)
@@ -3132,7 +3069,7 @@ class Command(BaseCommand):
)
make_eval_run(
name="Triage — prompt v3 verification",
- description="Optimiser winner replayed against the incumbent prompt.",
+ description="Prompt v3 replayed against the incumbent prompt.",
dataset=triage_golden,
eval_set=triage_set,
targets=[
@@ -3200,311 +3137,6 @@ class Command(BaseCommand):
use=False,
)
- # ── Optimiser runs ───────────────────────────────────────────────────────────────
-
- self.stdout.write("Creating optimiser runs...")
-
- def _run_score(run) -> float:
- headline = comparison.headline(run.summary)
- return round(headline * 100, 1) if headline is not None else 0.0
-
- def build_experiment(
- *,
- cap,
- dataset,
- eval_set,
- born,
- done,
- entrypoint,
- baseline_q,
- iteration_qs,
- diffs,
- status="completed",
- num_iterations=None,
- with_eval_runs=False,
- sample_fn=triage_sample,
- mode="optimize",
- model_ids=(),
- ):
- """iteration_qs: per iteration, a list of (quality, target_model) or plain qualities."""
- version = dataset.active_cell
- exp = OptimizerExperiment.objects.create(
- project=project,
- capability=cap,
- dataset=dataset,
- cell=version,
- eval_set=eval_set,
- triggered_by=owner,
- entrypoint=entrypoint,
- code_trigger=f"{entrypoint}(**datapoint)",
- mode=mode,
- model_ids=list(model_ids),
- status=status,
- num_iterations=num_iterations or len(iteration_qs),
- num_candidates_per_iteration=len(iteration_qs[0]) if iteration_qs else 3,
- command_template=_COMMAND_TEMPLATE,
- )
- datapoints = list(row_store.iter_rows(version))
- span_hours = max(4.0, (done - born).total_seconds() / 3600.0)
- total_iters = 1 + len(iteration_qs)
- cmd_pairs, cand_pairs, iter_pairs = [], [], []
-
- def _mk_eval_run(candidate, label, quality, t):
- (run,) = make_eval_run(
- name=f"Optimizer · {cap.name} · {label}",
- description=f"Optimizer experiment {exp.pk}, {label}",
- dataset=dataset,
- eval_set=eval_set,
- targets=[
- (
- label,
- cap.model,
- None,
- EvalRun.Mode.PROVIDED,
- candidate.is_baseline,
- quality,
- )
- ],
- born=t,
- n_samples=len(datapoints),
- sample_fn=sample_fn,
- use=False,
- group=exp.pk,
- params={
- "optimizer_candidate_id": str(candidate.pk),
- "optimizer_mode": mode,
- "target_model": candidate.target_model or cap.model,
- },
- )
- return run
-
- def _commands_for(candidate, iteration, quality, t, trace_type, originals):
- rows, per = [], []
- for idx, dp in enumerate(datapoints):
- score = round(min(100.0, max(5.0, random.gauss(quality * 100, 7.0))), 1)
- per.append(score)
- out = (
- dp.expected_output
- if isinstance(dp.expected_output, dict)
- else {"output": dp.expected_output}
- )
- rows.append(
- OptimizerCommand(
- experiment=exp,
- candidate=candidate,
- iteration=iteration,
- datapoint_index=idx,
- input=dp.input,
- command=exp.command_template.replace(
- "__DATAPOINT_INPUT__", repr(dp.input)
- ),
- output=json.dumps(out)[:400],
- result={
- "output": json.dumps(out)[:400],
- "trace_id": hexid(16),
- "exit_code": 0,
- "duration_ms": random.randint(900, 4200),
- "stdout": "",
- "stderr": "",
- },
- score=score,
- trace_type=trace_type,
- original_trace_id=originals[idx] if originals else "",
- status="evaluated",
- timeout=600,
- )
- )
- OptimizerCommand.objects.bulk_create(rows)
- cmd_pairs.extend((r.pk, t + timedelta(minutes=j * 0.5)) for j, r in enumerate(rows))
- return rows, round(sum(per) / len(per), 1)
-
- def _align(candidate, target, current):
- from django.db.models import F
-
- OptimizerCommand.objects.filter(candidate=candidate).update(
- score=F("score") + (target - current)
- )
-
- t = born + timedelta(minutes=20)
- base_iter = OptimizerIteration.objects.create(
- experiment=exp, order=0, name="Baseline", status="evaluated"
- )
- base_cand = OptimizerCandidate.objects.create(
- experiment=exp,
- iteration=base_iter,
- candidate_index=0,
- code_path="",
- is_baseline=True,
- status="evaluated",
- )
- base_cmds, base_score = _commands_for(
- base_cand, base_iter, baseline_q, t, "original", None
- )
- base_originals = [c.result["trace_id"] for c in base_cmds]
- if with_eval_runs:
- base_run = _mk_eval_run(base_cand, "baseline", baseline_q, t)
- new_score = _run_score(base_run)
- _align(base_cand, new_score, base_score)
- base_score = new_score
- base_cand.eval_run = base_run
- base_cand.score = base_score
- base_cand.save(update_fields=["score", "eval_run"] if with_eval_runs else ["score"])
- base_iter.scores = {"best": base_score}
- base_iter.save(update_fields=["scores"])
- iter_pairs.append((base_iter.pk, t))
- cand_pairs.append((base_cand.pk, t))
-
- scores = {"baseline": base_score, "best": base_score}
- by_model = {}
- stalled = 0
- winner = None
- for i, cand_qs in enumerate(iteration_qs, start=1):
- t = born + timedelta(hours=span_hours * i / total_iters)
- iteration = OptimizerIteration.objects.create(
- experiment=exp, order=i, name=f"Iteration{i}", status="completed"
- )
- iter_pairs.append((iteration.pk, t))
- iter_scores, iter_models = {}, {}
- iter_best_cand, iter_best = None, -1.0
- for ci, spec in enumerate(cand_qs):
- q, target_model = spec if isinstance(spec, tuple) else (spec, "")
- cand = OptimizerCandidate.objects.create(
- experiment=exp,
- iteration=iteration,
- candidate_index=ci,
- code_path="" if target_model else diffs[(i + ci) % len(diffs)],
- target_model=target_model,
- is_baseline=False,
- status="evaluated",
- )
- _, cscore = _commands_for(
- cand,
- iteration,
- q,
- t + timedelta(minutes=5 + ci * 10),
- "replay",
- base_originals,
- )
- if with_eval_runs:
- crun = _mk_eval_run(
- cand, f"candidate {ci}", q, t + timedelta(minutes=5 + ci * 10)
- )
- new_score = _run_score(crun)
- _align(cand, new_score, cscore)
- cscore = new_score
- cand.eval_run = crun
- cand.score = cscore
- if target_model:
- cand.scores = {"coverage_rate": rnd(0.92, 1.0)}
- iter_models[target_model] = cscore
- by_model[target_model] = cscore
- cand.save()
- cand_pairs.append((cand.pk, t + timedelta(minutes=5 + ci * 10)))
- iter_scores[str(cand.pk)] = cscore
- if cscore > iter_best:
- iter_best, iter_best_cand = cscore, cand
- scores[str(i)] = iter_scores
- iteration.scores = {
- "best": iter_best,
- **({"models": iter_models} if iter_models else {}),
- }
- iteration.save(update_fields=["scores"])
- if iter_best > scores["best"] + 1.0:
- scores["best"] = iter_best
- winner = iter_best_cand
- stalled = 0
- else:
- stalled += 1
- if by_model:
- scores["by_model"] = by_model
- scores["models"] = by_model
- exp.scores = scores
- exp.current_iteration = len(iteration_qs)
- exp.stalled_iterations = stalled
- state = {"eval_pending": {}}
- if status == "completed" and winner is not None and mode == "optimize":
- state["winner_score"] = scores["best"]
- state["winner_candidate_id"] = str(winner.pk)
- if mode == "model_comparison" and by_model:
- best_model = max(by_model, key=by_model.get)
- incumbent_wins = base_score >= by_model[best_model]
- state["model_comparison"] = {
- "selected_winner": best_model,
- "selected_winner_score": by_model[best_model],
- "incumbent_score": base_score,
- "overall_winner": "incumbent" if incumbent_wins else best_model,
- "incumbent_wins": incumbent_wins,
- }
- exp.state = state
- exp.save()
- backdate(OptimizerCommand, cmd_pairs)
- backdate(OptimizerCandidate, cand_pairs)
- backdate(OptimizerIteration, iter_pairs)
- OptimizerExperiment.objects.filter(pk=exp.pk).update(created_at=born, updated_at=done)
- return exp, winner
-
- triage_opt_subset = _from_traces(
- triage_capability, "Triage Optimiser Subset", want=12, intent="eval", born=days_ago(12)
- )
- Cell.objects.filter(pk=triage_opt_subset.active_cell.pk).update(used_at=days_ago(12))
- triage_exp, triage_winner = build_experiment(
- cap=triage_capability,
- dataset=triage_opt_subset,
- eval_set=triage_set,
- born=days_ago(12, h=-2),
- done=days_ago(11, h=-3),
- entrypoint="run_triage",
- baseline_q=0.714,
- iteration_qs=[
- [0.75, 0.69, 0.73],
- [0.80, 0.74, 0.76],
- [0.86, 0.78, 0.80],
- [0.83, 0.79, 0.82],
- [0.82, 0.80, 0.84],
- ],
- diffs=_TRIAGE_DIFFS,
- with_eval_runs=True,
- )
- kb_compare_exp, _ = build_experiment(
- cap=kb_capability,
- dataset=kb_golden,
- eval_set=kb_set,
- born=days_ago(6),
- done=days_ago(6, h=-3),
- entrypoint="answer_question",
- baseline_q=0.84,
- iteration_qs=[
- [
- (0.79, "openai/gpt-5.6-terra"),
- (0.86, "google/gemini-3.1-pro-preview"),
- (0.81, "qwen/qwen3.6-235b"),
- ]
- ],
- diffs=[],
- sample_fn=kb_sample,
- mode="model_comparison",
- model_ids=[
- "openai/gpt-5.6-terra",
- "google/gemini-3.1-pro-preview",
- "qwen/qwen3.6-235b",
- ],
- num_iterations=1,
- )
- dispute_cancelled_exp, _ = build_experiment(
- cap=dispute_capability,
- dataset=dispute_golden,
- eval_set=dispute_set,
- born=days_ago(3),
- done=days_ago(3, h=-1.5),
- entrypoint="resolve_dispute",
- baseline_q=0.79,
- iteration_qs=[[0.80, 0.77, 0.81]],
- diffs=_TRIAGE_DIFFS[2:],
- sample_fn=dispute_sample,
- status="cancelled",
- num_iterations=5,
- )
-
# ── Training ─────────────────────────────────────────────────────────────────────
self.stdout.write("Creating training runs...")
@@ -4392,7 +4024,6 @@ class Command(BaseCommand):
("Eval runs", EvalRun.objects.filter(project=project).count()),
("Eval scores", EvalScore.objects.filter(project=project).count()),
("Signal events", SignalEvent.objects.filter(project=project).count()),
- ("Optimiser runs", OptimizerExperiment.objects.filter(project=project).count()),
("Training jobs", FinetuningJob.objects.filter(project=project).count()),
("Deployed models", DeployedModel.objects.filter(project=project).count()),
("Inference calls", InferenceCall.objects.filter(project=project).count()),
diff --git a/overbae/migrations/0066_remove_optimizer.py b/overbae/migrations/0066_remove_optimizer.py
new file mode 100644
index 00000000..6c61cd5c
--- /dev/null
+++ b/overbae/migrations/0066_remove_optimizer.py
@@ -0,0 +1,78 @@
+from django.db import migrations, models
+
+
+def optimizer_feedback_to_other(apps, schema_editor):
+ Feedback = apps.get_model("overbae", "Feedback")
+ Feedback.objects.filter(area="optimizer").update(area="other")
+
+
+def delete_optimizer_eval_runs(apps, schema_editor):
+ # Baseline and candidate runs were optimiser internals; without their experiment
+ # they would read as manual runs. Only the optimiser posted "provided" outputs.
+ EvalRun = apps.get_model("overbae", "EvalRun")
+ Candidate = apps.get_model("overbae", "OptimizerCandidate")
+ Iteration = apps.get_model("overbae", "OptimizerIteration")
+ run_ids = {
+ *Candidate.objects.exclude(eval_run=None).values_list("eval_run_id", flat=True),
+ *Iteration.objects.exclude(eval_run=None).values_list("eval_run_id", flat=True),
+ }
+ EvalRun.objects.filter(models.Q(pk__in=run_ids) | models.Q(mode="provided")).delete()
+
+
+def retire_optimizer_reconciler(apps, schema_editor):
+ # The database scheduler keeps a row for every entry it ever loaded from settings.
+ PeriodicTask = apps.get_model("django_celery_beat", "PeriodicTask")
+ PeriodicTask.objects.using(schema_editor.connection.alias).filter(
+ task="overbae.tasks.optimizer_reconciler.reconcile_optimizer_experiments"
+ ).delete()
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("overbae", "0065_job_leases"),
+ ("django_celery_beat", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.RunPython(optimizer_feedback_to_other, migrations.RunPython.noop),
+ migrations.RunPython(retire_optimizer_reconciler, migrations.RunPython.noop),
+ migrations.RunPython(delete_optimizer_eval_runs, migrations.RunPython.noop),
+ migrations.AlterField(
+ model_name="feedback",
+ name="area",
+ field=models.CharField(
+ choices=[
+ ("setup", "Setup and connection"),
+ ("observability", "Observability"),
+ ("datasets", "Datasets"),
+ ("evaluation", "Evaluation"),
+ ("training", "Training"),
+ ("serving", "Serving"),
+ ("billing", "Billing"),
+ ("other", "Other"),
+ ],
+ default="other",
+ max_length=16,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="evalrun",
+ name="mode",
+ field=models.CharField(
+ choices=[("recorded", "Recorded"), ("generate", "Generate")],
+ default="recorded",
+ max_length=16,
+ ),
+ ),
+ migrations.DeleteModel(name="OptimizerCommand"),
+ migrations.DeleteModel(name="OptimizerCandidate"),
+ migrations.DeleteModel(name="OptimizerIteration"),
+ migrations.DeleteModel(name="OptimizerExperiment"),
+ migrations.RemoveField(model_name="capability", name="analyzer_model"),
+ migrations.RemoveField(model_name="capability", name="consistency_rules"),
+ migrations.RemoveField(model_name="capability", name="fixed_elements"),
+ migrations.RemoveField(model_name="capability", name="optimizable_elements"),
+ migrations.RemoveField(model_name="capability", name="structure_weight"),
+ migrations.RemoveField(model_name="capability", name="tool_usage_weight"),
+ migrations.RemoveField(model_name="capability", name="total_points"),
+ ]
diff --git a/overbae/models/__init__.py b/overbae/models/__init__.py
index 53ac7cfa..4911b9f3 100644
--- a/overbae/models/__init__.py
+++ b/overbae/models/__init__.py
@@ -69,12 +69,6 @@ from .innermind import (
from .mcp_oauth import MCPOAuthClient, MCPOAuthGrant, MCPOAuthToken
from .mcp_operations import EvalMatrixRevision, MCPMutation
from .operations import InferenceRequest, OperationalEvent, OperationalRun
-from .optimizer import (
- OptimizerCandidate,
- OptimizerCommand,
- OptimizerExperiment,
- OptimizerIteration,
-)
from .traces import Conversation, Span
from .training_monitoring import TrainingCheckpoint, TrainingValidationRun
from .training_plan import TrainingPlan
@@ -138,10 +132,6 @@ __all__ = [
"DatasetContext",
"Conversation",
"Span",
- "OptimizerExperiment",
- "OptimizerIteration",
- "OptimizerCandidate",
- "OptimizerCommand",
"Prompt",
"Feedback",
"FinetuningJob",
diff --git a/overbae/models/capabilities.py b/overbae/models/capabilities.py
index ef7cc17b..c4f1582e 100644
--- a/overbae/models/capabilities.py
+++ b/overbae/models/capabilities.py
@@ -35,7 +35,6 @@ class Capability(models.Model):
source_path = models.CharField(max_length=512, blank=True, default="")
entrypoint_fn = models.CharField(max_length=255, blank=True, default="")
model = models.CharField(max_length=128, blank=True, default="")
- analyzer_model = models.CharField(max_length=128, blank=True, default="")
cli_version = models.CharField(max_length=20, blank=True, default="unknown")
status = models.CharField(
@@ -48,18 +47,10 @@ class Capability(models.Model):
# scores candidates against it instead of re-deriving from the row.
footprint = models.JSONField(default=dict, blank=True)
- # Eval spec flattened from the SDK's eval_spec.json; these columns feed the
- # optimizer and the eval_spec endpoint.
input_schema = models.JSONField(default=dict, blank=True)
output_fields = models.JSONField(default=dict, blank=True)
output_schema = models.JSONField(default=dict, blank=True)
- structure_weight = models.FloatField(default=20.0)
- total_points = models.FloatField(default=100.0)
tool_config = models.JSONField(default=dict, blank=True)
- tool_usage_weight = models.FloatField(default=10.0)
- consistency_rules = models.JSONField(default=list, blank=True)
- optimizable_elements = models.JSONField(default=list, blank=True)
- fixed_elements = models.JSONField(default=list, blank=True)
policy_markdown = models.TextField(blank=True, default="")
tools_summary = models.TextField(blank=True, default="")
decision_logic = models.TextField(blank=True, default="")
diff --git a/overbae/models/feedback.py b/overbae/models/feedback.py
index b6b11a77..ec0f80f6 100644
--- a/overbae/models/feedback.py
+++ b/overbae/models/feedback.py
@@ -27,7 +27,6 @@ class Feedback(models.Model):
OBSERVABILITY = "observability", "Observability"
DATASETS = "datasets", "Datasets"
EVALUATION = "evaluation", "Evaluation"
- OPTIMIZER = "optimizer", "Optimiser"
TRAINING = "training", "Training"
SERVING = "serving", "Serving"
BILLING = "billing", "Billing"
diff --git a/overbae/models/innermind.py b/overbae/models/innermind.py
index 7577cccb..cda976ee 100644
--- a/overbae/models/innermind.py
+++ b/overbae/models/innermind.py
@@ -138,7 +138,7 @@ class EvalMatrix(models.Model):
class EvalSet(models.Model):
- """``Capability.active_eval_set`` drives the optimizer, backtest and training defaults."""
+ """``Capability.active_eval_set`` drives the live scoring, eval run and training defaults."""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
project = models.ForeignKey(
@@ -200,8 +200,6 @@ class EvalRun(models.Model):
RECORDED = "recorded"
# A model generates each row's output.
GENERATE = "generate"
- # The caller posts each row's output before scoring.
- PROVIDED = "provided"
TERMINAL = (Status.COMPLETED, Status.FAILED, Status.CANCELLED)
diff --git a/overbae/models/optimizer.py b/overbae/models/optimizer.py
deleted file mode 100644
index b2786ade..00000000
--- a/overbae/models/optimizer.py
+++ /dev/null
@@ -1,1029 +0,0 @@
-# ruff: noqa: UP037
-"""Capability optimizer: experiment / iteration / candidate scoring.
-
-The client posts candidates and datapoint outputs. Server runs EvalRuns and
-records scores. ``run_experiment_advance`` only drives EVALUATING_* wait-states.
-"""
-
-from __future__ import annotations
-
-import json
-import logging
-import uuid
-
-from celery import shared_task
-from django.conf import settings
-from django.db import models, transaction
-
-logger = logging.getLogger(__name__)
-
-MIN_ITERATION_IMPROVEMENT = 1.0
-
-
-def _normalise_model_id(value) -> str:
- """Normalize OpenRouter's optional namespace without dropping provider identity."""
- return str(value or "").strip().lower().removeprefix("openrouter/")
-
-
-def _model_ids_match(expected: str, observed: str) -> bool:
- expected = _normalise_model_id(expected)
- observed = _normalise_model_id(observed)
- return expected == observed or (
- "/" in expected and "/" not in observed and expected.rsplit("/", 1)[-1] == observed
- )
-
-
-def _telemetry_values(payload, names: tuple[str, ...]) -> list[str]:
- """Collect scalar telemetry values from a nested result payload, in walk order."""
- values: list[str] = []
- if isinstance(payload, dict):
- for key, value in payload.items():
- key_norm = str(key).lower().replace("-", "_").replace(".", "_")
- if key_norm in names and isinstance(value, (str, int, float)) and str(value).strip():
- values.append(str(value).strip())
- else:
- values.extend(_telemetry_values(value, names))
- elif isinstance(payload, (list, tuple)):
- for value in payload:
- values.extend(_telemetry_values(value, names))
- return values
-
-
-def _telemetry_value(payload, names: tuple[str, ...]) -> str:
- """The first scalar telemetry value in a nested result payload, or ``""``."""
- return next(iter(_telemetry_values(payload, names)), "")
-
-
-def optimizer_dataset_error(capability, dataset, cell=None) -> str | None:
- """Why ``dataset`` can't drive an optimizer run for ``capability`` — None if it can.
-
- The gate for both create doors. It checks the version's contracts, not the
- entrypoint signature; a wrong signature still surfaces at the smoke test.
- """
- from overbae.services.datasets import use # noqa: PLC0415 — avoid import cycle
- from overbae.services.datasets.lifecycle import DatasetError # noqa: PLC0415
-
- if dataset is None:
- return "No dataset given."
- if dataset.project_id != capability.project_id:
- return "This dataset belongs to a different project."
- try:
- use.check(dataset, "eval", cell=cell)
- except DatasetError as exc:
- return exc.detail
- return None
-
-
-def _usable_output(command) -> str:
- """A command's gradeable output, or ``""`` when it failed or produced nothing.
-
- Callers keep these out of judge calls and out of the score mean: an execution
- error is not a model score, and one timeout must not become a zero.
- """
- if command.status == OptimizerCommand.Status.FAILED:
- return ""
- result = command.result if isinstance(command.result, dict) else {}
- output = result.get("output") or command.output or ""
- if not isinstance(output, str):
- output = json.dumps(output, default=str, ensure_ascii=False)
- return "" if output.strip() in {"", "-"} else output
-
-
-def _coverage(commands_by_index: dict, total_datapoints: int) -> dict:
- """Which datapoints produced gradeable output, and why others did not."""
- errors: list[str] = []
- scored = 0
- for index in range(total_datapoints):
- command = commands_by_index.get(index)
- if command is None:
- errors.append(f"datapoint {index}: no command output")
- elif _usable_output(command):
- scored += 1
- elif command.status == OptimizerCommand.Status.FAILED:
- errors.append(command.error[:500] or f"datapoint {index}: execution failed")
- else:
- errors.append(f"datapoint {index}: empty output")
- total_rows = total_datapoints
- return {
- "excluded_commands": total_rows - scored,
- "errors": errors[:10],
- "scored_rows": scored,
- "graded_rows": total_rows,
- "total_rows": total_rows,
- "coverage_rate": scored / total_rows if total_rows else 0.0,
- }
-
-
-def candidate_comparison_rank(candidate) -> tuple[float, float, int]:
- """Lexicographic rank for model-comparison winner selection."""
- scores = candidate.scores or {}
- coverage = scores.get("coverage") or {}
- coverage_rate = float(
- scores.get("coverage_rate")
- if scores.get("coverage_rate") is not None
- else coverage.get("coverage_rate") or 0.0
- )
- excluded = int(coverage.get("excluded_commands") or 0)
- return (candidate.score, coverage_rate, -excluded)
-
-
-class OptimizerExperiment(models.Model):
- """Orchestrates the optimization run; ``status`` is a coarse rollup of children."""
-
- class Mode(models.TextChoices):
- OPTIMIZE = "optimize"
- MODEL_COMPARISON = "model_comparison"
- HYBRID = "hybrid", "Harness + Models"
-
- class Status(models.TextChoices):
- SCHEDULED = "scheduled"
- BASELINE = "baseline"
- # Wait-states: the FSM parks in EVALUATING_* while an iteration's EvalRuns
- # grade on the worker, and ``on_candidate_eval_finished`` moves it to
- # EVALUATED_*.
- EVALUATING_BASELINE_OUTPUTS = "evaluating_baseline_outputs"
- EVALUATED_BASELINE_OUTPUTS = "evaluated_baseline_outputs"
- ITERATING = "iterating"
- EVALUATING_CANDIDATE_OUTPUTS = "evaluating_candidate_outputs"
- EVALUATED_CANDIDATE_OUTPUTS = "evaluated_candidate_outputs"
- COMPLETED = "completed"
- FAILED = "failed"
- CANCELLED = "cancelled"
- PAUSED = "paused"
-
- TERMINAL = (Status.COMPLETED, Status.FAILED, Status.CANCELLED)
-
- class OpenRouterKeySource(models.TextChoices):
- PLATFORM = "platform", "Overmind credits"
- LOCAL = "local", "Local .env"
-
- id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
- project = models.ForeignKey(
- "overbae.Project", on_delete=models.CASCADE, related_name="optimizer_experiments"
- )
- capability = models.ForeignKey(
- "overbae.Capability", on_delete=models.CASCADE, related_name="optimizer_experiments"
- )
- dataset = models.ForeignKey(
- "overbae.Dataset",
- on_delete=models.SET_NULL,
- null=True,
- blank=True,
- related_name="optimizer_experiments",
- )
- # The cell whose rows ``datapoint_index`` counts into.
- cell = models.ForeignKey(
- "overbae.Cell",
- on_delete=models.PROTECT,
- null=True,
- blank=True,
- related_name="optimizer_experiments",
- )
- # Defaults to the capability's ``active_eval_set`` at create time and is pinned
- # here, so activating a different set cannot rewrite an in-flight
- # experiment's graders.
- eval_set = models.ForeignKey(
- "overbae.EvalSet",
- on_delete=models.SET_NULL,
- null=True,
- blank=True,
- related_name="optimizer_experiments",
- )
- triggered_by = models.ForeignKey(
- settings.AUTH_USER_MODEL,
- on_delete=models.SET_NULL,
- null=True,
- blank=True,
- related_name="+",
- )
- entrypoint = models.CharField(max_length=512, blank=True, default="")
- code_trigger = models.TextField(blank=True, default="")
- mode = models.CharField(max_length=32, choices=Mode.choices, default=Mode.OPTIMIZE)
- model_ids = models.JSONField(default=list, blank=True)
- # Model-access trust boundary: ``platform`` routes completions through
- # Overmind's gateway on the client's ``OVERMIND_API_KEY``; ``local``
- # leaves the OpenRouter key in the client's own process env.
- openrouter_key_source = models.CharField(
- max_length=16,
- choices=OpenRouterKeySource.choices,
- default=OpenRouterKeySource.PLATFORM,
- )
-
- status = models.CharField(max_length=40, choices=Status.choices, default=Status.SCHEDULED)
- current_iteration = models.IntegerField(default=0)
- num_iterations = models.IntegerField(default=5)
- num_candidates_per_iteration = models.IntegerField(default=3)
- max_iterations_without_improvement = models.IntegerField(default=3)
- scores = models.JSONField(default=dict, blank=True)
- # Token-parameterised shell script, shared by every iteration so codegen runs
- # once per experiment.
- command_template = models.TextField(blank=True, default="")
- stalled_iterations = models.IntegerField(default=0)
- # winner_score, eval_pending, model_comparison, …
- state = models.JSONField(default=dict, blank=True)
- failure_reason = models.TextField(blank=True, default="")
- created_at = models.DateTimeField(auto_now_add=True)
- updated_at = models.DateTimeField(auto_now=True)
-
- class Meta:
- ordering = ["-created_at"]
-
- def generate_next(self):
- """Score posted outputs. The client owns codegen, smoke, and datapoint runs."""
- S = self.Status # noqa: N806
-
- if self.status == S.EVALUATING_BASELINE_OUTPUTS:
- if not self._iteration_eval_pending(0):
- self.start_iteration_eval(0)
- return
-
- if self.status == S.EVALUATING_CANDIDATE_OUTPUTS:
- # The ledger bumps current_iteration to the order under evaluation before
- # the evals finish, so current_iteration+1 points past it — derive the
- # order from the newest iteration row instead.
- active = self.iterations.exclude(order=0).order_by("-order").first()
- if active is None:
- return
- if not self._iteration_eval_pending(active.order):
- self.start_iteration_eval(active.order)
- return
-
- def advance(self):
- """Drive scoring wait-states until parked on the client or done."""
- for _ in range(10_000):
- before = (self.status, self.current_iteration)
- self.generate_next()
- if (self.status, self.current_iteration) == before:
- return
-
- def _stop_children(self, *, reason: str) -> None:
- """Fail in-flight commands/candidates/iterations so nothing keeps running them."""
- OptimizerCommand.objects.filter(
- experiment=self,
- status__in=[OptimizerCommand.Status.PENDING, OptimizerCommand.Status.RUNNING],
- ).update(status=OptimizerCommand.Status.FAILED, error=reason)
-
- OptimizerCandidate.objects.filter(
- experiment=self,
- status__in=[
- OptimizerCandidate.Status.PENDING,
- OptimizerCandidate.Status.RUNNING_COMMANDS,
- OptimizerCandidate.Status.COMMANDS_DONE,
- OptimizerCandidate.Status.EVALUATING,
- ],
- ).update(status=OptimizerCandidate.Status.FAILED)
-
- OptimizerIteration.objects.filter(
- experiment=self,
- status__in=[
- OptimizerIteration.Status.PENDING,
- OptimizerIteration.Status.GENERATING_CANDIDATES,
- OptimizerIteration.Status.GENERATED_CANDIDATES,
- OptimizerIteration.Status.RUNNING_COMMANDS,
- OptimizerIteration.Status.EVALUATING,
- ],
- ).update(status=OptimizerIteration.Status.FAILED)
-
- def _fail(self, reason: str) -> None:
- """Park the experiment in FAILED and stop every in-flight child."""
- with transaction.atomic():
- self._stop_children(reason=reason)
- self.failure_reason = (reason or "").strip()[:2000]
- self.status = self.Status.FAILED
- self.save(update_fields=["failure_reason", "status", "updated_at"])
- # Activity imports models; defer this dependency until runtime.
- from overbae.services.activity import update_task
-
- update_task(self.project_id, "optimizer_experiment", self.pk, "failed")
-
- def _lock_unless_terminal(self) -> bool:
- """Take the row lock inside the caller's transaction; False once the run has ended."""
- locked = type(self).objects.select_for_update().get(pk=self.pk)
- for field in self._meta.concrete_fields:
- setattr(self, field.attname, getattr(locked, field.attname))
- return self.status not in self.TERMINAL
-
- def cancel(self):
- with transaction.atomic():
- if not self._lock_unless_terminal():
- return
- self._stop_children(reason="experiment cancelled")
- self.status = self.Status.CANCELLED
- self.save(update_fields=["status", "updated_at"])
- # Activity imports models; defer this dependency until runtime.
- from overbae.services.activity import update_task
-
- update_task(self.project_id, "optimizer_experiment", self.pk, "cancelled")
-
- def _record_baseline_scores(self, iteration: OptimizerIteration):
- best = max((c.score for c in iteration.candidates.all()), default=0.0)
- self.scores["baseline"] = best
- self.scores["best"] = best
-
- def _record_eval_scores(self, iteration: OptimizerIteration) -> None:
- """Model comparison never folds order=0 as an incumbent baseline."""
- if self.mode == self.Mode.MODEL_COMPARISON or iteration.order != 0:
- self._record_iteration_scores(iteration)
- else:
- self._record_baseline_scores(iteration)
-
- def _incumbent_model_name(self) -> str:
- """Stable display identity for the model used by the unchanged baseline."""
- active = getattr(self.capability, "active_model", None)
- return (
- (getattr(active, "model_id", "") if active is not None else "")
- or getattr(self.capability, "model", "")
- or "Incumbent model"
- )
-
- def _harness_index(self, candidate: OptimizerCandidate) -> int:
- """1-based harness round of a hybrid candidate; models fan out within a round."""
- return candidate.candidate_index // max(len(self.model_ids), 1) + 1
-
- def _candidate_label(self, candidate: OptimizerCandidate) -> tuple[str, str]:
- """The eval variant's (human label, model card identity)."""
- model_name = candidate.target_model or self._incumbent_model_name()
- if candidate.is_baseline:
- return "Baseline", model_name
- if self.mode == self.Mode.MODEL_COMPARISON:
- return model_name, model_name
- if self.mode == self.Mode.HYBRID:
- return f"Candidate {self._harness_index(candidate)} · {model_name}", model_name
- return f"Candidate {candidate.candidate_index + 1}", model_name
-
- def start_iteration_eval(self, iteration_order: int) -> None:
- """Kick off grading for every candidate in one iteration, one
- :class:`EvalRun` each so they list separately on the evals page.
-
- The experiment parks in ``EVALUATING_*`` until the runs finish, or fails
- when there is nothing to score.
- """
- from overbae.innermind import runs # noqa: PLC0415 — innermind imports these models
-
- iteration = OptimizerIteration.objects.get(experiment=self, order=iteration_order)
- candidates = list(iteration.candidates.all())
-
- pending = dict(self.state.get("eval_pending", {}))
- to_dispatch: list[tuple] = []
-
- for candidate in candidates:
- run = self.build_candidate_eval_run(candidate)
- if run is None:
- continue
- pending[str(candidate.id)] = str(run.id)
- to_dispatch.append((candidate, run))
-
- if not to_dispatch:
- self._fail("Nothing to score: the eval set has no rows or the dataset is empty.")
- return
-
- # Persist the pending markers BEFORE dispatch so eager Celery callbacks
- # can clear them; saving after dispatch re-stamps already-finished
- # candidates as pending.
- self.state["eval_pending"] = pending
- self.save(update_fields=["state", "updated_at"])
-
- for _candidate, run in to_dispatch:
- runs.launch(run)
-
- def _iteration_eval_pending(self, iteration_order: int) -> bool:
- iteration = OptimizerIteration.objects.filter(
- experiment=self, order=iteration_order
- ).first()
- if iteration is None:
- return False
- pending = self.state.get("eval_pending") or {}
- return any(str(c.id) in pending for c in iteration.candidates.all())
-
- def on_iteration_eval_complete(self, iteration_order: int) -> None:
- """Finalise iteration scores once every candidate eval run has finished.
-
- Called by :func:`on_candidate_eval_finished` after the last
- candidate clears its pending marker.
- """
- with transaction.atomic():
- if not self._lock_unless_terminal():
- return
- iteration = OptimizerIteration.objects.get(experiment=self, order=iteration_order)
- self._record_eval_scores(iteration)
- if iteration_order > 0:
- self.current_iteration = max(self.current_iteration, iteration_order)
- self.status = (
- self.Status.EVALUATED_BASELINE_OUTPUTS
- if iteration_order == 0
- else self.Status.EVALUATED_CANDIDATE_OUTPUTS
- )
- self.save()
-
- def build_candidate_eval_run(self, candidate: OptimizerCandidate):
- """One ``provided`` :class:`EvalRun` per candidate, carrying each command's
- output. Every candidate of the experiment shares the experiment's group, so
- each is compared row by row against the baseline. ``None`` when there is
- nothing to score.
- """
- from overbae.innermind import runs # noqa: PLC0415 — innermind imports these models
- from overbae.models import EvalRun # noqa: PLC0415 — avoid model import cycle
- from overbae.services.datasets import rows as row_store # noqa: PLC0415
-
- eval_set = self.eval_set or self.capability.active_eval_set
- first = EvalRun.objects.filter(group=self.id).order_by("created_at").first()
- matrix = (
- first.matrix
- if first
- else runs.freeze_matrix(eval_set=eval_set, capability=self.capability)
- )
- if not matrix or self.cell_id is None:
- return None
- datapoints = list(row_store.iter_rows(self.cell))
- if not datapoints:
- return None
-
- commands = {cmd.datapoint_index: cmd for cmd in candidate.commands.all()}
- outputs: dict[int, tuple[str | None, str]] = {}
- for d_index, datapoint in enumerate(datapoints):
- command = commands.get(d_index)
- output = ""
- trace_id = ""
- if command is not None:
- result = command.result or {}
- if command.status != OptimizerCommand.Status.FAILED:
- telemetry_error = command._telemetry_error(result)
- if telemetry_error:
- command.status = OptimizerCommand.Status.FAILED
- command.error = telemetry_error
- command.result = result
- command.save(update_fields=["status", "error", "result", "updated_at"])
- elif result.get("telemetry_missing") or result.get("telemetry"):
- command.result = result
- command.save(update_fields=["result", "updated_at"])
- output = _usable_output(command)
- trace_id = str(result.get("trace_id") or "")
- outputs[datapoint.index] = (output or None, trace_id)
-
- coverage = _coverage(commands, len(datapoints))
- label, model_name = self._candidate_label(candidate)
- run_label = label if label == model_name else f"{label} · {model_name}"
- with transaction.atomic():
- run = runs.create_run(
- project=self.project,
- name=f"Optimizer · {self.capability.name} · {run_label}"[:255],
- description=f"Optimizer experiment {self.id}, {run_label}",
- dataset=self.dataset,
- cell=self.cell,
- eval_set=eval_set,
- matrix=matrix,
- mode=EvalRun.Mode.PROVIDED,
- model_name=model_name,
- params={
- "label": label,
- "optimizer_candidate_id": str(candidate.id),
- "optimizer_mode": self.mode,
- "target_model": candidate.target_model or model_name,
- },
- group=self.id,
- is_baseline=candidate.is_baseline,
- max_items=len(datapoints),
- triggered_by=self.triggered_by,
- )
- runs.provide_outputs(run, outputs)
- candidate.eval_run = run
- candidate.scores = {
- **(candidate.scores or {}),
- "coverage": coverage,
- "graded_rows": coverage["graded_rows"],
- "total_rows": coverage["total_rows"],
- "coverage_rate": coverage["coverage_rate"],
- }
- candidate.save(update_fields=["eval_run", "scores"])
- return run
-
- def _fold_candidate_eval_scores(self, candidate: OptimizerCandidate) -> float:
- from overbae.innermind import runs # noqa: PLC0415 — innermind imports models
-
- run = candidate.eval_run
- if run is None:
- return 0.0
- run.refresh_from_db()
- row_scores = runs.row_scores(run)
- coverage = (candidate.scores or {}).get("coverage") or {}
- # A failed or unscored datapoint counts as zero, so dropping rows cannot raise a score.
- total = coverage.get("total_rows") or run.max_items or len(row_scores)
- scored = sum(value for value in row_scores.values() if value is not None)
- score = scored / total * 100 if total else 0.0
- candidate.score = score
- candidate.scores = {
- **(candidate.scores or {}),
- "coverage": coverage,
- "graded_rows": coverage.get("graded_rows"),
- "total_rows": coverage.get("total_rows"),
- "coverage_rate": coverage.get("coverage_rate"),
- "metrics": (run.summary or {}).get("metrics") or {},
- }
- candidate.status = OptimizerCandidate.Status.EVALUATED
- candidate.save(update_fields=["score", "scores", "status"])
- commands = list(candidate.commands.all())
- for command in commands:
- value = row_scores.get(command.datapoint_index)
- command.score = value * 100 if value is not None else 0.0
- if command.status != OptimizerCommand.Status.FAILED:
- command.status = OptimizerCommand.Status.EVALUATED
- OptimizerCommand.objects.bulk_update(commands, ["score", "status"])
- return score
-
- def _record_iteration_scores(self, iteration: OptimizerIteration):
- if self.mode == self.Mode.MODEL_COMPARISON:
- self._record_model_comparison_scores(iteration)
- return
-
- candidate_scores = {str(c.id): c.score for c in iteration.candidates.all()}
- iteration_best = max(candidate_scores.values(), default=0.0)
- self.scores[str(iteration.order)] = candidate_scores
- previous_best = self.scores.get("best", 0.0)
- # ``best`` is ranking truth, so record every higher score. The 1-point
- # threshold gates plateau detection only; ranking with it could crown 97.2
- # over a later 97.5.
- if iteration_best > previous_best:
- self.scores["best"] = iteration_best
- if iteration_best > previous_best + MIN_ITERATION_IMPROVEMENT:
- self.stalled_iterations = 0
- else:
- self.stalled_iterations += 1
- iteration.status = OptimizerIteration.Status.COMPLETED
- iteration.save(update_fields=["status"])
-
- def _record_model_comparison_scores(self, iteration: OptimizerIteration) -> None:
- models = {c.target_model: c.score for c in iteration.candidates.all() if c.target_model}
- iteration_best = max(models.values(), default=0.0)
- scores = dict(self.scores or {})
- scores["best"] = max(scores.get("best", 0.0) or 0.0, iteration_best)
- by_model = dict(scores.get("by_model") or scores.get("models") or {})
- by_model.update(models)
- scores["by_model"] = by_model
- scores["models"] = by_model
- scores[str(iteration.order)] = {str(c.id): c.score for c in iteration.candidates.all()}
- self.scores = scores
- iteration.scores = {"best": iteration_best, "models": models}
- iteration.status = OptimizerIteration.Status.COMPLETED
- iteration.save(update_fields=["status", "scores"])
-
- def should_continue_iterating(self) -> bool:
- if self.mode == self.Mode.MODEL_COMPARISON:
- # Comparison runs every selected model regardless of stall: the run
- # owes a full per-model table, not improvement-driven stopping.
- return self.current_iteration < self.num_iterations
- if self.current_iteration >= self.num_iterations:
- return False
- return self.stalled_iterations < self.max_iterations_without_improvement
-
- def best_candidate(self) -> OptimizerCandidate | None:
- """The highest-scoring non-baseline candidate across all iterations, tied
- on highest iteration order then lowest candidate_index. None when nothing
- scored above the baseline.
- """
- baseline = self.scores.get("baseline", 0.0)
- return (
- self.candidates.filter(is_baseline=False)
- .exclude(code_path="")
- .order_by("-score", "-iteration__order", "candidate_index")
- .select_related("iteration")
- .filter(score__gt=baseline)
- .first()
- )
-
- def generate_winner(self):
- """Record the winning score and candidate id so the downstream PR step can read them."""
- if self.mode == self.Mode.MODEL_COMPARISON:
- # ``_record_model_comparison_scores`` already maxed ``best`` over
- # these same rows when the iteration was scored.
- candidates = list(self.candidates.filter(is_baseline=False).exclude(target_model=""))
- ranked = sorted(candidates, key=candidate_comparison_rank, reverse=True)
- selected_winner = ranked[0] if ranked else None
-
- selected_score = selected_winner.score if selected_winner is not None else 0.0
- incumbent_score = self.scores.get("baseline", 0.0)
- incumbent_wins = incumbent_score >= selected_score
- comparison_state = {
- "selected_winner": selected_winner.target_model if selected_winner else "",
- "selected_winner_score": selected_score,
- "incumbent_score": incumbent_score,
- "overall_winner": (
- "incumbent"
- if incumbent_wins or selected_winner is None
- else selected_winner.target_model
- ),
- "incumbent_wins": incumbent_wins,
- }
- self.state["model_comparison"] = comparison_state
- return
-
- if self.mode == self.Mode.HYBRID:
- selected = (
- self.candidates.filter(is_baseline=False)
- .exclude(target_model="")
- .order_by("-score", "-iteration__order", "candidate_index")
- .select_related("iteration")
- .first()
- )
- incumbent_score = self.scores.get("baseline", 0.0)
- self.state["model_optimization"] = {
- "selected_model": selected.target_model if selected else "",
- "selected_harness_candidate": (self._harness_index(selected) if selected else None),
- "selected_score": selected.score if selected else 0.0,
- "incumbent_score": incumbent_score,
- "overall_winner": (
- "incumbent"
- if selected is None or incumbent_score >= selected.score
- else f"{selected.target_model} · harness {self._harness_index(selected)}"
- ),
- }
-
- winner = self.best_candidate()
- recorded_best = self.scores.get("best", self.scores.get("baseline", 0.0))
- winner_score = max(recorded_best, winner.score if winner is not None else 0.0)
- self.scores["best"] = winner_score
- self.state["winner_score"] = winner_score
- if winner is not None:
- self.state["winner_candidate_id"] = str(winner.id)
-
-
-class OptimizerIteration(models.Model):
- """One optimization round. order=0 is the baseline; 1, 2, … are candidate rounds."""
-
- class Status(models.TextChoices):
- PENDING = "pending"
- GENERATING_CANDIDATES = "generating_candidates"
- GENERATED_CANDIDATES = "generated_candidates"
- RUNNING_COMMANDS = "running_commands"
- EVALUATING = "evaluating"
- EVALUATED = "evaluated"
- COMPLETED = "completed"
- FAILED = "failed"
-
- id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
- experiment = models.ForeignKey(
- "overbae.OptimizerExperiment", on_delete=models.CASCADE, related_name="iterations"
- )
- order = models.IntegerField(default=0)
- name = models.CharField(max_length=255, blank=True, default="")
- status = models.CharField(max_length=32, choices=Status.choices, default=Status.PENDING)
- scores = models.JSONField(default=dict, blank=True)
- patch = models.TextField(blank=True, default="")
- eval_run = models.ForeignKey(
- "overbae.EvalRun",
- on_delete=models.SET_NULL,
- null=True,
- blank=True,
- related_name="optimizer_iterations",
- )
- created_at = models.DateTimeField(auto_now_add=True)
-
- class Meta:
- ordering = ["order"]
- constraints = [
- models.UniqueConstraint(fields=["experiment", "order"], name="uniq_experiment_order")
- ]
-
- def recompute_status(self):
- """Update this iteration's status from its candidates' aggregate state."""
- candidates = list(self.candidates.all())
- if not candidates:
- return
-
- CS = OptimizerCandidate.Status # noqa: N806
- statuses = {c.status for c in candidates}
-
- if all(c.status == CS.EVALUATED for c in candidates):
- new = self.Status.EVALUATED
- elif statuses & {CS.RUNNING_COMMANDS, CS.PENDING}:
- new = self.Status.RUNNING_COMMANDS
- elif all(c.status in (CS.COMMANDS_DONE, CS.EVALUATED, CS.FAILED) for c in candidates):
- # All-failed still rolls up to EVALUATING so grading scores ~0
- # rather than hard-failing the batch. Only experiment._fail /
- # _stop_children set FAILED here.
- new = self.Status.EVALUATING
- else:
- return
-
- if new != self.status:
- self.status = new
- self.save(update_fields=["status"])
-
-
-class OptimizerCandidate(models.Model):
- """One code variant (git diff) evaluated across all dataset datapoints."""
-
- class Status(models.TextChoices):
- PENDING = "pending"
- RUNNING_COMMANDS = "running_commands"
- COMMANDS_DONE = "commands_done"
- EVALUATING = "evaluating"
- EVALUATED = "evaluated"
- FAILED = "failed"
-
- id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
- experiment = models.ForeignKey(
- "overbae.OptimizerExperiment", on_delete=models.CASCADE, related_name="candidates"
- )
- iteration = models.ForeignKey(
- "overbae.OptimizerIteration", on_delete=models.CASCADE, related_name="candidates"
- )
- candidate_index = models.IntegerField(default=0)
- code_path = models.TextField(blank=True, default="")
- target_model = models.CharField(max_length=255, blank=True, default="")
- is_baseline = models.BooleanField(default=False)
- score = models.FloatField(default=0.0)
- scores = models.JSONField(default=dict, blank=True)
- status = models.CharField(max_length=32, choices=Status.choices, default=Status.PENDING)
- eval_run = models.ForeignKey(
- "overbae.EvalRun",
- on_delete=models.SET_NULL,
- null=True,
- blank=True,
- related_name="optimizer_candidates",
- )
- created_at = models.DateTimeField(auto_now_add=True)
-
- class Meta:
- ordering = ["candidate_index"]
-
- def recompute_status(self):
- """Update this candidate's status from its commands' aggregate state."""
- commands = list(self.commands.all())
- if not commands:
- return
-
- CS = OptimizerCommand.Status # noqa: N806
- statuses = {c.status for c in commands}
-
- if all(c.status == CS.EVALUATED for c in commands):
- new = self.Status.EVALUATED
- elif statuses & {CS.PENDING, CS.RUNNING}:
- new = self.Status.RUNNING_COMMANDS
- elif all(c.status in (CS.RAN, CS.FAILED, CS.EVALUATED) for c in commands):
- # FAILED folds in with RAN/EVALUATED so evaluate() still runs, usually
- # scoring ~0. Only experiment._fail / _stop_children set FAILED here.
- new = self.Status.COMMANDS_DONE
- else:
- return
-
- if new != self.status:
- self.status = new
- self.save(update_fields=["status"])
-
-
-class OptimizerCommand(models.Model):
- """One datapoint run of one candidate, executed locally by the SDK.
-
- The client renders the template, runs it, and posts the outcome through the
- ledger (``post_results``); the server only scores what lands here.
- """
-
- class Status(models.TextChoices):
- PENDING = "pending"
- RUNNING = "running"
- RAN = "ran" # execution succeeded; not yet scored
- PASSED = "passed" # legacy executioner alias for RAN; old rows only
- EVALUATED = "evaluated"
- FAILED = "failed"
-
- id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
- experiment: OptimizerExperiment = models.ForeignKey(
- "overbae.OptimizerExperiment", on_delete=models.CASCADE, related_name="commands"
- )
- candidate = models.ForeignKey(
- "overbae.OptimizerCandidate",
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- related_name="commands",
- )
- iteration = models.ForeignKey(
- "overbae.OptimizerIteration",
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- related_name="commands",
- )
- datapoint_index = models.IntegerField(default=0)
- # Copied from the dataset row so evaluators score against the actual input.
- input = models.JSONField(default=dict, blank=True)
- code_path = models.TextField(blank=True, default="")
- command = models.TextField(blank=True, default="")
- output = models.TextField(blank=True, default="")
- result = models.JSONField(default=dict, blank=True) # {output, trace_id, exit_code, ...}
- score = models.FloatField(default=0.0)
- trace_type = models.CharField(max_length=16, default="original") # "original" or "replay"
- original_trace_id = models.CharField(max_length=64, blank=True, default="")
- status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING)
- timeout = models.IntegerField(default=600)
- error = models.TextField(blank=True, default="")
- created_at = models.DateTimeField(auto_now_add=True)
- updated_at = models.DateTimeField(auto_now=True)
-
- class Meta:
- ordering = ["created_at"]
-
- def _trace_telemetry(self, trace_id: str) -> tuple[str, list[str]]:
- """Read provider/model observations from all LLM spans for a trace."""
- if not trace_id:
- return "", []
- from overbae.models.traces import Span # noqa: PLC0415 — avoid import cycle
-
- providers: set[str] = set()
- models: set[str] = set()
- rows = Span.objects.filter(
- project_id=self.experiment.project_id, trace_id=trace_id
- ).values_list("attributes", "resource_attrs")
- for attributes, resource_attrs in rows.iterator():
- for attrs in (attributes, resource_attrs):
- provider = _telemetry_value(
- attrs,
- (
- "provider",
- "observed_provider",
- "genai_provider",
- "llm_provider",
- "gen_ai_system",
- ),
- )
- model = _telemetry_value(
- attrs,
- (
- "model",
- "genai_model",
- "gen_ai_request_model",
- "gen_ai_response_model",
- "llm_model",
- ),
- )
- if provider:
- providers.add(provider)
- if model:
- models.add(model)
- return ", ".join(sorted(providers)), sorted(models)
-
- def _telemetry_error(self, result: dict) -> str:
- """Return a clear routing mismatch, or ``""`` when it is unobservable."""
- if not isinstance(result, dict):
- return ""
- expected_model = (self.candidate.target_model if self.candidate_id else "") or ""
- if not expected_model:
- return ""
-
- provider_names = (
- "provider",
- "observed_provider",
- "genai_provider",
- "llm_provider",
- "gen_ai_system",
- )
- model_names = (
- "model",
- "observed_model",
- "genai_model",
- "gen_ai_request_model",
- "gen_ai_response_model",
- "llm_model",
- )
- # Only explicit telemetry containers and top-level fields: a structured
- # capability output may hold a business field called ``model``, which must not
- # be read as provider telemetry.
- telemetry_payload = result.get("telemetry") or result.get("observed_telemetry") or {}
- direct = {
- key: value
- for key, value in result.items()
- if str(key).lower().replace("-", "_").replace(".", "_")
- in {*provider_names, *model_names}
- }
- result_telemetry = [telemetry_payload, direct]
- result_providers = _telemetry_values(result_telemetry, provider_names)
- models = _telemetry_values(result_telemetry, model_names)
- provider = ", ".join(sorted(set(result_providers)))
- trace_provider, trace_models = self._trace_telemetry(str(result.get("trace_id") or ""))
- provider = provider or trace_provider
- models.extend(trace_models)
-
- if provider or models:
- telemetry = result.get("telemetry") if isinstance(result.get("telemetry"), dict) else {}
- if provider:
- telemetry["provider"] = provider
- if models:
- telemetry["models"] = sorted(set(models))
- telemetry["model"] = models[0] if len(set(models)) == 1 else ""
- result["telemetry"] = telemetry
- result["telemetry_missing"] = not provider or not models
-
- mismatched = sorted(
- {model for model in models if not _model_ids_match(expected_model, model)}
- )
- if mismatched:
- return (
- "Model routing mismatch: expected OpenRouter model "
- f"{expected_model!r}, observed {', '.join(mismatched)!r}."
- )
- return ""
-
-
-def on_candidate_eval_finished(run) -> None:
- """Called once a candidate's run is terminal. Folds its scores and clears its
- pending marker; the last candidate of an iteration finalises it and resumes the FSM.
- """
- candidate = (
- OptimizerCandidate.objects.filter(eval_run=run)
- .select_related("experiment", "iteration")
- .first()
- )
- if candidate is None:
- return
- with transaction.atomic():
- experiment = OptimizerExperiment.objects.select_for_update().get(pk=candidate.experiment_id)
- if experiment.status in experiment.TERMINAL:
- return
- pending = dict(experiment.state.get("eval_pending", {}))
- if str(candidate.id) not in pending:
- return
- experiment._fold_candidate_eval_scores(candidate)
- iteration_order = candidate.iteration.order
- pending.pop(str(candidate.id))
- experiment.state["eval_pending"] = pending
- experiment.save(update_fields=["state", "updated_at"])
- if not experiment._iteration_eval_pending(iteration_order):
- experiment.on_iteration_eval_complete(iteration_order)
- transaction.on_commit(lambda: run_experiment_advance.delay(str(experiment.id)))
-
-
-@shared_task(name="overbae.models.optimizer.run_experiment_advance")
-def run_experiment_advance(experiment_id: str) -> None:
- """Drive one experiment's FSM to its next client-wait state in a worker."""
- from overbae.tasks.utils.task_lock import acquire_task_lock
-
- logger.info("optimizer advance start exp=%s", experiment_id)
- with acquire_task_lock(
- f"optimizer_advance_{experiment_id}", timeout=120, renew=True
- ) as acquired:
- if not acquired:
- logger.info(
- "optimizer advance skipped exp=%s (another worker holds the lock)", experiment_id
- )
- return
- experiment = OptimizerExperiment.objects.filter(id=experiment_id).first()
- if experiment is None:
- logger.warning("optimizer advance: experiment %s not found", experiment_id)
- return
- status_before = experiment.status
- iter_before = experiment.current_iteration
- logger.info(
- "optimizer advance start exp=%s status=%s iteration=%d",
- experiment_id,
- status_before,
- iter_before,
- )
- try:
- experiment.advance()
- except Exception as exc: # noqa: BLE001 — persist the failure; never lose it
- logger.exception("optimizer experiment %s advance failed", experiment_id)
- experiment._fail(f"advance failed: {type(exc).__name__}: {exc}"[:500])
- return
- logger.info(
- "optimizer advance end exp=%s status=%s→%s iteration=%d→%d",
- experiment_id,
- status_before,
- experiment.status,
- iter_before,
- experiment.current_iteration,
- )
-
-
-def optimize_capability(
- capability,
- *,
- dataset=None,
- eval_set=None,
- entrypoint: str = "",
- code_trigger: str = "",
- num_iterations: int = 5,
- num_candidates_per_iteration: int = 3,
- max_iterations_without_improvement: int = 3,
- last_state: dict = None,
- triggered_by=None,
- mode: str = OptimizerExperiment.Mode.OPTIMIZE,
- model_ids: list[str] | None = None,
- openrouter_key_source: str = OptimizerExperiment.OpenRouterKeySource.PLATFORM,
-) -> OptimizerExperiment:
- from overbae.services.optimizer_create import create_optimizer_experiment
-
- return create_optimizer_experiment(
- user=triggered_by,
- capability=capability,
- dataset=dataset,
- eval_set=eval_set,
- entrypoint=entrypoint,
- code_trigger=code_trigger,
- num_iterations=num_iterations,
- num_candidates_per_iteration=num_candidates_per_iteration,
- max_iterations_without_improvement=max_iterations_without_improvement,
- initial_state=last_state,
- mode=mode,
- model_ids=model_ids,
- openrouter_key_source=openrouter_key_source,
- )
diff --git a/overbae/services/datasets/lifecycle.py b/overbae/services/datasets/lifecycle.py
index 06c67b7c..4776b1ba 100644
--- a/overbae/services/datasets/lifecycle.py
+++ b/overbae/services/datasets/lifecycle.py
@@ -127,18 +127,7 @@ def usage(cell: Cell) -> dict[str, list[dict[str, Any]]]:
for j in cell.evaluation_finetuning_jobs.order_by("-created_at")[:50]
]
)
- experiments = [
- {
- "id": str(e.id),
- "name": e.capability.name,
- "status": e.status,
- "created_at": e.created_at,
- }
- for e in cell.optimizer_experiments.select_related("capability").order_by("-created_at")[
- :50
- ]
- ]
- return {"eval_runs": eval_runs, "finetuning_jobs": jobs, "optimizer_experiments": experiments}
+ return {"eval_runs": eval_runs, "finetuning_jobs": jobs}
def delete_blocked_reason(dataset: Dataset) -> str:
diff --git a/overbae/services/datasets/rows.py b/overbae/services/datasets/rows.py
index 1dfac2d1..da479ab2 100644
--- a/overbae/services/datasets/rows.py
+++ b/overbae/services/datasets/rows.py
@@ -1,7 +1,7 @@
"""How consumers read a cell's rows.
A row is addressed by ``(cell, index)``; ``DatasetRow`` is the in-process
-shape eval, training and the optimiser work with, so none of them touch
+shape eval and training work with, so neither touches
Parquet directly.
"""
diff --git a/overbae/services/mcp/__init__.py b/overbae/services/mcp/__init__.py
index 96d059b3..3160a671 100644
--- a/overbae/services/mcp/__init__.py
+++ b/overbae/services/mcp/__init__.py
@@ -1,3 +1,3 @@
"""MCP protocol and catalog services."""
-CONTRACT_VERSION = "11.0.0"
+CONTRACT_VERSION = "12.0.0"
diff --git a/overbae/services/mcp/catalog.py b/overbae/services/mcp/catalog.py
index 5f61f406..23680f13 100644
--- a/overbae/services/mcp/catalog.py
+++ b/overbae/services/mcp/catalog.py
@@ -64,7 +64,6 @@ _KNOWN_SCOPES = frozenset(
"overmind:evaluate",
"overmind:train",
"overmind:deploy",
- "overmind:optimize",
"overmind:connectors",
"overmind:account:write",
}
@@ -369,10 +368,6 @@ from overbae.services.mcp.tools_model_catalog import ( # noqa: E402
register_model_catalog_tools(CATALOG)
-from overbae.services.mcp.tools_optimizer import register_optimizer_tools # noqa: E402
-
-register_optimizer_tools(CATALOG)
-
from overbae.services.mcp.tools_connectors import register_connector_tools # noqa: E402
register_connector_tools(CATALOG)
diff --git a/overbae/services/mcp/contracts/feedback.py b/overbae/services/mcp/contracts/feedback.py
index f1f3fd3f..c707c6e5 100644
--- a/overbae/services/mcp/contracts/feedback.py
+++ b/overbae/services/mcp/contracts/feedback.py
@@ -13,7 +13,6 @@ Area = Literal[
"observability",
"datasets",
"evaluation",
- "optimizer",
"training",
"serving",
"billing",
diff --git a/overbae/services/mcp/contracts/inventory.py b/overbae/services/mcp/contracts/inventory.py
index 1a642177..8fe99fff 100644
--- a/overbae/services/mcp/contracts/inventory.py
+++ b/overbae/services/mcp/contracts/inventory.py
@@ -23,7 +23,6 @@ ObjectKind = Literal[
"eval_set",
"eval_row",
"eval_run",
- "optimizer",
"data_exploration",
"data_partition",
"native_evaluation",
diff --git a/overbae/services/mcp/contracts/observability.py b/overbae/services/mcp/contracts/observability.py
index 4185b79f..e67b3ba4 100644
--- a/overbae/services/mcp/contracts/observability.py
+++ b/overbae/services/mcp/contracts/observability.py
@@ -191,9 +191,6 @@ JobKind = Literal[
"finetune",
"finetune_job",
"decision_job",
- "optimizer",
- "optimizer_run",
- "optimizer_experiment",
"deployment",
"model_activation",
]
diff --git a/overbae/services/mcp/contracts/optimizer.py b/overbae/services/mcp/contracts/optimizer.py
deleted file mode 100644
index 562cfa71..00000000
--- a/overbae/services/mcp/contracts/optimizer.py
+++ /dev/null
@@ -1,189 +0,0 @@
-"""Strict contracts for the user-facing optimizer MCP tools."""
-
-from __future__ import annotations
-
-from datetime import datetime
-from typing import Any, Literal
-
-from pydantic import Field
-
-from overbae.services.mcp.contracts.common import (
- DatasetCellContract,
- MCPModel,
- ResourceLinkContract,
-)
-
-OptimizerMode = Literal["optimize", "model_comparison", "hybrid"]
-
-
-class OptimizerDatasetReadiness(MCPModel):
- id: str
- name: str
- intent: str | None
- cell: DatasetCellContract | None = None
- usable: bool
- issue: str | None = Field(default=None, max_length=500)
-
-
-class OptimizerEvalSetReadiness(MCPModel):
- id: str
- name: str
- capability: str
- active: bool
- row_count: int = Field(ge=0)
-
-
-class OptimizerExecutionerState(MCPModel):
- connected: bool
- hostname: str = Field(default="", max_length=255)
- cli_version: str = Field(default="", max_length=40)
- heartbeat_at: datetime | None = None
-
-
-class OptimizerModelReadiness(MCPModel):
- mode: OptimizerMode
- requested: list[str] = Field(default_factory=list, max_length=5)
- validated: list[str] = Field(default_factory=list, max_length=5)
- valid: bool
- issue: str | None = Field(default=None, max_length=500)
-
-
-class OptimizerCreditReadiness(MCPModel):
- required: bool = True
- available: bool
-
-
-class OptimizerNextAction(MCPModel):
- state: Literal[
- "ready", "connect_executioner", "fix_prerequisites", "run_executioner", "inspect_result"
- ]
- message: str = Field(min_length=1, max_length=500)
- command: str | None = Field(default=None, max_length=500)
-
-
-class CheckOptimizerReadinessInput(MCPModel):
- capability: str = Field(min_length=1, max_length=255)
- dataset: str | None = Field(default=None, max_length=255)
- eval_set: str | None = Field(default=None, max_length=255)
- cell: str | None = Field(default=None, max_length=255)
- version: str | None = Field(default=None, max_length=32)
- mode: OptimizerMode = "optimize"
- model_ids: list[str] = Field(default_factory=list, max_length=5)
-
-
-class CheckOptimizerReadinessOutput(MCPModel):
- summary: str = Field(min_length=1, max_length=240)
- ready: bool
- missing: list[str] = Field(default_factory=list, max_length=20)
- capability: ResourceLinkContract
- dataset: OptimizerDatasetReadiness | None = None
- eval_set: OptimizerEvalSetReadiness | None = None
- executioner: OptimizerExecutionerState
- models: OptimizerModelReadiness
- credits: OptimizerCreditReadiness
- next_action: OptimizerNextAction
- resource_links: list[ResourceLinkContract] = Field(default_factory=list, max_length=4)
-
-
-class StartOptimizerInput(MCPModel):
- capability: str = Field(min_length=1, max_length=255)
- dataset: str = Field(min_length=1, max_length=255)
- eval_set: str | None = Field(default=None, max_length=255)
- cell: str | None = Field(default=None, max_length=255)
- version: str | None = Field(default=None, max_length=32)
- mode: OptimizerMode = "optimize"
- model_ids: list[str] = Field(default_factory=list, max_length=5)
- entrypoint: str = Field(default="", max_length=512)
- code_trigger: str = Field(default="", max_length=10_000)
- num_iterations: int = Field(default=5, ge=2, le=5)
- num_candidates_per_iteration: int = Field(default=3, ge=2, le=3)
- max_iterations_without_improvement: int = Field(default=3, ge=1, le=10)
-
-
-class OptimizerExperimentReference(MCPModel):
- id: str
- status: str
- mode: OptimizerMode
- capability: ResourceLinkContract
- cell: DatasetCellContract | None = None
- resource: ResourceLinkContract
-
-
-class OptimizerJobReference(MCPModel):
- id: str
- kind: Literal["optimizer_experiment"] = "optimizer_experiment"
- status: str
- resource: ResourceLinkContract
-
-
-class StartOptimizerOutput(MCPModel):
- summary: str = Field(min_length=1, max_length=240)
- experiment_id: str
- experiment: OptimizerExperimentReference
- job: OptimizerJobReference
- executioner: OptimizerExecutionerState
- next_action: OptimizerNextAction
- resource_links: list[ResourceLinkContract] = Field(max_length=4)
-
-
-class InspectOptimizerResultInput(MCPModel):
- experiment: str = Field(min_length=1, max_length=255)
- max_iterations: int = Field(default=50, ge=1, le=50)
- max_candidates_per_iteration: int = Field(default=50, ge=1, le=50)
-
-
-class OptimizerCandidateResult(MCPModel):
- id: str
- index: int = Field(ge=0)
- status: str
- is_baseline: bool
- target_model: str | None = None
- score: float
- coverage_rate: float | None = Field(default=None, ge=0.0, le=1.0)
- graded_rows: int | None = Field(default=None, ge=0)
- total_rows: int | None = Field(default=None, ge=0)
- scores: dict[str, Any] = Field(default_factory=dict, max_length=100)
- patch: str | None = Field(default=None, max_length=4_000)
- patch_truncated: bool = False
- eval_run: ResourceLinkContract | None = None
-
-
-class OptimizerIterationResult(MCPModel):
- id: str
- order: int = Field(ge=0)
- name: str
- status: str
- scores: dict[str, Any] = Field(default_factory=dict, max_length=100)
- candidates: list[OptimizerCandidateResult] = Field(max_length=50)
- candidates_truncated: bool = False
-
-
-class OptimizerWinner(MCPModel):
- candidate_id: str | None = None
- target_model: str | None = None
- score: float
- kind: Literal["candidate", "incumbent"]
-
-
-class OptimizerResultSummary(MCPModel):
- id: str
- status: str
- mode: OptimizerMode
- capability: ResourceLinkContract
- cell: DatasetCellContract | None = None
- current_iteration: int = Field(ge=0)
- num_iterations: int = Field(ge=0)
- scores: dict[str, Any] = Field(default_factory=dict, max_length=100)
- failure_reason: str | None = Field(default=None, max_length=1_000)
- resource: ResourceLinkContract
-
-
-class InspectOptimizerResultOutput(MCPModel):
- summary: str = Field(min_length=1, max_length=240)
- experiment: OptimizerResultSummary
- iterations: list[OptimizerIterationResult] = Field(max_length=50)
- iterations_truncated: bool = False
- winner: OptimizerWinner | None = None
- executioner: OptimizerExecutionerState
- next_action: OptimizerNextAction
- resource_links: list[ResourceLinkContract] = Field(max_length=102)
diff --git a/overbae/services/mcp/errors.py b/overbae/services/mcp/errors.py
index ffe08778..91871817 100644
--- a/overbae/services/mcp/errors.py
+++ b/overbae/services/mcp/errors.py
@@ -59,10 +59,6 @@ ErrorCode = Literal[
"finetune_invalid",
"finetune_not_ready",
"finetune_dispatch_failed",
- "optimizer_not_found",
- "optimizer_not_ready",
- "optimizer_invalid",
- "optimizer_pr_not_ready",
"deployment_not_found",
"deployment_invalid",
"deployment_not_ready",
diff --git a/overbae/services/mcp/inventory.py b/overbae/services/mcp/inventory.py
index 0b7fffe1..152d41a8 100644
--- a/overbae/services/mcp/inventory.py
+++ b/overbae/services/mcp/inventory.py
@@ -20,7 +20,6 @@ from overbae.models import (
FinetuningJob,
InferenceRequest,
ModelActivation,
- OptimizerExperiment,
TrainingCheckpoint,
TrainingPreparation,
)
@@ -121,9 +120,6 @@ COLLECTIONS = {
"eval_run": Collection(
EvalRun, "name", "status", "eval-runs", "evaluations", "dataset__capability_id"
),
- "optimizer": Collection(
- OptimizerExperiment, "capability__name", "status", "optimizer-runs", "optimiser"
- ),
**{
kind: Collection(model, "name", "state", f"jobs/{kind}", "training", None)
for kind, model in model_workflows.MODELS.items()
@@ -445,12 +441,6 @@ def dependencies(project, payload):
EvalRun.objects.filter(project=project, dataset_id=identifier),
"eval-runs",
),
- (
- "optimizer",
- "optimization data",
- OptimizerExperiment.objects.filter(project=project, dataset_id=identifier),
- "optimizer-runs",
- ),
(
"dataset_binding",
"scheduled preparation target",
diff --git a/overbae/services/mcp/prompts.py b/overbae/services/mcp/prompts.py
index 870a75d6..791caa62 100644
--- a/overbae/services/mcp/prompts.py
+++ b/overbae/services/mcp/prompts.py
@@ -326,48 +326,6 @@ PROMPTS = (
"repository rollout to ship-model."
),
),
- PromptDefinition(
- name="optimize-capability",
- title="Optimize capability",
- description="Check readiness, schedule, and inspect a capability optimization experiment.",
- arguments=(
- _argument("capability", "Capability name, slug, or id."),
- _argument("dataset", "Evaluation dataset UUID from list_datasets."),
- ),
- template=(
- "Optimize capability {capability} using evaluation dataset {dataset}. Use "
- "list_datasets, inspect_dataset, and query_dataset to choose and verify an "
- "eval cell. Run check_optimizer_readiness with that dataset and cell, mode "
- "optimize, and inspect missing prerequisites "
- "before start_optimizer. Start only after readiness and human approval; the MCP "
- "server schedules metadata while a connected local executioner runs the "
- "experiment. Inspect progress with inspect_optimizer_result and "
- "overmind://optimizer-runs/{{experiment}}. When a completed winner is approved for "
- "landing, present its diff and hand the change to a human to apply locally."
- ),
- ),
- PromptDefinition(
- name="compare-models",
- title="Compare models",
- description="Schedule a bounded model-comparison experiment and report its measured winner.",
- arguments=(
- _argument("capability", "Capability name, slug, or id."),
- _argument("dataset", "Evaluation dataset UUID from list_datasets."),
- _argument("model_ids", "Comma-separated model ids selected for comparison."),
- ),
- template=(
- "Compare selected models for capability {capability} on evaluation dataset "
- "{dataset}; requested models: {model_ids}. Use list_datasets, inspect_dataset, "
- "and query_dataset to choose and verify an eval cell. Run "
- "check_optimizer_readiness with that dataset and cell, mode model_comparison and "
- "those model ids, then start_optimizer with the same "
- "mode only when ready and the human has confirmed the model list. The local "
- "executioner performs the repository-side runs; MCP schedules and records them. "
- "Inspect with inspect_optimizer_result and "
- "overmind://optimizer-runs/{{experiment}}; report per-model evidence, winner, "
- "and the next action."
- ),
- ),
PromptDefinition(
name="ship-model",
title="Ship model",
diff --git a/overbae/services/mcp/resources.py b/overbae/services/mcp/resources.py
index b9ce8d7a..0a8638e0 100644
--- a/overbae/services/mcp/resources.py
+++ b/overbae/services/mcp/resources.py
@@ -11,7 +11,7 @@ from urllib.parse import parse_qs, quote, unquote, urlparse
from asgiref.sync import sync_to_async
from django.conf import settings
-from django.db.models import Prefetch, Q
+from django.db.models import Q
from mcp import types
from mcp.server.lowlevel.helper_types import ReadResourceContents
from mcp.shared.exceptions import McpError
@@ -41,8 +41,6 @@ from overbae.models import (
FinetuningJob,
InferenceRequest,
ModelActivation,
- OptimizerCandidate,
- OptimizerExperiment,
SignalEvent,
SignalSubscription,
Span,
@@ -92,7 +90,6 @@ from sandbox.documents.languages import LANGUAGES
JSON_MIME = "application/json"
_MAX_EVENTS = 20
_MAX_LIST = 50
-_OPTIMIZER_PATCH_CAP = 4_000
_ERROR_CAP = 1_000
@@ -1151,179 +1148,6 @@ def _deployment_resource(project, value: str, uri: str) -> dict:
}
-_DISCONNECTED = {"connected": False, "hostname": "", "cli_version": "", "heartbeat_at": None}
-
-
-def _optimizer_resource(project, value: str, uri: str) -> dict:
- normalized_id = uuid_reference(value)
- experiment = (
- OptimizerExperiment.objects.filter(project=project, id=normalized_id)
- .select_related("capability", "dataset")
- .first()
- if normalized_id
- else None
- )
- if experiment is None:
- raise _not_found("optimizer run", value)
- candidates = OptimizerCandidate.objects.select_related("eval_run").order_by("candidate_index")
- iterations = list(
- experiment.iterations.order_by("order").prefetch_related(
- Prefetch("candidates", queryset=candidates)
- )[: _MAX_LIST + 1]
- )
- bounded_iterations = iterations[:_MAX_LIST]
- candidate_rows: list[dict] = []
- iteration_rows = []
- links = [
- resource_link(
- "optimizer-runs", str(experiment.id), f"Optimizer {experiment.capability.name}"
- )
- ]
- for iteration in bounded_iterations:
- iteration_candidates = list(iteration.candidates.all())
- bounded_candidates = iteration_candidates[:_MAX_LIST]
- rows = []
- for candidate in bounded_candidates:
- patch = (candidate.code_path or "")[:_OPTIMIZER_PATCH_CAP]
- row = {
- "id": str(candidate.id),
- "index": candidate.candidate_index,
- "status": candidate.status,
- "is_baseline": candidate.is_baseline,
- "target_model": candidate.target_model or None,
- "score": candidate.score,
- "scores": safe_json(candidate.scores or {}),
- "patch": patch or None,
- "patch_truncated": len(candidate.code_path or "") > _OPTIMIZER_PATCH_CAP,
- "eval_run": (
- resource_link("eval-runs", str(candidate.eval_run_id), candidate.eval_run.name)
- if candidate.eval_run_id and candidate.eval_run is not None
- else None
- ),
- }
- rows.append(row)
- candidate_rows.append(row)
- if row["eval_run"] is not None:
- links.append(row["eval_run"])
- iteration_rows.append(
- {
- "id": str(iteration.id),
- "order": iteration.order,
- "name": iteration.name
- or ("Baseline" if iteration.order == 0 else f"Iteration {iteration.order}"),
- "status": iteration.status,
- "scores": safe_json(iteration.scores or {}),
- "candidates": rows,
- "candidates_truncated": len(iteration_candidates) > len(bounded_candidates),
- }
- )
-
- state = safe_json(experiment.state or {})
- winner_id = str((experiment.state or {}).get("winner_candidate_id") or "")
- winner = next((row for row in candidate_rows if row["id"] == winner_id), None)
- if winner is None and winner_id:
- selected = (
- OptimizerCandidate.objects.filter(experiment=experiment, id=winner_id)
- .select_related("eval_run")
- .first()
- )
- if selected is not None:
- patch = (selected.code_path or "")[:_OPTIMIZER_PATCH_CAP]
- winner = {
- "id": str(selected.id),
- "target_model": selected.target_model or None,
- "score": selected.score,
- "is_baseline": selected.is_baseline,
- "patch": patch or None,
- }
- comparison = state.get("model_comparison") if isinstance(state, dict) else None
- if winner is None and experiment.mode == OptimizerExperiment.Mode.MODEL_COMPARISON:
- if isinstance(comparison, dict) and comparison.get("overall_winner") == "incumbent":
- winner = {
- "id": None,
- "target_model": None,
- "score": float(comparison.get("incumbent_score") or 0.0),
- "kind": "incumbent",
- }
- elif isinstance(comparison, dict) and comparison.get("selected_winner"):
- selected = (
- OptimizerCandidate.objects.filter(
- experiment=experiment, target_model=comparison["selected_winner"]
- )
- .order_by("-score", "-iteration__order", "candidate_index")
- .first()
- )
- if selected is not None:
- winner = {
- "id": str(selected.id),
- "target_model": selected.target_model or None,
- "score": selected.score,
- "kind": "candidate",
- "is_baseline": selected.is_baseline,
- "patch": (selected.code_path or "")[:_OPTIMIZER_PATCH_CAP] or None,
- }
- if winner is None:
- possible = [row for row in candidate_rows if not row["is_baseline"]]
- if experiment.mode == OptimizerExperiment.Mode.OPTIMIZE:
- baseline = float((experiment.scores or {}).get("baseline") or 0.0)
- possible = [row for row in possible if row["patch"] and row["score"] > baseline]
- winner = max(possible, key=lambda row: row["score"], default=None)
-
- terminal = experiment.status in {
- OptimizerExperiment.Status.COMPLETED,
- OptimizerExperiment.Status.FAILED,
- OptimizerExperiment.Status.CANCELLED,
- }
- if terminal:
- next_action = {
- "state": "inspect_result",
- "message": "The optimizer experiment is terminal.",
- "command": None,
- }
- else:
- next_action = {
- "state": "run_executioner",
- "message": "Drive the experiment with the local CLI.",
- "command": f"overmind optimise start -e {experiment.id} && overmind optimise next",
- }
- job_link = resource_link("jobs", f"optimizer_experiment/{experiment.id}", "Optimizer job")
- links.insert(1, job_link)
- return {
- "uri": uri,
- "kind": "optimizer_run",
- "id": str(experiment.id),
- "status": experiment.status,
- "capability": experiment.capability.slug if experiment.capability_id else None,
- "dataset": str(experiment.dataset_id) if experiment.dataset_id else None,
- "mode": experiment.mode,
- "current_iteration": experiment.current_iteration,
- "num_iterations": experiment.num_iterations,
- "scores": safe_json(experiment.scores or {}),
- "state": state,
- "failure_reason": experiment.failure_reason[:1_000],
- "iterations": iteration_rows,
- "iterations_truncated": len(iterations) > len(bounded_iterations),
- "winner": (
- {
- "candidate_id": winner["id"],
- "target_model": winner["target_model"],
- "score": winner["score"],
- "kind": winner.get("kind", "candidate"),
- }
- if winner is not None
- else None
- ),
- # The lease protocol is gone: the local CLI drives the run and never
- # registers a connection, so both blocks are permanently disconnected.
- "executioner": _DISCONNECTED,
- "connection": _DISCONNECTED,
- "next_action": next_action,
- "resource_links": links[: _MAX_LIST + 2],
- "created_at": experiment.created_at,
- "updated_at": experiment.updated_at,
- }
-
-
def _job_resource(project, kind: str, value: str, uri: str) -> dict:
if kind == "inference_request":
request = InferenceRequest.objects.filter(project=project, pk=uuid_reference(value)).first()
@@ -1411,8 +1235,6 @@ def _job_resource(project, kind: str, value: str, uri: str) -> dict:
}
if kind in {"deployment", "model_deployment"}:
return _deployment_resource(project, value, uri)
- if kind in {"optimizer", "optimizer_run", "optimizer_experiment"}:
- return _optimizer_resource(project, value, uri)
normalized_id = uuid_reference(value)
if kind == "dataset_transfer":
from overbae.services.datasets import transfers
@@ -1742,7 +1564,6 @@ def _read_resource_sync(project, raw_uri: str) -> dict:
"eval-sets",
"finetunes",
"deployments",
- "optimizer-runs",
"connectors",
}
and len(segments) == 1
@@ -1756,7 +1577,6 @@ def _read_resource_sync(project, raw_uri: str) -> dict:
"eval-sets": _eval_set_resource,
"finetunes": _finetune_resource,
"deployments": _deployment_resource,
- "optimizer-runs": _optimizer_resource,
"connectors": _connector_resource,
}
return kind_map[host](project, segments[0], raw_uri)
@@ -1889,7 +1709,6 @@ def resource_templates() -> list[types.ResourceTemplate]:
),
("finetune", "overmind://finetunes/{job_id}", "Fine-tuning job status"),
("deployment", "overmind://deployments/{deployment}", "Deployment status"),
- ("optimizer-run", "overmind://optimizer-runs/{experiment}", "Optimizer run status"),
("connector", "overmind://connectors/{connector}", "Connector metadata and sync status"),
("job", "overmind://jobs/{kind}/{id}", "Project job status"),
(
diff --git a/overbae/services/mcp/tools_observability.py b/overbae/services/mcp/tools_observability.py
index ac3f57e7..358259b3 100644
--- a/overbae/services/mcp/tools_observability.py
+++ b/overbae/services/mcp/tools_observability.py
@@ -24,7 +24,6 @@ from overbae.models import (
FinetuningJob,
InferenceRequest,
ModelActivation,
- OptimizerExperiment,
Span,
TrainingPreparation,
)
@@ -320,8 +319,6 @@ def _query_traces_sync(payload: QueryTracesInput, context: MCPContext) -> QueryT
_JOB_ALIASES = {
"finetune": "finetune_job",
- "optimizer": "optimizer_experiment",
- "optimizer_run": "optimizer_experiment",
}
@@ -517,30 +514,6 @@ def get_job_sync(payload: GetJobInput, context: MCPContext) -> GetJobOutput:
}
primary = _link("jobs", f"dataset_run/{job.id}", label)
underlying.append(_link("datasets", str(job.id), label))
- elif kind == "optimizer_experiment":
- job = (
- OptimizerExperiment.objects.filter(project=context.project, id=normalized_id)
- .select_related("capability")
- .first()
- if normalized_id
- else None
- )
- if job is None:
- raise MCPError("resource_not_found", "The optimizer run was not found.")
- created_at = job.created_at
- updated_at = job.updated_at
- label, status, job_error = (
- f"Optimize {job.capability.name}",
- job.status,
- job.failure_reason or None,
- )
- details = {
- "capability": job.capability.slug,
- "current_iteration": job.current_iteration,
- "num_iterations": job.num_iterations,
- "scores": safe_json(job.scores or {}),
- }
- primary = _link("optimizer-runs", str(job.id), label)
elif kind == "model_activation":
job = (
ModelActivation.objects.filter(
diff --git a/overbae/services/mcp/tools_optimizer.py b/overbae/services/mcp/tools_optimizer.py
deleted file mode 100644
index 4cfa0bd9..00000000
--- a/overbae/services/mcp/tools_optimizer.py
+++ /dev/null
@@ -1,597 +0,0 @@
-"""Project-scoped user-facing optimizer MCP tools."""
-
-from __future__ import annotations
-
-from asgiref.sync import sync_to_async
-from django.conf import settings
-from django.db.models import Prefetch, Q
-from rest_framework.exceptions import ValidationError as DRFValidationError
-
-from overbae.api.credit_gate import PaymentRequired
-from overbae.models import (
- Capability,
- Dataset,
- EvalSet,
- OptimizerCandidate,
- OptimizerExperiment,
- OptimizerIteration,
-)
-from overbae.models.optimizer import candidate_comparison_rank, optimizer_dataset_error
-from overbae.services.datasets.contract import public_intent
-from overbae.services.mcp.context import MCPContext
-from overbae.services.mcp.contracts.optimizer import (
- CheckOptimizerReadinessInput,
- CheckOptimizerReadinessOutput,
- InspectOptimizerResultInput,
- InspectOptimizerResultOutput,
- OptimizerCandidateResult,
- OptimizerCreditReadiness,
- OptimizerDatasetReadiness,
- OptimizerEvalSetReadiness,
- OptimizerExecutionerState,
- OptimizerExperimentReference,
- OptimizerIterationResult,
- OptimizerJobReference,
- OptimizerModelReadiness,
- OptimizerNextAction,
- OptimizerResultSummary,
- OptimizerWinner,
- StartOptimizerInput,
- StartOptimizerOutput,
-)
-from overbae.services.mcp.errors import MCPError, mcp_cell, mcp_cell_contract, mcp_dataset
-from overbae.services.mcp.references import uuid_reference
-from overbae.services.mcp.resources import resource_link, safe_json
-from overbae.services.optimizer_create import (
- create_optimizer_experiment,
- validate_optimizer_models,
-)
-from overbae.services.optimizer_prereqs import optimizer_prerequisite_report
-
-_PATCH_CAP = 4_000
-
-
-def _resolve_capability(context: MCPContext, reference: str) -> Capability:
- query = Capability.objects.filter(
- project=context.project, status=Capability.Status.CURRENT
- ).select_related("active_eval_set")
- normalized = uuid_reference(reference)
- capability = query.filter(id=normalized).first() if normalized else None
- if capability is None:
- capability = query.filter(name__iexact=reference.strip()).first()
- if capability is None:
- capability = query.filter(slug__iexact=reference.strip()).first()
- if capability is None:
- raise MCPError("capability_not_found", "The capability was not found in this project.")
- return capability
-
-
-def _resolve_eval_set(context: MCPContext, reference: str, *, capability: Capability) -> EvalSet:
- query = EvalSet.objects.filter(
- Q(capability=capability) | Q(capability__isnull=True), project=context.project
- ).select_related("capability")
- normalized = uuid_reference(reference)
- eval_set = query.filter(id=normalized).first() if normalized else None
- if eval_set is None:
- matches = list(query.filter(name__iexact=reference.strip()).order_by("-created_at")[:2])
- if len(matches) > 1:
- raise MCPError("eval_set_not_found", "Multiple eval sets match; use the eval set id.")
- eval_set = matches[0] if matches else None
- if eval_set is None:
- raise MCPError("eval_set_not_found", "The eval set was not found for this capability.")
- return eval_set
-
-
-def _resolve_experiment(context: MCPContext, reference: str) -> OptimizerExperiment:
- normalized = uuid_reference(reference)
- if normalized is None:
- raise MCPError("optimizer_not_found", "Use the optimizer experiment id.")
- candidates = OptimizerCandidate.objects.select_related("eval_run").order_by("candidate_index")
- iterations = OptimizerIteration.objects.order_by("order").prefetch_related(
- Prefetch("candidates", queryset=candidates)
- )
- experiment = (
- OptimizerExperiment.objects.filter(project=context.project, id=normalized)
- .select_related("capability", "dataset", "cell", "eval_set")
- .prefetch_related(Prefetch("iterations", queryset=iterations))
- .first()
- )
- if experiment is None:
- raise MCPError(
- "optimizer_not_found", "The optimizer experiment was not found in this project."
- )
- return experiment
-
-
-def _validation_message(error: DRFValidationError) -> str:
- detail = error.detail
- if isinstance(detail, dict):
- values = [str(value) for value in detail.values()]
- if values:
- return values[0][:500]
- if isinstance(detail, list) and detail:
- return str(detail[0])[:500]
- return "The optimizer request failed validation."
-
-
-def _executioner() -> OptimizerExecutionerState:
- return OptimizerExecutionerState(connected=False)
-
-
-def _credits_available(user) -> bool:
- from overbae.api.credit_gate import require_credits
-
- try:
- require_credits(user)
- except PaymentRequired:
- return False
- return True
-
-
-def _model_readiness(
- mode: str, model_ids: list[str], capability: Capability
-) -> OptimizerModelReadiness:
- try:
- validated = validate_optimizer_models(mode, model_ids, project=capability.project)
- except DRFValidationError as error:
- return OptimizerModelReadiness(
- mode=mode,
- requested=model_ids,
- valid=False,
- issue=_validation_message(error),
- )
- if mode in {
- OptimizerExperiment.Mode.MODEL_COMPARISON,
- OptimizerExperiment.Mode.HYBRID,
- } and not getattr(settings, "OPENROUTER_API_KEY", ""):
- return OptimizerModelReadiness(
- mode=mode,
- requested=model_ids,
- validated=validated,
- valid=False,
- issue="Overmind model access is not configured on this server.",
- )
- return OptimizerModelReadiness(
- mode=mode,
- requested=model_ids,
- validated=validated,
- valid=True,
- )
-
-
-def _dataset_readiness(
- capability: Capability, dataset: Dataset | None, *, cell=None
-) -> OptimizerDatasetReadiness | None:
- if dataset is None:
- return None
- issue = optimizer_dataset_error(capability, dataset, cell)
- chosen = cell or dataset.active_cell
- return OptimizerDatasetReadiness(
- id=str(dataset.id),
- name=dataset.name or str(dataset.id)[:8],
- intent=public_intent(dataset.intent),
- cell=mcp_cell_contract(dataset, chosen, "eval"),
- usable=issue is None,
- issue=issue,
- )
-
-
-def _eval_set_readiness(
- capability: Capability, eval_set: EvalSet | None
-) -> OptimizerEvalSetReadiness | None:
- if eval_set is None:
- return None
- return OptimizerEvalSetReadiness(
- id=str(eval_set.id),
- name=eval_set.name,
- capability=capability.slug,
- active=capability.active_eval_set_id == eval_set.id,
- row_count=eval_set.rows.filter(enabled=True).count(),
- )
-
-
-def _next_action(
- *,
- ready: bool,
- experiment_id: str | None = None,
-) -> OptimizerNextAction:
- if not ready:
- return OptimizerNextAction(
- state="fix_prerequisites",
- message="Fix the listed optimizer prerequisites before starting a run.",
- )
- if experiment_id is None:
- return OptimizerNextAction(
- state="ready", message="The project is ready to start an optimizer run."
- )
- return OptimizerNextAction(
- state="run_executioner",
- message="The experiment is scheduled; drive it with the local CLI.",
- command=f"overmind optimise start -e {experiment_id} && overmind optimise next",
- )
-
-
-def _readiness_sync(
- payload: CheckOptimizerReadinessInput, context: MCPContext
-) -> CheckOptimizerReadinessOutput:
- capability = _resolve_capability(context, payload.capability)
- optimizer_prerequisite_report(context.project, capability)
- explicit_cell = None
- dataset = mcp_dataset(context, payload.dataset) if payload.dataset else None
- if dataset is not None:
- explicit_cell = mcp_cell(dataset, payload.cell or payload.version or None)
- if dataset is None:
- for candidate in Dataset.objects.filter(
- project=context.project, capability=capability, intent=Dataset.Intent.EVAL
- ).order_by("-created_at")[:10]:
- candidate_readiness = _dataset_readiness(capability, candidate)
- if candidate_readiness and candidate_readiness.usable:
- dataset = candidate
- break
- eval_set = (
- _resolve_eval_set(context, payload.eval_set, capability=capability)
- if payload.eval_set
- else capability.active_eval_set
- )
- dataset_data = _dataset_readiness(capability, dataset, cell=explicit_cell)
- eval_set_data = _eval_set_readiness(capability, eval_set)
- executioner = _executioner()
- models = _model_readiness(payload.mode, payload.model_ids, capability)
- credits = OptimizerCreditReadiness(available=_credits_available(context.user))
-
- missing: list[str] = []
- if dataset_data is None:
- missing.append("eval dataset")
- elif not dataset_data.usable:
- missing.append(f"eval dataset: {dataset_data.issue or 'not usable'}")
- if eval_set_data is None:
- missing.append("eval set")
- if not models.valid:
- missing.append(f"model selection: {models.issue or 'invalid'}")
- if not credits.available:
- missing.append("credits")
-
- ready = not missing
- links = [resource_link("capabilities", str(capability.id), capability.name)]
- if dataset_data is not None:
- links.append(resource_link("datasets", dataset_data.id, dataset_data.name))
- return CheckOptimizerReadinessOutput(
- summary="Optimizer is ready." if ready else "Optimizer is not ready.",
- ready=ready,
- missing=missing,
- capability=links[0],
- dataset=dataset_data,
- eval_set=eval_set_data,
- executioner=executioner,
- models=models,
- credits=credits,
- next_action=_next_action(ready=ready),
- resource_links=links,
- )
-
-
-def _start_sync(payload: StartOptimizerInput, context: MCPContext) -> StartOptimizerOutput:
- readiness = _readiness_sync(
- CheckOptimizerReadinessInput(
- capability=payload.capability,
- dataset=payload.dataset,
- eval_set=payload.eval_set,
- cell=payload.cell,
- version=payload.version,
- mode=payload.mode,
- model_ids=payload.model_ids,
- ),
- context,
- )
- if not readiness.ready:
- raise MCPError(
- "optimizer_not_ready",
- "The optimizer is not ready to start.",
- fields={"missing": ", ".join(readiness.missing)[:500]},
- )
- capability = _resolve_capability(context, payload.capability)
- dataset = mcp_dataset(context, payload.dataset)
- cell = mcp_cell(dataset, payload.cell or payload.version or None)
- eval_set = (
- _resolve_eval_set(context, payload.eval_set, capability=capability)
- if payload.eval_set
- else capability.active_eval_set
- )
- try:
- experiment = create_optimizer_experiment(
- user=context.user,
- capability=capability,
- dataset=dataset,
- cell=cell,
- eval_set=eval_set,
- entrypoint=payload.entrypoint,
- code_trigger=payload.code_trigger,
- num_iterations=payload.num_iterations,
- num_candidates_per_iteration=payload.num_candidates_per_iteration,
- max_iterations_without_improvement=payload.max_iterations_without_improvement,
- mode=payload.mode,
- model_ids=payload.model_ids,
- openrouter_key_source=OptimizerExperiment.OpenRouterKeySource.PLATFORM,
- )
- except PaymentRequired as error:
- raise MCPError(
- "insufficient_credits", "This operation requires available credits."
- ) from error
- except DRFValidationError as error:
- raise MCPError(
- "optimizer_invalid",
- "The optimizer request failed validation.",
- fields={"request": _validation_message(error)},
- ) from error
-
- executioner = _executioner()
- exp_link = resource_link("optimizer-runs", str(experiment.id), f"Optimizer {capability.name}")
- job_link = resource_link(
- "jobs", f"optimizer_experiment/{experiment.id}", f"Optimizer {capability.name}"
- )
- experiment_ref = OptimizerExperimentReference(
- id=str(experiment.id),
- status=experiment.status,
- mode=experiment.mode,
- capability=resource_link("capabilities", str(capability.id), capability.name),
- cell=mcp_cell_contract(
- experiment.dataset or dataset,
- experiment.cell or cell,
- "eval",
- ),
- resource=exp_link,
- )
- return StartOptimizerOutput(
- summary="Optimizer experiment scheduled.",
- experiment_id=str(experiment.id),
- experiment=experiment_ref,
- job=OptimizerJobReference(
- id=str(experiment.id), status=experiment.status, resource=job_link
- ),
- executioner=executioner,
- next_action=_next_action(
- ready=True,
- experiment_id=str(experiment.id),
- ),
- resource_links=[exp_link, job_link, experiment_ref.capability],
- )
-
-
-def _candidate_coverage_fields(candidate: OptimizerCandidate) -> dict:
- scores = candidate.scores or {}
- coverage = scores.get("coverage") or {}
- return {
- "coverage_rate": scores.get("coverage_rate", coverage.get("coverage_rate")),
- "graded_rows": scores.get("graded_rows", coverage.get("graded_rows")),
- "total_rows": scores.get("total_rows", coverage.get("total_rows")),
- }
-
-
-def _candidate_result(candidate: OptimizerCandidate) -> OptimizerCandidateResult:
- patch = (candidate.code_path or "")[:_PATCH_CAP]
- eval_link = (
- resource_link("eval-runs", str(candidate.eval_run_id), candidate.eval_run.name)
- if candidate.eval_run_id and candidate.eval_run is not None
- else None
- )
- return OptimizerCandidateResult(
- id=str(candidate.id),
- index=candidate.candidate_index,
- status=candidate.status,
- is_baseline=candidate.is_baseline,
- target_model=candidate.target_model or None,
- score=candidate.score,
- **_candidate_coverage_fields(candidate),
- scores=safe_json(candidate.scores or {}),
- patch=patch or None,
- patch_truncated=len(candidate.code_path or "") > _PATCH_CAP,
- eval_run=eval_link,
- )
-
-
-def _winner(
- experiment: OptimizerExperiment, candidates: list[OptimizerCandidate]
-) -> OptimizerWinner | None:
- state = experiment.state if isinstance(experiment.state, dict) else {}
- winner_id = str(state.get("winner_candidate_id") or "")
- selected = next((candidate for candidate in candidates if str(candidate.id) == winner_id), None)
- if selected is None and winner_id:
- selected = (
- OptimizerCandidate.objects.filter(experiment=experiment, id=winner_id)
- .select_related("eval_run")
- .first()
- )
- comparison = state.get("model_comparison")
- if selected is None and experiment.mode == OptimizerExperiment.Mode.MODEL_COMPARISON:
- if isinstance(comparison, dict) and comparison.get("overall_winner") == "incumbent":
- return OptimizerWinner(
- target_model=None,
- score=float(comparison.get("incumbent_score") or 0.0),
- kind="incumbent",
- )
- selected_model = comparison.get("selected_winner") if isinstance(comparison, dict) else None
- if selected_model:
- selected = (
- OptimizerCandidate.objects.filter(
- experiment=experiment, target_model=selected_model
- )
- .select_related("eval_run")
- .order_by("-score", "-iteration__order", "candidate_index")
- .first()
- )
- if selected is None:
- eligible = [candidate for candidate in candidates if not candidate.is_baseline]
- if experiment.mode == OptimizerExperiment.Mode.OPTIMIZE:
- baseline = float((experiment.scores or {}).get("baseline") or 0.0)
- eligible = [
- candidate
- for candidate in eligible
- if candidate.code_path and candidate.score > baseline
- ]
- selected = max(eligible, key=candidate_comparison_rank, default=None)
- if selected is not None:
- return OptimizerWinner(
- candidate_id=str(selected.id),
- target_model=selected.target_model or None,
- score=selected.score,
- kind="candidate",
- )
- comparison = state.get("model_comparison") if isinstance(state, dict) else None
- if isinstance(comparison, dict) and comparison.get("overall_winner") == "incumbent":
- return OptimizerWinner(
- target_model=None,
- score=float(comparison.get("incumbent_score") or 0.0),
- kind="incumbent",
- )
- return None
-
-
-def _inspect_sync(
- payload: InspectOptimizerResultInput, context: MCPContext
-) -> InspectOptimizerResultOutput:
- experiment = _resolve_experiment(context, payload.experiment)
- all_iterations = list(experiment.iterations.order_by("order"))
- iterations = all_iterations[: payload.max_iterations]
- result_iterations: list[OptimizerIterationResult] = []
- all_candidates: list[OptimizerCandidate] = []
- for iteration in iterations:
- all_candidates.extend(list(iteration.candidates.order_by("candidate_index")))
- candidates = list(iteration.candidates.order_by("candidate_index"))
- bounded = candidates[: payload.max_candidates_per_iteration]
- result_iterations.append(
- OptimizerIterationResult(
- id=str(iteration.id),
- order=iteration.order,
- name=iteration.name
- or ("Baseline" if iteration.order == 0 else f"Iteration {iteration.order}"),
- status=iteration.status,
- scores=safe_json(iteration.scores or {}),
- candidates=[_candidate_result(candidate) for candidate in bounded],
- candidates_truncated=len(candidates) > len(bounded),
- )
- )
-
- executioner = _executioner()
- exp_link = resource_link(
- "optimizer-runs", str(experiment.id), f"Optimizer {experiment.capability.name}"
- )
- job_link = resource_link(
- "jobs", f"optimizer_experiment/{experiment.id}", f"Optimizer {experiment.capability.name}"
- )
- summary = OptimizerResultSummary(
- id=str(experiment.id),
- status=experiment.status,
- mode=experiment.mode,
- capability=resource_link(
- "capabilities", str(experiment.capability.id), experiment.capability.name
- ),
- cell=mcp_cell_contract(experiment.dataset, experiment.cell, "eval")
- if experiment.dataset_id
- else None,
- current_iteration=experiment.current_iteration,
- num_iterations=experiment.num_iterations,
- scores=safe_json(experiment.scores or {}),
- failure_reason=(experiment.failure_reason or "")[:1_000] or None,
- resource=exp_link,
- )
- terminal = experiment.status in {
- OptimizerExperiment.Status.COMPLETED,
- OptimizerExperiment.Status.FAILED,
- OptimizerExperiment.Status.CANCELLED,
- }
- next_action = OptimizerNextAction(
- state="inspect_result"
- if terminal
- else _next_action(ready=True, experiment_id=str(experiment.id)).state,
- message="The optimizer experiment is terminal."
- if terminal
- else "Drive the scheduled experiment with the local CLI.",
- command=None
- if terminal
- else f"overmind optimise start -e {experiment.id} && overmind optimise next",
- )
- return InspectOptimizerResultOutput(
- summary=f"Optimizer experiment {experiment.status}.",
- experiment=summary,
- iterations=result_iterations,
- iterations_truncated=len(all_iterations) > len(iterations),
- winner=_winner(experiment, all_candidates),
- executioner=executioner,
- next_action=next_action,
- resource_links=[exp_link, job_link, summary.capability],
- )
-
-
-def register_optimizer_tools(catalog) -> None:
- from overbae.services.mcp.catalog import ToolDefinition
-
- definitions = [
- (
- "check_optimizer_readiness",
- "Check optimizer readiness",
- "Inspect project-scoped optimizer dataset, eval set, model, credit, and plan readiness.",
- CheckOptimizerReadinessInput,
- CheckOptimizerReadinessOutput,
- _readiness_sync,
- True,
- True,
- "free",
- "sync",
- {"overmind:read"},
- ),
- (
- "start_optimizer",
- "Start optimizer",
- "Validate and schedule an optimizer, model comparison, or hybrid experiment; drive it with `overmind optimise`.",
- StartOptimizerInput,
- StartOptimizerOutput,
- _start_sync,
- False,
- True,
- "llm",
- "job",
- {"overmind:optimize"},
- ),
- (
- "inspect_optimizer_result",
- "Inspect optimizer result",
- "Read a bounded project-scoped optimizer experiment with iteration scores, candidate patches, winner state, and next action.",
- InspectOptimizerResultInput,
- InspectOptimizerResultOutput,
- _inspect_sync,
- True,
- True,
- "free",
- "sync",
- {"overmind:read"},
- ),
- ]
- for (
- name,
- title,
- description,
- input_model,
- output_model,
- function,
- read_only,
- idempotent,
- cost_class,
- async_mode,
- scopes,
- ) in definitions:
- catalog.register(
- ToolDefinition(
- name=name,
- title=title,
- description=description,
- input_model=input_model,
- output_model=output_model,
- read_only=read_only,
- idempotent=idempotent if name != "start_optimizer" else False,
- open_world=name == "start_optimizer",
- required_scopes=frozenset(scopes),
- cost_class=cost_class,
- async_mode=async_mode,
- ),
- sync_to_async(function, thread_sensitive=True),
- )
diff --git a/overbae/services/model_catalog.py b/overbae/services/model_catalog.py
index c96c35f1..8dda15db 100644
--- a/overbae/services/model_catalog.py
+++ b/overbae/services/model_catalog.py
@@ -174,27 +174,6 @@ def resolve_training_openrouter_slug(model_id: str) -> str | None:
return match["openrouter_id"] if match["openrouter_status"] == "available" else None
-def resolve_bare_openrouter_slug(model_name: str) -> str | None:
- """Canonical OpenRouter slug for a bare model name (no ``provider/`` prefix),
- or ``None`` when it cannot be resolved. Curated names win; otherwise the
- cached catalog is indexed by final path segment so base models like
- ``qwen3-8b`` resolve too.
- """
- name = normalize_model_name(model_name)
- if not name or "/" in name:
- return None
- if name in OPENROUTER_MODEL_SLUGS:
- return OPENROUTER_MODEL_SLUGS[name]
- models, upstream_available = fetch_model_catalog()
- if not upstream_available:
- return None
- by_last_segment: dict[str, str] = {}
- for entry in models:
- slug = entry.get("id") or ""
- by_last_segment.setdefault(slug.rsplit("/", 1)[-1], slug)
- return by_last_segment.get(name)
-
-
def estimate_cost(
model_name: str,
prompt_tokens: int | None,
diff --git a/overbae/services/optimizer_create.py b/overbae/services/optimizer_create.py
deleted file mode 100644
index f518dcf1..00000000
--- a/overbae/services/optimizer_create.py
+++ /dev/null
@@ -1,190 +0,0 @@
-"""Shared optimizer experiment creation — REST viewset and MCP tools.
-
-Every create door goes through here so the defaults, dataset gate and billing
-gates stay identical. The client drives execution; create only stores meta.
-"""
-
-from __future__ import annotations
-
-from django.conf import settings
-from rest_framework.exceptions import ValidationError
-
-from overbae.api.credit_gate import require_credits
-from overbae.core.model_registry import pricing_slug
-from overbae.models import DeployedModel, OptimizerExperiment
-from overbae.models.optimizer import optimizer_dataset_error
-from overbae.services.model_catalog import (
- is_model_available,
-)
-
-
-def validate_openrouter_key_source(source: str | None) -> str:
- """Validate the credential trust boundary. Persisted on every experiment for the
- audit trail, though only model-bearing runs use OpenRouter credentials.
- """
- source = source or OptimizerExperiment.OpenRouterKeySource.PLATFORM
- if source not in OptimizerExperiment.OpenRouterKeySource.values:
- raise ValidationError({"openrouter_key_source": "Choose Overmind credits or local .env."})
- return source
-
-
-def _is_finetuned_reference(model_id: str) -> bool:
- """True for a bare ``ft-…`` id; OpenRouter slugs always carry a ``provider/model``
- slash. The ``overmind/<capability-uuid>`` alias is deliberately not a valid optimiser
- reference — it chases the capability's active model, so a comparison could run a
- different model than the one picked.
- """
- return "/" not in model_id
-
-
-def _finetuned_reference_routable(model_id: str, project) -> bool:
- """READY deployment inside ``project`` — the resolution the chat gateway performs."""
- return (
- DeployedModel.objects.filter(project=project, model_id=model_id)
- .filter(status=DeployedModel.Status.READY)
- .exists()
- )
-
-
-def validate_optimizer_models(
- mode: str,
- model_ids,
- project=None,
- openrouter_key_source: str | None = None,
-) -> list[str]:
- """Accepts OpenRouter slugs from the live catalog plus ``ft-…`` ids for the
- project's own READY fine-tunes. Fine-tuned references route through Overmind's
- gateway only, so they are rejected when the run uses a local OpenRouter key.
- """
- model_ids = [] if model_ids is None else model_ids
- if mode == OptimizerExperiment.Mode.OPTIMIZE:
- if model_ids:
- raise ValidationError({"model_ids": "Normal optimization runs cannot select models."})
- return []
- if mode not in {
- OptimizerExperiment.Mode.MODEL_COMPARISON,
- OptimizerExperiment.Mode.HYBRID,
- }:
- raise ValidationError({"mode": "Unsupported optimizer mode."})
- if not isinstance(model_ids, list):
- raise ValidationError({"model_ids": "Expected a list of model slugs."})
- if not 1 <= len(model_ids) <= 5:
- raise ValidationError({"model_ids": "Select between 1 and 5 models."})
- if any(
- not isinstance(model_id, str) or not model_id or model_id != model_id.strip()
- for model_id in model_ids
- ):
- raise ValidationError({"model_ids": "Every model must be a non-empty model slug."})
- canonical_ids = [
- model_id if _is_finetuned_reference(model_id) else pricing_slug(model_id) or model_id
- for model_id in model_ids
- ]
- if len(set(canonical_ids)) != len(canonical_ids):
- raise ValidationError({"model_ids": "Duplicate models are not allowed."})
- if (
- any(_is_finetuned_reference(model_id) for model_id in model_ids)
- and openrouter_key_source == OptimizerExperiment.OpenRouterKeySource.LOCAL
- ):
- raise ValidationError(
- {
- "model_ids": (
- "Fine-tuned models route through Overmind's model gateway — "
- "select Overmind credits in the Model access step."
- )
- }
- )
- unavailable = [
- model_id
- for model_id in model_ids
- if not (
- is_model_available(model_id)
- if not _is_finetuned_reference(model_id)
- else project is not None and _finetuned_reference_routable(model_id, project)
- )
- ]
- if unavailable:
- raise ValidationError({"model_ids": f"Unavailable model: {', '.join(unavailable)}."})
- return canonical_ids
-
-
-def create_optimizer_experiment(
- *,
- user,
- capability,
- dataset=None,
- cell=None,
- eval_set=None,
- entrypoint: str = "",
- code_trigger: str = "",
- num_iterations: int = 5,
- num_candidates_per_iteration: int = 3,
- max_iterations_without_improvement: int = 3,
- initial_state: dict | None = None,
- mode: str = OptimizerExperiment.Mode.OPTIMIZE,
- model_ids: list[str] | None = None,
- openrouter_key_source: str = OptimizerExperiment.OpenRouterKeySource.PLATFORM,
-) -> OptimizerExperiment:
- openrouter_key_source = validate_openrouter_key_source(openrouter_key_source)
- model_ids = validate_optimizer_models(
- mode, model_ids, project=capability.project, openrouter_key_source=openrouter_key_source
- )
- if mode == OptimizerExperiment.Mode.MODEL_COMPARISON:
- # One iteration per model so the table reads as a per-model leaderboard.
- num_iterations = len(model_ids)
- num_candidates_per_iteration = 1
- max_iterations_without_improvement = 0
-
- if error := optimizer_dataset_error(capability, dataset, cell):
- raise ValidationError({"dataset": error})
- eval_set = eval_set or capability.active_eval_set
- if eval_set is not None and (
- eval_set.project_id != capability.project_id
- or eval_set.capability_id not in (None, capability.id)
- ):
- raise ValidationError(
- {"eval_set": "Eval set does not belong to this project or capability."}
- )
- entrypoint = entrypoint or capability.entrypoint_fn
-
- if user is not None:
- require_credits(user)
-
- # "Overmind credits" proxies to OpenRouter with the server key, so fail fast when
- # it is unset rather than 503ing mid-run. A local run uses only the client's
- # own key, which the server never sees.
- if (
- mode in {OptimizerExperiment.Mode.MODEL_COMPARISON, OptimizerExperiment.Mode.HYBRID}
- and openrouter_key_source == OptimizerExperiment.OpenRouterKeySource.PLATFORM
- and not getattr(settings, "OPENROUTER_API_KEY", "")
- ):
- raise ValidationError(
- {
- "openrouter": (
- "Overmind's model gateway is not configured on this server. "
- "Choose local .env instead."
- )
- }
- )
-
- from overbae.services.datasets import use # noqa: PLC0415 — avoid import cycle
-
- return OptimizerExperiment.objects.create(
- project=capability.project,
- capability=capability,
- dataset=dataset,
- cell=use.use(dataset, "eval", cell=cell),
- eval_set=eval_set,
- entrypoint=entrypoint,
- code_trigger=code_trigger,
- mode=mode,
- model_ids=model_ids,
- openrouter_key_source=openrouter_key_source,
- num_iterations=num_iterations,
- num_candidates_per_iteration=num_candidates_per_iteration,
- max_iterations_without_improvement=max_iterations_without_improvement,
- triggered_by=user,
- status=OptimizerExperiment.Status.SCHEDULED,
- state=initial_state or {},
- scores={},
- current_iteration=0,
- )
diff --git a/overbae/services/optimizer_ledger.py b/overbae/services/optimizer_ledger.py
deleted file mode 100644
index 4034b8ac..00000000
--- a/overbae/services/optimizer_ledger.py
+++ /dev/null
@@ -1,216 +0,0 @@
-"""Ledger write API — the server half of the client-side optimizer FSM.
-
-The client owns codegen, smoke testing, and command execution. These functions
-record what the client reports, drive the eval pipeline, and seal the experiment.
-"""
-
-from __future__ import annotations
-
-import logging
-
-from rest_framework.exceptions import ValidationError
-
-from overbae.models.optimizer import (
- OptimizerCandidate,
- OptimizerCommand,
- OptimizerExperiment,
- OptimizerIteration,
-)
-from overbae.services.activity import update_task
-
-logger = logging.getLogger(__name__)
-
-
-def set_command_template(experiment: OptimizerExperiment, template: str) -> OptimizerExperiment:
- """Store the client-generated command template. Experiment stays SCHEDULED."""
- experiment.command_template = (template or "").strip()
- experiment.save(update_fields=["command_template", "updated_at"])
- return experiment
-
-
-def create_iteration(
- experiment: OptimizerExperiment,
- *,
- order: int,
- name: str = "",
- candidates: list[dict],
-) -> OptimizerIteration:
- """Create an OptimizerIteration + OptimizerCandidate rows from client data.
-
- order=0 → baseline; advances experiment to BASELINE.
- order>0 → candidate round; advances experiment to ITERATING.
-
- ``candidates`` items: {candidate_index, code_path/patch, target_model, is_baseline}
- OptimizerCommand rows are NOT created here — the client posts results directly.
- """
- if not candidates:
- raise ValidationError({"candidates": "At least one candidate is required."})
- if order < 0:
- raise ValidationError({"order": "Iteration order must be 0 or greater."})
-
- iteration = OptimizerIteration.objects.create(
- experiment=experiment,
- order=order,
- name=name or ("Baseline" if order == 0 else f"Iteration {order}"),
- status=OptimizerIteration.Status.RUNNING_COMMANDS,
- )
-
- for cand_data in candidates:
- target_model = str(cand_data.get("target_model") or "")
- # A model-bearing candidate is a challenger: comparison runs its first
- # model at order 0, and generate_winner drops baselines from the table.
- OptimizerCandidate.objects.create(
- experiment=experiment,
- iteration=iteration,
- candidate_index=int(cand_data.get("candidate_index", 0)),
- code_path=str(cand_data.get("code_path") or cand_data.get("patch") or ""),
- target_model=target_model,
- is_baseline=bool(cand_data.get("is_baseline", order == 0 and not target_model)),
- status=OptimizerCandidate.Status.RUNNING_COMMANDS,
- )
-
- if order == 0:
- experiment.status = OptimizerExperiment.Status.BASELINE
- else:
- experiment.status = OptimizerExperiment.Status.ITERATING
- experiment.save(update_fields=["status", "updated_at"])
- return iteration
-
-
-def post_results(experiment: OptimizerExperiment, results: list[dict]) -> dict:
- """Upsert OptimizerCommand rows with client-reported execution outcomes.
-
- Each entry: {candidate_id, datapoint_index, success, output, trace_id?, error?, input?}
- ``input`` is copied from the dataset datapoint when not supplied.
- ``command`` is left blank — the client ran it locally.
- """
- if not isinstance(results, list):
- raise ValidationError({"results": "Expected a list of result objects."})
-
- from overbae.services.datasets import rows as row_store # noqa: PLC0415 — avoid import cycle
-
- datapoints_by_index: dict[int, object] = {}
- if experiment.cell_id:
- for dp in row_store.iter_rows(experiment.cell):
- datapoints_by_index[dp.index] = dp
-
- upserted = 0
- for entry in results:
- candidate_id = str(entry.get("candidate_id") or "")
- datapoint_index = int(entry.get("datapoint_index", 0))
- success = bool(entry.get("success", True))
- output = str(entry.get("output") or "")
- error = str(entry.get("error") or "")
- trace_id = str(entry.get("trace_id") or "")
- input_data = entry.get("input")
- if input_data is None:
- dp = datapoints_by_index.get(datapoint_index)
- input_data = dp.input if dp is not None else {}
-
- try:
- candidate = OptimizerCandidate.objects.select_related("iteration").get(
- experiment=experiment, id=candidate_id
- )
- except OptimizerCandidate.DoesNotExist:
- raise ValidationError(
- {"candidate_id": f"Candidate {candidate_id!r} not found in this experiment."}
- ) from None
-
- result_payload: dict = {}
- if output:
- result_payload["output"] = output
- if trace_id:
- result_payload["trace_id"] = trace_id
-
- OptimizerCommand.objects.update_or_create(
- experiment=experiment,
- candidate=candidate,
- iteration=candidate.iteration,
- datapoint_index=datapoint_index,
- defaults={
- "input": input_data,
- "output": output,
- "result": result_payload,
- "error": error,
- "status": (
- OptimizerCommand.Status.RAN if success else OptimizerCommand.Status.FAILED
- ),
- "command": "",
- },
- )
- upserted += 1
-
- candidate.recompute_status()
- candidate.iteration.recompute_status()
-
- return {"upserted": upserted}
-
-
-def evaluate_iteration(experiment: OptimizerExperiment, order: int) -> OptimizerExperiment:
- """Trigger EvalRun grading for one iteration after the client has finished running commands.
-
- Verifies all commands for the iteration are in a terminal status (RAN/PASSED/EVALUATED/FAILED),
- then sets EVALUATING_* and calls start_iteration_eval. If no runnable evaluators exist the
- stub scores synchronously and EVALUATED_* is set immediately.
- """
- try:
- iteration = OptimizerIteration.objects.get(experiment=experiment, order=order)
- except OptimizerIteration.DoesNotExist:
- raise ValidationError(
- {"order": f"Iteration {order} not found for this experiment."}
- ) from None
-
- _terminal = {
- OptimizerCommand.Status.RAN,
- OptimizerCommand.Status.PASSED,
- OptimizerCommand.Status.EVALUATED,
- OptimizerCommand.Status.FAILED,
- }
- non_terminal = experiment.commands.filter(iteration=iteration).exclude(status__in=_terminal)
- if non_terminal.exists():
- raise ValidationError(
- {
- "detail": (
- "Not all commands for this iteration are complete. "
- "Wait for all commands to reach RAN, PASSED, EVALUATED, or FAILED."
- )
- }
- )
-
- eval_status = (
- OptimizerExperiment.Status.EVALUATING_BASELINE_OUTPUTS
- if order == 0
- else OptimizerExperiment.Status.EVALUATING_CANDIDATE_OUTPUTS
- )
- experiment.status = eval_status
- if order > 0:
- # Track how far the client has progressed.
- experiment.current_iteration = max(experiment.current_iteration, order)
- experiment.save(update_fields=["status", "current_iteration", "updated_at"])
-
- experiment.start_iteration_eval(order)
- experiment.refresh_from_db()
- return experiment
-
-
-def complete_experiment(experiment: OptimizerExperiment) -> OptimizerExperiment:
- """Record the winner and mark the experiment COMPLETED.
-
- Safe to call from any non-terminal status; use after the last iteration's
- evaluate_iteration resolves (or when the client decides to stop early).
- """
- if experiment.status in (
- OptimizerExperiment.Status.COMPLETED,
- OptimizerExperiment.Status.FAILED,
- OptimizerExperiment.Status.CANCELLED,
- ):
- raise ValidationError({"detail": f"Experiment is already terminal ({experiment.status})."})
-
- experiment.generate_winner()
- experiment.status = OptimizerExperiment.Status.COMPLETED
- experiment._stop_children(reason="experiment completed")
- experiment.save()
- experiment.refresh_from_db()
-
- update_task(experiment.project_id, "optimizer_experiment", experiment.pk, "completed")
- return experiment
diff --git a/overbae/services/optimizer_prereqs.py b/overbae/services/optimizer_prereqs.py
deleted file mode 100644
index 8eee238f..00000000
--- a/overbae/services/optimizer_prereqs.py
+++ /dev/null
@@ -1,47 +0,0 @@
-"""Optimizer launch prerequisites — the readiness report behind MCP."""
-
-from __future__ import annotations
-
-from overbae.models import Capability, Dataset
-from overbae.models.optimizer import optimizer_dataset_error
-
-
-def optimizer_prerequisite_report(project, capability: Capability) -> dict:
- eval_set = capability.active_eval_set
-
- eval_qs = Dataset.objects.filter(
- project=project, capability=capability, intent=Dataset.Intent.EVAL
- ).order_by("-updated_at")[:10]
- eval_datasets = []
- for row in eval_qs:
- product = row.active_cell
- eval_datasets.append(
- {
- "id": str(row.id),
- "name": row.name or str(row.id)[:8],
- "rows": str(product.rows if product is not None else 0),
- "usable": optimizer_dataset_error(capability, row) is None,
- }
- )
- has_usable_dataset = any(row["usable"] for row in eval_datasets)
-
- missing: list[str] = []
- if not has_usable_dataset:
- missing.append(
- "eval dataset — pass dataset_name to create_optimizer_experiment "
- "(needs a frozen version whose contract is eval; use list_datasets)"
- )
- if eval_set is None:
- missing.append(
- "eval set — set the capability's active eval set or pass eval_set_name (use list_eval_sets)"
- )
-
- return {
- "capability": capability.slug,
- "ready": not missing,
- "missing": missing,
- "eval_set": eval_set.name if eval_set else None,
- "eval_datasets": eval_datasets or None,
- "drive_command": "overmind optimise start -c "
- f"{capability.slug} -d <dataset-id> && overmind optimise next",
- }
diff --git a/overbae/services/user_insights.py b/overbae/services/user_insights.py
index 9988dc14..a3a327b6 100644
--- a/overbae/services/user_insights.py
+++ b/overbae/services/user_insights.py
@@ -38,7 +38,6 @@ from overbae.models import (
EvalRun,
FinetuningJob,
InferenceCall,
- OptimizerExperiment,
Project,
ProjectMembership,
Span,
@@ -499,8 +498,5 @@ def user_activity(user: User, since: datetime) -> dict[str, Any]:
"by_intent": _counts(datasets, "intent"),
"daily": _daily(datasets.filter(created_at__gte=since), "created_at"),
},
- "optimizer": _workflow(
- OptimizerExperiment.objects.filter(project_id__in=project_ids), since
- ),
"evaluations": _workflow(EvalRun.objects.filter(project_id__in=project_ids), since),
}
diff --git a/overbae/settings.py b/overbae/settings.py
index 854d0865..d5e48b98 100644
--- a/overbae/settings.py
+++ b/overbae/settings.py
@@ -555,10 +555,6 @@ CELERY_BEAT_SCHEDULE = {
"task": "overbae.tasks.guest_cleanup.sweep_guest_workspaces",
"schedule": 86400.0,
},
- "reconcile-optimizer-experiments": {
- "task": "overbae.tasks.optimizer_reconciler.reconcile_optimizer_experiments",
- "schedule": 10.0,
- },
"reconcile-deployments": {
"task": "overbae.tasks.inference_controller.reconcile_deployments",
"schedule": 15.0,
diff --git a/overbae/tasks/__init__.py b/overbae/tasks/__init__.py
index d5b69e36..98f60303 100644
--- a/overbae/tasks/__init__.py
+++ b/overbae/tasks/__init__.py
@@ -18,7 +18,6 @@ from . import ( # noqa: E402
inference_requests,
innermind,
model_deployment,
- optimizer_reconciler,
queue_metrics,
training_experiments,
training_preparation,
@@ -40,7 +39,6 @@ __all__ = [
"inference_controller",
"inference_requests",
"innermind",
- "optimizer_reconciler",
"queue_metrics",
"model_deployment",
"process_span",
diff --git a/overbae/tasks/optimizer_reconciler.py b/overbae/tasks/optimizer_reconciler.py
deleted file mode 100644
index ab6dd9fd..00000000
--- a/overbae/tasks/optimizer_reconciler.py
+++ /dev/null
@@ -1,31 +0,0 @@
-"""Optimizer reconciler — re-drives stuck experiment FSMs after restarts or worker crashes."""
-
-import logging
-
-from celery import shared_task
-
-from overbae.tasks.utils.task_lock import with_task_lock
-
-logger = logging.getLogger(__name__)
-
-_DRIVE_STATUSES = frozenset(["evaluating_baseline_outputs", "evaluating_candidate_outputs"])
-
-
-@shared_task(name="overbae.tasks.optimizer_reconciler.reconcile_optimizer_experiments")
-@with_task_lock(lock_name="optimizer_reconciler", timeout=300)
-def reconcile_optimizer_experiments() -> dict:
- from overbae.models.optimizer import OptimizerExperiment, run_experiment_advance
-
- rows = list(
- OptimizerExperiment.objects.filter(status__in=_DRIVE_STATUSES).values_list("id", "status")
- )
- if not rows:
- logger.debug("optimizer reconciler: no non-terminal experiments")
- return {"dispatched": 0}
-
- for exp_id, status in rows:
- logger.info("optimizer reconciler dispatching advance exp=%s status=%s", exp_id, status)
- run_experiment_advance.delay(str(exp_id))
-
- logger.info("optimizer reconciler dispatched %d experiments", len(rows))
- return {"dispatched": len(rows)}
diff --git a/overbae/urls.py b/overbae/urls.py
index 37926bf7..ee40e13f 100644
--- a/overbae/urls.py
+++ b/overbae/urls.py
@@ -55,7 +55,6 @@ from overbae.api.inference_requests import (
)
from overbae.api.mcp_oauth import MCPConsentView
from overbae.api.native_evaluation import NativeEvaluationViewSet
-from overbae.api.optimizer import OptimizerCandidateViewSet, OptimizerExperimentViewSet
from overbae.api.otlp import otlp_traces
from overbae.api.overwatch_agent import OverwatchQueryView
from overbae.api.public_models import PublicModelLibraryDetailView, PublicModelLibraryListView
@@ -130,10 +129,6 @@ router.register(r"feedback", FeedbackViewSet, basename="feedback")
router.register(
r"connector-credentials", ConnectorCredentialViewSet, basename="connectorcredential"
)
-router.register(
- r"optimizer-experiments", OptimizerExperimentViewSet, basename="optimizer-experiment"
-)
-router.register(r"optimizer-candidates", OptimizerCandidateViewSet, basename="optimizer-candidate")
router.register(r"finetuning-jobs", FinetuningJobViewSet, basename="finetuningjob")
router.register(r"deployed-models", DeployedModelViewSet, basename="deployedmodel")
router.register(r"eval-matrix", EvalMatrixViewSet, basename="evalmatrix")
diff --git a/overmind/.claude-plugin/plugin.json b/overmind/.claude-plugin/plugin.json
index 4a5c2c44..83e62c77 100644
--- a/overmind/.claude-plugin/plugin.json
+++ b/overmind/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "overmind",
- "version": "1.2.14",
+ "version": "1.3.0",
"description": "Overmind skills — agent observability, tracing, and platform workflows for coding agents.",
"author": {
"name": "Overmind",
@@ -15,7 +15,6 @@
"observability",
"tracing",
"agent",
- "optimization",
"mcp"
],
"skills": "./skills/",
diff --git a/overmind/.codex-plugin/plugin.json b/overmind/.codex-plugin/plugin.json
index f3aefb51..7ce3ef52 100644
--- a/overmind/.codex-plugin/plugin.json
+++ b/overmind/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "overmind",
- "version": "1.2.14",
+ "version": "1.3.0",
"description": "Investigate agent failures, prepare datasets, evaluate models, and manage training and serving with Overmind.",
"author": {
"name": "Overmind",
@@ -16,7 +16,6 @@
"observability",
"tracing",
"agent",
- "optimization",
"mcp"
],
"skills": "./skills/",
diff --git a/overmind/.cursor-plugin/plugin.json b/overmind/.cursor-plugin/plugin.json
index 8e57fe16..73b17e0b 100644
--- a/overmind/.cursor-plugin/plugin.json
+++ b/overmind/.cursor-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "overmind",
"displayName": "Overmind",
- "version": "1.2.14",
+ "version": "1.3.0",
"description": "Overmind skills and MCP — agent observability, tracing, and platform tools for coding agents.",
"author": {
"name": "Overmind",
@@ -16,7 +16,6 @@
"observability",
"tracing",
"agent",
- "optimization",
"mcp"
],
"category": "developer-tools",
diff --git a/overmind/CHANGELOG.md b/overmind/CHANGELOG.md
index ec7ced54..64e52a2c 100644
--- a/overmind/CHANGELOG.md
+++ b/overmind/CHANGELOG.md
@@ -42,16 +42,16 @@ entries here cover the SDK surface.
- `overmind sync` reads the `expectations=` declared on the checkout's `entry_point`,
`workflow` and `observe` decorators and sends them with each synced capability; they never
enter `overmind.toml`. The platform adds them to the capability's Default eval set, so
- `overmind backtest`, optimiser runs and training evaluations judge the same criteria as
- live scoring. Run `overmind sync` again after decorating.
-- `overmind backtest` creates one run per target in a single eval-run group
- (`targets`, a `recorded` baseline plus one `generate` run per model) and gates
- on each candidate's `/comparison/` against the baseline.
+ eval runs and training evaluations judge the same criteria as live scoring. Run
+ `overmind sync` again after decorating.
- `overmind dataset upload` inspects the upload before creating the dataset; the
server now refuses an uninspected upload, so older CLI versions must upgrade.
### Added
+- `/overmind improve` and `/overmind compare-models`: helper workflows in the
+ `overmind` skill. A coding agent measures a prompt or code change with live
+ scoring, or scores other models on recorded calls with an eval run.
- `overmind dataset attach FILE --json` uploads a table without creating a
dataset and prints its `upload_id`, rows and sha256; a dataset script reads it
as the frame `attachment` through `try_dataset_script` or `add_dataset_version`.
@@ -97,6 +97,17 @@ entries here cover the SDK surface.
### Removed
+- `overmind optimise`, `overmind backtest`, the `overmind-optimiser` skill and the
+ `/overmind optimise` and `/overmind backtest` routes. The platform no longer runs
+ optimiser experiments or model comparisons. `overmind init` deletes the installed
+ `overmind-optimiser` skill.
+- The `overmind.attrs` constants for the `overmind.command`, `overmind.optimize.*`,
+ `overmind.setup.*`, `overmind.init.*`, `overmind.run.*`, `overmind.run_state.*`,
+ `overmind.candidates.*`, `overmind.seed_validation.*`, `overmind.seed_coverage.*`
+ and `overmind.coding_agent.*` attributes, the evaluator's `overmind.eval.*`
+ batch attributes (`EVAL_BATCH_SIZE` to `EVAL_SOURCE_SUMMARY`), and the
+ `OVERMIND_TRACE_FILE` trace-file mode the optimiser used.
+- `layer_cmd` is now `finetune_cmd`.
- `observe_safe` — use `observe(capture="none")` (or `init(redact_keys=...)`).
- `function`, `conversation`, `get_tracer`, `set_agent_id`, `set_agent_name`,
`set_project_id` are no longer exported; identity rides on
diff --git a/overmind/README.md b/overmind/README.md
index 07daacc9..0ad9ec29 100644
--- a/overmind/README.md
+++ b/overmind/README.md
@@ -28,7 +28,7 @@ Codex, Cursor or OpenCode, and asks the person to sign in once.
## Install
```bash
-pip install overmind # CLI (`overmind init`, sync, dataset/model files, optimiser)
+pip install overmind # CLI (`overmind init`, sync, dataset/model files, fine-tuning)
pip install "overmind[tracing]" # OpenTelemetry tracing (optional extra)
```
@@ -296,7 +296,6 @@ untouched. Codex loads project configuration only for trusted repositories.
| `overmind-observability` | Investigate traces, failures, latency and instrumentation gaps |
| `overmind-datasets` | Prepare, verify, generate and export Data Workshop versions |
| `overmind-evaluations` | Author eval matrix rows, prepare runs and compare results |
-| `overmind-optimiser` | Run prompt/code experiments and model comparisons |
| `overmind-training` | Prepare exact inputs, estimate costs and inspect fine-tuning |
| `overmind-inference` | Inspect serving metrics, worker state and live routing |
| `overmind-integrations` | Configure provider mappings and verify imported traces |
@@ -378,7 +377,6 @@ overmind dataset export DATASET Download committed rows as JSONL or CSV
overmind connector add TYPE Add a tracing connector from env or a TTY prompt
overmind model download-checkpoint DEPLOYMENT
Download an archived fine-tuned checkpoint
-overmind optimise [OPTIONS] SDK loop the /overmind optimise skill drives
overmind skills list [--verbose] List installed/available skills
overmind skills sync <name>... Sync one or more skills to the latest version
```
diff --git a/overmind/docs/tracing-attributes.md b/overmind/docs/tracing-attributes.md
index 2cfc6815..5dc6c8b9 100644
--- a/overmind/docs/tracing-attributes.md
+++ b/overmind/docs/tracing-attributes.md
@@ -11,7 +11,7 @@ Rules of the road:
inline a raw string.
- Token usage and cost use the **`genai.*`** keys (NOT the OTel semconv
`gen_ai.*`). The SDK *also* emits the `gen_ai.*` semconv keys alongside them so
- OTel-native consumers and the optimiser's `trace_reader` keep working, and the
+ OTel-native consumers keep working, and the
on-end enrichment processor mirrors any `gen_ai.*` usage produced by
third-party auto-instrumentors into these canonical keys.
- **Never zero-fill.** A token count / cost we don't have is omitted, so the
diff --git a/overmind/overmind/__init__.py b/overmind/overmind/__init__.py
index 16d3d94a..f7b3f4c3 100644
--- a/overmind/overmind/__init__.py
+++ b/overmind/overmind/__init__.py
@@ -1,7 +1,6 @@
"""
Overmind Python Client
-Overmind: autonomous agent optimisation through structured experimentation.
Overmind: automatic observability for LLM applications.
"""
@@ -10,7 +9,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any
-__version__ = "0.1.128"
+__version__ = "0.1.129"
from .client import Client, ModelDeleted, OvermindInferenceError
diff --git a/overmind/overmind/__main__.py b/overmind/overmind/__main__.py
index 6b39bf2f..3979ed60 100644
--- a/overmind/overmind/__main__.py
+++ b/overmind/overmind/__main__.py
@@ -1,4 +1,4 @@
-"""Overmind CLI — optimise LLM agents and manage agent skills.
+"""Overmind CLI — connect an agent to Overmind and manage agent skills.
Commands:
init Install skills, slash commands, MCP; seed overmind.toml.
@@ -9,8 +9,6 @@ Commands:
connector add TYPE Add a tracing connector from env or a TTY prompt.
model download-checkpoint DEPLOYMENT
Download a deployed model checkpoint locally.
- optimise Client-driven optimiser loop (skill generates diffs; server scores).
- backtest Score models on stored LLM calls.
finetune Start fine-tunes from stored LLM calls.
skills Manage Overmind agent skills.
@@ -29,11 +27,9 @@ try:
from overmind.connection_cmd import connection_app
from overmind.connector_cmd import connector_app
from overmind.dataset_cmd import dataset_app
+ from overmind.finetune_cmd import finetune as finetune_cmd
from overmind.init_cmd import init as init_cmd
- from overmind.layer_cmd import backtest as backtest_cmd
- from overmind.layer_cmd import finetune as finetune_cmd
from overmind.model_cmd import model_app
- from overmind.optimizer_cmd import OPTIMISE_HELP, optimise_app
from overmind.skills import skills_app
from overmind.sync import sync as sync_cmd
except ImportError as exc:
@@ -42,8 +38,8 @@ except ImportError as exc:
app = typer.Typer(
name="overmind",
- help="Overmind CLI — local skills, sync, tracing, optimiser client.",
- epilog="Overmind https://overmindlab.ai is a tool for optimising LLM agents and managing agent skills.",
+ help="Overmind CLI — local skills, sync, tracing, datasets and training.",
+ epilog="Overmind https://overmindlab.ai observes, evaluates and trains LLM agents.",
pretty_exceptions_enable=True,
no_args_is_help=True,
)
@@ -86,8 +82,6 @@ def common(
ctx.call_on_close(on_command_complete)
-app.add_typer(optimise_app, name="optimise", help=OPTIMISE_HELP)
-
app.add_typer(skills_app, name="skills")
app.add_typer(dataset_app, name="dataset")
app.add_typer(connection_app, name="connection")
@@ -96,7 +90,6 @@ app.add_typer(model_app, name="model")
app.command("init")(init_cmd)
app.command("sync")(sync_cmd)
app.command("chassis")(chassis_cmd)
-app.command("backtest")(backtest_cmd)
app.command("finetune")(finetune_cmd)
diff --git a/overmind/overmind/attrs.py b/overmind/overmind/attrs.py
index 7332ae33..d3429d6b 100644
--- a/overmind/overmind/attrs.py
+++ b/overmind/overmind/attrs.py
@@ -18,9 +18,6 @@ adding or renaming keys.
from __future__ import annotations
-# Top-level command tag (set on every CLI entry-point span).
-COMMAND = "overmind.command"
-
# Generic lifecycle tags — explicit status / progress markers we set on any
# span so the platform can surface "what's happening?" without parsing the
# OTel ``status_code`` directly.
@@ -52,143 +49,6 @@ WORKFLOW_NAME = "overmind.workflow.name"
# traces under the same user-visible session.
CONVERSATION_ID = "overmind.conversation.id"
-# `overmind init` (overmind/commands/init_cmd.py)
-INIT_ENV_PATH = "overmind.init.env_path"
-INIT_HAS_OPENAI_KEY = "overmind.init.has_openai_key"
-INIT_HAS_ANTHROPIC_KEY = "overmind.init.has_anthropic_key"
-INIT_HAS_OVERMIND_TOKEN = "overmind.init.has_overmind_token"
-INIT_ANALYZER_MODEL = "overmind.init.analyzer_model"
-INIT_HAS_SYNTHETIC_DATAGEN_MODEL = "overmind.init.has_synthetic_datagen_model"
-
-# `overmind setup` (overmind/commands/setup_cmd.py +
-# overmind/setup/{questionnaire,policy_generator}.py)
-SETUP_FAST = "overmind.setup.fast"
-SETUP_MODEL = "overmind.setup.model"
-SETUP_HAS_POLICY = "overmind.setup.has_policy"
-SETUP_HAS_SEED_DATA = "overmind.setup.has_seed_data"
-SETUP_POLICY_PATH = "overmind.setup.policy_path"
-SETUP_DATA_PATH = "overmind.setup.data_path"
-SETUP_STORAGE_BACKEND = "overmind.setup.storage_backend"
-SETUP_ENTRYPOINT_FN = "overmind.setup.entrypoint_fn"
-SETUP_ANALYZER_MODEL = "overmind.setup.analyzer_model"
-SETUP_PHASE = "overmind.setup.phase"
-SETUP_EVAL_SPEC_FIELD_COUNT = "overmind.setup.eval_spec_field_count"
-SETUP_EVAL_SPEC_HAS_TOOLS = "overmind.setup.eval_spec_has_tools"
-SETUP_EVAL_SPEC_HAS_JUDGE = "overmind.setup.eval_spec_has_judge"
-SETUP_EVAL_SPEC_HAS_POLICY = "overmind.setup.eval_spec_has_policy"
-SETUP_EVAL_SPEC_STRUCTURE_WEIGHT = "overmind.setup.eval_spec_structure_weight"
-SETUP_EVAL_SPEC_TOOL_COUNT = "overmind.setup.eval_spec_tool_count"
-SETUP_EVAL_SPEC_CONSISTENCY_RULE_COUNT = "overmind.setup.eval_spec_consistency_rule_count"
-SETUP_CRITERIA_SOURCE = "overmind.setup.criteria_source"
-SETUP_POLICY_SOURCE = "overmind.setup.policy_source"
-# Agent description and full eval spec snapshot (text / JSON string).
-SETUP_EVAL_SPEC = "overmind.setup.eval_spec"
-# Post-analysis artefacts from the setup pipeline.
-SETUP_PROPOSED_CRITERIA = "overmind.setup.proposed_criteria"
-SETUP_TOOL_ANALYSIS = "overmind.setup.tool_analysis"
-SETUP_INPUT_SCHEMA = "overmind.setup.input_schema"
-SETUP_OUTPUT_SCHEMA = "overmind.setup.output_schema"
-SETUP_CONSISTENCY_RULES = "overmind.setup.consistency_rules"
-SETUP_TOOLS_SUMMARY = "overmind.setup.tools_summary"
-SETUP_DECISION_LOGIC = "overmind.setup.decision_logic"
-SETUP_SCOPE = "overmind.setup.scope"
-SETUP_OPTIMIZABLE_ELEMENTS = "overmind.setup.optimizable_elements"
-
-# `overmind optimise` (overmind/commands/optimize_cmd.py)
-OPTIMIZE_FAST = "overmind.optimize.fast"
-OPTIMIZE_ENTRYPOINT_FN = "overmind.optimize.entrypoint_fn"
-OPTIMIZE_STORAGE_BACKEND = "overmind.optimize.storage_backend"
-OPTIMIZE_ANALYZER_MODEL = "overmind.optimize.analyzer_model"
-OPTIMIZE_LLM_JUDGE_MODEL = "overmind.optimize.llm_judge_model"
-OPTIMIZE_ITERATIONS = "overmind.optimize.iterations"
-OPTIMIZE_CANDIDATES_PER_ITERATION = "overmind.optimize.candidates_per_iteration"
-OPTIMIZE_PARALLEL = "overmind.optimize.parallel"
-OPTIMIZE_MAX_WORKERS = "overmind.optimize.max_workers"
-OPTIMIZE_RUNS_PER_EVAL = "overmind.optimize.runs_per_eval"
-OPTIMIZE_REGRESSION_THRESHOLD = "overmind.optimize.regression_threshold"
-OPTIMIZE_HOLDOUT_RATIO = "overmind.optimize.holdout_ratio"
-OPTIMIZE_HOLDOUT_ENFORCEMENT = "overmind.optimize.holdout_enforcement"
-OPTIMIZE_EARLY_STOPPING_PATIENCE = "overmind.optimize.early_stopping_patience"
-OPTIMIZE_CROSS_RUN_PERSISTENCE = "overmind.optimize.cross_run_persistence"
-OPTIMIZE_FAILURE_CLUSTERING = "overmind.optimize.failure_clustering"
-OPTIMIZE_ADAPTIVE_FOCUS = "overmind.optimize.adaptive_focus"
-OPTIMIZE_MODEL_BACKTESTING = "overmind.optimize.model_backtesting"
-OPTIMIZE_BACKTEST_MODELS = "overmind.optimize.backtest_models"
-OPTIMIZE_EVAL_SPEC_PATH = "overmind.optimize.eval_spec_path"
-OPTIMIZE_DATA_PATH = "overmind.optimize.data_path"
-# Full eval_spec.json (JSON string) for OTLP ingest to refresh Agent eval fields during optimise.
-OPTIMIZE_EVAL_SPEC = "overmind.optimize.eval_spec"
-
-# Optimiser pipeline (overmind/optimize/optimizer.py) — runtime tags emitted
-# from the optimiser's spans during a run.
-OPTIMIZE_PHASE = "overmind.optimize.phase"
-OPTIMIZE_DATASET_TOTAL = "overmind.optimize.dataset_total"
-OPTIMIZE_DATASET_TRAIN = "overmind.optimize.dataset_train"
-OPTIMIZE_DATASET_HOLDOUT = "overmind.optimize.dataset_holdout"
-OPTIMIZE_BASELINE_SCORE = "overmind.optimize.baseline_score"
-OPTIMIZE_ITERATION = "overmind.optimize.iteration"
-OPTIMIZE_TOTAL_ITERATIONS = "overmind.optimize.total_iterations"
-OPTIMIZE_BEST_SCORE_BEFORE = "overmind.optimize.best_score_before"
-OPTIMIZE_STALL_COUNT = "overmind.optimize.stall_count"
-OPTIMIZE_TEMPERATURE = "overmind.optimize.temperature"
-OPTIMIZE_N_CANDIDATES_GENERATED = "overmind.optimize.n_candidates_generated"
-OPTIMIZE_N_CANDIDATES_VALID = "overmind.optimize.n_candidates_valid"
-OPTIMIZE_CANDIDATE_INDEX = "overmind.optimize.candidate_index"
-OPTIMIZE_CANDIDATE_METHOD = "overmind.optimize.candidate_method"
-OPTIMIZE_CANDIDATE_SCORE = "overmind.optimize.candidate_score"
-OPTIMIZE_CANDIDATE_ADJUSTED_SCORE = "overmind.optimize.candidate_adjusted_score"
-OPTIMIZE_COMPLEXITY_PENALTY = "overmind.optimize.complexity_penalty"
-OPTIMIZE_ITERATION_DECISION = "overmind.optimize.iteration_decision"
-OPTIMIZE_ITERATION_SCORE = "overmind.optimize.iteration_score"
-OPTIMIZE_ITERATION_IMPROVEMENT = "overmind.optimize.iteration_improvement"
-OPTIMIZE_ITERATION_REASON = "overmind.optimize.iteration_reason"
-# Skill-driven flow identifiers — each ``overmind optimize-step`` call
-# stamps its phase here so OTLP can attribute every span back to its
-# step (init / baseline / diagnose / evaluate / accept / report).
-OPTIMIZE_STEP = "overmind.optimize.step"
-# Terminal state of the optimise run. ``running`` while in flight,
-# flipped to ``completed`` / ``failed`` / ``cancelled`` by the step
-# that owns end-of-run. OTLP uses this (alongside the legacy
-# ``is_optimize_root`` heuristic) to drive ``Job.status``.
-OPTIMIZE_RUN_STATUS = "overmind.optimize.run_status"
-# Per-dimension scores for the iteration (e.g. ``{"correctness": 87.0,
-# "tool_use": 64.2}``). Serialised as JSON because OTel attributes
-# cannot carry nested dicts directly.
-OPTIMIZE_ITERATION_DIMENSION_SCORES = "overmind.optimize.iteration_dimension_scores"
-# Full agent source code produced by the iteration's best candidate.
-# Stamped on the ``optimizer.iteration`` span so OTLP can project it
-# onto ``JobIteration.agent_code``.
-OPTIMIZE_ITERATION_AGENT_CODE = "overmind.optimize.iteration_agent_code"
-# JSON-encoded list of human-readable change summaries (the
-# ``suggestions`` field of the best candidate). OTLP folds these into
-# ``JobIteration.description``.
-OPTIMIZE_ITERATION_SUGGESTIONS = "overmind.optimize.iteration_suggestions"
-OPTIMIZE_ACCEPTED = "overmind.optimize.accepted"
-OPTIMIZE_FINAL_BEST_SCORE = "overmind.optimize.final_best_score"
-# Final report.md text produced by ``Optimizer._generate_report``.
-# Stamped on the optimise run span so OTLP can persist it on the
-# corresponding ``Job.report_markdown`` row.
-OPTIMIZE_REPORT_MARKDOWN = "overmind.optimize.report_markdown"
-# Final best agent code text (``Job.best_agent_code``).
-OPTIMIZE_BEST_AGENT_CODE = "overmind.optimize.best_agent_code"
-OPTIMIZE_HOLDOUT_SCORE = "overmind.optimize.holdout_score"
-OPTIMIZE_HOLDOUT_BASELINE_SCORE = "overmind.optimize.holdout_baseline_score"
-OPTIMIZE_HOLDOUT_IMPROVEMENT = "overmind.optimize.holdout_improvement"
-OPTIMIZE_BLENDED_IMPROVEMENT = "overmind.optimize.blended_improvement"
-OPTIMIZE_HOLDOUT_REVERTED = "overmind.optimize.holdout_reverted"
-# Train-vs-holdout score gap (positive = train score is higher than
-# holdout, i.e. overfitting). Projected onto
-# ``Job.result["holdout"]["overfit_gap"]``.
-OPTIMIZE_OVERFIT_GAP = "overmind.optimize.overfit_gap"
-# End-of-run summary counters, projected onto ``Job.result["summary"]``.
-OPTIMIZE_TOTAL_ACCEPTED = "overmind.optimize.total_accepted"
-OPTIMIZE_TOTAL_REJECTED = "overmind.optimize.total_rejected"
-# Final headline improvement (``best_score - baseline_score``) — drives
-# ``Job.improvement`` in the OTLP ingest.
-OPTIMIZE_REPORT_IMPROVEMENT = "overmind.optimize.report_improvement"
-OPTIMIZE_BACKTEST_MODEL = "overmind.optimize.backtest_model"
-OPTIMIZE_BACKTEST_SCORE = "overmind.optimize.backtest_score"
-
# Runtime eval envelope (overmind/evals.py) — SPAN EVENT names plus the two
# attributes every envelope event carries. These are wire contract v1: the
# platform parses them server-side (see docs/tracing-attributes.md §6), so
@@ -218,107 +78,6 @@ INTENT = "overmind.intent"
EXPECTATIONS = "overmind.expectations"
REFERENCE_TRAJECTORY = "overmind.reference_trajectory"
-# Evaluator (overmind/optimize/evaluator.py)
-EVAL_BATCH_SIZE = "overmind.eval.batch_size"
-EVAL_AVG_TOTAL = "overmind.eval.avg_total"
-EVAL_USED_LLM_JUDGE = "overmind.eval.used_llm_judge"
-EVAL_JUDGE_NEEDS_COUNT = "overmind.eval.judge_needs_count"
-EVAL_JUDGE_FAIL_COUNT = "overmind.eval.judge_fail_count"
-EVAL_JUDGE_FAIL_PCT = "overmind.eval.judge_fail_pct"
-EVAL_AVG_CONFIDENCE = "overmind.eval.avg_confidence"
-EVAL_SOURCE_SUMMARY = "overmind.eval.source_summary"
-# Per-run agent execution telemetry (run_agent_on_dataset / parallel /
-# sequential subprocess spans). These let the platform UI distinguish
-# baseline / candidate / holdout runs and surface backend health.
-RUN_AGENT_RUN_NAME = "overmind.run.run_name"
-RUN_AGENT_AGENT_PATH = "overmind.run.agent_path"
-RUN_AGENT_CASES_TOTAL = "overmind.run.cases_total"
-RUN_AGENT_CASES_SUCCEEDED = "overmind.run.cases_succeeded"
-RUN_AGENT_CASES_FAILED = "overmind.run.cases_failed"
-RUN_AGENT_CASES_WITH_PROVENANCE = "overmind.run.cases_with_provenance"
-RUN_AGENT_PARALLEL = "overmind.run.parallel"
-RUN_AGENT_MAX_WORKERS = "overmind.run.max_workers"
-RUN_AGENT_BACKENDS = "overmind.run.backends"
-RUN_AGENT_BACKEND_USED = "overmind.run.backend_used"
-# Aggregated batch evaluation results — stamped on the
-# ``optimizer.run_agent_on_dataset`` and ``optimizer.build_eval_results``
-# spans once every case has been scored.
-RUN_AGENT_AVG_SCORE = "overmind.run.avg_score"
-RUN_AGENT_DIMENSION_SCORES = "overmind.run.dimension_scores"
-RUN_AGENT_PASS_RATE = "overmind.run.pass_rate"
-RUN_AGENT_DURATION_SECONDS = "overmind.run.duration_seconds"
-RUN_AGENT_PER_CASE_SCORES = "overmind.run.per_case_scores"
-
-# Per-case telemetry (``optimizer.run_case_with_plan``) — one span per
-# datapoint, lets the UI drill down from a run into the individual
-# subprocess invocations and the backend fallback decisions.
-RUN_CASE_RUN_NAME = "overmind.run.case.run_name"
-RUN_CASE_INDEX = "overmind.run.case.index"
-RUN_CASE_INPUT_KEYS = "overmind.run.case.input_keys"
-RUN_CASE_INPUT_CHARS = "overmind.run.case.input_chars"
-RUN_CASE_BACKEND_ATTEMPTS = "overmind.run.case.backend_attempts"
-RUN_CASE_BACKENDS_TRIED = "overmind.run.case.backends_tried"
-RUN_CASE_BACKEND_USED = "overmind.run.case.backend_used"
-RUN_CASE_SUCCESS = "overmind.run.case.success"
-RUN_CASE_RETURNCODE = "overmind.run.case.returncode"
-RUN_CASE_ERROR = "overmind.run.case.error"
-RUN_CASE_OUTPUT_CHARS = "overmind.run.case.output_chars"
-RUN_CASE_DURATION_SECONDS = "overmind.run.case.duration_seconds"
-RUN_CASE_PROVENANCE_COUNT = "overmind.run.case.provenance_count"
-RUN_CASE_CONFIDENCE = "overmind.run.case.confidence"
-
-# ``optimizer.evaluate_worktree`` — invoked from the skill-driven
-# `overmind optimize-step evaluate` flow, scores a worktree's candidate
-# agent against the training set. These tags let the UI surface
-# per-candidate / per-iteration scores even when the optimiser is being
-# driven from a host coding agent rather than the legacy loop.
-OPTIMIZE_WORKTREE_RUN_NAME = "overmind.optimize.worktree.run_name"
-OPTIMIZE_WORKTREE_ENTRY_PATH = "overmind.optimize.worktree.entry_path"
-OPTIMIZE_WORKTREE_CASES_TOTAL = "overmind.optimize.worktree.cases_total"
-OPTIMIZE_WORKTREE_AVG_SCORE = "overmind.optimize.worktree.avg_score"
-OPTIMIZE_WORKTREE_DIMENSION_SCORES = "overmind.optimize.worktree.dimension_scores"
-OPTIMIZE_WORKTREE_PASS_RATE = "overmind.optimize.worktree.pass_rate"
-OPTIMIZE_WORKTREE_DURATION_SECONDS = "overmind.optimize.worktree.duration_seconds"
-
-# Cross-run optimisation state (overmind/optimize/run_state.py)
-RUN_STATE_TOTAL_RUNS = "overmind.run_state.total_runs"
-RUN_STATE_REGRESSION_CASES = "overmind.run_state.regression_cases"
-RUN_STATE_FAILURE_CLUSTERS = "overmind.run_state.failure_clusters"
-RUN_STATE_LATEST_BASELINE = "overmind.run_state.latest_baseline"
-RUN_STATE_LATEST_FINAL = "overmind.run_state.latest_final"
-RUN_STATE_LATEST_ACCEPTED = "overmind.run_state.latest_accepted"
-RUN_STATE_LATEST_REJECTED = "overmind.run_state.latest_rejected"
-
-# Candidate generation (overmind/optimize/analyzer.py)
-CANDIDATES_REQUESTED = "overmind.candidates.requested"
-CANDIDATES_PRODUCED = "overmind.candidates.produced"
-CANDIDATES_METHODS = "overmind.candidates.methods"
-CANDIDATES_HAS_DIAGNOSIS = "overmind.candidates.has_diagnosis"
-CANDIDATES_USE_BUNDLE = "overmind.candidates.use_bundle"
-CANDIDATES_HAS_ROOT_CAUSE = "overmind.candidates.has_root_cause"
-CANDIDATES_FALLBACK = "overmind.candidates.fallback"
-
-# Seed data validation / coverage (overmind/optimize/data_analyzer.py)
-SEED_VALIDATION_TOTAL_CASES = "overmind.seed_validation.total_cases"
-SEED_VALIDATION_VALID_COUNT = "overmind.seed_validation.valid_count"
-SEED_VALIDATION_INVALID_COUNT = "overmind.seed_validation.invalid_count"
-SEED_COVERAGE_QUALITY_SCORE = "overmind.seed_coverage.quality_score"
-SEED_COVERAGE_CASE_COUNT = "overmind.seed_coverage.case_count"
-SEED_COVERAGE_GAP_COUNT = "overmind.seed_coverage.gap_count"
-SEED_COVERAGE_UNCOVERED_RULE_COUNT = "overmind.seed_coverage.uncovered_rule_count"
-SEED_COVERAGE_SUGGESTED_ADDITIONAL_CASES = "overmind.seed_coverage.suggested_additional_cases"
-
-# Coding agent (overmind/coding_agent/{__init__,agent}.py)
-CODING_AGENT_MODEL = "overmind.coding_agent.model"
-CODING_AGENT_INPUT_FILE_COUNT = "overmind.coding_agent.input_file_count"
-CODING_AGENT_MODIFIED_FILE_COUNT = "overmind.coding_agent.modified_file_count"
-CODING_AGENT_STEPS_TAKEN = "overmind.coding_agent.steps_taken"
-CODING_AGENT_MAX_STEPS = "overmind.coding_agent.max_steps"
-CODING_AGENT_TOKENS_IN = "overmind.coding_agent.tokens_in"
-CODING_AGENT_TOKENS_OUT = "overmind.coding_agent.tokens_out"
-CODING_AGENT_LOOP_STEPS = "overmind.coding_agent.loop_steps"
-CODING_AGENT_EXIT_REASON = "overmind.coding_agent.exit_reason"
-
# LLM call metadata — CANONICAL ``genai.*`` contract
#
# These are the keys the Overmind server actually reads (see
@@ -328,8 +87,7 @@ CODING_AGENT_EXIT_REASON = "overmind.coding_agent.exit_reason"
# (NOT the OTel semconv ``input_tokens`` / ``output_tokens``).
#
# The SDK ALSO emits the OTel semconv ``gen_ai.*`` keys below (see
-# ``OTEL_*``) so third-party consumers and the optimiser's ``trace_reader``
-# keep working, and the on-end enrichment processor mirrors any ``gen_ai.*``
+# ``OTEL_*``) so third-party consumers keep working, and the on-end enrichment processor mirrors any ``gen_ai.*``
# usage produced by auto-instrumentors into these canonical keys.
LLM_MODEL = "genai.model"
LLM_RESPONSE_MODEL = "genai.response.model"
@@ -367,8 +125,7 @@ LLM_USAGE_TOTAL_TOKENS = "genai.usage.total_tokens"
# OpenTelemetry GenAI semantic-convention keys.
#
# Emitted ALONGSIDE the canonical ``genai.*`` keys above so OTel-native
-# consumers and the optimiser's ``trace_reader`` (which parses local JSONL
-# traces) keep resolving model + tokens. Never read these on the server —
+# consumers keep resolving model + tokens. Never read these on the server —
# read the canonical ``genai.*`` keys instead.
OTEL_LLM_REQUEST_MODEL = "gen_ai.request.model"
OTEL_LLM_SYSTEM = "gen_ai.system"
@@ -404,8 +161,7 @@ VCS_REF_HEAD_REVISION = "vcs.ref.head.revision"
# Span-level classification / error summary
# Human-readable summary string attached when a span fails. ``ERROR_TYPE``
# and ``ERROR_MESSAGE`` carry the structured (class name + scrubbed
-# message) pair; ``ERROR_SUMMARY`` is the free-form line the UI renders
-# next to the failed iteration.
+# message) pair; ``ERROR_SUMMARY`` is the free-form line the UI renders.
ERROR_SUMMARY = "overmind.error"
# Explicit span-type override — set to SpanType values when the heuristic
# classification would be wrong (e.g. "entry_point", "tool", "workflow").
diff --git a/overmind/overmind/backtest.py b/overmind/overmind/backtest.py
deleted file mode 100644
index dea4a42a..00000000
--- a/overmind/overmind/backtest.py
+++ /dev/null
@@ -1,56 +0,0 @@
-"""OpenRouter helpers for local model comparison.
-
-The ``/overmind backtest`` skill rewrites the user's repo onto OpenRouter, runs
-the eval dataset locally, and posts outputs. The CLI command only prints how.
-``openrouter_env`` is the env overlay hybrid ``overmind optimise --model`` uses.
-"""
-
-from __future__ import annotations
-
-import json
-import os
-from pathlib import Path
-
-OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
-STATE_PATH = Path(".overmind") / "backtest_state.json"
-
-
-def openrouter_env(model: str) -> dict[str, str]:
- """Env overlay that forces OpenAI-compatible clients onto OpenRouter + ``model``."""
- key = os.environ.get("OPENROUTER_API_KEY") or os.environ.get("OPENAI_API_KEY") or ""
- if not key:
- raise RuntimeError(
- "OPENROUTER_API_KEY is required for OpenRouter routing. "
- "Export it (or set OPENAI_API_KEY) before running models."
- )
- return {
- "OPENROUTER_API_KEY": key,
- "OPENROUTER_MODEL": model,
- "OPENAI_API_KEY": key,
- "OPENAI_BASE_URL": OPENROUTER_BASE_URL,
- "OPENAI_API_BASE": OPENROUTER_BASE_URL,
- "OR_SITE_URL": os.environ.get("OR_SITE_URL", "https://overmindlab.ai"),
- "OR_APP_NAME": os.environ.get("OR_APP_NAME", "overmind-backtest"),
- }
-
-
-def write_state(root: str | os.PathLike[str], payload: dict) -> Path:
- """Persist backtest experiment id next to the dataset cache."""
- path = Path(root) / STATE_PATH
- path.parent.mkdir(parents=True, exist_ok=True)
- existing: dict = {}
- if path.exists():
- try:
- existing = json.loads(path.read_text())
- except (json.JSONDecodeError, OSError):
- existing = {}
- existing.update(payload)
- path.write_text(json.dumps(existing, indent=2))
- return path
-
-
-def rewrite_repo(root: str | os.PathLike[str] = "."):
- """Rewrite LLM clients under *root* onto OpenRouter. See openrouter_rewrite."""
- from overmind.openrouter_rewrite import rewrite_repo as _rewrite
-
- return _rewrite(root)
diff --git a/overmind/overmind/layer_cmd.py b/overmind/overmind/finetune_cmd.py
similarity index 55%
rename from overmind/overmind/layer_cmd.py
rename to overmind/overmind/finetune_cmd.py
index 69651f37..e074acca 100644
--- a/overmind/overmind/layer_cmd.py
+++ b/overmind/overmind/finetune_cmd.py
@@ -1,4 +1,4 @@
-"""Score or fine-tune from stored LLM calls. The application is not run."""
+"""Fine-tune from stored LLM calls. The application is not run."""
from __future__ import annotations
@@ -18,28 +18,26 @@ from overmind.config import DEFAULT_PATH, Config, load, resolve_api_credentials
console = Console()
-BACKTEST_CAP = 5
FINETUNE_CAP = 4
_DURATION = re.compile(r"^(\d+)([dhm])$")
-_PASS = {"improved", "unchanged"}
-class LayerError(Exception):
+class FinetuneError(Exception):
def __init__(self, message: str, *, code: int = 1):
super().__init__(message)
self.code = code
-def parse_models(values: list[str] | None, *, cap: int) -> list[str]:
+def parse_models(values: list[str] | None) -> list[str]:
models: list[str] = []
for value in values or []:
models.extend(part.strip() for part in value.split(",") if part.strip())
if not models:
- raise LayerError(f"Pass between 1 and {cap} models with --models.")
+ raise FinetuneError(f"Pass between 1 and {FINETUNE_CAP} models with --models.")
if len(models) != len(set(models)):
- raise LayerError("Duplicate models are not allowed.")
- if len(models) > cap:
- raise LayerError(f"Select between 1 and {cap} models.")
+ raise FinetuneError("Duplicate models are not allowed.")
+ if len(models) > FINETUNE_CAP:
+ raise FinetuneError(f"Select between 1 and {FINETUNE_CAP} models.")
return models
@@ -61,7 +59,7 @@ def parse_until(value: str) -> datetime | None:
def parse_timeout(value: str) -> float:
match = _DURATION.match(value.strip())
if not match:
- raise LayerError("timeout must look like 45m, 2h or 1d.")
+ raise FinetuneError("timeout must look like 45m, 2h or 1d.")
count, unit = int(match.group(1)), match.group(2)
scale = {"m": 60, "h": 3600, "d": 86400}[unit]
return float(count * scale)
@@ -72,7 +70,7 @@ def _parse_iso(value: str, *, what: str) -> datetime:
try:
parsed = datetime.fromisoformat(text)
except ValueError as exc:
- raise LayerError(f"{what} must be an ISO timestamp or a duration like 7d.") from exc
+ raise FinetuneError(f"{what} must be an ISO timestamp or a duration like 7d.") from exc
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed
@@ -88,13 +86,13 @@ def resolve_capability(config: Config, reference: str) -> tuple[str, str]:
try:
return str(uuid.UUID(reference)), reference[:8]
except ValueError as exc:
- raise LayerError("Capability not found in overmind.toml. Pass its slug or id.") from exc
+ raise FinetuneError("Capability not found in overmind.toml. Pass its slug or id.") from exc
if len(caps) == 1:
cap = caps[0]
return cap.id, cap.slug or cap.id[:8]
if not caps:
- raise LayerError("Pass --capability. overmind.toml has no capability id.")
- raise LayerError("Pass --capability. overmind.toml has more than one.")
+ raise FinetuneError("Pass --capability. overmind.toml has no capability id.")
+ raise FinetuneError("Pass --capability. overmind.toml has more than one.")
class Client:
@@ -118,21 +116,9 @@ class Client:
if dataset.get("state") == "idle":
return dataset
if dataset.get("state") == "error":
- raise LayerError(dataset.get("error") or "Landing failed.")
+ raise FinetuneError(dataset.get("error") or "Landing failed.")
if self.clock() >= deadline:
- raise LayerError("Timed out waiting for the dataset.", code=2)
- self.sleep(2)
-
- def wait_eval(self, run_id: str, *, deadline: float) -> dict[str, Any]:
- while True:
- run = self.get(f"/api/eval-runs/{run_id}/")
- status = run.get("status")
- if status == "completed":
- return run
- if status in {"failed", "cancelled"}:
- raise LayerError(run.get("error") or f"Evaluation {status}.")
- if self.clock() >= deadline:
- raise LayerError("Timed out waiting for the evaluation.", code=2)
+ raise FinetuneError("Timed out waiting for the dataset.", code=2)
self.sleep(2)
@@ -149,7 +135,7 @@ def _json(response: requests.Response, operation: str) -> dict[str, Any]:
detail = raw if isinstance(raw, str) else json.dumps(raw, ensure_ascii=False)
elif getattr(response, "text", ""):
detail = str(response.text)[:400]
- raise LayerError(detail or f"{operation} failed ({response.status_code}).")
+ raise FinetuneError(detail or f"{operation} failed ({response.status_code}).")
def _cell_id(dataset: dict[str, Any]) -> str:
@@ -157,7 +143,7 @@ def _cell_id(dataset: dict[str, Any]) -> str:
return str(dataset["active"])
cells = dataset.get("cells") or []
if not cells:
- raise LayerError("The dataset has no version.")
+ raise FinetuneError("The dataset has no version.")
return str(cells[0]["id"])
@@ -181,13 +167,6 @@ def _selection(
return body
-def _openrouter_ids(client: Client) -> set[str]:
- catalog = client.get("/api/models/catalog/")
- if catalog.get("upstream_available") is False:
- raise LayerError("The model catalog is unavailable.")
- return {str(item.get("id")) for item in catalog.get("models") or [] if item.get("id")}
-
-
def _finetune_ids(client: Client) -> set[str]:
catalog = client.get("/api/finetuning-jobs/models/")
found: set[str] = set()
@@ -203,106 +182,11 @@ def _finetune_ids(client: Client) -> set[str]:
return found
-def _require_models(client: Client, models: list[str], *, finetune: bool) -> None:
- known = _finetune_ids(client) if finetune else _openrouter_ids(client)
+def _require_models(client: Client, models: list[str]) -> None:
+ known = _finetune_ids(client)
missing = [model for model in models if model not in known]
if missing:
- raise LayerError(f"Unknown model: {', '.join(missing)}.")
-
-
-def _metric_errors(run: dict[str, Any]) -> int:
- metrics = (run.get("summary") or {}).get("metrics") or {}
- return sum(int(row.get("errors") or 0) for row in metrics.values() if isinstance(row, dict))
-
-
-def _gate(client: Client, baseline: dict[str, Any], candidates: list[dict[str, Any]]) -> int:
- failed = _metric_errors(baseline) > 0
- console.print(f"{'recorded':<40} {'unscored' if failed else 'baseline'}")
- for run in candidates:
- overall = client.get(f"/api/eval-runs/{run['id']}/comparison/").get("overall") or {}
- status = overall.get("status") or "missing"
- errors = _metric_errors(run)
- if errors and status in _PASS:
- status = "unscored"
- candidate = overall.get("candidate")
- delta = overall.get("delta")
- score = "" if candidate is None else f"{candidate:.3f}"
- change = "" if delta is None else f"{delta:+.3f}"
- console.print(f"{run['label']:<40} {score:<8} {status:<12} {change}")
- if status not in _PASS or errors:
- failed = True
- return 1 if failed else 0
-
-
-def run_backtest(
- client: Client,
- *,
- project_id: str,
- capability_id: str,
- capability_slug: str,
- models: list[str],
- since: datetime,
- until: datetime | None,
- limit: int,
- from_model: str,
- timeout_s: float,
-) -> int:
- _require_models(client, models, finetune=False)
- capability = client.get(f"/api/capabilities/{capability_id}/")
- eval_set = capability.get("active_eval_set")
- if not eval_set:
- raise LayerError("The capability has no eval set.")
- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
- created = client.post(
- "/api/datasets/",
- {
- "project": project_id,
- "name": f"backtest {capability_slug} {stamp}"[:255],
- "capability": capability_id,
- "intent": "eval",
- "source": {
- "llm_calls": _selection(
- capability_id=capability_id,
- since=since,
- until=until,
- limit=limit,
- from_model=from_model,
- )
- },
- },
- )
- deadline = client.clock() + timeout_s
- dataset = client.wait_dataset(str(created["id"]), deadline=deadline)
- kept = (dataset.get("source_spec") or {}).get("kept")
- skipped = (dataset.get("source_spec") or {}).get("skipped")
- console.print(f"{kept if kept is not None else dataset.get('rows')} calls, {skipped or 0} skipped")
- targets = [
- {"label": "recorded", "mode": "recorded", "is_baseline": True},
- *[
- {
- "label": model,
- "mode": "generate",
- "model_name": model,
- "params": {"generation_strategy": "single_completion"},
- }
- for model in models
- ],
- ]
- group = client.post(
- "/api/eval-runs/",
- {
- "project": project_id,
- "name": f"backtest {capability_slug} {stamp}"[:255],
- "dataset": dataset["id"],
- "cell": _cell_id(dataset),
- "eval_set": eval_set,
- "max_items": int(dataset.get("rows") or limit),
- "targets": targets,
- },
- )
- finished = [client.wait_eval(str(run["id"]), deadline=deadline) for run in group["runs"]]
- baseline = next(run for run in finished if run.get("is_baseline"))
- return _gate(client, baseline, [run for run in finished if not run.get("is_baseline")])
+ raise FinetuneError(f"Unknown model: {', '.join(missing)}.")
def run_finetune(
@@ -319,11 +203,11 @@ def run_finetune(
eval_percent: int,
timeout_s: float,
) -> int:
- _require_models(client, models, finetune=True)
+ _require_models(client, models)
capability = client.get(f"/api/capabilities/{capability_id}/")
eval_set = capability.get("active_eval_set")
if not eval_set:
- raise LayerError("The capability has no eval set.")
+ raise FinetuneError("The capability has no eval set.")
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
created = client.post(
"/api/datasets/split/",
@@ -367,10 +251,10 @@ def run_finetune(
},
)
queued.append(f"{model} {job['id']}")
- except LayerError as exc:
+ except FinetuneError as exc:
for line in queued:
console.print(line)
- raise LayerError(f"{exc} Queued: {len(queued)}.", code=1) from exc
+ raise FinetuneError(f"{exc} Queued: {len(queued)}.", code=1) from exc
console.print(f"group {group_id}")
for line in queued:
console.print(line)
@@ -382,9 +266,9 @@ def _client(api_key: str, api_url: str, path) -> tuple[Client, Config]:
try:
key, url = resolve_api_credentials(api_key, api_url, config)
except ValueError as exc:
- raise LayerError(str(exc)) from exc
+ raise FinetuneError(str(exc)) from exc
if not key:
- raise LayerError("Missing API key. Pass --api-key or set OVERMIND_API_KEY.")
+ raise FinetuneError("Missing API key. Pass --api-key or set OVERMIND_API_KEY.")
session = requests.Session()
session.headers["X-Api-Key"] = key
return Client(session, url), config
@@ -403,62 +287,16 @@ def _common(
client, config = _client(api_key, api_url, path)
project = project_id.strip() or config.project_id.strip()
if not project:
- raise LayerError("Missing project-id. Pass --project-id or add project-id to overmind.toml.")
+ raise FinetuneError("Missing project-id. Pass --project-id or add project-id to overmind.toml.")
capability_id, slug = resolve_capability(config, capability)
now = datetime.now(timezone.utc)
start = parse_since(since, now=now)
end = parse_until(until)
if end is not None and end < start:
- raise LayerError("until is before since.")
+ raise FinetuneError("until is before since.")
return client, project, capability_id, slug, start, end
-def backtest(
- models: Annotated[
- list[str] | None,
- typer.Option("--models", help="1–5 model ids, comma-separated or repeated."),
- ] = None,
- capability: Annotated[str, typer.Option("--capability", help="Capability slug or id.")] = "",
- since: Annotated[str, typer.Option("--since", help="ISO timestamp or a duration like 7d.")] = "7d",
- until: Annotated[str, typer.Option("--until", help="ISO timestamp.")] = "",
- limit: Annotated[int, typer.Option("--limit", min=1, max=10_000)] = 200,
- from_model: Annotated[str, typer.Option("--from-model", help="Only spans recorded from this model.")] = "",
- timeout: Annotated[str, typer.Option("--timeout", help="Wait budget, like 45m.")] = "45m",
- project_id: Annotated[str, typer.Option("--project-id")] = "",
- api_key: Annotated[str, typer.Option("--api-key", envvar="OVERMIND_API_KEY")] = "",
- api_url: Annotated[str, typer.Option("--api-url", envvar="OVERMIND_API_URL")] = "",
- path: Annotated[Path, typer.Option("--path", help="Path to overmind.toml")] = DEFAULT_PATH,
-) -> None:
- """Score models on stored LLM calls. Exit 1 when any model regresses."""
- try:
- chosen = parse_models(models, cap=BACKTEST_CAP)
- client, project, capability_id, slug, start, end = _common(
- api_key=api_key,
- api_url=api_url,
- path=path,
- project_id=project_id,
- capability=capability,
- since=since,
- until=until,
- )
- code = run_backtest(
- client,
- project_id=project,
- capability_id=capability_id,
- capability_slug=slug,
- models=chosen,
- since=start,
- until=end,
- limit=limit,
- from_model=from_model,
- timeout_s=parse_timeout(timeout),
- )
- except LayerError as exc:
- console.print(f"[red]{exc}[/red]")
- raise typer.Exit(exc.code) from exc
- raise typer.Exit(code)
-
-
def finetune(
models: Annotated[
list[str] | None,
@@ -478,7 +316,7 @@ def finetune(
) -> None:
"""Start one fine-tune job per model from stored LLM calls. Does not wait for training."""
try:
- chosen = parse_models(models, cap=FINETUNE_CAP)
+ chosen = parse_models(models)
client, project, capability_id, slug, start, end = _common(
api_key=api_key,
api_url=api_url,
@@ -501,7 +339,7 @@ def finetune(
eval_percent=eval_percent,
timeout_s=parse_timeout(timeout),
)
- except LayerError as exc:
+ except FinetuneError as exc:
console.print(f"[red]{exc}[/red]")
raise typer.Exit(exc.code) from exc
raise typer.Exit(code)
diff --git a/overmind/overmind/init_cmd.py b/overmind/overmind/init_cmd.py
index 61b218db..74937202 100644
--- a/overmind/overmind/init_cmd.py
+++ b/overmind/overmind/init_cmd.py
@@ -21,7 +21,7 @@ from overmind.config import (
load,
saved_project_api_key,
)
-from overmind.skills import get_destination_dir, sync_skills
+from overmind.skills import get_destination_dir, remove_retired_skills, sync_skills
from overmind.skills_db import skills
console = Console()
@@ -62,8 +62,6 @@ COMMANDS: dict[str, str] = {
# "overmind-ensure-tracing": "../overmind-observability/SKILL.md",
# "overmind-dataset": "../overmind-datasets/SKILL.md",
# "overmind-finetune": "../overmind-training/SKILL.md",
- # "overmind-optimise": "../overmind-optimiser/SKILL.md",
- # "overmind-backtest": "../overmind-optimiser/SKILL.md",
}
SLASH_LABELS: dict[str, str] = {
@@ -73,19 +71,15 @@ SLASH_LABELS: dict[str, str] = {
"overmind-ensure-tracing": "/overmind ensure-tracing",
"overmind-dataset": "/overmind dataset",
"overmind-finetune": "/overmind finetune",
- "overmind-optimise": "/overmind optimise",
- "overmind-backtest": "/overmind backtest",
}
COMMAND_DESCRIPTIONS: dict[str, str] = {
- "overmind": "Route Overmind setup, tracing, datasets, finetune, optimise, and backtest",
+ "overmind": "Route Overmind setup, tracing, datasets and finetune",
"overmind-onboard": "Connect this repository to Overmind",
"overmind-setup": "Scan the repository and sync capabilities",
"overmind-ensure-tracing": "Inspect traces and instrument the agent",
"overmind-dataset": "Build, clean, upload, or export a dataset",
"overmind-finetune": "Fine-tune, deploy, and smoke-test a model",
- "overmind-optimise": "Run prompt and code optimisation",
- "overmind-backtest": "Compare models in the repository",
}
_FRONTMATTER = re.compile(r"\A---\n.*?\n---\n*", re.DOTALL)
@@ -260,6 +254,7 @@ def run_init(
mcp_url, base_url = resolve_mcp_url(env, configured_url)
sync_skills([skill.slug for skill in skills], ide=ide)
+ remove_retired_skills(ide)
dest = get_destination_dir(ide)
console.print(f"Skills → {dest}/skills ({len(skills)})")
diff --git a/overmind/overmind/openrouter_rewrite.py b/overmind/overmind/openrouter_rewrite.py
deleted file mode 100644
index 5db37bb3..00000000
--- a/overmind/overmind/openrouter_rewrite.py
+++ /dev/null
@@ -1,385 +0,0 @@
-"""Deterministic OpenRouter rewrite — Anthropic/OpenAI constructors → env-driven OpenRouter.
-
-Used by the ``/overmind backtest`` skill so provider translation is code, not a
-prompt. Leftover call sites (ChatAnthropic, Google genai, …) are reported for
-the agent to patch.
-"""
-
-from __future__ import annotations
-
-import ast
-import os
-from dataclasses import dataclass, field
-from pathlib import Path
-
-OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
-
-_SKIP_DIRS = frozenset({
- ".git",
- ".hg",
- ".svn",
- ".venv",
- "venv",
- "env",
- "node_modules",
- "__pycache__",
- ".overmind",
- ".tox",
- "dist",
- "build",
- ".mypy_cache",
- ".ruff_cache",
- "site-packages",
-})
-_OPENAI_CTORS = frozenset({"OpenAI", "AsyncOpenAI"})
-_ANTHROPIC_CTORS = frozenset({"Anthropic", "AsyncAnthropic"})
-_CHAT_OPENAI = frozenset({"ChatOpenAI"})
-_LEFTOVER_CTORS = frozenset({
- "ChatAnthropic",
- "ChatGoogleGenerativeAI",
- "GenerativeModel",
- "AnthropicVertex",
-})
-_MODEL_CALL_ATTRS = frozenset({
- "create",
- "generate",
- "ainvoke",
- "invoke",
- "generate_content",
- "completions",
- "messages",
- "chat",
- "responses",
-})
-_ENV_FILES = (".env", ".env.local", ".env.development", ".env.example")
-
-
-@dataclass
-class RewriteReport:
- changed: list[str] = field(default_factory=list)
- leftover: list[str] = field(default_factory=list)
- env_files: list[str] = field(default_factory=list)
-
- def as_dict(self) -> dict:
- return {
- "changed": list(self.changed),
- "leftover": list(self.leftover),
- "env_files": list(self.env_files),
- }
-
-
-def _line_starts(src: str) -> list[int]:
- starts = [0]
- for i, ch in enumerate(src):
- if ch == "\n":
- starts.append(i + 1)
- return starts
-
-
-def _abs(starts: list[int], lineno: int, col: int) -> int:
- return starts[lineno - 1] + col
-
-
-def _span(starts: list[int], node: ast.AST) -> tuple[int, int] | None:
- lineno = getattr(node, "lineno", None)
- end_lineno = getattr(node, "end_lineno", None)
- col = getattr(node, "col_offset", None)
- end_col = getattr(node, "end_col_offset", None)
- if None in (lineno, end_lineno, col, end_col):
- return None
- return _abs(starts, lineno, col), _abs(starts, end_lineno, end_col)
-
-
-def _call_name(node: ast.Call) -> str:
- func = node.func
- if isinstance(func, ast.Name):
- return func.id
- if isinstance(func, ast.Attribute):
- return func.attr
- return ""
-
-
-def _attr_chain(node: ast.AST) -> list[str]:
- names: list[str] = []
- cur: ast.AST | None = node
- while isinstance(cur, ast.Attribute):
- names.append(cur.attr)
- cur = cur.value
- if isinstance(cur, ast.Name):
- names.append(cur.id)
- names.reverse()
- return names
-
-
-def _kw(node: ast.Call, name: str) -> ast.keyword | None:
- return next((k for k in node.keywords if k.arg == name), None)
-
-
-def _str_const(node: ast.AST | None) -> str | None:
- if isinstance(node, ast.Constant) and isinstance(node.value, str):
- return node.value
- return None
-
-
-def _already_openrouter(node: ast.AST | None) -> bool:
- text = _str_const(node) or ""
- return "openrouter.ai" in text
-
-
-def _openai_ctor_source(node: ast.Call, *, name: str) -> str:
- kept = [f"{k.arg}={ast.unparse(k.value)}" for k in node.keywords if k.arg and k.arg not in {"api_key", "base_url"}]
- parts = [
- 'api_key=os.environ["OPENROUTER_API_KEY"]',
- f'base_url="{OPENROUTER_BASE_URL}"',
- *kept,
- ]
- positional = [ast.unparse(a) for a in node.args]
- return f"{name}({', '.join([*positional, *parts])})"
-
-
-def _has_import(tree: ast.AST, module: str, name: str) -> bool:
- return any(
- isinstance(node, ast.ImportFrom)
- and node.module == module
- and any(a.name == name and a.asname in (None, name) for a in node.names)
- for node in ast.walk(tree)
- )
-
-
-def _has_name_import_os(tree: ast.AST) -> bool:
- for node in ast.walk(tree):
- if isinstance(node, ast.Import) and any(a.name == "os" and a.asname in (None, "os") for a in node.names):
- return True
- return False
-
-
-def _is_docstring(node: ast.AST) -> bool:
- return (
- isinstance(node, ast.Expr)
- and isinstance(getattr(node, "value", None), ast.Constant)
- and isinstance(node.value.value, str)
- )
-
-
-def _import_insert_pos(src: str) -> int:
- """After shebang, module docstring, and ``from __future__`` — never before them."""
- starts = _line_starts(src)
- pos = 0
- first = src.lstrip("\ufeff")
- offset = len(src) - len(first)
- if first.startswith("#!") or first.startswith("# -*-") or first.startswith("# coding"):
- nl = first.find("\n")
- pos = offset + (nl + 1 if nl != -1 else len(first))
- try:
- tree = ast.parse(src)
- except SyntaxError:
- return pos
- body = list(tree.body)
- idx = 0
- if body and _is_docstring(body[0]):
- end = body[0].end_lineno or 1
- pos = starts[end] if end < len(starts) else len(src)
- idx = 1
- last_future = None
- for node in body[idx:]:
- if isinstance(node, ast.ImportFrom) and node.module == "__future__":
- last_future = node
- else:
- break
- if last_future is not None:
- end = last_future.end_lineno or last_future.lineno
- pos = starts[end] if end < len(starts) else len(src)
- return pos
-
-
-def _insert_imports(src: str, *, need_os: bool, openai_names: set[str]) -> str:
- if not need_os and not openai_names:
- return src
- lines: list[str] = []
- if need_os:
- lines.append("import os")
- if openai_names:
- lines.append(f"from openai import {', '.join(sorted(openai_names))}")
- block = "\n".join(lines) + "\n"
- pos = _import_insert_pos(src)
- return src[:pos] + block + src[pos:]
-
-
-def _rewrite_python(path: Path, src: str) -> tuple[str, list[str], bool]:
- leftover: list[str] = []
- try:
- tree = ast.parse(src)
- except SyntaxError:
- leftover.append(f"{path}: unparseable")
- return src, leftover, False
-
- starts = _line_starts(src)
- replacements: list[tuple[int, int, str]] = []
- need_os = False
- openai_names: set[str] = set()
- rewrote_anthropic = False
-
- for node in ast.walk(tree):
- if not isinstance(node, ast.Call):
- continue
- name = _call_name(node)
- span = _span(starts, node)
- if span is None:
- continue
- start, end = span
- rel = f"{path}:{node.lineno}"
-
- if name in _LEFTOVER_CTORS:
- leftover.append(rel)
- continue
-
- if name in _ANTHROPIC_CTORS:
- ctor_name = "AsyncOpenAI" if name.startswith("Async") else "OpenAI"
- openai_names.add(ctor_name)
- replacements.append((start, end, _openai_ctor_source(node, name=ctor_name)))
- need_os = True
- rewrote_anthropic = True
- continue
-
- if name in _OPENAI_CTORS:
- base = _kw(node, "base_url")
- if base is not None and _already_openrouter(base.value):
- continue
- replacements.append((start, end, _openai_ctor_source(node, name=ast.unparse(node.func))))
- need_os = True
- continue
-
- if name in _CHAT_OPENAI:
- base = _kw(node, "openai_api_base") or _kw(node, "base_url")
- if base is not None and _already_openrouter(base.value):
- continue
- keywords = [
- k
- for k in node.keywords
- if k.arg not in {"openai_api_base", "base_url", "openai_api_key", "api_key", "model"}
- ]
- env_key = ast.Subscript(
- value=ast.Attribute(value=ast.Name(id="os", ctx=ast.Load()), attr="environ", ctx=ast.Load()),
- slice=ast.Constant(value="OPENROUTER_API_KEY"),
- ctx=ast.Load(),
- )
- new_kws = [
- ast.keyword(arg="openai_api_base", value=ast.Constant(value=OPENROUTER_BASE_URL)),
- ast.keyword(arg="openai_api_key", value=env_key),
- ]
- model_kw = _kw(node, "model")
- original_model = _str_const(model_kw.value) if model_kw else None
- if original_model:
- new_kws.append(
- ast.keyword(
- arg="model",
- value=ast.parse(
- f"os.environ.get('OPENROUTER_MODEL', {original_model!r})",
- mode="eval",
- ).body,
- )
- )
- elif model_kw is not None:
- new_kws.append(model_kw)
- new_call = ast.Call(func=node.func, args=node.args, keywords=[*new_kws, *keywords])
- replacements.append((start, end, ast.unparse(new_call)))
- need_os = True
- continue
-
- model_kw = _kw(node, "model")
- original_model = _str_const(model_kw.value) if model_kw else None
- if original_model is None or original_model.startswith("$"):
- continue
- chain = _attr_chain(node.func)
- if not _MODEL_CALL_ATTRS.intersection(chain) and name not in _MODEL_CALL_ATTRS:
- continue
- if "OPENROUTER_MODEL" in ast.dump(model_kw.value): # type: ignore[union-attr]
- continue
- value_span = _span(starts, model_kw.value)
- if value_span is None:
- continue
- replacements.append((value_span[0], value_span[1], f"os.environ.get('OPENROUTER_MODEL', {original_model!r})"))
- need_os = True
-
- if not replacements and not rewrote_anthropic:
- return src, leftover, False
-
- replacements.sort(key=lambda item: item[0], reverse=True)
- new_src = src
- for start, end, text in replacements:
- new_src = new_src[:start] + text + new_src[end:]
-
- if rewrote_anthropic:
- new_src = new_src.replace(".messages.create(", ".chat.completions.create(")
-
- try:
- tree_after = ast.parse(new_src) if new_src != src else tree
- except SyntaxError:
- leftover.append(f"{path}: rewrite produced invalid Python")
- return src, leftover, False
- inject_os = need_os and not _has_name_import_os(tree_after)
- missing_names = {name for name in openai_names if not _has_import(tree_after, "openai", name)}
- new_src = _insert_imports(new_src, need_os=inject_os, openai_names=missing_names)
- return new_src, leftover, new_src != src
-
-
-def _rewrite_env_file(path: Path) -> bool:
- original = path.read_text()
- lines = original.splitlines(keepends=True)
- keys = {
- "OPENAI_BASE_URL": f"OPENAI_BASE_URL={OPENROUTER_BASE_URL}\n",
- "OPENAI_API_BASE": f"OPENAI_API_BASE={OPENROUTER_BASE_URL}\n",
- }
- seen: set[str] = set()
- out: list[str] = []
- changed = False
- for line in lines:
- stripped = line.strip()
- assigned = stripped.split("=", 1)[0] if "=" in stripped and not stripped.startswith("#") else ""
- if assigned in keys:
- seen.add(assigned)
- replacement = keys[assigned]
- if line != replacement and not line.startswith(replacement.rstrip("\n")):
- out.append(replacement)
- changed = True
- else:
- out.append(line)
- else:
- out.append(line)
- for key, line in keys.items():
- if key not in seen:
- if out and not out[-1].endswith("\n"):
- out.append("\n")
- out.append(line)
- changed = True
- if not changed:
- return False
- path.write_text("".join(out))
- return True
-
-
-def rewrite_repo(root: str | os.PathLike[str] = ".") -> RewriteReport:
- """Rewrite LLM clients under *root* onto OpenRouter. Returns what changed."""
- base = Path(root).resolve()
- report = RewriteReport()
- for dirpath, dirnames, filenames in os.walk(base):
- dirnames[:] = [d for d in dirnames if d not in _SKIP_DIRS and not d.startswith(".")]
- for name in filenames:
- path = Path(dirpath) / name
- rel = str(path.relative_to(base))
- if name.endswith(".py"):
- try:
- src = path.read_text()
- except (OSError, UnicodeDecodeError):
- continue
- if len(src) > 400_000:
- continue
- new_src, leftover, changed = _rewrite_python(path.relative_to(base), src)
- report.leftover.extend(leftover)
- if changed:
- path.write_text(new_src)
- report.changed.append(rel)
- elif name in _ENV_FILES:
- if _rewrite_env_file(path):
- report.env_files.append(rel)
- return report
diff --git a/overmind/overmind/optimizer.py b/overmind/overmind/optimizer.py
deleted file mode 100755
index 96661482..00000000
--- a/overmind/overmind/optimizer.py
+++ /dev/null
@@ -1,476 +0,0 @@
-"""Client-driven optimiser loop — skill generates diffs/commands; server scores.
-
-Driven by the ``/overmind optimise`` skill. SDK verbs: ``overmind optimise start`` /
-``next``. Winning diffs stay on the candidate ``code_path``; apply them locally.
-"""
-
-from __future__ import annotations
-
-import json
-import time
-from concurrent.futures import ThreadPoolExecutor, as_completed
-from pathlib import Path
-from typing import Any
-
-from overmind.backtest import openrouter_env
-from overmind.optimizer_api import (
- _EVALUATED_STATUSES,
- _TERMINAL_STATUSES,
- OUTPUT_TAIL,
- REFERENCE_COMMAND_TEMPLATE,
- OptimizerAPI,
- _ensure_worktree,
- _remove_worktrees,
- _run_datapoint,
-)
-
-
-def command_template_prompt(*, capability_name: str = "", entrypoint: str = "") -> str:
- return (
- "Write EXACTLY ONE reusable shell command that runs the capability on a single "
- "datapoint and prints its output.\n\n"
- f"## Capability\n- name: {capability_name or '(from overmind.toml)'}\n"
- f"- entrypoint: {entrypoint or '(discover in repo)'}\n\n"
- "Leave these tokens verbatim (substituted per datapoint):\n"
- " __DATAPOINT_INPUT__, __EXPERIMENT_ID__, __CAPABILITY_ID__, __CANDIDATE_ID__,\n"
- " __ITERATION_ID__, __DATAPOINT_INDEX__, __PROJECT_ID__\n\n"
- f"## Reference shape\n```\n{REFERENCE_COMMAND_TEMPLATE}```\n"
- "Adapt the import to this repo, keep tokens unchanged, write the file, then:\n\n"
- " overmind optimise set-template <file>\n"
- )
-
-
-def candidate_prompt(
- *,
- capability_name: str = "",
- entrypoint: str = "",
- scores: dict | None = None,
- n_candidates: int = 3,
-) -> str:
- return (
- f"Write {n_candidates} candidate unified git diff(s) that improve "
- f"{capability_name or 'the capability'} "
- f"(entrypoint `{entrypoint or 'discover in repo'}`).\n\n"
- f"Scores so far: {json.dumps(scores or {})}\n\n"
- "Each patch is a git unified diff against the current repo. Keep the entrypoint "
- "signature. Do not hardcode datapoint answers.\n\n"
- "Then:\n"
- " overmind optimise add-candidate --diff <file>\n"
- " overmind optimise run-iteration\n"
- )
-
-
-class OptimiseLoop:
- """Template → smoke → baseline → candidate diffs → complete."""
-
- def __init__(
- self,
- api: OptimizerAPI,
- experiment_id: str,
- *,
- repo_cwd: str,
- dataset_path: Path,
- state_path: Path,
- timeout: int = 600,
- poll_interval: float = 5.0,
- poll_timeout: float = 600.0,
- ) -> None:
- self.api = api
- self.experiment_id = experiment_id
- self.repo_cwd = repo_cwd
- self.dataset_path = dataset_path
- self.state_path = state_path
- self.timeout = timeout
- self.poll_interval = poll_interval
- self.poll_timeout = poll_timeout
-
- def _load_dataset(self) -> list[dict]:
- rows: list[dict] = []
- with self.dataset_path.open() as fh:
- for line in fh:
- line = line.strip()
- if line:
- rows.append(json.loads(line))
- return rows
-
- def _load_state(self) -> dict:
- if self.state_path.exists():
- try:
- return json.loads(self.state_path.read_text())
- except (json.JSONDecodeError, OSError):
- return {}
- return {}
-
- def _save_state(self, state: dict) -> None:
- self.state_path.parent.mkdir(parents=True, exist_ok=True)
- self.state_path.write_text(json.dumps(state, indent=2))
-
- def _poll_until_evaluated(self) -> dict:
- deadline = time.monotonic() + self.poll_timeout
- while time.monotonic() < deadline:
- exp = self.api.get_experiment(self.experiment_id)
- status = exp.get("status", "")
- if status in _EVALUATED_STATUSES or status in _TERMINAL_STATUSES:
- return exp
- time.sleep(self.poll_interval)
- raise TimeoutError(f"Optimise {self.experiment_id} did not finish scoring within {self.poll_timeout}s")
-
- def next_action(self) -> dict[str, Any]:
- exp = self.api.get_experiment(self.experiment_id)
- status = exp.get("status", "")
- local = self._load_state()
- iterations = exp.get("iterations") or []
-
- if status in _TERMINAL_STATUSES:
- return {"action": "DONE", "experiment": exp, "scores": exp.get("scores") or {}}
-
- if not exp.get("command_template"):
- return {
- "action": "WRITE_COMMAND_TEMPLATE",
- "prompt": command_template_prompt(
- capability_name=str(exp.get("capability_name") or ""),
- entrypoint=str(exp.get("entrypoint") or ""),
- ),
- "experiment": exp,
- }
-
- if not local.get("smoke_done"):
- return {"action": "RUN_SMOKE", "experiment": exp}
-
- if status in ("evaluating_baseline_outputs", "evaluating_candidate_outputs"):
- return {
- "action": "WAIT",
- "message": "Server is scoring — run `overmind optimise next` again shortly.",
- "experiment": exp,
- }
-
- has_baseline = any(int(it.get("order") or 0) == 0 for it in iterations)
- if not has_baseline:
- return {"action": "RUN_BASELINE", "experiment": exp}
-
- n_cand = int(exp.get("num_candidates_per_iteration") or 3)
- max_iter = int(exp.get("num_iterations") or 5)
- current = int(exp.get("current_iteration") or 0)
- pending = list(local.get("pending_diffs") or [])
- if pending:
- return {
- "action": "RUN_ITERATION",
- "pending": len(pending),
- "experiment": exp,
- }
-
- if current >= max_iter:
- return {
- "action": "COMPLETE",
- "experiment": exp,
- "scores": exp.get("scores") or {},
- }
-
- stall_limit = int(exp.get("max_iterations_without_improvement") or 0)
- stalled = int(exp.get("stalled_iterations") or 0)
- if stall_limit and stalled >= stall_limit:
- return {
- "action": "COMPLETE",
- "reason": f"plateau: {stalled} iteration(s) without improvement",
- "experiment": exp,
- "scores": exp.get("scores") or {},
- }
-
- return {
- "action": "WRITE_CANDIDATES",
- "prompt": candidate_prompt(
- capability_name=str(exp.get("capability_name") or ""),
- entrypoint=str(exp.get("entrypoint") or ""),
- scores=exp.get("scores") or {},
- n_candidates=n_cand,
- ),
- "experiment": exp,
- }
-
- def set_template(self, template: str) -> dict:
- return self.api.set_template(self.experiment_id, template)
-
- def run_smoke(self) -> dict:
- exp = self.api.get_experiment(self.experiment_id)
- template = exp.get("command_template") or ""
- if not template:
- raise RuntimeError("No command template. Run `overmind optimise set-template` first.")
- dataset = self._load_dataset()
- if not dataset:
- raise RuntimeError("Dataset is empty.")
- extra = None
- models = list(exp.get("model_ids") or [])
- if models:
- extra = openrouter_env(models[0])
- result = _run_datapoint(
- template=template,
- experiment_id=self.experiment_id,
- capability_id=str(exp.get("capability") or ""),
- project_id=str(exp.get("project") or ""),
- candidate_id="smoke",
- iteration_id="smoke",
- datapoint_index=0,
- datapoint_input=dataset[0].get("input"),
- cwd=self.repo_cwd,
- timeout=self.timeout,
- extra_env=extra,
- )
- if result["success"]:
- local = self._load_state()
- local["smoke_done"] = True
- self._save_state(local)
- result["output"] = (result.get("output") or "")[-OUTPUT_TAIL:]
- return result
-
- def _run_candidates(
- self,
- *,
- template: str,
- exp: dict,
- iteration: dict,
- pairs: list[tuple[dict, str]],
- dataset: list[dict],
- ) -> list[dict]:
- """Run every (candidate, datapoint) job across ``pairs`` of (candidate, cwd)
- in one shared pool, so candidates execute in parallel across worktrees."""
- iter_id = str(iteration.get("id") or "")
- jobs: list[dict] = []
- for candidate, cwd in pairs:
- target = str(candidate.get("target_model") or "")
- extra = openrouter_env(target) if target else None
- for idx, dp in enumerate(dataset):
- jobs.append({
- "template": template,
- "experiment_id": self.experiment_id,
- "capability_id": str(exp.get("capability") or ""),
- "project_id": str(exp.get("project") or ""),
- "candidate_id": str(candidate.get("id") or ""),
- "iteration_id": iter_id,
- "datapoint_index": idx,
- "datapoint_input": dp.get("input"),
- "cwd": cwd,
- "timeout": self.timeout,
- "extra_env": extra,
- })
- results: list[dict] = []
- with ThreadPoolExecutor(max_workers=8) as pool:
- for fut in as_completed([pool.submit(_run_datapoint, **kw) for kw in jobs]):
- results.append(fut.result())
- return results
-
- def run_baseline(self) -> dict:
- exp = self.api.get_experiment(self.experiment_id)
- template = exp.get("command_template") or ""
- if not template:
- raise RuntimeError("No command template set.")
- local = self._load_state()
- iteration = self.api.add_iteration(
- self.experiment_id,
- order=0,
- name="Baseline",
- candidates=[{"candidate_index": 0, "code_path": "", "is_baseline": True}],
- )
- candidates = iteration.get("candidates") or []
- if not candidates:
- raise RuntimeError("No baseline candidate created.")
- dataset = self._load_dataset()
- results = self._run_candidates(
- template=template,
- exp=exp,
- iteration=iteration,
- pairs=[(candidates[0], self.repo_cwd)],
- dataset=dataset,
- )
- self.api.post_results(self.experiment_id, results)
- self.api.evaluate(self.experiment_id, 0)
- exp = self._poll_until_evaluated()
- local["next_order"] = 1
- self._save_state(local)
- return exp
-
- def add_candidate_diff(self, diff: str) -> dict:
- local = self._load_state()
- pending = list(local.get("pending_diffs") or [])
- pending.append(diff)
- local["pending_diffs"] = pending
- self._save_state(local)
- return {"pending": len(pending)}
-
- def run_iteration(self, diffs: list[str] | None = None) -> dict:
- exp = self.api.get_experiment(self.experiment_id)
- template = exp.get("command_template") or ""
- if not template:
- raise RuntimeError("No command template set.")
- local = self._load_state()
- pending = list(diffs if diffs is not None else local.get("pending_diffs") or [])
- if not pending:
- raise RuntimeError("No candidate diffs. Run `overmind optimise add-candidate --diff`.")
-
- order = int(local.get("next_order") or 1)
- models = list(exp.get("model_ids") or [])
- mode = exp.get("mode") or "optimize"
- candidates_payload: list[dict] = []
- index = 0
- for diff in pending:
- if mode == "hybrid" and models:
- for model in models:
- candidates_payload.append({
- "candidate_index": index,
- "code_path": diff,
- "target_model": model,
- "is_baseline": False,
- })
- index += 1
- else:
- candidates_payload.append({
- "candidate_index": index,
- "code_path": diff,
- "is_baseline": False,
- })
- index += 1
-
- iteration = self.api.add_iteration(
- self.experiment_id,
- order=order,
- name=f"Iteration {order}",
- candidates=candidates_payload,
- )
- created = iteration.get("candidates") or []
- if not created:
- raise RuntimeError(f"No candidates created for iteration order={order}.")
-
- dataset = self._load_dataset()
- # Worktree creation mutates the shared .git, so it stays sequential; the
- # datapoint runs themselves share one pool across all candidates.
- pairs: list[tuple[dict, str]] = []
- for candidate in created:
- diff = str(candidate.get("code_path") or "")
- cwd = str(_ensure_worktree(self.repo_cwd, self.experiment_id, str(candidate.get("id")), diff))
- pairs.append((candidate, cwd))
- all_results = self._run_candidates(
- template=template,
- exp=exp,
- iteration=iteration,
- pairs=pairs,
- dataset=dataset,
- )
-
- self.api.post_results(self.experiment_id, all_results)
- self.api.evaluate(self.experiment_id, order)
- exp = self._poll_until_evaluated()
- local["pending_diffs"] = []
- local["next_order"] = order + 1
- self._save_state(local)
- return exp
-
- def complete(self) -> dict:
- _remove_worktrees(self.repo_cwd, self.experiment_id)
- return self.api.complete(self.experiment_id)
-
- def status(self) -> dict:
- return self.api.get_experiment(self.experiment_id)
-
-
-def start_optimise(
- api: OptimizerAPI,
- *,
- capability_id: str,
- dataset_id: str,
- eval_set_id: str = "",
- cache_dir: Path,
- state_path: Path,
- repo_cwd: str,
- mode: str = "optimize",
- model_ids: list[str] | None = None,
- num_iterations: int = 5,
- num_candidates_per_iteration: int = 3,
- max_iterations_without_improvement: int = 3,
- openrouter_key_source: str = "local",
-) -> tuple[dict, Path, OptimiseLoop]:
- exp = api.create_experiment(
- capability_id=capability_id,
- dataset_id=dataset_id,
- eval_set_id=eval_set_id,
- mode=mode,
- model_ids=model_ids,
- num_iterations=num_iterations,
- num_candidates_per_iteration=num_candidates_per_iteration,
- max_iterations_without_improvement=max_iterations_without_improvement,
- openrouter_key_source=openrouter_key_source,
- )
- # The experiment exists from here on: its id is saved before the download,
- # so a failed pull is resumed with --experiment and never starts a second one.
- state = {
- "experiment_id": exp["id"],
- "dataset_id": dataset_id,
- "dataset_path": "",
- "capability_id": capability_id,
- "smoke_done": False,
- "next_order": 0,
- "pending_diffs": [],
- "kind": "optimise",
- }
- state_path.parent.mkdir(parents=True, exist_ok=True)
- state_path.write_text(json.dumps(state, indent=2))
- dataset_path = pull_dataset(api, exp, cache_dir)
- state["dataset_path"] = str(dataset_path)
- state_path.write_text(json.dumps(state, indent=2))
- loop = OptimiseLoop(
- api,
- exp["id"],
- repo_cwd=repo_cwd,
- dataset_path=dataset_path,
- state_path=state_path,
- )
- return exp, dataset_path, loop
-
-
-def pull_dataset(api: OptimizerAPI, exp: dict, cache_dir: Path) -> Path:
- """The experiment's used version, on disk under ``cache_dir``."""
- info = exp.get("cell_info") or {}
- return api.export_dataset(
- str(exp.get("dataset") or ""),
- str(exp.get("cell") or ""),
- cache_dir,
- fingerprint=str(info.get("fingerprint") or ""),
- )
-
-
-def attach_optimise(
- api: OptimizerAPI,
- experiment_id: str,
- *,
- cache_dir: Path,
- state_path: Path,
- repo_cwd: str,
-) -> tuple[dict, Path, OptimiseLoop]:
- exp = api.get_experiment(experiment_id)
- dataset_id = str(exp.get("dataset") or "")
- if not dataset_id:
- raise RuntimeError(f"Experiment {experiment_id} has no dataset.")
- dataset_path = pull_dataset(api, exp, cache_dir)
- iterations = exp.get("iterations") or []
- has_baseline = any(int(it.get("order") or 0) == 0 for it in iterations)
- next_order = 0
- if iterations:
- next_order = max(int(it.get("order") or 0) for it in iterations) + 1
- state = {
- "experiment_id": exp["id"],
- "dataset_id": dataset_id,
- "dataset_path": str(dataset_path),
- "capability_id": str(exp.get("capability") or ""),
- "smoke_done": has_baseline,
- "next_order": next_order,
- "pending_diffs": [],
- "kind": "optimise",
- }
- state_path.parent.mkdir(parents=True, exist_ok=True)
- state_path.write_text(json.dumps(state, indent=2))
- loop = OptimiseLoop(
- api,
- exp["id"],
- repo_cwd=repo_cwd,
- dataset_path=dataset_path,
- state_path=state_path,
- )
- return exp, dataset_path, loop
diff --git a/overmind/overmind/optimizer_api.py b/overmind/overmind/optimizer_api.py
deleted file mode 100644
index 5cb0d878..00000000
--- a/overmind/overmind/optimizer_api.py
+++ /dev/null
@@ -1,392 +0,0 @@
-"""HTTP client + datapoint runner for client-driven optimizer / backtest loops."""
-
-from __future__ import annotations
-
-import os
-import secrets
-import subprocess
-from pathlib import Path
-from typing import Any
-
-import requests
-
-TOKENS: dict[str, str] = {
- "EXPERIMENT_ID": "__EXPERIMENT_ID__",
- "CAPABILITY_ID": "__CAPABILITY_ID__",
- "CANDIDATE_ID": "__CANDIDATE_ID__",
- "ITERATION_ID": "__ITERATION_ID__",
- "PROJECT_ID": "__PROJECT_ID__",
- "DATAPOINT_INDEX": "__DATAPOINT_INDEX__",
- "TRACE_TYPE": "__TRACE_TYPE__",
- "ORIGINAL_TRACE_ID": "__ORIGINAL_TRACE_ID__",
- "DATAPOINT_INPUT": "__DATAPOINT_INPUT__",
-}
-
-# Short reference shown in codegen prompts.
-REFERENCE_COMMAND_TEMPLATE = f"""\
-uv run python manage.py shell <<'EOF'
-
-def main():
- datapoint = {TOKENS["DATAPOINT_INPUT"]}
- # adapt this import + call to the capability's real entrypoint in THIS repo
- from project import trigger
- return trigger(datapoint)
-
-main()
-EOF
-"""
-
-OUTPUT_TAIL = 8_000 # chars of stdout/stderr to capture per run
-REDACTED_SECRET = "[REDACTED]"
-MIN_ITERATION_IMPROVEMENT = 1.0 # minimum score delta counted as improvement
-
-_EVALUATED_STATUSES = frozenset({
- "evaluated_baseline_outputs",
- "evaluated_candidate_outputs",
- "iterating",
- "completed",
- "failed",
- "cancelled",
-})
-_TERMINAL_STATUSES = frozenset({"completed", "failed", "cancelled"})
-
-
-def _new_traceparent() -> tuple[str, str]:
- """Return (traceparent_header, trace_id) — W3C format, no OTel dependency."""
- trace_id = secrets.token_hex(16)
- span_id = secrets.token_hex(8)
- return f"00-{trace_id}-{span_id}-01", trace_id
-
-
-def _secret_env_values(env: dict[str, str]) -> tuple[str, ...]:
- markers = ("KEY", "TOKEN", "SECRET", "PASSWORD")
- values = {str(v) for k, v in env.items() if v and any(m in str(k).upper() for m in markers)}
- return tuple(sorted(values, key=len, reverse=True))
-
-
-def _redact_secret_values(text: str, secret_values: tuple[str, ...]) -> str:
- for v in secret_values:
- text = text.replace(v, REDACTED_SECRET)
- return text
-
-
-def _git_apply(diff_text: str, cwd: str, *, index: bool = False) -> subprocess.CompletedProcess:
- if diff_text and not diff_text.endswith("\n"):
- diff_text += "\n"
- cmd = ["git", "apply", "--whitespace=nowarn"]
- if index:
- cmd.append("--index")
- cmd.append("-")
- return subprocess.run(
- cmd,
- input=diff_text,
- cwd=cwd,
- text=True,
- capture_output=True,
- )
-
-
-def _render_command(
- template: str,
- *,
- experiment_id: str,
- capability_id: str,
- project_id: str,
- candidate_id: str,
- iteration_id: str,
- datapoint_index: int,
- trace_type: str,
- original_trace_id: str,
- datapoint_input: Any,
-) -> str:
- subs = {
- TOKENS["EXPERIMENT_ID"]: experiment_id,
- TOKENS["CAPABILITY_ID"]: capability_id,
- TOKENS["PROJECT_ID"]: project_id,
- TOKENS["CANDIDATE_ID"]: candidate_id,
- TOKENS["ITERATION_ID"]: iteration_id,
- TOKENS["DATAPOINT_INDEX"]: str(datapoint_index),
- TOKENS["TRACE_TYPE"]: trace_type,
- TOKENS["ORIGINAL_TRACE_ID"]: original_trace_id,
- TOKENS["DATAPOINT_INPUT"]: repr(datapoint_input),
- }
- result = template
- for token, value in subs.items():
- result = result.replace(token, value)
- return result
-
-
-def _worktree_path(repo_cwd: str, experiment_id: str, candidate_id: str) -> Path:
- return Path(repo_cwd) / ".overmind" / "worktrees" / experiment_id[:8] / candidate_id[:8]
-
-
-def _ensure_worktree(repo_cwd: str, experiment_id: str, candidate_id: str, diff: str) -> Path:
- """Create (once) a git worktree for a candidate and apply its diff."""
- path = _worktree_path(repo_cwd, experiment_id, candidate_id)
- if not path.exists():
- path.parent.mkdir(parents=True, exist_ok=True)
- subprocess.run(
- ["git", "worktree", "add", "--detach", str(path)],
- cwd=repo_cwd,
- check=True,
- capture_output=True,
- )
- if diff:
- result = _git_apply(diff, str(path))
- if result.returncode != 0:
- raise RuntimeError(f"git apply failed for candidate {candidate_id}: {result.stderr.strip()}")
- return path
-
-
-def _remove_worktrees(repo_cwd: str, experiment_id: str) -> None:
- """Remove all worktrees for an experiment and prune the worktree list."""
- base = Path(repo_cwd) / ".overmind" / "worktrees" / experiment_id[:8]
- if base.exists():
- for wt in base.iterdir():
- subprocess.run(
- ["git", "worktree", "remove", "--force", str(wt)],
- cwd=repo_cwd,
- capture_output=True,
- )
- subprocess.run(["git", "worktree", "prune"], cwd=repo_cwd, capture_output=True)
-
-
-def _run_datapoint(
- *,
- template: str,
- experiment_id: str,
- capability_id: str,
- project_id: str,
- candidate_id: str,
- iteration_id: str,
- datapoint_index: int,
- datapoint_input: Any,
- cwd: str,
- timeout: int = 600,
- extra_env: dict[str, str] | None = None,
-) -> dict:
- """Run one rendered command in ``cwd``, return result dict for POST /results/."""
- traceparent, trace_id = _new_traceparent()
- rendered = _render_command(
- template,
- experiment_id=experiment_id,
- capability_id=capability_id,
- project_id=project_id,
- candidate_id=candidate_id,
- iteration_id=iteration_id,
- datapoint_index=datapoint_index,
- trace_type="optimized",
- original_trace_id="",
- datapoint_input=datapoint_input,
- )
- env = {**os.environ, "TRACEPARENT": traceparent, **(extra_env or {})}
- secret_values = _secret_env_values(env)
- try:
- proc = subprocess.run(
- rendered,
- shell=True,
- cwd=cwd,
- env=env,
- capture_output=True,
- text=True,
- timeout=timeout,
- )
- success = proc.returncode == 0
- output = _redact_secret_values(proc.stdout or "", secret_values)
- error = "" if success else _redact_secret_values(proc.stderr or "", secret_values)
- return {
- "candidate_id": candidate_id,
- "datapoint_index": datapoint_index,
- "success": success,
- "output": output[-OUTPUT_TAIL:],
- "trace_id": trace_id,
- "error": error[-OUTPUT_TAIL:],
- }
- except subprocess.TimeoutExpired:
- return {
- "candidate_id": candidate_id,
- "datapoint_index": datapoint_index,
- "success": False,
- "output": "",
- "trace_id": trace_id,
- "error": f"timed out after {timeout}s",
- }
-
-
-def _raise_with_detail(resp: requests.Response) -> None:
- """``raise_for_status`` that carries the server's reason: a refusal such as
- "X is a train dataset; this needs eval." is the message, not "Bad Request"."""
- if resp.ok:
- return
- try:
- body = resp.json()
- except ValueError:
- body = None
- if isinstance(body, dict):
- parts = [
- f"{field}: {'; '.join(map(str, reason)) if isinstance(reason, list) else reason}"
- for field, reason in body.items()
- ]
- detail = " ".join(parts)
- else:
- detail = (resp.text or "").strip()
- raise requests.HTTPError(f"HTTP {resp.status_code} from {resp.url}: {detail[:600] or resp.reason}", response=resp)
-
-
-class OptimizerAPI:
- """Thin HTTP client for the optimizer-experiments write API.
-
- Endpoints are the planned client-write surface on
- ``/api/optimizer-experiments/{id}/``. Tests mock at the requests layer.
- """
-
- def __init__(self, base_url: str, api_key: str) -> None:
- self.base_url = base_url.rstrip("/")
- self._session = requests.Session()
- self._session.headers.update({"X-Api-Key": api_key, "Content-Type": "application/json"})
-
- def _exp_url(self, experiment_id: str, *parts: str) -> str:
- return "/".join([f"{self.base_url}/api/optimizer-experiments/{experiment_id}", *parts, ""])
-
- def create_experiment(
- self,
- *,
- capability_id: str,
- dataset_id: str,
- eval_set_id: str = "",
- mode: str = "optimize",
- num_iterations: int = 5,
- num_candidates_per_iteration: int = 3,
- max_iterations_without_improvement: int = 3,
- model_ids: list[str] | None = None,
- openrouter_key_source: str = "local",
- ) -> dict:
- payload: dict[str, Any] = {
- "capability": capability_id,
- "dataset": dataset_id,
- "mode": mode,
- "num_iterations": num_iterations,
- "num_candidates_per_iteration": num_candidates_per_iteration,
- "max_iterations_without_improvement": max_iterations_without_improvement,
- "openrouter_key_source": openrouter_key_source,
- }
- if eval_set_id:
- payload["eval_set"] = eval_set_id
- if model_ids:
- payload["model_ids"] = model_ids
- resp = self._session.post(
- f"{self.base_url}/api/optimizer-experiments/",
- json=payload,
- timeout=30,
- )
- _raise_with_detail(resp)
- return resp.json()
-
- def list_iterations(self, experiment_id: str) -> list[dict]:
- resp = self._session.get(self._exp_url(experiment_id, "iterations"), timeout=30)
- _raise_with_detail(resp)
- data = resp.json()
- if isinstance(data, dict) and "results" in data:
- return list(data["results"])
- if isinstance(data, list):
- return data
- return []
-
- def get_experiment(self, experiment_id: str) -> dict:
- resp = self._session.get(self._exp_url(experiment_id), timeout=30)
- _raise_with_detail(resp)
- exp = resp.json()
- # Retrieve does not nest iterations; attach them for client FSM callers.
- try:
- exp["iterations"] = self.list_iterations(experiment_id)
- except Exception: # noqa: BLE001 — status callers still work without the tree
- exp.setdefault("iterations", [])
- return exp
-
- def set_template(self, experiment_id: str, template: str) -> dict:
- resp = self._session.post(
- self._exp_url(experiment_id, "template"),
- json={"template": template},
- timeout=30,
- )
- _raise_with_detail(resp)
- return resp.json()
-
- def add_iteration(
- self,
- experiment_id: str,
- *,
- order: int,
- name: str,
- candidates: list[dict],
- ) -> dict:
- resp = self._session.post(
- self._exp_url(experiment_id, "add-iteration"),
- json={"order": order, "name": name, "candidates": candidates},
- timeout=30,
- )
- _raise_with_detail(resp)
- return resp.json()
-
- def post_results(self, experiment_id: str, results: list[dict]) -> dict:
- resp = self._session.post(
- self._exp_url(experiment_id, "results"),
- json={"results": results},
- timeout=60,
- )
- _raise_with_detail(resp)
- return resp.json()
-
- def evaluate(self, experiment_id: str, order: int) -> dict:
- resp = self._session.post(
- self._exp_url(experiment_id, "evaluate"),
- json={"order": order},
- timeout=30,
- )
- _raise_with_detail(resp)
- return resp.json()
-
- def complete(self, experiment_id: str) -> dict:
- resp = self._session.post(
- self._exp_url(experiment_id, "complete"),
- json={},
- timeout=30,
- )
- _raise_with_detail(resp)
- return resp.json()
-
- def export_dataset(self, dataset_id: str, cell_id: str, cache_dir: Path, *, fingerprint: str = "") -> Path:
- """The used version's JSONL, cached as ``<cell>.jsonl`` with its frame
- fingerprint beside it. A cache whose fingerprint is missing or differs
- from the version is fetched again."""
- if not cell_id:
- raise RuntimeError("The experiment has no used version.")
- cache_dir.mkdir(parents=True, exist_ok=True)
- cached = cache_dir / f"{cell_id}.jsonl"
- hash_file = cache_dir / f"{cell_id}.hash"
- if cached.exists() and hash_file.exists():
- stored = hash_file.read_text().strip()
- if stored and (not fingerprint or stored == fingerprint):
- return cached
- resp = self._session.get(
- f"{self.base_url}/api/datasets/{dataset_id}/export/",
- params={"fmt": "jsonl", "cell": cell_id},
- timeout=120,
- stream=True,
- )
- _raise_with_detail(resp)
- partial = cached.with_suffix(".part")
- with partial.open("wb") as fh:
- for chunk in resp.iter_content(chunk_size=65_536):
- fh.write(chunk)
- partial.replace(cached)
- hash_file.write_text(resp.headers.get("X-Overmind-Fingerprint") or fingerprint)
- return cached
-
- def get_candidate(self, candidate_id: str) -> dict:
- resp = self._session.get(
- f"{self.base_url}/api/optimizer-candidates/{candidate_id}/",
- timeout=30,
- )
- _raise_with_detail(resp)
- return resp.json()
diff --git a/overmind/overmind/optimizer_cmd.py b/overmind/overmind/optimizer_cmd.py
deleted file mode 100644
index e631b5cc..00000000
--- a/overmind/overmind/optimizer_cmd.py
+++ /dev/null
@@ -1,433 +0,0 @@
-"""``overmind optimise`` — client-driven prompt/code search; server scores.
-
-Typical loop (driven by the ``/overmind optimise`` skill):
-
- overmind optimise start -c <slug> -d <dataset-id>
- overmind optimise next
- overmind optimise set-template run_cmd.sh
- overmind optimise run-smoke
- overmind optimise run-baseline
- overmind optimise add-candidate --diff <file>
- overmind optimise run-iteration
- overmind optimise complete
-"""
-
-from __future__ import annotations
-
-import json
-import os
-from pathlib import Path
-from typing import Annotated
-
-import typer
-from rich.console import Console
-from rich.panel import Panel
-from rich.table import Table
-
-import overmind.config as config_mod
-from overmind.config import resolve_api_credentials
-from overmind.optimizer import OptimiseLoop, attach_optimise, start_optimise
-from overmind.optimizer_api import OptimizerAPI
-
-OPTIMISE_HELP = "Generate candidates locally; the server scores them."
-
-optimise_app = typer.Typer(
- name="optimise",
- help=OPTIMISE_HELP,
- no_args_is_help=True,
- invoke_without_command=False,
-)
-console = Console()
-
-_STATE_FILE = Path(".overmind") / "optimise_state.json"
-_DATASET_CACHE = Path(".overmind") / "datasets"
-
-
-def _load_config() -> config_mod.Config:
- try:
- return config_mod.load()
- except FileNotFoundError:
- console.print("[red]overmind.toml not found. Run `overmind sync` first.[/]")
- raise typer.Exit(1) from None
-
-
-def _make_api(cfg: config_mod.Config) -> OptimizerAPI:
- try:
- api_key, base_url = resolve_api_credentials("", "", cfg)
- except ValueError as exc:
- console.print(f"[red]{exc}[/]")
- raise typer.Exit(1) from exc
- if not api_key:
- console.print("[red]No API key. Run `overmind sync` or set OVERMIND_API_KEY.[/]")
- raise typer.Exit(1)
- return OptimizerAPI(base_url, api_key)
-
-
-def _load_state() -> dict:
- if _STATE_FILE.exists():
- try:
- return json.loads(_STATE_FILE.read_text())
- except (json.JSONDecodeError, OSError):
- return {}
- return {}
-
-
-def _save_state(state: dict) -> None:
- _STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
- _STATE_FILE.write_text(json.dumps(state, indent=2))
-
-
-def _resolve_experiment_id(explicit: str | None) -> str:
- if explicit:
- return explicit
- state = _load_state()
- eid = state.get("experiment_id")
- if not eid:
- console.print("[red]No active experiment. Run `overmind optimise start` first, or pass --experiment <id>.[/]")
- raise typer.Exit(1)
- return eid
-
-
-def _make_loop(experiment_id: str, cfg: config_mod.Config) -> OptimiseLoop:
- api = _make_api(cfg)
- state = _load_state()
- dataset_path_raw = state.get("dataset_path")
- if not dataset_path_raw:
- console.print("[red]No dataset path in local state. Re-run `overmind optimise start`.[/]")
- raise typer.Exit(1)
- return OptimiseLoop(
- api,
- experiment_id,
- repo_cwd=os.getcwd(),
- dataset_path=Path(dataset_path_raw),
- state_path=_STATE_FILE,
- )
-
-
-def _print_experiment(exp: dict) -> None:
- scores = exp.get("scores") or {}
- console.print(
- Panel(
- f"[bold]Optimise[/] {exp.get('id', '')}\n"
- f"status: [cyan]{exp.get('status', '')}[/] "
- f"mode: {exp.get('mode', 'optimize')}\n"
- f"scores: {json.dumps(scores)}",
- title="Overmind Optimise",
- border_style="blue",
- )
- )
-
-
-def _print_scores(exp: dict) -> None:
- scores = exp.get("scores") or {}
- if not scores:
- console.print("scores: {}")
- return
- table = Table(title="Scores")
- table.add_column("key")
- table.add_column("value", justify="right")
- for key, value in scores.items():
- if isinstance(value, dict):
- continue
- table.add_row(str(key), f"{value}")
- console.print(table)
-
-
-def _print_action(action: dict) -> None:
- name = action.get("action", "")
- exp = action.get("experiment") or {}
- _print_experiment(exp)
-
- if name == "WRITE_COMMAND_TEMPLATE":
- console.print("\n[bold yellow]Action: WRITE_COMMAND_TEMPLATE[/]")
- console.print("Write the command template, then:\n\n [bold]overmind optimise set-template <file>[/]\n")
- prompt = action.get("prompt", "")
- if prompt:
- console.print(Panel(prompt, title="Prompt for your agent", border_style="yellow"))
-
- elif name == "RUN_SMOKE":
- console.print("\n[bold yellow]Action: RUN_SMOKE[/]")
- console.print("Run: [bold]overmind optimise run-smoke[/]")
-
- elif name == "RUN_BASELINE":
- console.print("\n[bold yellow]Action: RUN_BASELINE[/]")
- console.print("Run: [bold]overmind optimise run-baseline[/]")
-
- elif name == "WRITE_CANDIDATES":
- console.print("\n[bold yellow]Action: WRITE_CANDIDATES[/]")
- console.print(
- "Write unified diffs, then:\n\n"
- " [bold]overmind optimise add-candidate --diff <file>[/]\n"
- " [bold]overmind optimise run-iteration[/]\n"
- )
- prompt = action.get("prompt", "")
- if prompt:
- console.print(Panel(prompt, title="Prompt for your agent", border_style="yellow"))
-
- elif name == "RUN_ITERATION":
- pending = action.get("pending", 0)
- console.print("\n[bold yellow]Action: RUN_ITERATION[/]")
- console.print(f"Pending diffs: {pending}")
- console.print("Run: [bold]overmind optimise run-iteration[/]")
-
- elif name == "WAIT":
- console.print(f"\n[bold blue]Action: WAIT[/] — {action.get('message', '')}")
-
- elif name == "COMPLETE":
- console.print("\n[bold green]Action: COMPLETE[/]")
- console.print(f"Scores: {json.dumps(action.get('scores') or {})}")
- console.print("Run: [bold]overmind optimise complete[/]")
-
- elif name == "DONE":
- console.print("\n[bold green]DONE[/] — experiment is terminal.")
- console.print(f"Status: {exp.get('status', '')}")
- _print_scores(exp)
-
- else:
- console.print(f"[yellow]Unknown action: {name}[/]")
-
-
-@optimise_app.command("start")
-def start(
- capability: Annotated[
- str,
- typer.Option("--capability", "-c", help="Capability slug or UUID"),
- ] = "",
- dataset: Annotated[
- str,
- typer.Option("--dataset", "-d", help="Dataset UUID"),
- ] = "",
- experiment: Annotated[
- str,
- typer.Option("--experiment", "-e", help="Attach to an existing experiment instead of creating"),
- ] = "",
- eval_set: Annotated[
- str,
- typer.Option("--eval-set", help="Eval set UUID (defaults to capability active set)"),
- ] = "",
- mode: Annotated[
- str,
- typer.Option("--mode", help="optimize | hybrid"),
- ] = "optimize",
- models: Annotated[
- list[str] | None,
- typer.Option("--model", "-m", help="OpenRouter model id (hybrid only, repeatable)"),
- ] = None,
- iterations: Annotated[int, typer.Option("--iterations", help="Max candidate iterations")] = 5,
- candidates: Annotated[int, typer.Option("--candidates", help="Candidates per iteration")] = 3,
-) -> None:
- """Create an optimize experiment (or attach to one) and cache the dataset locally."""
- cfg = _load_config()
- api = _make_api(cfg)
- before = experiment or _load_state().get("experiment_id", "")
-
- try:
- if experiment:
- exp, dataset_path, _loop = attach_optimise(
- api,
- experiment,
- cache_dir=_DATASET_CACHE,
- state_path=_STATE_FILE,
- repo_cwd=os.getcwd(),
- )
- else:
- if not capability or not dataset:
- console.print("[red]Pass --capability and --dataset, or --experiment to attach.[/]")
- raise typer.Exit(1)
- cap = cfg.capabilities.get(capability)
- cap_id = (cap.id if cap else "") or capability
- exp, dataset_path, _loop = start_optimise(
- api,
- capability_id=cap_id,
- dataset_id=dataset,
- eval_set_id=eval_set,
- cache_dir=_DATASET_CACHE,
- state_path=_STATE_FILE,
- repo_cwd=os.getcwd(),
- mode=mode,
- model_ids=models or None,
- num_iterations=iterations,
- num_candidates_per_iteration=candidates,
- )
- except Exception as exc:
- console.print(f"[red]Failed to start: {exc}[/]")
- created = _load_state().get("experiment_id", "")
- if created and created != before:
- console.print(f"Experiment {created} was created. Resume with --experiment {created}.")
- raise typer.Exit(1) from exc
-
- state = _load_state()
- state["dataset_path"] = str(dataset_path)
- _save_state(state)
-
- _print_experiment(exp)
- console.print(f"\n[green]Experiment ready:[/] {exp['id']}")
- console.print("Next: [bold]overmind optimise next[/]")
-
-
-@optimise_app.command("next")
-def next_action(
- experiment: Annotated[
- str | None,
- typer.Option("--experiment", "-e", help="Experiment ID (defaults to active)"),
- ] = None,
-) -> None:
- """Print the next action for the skill / agent to take."""
- cfg = _load_config()
- loop = _make_loop(_resolve_experiment_id(experiment), cfg)
- try:
- action = loop.next_action()
- except Exception as exc:
- console.print(f"[red]Error: {exc}[/]")
- raise typer.Exit(1) from exc
- _print_action(action)
-
-
-@optimise_app.command("set-template")
-def set_template(
- file: Annotated[Path, typer.Argument(help="Shell command template file")],
- experiment: Annotated[
- str | None,
- typer.Option("--experiment", "-e"),
- ] = None,
-) -> None:
- """Upload the command template the datapoint runner will render."""
- if not file.exists():
- console.print(f"[red]File not found: {file}[/]")
- raise typer.Exit(1)
- cfg = _load_config()
- loop = _make_loop(_resolve_experiment_id(experiment), cfg)
- try:
- exp = loop.set_template(file.read_text())
- except Exception as exc:
- console.print(f"[red]Failed to set template: {exc}[/]")
- raise typer.Exit(1) from exc
- console.print("[green]Template saved.[/]")
- _print_experiment(exp)
-
-
-@optimise_app.command("run-smoke")
-def run_smoke(
- experiment: Annotated[
- str | None,
- typer.Option("--experiment", "-e"),
- ] = None,
-) -> None:
- """Run the first datapoint once to verify the template."""
- cfg = _load_config()
- loop = _make_loop(_resolve_experiment_id(experiment), cfg)
- try:
- result = loop.run_smoke()
- except Exception as exc:
- console.print(f"[red]Smoke failed: {exc}[/]")
- raise typer.Exit(1) from exc
- if result.get("success"):
- console.print("[green]Smoke passed.[/]")
- else:
- console.print(f"[red]Smoke failed:[/] {result.get('error', '')}")
- raise typer.Exit(1)
- if result.get("output"):
- console.print(Panel(result["output"][-2000:], title="stdout (tail)", border_style="dim"))
-
-
-@optimise_app.command("run-baseline")
-def run_baseline(
- experiment: Annotated[
- str | None,
- typer.Option("--experiment", "-e"),
- ] = None,
-) -> None:
- """Run the full dataset against the current tree, post outputs, wait for scores."""
- cfg = _load_config()
- loop = _make_loop(_resolve_experiment_id(experiment), cfg)
- try:
- exp = loop.run_baseline()
- except Exception as exc:
- console.print(f"[red]Baseline failed: {exc}[/]")
- raise typer.Exit(1) from exc
- console.print("[green]Baseline scored.[/]")
- _print_experiment(exp)
-
-
-@optimise_app.command("add-candidate")
-def add_candidate(
- diff: Annotated[Path, typer.Option("--diff", help="Unified git diff file")],
- experiment: Annotated[
- str | None,
- typer.Option("--experiment", "-e"),
- ] = None,
-) -> None:
- """Queue a candidate unified diff for the next iteration."""
- if not diff.exists():
- console.print(f"[red]File not found: {diff}[/]")
- raise typer.Exit(1)
- cfg = _load_config()
- loop = _make_loop(_resolve_experiment_id(experiment), cfg)
- try:
- result = loop.add_candidate_diff(diff.read_text())
- except Exception as exc:
- console.print(f"[red]Failed to add candidate: {exc}[/]")
- raise typer.Exit(1) from exc
- console.print(f"[green]Queued.[/] pending={result['pending']}")
-
-
-@optimise_app.command("run-iteration")
-def run_iteration(
- experiment: Annotated[
- str | None,
- typer.Option("--experiment", "-e"),
- ] = None,
-) -> None:
- """Apply queued diffs, run datapoints, post outputs, wait for scores."""
- cfg = _load_config()
- loop = _make_loop(_resolve_experiment_id(experiment), cfg)
- try:
- exp = loop.run_iteration()
- except Exception as exc:
- console.print(f"[red]Iteration failed: {exc}[/]")
- raise typer.Exit(1) from exc
- console.print("[green]Iteration scored.[/]")
- _print_experiment(exp)
- _print_scores(exp)
-
-
-@optimise_app.command("status")
-def status(
- experiment: Annotated[
- str | None,
- typer.Option("--experiment", "-e"),
- ] = None,
- as_json: Annotated[bool, typer.Option("--json")] = False,
-) -> None:
- """Show experiment status and scores."""
- cfg = _load_config()
- loop = _make_loop(_resolve_experiment_id(experiment), cfg)
- exp = loop.status()
- if as_json:
- console.print_json(data=exp)
- return
- _print_experiment(exp)
- _print_scores(exp)
-
-
-@optimise_app.command("complete")
-def complete(
- experiment: Annotated[
- str | None,
- typer.Option("--experiment", "-e"),
- ] = None,
-) -> None:
- """Seal the experiment and record the winner on the server."""
- cfg = _load_config()
- loop = _make_loop(_resolve_experiment_id(experiment), cfg)
- try:
- exp = loop.complete()
- except Exception as exc:
- console.print(f"[red]Complete failed: {exc}[/]")
- raise typer.Exit(1) from exc
- console.print("[green]Experiment completed.[/]")
- _print_experiment(exp)
- _print_scores(exp)
- winner = (exp.get("state") or {}).get("winner_candidate_id")
- if winner:
- console.print(f"Winner: [bold]{winner}[/]")
diff --git a/overmind/overmind/skills.py b/overmind/overmind/skills.py
index 4b3d43f4..9d826d54 100644
--- a/overmind/overmind/skills.py
+++ b/overmind/overmind/skills.py
@@ -10,7 +10,7 @@ from rich.console import Console
from rich.table import Table
from typer import echo
-from overmind.skills_db import SKILLS_VERSION, Skill, skills
+from overmind.skills_db import RETIRED_SKILL_SLUGS, SKILLS_VERSION, Skill, skills
console = Console()
@@ -83,6 +83,15 @@ def sync_skill(skill: Skill, ide: str):
logging.info(f"Copied {src} to {dest}")
+def remove_retired_skills(ide: str) -> None:
+ roots = [os.path.join(get_destination_dir(ide), "skills")]
+ if ide == "cursor":
+ roots.append(os.path.join(".cursor", "skills"))
+ for root in roots:
+ for slug in RETIRED_SKILL_SLUGS:
+ shutil.rmtree(os.path.join(root, slug), ignore_errors=True)
+
+
def get_destination_dir(ide: str):
if ide in ("cursor", "codex"):
return ".agents"
diff --git a/overmind/overmind/skills_db.py b/overmind/overmind/skills_db.py
index 5f8dd847..0f24f964 100644
--- a/overmind/overmind/skills_db.py
+++ b/overmind/overmind/skills_db.py
@@ -1,7 +1,7 @@
from dataclasses import dataclass
# Every plugin manifest (.claude-plugin, .codex-plugin, .cursor-plugin) carries this version.
-SKILLS_VERSION = "1.2.14"
+SKILLS_VERSION = "1.3.0"
@dataclass
@@ -46,12 +46,6 @@ skills = [
description="Prepare evaluations and compare measured results",
provider="overmind-core",
),
- Skill(
- name="Overmind Optimiser",
- slug="overmind-optimiser",
- description="Improve prompts, code and model choices",
- provider="overmind-core",
- ),
Skill(
name="Model Training Engineering",
slug="model-training-engineering",
@@ -77,3 +71,6 @@ skills = [
provider="overmind-core",
),
]
+
+# Slugs the catalog no longer ships; `overmind init` deletes their installed copies.
+RETIRED_SKILL_SLUGS: tuple[str, ...] = ("overmind-optimiser",)
diff --git a/overmind/overmind/tracing.py b/overmind/overmind/tracing.py
index f852c150..fa096748 100644
--- a/overmind/overmind/tracing.py
+++ b/overmind/overmind/tracing.py
@@ -539,8 +539,8 @@ class _GenAiUsageSpanProcessor(SpanProcessor):
def _attach_remote_parent_if_present() -> None:
- """Attach the W3C ``TRACEPARENT`` env var (injected by the optimiser into
- agent subprocesses) as the ambient parent context. No-op when absent."""
+ """Attach the W3C ``TRACEPARENT`` env var (set by a parent process that launched
+ this one) as the ambient parent context. No-op when absent."""
raw = os.environ.get("TRACEPARENT") or os.environ.get("OTEL_TRACEPARENT")
if not raw:
return
@@ -757,30 +757,6 @@ def init(
_track_sdk_init("success", providers=providers, capability_id=capability_id)
return True
- # Optimise-step subprocess: the runner wrapper set up a file-exporter
- # provider (OVERMIND_TRACE_FILE) and stripped the API key — reuse it
- # instead of crashing or replacing the exporter.
- if os.environ.get("OVERMIND_TRACE_FILE") and not (overmind_api_key or os.environ.get("OVERMIND_API_KEY")):
- from overmind import __version__ as sdk_version
-
- logger.debug(
- "Overmind SDK init() skipped: OVERMIND_TRACE_FILE is set and no "
- "OVERMIND_API_KEY available; reusing the local file-exporter "
- "TracerProvider configured by the optimise runner wrapper.",
- )
- _ensure_pipeline_processors(trace.get_tracer_provider())
- _tracer = trace.get_tracer("overmind", sdk_version)
- _seed_identity_context(capability_id, capability_name, project_id)
- enable_tracing(providers)
- _attach_remote_parent_if_present()
- _initialized = True
- if debug:
- _log_debug_summary(
- f"file:{os.environ['OVERMIND_TRACE_FILE']}", capability_id, capability_name, project_id
- )
- _track_sdk_init("success", providers=providers, capability_id=capability_id)
- return True
-
local_config = _local_config()
try:
overmind_api_key, overmind_base_url = resolve_api_credentials(
diff --git a/overmind/pyproject.toml b/overmind/pyproject.toml
index c1bb39d9..4025fbee 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.128"
+version = "0.1.129"
[project.urls]
"Agent setup" = "https://console.overmindlab.ai/setup.md"
diff --git a/overmind/skills/overmind-datasets/SKILL.md b/overmind/skills/overmind-datasets/SKILL.md
index 692a303c..27770a60 100644
--- a/overmind/skills/overmind-datasets/SKILL.md
+++ b/overmind/skills/overmind-datasets/SKILL.md
@@ -47,7 +47,7 @@ create (`create_dataset_from_traces` / `_failures`), or later with
a train dataset and an eval dataset with disjoint rows. There is no reingest tool and
no dual-intent dataset.
-Eval runs (`run_evaluation`) and optimizer experiments (`start_optimizer`) use an
+Eval runs (`run_evaluation`) use an
**eval** version; `train` and `pending` are refused. Fine-tuning (`start_finetune`)
needs a **train** version and, for a chat model, a user-confirmed eval set; a separate
**eval** dataset is needed only when chat judge evaluations are requested. Native
diff --git a/overmind/skills/overmind-evaluations/SKILL.md b/overmind/skills/overmind-evaluations/SKILL.md
index ffe63980..f500fc5d 100644
--- a/overmind/skills/overmind-evaluations/SKILL.md
+++ b/overmind/skills/overmind-evaluations/SKILL.md
@@ -1,6 +1,6 @@
---
name: overmind-evaluations
-description: Prepare and run Overmind evaluations, author eval matrix rows and eval sets, compare runs, and inspect row-level failures. Use for judging a change against a baseline; training and repository optimisation have separate workflows.
+description: Prepare and run Overmind evaluations, author eval matrix rows and eval sets, compare runs, and inspect row-level failures. Use for judging a change against a baseline; training has a separate workflow.
---
# Overmind Evaluations
@@ -66,7 +66,7 @@ observations of the same criteria.
## Configure the active eval set
A capability's **active eval set** is the one set of criteria live scoring, eval
-runs, `overmind backtest`, the optimizer and training all grade with. Its rows come
+runs and training all grade with. Its rows come
from three places:
| Source | Holds | Changed by |
@@ -153,8 +153,8 @@ Omission uses the default judge. The run freezes its judge and matrix; create a
new run to change either. Pass an approved judge choice to `start_finetune` as
`eval_judge_model`.
-The dataset's intent must be **eval** and the chosen cell must fit: eval runs and
-optimizer experiments refuse `train` and `pending` datasets (see the
+The dataset's intent must be **eval** and the chosen cell must fit: eval runs
+refuse `train` and `pending` datasets (see the
[dataset contracts](../overmind-datasets/SKILL.md#intent-and-contracts)). The run uses the version it
read, which freezes it.
@@ -184,9 +184,8 @@ reason, and the run's `summary` (`score`, per-metric means, failures and errors,
baseline. Status is `improved`, `regressed`, `unchanged`, `added` or `removed`;
deltas within half a point are `unchanged`.
-`overmind backtest`, the optimizer (including `model_comparison`) and fine-tuning
-before/after evaluations each grade with the capability's active set unless given
-another and keep the same rows for their whole run, so confirm the set before
+Fine-tuning before/after evaluations grade with the capability's active set unless
+given another and keep the same rows for their whole run, so confirm the set before
starting one. They create their own baseline and candidate runs in one group; a
manual eval run beforehand is only for comparisons you drive yourself.
diff --git a/overmind/skills/overmind-optimiser/SKILL.md b/overmind/skills/overmind-optimiser/SKILL.md
deleted file mode 100644
index f17708f8..00000000
--- a/overmind/skills/overmind-optimiser/SKILL.md
+++ /dev/null
@@ -1,174 +0,0 @@
----
-name: overmind-optimiser
-description: Set up, inspect and complete Overmind Optimiser experiments for prompt/code changes or model comparisons. Use when improving a capability through measured candidates and a local repository executioner.
----
-
-# Overmind Optimiser
-
-Start with `list_projects` and choose the intended accessible project. For an
-account connection, pass its `project_id` on every project tool and resource
-URI query; follow returned links. Project API keys retain their narrower access.
-
-Find a measured improvement while preserving the experiment's own baseline and
-the user's selected task. Use the chosen MCP project and resolve all dataset
-and capability references from its returned records.
-
-## Choose the experiment
-
-Distinguish prompt/code optimization from model comparison. Prefer the native
-`optimize-capability` prompt for the first, or `compare-models` for a selected
-model list. Check the current schema for `optimize`, `model_comparison` or
-`hybrid` mode; do not silently substitute one for another.
-
-Use `list_datasets`, `inspect_dataset` and `query_dataset` to select a fitting
-eval cell. Call `check_optimizer_readiness` with that cell, capability, mode,
-eval set and requested models. Explain missing executioner, model or credit
-prerequisites. Every iteration is graded with the rows of the
-experiment's first run, by default the capability's active eval set; confirm
-it holds the code's expectations and toml checks (`eval_preload` on the
-capability, refreshed by `overmind sync`) before starting. The dataset stays on the server; a local file must be
-landed before an experiment can use it.
-
-## Execute within the approved scope
-
-After the mode, candidate scope and spend are authorized, `start_optimizer`
-creates the experiment. MCP schedules and reports it; a local executioner runs
-repository commands and candidates. Do not claim that a scheduled experiment
-has executed or that MCP can apply a repository diff.
-
-Follow the returned `next_action` and exact command in the intended checkout.
-Use local `overmind optimise ... --help` for commands unavailable in the client.
-If the client cannot run local code, provide that handoff and continue read-only
-status inspection. Preserve existing repository changes.
-
-The experiment scores its own baseline iteration. Do not create a separate
-baseline run and use it as the improvement gate. Candidate changes must solve
-the task rather than encode held-out answers. Stop at the returned completion
-or plateau checkpoint; do not extend the search budget without authorization.
-
-Hard rules for every experiment:
-
-1. **Eval intent only.** The chosen dataset cell must fit the **eval** contract (see
- [dataset contracts](../overmind-datasets/SKILL.md#intent-and-contracts)).
- Train and pending datasets are refused.
-1. **The server always holds the dataset.** The experiment uses the chosen cell and
- the loop pulls that version to `.overmind/datasets/<cell_id>.jsonl`. A JSONL path
- on this machine is landed first (`POST /api/datasets/` with `rows` and
- `intent: eval`), then used by id. Pull the used version once; never re-fetch it
- per model.
-1. **No manual baseline eval run.** The experiment scores its own baseline iteration
- (`order=0`); that is what the improvement delta and the landing gate use.
-1. **Grade with the active eval set.** Every iteration or model is scored with the
- rows of the experiment's first run, by default the capability's active set.
- Modes are exactly `optimize`, `model_comparison` and `hybrid`.
-
-Experiment statuses include `scheduled`, `smoke_testing`, `baseline`, `iterating`,
-evaluation wait states, `applying_winner`, `completed`, `failed`, `cancelled` and
-`paused`. A terminal result may select a candidate or the incumbent.
-
-## Local executioner loop
-
-The connected executioner runs repository commands and records per-datapoint results
-in the local SDK/CLI ledger. The main MCP server schedules metadata and reports
-scores; it does not execute the repository, apply candidate diffs, or provide
-per-iteration result-posting tools, so do not call removed per-iteration tools. When
-the server returns it, the local command is:
-
-```bash
-overmind optimise start -e <experiment-id> && overmind optimise next
-```
-
-The local loop may request these SDK/CLI actions: `set-template`, `run-smoke`,
-`run-baseline`, `add-candidate`, `run-iteration`, `status` and `complete`. They are
-local commands, not MCP tool names; run them in the repository with the required
-human authorization for local code or Git side effects. `overmind optimise next`
-returns the action to take:
-
-| Action | What you do |
-| ------------------------ | ------------------------------------------------------------ |
-| `WRITE_COMMAND_TEMPLATE` | Write the template, then `set-template` |
-| `RUN_SMOKE` | `overmind optimise run-smoke` |
-| `RUN_BASELINE` | `overmind optimise run-baseline` |
-| `WRITE_CANDIDATES` | Write unified diffs, `add-candidate --diff`, `run-iteration` |
-| `RUN_ITERATION` | `overmind optimise run-iteration` |
-| `WAIT` | Server scoring — `next` again shortly |
-| `COMPLETE` | `overmind optimise complete` |
-| `DONE` | Finished — report scores |
-
-`next` returns `COMPLETE` early (with a `reason`) once
-`max_iterations_without_improvement` consecutive rounds fail to beat the best score;
-write no more candidates past that plateau.
-
-Command template (`WRITE_COMMAND_TEMPLATE`): one reusable shell command that runs the
-capability on a single datapoint and prints output. Keep tokens verbatim
-(`__DATAPOINT_INPUT__`, `__EXPERIMENT_ID__`, `__CAPABILITY_ID__`, `__CANDIDATE_ID__`,
-`__ITERATION_ID__`, `__DATAPOINT_INDEX__`, `__PROJECT_ID__`). Prefer an env/config
-model swap over rewriting call sites.
-
-Candidates are unified git diffs against the current repository. Keep the entrypoint
-signature and do not hardcode datapoint answers. The SDK applies each diff in a
-worktree, runs the dataset and POSTs outputs; the server runs the eval runs.
-
-```
-overmind optimise start -c <slug> -d <dataset-id>
-overmind optimise start -e <experiment-id>
-overmind optimise next
-overmind optimise set-template <file>
-overmind optimise run-smoke
-overmind optimise run-baseline
-overmind optimise add-candidate --diff <file>
-overmind optimise run-iteration
-overmind optimise status [--json]
-overmind optimise complete
-```
-
-Done when the experiment is completed and scores are reported, the best candidate
-beat the baseline or the plateau is clear, and a winning diff is applied locally when
-it won.
-
-## Model comparison and backtest
-
-Use the native `compare-models` prompt. This is optimizer mode `model_comparison`,
-not prompt/code optimisation and not fine-tuning; do not use the iteration loop for
-it. Call `check_optimizer_readiness` with `mode="model_comparison"` and 1–5
-`model_ids` (the backend rejects an empty list or more than five), then
-`start_optimizer` with the same capability, dataset, mode and models after the human
-approves the model list. Use only model ids the readiness result returns or accepts;
-do not invent catalogue ids. The server validates model access, credits,
-eval-set readiness and executioner connectivity. Inspect progress with
-`inspect_optimizer_result` and `overmind://optimizer-runs/{experiment}`.
-
-The executioner owns local state, provider configuration, trace emission and result
-reporting; MCP owns project-scoped scheduling and result inspection. Provider rewrite
-is code, not a prompt: when the repository needs model-provider translation, run
-`overmind.backtest.rewrite_repo(".")`, review its report and patch only the leftover
-sites it lists. The runtime model is `OPENROUTER_MODEL` or the repository's existing
-configuration; never hardcode a model slug. Pinning a winner is a local repository or
-configuration change that a human reviews and applies.
-
-`overmind backtest` is the model layer: it scores stored `llm_call` spans, does not
-run the application or its tools, and uses the recorded completion as the baseline.
-
-```bash
-overmind backtest --models openai/gpt-5-mini,anthropic/claude-sonnet-4.5 --since 7d
-```
-
-`--capability` is required when `overmind.toml` lists more than one. `--limit` caps
-the calls (default 200). The command waits and exits 1 when any candidate regresses
-against the recorded outputs, 2 on timeout. `overmind optimise` remains the path that
-reruns the repository.
-
-## Inspect and land
-
-Use `inspect_optimizer_result`, `overmind://optimizer-runs/{experiment}` and
-`get_job(kind=optimizer_experiment, id=...)` for progress, coverage, failures,
-candidate scores and the winner. A terminal run may retain the incumbent.
-Describe partial coverage and incomplete evaluations before naming a winner.
-
-Present the winning diff and its measured delta against the experiment's own
-baseline. Apply it locally only when landing that change is authorized; changing
-code, switching the live serving alias and selecting a benchmark are distinct
-actions. Report whether a change was merely proposed or actually applied.
-
-Open `optimiser/{experiment_id}` under the project's Console base with the same
-`projectId` when a visual result is useful.
diff --git a/overmind/skills/overmind-optimiser/agents/openai.yaml b/overmind/skills/overmind-optimiser/agents/openai.yaml
deleted file mode 100644
index c6cdacb3..00000000
--- a/overmind/skills/overmind-optimiser/agents/openai.yaml
+++ /dev/null
@@ -1,7 +0,0 @@
-interface:
- display_name: "Overmind Optimiser"
- short_description: "Improve prompts, code and model choices"
- default_prompt: "Use $overmind-optimiser to assess readiness for a capability optimisation experiment."
- brand_color: "#ED670F"
- icon_small: "./assets/icon.png"
- icon_large: "./assets/icon.png"
diff --git a/overmind/skills/overmind-optimiser/assets/icon.png b/overmind/skills/overmind-optimiser/assets/icon.png
deleted file mode 100644
index f069132e..00000000
Binary files a/overmind/skills/overmind-optimiser/assets/icon.png and /dev/null differ
diff --git a/overmind/skills/overmind/SKILL.md b/overmind/skills/overmind/SKILL.md
index 096f9205..1535e200 100644
--- a/overmind/skills/overmind/SKILL.md
+++ b/overmind/skills/overmind/SKILL.md
@@ -30,8 +30,8 @@ file and follow it:
- `dataset`: [Datasets](../overmind-datasets/SKILL.md)
- `model-workflows`: [Develop models from data](../overmind-training/SKILL.md#develop-models-from-data)
- `finetune`: [Training](../overmind-training/SKILL.md)
-- `optimise`: [Optimiser](../overmind-optimiser/SKILL.md)
-- `backtest`: [Model comparison and backtest](../overmind-optimiser/SKILL.md#model-comparison-and-backtest)
+- `improve`: [references/improve.md](references/improve.md)
+- `compare-models`: [references/compare-models.md](references/compare-models.md)
## Product surface skills
@@ -45,7 +45,6 @@ Each works directly with the configured MCP connection and can be used on its ow
| [Observability](../overmind-observability/SKILL.md) | Traces, failures, signals, latency and Python instrumentation |
| [Datasets](../overmind-datasets/SKILL.md) | Intent and contracts, transformations, lineage, export |
| [Evaluations](../overmind-evaluations/SKILL.md) | Eval matrix, eval sets, live scoring, runs and comparisons |
-| [Optimiser](../overmind-optimiser/SKILL.md) | Prompt/code experiments, model comparison and backtest |
| [Training](../overmind-training/SKILL.md) | Model selection, preparation, cost, fine-tuning, data-first |
| [Inference](../overmind-inference/SKILL.md) | Deployments, serving metrics, inference and activation |
| [Integrations](../overmind-integrations/SKILL.md) | Provider connectors, boundary mapping and trace import |
@@ -66,8 +65,6 @@ Route guided work to these exact prompt names:
- `prepare-evaluation`: check evaluation dataset, eval matrix rows, eval set, and credits.
- `evaluate-change`: run an evaluation and compare it with a supplied baseline.
- `finetune-capability`: check, estimate, launch, and verify fine-tuning.
-- `optimize-capability`: schedule and inspect prompt/code optimization.
-- `compare-models`: schedule and inspect model comparison.
- `ship-model`: verify deployment, activate a model, and hand off repository rollout.
Do not reimplement these workflows as a single generic call. The prompt
@@ -144,7 +141,7 @@ update the report when the outcome changes.
Use returned scoped resource links and explicit IDs for follow-up work.
`list_datasets` remains the dataset-specific inventory.
1. **Contracts gate dataset consumption.** Fine-tuning needs a `train`
- version; eval runs and optimizer experiments need `eval`; `pending` is
+ version; eval runs need `eval`; `pending` is
refused. See [Datasets: intent and contracts](../overmind-datasets/SKILL.md#intent-and-contracts).
1. **Follow structured errors and durable receipts.** Read the error code, fields and retryability. Creation and paid launch are separate where the schema specifies a draft. Authorization already granted for an unchanged saved scope persists through routine continuation. Unresolved provider submissions require receipt recovery; never blindly repeat them.
1. **Tracing is Python-only and approval-gated.** Check the application code
@@ -171,7 +168,7 @@ update the report when the outcome changes.
resource for recipe/checkpoint details; absent pins remain unknown.
- **Async jobs.** Poll returned job references with `get_job(kind, id)`, or inspect up to eight with `inspect_jobs`. Pass its cursor as `after` with `timeout_seconds` (0–30) to wait for changes.
Source landing uses `kind=dataset_run`; transformations use the returned `kind=dataset_pipeline` and run ID. Other supported kinds include
- `eval_run`, `finetune_job`, `deployment`, `model_activation`, and `optimizer_experiment`.
+ `eval_run`, `finetune_job`, `deployment` and `model_activation`.
- `inspect_operation` reads a linked operational receipt, with `after`/`limit`
pagination over its durable events. It never wakes a worker. Distinguish observed
state, heartbeat and forward progress; shared-pool telemetry does not prove a
@@ -202,7 +199,6 @@ group's owning skill carries its workflow.
`start_finetune`, `save_training_plan`, `create_training_experiment`.
- Serving: `retry_deployment`, `set_active_model`, `set_benchmark_model`,
`run_inference`, `get_model_swap_prompt`.
-- Optimization: `check_optimizer_readiness`, `start_optimizer`, `inspect_optimizer_result`.
- Connectors: `inspect_connectors`, `configure_connector`, `sync_connector`.
## How the workflows chain
@@ -215,15 +211,15 @@ Typical loop (local setup once, then MCP):
is Python, add tracing; any other language gets none.
1. **Turn traces into data and shape it**: [Datasets](../overmind-datasets/SKILL.md).
1. **Grade it**: [Evaluations](../overmind-evaluations/SKILL.md). The capability's
- active eval set grades live traces, eval runs, backtests, the optimizer and
- training alike. Finetune and optimizer runs create their own baselines; do not
- spend a manual eval run just to give them a comparison point.
-1. **Improve**: [Training](../overmind-training/SKILL.md) (**train** dataset),
- [Optimiser](../overmind-optimiser/SKILL.md) (**eval** dataset; `/overmind optimise`
- or `/overmind backtest`).
+ active eval set grades live traces, eval runs and training alike. Fine-tuning
+ creates its own baseline; do not spend a manual eval run just to give it a
+ comparison point.
+1. **Improve**: [Training](../overmind-training/SKILL.md) (**train** dataset), or
+ change a prompt or code with [improve](references/improve.md) and try other
+ models with [compare-models](references/compare-models.md) (**eval** dataset).
1. **Prove it**: `compare_evaluations` new vs the automatic baseline.
1. **Ship**: [Inference](../overmind-inference/SKILL.md) for activation and
- `get_model_swap_prompt`, or land the optimizer winner's diff locally.
+ `get_model_swap_prompt`.
## Resources
@@ -254,11 +250,10 @@ The implemented resource templates are:
- `overmind://signal-events`
- `overmind://finetunes/{job_id}`
- `overmind://deployments/{deployment}`
-- `overmind://optimizer-runs/{experiment}`
- `overmind://connectors/{connector}`
- `overmind://jobs/{kind}/{id}`
-Use a capability, dataset, run, deployment, connector, or experiment name/id
+Use a capability, dataset, run, deployment or connector name/id
only where the tool schema accepts it. Resource reads are project-scoped and
return JSON.
@@ -276,7 +271,6 @@ the relevant route using a resource ID already resolved through MCP:
| Dataset | `datasets/{id}` |
| Evaluation run | `evaluations/runs/{id}` |
| Training | `training` |
-| Optimiser | `optimiser` |
| Serving | `inference` |
Use the host's browser-opening tool (Codex `open_in_codex` when available), or
diff --git a/overmind/skills/overmind/references/compare-models.md b/overmind/skills/overmind/references/compare-models.md
new file mode 100644
index 00000000..511b7f8f
--- /dev/null
+++ b/overmind/skills/overmind/references/compare-models.md
@@ -0,0 +1,44 @@
+# Compare models
+
+Use this to see how other models do on the calls a capability already made. The
+platform replays each recorded model call with a candidate model and scores the
+answers with the capability's active eval set. It does not run the application,
+its tools or its control flow, so a result covers one model call, not the whole
+agent.
+
+**Prerequisite:** a synced capability with an active eval set (see
+[Evaluations](../../overmind-evaluations/SKILL.md#configure-the-active-eval-set)).
+
+## Workflow
+
+1. **Choose the calls.** Use an existing **eval** dataset for the capability
+ (`list_datasets`, `inspect_dataset`). Without one, land recent calls with
+ `create_dataset_from_llm_calls` and intent `eval`, then wait for its
+ `dataset_run` job. Use `query_dataset` to confirm that rows carry the recorded
+ output.
+1. **Choose the models.** Use the OpenRouter ids the user names, in
+ `provider/model` form (for example `openai/gpt-5-mini`). Do not invent ids;
+ the platform rejects an id that OpenRouter does not serve. Ask the user to
+ confirm the list.
+1. **Check readiness and cost.** Call `check_evaluation_readiness` with the
+ dataset, its cell and these `targets`: one `recorded` target with
+ `is_baseline: true`, and one `generate` target per candidate with its
+ `model_name` and a `label`. Show `ready`, `estimated_cost_usd` and the context
+ warnings. `suggestions` lists models with room for longer rows; offer them, do
+ not add them yourself. Wait for the user to approve the spend.
+1. **Run.** Call `run_evaluation` with the same targets and a stable
+ `request_key`. Poll each returned run with `get_job(kind="eval_run")` until it
+ is terminal.
+1. **Compare.** Call `compare_evaluations` for each candidate run. Its baseline is
+ the recorded run in the same group.
+
+## Report
+
+For each model, give the overall score, the change against the recorded outputs,
+wins and losses, the per-metric changes and the trust flags. Name the cheapest
+model that does not regress. Report errored or degraded rows as missing data, not
+as low scores.
+
+Switching the model is a change to the user's code or configuration. Show the
+change and let the user apply it. For a model trained on Overmind, use
+`set_active_model` only when the user asks.
diff --git a/overmind/skills/overmind/references/improve.md b/overmind/skills/overmind/references/improve.md
new file mode 100644
index 00000000..bb12f1f6
--- /dev/null
+++ b/overmind/skills/overmind/references/improve.md
@@ -0,0 +1,44 @@
+# Improve a capability
+
+Use this to change a capability's prompt or code and show whether the change
+helps. You author the change; live scoring measures it with the capability's
+active eval set. A human applies the result.
+
+**Prerequisite:** a synced capability with an active eval set (see
+[Evaluations](../../overmind-evaluations/SKILL.md#configure-the-active-eval-set)),
+an **eval** dataset for it and Overmind tracing in the application.
+
+## Find what to fix
+
+1. Call `inspect_capability_health` and `query_failures` for the capability. Read
+ the failing metrics and the judge reasons on a few failed traces
+ (`query_traces`, then the trace resource).
+1. State the failure you will address and the metric that measures it. Do not
+ change the eval set to make a change pass.
+
+## Make and measure the change
+
+The platform cannot run the user's application. A prompt lives in the
+application, so a prompt change is measured the same way as a code change: run
+the application before and after the change, and let live scoring score both.
+
+1. Make the change on a new branch. Do not touch the main branch.
+1. Read the eval inputs with `query_dataset`.
+1. Before you run anything, show the user the command, the number of rows you will
+ run and what the application may call (tools, paid APIs, production systems).
+ Run only after the user approves.
+1. Run the application on the same inputs twice, once before and once after the
+ change, with Overmind tracing on. Give each run its own conversation id, so
+ each set of traces is one session.
+1. Wait for live scoring, then read `eval_score` for each set with `query_traces`
+ filtered by `session`. Compare the two sets on the same inputs. A trace without
+ a score is missing data.
+
+This comparison is not a paired eval run: the platform did not freeze the rows or
+pair the outputs. Say so in the report.
+
+## Report
+
+Show the diff, the metric it targets and the measured change. When the platform
+did not score a result, call it unmeasured and give no estimate. Do not merge or
+deploy the change; the user applies it.
diff --git a/overmind/skills/overmind/references/setup.md b/overmind/skills/overmind/references/setup.md
index 39fe7fe7..ea9f9401 100644
--- a/overmind/skills/overmind/references/setup.md
+++ b/overmind/skills/overmind/references/setup.md
@@ -254,7 +254,7 @@ Run this after `python -m overmind sync` succeeds: the entry-point decorator car
- **`llm_utilities` helper:** one expectation from the output side of `io_contract` when `structured_output` is true.
- **`reference_trajectory=[...]`:** only on an entry point whose `code_path` trajectory entry names an ordered tool sequence; copy the tool names from that entry.
- `output_schema`, `constraints` and `tool_protocol` are not expectations: the checkable ones already went to the toml's deterministic `eval_matrix`. Skip what the seeded checks cover (valid JSON, tool selection).
-1. Run `python -m overmind sync` again. It reads the `expectations` on the entry-point, workflow and `observe` decorators and adds them to each capability's Default eval set, so eval runs, `overmind backtest`, the optimizer and training judge what live scoring judges. Read `eval_preload.counts.expectations` on `overmind://capabilities/{capability}`; zero after decorating means the entry point's `capability_id` is missing or not the synced id.
+1. Run `python -m overmind sync` again. It reads the `expectations` on the entry-point, workflow and `observe` decorators and adds them to each capability's Default eval set, so eval runs and training judge what live scoring judges. Read `eval_preload.counts.expectations` on `overmind://capabilities/{capability}`; zero after decorating means the entry point's `capability_id` is missing or not the synced id.
1. Do not run the application. Verification needs the approved run described in [Observability](../../overmind-observability/SKILL.md#explicit-run-approval).
Never upload the repository. Never invent project or capability UUIDs.
diff --git a/overmind/tests/test_backtest.py b/overmind/tests/test_backtest.py
deleted file mode 100644
index dd19abed..00000000
--- a/overmind/tests/test_backtest.py
+++ /dev/null
@@ -1,157 +0,0 @@
-"""Tests for openrouter_env, write_state and rewrite_repo."""
-
-from __future__ import annotations
-
-import ast
-import importlib.util
-import json
-import sys
-from types import ModuleType, SimpleNamespace
-
-import pytest
-
-from overmind.backtest import OPENROUTER_BASE_URL, openrouter_env, rewrite_repo, write_state
-
-pytestmark = pytest.mark.covers("agent-code")
-
-
-def test_openrouter_env_requires_key(monkeypatch):
- monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)
- monkeypatch.delenv("OPENAI_API_KEY", raising=False)
- with pytest.raises(RuntimeError, match="OPENROUTER_API_KEY"):
- openrouter_env("openai/gpt-5-mini")
-
-
-def test_write_state_merges(tmp_path):
- path = write_state(tmp_path, {"experiment_id": "aaa", "models": ["m1"]})
- write_state(tmp_path, {"models": ["m1", "m2"]})
- payload = json.loads(path.read_text())
- assert payload["experiment_id"] == "aaa"
- assert payload["models"] == ["m1", "m2"]
-
-
-def test_rewrite_repo_openai_anthropic_env_and_leftover(tmp_path):
- (tmp_path / "client.py").write_text(
- "from openai import OpenAI\n"
- "client = OpenAI(api_key='sk')\n"
- "client.chat.completions.create(model='gpt-4', messages=[])\n"
- )
- (tmp_path / "anthropic_client.py").write_text(
- "from anthropic import Anthropic\n"
- "client = Anthropic(api_key='sk')\n"
- "client.messages.create(model='claude-3', max_tokens=8)\n"
- )
- (tmp_path / "chat.py").write_text(
- "from langchain_openai import ChatOpenAI\nllm = ChatOpenAI(model='gpt-4', temperature=0)\n"
- )
- (tmp_path / "leftover.py").write_text(
- "from langchain_anthropic import ChatAnthropic\nChatAnthropic(model='claude')\n"
- )
- venv = tmp_path / ".venv" / "lib"
- venv.mkdir(parents=True)
- (venv / "hidden.py").write_text("from openai import OpenAI\nOpenAI()\n")
- (tmp_path / ".env").write_text("FOO=bar\n")
-
- report = rewrite_repo(tmp_path)
-
- openai_src = (tmp_path / "client.py").read_text()
- assert "openrouter.ai" in openai_src
- assert "OPENROUTER_API_KEY" in openai_src
- assert "OPENROUTER_MODEL" in openai_src
- assert "import os" in openai_src
-
- anthropic_src = (tmp_path / "anthropic_client.py").read_text()
- assert "from openai import OpenAI" in anthropic_src
- assert "chat.completions.create" in anthropic_src
- assert ".messages.create(" not in anthropic_src
- assert "OPENROUTER_API_KEY" in anthropic_src
-
- chat_src = (tmp_path / "chat.py").read_text()
- assert "openai_api_base" in chat_src
- assert "OPENROUTER_MODEL" in chat_src
-
- leftover_src = (tmp_path / "leftover.py").read_text()
- assert "ChatAnthropic" in leftover_src
- assert any("leftover.py" in item for item in report.leftover)
-
- assert (venv / "hidden.py").read_text() == "from openai import OpenAI\nOpenAI()\n"
- env_src = (tmp_path / ".env").read_text()
- assert "OPENAI_BASE_URL=" in env_src
- assert "OPENAI_API_BASE=" in env_src
- assert ".env" in report.env_files
- assert "client.py" in report.changed
-
-
-def test_rewritten_entrypoint_routes_openrouter_per_model(tmp_path, monkeypatch):
- """The skill's runtime path: rewrite, set openrouter_env per model, run the
- repo's own entrypoint per datapoint — every call must hit OpenRouter with
- the env-selected model."""
- (tmp_path / "agent.py").write_text(
- "from openai import OpenAI\n"
- "\n"
- "def run(question):\n"
- " client = OpenAI(api_key='sk-original')\n"
- " resp = client.chat.completions.create(\n"
- " model='gpt-4o', messages=[{'role': 'user', 'content': question}]\n"
- " )\n"
- " return resp.choices[0].message.content\n"
- )
- rewrite_repo(tmp_path)
-
- ctors: list[dict] = []
- calls: list[dict] = []
-
- class _StubOpenAI:
- def __init__(self, **kwargs):
- ctors.append(kwargs)
- create = self._create
- self.chat = SimpleNamespace(completions=SimpleNamespace(create=create))
-
- @staticmethod
- def _create(**kwargs):
- calls.append(kwargs)
- message = SimpleNamespace(content=f"echo:{kwargs['model']}")
- return SimpleNamespace(choices=[SimpleNamespace(message=message)])
-
- stub = ModuleType("openai")
- stub.OpenAI = _StubOpenAI
- stub.AsyncOpenAI = _StubOpenAI
- monkeypatch.setitem(sys.modules, "openai", stub)
- monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-test")
-
- datapoints = ["hello", "bye"]
- results = []
- models = ["openai/gpt-5-mini", "anthropic/claude-sonnet-4"]
- for order, model in enumerate(models):
- for key, value in openrouter_env(model).items():
- monkeypatch.setenv(key, value)
- spec = importlib.util.spec_from_file_location(f"agent_{order}", tmp_path / "agent.py")
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- for index, question in enumerate(datapoints):
- output = module.run(question)
- results.append({"order": order, "datapoint_index": index, "success": True, "output": output})
-
- assert len(ctors) == len(models) * len(datapoints)
- assert all(c["base_url"] == OPENROUTER_BASE_URL for c in ctors)
- assert all(c["api_key"] == "sk-or-test" for c in ctors)
- assert [c["model"] for c in calls] == [m for m in models for _ in datapoints]
- assert [r["output"] for r in results] == [f"echo:{m}" for m in models for _ in datapoints]
-
-
-def test_rewrite_repo_keeps_future_import_first(tmp_path):
- (tmp_path / "mod.py").write_text(
- "#!/usr/bin/env python3\n"
- '"""client."""\n'
- "from __future__ import annotations\n"
- "from openai import OpenAI\n"
- "OpenAI(api_key='sk')\n"
- )
- rewrite_repo(tmp_path)
- src = (tmp_path / "mod.py").read_text()
- tree = ast.parse(src)
- assert src.splitlines()[0].startswith("#!")
- assert "import os" in src
- future = next(n for n in tree.body if isinstance(n, ast.ImportFrom) and n.module == "__future__")
- os_import = next(n for n in tree.body if isinstance(n, ast.Import) and any(a.name == "os" for a in n.names))
- assert future.lineno < os_import.lineno
diff --git a/overmind/tests/test_layer_cmd.py b/overmind/tests/test_finetune_cmd.py
similarity index 58%
rename from overmind/tests/test_layer_cmd.py
rename to overmind/tests/test_finetune_cmd.py
index a128fc59..e2164280 100644
--- a/overmind/tests/test_layer_cmd.py
+++ b/overmind/tests/test_finetune_cmd.py
@@ -8,12 +8,11 @@ from typer.testing import CliRunner
from overmind.__main__ import app
from overmind.config import Capability, Config
-from overmind.layer_cmd import (
+from overmind.finetune_cmd import (
Client,
- LayerError,
+ FinetuneError,
parse_models,
resolve_capability,
- run_backtest,
run_finetune,
)
@@ -70,13 +69,13 @@ def _dataset(dataset_id, *, rows=4):
def test_parse_models_rejects_duplicates_and_the_cap():
- assert parse_models(["openai/a, anthropic/b"], cap=5) == ["openai/a", "anthropic/b"]
- with pytest.raises(LayerError):
- parse_models(["openai/a", "openai/a"], cap=5)
- with pytest.raises(LayerError):
- parse_models(["a,b,c,d,e,f"], cap=5)
- with pytest.raises(LayerError):
- parse_models(None, cap=4)
+ assert parse_models(["Qwen/a, meta/b"]) == ["Qwen/a", "meta/b"]
+ with pytest.raises(FinetuneError, match="Duplicate"):
+ parse_models(["Qwen/a", "Qwen/a"])
+ with pytest.raises(FinetuneError, match="between 1 and 4"):
+ parse_models(["a,b,c,d,e"])
+ with pytest.raises(FinetuneError, match="--models"):
+ parse_models(None)
def test_capability_defaults_to_the_only_toml_entry():
@@ -85,116 +84,12 @@ def test_capability_defaults_to_the_only_toml_entry():
assert resolve_capability(config, "")[0] == only.id
other = Capability(slug="other", name="Other", id="22222222-2222-2222-2222-222222222222")
crowded = Config(capabilities={"support": only, "other": other})
- with pytest.raises(LayerError, match="Pass --capability"):
+ with pytest.raises(FinetuneError, match="Pass --capability"):
resolve_capability(crowded, "")
raw = "33333333-3333-3333-3333-333333333333"
assert resolve_capability(Config(), raw)[0] == raw
-def _group(*labels: str) -> dict:
- return {
- "group": "group-1",
- "runs": [
- {"id": f"run-{index}", "label": label, "is_baseline": index == 0} for index, label in enumerate(labels)
- ],
- }
-
-
-def _finished(index: int, label: str, *, errors: int = 0) -> dict:
- return {
- "id": f"run-{index}",
- "label": label,
- "is_baseline": index == 0,
- "status": "completed",
- "summary": {"score": 0.5, "metrics": {"faithful": {"errors": errors}}},
- }
-
-
-def _overall(status: str, candidate: float, delta: float) -> dict:
- return {"overall": {"baseline": candidate - delta, "candidate": candidate, "delta": delta, "status": status}}
-
-
-def test_backtest_scores_each_model_and_exits_on_regression():
- session_client = _client(
- Response({
- "upstream_available": True,
- "models": [{"id": "openai/gpt-5-mini"}, {"id": "anthropic/claude-sonnet-4.5"}],
- }),
- Response({"active_eval_set": "set-1"}),
- Response({"id": "ds-1"}),
- Response(_dataset("ds-1")),
- Response(_group("recorded", "openai/gpt-5-mini", "anthropic/claude-sonnet-4.5")),
- Response(_finished(0, "recorded")),
- Response(_finished(1, "openai/gpt-5-mini")),
- Response(_finished(2, "anthropic/claude-sonnet-4.5")),
- Response(_overall("regressed", 0.4, -0.2)),
- Response(_overall("improved", 0.9, 0.1)),
- )
- code = run_backtest(
- session_client,
- project_id="project",
- capability_id="cap",
- capability_slug="support",
- models=["openai/gpt-5-mini", "anthropic/claude-sonnet-4.5"],
- since=datetime(2026, 1, 1, tzinfo=timezone.utc),
- until=None,
- limit=200,
- from_model="",
- timeout_s=30,
- )
- assert code == 1
- created = next(body for _method, url, body in session_client.session.calls if url.endswith("/api/eval-runs/"))
- labels = [target["label"] for target in created["targets"]]
- assert labels == ["recorded", "openai/gpt-5-mini", "anthropic/claude-sonnet-4.5"]
- assert created["targets"][1]["params"] == {"generation_strategy": "single_completion"}
- assert created["targets"][0]["mode"] == "recorded"
- assert created["targets"][0]["is_baseline"] is True
-
-
-def test_backtest_fails_when_a_metric_does_not_score():
- session_client = _client(
- Response({"upstream_available": True, "models": [{"id": "openai/gpt-5-mini"}]}),
- Response({"active_eval_set": "set-1"}),
- Response({"id": "ds-1"}),
- Response(_dataset("ds-1")),
- Response(_group("recorded", "openai/gpt-5-mini")),
- Response(_finished(0, "recorded")),
- Response(_finished(1, "openai/gpt-5-mini", errors=1)),
- Response(_overall("unchanged", 1.0, 0.0)),
- )
- code = run_backtest(
- session_client,
- project_id="project",
- capability_id="cap",
- capability_slug="support",
- models=["openai/gpt-5-mini"],
- since=datetime(2026, 1, 1, tzinfo=timezone.utc),
- until=None,
- limit=10,
- from_model="",
- timeout_s=30,
- )
- assert code == 1
-
-
-def test_unknown_model_does_not_create_a_dataset():
- session_client = _client(Response({"upstream_available": False, "models": []}))
- with pytest.raises(LayerError, match="catalog is unavailable"):
- run_backtest(
- session_client,
- project_id="project",
- capability_id="cap",
- capability_slug="support",
- models=["openai/gpt-5-mini"],
- since=datetime(2026, 1, 1, tzinfo=timezone.utc),
- until=None,
- limit=10,
- from_model="",
- timeout_s=30,
- )
- assert session_client.session.calls == [("GET", "https://api.example/api/models/catalog/", None)]
-
-
def test_finetune_starts_one_job_per_model_in_one_group():
session_client = _client(
Response({
@@ -250,7 +145,7 @@ def test_a_later_finetune_failure_reports_the_jobs_already_queued():
Response({"id": "job-1"}),
Response({"detail": "rejected"}, status_code=400),
)
- with pytest.raises(LayerError, match="Queued: 1"):
+ with pytest.raises(FinetuneError, match="Queued: 1"):
run_finetune(
session_client,
project_id="project",
@@ -266,34 +161,52 @@ def test_a_later_finetune_failure_reports_the_jobs_already_queued():
)
-def test_backtest_times_out_while_the_run_is_still_going():
+def test_unknown_model_does_not_create_a_dataset():
+ session_client = _client(Response({"models": {"small": [{"id": "Qwen/Qwen2.5-7B-Instruct"}]}}))
+ with pytest.raises(FinetuneError, match="Unknown model: openai/gpt-5-mini"):
+ run_finetune(
+ session_client,
+ project_id="project",
+ capability_id="cap",
+ capability_slug="support",
+ models=["openai/gpt-5-mini"],
+ since=datetime(2026, 1, 1, tzinfo=timezone.utc),
+ until=None,
+ limit=10,
+ from_model="",
+ eval_percent=20,
+ timeout_s=30,
+ )
+ assert session_client.session.calls == [("GET", "https://api.example/api/finetuning-jobs/models/", None)]
+
+
+def test_finetune_times_out_while_the_dataset_is_still_landing():
session_client = _client(
- Response({"upstream_available": True, "models": [{"id": "openai/gpt-5-mini"}]}),
+ Response({"models": {"small": [{"id": "Qwen/Qwen2.5-7B-Instruct"}]}}),
Response({"active_eval_set": "set-1"}),
- Response({"id": "ds-1"}),
- Response(_dataset("ds-1")),
- Response(_group("recorded", "openai/gpt-5-mini")),
- Response({"id": "run-0", "status": "running"}),
+ Response({"train": {"id": "train-1"}, "eval": {"id": "eval-1"}}),
+ Response({"id": "train-1", "state": "landing"}),
clock=lambda: 100.0,
)
- with pytest.raises(LayerError, match="Timed out") as exc:
- run_backtest(
+ with pytest.raises(FinetuneError, match="Timed out") as exc:
+ run_finetune(
session_client,
project_id="project",
capability_id="cap",
capability_slug="support",
- models=["openai/gpt-5-mini"],
+ models=["Qwen/Qwen2.5-7B-Instruct"],
since=datetime(2026, 1, 1, tzinfo=timezone.utc),
until=None,
limit=10,
from_model="",
+ eval_percent=20,
timeout_s=0,
)
assert exc.value.code == 2
def test_cli_requires_models():
- result = CliRunner().invoke(app, ["backtest"])
+ result = CliRunner().invoke(app, ["finetune"])
assert result.exit_code == 1
assert "models" in result.output.lower()
@@ -305,7 +218,7 @@ def test_cli_reports_a_saved_key_meeting_another_endpoint(tmp_path, monkeypatch)
dump(Config(api_key="saved-key", base_url="https://api.example", project_id="p"), tmp_path / "overmind.toml")
monkeypatch.setenv("OVERMIND_API_URL", "https://other.example")
monkeypatch.delenv("OVERMIND_API_KEY", raising=False)
- result = CliRunner().invoke(app, ["backtest", "--models", "openai/gpt-5-mini", "--capability", "cap"])
+ result = CliRunner().invoke(app, ["finetune", "--models", "Qwen/Qwen2.5-7B-Instruct", "--capability", "cap"])
assert result.exit_code == 1
assert "different API" in result.output
assert result.exception is None or isinstance(result.exception, SystemExit)
diff --git a/overmind/tests/test_init.py b/overmind/tests/test_init.py
index a7d8ad2c..ce16e159 100644
--- a/overmind/tests/test_init.py
+++ b/overmind/tests/test_init.py
@@ -19,7 +19,6 @@ SURFACE_SKILLS = (
"overmind-observability",
"overmind-datasets",
"overmind-evaluations",
- "overmind-optimiser",
"model-training-engineering",
"overmind-training",
"overmind-inference",
@@ -108,6 +107,22 @@ def test_cursor_init_replaces_previous_skill_installs(tmp_path, monkeypatch):
assert (tmp_path / ".agents" / "skills" / "overmind" / "SKILL.md").is_file()
[email protected](("ide", "skill_dir"), [("claude", ".claude"), ("cursor", ".agents")])
+def test_init_deletes_retired_skills_and_keeps_others(tmp_path, monkeypatch, ide, skill_dir):
+ monkeypatch.chdir(tmp_path)
+ retired = tmp_path / skill_dir / "skills" / "overmind-optimiser"
+ retired.mkdir(parents=True)
+ (retired / "SKILL.md").write_text("Retired\n")
+ own = tmp_path / skill_dir / "skills" / "team-release"
+ own.mkdir(parents=True)
+ (own / "SKILL.md").write_text("Ours\n")
+
+ _init(tmp_path, ide)
+
+ assert not retired.exists()
+ assert (own / "SKILL.md").read_text() == "Ours\n"
+
+
def test_codex_local_init_without_url_override(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
for name in ("OVERMIND_API_URL", "OVERMIND_BASE_URL", "OVERMIND_PROJECT_ID"):
diff --git a/overmind/tests/test_openrouter_rewrite.py b/overmind/tests/test_openrouter_rewrite.py
deleted file mode 100644
index 5c98e734..00000000
--- a/overmind/tests/test_openrouter_rewrite.py
+++ /dev/null
@@ -1,36 +0,0 @@
-from __future__ import annotations
-
-import re
-import sys
-from types import SimpleNamespace
-
-import pytest
-
-from overmind.openrouter_rewrite import rewrite_repo
-
-pytestmark = pytest.mark.covers("cli-contract")
-
-
- "source",
- [
- "import openai\nclient = openai.OpenAI()\n",
- "import openai as provider\nclient = provider.AsyncOpenAI()\n",
- "from anthropic import Anthropic, AsyncAnthropic\na = Anthropic()\nb = AsyncAnthropic()\n",
- "from openai import AsyncOpenAI\nfrom anthropic import Anthropic\na = Anthropic()\nb = AsyncOpenAI()\n",
- "try:\n from openai import OpenAI\nexcept ImportError:\n OpenAI = None\nfrom anthropic import Anthropic\na = Anthropic()\n",
- ],
-)
-def test_rewritten_constructors_resolve_all_client_names(tmp_path, monkeypatch, source):
- monkeypatch.setenv("OPENROUTER_API_KEY", "test-key")
- monkeypatch.setitem(sys.modules, "anthropic", SimpleNamespace(Anthropic=None, AsyncAnthropic=None))
- path = tmp_path / "agent.py"
- path.write_text(source)
- report = rewrite_repo(tmp_path)
- assert report.leftover == []
- imported = [n.strip() for g in re.findall(r"from openai import ([\w, ]+)", path.read_text()) for n in g.split(",")]
- assert len(imported) == len(set(imported))
- namespace = {}
- exec(compile(path.read_text(), str(path), "exec"), namespace)
- clients = [namespace[name] for name in ("client", "a", "b") if name in namespace]
- assert all(str(client.base_url) == "https://openrouter.ai/api/v1/" for client in clients)
diff --git a/overmind/tests/test_optimizer.py b/overmind/tests/test_optimizer.py
deleted file mode 100644
index bf7ac802..00000000
--- a/overmind/tests/test_optimizer.py
+++ /dev/null
@@ -1,116 +0,0 @@
-"""No-network checks for the client-driven optimiser loop."""
-
-from __future__ import annotations
-
-import json
-from unittest.mock import MagicMock
-
-import pytest
-
-from overmind.optimizer import OptimiseLoop
-from overmind.optimizer_api import (
- _run_datapoint,
-)
-
-pytestmark = pytest.mark.covers("state-machines")
-
-
-def test_run_datapoint_failure_reports_error(tmp_path):
- result = _run_datapoint(
- template="echo boom >&2; exit 3",
- experiment_id="e",
- capability_id="c",
- project_id="p",
- candidate_id="cand",
- iteration_id="it",
- datapoint_index=0,
- datapoint_input="x",
- cwd=str(tmp_path),
- timeout=10,
- )
- assert result["success"] is False
- assert "boom" in (result.get("error") or "")
-
-
-def test_export_dataset_reuses_a_cache_whose_hash_matches_the_pin(tmp_path):
- from overmind.optimizer_api import OptimizerAPI
-
- cache = tmp_path / "datasets"
- cache.mkdir()
- (cache / "ver-9.jsonl").write_text('{"input": 1}\n')
- (cache / "ver-9.hash").write_text("abc")
- api = OptimizerAPI("http://unused", "k")
- api._session = MagicMock()
- assert api.export_dataset("ds-1", "ver-9", cache, fingerprint="abc") == cache / "ver-9.jsonl"
- assert api.export_dataset("ds-1", "ver-9", cache) == cache / "ver-9.jsonl"
- api._session.get.assert_not_called()
-
-
-def test_export_dataset_refetches_when_the_hash_is_stale_or_missing(tmp_path):
- from overmind.optimizer_api import OptimizerAPI
-
- cache = tmp_path / "datasets"
- cache.mkdir()
- (cache / "ver-9.jsonl").write_text("old\n")
- (cache / "ver-9.hash").write_text("old-hash")
- api = OptimizerAPI("http://api", "k")
- api._session = MagicMock()
- api._session.get.return_value.iter_content.return_value = [b"new\n"]
- api._session.get.return_value.headers = {"X-Overmind-Fingerprint": "new-hash"}
- api.export_dataset("ds-1", "ver-9", cache, fingerprint="new-hash")
- assert (cache / "ver-9.jsonl").read_text() == "new\n"
- assert (cache / "ver-9.hash").read_text() == "new-hash"
- (cache / "ver-9.hash").unlink()
- api.export_dataset("ds-1", "ver-9", cache)
- assert api._session.get.call_count == 2
-
-
-def test_export_dataset_needs_a_used_version(tmp_path):
- from overmind.optimizer_api import OptimizerAPI
-
- api = OptimizerAPI("http://api", "k")
- with pytest.raises(RuntimeError, match="used version"):
- api.export_dataset("ds-1", "", tmp_path)
-
-
-def test_next_action_asks_for_template(tmp_path):
- api = MagicMock()
- api.get_experiment.return_value = {
- "id": "e1",
- "status": "scheduled",
- "command_template": "",
- "iterations": [],
- "capability_name": "picker",
- "entrypoint": "run",
- }
- dataset = tmp_path / "ds.jsonl"
- dataset.write_text("{}\n")
- loop = OptimiseLoop(
- api,
- "e1",
- repo_cwd=str(tmp_path),
- dataset_path=dataset,
- state_path=tmp_path / "state.json",
- )
- action = loop.next_action()
- assert action["action"] == "WRITE_COMMAND_TEMPLATE"
- assert "set-template" in action["prompt"]
-
-
-def _loop_with_experiment(tmp_path, exp: dict) -> OptimiseLoop:
- api = MagicMock()
- api.get_experiment.return_value = exp
- dataset = tmp_path / "ds.jsonl"
- dataset.write_text("{}\n")
- state_path = tmp_path / "state.json"
- state_path.write_text(json.dumps({"smoke_done": True, "pending_diffs": []}))
- return OptimiseLoop(
- api,
- "e1",
- repo_cwd=str(tmp_path),
- dataset_path=dataset,
- state_path=state_path,
- )
diff --git a/overmind/tests/test_sdk.py b/overmind/tests/test_sdk.py
index 2a69b256..fc5298ce 100644
--- a/overmind/tests/test_sdk.py
+++ b/overmind/tests/test_sdk.py
@@ -68,7 +68,6 @@ def test_sdk_init_only_once():
@pytest.fixture
def no_api_key(monkeypatch):
monkeypatch.delenv("OVERMIND_API_KEY", raising=False)
- monkeypatch.delenv("OVERMIND_TRACE_FILE", raising=False)
def test_init_without_key_returns_false(no_api_key):
diff --git a/overmind/uv.lock b/overmind/uv.lock
index 8966b69c..a225595d 100644
--- a/overmind/uv.lock
+++ b/overmind/uv.lock
@@ -300,7 +300,7 @@ name = "exceptiongroup"
version = "1.3.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "typing-extensions", marker = "python_full_version < '3.11'" },
+ { name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" }
wheels = [
@@ -351,8 +351,8 @@ name = "httpcore2"
version = "2.13.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "h11", marker = "python_full_version < '3.12' or sys_platform != 'emscripten'" },
- { name = "truststore", marker = "python_full_version < '3.12' or sys_platform != 'emscripten'" },
+ { name = "h11" },
+ { name = "truststore" },
]
sdist = { url = "https://files.pythonhosted.org/packages/cb/f3/1db7aa2bc2524062192bb0e0323969492d1883152a232fe36eea65f4e35c/httpcore2-2.13.1.tar.gz", hash = "sha256:e0aa977abe17e69a3b820a24542a6fa88702676d83880b8d194dcd18408e5103", size = 68071, upload-time = "2026-09-23T07:47:22.372Z" }
wheels = [
@@ -923,7 +923,7 @@ wheels = [
[[package]]
name = "overmind"
-version = "0.1.128"
+version = "0.1.129"
source = { editable = "." }
dependencies = [
{ name = "packaging" },
diff --git a/sales-dashboard/src/lib/api.ts b/sales-dashboard/src/lib/api.ts
index afc17756..4af6b39e 100644
--- a/sales-dashboard/src/lib/api.ts
+++ b/sales-dashboard/src/lib/api.ts
@@ -146,7 +146,6 @@ export type UserActivity = Cached & {
by_intent: Record<string, number>;
daily: Daily[];
};
- optimizer: Workflow;
evaluations: Workflow;
};
diff --git a/sales-dashboard/src/routes/_app/accounts_.$accountId.tsx b/sales-dashboard/src/routes/_app/accounts_.$accountId.tsx
index 1db3d699..84645cc6 100644
--- a/sales-dashboard/src/routes/_app/accounts_.$accountId.tsx
+++ b/sales-dashboard/src/routes/_app/accounts_.$accountId.tsx
@@ -74,7 +74,7 @@ function AccountPage() {
}
function AccountBody({ data, days }: { data: UserActivity; days: number }) {
- const { training, traces, inference, datasets, optimizer, evaluations, billing } = data;
+ const { training, traces, inference, datasets, evaluations, billing } = data;
const trainingByDay = new Map(training.daily.map((point) => [point.day.slice(0, 10), point]));
const trainingDaily = fillDays([], days, data.computed_at).map(({ day }) => {
const values = trainingByDay.get(day)?.values ?? {};
@@ -112,7 +112,6 @@ function AccountBody({ data, days }: { data: UserActivity; days: number }) {
value={formatInt(inference.models)}
/>
<Stat label="Datasets" value={formatInt(datasets.total)} />
- <Stat label="Optimiser runs" value={formatInt(optimizer.total)} />
<Stat label="Evaluations" value={formatInt(evaluations.total)} />
<Stat label="Projects" value={formatInt(data.user.projects)} />
</div>
@@ -159,14 +158,9 @@ function AccountBody({ data, days }: { data: UserActivity; days: number }) {
values={inference.by_model}
/>
</div>
- <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
+ <div className="grid gap-4 md:grid-cols-3">
<Breakdown format={formatInt} title="Datasets by source" values={datasets.by_source} />
<Breakdown format={formatInt} title="Datasets by intent" values={datasets.by_intent} />
- <Breakdown
- format={formatInt}
- title="Optimiser runs by status"
- values={optimizer.by_status}
- />
<Breakdown
format={formatInt}
title="Evaluations by status"
diff --git a/tests/coverage_map.py b/tests/coverage_map.py
index 0b736406..07dcbc19 100644
--- a/tests/coverage_map.py
+++ b/tests/coverage_map.py
@@ -113,9 +113,8 @@ COVERAGE_MAP: dict[str, Entry] = {
"evaluate": Entry(
S2,
PROMISE,
- "An eval set runs every candidate and backtests it against the recorded baseline.",
+ "An eval set runs every candidate and compares it with the recorded baseline.",
),
- "optimise": Entry(S2, PROMISE, "Failing traces become a measured winning diff."),
"train": Entry(
S2,
PROMISE,
@@ -297,7 +296,7 @@ COVERAGE_MAP: dict[str, Entry] = {
"state-machines": Entry(
S3,
LOGIC,
- "Job lifecycle, the optimiser, the native evaluation plan and model activation.",
+ "Job lifecycle, the native evaluation plan and model activation.",
),
"recommendations": Entry(
S4,
diff --git a/tests/journeys/test_evaluate.py b/tests/journeys/test_evaluate.py
index e54bc90c..eb9077be 100644
--- a/tests/journeys/test_evaluate.py
+++ b/tests/journeys/test_evaluate.py
@@ -20,7 +20,7 @@ def test_evaluate(workshop, cli, sample_agent, worker, tmp_path, fake_llm, conso
group = workshop.call(
"run_evaluation",
{
- "name": "backtest",
+ "name": "compare",
"dataset": dataset,
"judge_model": JUDGE,
"targets": [
@@ -53,8 +53,7 @@ def test_evaluate(workshop, cli, sample_agent, worker, tmp_path, fake_llm, conso
project = workshop.project()["id"]
console.goto(f"/evaluations?projectId={project}")
for label in ("recorded", "candidate", "weak"):
- console.sees(f"backtest · {label}")
- console.click("backtest · weak")
+ console.sees(f"compare · {label}")
+ console.click("compare · weak")
console.sees("Re-run")
- console.sees("Optimise")
console.save_evidence("evaluate-weak-run")
diff --git a/tests/journeys/test_http_api.py b/tests/journeys/test_http_api.py
index 32ed29e0..73dd066c 100644
--- a/tests/journeys/test_http_api.py
+++ b/tests/journeys/test_http_api.py
@@ -10,7 +10,6 @@ def test_project_surfaces_render_without_browser_or_server_errors(console, works
("training", "Train model"),
("evaluations", "Evaluations"),
("inference", "Inference"),
- ("optimiser", "Optimiser"),
]:
console.goto(f"/{route}?projectId={project}")
console.sees(text)
diff --git a/tests/journeys/test_optimise.py b/tests/journeys/test_optimise.py
deleted file mode 100644
index 83093f78..00000000
--- a/tests/journeys/test_optimise.py
+++ /dev/null
@@ -1,152 +0,0 @@
-import json
-import subprocess
-import sys
-
-import pytest
-
-from .conftest import GOOD_REPLY
-from .stack import drain
-from .surfaces import SDK
-
-pytestmark = pytest.mark.covers("optimise")
-
-TICKETS = ("Refund order 42 please", "Where is order 42?")
-
-RUN_ONE_DATAPOINT = """\
-OPENAI_BASE_URL={llm} OPENAI_API_KEY=sk-fake OVERMIND_API_URL={api} OVERMIND_API_KEY={key} \
-OVERMIND_ANALYTICS_ENABLED=false PYTHONPATH={sdk}:. {python} - <<'PY'
-import json
-import overmind
-from openai import OpenAI
-from support_desk.agent import answer
-
-datapoint = __DATAPOINT_INPUT__
-payload = json.loads(datapoint) if isinstance(datapoint, str) else datapoint
-user = next(m["content"] for m in payload["messages"] if m["role"] == "user")
-category, _, ticket = user.partition("] ")
-overmind.init(service_name="support-desk", providers=["openai"])
-print(answer(OpenAI(), ticket, category.lstrip("[")))
-overmind.force_flush_traces(timeout_millis=10_000)
-PY
-"""
-
-
-def _candidate_diff(repo) -> str:
- agent = repo / "support_desk" / "agent.py"
- original = agent.read_text()
- agent.write_text(
- original.replace(
- '"Use lookup_order when the ticket names an order."',
- '"Use lookup_order when the ticket names an order. Quote the order id and its status."',
- )
- )
- diff = subprocess.run(
- ["git", "diff"], cwd=repo, capture_output=True, text=True, check=True
- ).stdout
- agent.write_text(original)
- return diff
-
-
-def test_optimise(
- cli,
- mcp_for,
- sample_agent,
- worker,
- live_api,
- support_desk_llm,
- judges,
- fake_llm,
- tmp_path,
-):
- cli.scan(sample_agent)
- cli.sync(sample_agent)
- key = cli.project_key(sample_agent)
- mcp = mcp_for(key)
- answer = mcp.capability("answer")
-
- sample_agent.run(*TICKETS, api_url=live_api.url, llm_url=support_desk_llm)
- drain(worker)
- failures = mcp.call("query_failures", {"capability": "answer"})["failures"]
- assert len(failures) == len(TICKETS)
-
- created = mcp.call(
- "create_dataset_from_traces",
- {
- "name": "answer misses",
- "trace_ids": [f["trace_id"] for f in failures],
- "intent": "eval",
- "capability": answer["id"],
- },
- )
- dataset = created["dataset"]["id"]
- drain(worker)
- source = mcp.call("inspect_dataset", {"dataset": dataset})["active"]
- rows = mcp.call("query_dataset", {"dataset": dataset, "sql": "select * from t"})["rows"]
- mcp.call(
- "import_dataset_version",
- {
- "dataset": dataset,
- "source_cell": source["id"],
- "source_fingerprint": source["fingerprint"],
- "request_key": "correct-fixture-references",
- "name": "Correct the references",
- "imported_rows": [
- {
- **row,
- "input": {
- "messages": [
- message
- for message in row["messages"]
- if message["role"] in {"system", "user"}
- ]
- },
- "expected_output": GOOD_REPLY,
- }
- for row in rows
- ],
- "provenance": "The native agent projects system and user messages for answer replay and applies the support-desk fixture's declared correct reply. Full source transcripts and row identities remain retained.",
- },
- )
- drain(worker)
- references = mcp.call(
- "query_dataset", {"dataset": dataset, "sql": "select distinct expected_output from t"}
- )["rows"]
- assert references == [{"expected_output": GOOD_REPLY}]
-
- repo = sample_agent.repo
- cli.run("optimise", "start", "-c", "answer", "-d", dataset, "--iterations", "5", cwd=repo)
- template = tmp_path / "run_one_datapoint.sh"
- template.write_text(
- RUN_ONE_DATAPOINT.format(
- llm=support_desk_llm, api=live_api.url, key=key, sdk=SDK, python=sys.executable
- )
- )
- cli.run("optimise", "set-template", str(template), cwd=repo)
- cli.run("optimise", "run-smoke", cwd=repo)
- cli.run("optimise", "run-baseline", cwd=repo)
- patch = tmp_path / "candidate.diff"
- patch.write_text(_candidate_diff(repo))
- cli.run("optimise", "add-candidate", "--diff", str(patch), cwd=repo)
- cli.run("optimise", "run-iteration", cwd=repo)
- assert "Action: WRITE_CANDIDATES" in cli.run("optimise", "next", cwd=repo)
- for _ in range(3):
- cli.run("optimise", "add-candidate", "--diff", str(patch), cwd=repo)
- cli.run("optimise", "run-iteration", cwd=repo)
- assert "Action: COMPLETE" in cli.run("optimise", "next", cwd=repo)
- cli.run("optimise", "complete", cwd=repo)
-
- state = json.loads((repo / ".overmind" / "optimise_state.json").read_text())
- result = mcp.call("inspect_optimizer_result", {"experiment": state["experiment_id"]})
- scores = result["experiment"]["scores"]
- assert result["experiment"]["status"] == "completed"
- assert result["experiment"]["cell"]["version"] == "2.0"
- assert scores["best"] > scores["baseline"]
-
- [baseline] = result["iterations"][0]["candidates"]
- [candidate] = result["iterations"][1]["candidates"]
- runs = [mcp.read(c["eval_run"]["uri"]) for c in (baseline, candidate)]
- assert runs[0]["dataset"] == runs[1]["dataset"] == dataset
- assert candidate["score"] > baseline["score"]
-
- subprocess.run(["git", "apply", "--check", str(patch)], cwd=repo, check=True)
- assert candidate["patch"].strip() == patch.read_text().strip()
diff --git a/tests/mcp_fixtures.py b/tests/mcp_fixtures.py
index 647ab628..7248e0b1 100644
--- a/tests/mcp_fixtures.py
+++ b/tests/mcp_fixtures.py
@@ -98,9 +98,6 @@ EXPECTED_TOOL_NAMES = {
"set_benchmark_model",
"run_inference",
"get_model_swap_prompt",
- "check_optimizer_readiness",
- "start_optimizer",
- "inspect_optimizer_result",
"inspect_connectors",
"configure_connector",
"sync_connector",
diff --git a/tests/test_completions_api.py b/tests/test_completions_api.py
index d74253e3..67c3064a 100644
--- a/tests/test_completions_api.py
+++ b/tests/test_completions_api.py
@@ -422,7 +422,7 @@ class TestChatCompletionsEndpoint:
assert chat.status_code == status.HTTP_404_NOT_FOUND
assert all(row["finetuned"] for row in listed.json()["data"])
- def test_unlisted_slug_without_optimiser_header_returns_404(self):
+ def test_unlisted_slug_returns_404(self):
u, p = _user(), _project()
_membership(u, p)
r = _jwt_client(u).post(
@@ -432,87 +432,6 @@ class TestChatCompletionsEndpoint:
)
assert r.status_code == status.HTTP_404_NOT_FOUND
- @override_settings(OPENROUTER_API_KEY="or-test", OPENROUTER_PROXY_ENABLED=True)
- def test_optimiser_header_bypasses_the_allowlist_for_api_keys_only(self):
- u, p = _user(), _project()
- _membership(u, p)
- fake_resp = {
- "id": "chatcmpl-opt",
- "object": "chat.completion",
- "model": "mistralai/mistral-large",
- "choices": [
- {
- "index": 0,
- "message": {"role": "assistant", "content": "Hi!"},
- "finish_reason": "stop",
- }
- ],
- "usage": {"prompt_tokens": 5, "completion_tokens": 3, "total_tokens": 8},
- }
- mock_post = MagicMock()
- mock_post.return_value.ok = True
- mock_post.return_value.json.return_value = fake_resp
- with patch("overbae.api.completions._requests.post", mock_post):
- r = _api_key_client(u, p).post(
- self.URL,
- {"model": "mistralai/mistral-large", "messages": self.MESSAGES},
- format="json",
- HTTP_X_OVERMIND_OPTIMISER="1",
- )
- assert r.status_code == status.HTTP_200_OK
- assert r.json()["id"] == "chatcmpl-opt"
- assert mock_post.call_args.kwargs["json"]["model"] == "mistralai/mistral-large"
-
- # The same header on a JWT session buys nothing — the allowlist still gates.
- with patch("overbae.api.completions._requests.post", mock_post):
- jwt = _jwt_client(u).post(
- self.URL,
- {"model": "mistralai/mistral-large", "messages": self.MESSAGES},
- format="json",
- HTTP_X_OVERMIND_OPTIMISER="1",
- )
- assert jwt.status_code == status.HTTP_404_NOT_FOUND
-
- @override_settings(OPENROUTER_API_KEY="or-test", OPENROUTER_PROXY_ENABLED=True)
- def test_optimiser_bare_model_name_resolves_to_full_slug(self):
- u, p = _user(), _project()
- _membership(u, p)
- fake_resp = {
- "id": "chatcmpl-opt",
- "object": "chat.completion",
- "model": "openai/gpt-5-mini",
- "choices": [
- {
- "index": 0,
- "message": {"role": "assistant", "content": "Hi!"},
- "finish_reason": "stop",
- }
- ],
- "usage": {"prompt_tokens": 5, "completion_tokens": 3, "total_tokens": 8},
- }
- mock_post = MagicMock()
- mock_post.return_value.ok = True
- mock_post.return_value.json.return_value = fake_resp
- with patch("overbae.api.completions._requests.post", mock_post):
- r = _api_key_client(u, p).post(
- self.URL,
- {"model": "gpt-5-mini", "messages": self.MESSAGES},
- format="json",
- HTTP_X_OVERMIND_OPTIMISER="1",
- )
- assert r.status_code == status.HTTP_200_OK
- assert mock_post.call_args.kwargs["json"]["model"] == "openai/gpt-5-mini"
-
- def test_bare_model_name_without_optimiser_header_still_404s(self):
- u, p = _user(), _project()
- _membership(u, p)
- r = _jwt_client(u).post(
- self.URL,
- {"model": "gpt-5-mini", "messages": self.MESSAGES},
- format="json",
- )
- assert r.status_code == status.HTTP_404_NOT_FOUND
-
@override_settings(OPENROUTER_API_KEY="or-test", OPENROUTER_PROXY_ENABLED=True)
def test_response_format_is_forwarded_upstream(self):
u, p = _user(), _project()
diff --git a/tests/test_dataset_api.py b/tests/test_dataset_api.py
index 6768b767..b188e9f2 100644
--- a/tests/test_dataset_api.py
+++ b/tests/test_dataset_api.py
@@ -14,7 +14,7 @@ from rest_framework_simplejwt.tokens import RefreshToken
from overbae.models import (
Capability,
Dataset,
- OptimizerExperiment,
+ EvalRun,
Project,
ProjectMembership,
Span,
@@ -200,7 +200,7 @@ def test_patch_sets_capability_intent_and_active_cell():
}
-def test_preparation_names_an_optimizer_experiment_by_its_capability():
+def test_preparation_lists_the_eval_runs_that_used_a_version():
project = _project()
client = _client(project)
capability = Capability.objects.create(project=project, name="Support", slug="support")
@@ -212,20 +212,16 @@ def test_preparation_names_an_optimizer_experiment_by_its_capability():
capability=str(capability.id),
)
cell = use.use(dataset, "eval")
- experiment = OptimizerExperiment.objects.create(
- project=project, capability=capability, dataset=dataset, cell=cell, entrypoint="answer"
- )
+ run = EvalRun.objects.create(project=project, name="Nightly", dataset=dataset, cell=cell)
res = client.get(f"/api/datasets/{dataset.id}/preparation/")
assert res.status_code == 200, res.content
usage = next(
node["cell"]["usage"] for node in res.data["nodes"] if node["cell"]["id"] == str(cell.id)
)
- assert usage["optimizer_experiments"][0]["id"] == str(experiment.id)
- assert usage["optimizer_experiments"][0]["name"] == "Support"
- assert usage["optimizer_experiments"][0]["status"] == experiment.status
+ assert [(row["id"], row["name"]) for row in usage["eval_runs"]] == [(str(run.id), "Nightly")]
detail = client.get(f"/api/datasets/{dataset.id}/")
assert detail.status_code == 200
- assert detail.data["cells"][0]["usage"]["optimizer_experiments"][0]["name"] == "Support"
+ assert detail.data["cells"][0]["usage"]["eval_runs"][0]["name"] == "Nightly"
def test_delete_refused_while_a_version_is_used():
diff --git a/tests/test_dataset_gate.py b/tests/test_dataset_gate.py
index db4440fc..e3cdb06e 100644
--- a/tests/test_dataset_gate.py
+++ b/tests/test_dataset_gate.py
@@ -23,7 +23,6 @@ from overbae.models import (
ProjectMembership,
User,
)
-from overbae.models.optimizer import optimizer_dataset_error
from overbae.services.datasets import lifecycle, use
from overbae.tasks import datasets as dataset_tasks
from tests.workshop_script_fixtures import retained_package, select_script
@@ -68,9 +67,8 @@ def _used(*datasets: Dataset) -> list[bool]:
def test_a_check_changes_nothing_and_a_use_freezes_once():
- _project, capability, _user, train, evaluation = _setup()
+ _project, _capability, _user, train, evaluation = _setup()
assert use.check(train, "train") == train.active_cell
- assert optimizer_dataset_error(capability, evaluation) is None
assert _used(train, evaluation) == [False, False]
cell = use.use(train, "train")
first = cell.used_at
diff --git a/tests/test_mcp_evaluations.py b/tests/test_mcp_evaluations.py
index c518f837..923a6854 100644
--- a/tests/test_mcp_evaluations.py
+++ b/tests/test_mcp_evaluations.py
@@ -178,7 +178,7 @@ def _completed_run(context, dataset, label, row_scores, *, group, is_baseline=Fa
project=context.project,
name=label,
cell=dataset.active_cell,
- mode=EvalRun.Mode.PROVIDED,
+ mode=EvalRun.Mode.RECORDED,
matrix=[row.snapshot()],
group=group,
is_baseline=is_baseline,
diff --git a/tests/test_mcp_optimizer.py b/tests/test_mcp_optimizer.py
deleted file mode 100644
index 15991dbd..00000000
--- a/tests/test_mcp_optimizer.py
+++ /dev/null
@@ -1,186 +0,0 @@
-from __future__ import annotations
-
-import json
-import uuid
-
-import pytest
-from asgiref.sync import async_to_sync
-from conftest import EVAL_ROWS, frozen_dataset
-from mcp_fixtures import call_tool, mcp_context
-
-from overbae.models import (
- Capability,
- Dataset,
- EvalSet,
- OptimizerCandidate,
- OptimizerExperiment,
- OptimizerIteration,
-)
-from overbae.services.mcp.catalog import CATALOG
-from overbae.services.mcp.context import MCPContext, bind_context
-from overbae.services.mcp.contracts.optimizer import InspectOptimizerResultOutput
-from overbae.services.mcp.resources import read_resource
-
-pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]
-
-
-def _call(name: str, arguments: dict, context: MCPContext):
- return call_tool(name, arguments, context)
-
-
-def _ready_objects(context: MCPContext):
- capability = Capability.objects.create(
- project=context.project, name="Support", slug=f"support-{uuid.uuid4().hex[:6]}"
- )
- dataset = frozen_dataset(
- context.project, EVAL_ROWS, capability=capability, name="Eval", contract="eval"
- )
- eval_set = EvalSet.objects.create(
- project=context.project, capability=capability, name="Default eval"
- )
- capability.active_eval_set = eval_set
- capability.save(update_fields=["active_eval_set"])
- return capability, dataset, eval_set
-
-
-def _experiment(context: MCPContext, *, status: str | None = None) -> OptimizerExperiment:
- capability, dataset, eval_set = _ready_objects(context)
- return OptimizerExperiment.objects.create(
- project=context.project,
- capability=capability,
- dataset=dataset,
- eval_set=eval_set,
- status=status or OptimizerExperiment.Status.SCHEDULED,
- )
-
-
[email protected]("authentication")
-def test_read_only_key_hides_and_denies_optimizer_writes():
- context = mcp_context()
- visible = {tool.name for tool in CATALOG.tools(frozenset({"read"}))}
- assert {"check_optimizer_readiness", "inspect_optimizer_result"} <= visible
- assert "start_optimizer" not in visible
-
- result = _call("start_optimizer", {"capability": "x", "dataset": "x"}, context)
- assert result.isError is True
- assert result.structuredContent["error"]["code"] == "permission_denied"
-
-
-def test_readiness_reports_wrong_dataset_intent_and_executioner_state():
- context = mcp_context(permission=["read", "write"])
- capability = Capability.objects.create(
- project=context.project, name="Support", slug=f"support-{uuid.uuid4().hex[:6]}"
- )
- train = Dataset.objects.create(
- project=context.project, capability=capability, name="Train", intent=Dataset.Intent.TRAIN
- )
- result = _call(
- "check_optimizer_readiness",
- {"capability": str(capability.id), "dataset": str(train.id)},
- context,
- )
-
- assert result.isError is False
- output = result.structuredContent
- assert output["ready"] is False
- assert any("eval dataset" in item for item in output["missing"])
- assert output["dataset"]["usable"] is False
- assert output["executioner"]["connected"] is False
-
-
-def test_cross_project_experiment_is_inaccessible():
- context = mcp_context()
- other = mcp_context()
- experiment = _experiment(other)
-
- result = _call("inspect_optimizer_result", {"experiment": str(experiment.id)}, context)
- assert result.isError is True
- assert result.structuredContent["error"]["code"] == "optimizer_not_found"
-
-
-def test_inspect_exposes_candidate_coverage_fields():
- context = mcp_context()
- experiment = _experiment(context, status=OptimizerExperiment.Status.COMPLETED)
- iteration = OptimizerIteration.objects.create(experiment=experiment, order=0)
- OptimizerCandidate.objects.create(
- experiment=experiment,
- iteration=iteration,
- candidate_index=0,
- score=100.0,
- scores={
- "coverage_rate": 0.95,
- "graded_rows": 19,
- "total_rows": 20,
- "coverage": {"coverage_rate": 0.95, "graded_rows": 19, "total_rows": 20},
- },
- )
-
- result = _call("inspect_optimizer_result", {"experiment": str(experiment.id)}, context)
-
- assert result.isError is False
- output = InspectOptimizerResultOutput.model_validate(result.structuredContent)
- candidate = output.iterations[0].candidates[0]
- assert candidate.coverage_rate == pytest.approx(0.95)
- assert candidate.graded_rows == 19
- assert candidate.total_rows == 20
-
-
-def test_inspect_is_bounded_typed_and_exposes_winner_state():
- context = mcp_context()
- experiment = _experiment(context, status=OptimizerExperiment.Status.COMPLETED)
- winner = None
- for order in range(2):
- iteration = OptimizerIteration.objects.create(
- experiment=experiment, order=order, scores={"best": float(order)}
- )
- for index in range(2):
- candidate = OptimizerCandidate.objects.create(
- experiment=experiment,
- iteration=iteration,
- candidate_index=index,
- score=float(order * 10 + index),
- code_path="diff --git a/a b/a\n" if index else "",
- )
- winner = candidate if order == 1 and index == 1 else winner
- experiment.state = {"winner_candidate_id": str(winner.id)}
- experiment.save(update_fields=["state"])
-
- result = _call(
- "inspect_optimizer_result",
- {
- "experiment": str(experiment.id),
- "max_iterations": 1,
- "max_candidates_per_iteration": 1,
- },
- context,
- )
-
- assert result.isError is False
- output = InspectOptimizerResultOutput.model_validate(result.structuredContent)
- assert len(output.iterations) == 1
- assert len(output.iterations[0].candidates) == 1
- assert output.iterations_truncated is True
- assert output.winner is not None
- assert output.winner.candidate_id == str(winner.id)
-
-
-def test_optimizer_resource_is_bounded_and_does_not_leak_key_values():
- context = mcp_context()
- experiment = _experiment(context)
- experiment.state = {"openrouter_api_key": "secret-value"}
- experiment.save(update_fields=["state"])
-
- uri = f"overmind://optimizer-runs/{experiment.id}"
-
- async def read():
- with bind_context(context):
- contents = list(await read_resource(uri))
- return contents[0].content
-
- payload = json.loads(async_to_sync(read)())
- assert "secret-value" not in json.dumps(payload)
- assert "iterations" in payload
- assert "executioner" in payload
- assert "next_action" in payload
diff --git a/tests/test_mcp_prompts.py b/tests/test_mcp_prompts.py
index 33e3dee2..3739bcc9 100644
--- a/tests/test_mcp_prompts.py
+++ b/tests/test_mcp_prompts.py
@@ -73,7 +73,7 @@ def test_lists_the_small_prompt_manifest_over_transport():
assert {prompt["name"] for prompt in response.json()["result"]["prompts"]} == {
prompt.name for prompt in PROMPTS
}
- assert len(PROMPTS) == 14
+ assert len(PROMPTS) == 12
def test_upload_prompt_requires_local_path_and_keeps_optional_shape():
@@ -124,8 +124,6 @@ def test_dataset_prompts_do_not_use_retired_workshop_language():
"prepare-evaluation",
"evaluate-change",
"finetune-capability",
- "optimize-capability",
- "compare-models",
"upload-dataset-file",
"export-dataset",
}
diff --git a/tests/test_mcp_resources.py b/tests/test_mcp_resources.py
index fe71e1ac..f588c762 100644
--- a/tests/test_mcp_resources.py
+++ b/tests/test_mcp_resources.py
@@ -20,7 +20,6 @@ from overbae.models import (
EvalRun,
EvalSet,
FinetuningJob,
- OptimizerExperiment,
Project,
ProjectMembership,
Span,
@@ -153,7 +152,6 @@ def test_resource_templates_cover_the_public_resource_surface():
"overmind://eval-sets/{eval_set}",
"overmind://finetunes/{job_id}",
"overmind://deployments/{deployment}",
- "overmind://optimizer-runs/{experiment}",
"overmind://jobs/{kind}/{id}",
"overmind://operations/{id}",
"overmind://jobs/data_exploration/{id}/strata",
@@ -306,11 +304,6 @@ def test_resource_reads_are_json_and_project_scoped():
base_model="model/base",
)
deployment = DeployedModel.objects.create(project=project, model_id="ft-support")
- optimizer = OptimizerExperiment.objects.create(
- project=project,
- capability=capability,
- dataset=dataset,
- )
token = APIToken(scope={"scope": "project", "permission": ["read"]})
context = MCPContext(user=User(email="[email protected]"), token=token, project=project)
@@ -323,7 +316,6 @@ def test_resource_reads_are_json_and_project_scoped():
f"overmind://eval-runs/{eval_run.id}",
f"overmind://finetunes/{finetune.id}",
f"overmind://deployments/{deployment.id}",
- f"overmind://optimizer-runs/{optimizer.id}",
f"overmind://jobs/dataset_run/{dataset.id}",
]
diff --git a/tests/test_model_registry.py b/tests/test_model_registry.py
index e44a5542..6b7a2e74 100644
--- a/tests/test_model_registry.py
+++ b/tests/test_model_registry.py
@@ -6,7 +6,6 @@ from overbae.core.model_registry import (
OPENROUTER_MODEL_SLUGS,
ROLE_CHAINS,
TaskType,
- default_backtest_models,
default_judge_model,
model_chain,
openrouter_configured,
@@ -68,7 +67,6 @@ def test_judge_chain_spans_three_families():
def test_defaults_come_from_the_chains():
assert default_judge_model() == model_chain(TaskType.JUDGE_SCORING)[0]
- assert default_backtest_models() == ["openai/gpt-5.6-luna", "anthropic/claude-sonnet-5"]
def test_catalog_names_are_unique_and_slugs_are_vendor_qualified():
diff --git a/tests/test_optimizer_fsm.py b/tests/test_optimizer_fsm.py
deleted file mode 100644
index 1ad031f2..00000000
--- a/tests/test_optimizer_fsm.py
+++ /dev/null
@@ -1,372 +0,0 @@
-"""The client runs every datapoint and posts outputs; the server grades them and
-parks for the client. Driven through the ledger, the eval chord and the tasks."""
-
-from __future__ import annotations
-
-import threading
-import uuid
-from concurrent.futures import ThreadPoolExecutor
-from contextlib import contextmanager
-
-import pytest
-from conftest import frozen_dataset
-from django.db import close_old_connections
-from django.urls import reverse
-from factories import auth_client, make_matrix_row, make_project, make_user
-
-from overbae.models import (
- Capability,
- EvalMatrix,
- EvalRun,
- EvalScore,
- OptimizerCandidate,
- OptimizerCommand,
- OptimizerExperiment,
- OptimizerIteration,
-)
-from overbae.models.optimizer import (
- on_candidate_eval_finished,
- optimize_capability,
- run_experiment_advance,
-)
-from overbae.services.optimizer_create import create_optimizer_experiment
-from overbae.services.optimizer_ledger import (
- complete_experiment,
- create_iteration,
- evaluate_iteration,
- post_results,
-)
-from overbae.tasks.optimizer_reconciler import reconcile_optimizer_experiments
-
-pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]
-
-EXACT_MATCH = "def evaluate(span):\n return span.output == span.expected\n"
-
-ROWS = [({"q": "2+2"}, "four"), ({"q": "capital of France"}, "paris")]
-S = OptimizerExperiment.Status
-
-
-def _experiment(*, graded: bool = True, user=None) -> OptimizerExperiment:
- project = make_project(member=user) if user else make_project()
- capability = Capability.objects.create(
- project=project, name="A", slug=f"a-{uuid.uuid4().hex[:6]}"
- )
- dataset = frozen_dataset(
- project,
- [{"input": inp, "expected_output": expected} for inp, expected in ROWS],
- capability=capability,
- )
- if graded:
- make_matrix_row(
- project,
- "Exact match",
- capability=capability,
- type=EvalMatrix.Type.DETERMINISTIC,
- source=EXACT_MATCH,
- )
- return create_optimizer_experiment(user=user, capability=capability, dataset=dataset)
-
-
-def _run(exp, order: int, outputs: list[str | None]) -> OptimizerCandidate:
- iteration = create_iteration(
- exp, order=order, candidates=[{"candidate_index": 0, "code_path": f"+v{order}"}]
- )
- candidate = iteration.candidates.get()
- post_results(
- exp,
- [
- {
- "candidate_id": str(candidate.id),
- "datapoint_index": index,
- "success": output is not None,
- "output": output or "",
- "error": "" if output is not None else "provider timeout",
- }
- for index, output in enumerate(outputs)
- ],
- )
- return candidate
-
-
- ("outputs", "score", "coverage"),
- [
- (["four", "paris"], 100.0, 1.0),
- (["wrong", "nope"], 0.0, 1.0),
- (["four", None], 50.0, 0.5),
- ([None, None], 0.0, 0.0),
- ],
- ids=["right", "wrong", "one failed row", "every row failed"],
-)
[email protected]_db(transaction=True)
-def test_posted_outputs_are_graded_by_a_real_eval_run(eager, outputs, score, coverage):
- exp = _experiment()
- candidate = _run(exp, 0, outputs)
-
- evaluate_iteration(exp, 0)
-
- exp.refresh_from_db()
- candidate.refresh_from_db()
- assert exp.status == S.EVALUATED_BASELINE_OUTPUTS
- assert candidate.eval_run.status == EvalRun.Status.COMPLETED
- assert candidate.eval_run.max_items == len(ROWS)
- assert candidate.score == pytest.approx(score)
- assert candidate.scores["coverage_rate"] == pytest.approx(coverage)
- assert exp.scores["baseline"] == pytest.approx(score)
-
-
-def test_without_matrix_rows_the_experiment_fails():
- exp = _experiment(graded=False)
- candidate = _run(exp, 0, ["four", "paris"])
-
- evaluate_iteration(exp, 0)
-
- exp.refresh_from_db()
- candidate.refresh_from_db()
- assert exp.status == S.FAILED
- assert candidate.eval_run is None
-
-
- ("best", "stalled", "score", "stalled_after", "best_after"),
- [
- (60.0, 2, 70.0, 0, 70.0),
- (90.0, 0, 90.5, 1, 90.5),
- (97.2, 1, 97.5, 2, 97.5),
- (90.0, 1, 40.0, 2, 90.0),
- ],
- ids=["improves", "within the plateau threshold", "small win still ranks", "regresses"],
-)
-def test_a_graded_iteration_updates_the_best_score_and_the_plateau_count(
- best, stalled, score, stalled_after, best_after
-):
- exp = _experiment()
- exp.scores = {"baseline": 50.0, "best": best}
- exp.stalled_iterations = stalled
- exp.save()
- iteration = OptimizerIteration.objects.create(experiment=exp, order=1)
- candidate = OptimizerCandidate.objects.create(
- experiment=exp, iteration=iteration, code_path="+v1", score=score
- )
-
- exp.on_iteration_eval_complete(1)
- complete_experiment(exp)
-
- exp.refresh_from_db()
- assert exp.stalled_iterations == stalled_after
- assert exp.scores["best"] == pytest.approx(best_after)
- assert exp.state["winner_score"] == pytest.approx(best_after)
- if score > best:
- assert exp.state["winner_candidate_id"] == str(candidate.id)
-
-
- ("scores", "winner"),
- [({"baseline": 50.0, "best": 82.0}, 82.0), ({"baseline": 50.0}, 50.0), ({}, 0.0)],
- ids=["best", "baseline only", "nothing scored"],
-)
-def test_completion_records_the_winning_score(scores, winner):
- exp = _experiment()
- exp.scores = scores
- exp.save()
- complete_experiment(exp)
- exp.refresh_from_db()
- assert exp.status == S.COMPLETED
- assert exp.state["winner_score"] == pytest.approx(winner)
-
-
-def test_completion_fails_an_iteration_the_client_never_finished():
- exp = _experiment()
- iteration = create_iteration(exp, order=1, candidates=[{"candidate_index": 0}])
-
- complete_experiment(exp)
-
- iteration.refresh_from_db()
- assert iteration.status == OptimizerIteration.Status.FAILED
- assert iteration.candidates.get().status == OptimizerCandidate.Status.FAILED
-
-
-def test_cancel_stops_the_running_iteration():
- user = make_user()
- exp = _experiment(user=user)
- candidate = _run(exp, 0, ["four", None])
-
- response = auth_client(user).post(
- reverse("optimizer-experiment-cancel", kwargs={"id": exp.id}), format="json"
- )
-
- assert response.status_code == 200
- assert response.data["status"] == S.CANCELLED
- candidate.refresh_from_db()
- assert candidate.status == OptimizerCandidate.Status.FAILED
- assert candidate.iteration.status == OptimizerIteration.Status.FAILED
- assert set(candidate.commands.values_list("status", flat=True)) == {
- OptimizerCommand.Status.RAN,
- OptimizerCommand.Status.FAILED,
- }
-
-
[email protected]("terminal", [S.COMPLETED, S.FAILED, S.CANCELLED])
-def test_cancel_leaves_a_finished_experiment_alone(terminal):
- user = make_user()
- exp = _experiment(user=user)
- candidate = _run(exp, 0, ["four", "paris"])
- OptimizerExperiment.objects.filter(pk=exp.pk).update(status=terminal)
-
- auth_client(user).post(reverse("optimizer-experiment-cancel", kwargs={"id": exp.id}))
-
- exp.refresh_from_db()
- candidate.refresh_from_db()
- assert exp.status == terminal
- assert candidate.status == OptimizerCandidate.Status.COMMANDS_DONE
-
-
-def test_a_grading_run_that_finishes_after_cancel_does_not_revive_the_experiment():
- user = make_user()
- exp = _experiment(user=user)
- candidate = _run(exp, 0, ["four", "paris"])
- evaluate_iteration(exp, 0)
- auth_client(user).post(reverse("optimizer-experiment-cancel", kwargs={"id": exp.id}))
-
- candidate.refresh_from_db()
- on_candidate_eval_finished(candidate.eval_run)
-
- exp.refresh_from_db()
- assert exp.status == S.CANCELLED
-
-
-def test_an_advance_during_candidate_grading_waits_for_the_grades():
- exp = _experiment()
- _run(exp, 0, ["four", "paris"])
- evaluate_iteration(exp, 0)
- _run(exp, 1, ["four", "paris"])
- evaluate_iteration(exp, 1)
-
- run_experiment_advance(str(exp.id))
-
- exp.refresh_from_db()
- assert exp.status == S.EVALUATING_CANDIDATE_OUTPUTS
- assert exp.failure_reason == ""
-
-
-def test_a_late_advance_does_not_grade_an_iteration_still_receiving_outputs(eager):
- exp = _experiment()
- _run(exp, 0, ["four", "paris"])
- evaluate_iteration(exp, 0)
- iteration = create_iteration(exp, order=1, candidates=[{"candidate_index": 0}])
-
- run_experiment_advance(str(exp.id))
-
- exp.refresh_from_db()
- assert exp.status == S.ITERATING
- assert iteration.candidates.get().eval_run is None
-
-
-def test_an_advance_that_raises_fails_the_experiment():
- exp = _experiment()
- OptimizerExperiment.objects.filter(pk=exp.pk).update(status=S.EVALUATING_BASELINE_OUTPUTS)
-
- run_experiment_advance(str(exp.id))
-
- exp.refresh_from_db()
- assert exp.status == S.FAILED
- assert exp.failure_reason.startswith("advance failed: DoesNotExist")
-
-
-def test_an_advance_for_a_deleted_experiment_is_a_noop():
- run_experiment_advance(str(uuid.uuid4()))
-
-
-def test_an_advance_that_cannot_take_the_lock_leaves_the_experiment(monkeypatch):
- @contextmanager
- def held(*_args, **_kwargs):
- yield False
-
- monkeypatch.setattr("overbae.tasks.utils.task_lock.acquire_task_lock", held)
- exp = _experiment()
- OptimizerExperiment.objects.filter(pk=exp.pk).update(status=S.EVALUATING_BASELINE_OUTPUTS)
-
- run_experiment_advance(str(exp.id))
-
- exp.refresh_from_db()
- assert exp.status == S.EVALUATING_BASELINE_OUTPUTS
-
-
-def test_the_reconciler_redrives_only_experiments_waiting_on_grades(monkeypatch):
- dispatched = []
- monkeypatch.setattr(run_experiment_advance, "delay", dispatched.append)
- by_status = {}
- for status in S.values:
- exp = _experiment(graded=False)
- OptimizerExperiment.objects.filter(pk=exp.pk).update(status=status)
- by_status[status] = str(exp.id)
-
- reconcile_optimizer_experiments()
-
- assert sorted(dispatched) == sorted(
- [by_status[S.EVALUATING_BASELINE_OUTPUTS], by_status[S.EVALUATING_CANDIDATE_OUTPUTS]]
- )
-
-
-def test_optimize_capability_schedules_without_dispatch(monkeypatch):
- dispatched = []
- monkeypatch.setattr(run_experiment_advance, "delay", dispatched.append)
- project = make_project()
- capability = Capability.objects.create(
- project=project, name="a", slug="a", entrypoint_fn="trigger"
- )
- dataset = frozen_dataset(
- project, [{"input": {"q": 1}, "expected_output": "one"}], capability=capability
- )
-
- experiment = optimize_capability(capability, dataset=dataset)
-
- assert experiment.status == S.SCHEDULED
- assert experiment.entrypoint == "trigger"
- assert dispatched == []
-
-
[email protected]_db(transaction=True)
-def test_concurrent_candidate_completions_keep_all_scores_and_clear_pending(monkeypatch):
- exp = _experiment()
- iteration = OptimizerIteration.objects.create(experiment=exp, order=1, status="evaluating")
- candidates = []
- for index, score in enumerate([0.2, 0.8]):
- run = EvalRun.objects.create(
- project=exp.project, name=f"Candidate {index}", status="completed", max_items=1
- )
- EvalScore.objects.create(
- project=exp.project,
- run=run,
- source_type="dataset_row",
- source_id=f"{run.pk}:0",
- score=score,
- )
- candidates.append(
- OptimizerCandidate.objects.create(
- experiment=exp, iteration=iteration, candidate_index=index, eval_run=run
- )
- )
- exp.state = {"eval_pending": {str(c.pk): str(c.eval_run_id) for c in candidates}}
- exp.status = S.EVALUATING_CANDIDATE_OUTPUTS
- exp.save()
- dispatches = []
- monkeypatch.setattr(run_experiment_advance, "delay", lambda *args: dispatches.append(args))
- ready = threading.Barrier(2)
-
- def finish(candidate):
- try:
- ready.wait(timeout=5)
- on_candidate_eval_finished(candidate.eval_run)
- finally:
- close_old_connections()
-
- with ThreadPoolExecutor(max_workers=2) as executor:
- list(executor.map(finish, candidates))
- exp.refresh_from_db()
- assert exp.state["eval_pending"] == {}
- assert exp.status == S.EVALUATED_CANDIDATE_OUTPUTS
- assert sorted(exp.scores["1"].values()) == [20, 80]
- assert len(dispatches) == 1
- on_candidate_eval_finished(candidates[0].eval_run)
- assert len(dispatches) == 1
diff --git a/tests/test_optimizer_input_shapes.py b/tests/test_optimizer_input_shapes.py
deleted file mode 100644
index 413ebd56..00000000
--- a/tests/test_optimizer_input_shapes.py
+++ /dev/null
@@ -1,27 +0,0 @@
-"""Eval-intent gate for optimizer datasets. Command templates are authored on the client."""
-
-from __future__ import annotations
-
-import uuid
-
-import pytest
-from conftest import EVAL_ROWS, TRAIN_ROWS, frozen_dataset
-
-from overbae.models import Capability, Project
-from overbae.models.optimizer import optimizer_dataset_error
-
-pytestmark = [pytest.mark.django_db, pytest.mark.covers("data-logic")]
-
-
-def test_optimizer_rejects_ft_and_missing_datasets():
- project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
- capability = Capability.objects.create(
- project=project, name="A", slug=f"a-{uuid.uuid4().hex[:6]}"
- )
- ft_dataset = frozen_dataset(project, TRAIN_ROWS, name="D", contract="train")
-
- assert optimizer_dataset_error(capability, ft_dataset) is not None
- assert optimizer_dataset_error(capability, None) is not None
-
- eval_dataset = frozen_dataset(project, EVAL_ROWS, name="D2", contract="eval")
- assert optimizer_dataset_error(capability, eval_dataset) is None
diff --git a/tests/test_optimizer_ledger.py b/tests/test_optimizer_ledger.py
deleted file mode 100644
index 64e48a1e..00000000
--- a/tests/test_optimizer_ledger.py
+++ /dev/null
@@ -1,139 +0,0 @@
-from __future__ import annotations
-
-import uuid
-
-import pytest
-from conftest import frozen_dataset
-from factories import make_matrix_row
-
-from overbae.models import (
- Capability,
- EvalMatrix,
- OptimizerCommand,
- OptimizerExperiment,
- Project,
-)
-from overbae.services.optimizer_create import create_optimizer_experiment
-from overbae.services.optimizer_ledger import (
- complete_experiment,
- create_iteration,
- evaluate_iteration,
- post_results,
- set_command_template,
-)
-
-pytestmark = [pytest.mark.django_db, pytest.mark.covers("metrics-math")]
-
-
-def _capability_with_eval_dataset():
- project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
- capability = Capability.objects.create(
- project=project, name="a", slug=f"a-{uuid.uuid4().hex[:6]}"
- )
- dataset = frozen_dataset(
- project,
- [{"input": {"q": 1}, "expected_output": "one"}],
- capability=capability,
- contract="eval",
- )
- make_matrix_row(
- project,
- "Exact match",
- capability=capability,
- type=EvalMatrix.Type.DETERMINISTIC,
- source="def evaluate(span):\n return span.output == span.expected\n",
- )
- return capability, dataset
-
-
-def test_posted_candidate_outputs_are_scored(eager):
- capability, dataset = _capability_with_eval_dataset()
- exp = create_optimizer_experiment(user=None, capability=capability, dataset=dataset)
- set_command_template(exp, "echo __DATAPOINT_INPUT__")
- iteration = create_iteration(
- exp,
- order=0,
- name="Baseline",
- candidates=[{"candidate_index": 0, "code_path": "", "is_baseline": True}],
- )
- candidate = iteration.candidates.get()
- post_results(
- exp,
- [
- {
- "candidate_id": str(candidate.id),
- "datapoint_index": 0,
- "success": True,
- "output": "ok",
- "trace_id": "a" * 32,
- }
- ],
- )
- cmd = OptimizerCommand.objects.get(experiment=exp, candidate=candidate)
- assert cmd.status == OptimizerCommand.Status.RAN
- assert cmd.output == "ok"
-
- exp = evaluate_iteration(exp, 0)
- exp.refresh_from_db()
- assert exp.status == OptimizerExperiment.Status.EVALUATED_BASELINE_OUTPUTS
- assert "baseline" in (exp.scores or {})
-
-
-def test_order_zero_model_candidate_defaults_to_challenger():
- capability, dataset = _capability_with_eval_dataset()
- exp = create_optimizer_experiment(user=None, capability=capability, dataset=dataset)
- iteration = create_iteration(
- exp,
- order=0,
- candidates=[
- {"candidate_index": 0, "code_path": ""},
- {"candidate_index": 1, "target_model": "openai/gpt-5-mini"},
- ],
- )
- plain, model_bearing = list(iteration.candidates.order_by("candidate_index"))
- assert plain.is_baseline is True
- assert model_bearing.is_baseline is False
-
-
-def test_model_comparison_accumulates_scores_by_model(eager, fake_llm):
- models = ["openai/gpt-5-mini", "anthropic/claude-sonnet-4"]
- fake_llm.extra_models = models
- capability, dataset = _capability_with_eval_dataset()
- exp = create_optimizer_experiment(
- user=None,
- capability=capability,
- dataset=dataset,
- mode=OptimizerExperiment.Mode.MODEL_COMPARISON,
- model_ids=models,
- openrouter_key_source=OptimizerExperiment.OpenRouterKeySource.LOCAL,
- )
- models = list(exp.model_ids)
- for order, model in enumerate(models):
- iteration = create_iteration(
- exp,
- order=order,
- name=model,
- candidates=[{"candidate_index": 0, "target_model": model, "is_baseline": False}],
- )
- candidate = iteration.candidates.get()
- post_results(
- exp,
- [
- {
- "candidate_id": str(candidate.id),
- "datapoint_index": 0,
- "success": True,
- "output": f"out-{order}",
- }
- ],
- )
- exp = evaluate_iteration(exp, order)
-
- exp.refresh_from_db()
- scores = exp.scores or {}
- assert set(scores.get("by_model") or {}) == set(models)
- assert scores.get("models") == scores["by_model"]
- assert "baseline" not in scores
- exp = complete_experiment(exp)
- assert exp.status == OptimizerExperiment.Status.COMPLETED
- assert exp.state["model_comparison"]["selected_winner"] in models
diff --git a/tests/test_optimizer_model_comparison.py b/tests/test_optimizer_model_comparison.py
deleted file mode 100644
index 28471fe2..00000000
--- a/tests/test_optimizer_model_comparison.py
+++ /dev/null
@@ -1,251 +0,0 @@
-from __future__ import annotations
-
-import uuid
-
-import pytest
-from conftest import frozen_dataset
-from factories import make_matrix_row
-from rest_framework.exceptions import ValidationError
-
-from overbae.models import (
- Capability,
- DeployedModel,
- EvalMatrix,
- OptimizerCandidate,
- OptimizerExperiment,
- OptimizerIteration,
- Project,
-)
-from overbae.services.optimizer_create import (
- validate_optimizer_models,
-)
-from overbae.services.optimizer_ledger import (
- complete_experiment,
- create_iteration,
- evaluate_iteration,
- post_results,
-)
-
-pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]
-
-EXACT_MATCH = "def evaluate(span):\n return span.output == span.expected\n"
-
-MODE = OptimizerExperiment.Mode.MODEL_COMPARISON
-MODELS = ["openai/gpt-5", "anthropic/claude-sonnet-4"]
-
-
[email protected](autouse=True)
-def _listed(fake_llm):
- fake_llm.extra_models = list(MODELS)
-
-
-def _experiment(*, mode=MODE, model_ids=None, status=None, openrouter_key_source=None):
- project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
- capability = Capability.objects.create(
- project=project, name="A", slug=f"a-{uuid.uuid4().hex[:8]}"
- )
- dataset = frozen_dataset(
- project,
- [
- {"input": {"question": "hello"}, "expected_output": "a"},
- {"input": {"question": "world"}, "expected_output": "b"},
- ],
- capability=capability,
- contract="eval",
- )
- kwargs = {}
- if openrouter_key_source is not None:
- kwargs["openrouter_key_source"] = openrouter_key_source
- experiment = OptimizerExperiment.objects.create(
- project=project,
- capability=capability,
- dataset=dataset,
- cell=dataset.active_cell,
- mode=mode,
- model_ids=model_ids or list(MODELS),
- status=status or OptimizerExperiment.Status.ITERATING,
- command_template="run __CANDIDATE_ID__",
- scores={"baseline": 80.0, "best": 80.0},
- **kwargs,
- )
- return experiment
-
-
-def test_finetuned_deployment_id_requires_ready_in_project():
- project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
- ready = DeployedModel.objects.create(
- project=project,
- model_id=f"ft-ready-{uuid.uuid4().hex[:8]}",
- status=DeployedModel.Status.READY,
- base_model_id="meta-llama/Meta-Llama-3.1-8B-Instruct-Reference",
- )
-
- assert validate_optimizer_models(MODE, [ready.model_id], project=project) == [ready.model_id]
-
- not_ready = DeployedModel.objects.create(
- project=project,
- model_id=f"ft-busy-{uuid.uuid4().hex[:8]}",
- status=DeployedModel.Status.DEPLOYING,
- base_model_id="meta-llama/Meta-Llama-3.1-8B-Instruct-Reference",
- )
- with pytest.raises(ValidationError, match=not_ready.model_id):
- validate_optimizer_models(MODE, [not_ready.model_id], project=project)
-
- with pytest.raises(ValidationError, match="ft-nobody"):
- validate_optimizer_models(MODE, ["ft-nobody-00000000"], project=project)
-
-
-def test_finetuned_references_require_platform_source():
- with pytest.raises(ValidationError, match="Overmind credits"):
- validate_optimizer_models(
- MODE,
- ["ft-3a4860af-qwen3-5-27b"],
- openrouter_key_source=OptimizerExperiment.OpenRouterKeySource.LOCAL,
- )
- assert validate_optimizer_models(
- MODE,
- [MODELS[0]],
- openrouter_key_source=OptimizerExperiment.OpenRouterKeySource.LOCAL,
- ) == [MODELS[0]]
-
-
-def test_normal_optimizer_rejects_model_selection():
- with pytest.raises(ValidationError, match="cannot select models"):
- validate_optimizer_models(OptimizerExperiment.Mode.OPTIMIZE, [MODELS[0]])
-
-
-def _grade(experiment, candidate: dict, results: list[dict], *, order: int = 1):
- make_matrix_row(
- experiment.project,
- "Exact match",
- capability=experiment.capability,
- type=EvalMatrix.Type.DETERMINISTIC,
- source=EXACT_MATCH,
- )
- iteration = create_iteration(experiment, order=order, candidates=[candidate])
- posted = iteration.candidates.get()
- post_results(experiment, [{"candidate_id": str(posted.id), **r} for r in results])
- evaluate_iteration(experiment, order)
- posted.refresh_from_db()
- return posted
-
-
- ("mode", "candidate", "label", "model_name"),
- [
- (MODE, {"target_model": MODELS[0]}, MODELS[0], MODELS[0]),
- (MODE, {"is_baseline": True}, "Baseline", "Incumbent model"),
- (
- OptimizerExperiment.Mode.HYBRID,
- {"candidate_index": 2, "target_model": MODELS[1]},
- f"Candidate 2 · {MODELS[1]}",
- MODELS[1],
- ),
- (
- OptimizerExperiment.Mode.OPTIMIZE,
- {"candidate_index": 1},
- "Candidate 2",
- "Incumbent model",
- ),
- ],
- ids=["comparison", "baseline", "hybrid", "optimize"],
-)
-def test_the_eval_run_carries_the_candidate_identity(eager, mode, candidate, label, model_name):
- experiment = _experiment(mode=mode)
- graded = _grade(experiment, candidate, [{"datapoint_index": 0, "output": "a"}])
-
- run = graded.eval_run
- assert (run.params["label"], run.model_name) == (label, model_name)
-
-
-def test_comparison_scores_report_the_incumbent_when_it_wins():
- experiment = _experiment()
- iteration = OptimizerIteration.objects.create(experiment=experiment, order=1)
- for index, (model, score) in enumerate(zip(MODELS, [75.0, 70.0], strict=True)):
- OptimizerCandidate.objects.create(
- experiment=experiment,
- iteration=iteration,
- candidate_index=index,
- target_model=model,
- score=score,
- code_path=f"+model = '{model}'",
- )
-
- experiment.on_iteration_eval_complete(1)
- complete_experiment(experiment)
-
- experiment.refresh_from_db()
- assert experiment.scores["best"] == 80.0
- assert experiment.scores["by_model"] == {MODELS[0]: 75.0, MODELS[1]: 70.0}
- assert experiment.scores["models"] == experiment.scores["by_model"]
- assert experiment.state["model_comparison"] == {
- "selected_winner": MODELS[0],
- "selected_winner_score": 75.0,
- "incumbent_score": 80.0,
- "overall_winner": "incumbent",
- "incumbent_wins": True,
- }
-
-
-def test_hybrid_report_surfaces_best_combination_even_when_incumbent_wins():
- experiment = _experiment(mode=OptimizerExperiment.Mode.HYBRID)
- iteration = OptimizerIteration.objects.create(experiment=experiment, order=1)
- OptimizerCandidate.objects.create(
- experiment=experiment,
- iteration=iteration,
- candidate_index=0,
- target_model=MODELS[0],
- code_path="+combined",
- score=75.0,
- status=OptimizerCandidate.Status.EVALUATED,
- )
-
- complete_experiment(experiment)
-
- assert experiment.state["model_optimization"] == {
- "selected_model": MODELS[0],
- "selected_harness_candidate": 1,
- "selected_score": 75.0,
- "incumbent_score": 80.0,
- "overall_winner": "incumbent",
- }
-
-
-def test_model_comparison_winner_breaks_score_tie_on_coverage():
- experiment = _experiment()
- iteration = OptimizerIteration.objects.create(
- experiment=experiment,
- order=1,
- status=OptimizerIteration.Status.EVALUATED,
- )
- full_coverage = {
- "coverage_rate": 1.0,
- "coverage": {"coverage_rate": 1.0, "excluded_commands": 0},
- }
- partial_coverage = {
- "coverage_rate": 0.5,
- "coverage": {"coverage_rate": 0.5, "excluded_commands": 1},
- }
- OptimizerCandidate.objects.create(
- experiment=experiment,
- iteration=iteration,
- candidate_index=0,
- target_model=MODELS[0],
- score=100.0,
- scores=full_coverage,
- status=OptimizerCandidate.Status.EVALUATED,
- )
- OptimizerCandidate.objects.create(
- experiment=experiment,
- iteration=iteration,
- candidate_index=1,
- target_model=MODELS[1],
- score=100.0,
- scores=partial_coverage,
- status=OptimizerCandidate.Status.EVALUATED,
- )
-
- complete_experiment(experiment)
-
- assert experiment.state["model_comparison"]["selected_winner"] == MODELS[0]
diff --git a/tests/test_sdk_permutations.py b/tests/test_sdk_permutations.py
deleted file mode 100644
index c3bab3bc..00000000
--- a/tests/test_sdk_permutations.py
+++ /dev/null
@@ -1,158 +0,0 @@
-"""SDK routing permutations — how each capability SDK names models vs what the
-platform's routing chain (gateway resolution, telemetry comparison, model
-validation) accepts.
-
-Each section mirrors one real-world way people use their models:
-- bare hardcoded names (plain openai, langchain, smolagents, crewai)
-- full ``provider/slug`` names (openai-agents — the ``Unknown prefix`` trap)
-- ``openrouter/``-namespaced slugs, ``ft-…`` deployment ids, colon forms
-"""
-
-from __future__ import annotations
-
-from decimal import Decimal
-
-import pytest
-from factories import api_key_client, make_member, make_project, make_user
-
-from overbae.models import (
- DeployedModel,
- OptimizerExperiment,
-)
-
-pytestmark = [pytest.mark.django_db, pytest.mark.covers("sdk-wire")]
-
-
-URL = "/api/v1/chat/completions"
-MESSAGES = [{"role": "user", "content": "Hello"}]
-
-
-def gateway(fake_llm, settings):
- settings.OPENROUTER_API_KEY = "or-test"
- settings.OPENROUTER_PROXY_ENABLED = True
-
- def post(model_id: str, *, optimiser_header: bool = True) -> tuple[int, str]:
- user, project = make_user(), make_project()
- make_member(user, project)
- headers = {"HTTP_X_OVERMIND_OPTIMISER": "1"} if optimiser_header else {}
- before = len(fake_llm.requests)
- r = api_key_client(user, project).post(
- URL, {"model": model_id, "messages": MESSAGES}, format="json", **headers
- )
- if r.status_code == 200:
- return r.status_code, fake_llm.requests[before].model
- return r.status_code, r.json().get("error", {}).get("message", "")
-
- return post
-
-
-class TestGatewayModelNamePermutations:
- @pytest.mark.parametrize(
- ("sent", "forwarded"),
- [
- ("gpt-5-mini", "openai/gpt-5-mini"),
- ("deepseek-v4-flash", "deepseek/deepseek-v4-flash"),
- ("deepseek/deepseek-v4-flash", "deepseek/deepseek-v4-flash"),
- ("openrouter/openai/gpt-5-mini", "openai/gpt-5-mini"),
- ],
- ids=["curated bare name", "catalog-only bare name", "full slug", "openrouter namespace"],
- )
- def test_the_optimiser_names_a_model_the_way_its_sdk_does(
- self, gateway, fake_llm, sent, forwarded
- ):
- fake_llm.extra_models.append("deepseek/deepseek-v4-flash")
- assert gateway(sent) == (200, forwarded)
-
- @pytest.mark.parametrize(
- ("sent", "header"),
- [
- ("no-such-model", True),
- ("openai:gpt-5-mini", True),
- ("gpt-5-mini", False),
- ("ft-deadbeef", True),
- ],
- ids=["unknown", "colon form", "no optimiser header", "ft id"],
- )
- def test_a_name_the_gateway_cannot_route_is_not_found_and_named(self, gateway, sent, header):
- status_code, message = gateway(sent, optimiser_header=header)
- assert status_code == 404
- assert sent in message
-
- def test_a_bare_name_is_billed_under_its_resolved_slug(self, fake_llm, settings):
- from overbae.models import BillingService, BillingTelemetry
-
- settings.OPENROUTER_API_KEY = "or-test"
- settings.OPENROUTER_PROXY_ENABLED = True
- fake_llm.on(
- lambda r: r.model == "openai/gpt-5-mini",
- {"content": "Hi!", "usage": {"prompt_tokens": 10, "completion_tokens": 5}},
- )
- user, project = make_user(), make_project()
- make_member(user, project)
- r = api_key_client(user, project).post(
- URL,
- {"model": "gpt-5-mini", "messages": MESSAGES},
- format="json",
- HTTP_X_OVERMIND_OPTIMISER="1",
- )
-
- assert r.status_code == 200
- [charge] = BillingTelemetry.objects.filter(user=user, service=BillingService.INFERENCE)
- assert charge.metadata["model_id"] == "openai/gpt-5-mini"
- assert -charge.amount == Decimal("0.00002")
-
-
-class TestModelValidationPermutations:
- """A2: stored ids must be canonical — ``openrouter/`` namespaces stripped,
- full slugs kept, ft ids never touched, bare names rejected up front."""
-
- def test_openrouter_namespaced_slug_stored_canonical(self):
- from overbae.services.optimizer_create import validate_optimizer_models
-
- stored = validate_optimizer_models(
- OptimizerExperiment.Mode.MODEL_COMPARISON, ["openrouter/openai/gpt-5-mini"]
- )
- assert stored == ["openai/gpt-5-mini"]
-
- def test_full_slug_stored_verbatim(self):
- from overbae.services.optimizer_create import validate_optimizer_models
-
- stored = validate_optimizer_models(
- OptimizerExperiment.Mode.MODEL_COMPARISON, ["openai/gpt-5-mini"]
- )
- assert stored == ["openai/gpt-5-mini"]
-
- def test_provider_aliases_cannot_duplicate_one_model(self):
- from rest_framework.exceptions import ValidationError
-
- from overbae.services.optimizer_create import validate_optimizer_models
-
- with pytest.raises(ValidationError, match="Duplicate"):
- validate_optimizer_models(
- OptimizerExperiment.Mode.MODEL_COMPARISON,
- ["openai/gpt-5-mini", "openrouter/openai/gpt-5-mini"],
- )
-
- def test_bare_name_rejected_before_storage(self):
- from rest_framework.exceptions import ValidationError
-
- from overbae.services.optimizer_create import validate_optimizer_models
-
- with pytest.raises(ValidationError):
- validate_optimizer_models(OptimizerExperiment.Mode.MODEL_COMPARISON, ["gpt-5-mini"])
-
- def test_ft_id_stored_verbatim(self):
- from overbae.services.optimizer_create import validate_optimizer_models
-
- project = make_project()
- DeployedModel.objects.create(
- project=project,
- model_id="ft-nimbus-1234",
- status=DeployedModel.Status.READY,
- base_model_id="qwen/qwen3-14b",
- )
- stored = validate_optimizer_models(
- OptimizerExperiment.Mode.MODEL_COMPARISON, ["ft-nimbus-1234"], project=project
- )
- assert stored == ["ft-nimbus-1234"]