31 Commits

Author SHA1 Message Date
53fdf4d060 Referenz: externe Läufe exportieren und importieren, Referenz ohne Rang mit Strich im Ranking, Reiter Referenz; Roadmap 0.1.1
All checks were successful
release / deb (push) Successful in 4m3s
release / arch (push) Successful in 5m33s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 11:04:12 +01:00
bc461a404f ROADMAP/KLICKTESTS: GUI-Überarbeitung nachgezogen, neue Todos #1048-#1050, Klicktests aufgaben2plan und einstellungen2bereitschaft
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:25:52 +01:00
e322a14030 GUI: abgebrochenen oder teils ausgefallenen Batch fortsetzen
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:25:25 +01:00
52b13bd269 GUI: Einstellungen mit Bereitschafts-Ampel, einklappbaren Modellkarten und Modell-Liste vom Server
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:25:00 +01:00
10b0b1ce8e GUI: Aufgabenkarten mit Beschreibung, Plan-und-Stand-Matrix, feste Startleiste mit Zeitschätzung, Hinweis bei wenigen Durchläufen, klickbare Ergebnis-Zellen
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 17:54:17 +01:00
0832b8c96f GUI: dunkles Theme mit orangem Akzent, Ranking als Karten mit Tok/s, Logo und Icons, Start immer auf Benchmark
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 17:52:14 +01:00
ea4fb724d4 fix: Review-Befunde beheben (Image-Bau, Absturzsicherung, Image-Name, Ausgabelimit)
All checks were successful
release / deb (push) Successful in 3m57s
release / arch (push) Successful in 5m19s
- App baut cb-python selbst: Containerfile eingebettet, Befehle image_status
  und build_image, Live-Ausgabe, Knopf in den Einstellungen. start_batch
  prüft vorher, ob die Images da sind.
- running-Flag wird per Wächter zurückgesetzt, auch nach einem Absturz.
- Ein Fehler in einem Lauf beendet nicht mehr den Batch: Lauf wird als
  sandbox_error gespeichert. endpoint_error und sandbox_error zählen nicht
  in die Bewertung und werden beim Fortsetzen wiederholt.
- Image-Name wird geprüft (kein führendes -, nur erlaubte Zeichen), Podman
  bekommt -- vor dem Image.
