The platform for continuously improving AI agents.
Align Dev Skills + Trim AGENTS.md under the Codex limit (#262)
Freyam Mehta6fcecd3b8377
diff --git a/.agents/skills/api-endpoints/SKILL.md b/.agents/skills/api-endpoints/SKILL.mdindex b7e95a89..a4e8f4a0 100644--- a/.agents/skills/api-endpoints/SKILL.md+++ b/.agents/skills/api-endpoints/SKILL.md@@ -31,7 +31,7 @@ or in `urlpatterns` for plain views.make generate_api_client```-Settings refuse to load without Modal tokens when `.env` has none: prefix with `MODAL_TOKEN_ID=dummy MODAL_TOKEN_SECRET=dummy` — the schema step never talks to Modal.+Settings refuse to load when any key in `_REQUIRED_KEYS` (`overbae/settings.py`: sandbox, OpenRouter, Modal, inference, AWS, Hugging Face) is unset. If `.env` lacks some, prefix the command with dummy values for those keys — the schema step calls none of these services.Runs `manage.py spectacular` → dockerized `openapi-generator-cli` → rewrites `frontend/src/openapi/{apis,models}`.@@ -63,5 +63,5 @@ Hardcoded URLs and bare `fetch`/`axios` bypass auth middleware and typing. Respo## Rules-- Never hand-edit anything under `frontend/src/openapi/` — a hook blocks it under Claude Code, and the next regeneration would overwrite it anyway.+- Never hand-edit anything under `frontend/src/openapi/` — the `protect_generated` hook blocks it in Claude Code, Codex and Cursor, and the next regeneration would overwrite it anyway.- A DRF view docstring becomes the OpenAPI operation `description`, so editing one changes the generated client. Prefer an explicit `@extend_schema(summary=...)`.diff --git a/.agents/skills/backend-architecture/SKILL.md b/.agents/skills/backend-architecture/SKILL.mdindex 1badbe90..d982d42c 100644--- a/.agents/skills/backend-architecture/SKILL.md+++ b/.agents/skills/backend-architecture/SKILL.md@@ -1,6 +1,6 @@---name: backend-architecture-description: Deeper backend map of overbae — module layout, celery queue topology, the span-only tracing model and its API surface, capabilities and toml sync, matrix-keyed live scoring, evaluation runs and signals, auth and guests, model serving and base weights. Use when navigating unfamiliar backend subsystems or wiring cross-subsystem behavior.+description: Map of the overbae backend — module layout, the patterns every subsystem shares, and reference files for Celery topology, tracing and scoring, evaluation, capabilities and sync, auth and billing, training, serving and data-first workflows. Use when navigating an unfamiliar backend subsystem or wiring behavior across subsystems.---# overbae backend map@@ -9,551 +9,36 @@ Single Django app `overbae`, project-scoped tenancy.## Layout-- `overbae/api/` — DRF views/serializers, one module per surface (`eval_views.py`, `datasets.py`, `optimizer.py`, `otlp.py`, `billing.py`, `mcp.py`, …). `views.py` and `serializers.py` are the legacy monoliths — new surfaces get their own module. Global exception handler returns `{detail, code, error_id}`.-- `overbae/models/` — split by domain (`iam.py`, `capabilities.py`, `traces.py`, `innermind.py`, `finetuning.py`, `datasets.py`, `optimizer.py`, `billing.py`, …).-- `overbae/innermind/` — evals: the eval matrix evaluators, live span and trajectory scoring, deterministic sandbox and seeded checks, evaluation runs (generation, replay, comparison, context), the Default set, health and signals. See § Scoring and § Evaluation.-- `overbae/services/` — business logic; largest subtrees: `datasets/` (Parquet store, landing, cell runner, contract, alignment, diff, use), `mcp/` (Streamable HTTP MCP server — procedure in the mcp skill), `codebase/`, `scan/` (AI-surface extraction, footprint matcher, scan application), `capabilities/` (identity, lifecycle, graph).-- `overbae/tasks/` — Celery tasks, roughly one module per feature; `utils/task_lock.py` for locking.-- `overbae/modal/` — Modal.com GPU workers (vLLM serving, SFT, native decision evaluation).-- `overbae/management/commands/` — backfills and syncs.--## Celery topology--Six workers, six queues. Workers are resource profiles; queues are fairness classes.--| Worker | Pool | Conc | Queues | Holds |-| ------------- | ------- | ---- | ------------- | ------------------------------------------------------------------ |-| `control` | threads | 8 | `control` | orchestration, chord callbacks, FSM advances, beat |-| `io` | threads | 24 | `io` | preparation, eval launch, serving, connector polling |-| `io_traces` | prefork | 4 | `io_traces` | live span/trajectory scoring and signals |-| `batch` | prefork | 6 | `batch` | pipeline bindings, evaluation generation/scoring, connector chunks |-| `landing` | prefork | 1 | `landing` | source imports |-| `interactive` | prefork | 4 | `interactive` | retained-package pipelines and runtime health |--Three constraints set the worker split. Only prefork enforces `time_limit` and `revoke(terminate=True)`, so every time-limited task routes to `batch`, `landing`, `interactive` or `io_traces`. A loaded prefork child costs hundreds of MB, so wide fan-out cannot be prefork. Orchestration holds its own lane because a chord callback stuck behind work never finalises its run. `run_eval_run` routes to `io` because Modal warm-up blocks for minutes; the import and workshop reconcilers and queue metrics run on `control` with short expiries and are dropped when it is full.--`io` and `io_traces` have exclusive worker pools. Round-robin delivery cannot protect IO once long-running trace tasks occupy every thread. Both pools disable prefetch. LiveScoringWork retains waiting span, trajectory and signal work in PostgreSQL; a row-locked dispatcher admits at most 16 items globally and two per project, ordered by least recent project admission. Each prefork attempt has a five-minute hard limit and a six-minute fenced running lease. Duplicate broker deliveries cannot claim a running or superseded token. Existing span claim grace and three-attempt rules govern recovery, never fabricated scores. Queue metrics include durable live-scoring backlog and oldest waiting age. Signal scans retain at most 20,000 lightweight span identities, then load complete selected conversation/trace groups in batches of at most 8 MiB of encoded payloads. SQL rechecks each batch before materialization. Oversized groups are explicitly unprocessed, other groups still publish, and the work receipt records a limit error; no group is truncated to fit. Deploy and verify the trace-only worker before removing trace consumption from IO. Drain old mixed consumers before stopping them; do not discard reserved tasks or revoke acknowledged provider work.--Every prefork lane (`batch`, `landing`, `interactive`, `io_traces`) sets `--prefetch-multiplier=1 --disable-prefetch`, so a busy process never reserves waiting work. A reserved late-ack message stays unacknowledged, and Redis redelivers it after the broker `visibility_timeout` (2 h, above every late-ack time limit; `tests/test_celery_topology.py` holds both). Landing workers consume only `landing`. Durable DatasetLandingWork admission keeps waiting imports in PostgreSQL, admits one per project in least-recent-project order, and follows observed worker capacity up to eight. Waiting age remains observable; only an explicit nonzero DATASET_IMPORT_MAX_QUEUE_SECONDS expires a waiting import. Started worker loss fences publication and requires explicit retry. Landing scale-out demand counts useful competing projects, and ScalingQueuedAgeSeconds is zero when more workers cannot unblock another project.--Evaluation generation (`innermind/generation.py`) admits `EvalRunRow`s under a global `EvalGenerationScheduler` row lock. `EVAL_MAX_IN_FLIGHT` bounds admitted provider work (default 12), with `EVAL_MAX_IN_FLIGHT_PER_PROJECT` (default 4 across all runs), `EVAL_MAX_IN_FLIGHT_PER_RUN` (default 2) and least-recently-admitted project/run fairness. Waiting rows remain in Postgres; completion and a 30-second control tick replenish available slots. Completion wakeups coalesce through a cache key, so at most one dispatcher waits on the lock. Failed/cancelled parents cannot claim or continue generation. Lost started attempts become explicit unknown outcomes and are not automatically repeated.--Chat HTTP clients enforce one cancellable elapsed deadline across request bodies, SSE heartbeats and retry waits. They close their connections on expiration; a socket read timeout alone is not a total time bound.--Hosted commands come from `docker/worker-topology.json`. Deployment runs migrations, verifies a healthy landing-only consumer on the new image, then updates workers, beat and API. Landing and interactive workers run with their queue as the Celery hostname, and `overbae.worker_health <queue>` checks that the consumer reads only its queue and registers that queue's task; a rollout of either waits for that health check. `scripts/plan_landing_capacity.py` generates the reviewed ECS, IAM, bounded scale-out and CloudWatch queue-age/newly-blocked-import/monitor-health plan. `NewlyBlockedImports` counts imports blocked in the last 5 minutes by a system cause (`queue_timeout`, `worker_timeout`, `dispatch_failed`, `attempts_exhausted`); a user-data failure does not raise it. Scale-in requires an explicit idle drain; automatic scale-in is disabled.--Routing lives in `CELERY_TASK_ROUTES` and must stay in sync with `make worker` (one process standing in for the whole fleet, so its `-Q` lists every queue) , docker-compose and the deployment command manifest. `tests/test_celery_topology.py` enforces it, and asserts no time-limited task lands on a threads lane. Workers hot-restart via watchmedo on `.py` changes.--The training reconciler renews a 30-second Redis lease while alive. Worker death-expires that lease instead of suppressing observations for five minutes. Domain-finalization records terminal operational facts on the refreshed job; reconciliation-repairs missed terminal events from durable local receipts without polling or-resubmitting a provider. Completion does not advance the worker heartbeat.--Modal training billing and forecast evidence use deduplicated worker usage, not-the interval before the collector observes completion. Billing retains hardware,-usage IDs and fetched GPU rates; missing/conflicting usage is unmeasured, never-replaced with local elapsed time. Ledger creation and the saved charge receipt are-atomic. Historical charges without a retained calculation remain unattributed;-they are not silently rewritten. This is measured GPU coverage, not an all-in-provider invoice.--## Tracing--Span-only: there is no Trace table. A trace is the set of spans sharing a `trace_id`; the root span has `parent_span_id IS NULL`. `span_id` is the primary key; `trace_id` is an indexed 32-char hex `CharField`.--`Span` carries OTel-native fields plus platform linkage:--- Identity: `span_id`, `trace_id`, `parent_span_id`-- Classification: `span_type` (`llm_call`/`tool_call`/`retrieval`/`workflow`), `operation`-- Timing: `start_time_ns`, `end_time_ns`, `duration_ns` — nanosecond ints, no datetime column-- Status: `status_code`, `status_message`-- Resource/scope: `service_name`, `resource_attrs`, `scope_name`, `scope_version`-- Payload: `attributes`, `events`, `links`-- Linkage, filled by `process_span`: `capability` (resolved through `IdentityAlias`, never created), `job`, `iteration`-- Ingest time: `received_at`-- Scoring: `eval_attributes` (latest span score, metrics and, on a root, the trajectory) and `eval_claimed_at` (the scoring claim)--Ingest: `POST /api/v1/traces` (with a `/v1/traces` compat alias) takes an OTLP protobuf or JSON export → parse `ResourceSpans → ScopeSpans → Span` → flatten → bulk upsert on `span_id` → `process_span` per span for linkage → enqueue `tasks.innermind.score_spans`. Connector imports enqueue the same task.--Span cost has one owner: `services/span_pricing.stamp_span_cost` runs on every OTLP and connector span before it is stored. A reported cost (any alias, coalesced to `genai.cost`) is kept; otherwise `genai-prices` sets `genai.cost` from model, tokens and cache reads at the span's start time. The span, trace totals and `Capability.usage_stats` all read that value, and the SDK never prices. Gateway billing is separate on purpose: `model_catalog.estimate_cost` charges what OpenRouter charged us.--Read surface, backed by `SpanViewSet` rather than a trace viewset:--- `GET /api/traces/` — one row per trace, its head span (`Span.trace_heads`): the root once it arrives, else the earliest span, so traces stream in as spans land. Each row carries `trace_status` (`completed` = root present, `live` = rootless and recent, `interrupted` = rootless and quiet past `TRACE_SETTLE_SECONDS`)-- `GET /api/traces/{trace_id}/` — every span sharing that `trace_id`, plus root summary and `trace_status`-- `GET /api/traces/services/` — distinct `service_name`; `GET /api/traces/models/` — distinct models-- No `/api/spans/` route exists.--Query params are span-native (`received_at__gte`, `trace_id`, `span_type`, `operation`, `service_name`, `has_error`). In the trace-head view, `capability` matches any span within the same project and trace; `all_spans=true` filters each span directly. REST, MCP and trace-source selection share this filter.--## Evaluation--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). Creation with several `targets` makes one run per target under a shared `group`, at most one `is_baseline`. Startup commits the running state and complete row inventory atomically before admission can generate or score; model warmup stays outside that transaction. `innermind/runs.py` owns the lifecycle (create, launch, generate, score, aggregate, finish, cancel, relaunch, reap stalled); `generation.py` and `replay.py` produce outputs; `dataset.DatasetRowProcessor` scores rows through the same span evaluators as live scoring, appending `EvalScore(source_type=dataset_row, run=…)`. A row stands for the capability's answer, so it takes every frozen row whose `span_type` is blank or `llm_call` regardless of `span_name`; `tool_call`, `retrieval` and `workflow` rows stay live-only. An optimiser experiment reuses its first run's `matrix` for later candidates, as a training job does for its after-eval. `comparison.compare` pairs the latest score per row both runs scored (`EPSILON` 0.005; improved/regressed/unchanged/added/removed; wins/losses/ties; trust). Finetuning before/after evals, optimiser iterations (`provided` runs fed by posted outputs) and backtests all create grouped runs and read `comparison`. A `provided` run cannot relaunch.--`innermind/context.py` supplies model-aware advisory estimates for generate targets and the explanation judge through REST `POST /api/eval-runs/context-check/`, run detail and MCP readiness/resources. Readiness accepts the proposed targets; context warnings never change `ready`, gate launch or exclude training candidates. Unknown limits remain unverified. Estimates include reserved output. `suggest_models` adds preflight-only alternatives from the configured registry, filtered by published context/output and tool/schema support; registry order is retained, never auto-selected. `cost_basis` scopes USD estimates to all checked inputs plus full reserved output for one pass per model/judge; unknown prices are null. Trained benchmark hosting costs must not borrow base-model token rates.--Training setup puts the judge selector below the eval set. `FinetuningJob.eval_judge_model` picks the explanation model for that job's runs; blank uses the `EVAL_EXPLANATION` registry default. It never changes Jev. Every evaluation of a job grades with the first run's frozen matrix, and sibling baseline reuse includes judge-selection identity. REST context preview and MCP readiness accept `judge_model` and return `judge_models`: all registry judge options, annotated with estimated fit and aggregate USD budget per evaluated model/dataset pass. Unknown or undersized options stay selectable. MCP `start_finetune` accepts the same immutable `eval_judge_model`. Console tints judge/benchmark selectors only for estimated limit overflows, mutes undersized options without disabling them, and uses a warning-coloured Start button to open a short risk summary with Start anyway. Unverified, unavailable and pending checks stay neutral and do not open the warning summary. Context issues never require a model change to launch.--Bounded decisions use `core/decisions.py`: registered Jev on OpenRouter's `/systemone` endpoint, structured choice questions, validated complete probability distributions, project/contract-scoped caching, a conservative UTF-8 context guard, and shared Redis request/token pacing. Eval matrix llm rows (`innermind/evals.JevEvaluator`, workload `innermind_expectation`) call it directly with no generative fallback: transient transport failures raise so the span is retried, other `DecisionError`s become metric errors, and state over `JEV_STATE_LIMIT` is clipped head-and-tail. The trajectory `path_judge` and the `plan_drift` signal use the same evaluator. Fixed classification and workshop semantic services keep Jev with generative fallback through `services/judging/decisions.py`; confidence is not calibrated correctness. Jev is excluded from inference and chat-model pickers. Eval comparisons can select `typesafe/jev-1.13` or `typesafe/jev-1.14`; judges stay on `typesafe/jev-1.13`. `POST /api/v1/systemone` proxies that body in the request: a catalog model goes to OpenRouter, and a fine-tuned decision deployment calls its Modal worker. Provider calls in tests are blocked unless explicitly stubbed.--Generated rows snapshot the runner's initial messages and tool schemas; the REST row detail and MCP run resource expose separate input, generated output and reference, with each metric's score, verdict and reason.--Standalone REST creation and MCP `run_evaluation` accept the same optional `judge_model` used by context preview. It is frozen in `EvalRun.judge_model`; blank uses the registry default. Existing runs reject judge changes. The Console only lists runs (read-only) and creates and deletes matrix rows (REST and MCP never edit a row); the judge selector and advisory Start warning live in training setup; run detail and the MCP run resource show the frozen judge.--## Capabilities and sync--The agent is the project itself — one graph per project, no table. `Capability` rows are its nodes (UI: "Capability"; the sidebar's "Agent" is the product).--- A scan never deletes: absence sets `status=leftover` and the row reactivates in place when the code returns; `observed` rows (telemetry- or hand-made) are exempt from leftover.-- `DELETE /api/capabilities/{id}/` is a soft delete (`status=deleted`): the row and its data stay, but it is invisible to lists, scans, and identity lookup, so a later scan of the same code mints a fresh row. There is no merge, split, retire, or history.-- Ingest never creates a capability: `services/capabilities/identity.lookup` resolves ids/names/slugs through `IdentityAlias` (renames included), an unknown identity leaves the span unbound, and `tasks/capability_rebind` re-binds the backlog after scans and hand-made rows.-- Wire identity is id-only: ingest binds spans by `overmind.capability.id` alone; `overmind.agent.*` attributes are not read; `overmind.capability.name` is a display label that never resolves. The `overmind/<uuid>` model alias never changes.-- Discovery is local: `/overmind setup` runs `overmind chassis` (AST inventory + call graph), writes `overmind_capabilities.json`, `convert_json_to_toml` fills prompt spans, drops fabricated anchors and unverifiable provenance, then stamps `trajectory_map[].verified`, then `overmind sync`.-- Tool branches and execution steps may carry explicit `transitions: [{target, condition}]`. `target` resolves to an exact step anchor on the owning path, or `terminal` for that path's result. Normalization, REST flow serializers and the capability MCP resource preserve these continuations; missing or ambiguous destinations stay unresolved. SDK declaration ownership retains module-qualified entrypoint anchors while span names retain their runtime qualnames, so repeated class names cannot select another module's entrypoint.-- Toml sync is `POST`/`GET /api/v1/sync` (API-key auth). It maps onto `Capability` (`current`/`leftover`), stores `system_prompt` / `eval_metrics` / `capability_card` / `eval_matrix` in `improvement_metadata`, keeps `repo_summary` / `trace_provider` / toml `version` in `Project.settings`, writes leftovers back to toml with `archived = true`, and calls `innermind.default_set.upsert` per current capability: the project's seeded checks (`innermind/checks`, created only when missing), one deterministic `EvalMatrix` row per toml `eval_matrix` entry with `type="deterministic"` (`checks.render` sets the catalog script's constants from `params`; sync validates it and answers 400 for an unknown `check` or constant), one llm row per legacy toml expectation (managed metrics a seeded check covers map to that check), one llm row per synced code expectation (`expectations` on the wire: `overmind sync` reads `expectations=` from the checkout's entry-point, workflow and function decorators via `overmind.chassis.declared_expectations`, scoped by `span_name`; the sentence is the row name, and `eval_preload.declared` lets the next sync delete rows the code no longer declares), and the capability's `Default` `EvalSet`, activated when none is active. The result lands in `improvement_metadata.eval_preload`.-- Repository provenance: `overmind chassis` saves a local `.overmind/scan.json` receipt before inspection. Conversion verifies branch, commit and a SHA-256 fingerprint of tracked and unignored working-tree files (excluding generated scan files), then persists `repository_snapshot` in toml. A changed checkout requires a rescan. Sync never recaptures Git state: it stores provenance in `Project.settings` and stamps `last_synced_at` separately; a push without provenance clears the prior label. The agent graph and `overmind://project/current` expose both. Missing Git or a missing scan receipt leaves provenance unknown.--## Scoring--Matrix-keyed, in `overbae/innermind/`. `EvalMatrix` rows are `llm` (one-sentence expectation, `evals.JevEvaluator`) or `deterministic` (`def evaluate(span)` run by `deterministic.py` in an audited `python3 -I` child: no imports, `json`/`re` preloaded, frozen span plus parent/children/siblings, 5 s CPU / 15 s wall / 512 MB). Rows are project-wide or per capability, narrowed by `span_type`/`span_name`; span-declared `overmind.expectations` and `expect("constraint", …)` events add llm rows for that span.--REST and MCP expose a read-only `definition_source` for each matrix row. `innermind.definitions` matches saved content against the stock catalogue, synced code expectations or repository configuration; otherwise a recorded creator yields `custom`, and missing evidence yields `unknown`. This describes the current definition, not historical authorship. The Console separates Stock and Agent-specific rows, defaults to enabled rules, and labels the definition location.--- `span_processor.score_spans` skips spans that hold a score, claims each span (`eval_claimed_at`) only when it starts, applies the matching enabled rows per span type (`SpanProcessorFactory`; unscoped llm rows only on the root or a capability's topmost span, `metrics.answers_for_capability`, never tool/retrieval spans) and stores each span as it finishes (`persist`: one guarded update plus its `EvalScore`, so a score is written once) as `Span.eval_attributes` `{version, intent, fingerprint, score, metrics}`. Rows with the same expectation are judged once per span, and a computed row's metric is kept in `partial` so a retry judges only the rows that failed. A judging pass is counted in `attempts` before its judges run, so a killed or hung pass counts too: a row failing on the third (`MAX_ATTEMPTS`) pass is recorded as an error metric, and a span whose passes are spent is scored with error metrics without calling a judge. A span never waits for an ancestor or the root: it is judged with what has arrived, intent falling back from the span's own and the nearest arrived ancestor's `overmind.intent`, to the root's input if it has landed, to the capability description, and the 120 s beat sweep re-drives spans unscored past 90 s (newest first). Batches keep a trace together and load only the trace's roots and each span's arrived ancestors, plus its parent's children and its own when the project has a deterministic row. Re-ingest keeps a score whose `fingerprint` (name, type, parent, status, attributes) matches the incoming span and resets `eval_attributes` only when the evidence changed. Jev and explanation calls share one process-wide thread cap (`evals.throttled`); an event-loop semaphore cannot bound them, since every task has its own loop.-- `trajectory.score_trace` runs once, when every arrived span of a single-root trace is final; spans arriving later do not score it again: `outcome` (mean over answering spans, the trajectory score), `weakest_step`, `efficiency`, `path_judge`, `reference`, stored under the root's `eval_attributes.trajectory`. Its passes count in the root's `trajectory_attempts` under the same `MAX_ATTEMPTS`; a `path_judge` still failing then is an error metric.-- Every span, trajectory and run-row score appends an `EvalScore` (`source_type` `span`/`trajectory`/`dataset_row`); `GET /api/eval-scores/` reads it. The session score is the mean root trajectory score.-- `signals.SignalRunner` (beat every 5 min) checks each project with spans received in the last day, grouped by conversation or trace. Deterministic checks run by default without materializing subscriptions. Stored `SignalSubscription` settings override defaults; capability settings override project settings, including mutes. A per-project cache lock prevents overlap. `plan_drift` stays opt-in because it calls the judge, recording verdicts in `eval_attributes.drift` with bounded attempts. Events retain their source trace IDs in `details.trace_ids`; REST `/api/traces/?signal_event=UUID` and MCP `query_traces(signal_event=UUID)` share the project-scoped evidence filter. Historical events without the inventory retain their original trace link. Console Observability has three views: Sessions, Signals, Traces; no separate Signals page. REST `/api/signal-subscriptions/` configures overrides; MCP `list_signals` reports defaults and effective state, `set_signal_subscription` configures overrides, and `overmind://signal-events` reads saved findings.-- `health.py` backs MCP `inspect_capability_health` and `query_failures` from `eval_attributes`.--API: `api/eval_views.py`, `api/signal_views.py`.--## Data Workshop--Source → cells → derived versions. Native coding agents author reusable project revisions or attributed variants. Shared services validate lineage, execute retained packages through interactive workers in the isolated sandbox, and atomically publish step cells. Preview never publishes; explicitly enabled bindings rebuild changing source snapshots without agent authoring. Platform chat/agent tasks are retired. The dataset table opens existing cells with run inspection; historical records remain readable. Contracts and lifecycle: data-workshop skill.--## Auth and tenancy--Clerk when `CLERK_API_SECRET_KEY` is set; blank secret is self-hosted local JWT (`POST /api/auth/local/` — email + password, create on first use, no verification). ChatGPT login, linking, funding and credential storage are removed. Existing users remain; accounts without a usable password need administrator password setup. Project-scoped tenancy (`User` ↔ `Project` via `ProjectMembership`), no org layer. Everything queryable is filtered by project.--- A guest (`User.is_guest`, minted by `POST /api/auth/guest/`) holds one project and can read and claim. `GuestJWTAuthentication` (`api/authentication.py`) refuses every other write with `guest_upgrade_required`; a view opts in with `guest_allowed = True` — never a permission class or middleware, since a view's own `permission_classes` replaces the defaults and a guest identity exists only through that token. Guests get no free credits; `/demo` points at local setup. A claim moves the memberships to the Clerk account and deactivates the guest; `tasks/guest_cleanup.py` deletes inactive guests and unclaimed ones after 7 days. Guest claim requires Clerk.-- Console: `VITE_SELF_HOSTED=true` and a blank `VITE_CLERK_PUBLISHABLE_KEY` skip `ClerkProvider` and show the local login form; otherwise Clerk.-- Project invites: with Clerk, an invitation email is sent; without Clerk the `ProjectInvite` row is stored and claimed on first local (or Clerk) sign-in for that email.-- Commercial billing (remaining-credit 402s, the Free seat limit, Stripe Checkout) injects when `STRIPE_SECRET_KEY` is set (`overbae/services/billing_provider.py`). Ledger charges always run. Empty key → uncapped OSS: spend is recorded and shown, gates and grants no-op.-- API keys are either `scope=account` (every project the user belongs to) or `scope=project` with one `resourceIds` entry. Creating a key with `project` always mints project scope. REST and MCP `create_api_key` share `APIToken.create_for_user` and accept the Console dialog's name, description and expiry (30, 90, 180, 365 days, or 0 for never). MCP omits `project_id` for an account key and passes it for a project key. The plaintext is returned once. A project-scoped credential cannot mint an account key.--## Training preparation--Chat-training cost estimates use dataset text statistics and assumed H100 throughput, not an exact tokenizer report. Native forecasts use compatible completed execution measurements as described below. Modal GPU compute uses current workspace rates; Baseten uses its per-minute rate. Modal CPU, memory, storage and rate multipliers are additional. Exact preprocessing is a separate operation and does not validate the duration estimate.--Workshop findings are advisory before model-specific work: incomplete task/evidence/answer/schema reviews, capability mismatches and train/eval overlap produce warnings, not launch blockers. Exact preprocessing checks technical compatibility and does not repair datasets. Fine-tuning validation is read-only, and successful creation freezes the selected train, validation and `eval_cell` versions atomically. The same pinned eval cell is reused for before/after runs; dataset versions and capability cannot be swapped after creation. Internal loss-validation splitting preserves duplicates and cannot silently clean selected data.--Workshop is model-independent. Native agents inspect before transforming; historical source-bound plans and measured reviews stay attached to their exact versions. New pipeline/import runs record source bindings, impact and external attribution; no automatic semantic audit is scheduled. `services/training_preparation.py` caches exact Modal preprocessing by training/validation cell fingerprints, model, training type, context length, training stack and the SFT asset code fingerprint. REST `POST /api/training-preparations/` and MCP `prepare_training_data` share the service; MCP returns a `training_preparation` job receipt readable through `get_job` and the jobs resource. Preparation stages checksummed gzip JSONL through Modal Volume uploads and uses CPU-only `prepare_<train_function>` in the matching training image; it does not start GPU training. Tokenization writes artifacts incrementally. All Modal launches upload ordered binary SHA-256 row selections instead of the source rows a second time. The worker verifies each selection checksum and count plus the caller-pinned token artifact, then materializes training/validation through a bounded disk index, preserving order and duplicate visits. Initial source decompression and selection construction stream without retaining the corpus in memory.--Explicit preparation atomically creates a `FinetuningJob` linked by `preparation`, before the preprocessing task is queued. `preprocessing` and `awaiting_launch` are dashboard-visible setup states excluded from the training dispatcher and launch admission. The preprocessing observer updates setup progress and failures, without changing launched or cancelled jobs. A matching REST/MCP launch promotes the same job under the project lock, applies normal budget admission and freezes the complete recipe; repeating its launch key remains idempotent. Retrying a setup failure never launches GPU training. MCP preparation returns both preparation and training job receipts.--Console setup does not submit or await preprocessing and has no per-model preparation cards or workshop review recommendations. `run_finetuning` requests or reuses the exact artifact after launch, records its ID, state and report in job progress, and starts GPU training only when ready. Provider observations and finalization preserve that receipt and submission recovery history. Explicit REST/MCP preparation remains available.--Explicit preparation rejects unsupported context lengths rather than silently rounding them to a supported bucket. Model-specific recommendation and internal context selection happen before requesting that exact preparation.--Preparation reports source-export and tokenization row counts against the pinned total, then names upload, file validation and provider submission separately. The training monitor reads the current `TrainingPreparation` receipt on its fast metrics poll; the MCP training-job resource uses the same current progress, so neither has to wait for the job controller's next copy of the receipt. Counts describe their own stage, not overall training completion.--Training handoff separates selection construction, acknowledged selection-file uploads,-provider artifact verification, indexing, row selection and publication. Only successful-Modal batch completion increments acknowledged bytes/files; live network-byte progress-is unavailable. The pinned worker publishes bounded transfer measurements to the run's-`transfer-progress.json` and commits that volume when a stage finishes. Modal's-background commit publishes step files; a timer commit is not used, and at most-five launches upload at once. The existing 15-second reconciler collects transfer-facts even while the submission task is active. Console and MCP read persisted, attempt-fenced diagnostics-and operational events, never invoking a worker to read status. Stage start, source-observation and last forward progress remain separate; absent measurements show no-percentage. Worker instrumentation requires deployment of a new immutable release and-cannot retrofit a running pinned call.--GPU startup records file staging, runtime imports, weight loading, adapter setup,-tokenizer verification, dataset loading/building and trainer/optimiser startup-separately. Dataset construction reports processed rows; opaque library weight-loading has no invented percentage. Console and MCP expose stage start, source-observation, worker heartbeat and last forward progress. A committer heartbeat-does not advance progress; each new attempt resets its stage clock.--Recommendations compare the stored longest row, plus training headroom, with each model's LoRA and full fine-tuning context. A model is dropped when neither kind covers that length. A candidate keeps only the kinds that do, so a dataset that fits LoRA and not full fine-tuning is offered as LoRA only, and the reverse. Job preparation repeats sizing across the pinned training and enabled validation cells, preserving a larger requested context. A requested context equal to that estimate is still the first pass, including when a launch or setup job stored it: if exact tokenization exceeds it but fits the model's training-type limit, preparation requests the measured bucket and rechecks every row before the job fails. A different requested context stays fixed and overflow is rejected. Exact lengths need no estimate headroom; over-limit rows and other incompatibilities still block. No dataset is rewritten, truncated or filtered. A training-job retry can recover an undersized context through this same path.--`TrainingPreparation` persists queued/starting/running/ready/incompatible/failed, the remote call ID and a 24-hour deadline. A 15-second controller queues short `io` observers. Restarts poll the saved call; transport failures retain it. An unacknowledged submission fails closed. Explicit retry of a confirmed failure cancels its saved remote operation before requeueing; uncertain submissions cannot be retried automatically. REST `/retry/` and MCP `retry_failed` use the same guard. Retrying a failed/cancelled training job also retries its cached confirmed-failed preparation before queuing training, unless GPU training already has a remote ID. Ready or in-flight preparations are reused; unsafe failures and incompatible data refuse the retry without resetting job or eval state.--`sft_assets/preprocess.py` uses the trainer's `pretok` path, reporting exact token counts, shifted supervised targets, decoded masked previews and incompatible source-row IDs. It rejects over-context rows and zero-supervision examples without truncation or silent deletion. A ready artifact stores token IDs/labels, checksum and tokenizer; `upload_dataset` only materializes rows present in that artifact. The GPU engine validates context/vocabulary and consumes those tokens without preprocessing them again. Changes to the model/context or data require a matching artifact. Other providers retain their existing provider-side preprocessing; do not label those configurations exact-preflight-ready.--Changes to the SFT assets or preparation functions require `modal deploy overbae/modal/modal_sft_worker.py`; recreating local Docker services does not deploy Modal code. A worker/code fingerprint mismatch blocks preparation until the matching worker is deployed. Preprocessing infrastructure failures return a safe, actionable error and remain `failed`, distinct from incompatible rows. Each preparation retains subprocess stdout/stderr at `preparations/<id>/preprocess_stdout.log` on the SFT volume, including failed attempts; raw diagnostics do not enter user-facing error messages.--Unsloth token accuracy is measured from the final decoder output through the actual-output head, in bounded chunks over supervised next-token targets. Fused CE stays-enabled; accuracy does not depend on returned logits or a batch/context threshold.-Counts are token-weighted across microbatches, with separate training and validation-windows; checkpoint recomputation does not count twice. A missing decoder capture-fails explicitly rather than silently dropping the metric. A rolling Modal deploy-leaves active calls on their existing code; it cannot add metrics to an already-running-trainer or reconstruct historical accuracy.--## Development monitoring--`modal_shared/training_monitoring.py` owns strict policy resolution, whole-key/group-sampling, the timing scheduler and deterministic generated-output metrics.-`training_monitoring_runtime.py` persists atomic worker check/checkpoint receipts.-The chat callback preserves RNG, module modes and outer TrainerControl flags;-all teacher-forced checks use evaluation counters, including the fixed training-reference. Native checks preserve probability/ordinal targets and existing resume-artifacts. Initial/final checks are separate from periodic overhead scheduling.--Modal transfer freezes a manifest after exact token materialisation and before GPU-dispatch. `services/training_monitoring.py` stores the manifest, validates immutable-receipts, collects generated evidence in background and exposes passive paginated-reads. Preparation alone has no chosen development split. Check operational events-link to `TrainingValidationRun`; `TrainingCheckpoint` records checksums, reload-verification and explicit resume limitations. A locally interrupted check may gain-late terminal evidence without resurrecting a cancelled training job. Retained-checkpoints prevent volume cleanup; intermediate download/pruning is not yet exposed.--Status observation ingests metrics and checkpoints without downloading examples.-Missing evidence is `pending` until the per-job-locked IO collector reads each sealed-Modal Volume artifact once, with a 30-second read deadline and checksum verification.-Each verified check is persisted independently; duplicate collection skips saved-files and cannot overwrite newer monitoring facts. This keeps large development-sets and unavailable evidence downloads out of the shared training status loop.--The shared policy is accepted in readiness, preparation, estimates and launch;-Console setup uses the same hyperparameter payload. Defaults are adaptive with-2,048 loss rows, 256 reference rows, a 300-second interval target, 10% overhead-target and at most 12 interim checks. Whole groups can exceed target sizes.-Generation is opt-in and supports explicit classification labels, exact matching-and local JSON Schema or declared `json_fields` checks on Modal. The field scorer-accepts 1–64 explicit JSON Pointers, preserves boolean/number/null distinctions,-decimal precision and array order, and rejects ambiguous duplicate JSON keys.-Missing or malformed references remain unscorable; model-invalid JSON fails.-Whole-example and per-field pass rates retain their own coverage. Undeclared-fields are not judged; this does not infer tool contracts or execute tools.-Inputs exclude the final supervised answer;-generation never executes tools. Paired changes use group-bootstrap descriptive-intervals, not final-test guarantees. Metered judges, independent challenge suites-and declared-strata sampling are rejected as unsupported, not silently ignored.--MCP `inspect_training_progress(job, check|probe|field, offset, limit)` and REST expose-the same retained data without provider calls. Native per-question metrics and-assessments appear as `collections` descriptors in MCP overviews. Pass their-`field` JSON Pointer to page exact object entries or array items; append escaped-keys or indices for nested fields. REST monitoring-evidence shares this read path.-MCP evidence over 128 KiB fails explicitly; clients reduce page size or select a-deeper field. `cancel_finetune` and REST share intent-first cancellation-and delayed evidence collection. Optional check failures remain durable; explicit-best-loss selection/early stopping require successful checks. Monitoring cost is-not yet included in the forecasting model and is labelled unmeasured.--The chat monitoring context restores RNG, module modes, gradient checkpointing,-cache settings and the provider's training mode after generation. A training--reference evaluation uses the same loss path but never emits a development-curve-point. Native prediction receipts preserve probability vectors, original target-semantics and weights. Completion keeps the frozen manifest and final monitoring-observation instead of replacing them with a provider-only progress projection.-Precision with no predicted examples stays null, while missed represented labels-retain zero recall/F1. Paired classification changes exclude references outside-the frozen label contract. Evaluation announces zero completed batches before-the first forward pass, so completed sample construction is not mistaken for-ongoing validation progress.-Completed loss, reference and generation measurements are published while the-overall check is still running; later checkpoint failures retain those facts.-Adaptive schedule formula 2 retains the preceding interval across restarts, holds-changes within a 20% deadband and bounds larger changes to half/double per check.-A bounded cadence that misses the overhead target reports the conflict. Normal-run/check-count boundaries and explicit step/epoch modes do not imply a budget-failure. A measured overhead interval that prevents an otherwise due interim-check is reported separately. Active jobs retain their pinned scheduler release.-Launch credit admission runs inside the project-locked creation path only-after request-key recovery. Identical REST/MCP retries remain readable after-credits are exhausted; changed recipes conflict and new jobs remain gated.-Chat success records the deduplicated training GPU charge before deployment;-deployment readiness and its own usage cannot delay or replace the training receipt.--`training_experience.py` adds `facts.delivery.first_result_at` and `finished_at`-from the collector's receipt clock, independently of optional analytics. An available-result requires finite loss and complete nonempty loss coverage; it does not-claim generated-output success. Repeated receipts and late evidence attachment-preserve those times. Cancellation records an interruption under the same job lock.-Configured PostHog receives `training_result_available`, `training_check_finished`-and `training_checkpoint_available` after transaction commit with stable event IDs.-Events contain project/job/check IDs, counts, measured timing and explicit resume-availability, not labels, text, error messages or artifact paths. Delivery is-best-effort, bounded and nonblocking; database receipts remain authoritative.-Blank `POSTHOG_PROJECT_TOKEN` disables delivery, including local self-host defaults.-Analytics elapsed time is measured after commit; receipt times are recorded before-commit and are not a guarantee that another client could already read them.-The earliest result event per job measures server availability, not user comprehension;-unobserved-time attribution and explicit human feedback remain separate work.--`training_quality.py` derives versioned classification assessments during receipt-collection, never on reads. It validates frozen labels, policy identity, confusion-counts, scored supports and accuracy before comparing with the same scored subset's-majority-label baseline or noting represented labels without predictions. Original-worker metrics, findings and receipt fingerprints remain unchanged. Missing or-inconsistent counts are inconclusive. Late duplicate collection can add this-separately attributed assessment without replaying work; stable IDs deduplicate-findings. No automatic training action follows. Compact MCP summaries retain the-latest generation check independently from loss-only checks, ordered by attempt-then step; detailed checks retain complete denominators and provenance.--## Serving and weights--`services/operational_progress.py` stores project-scoped `OperationalRun` attempts-and append-only events. Domain controllers, not status reads, collect provider-events. `provider_progress.py` copies the serving journal into the database with-durable cursors. `modal_shared/operational_events.py` publishes bounded-time-measurements; unavailable delivery does not fail or replay GPU work. Shared-pool-startup observations are not tenant-adapter attestation. Preparation and training-retain their existing row/stage/heartbeat sources in the shared observation model.-MCP `inspect_operation` pages history; inference result resources support content-offset/limit paging. Captured history is durable; absent provider instrumentation-and dropped publications remain explicit rather than reconstructed.-Collection backlogs survive terminal jobs and drain in background for up to one-hour after the last active observation. Engine health waits publish process-liveness without advancing the work counter. Failed publications and dropped-events are separate facts. Exported row counts never measure upload completion.--MCP inference uses `services/inference_requests.py`: save project request key,-input/routing fingerprint and payload before dispatch, then the 15-second controller-claims, submits or observes the existing Modal call. The worker publishes its-request-to-call mapping before inference, enabling acknowledgement recovery. A-client reconnect never owns execution. Unknown submissions are never reissued;-an expired observation deadline is unresolved, not proof of provider cancellation.-Unresolved requests remain eligible for five-minute reconciliation without-resubmission; terminal receipts recover missing usage records without another-provider call.-The ordinary application completion API retains its streaming/synchronous contract.--`services/model_activation.py` owns making a ready deployment live. REST `active_model` writes and MCP `set_active_model` persist a per-capability `ModelActivation`; the 15s deployment reconciler advances checking, waking/verifying via the existing `pre_warm` handle, and atomic routing switch. Until verification succeeds the previous target serves. Claims expire after 45s, transport errors retain the remote handle, and activation has a 50-minute deadline. Failed activation is retried through the same selection operation; duplicate in-progress selections are idempotent, competing selections are rejected, and clearing routing invalidates the operation generation. The capability retains its previous selection for verified switch-back. First/last application request timestamps only advance on successful API-key calls to the capability alias, excluding optimiser traffic and requests begun before the current switch. Internal probes and pinned calls never confirm alias integration.--`services/inference_metrics.py` supplies REST and MCP deployment metrics and activity. Both surfaces share `period` (1h, 24h, 7d, 30d, all) and `source` (application, all) filters; API defaults remain all time/all traffic, while the Console defaults to application traffic in the last 24 hours. The same selection applies to totals, failure counts, cost coverage, latest request/failure and chart buckets. Empty time buckets have zero requests and null latency; successful end-to-end timings include cold requests. Percentiles use the most recent 5,000 measured successful calls (per bucket for activity). Failed calls count as requests but do not contaminate successful latency distributions. Historical end-to-end timings and traffic sources remain unknown. `services/inference_live.py` reads Modal stats from the parameter-bound worker method without invoking inference. Pool identity includes base identity, GPU/image, context and LoRA rank; LoRA deployments use the shared base name. Counts are cached for 5 seconds and remote reads have a 10-second deadline. Recent successful inference (including deployment/activation verification) and gateway warming stamps remain fresh on every read. Zero measured runners means asleep; unavailable measurements remain unknown. Class-wide counts cannot establish one deployment's warmth.--`services/serving_context.py` estimates the pinned evaluation workload (including the capability prompt and reference-output headroom) independently of training `context_length`. Model recommendations with an eval dataset and REST/MCP launch share the serving plan. Estimated context overflow warns without excluding a candidate or rejecting launch. The plan respects native context without assuming RoPE scaling and still validates single-GPU capacity. Deployment and base-model evaluation use the plan; all before/after calls reserve the same output budget. A shared baseline grows only from a settled deployment state. Existing ready fine-tunes are not silently reconfigured.--`modal_shared/context_budget.py` supplies a positive default output reservation and rejects prompt truncation. Both streaming and non-streaming serving enforce it; vLLM validates the exact templated input plus reserved output before generation. MCP `run_inference` uses the same default reservation (8,192 tokens) when `max_tokens` is omitted or null, passes explicit positive integers unchanged, and returns non-retryable `context_length_exceeded` errors for requests that do not fit. Core LLM calls preserve finish reasons and reject token-limited responses before parsers or tool executors consume them. Eval runners retain the partial answer and usage and mark the row degraded; degraded rows are excluded from trusted scores rather than scored as zeros. Finalization synchronizes training-eval status explicitly; degraded runs cannot become successful training-quality comparisons. MCP inference returns finish reason, model truncation and response-content clipping separately.--The MCP deployment resource exposes current `worker` state and measurements through `inference_live.worker_status`, independently of deployment readiness, alias selection and historical metrics filters. It uses the Console's cached pool measurements and recent traffic/warming stamps without invoking inference. Unavailable counts stay null; state remains unknown unless recent successful traffic or a warming stamp supplies evidence.--Training jobs and eval sets may have no capability. Training still requires an eval dataset-and an eval set with at least one enabled matrix row; a job without a capability can also-select a ready trained benchmark. Unassigned eval sets are project-scoped and cannot be activated.-REST `POST /api/eval-sets/` and MCP `create_eval_set` share the serializer that validates `rows`.--Training has four persisted evaluation choices: `eval_incumbent_before/after` and-`eval_model_before/after`. The training model's before target is its untouched base;-after is its ready trained deployment. The training setup's **Benchmark model** selector-chooses the codebase incumbent or a ready, project-scoped trained model for this run.-REST and MCP `start_finetune` accept its serving model ID as `baseline_model`; the choice-is immutable once the job is created and never changes `active_model` or serving.-Omitting it uses the capability's separate `benchmark_model` default (set through MCP-`set_benchmark_model`), or the codebase `model` when that default is null. The Console-defaults to the codebase incumbent and sends its selection explicitly. New incumbent-evaluations reject an unavailable selection. The capability Models tab only selects live routing.-Every foundation entry in `models.json` carries an explicit nullable `openrouter_id`.-The shared resolver searches the cached OpenRouter catalogue by that mapping, then-exact model/checkpoint identities (including declared benchmark aliases), never fuzzy-names or another model size. Chat models retain their existing core registry slugs.-MCP and REST training catalogues expose `openrouter_id` and `openrouter_status`:-`available`, `not_listed`, or `catalog_unavailable`. A retained ID alone does not prove-availability; null mappings can resolve when an exact checkpoint becomes listed.-When configured and matched, before evals use OpenRouter ahead of an unused ready-hosted base. Unavailable models/catalogues retain the provider/Modal fallback.-A started evaluation or unresolved attached deployment pins its route; refreshes-do not switch live evaluations or duplicate in-flight deployment work.-Defaults are untouched-base-before + trained-after; incumbent comparisons are-separate opt-ins. The matched base is the preferred delta reference. All four can be off, but the eval-dataset and eval set remain required. Baseline evals launch as independent jobs alongside-GPU training; their completion and failure do not gate training. Retries retain EvalRuns-but detach failed baseline-eval links. After evals start once training finishes.-The same pinned eval cell and frozen matrix are reused across the job's evaluations, all in one run group.-Generate targets snapshot the capability prompt in params, injecting it only when-the row has no system turn. They evaluate the raw model with recorded context, not-the live application. Every selected training evaluation uses all rows of the pinned-version, with no row cap or sampling; shared group baselines must also cover all rows.-Automatic intermediate-checkpoint judging is replaced by this explicit schedule;-historical checkpoint results remain readable. MCP `start_finetune` accepts all four-choices and the fine-tune resource returns `evaluation_plan`.-The Console projects selected evaluations into waiting rows immediately and replaces-each by kind when its run arrives. Loss-curve polling continues after deployment while-evaluations remain pending. `services.deployment` persists each deployment's stage,-remote call handle, generation, retry budget, deadline, and evaluation waiters.-The single 15-second deployment controller covers training outputs and baselines.-A finished stage starts the next remote call before the claim is released. The S3-checkpoint archive is spawned beside that sequence and does not gate readiness.-Short IO tasks claim a row for 45 seconds. Worker death reconnects to the saved call rather than restarting GPU work. Each-attempt has a four-hour deadline and at most three confirmed-failure attempts with-30/60-second backoff. Transport errors retain the handle. Submission without a saved-acknowledgement fails closed; never launch another call until remote state is resolved.-Failed baseline deployments notify waiting evaluations even without a remote handle-or while cancellation is pending. Baseline stage progress is mirrored to the training-job while it runs; eval score updates merge into freshly locked progress.-Base preparation always uses `fetch_base_model` before publishing/merging and booting.-Cancelled jobs and superseded generations cannot become ready; terminal notifications-and remote cancellation are durable work too. Explicit retries reset the generation-and budget without losing checkpoint metadata. Training remains successful if only-deployment fails; the dependent evaluation is marked failed. REST and MCP share the-retry service and expose stage, attempt, retry time, deadline, and last error.-The deployed-model list includes only deployments linked to training jobs, before-pagination and filtering. Baseline eval infrastructure remains addressable by ID-but is excluded from the Console's model lists and counts.--Training recommendations classify the selected capability's recorded codebase context-(`codebase.task_type`), cached by context fingerprint. Task type drives benchmark skill-weights; dataset stats still drive context/tool compatibility, hyperparameters and cost.-With no selected capability, use the dataset's stored semantic task or profile heuristic,-even if the dataset has a capability mapping. An unclassifiable selected capability stays-unknown and ungraded; it does not fall back to the dataset. Console and MCP readiness use-the same recommendation service; an uncached capability classification may call an LLM.--Training mode is separate from task type. Native decision recommendations use the-selected capability or an existing semantic dataset classification; chat-output-heuristics cannot establish their task. Missing classification stays unknown. Native-model eligibility follows the validated decision format, independently of the task-label; chat benchmark grades remain unavailable for native probability training.--- Serving splits by finetune shape in `deployment.serves_as_adapter`. A dense or explicitly supported MoE Modal-trained LoRA is served as an adapter on a shared BF16 base — `publish_adapter` copies the adapter, and every deployment on that base shares one container pool, so a second adapter deploys in seconds. Everything else (full finetunes, unsupported MoE, non-Modal providers) is merged and quantized into a private checkpoint. The shared base must stay BF16: an FP8 base measurably degrades adapter quality. MoE models (`"moe": true`) require verified `inference.lora_supported` in `models.json`. Qwen3-Coder uses native mixed-format MoE LoRA with the fused expert format declared at adapter load; weights remain separate from the BF16 base. Shared workers resolve the family from the sealed base manifest. `inference.min_vram_gb` enforces measured GPU capacity floors; Gemma 4 E2B and E4B require at least L40S. A deployment whose stored GPU is below that floor is raised before the next boot.-- Base weights live in exactly one place: `.base_models/{org--model}` on the weights Volume. `fetch_base_model` is the only writer and a global mutex (`max_containers=1`), so concurrent callers cannot corrupt a shared dir or download twice. Celery waits on that Function (`.remote()`) before spawning a GPU train job, so a cold base downloads on CPU. Training then loads `BASE_MODEL_PATH` and fails if the snapshot is incomplete — no Hub fallback, no AWS for bases, no catalog prewarm.-- Nothing on the `overmind-sft` Volume is read at serve time — GPU workers mount weights and vllm-cache, plus inference-artifacts for shared-base LoRA. `tasks/cleanup_modal.py` sweeps it daily, ages run dirs with no `FinetuningJob` row off the Volume's own mtimes, and drops `runs/{run_id}/final/` once the deploy has landed (a READY deployment means the serving copy is on the weights Volume and a confirmed S3 archive covers a rebuild). The same beat drops spent `/weights/.staging/{id}/` trees. `stage_modal_checkpoint` and `publish_adapter` fall back to `download_checkpoint_from_s3` when the checkpoint is absent — the one place an S3 round trip is allowed, never the first deploy. Both delete the job's staging dir as soon as the serving copy is written.-- Shared-base LoRA workers use a separate `{gpu}_{image}_lora` class for every existing GPU/image pair; the selector is unchanged. `fetch_base_model` hashes and seals `.base-manifest.json` once, then validates its file identities on reuse. The base digest participates in the container parameters. Snapshot capture initializes vLLM and CUDA graphs, exports adapter-free runtime-layout weights to immutable generations on `overmind-inference-artifacts`, caches parsed headers, and uses level-2 sleep to omit large weight backups. Artifact identity includes base, effective serving arguments, GPU, image, loader source and runtime versions; it is not portable across arbitrary engine profiles. A new LoRA on a compatible base/profile reuses these assets.-- Restore refreshes the Volumes, validates identities, wakes weight allocations, streams 2 GiB shards in manifest order into native pinned buffers, copies into the original CUDA graph addresses, resets empty LoRA banks, then wakes KV memory and checks health. LoRA images pin Run:ai 0.16.1; one reader uses 16 native threads, eight Torch threads and an 8 GB buffer for bases up to 80 GB, otherwise 16 GB. The pin is required by the upstream allocation site. Snapshots contain no tenant adapters; adapters are attached after restore under the existing lock. Lifecycle failures are recorded and surfaced on the input, not raised from `enter` into an endless retry. Internal sleep/reload/adapter-control endpoints cannot be forwarded through public inference methods.-- Full-checkpoint workers retain their non-snapshot startup and compile-cache persistence. Only those concrete classes own the normal post-snapshot startup hook: putting it on the common base causes Modal to run it alongside the LoRA restore hook. `pre_warm` still verifies a deployment before READY; for LoRA it also completes first-time artifact/snapshot preparation. `CUDAGRAPH_CAPTURE_SIZES` and GPU selection are unchanged. The Modal gateway and Django SSE write idle pings immediately and every 15s; Django non-stream completions wait up to 15s for a result before starting newline keepalives. Playground SSE retains its keepalive. The edge ALB drops idle connections after 60s. Early non-stream errors return 400/502; after a keepalive commits headers, Django aborts an incomplete JSON response so clients raise a transport error. SSE failures use an error frame. Requests carry X-Request-ID, and failures and end-to-end timing are recorded alongside engine timing. The Django client rejects upstream JSON errors and consumes SSE lines without byte-buffer accumulation. GPU scheduling remains outside the loader's control; no cold-start SLA is implied.--### Native decision serving--Training completion always enters the shared deployment controller, including-native decision jobs. `DeployedModel.inference_contract` separates chat from typed-probability serving. Native deployments pin `serving_runtime`, recorded training-GPU/context and the verified artifact identity. The release-pinned-`overmind-decision-serve-*` app copies the complete immutable adapter/head artifact-to the weights Volume and loads it through the same decision encoder/readout.-Workers never read the training Volume during inference. Publication checks the-artifact and base identities; READY requires a successful probability prediction.-There is no chat-gateway registration or implicit capability activation.--REST `POST /api/deployed-models/{id}/inference/`, request polling and MCP-`run_inference` share the durable inference-request service. Input-only decisions-exclude targets and generation parameters; output retains original option order-and artifact identity. Existing request keys recover receipts without another-provider submission. `deploy_finetune` can backfill successful historical jobs;-existing deployments are reused and failed/deleted deployments require explicit-retry. Native comparisons remain independent batch measurements.--### Native decision training--`DecisionJob` supplies a separate public UUID over a one-to-one `FinetuningJob` run. Its status, preparation, monitoring, cancellation, billing, provider recovery and verified deployment come from that run. REST and MCP return both IDs, and explicit preparation links a decision setup job before launch. The decision catalogue names Clef, D3 and D1 families. Clef uses the qualified shared runtime; D3 and D1 are discoverable but cannot launch until their family-specific preparation, checkpoint and serving contracts reach the same standard. Historical jobs from the retired independent lifecycle remain in `DatasetHistory` rather than being treated as new shared runs.--`training_labels.prediction_labels` supplies `record.prediction_labels` to REST detail-and the MCP finetune resource. It projects distinct questions, ordered options and-declared score axes from the checksum-verified pinned cell, checking launch selection-identity when recorded. The cache binds cell, fingerprint and file stat; full-source-queries return at most eight complete label sets within 12 KB, with total coverage-explicit. Missing or unreadable data stays unavailable; chat runs return null. This-read path never invokes a model or derives labels from target argmax.--A train cell may carry a `decision` object instead of assistant-bearing messages. `modal_shared/decisions.py` validates state, question, kind, runtime options, full target distributions and positive weights. The measured contract freezes the objective. The separately pinned `u2026_10_3_decision` image supplies Unsloth `FastDecisionModel`, `DecisionTrainer` and the Clef joint schema head, with `UNSLOTH_COMPILE_DISABLE` set because Unsloth's default block compile does not finish a Qwen3.5 decision step. Qwen and Llama chat training use `u2026_10_7` (Unsloth 2026.10.7 / Zoo 2026.10.7, transformers 5.17, TRL v1.10.0); other conversational families keep their existing stacks. `modal_shared/decision_encoding.py` maps the product request to upstream encoding, retains exact token/question/option spans and maps sorted choice and true/false outputs back to the requested option order. Targets never enter the encoder. Oversized inputs fail without truncation. Preparation fingerprints retain exact supervision and processor identity.--`SupervisedDecisionTrainer` delegates model setup, optimization, scheduling, precision and recovery to Unsloth. Its loss extension preserves complete distributions, nonuniform weights and mean-only ordinal targets. Accumulated losses share the actual optimizer batch's total weight, including partial batches. Mean targets use normalized-axis expectation error without invented distributions. Predictions retain full probabilities and stable log probabilities.--Decision artifacts contain the adapter, full-precision joint head, both upstream head/config files, tokenizer and `decision.json`. Every trainable tensor must be covered by the saved adapter or head. Training and prediction pin SDPA explicitly, including nested text backbones, so upstream trainer cleanup cannot switch the attention implementation. The head uses native PyTorch LayerNorm with FP32 normalization and output dtype restoration, avoiding compiled first-call numerical changes and changing checkpoint recomputation graphs. The Unsloth head architecture, encoder kernels and activation checkpointing are retained. Retained checkpoints publish atomically after exact tensor reload and nonempty probability verification at 0.0001 absolute tolerance. Final publication repeats verification in a fresh process. Worker receipts classify probability and weight reload failures without exposing raw worker logs. Trainer recovery includes optimizer, scheduler, RNG, progress and a base/data/runtime/recipe signature, with a checksum receipt written after a complete save; incomplete later saves cannot hide the last complete checkpoint. Catalog eligibility, runtime qualification and held-out quality remain separate evidence. Native artifacts do not enter chat evaluation or deployment. The supported method remains one-GPU Modal LoRA.--Preparation and training reuse the shared exact token artifact and monitoring lifecycle. `decision_artifact.py` seals verified adapters and heads with relocation-independent checksums. Provider retries return an already verified published artifact without optimizing again. Native validation exposes distribution CE/Brier, applicable hard-label accuracy and mean error with separate denominators. Categorical assessments compare explicitly declared gold-label families against their same-subset majority baseline; soft targets and mean-only targets never become categorical labels. MCP retains the latest decision-quality check independently of later loss-only checks.--Native `hyperparameters.pre_training_baseline` is a strict boolean, default true. False skips only the starting-model development evaluation; development checkpoint selection, post-training validation, reload verification and separately scheduled benchmarks remain independent. The Console checkbox, MCP recipe and saved variants share the choice. Launch/effective receipts, resume signatures and forecast recipe matching retain it; worker telemetry reports `not_requested` rather than a score when disabled.--Training progress keeps cumulative optimizer steps and token counts, but throughput and ETA use only work since the current attempt began. Native recovery supplies the restored token count to `ProgressCallback`; attempt starting counters are emitted with its memory event.--The release-pinned `overmind-decision-eval-*` Modal app prepares input-only benchmark records on CPU, then runs the Unsloth encoder/head with either the complete saved artifact or a freshly initialized head on the unchanged foundation. Reference distributions never enter that worker. It writes full probabilities, stable log-probabilities, input hashes and model identities. Preparation records incompatible inputs explicitly. `decision_metrics.py` scores full distributions; mean-only ordinal references receive expected-score errors rather than invented NLL/Brier. MCP, REST and Console native comparisons use this worker through the same durable services. Native comparisons are separate from chat `EvalRun` and live inference deployment.--## Reproducible training experiments--`training_record` freezes dataset selections, objective, user-accepted findings and requested configuration. `request_key` is unique within the project; creation locks the project and dataset selections in one transaction. Reusing a key and recipe returns its job without dispatching again. A different recipe under the same key conflicts. Effective provider settings are recorded separately; explicit context, batch, packing, dropout and seed must be honored or rejected, never silently clamped.--`training_release` requires an explicit Modal environment. `modal_shared.training_release` hashes the worker, shared modules, data format and training assets into an immutable app name. Preparations and jobs pin that identity; retries and observers use it even after API configuration changes. Deploying an identically named release with different code is unsupported. Existing unpinned jobs require a verified runtime reconciliation before adopting this release; never deploy this API over an active unpinned run.--CPU preparation writes closed token shards, source offsets and checksums. A restart verifies source, tokenizer and committed shards before reuse; uncommitted work is regenerated. Initial JSONL transfer is gzip compressed; the training handoff sends ordered 32-byte row keys and validates the original token artifact. Repeated observations and external validation selections survive materialization unchanged. This is shared by conversational and decision training.--`training_submission` journals intent and run ID before provider submission. Lost acknowledgements enter `submission_unknown`; the reconciler uses the saved run's provider call metadata and pinned release. It never dispatches a second trainer while ownership is unresolved. If worker inventory confirms a Modal staging task is absent and no GPU dispatch intent exists, it requeues the same job and retains the interrupted intent in its progress history. Attempt identities fence late staging owners from dispatching after recovery. Provider telemetry records stages, heartbeat, counters, attempts, checkpoint and verified restore separately. The no-progress observer compares native stage, completed-work, attempt and checkpoint/restore counters as well as optimizer metrics. Advancing validation or reload stages reset its stall window; a background commit heartbeat alone does not. MCP returns the most recent bounded metrics with truncation metadata. An observer outage is separate from job failure. Volume retention uses the current explicit release and protects run IDs from unresolved submission receipts. Native forecast matching uses the recorded effective GPU/count, never a retrospective hardware guess from the current planner.--`NativeEvaluationPlan` supports standalone comparisons or a paired training-job comparison and freezes native-only calibration and final cells, exact overlap receipts, runtime, bootstrap seed and calibration recipe. REST `native-evaluation`, MCP `schedule_native_evaluation`, resources and Console share `services.native_evaluation`. Beat dispatches bounded `batch` tasks; the plan journals every paid call, retains uncertain intents and resumes saved call IDs. Verified artifact/reload is checked by the native worker before prediction. Calibration preparation/base/candidate/fit precede final preparation/base/candidate/scoring. New plans fit global then per-kind Clef temperature scaling with local L-BFGS-B, retaining distribution targets and minimum-sample rules. Historical frozen grid recipes remain readable. References remain local. All expected decisions remain in denominators, including incompatible inputs; missing/invalid predictions prevent calibration fitting. Exact overlap checks do not prove absence of paraphrase or pretraining contamination. Quality warnings do not rewrite labels or veto accepted experiment risk.--Matched native forecasts use completed execution duration for the same project, model, training/processor/data identities, hardware, recipe and approximate character-length profile. Native omitted packing matches the unpacked launch default; explicit step limits must match. A supplied native recipe epoch count takes precedence over the generic estimate default. Evidence and rejection reasons are returned. Workload scaling uses the same source-character estimate on both sides and is limited to 0.5–2x. One or two observations receive low confidence and an explicit 0.5–1.5 planning margin; three or more use 0.8–1.3. These are planning ranges, not statistical intervals. An unmeasured recipe reports unknown duration and total GPU cost, separately from the current GPU-hour rate. Forecasts expose price/duration status and estimate blockers, and multiply duration by the same fetched rate-card snapshot; historical charges are never reused as current rates. Native timing exposes elapsed time and a remaining-time range after five recent step intervals spanning 30 seconds. The range covers the elapsed-time average with a 0.8–1.3 planning margin and widens for observed step-time quantiles; it is not a confidence interval. It resets on attempt restart and is absent during final validation/reload. MCP and the monitor do not turn it into a single countdown or finish timestamp; the monitor rounds range endpoints outward to minutes. `compute_costs` prices worker usage receipts with workspace rates fetched from `modal.Workspace.billing.rates` (five-minute cache, eight-second timeout, no static-price fallback). Training, preparation, native evaluation and native performance report CPU/memory/GPU estimates separately from recorded ledger/API charges; cumulative worker observations are deduplicated and recorded training GPU is never added twice. CPU and peak-memory observations are proxies, not provider meters. Modal workers use process resource counters because cgroup mounts are unavailable. Reaped child CPU is included; live child usage is incomplete until exit, and summed process memory peaks can overestimate simultaneous use. Missing receipts/rates remain unknown, and image boot, later idle, storage, network, local orchestration and provider adjustments remain excluded. No all-in invoice or spending cap is claimed.--Native comparison database results retain aggregate and per-benchmark metrics. Per-slice diagnostics remain in the complete downloadable report, whose checksum and byte count are stored in the scoring receipt. A paused comparison can explicitly resume an interrupted local `verify_inputs`, `fit_calibration` or `score` stage; the previous lease is fenced and saved inputs are reused without provider resubmission.--`native_evaluation_monitor.py` maintains a local SQLite sample projection beside-each sealed suite. The evaluation worker publishes immutable, checksum-bound-chunks of flushed predictions and stage/count timestamps every ten seconds,-under its exact provider call ID. The existing collector verifies call, runtime,-input and artifact identities before ingestion. Repeated observations are-idempotent; publication failure does not fail or replay inference. Preparation-incompatibility, invalid outputs and missing results remain distinct. Scoring-uses the existing decision metric contract with each metric's own denominator.-Calibration is applied only after the calibration receipt is frozen.-REST `native-evaluations/{id}/monitor` and MCP `inspect_native_evaluation` read-bounded sample pages and recorded summaries, without provider reads. Missing-historical indexes are built by `native_evaluation.refresh_monitor` on `batch`-from retained predictions and their checksums, never a new inference run.--## Data-first model workflows--### Evidence-linked training plans--`training_plans.py` saves immutable `TrainingPlan` snapshots via shared REST and-MCP. Strict `training_plan_contract.py` defines task, attributable evidence and-pilot selection. Saved source/prepared/partition identities are frozen. A quality-pilot binds an experiment to those identities, with explicit bounded steps and-development-loss selection when a pilot is requested. Full experiments require-audit/baseline/sanity reports but no pilot job or pilot selection. Optional pilot-selection requires a measured task metric from a matching settled pilot's fully-scored development check with a verified checkpoint; when supplied, only declared-exposure/time fields can change from that recipe. Final/calibration data never-selects a recipe. Launch-rechecks bindings and records the snapshot in requested configuration. Changed-upstream identities need matching evidence; historical snapshots remain readable.-This is not a universal semantic-approval gate for exploratory jobs. Hardware-profiles and forecasts remain separate from task-quality evidence.--Onboarding can create a project directly for uploads; `Dataset.brief` retains the original task. Workshop exploration proposes per-family meaning with `target_evidence`; structural shape never supplies reference truth. `decision_supervised` combines distribution cross entropy and normalized-axis mean-squared error for mean-only ordinal targets. Their denominators stay separate in evaluation.--`datasets/partition_plans.py` saves seeded role fractions, grouping, stratification and explicit holdout rules. It writes durable assignments and derived source cells, retaining every observation and inherited identity. Typed training `decision` and evaluation `input.decision` share the same input-content key. Group/content checks report exact overlap only. Scientific overlap findings remain advisory.--`native_evaluation.py` serves standalone multi-participant comparisons; `decision_providers.py` owns the supported System One adapter and durable request/response ledger. `training_experiments.py` validates explicit candidates with the existing training serializer and dispatches them under their saved group. `decision_checkpoint_policy.py` constrains retention and last/development-loss selection. Retained artifacts publish atomically after nonempty reload verification. `decision_performance.py` uses a separate native measurement worker or the qualified external snapshot, with saved call IDs, bounded input workloads, measured client latency and partial cost amortization. Catalog eligibility, exact preparation, observed hardware execution, reload and quality are separate evidence.--New tasks route partitions to batch and evaluation/performance advance to batch; their reconcilers use control. Native evaluation reconciliation also recovers undispatched experiment jobs. Unknown acknowledgements remain explicit and successful work is reused. No production activation occurs. Historical native plan migration preserves calls, predictions and calibration, including the original unfloored scoring contract.--The public MCP catalog adds partition creation/retry, native comparison creation/resume, experiment save/launch, performance measurement/resume and model/workflow discovery. `get_job` and project-scoped job resources expose complete protocols and reports. `develop-model-from-data` guides the same lifecycle. The bounded manifest budget is 50 KiB for 50 tools (previously 40 KiB for 40); secrets and output schemas remain absent from discovery.--### Durable data-first mechanics--`datasets/exploration.py`, `training_experiments.py`, `native_evaluation.py` and `decision_performance.py` own shared REST/MCP lifecycle behavior. Expensive source verification and experiment planning run on batch workers with short database claims. Native comparisons separate draft, preparation and authorized launch; each ready arm has its own lease and receipt, and calibration remains a barrier. The periodic reconciler repairs missed continuation. `evaluation_inputs.py` binds durable chunk offsets and digests to the sealed manifest. Explicit compatible prediction reuse retains source lineage and zero incremental prediction calls. Performance can qualify independently before final quality results; snapshot changes remain failures. Training profiles are bounded attempts with representative native length coverage and no default monetary cutoff. Planning constraints bind quote and launch configuration and cannot be described as an invoice cap.--Training experiment validation names the variant and field requiring correction. Prepared reports expose `launch_readiness` against the saved training constraints; unmeasured or over-budget quotes do not recommend launch. Launch rechecks the same authorization. Every routed or scheduled task must be registered by a fresh worker importing `overbae.tasks`; the cold-start topology regression prevents test imports from masking missing task registration.--A paused native evaluation collector can resume an explicit stage with its exact recorded `call_id`. Missing or different IDs are rejected; recovery fences the interrupted lease and observes the same provider call without a new submission.--Native evaluation transient stage failures automatically enter `retrying` while the-plan remains `running`. Durable `retry_at` and recovery history drive 15/30-second-backoff with three consecutive attempts; independent eligible stages continue.-Native collection reuses its saved call and local stages reuse frozen inputs.-External read-only prediction timeouts, capacity outages and 429/5xx responses-retry only missing rows, at most three attempts per input, preserving unknown-costs in the attempt ledger. Saved responses are consumed first. Bare submission-intents, unacknowledged native launches, invalid data/identity and permanent errors-do not auto-replay. Paused plans stay paused; explicit resume honors request budgets.--Exhausted/permanent collection errors settle the affected work and allow scoring-of available verified predictions. External failed rows do not block later chunks;-native partials use checksum- and identity-verified retained monitor predictions.-Failed preparation skips dependent provider submission. Incomplete calibration-is unavailable per arm; final raw scores continue, with calibrated comparisons-only for fitted pairs. Results and reports expose `completion.status`, per-suite-coverage and issues; partial results are `completed_with_issues`, never silent-success or zero-filled scores. Input verification and report failures still stop.-Orphaned external intents are retained as `submission_unknown`, excluded from-scoring and never replayed; the collector continues subsequent inputs. Resuming-a paused external stage fences its interrupted lease without requiring a native-call ID. Native unknown submissions still require their original call ID.+- `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.+- `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/`.+- `tasks/` — Celery tasks, roughly one module per feature; `utils/task_lock.py` for locking.+- `modal/` — Modal app entrypoints (vLLM serving, SFT, native decision evaluation and serving) and `models.json`. Code shared by those workers and the API lives in the root `modal_shared/` package.+- `management/commands/` — `seed_demo` (seed-demo-data skill), `grant_credits`, `check_workshop_transition`, `sync_baseten_finetuning_costs`.++## Patterns every subsystem follows++- **One domain service, three surfaces.** REST, MCP and the Console call the same service. Never copy business logic into a view or an MCP adapter.+- **Request keys.** An operation that starts work takes a project-scoped `request_key`. An identical retry returns the original record; a changed payload under the same key conflicts.+- **Durable admission.** Waiting work lives in PostgreSQL rows, and a locked dispatcher admits it with per-project fairness. Do not park waiting work in the broker.+- **Unknown provider outcomes are reconciled, never resubmitted.** Intent is journaled before a provider call; a lost acknowledgement becomes `submission_unknown` and is resolved from the saved call ID.+- **Measured, not invented.** Missing usage, progress, scores or telemetry stay unknown or null. Never fill a percentage, a zero score, an ETA or a cost from elapsed time or a guess.+- **Status writes use `.filter().update()`.** No Django signals fire; reload the row and wire side effects at the call site.+- **Model IDs**: platform models (judges, generation, Jev) live in `core/model_registry.py`; the training and serving catalog lives in `modal/models.json`, read through `modal/model_registry.py`. Jev decisions go through `core/decisions.py`.+- **Modal code ships separately.** Changes under `overbae/modal/`, `modal_shared/` or `services/sft_assets/` reach running jobs only after `modal deploy`; training and serving pin immutable releases.++## Reference files++Read the one that matches the task:++| File | Covers |+| ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |+| [references/celery.md](references/celery.md) | Workers, queues, routing, admission, deployment order |+| [references/tracing-and-scoring.md](references/tracing-and-scoring.md) | Span model, OTLP ingest, span cost, live scoring, signals, Jev |+| [references/evaluation.md](references/evaluation.md) | Evaluation runs, comparison, judges, context estimates, benchmark selection |+| [references/capabilities.md](references/capabilities.md) | The agent graph, scans, toml sync, Default eval set, provenance |+| [references/auth-and-billing.md](references/auth-and-billing.md) | Clerk and local auth, guests, API keys, billing, Overwatch internal endpoints |+| [references/training.md](references/training.md) | Preparation, launch, monitoring, transfer, native decision training |+| [references/serving.md](references/serving.md) | Deployments, shared-base LoRA, activation, inference requests, operational receipts |+| [references/data-first.md](references/data-first.md) | Training plans, partitions, native evaluation, experiments, performance runs |diff --git a/.agents/skills/backend-architecture/references/auth-and-billing.md b/.agents/skills/backend-architecture/references/auth-and-billing.mdnew file mode 100644index 00000000..9e3d3e58--- /dev/null+++ b/.agents/skills/backend-architecture/references/auth-and-billing.md@@ -0,0 +1,34 @@+# Auth, tenancy and billing++## Auth++Clerk when `CLERK_API_SECRET_KEY` is set. A blank secret means self-hosted local JWT: `POST /api/auth/local/`, email and password, create on first use, no verification. The Console shows the local form when `VITE_SELF_HOSTED=true` or `VITE_CLERK_PUBLISHABLE_KEY` is blank (`frontend/src/config.ts`). ChatGPT login, account linking and stored provider credentials are removed.++Tenancy is project-scoped (`User` ↔ `Project` through `ProjectMembership`), with no org layer. Every queryable model is filtered by project.++- **Guests** (`User.is_guest`, `POST /api/auth/guest/`) hold one project and can read and claim. `GuestJWTAuthentication` refuses other writes with `guest_upgrade_required`. A view that accepts guest writes opts in with `guest_allowed = True`, never with a permission class or middleware: a view's own `permission_classes` replaces the defaults. A claim (Clerk only) moves memberships and deactivates the guest. The daily `tasks/guest_cleanup.py` sweep deletes claimed (inactive) guests at its next run, unclaimed guests 7 days after they joined, and their guest-only projects.+- **Invites**: with Clerk an email is sent; without Clerk the `ProjectInvite` row is claimed on the first sign-in for that email.++## API keys++`scope=account` (every project the user belongs to) or `scope=project` (one `resourceIds` entry). REST and MCP `create_api_key` share `APIToken.create_for_user` and the Console dialog's fields: name, description, expiry of 30, 90, 180 or 365 days, or 0 for never. MCP omits `project_id` for an account key. The plaintext is returned once. Over MCP, a project credential cannot mint an account key; guests cannot mint keys. MCP OAuth credentials work only on MCP (mcp skill).++## Billing++- Ledger charges always run. Remaining-credit 402s, the Free seat limit and Stripe Checkout apply only when `STRIPE_SECRET_KEY` is set (`services/billing_provider.py`); otherwise spend is recorded and shown, and gates and grants are no-ops.+- Native-agent model choice and funding belong to the coding-agent environment. Training, evaluation and serving keep their own billing.+- Compute estimates use live provider rates with fetch timestamps (`services/provider_pricing.py`: Modal workspace rates, cached 300 s when current and 30 s when unavailable, no static fallback; `compute_costs.py` and the forecasts call it). They never create ledger charges. One quote uses one rate snapshot. Chat-training cost estimates are the exception: they use the fixed `_MODAL_H100_USD_PER_SECOND` in `finetuning_pricing.py`.+- Modal training charges use deduplicated worker usage receipts and recorded hardware, never the delay before the collector notices completion. Missing usage stays unmeasured; historical ledger entries are not rewritten.++## Overwatch (internal insights)++Overwatch is the internal user-insights dashboard. Its dashboard endpoints under `/api/internal/overwatch/*` (`api/overwatch_dashboard.py`, `services/user_insights.py`, `services/overwatch_insights.py`) are gated by the static bearer token `SALES_DASHBOARD_TOKEN` (legacy name kept for deployment compatibility). `overbae/urls.py` registers them only when the token is set at import (`tests/settings.py` sets one). The agent query endpoint is always registered and uses its own token (below).++- Each path and query is computed at most once an hour through the Django cache; responses carry `computed_at`/`refreshes_at` and forbid browser and shared caches. Internal reads have SQL and report time budgets.+- They skip user authentication, stay out of MCP and the OpenAPI schema, and exclude guests and guest-only projects.+- Overwatch only reads product records: no product models, migrations, notification ledger, periodic writer or event emitter in this backend. Notification state lives in Overwatch storage outside it. Shared backend dependency upgrades need a separate platform review.+- Optional PostHog aggregates need a project-query read key and project ID in the backend environment. The key stays server-side, and responses carry only validated aggregate event counts.+- `POST /api/internal/overwatch/agent/query/` (`api/overwatch_agent.py`) uses a dedicated `OVERWATCH_SERVICE_TOKEN` and rejects dashboard, product and staff credentials. It validates five bounded read tools (`services/overwatch_tools.py`) inside a PostgreSQL read-only transaction. POST keeps customer emails out of URL logs, and the service key cannot authenticate product writes.+- Slack Q&A runs as a separate profile in the Overlord repository; this backend has no Slack or model adapter, routes or Celery tasks for it. That profile needs its own app credentials, an explicit user-ID allowlist and a linked unrestricted internal employee (HR admins do not bypass it). Customer reports stay in private replies and never return records to the model. Overwatch must not use Overlord HR tools, conversation storage, extraction or training traces. Direct Anthropic use is off by default and needs an approved data and retention policy.++The app lives in `sales-dashboard/` because the deployment workflow and Pages project use that path. It reuses the Console's `styles.css` (relative `@import`), `public/` (`publicDir`) and `components/ui` (the `@` alias), so keep those primitives free of app-level imports. It keeps the admin token in sessionStorage for 30 minutes and clears legacy localStorage tokens. `bun run dev` proxies `/api` to `SALES_API_PROXY` (default `http://localhost:8000`).diff --git a/.agents/skills/backend-architecture/references/capabilities.md b/.agents/skills/backend-architecture/references/capabilities.mdnew file mode 100644index 00000000..b3cc288d--- /dev/null+++ b/.agents/skills/backend-architecture/references/capabilities.md@@ -0,0 +1,29 @@+# Capabilities and sync++The agent is the project itself: one graph per project, with no table. `Capability` rows are its nodes (UI "Capability"; the sidebar's "Agent" is the product).++## Identity++- OTLP ingest never creates a capability; a connector import with `auto_create` in its capability mapping creates `observed` rows. `services/capabilities/identity.lookup` resolves IDs, names and slugs through `IdentityAlias` (renames included). A span with no resolvable identity binds to its trace's capability when the trace has exactly one; otherwise it stays unbound, and `tasks/capability_rebind.py` re-binds the backlog after scans and hand-made rows.+- On OTLP spans, wire identity is `overmind.capability.id` alone; connector spans bind through the credential's capability mapping. `overmind.agent.*` attributes are not read, and `overmind.capability.name` is a display label that never resolves. The `overmind/<uuid>` model alias never changes.+- A scan never deletes. An absent capability becomes `status=leftover` and reactivates in place when the code returns; `observed` rows (made by hand or by a connector `auto_create`) are exempt.+- `DELETE /api/capabilities/{id}/` is a soft delete (`status=deleted`): the row and its data stay but are invisible to lists, scans and identity lookup, so a later scan mints a fresh row. There is no merge, split, retire or history.++## Discovery and sync++Discovery runs locally. `/overmind setup` runs `overmind chassis` (AST inventory and call graph for Python and TypeScript), writes `overmind_capabilities.json`, and conversion fills prompt spans, drops fabricated anchors and unverifiable provenance, and stamps `trajectory_map[].verified` against the chassis. `overmind sync` uploads the toml.++Tool branches and steps may carry `transitions: [{target, condition}]`. SDK conversion rejects a target that is neither a known step anchor nor `terminal`; the Console leaves a missing or ambiguous target unresolved.++Toml sync is `POST`/`GET /api/v1/sync` (API-key auth). It maps onto `Capability` (`current`/`leftover`), stores the card, prompt and matrix in `improvement_metadata`, keeps `repo_summary`, `trace_provider` and the toml `version` in `Project.settings`, and writes leftovers back with `archived = true`. Then `innermind.default_set.upsert` runs per current capability and records the result in `improvement_metadata.eval_preload`:++- seeded checks for the capability's span types (created only when missing);+- one deterministic row per toml `eval_matrix` entry that names a catalog `check` with `params` (an unknown check or constant is a 400);+- one llm row per legacy toml expectation;+- one span-scoped llm row per `expectations=` sentence on the checkout's Python `observe`, `entry_point` and `workflow` decorators. `overmind sync` reads them; setup never writes judge criteria to the toml. Tool and retrieval expectations get no synced row; they become live span-declared rows when the span reports them. A sentence the code drops loses its row on the next sync.++The Default eval set is activated when none is active. The upsert is synchronous and calls no model.++## Repository provenance++`overmind chassis` saves `.overmind/scan.json` before inspection. Conversion verifies branch, commit and a SHA-256 fingerprint of tracked and unignored files, then writes `repository_snapshot` to the toml; a changed checkout needs a rescan. Sync never recaptures Git state: it stores the snapshot in `Project.settings` and stamps `last_synced_at` separately. A push without provenance clears the old label, and missing provenance stays unknown. The Agent header and `overmind://project/current` show both.diff --git a/.agents/skills/backend-architecture/references/celery.md b/.agents/skills/backend-architecture/references/celery.mdnew file mode 100644index 00000000..f7eac5ed--- /dev/null+++ b/.agents/skills/backend-architecture/references/celery.md@@ -0,0 +1,51 @@+# Celery topology++Six workers over six queues. Workers are resource profiles; queues are fairness classes.++| Worker | Pool | Conc | Holds |+| ------------- | ------- | ---- | ----------------------------------------------------------------------------------- |+| `control` | threads | 8 | orchestration, chord callbacks, FSM advances, reconcilers |+| `io` | threads | 24 | preparation, eval launch, serving, connector polling |+| `io_traces` | prefork | 4 | live span and trajectory scoring, signals |+| `batch` | prefork | 6 | pipeline bindings, evaluation generation and scoring, partitions, native evaluation |+| `landing` | prefork | 1 | source imports |+| `interactive` | prefork | 4 | retained-package Workshop pipelines, runtime health |++Each worker consumes only its own queue. Beat runs as its own `celery-beat` service; its tasks route like any other task.++## Why the split exists++- Only prefork enforces `time_limit` and `revoke(terminate=True)`. Every time-limited task routes to `batch`, `landing`, `interactive` or `io_traces`.+- A loaded prefork child costs hundreds of MB, so wide fan-out stays on thread pools.+- Orchestration has its own lane: a chord callback stuck behind work never finalises its run.+- `run_eval_run` routes to `io` because Modal warm-up blocks for minutes.+- `io_traces` is separate from `io` so trace scoring cannot occupy preparation or serving slots.++Every prefork lane runs `--prefetch-multiplier=1 --disable-prefetch`. A reserved late-ack message is redelivered after the broker `visibility_timeout` (2 h), which must stay above every late-ack time limit.++## Routing must agree in four places++`CELERY_TASK_ROUTES`, `make worker` (one local process, so its `-Q` lists every queue), docker-compose and `docker/worker-topology.json`. `tests/test_celery_topology.py` checks that compose and `make worker` drain every routed queue, rejects a time-limited task on a compose thread pool, checks the prefork prefetch flags and the `io`/`io_traces` split in `worker-topology.json`, and imports `overbae.tasks` in a fresh worker. Nothing checks that `worker-topology.json` drains every queue; keep it in step by hand. Workers hot-restart via watchmedo on `.py` changes.++## Durable admission++Waiting work is a PostgreSQL row, admitted by a row-locked dispatcher in least-recent-project order:++- `LiveScoringWork` — spans, trajectories and signals; global and per-project caps; fenced running lease longer than the five-minute hard limit.+- `DatasetLandingWork` — one import per project, global admission follows observed landing capacity up to eight. Waiting never expires unless `DATASET_IMPORT_MAX_QUEUE_SECONDS` is nonzero. A lost started import needs explicit recovery.+- `EvalGenerationScheduler` — `EVAL_MAX_IN_FLIGHT`, `EVAL_MAX_IN_FLIGHT_PER_PROJECT` and `EVAL_MAX_IN_FLIGHT_PER_RUN`; completion and a 30-second control tick refill slots.+- `DatasetPipelineRun` is the exception: a queued run takes a per-project Redis slot or retries through the broker every 2 s, and fails after 15 minutes without capacity. The default project limit stays below the minimum interactive worker size.++A lost started attempt becomes an explicit unknown outcome. It is never repeated automatically. Queue metrics report durable backlog and oldest waiting age.++## Leases and reconcilers++Frequent beat tasks (live-scoring admission, import and evaluation dispatch, Workshop bindings, queue metrics, sweeps) set short `expires`, so a busy queue drops stale ticks; most domain reconcilers set none. The training reconciler renews a 30-second Redis lease, so a dead worker stops suppressing observations quickly. Reconciliation repairs missed terminal events from local receipts; it never polls or resubmits a provider to do so.++## Deployment++Hosted commands come from `docker/worker-topology.json`. A rollout runs migrations, verifies a healthy landing-only consumer on the new image (`overbae.worker_health <queue>`), then updates workers, beat and API. Drain old consumers before stopping them; never discard reserved tasks or revoke acknowledged provider work. Scale-in needs an explicit idle drain.++## HTTP clients++Chat HTTP clients enforce one cancellable elapsed deadline across request bodies, SSE heartbeats and retry waits. A socket read timeout alone is not a total time bound.diff --git a/.agents/skills/backend-architecture/references/data-first.md b/.agents/skills/backend-architecture/references/data-first.mdnew file mode 100644index 00000000..289f6328--- /dev/null+++ b/.agents/skills/backend-architecture/references/data-first.md@@ -0,0 +1,28 @@+# Data-first model workflows++Data-first projects start from uploaded data and the original task brief (`Dataset.brief`); repository scans and capabilities are optional. Console, REST and MCP share every service below. Reconcilers run on `control`; expensive work runs on `batch` with short database claims.++## Services++| Service | Owns |+| --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |+| `services/datasets/exploration.py` | `DataExploration`: freezes a cell for whole-source profiles or a separate derived chain; sampling never silently changes coverage |+| `services/datasets/partition_plans.py` | `DataPartitionPlan`: seeded role fractions, groups, stratification and holdouts across train, development, calibration and final roles |+| `services/training_plans.py`, `training_plan_contract.py` | Immutable `TrainingPlan` snapshots of task, evidence and optional pilot selection |+| `services/training_experiments.py` | `TrainingExperiment`: explicit variants under one job group, a shared protocol, development-only checkpoint selection |+| `services/native_evaluation.py`, `native_evaluation_monitor.py` | `NativeEvaluationPlan` comparisons of foundations, trained artifacts and qualified external adapters |+| `services/decision_performance.py`, `decision_providers.py` | `DecisionPerformanceRun` client workloads, without activation; the System One adapter and its request ledger |++## Rules++- Partitions keep exact content, declared groups, synthetic lineage and duplicate observations together. Calibration and final members have eval intent. Group and content checks report exact overlap only; they do not prove absence of paraphrase or pretraining contamination.+- Final and calibration data never select a recipe. Full experiments need audit, baseline and sanity reports but no pilot. Optional pilot selection needs a measured task metric from a matching settled pilot with a verified checkpoint.+- Experiments prepare a configuration-bound forecast before launch and may enforce user-defined planning constraints. Unmeasured or over-budget quotes do not recommend launch. Constraints are not an invoice cap.+- Native comparisons save a draft, prepare immutable suites in the background and launch explicitly. Calibration is a barrier: it is fitted (global, then per kind, by local L-BFGS-B) before final predictions, and stays separate from final scoring. References stay local and never enter a worker.+- Every paid call is journaled. Unacknowledged native submissions and bare external intents are never replayed; a paused native collector resumes only with its exact recorded `call_id`. Explicit resume of a local stage (`verify_inputs`, `fit_calibration`, `score`) fences the interrupted lease and reuses saved inputs without provider calls. Pause stops new claims; it does not cancel remote work.+- Transient stage failures retry with 15/30-second backoff, at most three attempts. External timeouts and 429/5xx responses retry only missing rows, keeping uncertain costs in the attempt ledger.+- Exhausted collection scores the verified predictions that exist. Results report `completion.status`, per-suite coverage and issues; partial results are `completed_with_issues`, never silent success or zero-filled scores.+- Database receipts keep aggregate and per-benchmark metrics; complete diagnostic slices live in the checksum-bound downloadable report.+- Benchmark workers publish checksum-bound prediction chunks under the exact call ID. The collector verifies runtime, input and artifact identity before indexing into a local SQLite projection beside the suite. Missing indexes rebuild from retained predictions, never from new inference.+- Per-label precision, recall and F1 (`view=labels`) need hard references with a fixed option order. Missing predictions and zero denominators stay distinct from wrong answers. Ordinal means never become probability references.+- Prediction reuse is explicit and never stands in for independent repetitions or performance measurements. Nothing here activates a model in production.diff --git a/.agents/skills/backend-architecture/references/evaluation.md b/.agents/skills/backend-architecture/references/evaluation.mdnew file mode 100644index 00000000..ec23eb4f--- /dev/null+++ b/.agents/skills/backend-architecture/references/evaluation.md@@ -0,0 +1,31 @@+# Evaluation++## 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.++- `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.+- `dataset.DatasetRowProcessor` scores rows with the live span evaluators and appends `EvalScore(source_type=dataset_row)`.+- 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.+- `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.++## Judges and context estimates++- `EvalRun.judge_model` freezes the explanation judge; blank uses the `EVAL_EXPLANATION` registry default. It never changes Jev. Existing runs reject judge changes. Training's `eval_judge_model` overrides it for that job's runs, and baseline sharing requires the same judge selection.+- `innermind/context.py` supplies advisory context estimates for generate targets and the judge, including reserved output (REST `POST /api/eval-runs/context-check/`, run detail, MCP readiness). Warnings never change `ready`, gate launch or remove a candidate. Unknown limits stay unverified; unknown prices are null.+- The Console creates standalone runs (`CreateRunDialog`, with judge model and context preview), relaunches and deletes runs, and creates and deletes matrix rows. Training setup carries its own judge selector and advisory warnings: selectors are tinted only for estimated overflows, undersized options stay selectable, and Start opens a short risk summary with Start anyway. Unverified and pending checks stay neutral. Nothing blocks launch or changes a model automatically.++## Training evaluations and benchmark selection++Training has four persisted choices: `eval_model_before` and `eval_model_after` (untouched base, then the trained deployment; on by default) and `eval_incumbent_before` and `eval_incumbent_after` (opt-in). An eval dataset and an eval set with at least one enabled row are required only when at least one choice is on. MCP turns `eval_model_before` and `eval_model_after` off by default for native decision cells.++- The benchmark model is a ready trained model or null for the codebase incumbent. A job snapshots it as `baseline_model`; it never changes `active_model` or serving. The capability default is `benchmark_model` (MCP `set_benchmark_model`).+- Every evaluation of a job uses all rows of the same pinned eval cell and the same frozen matrix, in one run group. There is no row cap or sampling.+- Chat-training setup can pin extra benchmark models for the same eval set and dataset; with benchmarking on, they and the selected training bases are scored before training.+- Baseline evaluations run alongside GPU training and never gate it. After-evaluations start when training finishes.+- Foundation entries in `models.json` carry a nullable `openrouter_id`. The resolver matches that mapping, then exact model or checkpoint identities, never fuzzy names or another size. Catalogues expose `openrouter_status`: `available`, `not_listed` or `catalog_unavailable`. A started evaluation or unresolved deployment keeps its route.+- Training jobs and eval sets may have no capability. Unassigned eval sets are project-scoped and cannot be activated.++API modules: `api/eval_views.py`, `api/signal_views.py`.diff --git a/.agents/skills/backend-architecture/references/serving.md b/.agents/skills/backend-architecture/references/serving.mdnew file mode 100644index 00000000..c0de21a9--- /dev/null+++ b/.agents/skills/backend-architecture/references/serving.md@@ -0,0 +1,40 @@+# Serving and inference++## Deployment shape++- `deployment.serves_as_adapter` decides the shape. A dense or explicitly supported MoE Modal-trained LoRA is served as an adapter on a shared BF16 base, and every deployment on that base shares one container pool. Everything else (full finetunes, unsupported MoE, other providers) is merged into a private checkpoint, quantized to FP8 unless the catalog entry sets `fp8_supported: false`. Native decision deployments copy their verified artifact without a merge.+- The shared base stays BF16: an FP8 base measurably degrades adapter quality. MoE models need verified `inference.lora_supported` in `models.json`. `inference.min_vram_gb` is a measured floor; a deployment below it is raised before the next boot.+- Base weights live only in `.base_models/{org--model}` on the weights Volume. `fetch_base_model` is the only writer and a global mutex; it seals `.base-manifest.json` and validates it on reuse. Celery waits on it before spawning GPU training, so a cold base downloads on CPU. Training fails on an incomplete snapshot; there is no Hub fallback.+- Nothing on the `overmind-sft` Volume is read at serve time. `tasks/cleanup_modal.py` sweeps it daily. A Modal deploy restores from the S3 archive only when retention already pruned the checkpoint (`register_model._dispatch_download`); the first Modal deploy never round-trips through S3.++## Workers++- Every GPU/image pair has a `{gpu}_{image}_lora` class. It snapshots the engine after level-2 sleep, then restores an adapter-free runtime-layout artifact through pinned buffers. Artifact identity includes the base revision and serving profile, never tenant adapters; adapters attach after restore.+- Only the concrete full-checkpoint classes own the normal post-snapshot startup hook. Putting it on the shared base class makes Modal run it beside the LoRA restore hook.+- `pre_warm` verifies a deployment before READY. For LoRA, the first boot of a `_lora` class that it triggers also prepares the artifact and snapshot.+- The Modal gateway and Django SSE send idle pings immediately and every 15 s; Django non-stream completions start newline keepalives after 15 s. The edge drops connections idle for 60 s (`api/streaming.py`), so these pings are load-bearing.++## Deployment controller++`services/deployment.py` persists stage, remote call handle, generation, retry budget, deadline and evaluation waiters. One 15-second controller covers training outputs and baselines. Worker death reconnects to the saved call instead of restarting GPU work. Each deployment generation has one four-hour deadline shared by at most three confirmed-failure attempts (30/60-second backoff); an archive-stage failure moves on to `weights` without spending an attempt. A submission without a saved acknowledgement fails closed. Training stays successful when only deployment fails; the dependent evaluation fails. Successful training deploys every model automatically; `deploy_finetune` backfills historical successes without changing routing.++## 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.++## Inference requests++MCP `run_inference` and REST `POST /api/deployed-models/{id}/inference/` (chat or decisions) use `services/inference_requests.py`: save the request key, input and routing fingerprint before dispatch; the 15-second controller then submits or observes the existing Modal call. Unknown submissions are never reissued; an expired observation deadline is unresolved, not cancelled. The ordinary completion API keeps its streaming and synchronous contract.++- `services/serving_context.py` sizes serving context from the pinned evaluation inputs, references and output headroom, independently of training `context_length`. Overflow warns; it never excludes a candidate.+- `modal_shared/context_budget.py` reserves a positive output budget (default 8,192 tokens) and rejects prompt truncation. Requests never shrink silently to the remaining context; MCP returns `context_length_exceeded`.+- Token-limited generations keep their finish reason and stop before tool execution or parsing.+- `services/inference_metrics.py` and `inference_live.py` serve metrics and worker state without invoking inference. Zero measured runners means asleep; unavailable counts stay unknown.++## Native decision serving++`DeployedModel.inference_contract` separates chat from typed probability serving. Native deployments pin the serving release, recorded training GPU and context, and the verified artifact identity. READY requires a real probability prediction. There is no chat-gateway registration or implicit activation. Output keeps the original option order.++## Operational receipts++`services/operational_progress.py` stores `OperationalRun` attempts and append-only `OperationalEvent`s for preparation, training, deployment, activation and inference. Background controllers copy provider events (`provider_progress.py`); status reads never call a worker. MCP `inspect_operation` and `overmind://operations/{id}` page them. Shared-pool events never prove tenant-adapter readiness. Missing telemetry, cursor backlog and dropped publications stay explicit. New worker instrumentation needs a new pinned release and a Modal deployment before its events exist.diff --git a/.agents/skills/backend-architecture/references/tracing-and-scoring.md b/.agents/skills/backend-architecture/references/tracing-and-scoring.mdnew file mode 100644index 00000000..ebcbdd22--- /dev/null+++ b/.agents/skills/backend-architecture/references/tracing-and-scoring.md@@ -0,0 +1,47 @@+# Tracing and scoring++## Span model++Span-only: there is no Trace table. A trace is the spans sharing a `trace_id`; the root has `parent_span_id IS NULL`. `span_id` is the primary key. Timing is nanosecond integers (`start_time_ns`, `end_time_ns`, `duration_ns`), with no datetime column. `received_at` is ingest time. `process_span` fills the linkage: `capability` (resolved through `IdentityAlias`, never created) and `conversation`. `eval_attributes` holds the latest span score and, on a root, the trajectory.++## Ingest++`POST /api/v1/traces` (alias `/v1/traces`) accepts an OTLP protobuf or JSON export → flatten `ResourceSpans → ScopeSpans → Span` → bulk upsert on `span_id` → `process_span` → `enqueue_scoring`, which adds `LiveScoringWork` rows and wakes `dispatch_live_scoring`; `execute_live_scoring` then runs `span_processor.score_spans`. Connector imports use the same path.++Span cost has one owner: `services/span_pricing.stamp_span_cost` runs on every OTLP and connector span before storage. A reported cost (any alias, coalesced to `genai.cost`) is kept; otherwise `genai-prices` prices it from model, tokens and cache reads. The SDK never prices. Gateway billing is separate on purpose: it charges what OpenRouter reports (`usage.cost`), with `model_catalog.estimate_cost` list prices as the fallback.++## Read surface++`SpanViewSet` backs it; there is no `/api/spans/` route.++- `GET /api/traces/` — one row per trace head (`Span.trace_heads`: the root once it arrives, else the earliest span) with `trace_status` (`completed`, `live`, or `interrupted` after `TRACE_SETTLE_SECONDS`).+- `GET /api/traces/{trace_id}/`, `/api/traces/services/`, `/api/traces/models/`.++Filters are span-native (`received_at__gte`, `span_type`, `operation`, `service_name`, `has_error`). In the head view, `capability` matches any span in the trace; `all_spans=true` filters each span. REST, MCP and trace-source selection share this filter.++## Live scoring (`innermind/`)++`EvalMatrix` rows are `llm` (a one-sentence expectation judged by `evals.JevEvaluator`) or `deterministic` (`def evaluate(span)` run by `deterministic.py` in an audited `python3 -I` child: no imports, `json`/`re` preloaded, 5 s CPU, 15 s wall, 512 MB). Rows are project-wide or per capability and narrow by `span_type`/`span_name`; span-declared expectations add llm rows for that span. `innermind.definitions` derives the read-only `definition_source` of each row.++`span_processor.score_spans`:++- Claims a span only when it starts and writes each score once (`persist`: one guarded update plus its `EvalScore`).+- Unscoped llm rows apply only to the root or a capability's topmost span, never to tool or retrieval spans.+- A pass counts in `attempts` before its judges run, so a killed pass counts too. At `MAX_ATTEMPTS` (3) the failing rows become error metrics and no judge is called again.+- A span never waits for its ancestors. Intent falls back from the span, to the nearest arrived ancestor, to the root input, to the capability description. The beat sweep re-drives spans unscored after 90 s.+- Re-ingest keeps a score whose `fingerprint` matches the incoming span.+- Jev and explanation calls share one process-wide thread cap (`evals.throttled`); an event-loop semaphore cannot bound them.++`trajectory.score_trace` runs once, when every arrived span of a single-root trace is final, and stores `score` (the outcome), `passed`, `span_count` and `metrics` (`weakest_step`, `efficiency`, `path_judge`, `reference`) under the root's `eval_attributes.trajectory`; a single-span trace stores the outcome only. It shares the attempt limit.++Every span, trajectory and run-row score appends an `EvalScore` (`source_type` `span`, `trajectory` or `dataset_row`). The session score is the mean root trajectory score, using the root span score where a root has no trajectory.++## Signals++`signals.SignalRunner` (beat, every 5 min) checks projects with spans from the last day, grouped by conversation or trace. Deterministic signals run by default without stored subscriptions; stored `SignalSubscription` settings override defaults, and capability settings override project settings. `plan_drift` stays opt-in because it calls the judge. Events keep their source trace IDs; `/api/traces/?signal_event=` and MCP `query_traces(signal_event=)` share that filter. The Console shows signals inside Observability (Sessions, Signals, Traces); there is no separate Signals page.++`health.py` backs MCP `inspect_capability_health` and `query_failures`.++## Jev decisions++`core/decisions.py` calls the registered Jev model with structured choice questions and validates complete probability distributions. A generative model (`EVAL_EXPLANATION`) only writes reasons for low scores. Eval matrix llm rows call Jev with no generative fallback: transient transport failures raise so the span retries; other `DecisionError`s become metric errors. Fixed classification and Workshop semantic services keep a generative fallback through `services/judging/decisions.py`. Jev confidence is not calibrated correctness. Jev is excluded from inference and chat-model pickers. `POST /api/v1/systemone` proxies a body synchronously to OpenRouter, or to a fine-tuned decision deployment's Modal worker; it has no request key or receipt.diff --git a/.agents/skills/backend-architecture/references/training.md b/.agents/skills/backend-architecture/references/training.mdnew file mode 100644index 00000000..b2d9a9a5--- /dev/null+++ b/.agents/skills/backend-architecture/references/training.md@@ -0,0 +1,52 @@+# Training++UI "Training" is backend `finetuning`. All training runs on Modal with Unsloth; onboarding a model or family is the finetuning-model-onboarding skill.++## Preparation++`services/training_preparation.py` caches exact Modal preprocessing by training and validation cell fingerprints, model, training type, context length, training stack and the SFT asset code fingerprint. REST `POST /api/training-preparations/` and MCP `prepare_training_data` share it.++- Explicit preparation atomically creates the dashboard `FinetuningJob` before queuing preprocessing. Its `preprocessing` and `awaiting_launch` states are excluded from GPU dispatch and launch admission. A matching launch promotes that same job; retrying a setup failure never launches GPU training.+- Preparation runs CPU-only `prepare_<train_function>` in the matching training image. `sft_assets/preprocess.py` uses the trainer's `pretok` path and rejects over-context rows and zero-supervision examples. It never truncates, filters or rewrites data.+- Context sizing compares the stored longest row with each model's LoRA and full limits. An unsupported explicit context is rejected, never rounded. When exact tokenization exceeds an estimated context but fits the model, preparation requests the measured bucket once and rechecks every row.+- `TrainingPreparation` keeps state, the remote call ID and a 24-hour deadline. An unacknowledged submission fails closed. Retry of a confirmed failure cancels the saved remote operation first; uncertain submissions are never retried automatically.+- A worker or code fingerprint mismatch blocks preparation until `modal deploy overbae/modal/modal_sft_worker.py` runs. Recreating Docker services does not deploy Modal code. Subprocess logs stay at `preparations/<id>/preprocess_stdout.log` on the SFT volume and never enter user-facing errors.+- Workshop findings before training are advisory warnings, not launch blockers. Training does model-specific preprocessing only.++## Launch++- `training_record` freezes dataset selections, objective and requested configuration. `request_key` is project-unique: the same key and recipe return the same job; a changed recipe conflicts. Explicit context, batch, packing, dropout and seed are honored or rejected, never clamped.+- Creation pins train, validation and eval cells atomically. Launch credit admission runs inside the project-locked creation path after request-key recovery.+- `training_release` hashes the `*.py` files in `modal_shared/` and `sft_assets/`, the worker and the data format into the Modal app name. Preparations and jobs pin it; retries and observers use it after configuration changes. Templates (`.jinja`) and `run.sh` count only in the processor and training fingerprints, so a template-only change keeps the app name and a redeploy replaces that app's code. Never deploy over an active unpinned run.+- `training_submission` journals intent and run ID before provider submission. A lost acknowledgement is `submission_unknown`; the reconciler resolves it from the saved call metadata and never starts a second trainer while ownership is unresolved.+- Launches upload ordered SHA-256 row selections instead of the rows again; the worker verifies them against the pinned token artifact and preserves order and duplicates. At most five writers (`VOLUME_WRITERS`, shared by launches and preparation uploads) write to the SFT volume at once. The training volume commits when a stage finishes, not on a timer.+- Modal training attempts keep a 24-hour function timeout. `runtime_limit_seconds` does not shorten that call and is not an invoice cap. The downloadable run record separates recorded GPU spend from unreported components.+- Chat-training cost estimates use dataset text statistics and assumed H100 throughput. Native forecasts use completed execution measurements with matching identities and hardware; an unmeasured recipe reports unknown duration and total cost beside the current GPU rate.++## Progress and stall detection++Startup records runtime imports, weight loading, adapter setup, tokenizer verification, dataset construction and trainer startup as separate stages. Console and MCP expose stage start, source observation, worker heartbeat and last forward progress as separate clocks. A committer heartbeat does not count as progress. Opaque library weight loading has no percentage. Transfer counters count acknowledged files, not live network bytes.++The no-progress observer compares native stage, completed work, attempt and checkpoint counters as well as optimizer metrics. Native timing shows elapsed time and a remaining-time range, never a single countdown or finish timestamp; it resets on a new attempt.++## Development monitoring++`hyperparameters.monitoring` is one strict policy, accepted by readiness, preparation, estimates and launch, and frozen across them. `modal_shared/training_monitoring.py` resolves it, samples whole groups and schedules checks; `services/training_monitoring.py` stores the manifest that Modal freezes before GPU dispatch.++- `TrainingValidationRun` and `TrainingCheckpoint` keep failures, sample and artifact fingerprints, reload verification and evidence from cancelled runs.+- Status observation ingests metrics without downloading examples. The per-job IO collector reads each sealed artifact once with checksum verification; reads (MCP `inspect_training_progress`, REST monitoring evidence) never invoke a worker. MCP evidence over 128 KiB fails explicitly; `field` JSON Pointers page exact values.+- Generation checks need agent-declared labels, exact matching, a JSON Schema or `json_fields` pointers. `json_fields` compares declared JSON Pointers with type- and precision-preserving equality and ordered arrays; per-field coverage and whole-example pass rates are separate. Missing references are unscorable; invalid or missing predictions fail. Generation never executes tools. Metered judges, challenge suites and declared-strata sampling are rejected as unsupported.+- Development-loss selection and early stopping are explicit opt-ins. Classification `facts.assessment` compares the same scored subset with its majority-label baseline during collection, never on reads, and triggers no training action. Compact MCP summaries keep the latest generation check even when newer checks have loss only.+- Optional PostHog events (`training_result_available`, `training_check_finished`, `training_checkpoint_available`) fire after commit and carry counts and timings, never examples, labels or paths. Analytics failure cannot fail training.+- `cancel_finetune` and REST record cancellation intent before provider requests.++## Native decision training++`DecisionJob` is a separate public ID over one `FinetuningJob`; it has no status machine of its own. REST and MCP return both IDs, and preparation returns the DecisionJob ID when present.++- A train cell may carry a `decision` object instead of messages. `modal_shared/decisions.py` validates state, question, kind, options, full target distributions and positive weights. Targets never enter the encoder (`modal_shared/decision_encoding.py`); oversized inputs fail without truncation.+- The separately pinned decision image supplies Unsloth `FastDecisionModel`, `DecisionTrainer` and the Clef joint head. The measured contract selects distribution cross entropy or mixed distribution and ordinal-mean supervision. It never invents a distribution from a mean or turns soft labels into argmax text.+- The catalogue lists Clef, D3 and D1. Only Clef launches; D3 and D1 stay disabled until their preparation, checkpoint and serving runtimes pass the same checks. The supported method is one-GPU Modal LoRA.+- Artifacts hold the adapter, full-precision head, upstream head and config files, tokenizer and `decision.json`. Checkpoints publish only after exact tensor reload and a nonempty probability check.+- `hyperparameters.pre_training_baseline` defaults to true; false skips only the starting-model development evaluation, and telemetry records `not_requested`.+- Decision checkpoints use typed probabilities and never enter chat evaluation or deployment.diff --git a/.agents/skills/data-workshop/SKILL.md b/.agents/skills/data-workshop/SKILL.mdindex 8de6adaa..5869b486 100644--- a/.agents/skills/data-workshop/SKILL.md+++ b/.agents/skills/data-workshop/SKILL.md@@ -1,362 +1,82 @@---name: data-workshop-description: Data Workshop internals — source landing, immutable dataset pipelines and runs, lineage-bound external imports, version inspection and consumer pinning. Use when changing these services, Console screens or MCP contracts.+description: Data Workshop internals — source landing and OCR, immutable dataset pipelines and runs, lineage-bound external imports, version inspection, consumer pinning and the Workshop canvas. Use when changing these services, their Console screens or their MCP contracts.---# Data Workshop-The native coding agent owns intelligence. The platform stores evidence and runs-explicit operations. Source landing does not diagnose, start a chat turn, generate-examples or resume a platform agent. Chat, mutable-cell and replay endpoints are removed, together with their Console callers. Historical Cell scripts, reviews and frames remain readable. Old conversations, generation records and provider receipts are archived in DatasetHistory before their runtime tables are dropped.--## Active path--- `services/datasets/dispatch.py`: create, split and attach sources.-- `tasks/datasets.py`: landing and deterministic pipeline execution on the batch- prefork worker; the reaper fails expired runs without replaying them.-- `services/datasets/workbench.py`: shared REST/MCP pipeline, import and publication- lifecycle. `api/workbench.py` and `mcp/tools_workbench.py` adapt it.-- `models/dataset_pipeline.py`: immutable DatasetPipeline recipes and durable- DatasetPipelineRun receipts, source/output/artifact FKs and fingerprints.-- `pipeline_packages.py`, `pipeline_runner.py`, `pipeline_bindings.py`: retained- script packages, dedicated container execution and explicitly enabled source bindings.-- `services/datasets/versions.py`: version/UUID resolution without importing an agent.-- The Console landing page is a project dataset table. Rows open the existing- cells on a grid-snapped flow canvas; the folder button reveals compact,- project-scoped navigation. Chat and funding controls are removed. Corrections replace the- displayed process, with no repair-history or restore view. Exact consumer-pinned- inputs remain immutable internally.- Connections follow recorded parents. Moving cells never changes dependencies.--New revisions require a retained Python package with native-agent-authored stages.-Package-free historical revisions stay readable, but validation, new execution and-bindings reject them with pipeline_package_required. REST and MCP reject inline-operation definitions; the in-process declarative executor is removed. Project-owned families have immutable numbered-revisions; `derived_from` creates a separate attributed family. Reuse the exact-revision across compatible sources in the same project. Packages execute only in-the isolated sandbox service through interactive workers: pinned source/lockfile-identities, separate UIDs, no network egress, app credentials, media mounts or Docker-socket, measured resource admission and retained logs.-Registration and static validation never execute code. The sandbox records process exit-status; script-authored status files do not establish completion. Dependencies are-locked in the shared application image. Setup and package protocol: `docs/workshop-pipelines.md`.-External semantic/provider work remains native-agent-owned and imported with lineage.--A run request key is unique per dataset; revision keys are project-scoped. Identical retries recover the same record;-changed content conflicts. Pipeline creation does not execute. Runs bind immutable-source cell IDs and checksums; all output is measured before atomic publication.-Workbench inspection pages recipes and receipts independently with pipeline_offset,-run_offset, binding_offset and limit (20 by default, at most 100), returning total and next_cursor.-Each successful run publishes all step cells atomically. Preview retains samples-and checks but publishes no cells. Absolute min_rows/max_rows checks are deferred in previews and enforced-on publication; preservation, schemas and lineage are checked in both modes.-Step check_results retain passed/failed/deferred checks with expected/actual counts-on failure. Static validation warns about undeclared output lineage without claiming-runtime failure. Run receipts expose queue age, a polling interval and terminal time.-Runner availability heartbeats continue during validation and publication; they-do not advance measured progress or certify a stage has completed.-Bindings start paused, pin a revision and-parameters, and rebuild full source snapshots, including late trace changes and-removed matches. Checkpoint and cells commit together. Failed attempts pause on-the next inspection; re-enable or revise explicitly to authorize another attempt.-Scheduled/ingestion bindings are checked by a bounded batch task;-trace snapshots are capped at 10,000 selected traces and reject overflow.--Trace landing pins `preferred_capability_id` in the source recipe. A source capability-filter takes precedence over the destination capability; otherwise the destination-is preferred when it appears in a trace. Each row uses the unique outer matching-invocation and its descendants for I/O, transcript, usage and score. Repeated outer-invocations fail before publication. Without a match, whole-trace evidence remains;-mixed traces are not attributed to their first capability. Missing wrapper I/O-stays missing instead of borrowing tool arguments. Bindings use the same extraction.-Pipeline receipts expose the current measured stage, pinned source row count and-output row count once written. A running stage is not a percentage or an ETA.-Landing claims also bind attachment-request identities, so a cancelled delivery-cannot consume a later attachment. Paired source claims are atomic; a cancelled-or replaced member releases its unclaimed partner with a retryable source error.-A failed or cancelled run leaves the selected and consumed versions untouched.-Cancellation prevents publication; it does not claim to kill an in-flight calculation.-Worker deadlines and leases bound execution. Unresolved work is never blindly replayed.--For deployment, stop old Workshop agent workers before the API cutover. A 3.0-deployment does not acknowledge cancellation of a model request submitted by an-older worker. Preserve historical receipts and reconcile unknown provider outcomes.--Initial source imports retain `DatasetImport` receipts; all landing submissions-also enter `DatasetLandingWork` before broker publication. A nonblocking control-dispatcher admits one import per project with least-recent-project fairness and-bounds global work by observed landing worker slots, capped at eight. Waiting-imports remain in PostgreSQL, not the broker. Queue waiting has no default expiry;-`DATASET_IMPORT_MAX_QUEUE_SECONDS` explicitly sets one when nonzero. Worker leases-and execution limits remain bounded. Unacknowledged, unstarted deliveries can be-fenced and admitted again; lost started imports require explicit recovery.-Publication fences recovery through dataset locks; admission checks must leave-the work row unlocked so its independent heartbeat can renew throughout publication.-REST operation and MCP dataset/run inspection expose the same admission state and-measured timestamps without exposing ownership tokens. The dedicated `landing`-queue consumes only admitted deliveries. Publication and execution have separate fenced ownership; the-control reconciler recovers lost broker acknowledgements and records expired-attempts. `resume_dataset_import` and REST `resume-import` explicitly retry a-blocked import within its attempt budget. Cancellation fences both split members.-Landing retains evidence and returns to idle; it does not start preparation.-First-source uploads into an existing empty draft use the same durable import-receipt. MCP also offers explicit recovery for retained failed draft uploads that-predate that receipt, preserving the draft and its task brief.-Pipeline queue demand contributes to interactive capacity through `DatasetPipelineRun`.-The default project limit is two concurrent pipelines, below the minimum four-slot-interactive worker so one project's burst cannot occupy the entire worker. Raising-this limit requires testing it against the minimum deployed worker capacity.--## Sources, identities and versions--Datasets retain a written brief and explicit train/eval/explore/pending purpose.-A missing purpose stays pending. Capability inference remains a bounded landing-hint, not a substitute for user intent. A capability is optional for data-first work.-Name, purpose, capability and default-version changes use lifecycle services.--Frames are Parquet under `MEDIA_ROOT/datasets/<dataset>/cells/<cell>.parquet`.-Cell IDs bind versions; displayed version labels are derived by Dataset.versions().-Source identity is `source_row`, not the current display position. The Console-hides internal lineage columns, while export preserves them. SQL query responses-decode declared JSON results, including aliases and JSON expressions, without-reinterpreting ordinary text that happens to look like JSON.--CLI uploads use DatasetTransfer receipts: a project request key binds SHA-256,-byte count and destination recipe. Byte writes and publication serialize on the-transfer, and publication persists the dataset IDs and landing task before-dispatch. Repeating completion recovers an unacknowledged broker handoff; the-landing task's claim prevents duplicate cells. Unscoped staging endpoints cannot-access managed transfer bytes. An explicit json_rows_field selects a top-level-JSON array and is retained in extraction metadata. MCP get_job(dataset_transfer)-reads these facts without dispatching. CLI upload states are publication snapshots-(`state_scope=at_publication`), not-current landing status. `--wait` observes terminal landing; MCP `get_job` reads-current progress. First-source attachment-preserves a draft; later attachment appends a new version. Original document/image-bytes, extraction metadata and row evidence remain retained. Local Tesseract OCR covers scanned PDF regions and PNG/JPEG/WebP images.-It uses English by default and records actual languages and model identities.-`update_dataset(ocr_languages=[...])` sets explicit Tesseract codes for subsequent-imports; `[]` restores the English default.-Set this on a draft before uploading; retries retain the original import settings.-PDF pages use bounded spawned processes under the sandbox memory reservation.-Completed OCR pages stream to project-scoped database checkpoints retained for-30 days, keyed by document, language policy, engine/model hashes and parser settings.-Import resume and identical sources reuse only matching completed pages.-Progress counters write at most every two seconds; stage and terminal transitions-remain immediate. Details and rollout: `docs/workshop-ocr.md`. Image orientation and-source coordinates survive extraction. OCR does not reconstruct visual tables.-Document parsing runs in the isolated `sandbox` service (`sandbox/documents/`),-without application credentials, media mounts or outbound network. The landing-worker streams retained bytes and receives extraction progress; missing parser-configuration fails closed. If the primary PDF parser returns no text on a page,-`sandbox/documents/pdf_text.py` recovers the-encoded layer through PDFium before OCR. This includes Type 3 text layers.-`native_text_recovery` retains affected pages, engine/version, row/character-counts and non-whitespace control-character count; rows carry their own method-and regions. Encoding artifacts remain unchanged and flagged. Recovery does not-certify visual fidelity or partial omissions on otherwise populated pages.-Documents are capped at 100 MiB; PDFs at 2,000 pages. Upload reservations return-the file-type byte limit, and chunk writes enforce it before landing. PDF page-limits are checked before extraction. `overmind://dataset-upload` exposes these-limits as numeric fields. Single and batch uploads persist file/stage progress;-PDF OCR also reports total pages and completed/total OCR pages through-`get_job(kind=dataset_run).progress.landing` and dataset inspection.-Server-side analytics are measured during publication's full-row profile pass,-including partition outputs, and bound to the exact fingerprint and rule version.-Terminal cells show Metrics and collapsed Data alert chips. REST and MCP cells-share the report; completed pipeline receipts include final-output analytics.-Use `explore_dataset` to backfill historical versions without changing rows.-Class imbalance/rare-class thresholds are advisory. Never argmax soft targets,-infer gold labels, or present a majority baseline as model performance. Bounded-coverage and `not_checked` risks stay explicit; see `docs/workshop-pipelines.md`.--`inspect_dataset` pages source metadata independently with `source_offset` and-`source_limit` (default 10, maximum 20). Follow `source_page.next_cursor`; response-budgets may shorten a page. Complete checksums and extraction/OCR metadata survive-pagination, rather than being replaced by truncated summaries.--Row storage preserves heterogeneous scalars and integers outside signed 64-bit-range as JSON. Mixed numeric columns also use JSON when float promotion would-lose integer precision. Shared pandas readers must preserve these values and-nullable integers without another inference pass. This is storage fidelity,-not agent-authored normalization; old immutable cells are not rewritten.-`query_dataset` bounds its JSON output to 32 KiB as well as 100 rows. Oversize-responses return `query_result_too_large` without clipping values; project or-aggregate in SQL, or export the exact cell. A separate configurable execution-deadline defaults to ten seconds and returns `query_timeout`; source cells and-later queries remain usable. Redis admission bounds MCP SQL across API workers-(default eight global, two per project). Busy or unavailable admission returns-retryable errors with exact cell and retry delay before creating a query engine.-Expired leases recover crashed workers; capacity does not authorize source writes.-The byte/column budget is enforced while reading-results, before building an unbounded Python result.-Results above 200 columns also fail rather than omitting column metadata.-MCP Workshop run summaries omit bulky row examples and preview samples from-routine polling/history. `evidence_resource` points to the unchanged full receipt;-measured progress, checks, lineage identities and timings stay inline.-Preview duration and script runtime phases are measured separately from queue-time. Runtime cleanup confirmation never implies publication success.-Original sources can be downloaded through `overmind dataset export DATASET --source SHA256 --output FILE --json`; the CLI verifies bytes, refuses redirects-and existing destinations, and removes checksum failures.-The upload CLI accepts `FILE1 FILE2 ...`: up to 100 ordered files and 2 GiB-combined bytes per transfer, with unchanged per-file type limits. Each file has-its own checksum and resumable offset; publication waits for every file. A new-batch creates one source cell; an attachment adds the batch in one version.-Repeat the identical command after interruption. File order is part of identity.-The single-file `--json-rows-field` flag retains its existing selection semantics.-Document-limit reservation errors expose `file_too_large`; no receipt is created.--External results use either at most 2,000 inline rows/4 MiB or a project-scoped-uploaded artifact cell and fingerprint. Every row retains source_row or supplies-all contributing identities in \_overmind_parent_rows. The provenance service-validates every parent and preserves content/group contamination identities.-Scripts must emit the actual source_row or intentional parent declarations;-landed fields are data, not instructions to adopt as transformation lineage.-The original source remains unchanged.-An artifact FK prevents disposal of a referenced uploaded output. External execution-is recorded as external_attributed. Never promote source references or supplied-human-review flags into proof of semantic correctness.+The native coding agent owns interpretation, code and semantic work. The platform stores evidence and runs explicit, deterministic operations. Landing never diagnoses, starts a chat turn, generates examples or starts preparation. There is no platform chat, mutable cell or replay endpoint; old conversations and provider receipts are archived in `DatasetHistory`, and historical cell scripts, reviews and frames stay readable.++## Map++| Path | Owns |+| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |+| `services/datasets/dispatch.py` | Create, split and attach sources |+| `services/datasets/land.py`, `imports.py`, `admission.py` | Landing, `DatasetImport` receipts, `DatasetLandingWork` admission |+| `services/datasets/transfers.py` | CLI `DatasetTransfer` receipts |+| `services/datasets/workbench.py` | Shared REST/MCP pipeline, import and publication lifecycle (`api/workbench.py`, `mcp/tools_workbench.py` adapt it) |+| `models/dataset_pipeline.py` | Immutable `DatasetPipeline` revisions and `DatasetPipelineRun` receipts |+| `pipeline_packages.py`, `pipeline_runner.py`, `pipeline_execution.py`, `pipeline_graph.py`, `pipeline_bindings.py` | Retained packages, sandbox execution, row batching, the `flow` graph, explicitly enabled bindings |+| `services/datasets/versions.py`, `use.py` | Version resolution; consumer checks and pinning |+| `services/datasets/preparation.py` | The source-to-output graph shared by the Console and MCP |+| `sandbox/documents/` | Document parsing and OCR in the isolated `sandbox` service |+| `tasks/datasets.py` | Landing and pipeline execution; the reaper fails expired runs without replay |++## Sources and landing++- A dataset may start from a written `brief` with no source or capability. Purpose is explicit (`train`, `eval`, `explore`) and otherwise stays pending; when no capability is given, REST and MCP landing assign the top-ranked capability if its score is above zero; CLI transfers never infer one.+- The first source attaches to the draft; later uploads append versions. Original bytes, extraction metadata and row evidence are retained.+- CLI uploads use `DatasetTransfer`: a project request key binds SHA-256, byte count and destination. Up to 100 ordered files and 2 GiB per transfer; file order is part of identity; one batch becomes one source cell or one version. Repeat the identical command after an interruption. `get_job(kind=dataset_transfer)` reads byte and publication state; `dataset_run` reports landing. An explicit `--json-rows-field` selects a top-level JSON row array and is recorded.+- Local upload, export and checkpoint download authenticate separately from MCP. Without an explicit or repository key they use the address-bound account connection at `$XDG_CONFIG_HOME/overmind/connection.toml` (mode `0600`); repository keys are endpoint-bound too. `overmind connection check --project-id PROJECT --json` verifies MCP and transfer access from the invoking environment; MCP connectivity alone is not readiness. Verify the installed CLI from the workspace and from a repository-free directory.+- Confirmed permission denial uses the host's scoped approval. Missing credentials and transfer errors never authorize a browser fallback or an automatic sandbox-policy change.+- Landing admission is one import per project, least-recent-project first, up to the observed landing capacity (backend-architecture `references/celery.md`). A lost started import needs explicit `resume_dataset_import`.+- Trace sources pin `preferred_capability_id`. A unique matching invocation scopes I/O, transcript, usage and score; repeated invocations fail before publication; unmatched traces keep whole-trace evidence. Missing wrapper I/O stays missing and never borrows tool arguments.++## Documents and OCR++- Parsing runs in the `sandbox` service without app credentials, media mounts or outbound network. Landing streams bytes and progress; missing parser configuration fails closed; there is no in-process fallback.+- PDF pages the primary parser misses are recovered through PDFium before OCR. `native_text_recovery` records engine, pages and counts; encoding artifacts are flagged, never corrected.+- OCR is local Tesseract, English by default, with explicit languages through `update_dataset(ocr_languages=[...])` on a draft before upload. Completed pages are cached per project for 30 days, keyed by document, language policy, engine and parser settings.+- Limits (100 MiB per document, 2,000 PDF pages) are discoverable at `overmind://dataset-upload` and enforced before extraction.++## Pipelines++- New revisions need a retained Python package with agent-authored stages; inline operations are rejected (`pipeline_package_required`). Package-free historical revisions are read-only.+- Revisions are immutable and numbered per project family; `derived_from` starts a separate attributed family. Revision keys are project-scoped; run keys are per dataset.+- Packages run only in the isolated sandbox through interactive workers: separate UIDs, no network, credentials, media mounts or Docker socket, measured memory admission. Registration and validation never execute code. Process exit status, not a script-written file, establishes completion.+- Steps declare `id` and `input`; `inputs` concatenates disjoint earlier branches in order and rejects overlapping `source_row` identities. It is not a relational join. `flow` (`pipeline_graph.py`) returns `nodes`, `edges` (each with its `condition`), `terminal_steps` and `unconsumed_steps`. Script conditions cite `expression` and `line` and never execute as expressions.+- A successful run publishes all step cells atomically. Preview publishes nothing. `min_rows`/`max_rows` apply at publication and show as deferred in previews; row preservation, schema and lineage checks apply in both. Run receipts expose queue age, a polling interval, terminal time and structured failed checks. Runner heartbeats continue through validation and publication without advancing measured progress.+- Cells carry receipt-backed `transformation` attribution (run, revision, package checksum, entrypoint). External imports and unrecorded history never claim platform execution. Every retained package file is inspectable with checksum-verified pagination.+- Recovery is lease expiry: the `reap_stuck_runs` beat task calls `workbench.expire_runs`, which fails runs past their lease without publishing partial output or replaying scripts.+- Failure or cancellation leaves source and consumer versions unchanged. Cancellation prevents publication; it does not claim to stop a running calculation.+- `batch_rows` (1–100,000) splits a row-independent step into separate sandbox runs (`pipeline_execution.py`); global sorting, grouping, splitting and deduplication must not batch.+- Bindings start paused, pin a revision, and rebuild full source snapshots; checkpoint and cells commit together.+- Keep each step's logic in its visible entrypoint; helpers hold reusable utilities, not an opaque dispatcher. Change a recipe through a new revision and run; never rewrite historical scripts.+- `save_dataset_pipeline(dataset=..., package=...)` associates the script with the dataset's preparation; retrying an older request never resets a newer association.+- Corrections update the same family and run against the original source; the clean process replaces the displayed cells. There is no repair history or restore view.++## External imports++External results arrive inline (at most 2,000 rows or 4 MiB) or as a project-scoped artifact cell. Every row keeps `source_row` or declares all parents in `_overmind_parent_rows`; publication validates every parent (`review.py`, `workbench.py`). External runs are recorded as `external_attributed`, and their cells' `transformation.execution` is `external_import`. Never promote source references or supplied review flags into proof of semantic correctness.++## Storage and queries++- Frames are Parquet at `MEDIA_ROOT/datasets/<dataset>/cells/<cell>.parquet`. Cell IDs bind versions; version labels are derived. Source identity is `source_row`, not display position.+- A column becomes JSON when it mixes kinds, holds an integer outside signed 64-bit range, or mixes floats with an integer a float cannot represent exactly (`store.py`). Shared pandas readers must not coerce these values again.+- `query_dataset` caps output at 100 rows and 32 KiB and returns `query_result_too_large` without clipping; a configurable ten-second deadline returns `query_timeout`. Redis admission bounds MCP SQL globally and per project; busy admission returns a retryable error with the cell and retry delay.+- `overmind dataset export --source SHA256` downloads retained originals with byte verification.## Checks and consumers-The platform measures format and change impact on the published output. Semantic-quality remains unmeasured unless actual attributable evidence exists; technical-compatibility is not a semantic pass. Existing reviews stay attached to their exact-historical cells. Do not create a universal quality-approval gate.--Preserve full probability targets, option order, weights, repeated observations and-valid blank states. Do not derive argmax labels or invent distributions from means.-Decision/Jev preparation publishes a typed `decision`, retaining tied maxima and-declared supervision metadata. Record evidence-backed target semantics in retained-code and output metadata; historical preparation plans are not a writable API.-Flat-source profiles and impact measurements include weights, semantics and target-provenance. Profiler upgrades invalidate cached measurements for new requests;-replaying a request key still returns its original frozen operation.-Exploration measures sampling feasibility and allocations; derivation copies a-complete source. Sample selection runs externally and returns through the import-contract. Partition plans keep related content, declared groups and synthetic-seeds together. Unknown explicit group fields fail construction; projected-away-groups remain usable through preserved lineage. Partition request keys serialize-at project scope. Generated member names reserve space for the role suffix while-retaining the full plan name.--Group identity aliases are shared by lineage recording and partition validation.-A declared `content` column has a separate group identity from internal input-fingerprints, including after projection removes that column.--Raw tables have no inferred feature/target mapping. Their full records, excluding-platform row/provenance identities, receive versioned `record:v1:` fingerprints.-Names such as `state`, `text`, `label` and `score` never select or exclude columns.-Explicit input/chat envelopes and the complete native decision wire format use-model-input fingerprints; native target variants stay together across flat,-nested and wrapped formats. Declared groups and inherited source/seed keys remain-partition constraints. Historical keys are not silently dropped or rewritten.-For affected historical imports, follow the immutable-source rebuild procedure-in `docs/workshop-pipelines.md` before creating new consumer snapshots.--`use.check` verifies readability and technical fit. `use.use` / `use.freeze`-pin exact cells in the consumer transaction. Training pins train/validation/eval-cells atomically and does model-specific preprocessing outside Workshop.-Later transformations append; they do not rewrite these frames.-Sources and successful versions remain readable after failures or cancellation.--## Contracts and verification--MCP contract 5.1 adds project revisions, packages, preview, validation, exact-run-cancellation and binding save/state/run tools. The removed agent endpoints remain-absent. `get_job` supports exact dataset_pipeline run IDs; revision/package/binding-resources and paginated pipeline diagnostics expose retained facts. Existing source,-exploration, partition, export and consumer-readiness operations remain.--`docs/workshop-pipelines.md` records runtime setup and repeatable regression commands.-Frontend uses the generated OpenAPI client.-Keep account/project isolation, stable retry keys, changed-key conflicts, source-checksum checks, failed/cancelled publication and artifact lineage covered.--Native agents author explicit `id`/`input` dependencies in steps. Inputs name-`source` or an earlier step; repeated inputs create real forks. The saved entity-and MCP resource return `flow` with nodes, edges, conditions and output. Script-conditions cite `expression` and entrypoint `line`, remain `agent_declared`, and-never execute as expressions. Scripts route rows; every step executes, including-empty branches. `inputs` concatenates distinct earlier branches in declared order;-overlapping source_row identities fail before publication. The script receives a-schema-compatible union; incompatible nonempty data columns/types fail rather than-coercing values. It is a-disjoint union, not a relational key join. Flow exposes terminal and unconsumed-steps so native agents can converge training deliverables rather than leave dead ends.-Publication records actual `input_cells`, `step_id` and condition evidence per cell.-Cell `transformation` metadata binds publication membership and output fingerprint to-the completed run, exact revision, entrypoint and package. It distinguishes isolated-script execution, historical declarative operations, external imports, sources and unrecorded-history; review text alone is not proof of execution. The Script section can inspect-every retained package file, with checksum-verified character pagination shared by-REST and MCP. Keep each step's substantive logic in its visible entrypoint; shared-helpers contain genuinely reusable utilities, not an opaque step dispatcher. Change-recipes by new revisions and executions, never rewriting historical cell scripts.-The Console preserves full-size cell contents on a 20px grid-snapped flow canvas.-Steps cascade down; sibling branches align side by side on the same horizontal-layer. Cells open at scale 1; explicit zoom, Fit view and a toggleable minimap-navigate the graph without changing cell dimensions. Reset and linked-cell focus-restore scale 1; resizing preserves the chosen zoom. `preparation.py` builds the-selected successful process from verified run inputs, partition members and-derivations across datasets; unrelated attempts are not canvas nodes.-The right-hand box contains dataset navigation and the minimap toggle, without-cell search or a cell-selector strip.--MCP contract 5.2 adds the `author-dataset-transformation` prompt and exact-revision-lookup using `inspect_dataset_workbench(pipeline=REVISION_UUID)`: selected recipe,-paged family history and scoped runs/bindings. Stale family updates return-`revision_conflict`. Branch correctness requires independent member/coverage checks;-declarations, preview prefixes and successful execution do not establish it.--## Preparation execution and corrections--Upload original source bytes once and pin upstream revisions. Register retained-transformation code before processing the full data. Do not upload prepared-outputs as unrelated sources. For corrections, update the same recipe family-and run the corrected package against the original source; the resulting clean-process replaces the displayed cells without repair-history or restore controls.-Consumer-pinned artifacts remain immutable internally. Recipes belong to the-project; reuse is optional and requires compatible source and target semantics.-`inspect_dataset_workbench.preparation` exposes the same source-to-output graph-as the Console, including recorded train/development/calibration/final links.--Column contracts use `object` for a nested decision, never `json`. Declare the-final step's `consumer` as `decision_train`, `decision_eval`, `chat_train` or-`model_eval` to validate nested targets in both preview and publication. Preserve-evidenced semantics and structured provenance; never remove them to pass checks.-Preview samples a bounded prefix and does not establish coverage of every family.--For row-independent transformations, declare step `batch_rows` (1–100000).-Consecutive batches execute in separate restricted containers and concatenate in-source order. Each expanded JSONL input/output must fit half the package's-`scratch_mb`; each batch has the declared time limit. Global sorting, grouping,-splitting and deduplication must not use batching. Row checks apply to the combined-output, publication remains atomic, and progress records completed batches and-rows. A failed or cancelled batch publishes no partial cells. CLI directory-packages omit Python bytecode caches; other unsupported files remain errors.--Controller recovery uses a dedicated PostgreSQL session lock. Only its owner may execute queued recipes. On startup it fails interrupted recipe runs and removes their owned containers before accepting new work. Recovery never publishes partial outputs or automatically replays scripts. Each batch clears the previous batch's execution identity and exit code before reporting progress.--Large row stores bound staging and DataFrame chunks to 16 MiB of serialized row data (one larger row remains indivisible), with 256-row Arrow decoding batches. Declared transformation batches stream through temporary Parquet files rather than collecting all rows in memory. Runtime JSONL scratch limits remain separate and enforced.--### Script association and cell comparisons--Keep the existing cell and branch UI. `save_dataset_pipeline(dataset=..., package=...)` automatically retains the script and associates the current revision with its preparation. Registration retries return the old receipt without resetting a newer association. Submission also binds reused project recipes to the dataset; package-free execution remains prohibited. `DatasetPipeline.authoring_dataset_id` retains the request identity independently of dataset deletion.--Grid comparisons use the recorded single input, so corrections do not display discarded attempts as their baseline. Multi-input cells do not invent a single comparison parent.--Trace source cells expose a preparation prompt for the external coding agent. It-pins the deployment, project, dataset and original source fingerprint, carries the-explicit purpose and brief, and uses the retained-package workflow. Observed trace-outputs never become verified references implicitly. Dataset polling refreshes the-preparation graph by dataset revision; event reconnection also refreshes it.+- The platform measures format and change impact. Semantic quality stays unmeasured without attributable evidence; technical compatibility is not semantic correctness. Do not add a universal quality gate.+- Preserve probability targets, option order, weights, duplicates, blank states and declared groups. Never argmax soft targets or invent distributions from means. Decision recipes publish a typed `decision` with tied maxima and supervision metadata.+- The native agent declares target meaning per family from evidence in retained code and output metadata; unknown meaning stays unknown. Historical preparation plans are not a writable API. Profiles and impact checks keep declared supervision metadata, so a changed weight or semantic declaration shows in review.+- Publication measures analytics on the full rows, bound to the exact fingerprint and rule version. They are advisory; `explore_dataset` backfills older cells, and reads never scan.+- Raw tables have no inferred feature or target mapping; column names such as `label` or `score` never select columns.+- Column contracts use `object` for a nested decision. A final step's `consumer` (`decision_train`, `decision_eval`, `chat_train`, `model_eval`) validates targets in preview and publication.+- `use.check` verifies technical fit; `use.use` and `use.freeze` pin exact cells inside the consumer transaction.+- The native agent inspects the named capability and verifies published output before it calls preparation complete. Format readiness does not establish task suitability.-Creating a dataset from selected traces asks for its name and optional capability-only. It lands with pending purpose; preparation and consumer intent follow in-Workshop. Trace selections omit the table-only `all_spans` display parameter.+## Console canvas-The upload client retries at most five transient chunk-transport failures with-smaller chunks and bounded backoff against the same transfer and offset. Confirmed-permission denial stops immediately. Exhausted retries retain the receipt for the-identical command to resume; publication is not blindly replayed.+The landing page is a project dataset table; a row opens its cells on a grid-snapped flow canvas. Cells stay full-size at scale 1; zoom and Fit view change only the camera. Steps run downward and sibling branches share a horizontal layer. Positions persist in the browser and never change execution. The folder button opens project-scoped dataset navigation. There is no chat, funding control, cell search or cell-selector strip.diff --git a/.agents/skills/finetuning-model-onboarding/SKILL.md b/.agents/skills/finetuning-model-onboarding/SKILL.mdindex 2f5a2950..edae79c3 100644--- a/.agents/skills/finetuning-model-onboarding/SKILL.md+++ b/.agents/skills/finetuning-model-onboarding/SKILL.md@@ -5,7 +5,7 @@ description: Rules for adding a new model or model family to the finetuning pipe# Finetuning model onboarding-All finetuning runs on Modal with Unsloth (`overbae/services/sft_assets/engine_unsloth.py`). Every model and family in this pipeline goes through the same engine — the rules below exist to keep it that way.+All finetuning runs on Modal with Unsloth (`overbae/services/sft_assets/engine_unsloth.py`). Every chat model and family goes through the same engine — the rules below exist to keep it that way. Decision families (Clef, D3, D1) run `sft_assets/decision_engine.py` instead.## 1. Never branch on model/family in the shared script@@ -13,10 +13,10 @@ All finetuning runs on Modal with Unsloth (`overbae/services/sft_assets/engine_u- Do **not** add `if model_id == "..."` or `if family == "..."` branches to the engine, runner, or policy.- Do add/extend a family hooks module under `overbae/services/sft_assets/families/<family>.py`, subclassing `DefaultHooks` (`families/__init__.py`) and overriding only the hook methods you need (`env_overrides`, `load_kwargs`, `post_load`, `device_map`, `sft_config_overrides`, `peft_lora_dropout`, `peft_gradient_checkpointing`, `fast_model_cls`). Export a single `hooks = XxxHooks()`.-- Register the family in `modal_shared/modelfam/families.py` as a `FamilySpec` (patterns, images, `hooks_module="families.<family>"`), then add it to the ordered `_FAMILIES` tuple in `modal_shared/modelfam/registry.py` — **specific patterns before general ones** (e.g. `qwen35`/`qwen_coder` before `qwen_mm` before `qwen`).+- Register the family in `modal_shared/modelfam/families.py` as a `FamilySpec` (patterns, images, `hooks_module="families.<family>"`), then add it to the ordered `_FAMILIES` tuple in `modal_shared/modelfam/registry.py` — **specific patterns before general ones** (e.g. `qwen38`, `qwen35` and `qwen3_coder` before `qwen_mm` before `qwen`).- The engine calls hooks uniformly (`load_hooks(_spec.hooks_module)` then `_hooks.<method>(...)`) — it never knows which family it's running. That's the contract to preserve.-Reference existing hooks files for scale: `qwen35.py` (two-line SDPA override) up to `gpt_oss.py` (monkeypatches + adapter base-model swap) — match the size of the override to the size of the actual quirk, don't build more than the model needs.+Reference existing hooks files for scale: `llama.py` (`hooks = DefaultHooks()`) up to `gpt_oss.py` (monkeypatches + adapter base-model swap) — match the size of the override to the size of the actual quirk, don't build more than the model needs.## 2. Chat template must be training-compatible (pretok Path A)@@ -28,25 +28,25 @@ If the log shows:diag: pretok_trl unsupported (ValueError('The chat template is not training-compatible (missing prefix-preservation or `{% generation %}` markers) and patching is not supported for this template. ...')); using multi_header fallback```-the job may still train, but assistant-only masks are the weaker Path B. **Onboarding is not done until Path A succeeds** (`pretok paths:` contains `trl_training_template` or `native_generation_markers`, not only `multi_header_fallback`).+the job may still train, but assistant-only masks are the weaker Path B. **Onboarding is not done until Path A succeeds**: `pretok_row` returns `path` `trl_training_template` or `native_generation_markers`, not `multi_header_fallback`. A missing `pretok_trl unsupported` line is not proof: when TRL's helper is unavailable the fallback is silent, and preprocessing does not keep the path.How to check (tokenizer issue — LoRA is enough; skip a second Full run):1. Probe the catalog **`hf_model_id`**, not the catalog `id`. Unsloth repos often ship a different `chat_template.jinja` than the upstream id; TRL and our patches match the live string after `from_pretrained`.-1. Tiny Modal LoRA (`MAX_STEPS=2`, short `MAX_LENGTH`) is enough. Read `runs/<run_id>/train_stdout.log` for `pretok paths:` / `pretok_trl unsupported`.+1. Tiny Modal LoRA (`MAX_STEPS=2`, short `MAX_LENGTH`) is enough. Pretok runs in CPU preparation, so read `preparations/<id>/preprocess_stdout.log` on the SFT volume for `pretok_trl unsupported`, and confirm Path A by calling `pretok_row` on a sample conversation in the training image and reading its `path`.1. One size is not enough when Unsloth templates differ inside a family (Gemma 4 E2B vs 12B, Qwen3-0.6B vs 8B, Qwen3.5-0.8B vs 4B). Hash the Hub template for each `hf_model_id` you enable.How to fix — do **not** branch in `engine_unsloth.py` / `pretok.py`:1. Save the **live** Hub template as a base jinja under `overbae/services/sft_assets/` (existing dirs: `llama_templates/`, `qwen_templates/`, `gemma_templates/`, …).1. Copy it to `*_training.jinja` and wrap only assistant-generated spans in `{% generation %}` / `{% endgeneration %}`. `{% generation %}` is a real Jinja block: it cannot open inside `{% if %}` and close after `{% endif %}`, and `{% if %}`/`{% else %}`/`{% endif %}` must sit wholly inside or wholly outside it. The training file must render **byte-identical** text to the base; markers are invisible in the rendered string. Qwen3's twins omit the empty `<think>` block the base inserts on a final assistant turn: that block is not prefix-preserving, and serving keeps thinking off. Compile every twin (see `test_every_training_template_compiles`).-1. Register `(base, training)` in `KNOWN_TEMPLATE_PATCHES` in `overbae/services/sft_assets/training_chat_template.py`. `pretok.py` and `engine_unsloth.py` both call `patch_known_training_template` — that is the only dispatch table.+1. Register `(base, training)` in `KNOWN_TEMPLATE_PATCHES` in `overbae/services/sft_assets/training_chat_template.py`. `pretok.py` calls `patch_known_training_template` — that is the only dispatch table.1. Add a pair assertion in `tests/test_sft_training_chat_template.py` (or rely on `test_every_patch_pair_exists_and_training_has_markers`).1. `sft_assets` is baked into the train image (`add_local_dir`). A pretok/jinja change does nothing until `modal deploy` of `overbae/modal/modal_sft_worker.py`. Re-run the LoRA probe after deploy.## 3. If a model fails on its assigned environment, re-derive the GPU, don't patch around it-GPU selection for training lives in `finetuning_runner.py`'s `_GPU_TABLE` / `_GPU_TABLE_FULL` (params_b → gpu_type/count) plus the `_LONG_CONTEXT_H200` bump and any family-specific clamp (e.g. `clamp_gemma4_training_gpu` — Gemma4 forced onto 1×H200 because Unsloth's `device_map="balanced"` multi-GPU split is broken for it).+GPU selection for training lives in `finetuning_runner.py`'s `_GPU_TABLE` / `_GPU_TABLE_FULL` (params_b → gpu_type/count) plus the `_LONG_CONTEXT_H200` bump and any family-specific clamp (e.g. `clamp_gemma4_training_gpu` — a Gemma4 run the table puts on more than one GPU moves to 1×H200, because Unsloth's `device_map="balanced"` multi-GPU split is broken for it).If a new model OOMs or errors on its assigned GPU:@@ -59,7 +59,7 @@ If a new model OOMs or errors on its assigned GPU:For every new model, before it's usable for finetuning:1. **Find the real max context length.** This is the HF `max_position_embeddings` (no RoPE/YaRN scaling) — it goes in `finetuning.context_length` in `models.json`, distinct from the top-level `context_length` (published inference window, which may be YaRN-extended).-1. **Probe each enabled training type (`full`, `lora`) independently.** Use `scripts/calibrate_activation_budget.py` (`--experiment e3` context sweep, spawns real Modal `sft_unsloth` jobs and reads peak VRAM) to find the largest context that actually trains without OOM.+1. **Probe each enabled training type (`full`, `lora`) independently.** Run tiny real Modal jobs (`MAX_STEPS=2`) at increasing `MAX_LENGTH` and read `vram_peak_gb` from the run's metrics records to find the largest context that trains without OOM. The repo has no calibration script for this sweep.1. **Try H100 first, then H200.** `TRAINING_GPU_VRAM_GB = {"H100": 80.0, "H200": 141.0}` (`finetuning_policy.py`) — H100 has less VRAM, so it's the cheaper GPU and must be tried first. Only fall back to H200 if the model can't reach its real max context length on H100.1. **Record the result per training type** in `models.json` under `finetuning.training_type.<full|lora>`:- `context_length`: the largest context that trained successfully (equal to `finetuning.context_length` if the full ceiling was reached, lower otherwise).@@ -76,10 +76,10 @@ Model configuration — context lengths, batch sizes, training type enablement,Actual training cost is **computed, not stored per model** — `overbae/services/finetuning_pricing.py` derives it from fields already in `models.json`:-- Baseten/Modal: `estimate_training_cost()` picks GPU count from `_BASETEN_GPU_COUNT_TIERS` keyed on `total_params_b`, estimates duration from FLOPs (`6·N·D` full / `4·N·D` LoRA at 35% assumed MFU), and bills GPU-count × minutes × the fixed H100 per-minute rate.-- Together: `training_price_per_million()` looks up a $/1M-token rate from `_TOGETHER_SFT_TIERS`, again keyed on `total_params_b`.+- Modal (the only backend settings allow): `estimate_training_cost()` picks GPU count from `_BASETEN_GPU_COUNT_TIERS` keyed on `total_params_b`, estimates duration from FLOPs (`6·N·D` full / `4·N·D` LoRA at 35% assumed MFU) plus a fixed 10-minute overhead, and bills GPU count × seconds × `_MODAL_H100_USD_PER_SECOND`.+- The Baseten (per-minute) and Together (`training_price_per_million()`, `_TOGETHER_SFT_TIERS`) branches remain for catalog entries on those backends.-So as long as the new model's `total_params_b` is set correctly in `models.json`, cost estimation works automatically — don't add a new pricing branch or per-model rate to `finetuning_pricing.py`. The only case it returns `None` is a >100B-param Together model, which needs an individually negotiated rate (not in this catalog today).+So as long as the new model's `total_params_b` is set correctly in `models.json`, cost estimation works automatically — don't add a new pricing branch or per-model rate to `finetuning_pricing.py`. It returns `None` for an unpriced backend, for zero trained tokens, and for a >100B-param Together model, which needs an individually negotiated rate.The one thing to add by hand is the **marketing "from" floor**: `models.json`'s `pricing.train_from_usd` (paired with `pricing.run_from_usd_per_1m_output` — `model_library.py`'s `_pricing()` drops the whole block from the API response unless both are set). This is a display-only number for the model library UI, not read by the cost estimator. Set it by calling `estimate_training_run()`/`estimate_training_cost()` for a small representative dataset on the new model and rounding to a customer-facing number consistent with similarly-sized peer models already in the catalog (e.g. dense ~1-4B models cluster around `0.5–0.7`, larger dense/MoE tiers step up to `1.0–2.5`, frontier-scale up to `4.5–5.0`).@@ -87,7 +87,7 @@ The one thing to add by hand is the **marketing "from" floor**: `models.json`'sIf the family has no existing icon mapping, it falls through to a generic simpleicons/placeholder fallback (see `model-provider.ts`'s `SIMPLEICONS_SLUG_FIXES`, and `model-provider-chip.tsx`'s `ProviderLogo` fallback chain). To add one:-1. Add a `ProviderId` variant and `PROVIDER_BY_SLUG` entry in `frontend/src/components/model-provider.ts` (or a `PROVIDER_ALIASES` entry if it should map onto an existing provider, e.g. Meta/NVIDIA).+1. Add a `ProviderId` variant and `PROVIDER_BY_SLUG` entry in `frontend/src/components/model-provider.ts` (or a `PROVIDER_ALIASES` entry if it should map onto an existing provider, e.g. `metallama` → `meta`).1. If a dedicated icon should render (not the CDN fallback), import the `@lobehub/icons` component and add it to `PROVIDER_ICONS` in `frontend/src/components/model-provider-chip.tsx`.1. Extend `inferProviderFromModelId()` if the model id doesn't carry an explicit provider prefix.@@ -95,9 +95,9 @@ If the family has no existing icon mapping, it falls through to a generic simple- [ ] Family resolves correctly (`modal_shared/modelfam/registry.py` pattern order) — add a `FamilySpec` only if genuinely new, otherwise reuse- [ ] Family quirks live in a hooks module, not in `engine_unsloth.py`/`finetuning_runner.py`/`finetuning_policy.py`-- [ ] Chat template is pretok Path A on the **`hf_model_id` tokenizer** (log `pretok paths:` is `trl_training_template` or `native_generation_markers`). If TRL cannot auto-patch, add a byte-identical `{% generation %}` twin and register it in `training_chat_template.py` `KNOWN_TEMPLATE_PATCHES`; LoRA-only is enough to verify. Redeploy the SFT worker after jinja/pretok edits+- [ ] Chat template is pretok Path A on the **`hf_model_id` tokenizer** (`pretok_row` returns `path` `trl_training_template` or `native_generation_markers`). If TRL cannot auto-patch, add a byte-identical `{% generation %}` twin and register it in `training_chat_template.py` `KNOWN_TEMPLATE_PATCHES`; LoRA-only is enough to verify. Redeploy the SFT worker after jinja/pretok edits- [ ] `finetuning.context_length` set to the real HF max position embeddings-- [ ] Context probed per training type, H100 before H200, via `calibrate_activation_budget.py`+- [ ] Context probed per training type, H100 before H200, with real Modal runs- [ ] `training_type.{full,lora}.context_length` + `validated_context_length` set from actual probe results- [ ] `real_max_context_length` set and consistent with validated training types- [ ] `tests/test_modelfam.py` passes, including `test_baseten_real_max_context_length`diff --git a/.agents/skills/frontend-design/SKILL.md b/.agents/skills/frontend-design/SKILL.mdindex 132a9ad2..c5423394 100644--- a/.agents/skills/frontend-design/SKILL.md+++ b/.agents/skills/frontend-design/SKILL.md@@ -1,98 +1,82 @@---name: frontend-design-description: Overmind Console design system — semantic tokens, shared primitives, geometry and icons, the border-contrast floor, the duplicated table implementations, and the verification scripts. Use when writing or changing frontend UI, styles, tables, or component markup.+description: Overmind Console design system — semantic tokens, shared primitives, geometry and icons, the border-contrast floor, the duplicated table implementations, canvas decisions and the verification scripts. Use when writing or changing frontend UI, styles, tables, or component markup.---# Frontend design conventions-The Console is "a quiet workshop for agent improvement" — warm minimalism, copper/gold brand, Geist Pixel for body, card, section and popup text, PP Mondwest only for main page titles, and NeueBit for navigation, small radii, flat surfaces. Keep it; don't drift toward default Tailwind.+The Console is "a quiet workshop for agent improvement": warm minimalism, a copper brand, small radii, flat surfaces. Geist Pixel is the body, card, section and popup face; PP Mondwest is only for main page titles; NeueBit is for navigation. Keep it; don't drift toward default Tailwind.-The token spec is the root `DESIGN.md` — extend its values, don't restructure it. The Console is dark-only: palette values live on `:root` in `frontend/src/styles.css`, exposed under `@theme inline`. First paint, authentication, toasts and flow canvases stay dark regardless of stored or OS preferences. Do not add a theme selector, theme provider or preference listener.+The token spec is the root `DESIGN.md`; extend its values, don't restructure it. The Console is dark-only: palette values live on `:root` in `frontend/src/styles.css`, exposed under `@theme inline`. First paint, authentication, toasts and flow canvases stay dark whatever the stored or OS preference. There is no theme selector, theme provider or preference listener.-## Color — semantic tokens only+## Color: semantic tokens only-- **Never** raw Tailwind palette utilities (`bg-green-500`, `text-blue-600`, `border-amber-400`) or hex in class strings (`bg-[#1c1917]`).-- **Status** → the four semantic tokens as a tint triplet. The palette is fixed, so **no `dark:` variants**: `border-success/40 bg-success/10 text-success`. Meanings: `success` = passed/healthy/connected/completed; `warning` = review/degraded/stale; `info` = running/pending/queued/training; `destructive` = failed/error/cancelled. Prefer the components — `<Badge variant="success|warning|info|error|neutral">` or `<StatusBadge status={domainStatus(state)}>` (`lib/job-status.tsx`, `lib/colors.ts`).-- **Categorical** — a fixed set of entity types, not status → `text-cat-1 … text-cat-6` / `bg-cat-1/10`. Assign a stable slot per type.-- **Login / onboarding**, the always-dark cinematic surfaces → the named `--auth-*` tokens (`bg-auth-panel`, `border-auth-border`, `text-auth-text-dim`, `text-auth-accent`, …), never inline hex.-- Neutrals → `bg-background/card/muted`, `text-foreground/muted-foreground`, `border-border`. Titles use `text-foreground`, never `text-black dark:text-white`.+- Use no raw Tailwind palette utilities (`bg-green-500`) and no hex in class strings (`bg-[#1c1917]`).+- **Status** uses a tint triplet, with no `dark:` variants: `border-success/40 bg-success/10 text-success`. The tones are `success` (passed, healthy, connected, completed), `warning` (review, degraded, stale), `info` (running, pending, queued, training), `error` (failed, cancelled; the `destructive` token) and `neutral` (draft, skipped, awaiting launch, unknown). Prefer `<Badge variant="success|warning|info|error|neutral">`; `variant="destructive"` is a solid fill, not the tint. For a domain state use `<StatusBadge status={state} fallback=…>`, which maps it through `domainStatus` itself (`lib/job-status.tsx`, `lib/colors.ts`).+- **Categorical** entity types use `text-cat-1 … text-cat-6` and `bg-cat-1/10`, one stable slot per type.+- **Login and onboarding** use the `--auth-*` tokens (`bg-auth-panel`, `border-auth-border`, `text-auth-accent`, …).+- Neutrals: `bg-background`, `bg-card`, `bg-muted`, `text-foreground`, `text-muted-foreground`, `border-border`.-## Border contrast — hard constraint+## Border contrast-`--border` at full strength is only ~1.3:1 against a card; the visibility floor in `scripts/check-contrast.mjs` is 1.2. The sanctioned ramp:+`--border` at full strength is only about 1.3:1 against a card; the visibility floor in `frontend/scripts/check-contrast.mjs` is 1.2. Use the sanctioned ramp: outline `border-border`, divider `border-border/70`, faint `border-border/60`. Anything below `/60` is invisible. Run `bun run check:contrast -- --all` before you lower a border opacity.-- outline = bare `border-border`-- divider = `border-border/70`-- faint = `border-border/60`+## Shared primitives-Anything below `/60` is invisible. Never lower a border opacity without running `bun run check:contrast -- --all` and reading the border rows.--## Shared primitives — use them, don't hand-roll--- A page title is `<PageHeader title description count actions icon leading/>`. Never a raw `<h1>`.-- A page scaffold is `<PageShell variant="scroll|full" header/>`.-- Initial pages use `<LoadingState label fullPage/>`, an accessible spinner inside the existing page shell. Unknown-layout regions use `<LoadingState label/>`. Reserve `Skeleton` for known component or asset slots that match the real dimensions: table headers/columns/rows, chart frames, metadata and controls. Keep loaded content mounted during background refreshes, including selections, expanded rows and canvas position. Announce loading once per region, hide decorative placeholders and respect reduced motion. Pending actions and live jobs use `<Spinner size/>`; never hand-roll `animate-spin`. See DESIGN.md § Loading and live updates.-- An empty state is `<EmptyState icon title description action size/>`.-- A titled card is `<SectionCard title …>`; plain `<Card>` otherwise. Don't hand-roll `rounded-lg border` surfaces.-- A destructive confirm is `<ConfirmDialog destructive onConfirm/>`. Never `window.confirm`. Dialog Cancel is always `variant="secondary"` (what `AlertDialogCancel` renders).-- Feedback: `sonner` toast = transient async result; `Alert` = persistent inline notice; `DismissibleAlert` = in-dialog mutation error.-- Model choices use `ModelOptionLabel`: provider logo, model name, then separate metadata. Use it in both dropdown rows and selected values, including judge, benchmark, comparison and filter selectors. Keep fit/cost/size annotations and selection rules; model IDs remain the stored values. `ModelProviderChip` is for read-only badges, not dropdown rows.+- Page title: `<PageHeader title description count actions icon meta/>`, never a raw `<h1>`. Page scaffold: `<PageShell variant="scroll|full" header/>`.+- Loading: `<LoadingState label fullPage/>` for initial pages, `<LoadingState label/>` for unknown-layout regions, `Skeleton` only for slots whose real dimensions are known. Keep loaded content mounted during background refreshes. Pending actions and live jobs use `<Spinner size/>`, never a hand-rolled `animate-spin`. See DESIGN.md § Loading and live updates.+- Empty state: `<EmptyState icon title description action size/>`. Titled card: `<SectionCard title …>`; otherwise `<Card>`. Don't hand-roll `rounded-lg border` surfaces.+- Destructive confirm: `<ConfirmDialog destructive onConfirm/>`, never `window.confirm`. Dialog Cancel is `variant="secondary"`.+- Feedback: `sonner` toast for a transient async result, `Alert` for a persistent inline notice, `DismissibleAlert` for an in-dialog mutation error.+- Model choices use `ModelOptionLabel` (provider logo, model name, then metadata) in dropdown rows and selected values. `ModelProviderChip` is for read-only badges. Model IDs stay the stored values.## Geometry, type, icons-- **Flat surfaces** — standard `shadow-*` utilities remain disabled. Depth = surface layering + 1px borders. Shared confirmation dialogs alone use `shadow-confirmation`, a subtle palette-matched drop shadow requested by the user.-- Radii: `rounded-sm` for interactive primitives, `rounded-md` for containers. `rounded-lg/xl/2xl/3xl` are off-system. The Workshop bezel uses the same `rounded-md` (3px) as other pages. Dataset navigation shares the outer bezel with the content; its 248px grid column starts collapsed and expands with the notebook's folder toggle, with a reduced-motion alternative. Rows are 28px on desktop and 36px on touch layouts, with no gaps between items. Mobile reveals the same navigation in the bezel while retaining the hidden notebook; it does not create a separate pane.-- Main page titles use `TITLE.page` (PP Mondwest). Card, section, dialog, sheet and empty-state headings use their `TITLE` role in Geist Pixel. Never add Mondwest outside the main page title. `font-mono` also resolves to Geist Pixel; Fira Code is not shipped.-- Icons: **always the central registry** — `import { Icon } from "@/components/ui/icons"` → `<Icon.name className="size-4" />`. The glyphs are pixelarticons paths vendored into `ui/icons/glyphs.ts` (24×24 grid, 2px inset, `currentColor`); never import that module or `lucide-react` in app code; both fail `check:design`. One concept = one glyph (`Icon.delete` = trash, `Icon.close`/`Icon.failed` = the "X"). Missing a glyph? Add `name: glyph("<svg-name>")` to `ui/icons/index.ts`, the only file that may read the table, then `bun run icons:vendor` with `PIXELARTICONS_LICENSE_KEY` set (or `--source <svg dir>` of an unlocked package) — typecheck fails until the table is regenerated. Removing one is the reverse. There is no icon package to install. Sizes: `size-4` in buttons, `size-[17px]` in nav, `size-3` for dense chips.+- Flat surfaces: `shadow-*` utilities are disabled. Depth is surface layering plus 1px borders. Shared confirmation dialogs alone use `shadow-confirmation`.+- Radii: `rounded-sm` for interactive primitives, `rounded-md` for containers, `rounded-xs` only for elements smaller than about 8px. `rounded-lg` and larger are off-system.+- Main page titles use `TITLE.page` (Mondwest); every other heading uses its `TITLE` role in Geist Pixel. `font-mono` also resolves to Geist Pixel.+- Icons come only from `import { Icon } from "@/components/ui/icons"` → `<Icon.name className="size-4" />`. The pixelarticons paths are vendored in `ui/icons/glyphs.ts`; app code never imports it or `lucide-react` (`check:design` fails). One concept, one glyph. Provider logos are the exception: `model-provider-chip.tsx` imports `@lobehub/icons`. To add a glyph, add `name: glyph("<svg-name>")` to `ui/icons/index.ts`, then run `bun run icons:vendor` with `PIXELARTICONS_LICENSE_KEY` set (or `--source <svg dir>`). Sizes: `size-4` in buttons, `size-[17px]` in nav, `size-3` in dense chips.-## Two duplicated table implementations+## Two table implementations-Workshop cells retain their existing markup and controls inside the same React Flow-infrastructure used by Agent. Cell headers drag on a 20px grid; elbow edges follow-recorded lineage. Steps cascade downward, with sibling branches side by side on-the same horizontal layer. Cells open full-width at scale 1. Preserve max-w-7xl-and original notebook padding; explicit zoom and Fit view change only the camera.-Reset and linked-cell focus restore scale 1; resizing preserves the chosen zoom.-Reuse Agent trajectory controls and its toggleable, persisted minimap treatment.-The minimap toggle shares the right-hand control box with the dataset sidebar-button; there is no cell-search button or cell-selector strip.-Positions persist per project/dataset in the browser and never-change execution. Canvas wrapper styles must not redesign cells or the rows grid. Corrections replace the-displayed process; there is no repair-history or restore view. Verified source,-script, derivation and partition dependencies connect related datasets. Condition chips sit just above destination handles,-with an opaque card surface and input-token border, not on the shared branch rail.+A table fix applied to one misses the other:-A table fix applied to one codepath silently misses the other:+1. `src/components/ui/data-table.tsx` — the shared TanStack `<DataTable>` (Traces, Sessions, Runs, Datasets, Experiments, Billing), with inline sort headers.+1. `src/components/datasets/notebook/rows-grid.tsx` — the paged rows grid every dataset table renders through. Hand-built tables use `components/ui/sortable-header.tsx`.-1. `src/components/ui/data-table.tsx` — the shared TanStack `<DataTable>` (Traces, Sessions, Runs, Datasets, Experiments, Billing)-1. `src/components/datasets/notebook/rows-grid.tsx` — the paged rows grid every dataset table (source, cell output, product) renders through+Eval results align model variants by a sample key (`components/evaluations/generated-run-results.tsx`): the cell row index (`metadata.legacy_sample.row_index` first, then the generated client's `rowIndex`, including zero) when the run has a cell, else `sourceTraceId`, together with input and reference; samples with neither keep their own identity. Unrelated outputs never collapse or stand in for another model's missing response.-Sort headers are in `components/ui/sortable-header.tsx` for hand-built tables and inline inside `data-table.tsx` for the shared one — check both before declaring a header fix done.+Evaluation tables show the rule, its trajectory step or tool, its method (code check or model judge) and its definition origin. Enabled-only views don't repeat an Enabled badge on every row.-Eval results align model variants by the generated client's `rowIndex`, including zero. Trace-filter samples use `sourceTraceId`; samples with neither keep their own identity. Use `components/evaluations/sample-index.ts` for table and detail lookups so unrelated outputs never collapse or stand in for another model's missing response.+## Datapoint popups-The generative eval datapoint popup selects one model at a time and shows its input beside its generated output, grading reference, and evaluator reasoning. `SampleInput` consumes the generated `EvalSampleIO` contract: captured initial runner requests include system prompts and tools; historical dataset inputs explicitly say the exact request was not captured. Never label a combined trajectory as input or an extracted statistical prediction as the model's full output.+- Generative: one model at a time, its input beside its output, reference and judge reasoning. Never label a combined trajectory as input or an extracted prediction as the full output.+- Native probability: shared frozen input on the left and every model's output in one scrolling list on the right, with no model tabs. Narrow screens stack them.-The native probability datapoint popup shows shared frozen input on the left and all models' outputs in a vertically scrolling list on the right, without model tabs or a selector. Each model keeps its own probabilities, references, scores and missing/error state. Narrow screens stack the input above the model list.+## Canvas decisions-Trajectory cards lead with the behaviour name and a compact source-text preview. Use compact raised-wash headers with the existing console grain asset, categorical icon tiles and inset role labels for task, model call, execution step, tool, local outcome and result. Group input/output and continuation facts in an unbordered subtle-wash inset, with labels above values for a full-width reading measure. Use spacing to separate card content, retaining only the evaluation-footer rule. Model headers combine provider identity and a full-width model chip; the behaviour sentence appears once in the body. Trajectory nodes have no detail sidebar or clickable header. Long on-card text stays available in bounded, keyboard-focusable scroll regions; model calls retain `ModelProviderChip`, including an explicit missing-model chip. The instructions preview opens the full system prompt directly in a dialog. Mode-specific model/prompt context requires an exact step-anchor match; unbound or shared calls show only context common to their candidates. Never borrow a conflicting worker prompt. Excerpts stay labelled as excerpts; missing capture has no expand control.+These apply to the capability trajectory canvas (`components/capability-detail/flow/`). They are decisions, not defaults; keep them:-Trajectory layout keeps the source-authored execution steps, conditional routes and terminals on the main graph. Merge steps only when their labels, source anchors, kind and execution contracts agree. Connect available actions to their owning decision through compact category nodes on the same graph, using the central tool icon and a header chevron. Expanded tools and outcomes are independent canvas nodes, never nested cards or parent containers. Neutral icon controls expand paths without selecting a node. Tool outcomes expand from the Outcomes row in the card body, with the count and chevron forming one control; never put this control in the tool header. Explicit source-backed transitions connect outcomes to result processing, retries and the next decision; keep a summary return connection when a group is collapsed. Never infer a destination from continuation prose. Continuation edges do not expand structural search ancestry. Expanding an action reveals source-cited conditions, local outcomes and continuations in place; preserve viewport context and relayout measured heights. Dashed action edges express available choices, not observed execution. Never create a separate execution overview or action-only navigator. Branches collapse in place; keep shared nodes reachable through open routes. Search the complete graph, reveal hidden matches with their incoming paths, and restore the collapsed state when search clears. Put search in a popover opened from the canvas actions, alongside expand-all and collapse-all; do not add a separate top toolbar or legend. Group canvas actions into a neutral bordered dock and use a matching zoom/fit dock. Open with the whole visible flow fitted to the canvas, including connector routes and condition labels outside node bounds. Fit view restores that overview; search frames the matching path. Use the outward/inward arrow glyphs for global expansion/collapse, and the shared tooltip on every canvas action, including search; native title attributes are not a substitute. Reserve layout space for static condition labels on connectors; do not add duplicate dropdowns for the same rule. Sibling outcomes share a row beneath their tool, with the first outcome aligned for a straight incoming connection. Remaining branches fan out above their conditions without reversing direction. Return paths join below the tallest sibling before the next tool starts. Category widths grow with the complete outcome row; return rails stay beyond the rightmost visible descendant. Keep outcome source handles mounted so disclosure does not leave stale graph geometry. All connectors, including shared tool-return rails, use the same rounded corners. Shared tool-return rails carry no repeated labels; each outcome retains its continuation condition in the card. Distinguish model-selected tools from code branch conditions and nonbinding prompt guidance; an execution branch is not a prediction of the model's tool choice. Mark missing conditions as unmapped. Hide the capability next-step nudge while the trajectory is full screen. Keep the evaluation count toggle in the matching step card; expanding it reveals separate bordered evaluation rows floating beneath the card, with a visible gap and no enclosing panel. Rows show the name, Judge/Check type and stock provenance; selecting one opens its existing definition. Empty steps have a static zero count. Capability-entry rules retain their whole-run scope label; graph path expansion does not control evaluation disclosure. Rules with broad span scopes and rules without a unique source match remain separate. Configured evaluation counts remain separate from measured scores. The canvas run picker searches the complete capability trace history on the server with bounded 25-run pages and date and error filters. Use compact single-line run-ID and time rows in a narrow picker; do not add Latest run, follow-latest or map-view rows. No run is selected automatically. Selecting a new run pins that trace and enables highlighting; selecting the same run toggles highlighting. A matching toolbar route icon toggles highlighting without opening the picker, retaining the selected trace and its scores. Highlighting reveals recorded tools and outcomes and frames the captured route; turning it off restores the previous disclosures and the full map. Match recorded spans by code identity and unique source anchors or tool names, highlight visited steps and recorded connectors, and dim unvisited branches. Never infer uncaptured steps, concurrent call ordering or ambiguous conditions. A conditional outcome requires a named captured span beneath its matching tool; an unbranched result requires a captured tool output. Collapsed tool categories retain recorded execution context; score updates change styling and scores without rebuilding graph geometry or resetting the viewport. The observability icon button opens capability-filtered traces, including the selected trace when present. The card footer and floating rows show the selected run’s measured means and scored-rule counts. Load all score pages for that trace; use only the newest span receipt, excluding trajectory aggregates. Errors and abstentions stay distinct and never become numeric zeros; unmatched rules say Not scored. Score updates must not rebuild graph geometry or reset the viewport. Runtime-only expectations may not exist in the saved matrix.+- Tools and outcomes are separate canvas nodes, never nested cards. Nodes have no detail sidebar and no clickable header.+- No separate execution overview, action-only navigator, top toolbar or legend. Search is a popover in the canvas action dock beside expand-all and collapse-all.+- Never infer a destination from continuation prose, uncaptured steps, concurrent call order or ambiguous conditions. Missing conditions show as unmapped. Dashed action edges are available choices, not observed execution.+- The run picker searches the full trace history on the server in 25-run pages. No "Latest run" or follow-latest rows, and no automatic selection.+- Score updates restyle nodes without rebuilding geometry or resetting the viewport. Errors and abstentions never become zeros; unmatched rules say Not scored.+- Every canvas action uses the shared tooltip; a native `title` is not a substitute.+- The Workshop canvas rules are in the data-workshop skill.## App shell-The left sidebar logic in `src/routes/_auth.tsx` and `src/components/ui/sidebar.tsx` is owned separately — pages adapt to the native in-flow sidebar. Don't add routes to focus-mode patterns or modify shell logic without explicit approval.+The sidebar logic in `src/routes/_auth.tsx` and `src/components/ui/sidebar.tsx` has a separate owner. Pages adapt to the in-flow sidebar. Don't add routes to focus-mode patterns or change shell logic without explicit approval.## Tooling-- Package manager is **Bun** (`bun add`, `bunx shadcn@latest add …`) — never pnpm/npm/yarn. New shadcn components get adapted to the token system after generation.-- **Biome must not format assets.** `.svg` is excluded in `biome.json` — keep it excluded and never run `biome … --write` over `**/*.svg` (2.5.x sorts attributes and corrupted a logo's XML prolog).-- Verify every UI change in the dark-only Console, including first paint with a previously saved light preference:+- Bun only (`bun add`, `bunx shadcn@latest add …`). Adapt generated shadcn components to the tokens.+- Biome must not format assets: `.svg` is excluded in `biome.json`, because biome sorts SVG attributes and once corrupted a logo's XML prolog.+- Verify every UI change in the dark Console, including first paint with a saved light preference:```bashcd frontendbun run typecheck && bun run lintbun run check:all # check:design + check:contrast + check:controls```--Evaluation tables show the rule or authored criterion, its readable trajectory step or tool, its code-check/model-judge method and its recorded definition origin. Order capability rules by trajectory position before tools, and retain broad and unmapped scopes explicitly. Filter by agent part and assessment method; expose raw span identifiers and full definitions in row details. Enabled-only views do not repeat a green Enabled badge on every row.diff --git a/.agents/skills/mcp/SKILL.md b/.agents/skills/mcp/SKILL.mdindex eaa539fc..c0b8d218 100644--- a/.agents/skills/mcp/SKILL.md+++ b/.agents/skills/mcp/SKILL.md@@ -1,108 +1,22 @@---name: mcp-description: End-to-end workflow for adding or changing Overmind MCP tools, resources, prompts, authentication, or result contracts — server layers, catalog registration, MCP-impact classification, and required tests. Use when adding, changing, or removing an MCP tool, resource, prompt, auth rule, or CallToolResult contract.+description: End-to-end workflow for adding or changing Overmind MCP tools, resources, prompts, authentication, or result contracts — server layers, catalog registration, MCP-impact classification, contract versioning and required tests. Use when adding, changing, or removing an MCP tool, resource, prompt, auth rule, or CallToolResult contract.---# Adding or changing MCP-Contract 7.12.0 adds `create_api_key`. It accepts the Console dialog's name,-description and expiry (30, 90, 180 or 365 days, or 0 for never). Omit-`project_id` for an account key; pass `project_id` for a project key. The-plaintext is returned only in that response. A project connection can mint a-key only for its own project. An account connection can mint either scope.-Guests cannot create keys. The secret is not readable again.--Contract 7.11.0 removes automatic OCR language detection. `ocr_languages=[]`-uses English; explicit language choices remain MCP-ready through `update_dataset`.-Supported Tesseract codes are discoverable at `overmind://dataset-upload`. Set-preferences before uploading to a draft. Inspection exposes requested settings-separately from actual languages, model identities and cached-page reuse. Existing import resume retains its-original settings and reuses only matching project-scoped page checkpoints.--Contract 7.8.2 makes SQL query capacity MCP-ready: the interface resource reports-global/per-project concurrency and deadlines. Busy or unavailable admission returns-retryable errors with the exact cell and minimum retry delay. Retry with backoff,-never fan out retries; bulk analysis belongs in retained pipelines.--Contract 7.8.0 makes automatic signal defaults and evidence inspection MCP-ready.-`list_signals` returns `default_enabled` and effective `enabled` values; explicit-capability settings override project settings. `plan_drift` remains opt-in.-`query_traces(signal_event=UUID)` scopes to that event's retained source traces;-signal resources include conversation identity and the retained trace inventory.--Contract 7.6.2 is MCP-ready: exhausted prediction collection completes scoring-from verified available outputs. `results.completion` retains per-suite/per-arm-expected, scored, missing, invalid and incompatible counts, plus stage issues.-`completed_with_issues` is a result annotation, not a new job lifecycle state.-Missing outputs are not quality zeros; paired metrics use shared scored inputs.-Incomplete calibration leaves raw scores available without invented temperatures.-Verification/report failures and unresolved native submissions still need inspection.-Unknown external intents remain missing with uncertain costs; they are not replayed-and do not prevent collecting subsequent inputs. A paused external collector can-resume its explicit stage without a native call ID.--Contract 7.6.1 makes automatic native-evaluation recovery MCP-ready through existing-job receipts: stage retry time/history, running state and polling guidance. Shared-services retry transient local work and collect saved native calls; timed-out-external predictions retry only missing responses within three attempts and retain-uncertain prior costs. Bare submission intents remain unresolved. No new tool is-required; explicit resume uses the same bounded request recovery.--Platform-agent procedure for changing the server. The skill shipped by-`overmind init` is `overmind/skills/overmind/` — do not copy this file there.--The MCP server is the project-scoped agent API. It shares-domain services with the Console and REST API; it does not proxy either of-them.--The optional Claude Code, Codex and Cursor plugins under-`overmind/.{claude,codex,cursor}-plugin/` package the existing MCP connection and-shared workflow skills; their versions match `SKILLS_VERSION` in-`overmind/overmind/skills_db.py`. The focused skills in-`overmind/skills/overmind-*/` cover Agent, Observability, Datasets, Evaluations,-Optimiser, Training, Inference and Integrations; the main `overmind` skill keeps-local setup and workflows across surfaces. CLI initialization installs all of them.-Essential client-independent guidance-belongs in server initialization, tool descriptions and resources; longer-workflows use native prompts and skill fallbacks. The current-project resource-includes `console_url` from `FRONTEND_URL` for ordinary browser navigation.-Do not make a plugin or a custom UI a prerequisite for platform operations.+The MCP server at `/api/mcp/` is the project-scoped agent API. It shares domain services with the Console and REST API; it does not proxy either. This skill is for changing the server. The skills that `overmind init` installs for users live in `overmind/skills/`; never copy this file there.## MCP-impact classification-Contract 7.6.0 adds MCP-ready `save_training_plan` and `training_plan` workflow-inspection. Pilot/full experiment bindings consume immutable task/data/partition-and attributed evidence snapshots. Contract 7.6.3 removes mandatory pilot selection-from full-run eligibility: full runs may launch directly; optional pilot selection-still requires matching measured development metrics and a verified checkpoint. The bounded discovery budget is 91 KiB-for 76 tools. Source/package byte transfers remain CLI-guided. Hardware profiles-are not quality evidence, and exploratory jobs are not universally gated.--For every new or modified Overmind capability, function, API workflow, or-Console workflow, make an explicit MCP-impact decision in the same change. A-change is not complete merely because the frontend works. Classify it as one-of the following:--- **MCP-ready** — an agent can discover, inspect, or progress the workflow.- Add or update the smallest appropriate MCP tool, resource, or prompt in the- same change.-- **CLI-guided** — the workflow needs local files, repository edits, a- binary download/upload, or third-party connector credentials. MCP supplies- the state, exact identifiers, and a structured human/coding-agent action;- the existing CLI or SDK performs the local transfer or edit.-- **Frontend-only** — presentation, navigation, visual exploration, billing,- or another workflow that has no useful safe agent action. The underlying- project state remains MCP-ready when it is useful to agents.-- **Out of scope** — destructive operations remain absent from the public MCP- surface until explicitly designed and authorized.--Record a concrete reason when a change is not MCP-ready. Do not silently let-the Console become the only way to complete an agent-relevant workflow.--Textual state is the required baseline. Console-only visualizations may stay-visual, but their underlying inspectable data and agent actions should be-available through the appropriate MCP surface when they pass the classification-above.+Every new or changed capability, API workflow or Console workflow needs an explicit MCP decision in the same change. Classify it:++- **MCP-ready** — an agent can discover, inspect or progress the workflow. Add or update the smallest tool, resource or prompt.+- **CLI-guided** — the workflow needs local files, repository edits, binary transfer or third-party credentials. MCP returns state, exact IDs and a structured action; the CLI or SDK does the local work.+- **Frontend-only** — presentation, navigation, visual exploration or billing with no useful agent action. The underlying state stays readable through MCP when agents need it.+- **Out of scope** — destructive operations stay off the public surface until designed and authorized.++Record the reason when a change is not MCP-ready. The Console must not become the only way to finish an agent-relevant workflow. Textual state is the baseline; charts may stay visual.## Shape of the server@@ -115,391 +29,93 @@ MCP client-> curated ToolCatalog-> feature tool adapter + strict input/output contracts-> existing domain service / model / task- -> compatible CallToolResult + resource links+ -> CallToolResult + resource links-> client reads overmind:// resources or polls a job receipt```-The entrypoint is `overbae/api/mcp.py`; ASGI mounts it through-`overbae/asgi.py` as the outer Starlette app with Django at `/`. `/api/mcp/`-and the OAuth routes never reach Django's `ASGIHandler`, so-`RequestThreadMiddleware` (outermost) does its two jobs: a-`ThreadSensitiveContext` per request, without which every thread-sensitive-`sync_to_async` call in the process shares one thread, and closing the-request's DB connections on that thread when it ends.-`overbae/services/mcp/server.py` owns the official MCP SDK server, stateless-Streamable HTTP transport, protocol checks, resource and prompt callbacks, and-middleware ordering. Do not create a second MCP app or mount a feature-specific-server. With a PostHog token (`POSTHOG_PROJECT_TOKEN`, or the committed default on-hosted Clerk deployments without DEBUG), it also instruments the server with-PostHog MCP analytics (`$mcp_*` events, a session-token wrapper on the MCP route,-a flush at lifespan shutdown). Events identify the caller by Clerk user id, the-Console's distinct id, and carry `project_id`. They are metadata only: `before_send`-drops tool arguments, results and error text (failures keep `error_code`), and-`$exception` capture is off. Argument injection stays off: catalog input models-forbid extra fields. `tests/test_mcp_analytics.py` holds these invariants.+`overbae/api/mcp.py` is the entrypoint. `overbae/asgi.py` makes the MCP Starlette app the outer ASGI app and mounts Django inside it at `/`; its middlewares pass non-MCP paths through. `/api/mcp/` and the OAuth routes never reach Django's `ASGIHandler`, so the outermost `RequestThreadMiddleware` gives each request a `ThreadSensitiveContext` (without it every thread-sensitive `sync_to_async` call shares one thread) and closes the request's DB connections. `services/mcp/server.py` owns the SDK server, stateless transport, protocol checks and middleware order. Never create a second MCP app or a feature-specific server.++With a PostHog token, the server sends `$mcp_*` analytics. Events carry identity, `project_id` and, on failure, `error_code`: `before_send` drops arguments, results and error text, `$exception` capture is off, and input models forbid extra fields so argument injection stays off. `tests/test_mcp_analytics.py` holds these rules.## Layer ownership-| Layer | Location | Responsibility |-| ------------------ | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Transport | `services/mcp/server.py` | MCP protocol, allowed hosts/origins, request-size limit, SDK callbacks. |-| Authentication | `services/mcp/auth.py` | Authenticate an account/project API key or MCP OAuth token, enforce credential limits, and bind context. |-| Context | `services/mcp/context.py` | Make immutable `{user, token, project, client_ip}` available only during the request. |-| Catalog | `services/mcp/catalog.py` | Publish a curated visible tool set, validate contracts, invoke handlers, and turn known failures into MCP results. |-| Contracts | `services/mcp/contracts/` | Strict Pydantic input/output models, resource links, page metadata, and job receipts. |-| Feature adapters | `services/mcp/tools_*.py` | Resolve project-scoped references and adapt a semantic MCP intent onto domain services. |-| Domain logic | `services/`, `innermind/`, models, tasks | Own business rules, persistence, authorization-sensitive state transitions, and background work. Evaluation and signal tools call `innermind` (runs, comparison, context, health, signals). |-| Results and errors | `result_compat.py`, `errors.py` | Preserve all typed output for every client and emit safe, stable error values. |-| Resources | `resources.py` | Read-only, project-scoped entity state and static CLI handoff guidance. |-| Prompts | `prompts.py` | Native multi-step workflow instructions composed from the public catalog. |--Tools must call the domain layer directly. They may share serializers or-entity-resolution helpers where those express domain semantics, but must not-invoke frontend code, Console tool registries, or an internal REST-endpoint.--## Authentication and authorization--Every MCP request is authenticated before the SDK callback runs. Account API-keys and OAuth grants can access active projects belonging to their user;-project API keys remain limited to their one project and allowed IPs. All-credentials enforce public `read` and/or `write` permissions. `list_projects`-returns only accessible projects. The catalog resolves `project_id` against-membership before invoking project handlers; handlers receive the selected-project only through `MCPContext`. Resources accept the same `project_id` as a-query parameter. Account result links retain it. Selection is per request,-never shared session state; missing or inaccessible projects are rejected.--OAuth uses the installed MCP SDK protocol handlers and durable, hashed codes-and tokens in `models/mcp_oauth.py`. Console sign-in and explicit consent grant-account access, including future memberships. Public clients register with-auth method `none` and S256 PKCE. Authorization and token exchange require the-exact `MCP_SERVER_URL` resource. Access tokens expire after one hour; refresh-tokens rotate without a time-based expiry; authorization continues until revoked.-Refresh-token reuse revokes the family. Account status and project memberships-remain enforced on every request.-OAuth credentials work only on MCP. API keys remain supported through-`X-Api-Key` or `Authorization: Bearer`.--Set `MCP_SERVER_URL` to the deployed HTTPS `/api/mcp/` URL (local loopback HTTP-is supported). Only configured OAuth servers advertise a Bearer challenge and-discovery/registration routes. `OPENAI_APPS_CHALLENGE` serves the public domain-verification token at `/.well-known/openai-apps-challenge`.--`ToolDefinition.required_scopes` records the product capability a tool needs-(`overmind:read`, `overmind:data:write`, and so on). Catalog visibility-currently enforces the public `read_only`/`read` versus mutation/`write`-boundary. If more granular API-key enforcement is introduced, implement it in-the catalog/auth layer for every tool—do not add one-off handler checks.--The public surface remains permission-scoped read/write. Deliberate lifecycle operations are `cancel_dataset`, `retry_deployment`, `retry_data_partition`, native-comparison pause/resume, and performance resume. Do not infer generic destructive operations from these exceptions. A comparison pause prevents new claims; in-flight work may complete and retain receipts. Unacknowledged native submissions and bare external intents require reconciliation. Recorded external prediction transport failures use the bounded automatic recovery policy, retaining uncertain costs.--Contract 5.1 retains draft → optional background preparation → explicit launch. `run_inference` requires a stable request key and returns an `inference_request` job; read its result with `get_job`. Unknown acknowledgements are reconciled without another submission. `inspect_operation` pages durable operational events; reads never invoke workers. `overmind://interface/current` and `list_projects` return the request-derived MCP endpoint, Console origin and permission-scoped tool count/catalog fingerprint. Compare these with the intended environment and refresh `tools/list` on a mismatch; never silently change endpoints or credentials. The interface resource also returns lifecycle rules; it does not attest that remote GPU images are deployed. Ordinary action receipts stay compact and point to detailed resources. Nested partition, sampling, workload and inference settings are typed; training hyperparameters are an intentional model-dependent extension validated by the training serializer/catalog. Manifest budget is 72 KiB including the five reusable-pipeline lifecycle tools and their typed inputs. Package bytes remain CLI-guided; script execution and binding lifecycle are MCP-ready. Pipeline revisions return explicit `flow` nodes, input edges, conditions and output. Native agents declare script conditions with code-line provenance; measured branch outcomes remain separate run facts. Forks execute from their declared parents; compatible disjoint branches converge through inputs. Cycles and job-level conditional skipping are not supported.+| Layer | Location | Responsibility |+| ------------------ | ---------------------------------------- | -------------------------------------------------------------------------------------- |+| Transport | `services/mcp/server.py` | Protocol, allowed hosts and origins, request-size limit, SDK callbacks |+| Authentication | `services/mcp/auth.py`, `oauth.py` | API keys and OAuth tokens, credential limits, context binding |+| Context | `services/mcp/context.py` | Immutable `{user, token, project, client_ip, inference_base_url}` for the request only |+| Catalog | `services/mcp/catalog.py` | Curated visible tools, contract validation, handler calls, known failures |+| Contracts | `services/mcp/contracts/` | Strict Pydantic inputs and outputs, resource links, pages, job receipts |+| Feature adapters | `services/mcp/tools_*.py` | Resolve project-scoped references and map an intent onto domain services |+| Domain logic | `services/`, `innermind/`, models, tasks | Business rules, persistence, state transitions, background work |+| Results and errors | `result_compat.py`, `errors.py` | Same typed output for every client; safe, stable errors |+| Resources | `resources.py` | Read-only, project-scoped state and CLI handoff guidance |+| Prompts | `prompts.py` | Multi-step workflow recipes composed from the public catalog |++Tools call the domain layer directly. They may share serializers or entity-resolution helpers, but never call frontend code, Console registries or an internal REST endpoint. If a Console workflow has no reusable service, fix the service boundary first.++## Authentication++- Every request authenticates before the SDK callback. Account API keys and OAuth grants reach the user's active projects; project keys stay on one project. Every API key enforces its allowed IPs, and all credentials enforce `read` and `write`.+- Account credentials pass `project_id` per operation; `list_projects` returns accessible projects. The catalog checks membership before the handler runs, and handlers get the project only from `MCPContext`. Selection is per request, never session state.+- OAuth uses the SDK protocol handlers with hashed codes and tokens in `models/mcp_oauth.py`. Public clients register with auth method `none` and S256 PKCE, against the exact `MCP_SERVER_URL` resource. Access tokens last one hour; refresh tokens rotate, and reuse revokes the family. OAuth works only on MCP; API keys use `X-Api-Key` or `Authorization: Bearer` (or `Api-Key`).+- `ToolDefinition.required_scopes` records the capability a tool needs; visibility enforces read versus write. Granular enforcement, if added, belongs in the catalog or auth layer for every tool, never in a handler.+- Tool names containing `delete`, `remove`, `cancel`, `retry` or `undeploy` are rejected unless they are in `_ALLOWED_LIFECYCLE_TOOLS` (`catalog.py`); the destructive ones are also in `_DESTRUCTIVE_TOOLS`. Adding to either list needs explicit approval. Do not infer generic destructive operations from the existing entries.## Adding or changing a tool-Contract 7.7 adds MCP-ready version-bound Workshop analytics to cell inspection-and completed pipeline receipts, shared with REST/Console. `explore_dataset`-backfills older cells; reads never scan. Surface warning/error and `not_checked`-results before consumer handoff, with exact fingerprint and coverage. This is-advisory evidence, not a universal quality gate.--Contract 5.2 adds `author-dataset-transformation` and-`inspect_dataset_workbench(pipeline=REVISION_UUID)` for exact recipe lookup,-paged family history and revision-scoped runs/bindings. Stale family writes return-`revision_conflict`. The server instructions explicitly permit approved isolated-script packages; semantic/provider work remains native-agent-owned. The interface-resource declares row-routing limits and unmeasured branch-coverage guarantees.--Contract 5.3 returns project-bound upload argv for drafts, row-check scopes and-failed check details, queue age/poll interval/terminal time for Workshop runs,-and a separate unmeasured task-suitability assessment in training readiness.-Prompts and server instructions require capability inspection and a verified-platform handoff; local artifacts alone do not complete Overmind preparation.-Workbench results carry project scope and executable next_actions; dataset inspection-points to the exact active pipeline receipt instead of an earlier landing job.--Contract 5.4 adds `inputs` for distinct-earlier parents, concatenated in declared order. Declarative `merge` retains their-disjoint observations; overlapping source_row identities fail. Flow exposes terminal-and unconsumed steps; receipts retain per-input counts, fingerprints and cell IDs.-Training preparation converges intended branches to trainable output, with unresolved-review evidence preserved. This is not a relational key join or job-level skipping.--Contract 5.5 adds cell `transformation` attribution to `inspect_dataset`: exact-completed run, revision, package checksum and entrypoint, checked against publication-membership and output fingerprint. External imports and unrecorded history never-claim platform execution. Existing package resources share checksum-verified file-pagination with REST; read every retained helper/manifest without executing code.-Author meaningful logic in each entrypoint and only reusable functions in helpers.--Contract 5.6 keeps Workshop polling, idempotent run receipts and workbench history-compact: measured counts, checks, identities and timings remain inline; each run's-`evidence_resource` retains the original row examples and preview samples. Reading-that resource never executes work. Query results over 200 columns or 32 KiB fail-explicitly without clipping data or column metadata.--Contract 5.6.1 exposes PDF native-text recovery facts through existing source-inspection and upload guidance. Recovery engine, pages and measured encoding-artifacts are distinct from OCR confidence and semantic/visual correctness.--Contract 5.7 adds measured script runtime phases and preview duration, a bounded-query deadline, actionable package-parameter diagnostics and checksum-verified-original-source CLI exports. Native training readiness returns only the eligible-catalogue, not chat rankings or heuristic prices. `batch_size` is the effective-optimizer batch; unsupported accumulation/micro-batch overrides are rejected-before dispatch and in estimates with a recoverable authored diagnostic.-Training estimates preserve the requested baseline choice. New Modal charges and-forecast duration evidence use deduplicated worker receipts, not collector delay;-`recorded_basis` exposes the saved charge calculation. Terminal training timelines-are closed by finalization or passive local reconciliation, without another provider-call. Historical unverified charges and all-in invoice components remain explicit.--Contract 6.1 adds `inspect_training_progress` and `cancel_finetune`. Monitoring-policy, checks, generated evidence, sample identities and retained checkpoint-metadata are MCP-ready; charts are frontend-only and checkpoint bytes remain a-CLI handoff. Inspection reads persisted receipts without invoking workers.-Readiness/preparation/estimate/launch accept the same strict monitoring policy;-provider capabilities and unmeasured check costs remain explicit. Cancellation-records intent first and preserves durable evidence. Evidence responses have a-128 KiB lossless bound and return an error rather than clipping values. The current-tool-manifest budget is 92 KiB. Refresh the connected catalogue after deployment.-Native per-question metrics and assessments have `collections` descriptors in-check/checkpoint overviews. Pass a descriptor's `field` JSON Pointer with-`offset`/`limit` for exact retained object entries or array items. Append escaped-keys or indices to inspect a nested field that exceeds the response limit.-`field`, `check` and `probe` are mutually exclusive and job-scoped; REST-monitoring-evidence uses the same field pagination.-Check `facts.delivery` reports the first valid loss result's collector receipt time-and check-finish observation time. These are not worker timestamps or user-feedback-scores; passive inspection never emits another lifecycle analytics event.--Contract 6.2 adds `generation.kind=json_fields` with bounded explicit JSON Pointers-through the existing shared monitoring policy. Model-catalogue discovery advertises-it; no new tool is needed. Checks expose per-field and complete-example pass rates,-unscorable references and technical coverage. This is MCP-ready; the Console uses-the same receipts. Field meanings stay native-agent-owned. Worker deployment is-required for new runs; existing pinned runs retain their original contract.--Contract 6.2.1 retains `latest_generation_check` in compact job monitoring even-when a newer check contains only loss. Receipt-collected classification-`facts.assessment` compares the same scored subset with its majority-label baseline-and identifies represented labels without predictions. Source receipt, rule-version, coverage and assessment time are separate from immutable worker metrics.-Reads never derive missing assessments or change training. This is MCP-ready-through existing job/inspection resources; no new tool or worker deployment.--Contract 6.0 requires a retained Python package for every new Workshop revision.-The save schema removes inline steps; shared services reject package-free historical-revisions for validation, new runs and bindings. Historical receipts remain readable-with original attribution. Workbench authoring facts replace the operation catalogue;-pipeline.executable identifies package-backed revisions, not verified semantic quality.-MCP input errors point to pipeline-upload and overmind://dataset-upload; optional-installed guidance is not the enforcement boundary.--`get_model_catalog` also returns each foundation's nullable `openrouter_id` and-`openrouter_status`. Availability is catalogue evidence, not inference success or-credential readiness. The shared benchmark resolver uses the same exact identities;-`not_listed` and `catalog_unavailable` are distinct from an available provider route.--1. Classify the change above. Reuse a current tool when the agent intent is- unchanged; do not mirror a REST endpoint merely because it exists.-1. Add strict Pydantic request and response models under- `services/mcp/contracts/<domain>.py`. Extend `MCPModel`, bound collection- sizes and strings, and reject unknown fields. Use aliases only when they- preserve a deliberate public compatibility contract.-1. Put the handler in the matching `services/mcp/tools_<domain>.py` module.- Resolve all entities within `context.project`, call the existing domain- service/model/task, and translate expected failures to `MCPError`.-1. Register one `ToolDefinition` through that module's- `register_<domain>_tools` function. Declare accurate `read_only`,- `idempotent`, `open_world`, `required_scopes`, `cost_class`, and- `async_mode` metadata. The central `CATALOG` imports feature registrations;- add a new import there only when introducing a genuinely new domain module.-1. Return the declared output model, never a raw dictionary. The catalog- validates it before publishing. Add a `resource` or `resource_links` field- for durable entities that the agent can inspect next.-1. For background work, return a `JobReceipt`-shaped object with `kind`, `id`,- `status`, and an `overmind://jobs/{kind}/{id}` resource. Ensure `get_job`- and the resource reader understand that job kind before shipping.-1. Add a prompt only when the public tool sequence needs reusable guidance or- a human approval checkpoint. A prompt coordinates tools; it never becomes a- hidden implementation of a state change.--Keep handlers thin. If a Console workflow lacks a reusable domain service, fix-that service boundary first and have both surfaces call it. Do not copy the-Console view's business logic into `tools_*.py`.--## Result and error contract--`ToolCatalog.call` validates the input model, runs the handler, validates the-output model, then passes its JSON form to `tool_result`. `tool_result` emits-the same complete object in two forms:--- `structuredContent` for MCP clients that preserve structured fields.-- Compact JSON `TextContent` for clients such as `CallDynamicTool` that only- expose text to the model.--When output contains `resource` or `resource_links` matching-`ResourceLinkContract`, `result_compat.py` also emits deduplicated native MCP-`ResourceLink` content. Do not place identifiers, cost estimates, row data,-or a job receipt only in prose; they must be fields of the output contract.--Expected failures raise `MCPError`, which becomes-`{"error": {"code", "message", "retryable", "fields"}}` with-`isError=true` and the same JSON-text compatibility. Unexpected failures become-the safe `internal_error`; do not leak exceptions, provider responses, tokens,-or tracebacks. Resource reads use MCP protocol errors for malformed or missing-URIs, but must retain the same project boundary and safe message discipline.--## Resources, jobs, and local-file workflows--Resources are durable, read-only state—not a second mutation API. Add a-resource template when a tool returns an entity the agent needs to reread,-resume, or inspect. Implement its project-filtered payload in-`services/mcp/resources.py`, register its template, and produce links with-`resource_link`; do not manufacture URI strings in individual handlers.--`safe_json` is the resource serialization boundary. It bounds output and-removes sensitive fields. Keep access tokens, credentials, API keys, cookies,-private material, presigned URLs, and checkpoint URLs out of both tool and-resource output.-Known numeric token measurements (such as `tokens`, `supervised_tokens`,-`trained_tokens`, `max_tokens`, and `padded_tokens`) remain visible; strings, containers, and nonfinite values under-those keys do not bypass credential redaction.--Deployment job reads expose the shared deployment stage and its real status-change-timestamp. Activation progress exposes its deadline and next scheduled poll;-terminal activations have no next poll. These are scheduling facts, not worker-heartbeats or evidence of forward progress.--Operational receipts expose source and observation time independently, measured-counters and a paginated event timeline. Provider events are copied by background-controllers into durable project-scoped records; MCP inspection reads only those-records. Shared-pool startup is labelled separately from request-specific adapter-and generation events. Missing telemetry stays unavailable, with provider cursor-backlog and dropped-publication counts visible. Never expose raw provider logs,-prompts, credentials or another tenant's adapters as diagnostics.--Native evaluation job reads summarize every benchmark's coverage and macro-metrics before bounding the response. They omit duplicated score receipts and-per-benchmark details, and expose authenticated `report.json_path` and-`report.markdown_path` downloads on the same server. The complete report retains-all benchmarks, paired intervals and diagnostic slices; calibration results stay-marked in-sample. Never present a bounded benchmark preview as complete results.--Dataset transfer receipts use get_job(kind=dataset_transfer) and its job resource.-The CLI performs a read-only MCP handshake and project-scoped transfer preflight-with one resolved connection; it never certifies another sandbox's permissions.-Stable transfer keys survive client interruptions and publication retries. The-interface resource advertises transfer_protocol_version. JSON wrapper selection-is explicit, not semantic inference.--MCP carries JSON state, not local binary bytes. For uploads, exports,-checkpoints, repository edits, or local execution, return or link the-appropriate CLI guidance resource and give the coding agent exact IDs and-arguments. The CLI/SDK performs the filesystem action; MCP resumes at the-resulting build, dataset, deployment, or job resource.--## Prompts and tool catalog discipline--Prompts in `services/mcp/prompts.py` are named, parameterized public recipes.-They should name the public tools/resources to call, include approval and-human-action boundaries, and finish with a decision checkpoint. Do not add a-prompt to compensate for a missing primitive tool, and do not add a tool merely-to support a one-off prompt sentence.--Keep the catalog organized by user intent: discovery/read, mutation,-background work, and CLI/local handoff. Tool descriptions should say the goal,-the important constraint, and the returned next state. A broad search or-inspection tool is preferable to a cluster of near-duplicate filters; distinct-state transitions deserve distinct mutation tools.--## Required tests--Follow the testing policy in AGENTS.md. For every MCP change, verify the applicable outcomes below through existing E2E coverage first. The listed files locate existing focused coverage; they are not a requirement to add unit tests after implementation. If isolation is necessary, document failure modes before writing code.--| Change | Minimum proof |-| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |-| Tool contract or catalog metadata | Schema, annotations, permission visibility, input rejection, output validation in `tests/test_mcp_catalog.py` or the domain test. |-| Feature tool | Happy path, project isolation, expected errors, complete structured output, and returned resource/job identifiers in `tests/test_mcp_<domain>.py`. |-| Result format | JSON text exactly matches `structuredContent`; resource links are emitted and deduplicated in `tests/test_mcp_result_compat.py`. |-| Resource or job kind | Project scoping, safe redaction, not-found behavior, and transport read in `tests/test_mcp_resources.py`. |-| Auth or transport | Project-scoped key, read/write boundary, headers, protocol, and origin/host behavior in `tests/test_mcp_authorization.py`. |-| Prompt or CLI handoff | Prompt arguments and rendered workflow in `tests/test_mcp_prompts.py`; CLI command behavior in `overmind/tests/` when it changes. |--Run the relevant MCP tests plus `pre-commit run --files` for changed files. If-the feature also changes the REST contract used by the Console, regenerate the-frontend API client as part of that API change; MCP tools themselves do not use-the generated client.--## Completeness checklist--Before shipping an agent-relevant change, verify all applicable items:--- [ ] The MCP classification and, if omitted, its concrete reason are recorded- in the PR or implementation plan.-- [ ] The MCP tool/resource/prompt uses the shared domain service and respects- existing project-scoped API-key authorization.-- [ ] Inputs, full structured outputs, JSON text compatibility, resource links,- and async receipts are defined and tested.-- [ ] The entity has a read path after creation or mutation, including polling- for background work.-- [ ] Local-file workflows have CLI guidance rather than an MCP byte-transfer- workaround.-- [ ] The curated catalog, prompt list, resource list, user-facing Overmind- skill (`overmind/skills/overmind/`), and MCP tests are updated together.- Regenerate API clients when the API contract changed.--Training experiment changes expose `request_key`, explicit selection and contract receipts in readiness/estimate/start, elapsed time and remaining-time ranges with their recent metric-window evidence in `get_job`, and the generated run record in the finetune resource. `schedule_native_evaluation` is a metered GPU operation with train scope; its paired plan is a `native_evaluation` job/resource. `cancel_dataset` prevents pipeline publication or requests source-landing cancellation; it does not cancel external coding-agent or model-provider execution. Both routes share Console domain services and project scoping.--Dataset inspection uses cell_offset/cell_limit pagination, with active identity separate from the page. Large summaries expose truncation metadata; scripts, audit internals and previews are bounded before transport serialization. Reading a dataset never computes a missing whole-source profile synchronously; an unmeasured profile points to explore_dataset. These limits apply to the dataset resource and named inspection tool.--Contract 6.3.0 adds stored native decision-quality summaries, including applicable same-subset categorical assessments, to training progress. Native training uses the pinned Unsloth decision runtime through the existing preparation, launch, cancellation, records and operational-inspection tools.--Native comparison scoring stores a checksum-bound report receipt and compact metrics; full diagnostic slices remain downloadable. To recover interrupted local work on a paused comparison, pass its local `verify_inputs`, `fit_calibration` or `score` stage to `resume_native_evaluation`. This fences the prior local lease and reuses retained inputs; it does not resubmit provider calls.--A paused native evaluation collector can resume an explicit stage with its exact recorded `call_id`. Missing or different IDs are rejected; recovery fences the interrupted lease and observes the same provider call without a new submission.--Contract 6.4.0 adds `resume_dataset_import` for stopped source imports. Dataset-inspection and dataset-run jobs expose the saved source-import state and retry-availability. Recovery shares the REST and Console service and never starts an-autonomous preparation agent.--Contract 6.5.0 adds the shared `preparation` graph to Workshop inspection and-manifest guidance for explicit row batching and consumer validation. Corrections-replace the displayed process; there is no repair-history/restore UI. Source-transfer and package bytes are CLI-guided; execution, validation and lineage-inspection are MCP-ready. MCP readiness reuses its prerequisite validation result-instead of scanning the full training/validation population twice.--Contract 7.0.0 removes the preparation-findings tools and status fields. Workshop continues to expose retained scripts, the selected process, execution receipts and publication validation. Dataset-scoped pipeline saves automatically retain the current script association; retrying older receipts does not restore it.--Contract 7.1.0 makes native inference MCP-ready: `run_inference` accepts either-chat messages or input-only decisions, matched to the deployment's recorded-`inference_contract`. Decision results retain ordered probabilities and artifact-identity through the same durable request lifecycle. `deploy_finetune` backfills-successful historical training jobs through the automatic deployment service;-existing deployments are reused and application routing is unchanged.--Contract 7.2.0 adds `inspect_native_evaluation`: recorded model stages, provisional-per-benchmark metrics and paginated, identity-aligned input/reference/probability-samples. REST and MCP share the local indexed projection. Reads can enqueue local-indexing of retained historical evidence, never provider inference. Calibration-and final roles remain separate; a key selects one exact source row, including zero.-The bounded discovery budget is 82 KiB, including native deployment backfill and-the probability inspection tool; optional output schemas remain omitted.--Contract 7.3.0 adds search, participant and outcome filters to native evaluation-inspection. They apply to the full saved sample index before pagination; outcome-matching uses raw recorded scores, scoped to a participant or any model. Soft-targets never count as hard correctness. Aggregate metrics remain unchanged.-An exact sample key is independent of, and cannot be combined with, these filters.--Contract 7.4.0 adds `view=labels` to `inspect_native_evaluation`: paginated per-label precision, recall, F1 and counts shared with Console/REST. Search labels or benchmark names; order by `label`, `benchmark`, `expected` or `participant-key:precision|recall|f1` with optional `-` for descending. Label inspection cannot combine sample keys or outcomes. Only hard references with fixed benchmark option order qualify; soft targets are not collapsed. Reads can rebuild the local projection for historical results without provider calls. Missing predictions and zero denominators stay explicit.--Contract 7.5.0 makes `prepare_training_data` create the dashboard job atomically and return `training_job` alongside the preparation receipt. `get_job(kind=training_preparation)` also links that job. Matching `start_finetune` calls promote it after normal launch admission; preparing/awaiting-launch jobs and preparation retries cannot dispatch GPU training.--Eval-set resources expose complete evaluator sources with `limit` (1–100, default-20), `offset`, `total` and `next_offset`. Audits must follow every page; the-resource remains project-scoped and does not start scoring.+1. Classify the change. Reuse a tool when the agent intent is unchanged; do not mirror a REST endpoint because it exists.+1. Add strict request and response models in `services/mcp/contracts/<domain>.py`. Extend `MCPModel`, bound collections and strings, reject unknown fields.+1. Put the handler in `services/mcp/tools_<domain>.py`. Resolve entities inside `context.project`, call the domain service, and raise `MCPError` for expected failures.+1. Register one `ToolDefinition` in that module's `register_<domain>_tools` with accurate `read_only`, `idempotent`, `open_world`, `required_scopes`, `cost_class` and `async_mode`. Import a new domain module into `CATALOG` only when it is genuinely new.+1. Return the declared output model, never a raw dict. Add `resource` or `resource_links` for durable entities.+1. For background work, return a `JobReceipt` with `kind`, `id`, `status` and an `overmind://jobs/{kind}/{id}` resource, and teach `get_job` and the resource reader that kind.+1. Operations that start paid or long work take a stable `request_key`; an identical retry returns the original receipt and a changed payload conflicts.+1. Bump `CONTRACT_VERSION` in `services/mcp/__init__.py` with every contract change. `overmind://interface/current` publishes it with the catalog fingerprint.+1. Keep `tools/list` within `MAX_MANIFEST_BYTES` (`tests/mcp_fixtures.py`); output schemas and secrets stay out of discovery.++Keep handlers thin. Never copy a Console view's business logic into `tools_*.py`.++## Results and errors++`ToolCatalog.call` validates input, runs the handler, validates output, then `tool_result` emits the same object as `structuredContent` and as compact JSON text for clients that read only text. Matching `resource`/`resource_links` also become native `ResourceLink` content. Identifiers, costs, rows and receipts are contract fields, never prose only.++`MCPError` becomes `{"error": {"code", "message", "retryable", "fields"}}` with `isError=true`. Unexpected failures become a safe `internal_error`. Messages come from authored text or authored domain errors; never leak raw exceptions, provider responses, tokens or tracebacks.++Bound tool responses losslessly: page large results, or fail with a typed error such as `query_result_too_large`, rather than clip values. Action receipts stay compact and point to a resource with the full evidence.++## Resources, jobs and local files++- Resources are durable, read-only state, not a second mutation API. Implement the project-filtered payload in `resources.py`, register its template, and build links with `resource_link`.+- `safe_json` is the resource serialization boundary. It drops keys that name a token, secret, password, cookie, credential, authorization, API key or private key (numeric token counts stay), and it truncates strings at 12,000 characters and collections at 100 entries. `safe_finetune_progress` also removes presigned and checkpoint URLs.+- Reads never invoke a worker or a provider. Operational, monitoring and evaluation evidence come from receipts that background controllers saved.+- MCP carries JSON, not local bytes. Uploads, exports, checkpoints, repository edits and local execution return a CLI guidance resource with exact IDs and argv; MCP resumes at the resulting resource.+- Essential client-independent guidance belongs in server instructions, tool descriptions and resources. Plugins and installed skills are optional; never make one a prerequisite or the enforcement boundary. The `overmind/.{claude,codex,cursor}-plugin/` versions match `SKILLS_VERSION` in `overmind/overmind/skills_db.py`.++## Prompts and catalog discipline++Prompts are named, parameterized recipes. They name the public tools to call, mark approval and human-action points, and end with a decision checkpoint. Do not add a prompt to cover a missing tool, or a tool for one prompt sentence.++Organize the catalog by intent: discovery and read, mutation, background work, CLI handoff. A description states the goal, the main constraint and the next state. Prefer one broad inspection tool to near-duplicate filters; distinct state transitions deserve distinct tools.++## Tests++Follow the testing policy in AGENTS.md: prove the change through existing E2E coverage first. These files hold focused coverage:++| Change | Coverage |+| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |+| Contract or catalog metadata | `tests/test_mcp_catalog.py`, `tests/test_mcp_manifest.py` |+| Feature tool | `tests/test_mcp_<domain>.py`: happy path, project isolation, expected errors, structured output, returned IDs |+| Result format | `tests/test_mcp_result_compat.py` |+| Resource or job kind | `tests/test_mcp_resources.py` |+| Auth or transport | `tests/test_mcp_authorization.py`, `test_mcp_oauth.py`, `test_mcp_api_keys.py`, `test_mcp_account_access.py`, `test_mcp_transport.py` |+| Prompt or CLI handoff | `tests/test_mcp_prompts.py`; `overmind/tests/` for CLI behavior |++## Completeness++- [ ] The MCP classification, and the reason when not MCP-ready, is in the PR.+- [ ] The tool, resource or prompt uses the shared domain service and project-scoped authorization.+- [ ] Inputs, structured outputs, resource links and async receipts are defined and tested.+- [ ] The entity has a read path after creation, including polling for background work.+- [ ] Local-file workflows use CLI guidance, not an MCP byte-transfer workaround.+- [ ] `CONTRACT_VERSION`, the catalog, prompts, resources, the user-facing skills in `overmind/skills/` and the MCP tests change together. Regenerate the API client when the REST contract changed.diff --git a/.agents/skills/pr-etiquette/SKILL.md b/.agents/skills/pr-etiquette/SKILL.mdindex 60126193..6f786742 100644--- a/.agents/skills/pr-etiquette/SKILL.md+++ b/.agents/skills/pr-etiquette/SKILL.md@@ -1,20 +1,21 @@---name: pr-etiquette-description: How to open a complete pull request on overmind-core/overmind — the CI gates, the cross-cutting surfaces a change must carry with it (MCP, blast radius, the docs repo), gh pr edit being broken here, and body conventions. Use when opening a PR, editing a PR title or body, or pushing branch work for review.+description: How to open a complete pull request on overmind-core/overmind — the CI gates, the cross-cutting surfaces a change must carry with it (MCP, blast radius, the docs repo, agent instructions), gh pr edit being broken here, and body conventions. Use when opening a PR, editing a PR title or body, or pushing branch work for review.---# Pull requests on overmind-core/overmind## Before you push — what CI will run-`.github/workflows/ci.yml` runs four jobs on every non-draft PR. Run the equivalents locally rather than discovering them in CI:+`.github/workflows/ci.yml` runs five jobs on every non-draft PR; pushes to `main` run all but `migrations`. Run the equivalents locally rather than discovering them in CI:-| CI job | What it runs | Local equivalent |-| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- |-| `lint` | `uv run ruff check .` and `uv run ruff format --check .` | `make lint-backend` |-| `frontend` | `bun run check`, `bun run typecheck`, `bun run check:all`, `bun run test` — in parallel, all must pass | same four, from `frontend/` |-| `test` | `uv run pytest tests/ -n auto --dist worksteal -q` | `make test` |-| `migrations` | `makemigrations --check` on the merge commit plus `scripts/check_migrations.py`; only when `overbae/models/` or `overbae/migrations/` changed | `make check-migrations` |+| CI job | What it runs | Local equivalent |+| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |+| `lint` | `uv run ruff check .` and `uv run ruff format --check .` | the same two commands (`make lint-backend` fixes in place) |+| `frontend` | `bun run check`, `bun run typecheck`, `bun run check:all`, `bun run test` — in parallel, all must pass | same four, from `frontend/` |+| `test` | `uv run pytest tests/ -n auto --dist worksteal -q` | `make test` |+| `journeys` | `make test-journeys` with Postgres, Redis and Tesseract | `make test-journeys` |+| `migrations` | `makemigrations --check` on the merge commit plus `scripts/check_migrations.py`; only when `overbae/models/` or `overbae/migrations/` changed | `make check-migrations` |`pre-commit run --files <changed files>` before committing substantial work. Note that `mdformat` reflows markdown, so commit its output rather than fighting it.@@ -63,10 +64,10 @@ able to progress is not complete. The mcp skill itself lives inAsk what else reads what you changed, and check each one that does:-- Celery routing in `CELERY_TASK_ROUTES`, `make worker`, and docker-compose — `tests/test_celery_topology.py` enforces the three agreeing+- Celery routing in `CELERY_TASK_ROUTES`, `make worker`, docker-compose and `docker/worker-topology.json` — `tests/test_celery_topology.py` checks compose and `make worker`; keep `worker-topology.json` in step by hand- `manage.py seed_demo` — new tables and states must seed, and must stay terminal (seed-demo-data skill)- the generated OpenAPI client (api-endpoints skill)-- `AGENTS.md` and any skill whose statements the change makes untrue+- the agent instructions (section 4)### 3. Docs@@ -76,13 +77,34 @@ page, plus `docs.json` if the navigation moves. Open that PR alongside this oneand link the two. A platform PR that changes what a user sees is not completewhile the docs still describe the old behaviour.+### 4. Agent instructions++Agent docs drift when a PR changes behaviour and leaves the old text in place. Before+you open the PR, search them for every name, limit, route, state and command you+changed, and update each match in the same PR:++```bash+rg -n '<changed name>' AGENTS.md CONTRIBUTING.md DESIGN.md PRODUCT.md .agents/ overmind/skills/+```++- `AGENTS.md` — the rules and traps every task needs.+- `.agents/skills/*/SKILL.md` and their `references/*.md` — subsystem maps and procedures.+- `.agents/hooks/` — a guard whose rule or message names what you changed. Hook wiring in `.claude/settings.json` and `.codex/hooks.json` changes together.+- `overmind/skills/` — the user-facing skills that `overmind init` installs; a change there needs the SDK version bump above.+- `CONTRIBUTING.md`, `DESIGN.md` and `PRODUCT.md` when they describe the change.++Update or delete the stale line; don't append a description of the new behaviour+beside it. There is one copy of each rule: put a fact in the skill that owns the+subsystem and point to it from elsewhere. `AGENTS.md` keeps only what every task+needs, and the `agent-docs-size` hook enforces its size.+## Creating`gh pr create --body-file <file>` works normally. Write the body to a temp file in the scratchpad, never inline via `--body` (quoting breaks on long bodies). Fill in `.github/PULL_REQUEST_TEMPLATE.md` — the Verification section takes the commands you actually ran, not the ones you would run.-## Editing title/body — gh pr edit is BROKEN+## Editing title/body — use REST, not gh pr edit-`gh pr edit <n> --title/--body-file` aborts on this repo with a Projects-classic GraphQL deprecation error (`repository.pullRequest.projectCards`) **and exits looking like it worked**. The PR is left unchanged.+`gh pr edit <n> --title/--body-file` aborts on this repo with a Projects-classic GraphQL deprecation error (`repository.pullRequest.projectCards`) and exits looking like it worked, leaving the PR unchanged. The `bash_guard` hook denies it.Use REST instead:@@ -95,8 +117,7 @@ Always re-read the PR afterwards (`gh pr view <n>`) to confirm the edit landed.## Conventions-- Never push directly to `main`; land work via a PR from a feature branch. A hook blocks the push.+- Never push directly to `main`; land work via a PR from a feature branch. A hook blocks a push that names `main` or `master`; a bare `git push` while on `main` is not caught.- Verify the actual current branch with `git status -sb` before pushing — the session-start banner can be stale.- Commit messages: short subject + at most one body line. No co-author trailers.-- For fix-sweep PRs, a before/after table in the body is the house style (see PR #458/#460 for the shape).-- If the change makes `AGENTS.md` or a skill wrong, fix it in the same PR. There is one copy of each rule.+- For fix-sweep PRs, a before/after table in the body is the house style.diff --git a/.agents/skills/run-tests/SKILL.md b/.agents/skills/run-tests/SKILL.mdindex f6a20665..7fc21192 100644--- a/.agents/skills/run-tests/SKILL.md+++ b/.agents/skills/run-tests/SKILL.md@@ -5,7 +5,7 @@ description: How to run the platform test suites without wasting minutes — log# Running tests on this repo-Test runs here are expensive (backend suite ~90s+, frontend ~40s). Two rules:+Test runs here are expensive (`make test` about 75 s, frontend about 40 s, journeys about 6 min). Two rules:## 1. Decide whether to run at all@@ -42,9 +42,9 @@ uv run pytest tests/test_foo.py::test_bar 2>&1 | tee "$SCRATCHPAD/pytest-rerun.lthe compose `postgres` and `redis` services, and uses Redis DB 15. Each journeywrites a run record to `tests/journeys/.runs/<timestamp>/`; read it for theLLM requests, background task failures and the error. `make test` never-collects journeys: they need `TEST_REDIS_URL`. `make test-journeys` runs them with xdist (`-q`, `--dist loadfile`); each worker gets its own Redis DB, and DB 12 stays with the load subprocess. The journeys take several minutes, and CI runs them as their own job beside `test`;+collects journeys: a parallel run without `OVERMIND_JOURNEY_XDIST` skips them, and so does any run without `TEST_REDIS_URL`. `make test-journeys` sets both and runs them with xdist (`-v`, `--dist loadfile`); each worker gets its own Redis DB, and DB 12 stays with the load subprocess. The journeys take several minutes, and CI runs them as their own job beside `test`;`make test-journeys test_args="-k <name>"` runs one. `test_kit_*.py` files run one-journey per vendor (connectors, workshop LLM engines, GPU training outcomes): a new+journey per vendor (`tests/journeys/test_kit_connectors.py`, `test_kit_gpu_training.py`): a newvendor joins its kit's parametrize list.## Where a test belongs@@ -63,5 +63,4 @@ A known product defect gets a `pytest.mark.xfail(strict=True, reason=...)` contr(`TEST_POSTGRES_HOST`/`TEST_POSTGRES_PORT` override it).- `uv add`/`uv remove` resync the venv WITHOUT dev/test groups — pytestvanishes. Restore with `uv sync --group dev --group test`.-- Celery-dependent behavior needs `docker compose restart` of the worker to- pick up backend changes; API containers hot-reload.+- Compose workers restart through watchmedo on `.py` changes under `overbae/`; API containers hot-reload. A non-Python edit under `overbae/` (for example `overbae/modal/models.json`) needs `docker compose restart <worker>`. Recreate a worker after a dependency change (AGENTS.md Gotchas).diff --git a/.agents/skills/seed-demo-data/SKILL.md b/.agents/skills/seed-demo-data/SKILL.mdindex 816df8fa..a500cf72 100644--- a/.agents/skills/seed-demo-data/SKILL.md+++ b/.agents/skills/seed-demo-data/SKILL.md@@ -54,7 +54,7 @@ workers to re-drive seeded rows against **real providers** and spend credits:- `auto_now_add`/`auto_now` columns are backdated via the raw-SQL `backdate()`helper (executemany), not via the ORM.-- Datasets land through `services/datasets/land`. Explicit fixture transformations+- Datasets land through `services/datasets/land.py`. Explicit fixture transformationspublish measured, provenance-preserving frames directly; no platform agent orscript runner exists. Every dataset has a real active frame. Historical demo consumption stamps `used_at` directly and pins cells,including each training job's `eval_cell`; it does not fabricate a semanticdiff --git a/.env.example b/.env.exampleindex f87e5eb1..bd9ab4fa 100644--- a/.env.example+++ b/.env.example@@ -40,7 +40,7 @@ CELERY_RESULT_BACKEND=redis://redis:6379/0OPENROUTER_API_KEY=JEV_REQUESTS_PER_MINUTE=1200JEV_TOKENS_PER_SECOND=250000-# Optional. OPENAI_API_KEY serves the embedding_cosine evaluator.+# Optional. OPENAI_API_KEY is read only by the embeddings helper in overbae/core/llms.py; no platform feature calls it.OPENAI_API_KEY=FRONTEND_URL=http://localhost:5173diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdindex 429daf8a..2ac29adc 100644--- a/.github/PULL_REQUEST_TEMPLATE.md+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -26,7 +26,7 @@- [ ] **MCP** — classify (MCP-ready / CLI-guided / frontend-only / out of scope); catalog, contracts, tools, prompts, resources, `tests/test_mcp_*.py`- [ ] **Blast radius** — celery routing, `seed_demo`, generated OpenAPI client- [ ] **Docs** — `overmind-core/docs` PR opened and linked, if user-visible behaviour changed-- [ ] **Agent config** — `AGENTS.md` or the affected skill updated, if this changes behaviour they describe+- [ ] **Agent instructions** — searched `rg -n '<changed name>' AGENTS.md CONTRIBUTING.md DESIGN.md PRODUCT.md .agents/ overmind/skills/`; each stale line updated or deleted in this PR, not appended to## Checklistdiff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 16407bc7..69d04845 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -35,6 +35,12 @@ repos:entry: uv run python scripts/check_test_seams.pylanguage: systemfiles: "^tests/.*\\.py$"+ - id: agent-docs-size+ name: AGENTS.md and skills stay within agent load limits+ entry: uv run python scripts/check_agent_docs.py+ language: system+ files: "^(AGENTS\\.md|\\.agents/skills/.*\\.md)$"+ pass_filenames: false- id: biomename: biome check --writeentry: bash -c 'cd frontend && bun run biome check --write "${@#frontend/}"' --diff --git a/AGENTS.md b/AGENTS.mdindex 68f57c61..599dca2d 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,312 +1,117 @@# Overmind Platform-Monorepo for the Overmind Console (`frontend/`, React), API (`overbae/`, Django + DRF + Celery), and SDK/CLI (`overmind/`). Agent improvement platform: observability → data workshop → evals → finetuning/inference. The platform is AGPL-3.0; `overmind/` is MIT. `overmind chassis` scans TypeScript/JavaScript checkouts with tree-sitter as well as Python. There is no JavaScript SDK: a JavaScript app adds Overmind's OTLP endpoint (`/api/v1/traces`) to its existing OpenTelemetry setup, and `get_instrumentation_plan` returns no placements for its anchors.+Monorepo for the Overmind Console (`frontend/`, React), API (`overbae/`, Django + DRF + Celery) and SDK/CLI (`overmind/`). Agent improvement platform: observability → data workshop → evals → training and inference. The platform is AGPL-3.0; `overmind/` is MIT. There is no JavaScript SDK: a JavaScript app sends OpenTelemetry to `/api/v1/traces`, and `overmind chassis` scans TypeScript as well as Python.-This file is the single playbook. Claude Code, Codex and Cursor all read it natively. It holds what every task needs; procedures and subsystem maps live in `.agents/skills/`, which every tool loads on demand.+This file is the playbook every task needs; Claude Code, Codex and Cursor read it natively. Procedures and subsystem maps live in `.agents/skills/`, which each tool loads when a task matches. This file holds traps and rules only, so keep it under 16 KiB: change or delete a line rather than append a feature description.## Branches-- `main` is protected: feature branch → PR, using `.github/PULL_REQUEST_TEMPLATE.md`.-- The repo is public (`overmind-core/overmind`) and carries the platform plus the MIT SDK under `overmind/`. Never force-push `main`.-- Root ruff excludes `overmind/`. SDK CI is `.github/workflows/sdk-*.yml`. Every merge to `main` that touches `overmind/` publishes to PyPI, so `sdk-ci` requires a version bump on those PRs.+- `main` is protected: feature branch → PR, using `.github/PULL_REQUEST_TEMPLATE.md`. Never force-push `main`.+- The repo is public (`overmind-core/overmind`). Root ruff excludes `overmind/`. Every merge to `main` that touches `overmind/` publishes to PyPI, so SDK CI requires a version bump on those PRs (pr-etiquette skill).## Commands-- Frontend (**Bun**, from `frontend/`): `bun run typecheck`, `bun run lint` (Biome — no ESLint/Prettier), `bun run test` (vitest), `bun run check:all` (design/contrast/controls scripts). Scripts run with `bun`; there is no `node` on this machine.-- Backend (**uv**): `make test` (parallel pytest on the compose Postgres), `make test-journeys` (end-to-end journeys in `tests/journeys/` on the live ASGI app, a real Celery worker and compose Redis; outside services are faked at the network), `make test-serial`, `make lint-backend` (ruff), `make check-migrations` (after a model change, rebased on `origin/main`), `uv run <cmd>`.-- SDK (**uv**, from `overmind/`): `make -C overmind test`, `make -C overmind lint-check`.-- CI (`.github/workflows/ci.yml`) runs on `main`: platform lint, frontend, test and journeys as parallel jobs; draft PRs skip it. SDK CI (`sdk-ci.yml`) runs on `overmind/` changes.-- A local deployment already runs via `docker compose` with hot reload — do not start dev servers to verify changes. Celery workers auto-restart via watchmedo; `docker compose restart <worker>` if in doubt.-- After changing backend API surface: `make generate_api_client` (api-endpoints skill).-- `pre-commit run --files <changed files>` at the end of any substantial multi-file task, before committing.--## Architecture facts you can't guess--- Local file transfer is CLI-guided but has durable DatasetTransfer receipts.- `overmind connection check --project-id PROJECT --json` verifies MCP and transfer- access from the invoking environment; MCP connectivity alone is not readiness.- Upload preflights automatically and binds SHA-256, byte count and destination- recipe to a stable request key. Repeat the same command after interruption.- `get_job(kind=dataset_transfer)` reads byte/publication state; `dataset_run`- reports landing. Confirmed permission denial uses the host's scoped approval,- never automatic sandbox-policy changes or browser fallback. An explicit- `--json-rows-field FIELD` selects a top-level JSON row array and records that- choice; original bytes remain retained. Detail: data-workshop skill.--Each line is the invariant; the named skill section carries the mechanics.--- Single Django app `overbae`: `api/` (DRF views/serializers, one module per surface), `models/` (split by domain), `services/` (business logic), `innermind/` (evals, live scoring, runs, signals), `tasks/` (Celery), `modal/` (GPU workers). Map: backend-architecture skill. MCP is the first-class agent surface at `/api/mcp/` (`services/mcp/`); account API keys and OAuth connections discover authorized projects with `list_projects` and pass `project_id` per operation. Project API keys retain their narrower scope. It shares domain services with REST/Console and is not a proxy of either. Procedure: mcp skill.--- Tracing is **span-only**: no Trace table; a trace = spans sharing `trace_id`; the root span has `parent_span_id IS NULL`. OTLP ingest at `POST /api/v1/traces`.--- Local dataset upload/export and checkpoint downloads authenticate separately from MCP. With no explicit or repository key, they use the address-bound account connection at `$XDG_CONFIG_HOME/overmind/connection.toml` (default `~/.config/overmind/connection.toml`, permissions `0600`). Repository keys are also endpoint-bound: changing only the API URL, even while repeating that key explicitly, fails before network access. Verify the installed CLI from both the actual workspace and a repository-free directory without injected credentials; workspace MCP and project settings can override global defaults. Missing credentials and transfer errors never authorize a browser fallback. Detail: overmind-datasets skill.--- Repository provenance belongs to the scan: `overmind chassis` records the checkout, conversion verifies it is unchanged, and sync preserves it with a separate server sync time. The Agent header and MCP project resource identify that snapshot; missing provenance stays unknown. Detail: backend-architecture § Capabilities and sync.--- The agent is the project itself: one graph per project, no table. `Capability` rows are its nodes (UI: "Capability"; the sidebar's "Agent" is the product). Ingest never creates a capability, and wire identity is `overmind.capability.id` alone. A scan never deletes; an absent capability becomes `status=leftover`, and `DELETE` is a soft delete. Capability discovery runs locally: `/overmind setup` builds the `overmind chassis` digest and runs the Cursor scan, writes `overmind.toml`, and `overmind sync` uploads it. Convert fills prompt spans, drops fabricated anchors and unverifiable provenance, then stamps `trajectory_map[].verified` against the AST chassis. Sync upserts each capability's Default eval set (`innermind/default_set.py`): one deterministic row per toml `eval_matrix` entry that names a catalog `check` with its `params` (an invalid entry is a 400), one llm row per legacy toml expectation, one span-scoped llm row per `expectations=` sentence on the checkout's entry-point, workflow and function decorators (read by `overmind sync`, never written to the toml; a sentence the code drops loses its row), plus the seeded checks for its span types, recorded in `improvement_metadata.eval_preload`. Setup writes no judge criteria to the toml: they are `expectations` on the decorators it applies to every function, tool, retrieval step and model call the card names, then syncs again. Detail: backend-architecture § Capabilities and sync.--- Scoring is matrix-keyed: enabled `EvalMatrix` rows (llm expectations, sandboxed deterministic checks) score every ingested span into `Span.eval_attributes`; a finished trace's trajectory lands on its root, and every score appends an `EvalScore`. A span, a trajectory and a `plan_drift` step are each judged once, with at most 3 attempts; spent attempts become error metrics, never another retry. Evaluation runs freeze the matrix, one run per target in a group with an optional baseline; comparisons pair rows both runs scored. A dataset row is the capability's answer: it takes every row whose `span_type` is blank or `llm_call`, whatever its `span_name`, so backtest, optimiser and training judge what live scoring judges on the answer. An optimiser experiment keeps its first run's matrix, like a training job. Signals are in-app `SignalEvent`s shown inside Observability (Sessions, Signals, Traces). Deterministic checks run by default over recent spans; stored project/capability settings override defaults, and model-backed plan drift stays opt-in. Detail: backend-architecture § Scoring.--- Every model id lives in `overbae/core/model_registry.py`. Jev uses the dedicated `core.decisions` transport. Eval matrix llm rows use Jev without generative fallback; a generative model writes reasons for low scores. Data Workshop does not invoke a platform planning or generation agent. Native coding agents own interpretation, code and semantic work; deterministic execution and lineage-bound imports are platform services. Detail: data-workshop skill; backend-architecture § Evaluation.--- REST and MCP datasets may start from a written `brief` without a source or capability. First-source attachment preserves the draft; later uploads append versions. Intent is explicit (`train`, `eval`, `explore`) and otherwise stays pending. Landing never starts preparation. Original document bytes, extraction metadata and row evidence remain retained; PDF and PNG/JPEG/WebP landing use local Tesseract OCR with English by default or explicit MCP/REST language choices, preserving page regions, orientation and recognition provenance. MCP pages source inventories without discarding extraction facts and exposes measured landing/OCR and pipeline stages; the native agent owns their explanation. Document byte and PDF page limits are discoverable before extraction. Parsing runs in the isolated `sandbox` service without app credentials, shared media or outbound network; landing streams bytes and progress and has no in-process fallback. Detail: data-workshop skill. The Console landing page is a project dataset table; selecting a row opens the unchanged step-by-step cells. A folder button reveals compact, project-scoped dataset navigation. Platform chat, the prompt-style landing composer and mutable-cell replay actions are removed. Removed routes do not exist; the Console has no chat, mutable-cell replay or funding controls.-- Trace sources pin a capability preference: the source filter takes precedence- over the destination association. A matching unique invocation scopes I/O,- transcript, usage and score together; repeated invocations fail before publication.- Unmatched sources retain whole-trace evidence, and mixed traces have no invented- single-capability attribution. Missing wrapper I/O stays missing, never tool arguments.--- Datasets are sources and step-by-step chains of cells; displayed versions are derived. Native agents must upload retained Python packages and save immutable project-level revisions with `save_dataset_pipeline(package=...)`; inline operations are not accepted and package-free historical revisions are read-only. They reuse them across compatible project sources, or save attributed `derived_from` variants. Packages execute only in the isolated sandbox service through interactive workers, never API/Celery Python; external imports remain lineage-bound and attributed. Preview does not publish. Successful runs atomically append one cell per step; failures and cancellation preserve readable source and consumer versions. Explicitly enabled bindings rebuild source snapshots with a pinned revision and commit checkpoints with publication. Shared REST/MCP services own metadata, request-key conflicts, provenance and measured impact. Semantic quality stays unmeasured without attributable evidence; technical compatibility is not semantic correctness. Preserve probability targets, option order, weights, duplicates, blank states and declared groups. `use.use(dataset, intent, cell=)` freezes exact versions. Training pins train/validation/eval cells atomically and performs model-specific preprocessing only. Modal preparation transfers compressed sources once, verifies ordered row fingerprints and reuses the exact token artifact. Detail: data-workshop skill; backend-architecture § Training preparation.--- Tenancy is project-scoped, no org layer. Auth is Clerk when `CLERK_API_SECRET_KEY` is set; blank secret plus Console `VITE_SELF_HOSTED=true` uses local JWT: email/password (`POST /api/auth/local/`, create-on-first-use, no verification) only. ChatGPT login, account linking and credentials are removed. A guest holds one project and can only read and claim; a view that accepts guest writes opts in with `guest_allowed = True` — never a permission class or middleware. API keys are `scope=account` or `scope=project`. MCP `create_api_key` mints one with the Console dialog's name, description and expiry (30, 90, 180, 365 days or never). Omitting `project_id` mints an account key; passing it mints a project key. The plaintext is returned once, and a project key cannot mint an account key. Detail: backend-architecture § Auth and tenancy.--- The Overwatch user insights dashboard endpoints use `/api/internal/overwatch/*`, gated by the existing `SALES_DASHBOARD_TOKEN` environment variable (legacy name retained for deployment compatibility). They are registered only when the token is set at import; `tests/settings.py` sets one. Each path and query is computed at most once an hour (Django cache), and responses carry `computed_at`/`refreshes_at`. They run no user authentication, stay out of MCP and the OpenAPI schema, and exclude guests and guest-only projects. The source directory remains `sales-dashboard/` because the deployment workflow and Pages project use that path; the user-facing name is Overwatch. It imports the Console's `styles.css`, `public/` and `components/ui` through the `@` alias (keep those primitives free of app-level imports), keeps the admin token in sessionStorage for 30 minutes, clears legacy localStorage tokens, and `bun run dev` proxies `/api` to `SALES_API_PROXY` (default `http://localhost:8000`). Optional PostHog aggregate insights require a project-query read key and project ID in the backend environment; keep the key server-side and return validated aggregate event counts only. Responses prohibit browser/shared caches. Internal reads have SQL and report time budgets. Overwatch must only read product records: no product database models, migrations, notification ledger, periodic writer or event emitter. Notification state belongs in Overwatch storage outside this backend; archived prototypes under docs/proposals are not executable code. Shared backend dependency upgrades require a separate platform review. Slack Q&A runs as a separate profile in the Overlord repository using its shared engine; the standalone backend Slack/model adapter is archived, with no active routes or Celery tasks. `POST /api/internal/overwatch/agent/query/` uses a dedicated `OVERWATCH_SERVICE_TOKEN`, rejects dashboard/product/staff credentials, validates five bounded read tools, and enforces a PostgreSQL read-only transaction. POST keeps customer email arguments out of URL logs. The service key cannot authenticate product writes. The Slack profile requires its own app/workspace credentials, an explicit user ID allowlist and a linked unrestricted internal employee; HR admins do not bypass it. Customer reports terminate locally in private replies without returning records to the model. Overwatch must not use Overlord HR tools, conversation storage, extraction or training traces. Direct Anthropic use is disabled by default and needs an approved data/retention policy.--- Compute estimates use live provider rates with fetch timestamps and durable worker usage receipts; they never create ledger charges. Training forecasts use compatible completed execution measurements, with evidence, uncertainty and missing components explicit. Current GPU hourly rates remain visible when duration and total cost are unmeasured; one quote uses one fetched rate snapshot. Native progress reports elapsed time and a remaining-time range rather than a single countdown or finish timestamp. Detail: backend-architecture § Native decision training.--- Billing meters platform model/compute spend on the ledger. Remaining-credit 402s, the Free seat limit and Stripe apply when `STRIPE_SECRET_KEY` is set. Native-agent model selection and funding belong to the external coding-agent environment. Training, evaluation and serving retain their own billing. Detail: backend-architecture § Auth and tenancy.--- Celery is six workers over six queues: `control` (default, orchestration and beat), separate `io` (threads) and `io_traces` (prefork) workers, and `batch`, `landing` and `interactive` (prefork). IO and trace workers consume only their own queue and disable prefetch so trace scoring cannot occupy preparation or serving slots. Workers are resource profiles, queues are fairness classes; only prefork enforces `time_limit`, so every time-limited task routes to `batch`, `landing`, `interactive` or the isolated `io_traces` worker. Live scoring uses durable, bounded per-project admission with fenced execution; evaluation generation also caps total admission across a project’s runs. Imports have dedicated landing capacity; live span and trajectory scoring and signals run on `io_traces`; evaluation generation and scoring run on `batch` with durable, bounded admission and project and run fairness. Workshop pipelines retain queue and execution timestamps in their run receipts; their waiting and occupied slots contribute to interactive capacity, with shared per-project admission. Source imports retain fenced attempts and explicit recovery through REST and MCP. `tests/test_celery_topology.py` enforces these invariants and must stay in sync with `make worker` and docker-compose. Detail: backend-architecture § Celery topology.--- Landing submissions wait in `DatasetLandingWork` before bounded broker publication.- One import per project runs at a time; least-recent-project admission uses observed- worker capacity up to eight. Waiting does not consume an execution attempt or- expire unless a nonzero `DATASET_IMPORT_MAX_QUEUE_SECONDS` explicitly sets a limit.- Lost started workers are fenced and require explicit recovery. REST and MCP- expose the same admission state and timestamps. Landing scale-out counts useful- competing projects; raw queue age remains visible independently.--- Most status transitions use `.filter().update()` — **no Django signals fire** and the in-memory object goes stale. Any side effect a transition needs is wired explicitly at the call site, on a freshly reloaded row. Preserve this pattern.-- Training finalization also closes its operational timeline. The training- reconciler repairs missed terminal events without provider calls and uses a- renewable 30-second collector lease so worker restarts do not hide progress for- five minutes. Detail: backend-architecture § Celery topology.-- Modal training charges and forecast duration evidence use deduplicated worker- usage and recorded hardware, never completion-observation delay. Missing usage- remains unmeasured; charge receipts retain rates and usage IDs. Historical ledger- entries are not silently rewritten.--- Serving: a dense or explicitly supported MoE Modal-trained LoRA is served as an adapter on a shared BF16 base (never FP8); everything else is merged and quantized into a private checkpoint. `fetch_base_model` is the only base writer and seals immutable base identities. Every GPU/image pair has a LoRA worker that snapshots the engine after level-2 sleep, then reloads an adapter-free inference-layout artifact through pinned buffers; full-checkpoint workers do not snapshot. Artifact/snapshot identity includes the base revision and compatible serving profile, never tenant adapters. Completions and playground SSE retain their 15s idle pings. Detail: backend-architecture § Serving and weights.--- Making a model live runs the durable `ModelActivation` check in `services/model_activation.py`: wake and verify with the existing deployment prewarm, then atomically switch the alias and preserve the previous selection. REST and MCP share this path; the deployment reconciler also advances activation. Successful application API-key calls to the alias confirm connection, independently of readiness and worker warmth.--- Operational drill-down uses `OperationalRun` and append-only `OperationalEvent` receipts. Preparation, training, deployment, activation and MCP inference record separate observation, heartbeat and forward-progress timestamps. `get_job` links the latest attempt; `inspect_operation` and `overmind://operations/{id}` page recorded events without invoking a worker. Shared-pool events never establish tenant-adapter readiness. Provider telemetry availability, cursor backlog and dropped publications stay explicit. MCP contract 4.0 makes `run_inference` a durable `inference_request` job requiring a stable request key; unknown provider acknowledgement is reconciled, never blindly resubmitted. Serving-worker changes require a Modal deployment before their events exist.--- Training startup distinguishes runtime initialisation, weight loading, adapter- setup, tokenizer verification and dataset/trainer construction. Console and MCP- expose measured counters and separate stage, heartbeat and forward-progress- clocks. Weight-loading percentages remain unavailable when the library reports- no counter. New instrumentation requires a new pinned worker release.--- Typed decision training uses Unsloth `FastDecisionModel`/`DecisionTrainer` on its separately pinned runtime, supports Modal LoRA on one GPU and accepts a native `decision` column with runtime options and full target distributions. Clef encoding retains upstream option spans and an explicit order mapping; full-precision head weights accompany every adapter. Shared preparation, monitoring, operational receipts and MCP lifecycle remain authoritative. Native `hyperparameters.pre_training_baseline` defaults to true; false skips only the initial development baseline and retains checkpoint/final validation. Console and MCP expose the choice, receipts pin it, and worker telemetry records an omitted baseline as not requested. The native coding agent explores the source and user request before declaring evidence-backed per-family target semantics; unknown meaning stays unknown. The measured contract selects distribution cross entropy or mixed distribution/ordinal-mean supervision; it never invents a distribution from a mean or turns soft labels into argmax text. Decision checkpoints use typed probabilities and do not enter chat deployment/evaluation. Detail: backend-architecture § Native decision training.-- DecisionJob is a separate public ID over the same FinetuningJob lifecycle, not an independent status machine. Explicit Clef, D3 and D1 model paths appear in the decision catalogue. Only Clef uses the qualified shared preparation/training/serving path; D3 and D1 launches remain disabled until their family-specific input, checkpoint and probability-serving runtimes meet those same checks. REST and MCP expose both IDs, and preparation returns the DecisionJob ID when present.--- Successful training automatically deploys every model through its matching inference runtime. Native decision deployments preserve verified adapter/head artifacts, recorded single-GPU hardware and a pinned serving release; readiness requires a real probability prediction. `deploy_finetune` backfills historical successes without changing routing. Chat aliases and benchmark choices remain separate. REST and MCP share durable typed inference receipts. Detail: backend-architecture § Native decision serving.--- Explicit REST/MCP training preparation creates the dashboard FinetuningJob atomically before dispatching preprocessing. Setup jobs show preparing data, awaiting launch or preparation failure; they never enter GPU dispatch or pass launch admission. A matching launch promotes that same job and pins the full recipe; preparation retries only retry preprocessing.--- Training launch receipts pin the runtime release/environment, exact cells and requested recipe. The training volume commits when a stage finishes, not on a timer, and at most five launches upload to it at once. Stall detection counts native validation and checkpoint-stage progress independently of optimizer steps; a committer heartbeat alone does not establish forward progress. Reusing a project request key returns the same job; a changed recipe conflicts. Provider intent is persisted before dispatch; an unknown acknowledgement is reconciled against that job's provider metadata, never resubmitted. Explicit settings that require a clamp are rejected. Native paired evaluation uses its own frozen calibration/final plan, retains incompatible rows, keeps references local and fits calibration before final predictions. Downloadable run records distinguish recorded GPU spend from unreported components. Detail: backend-architecture § Reproducible training experiments.--- Development monitoring freezes `hyperparameters.monitoring` across readiness,- estimates and launch. Modal freezes loss/reference/generation samples before GPU- dispatch; the trainer verifies the manifest. Adaptive/steps/epoch/off schedules- use measured optimisation and check time, never quality-driven strategy changes.- `TrainingValidationRun` and `TrainingCheckpoint` retain failures, sample and- artifact fingerprints, reload verification and cancelled-run evidence. MCP- `inspect_training_progress` and REST read stored checks/examples/sample identities- without waking workers; `cancel_finetune` records intent before provider requests.- MCP check overviews expose large native per-question metrics and assessments as- `collections`; `field` JSON Pointers page the exact retained values, including- nested check/checkpoint fields. REST monitoring-evidence shares this pagination.- Development-loss selection and early stopping are explicit opt-ins. Generation- checks require agent-declared labels/exact matching/JSON schema/JSON field pointers; missing metrics- remain missing. Metered judges, challenge suites and declared-slice sampling are- not yet supported by this monitoring contract. Full optimizer resume is not- implied by adapter reload verification. Modal training attempts keep the 24-hour- function timeout. `runtime_limit_seconds` does not shorten that call and is not an- all-in invoice cap. Detail:- backend-architecture § Development monitoring.-- `json_fields` compares declared JSON Pointers against retained references, with- type/precision-preserving equality and ordered arrays. Missing reference fields- remain unscorable; wrong/missing predictions fail. Per-field coverage and whole- example pass rates are separate. No field inference or tool execution occurs.-- Check facts retain server-side result-receipt and terminal-observation times.- Optional product events expose counts, timings and verified checkpoint availability,- never examples or labels. Receipt commits precede analytics; analytics failure- cannot fail training. Availability is not proof of usefulness or user delight.-- Classification receipts also retain deterministic `facts.assessment` comparisons- against the same scored subset's majority-label baseline and represented labels- without predictions. These do not infer a cause or change training. Counts and- frozen policy identity must agree; otherwise assessment is inconclusive. MCP- retains the latest generated check independently of newer loss-only checks.--- Training transfer exposes stage-specific selection, upload acknowledgement and- provider materialization counters. Uploaded bytes mean acknowledged files, not- live network progress. The 15-second controller collects worker transfer facts- independently of the active submission task; Console and MCP read the same saved- facts and freshness. Missing telemetry never becomes a fabricated percentage.--- Data-first projects start from uploaded data and the original task brief; repository scans and capabilities are optional. Saved `DataPartitionPlan` recipes preserve exact content, declared groups, synthetic lineage and duplicate observations across train/development/calibration/final roles. Calibration/final members have eval intent; native inputs and references are projected losslessly for evaluation, and construction exposes stage/count progress. Standalone `NativeEvaluationPlan` comparisons accept foundations, trained artifacts and qualified external probability adapters, with optional frozen calibration before final scoring. `TrainingExperiment` extends job groups with explicit variants, a shared protocol and development-only checkpoint selection. `DecisionPerformanceRun` measures a saved client workload without activation. Console, REST and MCP share these services; completed responses and native call IDs are reused, unresolved submissions are never blindly replayed. Provider aliases, partial cost records and unmeasured hardware fit remain explicit. Detail: backend-architecture § Data-first model workflows.--- Workshop execution uses immutable `DatasetPipeline` recipes and durable `DatasetPipelineRun` receipts. They bind source/output/artifact cells and fingerprints, stable request keys, execution state, impact and producer attribution. `get_job(kind=dataset_pipeline)` and its resource read an exact run. Cancellation prevents publication without claiming remote termination; expired runs fail without automatic replay. Interactive Celery consumers admit runs through shared per-project Redis slots; sandbox subprocesses retain main’s UID isolation and measured memory admission. Worker loss expires the fenced receipt without replaying scripts. Runner availability heartbeats continue through validation and publication without advancing measured progress. External execution is attributed, not independently verified. The cutover archives old conversations, runs and provider receipts in DatasetHistory before dropping the agent tables and fields. Published cells retain their read-only scripts, reviews and frames. No legacy runtime or compatibility endpoints remain. MCP contract 3.0 retires `message_dataset_agent`, `run_dataset` and `manage_dataset_workflow`. Detail: data-workshop skill.--- `save_dataset_pipeline(dataset=..., package=...)` automatically associates the retained script with its preparation; old request retries never reset that association. Workshop exposes the selected process, execution receipts and publication validation without a preparation-findings feature.--- Workshop handoffs return project-bound upload argv. Absolute min_rows/max_rows checks apply at publication and remain visibly deferred in previews; row preservation, schema and lineage checks apply in both modes. Runs expose queue age, polling interval, terminal time and structured failed checks. Format readiness does not establish task suitability. The native agent inspects the named capability and verifies published output before claiming preparation complete. Detail: data-workshop and mcp skills.--- Data-first workflow mechanics share services across MCP and REST. `DataExploration` freezes an explicit cell for cached whole-source profiles or a separate derived chain; paginated sampling allocations never silently change coverage. Workshop interpretation remains agent-owned with scoped evidence and explicit hypothesis/conflict states. Native comparisons save drafts, prepare immutable suites in background and launch explicitly. Independent stages use recoverable leases, chunk-indexed input verification and durable provider receipts; pause stops new claims without claiming remote cancellation. Training experiments prepare a configuration-bound forecast before launch, optionally enforce user-defined planning constraints, and expose aggregate child outcomes. Bounded runtime profiles use explicit step/time limits; compatible prediction reuse is explicit and never substitutes for independent repetitions or performance measurements. MCP contract version and catalog fingerprint are discoverable at `overmind://interface/current`; installed guidance is not a correctness dependency.-- Native comparison database receipts retain aggregate and per-benchmark metrics;- complete diagnostic slices live in the checksum-bound downloadable report.- Scoring receipts reference that artifact rather than duplicating it. Explicit- local-stage resume on a paused comparison fences interrupted local work and- reuses saved inputs; it never resubmits provider inference. A paused native- collector can be recovered only with its exact recorded provider call ID.-- Native benchmark workers publish checksum-bound prediction chunks under the- exact provider call ID. Background collection verifies runtime, input and- artifact identity before indexing inputs, references and outputs locally.- Console and `inspect_native_evaluation` read that paginated projection, including- provisional metrics and unavailable telemetry. Completed historical evidence can- be indexed without another provider call. Calibration remains separate from final- scoring; ordinal means never become invented probability references.-- Native evaluation inspection also pages per-label precision, recall, F1 and- coverage with `view=labels`. REST and MCP share the retained local projection;- only hard references with a fixed benchmark option order qualify. Missing- predictions and zero denominators remain distinct from incorrect answers.--- Benchmark selection is separate from serving: capability `benchmark_model` selects a ready trained model, or null for the codebase incumbent. New training jobs snapshot the primary choice in `baseline_model`; `active_model` only controls serving. Chat-training setup can pin additional benchmark models for the same eval set and dataset; they and the selected training bases are scored before training when benchmarking is enabled. Trained models are scored after training when evaluations are enabled. MCP `set_benchmark_model` sets the capability default.--- Foundation catalogue entries carry nullable `openrouter_id` mappings. Base benchmarks verify the mapped ID or an exact declared checkpoint against OpenRouter's catalogue before using it, ahead of unused ready hosted bases. MCP/REST model catalogues distinguish `available`, `not_listed` and `catalog_unavailable`; missing matches never substitute a different size or variant. Started evaluations and unresolved deployments remain pinned. Detail: backend-architecture § Serving and weights.--- Evaluation context estimates cover generate targets and the explanation judge, including reserved output. REST and MCP expose warnings; Console highlights setup selectors and Start only for estimated limit overflows. Unverified, unavailable and pending checks stay neutral. Start opens a short risk summary with Start anyway; undersized dropdown options are muted but selectable, with fit labels and scoped judge-cost comparisons. Training `eval_judge_model` overrides the explanation judge for that job only; blank uses the configured default. Baseline sharing requires the same judge selection. No automatic model changes, hard launch blocking or candidate removal. Judge technical failures are metric errors, never quality scores. Detail: backend-architecture § Evaluation.--- Serving context is independent of training sequence length. `services/serving_context.py` sizes it from pinned evaluation inputs, references and output headroom; recommendations and launch share the check. Completion requests reserve explicit output tokens, never silently shrink to remaining context. Token-limited generations retain finish reasons, stop before tool execution, and are excluded from trusted evaluation scores with visible degraded/skipped outcomes.--- Frontend must use the generated OpenAPI client in `frontend/src/openapi/` — never hand-edit it.--- Dataset storage bounds Parquet staging and DataFrame chunks by bytes and reads small row batches. It preserves mixed scalars and precision-sensitive integers as JSON;- shared pandas readers must not coerce them again. MCP queries cap JSON output at- 32 KiB and return `query_result_too_large` without clipping values; a configurable- ten-second default execution deadline returns `query_timeout`. Shared Redis admission- bounds MCP SQL to eight concurrent queries globally and two per project by default;- retryable capacity errors retain the exact cell and retry delay. The CLI exports- retained original sources via `dataset export --source SHA256`, verifying bytes- without overwrite or credential-forwarding redirects. Local uploads- accept up to 100 ordered files / 2 GiB per resumable transfer. All files verify- before one source publication; one attachment adds the whole batch in one version. Detail: data-workshop skill.--- Naming quirks: UI "Optimiser" = backend `optimizer`; UI "Training" = backend `finetuning`.--- `DESIGN.md` and `PRODUCT.md` carry a fixed YAML frontmatter schema that tooling reads — extend the values, don't restructure the documents.--- Standalone evaluation creation accepts `judge_model` through REST and MCP. It freezes the run's explanation judge; blank uses the configured default. Existing runs reject judge changes. The Console starts no standalone evaluations: its judge selector and advisory context warnings live in training setup; results and MCP resources expose frozen judge identities. Detail: backend-architecture § Evaluation.--- Workshop flow is authored by the native agent: step `id`/`input` dependencies,- or `inputs` for disjoint branch fan-in (ordered concatenation, overlapping row- identities rejected). Training recipes converge on trainable outputs with- unresolved review metadata retained; `flow.unconsumed_steps` exposes dead ends.- retained-script condition citations and a returned `flow` entity. Runtime receipts- separate those declarations from actual input cells, row counts and fingerprints.- The Console keeps full-size existing cells at scale 1 on a grid-snapped canvas:- progress runs downward; sibling branches align on the same horizontal layer. Corrections replace the displayed process; there is no repair-history or restore view. The preparation graph follows verified run inputs, partition members and derivations across datasets; exact consumer-pinned cells remain reproducible internally. Detail: data-workshop skill.- Each entrypoint exposes its meaningful step logic; helpers hold reusable utilities.- Cells expose receipt-backed transformation attribution and allow inspection of all- checksum-verified retained package files. External imports remain distinct from- platform execution; historical scripts are never rewritten to imply new execution.--PDF landing checks pages missed entirely by the primary native parser with PDFium-before OCR. Recovery retains encoded text, page regions and engine/count facts;-font-encoding artifacts are flagged, never semantically corrected. Detail:-data-workshop skill.--Workshop decision/Jev recipes retain full distributions, ties, weights and source-groups in typed decisions. Target meaning and evidence belong to retained code-and output metadata; historical preparation plans are not a writable authoring-API. Flat-source profiling and impact checks retain declared supervision metadata-so changed weights or semantic declarations cannot disappear from the review.+- Frontend (Bun, from `frontend/`): `bun run typecheck`, `bun run lint` (Biome; no ESLint or Prettier), `bun run test` (vitest), `bun run check:all` (design, contrast and controls scripts). There is no `node` on this machine; run scripts with `bun`.+- Backend (uv): `make test` (parallel pytest on the compose Postgres), `make test-journeys` (end-to-end journeys on the live ASGI app, a real Celery worker and compose Redis), `make test-serial`, `make lint-backend` (ruff), `make check-migrations` (after a model change, rebased on `origin/main`), `uv run <cmd>`.+- SDK (uv): `make -C overmind test`, `make -C overmind lint-check`.+- CI (`.github/workflows/ci.yml`) runs lint, frontend, test and journeys on `main` and ready PRs, plus migrations on ready PRs; draft PRs skip it. SDK CI runs on `overmind/` changes.+- A local deployment already runs through `docker compose` with hot reload. Do not start dev servers to verify a change. Celery workers restart through watchmedo; `docker compose restart <worker>` if in doubt.+- After changing the backend API surface: `make generate_api_client` (api-endpoints skill).+- Run `pre-commit run --files <changed files>` at the end of a multi-file task, before committing.++## Traps you can't guess from the code++- Tracing is span-only: there is no Trace table. A trace is the spans sharing `trace_id`; the root has `parent_span_id IS NULL`. OTLP ingest is `POST /api/v1/traces`.+- Most status transitions use `.filter().update()`, so no Django signals fire and the in-memory object goes stale. Wire each side effect at the call site on a freshly reloaded row.+- MCP (`/api/mcp/`, `services/mcp/`) is the first-class agent surface. REST, MCP and the Console share domain services; MCP is not a proxy of either. Every change gets an MCP-impact decision (mcp skill).+- The frontend uses only the generated OpenAPI client in `frontend/src/openapi/`; never hand-edit it.+- Platform model IDs (judges, generation, Jev) live in `overbae/core/model_registry.py`; the training and serving catalog lives in `overbae/modal/models.json`. Jev decisions use `overbae/core/decisions.py`.+- Tenancy is project-scoped with no org layer. A view that accepts guest writes opts in with `guest_allowed = True`, never with a permission class or middleware.+- OTLP ingest never creates a capability, a scan never deletes one, and `DELETE` is a soft delete. On OTLP spans, wire identity is `overmind.capability.id` alone.+- Celery routing must agree across `CELERY_TASK_ROUTES`, `make worker`, docker-compose and `docker/worker-topology.json`. Only prefork pools enforce `time_limit`. `tests/test_celery_topology.py` checks compose and `make worker` against the routes.+- Native coding agents own interpretation, code and semantic work. The platform runs deterministic, lineage-bound operations and never invokes a platform planning or generation agent.+- 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.+- 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` and `PRODUCT.md` carry a fixed YAML frontmatter schema that tooling reads. Extend the values; don't restructure the documents.++Subsystem detail lives in the skills: backend-architecture (Celery, tracing and scoring, evaluation, capabilities, auth and billing, training, serving, data-first), data-workshop, mcp, frontend-design.## Style-- **Rebuild, don't patch.** There are no real users yet. Build the change the right way from first principles and delete the old path; no flags, shims, `_v2` names or `if legacy` branches. Migrations are the exception: production and staging hold real state. Full bar and the "never simplify away" list: engineering-taste skill.--- **Comments** carry only what the code can't: a workaround, a wire-format or contrast constraint, an ordering invariant, a trap. Delete restatements, banners, history and name-respelling docstrings. Full policy and the two local traps: code-comments skill.+- **Rebuild, don't patch.** There are no real users yet. Build the change the right way from first principles and delete the old path; no flags, shims, `_v2` names or `if legacy` branches. Migrations are the exception: production and staging hold real state. Full bar: engineering-taste skill.+- **Comments** carry only what the code can't: a workaround, a wire-format or contrast constraint, an ordering invariant, a trap. Delete restatements, banners, history and name-respelling docstrings. Full policy: code-comments skill.### PythonRuff enforces formatting and line length. What it can't:-- Imports at the top of the file. The only exception is a lazy import that breaks a cyclic dependency, with a one-line reason.-- Never import a `_`-prefixed name from another module. If an outside caller needs it, the owning module exposes a public name first.-- Serializers for all API input and output — never return a raw dict from a view.-- `select_related`/`prefetch_related` on any queryset whose rows will touch a relation.-- Business logic goes in model methods, managers, or `services/` — not in views.+- Imports go at the top of the file. The only exception is a lazy import that breaks a cyclic dependency, with a one-line reason.+- Never import a `_`-prefixed name from another module; the owning module exposes a public name first.+- Serializers for all API input and output; a view never returns a raw dict.+- `select_related`/`prefetch_related` on any queryset whose rows touch a relation.+- Business logic goes in model methods, managers or `services/`, not in views.### Frontend-- The Console is dark-only, including first paint, authentication, charts and flow canvases. There is no theme selector, stored-theme resolution or OS-theme listener. Semantic tokens only; **never write `dark:` variants** — `border-success/40 bg-success/10 text-success`, not a hardcoded pair.-- **Flat surfaces.** Standard `shadow-*` utilities are disabled. Depth is surface layering plus 1px borders; shared confirmation dialogs alone use the subtle `shadow-confirmation` token.-- Icons come from the central registry only: `import { Icon } from "@/components/ui/icons"`. The glyphs are a vendored path table in `ui/icons/glyphs.ts` that `bun run icons:vendor` regenerates; never import that module or `lucide-react` in app code — `check:design` fails on both.-- New shadcn components: `bunx shadcn@latest add <component>`, then adapt to the token system.-- Tokens, primitives, the border-contrast floor, and the duplicated table implementations: frontend-design skill.+- The Console is dark-only, including first paint, authentication, charts and flow canvases. Use semantic tokens, with no `dark:` variants: `border-success/40 bg-success/10 text-success`.+- Flat surfaces: `shadow-*` utilities are disabled. Depth is surface layering plus 1px borders.+- Icons come only from `import { Icon } from "@/components/ui/icons"`; `check:design` fails on `lucide-react` or the vendored glyph table.+- Tokens, primitives, the border-contrast floor and the two table implementations: frontend-design skill.### UI copy-Instrument voice — state the fact and stop ("9 rows", never "9 rows — small enough to read"). No design rationale, no reassurance, no coaching phrases. Applies to backend-generated copy too.+Instrument voice: state the fact and stop ("9 rows", not "9 rows — small enough to read"). No design rationale, reassurance or coaching phrases. This applies to backend-generated copy too.### Naming-Never put plan-phase labels (P0/P1, "Phase N") in code, comments, or test names — name by behavior. Backend tests live flat: `tests/test_<feature>.py`; journeys live in `tests/journeys/test_<promise>.py`.+Name by behavior. Plan-phase labels (P0/P1, "Phase N") stay out of code, comments and test names. Backend tests live flat in `tests/test_<feature>.py`; journeys in `tests/journeys/test_<promise>.py`.## Workflow-- Never write unit tests after you write code.-- Strongly prefer E2E tests as the sole testing mechanism. Use them to verify complex features work. At the end of each E2E run, produce a verifiable, repeatable artifact containing the command, inputs or fixtures, environment requirements, and observed results.-- If a system must be tested in isolation, first write down all the ways it could fail, then write the code. Keep an isolated test only when it catches a concrete failure that existing E2E coverage misses; do not add assertions that merely mirror the implementation, pin incidental source text, or assert tautologies.-- Tests fake only what we do not own, and only at the network: `tests/fakes` (FakeLLM, FakeModal, the vendor, Stripe and Clerk APIs, `scripted` HTTP). Never patch `overbae.*` except to capture a Celery `.delay`/`.apply_async`, and never import a private `overbae` name; call the public entry point. Each contract has one owning test; a journey owns a customer promise, so a unit test does not repeat it. Do not restate declarations (field lists, constants, `__all__`, prompt prose). The `test-seams` pre-commit hook refuses new seams. Detail: run-tests skill.-- Stay in the asked scope. Fix the stated thing plus genuine prerequisites; report adjacent findings as a short "found but did not change" list. If the task is much bigger than framed, say so before editing.-- Simple, self-evident fixes: typecheck + lint is the bar — skip the test suite and say so plainly. When a suite run is warranted: run once, tee to a log, grep the log (run-tests skill).-- Which tests to run locally (compose Postgres and Redis up):- - While editing: the test file for the code (`uv run pytest tests/test_<feature>.py`, seconds) and the journey for its area (`make test-journeys test_args="-k <name>"`, about a minute).- - Before a push: `make test` (about 75 s).- - When the change crosses ingest, sync, the worker, the gateway, MCP or the Console: `make test-journeys` (about 6 min).- - CI runs the platform suites (lint, frontend, test, journeys) on every ready PR, and SDK CI only when `overmind/` or `.github/workflows/sdk-ci.yml` changes, so a local run of everything is not required.-- A change is finished when every surface reflecting it is updated, not when its own vertical compiles. CI cannot catch this, so walk the list in the pr-etiquette skill before opening a PR: **MCP** (the first-class agent surface: `services/mcp/` — impact classification, catalog, contracts, tools, prompts, resources; mcp skill), **cross-vertical blast radius** (celery routing, the `seed_demo` command, the generated client, this file and the skills), and **docs** (the sibling `overmind-core/docs` repo at `../docs` — open that PR alongside and link the two).-- Commit messages: short subject + at most one body line. No co-author trailers. Commit and push only when asked; on a sweep branch, one commit per observation.-- Changing behavior that this file or a skill describes? Update it in the same PR. There is one copy of every rule; keeping it true is part of the change.+- Don't write unit tests after you write code. Prefer E2E tests as the testing mechanism. Each E2E run ends with a repeatable artifact: the command, inputs or fixtures, environment requirements and observed results.+- If a system must be tested in isolation, first write down the ways it can fail, then write the code. Keep an isolated test only when it catches a concrete failure that E2E coverage misses. No assertions that mirror the implementation, pin incidental text or restate declarations.+- Tests fake only what we do not own, and only at the network (`tests/fakes`: FakeLLM, FakeModal, vendor, Stripe and Clerk APIs, `scripted` HTTP). Patch `overbae.*` only to capture a Celery `.delay`/`.apply_async`; call public entry points. Each contract has one owning test, and a journey owns a customer promise. The `test-seams` pre-commit hook refuses new seams. Detail: run-tests skill.+- Stay in the asked scope: fix the stated thing plus genuine prerequisites, and list adjacent findings as "found but did not change". If the task is much bigger than framed, say so before editing.+- Simple, self-evident fixes need typecheck and lint only; say plainly that tests did not run. When a suite run is warranted, run it once, tee to a log and grep the log.+- Which tests to run (compose Postgres and Redis up): while editing, the feature's test file and its journey (`make test-journeys test_args="-k <name>"`); before a push, `make test` (about 75 s); when a change crosses ingest, sync, the worker, the gateway, MCP or the Console, `make test-journeys` (about 6 min). CI runs the rest.+- A change is finished when every surface that reflects it is updated: MCP, Celery routing, `seed_demo`, the generated client, this file and the skills, and the docs repo at `../docs` (pr-etiquette skill lists them). CI cannot catch these.+- When a change makes this file, a skill, a hook message or another agent doc untrue, update or delete that line in the same PR; the pr-etiquette skill lists the places to search. There is one copy of every rule.+- Commit messages: short subject plus at most one body line, no co-author trailers. Commit and push only when asked; on a sweep branch, one commit per observation.## Communication-- Lead with the outcome: the first sentence answers "what happened" or "what did you find". Detail and reasoning follow. Keep output short by leaving things out, not by compressing the writing.-- Before reporting progress, check each claim against a tool result from this session. Report faithfully: failing tests with their output, a skipped step as skipped, a verified result plainly.+- Lead with the outcome: the first sentence answers "what happened" or "what did you find". Keep output short by leaving things out, not by compressing the writing.+- Report what the tool results show: failing tests with their output, a skipped step as skipped, a verified result plainly.- UI work pauses for a look in the browser before screenshots or a PR; expect iterations.-- Sub-agents explore; edits and decisions happen in the main thread, with progress reports along the way. No multi-agent workflows unless asked.+- Sub-agents explore; edits and decisions stay in the main thread. No multi-agent workflows unless asked.- When there is enough information to act, act. Give a recommendation, not a survey of options.-## Guardrails+## Agent setup++One source serves all three tools:-`.agents/hooks/` holds deterministic guards. A denial names the fix; follow it rather than retrying.+| | Instructions | Skills | Hooks |+| ----------- | ------------------------- | ---------------------------------------------- | -------------------------------------------------------------------- |+| Claude Code | this file (v2.1.277+) | `.claude/skills` → symlink to `.agents/skills` | `.claude/settings.json` |+| Codex | this file (cut at 32 KiB) | `.agents/skills` | `.codex/hooks.json` |+| Cursor | this file | `.agents/skills` | imports `.claude/settings.json` (Third-Party Imports, on by default) |-- Claude Code reads the wiring in `.claude/settings.json`; Cursor reads the same file through its third-party hooks setting (on by default).-- Codex reads `.codex/hooks.json`; trust the project hooks once with `/hooks`.-- Skills live in `.agents/skills/` (frontmatter `name` and `description` only); `.claude/skills` is a symlink for Claude Code. Personal skills go in `~/.agents/skills/`.-- Claude Code reads this file only from v2.1.277 and only when no `CLAUDE.md` or `CLAUDE.local.md` exists. With a `CLAUDE.local.md`, set `/config` → Project instructions → `claude-md-and-agents-md`.+- `.agents/hooks/` holds deterministic guards shared by all three. A denial names the fix; follow it rather than retrying.+- Codex runs project hooks only after you approve them with `/hooks`, and asks again after every hook change.+- Claude Code reads this file only when no `CLAUDE.md` or `CLAUDE.local.md` exists. To keep a personal `CLAUDE.local.md`, set `/config` → Project instructions → `claude-md-and-agents-md`.+- Skill frontmatter is `name` and `description` only, so all three tools read it. Keep each `SKILL.md` under 500 lines and move detail into linked files beside it. Personal skills go in `~/.agents/skills/`.+- The `agent-docs-size` pre-commit hook enforces the size limits for this file and the skills.## Gotchas-- After `uv add`/`uv remove` the venv lacks the dev/test groups (pytest vanishes): `uv sync --group dev --group test`. The `uv_resync` hook runs it.-- A new Python dependency reaches a compose worker only when its container is recreated (`docker compose up -d --force-recreate --no-deps <worker>`); a worker started before the image changed keeps the old venv and crashes on import at its next watchmedo restart.-- `overbae/services/sft_assets/` ships via `add_local_dir`, which bakes it into the image at deploy time — editing `pretok.py`/`train.py` does nothing until `modal deploy overbae/modal/modal_sft_worker.py`. The job runs the old code and fails identically, so it reads as "the fix didn't work".-- Chat templates disagree on OpenAI wire shape: `content: null` and JSON-string `tool_calls[].function.arguments` either raise or silently render an argument-less call. `pretok.normalize_openai_wire` is the one place that reshapes them — training tool data on a new family means checking it there, not per-family.-- Vite on WSL serves stale module transforms after bulk out-of-editor file changes; hard reload won't fix it — restart vite. Tell: runtime "X is not defined" for code tsc accepts.-- Two table implementations exist (`components/ui/data-table.tsx` and the paged rows grid in `components/datasets/notebook/rows-grid.tsx`) — a table fix must be checked in both.-- `--border` has almost no contrast headroom; the ramp is bare/`70`/`60`. Never lower a border opacity without `bun run check:contrast -- --all`.-- `manage.py seed_demo` must keep every job/run terminal and every span scored, or beat/reconcilers re-drive them against real providers (seed-demo-data skill).+- After `uv add`/`uv remove` the venv lacks the dev and test groups (pytest vanishes): `uv sync --group dev --group test`. The `uv_resync` hook runs it.+- A new Python dependency reaches a compose worker only when its container is recreated (`docker compose up -d --force-recreate --no-deps <worker>`). An older worker crashes on import at its next watchmedo restart.+- `overbae/services/sft_assets/` is baked into the Modal image at deploy time. Editing `pretok.py` or `train.py` does nothing until `modal deploy overbae/modal/modal_sft_worker.py`; the job fails identically, so it reads as "the fix didn't work".+- Chat templates disagree on OpenAI wire shape: `content: null` and JSON-string `tool_calls[].function.arguments` either raise or render an argument-less call. `pretok.normalize_openai_wire` is the one place that reshapes them.+- Vite on WSL serves stale module transforms after bulk file changes made outside the editor; a hard reload won't fix it, so restart Vite. Tell: runtime "X is not defined" for code tsc accepts.+- Two table implementations exist (`components/ui/data-table.tsx` and `components/datasets/notebook/rows-grid.tsx`); check a table fix in both.+- `--border` has almost no contrast headroom; the ramp is bare, `/70`, `/60`. Run `bun run check:contrast -- --all` before you lower a border opacity.+- `manage.py seed_demo` must keep every job and run terminal and every span scored, or beat and the reconcilers re-drive them against real providers (seed-demo-data skill).diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 4786a24a..3bcdc5af 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -32,14 +32,14 @@ Run the same checks CI runs:- `main` is protected. Branch from `main`, open a PR, and fill in `.github/PULL_REQUEST_TEMPLATE.md`. The Verification section takes the commands you ran, not the ones you would run.- Keep a PR to one change. Fix the stated thing plus its real prerequisites; list adjacent findings in the PR body instead of fixing them.-- A change is finished when every surface reflecting it is updated: MCP (`overbae/services/mcp/`), Celery routing, `seed.py`, the generated OpenAPI client (`make generate_api_client`), and `AGENTS.md` or the skill that describes the behaviour. The PR template walks this list.+- A change is finished when every surface reflecting it is updated: MCP (`overbae/services/mcp/`), Celery routing, `manage.py seed_demo`, the generated OpenAPI client (`make generate_api_client`), and `AGENTS.md` or the skill that describes the behaviour. The PR template walks this list.- Frontend code uses the generated client in `frontend/src/openapi/`; never edit it by hand.- Commit messages: short subject plus at most one body line. No co-author trailers.- SDK changes (`overmind/`) bump `overmind/pyproject.toml` `version` and add a `CHANGELOG.md` entry.## Coding agents-`.agents/skills/` holds subsystem maps and procedures that Claude Code, Codex and Cursor load on demand; `AGENTS.md` indexes them. If you contribute with a coding agent, point it at the repo root and it picks these up. Hooks in `.agents/hooks/` guard generated files and dangerous commands; a denial names the fix.+`.agents/skills/` holds subsystem maps and procedures that Claude Code, Codex and Cursor load on demand; `AGENTS.md` indexes them. If you contribute with a coding agent, point it at the repo root and it picks these up. Hooks in `.agents/hooks/` guard generated files and dangerous commands; a denial names the fix. Codex runs them after you approve them with `/hooks`, and asks again after a hook changes.## Licencediff --git a/README.md b/README.mdindex be9500a3..dcde66e5 100644--- a/README.md+++ b/README.md@@ -22,16 +22,16 @@ Point it at your agent's codebase and it turns production traces (or any dataset> The weights are yours to download, retrain or roll back.-Available from the [Console](https://console.overmindlab.ai/), the `overmind` CLI, the [REST API](https://docs.overmindlab.ai/latest/platform/api.md), and an [MCP server](#connect-your-coding-agent) for Cursor, Claude Code, OpenCode and Codex. Hosted at [console.overmindlab.ai](https://console.overmindlab.ai/) or [run it yourself](#run-it-yourself).+Available from the [Console](https://console.overmindlab.ai/), the `overmind` CLI, the [REST API](https://docs.overmindlab.ai/reference/api), and an [MCP server](#connect-your-coding-agent) for Cursor, Claude Code, OpenCode and Codex. Hosted at [console.overmindlab.ai](https://console.overmindlab.ai/) or [run it yourself](#run-it-yourself).<table>-<tr><td><b><a href="https://docs.overmindlab.ai/latest/core/capabilities.md">Agent & Capabilities</a></b></td><td>A graph of your agent — capabilities, prompts, tools, and tasks — scanned from the repo.</td></tr>-<tr><td><b><a href="https://docs.overmindlab.ai/latest/core/observability.md">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/latest/core/datasets.md">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/latest/agent-testing/eval.md">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/latest/agent-testing/optimisers.md">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/latest/models/training.md">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/latest/models/inference.md">Inference</a></b></td><td>Trained and frontier models on one OpenAI-compatible API.</td></tr>+<tr><td><b><a href="https://docs.overmindlab.ai/explanation/capabilities">Agent & Capabilities</a></b></td><td>A graph of your agent — capabilities, prompts, tools, and tasks — scanned from the repo.</td></tr>+<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><p align="center">@@ -44,7 +44,7 @@ Available from the [Console](https://console.overmindlab.ai/), the `overmind` CL### Hosted-Sign up at [console.overmindlab.ai](https://console.overmindlab.ai/), pick your coding agent on **Get started** — Cursor, Claude Code, OpenCode or Codex — and paste the onboarding prompt into it with your agent's repo open. It installs `overmind`, runs `overmind init` and `overmind sync`, and builds the context graph. From then on everything is a `/overmind` command in the same chat:+Sign up at [console.overmindlab.ai](https://console.overmindlab.ai/), 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 || -------------------------- | --------------------------------------------- |@@ -61,40 +61,40 @@ Self-hosting keeps traces and training data inside your own network. The hosted```bashgit clone https://github.com/overmind-core/overmind.git && cd overmindcp .env.example .env # set the required keys below-docker compose up -d # Postgres, Redis, API on :8000, Console on :5173, Celery workers, beat, Grafana on :3001+docker compose up -d # Postgres, Redis, API on :8000, Console on :5173, Celery workers, beat, Workshop sandbox, Grafana on :3001```Document uploads include local English OCR for scanned PDFs, embedded images and direct PNG/JPEG/WebP uploads. Direct images are capped at 100 MB and 64 megapixels; animated images are not supported. The Docker image includes Tesseract and its English/orientation data. For workers or backend tests outside Docker, install `tesseract-ocr`, `tesseract-ocr-eng` and `tesseract-ocr-osd` on Debian/Ubuntu, or `brew install tesseract` on macOS. No external OCR service is required.-On first boot the API runs migrations and seeds the built-in evaluators; Swagger is at `/api/docs/`. Sign in at `http://localhost:5173` with any email and password. `docker compose exec api python manage.py seed_demo --owner <your email>` loads a full demo workspace.+On first boot the API runs migrations; Swagger is at `/api/docs/`. Sign in at `http://localhost:5173` with any email and password. `docker compose exec api python manage.py seed_demo --owner <your email>` loads a full demo workspace.<details><summary><b>What the API needs to boot</b></summary>The API refuses to start until every required key is set, and the error names each missing one. `.env.example` documents every key.-| Required | Used for |-| --------------------------------------------------------------- | ------------------------------------------------------------------------------------- |-| `OPENROUTER_API_KEY` | Judges, evals, trace scoring, optimiser scoring, frontier inference |-| `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 |-| `HF_TOKEN` | Gated Hugging Face base models; also set it in the Modal secret |+| Required | Used for |+| --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |+| `OPENROUTER_API_KEY` | Judges, evals, trace scoring, optimiser scoring, frontier inference |+| `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 |+| `HF_TOKEN` | Gated Hugging Face base models; also set it in the Modal secret |+| `SANDBOX_URL`, `SANDBOX_TOKEN` | The isolated Workshop sandbox; `.env.example` and compose set local values — change the token in production || Optional | Effect || ------------------- | ----------------------------------------------------------------------- |-| `OPENAI_API_KEY` | The `embedding_cosine` evaluator || `STRIPE_SECRET_KEY` | Paid plans and the credit cap; without it, usage is metered with no cap |-Fine-tuning and serving also need the Modal workers deployed (`modal deploy overbae/modal/modal_vllm_worker.py`, `register_model.py` and `modal_sft_worker.py`) and a Modal secret named `overmind-inference` with the AWS keys, `INFERENCE_API_KEY` and `HF_TOKEN`.+Fine-tuning and serving also need the Modal workers deployed (`modal deploy overbae/modal/modal_vllm_worker.py`, `register_model.py` and `modal_sft_worker.py`; native decision models also use `modal_decision_evaluation.py` and `modal_decision_serving.py`) and a Modal secret named `overmind-inference` with the AWS keys, `INFERENCE_API_KEY` and `HF_TOKEN`.Self-hosted login uses email and password. Keep Clerk and Stripe secrets blank.Data Workshop transformations are authored by your native coding agent through MCP;the platform stores source files, immutable cell versions and execution receipts.There is no platform Workshop agent or ChatGPT account connection.Reusable scripts, cross-source revisions and continuous bindings use the dedicated-[Workshop runtime and package protocol](docs/workshop-pipelines.md).-See [self-hosting](https://docs.overmindlab.ai/platform/self-hosting) for configuration+[Workshop runtime and package protocol](https://docs.overmindlab.ai/reference/pipelines).+See [self-hosting](https://docs.overmindlab.ai/how-to/self-host) for configurationand private VM setup.</details>@@ -103,7 +103,7 @@ and private VM setup.```bashpip install "overmind[tracing]"-export OVERMIND_API_KEY=ovr_… # project key from Console → Settings; add OVERMIND_API_URL for self-host+export OVERMIND_API_KEY=ovr_… # project key from the project page in the Console; add OVERMIND_API_URL for self-host``````python@@ -133,7 +133,7 @@ def handle(request: dict, session_id: str) -> dict:Overmind ships an MCP server at `/api/mcp/` with tools, resources and prompts for the platform's agent workflows. Account API keys and OAuth connections can access every active project their account is authorized to use: call `list_projects`, then pass the selected `project_id` on project tools and resource URIs. Membership is checked on every operation. Project API keys remain limited to their configured project. Every tool declares what it costs to run (`free`, `compute`, `llm`, `gpu`) and whether it is destructive. Evaluation matrix rows can be deleted through their scoped lifecycle tool.-The [optional plugin](overmind/README.md#mcp-and-optional-plugins) packages the MCP connection, Overmind branding and nine workflow skills. OAuth connections remain authorized until revoked; access tokens expire after one hour and refresh tokens rotate. Direct MCP connections can use an API key without OAuth or a plugin.+The [optional plugin](overmind/README.md#mcp-and-optional-plugins) packages the MCP connection, Overmind branding and the Overmind workflow skills. OAuth connections remain authorized until revoked; access tokens expire after one hour and refresh tokens rotate. Direct MCP connections can use an API key without OAuth or a plugin.`overmind init --ide <cursor|claude|opencode|codex>` prepares the local configuration and `overmind sync` installs the repository's project API key. To configure an API key by hand:@@ -195,17 +195,20 @@ http_headers = { "X-Api-Key" = "ovr_…" }<details><summary><b>What the tools cover</b></summary>-| Domain | Tools |-| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Projects | `list_projects` |-| Observability | `inspect_capability_health`, `query_failures`, `query_traces`, `query_task_executions`, `get_job` |-| Datasets | `list_datasets`, `inspect_dataset`, `query_dataset`, `create_dataset_from_traces`, `create_dataset_from_llm_calls`, `inspect_dataset_workbench`, `save_dataset_pipeline`, `run_dataset_pipeline`, `import_dataset_version`, `update_dataset` |-| Evaluations | `check_evaluation_readiness`, `upsert_evaluator`, `run_evaluation`, `compare_evaluations`, `annotate_evaluation_sample` |-| Training | `check_finetune_readiness`, `estimate_finetune`, `start_finetune`, `retry_deployment`, `set_active_model`, `run_inference`, `get_model_swap_prompt` |-| 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` |+| Domain | Main tools |+| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Projects | `list_projects`, `create_api_key` |+| Observability | `inspect_capability_health`, `query_failures`, `query_traces`, `list_signals`, `set_signal_subscription`, `get_job`, `inspect_operation` |+| Datasets | `list_datasets`, `inspect_dataset`, `query_dataset`, `create_dataset_from_traces`, `create_dataset_from_llm_calls`, `explore_dataset`, `create_data_partition`, `inspect_dataset_workbench`, `save_dataset_pipeline`, `run_dataset_pipeline`, `import_dataset_version`, `update_dataset` |+| 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` |++`tools/list` returns the tools the connection's permissions allow: a read-only connection omits every write tool.Prompts such as `investigate-capability`, `finetune-capability` and `ship-model` chain the tools into complete workflows.diff --git a/scripts/check_agent_docs.py b/scripts/check_agent_docs.pynew file mode 100644index 00000000..5d7f19d5--- /dev/null+++ b/scripts/check_agent_docs.py@@ -0,0 +1,33 @@+"""Keep agent instructions inside the limits the coding agents load.++Codex stops reading AGENTS.md at 32 KiB, so the playbook keeps half that as headroom.+Claude Code and Cursor advise SKILL.md under 500 lines, with detail in linked files.+"""++import sys+from pathlib import Path++AGENTS_MAX_BYTES = 16 * 1024+SKILL_MAX_LINES = 500+++def main() -> int:+ root = Path(__file__).resolve().parent.parent+ errors = []+ size = (root / "AGENTS.md").stat().st_size+ if size > AGENTS_MAX_BYTES:+ errors.append(f"AGENTS.md is {size} bytes; the limit is {AGENTS_MAX_BYTES}.")+ for skill in sorted((root / ".agents" / "skills").glob("*/SKILL.md")):+ lines = len(skill.read_text(encoding="utf-8").splitlines())+ if lines > SKILL_MAX_LINES:+ errors.append(+ f"{skill.relative_to(root)} has {lines} lines; the limit is {SKILL_MAX_LINES}. "+ "Move detail into a linked file beside it."+ )+ for error in errors:+ print(error, file=sys.stderr)+ return 1 if errors else 0+++if __name__ == "__main__":+ sys.exit(main())