- Ausgabe von Befehlen wird auf 1 MiB je Strom begrenzt.
- Abbruch wird auch vor dem Aufwärmen geprüft.
- Fehlerklassen lesbar, Hinweis auf nicht gewertete Läufe.
65 Unit-Tests grün (6 ignorierte Integrationstests); echter Sandbox- und Image-Test grün.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 13:15:11 +01:00
bd5afd44c9 docs: README-Aussage zum Ranking korrigieren
Der Satz nannte ein Intervall, das es nicht gibt (Wilson-Intervall ist
F-12, Phase 2). Gefunden vom Reality-Check-Agenten, im Code bestätigt.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 12:39:02 +01:00
78388a67b8 build: Arch-Paket im Workflow wirklich hochladen
Das Paket wurde nach <repo>/src/ kopiert, einem Ordner, den es im Repo schon
gibt (Frontend). Der Upload suchte im Wurzelverzeichnis und fand nichts,
der Job meldete trotzdem Erfolg. Jetzt eigener Ordner dist/ und der Upload
schlägt fehl, wenn keine Datei da ist.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 12:38:50 +01:00
105a3a11a3 feat: Oberfläche neu, Modell-Adapter wählbar, Bewertung je Bereich
All checks were successful
release / deb (push) Successful in 3m59s
release / arch (push) Successful in 5m23s
Die erste Fassung der Oberfläche war inhaltlich und optisch schwach. Neu:
drei Reiter (Benchmark, Ergebnisse, Einstellungen). Modelle werden in den
Einstellungen mit Adapter (Ollama oder OpenAI-kompatibel), URL, Modell-ID
und Schlüssel-Variable angelegt, mit Verbindungstest. config.toml speichert
die Liste. Bewertung absolut in Prozent: ein Wert je Bereich A bis D und
eine Gesamtnote, gewichtet nach weight. Batch-Verlauf, Schritt-Ansicht,
Erklärung der Bewertung. 55 Unit-Tests grün, svelte-check ohne Fehler.
Im Browser mit Beispieldaten geprüft, nicht in der echten App.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 12:27:23 +01:00
07994ed948 build: Release-Workflow korrigieren (upload-artifact v3, Arch ohne LTO)
All checks were successful
release / deb (push) Successful in 3m55s
release / arch (push) Successful in 5m24s
Der erste Lauf auf srv01 zeigte: Das .deb baut, aber upload-artifact@v4
wird von Gitea nicht unterstützt. Beim Arch-Paket scheiterte der Link an
fehlenden sqlite3-Symbolen, weil makepkg das gebündelte SQLite mit -flto
kompiliert. Fix: upload-artifact@v3 und options=(!lto).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 12:20:56 +01:00
04ecaa4585 build: Makefile für Entwicklung, Tests, Images und Paket
Ziele: dev, build, test, test-integration (mit Umgebungsvariablen), images,
arch-pkg, stop (Dev-App), stop-runs (cb-Container), clean. make help listet alles.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-07 12:12:50 +01:00
78728ef00e build: Paketbau für .deb und Arch-Paket vorbereiten
Some checks failed
release / deb (push) Failing after 4m33s
release / arch (push) Failing after 5m26s
Tauri-Bundle: .deb hängt von podman ab und installiert die Aufgaben nach
/usr/share/coding-bench/tasks. Die App findet diesen Ordner, wenn weder
Konfiguration noch Datenordner Aufgaben angeben. PKGBUILD, Desktop-Eintrag
und Gitea-Workflow (.deb und Arch-Paket, Start bei Tag v* oder manuell).

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-07 12:03:05 +01:00
a968acf3ae docs: Plattform auf CachyOS korrigieren, README-Status prüfen
Pop!_OS war als Zielplattform eingetragen, geprüft wurde auf CachyOS. README
nennt jetzt die tatsächlich geprüften Versionen (CachyOS, Podman 6.1.4,
Node 24.21, Rust 1.99.1), beschreibt den Stand ehrlich und listet die
Anforderungen mit Ollama oder OpenAI-kompatiblem Endpunkt.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-07 11:58:53 +01:00
91a15baebc feat: Podman-Status im Setup und Schritt-Ansicht je Lauf
Setup zeigt, ob der Container-Befehl läuft (Version). Ergebnistabelle hat
eine Schritte-Ansicht: Nachrichten, Tool-Aufrufe und Tool-Antworten eines
Laufs aus der Datenbank. Store-Test grün, 53 Unit-Tests insgesamt.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-07 11:55:56 +01:00
668e690cda feat: Rangliste und Matrix für Batches
ranking.rs: Gesamtscore je Modell (gewichtet nach weight aus task.toml),
Median-Dauer und Completion-Tokens als Tie-Breaker, Matrix Modell × Aufgabe
mit Erfolgen und mittlerem Score. Befehl batch_ranking, Anzeige nach dem
Batch. 5 Unit-Tests grün, 47 insgesamt. Wilson-Intervalle folgen mit F-12.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-07 11:54:28 +01:00
bf3d8d8459 test: Aufgaben über strata bestanden, Testbericht
Alle sechs Aufgaben mit qwen3.8-flash-next-q2_0 über den OpenAI-Endpunkt
von strata: 6 von 6 bestanden, Score 1.00. Vergleich zum kleinen Modell
qwen3:0.6b (0 von 6). Der Lauf ist eine Wiederholung.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 22:49:29 +01:00
dce98d3d11 feat: API-Schlüssel für strata aus Umgebungsvariable
strata verlangt nach dem Start mit --access lan einen Schlüssel (HTTP 401).
Der Client liest ihn aus der Umgebungsvariable STRATA_API_KEY (Name in
config.toml änderbar) und sendet ihn als Bearer-Token. Der Schlüssel steht
weder in der Konfiguration noch im Repo.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 21:13:26 +01:00
f35b68ae1f feat: OpenAI-kompatibler Modell-Client für strata
Backend in config.toml wählbar (ollama oder openai), Standard-URL für
strata im LAN (192.168.12.4:8082). Nachrichten werden ins OpenAI-Format
umgeschrieben, Tool-Antworten bekommen die passende tool_call_id. Test
für die Umwandlung grün (42 Unit-Tests). Verbindung zu strata noch nicht
möglich: alle drei Adressen lehnen ab.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 21:06:29 +01:00
49e543360b docs: Testbericht für automatische Läufe
Eine Datei mit je einer Zeile pro Klicktest: ✓ nur, wo ein Rust-Test oder
der Lauf gegen srv04 es tatsächlich prüft; manuelle Schritte bleiben offen.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 20:03:30 +01:00
a9fb334bca feat: Aufgaben a-01 bis a-03 und b-04 bis b-06
Aufgaben unter tasks/ mit prompt.md, task.toml, start/ und check.sh.
Musterlösungen bestehen die Checks, eine leere Lösung scheitert. b-06
erkennt fünf Mutationen; behoben: veralteter Bytecode in Mutantenkopien.
Echter Lauf mit qwen3:0.6b auf srv04: 0 von 6 bestanden. Ein Repo-Test
prüft die Gültigkeit der Aufgaben.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 20:01:24 +01:00
d49e4cfd05 feat: Batch aus der Oberfläche starten
Tauri-Befehle start_batch, cancel_batch, batch_results. Fortschritt läuft
als Ereignis batch-event. Datenbank coding-bench.sqlite im Datenordner.
Oberfläche: Aufgaben wählen, Modelle und Wiederholungen angeben, starten,
abbrechen, Live-Log und Ergebnistabelle. Ollama-URL in config.toml.
40 Unit-Tests grün, svelte-check ohne Fehler. Im Fenster nicht geprüft.
lib.rs wurde vor meiner Änderung auf der Platte zurückgesetzt (ohne
runner/store); ich habe auf dem aktuellen Stand aufgebaut.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 19:46:04 +01:00
c8290aeb94 feat: Runner und SQLite-Speicher
runner.rs: Plan in Reihenfolge Modell/Aufgabe/Wiederholung, Aufwärmen je
Modell, frische Sandbox pro Lauf, check.sh im selben Container, Abbruch
und Fortsetzen über die Datenbank. store.rs: Schema nach SPEC 8, Lauf und
Schritte in einer Transaktion. Agent-Loop bekommt Abbruchflag.
Ende-zu-Ende gegen srv04 mit qwen3:0.6b grün; Fortsetzen überspringt
fertige Läufe. 38 Unit-Tests grün.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 19:35:02 +01:00
e69f3be35b test: Agent-Lauf gegen Ollama auf srv04 mit qwen3:0.6b
Ignorierter Test ollama_lauf_schreibt_datei_und_beendet bestanden:
Modell schreibt out.txt und ruft done auf (1 Schritt, 496/219 Tokens, 20 s
inkl. Modell-Ladezeit).

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 19:31:50 +01:00
a02f57b469 feat: Agent-Loop mit Tools und Fehlerklassen
agent.rs: fünf Tools (read_file, write_file, list_dir, run_shell, done),
Pfadprüfung auf /work, Fehlerklassen nach SPEC 5, Schleifenerkennung,
Limits für Schritte und Zeit, Metriken. Ollama-Client über /api/chat.
31 Unit-Tests mit Mock-Modell grün; Werkzeuge gegen echte Sandbox grün.
Echter Modelllauf steht aus, weil Ollama nicht läuft und keine Modelle da sind.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 19:24:08 +01:00
173be01279 feat: Sandbox-Limits in config.toml und Image cb-python
Speicher-, CPU- und Runtime-Angabe in config.toml, Standard podman, 2g, 2.
Containerfile für cb-python (Python 3.12, pytest). Echter Sandbox-Test
mit cb-python:latest grün.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 19:15:04 +01:00
e7e0ad558d feat: Podman-Sandbox pro Lauf
sandbox.rs startet einen Container ohne Netz (--network none, Speicher-
und CPU-Limit, PID-Limit), kopiert die Aufgabe nach /work, führt Befehle
mit Timeout aus, exportiert /work und entfernt den Container beim Verwerfen.
Echter Test gegen Podman grün (ignoriert, braucht CB_TEST_IMAGE). Noch
nicht an Commands angebunden; Config-Limits und cb-python-Image offen.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 19:13:18 +01:00
304a7a644c docs: Sandbox auf Podman umstellen
Entscheidung #1039: Podman (rootless) statt Docker, weil nur Podman
installiert ist. SPEC, README, ROADMAP und KLICKTESTS angepasst.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 19:11:23 +01:00
e16788a3cb feat: Aufgaben laden und validieren
tasks/<gruppe>/<name>/ wird eingelesen. Pflichtdateien, task.toml-Werte
und ausführbares check.sh werden geprüft, fehlerhafte Aufgaben mit Grund
gemeldet. Setup zeigt gültige Aufgaben und Fehler. cargo test: 13 Tests
grün. Klicktests aufgabe2validierung.1-.2 noch manuell offen.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 19:06:06 +01:00
3bd5197867 feat: TOML-Config und Datenordner anlegen
config.toml im App-Konfigurationsordner, Standard wird beim ersten Start
angelegt. Datenordner und Aufgabenordner werden aufgelöst und im Setup
angezeigt. Standard-Startseite ersetzt durch Pfad-Ansicht.
cargo test: 6 Tests grün. Klicktests start2app.1-.2 noch manuell offen.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 18:49:29 +01:00
57fbc57a54 feat: Tauri-2-Gerüst mit Svelte und TypeScript anlegen
create-tauri-app, Template svelte-ts. npm run build und cargo check laufen
durch. App nicht gestartet, Datenordner und TOML-Config folgen (#1018).

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 18:37:40 +01:00
94 changed files with 14932 additions and 48 deletions

View File

@ -0,0 +1,61 @@
# Release-Pakete: .deb (Ubuntu/Debian) und Arch-Paket (CachyOS/Arch).
# Startet bei einem Tag v* oder manuell (workflow_dispatch). Die Artefakte hängen am Lauf.
name: release
on:
workflow_dispatch:
push:
tags:
- "v*"
jobs:
deb:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- name: Systemabhängigkeiten
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev build-essential curl wget file \
libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev patchelf
- uses: actions/setup-node@v4
with:
node-version: 24
- uses: dtolnay/rust-toolchain@stable
- run: npm ci
- run: npm run tauri build -- --bundles deb
- uses: actions/upload-artifact@v3
with:
name: coding-bench-deb
path: src-tauri/target/release/bundle/deb/*.deb
arch:
runs-on: ubuntu-24.04
container: archlinux:latest
steps:
- name: Pakete für Arch
run: |
pacman -Syu --noconfirm --needed base-devel git nodejs npm rust \
webkit2gtk-4.1 gtk3 librsvg libayatana-appindicator podman sudo
useradd -m builder
echo "builder ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/builder
- uses: actions/checkout@v4
with:
path: src
- name: Quellarchiv und Paket bauen
run: |
cd src
VERSION=$(sed -n 's/^pkgver=//p' packaging/arch/PKGBUILD)
git archive --prefix=coding-bench-$VERSION/ -o /tmp/coding-bench-$VERSION.tar.gz HEAD
mkdir -p /home/builder/pkg
cp packaging/arch/PKGBUILD /tmp/coding-bench-$VERSION.tar.gz /home/builder/pkg/
chown -R builder:builder /home/builder/pkg
su builder -c "cd /home/builder/pkg && makepkg -s --noconfirm -f"
# Eigener Ordner: Im Repo gibt es selbst ein src/ (Frontend), dorthin darf das Paket nicht.
mkdir -p "$GITHUB_WORKSPACE/dist"
cp /home/builder/pkg/*.pkg.tar.zst "$GITHUB_WORKSPACE/dist/"
ls -l "$GITHUB_WORKSPACE/dist/"
- uses: actions/upload-artifact@v3
with:
name: coding-bench-arch
path: dist/*.pkg.tar.zst
if-no-files-found: error

10
.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

7
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,7 @@
{
"recommendations": [
"svelte.svelte-vscode",
"tauri-apps.tauri-vscode",
"rust-lang.rust-analyzer"
]
}

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"svelte.enable-ts-plugin": true
}

View File

@ -33,12 +33,12 @@ für einen Block aufweichen; das steht dann im Todo.
## lauf2sandbox ## lauf2sandbox
**Zweck:** Ein Lauf startet in einem frischen Container ohne Netz und räumt danach auf. **Zweck:** Ein Lauf startet in einem frischen Container ohne Netz und räumt danach auf.
**Deckt ab:** #1004 **Deckt ab:** #1004
**Voraussetzung:** Docker läuft, Image `cb-python:latest` vorhanden. **Voraussetzung:** Podman läuft, Image `cb-python:latest` vorhanden.
| Test | Schritte | Erwartet | Art | | Test | Schritte | Erwartet | Art |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| lauf2sandbox.1 | Einen Lauf starten, im Agenten `curl` auf eine externe Adresse ausführen lassen | Netzwerk ist nicht erreichbar | manuell | | lauf2sandbox.1 | Einen Lauf starten, im Agenten `curl` auf eine externe Adresse ausführen lassen | Netzwerk ist nicht erreichbar | manuell |
| lauf2sandbox.2 | Nach Lauf-Ende Docker-Containerliste prüfen | Kein Container des Laufs mehr vorhanden, `/work` liegt als Artefakt vor | manuell | | lauf2sandbox.2 | Nach Lauf-Ende Podman-Containerliste prüfen | Kein Container des Laufs mehr vorhanden, `/work` liegt als Artefakt vor | manuell |
## lauf2ergebnis ## lauf2ergebnis
**Zweck:** Ein Agentenlauf wird bewertet und mit Schritten gespeichert. **Zweck:** Ein Agentenlauf wird bewertet und mit Schritten gespeichert.
@ -69,3 +69,37 @@ für einen Block aufweichen; das steht dann im Todo.
| Test | Schritte | Erwartet | Art | | Test | Schritte | Erwartet | Art |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| ergebnis2detail.1 | Ergebnisansicht öffnen, Rangliste und Matrix prüfen | Rang, Gesamtscore und Matrix-Farben stimmen mit den Läufen überein | manuell | | ergebnis2detail.1 | Ergebnisansicht öffnen, Rangliste und Matrix prüfen | Rang, Gesamtscore und Matrix-Farben stimmen mit den Läufen überein | manuell |
## aufgaben2plan
**Zweck:** Vor und während eines Laufs ist sichtbar, was getestet wird, was geplant ist und was schon gelaufen ist.
**Deckt ab:** #1008, #1009
**Voraussetzung:** Modell angebunden, Container-Image gebaut, mindestens ein früherer Batch.
| Test | Schritte | Erwartet | Art |
| --- | --- | --- | --- |
| aufgaben2plan.1 | Reiter „Benchmark“ öffnen, bei einer Aufgabe „Aufgabentext“ klicken | Karte zeigt Titel, Text, Schritt- und Zeitlimit, „zuletzt“ oder „noch nie gelaufen“ | manuell |
| aufgaben2plan.2 | Zwei Modelle und drei Aufgaben wählen, starten | Matrix „Plan und Stand“ zeigt erst „zuletzt“, dann „geplant“, „läuft …“ und den Prozentwert; die Startleiste zeigt Läufe und Zeitschätzung | manuell |
| aufgaben2plan.3 | Lauf abbrechen, dann „Fortsetzen“ klicken | Fertige Zellen zeigen „schon vorhanden“, nur offene Zellen laufen | manuell |
## einstellungen2bereitschaft
**Zweck:** Die Einstellungen sagen, ob alles für einen Benchmark bereit ist, und führen durch die Einrichtung.
**Deckt ab:** #1008
**Voraussetzung:** Podman installiert, ein Modell-Server erreichbar, einer ausgeschaltet.
| Test | Schritte | Erwartet | Art |
| --- | --- | --- | --- |
| einstellungen2bereitschaft.1 | Reiter „Einstellungen“ öffnen | Ampel zeigt je Punkt ✓ oder ○ mit Hinweis; Modellkarten zeigen grünen oder roten Punkt | manuell |
| einstellungen2bereitschaft.2 | Modell öffnen, Feld „Modell-ID“ anklicken | Der Server bietet seine Modelle zur Auswahl an | manuell |
| einstellungen2bereitschaft.3 | Image bauen, danach Ampel ansehen | Image-Zeile wird ✓, Ampel wechselt auf „Bereit“, sobald alle Punkte erfüllt sind | manuell |
## referenz2ranking
**Zweck:** Ein von Hand gelöster Lauf (z. B. Claude Code) wird als Referenz in die Bewertung übernommen.
**Deckt ab:** #1052
**Voraussetzung:** Container-Image gebaut, ein Batch mit lokalen Modellen vorhanden, Claude Code oder ähnliches zur Hand.
| Test | Schritte | Erwartet | Art |
| --- | --- | --- | --- |
| referenz2ranking.1 | Im Reiter „Referenz“ zwei Aufgaben und 1 Durchlauf wählen, „Exportieren“ klicken | Ordner mit je einem Unterordner je Aufgabe und Durchlauf; darin Startdateien und `AUFGABE.md`, keine `check.sh` | manuell |
| referenz2ranking.2 | Eine Aufgabe in Claude Code lösen lassen, Ordner im Reiter „Referenz“ importieren, Modellname und Batch angeben | Meldung „1 Lauf geprüft“; Ergebnis der Prüfung (bestanden oder nicht) stimmt mit dem Ordnerinhalt überein | manuell |
| referenz2ranking.3 | Reiter „Ergebnisse“ des Batches öffnen | Referenz steht getrennt mit Kennzeichnung „extern“; in den Bereichsbalken der lokalen Modelle ist ein Strich beim Wert der Referenz | manuell |

46
Makefile Normal file
View File

@ -0,0 +1,46 @@
# coding-bench: Bedienung über make. `make help` zeigt alle Ziele.
CB_IMAGE ?= cb-python:latest
ARCH_BUILD := build/arch
VERSION := $(shell sed -n 's/^pkgver=//p' packaging/arch/PKGBUILD)
.PHONY: help dev build test test-integration images arch-pkg stop stop-runs clean
help: ## Zeigt diese Hilfe
@grep -E '^[a-zA-Z_-]+:.*## ' $(MAKEFILE_LIST) | awk -F":.*## " '{printf " %-18s %s\n", $$1, $$2}'
dev: ## App im Entwicklungsmodus starten (Fenster öffnet sich)
npm run tauri dev
build: ## Release-Binary bauen (ohne Paket)
npm run tauri build -- --no-bundle
test: ## Unit-Tests, Frontend-Build und Typprüfung
cd src-tauri && cargo test
npm run build
npx svelte-check --threshold error
test-integration: ## Echte Läufe: Podman, Modell-Endpunkt (CB_BACKEND, CB_OLLAMA_URL oder CB_OPENAI_URL, CB_OLLAMA_MODEL)
@test -n "$$CB_OLLAMA_MODEL" || { echo "CB_OLLAMA_MODEL setzen (und CB_OLLAMA_URL oder CB_BACKEND=openai mit CB_OPENAI_URL)"; exit 1; }
cd src-tauri && CB_TEST_IMAGE=$(CB_IMAGE) cargo test -- --ignored --nocapture --test-threads=1
images: ## Container-Image cb-python bauen
podman build -t $(CB_IMAGE) images/cb-python
arch-pkg: ## Arch-Paket lokal bauen (build/arch, braucht makepkg)
rm -rf $(ARCH_BUILD) && mkdir -p $(ARCH_BUILD)
git archive --prefix=coding-bench-$(VERSION)/ -o $(ARCH_BUILD)/coding-bench-$(VERSION).tar.gz HEAD
cp packaging/arch/PKGBUILD $(ARCH_BUILD)/
cd $(ARCH_BUILD) && makepkg -f
stop: ## Laufende App (Dev-Modus) beenden
-pkill -f "target/debug/coding-bench"
-pkill -f "tauri dev"
-fuser -k 1420/tcp 2>/dev/null
stop-runs: ## Übrig gebliebene Sandbox-Container (cb-*) entfernen
-podman ps -a --filter name=^cb- -q | xargs -r podman rm -f
clean: ## Build-Ausgaben entfernen (nicht die Quellen)
rm -rf build build-frontend .svelte-kit
rm -rf src-tauri/target

View File

@ -10,15 +10,15 @@ Fehlerberichte und Feature-Wünsche sind als Issues willkommen. Pull Requests we
## Status ## Status
Version: noch keine (Release 0.1.0 ist geplant, siehe `ROADMAP.md`). Es gibt bisher **keinen lauffähigen Code**. Dieses Dokument beschreibt das Ziel aus der `SPEC.md`. Version: noch keine (Release 0.1.0 in Arbeit, siehe `ROADMAP.md`). Der Code ist gebaut und die Kernfunktionen sind getestet, die Oberfläche ist noch nicht im Fenster abgenommen.
Getestet auf: nichts. Die Zielplattform ist Linux (Pop!_OS), dort ist noch nichts gebaut oder geprüft. Getestet auf: CachyOS (Kernel 7.3.1), Podman 6.1.4, Node.js 24.21, Rust 1.99.1. Geprüft sind Build, Unit-Tests, ein Ende-zu-Ende-Lauf gegen Ollama (`qwen3:0.6b`) und ein Lauf aller sechs Aufgaben über einen OpenAI-kompatiblen Endpunkt (`qwen3.8-flash-next-q2_0`). Andere Systeme sind nicht geprüft.
## Before you use it ## Before you use it
**Ausführung von Modellbefehlen:** Das Modell darf im Container Shell-Befehle ausführen. Die Läufe sind dafür per Docker abgeschottet (kein Netzwerk). Trotzdem sollten Aufgaben-Ordner vor dem Start geprüft werden. **Ausführung von Modellbefehlen:** Das Modell darf im Container Shell-Befehle ausführen. Die Läufe sind dafür per Podman abgeschottet (kein Netzwerk). Trotzdem sollten Aufgaben-Ordner vor dem Start geprüft werden.
**Docker nötig:** Jeder Lauf braucht Docker. Ohne Docker startet kein Lauf. **Podman nötig:** Jeder Lauf braucht Podman (rootless). Ohne Podman startet kein Lauf.
**Disclaimer:** coding-bench ist nicht verbunden mit oder gesponsert von Dritten. Das Projekt wird im Ist-Zustand und ohne Garantie bereitgestellt. **Disclaimer:** coding-bench ist nicht verbunden mit oder gesponsert von Dritten. Das Projekt wird im Ist-Zustand und ohne Garantie bereitgestellt.
@ -32,14 +32,21 @@ Noch nicht verfügbar. Installationshinweise folgen mit dem ersten Release.
## Requirements ## Requirements
* Linux (Pop!_OS als Zielplattform) * Linux (geprüft auf CachyOS)
* Docker * Podman, rootless, mit Netzwerk-Unterstützung für Images beim ersten Bauen
* Rust-Toolchain und Node.js (für den Build, Details folgen) * Rust-Toolchain (Rust 1.99.1 geprüft) und Node.js (24.21 geprüft), dazu die Tauri-Systemvoraussetzungen (WebKitGTK 4.1)
* Ollama mit Modellen, die Tool-Calling unterstützen * Ein Modell-Endpunkt mit Tool-Calling: Ollama (`/api/chat`) oder ein OpenAI-kompatibler Server (z. B. strata, `/v1/chat/completions`)
## Build and run ## Build and run
Noch nicht verfügbar. ```bash
git clone ssh://git@git.wlkns.org:2222/wlkns-dev/coding-bench.git
cd coding-bench
make images # Container-Image cb-python bauen (einmalig)
make dev # App im Entwicklungsmodus starten
```
`make help` listet alle Ziele (Tests, Release-Build, Arch-Paket). Fertige Pakete (`.deb`, Arch) baut der Gitea-Workflow bei einem Release-Tag; sie sind noch nicht als Release veröffentlicht.
## What it does ## What it does
@ -51,9 +58,9 @@ Der Nutzer wählt Aufgaben und Modelle. Jedes Modell löst jede Aufgabe mehrfach
| :--- | :--- | | :--- | :--- |
| **Aufgaben** | Ordner mit Prompt, Startdateien und `check.sh`, beim Laden validiert. | | **Aufgaben** | Ordner mit Prompt, Startdateien und `check.sh`, beim Laden validiert. |
| **Agent-Loop** | Modell und Tools (`read_file`, `write_file`, `list_dir`, `run_shell`, `done`) mit Fehlerklassen. | | **Agent-Loop** | Modell und Tools (`read_file`, `write_file`, `list_dir`, `run_shell`, `done`) mit Fehlerklassen. |
| **Sandbox** | Frischer Docker-Container pro Lauf, ohne Netzwerk. | | **Sandbox** | Frischer Podman-Container pro Lauf, ohne Netzwerk. |
| **Runner** | Wiederholungen, Abbruch und Fortsetzen eines Batches. | | **Runner** | Wiederholungen, Abbruch und Fortsetzen eines Batches. |
| **Ranking** | Gesamtscore mit Intervall, Matrix Modell × Test (geplant für 0.2.0: Kategorien, Export). | | **Ranking** | Bewertung in Prozent je Bereich und als Gesamtnote, Matrix Modell × Aufgabe (geplant für 0.2.0: Konfidenzintervall, Export). |
## How it works ## How it works
@ -61,13 +68,19 @@ Eine Tauri-Oberfläche (Svelte und TypeScript) spricht über Commands mit dem Ru
## How to use / API & Configuration ## How to use / API & Configuration
Noch nicht verfügbar. Die Oberfläche hat drei Reiter. Sie wurde bisher im Browser mit Beispieldaten angesehen, in der echten App noch nicht abgenommen.
1. **Einstellungen:** Modelle anlegen. Jedes Modell hat einen **Adapter**: `Ollama` (`/api/chat`) oder `OpenAI-kompatibel` (`/v1/chat/completions`, z. B. strata). Dazu kommen Server-URL, Modell-ID und optional der Name einer Umgebungsvariable mit dem API-Schlüssel. Der Schlüssel selbst steht nie in der Konfiguration. „Verbindung testen“ prüft das Modell mit einer kurzen Anfrage.
2. **Benchmark:** Modelle und Aufgaben wählen, Durchläufe festlegen, starten. Der Fortschritt läuft live, ein Abbruch verwirft den laufenden Lauf.
3. **Ergebnisse:** Pro Batch eine Bewertung in Prozent: ein Wert je Bereich (A Tool-Calling, B kleine Coding-Aufgaben, C Agent im Repo, D Demos) und eine Gesamtnote. Die Bewertung ist absolut und nicht im Vergleich zu einem Referenzmodell. Darunter eine Matrix je Aufgabe und die einzelnen Läufe mit allen Schritten.
Die Konfiguration liegt in `~/.config/org.wlkns.codingbench/config.toml`. Aufgaben liegen als Ordner unter `tasks/<gruppe>/<name>/` (`task.toml`, `prompt.md`, `start/`, `check.sh`). Eine installierte Version findet die mitgelieferten Aufgaben unter `/usr/share/coding-bench/tasks`.
## References & Links ## References & Links
* **[Ollama](https://ollama.com)** – lokale Modelle mit Tool-Calling über `/api/chat`. * **[Ollama](https://ollama.com)** – lokale Modelle mit Tool-Calling über `/api/chat`.
* **[Tauri](https://tauri.app)** – Desktop-Framework mit Rust-Backend. * **[Tauri](https://tauri.app)** – Desktop-Framework mit Rust-Backend.
* **[Docker](https://www.docker.com)** – Sandbox pro Lauf. * **[Podman](https://podman.io)** – Sandbox pro Lauf.
## License ## License

View File

@ -1,15 +1,15 @@
# coding-bench – Anforderungen, Todo und Roadmap # coding-bench – Anforderungen, Todo und Roadmap
Stand: 2026-11-06 (18:30) · Projekt-ID: offen · Format: 1 · installiert ist noch nichts (Release 0.1.0 offen); lokal 0 Commits. Quellen dieser Liste: `SPEC.md` (Gespräch vom 06.11.2026), Anforderungskatalog F-01 bis F-17. Stand: 2026-11-09 (10:00) · Projekt-ID: offen · Format: 1 · installiert ist noch nichts (Release 0.1.0 offen); Release-Kandidat v0.1.0-rc4 auf srv01 gebaut (deb und Arch als Artefakte, nirgends installiert). Danach GUI-Überarbeitung auf `release/0.1.0`, noch nicht als Kandidat gebaut. Quellen dieser Liste: `SPEC.md` (Gespräch vom 06.11.2026), Anforderungskatalog F-01 bis F-17.
Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft. Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
**IDs:** Jeder Punkt in Stand-Tabelle, Todo, Entscheidungen und Risiken hat eine feste ID `#1xxx` (eine Zählung für alles, nie wiederverwendet, am Anfang der Zeile). „→ #…“ nennt die Anforderung, die ein Todo voranbringt. Erledigtes wandert mit ID in „Erledigt (einzeln)“. Nächste freie ID: #1039. **IDs:** Jeder Punkt in Stand-Tabelle, Todo, Entscheidungen und Risiken hat eine feste ID `#1xxx` (eine Zählung für alles, nie wiederverwendet, am Anfang der Zeile). „→ #…“ nennt die Anforderung, die ein Todo voranbringt. Erledigtes wandert mit ID in „Erledigt (einzeln)“. Nächste freie ID: #1056.
## 1. Leitplanken (von dir festgelegt, gelten für alles) ## 1. Leitplanken (von dir festgelegt, gelten für alles)
- **Lokal first:** Nur lokale Modelle (Ollama, ab Phase 2 OpenAI-kompatibler Endpunkt im Netz). Cloud-Modelle werden nicht verglichen (Nicht-Ziel v1). - **Lokal first:** Nur lokale Modelle (Ollama, ab Phase 2 OpenAI-kompatibler Endpunkt im Netz). Cloud-Modelle werden nicht verglichen (Nicht-Ziel v1).
- **Sandbox:** Jeder Lauf in einem frischen Docker-Container mit `--network none`. Der Agent arbeitet nur unter `/work`. - **Sandbox:** Jeder Lauf in einem frischen Podman-Container mit `--network none`. Der Agent arbeitet nur unter `/work`.
- **Sequentiell:** Modelle laufen nacheinander, weil ein Modell die GPU belegt. Parallelität nur, wenn du `parallel > 1` setzt. - **Sequentiell:** Modelle laufen nacheinander, weil ein Modell die GPU belegt. Parallelität nur, wenn du `parallel > 1` setzt.
- **Versionierung:** System-Prompt und Limits werden pro Batch in `config_json` mitgespeichert, damit Läufe vergleichbar bleiben. - **Versionierung:** System-Prompt und Limits werden pro Batch in `config_json` mitgespeichert, damit Läufe vergleichbar bleiben.
- **Plattform und Stack:** Linux (Pop!_OS) zuerst. Tauri 2, Rust-Backend, Svelte mit TypeScript fürs Frontend, SQLite für Ergebnisse. - **Plattform und Stack:** Linux (CachyOS) zuerst. Tauri 2, Rust-Backend, Svelte mit TypeScript fürs Frontend, SQLite für Ergebnisse.
- **Nicht-Ziele v1:** verteiltes Ausführen auf mehreren Rechnern, Nutzerverwaltung, Veröffentlichen von Ergebnissen. - **Nicht-Ziele v1:** verteiltes Ausführen auf mehreren Rechnern, Nutzerverwaltung, Veröffentlichen von Ergebnissen.
- **Git:** Repo auf deinem Gitea. Nicht pushen ohne dein ausdrückliches Wort. - **Git:** Repo auf deinem Gitea. Nicht pushen ohne dein ausdrückliches Wort.
- **Klicktests:** Eine neue Funktion gilt erst als fertig, wenn ihre Klicktests aus `KLICKTESTS.md` mindestens einmal ✓ haben. Das Todo nennt die zugehörigen Tests. Du darfst die Regel für einen Block aufweichen, wenn du ihn bewusst erledigen willst; das steht dann im Todo. - **Klicktests:** Eine neue Funktion gilt erst als fertig, wenn ihre Klicktests aus `KLICKTESTS.md` mindestens einmal ✓ haben. Das Todo nennt die zugehörigen Tests. Du darfst die Regel für einen Block aufweichen, wenn du ihn bewusst erledigen willst; das steht dann im Todo.
@ -18,22 +18,23 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
| ID | Anforderung | Quelle | Stand | Anmerkung | | ID | Anforderung | Quelle | Stand | Anmerkung |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| #1001 | F-01 Tauri-Grundgerüst, Datenordner, Config | SPEC 12 | ✗ | noch nicht begonnen (→ #1018) | | #1001 | F-01 Tauri-Grundgerüst, Datenordner, Config | SPEC 12 | ◐ | Umgesetzt: Gerüst, TOML-Config mit Standardanlage, Datenordner, Setup zeigt Pfade. `cargo test` 6/6, `npm run build` grün. Klicktests `start2app.1–.2` manuell noch nicht ✓ (→ #1018) |
| #1002 | F-02 Aufgaben laden und validieren | SPEC 4, 12 | ✗ | noch nicht begonnen (→ #1019) | | #1002 | F-02 Aufgaben laden und validieren | SPEC 4, 12 | ◐ | Umgesetzt: Laden, Validierung (Pflichtdateien, TOML, Werte, `check.sh` ausführbar), Fehler im Setup. `cargo test` 13/13. Klicktests `aufgabe2validierung.1–.2` manuell offen (→ #1019) |
| #1003 | F-03 Agent-Loop gegen Ollama mit Tools und Fehlerklassen | SPEC 5, 12 | ✗ | noch nicht begonnen (→ #1021) | | #1003 | F-03 Agent-Loop gegen Ollama mit Tools und Fehlerklassen | SPEC 5, 12 | ◐ | Loop, Tools, Pfadprüfung, Fehlerklassen und Metriken in `agent.rs`. 31 Unit-Tests grün (Mock-Modell). Werkzeuge gegen echte Sandbox grün. Echter Lauf gegen Ollama auf srv04 mit `qwen3:0.6b` bestanden (ignorierter Test `ollama_lauf_schreibt_datei_und_beendet`: Datei geschrieben, `done` aufgerufen). Offen: größere Modelle, Klicktests `lauf2ergebnis.1–.3` (→ #1021) |
| #1004 | F-04 Docker-Sandbox pro Lauf | SPEC 6, 12 | ✗ | noch nicht begonnen (→ #1020) | | #1004 | F-04 Podman-Sandbox pro Lauf | SPEC 6, 12 | ◐ | Modul `sandbox.rs` steht: Start ohne Netz, Limits, Kopieren nach `/work`, `exec` mit Timeout, Export, Entfernen. Limits und Runtime kommen aus `config.toml`. Echter Lauf gegen Podman mit Image `cb-python:latest` bestanden (ignorierter Test). Noch nicht an den Runner angebunden (#1022); Klicktests `lauf2sandbox.1–.2` manuell offen (→ #1020) |
| #1005 | F-05 Runner mit Wiederholungen, Abbruch, Fortsetzen | SPEC 7, 12 | ✗ | noch nicht begonnen (→ #1022) | | #1005 | F-05 Runner mit Wiederholungen, Abbruch, Fortsetzen | SPEC 7, 12 | ◐ | `runner.rs`: Plan, Warm-up je Modell, Sandbox pro Lauf, `check.sh`, Abbruch, Fortsetzen über die DB. Ende-zu-Ende gegen srv04 mit `qwen3:0.6b` grün (2 Läufe, dann Fortsetzen überspringt beide). Abbruch im Lauf nicht real getestet. Über Tauri-Befehle `start_batch`, `cancel_batch` angebunden, Ereignisse `batch-event` (→ #1022) |
| #1006 | F-06 SQLite inkl. Schritt-Log | SPEC 8, 12 | ✗ | noch nicht begonnen (→ #1023) | | #1006 | F-06 SQLite inkl. Schritt-Log | SPEC 8, 12 | ◐ | `store.rs`: Tabellen `batch`, `run`, `step` nach SPEC 8, Lauf und Schritte in einer Transaktion. Datei `coding-bench.sqlite` im Datenordner, wird beim Start angelegt. Lesen über `batch_results`. Getestet in-memory und im Batch (→ #1023) |
| #1007 | F-07 Tests a-01 bis a-03 und b-04 bis b-06 | SPEC 11, 12 | ✗ | noch nicht begonnen (→ #1024) | | #1007 | F-07 Tests a-01 bis a-03 und b-04 bis b-06 | SPEC 11, 12 | ◐ | Aufgaben liegen unter `tasks/`, gültig geladen (Test `repo_aufgaben_sind_gueltig`). Musterlösungen bestehen alle Checks, leere Lösung scheitert. Mit `qwen3:0.6b` 0 von 6 bestanden. Mit `qwen3.8-flash-next-q2_0` über strata (OpenAI-Format, LAN) 6 von 6 bestanden, Score 1.00 (Testbericht `testberichte/2026-11-06-strata-lauf.md`) (→ #1024) |
| #1008 | F-08 GUI: Setup, Batch starten, Live-Fortschritt | SPEC 10, 12 | ✗ | noch nicht begonnen (→ #1025) | | #1008 | F-08 GUI: Setup, Batch starten, Live-Fortschritt | SPEC 10, 12 | ◐ | Oberfläche neu gebaut (Reiter Benchmark, Ergebnisse, Einstellungen): Modell-Liste mit Adapter, Verbindungstest, Aufgaben nach Bereich, Start, Abbrechen, Fortschritt, Batch-Verlauf, Bewertung, Schrittansicht. `svelte-check` 0 Fehler. Im Browser mit Beispieldaten angesehen (Screenshots), nicht in der echten App; Klicktests `batch2fortsetzen.1–.2` offen (→ #1025) |
| #1009 | F-09 Rangliste und Matrix | SPEC 9, 10, 12 | ✗ | noch nicht begonnen (→ #1026) | | #1009 | F-09 Rangliste und Matrix | SPEC 9, 10, 12 | ◐ | `ranking.rs`: absolute Bewertung in Prozent je Bereich (A bis D) und als Gesamtnote, gewichtet nach `weight`; Tie-Breaker Median-Dauer, dann Tokens; schwächster Bereich; Matrix Modell × Aufgabe. 7 Unit-Tests grün. Ohne Wilson-Intervall (F-12). Klicktest `ergebnis2detail.1` manuell offen (→ #1026) |
| #1010 | F-10 Tests c-07 bis c-09 | SPEC 11, 12 | ✗ | Phase 2 (→ #1027) | | #1010 | F-10 Tests c-07 bis c-09 | SPEC 11, 12 | ✗ | Phase 2 (→ #1027) |
| #1011 | F-11 Adapter Aider-Polyglot-Teilmenge | SPEC 12 | ✗ | Phase 2 (→ #1028) | | #1011 | F-11 Adapter Aider-Polyglot-Teilmenge | SPEC 12 | ✗ | Phase 2 (→ #1028) |
| #1012 | F-12 Kategorie-Ranking, Wilson-Intervalle, Markierung | SPEC 9, 12 | ✗ | Phase 2 (→ #1029) | | #1012 | F-12 Kategorie-Ranking, Wilson-Intervalle, Markierung | SPEC 9, 12 | ✗ | Phase 2 (→ #1029) |
| #1013 | F-13 OpenAI-kompatibler Endpunkt | SPEC 2, 12 | ✗ | Phase 2 (→ #1030) | | #1013 | F-13 OpenAI-kompatibler Endpunkt | SPEC 2, 12 | ◐ | Adapter `openai` gebaut (`/v1/chat/completions`, Tool-Calls, optionaler Schlüssel aus Umgebungsvariable); Lauf aller sechs Aufgaben über strata erfolgreich. Gewählt wird er je Modell in den Einstellungen. Offen: Anthropic-kompatibler Adapter, weitere Server (→ #1030) |
| #1014 | F-14 Export JSON und HTML-Report | SPEC 10, 12 | ✗ | Phase 2 (→ #1031) | | #1014 | F-14 Export JSON und HTML-Report | SPEC 10, 12 | ✗ | Phase 2 (→ #1031) |
| #1015 | F-15 Playwright-Sidecar, Screenshot | SPEC 2, 12 | ✗ | Phase 3 (→ #1032) | | #1015 | F-15 Playwright-Sidecar, Screenshot | SPEC 2, 12 | ✗ | Phase 3 (→ #1032) |
| #1016 | F-16 Demos d-10 bis d-12 | SPEC 11, 12 | ✗ | Phase 3 (→ #1032) | | #1016 | F-16 Demos d-10 bis d-12 | SPEC 11, 12 | ✗ | Phase 3 (→ #1032) |
| #1052 | F-18 Externe Referenz: Export als Ordner, Import mit Prüfung durch `check.sh` | Gespräch 09.11.2026 | ◐ | Gebaut: `external.rs` (Export mit `AUFGABE.md` ohne `check.sh`, Import mit Prüfung im Container, Ersetzen bei Wiederholung), Spalte `external` mit Migration, Referenz ohne Rang im Ranking, Reiter „Referenz“, Strich im Balken. 72 Tests grün, echter Podman-Test `echter_import` grün (richtig 1,0, falsch 0,0, kein Doppelimport). Oberfläche nur als Screenshot mit Beispieldaten gesehen. Klicktests `referenz2ranking.1–.3` offen (→ #1053) |
| #1017 | F-17 Optionale Screenshot-Bewertung durch Vision-Modell | SPEC 12 | ✗ | Phase 3 (→ #1032) | | #1017 | F-17 Optionale Screenshot-Bewertung durch Vision-Modell | SPEC 12 | ✗ | Phase 3 (→ #1032) |
## 3. Aufträge an Dritte ## 3. Aufträge an Dritte
@ -44,21 +45,28 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
## 4. Todo (nach Priorität, Stand 2026-11-06) ## 4. Todo (nach Priorität, Stand 2026-11-06)
**P1 – als Nächstes (Release 0.1.0, Phase 1 Kern)** **P1 – als Nächstes (Release 0.1.0, Phase 1 Kern)**
- [#1018] **Gerüst anlegen.** Tauri 2 mit Svelte und TypeScript, Rust-Backend, Datenordner, TOML-Config. Tests `start2app.1–.2`. → #1001 - [#1018] **Gerüst anlegen.** Tauri 2 mit Svelte und TypeScript, Rust-Backend, Datenordner, TOML-Config. Gerüst (`create-tauri-app`, svelte-ts) und Config-/Datenordner-Logik (`src-tauri/src/config.rs`) sind gebaut; `cargo test` 6/6 grün. Offen: die Klicktests `start2app.1–.2` vom Menschen manuell ausführen lassen. Erst dann gilt #1018 als fertig. Tests `start2app.1–.2`. → #1001
- [#1019] **Aufgaben laden und validieren.** Ordner `tasks/<gruppe>/<name>/`, Pflichtdateien, TOML, ausführbares `check.sh`, Fehler in der GUI. Tests `aufgabe2validierung.1–.2`. → #1002 - [#1019] **Aufgaben laden und validieren.** Umgesetzt in `src-tauri/src/tasks.rs`, `cargo test` 13/13. Offen: Klicktests `aufgabe2validierung.1–.2` manuell ausführen lassen. Tests `aufgabe2validierung.1–.2`. → #1002
- [#1020] **Docker-Sandbox pro Lauf.** Frischer Container, `--network none`, Speicher-/CPU-Limit, `/work` als Artefakt, Container entfernen. Tests `lauf2sandbox.1–.2`. → #1004 - [#1020] **Podman-Sandbox pro Lauf.** Modul gebaut (`src-tauri/src/sandbox.rs`). Echter Test `CB_TEST_IMAGE=docker.io/library/python:3.12-slim cargo test -- --ignored` grün: Startdatei in `/work`, Netz aus, Timeout erkannt, Export, Container entfernt. Limits und Runtime aus der Config. Image `cb-python` gebaut (`images/cb-python/Containerfile`, Python 3.12 und pytest). Der Test lief mit `CB_TEST_IMAGE=cb-python:latest` grün. Offen: Anbindung an den Runner (#1022), Klicktests `lauf2sandbox.1–.2` manuell. Tests `lauf2sandbox.1–.2`. → #1004
- [#1021] **Agent-Loop gegen Ollama.** Tools `read_file`, `write_file`, `list_dir`, `run_shell`, `done`; Pfade auf `/work`; Fehlerklassen und Metriken. Tests `lauf2ergebnis.1–.3`. → #1003 - [#1021] **Agent-Loop gegen Ollama.** Umgesetzt in `src-tauri/src/agent.rs`: fünf Tools, Pfade auf `/work`, Fehlerklassen, Schleifenerkennung, Metriken, Ollama-Client (`/api/chat`, ohne Streaming, Temperatur 0). Offen: echter Lauf gegen Ollama (Dienst starten, Modell laden), Klicktests `lauf2ergebnis.1–.3`. Tests `lauf2ergebnis.1–.3`. → #1003
- [#1022] **Runner.** Wiederholungen, sequentiell pro Modell, Aufwärmen, Abbruch und Fortsetzen. Tests `batch2fortsetzen.1–.2`. → #1005 - [#1022] **Runner.** Umgesetzt in `src-tauri/src/runner.rs`, über `start_batch` und `cancel_batch` an die Oberfläche angebunden. Offen: Abbruch in der App real prüfen, Modelle mit eigenem Endpunkt in der Config (Phase 1 hat einen gemeinsamen `ollama_url`). Tests `batch2fortsetzen.1–.2`. → #1005
- [#1023] **SQLite-Speicher.** Tabellen `batch`, `run`, `step` nach Abschnitt 8. Tests `lauf2ergebnis.2`. → #1006 - [#1023] **SQLite-Speicher.** Umgesetzt in `src-tauri/src/store.rs`, Schema nach SPEC 8. Datei-Datenbank im Datenordner angebunden. Offen: Klicktest `lauf2ergebnis.2` mit Schritt-Ansicht (noch keine Oberfläche dafür). Tests `lauf2ergebnis.2`. → #1006
- [#1024] **Aufgaben a-01 bis a-03, b-04 bis b-06 schreiben.** Mindestens je ein lauffähiges Beispiel, Mutation bei b-06. Tests: je Aufgabe ein Lauf mit Bericht. → #1007 - [#1024] **Aufgaben a-01 bis a-03, b-04 bis b-06 schreiben.** Geschrieben unter `tasks/`. b-06 mit Mutationstest; ein Fehler im Check (veralteter Bytecode bei Mutanten) ist behoben. Ergebnis: mit `qwen3.8-flash-next-q2_0` über strata 6 von 6 bestanden. Bericht in `testberichte/`. Offen: Zeitlimit von b-04 bei langsamen Modellen prüfen. → #1007
- [#1025] **GUI Setup und Batch.** Modelle, Docker-Status, Datenordner, Aufgabenauswahl, Start, Live-Fortschritt mit Schritt-Log. Tests `batch2fortsetzen.1`. → #1008 - [#1025] **GUI Setup und Batch.** Zweimal neu gebaut (nach deiner Kritik und nach der Agenten-Prüfung): dunkles Theme mit orangem Akzent, Logo und Icons, Start auf „Benchmark“. Benchmark-Tab mit Modell- und Aufgabenkarten (Beschreibung, Limits, „zuletzt“), Matrix „Plan und Stand“ (live), fester Startleiste mit Zeitschätzung, Hinweis bei weniger als 3 Durchläufen und Fortsetzen. Einstellungen mit Bereitschafts-Ampel, einklappbaren Modellkarten, Server-Prüfung und Modell-Liste vom Server (`discover.rs`). Geprüft nur als Screenshot im Headless-Browser mit Beispieldaten und mit Unit-Tests (67 grün), nicht in der echten App. Offen: echte App im Fenster prüfen, Klicktests `batch2fortsetzen.1`, `lauf2ergebnis.2`, `aufgaben2plan.1–.2` und `einstellungen2bereitschaft.1–.2` manuell, laufender Schritt live anzeigen, Gewichte in der Oberfläche ändern (SPEC 9). → #1008
- [#1026] **Rangliste und Matrix.** Gesamtscore mit Intervall, Matrix Modell × Test nach Erfolgsquote, Lauf-Detail. Tests `ergebnis2detail.1`. → #1009 - [#1026] **Rangliste und Matrix.** Gebaut (jetzt als Rangkarten mit Medaillen, Tok/s als Median, klickbare Matrix-Zellen): Prozent je Bereich und Gesamtnote (Entscheidung #1040), Schwächster Bereich, Matrix, Hinweis „grob“ bei weniger als 3 Aufgaben je Bereich, Erklärung „So wird bewertet“. Offen: Wilson-Intervall und „nicht unterscheidbar“ (F-12, Phase 2), Klicktest `ergebnis2detail.1` manuell. Tests `ergebnis2detail.1`. → #1009
**P1b – Release 0.1.1, Referenz**
- [#1053] **Externe Referenz-Läufe.** Aufgaben als Ordner exportieren (Startdateien plus `AUFGABE.md`, ohne `check.sh`), von Hand mit Claude Code oder ähnlichem lösen lassen, den Ordner zurückgeben; die App lässt `check.sh` im Container laufen und speichert den Lauf als „extern“. Ergebnisse erscheinen als Referenz mit Strich je Bereich. Tests `referenz2ranking.1–.3`. → #1052 Stand: gebaut und mit Podman geprüft, Klicktests offen. Offen: Dateidialog statt Pfad eintippen, Dauer und Tokens optional eintragen.
**P2 – danach (Release 0.2.0, Referenz und Tiefe)** **P2 – danach (Release 0.2.0, Referenz und Tiefe)**
- [#1027] **Tests c-07 bis c-09.** Neuer CLI-Parameter, Refactoring, Stacktrace-Fehler. → #1010 - [#1027] **Tests c-07 bis c-09.** Neuer CLI-Parameter, Refactoring, Stacktrace-Fehler. → #1010
- [#1028] **Aider-Polyglot-Adapter.** 20 bis 30 Aufgaben ins Aufgabenformat übersetzen. → #1011 - [#1028] **Aider-Polyglot-Adapter.** 20 bis 30 Aufgaben ins Aufgabenformat übersetzen. → #1011
- [#1029] **Kategorie-Ranking und Wilson-Intervalle.** Markierung „statistisch nicht unterscheidbar“. → #1012 - [#1029] **Kategorie-Ranking und Wilson-Intervalle.** Markierung „statistisch nicht unterscheidbar“. → #1012
- [#1030] **OpenAI-kompatibler Endpunkt.** Für den GPU Dispatcher, Typ im Setup wählbar. → #1013 - [#1030] **OpenAI-kompatibler Endpunkt.** Adapter und Auswahl je Modell sind gebaut (vorgezogen nach 0.1.0, siehe #1041). Offen: Anthropic-kompatibler Adapter, GPU Dispatcher prüfen. → #1013
- [#1048] **Echte Tempo-Messung.** Antworten streamen, Zeit bis zum ersten Token und reine Erzeugungsgeschwindigkeit messen. Heute ist Tok/s Tokens geteilt durch die ganze Laufzeit inklusive Tool- und Prüfzeit. → #1006
- [#1049] **Batches vergleichen.** Zwei Batches nebeneinander (gleiches Modell vor und nach Wechsel, Aufgabenmenge und Wiederholungen sichtbar). → #1009
- [#1050] **Ollama-Modelle direkt anlegen.** Aus der Modell-Liste des Servers per Klick Modelle als Einträge übernehmen, statt die ID zu wählen. → #1008
- [#1055] **Harness-Adapter (Pi, OpenCode).** Das Harness wird eine Auswahl neben dem eigenen von coding-bench: Jedes Ergebnis gehört zu einem Harness, verglichen wird nur innerhalb eines Harness. Die App startet Pi oder OpenCode headless in einem Arbeitsordner und prüft danach wie beim Import (#1053). Vorab ein kleiner Versuch: dieselben zwei Aufgaben mit einem lokalen Modell im eigenen Harness und in Pi, um den Harness-Effekt zu sehen. Offen zu klären: Netz für das Modell im Container, welche Messdaten das Harness liefert, Nutzungsbedingungen für Abo-Zugänge. Blocker: #1053 (Import) muss geprüft sein. → #1052
- [#1031] **Export.** JSON und eigenständiger HTML-Report. → #1014 - [#1031] **Export.** JSON und eigenständiger HTML-Report. → #1014
**P3 – Backlog (Release 0.3.0, Demos)** **P3 – Backlog (Release 0.3.0, Demos)**
@ -74,13 +82,25 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
- [#1034] Entschieden: Projektname `coding-bench`, Ordner bleibt `llm-arena`. → #1001 - [#1034] Entschieden: Projektname `coding-bench`, Ordner bleibt `llm-arena`. → #1001
- [#1035] Gitea-Adresse für das Remote `origin` (URL oder Repo-Name)? Ohne sie gibt es kein Remote, und die Projekt-ID bleibt `offen`. → #1001 - [#1035] Gitea-Adresse für das Remote `origin` (URL oder Repo-Name)? Ohne sie gibt es kein Remote, und die Projekt-ID bleibt `offen`. → #1001
- [#1036] Entschieden: Lizenz wird vorerst nicht festgelegt, die README sagt das ausdrücklich. → #1001 - [#1036] Entschieden: Lizenz wird vorerst nicht festgelegt, die README sagt das ausdrücklich. → #1001
- [#1040] Entschieden: Bewertet wird absolut in Prozent, ohne Referenzmodell. Wert je Bereich (A bis D) und eine Gesamtnote, beides gewichtet nach `weight` aus `task.toml`; Bereiche ohne Läufe bleiben leer. → #1009
- [#1051] Entschieden am 09.11.2026: Externe Läufe (Claude Code u. ä., von Hand ausgeführt) dienen als Referenz. Die Bewertung bleibt absolut (#1040), Referenzen stehen getrennt und als Strich bei jedem Bereichsbalken, sie zählen nicht im Rang. Import nimmt den Ergebnisordner, die App prüft mit `check.sh` im Container. Gilt ab Release 0.1.1. → #1052
- [#1041] Entschieden: Modelle werden in der Oberfläche als Liste angelegt, jedes mit Adapter (`ollama` oder `openai`), URL, Modell-ID und Name der Schlüssel-Variable. Die Liste steht in `config.toml`; Schlüssel stehen nie dort. → #1013
- [#1042] Entschieden: Die App baut das Container-Image `cb-python` selbst. Das Containerfile ist in die App eingebettet, in den Einstellungen gibt es „Image bauen“ mit Live-Ausgabe. Ein Paket muss kein Image mitliefern. → #1004
- [#1039] Entschieden: Podman (rootless) statt Docker für die Sandbox. Die SPEC ist entsprechend angepasst. Docker ist auf diesem Rechner nicht installiert. → #1004
## 6. Roadmap (Aufwand grob, ohne Kalenderdaten) ## 6. Roadmap (Aufwand grob, ohne Kalenderdaten)
**0.1.0 – Kern.** Todo: #1018, #1019, #1020, #1021, #1022, #1023, #1024, #1025, #1026. Ziel: Zwei Modelle × sechs Tests × drei Wiederholungen laufen durch, die Rangliste erscheint, ein Einzellauf ist nachvollziehbar, Abbruch und Fortsetzen funktionieren. **0.1.0 – Kern.** Todo: #1018, #1019, #1020, #1021, #1022, #1023, #1024, #1025, #1026. Ziel: Zwei Modelle × sechs Tests × drei Wiederholungen laufen durch, die Rangliste erscheint, ein Einzellauf ist nachvollziehbar, Abbruch und Fortsetzen funktionieren.
**0.2.0 – Referenz und Tiefe.** Todo: #1027, #1028, #1029, #1030, #1031. Ziel: Schwere Aufgaben (c-Gruppe, Aider-Teilmenge) laufen, Ranking mit Unsicherheit, OpenAI-Endpunkt und Export. **0.1.1 – Referenz.** Todo: #1053. Ziel: Ein Abo-Modell (z. B. Claude über Claude Code) lässt sich von Hand als Referenz in die Bewertung einbringen, die lokalen Modelle werden gegen diesen Strich gesehen.
**0.2.0 – Referenz und Tiefe.** Todo: #1027, #1028, #1029, #1030, #1031, #1048, #1049, #1050, #1055. Ziel: Schwere Aufgaben (c-Gruppe, Aider-Teilmenge) laufen, Ranking mit Unsicherheit, OpenAI-Endpunkt und Export.
**0.3.0 – Demos.** Todo: #1032. Ziel: Playwright-Demos und optionale Screenshot-Bewertung. **0.3.0 – Demos.** Todo: #1032. Ziel: Playwright-Demos und optionale Screenshot-Bewertung.
**Danach.** Ideen ohne Zusage. **Danach.** Ideen ohne Zusage.
## 7. Risiken und Schulden ## 7. Risiken und Schulden
- [#1037] Modelle ohne Tool-Support liefern `endpoint_error` und werden übersprungen (SPEC 13). → #1003 - [#1037] Modelle ohne Tool-Support liefern `endpoint_error` und werden übersprungen (SPEC 13). → #1003
- [#1038] Vergleichbarkeit mit veröffentlichten Benchmarkzahlen hängt vom Harness ab (Prompt, Tools, Limits). → #1021 - [#1038] Vergleichbarkeit mit veröffentlichten Benchmarkzahlen hängt vom Harness ab (Prompt, Tools, Limits). → #1021
- [#1054] Die Referenz misst „Modell plus fremdes Harness“ (eigener System-Prompt, eigene Tools, kein Schrittlimit, Netz erlaubt, von Hand ausgeführt), nicht das Modell im Harness von coding-bench. Der Strich ist ein Orientierungswert, kein Gleichstand der Bedingungen. Gegenmaßnahme: Kennzeichnung „extern“ in der Oberfläche, Anleitung mit „kein Web, nur dieser Ordner“, Aufgabentext unverändert. → #1038
- [#1043] Die Sandbox ist nur durch die Standardwerte von rootless Podman gehärtet (kein `--cap-drop=ALL`, kein `no-new-privileges`, Prozess als Root im Container, keine Platten- und Datei-Limits). Aus dem Review vom 07.11.2026. Nach vorn bringt es: Phase 2 oder fremde Aufgaben-Quellen. → #1004
- [#1044] `check.sh` läuft im selben Container wie der Agent. Ein Modell könnte Interpreter oder `sh` im Container verändern und so die Bewertung beeinflussen. Gegenmaßnahme: Prüfung in einem frischen Container auf dem exportierten `/work`. → #1004
- [#1045] Tauri-CSP ist abgeschaltet (`csp: null`), `api_key_env` und Modell-URL sind frei wählbar. Kein Angriffsweg belegt, die Oberfläche nutzt kein `{@html}`. Eine strenge CSP und eine Prüfung der Variablennamen sind offen. → #1013
- [#1046] Abbruch greift spät: Der Abbruch wird nur zwischen Schritten geprüft, eine laufende Modell-Anfrage läuft bis zum Zeitlimit weiter. Beim Timeout eines Befehls endet nur der `podman exec`-Client, nicht der Prozess im Container. → #1022
- [#1047] Die Messung ist dünn: je Aufgabe eine Wiederholung, zwei Modelle, kein Modell ohne Tool-Support, keine Streuung. Das Ziel „2 Modelle × 6 Aufgaben × 3 Wiederholungen“ ist nicht erreicht. Vor einem Release 0.1.0 nachholen. → #1024

16
SPEC.md
View File

@ -20,7 +20,7 @@ Der Nutzer wählt 1..n Tests und 1..m Modelle. Die App lässt jedes Modell jeden
| Frontend | Svelte oder React + TypeScript, schlicht, Tabellen und Heatmap | | Frontend | Svelte oder React + TypeScript, schlicht, Tabellen und Heatmap |
| HTTP | `reqwest` + `tokio` | | HTTP | `reqwest` + `tokio` |
| Modell-API | Ollama `/api/chat` mit `tools`; zusätzlich OpenAI-kompatibler Endpunkt (GPU Dispatcher) | | Modell-API | Ollama `/api/chat` mit `tools`; zusätzlich OpenAI-kompatibler Endpunkt (GPU Dispatcher) |
| Sandbox | Docker über `bollard` oder Docker-CLI | | Sandbox | Podman (rootless), Aufruf über die Podman-CLI |
| Speicher | SQLite (`rusqlite`), Artefakte als Dateien im Datenordner | | Speicher | SQLite (`rusqlite`), Artefakte als Dateien im Datenordner |
| Config | TOML (`serde`, `toml`) | | Config | TOML (`serde`, `toml`) |
| Playwright-Sidecar | Kleines Node-Skript, wird von der App als Prozess gestartet (nur Demo-Tests, ab Phase 3) | | Playwright-Sidecar | Kleines Node-Skript, wird von der App als Prozess gestartet (nur Demo-Tests, ab Phase 3) |
@ -36,7 +36,7 @@ Backend (Rust)
├─ config Modelle, Endpunkte, Pfade ├─ config Modelle, Endpunkte, Pfade
├─ tasks Laden/Validieren der Aufgabenordner ├─ tasks Laden/Validieren der Aufgabenordner
├─ agent Agent-Loop (Modell <-> Tools) ├─ agent Agent-Loop (Modell <-> Tools)
├─ sandbox Docker-Container pro Lauf, Tool-Ausführung ├─ sandbox Podman-Container pro Lauf, Tool-Ausführung
├─ runner Job-Queue, Wiederholungen, Abbruch ├─ runner Job-Queue, Wiederholungen, Abbruch
├─ scoring Auswertung, Ranking, Statistik ├─ scoring Auswertung, Ranking, Statistik
└─ store SQLite + Artefakte └─ store SQLite + Artefakte
@ -62,7 +62,7 @@ id = "b-05-bugfix-parser"
title = "Bug im Parser finden und fixen" title = "Bug im Parser finden und fixen"
group = "B" # A, B, C, D group = "B" # A, B, C, D
weight = 1.0 # Gewicht im Gesamtscore weight = 1.0 # Gewicht im Gesamtscore
image = "cb-python:latest" # Docker-Image image = "cb-python:latest" # Container-Image
max_steps = 25 # max. Modell-Antworten max_steps = 25 # max. Modell-Antworten
timeout_s = 600 # Gesamtzeit pro Lauf timeout_s = 600 # Gesamtzeit pro Lauf
check_timeout_s = 120 check_timeout_s = 120
@ -105,9 +105,9 @@ Pfade sind auf `/work` beschränkt.
- Ein frischer Container pro Lauf, Image aus `task.toml`. - Ein frischer Container pro Lauf, Image aus `task.toml`.
- `start/` wird nach `/work` kopiert. - `start/` wird nach `/work` kopiert.
- Netzwerk aus (`--network none`), Speicher-/CPU-Limit konfigurierbar. - Netzwerk aus (`--network none`), Speicher-/CPU-Limit konfigurierbar.
- Tool-Ausführung per `docker exec`, `check.sh` im selben Container. - Tool-Ausführung per `podman exec`, `check.sh` im selben Container.
- Nach dem Lauf wird `/work` als Artefakt nach `runs/<run_id>/work/` kopiert, dann wird der Container entfernt. - Nach dem Lauf wird `/work` als Artefakt nach `runs/<run_id>/work/` kopiert, dann wird der Container entfernt.
- Mitgelieferte Images (Dockerfiles im Repo): `cb-python` (Python 3 + pytest), `cb-node` (Node + npm), `cb-rust` (Rust-Toolchain), `cb-web` (Node + Playwright, nur Phase 3). - Mitgelieferte Images (Containerfiles im Repo): `cb-python` (Python 3 + pytest), `cb-node` (Node + npm), `cb-rust` (Rust-Toolchain), `cb-web` (Node + Playwright, nur Phase 3).
--- ---
@ -147,7 +147,7 @@ step(id, run_id, idx, role, content, tool_name, tool_args_json,
## 10. GUI ## 10. GUI
1. **Setup:** Modelle (Name, Endpunkt, Typ Ollama oder OpenAI-kompatibel), Docker-Status, Datenordner, Aufgabenordner mit Validierungsstatus. 1. **Setup:** Modelle (Name, Endpunkt, Typ Ollama oder OpenAI-kompatibel), Podman-Status, Datenordner, Aufgabenordner mit Validierungsstatus.
2. **Batch starten:** Tests und Modelle ankreuzen, Wiederholungen, Start. Live-Fortschritt mit laufendem Schritt-Log des aktuellen Laufs. 2. **Batch starten:** Tests und Modelle ankreuzen, Wiederholungen, Start. Live-Fortschritt mit laufendem Schritt-Log des aktuellen Laufs.
3. **Ergebnisse:** 3. **Ergebnisse:**
- Rangliste (Rang, Modell, Gesamtscore mit Intervall, Score je Gruppe, Median-Zeit, Tokens) - Rangliste (Rang, Modell, Gesamtscore mit Intervall, Score je Gruppe, Median-Zeit, Tokens)
@ -192,7 +192,7 @@ Jede Anforderung hat eine feste ID.
- F-01 Tauri-Projekt mit Rust-Backend und Frontend-Grundgerüst, Datenordner und Config - F-01 Tauri-Projekt mit Rust-Backend und Frontend-Grundgerüst, Datenordner und Config
- F-02 Aufgaben laden und validieren (Abschnitt 4) - F-02 Aufgaben laden und validieren (Abschnitt 4)
- F-03 Agent-Loop gegen Ollama mit allen Tools und Fehlerklassifikation (Abschnitt 5) - F-03 Agent-Loop gegen Ollama mit allen Tools und Fehlerklassifikation (Abschnitt 5)
- F-04 Docker-Sandbox pro Lauf (Abschnitt 6) - F-04 Podman-Sandbox pro Lauf (Abschnitt 6)
- F-05 Runner mit Wiederholungen, Abbruch und Fortsetzen (Abschnitt 7) - F-05 Runner mit Wiederholungen, Abbruch und Fortsetzen (Abschnitt 7)
- F-06 SQLite-Speicherung inkl. Schritt-Log (Abschnitt 8) - F-06 SQLite-Speicherung inkl. Schritt-Log (Abschnitt 8)
- F-07 Tests a-01 bis a-03 und b-04 bis b-06 - F-07 Tests a-01 bis a-03 und b-04 bis b-06
@ -219,5 +219,5 @@ Jede Anforderung hat eine feste ID.
- Ollama läuft lokal oder im Netz und unterstützt Tool-Calling für die getesteten Modelle. Modelle ohne Tool-Support werden als `endpoint_error` markiert und übersprungen. - Ollama läuft lokal oder im Netz und unterstützt Tool-Calling für die getesteten Modelle. Modelle ohne Tool-Support werden als `endpoint_error` markiert und übersprungen.
- Vergleichbarkeit mit veröffentlichten Benchmarkzahlen hängt vom Harness ab (Prompt, Tools, Limits). Der System-Prompt und die Limits sind deshalb versioniert und werden im Batch mitgespeichert (`config_json`). - Vergleichbarkeit mit veröffentlichten Benchmarkzahlen hängt vom Harness ab (Prompt, Tools, Limits). Der System-Prompt und die Limits sind deshalb versioniert und werden im Batch mitgespeichert (`config_json`).
- Betriebssystem: Linux (Pop!_OS) zuerst, andere Plattformen nicht Teil von v1. - Betriebssystem: Linux (CachyOS) zuerst, andere Plattformen nicht Teil von v1.
- Entscheidung offen: Svelte oder React fürs Frontend. Der Entwickler wählt, was er schneller liefert. - Entscheidung offen: Svelte oder React fürs Frontend. Der Entwickler wählt, was er schneller liefert.

BIN
branding/logo-1024.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

15
branding/logo.svg Normal file
View File

@ -0,0 +1,15 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#ffb470"/>
<stop offset="1" stop-color="#ee8227"/>
</linearGradient>
</defs>
<rect x="32" y="32" width="960" height="960" rx="224" fill="url(#bg)"/>
<g fill="#1a1005">
<rect x="212" y="490" width="170" height="300" rx="44"/>
<rect x="427" y="340" width="170" height="450" rx="44"/>
<rect x="642" y="580" width="170" height="210" rx="44"/>
</g>
<circle cx="512" cy="245" r="46" fill="#1a1005"/>
</svg>

After

Width:  |  Height:  |  Size: 626 B

View File

@ -0,0 +1,8 @@
# cb-python: Python 3 mit pytest für Aufgaben der Gruppen A bis C.
# Bauen: podman build -t cb-python:latest images/cb-python
FROM docker.io/library/python:3.12-slim
RUN pip install --no-cache-dir pytest \
&& mkdir -p /work
WORKDIR /work

1605
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

30
package.json Normal file
View File

@ -0,0 +1,30 @@
{
"name": "coding-bench",
"version": "0.1.0",
"description": "",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"tauri": "tauri"
},
"license": "MIT",
"dependencies": {
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-opener": "^2"
},
"devDependencies": {
"@sveltejs/adapter-static": "^3.0.10",
"@sveltejs/kit": "^2.65.1",
"@sveltejs/vite-plugin-svelte": "^7.1.2",
"svelte": "^5.56.3",
"svelte-check": "^4.6.0",
"typescript": "~6.0.3",
"vite": "^8.0.16",
"@tauri-apps/cli": "^2"
}
}

32
packaging/arch/PKGBUILD Normal file
View File

@ -0,0 +1,32 @@
# Maintainer: wlkns-dev
# Paket aus dem Quellarchiv des Git-Tags. Das Archiv erzeugt der Release-Workflow
# (git archive) bzw. man lokal mit: git archive --prefix=coding-bench-$pkgver/ -o coding-bench-$pkgver.tar.gz HEAD
pkgname=coding-bench
pkgver=0.1.0
pkgrel=1
pkgdesc="Benchmark für lokale LLMs als Coding-Agent: Aufgaben lösen lassen, Ranking erstellen"
arch=('x86_64')
url="https://git.wlkns.org/wlkns-dev/coding-bench"
license=('custom:none')
depends=('webkit2gtk-4.1' 'gtk3' 'librsvg' 'libayatana-appindicator' 'podman')
makedepends=('rust' 'nodejs' 'npm')
source=("$pkgname-$pkgver.tar.gz")
sha256sums=('SKIP')
# !lto: makepkg compiliert sonst das gebündelte SQLite mit -flto, lld findet dann die Symbole nicht.
options=('!debug' '!lto')
build() {
cd "$srcdir/$pkgname-$pkgver"
npm ci
npm run tauri build -- --no-bundle
}
package() {
cd "$srcdir/$pkgname-$pkgver"
install -Dm755 "src-tauri/target/release/coding-bench" "$pkgdir/usr/bin/coding-bench"
install -Dm644 "packaging/coding-bench.desktop" "$pkgdir/usr/share/applications/coding-bench.desktop"
install -Dm644 "src-tauri/icons/128x128.png" "$pkgdir/usr/share/icons/hicolor/128x128/apps/coding-bench.png"
install -Dm644 "src-tauri/icons/32x32.png" "$pkgdir/usr/share/icons/hicolor/32x32/apps/coding-bench.png"
install -dm755 "$pkgdir/usr/share/coding-bench"
cp -r tasks "$pkgdir/usr/share/coding-bench/tasks"
}

View File

@ -0,0 +1,9 @@
[Desktop Entry]
Type=Application
Name=coding-bench
GenericName=Benchmark für lokale LLM-Agenten
Comment=Lokale LLMs als Coding-Agent gegen Aufgaben testen und vergleichen
Exec=coding-bench
Icon=coding-bench
Terminal=false
Categories=Development;Utility;

7
src-tauri/.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas

5388
src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

38
src-tauri/Cargo.toml Normal file
View File

@ -0,0 +1,38 @@
[package]
name = "coding-bench"
version = "0.1.0"
description = "A Tauri App"
authors = ["you"]
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
# The `_lib` suffix may seem redundant but it is necessary
# to make the lib name unique and wouldn't conflict with the bin name.
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
name = "coding_bench_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
toml = "0.8"
reqwest = { version = "0.12", features = ["blocking", "json"] }
base64 = "0.22"
rusqlite = { version = "0.32", features = ["bundled"] }
uuid = { version = "1", features = ["v4"] }
# Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration
[profile.release]
codegen-units = 1
lto = true
opt-level = 3
panic = "abort"
strip = true

3
src-tauri/build.rs Normal file
View File

@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

View File

@ -0,0 +1,10 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:default",
"opener:default"
]
}

BIN
src-tauri/icons/128x128.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

BIN
src-tauri/icons/32x32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

BIN
src-tauri/icons/icon.icns Normal file

Binary file not shown.

BIN
src-tauri/icons/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
src-tauri/icons/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

1056
src-tauri/src/agent.rs Normal file

File diff suppressed because it is too large Load Diff

285
src-tauri/src/config.rs Normal file
View File

@ -0,0 +1,285 @@
//! Konfiguration (TOML) und Datenordner (F-01).
//!
//! Die Datei `config.toml` liegt im App-Konfigurationsordner. Fehlt sie, wird sie
//! mit Standardwerten angelegt. Pfade in der Datei sind optional; ohne Angabe
//! gilt der Standardordner der App bzw. `<datenordner>/tasks`.
use crate::sandbox::Limits;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
pub const CONFIG_FILE_NAME: &str = "config.toml";
/// Aufgaben, die ein Paket installiert. Gilt, wenn weder die Konfiguration noch der Datenordner Aufgaben angeben.
pub const SYSTEM_TASKS_DIR: &str = "/usr/share/coding-bench/tasks";
/// Ein angebundenes Modell: Anzeigename, Adapter und Endpunkt.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ModelEntry {
/// Anzeigename, eindeutig. Erscheint in Ranglisten.
pub name: String,
/// `ollama` oder `openai` (OpenAI-kompatibel, z. B. strata).
pub adapter: String,
/// Basis-URL des Servers, z. B. `http://host:11434` oder `http://host:8082/v1`.
pub url: String,
/// Modell-ID, die an den Server gesendet wird. Leer = Anzeigename.
pub model: String,
/// Name der Umgebungsvariable mit dem API-Schlüssel. Leer = kein Schlüssel.
pub api_key_env: String,
}
impl Default for ModelEntry {
fn default() -> Self {
ModelEntry {
name: String::new(),
adapter: "ollama".into(),
url: String::new(),
model: String::new(),
api_key_env: String::new(),
}
}
}
pub const ADAPTERS: [&str; 2] = ["ollama", "openai"];
/// Prüft eine Modell-Liste: Namen nicht leer und eindeutig, Adapter bekannt, URL gesetzt.
pub fn validate_models(models: &[ModelEntry]) -> Result<(), String> {
let mut seen = std::collections::HashSet::new();
for m in models {
if m.name.trim().is_empty() {
return Err("Ein Modell hat keinen Namen.".into());
}
if !seen.insert(m.name.trim().to_string()) {
return Err(format!("Der Name {:?} kommt doppelt vor.", m.name));
}
if !ADAPTERS.contains(&m.adapter.as_str()) {
return Err(format!(
"{}: Adapter {:?} unbekannt (erlaubt: ollama, openai).",
m.name, m.adapter
));
}
if m.url.trim().is_empty() {
return Err(format!("{}: URL fehlt.", m.name));
}
}
Ok(())
}
/// Rohe Konfiguration, so wie sie in der Datei steht.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
/// Datenordner (Ergebnisse, Artefakte, Datenbank). Leer = Standard der App.
pub data_dir: Option<PathBuf>,
/// Aufgabenordner. Leer = `<datenordner>/tasks`.
pub tasks_dir: Option<PathBuf>,
/// Container-Programm für die Sandbox (Podman-CLI).
pub container_runtime: String,
/// Angebundene Modelle. Wird in der Oberfläche gepflegt.
pub models: Vec<ModelEntry>,
/// Veraltet, wird ignoriert. Bleibt nur, damit alte Dateien weiter laden.
pub backend: String,
/// Veraltet, wird ignoriert.
pub ollama_url: String,
/// Veraltet, wird ignoriert.
pub openai_url: String,
/// Veraltet, wird ignoriert.
pub openai_api_key_env: String,
/// Speicherlimit pro Lauf, Podman-Schreibweise.
pub sandbox_memory: String,
/// CPU-Anteil pro Lauf.
pub sandbox_cpus: String,
}
impl Default for Config {
fn default() -> Self {
let limits = Limits::default();
Config {
data_dir: None,
tasks_dir: None,
container_runtime: "podman".into(),
models: Vec::new(),
backend: String::new(),
ollama_url: String::new(),
openai_url: String::new(),
openai_api_key_env: String::new(),
sandbox_memory: limits.memory,
sandbox_cpus: limits.cpus,
}
}
}
/// Aufgelöste Pfade, die die App tatsächlich verwendet.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Paths {
pub config_file: PathBuf,
pub data_dir: PathBuf,
pub tasks_dir: PathBuf,
}
impl Config {
/// Liest die Konfiguration aus einem TOML-Text.
pub fn parse(text: &str) -> Result<Config, String> {
toml::from_str(text).map_err(|e| format!("config.toml ist ungültig: {e}"))
}
/// Ressourcenlimits der Sandbox aus der Konfiguration.
pub fn sandbox_limits(&self) -> Limits {
Limits {
memory: self.sandbox_memory.clone(),
cpus: self.sandbox_cpus.clone(),
}
}
/// Löst die Pfade auf. `default_data_dir` ist der Standardordner der App.
pub fn resolve(&self, config_file: &Path, default_data_dir: &Path) -> Paths {
let data_dir = self
.data_dir
.clone()
.unwrap_or_else(|| default_data_dir.to_path_buf());
let tasks_dir = self
.tasks_dir
.clone()
.unwrap_or_else(|| data_dir.join("tasks"));
Paths {
config_file: config_file.to_path_buf(),
data_dir,
tasks_dir,
}
}
}
/// Schreibt die Konfiguration zurück. Kommentare der alten Datei gehen dabei verloren.
pub fn save(config_file: &Path, config: &Config) -> Result<(), String> {
let text = toml::to_string_pretty(config)
.map_err(|e| format!("Konfiguration nicht serialisierbar: {e}"))?;
fs::write(config_file, format!("# coding-bench Konfiguration\n{text}"))
.map_err(|e| format!("{} nicht schreibbar: {e}", config_file.display()))
}
/// Lädt die Konfiguration aus `config_dir/config.toml`, legt die Datei bei Bedarf
/// mit Standardwerten an und stellt sicher, dass der Datenordner existiert.
pub fn load_or_create(config_dir: &Path, default_data_dir: &Path) -> Result<(Paths, Config), String> {
fs::create_dir_all(config_dir)
.map_err(|e| format!("Konfigurationsordner {} nicht anlegbar: {e}", config_dir.display()))?;
let config_file = config_dir.join(CONFIG_FILE_NAME);
let config = if config_file.exists() {
let text = fs::read_to_string(&config_file)
.map_err(|e| format!("{} nicht lesbar: {e}", config_file.display()))?;
Config::parse(&text)?
} else {
let defaults = Config::default();
let text = toml::to_string_pretty(&defaults)
.map_err(|e| format!("Standard-Config nicht serialisierbar: {e}"))?;
fs::write(&config_file, format!("# coding-bench Konfiguration\n{text}"))
.map_err(|e| format!("{} nicht schreibbar: {e}", config_file.display()))?;
defaults
};
let mut paths = config.resolve(&config_file, default_data_dir);
if config.tasks_dir.is_none() && !paths.tasks_dir.is_dir() && Path::new(SYSTEM_TASKS_DIR).is_dir() {
paths.tasks_dir = PathBuf::from(SYSTEM_TASKS_DIR);
}
fs::create_dir_all(&paths.data_dir)
.map_err(|e| format!("Datenordner {} nicht anlegbar: {e}", paths.data_dir.display()))?;
Ok((paths, config))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn leere_datei_ergibt_standardwerte() {
let c = Config::parse("").unwrap();
assert_eq!(c, Config::default());
}
#[test]
fn pfade_werden_gelesen() {
let c = Config::parse("data_dir = \"/x/daten\"\ntasks_dir = \"/x/aufgaben\"\n").unwrap();
assert_eq!(c.data_dir, Some(PathBuf::from("/x/daten")));
assert_eq!(c.tasks_dir, Some(PathBuf::from("/x/aufgaben")));
}
#[test]
fn sandbox_limits_werden_gelesen() {
let c = Config::parse("sandbox_memory = \"4g\"\nsandbox_cpus = \"1\"\n").unwrap();
assert_eq!(c.sandbox_limits(), Limits { memory: "4g".into(), cpus: "1".into() });
assert_eq!(c.container_runtime, "podman");
}
#[test]
fn modelle_werden_gelesen_und_geprueft() {
let c = Config::parse(
"[[models]]\nname = \"lokal\"\nadapter = \"ollama\"\nurl = \"http://h:11434\"\nmodel = \"qwen3:0.6b\"\n\n[[models]]\nname = \"strata\"\nadapter = \"openai\"\nurl = \"http://h:8082/v1\"\n",
)
.unwrap();
assert_eq!(c.models.len(), 2);
assert_eq!(c.models[1].adapter, "openai");
assert!(validate_models(&c.models).is_ok());
}
#[test]
fn modell_pruefung_findet_fehler() {
let m = |name: &str, adapter: &str, url: &str| ModelEntry {
name: name.into(),
adapter: adapter.into(),
url: url.into(),
..ModelEntry::default()
};
assert!(validate_models(&[m("", "ollama", "http://x")]).is_err());
assert!(validate_models(&[m("a", "ollama", "http://x"), m("a", "ollama", "http://y")]).is_err());
assert!(validate_models(&[m("a", "gpt", "http://x")]).is_err());
assert!(validate_models(&[m("a", "ollama", " ")]).is_err());
}
#[test]
fn alte_config_mit_veralteten_feldern_laedt_weiter() {
let c = Config::parse("ollama_url = \"http://srv04:11434\"\nbackend = \"openai\"\n").unwrap();
assert!(c.models.is_empty());
}
#[test]
fn unbekannter_schluessel_ist_fehler() {
assert!(Config::parse("unbekannt = 1\n").is_err());
}
#[test]
fn tasks_standard_liegt_im_datenordner() {
let p = Config::default().resolve(Path::new("/c/config.toml"), Path::new("/d"));
assert_eq!(p.data_dir, PathBuf::from("/d"));
assert_eq!(p.tasks_dir, PathBuf::from("/d/tasks"));
}
#[test]
fn angegebener_datenordner_gilt_auch_fuer_tasks() {
let c = Config::parse("data_dir = \"/x\"\n").unwrap();
let p = c.resolve(Path::new("/c/config.toml"), Path::new("/d"));
assert_eq!(p.data_dir, PathBuf::from("/x"));
assert_eq!(p.tasks_dir, PathBuf::from("/x/tasks"));
}
#[test]
fn load_or_create_legt_datei_und_ordner_an() {
let base = std::env::temp_dir().join(format!("cb-config-test-{}", std::process::id()));
let _ = fs::remove_dir_all(&base);
let cfg_dir = base.join("cfg");
let data_dir = base.join("data");
let (paths, _) = load_or_create(&cfg_dir, &data_dir).unwrap();
assert!(cfg_dir.join(CONFIG_FILE_NAME).exists());
assert!(data_dir.is_dir());
assert_eq!(paths.tasks_dir, data_dir.join("tasks"));
// Zweiter Aufruf liest die vorhandene Datei, ohne sie zu verändern.
let before = fs::read_to_string(cfg_dir.join(CONFIG_FILE_NAME)).unwrap();
load_or_create(&cfg_dir, &data_dir).unwrap();
let after = fs::read_to_string(cfg_dir.join(CONFIG_FILE_NAME)).unwrap();
assert_eq!(before, after);
let _ = fs::remove_dir_all(&base);
}
}

77
src-tauri/src/discover.rs Normal file
View File

@ -0,0 +1,77 @@
//! Fragt einen Modell-Server nach den Modellen, die er anbietet. Das erspart das Abtippen der Modell-ID.
use std::time::Duration;
/// Adresse der Modell-Liste. Ollama: `/api/tags`, OpenAI-kompatibel: `<basis>/models`.
pub fn models_url(adapter: &str, url: &str) -> Result<String, String> {
let t = url.trim().trim_end_matches('/');
if !(t.starts_with("http://") || t.starts_with("https://")) {
return Err("Die Server-URL muss mit http:// oder https:// beginnen.".into());
}
match adapter {
"ollama" => Ok(format!("{t}/api/tags")),
"openai" => {
let base = t.strip_suffix("/chat/completions").unwrap_or(t);
Ok(format!("{base}/models"))
}
other => Err(format!("Unbekannter Adapter {other:?}.")),
}
}
/// Liest die Modellnamen aus der Antwort. Unbekannte Form ergibt eine leere Liste.
pub fn parse_models(adapter: &str, body: &serde_json::Value) -> Vec<String> {
let (list, field) = match adapter {
"ollama" => (body.get("models"), "name"),
_ => (body.get("data"), "id"),
};
let mut names: Vec<String> = list
.and_then(|v| v.as_array())
.map(|a| a.iter().filter_map(|m| m.get(field)?.as_str().map(String::from)).collect())
.unwrap_or_default();
names.sort();
names.dedup();
names
}
/// Fragt den Server ab. `api_key` ist der Wert, nicht der Name der Variable.
pub fn list(adapter: &str, url: &str, api_key: Option<&str>) -> Result<Vec<String>, String> {
let endpoint = models_url(adapter, url)?;
let http = reqwest::blocking::Client::builder()
.timeout(Duration::from_secs(8))
.build()
.map_err(|e| format!("HTTP-Client nicht baubar: {e}"))?;
let mut req = http.get(&endpoint);
if let Some(k) = api_key {
req = req.bearer_auth(k);
}
let resp = req.send().map_err(|e| format!("Server nicht erreichbar: {e}"))?;
if !resp.status().is_success() {
return Err(format!("Der Server antwortete mit {}.", resp.status()));
}
let body: serde_json::Value = resp.json().map_err(|e| format!("Antwort nicht lesbar: {e}"))?;
Ok(parse_models(adapter, &body))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn adressen_je_adapter() {
assert_eq!(models_url("ollama", "http://h:11434/").unwrap(), "http://h:11434/api/tags");
assert_eq!(models_url("openai", "http://h:8082/v1").unwrap(), "http://h:8082/v1/models");
assert_eq!(models_url("openai", "http://h/v1/chat/completions").unwrap(), "http://h/v1/models");
assert!(models_url("openai", "ftp://h").is_err());
assert!(models_url("x", "http://h").is_err());
}
#[test]
fn modellnamen_werden_gelesen() {
let o = json!({"models": [{"name": "qwen3:0.6b"}, {"name": "a:1"}, {"name": "a:1"}]});
assert_eq!(parse_models("ollama", &o), vec!["a:1", "qwen3:0.6b"]);
let s = json!({"data": [{"id": "m2"}, {"id": "m1"}]});
assert_eq!(parse_models("openai", &s), vec!["m1", "m2"]);
assert!(parse_models("openai", &json!({"x": 1})).is_empty());
}
}

421
src-tauri/src/external.rs Normal file
View File

@ -0,0 +1,421 @@
//! Externe Referenz-Läufe: Aufgaben als Ordner exportieren, von Hand (Claude Code o. ä.) lösen
//! lassen und den Ergebnisordner zurückgeben. Die Prüfung läuft wie bei jedem Lauf mit `check.sh`
//! im Container. Die Läufe werden als „extern“ gespeichert und zählen nicht im Rang.
//!
//! Ordnerform: `<aufgabe>/run-<n>/arbeit/` (Arbeitsordner, wird importiert) und
//! `<aufgabe>/run-<n>/AUFGABE.md` (Text zum Einfügen, bleibt außerhalb des Arbeitsordners, damit
//! er die Prüfung nicht verfälscht, etwa beim Zählen von Dateien).
use crate::runner::{final_class, run_check, RunConfig};
use crate::agent::ErrorClass;
use crate::sandbox::{container_name, Sandbox};
use crate::store::{RunRecord, Store};
use crate::tasks::{Task, START_DIR};
use serde::Serialize;
use std::fs;
use std::path::{Path, PathBuf};
pub const MANIFEST: &str = "manifest.json";
pub const WORK_SUBDIR: &str = "arbeit";
/// Größte erlaubte Ergebnismenge je Lauf. Schützt vor versehentlich kopierten Abhängigkeitsordnern.
pub const MAX_IMPORT_BYTES: u64 = 50 * 1024 * 1024;
/// Namen, die beim Kopieren in den Container ausgelassen werden. Sie gehören nicht zur Lösung.
const SKIP_NAMES: [&str; 2] = [".claude", ".git"];
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ExportResult {
pub dir: String,
pub folders: usize,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ImportSummary {
pub imported: usize,
pub passed: usize,
/// Ordner, die nicht geprüft wurden, mit Grund.
pub skipped: Vec<String>,
}
fn instructions(repeats: u32, tasks: &[Task]) -> String {
let list: String = tasks.iter().map(|t| format!("- {}: {}", t.meta.id, t.meta.title)).collect::<Vec<_>>().join("\n");
format!(
"# Referenz-Läufe für coding-bench\n\n\
Dieser Ordner enthält {n} Aufgabe(n) mit je {repeats} Durchlauf/Durchläufen:\n\n{list}\n\n\
## So geht es\n\n\
1. Öffne **für jeden Durchlauf eine frische Sitzung** deines Werkzeugs (z. B. Claude Code) im Ordner `<aufgabe>/run-<n>/arbeit/`.\n\
2. Füge den Inhalt von `<aufgabe>/run-<n>/AUFGABE.md` als Auftrag ein. Hilf nicht nach, stelle keine Zwischenfragen.\n\
3. Warte, bis das Werkzeug fertig meldet. Lass **nur** den Ordner `arbeit/` verändern.\n\
4. Wenn alles erledigt ist, gib diesen Ordner in coding-bench unter „Referenz“ zurück.\n\n\
## Regeln, damit der Vergleich fair bleibt\n\n\
- Kein Web, keine Suche, keine Dateien außerhalb von `arbeit/`.\n\
- Keine Hinweise geben, keine Fehlermeldungen aus früheren Durchläufen mitgeben.\n\
- Ein Durchlauf pro Ordner. Wiederholst du einen Durchlauf, lösche die alte Sitzung und beginne im frischen Ordner.\n\
- Es gibt hier kein Schrittlimit und kein Zeitlimit. Das ist ein Unterschied zu den lokalen Modellen und wird in der Bewertung als „extern“ gekennzeichnet.\n\
- Die Prüfdatei (`check.sh`) liegt absichtlich nicht dabei.\n",
n = tasks.len(),
)
}
fn task_file(prompt: &str) -> String {
format!(
"> Hinweis zur Umgebung: Im Text unten heißt das Arbeitsverzeichnis `/work`. Gemeint ist der Ordner, \
in dem du gerade arbeitest (das aktuelle Verzeichnis). Arbeite nur darin. Ein Werkzeug `done` gibt es hier \
nicht: Sage einfach, dass du fertig bist.\n\n{}\n",
prompt.trim_end()
)
}
/// Kopiert einen Ordner rekursiv. Symbolische Links werden übersprungen. Gibt die Bytes zurück.
fn copy_dir(src: &Path, dst: &Path, skip: &[&str]) -> Result<u64, String> {
fs::create_dir_all(dst).map_err(|e| format!("Ordner nicht anlegbar: {e}"))?;
let mut total = 0;
for entry in fs::read_dir(src).map_err(|e| format!("{} nicht lesbar: {e}", src.display()))? {
let entry = entry.map_err(|e| e.to_string())?;
let name = entry.file_name();
if skip.iter().any(|s| name == *s) {
continue;
}
let kind = entry.file_type().map_err(|e| e.to_string())?;
let to = dst.join(&name);
if kind.is_symlink() {
continue;
} else if kind.is_dir() {
total += copy_dir(&entry.path(), &to, skip)?;
} else if kind.is_file() {
total += fs::copy(entry.path(), &to).map_err(|e| format!("Kopieren fehlgeschlagen: {e}"))?;
}
}
Ok(total)
}
/// Größe einer Ordnerstruktur ohne die ausgelassenen Namen und ohne Links.
fn dir_size(dir: &Path, skip: &[&str]) -> u64 {
let Ok(rd) = fs::read_dir(dir) else { return 0 };
let mut total = 0;
for entry in rd.flatten() {
if skip.iter().any(|s| entry.file_name() == *s) {
continue;
}
let Ok(kind) = entry.file_type() else { continue };
if kind.is_dir() {
total += dir_size(&entry.path(), skip);
} else if kind.is_file() {
total += entry.metadata().map(|m| m.len()).unwrap_or(0);
}
}
total
}
/// Legt den Exportordner an. `out_dir` darf nicht existieren oder muss leer sein.
pub fn export(tasks: &[Task], repeats: u32, out_dir: &Path) -> Result<ExportResult, String> {
if tasks.is_empty() {
return Err("Keine Aufgabe gewählt.".into());
}
if repeats == 0 {
return Err("Mindestens ein Durchlauf.".into());
}
if out_dir.exists() && fs::read_dir(out_dir).map(|mut r| r.next().is_some()).unwrap_or(true) {
return Err(format!("{} existiert und ist nicht leer.", out_dir.display()));
}
fs::create_dir_all(out_dir).map_err(|e| format!("Ordner nicht anlegbar: {e}"))?;
let mut folders = 0;
for task in tasks {
let prompt = fs::read_to_string(task.dir.join("prompt.md")).map_err(|e| format!("prompt.md nicht lesbar: {e}"))?;
for n in 1..=repeats {
let run_dir = out_dir.join(&task.meta.id).join(format!("run-{n}"));
let work = run_dir.join(WORK_SUBDIR);
fs::create_dir_all(&work).map_err(|e| format!("Ordner nicht anlegbar: {e}"))?;
let start = task.dir.join(START_DIR);
if start.is_dir() {
copy_dir(&start, &work, &[])?;
}
fs::write(run_dir.join("AUFGABE.md"), task_file(&prompt)).map_err(|e| format!("AUFGABE.md nicht schreibbar: {e}"))?;
folders += 1;
}
}
let ids: Vec<&str> = tasks.iter().map(|t| t.meta.id.as_str()).collect();
fs::write(
out_dir.join(MANIFEST),
serde_json::json!({ "format": 1, "tasks": ids, "repeats": repeats }).to_string(),
)
.map_err(|e| format!("manifest.json nicht schreibbar: {e}"))?;
fs::write(out_dir.join("ANLEITUNG.md"), instructions(repeats, tasks)).map_err(|e| format!("ANLEITUNG.md nicht schreibbar: {e}"))?;
Ok(ExportResult { dir: out_dir.display().to_string(), folders })
}
/// Ein Ergebnisordner: Aufgabe, Durchlauf und Pfad des Arbeitsordners.
#[derive(Debug, Clone, PartialEq)]
pub struct Found {
pub task_id: String,
pub repeat_idx: u32,
pub work: PathBuf,
}
/// Sucht `<aufgabe>/run-<n>/arbeit/` unterhalb von `root`. Unlesbares oder Fremdes wird gemeldet.
pub fn find_runs(root: &Path) -> Result<(Vec<Found>, Vec<String>), String> {
if !root.is_dir() {
return Err(format!("{} ist kein Ordner.", root.display()));
}
let mut found = Vec::new();
let mut notes = Vec::new();
let mut tasks: Vec<PathBuf> = fs::read_dir(root)
.map_err(|e| format!("Ordner nicht lesbar: {e}"))?
.flatten()
.map(|e| e.path())
.filter(|p| p.is_dir())
.collect();
tasks.sort();
for tdir in tasks {
let task_id = tdir.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string();
let mut runs: Vec<PathBuf> = fs::read_dir(&tdir).map(|r| r.flatten().map(|e| e.path()).collect()).unwrap_or_default();
runs.sort();
for rdir in runs.into_iter().filter(|p| p.is_dir()) {
let name = rdir.file_name().and_then(|n| n.to_str()).unwrap_or("");
let Some(n) = name.strip_prefix("run-").and_then(|x| x.parse::<u32>().ok()).filter(|n| *n >= 1) else {
notes.push(format!("{task_id}/{name}: kein Durchlauf-Ordner (erwartet run-<n>)"));
continue;
};
let work = rdir.join(WORK_SUBDIR);
if !work.is_dir() {
notes.push(format!("{task_id}/{name}: Ordner {WORK_SUBDIR}/ fehlt"));
continue;
}
found.push(Found { task_id: task_id.clone(), repeat_idx: n, work });
}
}
Ok((found, notes))
}
/// Prüft die Ergebnisordner und speichert sie als externe Läufe in `batch_id`.
/// Ein bereits importierter Lauf (gleiches Modell, gleiche Aufgabe, gleicher Durchlauf) wird ersetzt.
pub fn import(
store: &mut Store,
cfg: &RunConfig,
tasks: &[Task],
root: &Path,
model: &str,
batch_id: i64,
) -> Result<ImportSummary, String> {
if !store.batch_exists(batch_id)? {
return Err(format!("Batch {batch_id} existiert nicht."));
}
let (found, mut skipped) = find_runs(root)?;
if found.is_empty() {
return Err(format!(
"Keine Ergebnisordner gefunden. Erwartet wird <aufgabe>/run-<n>/{WORK_SUBDIR}/ unter {}.{}",
root.display(),
if skipped.is_empty() { String::new() } else { format!(" Hinweise: {}", skipped.join("; ")) }
));
}
let mut imported = 0;
let mut passed = 0;
for (seq, f) in found.iter().enumerate() {
let label = format!("{}/run-{}", f.task_id, f.repeat_idx);
let Some(task) = tasks.iter().find(|t| t.meta.id == f.task_id) else {
skipped.push(format!("{label}: Aufgabe unbekannt"));
continue;
};
if dir_size(&f.work, &SKIP_NAMES) > MAX_IMPORT_BYTES {
skipped.push(format!("{label}: Ergebnis größer als {} MB", MAX_IMPORT_BYTES / 1024 / 1024));
continue;
}
let name = container_name(&format!("imp-{batch_id}-{seq}"));
crate::sandbox::remove_by_name(&cfg.runtime, &name);
// Ohne die ausgelassenen Namen in einen Zwischenordner kopieren, dann in den Container.
let staging = std::env::temp_dir().join(format!("coding-bench-import-{}-{seq}", std::process::id()));
let _ = fs::remove_dir_all(&staging);
if let Err(e) = copy_dir(&f.work, &staging, &SKIP_NAMES) {
skipped.push(format!("{label}: {e}"));
let _ = fs::remove_dir_all(&staging);
continue;
}
let started = Sandbox::start(&cfg.runtime, &name, &task.meta.image, &cfg.limits, Some(&staging));
let _ = fs::remove_dir_all(&staging);
let sb = match started {
Ok(sb) => sb,
Err(e) => {
skipped.push(format!("{label}: Container nicht startbar ({e})"));
continue;
}
};
let (check, text) = run_check(&sb, task);
if let Err(e) = sb.remove() {
eprintln!("Container {name} nicht entfernt: {e}");
}
let class = final_class(ErrorClass::Ok, &check);
let record = RunRecord {
batch_id,
model: model.to_string(),
task_id: task.meta.id.clone(),
repeat_idx: f.repeat_idx,
error_class: class,
score: check.score,
steps: 0,
prompt_tokens: 0,
completion_tokens: 0,
duration_ms: 0,
tps: None,
ttft_tool_ms: None,
artifact_path: Some(f.work.display().to_string()),
summary: Some("Extern gelöst (von Hand), keine Schritte aufgezeichnet.".into()),
check_output: text,
external: true,
};
store.delete_run(batch_id, model, &record.task_id, record.repeat_idx)?;
store.insert_run(&record, &[])?;
imported += 1;
if check.passed {
passed += 1;
}
}
Ok(ImportSummary { imported, passed, skipped })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tasks::TaskToml;
fn scratch(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("cb-ext-{tag}-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
d
}
fn task_in(dir: &Path, id: &str) -> Task {
fs::create_dir_all(dir.join("start/sub")).unwrap();
fs::write(dir.join("start/info.txt"), "Projektcode: 42").unwrap();
fs::write(dir.join("start/sub/x.txt"), "x").unwrap();
fs::write(dir.join("prompt.md"), "Lies /work/info.txt.\n").unwrap();
fs::write(dir.join("check.sh"), "#!/bin/sh\nexit 0\n").unwrap();
Task {
meta: TaskToml {
id: id.into(),
title: "Titel".into(),
group: "A".into(),
weight: 1.0,
image: "cb-python:latest".into(),
max_steps: 5,
timeout_s: 60,
check_timeout_s: 30,
},
dir: dir.to_path_buf(),
prompt: String::new(),
}
}
#[test]
fn export_legt_ordner_an_ohne_pruefdatei() {
let base = scratch("export");
let task = task_in(&base.join("task"), "a-01");
let out = base.join("out");
let r = export(&[task], 2, &out).unwrap();
assert_eq!(r.folders, 2);
for n in 1..=2 {
let run = out.join(format!("a-01/run-{n}"));
assert!(run.join("arbeit/info.txt").is_file());
assert!(run.join("arbeit/sub/x.txt").is_file());
let md = fs::read_to_string(run.join("AUFGABE.md")).unwrap();
assert!(md.contains("Lies /work/info.txt."), "Aufgabentext bleibt unverändert");
assert!(md.contains("aktuelle Verzeichnis"));
// Weder die Prüfdatei noch die Aufgabendatei liegen im Arbeitsordner.
assert!(!run.join("arbeit/check.sh").exists());
assert!(!run.join("arbeit/AUFGABE.md").exists());
}
assert!(out.join("ANLEITUNG.md").is_file());
assert!(out.join(MANIFEST).is_file());
assert!(!out.join("a-01/check.sh").exists());
let _ = fs::remove_dir_all(&base);
}
#[test]
fn export_verweigert_belegten_ordner() {
let base = scratch("belegt");
let task = task_in(&base.join("task"), "a-01");
let out = base.join("out");
fs::create_dir_all(&out).unwrap();
fs::write(out.join("alt.txt"), "x").unwrap();
assert!(export(&[task], 1, &out).is_err());
let _ = fs::remove_dir_all(&base);
}
#[test]
fn ergebnisordner_werden_gefunden_und_fremdes_gemeldet() {
let base = scratch("find");
fs::create_dir_all(base.join("a-01/run-1/arbeit")).unwrap();
fs::create_dir_all(base.join("a-01/run-2/arbeit")).unwrap();
fs::create_dir_all(base.join("a-01/run-3")).unwrap(); // ohne arbeit/
fs::create_dir_all(base.join("a-01/notizen")).unwrap();
let (found, notes) = find_runs(&base).unwrap();
assert_eq!(found.len(), 2);
assert_eq!(found[0].task_id, "a-01");
assert_eq!(found[1].repeat_idx, 2);
assert_eq!(notes.len(), 2);
assert!(find_runs(&base.join("gibt-es-nicht")).is_err());
let _ = fs::remove_dir_all(&base);
}
#[test]
fn kopieren_laesst_claude_ordner_und_links_aus() {
let base = scratch("copy");
let src = base.join("src");
fs::create_dir_all(src.join(".claude")).unwrap();
fs::write(src.join(".claude/settings.json"), "{}").unwrap();
fs::write(src.join("lösung.py"), "print(1)").unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink("/etc/passwd", src.join("link")).unwrap();
let dst = base.join("dst");
let bytes = copy_dir(&src, &dst, &SKIP_NAMES).unwrap();
assert_eq!(bytes, 8);
assert!(dst.join("lösung.py").is_file());
assert!(!dst.join(".claude").exists());
assert!(!dst.join("link").exists());
assert_eq!(dir_size(&src, &SKIP_NAMES), 8);
let _ = fs::remove_dir_all(&base);
}
/// Echter Import gegen Podman: `CB_TEST_IMAGE=cb-python:latest cargo test external::tests::echter_import -- --ignored`
#[test]
#[ignore]
fn echter_import() {
use crate::sandbox::Limits;
let image = std::env::var("CB_TEST_IMAGE").unwrap_or_else(|_| "cb-python:latest".into());
let base = scratch("echt");
let mut task = task_in(&base.join("task"), "a-01");
task.meta.image = image;
// Prüfung: ergebnis.txt muss "42" enthalten.
fs::write(base.join("task/check.sh"), "#!/bin/sh\ngrep -qx 42 ergebnis.txt\n").unwrap();
let out = base.join("out");
export(&[task.clone()], 2, &out).unwrap();
fs::write(out.join("a-01/run-1/arbeit/ergebnis.txt"), "42\n").unwrap(); // richtig
fs::write(out.join("a-01/run-2/arbeit/ergebnis.txt"), "43\n").unwrap(); // falsch
fs::create_dir_all(out.join("a-01/run-1/arbeit/.claude")).unwrap();
let mut store = Store::open_in_memory().unwrap();
let batch = store.create_batch("t", 2, "{}").unwrap();
let cfg = RunConfig {
runtime: "podman".into(),
models: Vec::new(),
data_dir: base.join("data"),
limits: Limits::default(),
};
let r = import(&mut store, &cfg, &[task.clone()], &out, "Claude (extern)", batch).unwrap();
assert_eq!(r.imported, 2, "{:?}", r.skipped);
assert_eq!(r.passed, 1);
let runs = store.runs_for_batch(batch).unwrap();
assert!(runs.iter().all(|x| x.external));
assert_eq!(runs.iter().find(|x| x.repeat_idx == 1).unwrap().score, 1.0);
assert_eq!(runs.iter().find(|x| x.repeat_idx == 2).unwrap().score, 0.0);
// Zweiter Import ersetzt die Läufe, es entstehen keine Doppelten.
import(&mut store, &cfg, &[task], &out, "Claude (extern)", batch).unwrap();
assert_eq!(store.runs_for_batch(batch).unwrap().len(), 2);
let _ = fs::remove_dir_all(&base);
}
}

168
src-tauri/src/images.rs Normal file
View File

@ -0,0 +1,168 @@
//! Container-Images, die die App selbst bauen kann.
//!
//! Die Containerfiles sind in die App eingebettet. So braucht ein installiertes Paket keine
//! zusätzlichen Dateien, und die App baut das Image beim ersten Start auf Knopfdruck.
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::thread;
struct Embedded {
/// Name ohne Registry und ohne Tag.
name: &'static str,
containerfile: &'static str,
}
const EMBEDDED: &[Embedded] = &[Embedded {
name: "cb-python",
containerfile: include_str!("../../images/cb-python/Containerfile"),
}];
/// Repository-Name eines Images: ohne Registry-Pfad, ohne Tag und ohne Digest.
fn repo_name(image: &str) -> &str {
let last = image.rsplit('/').next().unwrap_or(image);
last.split(['@', ':']).next().unwrap_or(last)
}
/// Eingebettetes Containerfile für ein Image, falls es eines gibt.
pub fn embedded_containerfile(image: &str) -> Option<&'static str> {
let name = repo_name(image);
EMBEDDED.iter().find(|e| e.name == name).map(|e| e.containerfile)
}
/// Prüft, ob ein Image lokal vorhanden ist. `podman image exists` liefert 0 (ja) oder 1 (nein).
pub fn exists(runtime: &str, image: &str) -> Result<bool, String> {
let out = Command::new(runtime)
.args(["image", "exists", "--", image])
.output()
.map_err(|e| format!("{runtime} nicht startbar: {e}"))?;
match out.status.code() {
Some(0) => Ok(true),
Some(1) => Ok(false),
_ => Err(format!(
"{runtime} image exists schlug fehl: {}",
String::from_utf8_lossy(&out.stderr).trim()
)),
}
}
/// Baut ein eingebettetes Image. Jede Ausgabezeile geht an `on_line`.
pub fn build(runtime: &str, image: &str, on_line: &mut dyn FnMut(&str)) -> Result<(), String> {
let containerfile = embedded_containerfile(image).ok_or_else(|| {
format!("Für {image} gibt es kein eingebautes Containerfile. Das Image muss selbst bereitgestellt werden.")
})?;
crate::tasks::validate_image(image)?;
// Eigener Ordner als Build-Kontext, danach wieder gelöscht.
let dir: PathBuf = std::env::temp_dir().join(format!(
"coding-bench-image-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
));
std::fs::create_dir_all(&dir).map_err(|e| format!("Build-Ordner nicht anlegbar: {e}"))?;
let result = (|| {
std::fs::write(dir.join("Containerfile"), containerfile)
.map_err(|e| format!("Containerfile nicht schreibbar: {e}"))?;
let mut child = Command::new(runtime)
.arg("build")
.arg("-t")
.arg(image)
.arg(&dir)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("{runtime} build nicht startbar: {e}"))?;
// Beide Ströme in eigenen Threads lesen und über einen Kanal zusammenführen.
let (tx, rx) = mpsc::channel::<String>();
let mut handles = Vec::new();
if let Some(out) = child.stdout.take() {
let tx = tx.clone();
handles.push(thread::spawn(move || {
for line in BufReader::new(out).lines().map_while(Result::ok) {
let _ = tx.send(line);
}
}));
}
if let Some(err) = child.stderr.take() {
let tx = tx.clone();
handles.push(thread::spawn(move || {
for line in BufReader::new(err).lines().map_while(Result::ok) {
let _ = tx.send(line);
}
}));
}
drop(tx);
for line in rx {
on_line(&line);
}
for h in handles {
let _ = h.join();
}
let status = child.wait().map_err(|e| format!("Warten auf den Build schlug fehl: {e}"))?;
if status.success() {
Ok(())
} else {
Err(format!("Der Build von {image} ist fehlgeschlagen (Exit {}).", status.code().map_or("?".into(), |c| c.to_string())))
}
})();
let _ = std::fs::remove_dir_all(&dir);
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn repo_name_ohne_registry_tag_und_digest() {
assert_eq!(repo_name("cb-python:latest"), "cb-python");
assert_eq!(repo_name("localhost/cb-python:1.2"), "cb-python");
assert_eq!(repo_name("docker.io/library/python:3.12-slim"), "python");
assert_eq!(repo_name("cb-python@sha256:abc"), "cb-python");
assert_eq!(repo_name("cb-python"), "cb-python");
}
#[test]
fn eingebettetes_containerfile_wird_gefunden() {
let cf = embedded_containerfile("cb-python:latest").expect("cb-python eingebettet");
assert!(cf.contains("FROM "));
assert!(embedded_containerfile("localhost/cb-python:latest").is_some());
assert!(embedded_containerfile("python:3.12").is_none());
}
#[test]
fn build_fremdes_image_wird_abgelehnt() {
let mut lines = Vec::new();
let err = build("podman", "python:3.12", &mut |l| lines.push(l.to_string())).unwrap_err();
assert!(err.contains("kein eingebautes Containerfile"));
assert!(lines.is_empty());
}
#[test]
fn name_mit_optionszeichen_ist_kein_eingebettetes_image() {
assert!(embedded_containerfile("--cb-python").is_none());
assert!(build("podman", "--cb-python", &mut |_| {}).is_err());
}
/// Echter Build gegen Podman (braucht Netz für das Basis-Image). Ignoriert:
/// `cargo test images::tests::echter_build -- --ignored`
#[test]
#[ignore]
fn echter_build() {
let tag = format!("cb-python:test-{}", std::process::id());
let mut lines = Vec::new();
build("podman", &tag, &mut |l| lines.push(l.to_string())).expect("Build");
assert!(!lines.is_empty());
assert!(exists("podman", &tag).unwrap());
let _ = Command::new("podman").args(["rmi", "-f", &tag]).output();
assert!(!exists("podman", &tag).unwrap());
}
}

531
src-tauri/src/lib.rs Normal file
View File

@ -0,0 +1,531 @@
mod agent;
mod config;
mod discover;
mod external;
mod images;
mod ranking;
mod runner;
mod sandbox;
mod store;
mod tasks;
use config::{Config, ModelEntry, Paths};
use runner::{BatchSummary, Event, ModelConn, RunConfig};
use serde::Serialize;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use store::{BatchInfo, RunRecord, Store};
use tauri::{Emitter, Manager, State};
pub const DB_FILE: &str = "coding-bench.sqlite";
pub const EVENT_NAME: &str = "batch-event";
pub const IMAGE_EVENT: &str = "image-build";
/// Aufgelöste Pfade, einmal beim Start ermittelt.
pub struct AppPaths(pub Paths);
/// Die laufende Konfiguration. Die Oberfläche ändert die Modell-Liste, die Datei wird mitgeschrieben.
pub struct ConfigState {
pub config: Mutex<Config>,
pub file: PathBuf,
}
/// Steuerung für den laufenden Batch. Es läuft immer nur einer.
pub struct RunState {
/// Gesetzt, wenn der laufende Batch abbrechen soll.
pub cancel: Arc<AtomicBool>,
/// Gesetzt, solange ein Batch läuft.
pub running: Arc<AtomicBool>,
/// Gesetzt, solange ein Image gebaut wird.
pub building: Arc<AtomicBool>,
}
/// Setzt ein Flag beim Verlassen des Gültigkeitsbereichs zurück, auch nach einem Fehler oder Panic.
/// Ohne diesen Wächter bliebe `running` nach einem abgestürzten Batch-Thread dauerhaft gesetzt.
struct FlagGuard(Arc<AtomicBool>);
impl Drop for FlagGuard {
fn drop(&mut self) {
self.0.store(false, Ordering::SeqCst);
}
}
/// Ein Modell für die Oberfläche, mit Hinweis, ob die Schlüssel-Variable gesetzt ist.
#[derive(Serialize)]
pub struct ModelInfo {
#[serde(flatten)]
pub entry: ModelEntry,
pub api_key_set: bool,
}
fn model_info(entry: &ModelEntry) -> ModelInfo {
let api_key_set = !entry.api_key_env.is_empty()
&& std::env::var(&entry.api_key_env).map_or(false, |v| !v.is_empty());
ModelInfo { entry: entry.clone(), api_key_set }
}
/// Löst einen Eintrag in eine Verbindung auf: Modell-ID und Schlüssel aus der Umgebung.
fn conn_of(entry: &ModelEntry) -> ModelConn {
let api_key = if entry.api_key_env.is_empty() {
None
} else {
std::env::var(&entry.api_key_env).ok().filter(|k| !k.is_empty())
};
ModelConn {
name: entry.name.clone(),
adapter: entry.adapter.clone(),
url: entry.url.clone(),
model_id: if entry.model.trim().is_empty() { entry.name.clone() } else { entry.model.clone() },
api_key,
}
}
#[tauri::command]
fn get_paths(paths: State<'_, AppPaths>) -> Paths {
paths.0.clone()
}
#[tauri::command]
fn load_tasks(paths: State<'_, AppPaths>) -> tasks::LoadReport {
tasks::load_all(&paths.0.tasks_dir)
}
/// Angebundene Modelle.
#[tauri::command]
fn list_models(cfg: State<'_, ConfigState>) -> Result<Vec<ModelInfo>, String> {
let c = cfg.config.lock().map_err(|e| e.to_string())?;
Ok(c.models.iter().map(model_info).collect())
}
/// Ersetzt die Modell-Liste, prüft sie und schreibt `config.toml`.
#[tauri::command]
fn save_models(cfg: State<'_, ConfigState>, models: Vec<ModelEntry>) -> Result<Vec<ModelInfo>, String> {
let cleaned: Vec<ModelEntry> = models
.into_iter()
.map(|mut m| {
m.name = m.name.trim().to_string();
m.url = m.url.trim().to_string();
m.model = m.model.trim().to_string();
m.api_key_env = m.api_key_env.trim().to_string();
m
})
.collect();
config::validate_models(&cleaned)?;
let mut c = cfg.config.lock().map_err(|e| e.to_string())?;
let mut next = c.clone();
next.models = cleaned;
config::save(&cfg.file, &next)?;
*c = next;
Ok(c.models.iter().map(model_info).collect())
}
#[derive(Serialize)]
pub struct ModelTest {
pub ok: bool,
pub duration_ms: u128,
pub message: String,
}
/// Prüft die Verbindung zu einem Modell mit einer kurzen Anfrage.
#[tauri::command]
async fn test_model(cfg: State<'_, ConfigState>, name: String) -> Result<ModelTest, String> {
let entry = {
let c = cfg.config.lock().map_err(|e| e.to_string())?;
c.models
.iter()
.find(|m| m.name == name)
.cloned()
.ok_or_else(|| format!("Modell {name:?} ist nicht angebunden."))?
};
let conn = conn_of(&entry);
tauri::async_runtime::spawn_blocking(move || {
let started = Instant::now();
let result = runner::client_for(&conn).and_then(|client| {
client
.chat(
&[agent::Message::new("user", "Antworte nur mit: ok")],
&serde_json::json!([]),
Duration::from_secs(90),
)
.map_err(|e| match e {
agent::ModelError::Timeout => "Zeitlimit überschritten (90 s)".to_string(),
agent::ModelError::Endpoint(m) => m,
})
});
let duration_ms = started.elapsed().as_millis();
match result {
Ok(r) => ModelTest {
ok: true,
duration_ms,
message: format!(
"Antwort erhalten ({} Prompt-, {} Completion-Tokens).",
r.prompt_tokens, r.completion_tokens
),
},
Err(message) => ModelTest { ok: false, duration_ms, message },
}
})
.await
.map_err(|e| format!("Test abgebrochen: {e}"))
}
/// Fragt einen Server nach seinen Modellen. Der Schlüssel kommt aus der Umgebungsvariable `api_key_env`.
#[tauri::command]
async fn discover_models(adapter: String, url: String, api_key_env: String) -> Result<Vec<String>, String> {
tauri::async_runtime::spawn_blocking(move || {
let key = if api_key_env.trim().is_empty() { None } else { std::env::var(api_key_env.trim()).ok() };
discover::list(&adapter, &url, key.as_deref())
})
.await
.map_err(|e| format!("Abfrage abgebrochen: {e}"))?
}
/// Startet einen Batch mit den angegebenen Modellen (Anzeigenamen) und Aufgaben-IDs.
/// Mit `batch_id` wird ein bestehender Batch fortgesetzt: fertige Läufe werden übersprungen.
/// Fortschritt kommt als Ereignis `batch-event`. Das Ergebnis ist die Zusammenfassung.
#[tauri::command]
async fn start_batch(
app: tauri::AppHandle,
paths: State<'_, AppPaths>,
cfg: State<'_, ConfigState>,
run: State<'_, RunState>,
models: Vec<String>,
task_ids: Vec<String>,
repeats: u32,
note: String,
batch_id: Option<i64>,
) -> Result<BatchSummary, String> {
if models.is_empty() || task_ids.is_empty() {
return Err("Mindestens ein Modell und eine Aufgabe wählen.".into());
}
if repeats == 0 {
return Err("Wiederholungen müssen mindestens 1 sein.".into());
}
let (conns, runtime, limits) = {
let c = cfg.config.lock().map_err(|e| e.to_string())?;
let mut conns = Vec::new();
for name in &models {
let entry = c
.models
.iter()
.find(|m| &m.name == name)
.ok_or_else(|| format!("Modell {name:?} ist nicht angebunden."))?;
conns.push(conn_of(entry));
}
(conns, c.container_runtime.clone(), c.sandbox_limits())
};
let report = tasks::load_all(&paths.0.tasks_dir);
let selected: Vec<tasks::Task> = report
.tasks
.into_iter()
.filter(|t| task_ids.contains(&t.meta.id))
.collect();
if selected.len() != task_ids.len() {
return Err("Mindestens eine gewählte Aufgabe ist nicht gültig geladen.".into());
}
// Fehlt ein Image, scheitert sonst jeder Lauf einzeln. Besser sofort und mit klarer Anleitung.
let mut missing: Vec<String> = Vec::new();
for image in selected.iter().map(|t| t.meta.image.clone()).collect::<std::collections::BTreeSet<_>>() {
if !images::exists(&runtime, &image)? {
missing.push(image);
}
}
if !missing.is_empty() {
return Err(format!(
"Container-Image fehlt: {}. Baue es in den Einstellungen unter „Container-Images“.",
missing.join(", ")
));
}
if run.running.swap(true, Ordering::SeqCst) {
return Err("Ein Batch läuft bereits.".into());
}
let _running_guard = FlagGuard(run.running.clone());
run.cancel.store(false, Ordering::SeqCst);
let jobs = runner::plan(&models, &selected, repeats);
let run_cfg = RunConfig {
runtime,
models: conns,
data_dir: paths.0.data_dir.clone(),
limits,
};
let db_path = paths.0.data_dir.join(DB_FILE);
let cancel = run.cancel.clone();
let emitter = app.clone();
let result = tauri::async_runtime::spawn_blocking(move || {
let mut store = Store::open(&db_path)?;
let on_event = |e: &Event| {
let _ = emitter.emit(EVENT_NAME, e);
};
runner::run_batch(&mut store, &run_cfg, batch_id, &note, repeats, &jobs, &cancel, &on_event)
})
.await
.map_err(|e| format!("Batch-Thread abgebrochen: {e}"))?;
result
}
/// Legt einen Exportordner für Referenz-Läufe an (von Hand zu lösen, z. B. mit Claude Code).
#[tauri::command]
fn export_external(paths: State<'_, AppPaths>, task_ids: Vec<String>, repeats: u32) -> Result<external::ExportResult, String> {
let selected: Vec<tasks::Task> =
tasks::load_all(&paths.0.tasks_dir).tasks.into_iter().filter(|t| task_ids.contains(&t.meta.id)).collect();
if selected.len() != task_ids.len() {
return Err("Mindestens eine gewählte Aufgabe ist nicht gültig geladen.".into());
}
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let out = paths.0.data_dir.join("exports").join(format!("referenz-{stamp}"));
external::export(&selected, repeats, &out)
}
/// Prüft Ergebnisordner von Hand gelöster Aufgaben und speichert sie als externe Läufe.
#[tauri::command]
async fn import_external(
paths: State<'_, AppPaths>,
cfg: State<'_, ConfigState>,
run: State<'_, RunState>,
dir: String,
model: String,
batch_id: i64,
) -> Result<external::ImportSummary, String> {
let model = model.trim().to_string();
if model.is_empty() || model.chars().count() > 80 {
return Err("Der Modellname muss 1 bis 80 Zeichen lang sein.".into());
}
let (runtime, limits) = {
let c = cfg.config.lock().map_err(|e| e.to_string())?;
if c.models.iter().any(|m| m.name == model) {
return Err(format!(
"{model:?} ist ein angebundenes Modell. Wähle für die Referenz einen eigenen Namen, z. B. „{model} (extern)“."
));
}
(c.container_runtime.clone(), c.sandbox_limits())
};
let loaded = tasks::load_all(&paths.0.tasks_dir).tasks;
if run.running.swap(true, Ordering::SeqCst) {
return Err("Ein Batch oder Import läuft bereits.".into());
}
let _running_guard = FlagGuard(run.running.clone());
let run_cfg = RunConfig { runtime, models: Vec::new(), data_dir: paths.0.data_dir.clone(), limits };
let db_path = paths.0.data_dir.join(DB_FILE);
tauri::async_runtime::spawn_blocking(move || {
let mut store = Store::open(&db_path)?;
external::import(&mut store, &run_cfg, &loaded, std::path::Path::new(&dir), &model, batch_id)
})
.await
.map_err(|e| format!("Import abgebrochen: {e}"))?
}
/// Zustand eines Container-Images für die Einstellungen.
#[derive(Serialize)]
pub struct ImageStatus {
pub image: String,
pub available: bool,
/// Die App kann es selbst bauen.
pub buildable: bool,
/// Fehlertext, falls die Prüfung selbst scheiterte (z. B. Podman fehlt).
pub error: Option<String>,
}
/// Images, die die Aufgaben brauchen, und ihr Zustand.
#[tauri::command]
fn image_status(paths: State<'_, AppPaths>, cfg: State<'_, ConfigState>) -> Result<Vec<ImageStatus>, String> {
let runtime = cfg.config.lock().map_err(|e| e.to_string())?.container_runtime.clone();
let mut names: std::collections::BTreeSet<String> = tasks::load_all(&paths.0.tasks_dir)
.tasks
.into_iter()
.map(|t| t.meta.image)
.collect();
// Das eingebaute Standard-Image zeigen wir auch ohne Aufgaben.
names.insert("cb-python:latest".to_string());
Ok(names
.into_iter()
.map(|image| {
let buildable = images::embedded_containerfile(&image).is_some();
match images::exists(&runtime, &image) {
Ok(available) => ImageStatus { image, available, buildable, error: None },
Err(e) => ImageStatus { image, available: false, buildable, error: Some(e) },
}
})
.collect())
}
/// Baut ein eingebettetes Image. Die Ausgabe kommt zeilenweise als Ereignis `image-build`.
#[tauri::command]
async fn build_image(
app: tauri::AppHandle,
cfg: State<'_, ConfigState>,
run: State<'_, RunState>,
image: String,
) -> Result<(), String> {
tasks::validate_image(&image)?;
if images::embedded_containerfile(&image).is_none() {
return Err(format!("Für {image} gibt es kein eingebautes Containerfile."));
}
let runtime = cfg.config.lock().map_err(|e| e.to_string())?.container_runtime.clone();
if run.building.swap(true, Ordering::SeqCst) {
return Err("Es wird bereits ein Image gebaut.".into());
}
let _guard = FlagGuard(run.building.clone());
let emitter = app.clone();
tauri::async_runtime::spawn_blocking(move || {
let name = image.clone();
images::build(&runtime, &image, &mut |line| {
let _ = emitter.emit(IMAGE_EVENT, serde_json::json!({ "image": name, "line": line }));
})
})
.await
.map_err(|e| format!("Build-Thread abgebrochen: {e}"))?
}
/// Bricht den laufenden Batch ab. Der aktuelle Lauf wird verworfen.
/// Gibt `false` zurück, wenn gerade kein Batch läuft.
#[tauri::command]
fn cancel_batch(run: State<'_, RunState>) -> bool {
let running = run.running.load(Ordering::SeqCst);
if running {
run.cancel.store(true, Ordering::SeqCst);
}
running
}
/// Alle bisherigen Batches, neueste zuerst.
#[tauri::command]
fn list_batches(paths: State<'_, AppPaths>) -> Result<Vec<BatchInfo>, String> {
Store::open(&paths.0.data_dir.join(DB_FILE))?.list_batches()
}
/// Alle gespeicherten Läufe eines Batches.
#[tauri::command]
fn batch_results(paths: State<'_, AppPaths>, batch_id: i64) -> Result<Vec<RunRecord>, String> {
let store = Store::open(&paths.0.data_dir.join(DB_FILE))?;
store.runs_for_batch(batch_id)
}
/// Schritte eines einzelnen Laufs für die Detailansicht.
#[tauri::command]
fn run_steps(
paths: State<'_, AppPaths>,
batch_id: i64,
model: String,
task_id: String,
repeat_idx: u32,
) -> Result<Vec<store::StepRow>, String> {
let store = Store::open(&paths.0.data_dir.join(DB_FILE))?;
store.steps_for_run(batch_id, &model, &task_id, repeat_idx)
}
/// Zustand der Container-Laufzeit (Podman) für das Setup.
#[derive(Serialize)]
pub struct RuntimeStatus {
pub program: String,
pub available: bool,
pub detail: String,
}
#[tauri::command]
fn runtime_status(cfg: State<'_, ConfigState>) -> Result<RuntimeStatus, String> {
let program = cfg.config.lock().map_err(|e| e.to_string())?.container_runtime.clone();
Ok(
match std::process::Command::new(&program)
.args(["version", "--format", "{{.Client.Version}}"])
.output()
{
Ok(out) if out.status.success() => RuntimeStatus {
program,
available: true,
detail: format!("Version {}", String::from_utf8_lossy(&out.stdout).trim()),
},
Ok(out) => RuntimeStatus {
program,
available: false,
detail: String::from_utf8_lossy(&out.stderr).trim().to_string(),
},
Err(e) => RuntimeStatus {
program,
available: false,
detail: format!("nicht startbar: {e}"),
},
},
)
}
/// Bewertung je Modell und Bereich für einen Batch. Gruppe und Gewicht kommen aus den Aufgaben.
#[tauri::command]
fn batch_ranking(paths: State<'_, AppPaths>, batch_id: i64) -> Result<ranking::Ranking, String> {
let store = Store::open(&paths.0.data_dir.join(DB_FILE))?;
let runs = store.runs_for_batch(batch_id)?;
let infos: BTreeMap<String, ranking::TaskInfo> = tasks::load_all(&paths.0.tasks_dir)
.tasks
.into_iter()
.map(|t| {
(
t.meta.id.clone(),
ranking::TaskInfo { group: t.meta.group.clone(), weight: t.meta.weight },
)
})
.collect();
Ok(ranking::compute(batch_id, &runs, &infos))
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.setup(|app| {
let config_dir = app
.path()
.app_config_dir()
.map_err(|e| format!("Konfigurationsordner nicht ermittelbar: {e}"))?;
let default_data_dir = app
.path()
.app_data_dir()
.map_err(|e| format!("Datenordner nicht ermittelbar: {e}"))?;
let (paths, cfg) = config::load_or_create(&config_dir, &default_data_dir)?;
// Datenbank einmal anlegen, damit Fehler früh sichtbar werden.
Store::open(&paths.data_dir.join(DB_FILE))?;
let file = paths.config_file.clone();
app.manage(AppPaths(paths));
app.manage(ConfigState { config: Mutex::new(cfg), file });
app.manage(RunState {
cancel: Arc::new(AtomicBool::new(false)),
running: Arc::new(AtomicBool::new(false)),
building: Arc::new(AtomicBool::new(false)),
});
Ok(())
})
.invoke_handler(tauri::generate_handler![
get_paths,
load_tasks,
list_models,
save_models,
test_model,
discover_models,
export_external,
import_external,
start_batch,
cancel_batch,
list_batches,
batch_results,
batch_ranking,
run_steps,
runtime_status,
image_status,
build_image
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

6
src-tauri/src/main.rs Normal file
View File

@ -0,0 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
coding_bench_lib::run()
}

424
src-tauri/src/ranking.rs Normal file
View File

@ -0,0 +1,424 @@
//! Bewertung je Modell und Bereich (F-09, SPEC Abschnitt 9).
//!
//! Basis ist eine absolute Bewertung, kein Vergleich gegen ein Referenzmodell:
//! - Wert je Bereich (Gruppe A bis D): gewichteter Mittelwert der Aufgaben im Bereich in Prozent.
//! Je Aufgabe zählt der mittlere Score über die Wiederholungen.
//! - Gesamtnote: gewichteter Mittelwert über alle Aufgaben des Batches in Prozent.
//! - Gewichte kommen aus `weight` in `task.toml`.
//! - Bereiche ohne Läufe eines Modells bleiben leer und zählen nicht mit.
//! - Reihenfolge: Gesamtnote absteigend, dann Median der Dauer, dann mittlere Completion-Tokens.
//! - Läufe, die an Server oder Umgebung scheiterten (`endpoint_error`, `sandbox_error`), sagen
//! nichts über das Modell. Sie zählen nicht mit und werden getrennt gezählt (`excluded_runs`).
use crate::agent::ErrorClass;
use crate::store::RunRecord;
use serde::Serialize;
use std::collections::BTreeMap;
/// Gruppe und Gewicht einer Aufgabe.
#[derive(Debug, Clone, PartialEq)]
pub struct TaskInfo {
pub group: String,
pub weight: f64,
}
/// Wert eines Modells in einem Bereich.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct GroupScore {
pub group: String,
/// Prozent von 0 bis 100. `None`, wenn das Modell im Bereich keine Läufe hat.
pub percent: Option<f64>,
/// Anzahl Aufgaben, die in den Wert eingehen.
pub tasks: usize,
pub runs: usize,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ModelRank {
/// Platz unter den angebundenen Modellen. 0 bei Referenzen (`external`), sie zählen nicht im Rang.
pub rank: usize,
/// Referenz: von Hand außerhalb der App gelöst (z. B. Claude Code).
pub external: bool,
pub model: String,
/// Gesamtnote in Prozent von 0 bis 100.
pub total_percent: f64,
pub groups: Vec<GroupScore>,
/// Bereich mit dem niedrigsten Wert, nur wenn das Modell mindestens zwei Bereiche hat.
pub weakest_group: Option<String>,
pub runs: usize,
pub successes: usize,
pub median_duration_ms: u128,
pub mean_completion_tokens: f64,
/// Median der Tokens pro Sekunde über die Läufe (Tokens geteilt durch die gesamte Laufzeit,
/// also inklusive Tool- und Prüfzeit, nicht die reine Erzeugungsgeschwindigkeit).
pub median_tps: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct MatrixCell {
pub model: String,
pub task_id: String,
pub runs: usize,
pub successes: usize,
/// Mittlerer Score über die Wiederholungen, 0.0 bis 1.0.
pub mean_score: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TaskColumn {
pub id: String,
pub group: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Ranking {
pub batch_id: i64,
/// Bereiche, die im Batch vorkommen, sortiert.
pub groups: Vec<String>,
pub models: Vec<ModelRank>,
pub cells: Vec<MatrixCell>,
/// Aufgaben des Batches, sortiert nach Bereich und ID.
pub tasks: Vec<TaskColumn>,
/// Läufe, die wegen Server- oder Umgebungsfehlern nicht in die Bewertung eingehen.
pub excluded_runs: usize,
}
const UNKNOWN_GROUP: &str = "?";
/// Berechnet Bewertung und Matrix. Unbekannte Aufgaben zählen mit Gewicht 1.0 im Bereich `?`.
pub fn compute(batch_id: i64, all_runs: &[RunRecord], tasks: &BTreeMap<String, TaskInfo>) -> Ranking {
let valid: Vec<RunRecord> = all_runs
.iter()
.filter(|r| !r.error_class.is_infrastructure())
.cloned()
.collect();
let excluded_runs = all_runs.len() - valid.len();
let runs = valid.as_slice();
let info_of = |task: &str| -> TaskInfo {
tasks.get(task).cloned().unwrap_or(TaskInfo {
group: UNKNOWN_GROUP.into(),
weight: 1.0,
})
};
// Aufgaben des Batches mit Bereich.
let mut task_cols: BTreeMap<String, String> = BTreeMap::new();
for r in runs {
task_cols
.entry(r.task_id.clone())
.or_insert_with(|| info_of(&r.task_id).group);
}
let mut task_list: Vec<TaskColumn> = task_cols
.iter()
.map(|(id, group)| TaskColumn { id: id.clone(), group: group.clone() })
.collect();
task_list.sort_by(|a, b| a.group.cmp(&b.group).then(a.id.cmp(&b.id)));
let mut groups: Vec<String> = task_list.iter().map(|t| t.group.clone()).collect();
groups.dedup();
let mut by_model: BTreeMap<&str, Vec<&RunRecord>> = BTreeMap::new();
for r in runs {
by_model.entry(r.model.as_str()).or_default().push(r);
}
let mut models: Vec<ModelRank> = by_model
.iter()
.map(|(model, rs)| {
// Mittel je Aufgabe über die Wiederholungen.
let mut per_task: BTreeMap<&str, (f64, usize)> = BTreeMap::new();
for r in rs {
let e = per_task.entry(r.task_id.as_str()).or_insert((0.0, 0));
e.0 += r.score;
e.1 += 1;
}
// Je Bereich: gewichtete Summe, Gewicht, Aufgaben, Läufe.
let mut per_group: BTreeMap<String, (f64, f64, usize, usize)> = BTreeMap::new();
let (mut total_sum, mut total_w) = (0.0, 0.0);
for (task, (sum, n)) in &per_task {
let info = info_of(task);
let mean = sum / *n as f64;
let g = per_group.entry(info.group.clone()).or_insert((0.0, 0.0, 0, 0));
g.0 += info.weight * mean;
g.1 += info.weight;
g.2 += 1;
g.3 += *n;
total_sum += info.weight * mean;
total_w += info.weight;
}
let total_percent = if total_w > 0.0 { 100.0 * total_sum / total_w } else { 0.0 };
let group_scores: Vec<GroupScore> = groups
.iter()
.map(|g| match per_group.get(g) {
Some((sum, w, tasks_n, runs_n)) if *w > 0.0 => GroupScore {
group: g.clone(),
percent: Some(100.0 * sum / w),
tasks: *tasks_n,
runs: *runs_n,
},
_ => GroupScore { group: g.clone(), percent: None, tasks: 0, runs: 0 },
})
.collect();
let weakest_group = {
let filled: Vec<&GroupScore> =
group_scores.iter().filter(|g| g.percent.is_some()).collect();
if filled.len() >= 2 {
filled
.iter()
.min_by(|a, b| {
a.percent
.partial_cmp(&b.percent)
.unwrap_or(std::cmp::Ordering::Equal)
})
.map(|g| g.group.clone())
} else {
None
}
};
let mut durations: Vec<u128> = rs.iter().map(|r| r.duration_ms).collect();
durations.sort_unstable();
let mean_tokens =
rs.iter().map(|r| r.completion_tokens as f64).sum::<f64>() / rs.len() as f64;
let mut tps: Vec<f64> = rs.iter().filter_map(|r| r.tps).filter(|t| t.is_finite()).collect();
tps.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let median_tps = if tps.is_empty() {
None
} else if tps.len() % 2 == 1 {
Some(tps[tps.len() / 2])
} else {
Some((tps[tps.len() / 2 - 1] + tps[tps.len() / 2]) / 2.0)
};
ModelRank {
rank: 0,
external: rs.iter().any(|r| r.external),
model: model.to_string(),
total_percent,
groups: group_scores,
weakest_group,
runs: rs.len(),
successes: rs.iter().filter(|r| r.error_class == ErrorClass::Ok).count(),
median_duration_ms: median_u128(&durations),
mean_completion_tokens: mean_tokens,
median_tps,
}
})
.collect();
models.sort_by(|a, b| {
b.total_percent
.partial_cmp(&a.total_percent)
.unwrap_or(std::cmp::Ordering::Equal)
.then(a.median_duration_ms.cmp(&b.median_duration_ms))
.then(
a.mean_completion_tokens
.partial_cmp(&b.mean_completion_tokens)
.unwrap_or(std::cmp::Ordering::Equal),
)
});
// Referenzen stehen in der Liste, bekommen aber keinen Platz.
let mut next = 1;
for m in models.iter_mut() {
if m.external {
m.rank = 0;
} else {
m.rank = next;
next += 1;
}
}
let mut cell_map: BTreeMap<(&str, &str), Vec<&RunRecord>> = BTreeMap::new();
for r in runs {
cell_map
.entry((r.model.as_str(), r.task_id.as_str()))
.or_default()
.push(r);
}
let cells = cell_map
.iter()
.map(|((model, task), rs)| MatrixCell {
model: model.to_string(),
task_id: task.to_string(),
runs: rs.len(),
successes: rs.iter().filter(|r| r.error_class == ErrorClass::Ok).count(),
mean_score: rs.iter().map(|r| r.score).sum::<f64>() / rs.len() as f64,
})
.collect();
Ranking { batch_id, groups, models, cells, tasks: task_list, excluded_runs }
}
fn median_u128(sorted: &[u128]) -> u128 {
match sorted.len() {
0 => 0,
n if n % 2 == 1 => sorted[n / 2],
n => (sorted[n / 2 - 1] + sorted[n / 2]) / 2,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn run(model: &str, task: &str, score: f64, class: ErrorClass, dur: u128, tokens: u32) -> RunRecord {
RunRecord {
batch_id: 1,
model: model.into(),
task_id: task.into(),
repeat_idx: 1,
error_class: class,
score,
steps: 3,
prompt_tokens: 0,
completion_tokens: tokens,
duration_ms: dur,
tps: None,
ttft_tool_ms: None,
artifact_path: None,
summary: None,
check_output: String::new(),
external: false,
}
}
fn infos(list: &[(&str, &str, f64)]) -> BTreeMap<String, TaskInfo> {
list.iter()
.map(|(id, g, w)| (id.to_string(), TaskInfo { group: g.to_string(), weight: *w }))
.collect()
}
#[test]
fn referenz_bekommt_keinen_platz() {
let mut ext = run("Claude (extern)", "a", 1.0, ErrorClass::Ok, 0, 0);
ext.external = true;
let runs = vec![
run("klein", "a", 0.5, ErrorClass::CheckFailed, 10, 5),
run("groß", "a", 0.8, ErrorClass::CheckFailed, 10, 5),
ext,
];
let r = compute(1, &runs, &infos(&[("a", "A", 1.0)]));
let by = |n: &str| r.models.iter().find(|m| m.model == n).unwrap();
assert!(by("Claude (extern)").external);
assert_eq!(by("Claude (extern)").rank, 0);
assert_eq!(by("groß").rank, 1);
assert_eq!(by("klein").rank, 2);
}
#[test]
fn prozent_je_bereich_und_gesamt() {
// A: a1 (Gewicht 1), B: b1 (Gewicht 3).
let tasks = infos(&[("a1", "A", 1.0), ("b1", "B", 3.0)]);
let runs = vec![
run("m", "a1", 1.0, ErrorClass::Ok, 1000, 10),
run("m", "b1", 0.0, ErrorClass::CheckFailed, 1000, 10),
];
let r = compute(1, &runs, &tasks);
let m = &r.models[0];
assert_eq!(r.groups, vec!["A".to_string(), "B".to_string()]);
assert_eq!(m.groups[0].percent, Some(100.0));
assert_eq!(m.groups[1].percent, Some(0.0));
// Gesamt: (1*1 + 3*0) / 4 = 25 %
assert!((m.total_percent - 25.0).abs() < 1e-9);
assert_eq!(m.weakest_group.as_deref(), Some("B"));
}
#[test]
fn wiederholungen_werden_je_aufgabe_gemittelt() {
let tasks = infos(&[("a1", "A", 1.0), ("a2", "A", 1.0)]);
let runs = vec![
run("m", "a1", 1.0, ErrorClass::Ok, 1, 1),
run("m", "a1", 0.0, ErrorClass::CheckFailed, 1, 1),
run("m", "a2", 1.0, ErrorClass::Ok, 1, 1),
];
let r = compute(1, &runs, &tasks);
// a1: 50 %, a2: 100 % -> Bereich A 75 %. Jede Aufgabe zählt gleich viel, egal wie oft sie lief.
assert!((r.models[0].groups[0].percent.unwrap() - 75.0).abs() < 1e-9);
assert_eq!(r.models[0].groups[0].tasks, 2);
assert_eq!(r.models[0].groups[0].runs, 3);
}
#[test]
fn fehlender_bereich_bleibt_leer_und_zaehlt_nicht() {
let tasks = infos(&[("a1", "A", 1.0), ("b1", "B", 1.0)]);
let runs = vec![
run("x", "a1", 1.0, ErrorClass::Ok, 1, 1),
run("y", "a1", 1.0, ErrorClass::Ok, 1, 1),
run("y", "b1", 1.0, ErrorClass::Ok, 1, 1),
];
let r = compute(1, &runs, &tasks);
let x = r.models.iter().find(|m| m.model == "x").unwrap();
assert_eq!(x.groups[1].percent, None);
assert_eq!(x.weakest_group, None);
assert!((x.total_percent - 100.0).abs() < 1e-9);
}
#[test]
fn rang_nach_gesamt_dann_dauer() {
let tasks = infos(&[("a1", "A", 1.0)]);
let runs = vec![
run("slow", "a1", 1.0, ErrorClass::Ok, 9000, 10),
run("fast", "a1", 1.0, ErrorClass::Ok, 2000, 10),
run("schlecht", "a1", 0.0, ErrorClass::CheckFailed, 100, 10),
];
let r = compute(1, &runs, &tasks);
let order: Vec<&str> = r.models.iter().map(|m| m.model.as_str()).collect();
assert_eq!(order, vec!["fast", "slow", "schlecht"]);
assert_eq!(r.models[2].rank, 3);
}
#[test]
fn matrix_und_aufgabenliste_nach_bereich_sortiert() {
let tasks = infos(&[("b1", "B", 1.0), ("a1", "A", 1.0)]);
let runs = vec![
run("m", "b1", 1.0, ErrorClass::Ok, 1, 1),
run("m", "a1", 0.5, ErrorClass::CheckFailed, 1, 1),
];
let r = compute(1, &runs, &tasks);
let ids: Vec<&str> = r.tasks.iter().map(|t| t.id.as_str()).collect();
assert_eq!(ids, vec!["a1", "b1"]);
assert_eq!(r.cells.len(), 2);
let a1 = r.cells.iter().find(|c| c.task_id == "a1").unwrap();
assert!((a1.mean_score - 0.5).abs() < 1e-9);
assert_eq!(a1.successes, 0);
}
#[test]
fn unbekannte_aufgabe_landet_im_bereich_fragezeichen() {
let r = compute(1, &[run("m", "alt", 1.0, ErrorClass::Ok, 1, 1)], &BTreeMap::new());
assert_eq!(r.groups, vec!["?".to_string()]);
}
#[test]
fn ausfaelle_der_umgebung_zaehlen_nicht_gegen_das_modell() {
let tasks = infos(&[("a1", "A", 1.0), ("a2", "A", 1.0)]);
let runs = vec![
run("m", "a1", 1.0, ErrorClass::Ok, 1, 1),
run("m", "a2", 0.0, ErrorClass::SandboxError, 0, 0),
run("n", "a1", 0.0, ErrorClass::EndpointError, 0, 0),
];
let r = compute(1, &runs, &tasks);
assert_eq!(r.excluded_runs, 2);
// m: nur a1 zählt, 100 %. Modell n hat keine gültigen Läufe und fehlt.
assert_eq!(r.models.len(), 1);
assert!((r.models[0].total_percent - 100.0).abs() < 1e-9);
assert_eq!(r.tasks.len(), 1);
}
#[test]
fn leerer_batch() {
let r = compute(7, &[], &BTreeMap::new());
assert!(r.models.is_empty() && r.cells.is_empty() && r.tasks.is_empty() && r.groups.is_empty());
assert_eq!(r.batch_id, 7);
}
#[test]
fn median_gerade_und_ungerade() {
assert_eq!(median_u128(&[1, 2, 3]), 2);
assert_eq!(median_u128(&[1, 2, 3, 4]), 2);
assert_eq!(median_u128(&[]), 0);
}
}

643
src-tauri/src/runner.rs Normal file
View File

@ -0,0 +1,643 @@
//! Runner: Batch aus Modellen, Aufgaben und Wiederholungen (F-05, SPEC Abschnitt 7).
//!
//! Die Modelle laufen nacheinander, weil ein Modell die GPU belegt. Jeder Lauf
//! bekommt eine frische Sandbox, der Agent läuft, danach läuft `check.sh` im
//! selben Container. Fertige Läufe stehen in der Datenbank und werden beim
//! Fortsetzen übersprungen. Ein abgebrochener Lauf wird verworfen und nicht gespeichert.
use crate::agent::{
run_agent_cancellable, AgentLimits, ErrorClass, Message, ModelClient, ModelError,
OllamaClient, OpenAiClient, SandboxWorkspace,
};
use crate::sandbox::{container_name, remove_by_name, Limits, Sandbox};
use crate::store::{RunRecord, Store};
use crate::tasks::{Task, CHECK_FILE, START_DIR};
use serde::Serialize;
use serde_json::{json, Value};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
pub const CHECK_DIR: &str = "/checks";
pub const WARMUP_TIMEOUT: Duration = Duration::from_secs(300);
/// Ein einzelner Lauf im Plan.
#[derive(Debug, Clone, PartialEq)]
pub struct Job {
pub model: String,
pub task: Task,
pub repeat_idx: u32,
}
/// Verbindung zu einem Modell, aufgelöst aus der Konfiguration.
#[derive(Debug, Clone, PartialEq)]
pub struct ModelConn {
/// Anzeigename, wie er in Läufen und Ranglisten steht.
pub name: String,
/// `ollama` oder `openai`.
pub adapter: String,
pub url: String,
/// Modell-ID, die der Server erwartet.
pub model_id: String,
/// Schlüssel, wird nicht gespeichert.
pub api_key: Option<String>,
}
/// Einstellungen für einen Batch.
#[derive(Debug, Clone)]
pub struct RunConfig {
pub runtime: String,
pub models: Vec<ModelConn>,
pub data_dir: PathBuf,
pub limits: Limits,
}
/// Ereignisse für die Oberfläche.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Event {
RunStarted { model: String, task: String, repeat: u32 },
RunFinished { model: String, task: String, repeat: u32, class: ErrorClass, score: f64 },
RunSkipped { model: String, task: String, repeat: u32 },
ModelUnavailable { model: String, reason: String },
Progress { done: usize, total: usize },
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BatchSummary {
pub batch_id: i64,
pub completed: usize,
pub skipped: usize,
pub cancelled: bool,
}
/// Plan in fester Reihenfolge: Modell, dann Aufgabe, dann Wiederholung.
pub fn plan(models: &[String], tasks: &[Task], repeats: u32) -> Vec<Job> {
let mut jobs = Vec::new();
for model in models {
for task in tasks {
for repeat_idx in 1..=repeats {
jobs.push(Job {
model: model.clone(),
task: task.clone(),
repeat_idx,
});
}
}
}
jobs
}
/// Ergebnis der Prüfung durch `check.sh`.
#[derive(Debug, Clone, PartialEq)]
pub struct CheckResult {
pub score: f64,
pub passed: bool,
}
/// Wertet `check.sh` aus. Letzte Zeile als JSON `{"score": …}` gewinnt, sonst zählt der Exit-Code.
pub fn evaluate_check(exit: Option<i32>, stdout: &str) -> CheckResult {
let last = stdout.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("");
if let Ok(Value::Object(obj)) = serde_json::from_str::<Value>(last.trim()) {
if let Some(score) = obj.get("score").and_then(Value::as_f64) {
let score = score.clamp(0.0, 1.0);
return CheckResult { score, passed: score >= 1.0 };
}
}
let passed = exit == Some(0);
CheckResult { score: if passed { 1.0 } else { 0.0 }, passed }
}
/// Fehlerklasse eines fertigen Laufs: zuerst die Agentenklasse, dann die Prüfung.
pub fn final_class(agent: ErrorClass, check: &CheckResult) -> ErrorClass {
if agent != ErrorClass::Ok {
agent
} else if !check.passed {
ErrorClass::CheckFailed
} else {
ErrorClass::Ok
}
}
/// Startet einen Batch oder setzt einen bestehenden fort.
/// `batch_id = None` legt einen neuen Batch an. Fertige Läufe werden übersprungen.
pub fn run_batch(
store: &mut Store,
cfg: &RunConfig,
batch_id: Option<i64>,
note: &str,
repeats: u32,
jobs: &[Job],
cancel: &AtomicBool,
on_event: &dyn Fn(&Event),
) -> Result<BatchSummary, String> {
let config_json = json!({
"runtime": cfg.runtime,
"models": cfg.models.iter().map(|m| json!({
"name": m.name, "adapter": m.adapter, "url": m.url, "model_id": m.model_id
})).collect::<Vec<_>>(),
"limits": { "memory": cfg.limits.memory, "cpus": cfg.limits.cpus },
"system_prompt": crate::agent::SYSTEM_PROMPT,
"tool_output_chars": crate::agent::MAX_TOOL_OUTPUT_CHARS,
"loop_repeats": crate::agent::LOOP_REPEATS,
})
.to_string();
let batch_id = match batch_id {
Some(id) => {
if !store.batch_exists(id)? {
return Err(format!("Batch {id} existiert nicht"));
}
id
}
None => store.create_batch(note, repeats, &config_json)?,
};
let finished = store.finished_keys(batch_id)?;
let total = jobs.len();
let mut summary = BatchSummary { batch_id, completed: 0, skipped: 0, cancelled: false };
let mut done = 0usize;
// Modelle in der Reihenfolge des Plans, jedes Modell nur einmal aufwärmen.
let mut models: Vec<String> = Vec::new();
for j in jobs {
if !models.contains(&j.model) {
models.push(j.model.clone());
}
}
'models: for model in &models {
if cancel.load(Ordering::SeqCst) {
summary.cancelled = true;
break 'models;
}
let client = make_client(cfg, model)?;
let warm = client.chat(
&[Message::new("user", "ping")],
&json!([]),
WARMUP_TIMEOUT,
);
let unavailable = match warm {
Ok(_) => None,
Err(ModelError::Timeout) => Some("Aufwärmen hat das Zeitlimit überschritten".to_string()),
Err(ModelError::Endpoint(e)) => Some(e),
};
if let Some(reason) = &unavailable {
on_event(&Event::ModelUnavailable { model: model.clone(), reason: reason.clone() });
}
for (i, job) in jobs.iter().enumerate().filter(|(_, j)| &j.model == model) {
if cancel.load(Ordering::SeqCst) {
summary.cancelled = true;
break 'models;
}
let key = (job.model.clone(), job.task.meta.id.clone(), job.repeat_idx);
if finished.contains(&key) {
summary.skipped += 1;
done += 1;
on_event(&Event::RunSkipped {
model: job.model.clone(),
task: job.task.meta.id.clone(),
repeat: job.repeat_idx,
});
on_event(&Event::Progress { done, total });
continue;
}
on_event(&Event::RunStarted {
model: job.model.clone(),
task: job.task.meta.id.clone(),
repeat: job.repeat_idx,
});
let fin = match &unavailable {
// Modell nicht nutzbar: Lauf wird als endpoint_error gespeichert, ohne Container.
Some(reason) => Finished {
record: infra_record(batch_id, job, ErrorClass::EndpointError, reason),
transcript: vec![],
},
None => match execute_job(cfg, batch_id, i, job, &*client, cancel) {
Ok(JobResult::Cancelled) => {
summary.cancelled = true;
break 'models;
}
Ok(JobResult::Finished(f)) => f,
// Ein Fehler der Umgebung beendet nicht den Batch: Der Lauf wird als
// sandbox_error gespeichert und beim Fortsetzen wiederholt.
Err(message) => Finished {
record: infra_record(batch_id, job, ErrorClass::SandboxError, &message),
transcript: vec![],
},
},
};
on_event(&Event::RunFinished {
model: job.model.clone(),
task: job.task.meta.id.clone(),
repeat: job.repeat_idx,
class: fin.record.error_class,
score: fin.record.score,
});
store.insert_run(&fin.record, &fin.transcript)?;
summary.completed += 1;
done += 1;
on_event(&Event::Progress { done, total });
}
}
if summary.cancelled {
on_event(&Event::Progress { done, total });
}
Ok(summary)
}
/// Lauf ohne Ergebnis, weil Umgebung oder Server ausfielen. Zählt nicht gegen das Modell.
fn infra_record(batch_id: i64, job: &Job, class: ErrorClass, message: &str) -> RunRecord {
RunRecord {
batch_id,
model: job.model.clone(),
task_id: job.task.meta.id.clone(),
repeat_idx: job.repeat_idx,
error_class: class,
score: 0.0,
steps: 0,
prompt_tokens: 0,
completion_tokens: 0,
duration_ms: 0,
tps: None,
ttft_tool_ms: None,
artifact_path: None,
summary: None,
check_output: message.to_string(),
external: false,
}
}
struct Finished {
record: RunRecord,
transcript: Vec<Message>,
}
enum JobResult {
Finished(Finished),
Cancelled,
}
/// Baut den Modell-Client für den Adapter des Modells.
pub fn make_client(cfg: &RunConfig, name: &str) -> Result<Box<dyn ModelClient>, String> {
let conn = cfg
.models
.iter()
.find(|m| m.name == name)
.ok_or_else(|| format!("Modell {name:?} ist nicht angebunden."))?;
client_for(conn)
}
/// Baut den Client für eine Verbindung, je nach Adapter.
pub fn client_for(conn: &ModelConn) -> Result<Box<dyn ModelClient>, String> {
match conn.adapter.as_str() {
"ollama" => Ok(Box::new(OllamaClient::new(&conn.url, &conn.model_id)?)),
"openai" => Ok(Box::new(OpenAiClient::new(&conn.url, &conn.model_id, conn.api_key.clone())?)),
other => Err(format!("Unbekannter Adapter: {other} (erlaubt: ollama, openai)")),
}
}
/// Führt `check.sh` im Container aus, außerhalb von /work, und wertet das Ergebnis aus.
pub fn run_check(sb: &Sandbox, task: &Task) -> (CheckResult, String) {
let meta = &task.meta;
let check_output = sb
.exec(&format!("mkdir -p {CHECK_DIR}"), Duration::from_secs(30))
.and_then(|_| sb.copy_in(&task.dir.join(CHECK_FILE), &format!("{CHECK_DIR}/check.sh")))
.and_then(|_| {
sb.exec(
&format!("cd /work && sh {CHECK_DIR}/check.sh"),
Duration::from_secs(meta.check_timeout_s),
)
});
match check_output {
Ok(out) => {
let text = format!(
"exit {}{}\n{}{}",
out.exit_code.map_or("?".into(), |c| c.to_string()),
if out.timed_out { " (Zeitlimit)" } else { "" },
out.stdout,
out.stderr
);
let check = if out.timed_out {
CheckResult { score: 0.0, passed: false }
} else {
evaluate_check(out.exit_code, &out.stdout)
};
(check, text)
}
Err(e) => (CheckResult { score: 0.0, passed: false }, format!("Prüfung nicht ausführbar: {e}")),
}
}
fn execute_job(
cfg: &RunConfig,
batch_id: i64,
seq: usize,
job: &Job,
client: &dyn ModelClient,
cancel: &AtomicBool,
) -> Result<JobResult, String> {
let meta = &job.task.meta;
let name = container_name(&format!("{batch_id}-{seq}"));
remove_by_name(&cfg.runtime, &name);
let start_dir = job.task.dir.join(START_DIR);
let start_arg = if start_dir.is_dir() { Some(start_dir.as_path()) } else { None };
let sb = Sandbox::start(&cfg.runtime, &name, &meta.image, &cfg.limits, start_arg)?;
let ws = SandboxWorkspace { sandbox: &sb };
let limits = AgentLimits {
max_steps: meta.max_steps,
timeout: Duration::from_secs(meta.timeout_s),
};
let prompt = std::fs::read_to_string(job.task.dir.join("prompt.md"))
.map_err(|e| format!("prompt.md nicht lesbar: {e}"))?;
let outcome = run_agent_cancellable(client, &ws, &prompt, &limits, cancel);
if outcome.cancelled {
if let Err(e) = sb.remove() {
eprintln!("Container {} nicht entfernt: {e}", name);
}
return Ok(JobResult::Cancelled);
}
let (check, check_text) = run_check(&sb, &job.task);
let artifact = cfg
.data_dir
.join("runs")
.join(batch_id.to_string())
.join(format!("{}-{}-{}", job.model.replace([':', '/'], "_"), meta.id, job.repeat_idx));
let artifact_path = match sb.export_work(&artifact.join("work")) {
Ok(()) => Some(artifact.join("work").display().to_string()),
Err(_) => None,
};
// Ein fehlschlagendes Aufräumen darf einen fertigen Lauf nicht verwerfen.
if let Err(e) = sb.remove() {
eprintln!("Container {} nicht entfernt: {e}", name);
}
let class = final_class(outcome.class, &check);
let secs = outcome.duration_ms as f64 / 1000.0;
let tps = if outcome.completion_tokens > 0 && secs > 0.0 {
Some(outcome.completion_tokens as f64 / secs)
} else {
None
};
let record = RunRecord {
batch_id,
model: job.model.clone(),
task_id: meta.id.clone(),
repeat_idx: job.repeat_idx,
error_class: class,
score: check.score,
steps: outcome.steps,
prompt_tokens: outcome.prompt_tokens,
completion_tokens: outcome.completion_tokens,
duration_ms: outcome.duration_ms,
tps,
ttft_tool_ms: outcome.time_to_first_tool_ms,
artifact_path,
summary: outcome.summary.clone(),
check_output: check_text,
external: false,
};
Ok(JobResult::Finished(Finished {
record,
transcript: outcome.transcript,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tasks::TaskToml;
fn task(id: &str) -> Task {
Task {
meta: TaskToml {
id: id.into(),
title: id.into(),
group: "A".into(),
weight: 1.0,
image: "cb-python:latest".into(),
max_steps: 5,
timeout_s: 60,
check_timeout_s: 30,
},
dir: PathBuf::from("/x"),
prompt: String::new(),
}
}
#[test]
fn plan_reihenfolge_modell_aufgabe_wiederholung() {
let jobs = plan(
&["m1".into(), "m2".into()],
&[task("a-01"), task("b-04")],
2,
);
assert_eq!(jobs.len(), 8);
let keys: Vec<(String, String, u32)> = jobs
.iter()
.map(|j| (j.model.clone(), j.task.meta.id.clone(), j.repeat_idx))
.collect();
assert_eq!(keys[0], ("m1".into(), "a-01".into(), 1));
assert_eq!(keys[1], ("m1".into(), "a-01".into(), 2));
assert_eq!(keys[2], ("m1".into(), "b-04".into(), 1));
assert_eq!(keys[4], ("m2".into(), "a-01".into(), 1));
}
#[test]
fn check_json_score_gewinnt() {
let r = evaluate_check(Some(0), "viel text\n{\"score\": 0.5, \"notes\": \"halb\"}\n");
assert_eq!(r, CheckResult { score: 0.5, passed: false });
}
#[test]
fn check_ohne_json_zaehlt_exit_code() {
assert_eq!(evaluate_check(Some(0), "ok"), CheckResult { score: 1.0, passed: true });
assert_eq!(evaluate_check(Some(1), "fehler"), CheckResult { score: 0.0, passed: false });
assert_eq!(evaluate_check(None, ""), CheckResult { score: 0.0, passed: false });
}
#[test]
fn check_score_wird_begrenzt() {
let r = evaluate_check(Some(0), "{\"score\": 3.0}");
assert_eq!(r.score, 1.0);
assert!(r.passed);
}
/// Kleiner Batch end-to-end: echtes Modell, echte Sandbox, Fortsetzen über die Datenbank.
/// `CB_OLLAMA_URL=… CB_OLLAMA_MODEL=… CB_TEST_IMAGE=cb-python:latest cargo test batch_end_zu_end -- --ignored --nocapture`
#[test]
#[ignore]
fn batch_end_zu_end() {
let url = std::env::var("CB_OLLAMA_URL").expect("CB_OLLAMA_URL setzen");
let model = std::env::var("CB_OLLAMA_MODEL").expect("CB_OLLAMA_MODEL setzen");
let image = std::env::var("CB_TEST_IMAGE").expect("CB_TEST_IMAGE setzen");
let base = std::env::temp_dir().join(format!("cb-batch-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let task_dir = base.join("tasks").join("A").join("a-test");
std::fs::create_dir_all(task_dir.join("start")).unwrap();
std::fs::write(
task_dir.join("task.toml"),
format!("id = \"a-test\"\ntitle = \"Datei schreiben\"\ngroup = \"A\"\nimage = \"{image}\"\nmax_steps = 6\ntimeout_s = 300\ncheck_timeout_s = 60\n"),
)
.unwrap();
std::fs::write(task_dir.join("prompt.md"), "Erstelle die Datei out.txt mit dem Inhalt hallo (ohne Zeilenumbruch). Rufe danach done auf.").unwrap();
std::fs::write(task_dir.join("check.sh"), "#!/bin/sh\n[ \"$(cat /work/out.txt)\" = \"hallo\" ]\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(task_dir.join("check.sh"), std::fs::Permissions::from_mode(0o755)).unwrap();
}
let (tasks, errs) = {
let r = crate::tasks::load_all(&base.join("tasks"));
(r.tasks, r.errors)
};
assert!(errs.is_empty(), "{errs:?}");
let jobs = plan(&[model.clone()], &tasks, 2);
let cfg = RunConfig {
runtime: "podman".into(),
models: vec![ModelConn {
name: model.clone(),
adapter: "ollama".into(),
url,
model_id: model.clone(),
api_key: None,
}],
data_dir: base.join("data"),
limits: Limits::default(),
};
let mut store = Store::open_in_memory().unwrap();
let cancel = AtomicBool::new(false);
let events = std::cell::RefCell::new(Vec::new());
let on = |e: &Event| events.borrow_mut().push(e.clone());
let first = run_batch(&mut store, &cfg, None, "e2e", 2, &jobs, &cancel, &on).unwrap();
eprintln!("erster Lauf: {first:?}");
assert_eq!(first.completed, 2);
assert_eq!(first.skipped, 0);
// Fortsetzen mit demselben Batch: nichts läuft erneut.
let second = run_batch(&mut store, &cfg, Some(first.batch_id), "", 2, &jobs, &cancel, &on).unwrap();
eprintln!("zweiter Lauf: {second:?}");
assert_eq!(second.completed, 0);
assert_eq!(second.skipped, 2);
assert_eq!(store.run_count(first.batch_id).unwrap(), 2);
for e in events.borrow().iter() {
eprintln!("{}", serde_json::to_string(e).unwrap());
}
let _ = std::fs::remove_dir_all(&base);
}
/// Alle mitgelieferten Aufgaben gegen ein echtes Modell. Ergebnisse im Testlauf auf stderr.
/// `CB_OLLAMA_URL=… CB_OLLAMA_MODEL=… CB_TEST_IMAGE=cb-python:latest cargo test repo_aufgaben_mit_modell -- --ignored --nocapture`
#[test]
#[ignore]
fn repo_aufgaben_mit_modell() {
// Backend wählbar: CB_BACKEND=openai mit CB_OPENAI_URL (Standard: ollama mit CB_OLLAMA_URL).
let backend = std::env::var("CB_BACKEND").unwrap_or_else(|_| "ollama".into());
let url = if backend == "openai" {
std::env::var("CB_OPENAI_URL").expect("CB_OPENAI_URL setzen")
} else {
std::env::var("CB_OLLAMA_URL").expect("CB_OLLAMA_URL setzen")
};
let api_key = std::env::var("STRATA_API_KEY").ok().filter(|k| !k.is_empty());
let model = std::env::var("CB_OLLAMA_MODEL").expect("CB_OLLAMA_MODEL setzen");
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..").join("tasks");
let tasks = crate::tasks::load_all(&dir).tasks;
assert!(!tasks.is_empty());
let data = std::env::temp_dir().join(format!("cb-repo-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&data);
let jobs = plan(&[model.clone()], &tasks, 1);
let cfg = RunConfig {
runtime: "podman".into(),
models: vec![ModelConn {
name: model.clone(),
adapter: backend,
url,
model_id: model.clone(),
api_key,
}],
data_dir: data.clone(),
limits: Limits::default(),
};
std::fs::create_dir_all(&data).unwrap();
let mut store = Store::open(&data.join("db.sqlite")).unwrap();
let cancel = AtomicBool::new(false);
let summary = run_batch(&mut store, &cfg, None, "repo", 1, &jobs, &cancel, &|_| {}).unwrap();
eprintln!("Zusammenfassung: {summary:?}");
for r in store.runs_for_batch(summary.batch_id).unwrap() {
eprintln!(
"{:<6} {:<22} {:<16} score={:.2} schritte={} {:.0}s | {}",
r.task_id,
r.model,
format!("{:?}", r.error_class),
r.score,
r.steps,
r.duration_ms as f64 / 1000.0,
r.summary.clone().unwrap_or_default().chars().take(90).collect::<String>()
);
}
eprintln!("Datenbank: {}", data.join("db.sqlite").display());
}
/// Ein Modell, dessen Server nicht antwortet, bricht den Batch nicht ab. Die Läufe werden als
/// endpoint_error gespeichert, zählen nicht in die Bewertung und werden beim Fortsetzen wiederholt.
/// Braucht weder Podman noch einen Server (Port 1 auf localhost ist geschlossen).
#[test]
fn ausgefallenes_modell_wird_gespeichert_und_beim_fortsetzen_wiederholt() {
let cfg = RunConfig {
runtime: "podman".into(),
models: vec![ModelConn {
name: "weg".into(),
adapter: "ollama".into(),
url: "http://127.0.0.1:1".into(),
model_id: "x".into(),
api_key: None,
}],
data_dir: std::env::temp_dir().join("cb-unused"),
limits: Limits::default(),
};
let jobs = plan(&["weg".to_string()], &[task("a-01"), task("a-02")], 1);
let mut store = Store::open_in_memory().unwrap();
let cancel = AtomicBool::new(false);
let events = std::cell::RefCell::new(Vec::new());
let on = |e: &Event| events.borrow_mut().push(e.clone());
let first = run_batch(&mut store, &cfg, None, "t", 1, &jobs, &cancel, &on).unwrap();
assert_eq!(first.completed, 2);
assert!(events.borrow().iter().any(|e| matches!(e, Event::ModelUnavailable { .. })));
let runs = store.runs_for_batch(first.batch_id).unwrap();
assert_eq!(runs.len(), 2);
assert!(runs.iter().all(|r| r.error_class == ErrorClass::EndpointError));
// Fortsetzen: Ausfälle gelten nicht als fertig und werden wiederholt.
let second = run_batch(&mut store, &cfg, Some(first.batch_id), "", 1, &jobs, &cancel, &on).unwrap();
assert_eq!(second.completed, 2);
assert_eq!(second.skipped, 0);
// Die Bewertung ignoriert die Ausfälle.
let all = store.runs_for_batch(first.batch_id).unwrap();
let r = crate::ranking::compute(first.batch_id, &all, &Default::default());
assert_eq!(r.excluded_runs, 4);
assert!(r.models.is_empty());
}
#[test]
fn klasse_agent_vor_pruefung() {
let ok = CheckResult { score: 1.0, passed: true };
let bad = CheckResult { score: 0.0, passed: false };
assert_eq!(final_class(ErrorClass::MaxSteps, &ok), ErrorClass::MaxSteps);
assert_eq!(final_class(ErrorClass::Ok, &bad), ErrorClass::CheckFailed);
assert_eq!(final_class(ErrorClass::Ok, &ok), ErrorClass::Ok);
}
}

357
src-tauri/src/sandbox.rs Normal file
View File

@ -0,0 +1,357 @@
//! Sandbox pro Lauf (F-04, SPEC Abschnitt 6).
//!
//! Jeder Lauf bekommt einen frischen Podman-Container ohne Netzwerk. Die Aufgabe
//! wird nach `/work` kopiert, Befehle laufen per `podman exec`, und am Ende wird
//! `/work` herausgeholt und der Container entfernt. Podman wird über die CLI
//! angesprochen (rootless, Docker-kompatible Befehle).
use std::io::Read;
use std::path::Path;
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};
pub const WORK_DIR: &str = "/work";
/// Obergrenze je Ausgabestrom eines Befehls. Mehr wird gelesen und verworfen.
pub const MAX_CAPTURE_BYTES: u64 = 1 << 20;
/// Ressourcenlimits eines Containers.
#[derive(Debug, Clone, PartialEq)]
pub struct Limits {
/// Speicherlimit, Podman-Schreibweise, z. B. `2g`.
pub memory: String,
/// CPU-Anteil, z. B. `2`.
pub cpus: String,
}
impl Default for Limits {
fn default() -> Self {
Limits {
memory: "2g".into(),
cpus: "2".into(),
}
}
}
/// Ergebnis eines Befehls im Container.
#[derive(Debug, Clone, PartialEq)]
pub struct ExecOutput {
pub exit_code: Option<i32>,
pub stdout: String,
pub stderr: String,
pub timed_out: bool,
}
/// Argumente für `podman run`. Reine Funktion, damit sie testbar ist.
pub fn run_args(name: &str, image: &str, limits: &Limits) -> Vec<String> {
vec![
"run".into(),
"-d".into(),
"--name".into(),
name.into(),
"--network".into(),
"none".into(),
"--memory".into(),
limits.memory.clone(),
"--cpus".into(),
limits.cpus.clone(),
"--pids-limit".into(),
"512".into(),
"--label".into(),
"coding-bench=lauf".into(),
// `--` beendet die Optionen: ein Image-Name wird so nie als Option gelesen.
"--".into(),
image.into(),
"sleep".into(),
"infinity".into(),
]
}
/// Eindeutiger Containername pro Lauf.
pub fn container_name(run_id: &str) -> String {
format!("cb-{run_id}")
}
/// Ein laufender Sandbox-Container. Wird beim Verwerfen entfernt.
pub struct Sandbox {
runtime: String,
name: String,
removed: bool,
}
impl Sandbox {
/// Startet den Container und kopiert optional das Startverzeichnis nach `/work`.
pub fn start(
runtime: &str,
name: &str,
image: &str,
limits: &Limits,
start_dir: Option<&Path>,
) -> Result<Sandbox, String> {
let sb = Sandbox {
runtime: runtime.into(),
name: name.into(),
removed: false,
};
let out = Command::new(runtime)
.args(run_args(name, image, limits))
.output()
.map_err(|e| format!("{runtime} nicht startbar: {e}"))?;
if !out.status.success() {
return Err(format!(
"Container konnte nicht gestartet werden: {}",
String::from_utf8_lossy(&out.stderr).trim()
));
}
// Ab hier räumt Drop den Container auf, auch wenn der Rest fehlschlägt.
let mut sb = sb;
// Ohne `-w`, weil /work noch nicht existiert.
let mkdir = sb.exec_in(None, &format!("mkdir -p {WORK_DIR}"), Duration::from_secs(30))?;
if mkdir.exit_code != Some(0) {
return Err(format!("{WORK_DIR} nicht anlegbar: {}", mkdir.stderr.trim()));
}
if let Some(src) = start_dir {
let src_spec = format!("{}/.", src.display());
let dst_spec = format!("{}:{WORK_DIR}/", sb.name);
let cp = Command::new(runtime)
.args(["cp", &src_spec, &dst_spec])
.output()
.map_err(|e| format!("podman cp fehlgeschlagen: {e}"))?;
if !cp.status.success() {
return Err(format!(
"Startdateien nicht kopierbar: {}",
String::from_utf8_lossy(&cp.stderr).trim()
));
}
}
Ok(sb)
}
pub fn name(&self) -> &str {
&self.name
}
/// Führt `command` per `sh -c` in `/work` aus. Nach `timeout` wird der
/// Client-Prozess beendet und `timed_out` gesetzt.
pub fn exec(&self, command: &str, timeout: Duration) -> Result<ExecOutput, String> {
self.exec_in(Some(WORK_DIR), command, timeout)
}
fn exec_in(&self, workdir: Option<&str>, command: &str, timeout: Duration) -> Result<ExecOutput, String> {
let mut args: Vec<&str> = vec!["exec"];
if let Some(w) = workdir {
args.extend(["-w", w]);
}
args.extend([self.name.as_str(), "sh", "-c", command]);
let mut child = Command::new(&self.runtime)
.args(&args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("podman exec fehlgeschlagen: {e}"))?;
// Pipes in eigenen Threads lesen, sonst blockiert ein volles Ausgabepuffer.
let mut stdout = child.stdout.take().expect("stdout ist gepiped");
let mut stderr = child.stderr.take().expect("stderr ist gepiped");
let t_out = thread::spawn(move || read_limited(&mut stdout, MAX_CAPTURE_BYTES));
let t_err = thread::spawn(move || read_limited(&mut stderr, MAX_CAPTURE_BYTES));
let start = Instant::now();
let (status, timed_out) = loop {
if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
break (Some(status), false);
}
if start.elapsed() >= timeout {
let _ = child.kill();
let status = child.wait().ok();
break (status, true);
}
thread::sleep(Duration::from_millis(50));
};
Ok(ExecOutput {
exit_code: status.and_then(|s| s.code()),
stdout: t_out.join().unwrap_or_default(),
stderr: t_err.join().unwrap_or_default(),
timed_out,
})
}
/// Kopiert `/work` in den Zielordner (Artefakt).
pub fn export_work(&self, dest: &Path) -> Result<(), String> {
std::fs::create_dir_all(dest).map_err(|e| format!("Zielordner nicht anlegbar: {e}"))?;
let src_spec = format!("{}:{WORK_DIR}/.", self.name);
let dst_spec = dest.display().to_string();
let out = Command::new(&self.runtime)
.args(["cp", &src_spec, &dst_spec])
.output()
.map_err(|e| format!("podman cp fehlgeschlagen: {e}"))?;
if !out.status.success() {
return Err(format!(
"/work nicht exportierbar: {}",
String::from_utf8_lossy(&out.stderr).trim()
));
}
Ok(())
}
/// Kopiert eine einzelne Datei in den Container (z. B. `check.sh`, nicht in `/work`).
pub fn copy_in(&self, src: &Path, dst: &str) -> Result<(), String> {
let dst_spec = format!("{}:{dst}", self.name);
let out = Command::new(&self.runtime)
.args(["cp", &src.display().to_string(), &dst_spec])
.output()
.map_err(|e| format!("podman cp fehlgeschlagen: {e}"))?;
if out.status.success() {
Ok(())
} else {
Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
}
}
/// Entfernt den Container. Fehler werden zurückgegeben, nicht verschluckt.
pub fn remove(mut self) -> Result<(), String> {
self.remove_inner()
}
fn remove_inner(&mut self) -> Result<(), String> {
if self.removed {
return Ok(());
}
self.removed = true;
let out = Command::new(&self.runtime)
.args(["rm", "-f", &self.name])
.output()
.map_err(|e| format!("podman rm fehlgeschlagen: {e}"))?;
if out.status.success() {
Ok(())
} else {
Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
}
}
}
/// Liest höchstens `limit` Bytes, verwirft den Rest (damit der Prozess nicht an einer vollen Pipe
/// hängt) und wandelt ungültiges UTF-8 in Ersatzzeichen um.
pub fn read_limited<R: Read>(reader: &mut R, limit: u64) -> String {
let mut buf = Vec::new();
let _ = reader.take(limit).read_to_end(&mut buf);
let mut truncated = false;
let mut sink = [0u8; 8192];
loop {
match reader.read(&mut sink) {
Ok(0) | Err(_) => break,
Ok(_) => truncated = true,
}
}
let mut text = String::from_utf8_lossy(&buf).into_owned();
if truncated {
text.push_str("\n[Ausgabe gekürzt]");
}
text
}
/// Entfernt einen Container nach Name, falls ein früherer Lauf ihn hinterlassen hat.
pub fn remove_by_name(runtime: &str, name: &str) {
let _ = Command::new(runtime).args(["rm", "-f", name]).output();
}
impl Drop for Sandbox {
fn drop(&mut self) {
let _ = self.remove_inner();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn run_args_enthalten_netzwerk_aus_und_limits() {
let args = run_args("cb-x", "img:1", &Limits::default());
let s = args.join(" ");
assert!(s.contains("--network none"));
assert!(s.contains("--memory 2g"));
assert!(s.contains("--cpus 2"));
assert!(s.ends_with("img:1 sleep infinity"));
}
#[test]
fn image_steht_nach_doppeltem_strich() {
let args = run_args("cb-x", "img:1", &Limits::default());
let pos = args.iter().position(|a| a == "--").expect("-- fehlt");
assert_eq!(args[pos + 1], "img:1");
}
#[test]
fn ausgabe_wird_begrenzt_und_utf8_ersetzt() {
let mut data = std::io::Cursor::new(vec![b'a'; 100]);
let text = read_limited(&mut data, 10);
assert!(text.starts_with("aaaaaaaaaa"));
assert!(text.contains("[Ausgabe gekürzt]"));
assert!(!text.contains("aaaaaaaaaaa"));
let mut kurz = std::io::Cursor::new(b"ok".to_vec());
assert_eq!(read_limited(&mut kurz, 10), "ok");
let mut kaputt = std::io::Cursor::new(vec![b'x', 0xff, b'y']);
assert_eq!(read_limited(&mut kaputt, 10), "x\u{fffd}y");
}
#[test]
fn containername_ist_praefixiert() {
assert_eq!(container_name("42"), "cb-42");
}
/// Echter Lauf gegen Podman. Braucht ein lokales Image mit `sleep` und `sh`
/// und ist deshalb ignoriert. Ausführen mit:
/// `CB_TEST_IMAGE=docker.io/library/python:3.12-slim cargo test -- --ignored`
#[test]
#[ignore]
fn echter_lauf_ohne_netz_und_aufraeumen() {
let image = std::env::var("CB_TEST_IMAGE").expect("CB_TEST_IMAGE setzen");
let base = std::env::temp_dir().join(format!("cb-sandbox-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let start_dir = base.join("start");
std::fs::create_dir_all(&start_dir).unwrap();
std::fs::write(start_dir.join("eingabe.txt"), "hallo").unwrap();
let name = container_name(&format!("test-{}", std::process::id()));
let sb = Sandbox::start("podman", &name, &image, &Limits::default(), Some(&start_dir))
.expect("Start");
// Startdatei liegt in /work.
let r = sb.exec("cat eingabe.txt", Duration::from_secs(30)).unwrap();
assert_eq!(r.stdout, "hallo");
// Kein Netz: Verbindung muss scheitern.
let r = sb
.exec(
"python3 -c 'import socket; socket.create_connection((\"1.1.1.1\", 80), timeout=3)'",
Duration::from_secs(30),
)
.unwrap();
assert_ne!(r.exit_code, Some(0), "Netz sollte aus sein: {}", r.stderr);
// Timeout wird erkannt.
let r = sb.exec("sleep 10", Duration::from_secs(1)).unwrap();
assert!(r.timed_out);
// Artefakt herausholen.
let art = base.join("artefakt");
sb.export_work(&art).unwrap();
assert_eq!(std::fs::read_to_string(art.join("eingabe.txt")).unwrap(), "hallo");
sb.remove().unwrap();
let ps = Command::new("podman")
.args(["ps", "-a", "--filter", &format!("name={name}"), "--format", "{{.Names}}"])
.output()
.unwrap();
assert!(String::from_utf8_lossy(&ps.stdout).trim().is_empty(), "Container nicht entfernt");
let _ = std::fs::remove_dir_all(&base);
}
}

475
src-tauri/src/store.rs Normal file
View File

@ -0,0 +1,475 @@
//! SQLite-Speicher für Batches, Läufe und Schritte (F-06, SPEC Abschnitt 8).
use crate::agent::{ErrorClass, Message};
use rusqlite::{params, Connection, OptionalExtension};
use serde::Serialize;
use std::collections::HashSet;
use std::path::Path;
const SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS batch (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
note TEXT NOT NULL DEFAULT '',
repeats INTEGER NOT NULL,
config_json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS run (
id INTEGER PRIMARY KEY AUTOINCREMENT,
batch_id INTEGER NOT NULL REFERENCES batch(id),
model TEXT NOT NULL,
task_id TEXT NOT NULL,
repeat_idx INTEGER NOT NULL,
status TEXT NOT NULL,
error_class TEXT NOT NULL,
score REAL NOT NULL,
steps INTEGER NOT NULL,
prompt_tokens INTEGER NOT NULL,
completion_tokens INTEGER NOT NULL,
duration_ms INTEGER NOT NULL,
tps REAL,
ttft_tool_ms INTEGER,
started_at TEXT NOT NULL DEFAULT (datetime('now')),
artifact_path TEXT,
summary TEXT,
check_output TEXT
);
CREATE INDEX IF NOT EXISTS run_batch ON run(batch_id, model, task_id, repeat_idx);
CREATE TABLE IF NOT EXISTS step (
id INTEGER PRIMARY KEY AUTOINCREMENT,
run_id INTEGER NOT NULL REFERENCES run(id),
idx INTEGER NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
tool_name TEXT,
tool_args_json TEXT,
tool_result TEXT,
tokens INTEGER,
duration_ms INTEGER
);
";
/// Ein abgeschlossener Lauf, so wie er gespeichert wird.
/// Ein Batch in der Übersicht.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BatchInfo {
pub id: i64,
pub created_at: String,
pub note: String,
pub repeats: u32,
pub runs: i64,
/// Modellnamen, durch Komma getrennt.
pub models: String,
}
/// Ein Schritt eines Laufs, für die Anzeige.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct StepRow {
pub idx: i64,
pub role: String,
pub content: String,
pub tool_name: Option<String>,
pub tool_args_json: Option<String>,
pub tool_result: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RunRecord {
pub batch_id: i64,
pub model: String,
pub task_id: String,
pub repeat_idx: u32,
pub error_class: ErrorClass,
pub score: f64,
pub steps: u32,
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub duration_ms: u128,
pub tps: Option<f64>,
pub ttft_tool_ms: Option<u128>,
pub artifact_path: Option<String>,
pub summary: Option<String>,
pub check_output: String,
/// Von Hand außerhalb der App gelöst (Referenz), nicht von einem angebundenen Modell.
pub external: bool,
}
pub struct Store {
conn: Connection,
}
impl Store {
pub fn open(path: &Path) -> Result<Store, String> {
let conn = Connection::open(path).map_err(|e| format!("Datenbank nicht öffenbar: {e}"))?;
Self::init(conn)
}
pub fn open_in_memory() -> Result<Store, String> {
let conn = Connection::open_in_memory().map_err(|e| e.to_string())?;
Self::init(conn)
}
fn init(conn: Connection) -> Result<Store, String> {
conn.execute_batch("PRAGMA foreign_keys = ON;")
.and_then(|_| conn.execute_batch(SCHEMA))
.map_err(|e| format!("Schema nicht anlegbar: {e}"))?;
Self::migrate(&conn)?;
Ok(Store { conn })
}
/// Ältere Datenbanken bekommen neue Spalten nachgerüstet.
fn migrate(conn: &Connection) -> Result<(), String> {
let has_external = conn
.prepare("SELECT 1 FROM pragma_table_info('run') WHERE name = 'external'")
.and_then(|mut st| st.exists([]))
.map_err(|e| e.to_string())?;
if !has_external {
conn.execute_batch("ALTER TABLE run ADD COLUMN external INTEGER NOT NULL DEFAULT 0;")
.map_err(|e| format!("Migration fehlgeschlagen: {e}"))?;
}
Ok(())
}
/// Entfernt einen Lauf samt Schritten, damit ein Import ihn ersetzen kann.
pub fn delete_run(&mut self, batch_id: i64, model: &str, task_id: &str, repeat_idx: u32) -> Result<(), String> {
let tx = self.conn.transaction().map_err(|e| e.to_string())?;
tx.execute(
"DELETE FROM step WHERE run_id IN
(SELECT id FROM run WHERE batch_id = ?1 AND model = ?2 AND task_id = ?3 AND repeat_idx = ?4)",
params![batch_id, model, task_id, repeat_idx],
)
.map_err(|e| e.to_string())?;
tx.execute(
"DELETE FROM run WHERE batch_id = ?1 AND model = ?2 AND task_id = ?3 AND repeat_idx = ?4",
params![batch_id, model, task_id, repeat_idx],
)
.map_err(|e| e.to_string())?;
tx.commit().map_err(|e| e.to_string())
}
pub fn create_batch(&self, note: &str, repeats: u32, config_json: &str) -> Result<i64, String> {
self.conn
.execute(
"INSERT INTO batch (note, repeats, config_json) VALUES (?1, ?2, ?3)",
params![note, repeats, config_json],
)
.map_err(|e| e.to_string())?;
Ok(self.conn.last_insert_rowid())
}
pub fn batch_exists(&self, batch_id: i64) -> Result<bool, String> {
self.conn
.query_row("SELECT 1 FROM batch WHERE id = ?1", params![batch_id], |_| Ok(()))
.optional()
.map(|r| r.is_some())
.map_err(|e| e.to_string())
}
/// Schlüssel (Modell, Aufgabe, Wiederholung) der gültig beendeten Läufe eines Batches.
/// Läufe, die an Server oder Umgebung scheiterten, fehlen hier und werden wiederholt.
pub fn finished_keys(&self, batch_id: i64) -> Result<HashSet<(String, String, u32)>, String> {
let mut stmt = self
.conn
.prepare(
"SELECT model, task_id, repeat_idx FROM run
WHERE batch_id = ?1 AND error_class NOT IN ('endpoint_error', 'sandbox_error')",
)
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![batch_id], |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, u32>(2)?))
})
.map_err(|e| e.to_string())?;
rows.collect::<Result<HashSet<_>, _>>().map_err(|e| e.to_string())
}
/// Speichert einen Lauf mit seinen Schritten in einer Transaktion.
pub fn insert_run(&mut self, rec: &RunRecord, transcript: &[Message]) -> Result<i64, String> {
let tx = self.conn.transaction().map_err(|e| e.to_string())?;
let class = serde_json::to_value(rec.error_class)
.ok()
.and_then(|v| v.as_str().map(String::from))
.unwrap_or_default();
tx.execute(
"INSERT INTO run (batch_id, model, task_id, repeat_idx, status, error_class, score,
steps, prompt_tokens, completion_tokens, duration_ms, tps, ttft_tool_ms,
artifact_path, summary, check_output, external)
VALUES (?1, ?2, ?3, ?4, 'done', ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)",
params![
rec.batch_id,
rec.model,
rec.task_id,
rec.repeat_idx,
class,
rec.score,
rec.steps,
rec.prompt_tokens,
rec.completion_tokens,
rec.duration_ms as i64,
rec.tps,
rec.ttft_tool_ms.map(|v| v as i64),
rec.artifact_path,
rec.summary,
rec.check_output,
rec.external as i64,
],
)
.map_err(|e| e.to_string())?;
let run_id = tx.last_insert_rowid();
for (idx, m) in transcript.iter().enumerate() {
let (args, tool_name) = match m.tool_calls.first() {
Some(c) => (Some(c.function.arguments.to_string()), Some(c.function.name.clone())),
None => (None, m.tool_name.clone()),
};
tx.execute(
"INSERT INTO step (run_id, idx, role, content, tool_name, tool_args_json, tool_result)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
run_id,
idx as i64,
m.role,
m.content,
tool_name,
args,
if m.role == "tool" { Some(m.content.clone()) } else { None },
],
)
.map_err(|e| e.to_string())?;
}
tx.commit().map_err(|e| e.to_string())?;
Ok(run_id)
}
/// Alle gespeicherten Läufe eines Batches, sortiert nach Modell, Aufgabe und Wiederholung.
pub fn runs_for_batch(&self, batch_id: i64) -> Result<Vec<RunRecord>, String> {
let mut stmt = self
.conn
.prepare(
"SELECT batch_id, model, task_id, repeat_idx, error_class, score, steps,
prompt_tokens, completion_tokens, duration_ms, tps, ttft_tool_ms,
artifact_path, summary, check_output, external
FROM run WHERE batch_id = ?1 ORDER BY model, task_id, repeat_idx",
)
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![batch_id], |r| {
let class: String = r.get(4)?;
let error_class = serde_json::from_value(serde_json::Value::String(class))
.unwrap_or(ErrorClass::EndpointError);
Ok(RunRecord {
batch_id: r.get(0)?,
model: r.get(1)?,
task_id: r.get(2)?,
repeat_idx: r.get(3)?,
error_class,
score: r.get(5)?,
steps: r.get(6)?,
prompt_tokens: r.get(7)?,
completion_tokens: r.get(8)?,
duration_ms: r.get::<_, i64>(9)? as u128,
tps: r.get(10)?,
ttft_tool_ms: r.get::<_, Option<i64>>(11)?.map(|v| v as u128),
artifact_path: r.get(12)?,
summary: r.get(13)?,
check_output: r.get(14)?,
external: r.get::<_, i64>(15)? != 0,
})
})
.map_err(|e| e.to_string())?;
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
}
/// Schritte eines Laufs, identifiziert über Batch, Modell, Aufgabe und Wiederholung.
pub fn steps_for_run(
&self,
batch_id: i64,
model: &str,
task_id: &str,
repeat_idx: u32,
) -> Result<Vec<StepRow>, String> {
let mut stmt = self
.conn
.prepare(
"SELECT s.idx, s.role, s.content, s.tool_name, s.tool_args_json, s.tool_result
FROM step s JOIN run r ON s.run_id = r.id
WHERE r.batch_id = ?1 AND r.model = ?2 AND r.task_id = ?3 AND r.repeat_idx = ?4
ORDER BY s.idx",
)
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![batch_id, model, task_id, repeat_idx], |r| {
Ok(StepRow {
idx: r.get(0)?,
role: r.get(1)?,
content: r.get(2)?,
tool_name: r.get(3)?,
tool_args_json: r.get(4)?,
tool_result: r.get(5)?,
})
})
.map_err(|e| e.to_string())?;
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
}
/// Alle Batches, neueste zuerst.
pub fn list_batches(&self) -> Result<Vec<BatchInfo>, String> {
let mut stmt = self
.conn
.prepare(
"SELECT b.id, b.created_at, b.note, b.repeats, COUNT(r.id),
COALESCE(group_concat(DISTINCT r.model), '')
FROM batch b LEFT JOIN run r ON r.batch_id = b.id
GROUP BY b.id ORDER BY b.id DESC",
)
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map([], |r| {
Ok(BatchInfo {
id: r.get(0)?,
created_at: r.get(1)?,
note: r.get(2)?,
repeats: r.get(3)?,
runs: r.get(4)?,
models: r.get(5)?,
})
})
.map_err(|e| e.to_string())?;
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
}
pub fn run_count(&self, batch_id: i64) -> Result<i64, String> {
self.conn
.query_row("SELECT COUNT(*) FROM run WHERE batch_id = ?1", params![batch_id], |r| r.get(0))
.map_err(|e| e.to_string())
}
pub fn step_count(&self, run_id: i64) -> Result<i64, String> {
self.conn
.query_row("SELECT COUNT(*) FROM step WHERE run_id = ?1", params![run_id], |r| r.get(0))
.map_err(|e| e.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::agent::{FunctionCall, ToolCall};
use serde_json::json;
fn rec(batch: i64, model: &str, task: &str, rep: u32) -> RunRecord {
RunRecord {
batch_id: batch,
model: model.into(),
task_id: task.into(),
repeat_idx: rep,
error_class: ErrorClass::Ok,
score: 1.0,
steps: 2,
prompt_tokens: 10,
completion_tokens: 5,
duration_ms: 1234,
tps: Some(4.0),
ttft_tool_ms: Some(300),
artifact_path: None,
summary: Some("fertig".into()),
check_output: "ok".into(),
external: false,
}
}
#[test]
fn batch_und_lauf_werden_gespeichert() {
let mut s = Store::open_in_memory().unwrap();
let b = s.create_batch("test", 3, "{}").unwrap();
assert!(s.batch_exists(b).unwrap());
let transcript = vec![
Message::new("user", "Aufgabe"),
Message {
role: "assistant".into(),
content: String::new(),
tool_calls: vec![ToolCall {
function: FunctionCall { name: "done".into(), arguments: json!({"summary": "x"}) },
}],
tool_name: None,
},
];
let run_id = s.insert_run(&rec(b, "m1", "a-01", 1), &transcript).unwrap();
assert_eq!(s.run_count(b).unwrap(), 1);
assert_eq!(s.step_count(run_id).unwrap(), 2);
}
#[test]
fn fertige_schluessel_werden_gelesen() {
let mut s = Store::open_in_memory().unwrap();
let b = s.create_batch("", 2, "{}").unwrap();
s.insert_run(&rec(b, "m1", "a-01", 1), &[]).unwrap();
let keys = s.finished_keys(b).unwrap();
assert!(keys.contains(&("m1".to_string(), "a-01".to_string(), 1)));
assert!(!keys.contains(&("m1".to_string(), "a-01".to_string(), 2)));
}
#[test]
fn laeufe_eines_batches_werden_zurueckgelesen() {
let mut s = Store::open_in_memory().unwrap();
let b = s.create_batch("", 2, "{}").unwrap();
s.insert_run(&rec(b, "m1", "a-01", 2), &[]).unwrap();
s.insert_run(&rec(b, "m1", "a-01", 1), &[]).unwrap();
let runs = s.runs_for_batch(b).unwrap();
assert_eq!(runs.len(), 2);
assert_eq!(runs[0].repeat_idx, 1);
assert_eq!(runs[0].error_class, ErrorClass::Ok);
assert_eq!(runs[0].ttft_tool_ms, Some(300));
assert!(s.runs_for_batch(99).unwrap().is_empty());
}
#[test]
fn schritte_eines_laufs_werden_gefunden() {
let mut s = Store::open_in_memory().unwrap();
let b = s.create_batch("", 1, "{}").unwrap();
let transcript = vec![Message::new("user", "Aufgabe"), Message::new("assistant", "ok")];
s.insert_run(&rec(b, "m1", "a-01", 1), &transcript).unwrap();
let steps = s.steps_for_run(b, "m1", "a-01", 1).unwrap();
assert_eq!(steps.len(), 2);
assert_eq!(steps[0].role, "user");
assert_eq!(steps[1].content, "ok");
assert!(s.steps_for_run(b, "m1", "a-01", 2).unwrap().is_empty());
}
#[test]
fn batches_werden_mit_laeufen_und_modellen_aufgelistet() {
let mut s = Store::open_in_memory().unwrap();
let b1 = s.create_batch("erster", 1, "{}").unwrap();
let b2 = s.create_batch("zweiter", 2, "{}").unwrap();
s.insert_run(&rec(b1, "m1", "a-01", 1), &[]).unwrap();
s.insert_run(&rec(b1, "m2", "a-01", 1), &[]).unwrap();
let list = s.list_batches().unwrap();
assert_eq!(list.len(), 2);
assert_eq!(list[0].id, b2, "neuester zuerst");
assert_eq!(list[0].runs, 0);
assert_eq!(list[1].runs, 2);
assert!(list[1].models.contains("m1") && list[1].models.contains("m2"));
}
#[test]
fn infrastruktur_laeufe_werden_beim_fortsetzen_wiederholt() {
let mut s = Store::open_in_memory().unwrap();
let b = s.create_batch("", 1, "{}").unwrap();
s.insert_run(&rec(b, "m", "ok-task", 1), &[]).unwrap();
let mut ausfall = rec(b, "m", "sandbox-task", 1);
ausfall.error_class = ErrorClass::SandboxError;
s.insert_run(&ausfall, &[]).unwrap();
let mut server = rec(b, "m", "server-task", 1);
server.error_class = ErrorClass::EndpointError;
s.insert_run(&server, &[]).unwrap();
let keys = s.finished_keys(b).unwrap();
assert!(keys.contains(&("m".to_string(), "ok-task".to_string(), 1)));
assert!(!keys.contains(&("m".to_string(), "sandbox-task".to_string(), 1)));
assert!(!keys.contains(&("m".to_string(), "server-task".to_string(), 1)));
}
#[test]
fn unbekannter_batch_existiert_nicht() {
let s = Store::open_in_memory().unwrap();
assert!(!s.batch_exists(99).unwrap());
}
}

349
src-tauri/src/tasks.rs Normal file
View File

@ -0,0 +1,349 @@
//! Aufgaben laden und validieren (F-02, SPEC Abschnitt 4).
//!
//! Eine Aufgabe ist ein Ordner `tasks/<gruppe>/<name>/` mit `task.toml`,
//! `prompt.md`, `check.sh` und `start/`. Fehlerhafte Aufgaben werden nicht
//! geladen, sondern mit Pfad und Grund gemeldet.
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
pub const TASK_FILE: &str = "task.toml";
pub const PROMPT_FILE: &str = "prompt.md";
pub const CHECK_FILE: &str = "check.sh";
pub const START_DIR: &str = "start";
const GROUPS: [&str; 4] = ["A", "B", "C", "D"];
/// Metadaten aus `task.toml`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskToml {
pub id: String,
pub title: String,
pub group: String,
#[serde(default = "default_weight")]
pub weight: f64,
pub image: String,
pub max_steps: u32,
pub timeout_s: u64,
#[serde(default = "default_check_timeout")]
pub check_timeout_s: u64,
}
fn default_weight() -> f64 {
1.0
}
fn default_check_timeout() -> u64 {
120
}
/// Eine geladene, gültige Aufgabe.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Task {
#[serde(flatten)]
pub meta: TaskToml,
pub dir: PathBuf,
/// Inhalt von `prompt.md`, damit die Oberfläche zeigen kann, was die Aufgabe verlangt.
pub prompt: String,
}
/// Ein Fehler bei einer Aufgabe, mit Ordner und Grund.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TaskError {
pub dir: PathBuf,
pub message: String,
}
/// Ergebnis eines Ladelaufs.
#[derive(Debug, Default, Clone, PartialEq, Serialize)]
pub struct LoadReport {
pub tasks: Vec<Task>,
pub errors: Vec<TaskError>,
}
/// Prüft einen Image-Namen. Erlaubt sind Buchstaben, Ziffern und `. _ - / : @`; er darf nicht
/// mit `-` beginnen. Sonst könnte ein fremder Aufgaben-Ordner Podman-Optionen einschleusen.
pub fn validate_image(image: &str) -> Result<(), String> {
if image.is_empty() {
return Err("image ist leer".into());
}
if image.len() > 200 {
return Err("image ist zu lang".into());
}
if image.starts_with('-') {
return Err(format!("image {image:?} darf nicht mit - beginnen"));
}
if let Some(c) = image
.chars()
.find(|c| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '/' | ':' | '@')))
{
return Err(format!("image {image:?} enthält das unzulässige Zeichen {c:?}"));
}
Ok(())
}
/// Validiert die Metadaten. Gibt eine Liste aller Verstöße zurück.
pub fn validate_meta(meta: &TaskToml) -> Vec<String> {
let mut errs = Vec::new();
if meta.id.trim().is_empty() {
errs.push("id ist leer".into());
}
if meta.title.trim().is_empty() {
errs.push("title ist leer".into());
}
if !GROUPS.contains(&meta.group.as_str()) {
errs.push(format!("group muss A, B, C oder D sein, ist {:?}", meta.group));
}
if !meta.weight.is_finite() || meta.weight <= 0.0 {
errs.push("weight muss größer als 0 sein".into());
}
if let Err(e) = validate_image(&meta.image) {
errs.push(e);
}
if meta.max_steps == 0 {
errs.push("max_steps muss größer als 0 sein".into());
}
if meta.timeout_s == 0 {
errs.push("timeout_s muss größer als 0 sein".into());
}
if meta.check_timeout_s == 0 {
errs.push("check_timeout_s muss größer als 0 sein".into());
}
errs
}
/// Prüft die Pflichtdateien und Rechte eines Aufgabenordners.
pub fn validate_files(dir: &Path) -> Vec<String> {
let mut errs = Vec::new();
for name in [TASK_FILE, PROMPT_FILE, CHECK_FILE] {
if !dir.join(name).is_file() {
errs.push(format!("Pflichtdatei fehlt: {name}"));
}
}
if !dir.join(START_DIR).is_dir() {
errs.push(format!("Ordner fehlt: {START_DIR}/ (darf leer sein)"));
}
if dir.join(CHECK_FILE).is_file() && !is_executable(&dir.join(CHECK_FILE)) {
errs.push(format!("{CHECK_FILE} ist nicht ausführbar"));
}
errs
}
#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
fs::metadata(path)
.map(|m| m.permissions().mode() & 0o111 != 0)
.unwrap_or(false)
}
#[cfg(not(unix))]
fn is_executable(_path: &Path) -> bool {
true
}
/// Lädt eine einzelne Aufgabe aus ihrem Ordner.
pub fn load_one(dir: &Path) -> Result<Task, Vec<String>> {
let mut errs = validate_files(dir);
let meta = match fs::read_to_string(dir.join(TASK_FILE)) {
Ok(text) => match toml::from_str::<TaskToml>(&text) {
Ok(meta) => {
errs.extend(validate_meta(&meta));
Some(meta)
}
Err(e) => {
errs.push(format!("{TASK_FILE} ist kein gültiges TOML: {e}"));
None
}
},
Err(_) => None, // Fehlende Datei ist oben schon gemeldet.
};
match (meta, errs.is_empty()) {
(Some(meta), true) => Ok(Task {
meta,
dir: dir.to_path_buf(),
prompt: fs::read_to_string(dir.join(PROMPT_FILE)).unwrap_or_default(),
}),
_ => Err(errs),
}
}
/// Lädt alle Aufgaben unterhalb von `tasks_dir` (Ebene `<gruppe>/<name>`).
/// Ein fehlender Aufgabenordner ist kein Fehler: es gibt dann keine Aufgaben.
pub fn load_all(tasks_dir: &Path) -> LoadReport {
let mut report = LoadReport::default();
if !tasks_dir.is_dir() {
return report;
}
let groups = match sorted_subdirs(tasks_dir) {
Ok(v) => v,
Err(e) => {
report.errors.push(TaskError {
dir: tasks_dir.to_path_buf(),
message: format!("Aufgabenordner nicht lesbar: {e}"),
});
return report;
}
};
for group_dir in groups {
match sorted_subdirs(&group_dir) {
Ok(tasks) => {
for task_dir in tasks {
match load_one(&task_dir) {
Ok(task) => report.tasks.push(task),
Err(messages) => report.errors.push(TaskError {
dir: task_dir,
message: messages.join("; "),
}),
}
}
}
Err(e) => report.errors.push(TaskError {
dir: group_dir,
message: format!("Gruppenordner nicht lesbar: {e}"),
}),
}
}
report
}
fn sorted_subdirs(dir: &Path) -> std::io::Result<Vec<PathBuf>> {
let mut out: Vec<PathBuf> = fs::read_dir(dir)?
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| p.is_dir())
.collect();
out.sort();
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
const GUT: &str = r#"
id = "b-05-bugfix-parser"
title = "Bug im Parser finden und fixen"
group = "B"
image = "cb-python:latest"
max_steps = 25
timeout_s = 600
"#;
fn tmp(name: &str) -> PathBuf {
let p = std::env::temp_dir().join(format!("cb-tasks-{}-{}", name, std::process::id()));
let _ = fs::remove_dir_all(&p);
fs::create_dir_all(&p).unwrap();
p
}
fn make_task(dir: &Path, toml: &str, check_exec: bool) {
fs::create_dir_all(dir.join(START_DIR)).unwrap();
fs::write(dir.join(TASK_FILE), toml).unwrap();
fs::write(dir.join(PROMPT_FILE), "Aufgabe").unwrap();
fs::write(dir.join(CHECK_FILE), "#!/bin/sh\nexit 0\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = if check_exec { 0o755 } else { 0o644 };
fs::set_permissions(dir.join(CHECK_FILE), fs::Permissions::from_mode(mode)).unwrap();
}
}
#[test]
fn gueltige_aufgabe_wird_geladen() {
let base = tmp("gut");
let dir = base.join("B").join("b-05");
make_task(&dir, GUT, true);
let task = load_one(&dir).unwrap();
assert_eq!(task.meta.id, "b-05-bugfix-parser");
assert_eq!(task.meta.weight, 1.0);
assert_eq!(task.meta.check_timeout_s, 120);
let _ = fs::remove_dir_all(&base);
}
#[test]
fn fehlende_pflichtdatei_wird_gemeldet() {
let base = tmp("fehlt");
let dir = base.join("A").join("a-01");
make_task(&dir, GUT, true);
fs::remove_file(dir.join(CHECK_FILE)).unwrap();
let errs = load_one(&dir).unwrap_err();
assert!(errs.iter().any(|e| e.contains("check.sh")));
let _ = fs::remove_dir_all(&base);
}
#[test]
fn check_sh_ohne_ausfuehrungsrecht_wird_gemeldet() {
let base = tmp("exec");
let dir = base.join("A").join("a-01");
make_task(&dir, GUT, false);
let errs = load_one(&dir).unwrap_err();
assert!(errs.iter().any(|e| e.contains("nicht ausführbar")));
let _ = fs::remove_dir_all(&base);
}
#[test]
fn ungueltige_gruppe_und_unbekannter_schluessel() {
let base = tmp("toml");
let dir = base.join("X").join("x-01");
let toml = GUT.replace("group = \"B\"", "group = \"Z\"") + "unbekannt = 1\n";
make_task(&dir, &toml, true);
let errs = load_one(&dir).unwrap_err();
assert!(errs.iter().any(|e| e.contains("unbekannt") || e.contains("kein gültiges TOML")));
let _ = fs::remove_dir_all(&base);
}
#[test]
fn image_namen_werden_geprueft() {
for ok in ["cb-python:latest", "docker.io/library/python:3.12-slim", "localhost/cb-x@sha256:abc"] {
assert!(validate_image(ok).is_ok(), "{ok}");
}
for bad in ["", "--privileged", "-v", "img name", "img;rm", "img\nx", "a$b", "--mount=type=bind,src=/home"] {
assert!(validate_image(bad).is_err(), "{bad:?} sollte abgelehnt werden");
}
assert!(validate_image(&"a".repeat(201)).is_err());
}
#[test]
fn ungueltige_zahlen_werden_gemeldet() {
let meta: TaskToml = toml::from_str(&GUT.replace("max_steps = 25", "max_steps = 0")).unwrap();
assert!(validate_meta(&meta).iter().any(|e| e.contains("max_steps")));
}
#[test]
fn load_all_trennt_gute_und_schlechte_aufgaben() {
let base = tmp("all");
make_task(&base.join("B").join("b-05"), GUT, true);
fs::create_dir_all(base.join("A").join("a-01")).unwrap(); // leer, also kaputt
let report = load_all(&base);
assert_eq!(report.tasks.len(), 1);
assert_eq!(report.errors.len(), 1);
assert!(report.errors[0].dir.ends_with("a-01"));
let _ = fs::remove_dir_all(&base);
}
/// Die mitgelieferten Aufgaben im Repo müssen gültig sein.
#[test]
fn repo_aufgaben_sind_gueltig() {
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("tasks");
let report = load_all(&dir);
assert!(report.errors.is_empty(), "{:?}", report.errors);
let ids: Vec<&str> = report.tasks.iter().map(|t| t.meta.id.as_str()).collect();
for expected in ["a-01", "a-02", "a-03", "b-04", "b-05", "b-06"] {
assert!(ids.contains(&expected), "fehlt: {expected}, gefunden: {ids:?}");
}
}
#[test]
fn fehlender_aufgabenordner_ist_leer_nicht_fehler() {
let report = load_all(Path::new("/gibt/es/nicht/cb-test"));
assert!(report.tasks.is_empty() && report.errors.is_empty());
}
}

43
src-tauri/tauri.conf.json Normal file
View File

@ -0,0 +1,43 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "coding-bench",
"version": "0.1.0",
"identifier": "org.wlkns.codingbench",
"build": {
"beforeDevCommand": "npm run dev",
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "npm run build",
"frontendDist": "../build"
},
"app": {
"windows": [
{
"title": "coding-bench",
"width": 800,
"height": 600
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": "all",
"linux": {
"deb": {
"depends": ["podman"],
"files": {
"/usr/share/coding-bench/tasks": "../tasks"
}
}
},
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}

160
src/app.css Normal file
View File

@ -0,0 +1,160 @@
:root {
color-scheme: dark;
--bg: #0f1115;
--bg-glow: rgba(255, 155, 69, 0.10);
--surface: #181b21;
--surface-2: #222630;
--text: #eceff4;
--muted: #9099a8;
--border: #2b303a;
--accent: #ff9b45;
--accent-soft: rgba(255, 155, 69, 0.14);
--accent-text: #1a1005;
--danger: #ff7b72;
--ok: #6fd18a;
--gold: #ffcf5c;
--silver: #c3cad6;
--bronze: #d9915a;
--pct-l: 58%;
--radius: 14px;
--shadow: 0 6px 24px rgba(0, 0, 0, 0.35);
font-family: Inter, "Segoe UI", system-ui, -apple-system, sans-serif;
font-size: 15px;
line-height: 1.5;
color: var(--text);
background: var(--bg);
-webkit-text-size-adjust: 100%;
}
@media (prefers-color-scheme: light) {
:root {
color-scheme: light;
--pct-l: 38%;
--bg: #f6f3ef;
--bg-glow: rgba(255, 155, 69, 0.16);
--surface: #ffffff;
--surface-2: #f0ebe4;
--text: #1d1a17;
--muted: #6b645c;
--border: #e2dbd2;
--accent: #f08a2c;
--accent-soft: rgba(240, 138, 44, 0.14);
--accent-text: #ffffff;
--danger: #c0392b;
--ok: #2e8b57;
--gold: #d49a00;
--silver: #8a93a1;
--bronze: #b8691f;
--shadow: 0 6px 20px rgba(60, 40, 20, 0.10);
}
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
background: radial-gradient(ellipse 70rem 28rem at 50% -8rem, var(--bg-glow), transparent), var(--bg);
color: var(--text);
}
h1, h2, h3 {
line-height: 1.25;
margin: 0 0 0.6rem;
}
h2 { font-size: 1.25rem; letter-spacing: -0.01em; }
h3 { font-size: 1rem; }
button {
font: inherit;
padding: 0.45rem 0.9rem;
border-radius: 10px;
border: 1px solid var(--border);
background: var(--surface-2);
transition: border-color 0.12s, transform 0.12s, background 0.12s;
color: var(--text);
cursor: pointer;
}
button:hover:not(:disabled) { border-color: var(--accent); }
button:disabled { opacity: 0.5; cursor: not-allowed; }
button.primary {
background: linear-gradient(180deg, color-mix(in srgb, var(--accent) 88%, white), var(--accent));
color: var(--accent-text);
border-color: var(--accent);
font-weight: 600;
}
button.danger { color: var(--danger); }
button.link {
background: none;
border: none;
padding: 0;
color: var(--accent);
text-decoration: underline;
}
input, select, textarea {
font: inherit;
padding: 0.4rem 0.55rem;
border-radius: 8px;
border: 1px solid var(--border);
background: var(--surface);
color: var(--text);
min-width: 0;
}
input:focus, select:focus, textarea:focus {
outline: 2px solid var(--accent);
outline-offset: -1px;
}
code, pre {
font-family: ui-monospace, "JetBrains Mono", Menlo, monospace;
font-size: 0.88em;
}
.card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 1.2rem 1.4rem;
margin-bottom: 1.1rem;
box-shadow: var(--shadow);
}
.muted { color: var(--muted); }
.error { color: var(--danger); }
.ok { color: var(--ok); }
.chip {
display: inline-block;
padding: 0.05rem 0.55rem;
border-radius: 999px;
font-size: 0.8rem;
background: var(--surface-2);
border: 1px solid var(--border);
}
.chip.ok { background: color-mix(in srgb, var(--ok) 16%, transparent); border-color: transparent; }
.chip.error { background: color-mix(in srgb, var(--danger) 16%, transparent); border-color: transparent; }
table {
width: 100%;
border-collapse: collapse;
}
th, td {
text-align: left;
padding: 0.45rem 0.6rem;
border-bottom: 1px solid var(--border);
vertical-align: middle;
}
th {
font-size: 0.8rem;
font-weight: 600;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.03em;
}
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
input[type="checkbox"], input[type="radio"] { accent-color: var(--accent); }
.small { font-size: 0.8rem; }

14
src/app.html Normal file
View File

@ -0,0 +1,14 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8" />
<link rel="icon" type="image/svg+xml" href="%sveltekit.assets%/favicon.svg" />
<link rel="icon" type="image/png" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>coding-bench</title>
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

603
src/lib/BenchPanel.svelte Normal file
View File

@ -0,0 +1,603 @@
<script lang="ts">
import { onMount, onDestroy } from "svelte";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import {
api,
errorLabel,
fmtPct,
groupLabel,
isInfrastructure,
pctColor,
type BatchEvent,
type LoadReport,
type ModelInfo,
type Ranking,
type TaskInfo,
} from "$lib/api";
let {
models,
tasks,
ongotosettings,
onfinished,
}: {
models: ModelInfo[];
tasks: LoadReport | null;
ongotosettings: () => void;
onfinished: (batchId: number) => void;
} = $props();
let chosenModels = $state<string[]>([]);
let chosenTasks = $state<string[]>([]);
let repeats = $state(1);
let running = $state(false);
let error = $state("");
let progress = $state<{ done: number; total: number } | null>(null);
let log = $state<{ text: string; cls: string }[]>([]);
let current = $state("");
let finishedBatch = $state<number | null>(null);
let cancelled = $state(false);
let expanded = $state<string[]>([]);
// Was die letzte Messung ergeben hat: Grundlage für „zuletzt“ und die Zeitschätzung.
let last = $state<Ranking | null>(null);
// Stand je Modell und Aufgabe im aktuellen Lauf.
type Cell = { state: "planned" | "running" | "done" | "skipped" | "infra"; n: number; sum: number; cls: string };
let cells = $state<Record<string, Cell>>({});
const key = (model: string, task: string) => `${model}\u0001${task}`;
let unlisten: UnlistenFn | null = null;
async function loadLast() {
try {
const b = await api.batches();
last = b.length > 0 ? await api.ranking(b[0].id) : null;
} catch {
last = null;
}
}
onMount(async () => {
loadLast();
unlisten = await listen<BatchEvent>("batch-event", (ev) => onEvent(ev.payload));
});
onDestroy(() => unlisten?.());
function onEvent(e: BatchEvent) {
if (e.kind === "progress") {
progress = { done: e.done, total: e.total };
return;
}
if (e.kind === "model_unavailable") {
log.push({ text: `${e.model}: nicht erreichbar (${e.reason})`, cls: "error" });
for (const t of chosenTasks) {
const c = cells[key(e.model, t)];
if (c && c.state !== "done") c.state = "infra";
}
return;
}
const label = `${e.model} · ${e.task} · Durchlauf ${e.repeat}`;
const c = cells[key(e.model, e.task)];
if (e.kind === "run_started") {
current = label;
if (c) c.state = "running";
} else if (e.kind === "run_skipped") {
log.push({ text: `übersprungen: ${label}`, cls: "muted" });
if (c && c.state === "planned") c.state = "skipped";
} else if (e.kind === "run_finished") {
const ok = e.class === "ok";
log.push({
text: `${errorLabel(e.class)}: ${label}, ${Math.round(e.score * 100)} %`,
cls: ok ? "ok" : "error",
});
current = "";
if (c) {
if (isInfrastructure(e.class)) {
c.state = "infra";
c.cls = e.class;
} else {
c.n += 1;
c.sum += e.score;
c.state = c.n >= repeats ? "done" : "planned";
c.cls = e.class;
}
}
}
}
// Aufgaben nach Bereich gruppiert.
let byGroup = $derived.by(() => {
const m = new Map<string, TaskInfo[]>();
for (const t of tasks?.tasks ?? []) {
if (!m.has(t.group)) m.set(t.group, []);
m.get(t.group)!.push(t);
}
return [...m.entries()].sort((a, b) => a[0].localeCompare(b[0]));
});
function toggle(list: string[], id: string): string[] {
return list.includes(id) ? list.filter((x) => x !== id) : [...list, id];
}
function groupAll(group: string, on: boolean) {
const ids = (byGroup.find(([g]) => g === group)?.[1] ?? []).map((t) => t.id);
chosenTasks = on ? [...new Set([...chosenTasks, ...ids])] : chosenTasks.filter((id) => !ids.includes(id));
}
function allModels(on: boolean) {
chosenModels = on ? models.map((m) => m.name) : [];
}
function lastTask(id: string): { models: number; mean: number } | null {
const cs = last?.cells.filter((c) => c.task_id === id) ?? [];
if (cs.length === 0) return null;
return { models: cs.length, mean: (100 * cs.reduce((a, c) => a + c.mean_score, 0)) / cs.length };
}
function lastCell(model: string, task: string): number | null {
const c = last?.cells.find((c) => c.model === model && c.task_id === task);
return c ? c.mean_score * 100 : null;
}
function lastRank(model: string) {
return last?.models.find((m) => m.model === model) ?? null;
}
let totalRuns = $derived(chosenModels.length * chosenTasks.length * repeats);
let canStart = $derived(!running && chosenModels.length > 0 && chosenTasks.length > 0 && repeats >= 1);
// Geschätzte Dauer aus den Median-Laufzeiten früherer Läufe. Fehlt ein Modell, zählt der Schnitt der übrigen.
let estimate = $derived.by(() => {
const known = chosenModels.map((m) => lastRank(m)?.median_duration_ms).filter((x): x is number => typeof x === "number" && x > 0);
if (known.length === 0 || totalRuns === 0) return null;
const avg = known.reduce((a, b) => a + b, 0) / known.length;
const ms = chosenModels.reduce((sum, m) => sum + (lastRank(m)?.median_duration_ms || avg) * chosenTasks.length * repeats, 0);
return { minutes: Math.max(1, Math.round(ms / 60000)), basis: known.length, of: chosenModels.length };
});
function chosenTaskInfos(): TaskInfo[] {
return (tasks?.tasks ?? []).filter((t) => chosenTasks.includes(t.id));
}
async function start(resumeBatch: number | null = null) {
error = "";
log = [];
progress = null;
finishedBatch = null;
cancelled = false;
cells = {};
for (const m of chosenModels) for (const t of chosenTaskInfos()) cells[key(m, t.id)] = { state: "planned", n: 0, sum: 0, cls: "" };
running = true;
try {
const s = await api.startBatch($state.snapshot(chosenModels), $state.snapshot(chosenTasks), repeats, "", resumeBatch);
finishedBatch = s.batch_id;
cancelled = s.cancelled;
} catch (e) {
error = String(e);
} finally {
running = false;
current = "";
loadLast();
}
}
// Offen ist, was nicht fertig gewertet wurde: abgebrochen oder durch einen Ausfall nicht gewertet.
let openCells = $derived(Object.values(cells).filter((c) => c.state !== "done" && c.state !== "skipped").length);
let canResume = $derived(!running && finishedBatch !== null && openCells > 0);
function cellOf(model: string, task: string): Cell | undefined {
return cells[key(model, task)];
}
</script>
{#if models.length === 0}
<section class="card empty">
<h2>Noch kein Modell angebunden</h2>
<p class="muted">Bevor ein Benchmark laufen kann, braucht coding-bench mindestens ein Modell.</p>
<ol class="muted steps">
<li>Modell mit Adapter und Server-URL anlegen</li>
<li>Container-Image bauen (einmalig)</li>
<li>Hier Modelle und Aufgaben wählen und starten</li>
</ol>
<button class="primary" onclick={ongotosettings}>Modell in den Einstellungen anlegen</button>
</section>
{:else}
<section class="card">
<div class="head">
<h2>1. Modelle</h2>
<button class="link" disabled={running} onclick={() => allModels(true)}>alle</button>
<button class="link" disabled={running} onclick={() => allModels(false)}>keine</button>
</div>
<div class="model-grid">
{#each models as m (m.name)}
{@const r = lastRank(m.name)}
<label class="mcard" class:on={chosenModels.includes(m.name)}>
<input
type="checkbox"
checked={chosenModels.includes(m.name)}
disabled={running}
onchange={() => (chosenModels = toggle(chosenModels, m.name))}
/>
<span class="mtext">
<strong>{m.name}</strong>
<span class="muted small">{m.adapter === "ollama" ? "Ollama" : "OpenAI-kompatibel"} · {m.url}</span>
{#if r}
<span class="small" style:color={pctColor(r.total_percent)}>zuletzt {fmtPct(r.total_percent)} gesamt</span>
{:else}
<span class="muted small">noch nicht gemessen</span>
{/if}
{#if m.api_key_env && !m.api_key_set}
<span class="error small">Schlüssel-Variable {m.api_key_env} nicht gesetzt</span>
{/if}
</span>
</label>
{/each}
</div>
</section>
<section class="card">
<h2>2. Aufgaben</h2>
{#if !tasks}
<p class="muted">Lade Aufgaben …</p>
{:else if tasks.tasks.length === 0}
<p class="error">Keine gültigen Aufgaben gefunden.</p>
{/if}
{#each byGroup as [group, list] (group)}
<div class="group">
<div class="head">
<h3><span class="gbadge">{group}</span> {groupLabel(group)} <span class="muted">({list.length})</span></h3>
<button class="link" disabled={running} onclick={() => groupAll(group, true)}>alle</button>
<button class="link" disabled={running} onclick={() => groupAll(group, false)}>keine</button>
</div>
<div class="task-grid">
{#each list as t (t.id)}
{@const lt = lastTask(t.id)}
{@const open = expanded.includes(t.id)}
<div class="tcard" class:on={chosenTasks.includes(t.id)}>
<label class="thead">
<input
type="checkbox"
checked={chosenTasks.includes(t.id)}
disabled={running}
onchange={() => (chosenTasks = toggle(chosenTasks, t.id))}
/>
<span><strong>{t.title}</strong> <span class="muted small">{t.id}</span></span>
</label>
<p class="desc" class:clamp={!open}>{t.prompt.trim() || "Keine Beschreibung."}</p>
<div class="chips">
<span class="chip" title="Höchstzahl der Agentenschritte">≤ {t.max_steps} Schritte</span>
<span class="chip" title="Zeitlimit je Lauf">{t.timeout_s} s</span>
{#if t.weight !== 1}<span class="chip" title="Gewicht in der Bewertung">Gewicht {t.weight}</span>{/if}
<span class="chip" title="Container-Image">{t.image}</span>
</div>
<div class="tfoot">
{#if lt}
<span class="small" style:color={pctColor(lt.mean)}>zuletzt ∅ {fmtPct(lt.mean)} ({lt.models} Modell{lt.models === 1 ? "" : "e"})</span>
{:else}
<span class="muted small">noch nie gelaufen</span>
{/if}
<button class="link" onclick={() => (expanded = toggle(expanded, t.id))}>{open ? "weniger" : "Aufgabentext"}</button>
</div>
</div>
{/each}
</div>
</div>
{/each}
{#if tasks && tasks.errors.length > 0}
<details>
<summary class="error">{tasks.errors.length} Aufgabe(n) mit Fehlern</summary>
<ul>
{#each tasks.errors as e (e.dir)}
<li><code>{e.dir}</code>: {e.message}</li>
{/each}
</ul>
</details>
{/if}
</section>
{#if chosenModels.length > 0 && chosenTasks.length > 0}
<section class="card">
<h2>Plan und Stand</h2>
<p class="muted small">
Jede Zelle ist ein Modell bei einer Aufgabe. Vor dem Start steht dort, was zuletzt gemessen wurde. Beim Lauf füllt sie
sich live.
</p>
<div class="scroll">
<table class="plan">
<thead>
<tr>
<th>Modell</th>
{#each chosenTaskInfos() as t (t.id)}<th class="num" title={t.title}>{t.id}</th>{/each}
</tr>
</thead>
<tbody>
{#each chosenModels as m (m)}
<tr>
<td>{m}</td>
{#each chosenTaskInfos() as t (t.id)}
{@const c = cellOf(m, t.id)}
{@const lc = lastCell(m, t.id)}
<td class="num cell" class:running={c?.state === "running"}>
{#if c?.state === "done"}
{@const p = (100 * c.sum) / c.n}
<span class="done" style:background={`color-mix(in srgb, ${pctColor(p)} 30%, transparent)`}>{fmtPct(p)}</span>
{:else if c?.state === "running"}
<span class="pulse">läuft …</span>
{:else if c?.state === "infra"}
<span class="error small" title="Server oder Umgebung ausgefallen, nicht gewertet">nicht gewertet</span>
{:else if c?.state === "skipped"}
<span class="muted small">schon vorhanden</span>
{:else if c?.state === "planned"}
<span class="muted small">geplant{c.n > 0 ? ` ${c.n}/${repeats}` : ""}</span>
{:else if lc !== null}
<span class="muted small">zuletzt {fmtPct(lc)}</span>
{:else}
<span class="muted small">neu</span>
{/if}
</td>
{/each}
</tr>
{/each}
</tbody>
</table>
</div>
</section>
{/if}
{#if log.length > 0 || error || finishedBatch !== null}
<section class="card">
<h2>Verlauf</h2>
{#if error}<p class="error">{error}</p>{/if}
{#if finishedBatch !== null}
<p>
{cancelled ? "Abgebrochen." : openCells > 0 ? `Fertig, aber ${openCells} Zelle(n) offen oder nicht gewertet.` : "Fertig."}
<button class="link" onclick={() => onfinished(finishedBatch!)}>Ergebnisse ansehen</button>
{#if canResume}
· <button class="link" onclick={() => start(finishedBatch)}>Fortsetzen</button>
{/if}
</p>
{/if}
{#if log.length > 0}
<ul class="log">
{#each log as l, i (i)}
<li class={l.cls}>{l.text}</li>
{/each}
</ul>
{/if}
</section>
{/if}
<div class="startbar">
<div class="summary">
{#if totalRuns > 0}
<strong>{totalRuns} Läufe</strong>
<span class="muted">{chosenModels.length} Modell(e) × {chosenTasks.length} Aufgabe(n) × {repeats}</span>
{#if estimate}
<span class="muted" title="Median-Laufzeit früherer Läufe, {estimate.basis} von {estimate.of} Modellen gemessen">
≈ {estimate.minutes} min
</span>
{:else}
<span class="muted">Dauer unbekannt, noch keine Messung</span>
{/if}
{:else}
<span class="muted">Wähle Modelle und Aufgaben.</span>
{/if}
{#if repeats < 3 && totalRuns > 0}
<span class="warn small">Bei weniger als 3 Durchläufen können Unterschiede zwischen Modellen Zufall sein.</span>
{/if}
</div>
<label class="rep">
Durchläufe
<input type="number" min="1" max="20" bind:value={repeats} disabled={running} />
</label>
<button class="primary" onclick={() => start()} disabled={!canStart}>Benchmark starten</button>
<button class="danger" onclick={() => api.cancelBatch()} disabled={!running}>Abbrechen</button>
{#if progress}
<div class="progress">
<div class="bar" role="progressbar" aria-valuenow={progress.done} aria-valuemax={progress.total}>
<div class="fill" style:width="{progress.total ? (100 * progress.done) / progress.total : 0}%"></div>
</div>
<span class="small muted">{progress.done} von {progress.total}{current ? ` · läuft: ${current}` : ""}</span>
</div>
{/if}
</div>
{/if}
<style>
.head {
display: flex;
align-items: baseline;
gap: 0.8rem;
margin-bottom: 0.6rem;
}
.head h2,
.head h3 {
flex: 1;
margin: 0;
}
.small {
font-size: 0.8rem;
}
.warn {
color: var(--accent);
}
.empty .steps {
padding-left: 1.2rem;
}
.model-grid,
.task-grid {
display: grid;
gap: 0.7rem;
}
.model-grid {
grid-template-columns: repeat(auto-fill, minmax(17rem, 1fr));
}
.task-grid {
grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr));
}
.mcard,
.tcard {
border: 1px solid var(--border);
border-radius: 12px;
background: var(--surface-2);
padding: 0.75rem 0.9rem;
transition: border-color 0.12s, background 0.12s;
}
.mcard {
display: flex;
gap: 0.7rem;
align-items: flex-start;
cursor: pointer;
}
.mcard.on,
.tcard.on {
border-color: var(--accent);
background: color-mix(in srgb, var(--accent) 8%, var(--surface-2));
}
.mtext {
display: flex;
flex-direction: column;
gap: 0.1rem;
min-width: 0;
overflow-wrap: anywhere;
}
.group {
margin-bottom: 1.1rem;
}
.gbadge {
display: inline-grid;
place-items: center;
width: 1.5rem;
height: 1.5rem;
border-radius: 6px;
background: var(--accent);
color: var(--accent-text);
font-size: 0.8rem;
font-weight: 800;
margin-right: 0.3rem;
}
.thead input,
.mcard input {
flex-shrink: 0;
}
.thead .small {
white-space: nowrap;
}
.thead {
display: flex;
gap: 0.6rem;
align-items: baseline;
cursor: pointer;
}
.desc {
margin: 0.5rem 0;
font-size: 0.88rem;
color: var(--muted);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.desc.clamp {
display: -webkit-box;
-webkit-line-clamp: 3;
line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
}
.tfoot {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-top: 0.5rem;
}
.scroll {
overflow-x: auto;
}
.plan .cell {
white-space: nowrap;
}
.done {
display: inline-block;
padding: 0.05rem 0.5rem;
border-radius: 6px;
font-weight: 600;
}
.pulse {
color: var(--accent);
animation: pulse 1.1s ease-in-out infinite;
}
@keyframes pulse {
50% {
opacity: 0.35;
}
}
.log {
list-style: none;
padding: 0.6rem;
margin: 0.8rem 0 0;
max-height: 14rem;
overflow-y: auto;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 8px;
font-family: ui-monospace, Menlo, monospace;
font-size: 0.85rem;
}
.startbar {
position: sticky;
bottom: 0.8rem;
z-index: 4;
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.7rem 1rem;
padding: 0.8rem 1.1rem;
background: color-mix(in srgb, var(--surface) 90%, transparent);
backdrop-filter: blur(10px);
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: var(--shadow);
}
.summary {
flex: 1;
min-width: 14rem;
display: flex;
flex-wrap: wrap;
gap: 0.1rem 0.8rem;
align-items: baseline;
}
.summary .warn {
flex-basis: 100%;
}
.rep {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.85rem;
color: var(--muted);
}
.rep input {
width: 4.2rem;
color: var(--text);
}
.progress {
flex-basis: 100%;
}
.bar {
height: 8px;
background: var(--bg);
border-radius: 999px;
overflow: hidden;
margin-bottom: 0.25rem;
}
.fill {
height: 100%;
background: var(--accent);
transition: width 0.3s;
}
</style>

View File

@ -0,0 +1,269 @@
<script lang="ts">
import { onMount } from "svelte";
import { revealItemInDir } from "@tauri-apps/plugin-opener";
import { api, groupLabel, type BatchInfo, type ExportResult, type ImportSummary, type LoadReport, type TaskInfo } from "$lib/api";
let { tasks, onimported }: { tasks: LoadReport | null; onimported: (batchId: number) => void } = $props();
// 1. Exportieren
let chosen = $state<string[]>([]);
let repeats = $state(1);
let exporting = $state(false);
let exported = $state<ExportResult | null>(null);
let exportError = $state("");
let byGroup = $derived.by(() => {
const m = new Map<string, TaskInfo[]>();
for (const t of tasks?.tasks ?? []) {
if (!m.has(t.group)) m.set(t.group, []);
m.get(t.group)!.push(t);
}
return [...m.entries()].sort((a, b) => a[0].localeCompare(b[0]));
});
function toggle(id: string) {
chosen = chosen.includes(id) ? chosen.filter((x) => x !== id) : [...chosen, id];
}
async function doExport() {
exporting = true;
exportError = "";
exported = null;
try {
exported = await api.exportExternal($state.snapshot(chosen), repeats);
} catch (e) {
exportError = String(e);
} finally {
exporting = false;
}
}
async function reveal(path: string) {
try {
await revealItemInDir(path);
} catch {
// Ohne Dateimanager bleibt der Pfad als Text sichtbar.
}
}
// 3. Importieren
let batches = $state<BatchInfo[]>([]);
let dir = $state("");
let model = $state("Claude Code (extern)");
let batchId = $state<number | null>(null);
let importing = $state(false);
let summary = $state<ImportSummary | null>(null);
let importError = $state("");
onMount(async () => {
try {
batches = await api.batches();
if (batches.length > 0) batchId = batches[0].id;
} catch {
batches = [];
}
});
// Nach einem Export liegt der Pfad nahe, den wir nach dem Lösen wieder brauchen.
$effect(() => {
if (exported && !dir) dir = exported.dir;
});
async function doImport() {
if (batchId === null) return;
importing = true;
importError = "";
summary = null;
try {
summary = await api.importExternal(dir.trim(), model, batchId);
} catch (e) {
importError = String(e);
} finally {
importing = false;
}
}
</script>
<section class="card">
<h2>Referenz von Hand erzeugen</h2>
<p class="muted">
Modelle, die du nicht anbinden kannst (z. B. Claude über ein Abo), löst du mit einem Werkzeug deiner Wahl, etwa Claude Code.
coding-bench exportiert die Aufgaben als Ordner, prüft deine Ergebnisse mit derselben <code>check.sh</code> wie bei lokalen
Modellen und zeigt das Ergebnis als Referenz im Ranking.
</p>
<p class="notice">
<strong>Achtung, anderes Harness:</strong> Die Referenz misst „Modell plus dein Werkzeug“. Es gibt kein Schrittlimit, kein
Zeitlimit, und das Werkzeug hat eigene Tools und Anweisungen. Der Strich im Ranking ist ein Orientierungswert, kein
Gleichstand der Bedingungen.
</p>
</section>
<section class="card">
<h2>1. Aufgaben exportieren</h2>
{#if !tasks || tasks.tasks.length === 0}
<p class="muted">Keine Aufgaben geladen.</p>
{/if}
{#each byGroup as [group, list] (group)}
<h3><span class="gbadge">{group}</span> {groupLabel(group)}</h3>
<div class="list">
{#each list as t (t.id)}
<label class="choice">
<input type="checkbox" checked={chosen.includes(t.id)} onchange={() => toggle(t.id)} />
<span><strong>{t.title}</strong> <span class="muted small">{t.id}</span></span>
</label>
{/each}
</div>
{/each}
<div class="row">
<label class="rep">
Durchläufe je Aufgabe
<input type="number" min="1" max="10" bind:value={repeats} />
</label>
<span class="muted small">
{chosen.length * repeats} Sitzung(en) von Hand. Mit weniger als 3 Durchläufen ist die Referenz nur ein grober Hinweis.
</span>
<span class="spacer"></span>
<button class="primary" onclick={doExport} disabled={chosen.length === 0 || repeats < 1 || exporting}>
{exporting ? "exportiere …" : "Exportieren"}
</button>
</div>
{#if exportError}<p class="error">{exportError}</p>{/if}
{#if exported}
<p class="ok">
{exported.folders} Ordner angelegt:
<code>{exported.dir}</code>
<button class="link" onclick={() => reveal(exported!.dir)}>im Dateimanager zeigen</button>
</p>
{/if}
</section>
<section class="card">
<h2>2. Lösen lassen</h2>
<ol class="muted steps">
<li>Im Exportordner steht eine <code>ANLEITUNG.md</code>. Lies sie kurz.</li>
<li>
Pro Durchlauf eine frische Sitzung in <code>&lt;aufgabe&gt;/run-&lt;n&gt;/arbeit/</code> starten und den Inhalt von
<code>AUFGABE.md</code> als Auftrag einfügen.
</li>
<li>Kein Web, keine Hinweise, nur den Ordner <code>arbeit/</code> verändern lassen.</li>
</ol>
</section>
<section class="card">
<h2>3. Ergebnis importieren</h2>
<div class="grid">
<label class="wide">
Exportordner mit den Ergebnissen
<input bind:value={dir} placeholder="/home/…/exports/referenz-…" />
</label>
<label>
Name der Referenz
<input bind:value={model} />
</label>
<label>
In welchen Batch?
<select bind:value={batchId} disabled={batches.length === 0}>
{#each batches as b (b.id)}
<option value={b.id}>Batch {b.id} · {b.created_at.slice(0, 16)} · {b.runs} Läufe</option>
{/each}
</select>
</label>
</div>
{#if batches.length === 0}
<p class="muted small">Es gibt noch keinen Batch. Starte zuerst einen Benchmark mit lokalen Modellen, damit die Referenz einen Vergleich hat.</p>
{/if}
<div class="row">
<span class="muted small">Die App kopiert die Ergebnisse in einen Container und lässt dort <code>check.sh</code> laufen. Bereits importierte Läufe mit gleichem Namen werden ersetzt.</span>
<span class="spacer"></span>
<button class="primary" onclick={doImport} disabled={importing || !dir.trim() || !model.trim() || batchId === null}>
{importing ? "prüfe …" : "Prüfen und speichern"}
</button>
</div>
{#if importError}<p class="error">{importError}</p>{/if}
{#if summary}
<p class={summary.imported > 0 ? "ok" : "error"}>
{summary.imported} Lauf/Läufe geprüft, {summary.passed} bestanden.
{#if batchId !== null}<button class="link" onclick={() => onimported(batchId!)}>Ergebnisse ansehen</button>{/if}
</p>
{#if summary.skipped.length > 0}
<details open>
<summary class="error">{summary.skipped.length} Ordner nicht geprüft</summary>
<ul>
{#each summary.skipped as s (s)}<li>{s}</li>{/each}
</ul>
</details>
{/if}
{/if}
</section>
<style>
.notice {
border: 1px solid color-mix(in srgb, var(--accent) 50%, var(--border));
background: var(--accent-soft);
border-radius: 10px;
padding: 0.6rem 0.9rem;
margin: 0.8rem 0 0;
font-size: 0.9rem;
}
.gbadge {
display: inline-grid;
place-items: center;
width: 1.5rem;
height: 1.5rem;
border-radius: 6px;
background: var(--accent);
color: var(--accent-text);
font-size: 0.8rem;
font-weight: 800;
margin-right: 0.3rem;
}
.list {
display: grid;
gap: 0.25rem;
margin-bottom: 0.8rem;
}
.choice {
display: flex;
gap: 0.6rem;
align-items: baseline;
}
.row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.7rem 1rem;
margin-top: 0.9rem;
}
.spacer {
flex: 1;
}
.rep,
.grid label {
display: flex;
flex-direction: column;
gap: 0.2rem;
font-size: 0.85rem;
color: var(--muted);
}
.rep input {
width: 5rem;
color: var(--text);
}
.grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.6rem 0.8rem;
}
.grid .wide {
grid-column: 1 / -1;
}
.grid input,
.grid select {
color: var(--text);
font-size: 1rem;
}
.steps {
padding-left: 1.2rem;
margin: 0;
}
</style>

504
src/lib/ResultsPanel.svelte Normal file
View File

@ -0,0 +1,504 @@
<script lang="ts">
import { onMount, untrack } from "svelte";
import {
api,
errorLabel,
fmtDuration,
fmtPct,
fmtTps,
isInfrastructure,
groupLabel,
pctColor,
type BatchInfo,
type Ranking,
type RunRow,
type StepRow,
} from "$lib/api";
let { selected = $bindable(null) }: { selected: number | null } = $props();
let batches = $state<BatchInfo[]>([]);
let ranking = $state<Ranking | null>(null);
let rows = $state<RunRow[]>([]);
let error = $state("");
let loading = $state(false);
let detail = $state<{ run: RunRow; steps: StepRow[] } | null>(null);
let showRuns = $state(false);
async function loadBatches() {
try {
batches = await api.batches();
if (selected === null && batches.length > 0) selected = batches[0].id;
} catch (e) {
error = String(e);
}
}
async function loadBatch(id: number | null) {
ranking = null;
rows = [];
detail = null;
if (id === null) return;
loading = true;
error = "";
try {
[ranking, rows] = await Promise.all([api.ranking(id), api.results(id)]);
} catch (e) {
error = String(e);
} finally {
loading = false;
}
}
onMount(loadBatches);
// Beim Wechsel des Batches neu laden. Neue Batches erscheinen nach dem Lauf in der Liste.
$effect(() => {
const id = selected;
untrack(() => {
loadBatch(id);
if (id !== null && !batches.some((b) => b.id === id)) loadBatches();
});
});
async function showSteps(run: RunRow) {
if (selected === null) return;
detail = { run, steps: await api.steps(selected, run) };
}
// Angebundene Modelle zuerst, dann die Referenzen (von Hand gelöst, ohne Rang).
let ordered = $derived(
ranking ? [...ranking.models.filter((m) => !m.external), ...ranking.models.filter((m) => m.external)] : [],
);
let bestRef = $derived(ranking?.models.find((m) => m.external) ?? null);
function refPct(group: string): number | null {
return bestRef?.groups.find((g) => g.group === group)?.percent ?? null;
}
// Kleinste Zahl gewerteter Durchläufe in einer Zelle der Matrix.
let minRepeats = $derived(ranking && ranking.cells.length > 0 ? Math.min(...ranking.cells.map((c) => c.runs)) : 0);
async function openCell(model: string, task: string) {
const r = rows.find((x) => x.model === model && x.task_id === task);
if (!r) return;
try {
await showSteps(r);
setTimeout(() => document.getElementById("run-detail")?.scrollIntoView({ behavior: "smooth", block: "start" }), 50);
} catch (e) {
error = String(e);
}
}
function cell(model: string, task: string) {
return ranking?.cells.find((c) => c.model === model && c.task_id === task);
}
function batchLabel(b: BatchInfo): string {
return `Batch ${b.id} · ${b.created_at.slice(0, 16)} · ${b.runs} Läufe`;
}
// Bereiche mit wenigen Aufgaben sind nur grobe Hinweise.
const FEW_TASKS = 3;
</script>
<section class="card">
<div class="head">
<h2>Bewertung</h2>
{#if batches.length > 0}
<select bind:value={selected} aria-label="Batch wählen">
{#each batches as b (b.id)}
<option value={b.id}>{batchLabel(b)}</option>
{/each}
</select>
{/if}
</div>
{#if error}<p class="error">{error}</p>{/if}
{#if batches.length === 0 && !error}
<p class="muted">Noch keine Ergebnisse. Starte im Reiter „Benchmark“ einen Lauf.</p>
{/if}
{#if loading}<p class="muted">Lade …</p>{/if}
{#if ranking && ranking.models.length > 0}
<div class="board">
{#each ordered as m (m.model)}
<article class="mcard" class:ref={m.external} data-rank={m.rank}>
<div class="badge r{m.external ? 5 : Math.min(m.rank, 4)}" aria-label={m.external ? "Referenz" : `Platz ${m.rank}`}>
{m.external ? "R" : m.rank}
</div>
<div class="mhead">
<h3 class="mname">
{m.model}
{#if m.external}<span class="chip" title="Von Hand außerhalb der App gelöst, anderes Harness, zählt nicht im Rang">Referenz · extern</span>{/if}
</h3>
<div class="stats">
<span title="Bestandene Läufe">✔ {m.successes}/{m.runs}</span>
{#if !m.external}
<span title="Median der Laufzeit">⏱ {fmtDuration(m.median_duration_ms)}</span>
<span title="Tokens pro Sekunde: Tokens geteilt durch die gesamte Laufzeit eines Laufs, also inklusive Tool- und Prüfzeit. Nicht die reine Erzeugungsgeschwindigkeit.">⚡ {fmtTps(m.median_tps)}</span>
<span title="Durchschnittlich erzeugte Tokens je Lauf">∅ {Math.round(m.mean_completion_tokens)} Tokens</span>
{:else}
<span>Zeit und Tokens nicht gemessen</span>
{/if}
</div>
</div>
<div class="total">
<div class="pct big" style:color={pctColor(m.total_percent)}>{fmtPct(m.total_percent)}</div>
<div class="label">Gesamt</div>
</div>
<div class="groups">
{#each m.groups as g (g.group)}
<div class="g" title={groupLabel(g.group)}>
<div class="gtop">
<span><b>{g.group}</b> {groupLabel(g.group)}</span>
{#if g.percent === null}
<span class="muted">–</span>
{:else}
<span class="pct" style:color={pctColor(g.percent)}>{fmtPct(g.percent)}</span>
{/if}
</div>
<div class="meter">
{#if g.percent !== null}
<div class="f" style:width="{g.percent}%" style:background={pctColor(g.percent)}></div>
{/if}
{#if !m.external && refPct(g.group) !== null}
<div class="tick" style:left="{refPct(g.group)}%" title="Referenz {bestRef?.model}: {fmtPct(refPct(g.group))}"></div>
{/if}
</div>
{#if g.percent !== null}
<div class="n" class:few={g.tasks < FEW_TASKS} title={g.tasks < FEW_TASKS ? "Wenige Aufgaben: der Wert ist nur ein grober Hinweis." : ""}>
{g.tasks} Aufg.{g.tasks < FEW_TASKS ? " (grob)" : ""}
</div>
{/if}
</div>
{/each}
</div>
{#if m.weakest_group}
<div class="weak">Schwächster Bereich: {m.weakest_group} · {groupLabel(m.weakest_group)}</div>
{/if}
</article>
{/each}
</div>
{#if bestRef}
<p class="muted small legend">
<span class="tick-demo"></span> Strich im Balken = Referenz <strong>{bestRef.model}</strong> (extern, von Hand gelöst, anderes Harness).
</p>
{/if}
{#if minRepeats < 3}
<p class="notice">
Pro Aufgabe {minRepeats === 1 ? "gab es nur 1 Durchlauf" : `gab es nur ${minRepeats} Durchläufe`}. Dann können Unterschiede
zwischen Modellen Zufall sein, und die Rangfolge ist nur ein Hinweis. Für belastbare Werte mindestens 3 Durchläufe wählen.
</p>
{/if}
{#if ranking.excluded_runs > 0}
<p class="muted">
{ranking.excluded_runs} Lauf/Läufe sind nicht gewertet, weil der Modell-Server oder die Umgebung ausfiel. Sie
fließen nicht in die Prozentwerte ein. Beim Fortsetzen eines Batches werden sie wiederholt.
</p>
{/if}
<details class="how">
<summary>So wird bewertet</summary>
<ul>
<li>
Die Bewertung ist <strong>absolut</strong>, nicht im Vergleich zu einem Referenzmodell. 100 % heißt: alle
Prüfungen der Aufgaben bestanden.
</li>
<li>
Je Aufgabe zählt der Mittelwert der Durchläufe. Teilpunkte aus <code>check.sh</code> gehen anteilig ein.
</li>
<li>
Wert je Bereich: gewichteter Mittelwert der Aufgaben im Bereich. Gesamt: gewichteter Mittelwert über alle
Aufgaben des Batches. Die Gewichte stehen als <code>weight</code> in <code>task.toml</code>.
</li>
<li>Fehlt einem Modell ein Bereich, bleibt das Feld leer und zählt nicht in die Gesamtnote.</li>
<li>Die Reihenfolge richtet sich nach der Gesamtnote. Bei Gleichstand gewinnt die kürzere Median-Dauer.</li>
<li>Bereiche mit weniger als {FEW_TASKS} Aufgaben sind nur grobe Hinweise.</li>
</ul>
</details>
<h3>Aufgaben im Detail <span class="muted small">Zelle anklicken öffnet den Lauf</span></h3>
<div class="scroll">
<table class="matrix">
<thead>
<tr>
<th>Modell</th>
{#each ranking.tasks as t (t.id)}
<th class="num" title={groupLabel(t.group)}>{t.id}</th>
{/each}
</tr>
</thead>
<tbody>
{#each ranking.models as m (m.model)}
<tr>
<td>{m.model}</td>
{#each ranking.tasks as t (t.id)}
{@const c = cell(m.model, t.id)}
<td
class="num clickable"
onclick={() => openCell(m.model, t.id)}
style:background={c ? `color-mix(in srgb, ${pctColor(c.mean_score * 100)} 28%, transparent)` : ""}
title={c ? `${Math.round(c.mean_score * 100)} %, ${c.successes} von ${c.runs} bestanden` : "keine Läufe"}
>
{c ? `${Math.round(c.mean_score * 100)} %` : "–"}
</td>
{/each}
</tr>
{/each}
</tbody>
</table>
</div>
<h3>
Einzelne Läufe
<button class="link" onclick={() => (showRuns = !showRuns)}>{showRuns ? "ausblenden" : `anzeigen (${rows.length})`}</button>
</h3>
{#if showRuns}
<div class="scroll">
<table>
<thead>
<tr>
<th>Modell</th>
<th>Aufgabe</th>
<th class="num">Durchlauf</th>
<th>Ergebnis</th>
<th class="num">Score</th>
<th class="num">Schritte</th>
<th class="num">Dauer</th>
<th></th>
</tr>
</thead>
<tbody>
{#each rows as r (`${r.model}|${r.task_id}|${r.repeat_idx}`)}
<tr>
<td>{r.model}</td>
<td>{r.task_id}</td>
<td class="num">{r.repeat_idx}</td>
<td class={r.error_class === "ok" ? "ok" : isInfrastructure(r.error_class) ? "muted" : "error"}>
{errorLabel(r.error_class)}
{#if isInfrastructure(r.error_class)}<span class="chip" title="Zählt nicht in die Bewertung">nicht gewertet</span>{/if}
</td>
<td class="num">{Math.round(r.score * 100)} %</td>
<td class="num">{r.steps}</td>
<td class="num">{fmtDuration(r.duration_ms)}</td>
<td><button onclick={() => showSteps(r)}>Schritte</button></td>
</tr>
{/each}
</tbody>
</table>
</div>
{/if}
{#if detail}
<div class="detail" id="run-detail">
<h3>
Schritte: {detail.run.model} · {detail.run.task_id} · Durchlauf {detail.run.repeat_idx}
<button class="link" onclick={() => (detail = null)}>schließen</button>
</h3>
{#if detail.run.external}
<p class="muted">Extern gelöst, keine Schritte aufgezeichnet. Der Ergebnisordner steht unter <code>{detail.run.artifact_path ?? "unbekannt"}</code>.</p>
{/if}
{#if detail.run.check_output}
<p class="muted">Prüfung (<code>check.sh</code>):</p>
<pre>{detail.run.check_output}</pre>
{/if}
<ol class="steps">
{#each detail.steps as st (st.idx)}
<li>
<strong>{st.role}</strong>
{#if st.tool_name}<span class="chip">{st.tool_name}</span> <code>{st.tool_args_json ?? ""}</code>{/if}
{#if st.content}<pre>{st.content}</pre>{/if}
</li>
{/each}
</ol>
</div>
{/if}
{:else if ranking && !loading}
<p class="muted">Dieser Batch hat noch keine fertigen Läufe.</p>
{/if}
</section>
<style>
.head {
display: flex;
gap: 1rem;
align-items: center;
flex-wrap: wrap;
margin-bottom: 0.8rem;
}
.head h2 {
margin: 0;
flex: 1;
}
.head select {
max-width: 100%;
}
.scroll {
overflow-x: auto;
margin-bottom: 1rem;
}
.matrix th {
text-transform: none;
}
.board {
display: grid;
gap: 0.9rem;
margin-bottom: 1.2rem;
}
.mcard {
position: relative;
display: grid;
grid-template-columns: auto 1fr auto;
grid-template-areas:
"badge head total"
"groups groups groups"
"weak weak weak";
gap: 0.4rem 1rem;
align-items: center;
padding: 1rem 1.2rem;
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: 12px;
}
.mcard[data-rank="1"] {
border-color: color-mix(in srgb, var(--gold) 60%, var(--border));
background: linear-gradient(135deg, color-mix(in srgb, var(--gold) 10%, var(--surface-2)), var(--surface-2) 60%);
}
.badge {
grid-area: badge;
width: 2.6rem;
height: 2.6rem;
border-radius: 50%;
display: grid;
place-items: center;
font-weight: 800;
font-size: 1.15rem;
color: #1a1005;
background: var(--muted);
}
.badge.r1 { background: var(--gold); }
.badge.r2 { background: var(--silver); }
.badge.r3 { background: var(--bronze); }
.badge.r4 { background: var(--surface); color: var(--muted); border: 1px solid var(--border); }
.mhead { grid-area: head; min-width: 0; }
.mname { margin: 0; font-size: 1.1rem; overflow-wrap: anywhere; }
.stats {
display: flex;
flex-wrap: wrap;
gap: 0.2rem 1rem;
color: var(--muted);
font-size: 0.85rem;
font-variant-numeric: tabular-nums;
}
.total { grid-area: total; text-align: right; }
.total .label { font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; }
.groups {
grid-area: groups;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr));
gap: 0.7rem 1.2rem;
margin-top: 0.6rem;
}
.gtop { display: flex; justify-content: space-between; gap: 0.5rem; font-size: 0.85rem; }
.gtop b { color: var(--accent); }
.weak { grid-area: weak; font-size: 0.8rem; color: var(--muted); }
.pct {
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.pct.big {
font-size: 2.2rem;
line-height: 1;
}
.meter {
position: relative;
height: 7px;
background: var(--bg);
border-radius: 999px;
margin: 0.25rem 0;
}
.meter .f {
border-radius: 999px;
}
.tick,
.tick-demo {
background: var(--text);
border-radius: 2px;
}
.tick {
position: absolute;
top: -3px;
bottom: -3px;
width: 3px;
margin-left: -1px;
}
.tick-demo {
display: inline-block;
width: 3px;
height: 0.9rem;
vertical-align: middle;
}
.legend {
margin: 0 0 0.8rem;
}
.mcard.ref {
border-style: dashed;
}
.badge.r5 {
background: var(--surface);
color: var(--accent);
border: 1px dashed var(--accent);
}
.meter .f {
height: 100%;
}
.n {
font-size: 0.75rem;
color: var(--muted);
}
.n.few {
color: var(--danger);
}
.notice {
border: 1px solid color-mix(in srgb, var(--accent) 50%, var(--border));
background: var(--accent-soft);
border-radius: 10px;
padding: 0.6rem 0.9rem;
margin: 0 0 1rem;
font-size: 0.9rem;
}
td.clickable {
cursor: pointer;
}
td.clickable:hover {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.how {
margin: 0.5rem 0 1.2rem;
color: var(--muted);
}
.how summary {
cursor: pointer;
}
.detail {
margin-top: 1rem;
border-top: 1px solid var(--border);
padding-top: 1rem;
}
.steps pre,
.detail > pre {
white-space: pre-wrap;
overflow-wrap: anywhere;
max-height: 12rem;
overflow-y: auto;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 6px;
padding: 0.5rem;
margin: 0.3rem 0;
}
</style>

View File

@ -0,0 +1,534 @@
<script lang="ts">
import { onMount, onDestroy } from "svelte";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import {
api,
type ImageStatus,
type ModelEntry,
type ModelInfo,
type ModelTest,
type Paths,
type RuntimeStatus,
} from "$lib/api";
let {
models,
paths,
runtime,
onsaved,
}: {
models: ModelInfo[];
paths: Paths | null;
runtime: RuntimeStatus | null;
onsaved: (m: ModelInfo[]) => void;
} = $props();
const ADAPTERS = [
{ id: "ollama", label: "Ollama", hint: "http://host:11434" },
{ id: "openai", label: "OpenAI-kompatibel", hint: "http://host:8082/v1" },
];
function toEntry(m: ModelInfo): ModelEntry {
return { name: m.name, adapter: m.adapter, url: m.url, model: m.model, api_key_env: m.api_key_env };
}
// Bearbeitungsstand: Kopie beim Öffnen, bewusst vom Original gelöst. Gilt erst nach „Speichern“.
// svelte-ignore state_referenced_locally
let draft = $state<ModelEntry[]>(models.map(toEntry));
let dirty = $state(false);
let saveError = $state("");
let saving = $state(false);
let tests = $state<Record<string, ModelTest | "läuft">>({});
function markDirty() {
dirty = true;
saveError = "";
}
function addModel() {
draft.push({ name: "", adapter: "ollama", url: "", model: "", api_key_env: "" });
open = [...open, draft.length - 1];
markDirty();
}
function removeModel(i: number) {
draft.splice(i, 1);
reach = {};
open = [];
markDirty();
draft.forEach((_, k) => check(k));
}
function hintFor(adapter: string): string {
return ADAPTERS.find((a) => a.id === adapter)?.hint ?? "";
}
async function save() {
saving = true;
saveError = "";
try {
const saved = await api.saveModels($state.snapshot(draft));
draft = saved.map(toEntry);
dirty = false;
onsaved(saved);
draft.forEach((_, k) => check(k));
} catch (e) {
saveError = String(e);
} finally {
saving = false;
}
}
async function test(name: string) {
tests[name] = "läuft";
try {
tests[name] = await api.testModel(name);
} catch (e) {
tests[name] = { ok: false, duration_ms: 0, message: String(e) };
}
}
function savedInfo(name: string): ModelInfo | undefined {
return models.find((m) => m.name === name);
}
let images = $state<ImageStatus[]>([]);
let imagesError = $state("");
let building = $state<string | null>(null);
let buildLog = $state<string[]>([]);
let buildError = $state("");
let unlisten: UnlistenFn | null = null;
// Erreichbarkeit: fragt nur die Modell-Liste des Servers ab, lädt also kein Modell in den Speicher.
type Reach = { state: "prüft" | "ok" | "fehler"; models: string[]; message: string };
let reach = $state<Record<number, Reach>>({});
let open = $state<number[]>([]);
async function check(i: number) {
const m = draft[i];
if (!m || !m.url.trim()) {
reach[i] = { state: "fehler", models: [], message: "Keine Server-URL." };
return;
}
reach[i] = { state: "prüft", models: reach[i]?.models ?? [], message: "" };
try {
const list = await api.discoverModels(m.adapter, m.url, m.api_key_env);
reach[i] = { state: "ok", models: list, message: `${list.length} Modell(e) beim Server` };
} catch (e) {
reach[i] = { state: "fehler", models: [], message: String(e) };
}
}
function toggleOpen(i: number) {
open = open.includes(i) ? open.filter((x) => x !== i) : [...open, i];
}
// Bereitschaft: was fehlt noch, bevor ein Benchmark laufen kann?
let imagesReady = $derived(images.length > 0 && images.every((i) => i.available));
let anyReachable = $derived(Object.values(reach).some((r) => r.state === "ok"));
let checks = $derived([
{
ok: !!runtime?.available,
label: runtime ? (runtime.available ? `Container: ${runtime.program} bereit` : `Container: ${runtime.program} nicht nutzbar`) : "Container: prüfe …",
todo: "Podman installieren oder starten.",
},
{
ok: imagesReady,
label: imagesReady ? "Container-Image vorhanden" : "Container-Image fehlt",
todo: "Unten das Image bauen.",
},
{
ok: models.length > 0,
label: models.length > 0 ? `${models.length} Modell(e) angelegt` : "Noch kein Modell angelegt",
todo: "Ein Modell hinzufügen und speichern.",
},
{
ok: anyReachable,
label: anyReachable ? "Mindestens ein Server antwortet" : "Kein Server geprüft oder erreichbar",
todo: "Server-URL prüfen. Ist der Server an?",
},
]);
let ready = $derived(checks.every((c) => c.ok));
// Container-Images: Zustand, Bauen auf Knopfdruck, Ausgabe live.
async function loadImages() {
try {
images = await api.imageStatus();
imagesError = "";
} catch (e) {
imagesError = String(e);
}
}
async function build(image: string) {
building = image;
buildLog = [];
buildError = "";
try {
await api.buildImage(image);
} catch (e) {
buildError = String(e);
} finally {
building = null;
await loadImages();
}
}
onMount(async () => {
loadImages();
draft.forEach((_, k) => check(k));
unlisten = await listen<{ image: string; line: string }>("image-build", (ev) => {
buildLog.push(ev.payload.line);
if (buildLog.length > 300) buildLog.splice(0, buildLog.length - 300);
});
});
onDestroy(() => unlisten?.());
</script>
<section class="card ready" class:go={ready}>
<div class="ready-head">
<span class="lamp" class:go={ready}></span>
<h2>{ready ? "Bereit für einen Benchmark" : "Noch nicht ganz bereit"}</h2>
</div>
<ul class="checks">
{#each checks as c (c.label)}
<li class:ok={c.ok}>
<span class="mark">{c.ok ? "✓" : "○"}</span>
<span>{c.label}</span>
{#if !c.ok}<span class="muted small">→ {c.todo}</span>{/if}
</li>
{/each}
</ul>
</section>
<section class="card">
<h2>Modelle</h2>
<p class="muted">
Jedes Modell hat einen Adapter. Er bestimmt, wie coding-bench mit dem Server spricht. Ein Schlüssel steht nie in der
Konfiguration: Trage nur den Namen der Umgebungsvariable ein, aus der die App ihn beim Start liest.
</p>
{#if draft.length === 0}
<p class="muted">Noch kein Modell angebunden.</p>
{/if}
{#each draft as m, i (i)}
{@const r = reach[i]}
{@const isOpen = open.includes(i)}
<div class="model" class:open={isOpen}>
<button class="mhead" onclick={() => toggleOpen(i)} aria-expanded={isOpen}>
<span class="dot {r?.state ?? 'unbekannt'}" title={r?.message || "noch nicht geprüft"}></span>
<strong>{m.name || "Neues Modell"}</strong>
<span class="muted small">{ADAPTERS.find((a) => a.id === m.adapter)?.label} · {m.url || "keine URL"}</span>
<span class="spacer"></span>
<span class="muted small">
{r?.state === "ok" ? "erreichbar" : r?.state === "fehler" ? "nicht erreichbar" : r?.state === "prüft" ? "prüfe …" : ""}
</span>
<span class="chev">{isOpen ? "▾" : "▸"}</span>
</button>
{#if isOpen}
<div class="grid">
<label>
Name
<input bind:value={m.name} oninput={markDirty} placeholder="z. B. Qwen3 lokal" />
</label>
<label>
Adapter
<select bind:value={m.adapter} onchange={markDirty}>
{#each ADAPTERS as a (a.id)}
<option value={a.id}>{a.label}</option>
{/each}
</select>
</label>
<label class="wide">
Server-URL
<input bind:value={m.url} oninput={markDirty} onchange={() => check(i)} placeholder={hintFor(m.adapter)} />
</label>
<label>
Modell-ID beim Server
<input
bind:value={m.model}
oninput={markDirty}
list={`models-${i}`}
placeholder={r?.models.length ? "aus der Liste wählen oder leer = Name" : "leer = Name"}
/>
<datalist id={`models-${i}`}>
{#each r?.models ?? [] as name (name)}<option value={name}></option>{/each}
</datalist>
</label>
<label>
Schlüssel-Variable
<input bind:value={m.api_key_env} oninput={markDirty} placeholder="leer = kein Schlüssel" />
</label>
</div>
{#if r?.state === "fehler"}<p class="error small">{r.message}</p>{/if}
{#if r?.state === "ok" && r.models.length > 0}
<p class="muted small">Beim Server verfügbar: {r.models.slice(0, 8).join(", ")}{r.models.length > 8 ? " …" : ""}</p>
{/if}
<div class="row">
{#if m.api_key_env && savedInfo(m.name)}
{#if savedInfo(m.name)?.api_key_set}
<span class="chip ok">Schlüssel gefunden</span>
{:else}
<span class="chip error">Variable {m.api_key_env} ist nicht gesetzt</span>
{/if}
{/if}
<span class="spacer"></span>
{#if tests[m.name] === "läuft"}
<span class="muted">teste …</span>
{:else if tests[m.name]}
{@const t = tests[m.name] as ModelTest}
<span class={t.ok ? "ok" : "error"}>
{t.ok ? "Antwort ok" : "Fehler"}: {t.message}
{#if t.duration_ms}({(t.duration_ms / 1000).toFixed(1)} s){/if}
</span>
{/if}
<button onclick={() => check(i)}>Server prüfen</button>
<button
onclick={() => test(m.name)}
disabled={dirty || !savedInfo(m.name)}
title={dirty ? "Erst speichern" : "Schickt eine kurze Frage an das Modell und lädt es dabei"}
>
Antwort testen
</button>
<button class="danger" onclick={() => removeModel(i)}>Entfernen</button>
</div>
{/if}
</div>
{/each}
<div class="row">
<button onclick={addModel}>Modell hinzufügen</button>
<span class="spacer"></span>
{#if saveError}<span class="error">{saveError}</span>{/if}
{#if dirty}<span class="muted">Ungespeicherte Änderungen</span>{/if}
<button class="primary" onclick={save} disabled={!dirty || saving}>Speichern</button>
</div>
</section>
<section class="card">
<h2>Container-Images</h2>
<p class="muted">
Jede Aufgabe läuft in einem Container. Das Standard-Image <code>cb-python</code> baut die App selbst. Beim
ersten Mal lädt Podman dafür ein Basis-Image und braucht Netz und ein paar Minuten.
</p>
{#if imagesError}<p class="error">{imagesError}</p>{/if}
{#each images as img (img.image)}
<div class="image-row">
<code>{img.image}</code>
{#if img.error}
<span class="chip error" title={img.error}>Prüfung fehlgeschlagen</span>
{:else if img.available}
<span class="chip ok">vorhanden</span>
{:else}
<span class="chip error">fehlt</span>
{/if}
<span class="spacer"></span>
{#if img.buildable}
<button class="primary" disabled={building !== null || img.available} onclick={() => build(img.image)}>
{building === img.image ? "baut …" : "Image bauen"}
</button>
{:else if !img.available}
<span class="muted">Muss selbst bereitgestellt werden</span>
{/if}
</div>
{/each}
{#if buildError}<p class="error">{buildError}</p>{/if}
{#if buildLog.length > 0}
<pre class="buildlog">{buildLog.join("\n")}</pre>
{/if}
</section>
<section class="card">
<h2>System</h2>
<dl>
<dt>Container</dt>
<dd>
{#if runtime}
{#if runtime.available}
<span class="ok">{runtime.program} bereit, {runtime.detail}</span>
{:else}
<span class="error">{runtime.program} nicht nutzbar: {runtime.detail}</span>
{/if}
{:else}
<span class="muted">Prüfe …</span>
{/if}
</dd>
{#if paths}
<dt>Konfiguration</dt>
<dd><code>{paths.config_file}</code></dd>
<dt>Datenordner</dt>
<dd><code>{paths.data_dir}</code></dd>
<dt>Aufgabenordner</dt>
<dd><code>{paths.tasks_dir}</code></dd>
{/if}
</dl>
</section>
<style>
.model {
border: 1px solid var(--border);
border-radius: 12px;
padding: 0.3rem 0.9rem 0.8rem;
margin-bottom: 0.7rem;
background: var(--surface-2);
}
.model:not(.open) {
padding-bottom: 0.3rem;
}
.mhead {
display: flex;
align-items: center;
gap: 0.6rem;
width: 100%;
border: none;
background: none;
padding: 0.55rem 0;
text-align: left;
color: var(--text);
}
.mhead:hover:not(:disabled) {
border-color: transparent;
}
.chev {
color: var(--muted);
}
.small {
font-size: 0.8rem;
}
.dot {
width: 0.7rem;
height: 0.7rem;
border-radius: 50%;
background: var(--muted);
flex-shrink: 0;
}
.dot.ok {
background: var(--ok);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--ok) 25%, transparent);
}
.dot.fehler {
background: var(--danger);
}
.dot.prüft {
background: var(--accent);
animation: blink 1s ease-in-out infinite;
}
@keyframes blink {
50% {
opacity: 0.3;
}
}
.ready {
border-color: color-mix(in srgb, var(--accent) 45%, var(--border));
}
.ready.go {
border-color: color-mix(in srgb, var(--ok) 55%, var(--border));
}
.ready-head {
display: flex;
align-items: center;
gap: 0.7rem;
}
.ready-head h2 {
margin: 0;
}
.lamp {
width: 0.9rem;
height: 0.9rem;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 10px var(--accent);
}
.lamp.go {
background: var(--ok);
box-shadow: 0 0 10px var(--ok);
}
.checks {
list-style: none;
margin: 0.8rem 0 0;
padding: 0;
display: grid;
gap: 0.3rem;
}
.checks li {
display: flex;
gap: 0.6rem;
align-items: baseline;
color: var(--muted);
}
.checks li.ok {
color: var(--text);
}
.checks .mark {
width: 1rem;
color: var(--accent);
}
.checks li.ok .mark {
color: var(--ok);
}
.grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.6rem 0.8rem;
}
.grid .wide {
grid-column: 1 / -1;
}
label {
display: flex;
flex-direction: column;
gap: 0.2rem;
font-size: 0.85rem;
color: var(--muted);
}
label input,
label select {
color: var(--text);
font-size: 1rem;
}
.row {
display: flex;
align-items: center;
gap: 0.6rem;
margin-top: 0.7rem;
flex-wrap: wrap;
}
.spacer {
flex: 1;
}
.image-row {
display: flex;
align-items: center;
gap: 0.7rem;
padding: 0.4rem 0;
border-bottom: 1px solid var(--border);
}
.buildlog {
max-height: 14rem;
overflow-y: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.6rem;
margin: 0.8rem 0 0;
font-size: 0.8rem;
}
dl {
display: grid;
grid-template-columns: max-content 1fr;
gap: 0.4rem 1.2rem;
margin: 0;
}
dt {
color: var(--muted);
}
dd {
margin: 0;
overflow-wrap: anywhere;
}
</style>

183
src/lib/api.ts Normal file
View File

@ -0,0 +1,183 @@
import { invoke } from "@tauri-apps/api/core";
export type Paths = { config_file: string; data_dir: string; tasks_dir: string };
export type TaskInfo = {
id: string;
title: string;
group: string;
dir: string;
weight: number;
image: string;
max_steps: number;
timeout_s: number;
check_timeout_s: number;
prompt: string;
};
export type TaskError = { dir: string; message: string };
export type LoadReport = { tasks: TaskInfo[]; errors: TaskError[] };
export type ModelEntry = {
name: string;
adapter: string;
url: string;
model: string;
api_key_env: string;
};
export type ModelInfo = ModelEntry & { api_key_set: boolean };
export type ModelTest = { ok: boolean; duration_ms: number; message: string };
export type RuntimeStatus = { program: string; available: boolean; detail: string };
export type ImageStatus = { image: string; available: boolean; buildable: boolean; error: string | null };
export type BatchInfo = {
id: number;
created_at: string;
note: string;
repeats: number;
runs: number;
models: string;
};
export type BatchSummary = { batch_id: number; completed: number; skipped: number; cancelled: boolean };
export type RunRow = {
model: string;
task_id: string;
repeat_idx: number;
error_class: string;
score: number;
steps: number;
prompt_tokens: number;
completion_tokens: number;
duration_ms: number;
tps: number | null;
summary: string | null;
check_output: string;
artifact_path: string | null;
external: boolean;
};
export type StepRow = {
idx: number;
role: string;
content: string;
tool_name: string | null;
tool_args_json: string | null;
tool_result: string | null;
};
export type GroupScore = { group: string; percent: number | null; tasks: number; runs: number };
export type ModelRank = {
/** 0 bei Referenzen. */
rank: number;
external: boolean;
model: string;
total_percent: number;
groups: GroupScore[];
weakest_group: string | null;
runs: number;
successes: number;
median_duration_ms: number;
mean_completion_tokens: number;
median_tps: number | null;
};
export type MatrixCell = { model: string; task_id: string; runs: number; successes: number; mean_score: number };
export type TaskColumn = { id: string; group: string };
export type Ranking = {
batch_id: number;
groups: string[];
models: ModelRank[];
cells: MatrixCell[];
tasks: TaskColumn[];
/** Läufe, die wegen Server- oder Umgebungsfehlern nicht in die Bewertung eingehen. */
excluded_runs: number;
};
export type BatchEvent =
| { kind: "run_started"; model: string; task: string; repeat: number }
| { kind: "run_finished"; model: string; task: string; repeat: number; class: string; score: number }
| { kind: "run_skipped"; model: string; task: string; repeat: number }
| { kind: "model_unavailable"; model: string; reason: string }
| { kind: "progress"; done: number; total: number };
export type ExportResult = { dir: string; folders: number };
export type ImportSummary = { imported: number; passed: number; skipped: string[] };
export const api = {
paths: () => invoke<Paths>("get_paths"),
tasks: () => invoke<LoadReport>("load_tasks"),
runtime: () => invoke<RuntimeStatus>("runtime_status"),
imageStatus: () => invoke<ImageStatus[]>("image_status"),
buildImage: (image: string) => invoke<void>("build_image", { image }),
models: () => invoke<ModelInfo[]>("list_models"),
saveModels: (models: ModelEntry[]) => invoke<ModelInfo[]>("save_models", { models }),
discoverModels: (adapter: string, url: string, apiKeyEnv: string) =>
invoke<string[]>("discover_models", { adapter, url, apiKeyEnv }),
testModel: (name: string) => invoke<ModelTest>("test_model", { name }),
startBatch: (models: string[], taskIds: string[], repeats: number, note: string, batchId: number | null = null) =>
invoke<BatchSummary>("start_batch", { models, taskIds, repeats, note, batchId }),
exportExternal: (taskIds: string[], repeats: number) => invoke<ExportResult>("export_external", { taskIds, repeats }),
importExternal: (dir: string, model: string, batchId: number) =>
invoke<ImportSummary>("import_external", { dir, model, batchId }),
cancelBatch: () => invoke<boolean>("cancel_batch"),
batches: () => invoke<BatchInfo[]>("list_batches"),
results: (batchId: number) => invoke<RunRow[]>("batch_results", { batchId }),
ranking: (batchId: number) => invoke<Ranking>("batch_ranking", { batchId }),
steps: (batchId: number, r: RunRow) =>
invoke<StepRow[]>("run_steps", { batchId, model: r.model, taskId: r.task_id, repeatIdx: r.repeat_idx }),
};
/** Lesbare Bezeichnung einer Fehlerklasse. */
export function errorLabel(cls: string): string {
const labels: Record<string, string> = {
ok: "bestanden",
check_failed: "Prüfung fehlgeschlagen",
max_steps: "Zu viele Schritte",
timeout: "Zeitlimit überschritten",
loop_detected: "Schleife erkannt",
invalid_tool_json: "Ungültiger Tool-Aufruf",
unknown_tool: "Unbekanntes Werkzeug",
bad_args: "Falsche Argumente",
endpoint_error: "Modell-Server nicht erreichbar",
sandbox_error: "Fehler der Umgebung",
};
return labels[cls] ?? cls;
}
/** Läufe, die nicht am Modell scheiterten und deshalb nicht zählen. */
export function isInfrastructure(cls: string): boolean {
return cls === "endpoint_error" || cls === "sandbox_error";
}
/** Namen der Bereiche (Gruppen aus SPEC 11). */
export const GROUP_LABELS: Record<string, string> = {
A: "Tool-Calling",
B: "Kleine Coding-Aufgaben",
C: "Agent im Repo",
D: "Demos",
"?": "Unbekannt",
};
export function groupLabel(g: string): string {
return GROUP_LABELS[g] ?? g;
}
/** Farbe für einen Prozentwert: rot bei 0, gelb in der Mitte, grün bei 100. */
export function pctColor(p: number): string {
const hue = Math.max(0, Math.min(100, p)) * 1.2;
return `hsl(${hue} 72% var(--pct-l, 56%))`;
}
export function fmtPct(p: number | null): string {
return p === null ? "–" : `${Math.round(p)} %`;
}
export function fmtDuration(ms: number): string {
const s = ms / 1000;
return s < 90 ? `${s.toFixed(1)} s` : `${Math.floor(s / 60)} min ${Math.round(s % 60)} s`;
}
export function fmtTps(t: number | null): string {
return t === null ? "–" : `${t < 10 ? t.toFixed(1) : Math.round(t)} Tok/s`;
}

View File

@ -0,0 +1,6 @@
<script lang="ts">
import "../app.css";
let { children } = $props();
</script>
{@render children()}

5
src/routes/+layout.ts Normal file
View File

@ -0,0 +1,5 @@
// Tauri doesn't have a Node.js server to do proper SSR
// so we use adapter-static with a fallback to index.html to put the site in SPA mode
// See: https://svelte.dev/docs/kit/single-page-apps
// See: https://v2.tauri.app/start/frontend/sveltekit/ for more info
export const ssr = false;

149
src/routes/+page.svelte Normal file
View File

@ -0,0 +1,149 @@
<script lang="ts">
import { onMount } from "svelte";
import { api, type LoadReport, type ModelInfo, type Paths, type RuntimeStatus } from "$lib/api";
import BenchPanel from "$lib/BenchPanel.svelte";
import ReferencePanel from "$lib/ReferencePanel.svelte";
import ResultsPanel from "$lib/ResultsPanel.svelte";
import SettingsPanel from "$lib/SettingsPanel.svelte";
type Tab = "bench" | "results" | "reference" | "settings";
let tab = $state<Tab>("bench");
let loaded = $state(false);
let loadError = $state("");
let models = $state<ModelInfo[]>([]);
let tasks = $state<LoadReport | null>(null);
let paths = $state<Paths | null>(null);
let runtime = $state<RuntimeStatus | null>(null);
let selectedBatch = $state<number | null>(null);
onMount(async () => {
try {
[models, tasks, paths] = await Promise.all([api.models(), api.tasks(), api.paths()]);
runtime = await api.runtime();
} catch (e) {
loadError = String(e);
} finally {
loaded = true;
}
});
function showResults(batchId: number) {
selectedBatch = batchId;
tab = "results";
}
const tabs: { id: Tab; label: string }[] = [
{ id: "bench", label: "Benchmark" },
{ id: "results", label: "Ergebnisse" },
{ id: "reference", label: "Referenz" },
{ id: "settings", label: "Einstellungen" },
];
</script>
<header>
<div class="inner">
<span class="logo">
<svg viewBox="0 0 1024 1024" width="28" height="28" aria-hidden="true">
<rect x="32" y="32" width="960" height="960" rx="224" fill="var(--accent)" />
<g fill="var(--accent-text)">
<rect x="212" y="490" width="170" height="300" rx="44" />
<rect x="427" y="340" width="170" height="450" rx="44" />
<rect x="642" y="580" width="170" height="210" rx="44" />
<circle cx="512" cy="245" r="46" />
</g>
</svg>
coding<b>-bench</b>
</span>
<nav>
{#each tabs as t (t.id)}
<button class="tab" class:active={tab === t.id} onclick={() => (tab = t.id)}>{t.label}</button>
{/each}
</nav>
</div>
</header>
<main>
{#if loadError}
<section class="card"><p class="error">Start fehlgeschlagen: {loadError}</p></section>
{:else if !loaded}
<p class="muted">Lade …</p>
{:else}
<!-- Reiter bleiben gemountet, damit ein laufender Batch beim Wechsel nicht abreißt. -->
<div hidden={tab !== "bench"}>
<BenchPanel {models} {tasks} ongotosettings={() => (tab = "settings")} onfinished={showResults} />
</div>
<div hidden={tab !== "results"}>
<ResultsPanel bind:selected={selectedBatch} />
</div>
<div hidden={tab !== "reference"}>
<ReferencePanel {tasks} onimported={showResults} />
</div>
<div hidden={tab !== "settings"}>
<SettingsPanel {models} {paths} {runtime} onsaved={(m) => (models = m)} />
</div>
{/if}
</main>
<style>
header {
background: color-mix(in srgb, var(--bg) 82%, transparent);
backdrop-filter: blur(10px);
border-bottom: 1px solid var(--border);
position: sticky;
top: 0;
z-index: 5;
}
.inner {
max-width: 66rem;
margin: 0 auto;
padding: 0.7rem 1rem;
display: flex;
align-items: center;
gap: 2rem;
}
.logo {
display: inline-flex;
align-items: center;
gap: 0.55rem;
font-weight: 600;
font-size: 1.1rem;
letter-spacing: -0.01em;
}
.logo b {
color: var(--accent);
font-weight: 700;
margin-left: -0.5rem;
}
nav {
display: flex;
gap: 0.3rem;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 999px;
padding: 0.25rem;
}
.tab {
border: none;
border-radius: 999px;
background: none;
padding: 0.4rem 1.1rem;
color: var(--muted);
}
.tab:hover:not(:disabled) {
color: var(--text);
}
.tab.active {
background: var(--accent-soft);
color: var(--accent);
font-weight: 600;
}
main {
max-width: 66rem;
margin: 0 auto;
padding: 1.2rem 1rem 3rem;
}
[hidden] {
display: none !important;
}
</style>

BIN
static/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

15
static/favicon.svg Normal file
View File

@ -0,0 +1,15 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#ffb470"/>
<stop offset="1" stop-color="#ee8227"/>
</linearGradient>
</defs>
<rect x="32" y="32" width="960" height="960" rx="224" fill="url(#bg)"/>
<g fill="#1a1005">
<rect x="212" y="490" width="170" height="300" rx="44"/>
<rect x="427" y="340" width="170" height="450" rx="44"/>
<rect x="642" y="580" width="170" height="210" rx="44"/>
</g>
<circle cx="512" cy="245" r="46" fill="#1a1005"/>
</svg>

After

Width:  |  Height:  |  Size: 626 B

1
static/svelte.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="26.6" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 308"><path fill="#FF3E00" d="M239.682 40.707C211.113-.182 154.69-12.301 113.895 13.69L42.247 59.356a82.198 82.198 0 0 0-37.135 55.056a86.566 86.566 0 0 0 8.536 55.576a82.425 82.425 0 0 0-12.296 30.719a87.596 87.596 0 0 0 14.964 66.244c28.574 40.893 84.997 53.007 125.787 27.016l71.648-45.664a82.182 82.182 0 0 0 37.135-55.057a86.601 86.601 0 0 0-8.53-55.577a82.409 82.409 0 0 0 12.29-30.718a87.573 87.573 0 0 0-14.963-66.244"></path><path fill="#FFF" d="M106.889 270.841c-23.102 6.007-47.497-3.036-61.103-22.648a52.685 52.685 0 0 1-9.003-39.85a49.978 49.978 0 0 1 1.713-6.693l1.35-4.115l3.671 2.697a92.447 92.447 0 0 0 28.036 14.007l2.663.808l-.245 2.659a16.067 16.067 0 0 0 2.89 10.656a17.143 17.143 0 0 0 18.397 6.828a15.786 15.786 0 0 0 4.403-1.935l71.67-45.672a14.922 14.922 0 0 0 6.734-9.977a15.923 15.923 0 0 0-2.713-12.011a17.156 17.156 0 0 0-18.404-6.832a15.78 15.78 0 0 0-4.396 1.933l-27.35 17.434a52.298 52.298 0 0 1-14.553 6.391c-23.101 6.007-47.497-3.036-61.101-22.649a52.681 52.681 0 0 1-9.004-39.849a49.428 49.428 0 0 1 22.34-33.114l71.664-45.677a52.218 52.218 0 0 1 14.563-6.398c23.101-6.007 47.497 3.036 61.101 22.648a52.685 52.685 0 0 1 9.004 39.85a50.559 50.559 0 0 1-1.713 6.692l-1.35 4.116l-3.67-2.693a92.373 92.373 0 0 0-28.037-14.013l-2.664-.809l.246-2.658a16.099 16.099 0 0 0-2.89-10.656a17.143 17.143 0 0 0-18.398-6.828a15.786 15.786 0 0 0-4.402 1.935l-71.67 45.674a14.898 14.898 0 0 0-6.73 9.975a15.9 15.9 0 0 0 2.709 12.012a17.156 17.156 0 0 0 18.404 6.832a15.841 15.841 0 0 0 4.402-1.935l27.345-17.427a52.147 52.147 0 0 1 14.552-6.397c23.101-6.006 47.497 3.037 61.102 22.65a52.681 52.681 0 0 1 9.003 39.848a49.453 49.453 0 0 1-22.34 33.12l-71.664 45.673a52.218 52.218 0 0 1-14.563 6.398"></path></svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

6
static/tauri.svg Normal file
View File

@ -0,0 +1,6 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

1
static/vite.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

18
svelte.config.js Normal file
View File

@ -0,0 +1,18 @@
// Tauri doesn't have a Node.js server to do proper SSR
// so we use adapter-static with a fallback to index.html to put the site in SPA mode
// See: https://svelte.dev/docs/kit/single-page-apps
// See: https://v2.tauri.app/start/frontend/sveltekit/ for more info
import adapter from "@sveltejs/adapter-static";
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: vitePreprocess(),
kit: {
adapter: adapter({
fallback: "index.html",
}),
},
};
export default config;

3
tasks/A/a-01/check.sh Executable file
View File

@ -0,0 +1,3 @@
#!/bin/sh
# Erwartet: ergebnis.txt enthält genau 4711 (Zeilenumbruch am Ende erlaubt).
[ "$(tr -d ' \n' < /work/ergebnis.txt)" = "4711" ]

1
tasks/A/a-01/prompt.md Normal file
View File

@ -0,0 +1 @@
Im Ordner /work liegt die Datei info.txt. Lies sie und schreibe nur den Projektcode (die Zahl hinter "Projektcode:") in die neue Datei ergebnis.txt. Keine weiteren Zeichen. Rufe danach done auf.

View File

@ -0,0 +1,2 @@
Projektcode: 4711
Status: offen

6
tasks/A/a-01/task.toml Normal file
View File

@ -0,0 +1,6 @@
id = "a-01"
title = "Information aus Datei in neue Datei übertragen"
group = "A"
image = "cb-python:latest"
max_steps = 10
timeout_s = 300

4
tasks/A/a-02/check.sh Executable file
View File

@ -0,0 +1,4 @@
#!/bin/sh
# Erwartet: neu.txt = 1,2,30,4,30 und anzahl.txt enthält 5.
[ "$(tr -d ' \r' < /work/neu.txt | paste -sd, -)" = "1,2,30,4,30" ] || exit 1
[ "$(tr -d ' \n' < /work/anzahl.txt)" = "5" ]

6
tasks/A/a-02/prompt.md Normal file
View File

@ -0,0 +1,6 @@
Im Ordner /work liegt die Datei zahlen.txt mit einer Zahl pro Zeile.
1. Liste den Inhalt von /work auf.
2. Lies zahlen.txt.
3. Ersetze in jeder Zeile, die genau "3" lautet, durch "30". Schreibe das Ergebnis in neu.txt (eine Zahl pro Zeile).
4. Zähle die Zeilen von neu.txt mit einem Shell-Befehl und schreibe die Zahl in anzahl.txt.
Rufe danach done auf.

View File

@ -0,0 +1,5 @@
1
2
3
4
3

6
tasks/A/a-02/task.toml Normal file
View File

@ -0,0 +1,6 @@
id = "a-02"
title = "Mehrere Werkzeuge nacheinander: auflisten, lesen, ändern, ausführen"
group = "A"
image = "cb-python:latest"
max_steps = 15
timeout_s = 420

3
tasks/A/a-03/check.sh Executable file
View File

@ -0,0 +1,3 @@
#!/bin/sh
# Erwartet: name.txt enthält genau coding.
[ "$(tr -d ' \n' < /work/name.txt)" = "coding" ]

1
tasks/A/a-03/prompt.md Normal file
View File

@ -0,0 +1 @@
Im Ordner /work soll der Wert des Schlüssels "name" aus der Konfiguration in die Datei name.txt geschrieben werden. Achtung: Die Datei config.json existiert nicht. Die richtige Datei heißt settings.json. Lies sie und schreibe nur den Wert (ohne Anführungszeichen) in name.txt. Rufe danach done auf.

View File

@ -0,0 +1 @@
{"name": "coding"}

6
tasks/A/a-03/task.toml Normal file
View File

@ -0,0 +1,6 @@
id = "a-03"
title = "Auf Tool-Fehler reagieren und korrigieren"
group = "A"
image = "cb-python:latest"
max_steps = 12
timeout_s = 360

20
tasks/B/b-04/check.sh Executable file
View File

@ -0,0 +1,20 @@
#!/bin/sh
# Prüft fib gegen die Spezifikation mit festen Testfällen.
mkdir -p /checks
cat > /checks/test_fib.py <<'PY'
import sys
sys.path.insert(0, "/work")
import pytest
from mathe import fib
def test_werte():
assert [fib(n) for n in range(10)] == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
def test_gross():
assert fib(90) == 2880067194370816120
def test_negativ():
with pytest.raises(ValueError):
fib(-1)
PY
cd /work && python3 -m pytest -q -p no:cacheprovider /checks/test_fib.py

3
tasks/B/b-04/prompt.md Normal file
View File

@ -0,0 +1,3 @@
In /work liegt mathe.py mit einer leeren Funktion fib(n).
Spezifikation: fib(n) gibt die n-te Fibonacci-Zahl zurück, mit fib(0) = 0 und fib(1) = 1. Für n < 0 wirft sie ValueError. Für große n (etwa 90) soll sie schnell sein.
Implementiere fib in mathe.py. Ändere nichts anderes. Rufe danach done auf.

View File

@ -0,0 +1,2 @@
def fib(n):
raise NotImplementedError

6
tasks/B/b-04/task.toml Normal file
View File

@ -0,0 +1,6 @@
id = "b-04"
title = "Funktion nach Spezifikation schreiben"
group = "B"
image = "cb-python:latest"
max_steps = 20
timeout_s = 480

18
tasks/B/b-05/check.sh Executable file
View File

@ -0,0 +1,18 @@
#!/bin/sh
# Prüft parse_kv mit Fällen, die den Fehler aufdecken.
mkdir -p /checks
cat > /checks/test_parser.py <<'PY'
import sys
sys.path.insert(0, "/work")
from parser import parse_kv
def test_einfach():
assert parse_kv("a=1") == ("a", "1")
def test_gleichheitszeichen_im_wert():
assert parse_kv("a=b=c") == ("a", "b=c")
def test_leerzeichen():
assert parse_kv(" name = x = y ") == ("name", "x = y")
PY
cd /work && python3 -m pytest -q -p no:cacheprovider /checks/test_parser.py

1
tasks/B/b-05/prompt.md Normal file
View File

@ -0,0 +1 @@
In /work liegt parser.py mit der Funktion parse_kv(line). Sie soll 'schluessel=wert' in (schluessel, wert) zerlegen. Ein Wert, der selbst '=' enthält, wird dabei falsch behandelt. Finde den Fehler und behebe ihn in parser.py. Die Docstring-Beschreibung gilt als Spezifikation. Rufe danach done auf.

View File

@ -0,0 +1,8 @@
def parse_kv(line):
"""Zerlegt 'schluessel=wert' in (schluessel, wert).
Der Wert darf selbst '=' enthalten: parse_kv('a=b=c') ergibt ('a', 'b=c').
Leerzeichen um Schlüssel und Wert werden entfernt.
"""
parts = line.split("=")
return parts[0].strip(), parts[1].strip()

6
tasks/B/b-05/task.toml Normal file
View File

@ -0,0 +1,6 @@
id = "b-05"
title = "Fehler in der Parser-Funktion finden und beheben"
group = "B"
image = "cb-python:latest"
max_steps = 20
timeout_s = 480

19
tasks/B/b-06/check.sh Executable file
View File

@ -0,0 +1,19 @@
#!/bin/sh
# Score: 0.5 für grüne Tests auf dem Original, weitere 0.5 wenn die Tests
# eingebaute Fehler (Mutationen) erkennen. Letzte Zeile ist JSON.
cd /work || { echo '{"score": 0.0, "notes": "kein /work"}'; exit 0; }
# Kein Bytecode-Cache: sonst nutzt Python bei gleicher Größe und Zeit veralteten Code der Mutation.
export PYTHONDONTWRITEBYTECODE=1
[ -f test_rechner.py ] || { echo '{"score": 0.0, "notes": "test_rechner.py fehlt"}'; exit 0; }
python3 -m pytest -q -p no:cacheprovider test_rechner.py >/tmp/orig.log 2>&1 || { echo '{"score": 0.0, "notes": "Tests auf dem Original rot"}'; exit 0; }
caught=0; total=0
for m in 's/a + b/a - b/' 's/a - b/a + b/' 's/a \* b/a + b/' 's/return a \/ b/return a \/\/ b/' 's/if b == 0:/if b == 1:/'; do
total=$((total+1))
rm -rf /checks/mut && mkdir -p /checks/mut && cp -r /work/. /checks/mut/ && rm -rf /checks/mut/__pycache__
sed -i "$m" /checks/mut/rechner.py
if ! (cd /checks/mut && python3 -m pytest -q -p no:cacheprovider test_rechner.py >/dev/null 2>&1); then
caught=$((caught+1))
fi
done
score=$(python3 -c "print(round(0.5 + 0.5*$caught/$total, 2))")
echo "{\"score\": $score, \"notes\": \"Mutationen erkannt: $caught von $total\"}"

2
tasks/B/b-06/prompt.md Normal file
View File

@ -0,0 +1,2 @@
In /work liegt rechner.py mit vier Funktionen: addiere, subtrahiere, multipliziere, dividiere. Dividiere wirft ZeroDivisionError bei b = 0.
Schreibe Tests in die Datei test_rechner.py (pytest). Die Tests sollen den Code vollständig prüfen, auch den Fehlerfall. Sie müssen mit dem vorhandenen Code grün sein. Rufe danach done auf.

View File

@ -0,0 +1,13 @@
def addiere(a, b):
return a + b
def subtrahiere(a, b):
return a - b
def multipliziere(a, b):
return a * b
def dividiere(a, b):
if b == 0:
raise ZeroDivisionError("Division durch null")
return a / b

7
tasks/B/b-06/task.toml Normal file
View File

@ -0,0 +1,7 @@
id = "b-06"
title = "Tests für vorhandenen Code schreiben"
group = "B"
image = "cb-python:latest"
max_steps = 25
timeout_s = 600
check_timeout_s = 180

View File

@ -0,0 +1,23 @@
---
test: start2app.2 bis ergebnis2detail.1
zeit: 2026-11-06T20:03
commit: a9fb334
art: auto-lauf
ergebnis: ◐
---
Automatische Läufe (Rust-Tests und Lauf gegen srv04). Keine Klicktests: Die Oberfläche wurde nicht im Fenster bedient. Jede Zeile nennt, was der Lauf tatsächlich prüft.
- start2app.1: – Fenster nicht geöffnet geprüft (manuell offen).
- start2app.2: ✓ Config wird beim Start angelegt, Datenordner entsteht (Test `load_or_create_legt_datei_und_ordner_an`; Pfade im Fenster nicht gesehen).
- aufgabe2validierung.1: ✓ Mitgelieferte Aufgaben laden gültig (Test `repo_aufgaben_sind_gueltig`; GUI nicht geprüft).
- aufgabe2validierung.2: ✓ Fehlende `check.sh` und fehlende Pflichtdatei werden gemeldet (Unit-Tests in `tasks.rs`; GUI nicht geprüft).
- lauf2sandbox.1: ✓ Netz aus: Verbindung nach außen scheitert im Container (echter Podman-Lauf, Test `echter_lauf_ohne_netz_und_aufraeumen`, Image `cb-python:latest`).
- lauf2sandbox.2: ✓ `/work` wird als Artefakt exportiert, Container danach entfernt (gleicher Test; `podman ps -a` leer).
- lauf2ergebnis.1: ✓ Sechs Aufgaben mit `qwen3:0.6b` auf srv04 enden mit Status und Fehlerklasse (Test `repo_aufgaben_mit_modell`; Ergebnis: 0 von 6 bestanden, Klassen CheckFailed und Timeout).
- lauf2ergebnis.2: – Schrittliste ist in der DB gespeichert, aber nicht in der Oberfläche sichtbar (offen).
- lauf2ergebnis.3: – Modell ohne Tool-Support nicht getestet.
- batch2fortsetzen.1: – Live-Fortschritt in der App nicht gesehen (manuell offen).
- batch2fortsetzen.2: – Abbruch und Fortsetzen nicht real getestet. Nur das Überspringen fertiger Läufe ist geprüft (Test `batch_end_zu_end`, 2 Läufe, dann 2 übersprungen).
- ergebnis2detail.1: – Rangliste und Matrix noch nicht gebaut (#1026).
Hinweis: Die Läufe mit `qwen3:0.6b` zeigen, dass das Modell die Aufgaben nicht löst. Das ist ein Ergebnis des kleinen Modells, kein Test der Oberfläche.

View File

@ -0,0 +1,19 @@
---
test: a-01 bis b-06
zeit: 2026-11-06T21:00
commit: dce98d3
art: auto-lauf
ergebnis: ✓
---
Lauf aller sechs Aufgaben über den OpenAI-kompatiblen Endpunkt von strata (`http://192.168.12.4:8082/v1/chat/completions`, ohne Schlüssel, Modell `qwen3.8-flash-next-q2_0`), eine Wiederholung, Sandbox `cb-python:latest`.
- a-01: ✓ score 1.00, 5 Schritte, 12 s
- a-02: ✓ score 1.00, 5 Schritte, 13 s
- a-03: ✓ score 1.00, 5 Schritte, 11 s
- b-04: ✓ score 1.00, 4 Schritte, 21 s
- b-05: ✓ score 1.00, 5 Schritte, 15 s
- b-06: ✓ score 1.00, 4 Schritte, 31 s
Vergleich: Mit dem kleinen Modell `qwen3:0.6b` auf srv04 (Ollama) hatte keine Aufgabe bestanden. Das Ergebnis hängt also stark am Modell.
Nicht geprüft: Klicktests im Fenster (manuell offen), Wiederholungen (nur einmal gelaufen), Abbruch während des Laufs.

19
tsconfig.json Normal file
View File

@ -0,0 +1,19 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
// except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

32
vite.config.js Normal file
View File

@ -0,0 +1,32 @@
import { defineConfig } from "vite";
import { sveltekit } from "@sveltejs/kit/vite";
// @ts-expect-error type error without @types/node package
import process from "node:process";
const host = process.env.TAURI_DEV_HOST;
// https://vite.dev/config/
export default defineConfig(() => ({
plugins: [sveltekit()],
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
//
// 1. prevent Vite from obscuring rust errors
clearScreen: false,
// 2. tauri expects a fixed port, fail if that port is not available
server: {
port: 1420,
strictPort: true,
host: host || "127.0.0.1",
hmr: host
? {
protocol: "ws",
host,
port: 1421,
}
: undefined,
watch: {
// 3. tell Vite to ignore watching `src-tauri`
ignored: ["**/src-tauri/**"],
},
},
}));