From a53a3e700ee14a43b67dc5a220454f0d821bf7f5 Mon Sep 17 00:00:00 2001 From: merefield Date: Fri, 21 Aug 2026 19:04:20 +0100 Subject: [PATCH 01/18] POC: add single-game DigBench runner --- README.md | 52 +++- internal/codex/benchmark.go | 44 ++- internal/codex/benchmark_test.go | 14 + internal/codex/digbench.go | 463 +++++++++++++++++++++++++++++++ internal/codex/digbench_test.go | 128 +++++++++ internal/digbench/client.go | 282 +++++++++++++++++++ internal/digbench/client_test.go | 115 ++++++++ main.go | 100 ++++++- main_test.go | 41 ++- 9 files changed, 1219 insertions(+), 20 deletions(-) create mode 100644 internal/codex/digbench.go create mode 100644 internal/codex/digbench_test.go create mode 100644 internal/digbench/client.go create mode 100644 internal/digbench/client_test.go diff --git a/README.md b/README.md index c9f5bd9e..51806bf5 100644 --- a/README.md +++ b/README.md @@ -301,7 +301,7 @@ Codexometer deliberately does not: - read or copy Codex credential/token files; - implement a separate OAuth flow; - store access or refresh tokens; -- send credentials to another service; +- send Codex credentials to another service; - invoke a model merely to discover quota information. The Monitor and observed quota estimator additionally read locally persisted @@ -734,6 +734,56 @@ platform-standard user configuration directory: Missing, unreadable, or malformed preferences never prevent startup; Codexometer falls back to its safe defaults. +### Experimental DigBench agentic run + +Codexometer includes a deliberately narrow command-line proof of concept for +[DigBench](https://digbench.ai/), an external benchmark of discovering unknown +rules in interactive text games. It runs exactly one named game with exactly +one Codex model/reasoning-effort combination; it is not included in the +Benchmark tab's deterministic Run Selected or Run All actions. + +Create a token from the [DigBench token page](https://digbench.ai/account/tokens) +(sign-in is a passwordless email link), place it in the environment, and select +one of the 21 public game names returned by the API, such as `P-1`: + +```sh +export DIGBENCH_API_TOKEN="" +codexometer --digbench-game P-1 +``` + +The published Codex condition is the default: `gpt-5.6-sol` with `high` +reasoning effort. Override it or the 30-minute hard limit explicitly: + +```sh +codexometer --digbench-game P-3 \ + --digbench-model gpt-5.6-terra \ + --digbench-effort medium \ + --digbench-timeout 20m +``` + +The command creates a fresh remote DigBench session, so invoking it is an +external write as well as a Codex-quota-consuming model run. DigBench persists +sessions and currently exposes no deletion endpoint. The token is read only +from `DIGBENCH_API_TOKEN`, is never written to Codexometer preferences, and is +removed from the process environment before Codex is spawned. It is used only +by Codexometer's native HTTPS client to start the session. Codex sees only +session-scoped `get_session` and `step` tools, not the account token. + +The game runs in one ephemeral Codex app-server thread with a writable temporary +workspace and no approval prompts. The model may use its normal local tools for +notes, matching DigBench's agentic-harness design, but its only game access is +the scoped dynamic-tool bridge. Step calls are safely retried using DigBench's +idempotent `step_index` protocol; session creation is never automatically +retried because that endpoint does not document idempotency. + +The final line reports `WIN`, `LOSS`, or `INCOMPLETE`, levels beaten, total game +steps, duration, tokens, and estimated standard API-equivalent cost. A win +requires the authoritative terminal combination `done: true` and +`state.status: "completed"`; `game_over` is a loss. Contradictory terminal +fields fail as a protocol error. DigBench assigns a random game seed and does +not currently accept a requested seed, so one run is exploratory rather than a +fair deterministic cross-model ranking. + ### Deterministic benchmark The Benchmark tab discovers the current account's visible models and their diff --git a/internal/codex/benchmark.go b/internal/codex/benchmark.go index bd141b9e..f4a222d0 100644 --- a/internal/codex/benchmark.go +++ b/internal/codex/benchmark.go @@ -184,6 +184,7 @@ type appServerSession struct { readErrors chan error done chan struct{} stop sync.Once + experimentalAPI bool experimentalRawEvents bool turnTimeout time.Duration interruptTimeout time.Duration @@ -289,6 +290,7 @@ func startAppServerWithExperimentalUsage(ctx context.Context, binary string, exp binary = "codex" } cmd := exec.CommandContext(ctx, binary, "app-server", "--stdio") + cmd.Env = environmentWithout(os.Environ(), "DIGBENCH_API_TOKEN") stdin, err := cmd.StdinPipe() if err != nil { return nil, fmt.Errorf("open Codex input: %w", err) @@ -308,6 +310,7 @@ func startAppServerWithExperimentalUsage(ctx context.Context, binary string, exp server := &appServerSession{ cmd: cmd, stdin: stdin, encoder: json.NewEncoder(stdin), stderr: stderr, envelopes: make(chan benchmarkEnvelope, 64), readErrors: make(chan error, 1), done: make(chan struct{}), + experimentalAPI: experimental, experimentalRawEvents: experimental, } go server.readLoop(json.NewDecoder(bufio.NewReader(stdout))) @@ -331,6 +334,18 @@ func startAppServerWithExperimentalUsage(ctx context.Context, binary string, exp return server, nil } +func environmentWithout(environment []string, name string) []string { + filtered := make([]string, 0, len(environment)) + for _, entry := range environment { + key, _, found := strings.Cut(entry, "=") + if found && strings.EqualFold(key, name) { + continue + } + filtered = append(filtered, entry) + } + return filtered +} + func experimentalAPIUnsupported(err error) bool { var methodError *benchmarkMethodError if !errors.As(err, &methodError) { @@ -978,16 +993,9 @@ func (s *appServerSession) readUntilNotification(ctx context.Context, accept fun if err := ctx.Err(); err != nil { return nil, err } - var envelope benchmarkEnvelope - if len(s.pending) > 0 { - envelope = s.pending[0] - s.pending = s.pending[1:] - } else { - var err error - envelope, err = s.nextEnvelope(ctx) - if err != nil { - return nil, err - } + envelope, err := s.nextPendingEnvelope(ctx) + if err != nil { + return nil, err } if envelope.Method != "" && accept(envelope.Method, envelope.Params) { return envelope.Params, nil @@ -995,6 +1003,22 @@ func (s *appServerSession) readUntilNotification(ctx context.Context, accept fun } } +func (s *appServerSession) nextPendingEnvelope(ctx context.Context) (benchmarkEnvelope, error) { + if len(s.pending) > 0 { + envelope := s.pending[0] + s.pending = s.pending[1:] + return envelope, nil + } + return s.nextEnvelope(ctx) +} + +func (s *appServerSession) respond(id json.RawMessage, result any) error { + if len(id) == 0 { + return errors.New("app-server request omitted id") + } + return s.encoder.Encode(map[string]any{"id": id, "result": result}) +} + var benchmarkOutputSchema = map[string]any{ "type": "object", "properties": map[string]any{ diff --git a/internal/codex/benchmark_test.go b/internal/codex/benchmark_test.go index 296394c5..67c28cb3 100644 --- a/internal/codex/benchmark_test.go +++ b/internal/codex/benchmark_test.go @@ -622,6 +622,20 @@ func TestExperimentalAPIUnsupported(t *testing.T) { } } +func TestEnvironmentWithoutScrubsDigBenchTokenOnly(t *testing.T) { + environment := []string{"PATH=/usr/bin", "DIGBENCH_API_TOKEN=secret", "OTHER=value", "malformed"} + filtered := environmentWithout(environment, "digbench_api_token") + want := []string{"PATH=/usr/bin", "OTHER=value", "malformed"} + if len(filtered) != len(want) { + t.Fatalf("filtered environment = %#v", filtered) + } + for index := range want { + if filtered[index] != want[index] { + t.Fatalf("filtered environment = %#v", filtered) + } + } +} + func TestRunBenchmarkSuiteDiscoversAndRunsEveryCombination(t *testing.T) { message := string(rawJSON(map[string]string{"code": correctStarlarkSubmission})) server, _ := newFakeBenchmarkServer( diff --git a/internal/codex/digbench.go b/internal/codex/digbench.go new file mode 100644 index 00000000..35e203e7 --- /dev/null +++ b/internal/codex/digbench.go @@ -0,0 +1,463 @@ +package codex + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "strings" + "time" + + "github.com/merefield/codexometer/internal/digbench" +) + +const defaultDigBenchTimeout = 30 * time.Minute + +// DigBenchOptions selects one deliberately bounded external benchmark run. +type DigBenchOptions struct { + Game string + Model string + Effort string + Timeout time.Duration + ClientVersion string +} + +// DigBenchResult is the terminal state and Codex telemetry for one game. +type DigBenchResult struct { + Game string + Model string + DisplayName string + Effort string + ActualModel string + Won bool + Status string + LevelsBeaten int + MaxLevel int + Steps int + Seed *int64 + FrameworkVersion string + Duration time.Duration + Usage BenchmarkUsage + UsageObserved bool + UsageKnown bool + UsageIssue string + UsageSource BenchmarkUsageSource + ResponseUsage []BenchmarkResponseUsage + CostUSD float64 + CostKnown bool + CostIssue string + Failure string +} + +type digBenchService interface { + StartSession(context.Context, digbench.StartRequest) (digbench.Session, error) + GetSession(context.Context, string) (digbench.Session, error) + Step(context.Context, string, digbench.StepRequest) (digbench.StepResponse, error) +} + +// RunDigBench runs one game through Codex's agentic tool loop. The remote game +// session is created only after the requested model and effort are validated. +func (c Client) RunDigBench(ctx context.Context, service digBenchService, options DigBenchOptions) (DigBenchResult, error) { + if service == nil { + return DigBenchResult{}, errors.New("DigBench client is required") + } + options.Game = strings.TrimSpace(options.Game) + options.Model = strings.TrimSpace(options.Model) + options.Effort = strings.TrimSpace(options.Effort) + if options.Game == "" || options.Model == "" || options.Effort == "" { + return DigBenchResult{}, errors.New("DigBench game, model, and effort are required") + } + if options.Timeout <= 0 { + options.Timeout = defaultDigBenchTimeout + } + + server, err := openBenchmarkAppServer(ctx, c.Binary) + if err != nil { + return DigBenchResult{}, err + } + defer server.close() + if !server.experimentalAPI { + return DigBenchResult{}, errors.New("DigBench requires a Codex CLI with experimental dynamic-tool support") + } + models, err := server.models(ctx) + if err != nil { + return DigBenchResult{}, err + } + combination, err := findDigBenchCombination(models, options.Model, options.Effort) + if err != nil { + return DigBenchResult{}, err + } + return server.runDigBench(ctx, service, combination, options) +} + +func findDigBenchCombination(models []benchmarkModel, modelID, effort string) (benchmarkCombination, error) { + for _, combination := range benchmarkCombinations(models) { + if combination.model.Model == modelID && combination.effort == effort { + return combination, nil + } + } + return benchmarkCombination{}, fmt.Errorf("Codex model/effort combination %s/%s is unavailable", modelID, effort) +} + +func (s *appServerSession) runDigBench( + ctx context.Context, + service digBenchService, + combination benchmarkCombination, + options DigBenchOptions, +) (DigBenchResult, error) { + result := DigBenchResult{ + Game: options.Game, Model: combination.model.Model, + DisplayName: combination.model.DisplayName, Effort: combination.effort, + ActualModel: combination.model.Model, + } + runCtx, cancel := context.WithTimeout(ctx, options.Timeout) + defer cancel() + + temporary, err := os.MkdirTemp("", "codexometer-digbench-") + if err != nil { + return result, fmt.Errorf("create isolated DigBench workspace: %w", err) + } + defer os.RemoveAll(temporary) + + threadParams := map[string]any{ + "model": combination.model.Model, "cwd": temporary, + "approvalPolicy": "never", "sandbox": "workspace-write", "ephemeral": true, + "serviceName": "codexometer-digbench", + "developerInstructions": "Play only the assigned DigBench session. Use its scoped tools for game access, keep useful notes in the isolated workspace if needed, and stop calling tools as soon as the game is done.", + "dynamicTools": digBenchDynamicTools(), + } + if s.experimentalRawEvents { + threadParams["experimentalRawEvents"] = true + } + threadResult, err := s.call(runCtx, "thread/start", threadParams, nil) + if err != nil && s.experimentalRawEvents && experimentalAPIUnsupported(err) { + s.experimentalRawEvents = false + delete(threadParams, "experimentalRawEvents") + threadResult, err = s.call(runCtx, "thread/start", threadParams, nil) + } + if err != nil { + return result, fmt.Errorf("start DigBench Codex thread: %w", err) + } + var startedThread struct { + Thread struct { + ID string `json:"id"` + } `json:"thread"` + Model string `json:"model"` + } + if err := json.Unmarshal(threadResult, &startedThread); err != nil || startedThread.Thread.ID == "" { + return result, errors.New("Codex returned an invalid DigBench thread") + } + if startedThread.Model != "" { + result.ActualModel = startedThread.Model + } + + modelName := combination.model.Model + "/" + combination.effort + " via Codexometer" + modelVersion := strings.TrimSpace(options.ClientVersion) + startRequest := digbench.StartRequest{Game: options.Game, ModelName: &modelName} + if modelVersion != "" { + startRequest.ModelVersion = &modelVersion + } + session, err := service.StartSession(runCtx, startRequest) + if err != nil { + return result, fmt.Errorf("start DigBench game: %w", err) + } + applyDigBenchSession(&result, session) + + startedAt := time.Now() + turnParams := map[string]any{ + "threadId": startedThread.Thread.ID, + "input": []map[string]any{{"type": "text", "text": digBenchPrompt(session)}}, + } + if combination.effort != "default" && combination.effort != "" { + turnParams["effort"] = combination.effort + } + turnResponse, err := s.call(runCtx, "turn/start", turnParams, nil) + if err != nil { + return result, fmt.Errorf("start DigBench turn: %w", err) + } + var startedTurn struct { + Turn struct { + ID string `json:"id"` + } `json:"turn"` + } + if err := json.Unmarshal(turnResponse, &startedTurn); err != nil || startedTurn.Turn.ID == "" { + return result, errors.New("Codex returned an invalid DigBench turn") + } + + telemetry := newBenchmarkTelemetry() + completed := false + turnFailure := "" + for !completed { + envelope, envelopeErr := s.nextPendingEnvelope(runCtx) + if envelopeErr != nil { + result.Duration = time.Since(startedAt) + if recoverableBenchmarkTimeout(ctx, runCtx, envelopeErr) { + result.Failure = fmt.Sprintf("DigBench run timed out after %s", options.Timeout) + cleanupCompleted := false + handle := func(method string, params json.RawMessage) bool { + if method == "turn/completed" && digBenchTurnCompleted(params, startedThread.Thread.ID, startedTurn.Turn.ID, &turnFailure) { + cleanupCompleted = true + return true + } + return false + } + if interruptErr := s.interruptBenchmarkTurn(ctx, startedThread.Thread.ID, startedTurn.Turn.ID, &cleanupCompleted, handle); interruptErr != nil { + return result, fmt.Errorf("interrupt timed-out DigBench turn: %w", interruptErr) + } + applyDigBenchMeasurements(&result, telemetry) + if session.Done { + result.Failure = "" + } + return result, nil + } + return result, envelopeErr + } + if len(envelope.ID) > 0 && envelope.Method != "" { + if envelope.Method != "item/tool/call" { + return result, fmt.Errorf("unsupported Codex app-server request %q", envelope.Method) + } + response := handleDigBenchToolCall( + runCtx, service, startedThread.Thread.ID, startedTurn.Turn.ID, + session.SessionID, envelope.Params, &session, + ) + applyDigBenchSession(&result, session) + if err := s.respond(envelope.ID, response); err != nil { + return result, fmt.Errorf("respond to DigBench tool call: %w", err) + } + continue + } + switch envelope.Method { + case "thread/tokenUsage/updated": + var event struct { + ThreadID string `json:"threadId"` + TurnID string `json:"turnId"` + TokenUsage struct { + Total BenchmarkUsage `json:"total"` + } `json:"tokenUsage"` + } + if json.Unmarshal(envelope.Params, &event) == nil && event.ThreadID == startedThread.Thread.ID && event.TurnID == startedTurn.Turn.ID { + telemetry.recordCumulative(event.TokenUsage.Total) + } + case "rawResponse/completed": + var event struct { + ThreadID string `json:"threadId"` + TurnID string `json:"turnId"` + ResponseID string `json:"responseId"` + Usage *BenchmarkUsage `json:"usage"` + } + if json.Unmarshal(envelope.Params, &event) == nil && event.ThreadID == startedThread.Thread.ID && event.TurnID == startedTurn.Turn.ID { + telemetry.recordRawResponse(event.ResponseID, event.Usage) + } + case "model/rerouted": + var event struct { + ThreadID string `json:"threadId"` + TurnID string `json:"turnId"` + ToModel string `json:"toModel"` + } + if json.Unmarshal(envelope.Params, &event) == nil && event.ThreadID == startedThread.Thread.ID && event.TurnID == startedTurn.Turn.ID && event.ToModel != "" { + result.ActualModel = event.ToModel + } + case "turn/completed": + completed = digBenchTurnCompleted(envelope.Params, startedThread.Thread.ID, startedTurn.Turn.ID, &turnFailure) + } + } + + result.Duration = time.Since(startedAt) + applyDigBenchMeasurements(&result, telemetry) + if session.Done { + result.Won = session.State.Status == "completed" + return result, nil + } + if turnFailure != "" { + result.Failure = turnFailure + return result, nil + } + result.Failure = "Codex stopped before the DigBench game ended" + return result, nil +} + +func digBenchDynamicTools() []map[string]any { + sessionProperty := map[string]any{"type": "string", "description": "The assigned DigBench session_id."} + return []map[string]any{ + { + "type": "function", "name": "get_session", + "description": "Re-read the authoritative state of the assigned DigBench game session.", + "inputSchema": map[string]any{ + "type": "object", "properties": map[string]any{"session_id": sessionProperty}, + "required": []string{"session_id"}, "additionalProperties": false, + }, + }, + { + "type": "function", "name": "step", + "description": "Apply exactly one legal action to the assigned DigBench game session.", + "inputSchema": map[string]any{ + "type": "object", + "properties": map[string]any{ + "session_id": sessionProperty, + "step_index": map[string]any{"type": "integer", "minimum": 1, "description": "The server's last returned step_index plus one."}, + "action": map[string]any{"type": "string", "description": "Exactly one string from the current state's actions list."}, + }, + "required": []string{"session_id", "step_index", "action"}, "additionalProperties": false, + }, + }, + } +} + +func digBenchPrompt(session digbench.Session) string { + state, _ := json.Marshal(session.State) + return fmt.Sprintf(`We are not going to tell you the rules of this game—you have to figure them out for yourself. + +The aim is to reach as high a level as possible. You advance by reaching unknown states. Each level has a limited number of steps; exhausting them or reaching certain states can cost a life. Losing all lives ends the game. + +Creative mode is available when "/" appears in the state's actions list. Use the step tool with action "/" to enter or leave it. Creative mode permits experimentation without consuming ordinary steps or lives, but has its own finite budget. + +Your game session is already started: session_id=%q, game=%q. Do not start or choose another game. Use only get_session and step for game access, and pass this session_id to every call. + +Starting step_index: %d. Your first move must use step_index %d. +Initial state: +%s + +Each move must use exactly one string from the latest state's actions list and the latest returned step_index plus one. Infer the rules from state changes, keep useful notes if helpful, and continue at a deliberate but efficient pace until state.done is true. Then stop making moves and give a concise debrief of the mechanics, objective, strategy, and uncertainties.`, + session.SessionID, session.Game, session.StepIndex, session.StepIndex+1, state) +} + +func handleDigBenchToolCall( + ctx context.Context, + service digBenchService, + threadID string, + turnID string, + sessionID string, + params json.RawMessage, + current *digbench.Session, +) map[string]any { + var call struct { + ThreadID string `json:"threadId"` + TurnID string `json:"turnId"` + Tool string `json:"tool"` + Arguments json.RawMessage `json:"arguments"` + } + if err := json.Unmarshal(params, &call); err != nil { + return digBenchToolResponse(nil, fmt.Errorf("decode tool request: %w", err)) + } + if call.ThreadID != threadID || call.TurnID != turnID { + return digBenchToolResponse(nil, errors.New("access denied: tool call belongs to another Codex turn")) + } + var common struct { + SessionID string `json:"session_id"` + } + if err := json.Unmarshal(call.Arguments, &common); err != nil { + return digBenchToolResponse(nil, fmt.Errorf("decode %s arguments: %w", call.Tool, err)) + } + if common.SessionID != sessionID { + return digBenchToolResponse(nil, errors.New("access denied: tool is scoped to the assigned session")) + } + switch call.Tool { + case "get_session": + session, err := service.GetSession(ctx, sessionID) + if err == nil { + *current = session + } + return digBenchToolResponse(session, err) + case "step": + var arguments struct { + SessionID string `json:"session_id"` + StepIndex int `json:"step_index"` + Action string `json:"action"` + } + if err := json.Unmarshal(call.Arguments, &arguments); err != nil { + return digBenchToolResponse(nil, fmt.Errorf("decode step arguments: %w", err)) + } + response, err := service.Step(ctx, sessionID, digbench.StepRequest{Action: arguments.Action, StepIndex: arguments.StepIndex}) + if err == nil { + *current = response.Session + } + return digBenchToolResponse(response, err) + default: + return digBenchToolResponse(nil, fmt.Errorf("unknown DigBench tool %q", call.Tool)) + } +} + +func digBenchToolResponse(value any, err error) map[string]any { + success := err == nil + var data []byte + if err != nil { + data, _ = json.Marshal(map[string]string{"error": err.Error()}) + } else { + data, err = json.Marshal(value) + if err != nil { + success = false + data, _ = json.Marshal(map[string]string{"error": "encode DigBench tool response: " + err.Error()}) + } + } + return map[string]any{ + "contentItems": []map[string]string{{"type": "inputText", "text": string(data)}}, + "success": success, + } +} + +func applyDigBenchSession(result *DigBenchResult, session digbench.Session) { + result.Game = session.Game + result.Status = session.State.Status + result.LevelsBeaten = session.LevelsBeaten + result.Steps = session.StepIndex + result.Seed = session.Seed + if session.State.MaxLevel != nil { + result.MaxLevel = *session.State.MaxLevel + } + if session.FrameworkVersion != nil { + result.FrameworkVersion = *session.FrameworkVersion + } + result.Won = session.Done && session.State.Done && session.State.Status == "completed" +} + +func digBenchTurnCompleted(params json.RawMessage, threadID, turnID string, failure *string) bool { + var event struct { + ThreadID string `json:"threadId"` + Turn struct { + ID string `json:"id"` + Status string `json:"status"` + Error *struct { + Message string `json:"message"` + } `json:"error"` + } `json:"turn"` + } + if json.Unmarshal(params, &event) != nil || event.ThreadID != threadID || event.Turn.ID != turnID { + return false + } + if event.Turn.Status != "completed" { + *failure = "turn " + event.Turn.Status + if event.Turn.Error != nil && event.Turn.Error.Message != "" { + *failure += ": " + event.Turn.Error.Message + } + } + return true +} + +func applyDigBenchMeasurements(result *DigBenchResult, telemetry *benchmarkTelemetry) { + var measurements BenchmarkResult + telemetry.apply(&measurements) + result.Usage = measurements.Usage + result.UsageObserved = measurements.UsageObserved + result.UsageKnown = measurements.UsageKnown + result.UsageIssue = measurements.UsageIssue + result.UsageSource = measurements.UsageSource + result.ResponseUsage = measurements.ResponseUsage + if !result.UsageKnown { + result.CostIssue = result.UsageIssue + return + } + if result.UsageSource != BenchmarkUsageRawResponses { + result.CostUSD, result.CostKnown, result.CostIssue = estimateAPICostWithIssue(result.ActualModel, result.Usage) + return + } + result.CostKnown = true + for _, response := range result.ResponseUsage { + cost, known, issue := estimateSingleResponseAPICostWithIssue(result.ActualModel, response.Usage) + if !known { + result.CostUSD, result.CostKnown, result.CostIssue = 0, false, issue + return + } + result.CostUSD += cost + } +} diff --git a/internal/codex/digbench_test.go b/internal/codex/digbench_test.go new file mode 100644 index 00000000..a7e89026 --- /dev/null +++ b/internal/codex/digbench_test.go @@ -0,0 +1,128 @@ +package codex + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" + + "github.com/merefield/codexometer/internal/digbench" +) + +type fakeDigBenchService struct { + started digbench.StartRequest + session digbench.Session + stepCalls int +} + +func (f *fakeDigBenchService) StartSession(_ context.Context, request digbench.StartRequest) (digbench.Session, error) { + f.started = request + return f.session, nil +} + +func (f *fakeDigBenchService) GetSession(context.Context, string) (digbench.Session, error) { + return f.session, nil +} + +func (f *fakeDigBenchService) Step(_ context.Context, _ string, request digbench.StepRequest) (digbench.StepResponse, error) { + f.stepCalls++ + maxLevel := 3 + f.session = digbench.Session{ + Game: "P-1", SessionID: "session-1", Done: true, StepIndex: request.StepIndex, + LevelsBeaten: 3, Seed: f.session.Seed, FrameworkVersion: f.session.FrameworkVersion, + State: digbench.State{Done: true, Status: "completed", Level: 3, MaxLevel: &maxLevel, Observation: "WIN"}, + } + return digbench.StepResponse{Session: f.session}, nil +} + +func TestRunDigBenchBridgesScopedStepAndDetectsWin(t *testing.T) { + seed := int64(42) + framework := "engine-1" + maxLevel := 3 + service := &fakeDigBenchService{session: digbench.Session{ + Game: "P-1", SessionID: "session-1", Seed: &seed, FrameworkVersion: &framework, + State: digbench.State{Status: "in_progress", Level: 1, MaxLevel: &maxLevel, Observation: "___", Actions: []string{"b"}}, + }} + usage := BenchmarkUsage{TotalTokens: 120, InputTokens: 100, OutputTokens: 20} + server, requests := newFakeBenchmarkServer( + benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{"data": []any{map[string]any{ + "model": "gpt-5.6-sol", "displayName": "GPT-5.6 Sol", + "supportedReasoningEfforts": []any{map[string]string{"reasoningEffort": "high"}}, + }}})}, + benchmarkEnvelope{ID: rawJSON(2), Result: rawJSON(map[string]any{ + "thread": map[string]string{"id": "thread-1"}, "model": "gpt-5.6-sol", + })}, + benchmarkEnvelope{ID: rawJSON(3), Result: rawJSON(map[string]any{"turn": map[string]string{"id": "turn-1"}})}, + benchmarkEnvelope{ID: rawJSON(50), Method: "item/tool/call", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turnId": "turn-1", "callId": "call-1", "tool": "step", + "arguments": map[string]any{"session_id": "session-1", "step_index": 1, "action": "b"}, + })}, + benchmarkEnvelope{Method: "thread/tokenUsage/updated", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turnId": "turn-1", "tokenUsage": map[string]any{"total": usage}, + })}, + benchmarkEnvelope{Method: "turn/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turn": map[string]any{ + "id": "turn-1", "status": "failed", "error": map[string]string{"message": "debrief failed after terminal move"}, + }, + })}, + ) + server.experimentalAPI = true + + original := openBenchmarkAppServer + openBenchmarkAppServer = func(context.Context, string) (*appServerSession, error) { return server, nil } + t.Cleanup(func() { openBenchmarkAppServer = original }) + + result, err := (Client{}).RunDigBench(context.Background(), service, DigBenchOptions{ + Game: "P-1", Model: "gpt-5.6-sol", Effort: "high", Timeout: time.Minute, ClientVersion: "test", + }) + if err != nil { + t.Fatal(err) + } + if !result.Won || result.Failure != "" || result.Status != "completed" || result.LevelsBeaten != 3 || result.MaxLevel != 3 || result.Steps != 1 { + t.Fatalf("result = %#v", result) + } + if service.stepCalls != 1 || service.started.ModelName == nil || !strings.Contains(*service.started.ModelName, "gpt-5.6-sol/high") { + t.Fatalf("service = %#v", service) + } + if !result.UsageKnown || result.Usage != usage || !result.CostKnown { + t.Fatalf("telemetry = %#v", result) + } + requestLog := requests.String() + for _, expected := range []string{`"dynamicTools"`, `"sandbox":"workspace-write"`, `"method":"turn/start"`, `"id":50`, `"success":true`, `\"status\":\"completed\"`} { + if !strings.Contains(requestLog, expected) { + t.Fatalf("request log missing %q: %s", expected, requestLog) + } + } +} + +func TestDigBenchToolRejectsAnotherSession(t *testing.T) { + service := &fakeDigBenchService{session: digbench.Session{SessionID: "session-1"}} + current := service.session + params, _ := json.Marshal(map[string]any{ + "threadId": "thread-1", "turnId": "turn-1", "tool": "step", + "arguments": map[string]any{"session_id": "session-2", "step_index": 1, "action": "a"}, + }) + response := handleDigBenchToolCall(context.Background(), service, "thread-1", "turn-1", "session-1", params, ¤t) + if response["success"] != false || service.stepCalls != 0 { + t.Fatalf("response = %#v, calls = %d", response, service.stepCalls) + } + content := response["contentItems"].([]map[string]string) + if !strings.Contains(content[0]["text"], "access denied") { + t.Fatalf("response = %#v", response) + } +} + +func TestFindDigBenchCombinationRequiresExactEffort(t *testing.T) { + models := []benchmarkModel{{ + Model: "gpt-5.6-sol", DisplayName: "GPT-5.6 Sol", + SupportedReasoningEfforts: []benchmarkEffortOption{{ReasoningEffort: "medium"}, {ReasoningEffort: "high"}}, + }} + combination, err := findDigBenchCombination(models, "gpt-5.6-sol", "high") + if err != nil || combination.effort != "high" { + t.Fatalf("combination = %#v, error = %v", combination, err) + } + if _, err := findDigBenchCombination(models, "gpt-5.6-sol", "max"); err == nil { + t.Fatal("unsupported effort was accepted") + } +} diff --git a/internal/digbench/client.go b/internal/digbench/client.go new file mode 100644 index 00000000..ba8b5664 --- /dev/null +++ b/internal/digbench/client.go @@ -0,0 +1,282 @@ +package digbench + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +const ( + DefaultBaseURL = "https://api.digbench.ai/api/agent" + maxResponseSize = 1 << 20 + maxStepAttempts = 4 +) + +// Client is the minimal DigBench Agent REST API client used by the proof of concept. +type Client struct { + BaseURL string + Token string + HTTPClient *http.Client +} + +type GameDetail struct { + Name string `json:"name"` + Tier *int `json:"tier"` +} + +type GamesResponse struct { + Games []string `json:"games"` + GameDetails []GameDetail `json:"game_details"` +} + +type State struct { + Actions []string `json:"actions"` + Done bool `json:"done"` + Level int `json:"level"` + LivesLeft *int `json:"lives_left"` + MaxLevel *int `json:"max_level"` + MaxSteps *int `json:"max_steps"` + Mode *string `json:"mode"` + Observation string `json:"observation"` + StartingLives *int `json:"starting_lives"` + Status string `json:"status"` + StepsRemaining any `json:"steps_remaining"` + Transition *string `json:"transition"` +} + +type Session struct { + Description string `json:"description"` + Done bool `json:"done"` + FrameworkVersion *string `json:"framework_version"` + Game string `json:"game"` + LevelsBeaten int `json:"levels_beaten"` + MoveSchema json.RawMessage `json:"move_schema"` + Seed *int64 `json:"seed"` + SessionID string `json:"session_id"` + State State `json:"state"` + StepIndex int `json:"step_index"` +} + +type StartRequest struct { + Game string `json:"game"` + ModelName *string `json:"model_name,omitempty"` + ModelVersion *string `json:"model_version,omitempty"` + Notes *string `json:"notes,omitempty"` +} + +type StepRequest struct { + Action string `json:"action"` + Reasoning *string `json:"reasoning,omitempty"` + StepIndex int `json:"step_index"` +} + +type StepResponse struct { + Session + InvalidAction *bool `json:"invalid_action"` +} + +type APIError struct { + StatusCode int + Detail string + RetryAfter time.Duration +} + +func (e *APIError) Error() string { + if strings.TrimSpace(e.Detail) == "" { + return fmt.Sprintf("DigBench API returned HTTP %d", e.StatusCode) + } + return fmt.Sprintf("DigBench API returned HTTP %d: %s", e.StatusCode, e.Detail) +} + +func (c Client) ListGames(ctx context.Context) (GamesResponse, error) { + var response GamesResponse + err := c.do(ctx, http.MethodGet, "/games", nil, true, false, &response) + return response, err +} + +// StartSession intentionally does not retry. POST /sessions is not documented +// as idempotent, so retrying a lost response could create an orphaned second run. +func (c Client) StartSession(ctx context.Context, request StartRequest) (Session, error) { + var response Session + if strings.TrimSpace(request.Game) == "" { + return response, errors.New("DigBench game is required") + } + err := c.do(ctx, http.MethodPost, "/sessions", request, true, false, &response) + if err == nil { + err = validateSession(response) + } + return response, err +} + +func (c Client) GetSession(ctx context.Context, sessionID string) (Session, error) { + var response Session + if strings.TrimSpace(sessionID) == "" { + return response, errors.New("DigBench session id is required") + } + path := "/sessions/" + url.PathEscape(sessionID) + err := c.do(ctx, http.MethodGet, path, nil, false, true, &response) + if err == nil { + err = validateSession(response) + } + return response, err +} + +func (c Client) Step(ctx context.Context, sessionID string, request StepRequest) (StepResponse, error) { + var response StepResponse + if strings.TrimSpace(sessionID) == "" { + return response, errors.New("DigBench session id is required") + } + if strings.TrimSpace(request.Action) == "" { + return response, errors.New("DigBench action is required") + } + if request.StepIndex < 1 { + return response, errors.New("DigBench step index must be positive") + } + path := "/sessions/" + url.PathEscape(sessionID) + "/step" + err := c.do(ctx, http.MethodPost, path, request, false, true, &response) + if err == nil { + err = validateSession(response.Session) + } + return response, err +} + +func (c Client) do(ctx context.Context, method, path string, body any, bearer, retry bool, output any) error { + base := strings.TrimRight(strings.TrimSpace(c.BaseURL), "/") + if base == "" { + base = DefaultBaseURL + } + if bearer && strings.TrimSpace(c.Token) == "" { + return errors.New("DIGBENCH_API_TOKEN is required") + } + payload, err := json.Marshal(body) + if err != nil { + return fmt.Errorf("encode DigBench request: %w", err) + } + if body == nil { + payload = nil + } + attempts := 1 + if retry { + attempts = maxStepAttempts + } + var retryAfter time.Duration + for attempt := 0; attempt < attempts; attempt++ { + if attempt > 0 { + delay := retryAfter + if delay <= 0 { + delay = time.Duration(1<<(attempt-1)) * 250 * time.Millisecond + } + retryAfter = 0 + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(delay): + } + } + request, err := http.NewRequestWithContext(ctx, method, base+path, bytes.NewReader(payload)) + if err != nil { + return fmt.Errorf("create DigBench request: %w", err) + } + request.Header.Set("Accept", "application/json") + if body != nil { + request.Header.Set("Content-Type", "application/json") + } + if bearer { + request.Header.Set("Authorization", "Bearer "+strings.TrimSpace(c.Token)) + } else { + request.Header.Set("X-Session-ID", strings.TrimSpace(pathSessionID(path))) + } + client := c.HTTPClient + if client == nil { + client = http.DefaultClient + } + response, err := client.Do(request) + if err != nil { + if retry && attempt+1 < attempts && ctx.Err() == nil { + continue + } + return fmt.Errorf("call DigBench API: %w", err) + } + data, readErr := io.ReadAll(io.LimitReader(response.Body, maxResponseSize+1)) + closeErr := response.Body.Close() + if readErr != nil { + if retry && attempt+1 < attempts { + continue + } + return fmt.Errorf("read DigBench response: %w", readErr) + } + if closeErr != nil { + return fmt.Errorf("close DigBench response: %w", closeErr) + } + if len(data) > maxResponseSize { + return errors.New("DigBench response exceeds 1 MiB") + } + if response.StatusCode < 200 || response.StatusCode >= 300 { + apiErr := decodeAPIError(response, data) + if retry && attempt+1 < attempts && (response.StatusCode == http.StatusTooManyRequests || response.StatusCode >= 500) { + retryAfter = apiErr.RetryAfter + continue + } + return apiErr + } + if err := json.Unmarshal(data, output); err != nil { + return fmt.Errorf("decode DigBench response: %w", err) + } + return nil + } + return errors.New("DigBench request exhausted retries") +} + +func pathSessionID(path string) string { + parts := strings.Split(strings.Trim(path, "/"), "/") + if len(parts) < 2 || parts[0] != "sessions" { + return "" + } + value, err := url.PathUnescape(parts[1]) + if err != nil { + return parts[1] + } + return value +} + +func decodeAPIError(response *http.Response, data []byte) *APIError { + var payload struct { + Detail string `json:"detail"` + } + _ = json.Unmarshal(data, &payload) + retryAfter := time.Duration(0) + if seconds, err := strconv.Atoi(strings.TrimSpace(response.Header.Get("Retry-After"))); err == nil && seconds > 0 { + retryAfter = time.Duration(seconds) * time.Second + } + return &APIError{StatusCode: response.StatusCode, Detail: payload.Detail, RetryAfter: retryAfter} +} + +func validateSession(session Session) error { + if strings.TrimSpace(session.SessionID) == "" { + return errors.New("DigBench response omitted session id") + } + if session.StepIndex < 0 || session.LevelsBeaten < 0 { + return errors.New("DigBench response contained a negative progress counter") + } + switch session.State.Status { + case "in_progress": + if session.Done || session.State.Done { + return errors.New("DigBench response marked an in-progress game done") + } + case "completed", "game_over": + if !session.Done || !session.State.Done { + return errors.New("DigBench terminal status did not set done") + } + default: + return fmt.Errorf("DigBench response returned unknown status %q", session.State.Status) + } + return nil +} diff --git a/internal/digbench/client_test.go b/internal/digbench/client_test.go new file mode 100644 index 00000000..17cfcbe7 --- /dev/null +++ b/internal/digbench/client_test.go @@ -0,0 +1,115 @@ +package digbench + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" +) + +func TestStartSessionUsesBearerAndDecodesState(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.Method != http.MethodPost || request.URL.Path != "/sessions" { + t.Fatalf("request = %s %s", request.Method, request.URL.Path) + } + if authorization := request.Header.Get("Authorization"); authorization != "Bearer secret" { + t.Fatalf("authorization = %q", authorization) + } + body, err := io.ReadAll(request.Body) + if err != nil || !strings.Contains(string(body), `"game":"P-1"`) { + t.Fatalf("body = %q, err = %v", body, err) + } + writer.Header().Set("Content-Type", "application/json") + _, _ = writer.Write([]byte(`{ + "session_id":"session-1","game":"P-1","step_index":0, + "done":false,"levels_beaten":0,"seed":42,"framework_version":"abc", + "state":{"status":"in_progress","done":false,"level":1,"max_level":3, + "observation":"___","actions":["a","b"]} + }`)) + })) + defer server.Close() + + client := Client{BaseURL: server.URL, Token: "secret", HTTPClient: server.Client()} + model := "gpt-5.6-sol" + session, err := client.StartSession(context.Background(), StartRequest{Game: "P-1", ModelName: &model}) + if err != nil { + t.Fatal(err) + } + if session.SessionID != "session-1" || session.Seed == nil || *session.Seed != 42 || session.State.MaxLevel == nil || *session.State.MaxLevel != 3 { + t.Fatalf("session = %#v", session) + } +} + +func TestStepUsesSessionScopeRetriesAndDetectsWin(t *testing.T) { + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.Header.Get("Authorization") != "" || request.Header.Get("X-Session-ID") != "session-1" { + t.Fatalf("unexpected authentication headers: %#v", request.Header) + } + if calls.Add(1) == 1 { + writer.WriteHeader(http.StatusBadGateway) + _, _ = writer.Write([]byte(`{"detail":"temporary"}`)) + return + } + writer.Header().Set("Content-Type", "application/json") + _, _ = writer.Write([]byte(`{ + "session_id":"session-1","step_index":7,"done":true,"levels_beaten":3, + "state":{"status":"completed","done":true,"level":3,"max_level":3, + "observation":"WIN","actions":[]} + }`)) + })) + defer server.Close() + + client := Client{BaseURL: server.URL, HTTPClient: server.Client()} + response, err := client.Step(context.Background(), "session-1", StepRequest{Action: "b", StepIndex: 7}) + if err != nil { + t.Fatal(err) + } + if calls.Load() != 2 || !response.Done || !response.State.Done || response.State.Status != "completed" || response.LevelsBeaten != 3 { + t.Fatalf("calls = %d, response = %#v", calls.Load(), response) + } +} + +func TestStartSessionDoesNotRetryAnAmbiguousFailure(t *testing.T) { + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { + calls.Add(1) + writer.WriteHeader(http.StatusInternalServerError) + _, _ = writer.Write([]byte(`{"detail":"unknown commit state"}`)) + })) + defer server.Close() + + client := Client{BaseURL: server.URL, Token: "secret", HTTPClient: server.Client()} + _, err := client.StartSession(context.Background(), StartRequest{Game: "P-1"}) + var apiErr *APIError + if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusInternalServerError || calls.Load() != 1 { + t.Fatalf("calls = %d, error = %v", calls.Load(), err) + } +} + +func TestSessionValidationRejectsContradictoryOutcome(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { + _, _ = writer.Write([]byte(`{ + "session_id":"session-1","step_index":1,"done":true,"levels_beaten":1, + "state":{"status":"completed","done":false,"level":1,"observation":"?","actions":[]} + }`)) + })) + defer server.Close() + + client := Client{BaseURL: server.URL, HTTPClient: server.Client()} + _, err := client.GetSession(context.Background(), "session-1") + if err == nil || !strings.Contains(err.Error(), "terminal status did not set done") { + t.Fatalf("error = %v", err) + } +} + +func TestBearerOperationsRequireToken(t *testing.T) { + _, err := (Client{}).ListGames(context.Background()) + if err == nil || !strings.Contains(err.Error(), "DIGBENCH_API_TOKEN") { + t.Fatalf("error = %v", err) + } +} diff --git a/main.go b/main.go index 0a7288cc..f4b0e318 100644 --- a/main.go +++ b/main.go @@ -6,12 +6,14 @@ import ( "fmt" "io" "os" + "strings" "sync" "time" tea "charm.land/bubbletea/v2" "github.com/merefield/codexometer/internal/codex" + "github.com/merefield/codexometer/internal/digbench" "github.com/merefield/codexometer/internal/ui" "github.com/merefield/codexometer/internal/version" ) @@ -151,8 +153,9 @@ func main() { } type dependencies struct { - checkAuth func(context.Context, string) (codex.Snapshot, error) - startUI func(ui.Fetcher, time.Duration, bool) error + checkAuth func(context.Context, string) (codex.Snapshot, error) + runDigBench func(context.Context, string, string, codex.DigBenchOptions) (codex.DigBenchResult, error) + startUI func(ui.Fetcher, time.Duration, bool) error } func defaultDependencies() dependencies { @@ -160,6 +163,9 @@ func defaultDependencies() dependencies { checkAuth: func(ctx context.Context, binary string) (codex.Snapshot, error) { return (codex.Client{Binary: binary}).Fetch(ctx) }, + runDigBench: func(ctx context.Context, binary, token string, options codex.DigBenchOptions) (codex.DigBenchResult, error) { + return (codex.Client{Binary: binary}).RunDigBench(ctx, digbench.Client{Token: token}, options) + }, startUI: startUI, } } @@ -168,12 +174,16 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { flags := flag.NewFlagSet("codexometer", flag.ContinueOnError) flags.SetOutput(stderr) var ( - codexPath = flags.String("codex", "codex", "path to the Codex CLI") - refresh = flags.Duration("refresh", time.Minute, "quota refresh interval") - demo = flags.Bool("demo", false, "show the UI with simulated quota data") - inline = flags.Bool("inline", false, "render inline instead of using the alternate screen") - checkAuth = flags.Bool("check-auth", false, "verify access to the current Codex login and exit") - printVersion bool + codexPath = flags.String("codex", "codex", "path to the Codex CLI") + refresh = flags.Duration("refresh", time.Minute, "quota refresh interval") + demo = flags.Bool("demo", false, "show the UI with simulated quota data") + inline = flags.Bool("inline", false, "render inline instead of using the alternate screen") + checkAuth = flags.Bool("check-auth", false, "verify access to the current Codex login and exit") + digBenchGame = flags.String("digbench-game", "", "run one experimental DigBench game and exit") + digBenchModel = flags.String("digbench-model", "gpt-5.6-sol", "Codex model for --digbench-game") + digBenchEffort = flags.String("digbench-effort", "high", "reasoning effort for --digbench-game") + digBenchTimeout = flags.Duration("digbench-timeout", 30*time.Minute, "hard limit for --digbench-game") + printVersion bool ) flags.BoolVar(&printVersion, "version", false, "print the version and exit") flags.BoolVar(&printVersion, "v", false, "print the version and exit") @@ -194,6 +204,39 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { fmt.Fprintf(stdout, "Codex auth OK // %d limit meter(s) online\n", len(snapshot.Meters())) return 0 } + if strings.TrimSpace(*digBenchGame) != "" { + if *demo { + fmt.Fprintln(stderr, "codexometer: --digbench-game cannot be combined with --demo") + return 2 + } + token := strings.TrimSpace(os.Getenv("DIGBENCH_API_TOKEN")) + if token == "" { + fmt.Fprintln(stderr, "codexometer: DIGBENCH_API_TOKEN is required for --digbench-game") + return 1 + } + if err := os.Unsetenv("DIGBENCH_API_TOKEN"); err != nil { + fmt.Fprintln(stderr, "codexometer: remove DIGBENCH_API_TOKEN from child environment:", err) + return 1 + } + if deps.runDigBench == nil { + fmt.Fprintln(stderr, "codexometer: DigBench runner unavailable") + return 1 + } + fmt.Fprintf(stderr, "Starting DigBench %s; this creates a persisted remote session and consumes Codex quota.\n", strings.TrimSpace(*digBenchGame)) + result, err := deps.runDigBench(context.Background(), *codexPath, token, codex.DigBenchOptions{ + Game: strings.TrimSpace(*digBenchGame), Model: strings.TrimSpace(*digBenchModel), + Effort: strings.TrimSpace(*digBenchEffort), Timeout: *digBenchTimeout, ClientVersion: version.Current(), + }) + if err != nil { + fmt.Fprintln(stderr, "codexometer: DigBench run failed:", err) + return 1 + } + fmt.Fprintln(stdout, formatDigBenchResult(result)) + if result.Failure != "" { + return 1 + } + return 0 + } client := codex.Client{Binary: *codexPath} if liveUsage, err := codex.NewLiveUsageReader(""); err == nil { @@ -211,6 +254,47 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { return 0 } +func formatDigBenchResult(result codex.DigBenchResult) string { + outcome := "LOSS" + if result.Won { + outcome = "WIN" + } else if result.Failure != "" { + outcome = "INCOMPLETE" + } + levels := fmt.Sprintf("%d", result.LevelsBeaten) + if result.MaxLevel > 0 { + levels = fmt.Sprintf("%d/%d", result.LevelsBeaten, result.MaxLevel) + } + tokens := "N/A" + if result.UsageKnown { + tokens = fmt.Sprintf("%d", result.Usage.TotalTokens) + } + cost := "N/A" + if result.CostKnown { + cost = fmt.Sprintf("$%.4f", result.CostUSD) + } + line := fmt.Sprintf("DIGBENCH %s // %s // LEVELS %s // STEPS %d // %s/%s // %s // TOKENS %s // API EQ %s", + result.Game, outcome, levels, result.Steps, result.DisplayName, result.Effort, + result.Duration.Round(time.Millisecond), tokens, cost) + if result.ActualModel != "" && result.ActualModel != result.Model { + line += " // SERVED " + result.ActualModel + } + if result.Seed != nil { + line += fmt.Sprintf(" // SEED %d", *result.Seed) + } + if result.FrameworkVersion != "" { + line += " // ENGINE " + result.FrameworkVersion + } + if result.Failure != "" { + line += " // " + result.Failure + } else if !result.UsageKnown && result.UsageIssue != "" { + line += " // TELEMETRY " + result.UsageIssue + } else if !result.CostKnown && result.CostIssue != "" { + line += " // API EQ " + result.CostIssue + } + return line +} + func startUI(fetcher ui.Fetcher, refresh time.Duration, inline bool) error { model := ui.New(fetcher, refresh) if store, storeErr := ui.NewDefaultPreferenceStore(); storeErr == nil { diff --git a/main_test.go b/main_test.go index c6d5c91d..588f55f2 100644 --- a/main_test.go +++ b/main_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "os" "strings" "testing" "time" @@ -118,9 +119,47 @@ func TestRunReportsUIError(t *testing.T) { } } +func TestRunDigBenchUsesExplicitSingleGameOptions(t *testing.T) { + t.Setenv("DIGBENCH_API_TOKEN", "secret") + var stdout, stderr bytes.Buffer + called := false + deps := dependencies{ + runDigBench: func(_ context.Context, binary, token string, options codex.DigBenchOptions) (codex.DigBenchResult, error) { + called = true + if value := os.Getenv("DIGBENCH_API_TOKEN"); value != "" { + t.Fatalf("DigBench token remained in child environment: %q", value) + } + if binary != "/custom/codex" || token != "secret" || options.Game != "P-3" || options.Model != "gpt-5.6-terra" || options.Effort != "medium" || options.Timeout != 2*time.Minute { + t.Fatalf("binary=%q token=%q options=%#v", binary, token, options) + } + return codex.DigBenchResult{ + Game: "P-3", Won: true, Status: "completed", LevelsBeaten: 4, MaxLevel: 4, Steps: 17, + DisplayName: "GPT-5.6 Terra", Effort: "medium", Duration: 3 * time.Second, + UsageKnown: true, Usage: codex.BenchmarkUsage{TotalTokens: 1234}, CostKnown: true, CostUSD: 0.0123, + }, nil + }, + } + code := run([]string{ + "--digbench-game", "P-3", "--digbench-model", "gpt-5.6-terra", "--digbench-effort", "medium", + "--digbench-timeout", "2m", "--codex", "/custom/codex", + }, &stdout, &stderr, deps) + if code != 0 || !called || !strings.Contains(stdout.String(), "DIGBENCH P-3 // WIN // LEVELS 4/4") || !strings.Contains(stderr.String(), "persisted remote session") { + t.Fatalf("code=%d called=%v stdout=%q stderr=%q", code, called, stdout.String(), stderr.String()) + } +} + +func TestRunDigBenchRequiresToken(t *testing.T) { + t.Setenv("DIGBENCH_API_TOKEN", "") + var stdout, stderr bytes.Buffer + code := run([]string{"--digbench-game", "P-1"}, &stdout, &stderr, dependencies{}) + if code != 1 || !strings.Contains(stderr.String(), "DIGBENCH_API_TOKEN is required") { + t.Fatalf("code=%d stdout=%q stderr=%q", code, stdout.String(), stderr.String()) + } +} + func TestDefaultDependenciesAreConfigured(t *testing.T) { deps := defaultDependencies() - if deps.checkAuth == nil || deps.startUI == nil { + if deps.checkAuth == nil || deps.runDigBench == nil || deps.startUI == nil { t.Fatal("default dependencies are incomplete") } } From 56240c43e02319c810560719db17b3e719a2384a Mon Sep 17 00:00:00 2001 From: merefield Date: Fri, 21 Aug 2026 19:22:59 +0100 Subject: [PATCH 02/18] DOC: clarify benchmark authentication boundary --- README.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/README.md b/README.md index 51806bf5..2a98be2e 100644 --- a/README.md +++ b/README.md @@ -734,6 +734,42 @@ platform-standard user configuration directory: Missing, unreadable, or malformed preferences never prevent startup; Codexometer falls back to its safe defaults. +### Benchmark authentication and usage boundary + +> [!IMPORTANT] +> Codexometer's benchmarks are intended for a person running the local client +> with their own Codex authentication and quota. They are not a way to convert +> a ChatGPT subscription into general API traffic, re-serve model access, or +> share one person's included usage with other users. Do not deploy a shared +> benchmark service backed by one person's subscription. You remain responsible +> for complying with the terms and policies of OpenAI and each external +> benchmark provider; this project cannot guarantee that guidance or enforcement +> will remain unchanged. + +The justification for supporting the prevailing Codex login is that OpenAI's +[authentication documentation](https://learn.chatgpt.com/docs/auth) expressly +distinguishes **Sign in with ChatGPT** for subscription access from API-key +authentication for usage-based access. OpenAI also documents +[Codex app-server](https://learn.chatgpt.com/docs/app-server) as the interface +for embedding Codex into another product, including its ChatGPT login flows. A +[public clarification from OpenAI's Codex and ChatGPT lead](https://x.com/thsottiaux/status/2090675027670978569) +further says that using included subscription usage through **Sign in with +ChatGPT** is fine in official or OSS clients; it identifies converting a +subscription into API traffic for re-serving or sharing across users as the +unsupported pattern. That post is useful operational guidance, not a +contractual guarantee. + +Codexometer stays on the client side of that boundary: it invokes the official +local Codex app-server for the authenticated user, runs bounded user-triggered +trials, and reports results locally. It does not expose an inference API, +forward ChatGPT credentials, or offer another user access to the account. For +unattended automation, CI, or a centrally hosted benchmark service, use an +appropriately owned API-key-authenticated setup instead; OpenAI recommends API +key authentication for programmatic Codex CLI workflows and the +[Codex SDK](https://learn.chatgpt.com/docs/codex-sdk) for automated jobs and CI. +The separate DigBench token described below authorizes only DigBench and does +not change how Codex itself is authenticated. + ### Experimental DigBench agentic run Codexometer includes a deliberately narrow command-line proof of concept for From f418b4495a49556072a04766efb3f528f7658910 Mon Sep 17 00:00:00 2001 From: merefield Date: Fri, 21 Aug 2026 19:34:47 +0100 Subject: [PATCH 03/18] FEAT: prefer API keys for benchmark runs --- README.md | 39 ++++++++++++++--- internal/codex/benchmark.go | 75 +++++++++++++++++++++++++++----- internal/codex/benchmark_test.go | 63 +++++++++++++++++++++------ internal/codex/client.go | 3 ++ internal/codex/client_test.go | 23 +++++++++- internal/codex/digbench.go | 2 +- internal/codex/digbench_test.go | 11 ++++- main.go | 39 ++++++++++++++--- main_test.go | 51 ++++++++++++++++++++-- 9 files changed, 261 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index 2a98be2e..21863427 100644 --- a/README.md +++ b/README.md @@ -744,7 +744,8 @@ Codexometer falls back to its safe defaults. > benchmark service backed by one person's subscription. You remain responsible > for complying with the terms and policies of OpenAI and each external > benchmark provider; this project cannot guarantee that guidance or enforcement -> will remain unchanged. +> will remain unchanged. If you choose to run a benchmark with **Sign in with +> ChatGPT** subscription authentication, you do so at your own risk. The justification for supporting the prevailing Codex login is that OpenAI's [authentication documentation](https://learn.chatgpt.com/docs/auth) expressly @@ -770,6 +771,26 @@ key authentication for programmatic Codex CLI workflows and the The separate DigBench token described below authorizes only DigBench and does not change how Codex itself is authenticated. +For a clearer billing boundary, supply your own OpenAI API key. A dedicated key +takes precedence over the prevailing ChatGPT login for **all** benchmark model +discovery and runs, including DigBench: + +```sh +export CODEXOMETER_BENCHMARK_API_KEY="" +codexometer +``` + +`OPENAI_API_KEY` is accepted as a fallback when the dedicated variable is not +set. Codexometer removes both variables from its normal child environment and +passes the selected value only in the documented `account/login/start` request +to a benchmark-only app-server. That server uses a temporary `CODEX_HOME` and +ephemeral in-memory credential storage, so it neither replaces the normal Codex +login nor persists the key. API-authenticated trials use standard usage-based +API billing; quota monitoring continues to use the prevailing Codex login. +Environment variables may still be visible to other processes running as the +same operating-system user, so supply secrets only on a trusted local machine. +Neither key is written to preferences or accepted as a command-line argument. + ### Experimental DigBench agentic run Codexometer includes a deliberately narrow command-line proof of concept for @@ -798,8 +819,10 @@ codexometer --digbench-game P-3 \ ``` The command creates a fresh remote DigBench session, so invoking it is an -external write as well as a Codex-quota-consuming model run. DigBench persists -sessions and currently exposes no deletion endpoint. The token is read only +external write as well as a model run that consumes either Codex subscription +quota or usage-billed API tokens, according to the authentication choice above. +DigBench persists sessions and currently exposes no deletion endpoint. The +token is read only from `DIGBENCH_API_TOKEN`, is never written to Codexometer preferences, and is removed from the process environment before Codex is spawned. It is used only by Codexometer's native HTTPS client to start the session. Codex sees only @@ -822,9 +845,10 @@ fair deterministic cross-model ranking. ### Deterministic benchmark -The Benchmark tab discovers the current account's visible models and their -supported reasoning efforts through `model/list`. Select any challenge with the -arrow buttons; the selector reserves a stable responsive track for the longest +The Benchmark tab discovers models visible to the active benchmark +authentication and their supported reasoning efforts through `model/list`. +Select any challenge with the arrow buttons; the selector reserves a stable +responsive track for the longest name, so its controls do not move as the selection changes. Press `b` or click **Run Selected** to run that challenge against every model/effort combination. **Run All** runs the complete catalog against every combination. Because that @@ -832,7 +856,8 @@ means `challenge count × model/effort count` model turns, Codexometer displays the exact total and requires a second confirmation within five seconds. A fresh, ephemeral, read-only app-server thread is used for each trial, so benchmark history does not clutter normal Codex sessions. The turns still consume the -same account quota shown by Codexometer. +same account quota shown by Codexometer unless a benchmark API key is supplied; +with a key, they use standard usage-based API billing instead. Each model/effort trial has a five-minute deadline. If an in-flight turn reaches that deadline, Codexometer requests `turn/interrupt`, waits for the matching diff --git a/internal/codex/benchmark.go b/internal/codex/benchmark.go index f4a222d0..f5e4dc77 100644 --- a/internal/codex/benchmark.go +++ b/internal/codex/benchmark.go @@ -188,6 +188,7 @@ type appServerSession struct { experimentalRawEvents bool turnTimeout time.Duration interruptTimeout time.Duration + temporaryCodexHome string } type lockedBuffer struct { @@ -210,7 +211,7 @@ func (b *lockedBuffer) String() string { // BenchmarkCombinationCount returns the number of visible model/effort pairs // without starting a model turn. func (c Client) BenchmarkCombinationCount(ctx context.Context) (int, error) { - server, err := openBenchmarkAppServer(ctx, c.Binary) + server, err := openBenchmarkAppServer(ctx, c.Binary, c.BenchmarkAPIKey) if err != nil { return 0, err } @@ -235,7 +236,7 @@ func (c Client) RunBenchmarkSuite(ctx context.Context, taskIDs []BenchmarkTaskID emit(BenchmarkEvent{Done: true, Err: err}) return } - server, err := openBenchmarkAppServer(ctx, c.Binary) + server, err := openBenchmarkAppServer(ctx, c.Binary, c.BenchmarkAPIKey) if err != nil { emit(BenchmarkEvent{Done: true, Err: err}) return @@ -281,27 +282,48 @@ func (c Client) RunBenchmarkSuite(ctx context.Context, taskIDs []BenchmarkTaskID emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: len(combinations), Done: true}) } -func startAppServer(ctx context.Context, binary string) (*appServerSession, error) { - return startAppServerWithExperimentalUsage(ctx, binary, true) +func startAppServer(ctx context.Context, binary, apiKey string) (*appServerSession, error) { + return startAppServerWithExperimentalUsage(ctx, binary, strings.TrimSpace(apiKey), true) } -func startAppServerWithExperimentalUsage(ctx context.Context, binary string, experimental bool) (*appServerSession, error) { +func startAppServerWithExperimentalUsage(ctx context.Context, binary, apiKey string, experimental bool) (*appServerSession, error) { if strings.TrimSpace(binary) == "" { binary = "codex" } - cmd := exec.CommandContext(ctx, binary, "app-server", "--stdio") - cmd.Env = environmentWithout(os.Environ(), "DIGBENCH_API_TOKEN") + args := []string{"app-server", "--stdio"} + temporaryCodexHome := "" + if apiKey != "" { + var err error + temporaryCodexHome, err = os.MkdirTemp("", "codexometer-benchmark-auth-") + if err != nil { + return nil, fmt.Errorf("create isolated benchmark Codex home: %w", err) + } + args = append(args, "-c", `cli_auth_credentials_store="ephemeral"`) + } + removeTemporaryHome := func() { + if temporaryCodexHome != "" { + _ = os.RemoveAll(temporaryCodexHome) + } + } + cmd := exec.CommandContext(ctx, binary, args...) + cmd.Env = environmentWithout(os.Environ(), "DIGBENCH_API_TOKEN", "CODEXOMETER_BENCHMARK_API_KEY", "OPENAI_API_KEY") + if temporaryCodexHome != "" { + cmd.Env = environmentWith(cmd.Env, "CODEX_HOME", temporaryCodexHome) + } stdin, err := cmd.StdinPipe() if err != nil { + removeTemporaryHome() return nil, fmt.Errorf("open Codex input: %w", err) } stdout, err := cmd.StdoutPipe() if err != nil { + removeTemporaryHome() return nil, fmt.Errorf("open Codex output: %w", err) } stderr := &lockedBuffer{} cmd.Stderr = stderr if err := cmd.Start(); err != nil { + removeTemporaryHome() if errors.Is(err, exec.ErrNotFound) || errors.Is(err, os.ErrNotExist) { return nil, fmt.Errorf("Codex CLI not found; install it or pass --codex PATH") } @@ -312,6 +334,7 @@ func startAppServerWithExperimentalUsage(ctx context.Context, binary string, exp stderr: stderr, envelopes: make(chan benchmarkEnvelope, 64), readErrors: make(chan error, 1), done: make(chan struct{}), experimentalAPI: experimental, experimentalRawEvents: experimental, + temporaryCodexHome: temporaryCodexHome, } go server.readLoop(json.NewDecoder(bufio.NewReader(stdout))) initialize := map[string]any{ @@ -323,7 +346,7 @@ func startAppServerWithExperimentalUsage(ctx context.Context, binary string, exp if _, err := server.call(ctx, "initialize", initialize, nil); err != nil { server.close() if experimental && experimentalAPIUnsupported(err) { - return startAppServerWithExperimentalUsage(ctx, binary, false) + return startAppServerWithExperimentalUsage(ctx, binary, apiKey, false) } return nil, fmt.Errorf("initialize Codex app-server: %w", err) } @@ -331,21 +354,47 @@ func startAppServerWithExperimentalUsage(ctx context.Context, binary string, exp server.close() return nil, fmt.Errorf("acknowledge Codex app-server: %w", err) } + if apiKey != "" { + result, loginErr := server.call(ctx, "account/login/start", map[string]any{ + "type": "apiKey", "apiKey": apiKey, + }, nil) + if loginErr != nil { + server.close() + return nil, fmt.Errorf("authenticate benchmark Codex app-server with API key: %w", loginErr) + } + var login struct { + Type string `json:"type"` + } + if json.Unmarshal(result, &login) != nil || login.Type != "apiKey" { + server.close() + return nil, errors.New("Codex returned an invalid API-key login response") + } + } return server, nil } -func environmentWithout(environment []string, name string) []string { +func environmentWithout(environment []string, names ...string) []string { + excluded := make(map[string]struct{}, len(names)) + for _, name := range names { + excluded[strings.ToUpper(name)] = struct{}{} + } filtered := make([]string, 0, len(environment)) for _, entry := range environment { key, _, found := strings.Cut(entry, "=") - if found && strings.EqualFold(key, name) { - continue + if found { + if _, remove := excluded[strings.ToUpper(key)]; remove { + continue + } } filtered = append(filtered, entry) } return filtered } +func environmentWith(environment []string, name, value string) []string { + return append(environmentWithout(environment, name), name+"="+value) +} + func experimentalAPIUnsupported(err error) bool { var methodError *benchmarkMethodError if !errors.As(err, &methodError) { @@ -417,6 +466,10 @@ func (s *appServerSession) close() { _ = s.cmd.Wait() } }) + if s.temporaryCodexHome != "" { + _ = os.RemoveAll(s.temporaryCodexHome) + s.temporaryCodexHome = "" + } } func (s *appServerSession) call( diff --git a/internal/codex/benchmark_test.go b/internal/codex/benchmark_test.go index 67c28cb3..58061621 100644 --- a/internal/codex/benchmark_test.go +++ b/internal/codex/benchmark_test.go @@ -320,7 +320,7 @@ func TestRunBenchmarkSuiteInterruptsTimedOutTurnAndContinues(t *testing.T) { }() original := openBenchmarkAppServer - openBenchmarkAppServer = func(context.Context, string) (*appServerSession, error) { return server, nil } + openBenchmarkAppServer = func(context.Context, string, string) (*appServerSession, error) { return server, nil } t.Cleanup(func() { openBenchmarkAppServer = original }) var results []BenchmarkResult @@ -622,10 +622,11 @@ func TestExperimentalAPIUnsupported(t *testing.T) { } } -func TestEnvironmentWithoutScrubsDigBenchTokenOnly(t *testing.T) { - environment := []string{"PATH=/usr/bin", "DIGBENCH_API_TOKEN=secret", "OTHER=value", "malformed"} - filtered := environmentWithout(environment, "digbench_api_token") - want := []string{"PATH=/usr/bin", "OTHER=value", "malformed"} +func TestEnvironmentHelpersReplaceAndScrubSecrets(t *testing.T) { + environment := []string{"PATH=/usr/bin", "DIGBENCH_API_TOKEN=secret", "OPENAI_API_KEY=secret", "CODEX_HOME=/old", "OTHER=value", "malformed"} + filtered := environmentWithout(environment, "digbench_api_token", "openai_api_key") + filtered = environmentWith(filtered, "CODEX_HOME", "/isolated") + want := []string{"PATH=/usr/bin", "OTHER=value", "malformed", "CODEX_HOME=/isolated"} if len(filtered) != len(want) { t.Fatalf("filtered environment = %#v", filtered) } @@ -666,7 +667,7 @@ func TestRunBenchmarkSuiteDiscoversAndRunsEveryCombination(t *testing.T) { })}, ) original := openBenchmarkAppServer - openBenchmarkAppServer = func(context.Context, string) (*appServerSession, error) { return server, nil } + openBenchmarkAppServer = func(context.Context, string, string) (*appServerSession, error) { return server, nil } t.Cleanup(func() { openBenchmarkAppServer = original }) var events []BenchmarkEvent @@ -719,7 +720,7 @@ func TestRunBenchmarkSuiteMultipliesSelectedTasksByCombinations(t *testing.T) { })}, ) original := openBenchmarkAppServer - openBenchmarkAppServer = func(context.Context, string) (*appServerSession, error) { return server, nil } + openBenchmarkAppServer = func(context.Context, string, string) (*appServerSession, error) { return server, nil } t.Cleanup(func() { openBenchmarkAppServer = original }) var results []BenchmarkResult @@ -740,7 +741,7 @@ func TestRunBenchmarkSuiteMultipliesSelectedTasksByCombinations(t *testing.T) { func TestRunBenchmarkSuiteReportsStartupFailure(t *testing.T) { original := openBenchmarkAppServer - openBenchmarkAppServer = func(context.Context, string) (*appServerSession, error) { + openBenchmarkAppServer = func(context.Context, string, string) (*appServerSession, error) { return nil, errors.New("offline") } t.Cleanup(func() { openBenchmarkAppServer = original }) @@ -761,17 +762,53 @@ func TestBenchmarkCombinationCountUsesVisibleCatalogWithoutTurns(t *testing.T) { })}, ) original := openBenchmarkAppServer - openBenchmarkAppServer = func(context.Context, string) (*appServerSession, error) { return server, nil } + var receivedAPIKey string + openBenchmarkAppServer = func(_ context.Context, _, apiKey string) (*appServerSession, error) { + receivedAPIKey = apiKey + return server, nil + } t.Cleanup(func() { openBenchmarkAppServer = original }) - count, err := (Client{}).BenchmarkCombinationCount(context.Background()) + count, err := (Client{BenchmarkAPIKey: "benchmark-secret"}).BenchmarkCombinationCount(context.Background()) if err != nil || count != 3 { t.Fatalf("combination count = %d, %v; want 3", count, err) } + if receivedAPIKey != "benchmark-secret" { + t.Fatal("benchmark API key was not routed to the app-server") + } if strings.Contains(requests.String(), `"method":"turn/start"`) { t.Fatalf("catalog planning unexpectedly started a model turn: %s", requests.String()) } } +func TestStartAppServerUsesEphemeralIsolatedAPIKeyLogin(t *testing.T) { + t.Setenv("CODEXOMETER_FAKE_APP_SERVER", "1") + t.Setenv("CODEXOMETER_FAKE_EXPECT_BENCHMARK_LOGIN", "1") + t.Setenv("CODEXOMETER_BENCHMARK_API_KEY", "environment-secret") + t.Setenv("OPENAI_API_KEY", "environment-openai-secret") + t.Setenv("DIGBENCH_API_TOKEN", "digbench-secret") + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + server, err := startAppServer(context.Background(), executable, "benchmark-secret") + if err != nil { + t.Fatal(err) + } + temporaryHome := server.temporaryCodexHome + if temporaryHome == "" { + server.close() + t.Fatal("benchmark API login did not create an isolated Codex home") + } + if _, err := os.Stat(temporaryHome); err != nil { + server.close() + t.Fatalf("isolated Codex home was unavailable during the session: %v", err) + } + server.close() + if _, err := os.Stat(temporaryHome); !os.IsNotExist(err) { + t.Fatalf("isolated Codex home survived session close: %v", err) + } +} + func TestAppServerReadLoopAndClose(t *testing.T) { server, _ := newFakeBenchmarkServer() input := strings.NewReader("{\"method\":\"first\"}\n{\"method\":\"second\"}\n") @@ -838,7 +875,7 @@ func TestLiveBenchmarkModelCatalog(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - server, err := startAppServer(ctx, "codex") + server, err := startAppServer(ctx, "codex", "") if err != nil { t.Fatal(err) } @@ -863,7 +900,7 @@ func TestLiveBenchmarkThreadStart(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - server, err := startAppServer(ctx, "codex") + server, err := startAppServer(ctx, "codex", "") if err != nil { t.Fatal(err) } @@ -886,7 +923,7 @@ func TestLiveBenchmarkSingleLunaTrial(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), benchmarkTurnTimeout) defer cancel() - server, err := startAppServer(ctx, "codex") + server, err := startAppServer(ctx, "codex", "") if err != nil { t.Fatal(err) } diff --git a/internal/codex/client.go b/internal/codex/client.go index cff49827..52c9f56d 100644 --- a/internal/codex/client.go +++ b/internal/codex/client.go @@ -21,6 +21,9 @@ const requestTimeout = 15 * time.Second type Client struct { Binary string LiveUsage *LiveUsageReader + // BenchmarkAPIKey is used only by isolated benchmark app-server sessions. + // Fetch and local monitoring continue to use the prevailing Codex login. + BenchmarkAPIKey string } // FetchTokenUsage reads live telemetry from locally observed Codex sessions. diff --git a/internal/codex/client_test.go b/internal/codex/client_test.go index caaa835d..a3e42b0b 100644 --- a/internal/codex/client_test.go +++ b/internal/codex/client_test.go @@ -125,15 +125,34 @@ func runFakeAppServer() { encoder := json.NewEncoder(os.Stdout) for scanner.Scan() { var request struct { - ID *int `json:"id"` - Method string `json:"method"` + ID *int `json:"id"` + Method string `json:"method"` + Params json.RawMessage `json:"params"` } if json.Unmarshal(scanner.Bytes(), &request) != nil || request.ID == nil { continue } switch request.Method { case "initialize": + if os.Getenv("CODEXOMETER_FAKE_EXPECT_BENCHMARK_LOGIN") == "1" { + args := strings.Join(os.Args, " ") + if !strings.Contains(args, `cli_auth_credentials_store="ephemeral"`) || os.Getenv("CODEX_HOME") == "" || + os.Getenv("OPENAI_API_KEY") != "" || os.Getenv("CODEXOMETER_BENCHMARK_API_KEY") != "" || os.Getenv("DIGBENCH_API_TOKEN") != "" { + _ = encoder.Encode(map[string]any{"id": *request.ID, "error": map[string]any{"code": -32000, "message": "benchmark auth was not isolated"}}) + continue + } + } _ = encoder.Encode(map[string]any{"id": *request.ID, "result": map[string]any{}}) + case "account/login/start": + var params struct { + Type string `json:"type"` + APIKey string `json:"apiKey"` + } + if json.Unmarshal(request.Params, ¶ms) != nil || params.Type != "apiKey" || params.APIKey != "benchmark-secret" { + _ = encoder.Encode(map[string]any{"id": *request.ID, "error": map[string]any{"code": -32602, "message": "invalid benchmark login"}}) + continue + } + _ = encoder.Encode(map[string]any{"id": *request.ID, "result": map[string]any{"type": "apiKey"}}) case "account/read": if os.Getenv("CODEXOMETER_FAKE_ACCOUNT_ERROR") == "1" { _ = encoder.Encode(map[string]any{ diff --git a/internal/codex/digbench.go b/internal/codex/digbench.go index 35e203e7..b7cc70fa 100644 --- a/internal/codex/digbench.go +++ b/internal/codex/digbench.go @@ -72,7 +72,7 @@ func (c Client) RunDigBench(ctx context.Context, service digBenchService, option options.Timeout = defaultDigBenchTimeout } - server, err := openBenchmarkAppServer(ctx, c.Binary) + server, err := openBenchmarkAppServer(ctx, c.Binary, c.BenchmarkAPIKey) if err != nil { return DigBenchResult{}, err } diff --git a/internal/codex/digbench_test.go b/internal/codex/digbench_test.go index a7e89026..66b28517 100644 --- a/internal/codex/digbench_test.go +++ b/internal/codex/digbench_test.go @@ -70,15 +70,22 @@ func TestRunDigBenchBridgesScopedStepAndDetectsWin(t *testing.T) { server.experimentalAPI = true original := openBenchmarkAppServer - openBenchmarkAppServer = func(context.Context, string) (*appServerSession, error) { return server, nil } + var receivedAPIKey string + openBenchmarkAppServer = func(_ context.Context, _, apiKey string) (*appServerSession, error) { + receivedAPIKey = apiKey + return server, nil + } t.Cleanup(func() { openBenchmarkAppServer = original }) - result, err := (Client{}).RunDigBench(context.Background(), service, DigBenchOptions{ + result, err := (Client{BenchmarkAPIKey: "benchmark-secret"}).RunDigBench(context.Background(), service, DigBenchOptions{ Game: "P-1", Model: "gpt-5.6-sol", Effort: "high", Timeout: time.Minute, ClientVersion: "test", }) if err != nil { t.Fatal(err) } + if receivedAPIKey != "benchmark-secret" { + t.Fatal("DigBench did not route the benchmark API key to app-server") + } if !result.Won || result.Failure != "" || result.Status != "completed" || result.LevelsBeaten != 3 || result.MaxLevel != 3 || result.Steps != 1 { t.Fatalf("result = %#v", result) } diff --git a/main.go b/main.go index f4b0e318..724221ca 100644 --- a/main.go +++ b/main.go @@ -154,7 +154,7 @@ func main() { type dependencies struct { checkAuth func(context.Context, string) (codex.Snapshot, error) - runDigBench func(context.Context, string, string, codex.DigBenchOptions) (codex.DigBenchResult, error) + runDigBench func(context.Context, string, string, string, codex.DigBenchOptions) (codex.DigBenchResult, error) startUI func(ui.Fetcher, time.Duration, bool) error } @@ -163,8 +163,8 @@ func defaultDependencies() dependencies { checkAuth: func(ctx context.Context, binary string) (codex.Snapshot, error) { return (codex.Client{Binary: binary}).Fetch(ctx) }, - runDigBench: func(ctx context.Context, binary, token string, options codex.DigBenchOptions) (codex.DigBenchResult, error) { - return (codex.Client{Binary: binary}).RunDigBench(ctx, digbench.Client{Token: token}, options) + runDigBench: func(ctx context.Context, binary, token, apiKey string, options codex.DigBenchOptions) (codex.DigBenchResult, error) { + return (codex.Client{Binary: binary, BenchmarkAPIKey: apiKey}).RunDigBench(ctx, digbench.Client{Token: token}, options) }, startUI: startUI, } @@ -218,12 +218,21 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { fmt.Fprintln(stderr, "codexometer: remove DIGBENCH_API_TOKEN from child environment:", err) return 1 } + benchmarkAPIKey, benchmarkAPIKeySource, err := takeBenchmarkAPIKey() + if err != nil { + fmt.Fprintln(stderr, "codexometer:", err) + return 1 + } if deps.runDigBench == nil { fmt.Fprintln(stderr, "codexometer: DigBench runner unavailable") return 1 } - fmt.Fprintf(stderr, "Starting DigBench %s; this creates a persisted remote session and consumes Codex quota.\n", strings.TrimSpace(*digBenchGame)) - result, err := deps.runDigBench(context.Background(), *codexPath, token, codex.DigBenchOptions{ + billing := "the prevailing Codex login and quota" + if benchmarkAPIKey != "" { + billing = "API-key usage-based billing from " + benchmarkAPIKeySource + } + fmt.Fprintf(stderr, "Starting DigBench %s; this creates a persisted remote session and uses %s.\n", strings.TrimSpace(*digBenchGame), billing) + result, err := deps.runDigBench(context.Background(), *codexPath, token, benchmarkAPIKey, codex.DigBenchOptions{ Game: strings.TrimSpace(*digBenchGame), Model: strings.TrimSpace(*digBenchModel), Effort: strings.TrimSpace(*digBenchEffort), Timeout: *digBenchTimeout, ClientVersion: version.Current(), }) @@ -238,7 +247,12 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { return 0 } - client := codex.Client{Binary: *codexPath} + benchmarkAPIKey, _, err := takeBenchmarkAPIKey() + if err != nil { + fmt.Fprintln(stderr, "codexometer:", err) + return 1 + } + client := codex.Client{Binary: *codexPath, BenchmarkAPIKey: benchmarkAPIKey} if liveUsage, err := codex.NewLiveUsageReader(""); err == nil { client.LiveUsage = liveUsage } @@ -254,6 +268,19 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { return 0 } +func takeBenchmarkAPIKey() (key, source string, err error) { + for _, candidate := range []string{"CODEXOMETER_BENCHMARK_API_KEY", "OPENAI_API_KEY"} { + value := strings.TrimSpace(os.Getenv(candidate)) + if unsetErr := os.Unsetenv(candidate); unsetErr != nil { + return "", "", fmt.Errorf("remove %s from child environment: %w", candidate, unsetErr) + } + if key == "" && value != "" { + key, source = value, candidate + } + } + return key, source, nil +} + func formatDigBenchResult(result codex.DigBenchResult) string { outcome := "LOSS" if result.Won { diff --git a/main_test.go b/main_test.go index 588f55f2..0466ef56 100644 --- a/main_test.go +++ b/main_test.go @@ -124,13 +124,13 @@ func TestRunDigBenchUsesExplicitSingleGameOptions(t *testing.T) { var stdout, stderr bytes.Buffer called := false deps := dependencies{ - runDigBench: func(_ context.Context, binary, token string, options codex.DigBenchOptions) (codex.DigBenchResult, error) { + runDigBench: func(_ context.Context, binary, token, apiKey string, options codex.DigBenchOptions) (codex.DigBenchResult, error) { called = true if value := os.Getenv("DIGBENCH_API_TOKEN"); value != "" { t.Fatalf("DigBench token remained in child environment: %q", value) } - if binary != "/custom/codex" || token != "secret" || options.Game != "P-3" || options.Model != "gpt-5.6-terra" || options.Effort != "medium" || options.Timeout != 2*time.Minute { - t.Fatalf("binary=%q token=%q options=%#v", binary, token, options) + if binary != "/custom/codex" || token != "secret" || apiKey != "" || options.Game != "P-3" || options.Model != "gpt-5.6-terra" || options.Effort != "medium" || options.Timeout != 2*time.Minute { + t.Fatalf("binary=%q token=%q apiKeyPresent=%v options=%#v", binary, token, apiKey != "", options) } return codex.DigBenchResult{ Game: "P-3", Won: true, Status: "completed", LevelsBeaten: 4, MaxLevel: 4, Steps: 17, @@ -148,6 +148,51 @@ func TestRunDigBenchUsesExplicitSingleGameOptions(t *testing.T) { } } +func TestRunDigBenchPrefersDedicatedBenchmarkAPIKey(t *testing.T) { + t.Setenv("DIGBENCH_API_TOKEN", "digbench-secret") + t.Setenv("CODEXOMETER_BENCHMARK_API_KEY", "benchmark-secret") + t.Setenv("OPENAI_API_KEY", "fallback-secret") + var stdout, stderr bytes.Buffer + deps := dependencies{ + runDigBench: func(_ context.Context, _, _, apiKey string, _ codex.DigBenchOptions) (codex.DigBenchResult, error) { + if apiKey != "benchmark-secret" { + t.Fatalf("benchmark API key preference was not honored") + } + if os.Getenv("CODEXOMETER_BENCHMARK_API_KEY") != "" || os.Getenv("OPENAI_API_KEY") != "" { + t.Fatal("benchmark API key remained in the inherited environment") + } + return codex.DigBenchResult{Game: "P-1", Won: true}, nil + }, + } + if code := run([]string{"--digbench-game", "P-1"}, &stdout, &stderr, deps); code != 0 { + t.Fatalf("code=%d stdout=%q stderr=%q", code, stdout.String(), stderr.String()) + } + if !strings.Contains(stderr.String(), "API-key usage-based billing from CODEXOMETER_BENCHMARK_API_KEY") { + t.Fatalf("missing API billing notice: %q", stderr.String()) + } +} + +func TestRunPassesOpenAIAPIKeyToUIBenchmarks(t *testing.T) { + t.Setenv("CODEXOMETER_BENCHMARK_API_KEY", "") + t.Setenv("OPENAI_API_KEY", "openai-secret") + var stdout, stderr bytes.Buffer + deps := dependencies{ + startUI: func(fetcher ui.Fetcher, _ time.Duration, _ bool) error { + client, ok := fetcher.(codex.Client) + if !ok || client.BenchmarkAPIKey != "openai-secret" { + t.Fatalf("benchmark API key was not attached to Codex client") + } + if os.Getenv("OPENAI_API_KEY") != "" { + t.Fatal("OPENAI_API_KEY remained in the inherited environment") + } + return nil + }, + } + if code := run(nil, &stdout, &stderr, deps); code != 0 { + t.Fatalf("code=%d stdout=%q stderr=%q", code, stdout.String(), stderr.String()) + } +} + func TestRunDigBenchRequiresToken(t *testing.T) { t.Setenv("DIGBENCH_API_TOKEN", "") var stdout, stderr bytes.Buffer From 607783c443213e901b3c9b0931d7e47adb8af3d7 Mon Sep 17 00:00:00 2001 From: merefield Date: Fri, 21 Aug 2026 21:25:49 +0100 Subject: [PATCH 04/18] FEAT: report DigBench run progress --- README.md | 7 +++++ internal/codex/benchmark.go | 30 ++++++++++++------ internal/codex/digbench.go | 55 +++++++++++++++++++++++++++++++-- internal/codex/digbench_test.go | 18 +++++++++++ main.go | 31 ++++++++++++++++++- main_test.go | 27 +++++++++++++++- 6 files changed, 155 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 21863427..58cfc22a 100644 --- a/README.md +++ b/README.md @@ -835,6 +835,13 @@ the scoped dynamic-tool bridge. Step calls are safely retried using DigBench's idempotent `step_index` protocol; session creation is never automatically retried because that endpoint does not document idempotency. +The command prints the selected game, model, effort, and billing source before +connecting. It then reports remote-session creation, Codex-turn startup, +authoritative level/step/status updates after successful game-tool calls, and a +content-free elapsed-time heartbeat every 15 seconds while Codex is working. +Progress output never includes the DigBench session ID, observations, available +actions, model reasoning, or credentials. + The final line reports `WIN`, `LOSS`, or `INCOMPLETE`, levels beaten, total game steps, duration, tokens, and estimated standard API-equivalent cost. A win requires the authoritative terminal combination `done: true` and diff --git a/internal/codex/benchmark.go b/internal/codex/benchmark.go index f5e4dc77..84399fa8 100644 --- a/internal/codex/benchmark.go +++ b/internal/codex/benchmark.go @@ -424,31 +424,38 @@ func (s *appServerSession) readLoop(decoder *json.Decoder) { } func (s *appServerSession) nextEnvelope(ctx context.Context) (benchmarkEnvelope, error) { + envelope, _, err := s.nextEnvelopeOrHeartbeat(ctx, nil) + return envelope, err +} + +func (s *appServerSession) nextEnvelopeOrHeartbeat(ctx context.Context, heartbeat <-chan time.Time) (benchmarkEnvelope, bool, error) { // Drain decoded protocol messages before observing a terminal decoder error. // A short-lived server may write its final response and close stdout so close // together that both channels are ready at once. select { case envelope := <-s.envelopes: - return envelope, nil + return envelope, false, nil default: } select { case <-ctx.Done(): - return benchmarkEnvelope{}, ctx.Err() + return benchmarkEnvelope{}, false, ctx.Err() + case <-heartbeat: + return benchmarkEnvelope{}, true, nil case <-s.done: - return benchmarkEnvelope{}, errors.New("Codex app-server session closed") + return benchmarkEnvelope{}, false, errors.New("Codex app-server session closed") case err := <-s.readErrors: select { case envelope := <-s.envelopes: - return envelope, nil + return envelope, false, nil default: } if errors.Is(err, io.EOF) { - return benchmarkEnvelope{}, fmt.Errorf("Codex app-server closed unexpectedly: %s", strings.TrimSpace(s.stderr.String())) + return benchmarkEnvelope{}, false, fmt.Errorf("Codex app-server closed unexpectedly: %s", strings.TrimSpace(s.stderr.String())) } - return benchmarkEnvelope{}, err + return benchmarkEnvelope{}, false, err case envelope := <-s.envelopes: - return envelope, nil + return envelope, false, nil } } @@ -1057,12 +1064,17 @@ func (s *appServerSession) readUntilNotification(ctx context.Context, accept fun } func (s *appServerSession) nextPendingEnvelope(ctx context.Context) (benchmarkEnvelope, error) { + envelope, _, err := s.nextPendingEnvelopeOrHeartbeat(ctx, nil) + return envelope, err +} + +func (s *appServerSession) nextPendingEnvelopeOrHeartbeat(ctx context.Context, heartbeat <-chan time.Time) (benchmarkEnvelope, bool, error) { if len(s.pending) > 0 { envelope := s.pending[0] s.pending = s.pending[1:] - return envelope, nil + return envelope, false, nil } - return s.nextEnvelope(ctx) + return s.nextEnvelopeOrHeartbeat(ctx, heartbeat) } func (s *appServerSession) respond(id json.RawMessage, result any) error { diff --git a/internal/codex/digbench.go b/internal/codex/digbench.go index b7cc70fa..b0ce90dd 100644 --- a/internal/codex/digbench.go +++ b/internal/codex/digbench.go @@ -12,7 +12,33 @@ import ( "github.com/merefield/codexometer/internal/digbench" ) -const defaultDigBenchTimeout = 30 * time.Minute +const ( + defaultDigBenchTimeout = 30 * time.Minute + defaultDigBenchProgressInterval = 15 * time.Second +) + +// DigBenchProgressPhase identifies a safe, content-free runner milestone. +type DigBenchProgressPhase string + +const ( + DigBenchProgressSession DigBenchProgressPhase = "session" + DigBenchProgressTurn DigBenchProgressPhase = "turn" + DigBenchProgressUpdate DigBenchProgressPhase = "update" + DigBenchProgressHeartbeat DigBenchProgressPhase = "heartbeat" +) + +// DigBenchProgress reports authoritative game counters without exposing the +// session ID, observations, actions, reasoning, or credentials. +type DigBenchProgress struct { + Phase DigBenchProgressPhase + Level int + LevelsBeaten int + MaxLevel int + Steps int + Status string + Elapsed time.Duration + ActualModel string +} // DigBenchOptions selects one deliberately bounded external benchmark run. type DigBenchOptions struct { @@ -21,6 +47,7 @@ type DigBenchOptions struct { Effort string Timeout time.Duration ClientVersion string + Progress func(DigBenchProgress) } // DigBenchResult is the terminal state and Codex telemetry for one game. @@ -32,6 +59,7 @@ type DigBenchResult struct { ActualModel string Won bool Status string + CurrentLevel int LevelsBeaten int MaxLevel int Steps int @@ -165,6 +193,7 @@ func (s *appServerSession) runDigBench( applyDigBenchSession(&result, session) startedAt := time.Now() + emitDigBenchProgress(options.Progress, DigBenchProgressSession, result, startedAt) turnParams := map[string]any{ "threadId": startedThread.Thread.ID, "input": []map[string]any{{"type": "text", "text": digBenchPrompt(session)}}, @@ -184,12 +213,19 @@ func (s *appServerSession) runDigBench( if err := json.Unmarshal(turnResponse, &startedTurn); err != nil || startedTurn.Turn.ID == "" { return result, errors.New("Codex returned an invalid DigBench turn") } + emitDigBenchProgress(options.Progress, DigBenchProgressTurn, result, startedAt) telemetry := newBenchmarkTelemetry() completed := false turnFailure := "" + progressTicker := time.NewTicker(defaultDigBenchProgressInterval) + defer progressTicker.Stop() for !completed { - envelope, envelopeErr := s.nextPendingEnvelope(runCtx) + envelope, heartbeat, envelopeErr := s.nextPendingEnvelopeOrHeartbeat(runCtx, progressTicker.C) + if heartbeat { + emitDigBenchProgress(options.Progress, DigBenchProgressHeartbeat, result, startedAt) + continue + } if envelopeErr != nil { result.Duration = time.Since(startedAt) if recoverableBenchmarkTimeout(ctx, runCtx, envelopeErr) { @@ -222,6 +258,9 @@ func (s *appServerSession) runDigBench( session.SessionID, envelope.Params, &session, ) applyDigBenchSession(&result, session) + if response["success"] == true { + emitDigBenchProgress(options.Progress, DigBenchProgressUpdate, result, startedAt) + } if err := s.respond(envelope.ID, response); err != nil { return result, fmt.Errorf("respond to DigBench tool call: %w", err) } @@ -277,6 +316,17 @@ func (s *appServerSession) runDigBench( return result, nil } +func emitDigBenchProgress(callback func(DigBenchProgress), phase DigBenchProgressPhase, result DigBenchResult, startedAt time.Time) { + if callback == nil { + return + } + callback(DigBenchProgress{ + Phase: phase, Level: result.CurrentLevel, LevelsBeaten: result.LevelsBeaten, + MaxLevel: result.MaxLevel, Steps: result.Steps, Status: result.Status, Elapsed: time.Since(startedAt), + ActualModel: result.ActualModel, + }) +} + func digBenchDynamicTools() []map[string]any { sessionProperty := map[string]any{"type": "string", "description": "The assigned DigBench session_id."} return []map[string]any{ @@ -399,6 +449,7 @@ func digBenchToolResponse(value any, err error) map[string]any { func applyDigBenchSession(result *DigBenchResult, session digbench.Session) { result.Game = session.Game result.Status = session.State.Status + result.CurrentLevel = session.State.Level result.LevelsBeaten = session.LevelsBeaten result.Steps = session.StepIndex result.Seed = session.Seed diff --git a/internal/codex/digbench_test.go b/internal/codex/digbench_test.go index 66b28517..ebd3e098 100644 --- a/internal/codex/digbench_test.go +++ b/internal/codex/digbench_test.go @@ -77,8 +77,10 @@ func TestRunDigBenchBridgesScopedStepAndDetectsWin(t *testing.T) { } t.Cleanup(func() { openBenchmarkAppServer = original }) + var progress []DigBenchProgress result, err := (Client{BenchmarkAPIKey: "benchmark-secret"}).RunDigBench(context.Background(), service, DigBenchOptions{ Game: "P-1", Model: "gpt-5.6-sol", Effort: "high", Timeout: time.Minute, ClientVersion: "test", + Progress: func(event DigBenchProgress) { progress = append(progress, event) }, }) if err != nil { t.Fatal(err) @@ -95,6 +97,12 @@ func TestRunDigBenchBridgesScopedStepAndDetectsWin(t *testing.T) { if !result.UsageKnown || result.Usage != usage || !result.CostKnown { t.Fatalf("telemetry = %#v", result) } + if len(progress) != 3 || progress[0].Phase != DigBenchProgressSession || progress[1].Phase != DigBenchProgressTurn || progress[2].Phase != DigBenchProgressUpdate { + t.Fatalf("progress phases = %#v", progress) + } + if final := progress[2]; final.Level != 3 || final.LevelsBeaten != 3 || final.MaxLevel != 3 || final.Steps != 1 || final.Status != "completed" || final.Elapsed < 0 { + t.Fatalf("final progress = %#v", final) + } requestLog := requests.String() for _, expected := range []string{`"dynamicTools"`, `"sandbox":"workspace-write"`, `"method":"turn/start"`, `"id":50`, `"success":true`, `\"status\":\"completed\"`} { if !strings.Contains(requestLog, expected) { @@ -103,6 +111,16 @@ func TestRunDigBenchBridgesScopedStepAndDetectsWin(t *testing.T) { } } +func TestNextPendingEnvelopeCanReportHeartbeat(t *testing.T) { + server, _ := newFakeBenchmarkServer() + heartbeat := make(chan time.Time, 1) + heartbeat <- time.Now() + envelope, pulsed, err := server.nextPendingEnvelopeOrHeartbeat(context.Background(), heartbeat) + if err != nil || !pulsed || len(envelope.ID) != 0 || envelope.Method != "" || len(envelope.Params) != 0 || len(envelope.Result) != 0 || envelope.Error != nil { + t.Fatalf("envelope=%#v pulsed=%v error=%v", envelope, pulsed, err) + } +} + func TestDigBenchToolRejectsAnotherSession(t *testing.T) { service := &fakeDigBenchService{session: digbench.Session{SessionID: "session-1"}} current := service.session diff --git a/main.go b/main.go index 724221ca..f72bd58f 100644 --- a/main.go +++ b/main.go @@ -231,10 +231,14 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { if benchmarkAPIKey != "" { billing = "API-key usage-based billing from " + benchmarkAPIKeySource } - fmt.Fprintf(stderr, "Starting DigBench %s; this creates a persisted remote session and uses %s.\n", strings.TrimSpace(*digBenchGame), billing) + fmt.Fprintf(stderr, "Starting DigBench %s with %s/%s; this creates a persisted remote session and uses %s.\n", + strings.TrimSpace(*digBenchGame), strings.TrimSpace(*digBenchModel), strings.TrimSpace(*digBenchEffort), billing) result, err := deps.runDigBench(context.Background(), *codexPath, token, benchmarkAPIKey, codex.DigBenchOptions{ Game: strings.TrimSpace(*digBenchGame), Model: strings.TrimSpace(*digBenchModel), Effort: strings.TrimSpace(*digBenchEffort), Timeout: *digBenchTimeout, ClientVersion: version.Current(), + Progress: func(progress codex.DigBenchProgress) { + fmt.Fprintln(stderr, formatDigBenchProgress(progress)) + }, }) if err != nil { fmt.Fprintln(stderr, "codexometer: DigBench run failed:", err) @@ -268,6 +272,31 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { return 0 } +func formatDigBenchProgress(progress codex.DigBenchProgress) string { + label := "DIGBENCH PROGRESS" + switch progress.Phase { + case codex.DigBenchProgressSession: + label = "DIGBENCH SESSION CREATED" + case codex.DigBenchProgressTurn: + label = "CODEX TURN STARTED" + case codex.DigBenchProgressHeartbeat: + label = "DIGBENCH WORKING" + } + level := fmt.Sprintf("%d", progress.Level) + if progress.MaxLevel > 0 { + level = fmt.Sprintf("%d/%d", progress.Level, progress.MaxLevel) + } + parts := []string{label, "LEVEL " + level, fmt.Sprintf("BEATEN %d", progress.LevelsBeaten), fmt.Sprintf("STEPS %d", progress.Steps)} + if progress.Status != "" { + parts = append(parts, "STATUS "+progress.Status) + } + if progress.ActualModel != "" && progress.Phase == codex.DigBenchProgressTurn { + parts = append(parts, "MODEL "+progress.ActualModel) + } + parts = append(parts, "ELAPSED "+progress.Elapsed.Round(100*time.Millisecond).String()) + return strings.Join(parts, " // ") +} + func takeBenchmarkAPIKey() (key, source string, err error) { for _, candidate := range []string{"CODEXOMETER_BENCHMARK_API_KEY", "OPENAI_API_KEY"} { value := strings.TrimSpace(os.Getenv(candidate)) diff --git a/main_test.go b/main_test.go index 0466ef56..de14a970 100644 --- a/main_test.go +++ b/main_test.go @@ -132,6 +132,13 @@ func TestRunDigBenchUsesExplicitSingleGameOptions(t *testing.T) { if binary != "/custom/codex" || token != "secret" || apiKey != "" || options.Game != "P-3" || options.Model != "gpt-5.6-terra" || options.Effort != "medium" || options.Timeout != 2*time.Minute { t.Fatalf("binary=%q token=%q apiKeyPresent=%v options=%#v", binary, token, apiKey != "", options) } + if options.Progress == nil { + t.Fatal("DigBench progress callback was not configured") + } + options.Progress(codex.DigBenchProgress{ + Phase: codex.DigBenchProgressUpdate, Level: 2, MaxLevel: 4, + LevelsBeaten: 1, Steps: 9, Status: "in_progress", Elapsed: 1250 * time.Millisecond, + }) return codex.DigBenchResult{ Game: "P-3", Won: true, Status: "completed", LevelsBeaten: 4, MaxLevel: 4, Steps: 17, DisplayName: "GPT-5.6 Terra", Effort: "medium", Duration: 3 * time.Second, @@ -143,11 +150,29 @@ func TestRunDigBenchUsesExplicitSingleGameOptions(t *testing.T) { "--digbench-game", "P-3", "--digbench-model", "gpt-5.6-terra", "--digbench-effort", "medium", "--digbench-timeout", "2m", "--codex", "/custom/codex", }, &stdout, &stderr, deps) - if code != 0 || !called || !strings.Contains(stdout.String(), "DIGBENCH P-3 // WIN // LEVELS 4/4") || !strings.Contains(stderr.String(), "persisted remote session") { + if code != 0 || !called || !strings.Contains(stdout.String(), "DIGBENCH P-3 // WIN // LEVELS 4/4") || + !strings.Contains(stderr.String(), "Starting DigBench P-3 with gpt-5.6-terra/medium") || + !strings.Contains(stderr.String(), "DIGBENCH PROGRESS // LEVEL 2/4 // BEATEN 1 // STEPS 9 // STATUS in_progress // ELAPSED 1.3s") { t.Fatalf("code=%d called=%v stdout=%q stderr=%q", code, called, stdout.String(), stderr.String()) } } +func TestFormatDigBenchProgressMilestones(t *testing.T) { + tests := []struct { + progress codex.DigBenchProgress + want string + }{ + {progress: codex.DigBenchProgress{Phase: codex.DigBenchProgressSession, Level: 1, MaxLevel: 3}, want: "DIGBENCH SESSION CREATED // LEVEL 1/3"}, + {progress: codex.DigBenchProgress{Phase: codex.DigBenchProgressTurn, Level: 1, ActualModel: "gpt-5.6-sol"}, want: "CODEX TURN STARTED // LEVEL 1 // BEATEN 0 // STEPS 0 // MODEL gpt-5.6-sol"}, + {progress: codex.DigBenchProgress{Phase: codex.DigBenchProgressHeartbeat, Elapsed: 15 * time.Second}, want: "DIGBENCH WORKING // LEVEL 0 // BEATEN 0 // STEPS 0 // ELAPSED 15s"}, + } + for _, test := range tests { + if got := formatDigBenchProgress(test.progress); !strings.Contains(got, test.want) { + t.Errorf("formatDigBenchProgress(%#v) = %q, want containing %q", test.progress, got, test.want) + } + } +} + func TestRunDigBenchPrefersDedicatedBenchmarkAPIKey(t *testing.T) { t.Setenv("DIGBENCH_API_TOKEN", "digbench-secret") t.Setenv("CODEXOMETER_BENCHMARK_API_KEY", "benchmark-secret") From e9f6f8903cd4425d0599da8adfaba4e4b2c6a3a2 Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 22 Aug 2026 12:32:28 +0100 Subject: [PATCH 05/18] FEAT: surface DigBench in benchmark details --- README.md | 36 ++++-- internal/codex/benchmark.go | 24 +++- internal/codex/benchmark_tasks.go | 20 ++- internal/codex/client.go | 3 + internal/codex/digbench.go | 199 ++++++++++++++++++++++++++++++ internal/codex/digbench_test.go | 65 ++++++++++ internal/ui/benchmark.go | 66 +++++++++- internal/ui/benchmark_test.go | 41 ++++++ internal/ui/model.go | 30 ++++- main.go | 25 +++- main_test.go | 20 +++ 11 files changed, 503 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 5dd59376..db80972f 100644 --- a/README.md +++ b/README.md @@ -804,18 +804,27 @@ Neither key is written to preferences or accepted as a command-line argument. ### Experimental DigBench agentic run -Codexometer includes a deliberately narrow command-line proof of concept for +Codexometer includes a deliberately narrow integration for [DigBench](https://digbench.ai/), an external benchmark of discovering unknown -rules in interactive text games. It runs exactly one named game with exactly -one Codex model/reasoning-effort combination; it is not included in the -Benchmark tab's deterministic Run Selected or Run All actions. +rules in interactive text games. Supplying `DIGBENCH_API_TOKEN` adds +**DIGBENCH P-1** to the Benchmark tab's task selector. Select exactly one +compatible model/reasoning-effort pair on the **Scope** screen, choose that +task, and use **Run Selected**. DigBench is deliberately excluded from **Run +All** because every invocation creates a persisted remote session with a random +seed. Create a token from the [DigBench token page](https://digbench.ai/account/tokens) -(sign-in is a passwordless email link), place it in the environment, and select -one of the 21 public game names returned by the API, such as `P-1`: +(sign-in is a passwordless email link) and place it in the environment. The TUI +currently exposes the proof-of-concept game `P-1`: ```sh export DIGBENCH_API_TOKEN="" +codexometer +``` + +The existing headless form remains available for a named exploratory game: + +```sh codexometer --digbench-game P-1 ``` @@ -846,12 +855,19 @@ the scoped dynamic-tool bridge. Step calls are safely retried using DigBench's idempotent `step_index` protocol; session creation is never automatically retried because that endpoint does not document idempotency. -The command prints the selected game, model, effort, and billing source before -connecting. It then reports remote-session creation, Codex-turn startup, +In the TUI, the run appears immediately in the existing result table and can be +opened while it is in progress. Its benchmark-only detail view reports +authoritative level, beaten-level, step, and status counters, followed by every +captured move and the sanitized DigBench state returned for that move. The +**Copy** control exports that complete captured view. DigBench session IDs, +credentials, request headers, and Codex reasoning are never included. **Stop** +requests interruption of the active Codex turn, retains the captured moves, and +marks the row stopped. + +The headless command prints the selected game, model, effort, and billing source +before connecting. It then reports remote-session creation, Codex-turn startup, authoritative level/step/status updates after successful game-tool calls, and a content-free elapsed-time heartbeat every 15 seconds while Codex is working. -Progress output never includes the DigBench session ID, observations, available -actions, model reasoning, or credentials. The final line reports `WIN`, `LOSS`, or `INCOMPLETE`, levels beaten, total game steps, duration, tokens, and estimated standard API-equivalent cost. A win diff --git a/internal/codex/benchmark.go b/internal/codex/benchmark.go index fd8f7232..688a601e 100644 --- a/internal/codex/benchmark.go +++ b/internal/codex/benchmark.go @@ -24,8 +24,8 @@ const ( benchmarkInterruptTimeout = 15 * time.Second benchmarkCodeLimit = 64 * 1024 benchmarkInteractionLimit = 64 * 1024 - benchmarkTranscriptLimit = 128 * 1024 - benchmarkInteractionCount = 16 + benchmarkTranscriptLimit = 1024 * 1024 + benchmarkInteractionCount = 4096 benchmarkStepLimit = 250_000 benchmarkHardStepLimit = 2_000_000 @@ -103,6 +103,8 @@ const ( BenchmarkInteractionResponse BenchmarkInteractionKind = "response" BenchmarkInteractionPolicy BenchmarkInteractionKind = "policy" BenchmarkInteractionVerifier BenchmarkInteractionKind = "verifier" + BenchmarkInteractionMove BenchmarkInteractionKind = "move" + BenchmarkInteractionState BenchmarkInteractionKind = "state" ) // BenchmarkInteraction is content emitted only by a benchmark turn that @@ -138,6 +140,12 @@ type BenchmarkResult struct { ToolType string Failure string Interactions []BenchmarkInteraction + Provider string + GameStatus string + CurrentLevel int + LevelsBeaten int + MaxLevel int + Steps int } // BenchmarkEvent incrementally reports discovery, execution, and results. @@ -325,6 +333,18 @@ func (c Client) runBenchmarkSuite(ctx context.Context, taskIDs []BenchmarkTaskID if emit == nil { emit = func(BenchmarkEvent) {} } + if len(taskIDs) == 1 { + if game, ok := digBenchGame(taskIDs[0]); ok { + c.runDigBenchBenchmarkSuite(ctx, taskIDs[0], game, emit, scopes...) + return + } + } + for _, id := range taskIDs { + if _, external := digBenchGame(id); external { + emit(benchmarkTerminalEvent(ctx, 0, 0, 0, errors.New("DigBench must be run separately from deterministic benchmarks"))) + return + } + } definitions, err := resolveBenchmarkTasks(taskIDs) if err != nil { emit(benchmarkTerminalEvent(ctx, 0, 0, 0, err)) diff --git a/internal/codex/benchmark_tasks.go b/internal/codex/benchmark_tasks.go index 96113e26..c018be36 100644 --- a/internal/codex/benchmark_tasks.go +++ b/internal/codex/benchmark_tasks.go @@ -19,12 +19,14 @@ const ( BenchmarkDependencyScheduler BenchmarkTaskID = "dependency-scheduler" BenchmarkVersionResolver BenchmarkTaskID = "version-resolver" BenchmarkEventProcessor BenchmarkTaskID = "event-processor" + BenchmarkDigBenchP1 BenchmarkTaskID = "digbench-p-1" ) // BenchmarkTask is the public description used by the terminal selector. type BenchmarkTask struct { - ID BenchmarkTaskID - Name string + ID BenchmarkTaskID + Name string + External bool } type benchmarkDefinition struct { @@ -120,6 +122,20 @@ func BenchmarkTasks() []BenchmarkTask { return tasks } +// DigBenchTask returns the deliberately narrow external game exposed by the +// current integration. It is omitted from Run All because every invocation +// creates a persisted remote session with a random seed. +func DigBenchTask() BenchmarkTask { + return BenchmarkTask{ID: BenchmarkDigBenchP1, Name: "DIGBENCH P-1", External: true} +} + +func digBenchGame(id BenchmarkTaskID) (string, bool) { + if id == BenchmarkDigBenchP1 { + return "P-1", true + } + return "", false +} + func resolveBenchmarkTasks(ids []BenchmarkTaskID) ([]benchmarkDefinition, error) { if len(ids) == 0 { return nil, errors.New("select at least one benchmark task") diff --git a/internal/codex/client.go b/internal/codex/client.go index 52c9f56d..20ab2e0f 100644 --- a/internal/codex/client.go +++ b/internal/codex/client.go @@ -24,6 +24,9 @@ type Client struct { // BenchmarkAPIKey is used only by isolated benchmark app-server sessions. // Fetch and local monitoring continue to use the prevailing Codex login. BenchmarkAPIKey string + // DigBenchToken is retained in memory only and enables the external P-1 + // option in the Benchmark tab. + DigBenchToken string } // FetchTokenUsage reads live telemetry from locally observed Codex sessions. diff --git a/internal/codex/digbench.go b/internal/codex/digbench.go index b0ce90dd..4a460072 100644 --- a/internal/codex/digbench.go +++ b/internal/codex/digbench.go @@ -48,6 +48,7 @@ type DigBenchOptions struct { Timeout time.Duration ClientVersion string Progress func(DigBenchProgress) + Snapshot func(DigBenchResult) } // DigBenchResult is the terminal state and Codex telemetry for one game. @@ -76,6 +77,7 @@ type DigBenchResult struct { CostKnown bool CostIssue string Failure string + Interactions []BenchmarkInteraction } type digBenchService interface { @@ -84,6 +86,100 @@ type digBenchService interface { Step(context.Context, string, digbench.StepRequest) (digbench.StepResponse, error) } +var newDigBenchService = func(token string) digBenchService { + return digbench.Client{Token: token} +} + +// BenchmarkTasks exposes the external proof-of-concept only when this process +// received a DigBench token. Run All continues to use deterministic tasks only. +func (c Client) BenchmarkTasks() []BenchmarkTask { + tasks := BenchmarkTasks() + if strings.TrimSpace(c.DigBenchToken) != "" { + tasks = append(tasks, DigBenchTask()) + } + return tasks +} + +func (c Client) runDigBenchBenchmarkSuite(ctx context.Context, taskID BenchmarkTaskID, game string, emit func(BenchmarkEvent), scopes ...BenchmarkScope) { + if strings.TrimSpace(c.DigBenchToken) == "" { + emit(benchmarkTerminalEvent(ctx, 0, 0, 0, errors.New("DIGBENCH_API_TOKEN is required for DigBench"))) + return + } + plan, err := c.BenchmarkPlan(ctx) + if err != nil { + emit(benchmarkTerminalEvent(ctx, 0, 0, 0, err)) + return + } + scope := plan.AllScope() + if len(scopes) > 0 { + scope = scopes[0] + } + models, efforts := stringSet(scope.Models), stringSet(scope.Efforts) + var selected []struct{ model, name, effort string } + for _, model := range plan.Models { + if !models[model.Model] { + continue + } + for _, effort := range model.Efforts { + if efforts[effort] { + selected = append(selected, struct{ model, name, effort string }{model.Model, model.DisplayName, effort}) + } + } + } + if len(selected) != 1 { + emit(benchmarkTerminalEvent(ctx, 0, 0, 0, fmt.Errorf("DigBench requires exactly one selected model/effort pair; scope contains %d", len(selected)))) + return + } + choice := selected[0] + event := BenchmarkEvent{Total: 1, Combinations: 1, CurrentTaskID: taskID, CurrentTask: "DIGBENCH " + game, CurrentModel: choice.name, CurrentEffort: choice.effort} + pending := BenchmarkResult{ + TaskID: taskID, TaskName: "DIGBENCH " + game, Provider: "digbench", + Model: choice.model, DisplayName: choice.name, ActualModel: choice.model, Effort: choice.effort, + GameStatus: "connecting", + } + event.Active = &pending + emit(event) + result, runErr := c.RunDigBench(ctx, newDigBenchService(c.DigBenchToken), DigBenchOptions{ + Game: game, Model: choice.model, Effort: choice.effort, + Snapshot: func(snapshot DigBenchResult) { + active := benchmarkResultFromDigBench(taskID, snapshot) + event.Active = &active + emit(event) + }, + }) + if result.Game == "" { + result.Game = game + } + if result.Model == "" { + result.Model, result.DisplayName, result.ActualModel, result.Effort = choice.model, choice.name, choice.model, choice.effort + } + converted := benchmarkResultFromDigBench(taskID, result) + if errors.Is(ctx.Err(), context.Canceled) { + markBenchmarkStopped(&converted) + event.Active, event.Result, event.Stopped = nil, &converted, true + emit(event) + emit(BenchmarkEvent{Total: 1, Combinations: 1, Stopped: true, Done: true}) + return + } + event.Completed, event.Active, event.Result = 1, nil, &converted + emit(event) + emit(BenchmarkEvent{Total: 1, Completed: 1, Combinations: 1, Done: true, Err: runErr}) +} + +func benchmarkResultFromDigBench(taskID BenchmarkTaskID, result DigBenchResult) BenchmarkResult { + return BenchmarkResult{ + TaskID: taskID, TaskName: "DIGBENCH " + result.Game, + Model: result.Model, DisplayName: result.DisplayName, Effort: result.Effort, ActualModel: result.ActualModel, + Correct: result.Won, Duration: result.Duration, Usage: result.Usage, UsageObserved: result.UsageObserved, + UsageKnown: result.UsageKnown, UsageIssue: result.UsageIssue, UsageSource: result.UsageSource, + ResponseUsage: append([]BenchmarkResponseUsage(nil), result.ResponseUsage...), CostUSD: result.CostUSD, + CostKnown: result.CostKnown, CostIssue: result.CostIssue, Failure: result.Failure, + Interactions: append([]BenchmarkInteraction(nil), result.Interactions...), Provider: "digbench", + GameStatus: result.Status, CurrentLevel: result.CurrentLevel, LevelsBeaten: result.LevelsBeaten, + MaxLevel: result.MaxLevel, Steps: result.Steps, + } +} + // RunDigBench runs one game through Codex's agentic tool loop. The remote game // session is created only after the requested model and effort are validated. func (c Client) RunDigBench(ctx context.Context, service digBenchService, options DigBenchOptions) (DigBenchResult, error) { @@ -193,6 +289,8 @@ func (s *appServerSession) runDigBench( applyDigBenchSession(&result, session) startedAt := time.Now() + appendDigBenchInteraction(&result, startedAt, BenchmarkInteractionState, formatDigBenchState(session)) + publishDigBenchSnapshot(options.Snapshot, result) emitDigBenchProgress(options.Progress, DigBenchProgressSession, result, startedAt) turnParams := map[string]any{ "threadId": startedThread.Thread.ID, @@ -214,6 +312,7 @@ func (s *appServerSession) runDigBench( return result, errors.New("Codex returned an invalid DigBench turn") } emitDigBenchProgress(options.Progress, DigBenchProgressTurn, result, startedAt) + publishDigBenchSnapshot(options.Snapshot, result) telemetry := newBenchmarkTelemetry() completed := false @@ -228,6 +327,25 @@ func (s *appServerSession) runDigBench( } if envelopeErr != nil { result.Duration = time.Since(startedAt) + if errors.Is(ctx.Err(), context.Canceled) { + cleanupCompleted := false + handle := func(method string, params json.RawMessage) bool { + if method == "turn/completed" && digBenchTurnCompleted(params, startedThread.Thread.ID, startedTurn.Turn.ID, &turnFailure) { + cleanupCompleted = true + return true + } + return false + } + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), s.benchmarkInterruptTimeout()) + interruptErr := s.interruptBenchmarkTurn(cleanupCtx, startedThread.Thread.ID, startedTurn.Turn.ID, &cleanupCompleted, handle) + cleanupCancel() + applyDigBenchMeasurements(&result, telemetry) + if interruptErr != nil { + result.Failure = "remote interruption could not be confirmed: " + interruptErr.Error() + } + publishDigBenchSnapshot(options.Snapshot, result) + return result, ctx.Err() + } if recoverableBenchmarkTimeout(ctx, runCtx, envelopeErr) { result.Failure = fmt.Sprintf("DigBench run timed out after %s", options.Timeout) cleanupCompleted := false @@ -245,6 +363,7 @@ func (s *appServerSession) runDigBench( if session.Done { result.Failure = "" } + publishDigBenchSnapshot(options.Snapshot, result) return result, nil } return result, envelopeErr @@ -253,13 +372,19 @@ func (s *appServerSession) runDigBench( if envelope.Method != "item/tool/call" { return result, fmt.Errorf("unsupported Codex app-server request %q", envelope.Method) } + tool, action := digBenchToolSummary(envelope.Params) response := handleDigBenchToolCall( runCtx, service, startedThread.Thread.ID, startedTurn.Turn.ID, session.SessionID, envelope.Params, &session, ) applyDigBenchSession(&result, session) if response["success"] == true { + if tool == "step" { + appendDigBenchInteraction(&result, startedAt, BenchmarkInteractionMove, action) + } + appendDigBenchInteraction(&result, startedAt, BenchmarkInteractionState, formatDigBenchState(session)) emitDigBenchProgress(options.Progress, DigBenchProgressUpdate, result, startedAt) + publishDigBenchSnapshot(options.Snapshot, result) } if err := s.respond(envelope.ID, response); err != nil { return result, fmt.Errorf("respond to DigBench tool call: %w", err) @@ -299,6 +424,12 @@ func (s *appServerSession) runDigBench( } case "turn/completed": completed = digBenchTurnCompleted(envelope.Params, startedThread.Thread.ID, startedTurn.Turn.ID, &turnFailure) + if completed { + if final := digBenchFinalResponse(envelope.Params, startedThread.Thread.ID, startedTurn.Turn.ID, session.SessionID); final != "" { + appendDigBenchInteraction(&result, startedAt, BenchmarkInteractionResponse, final) + publishDigBenchSnapshot(options.Snapshot, result) + } + } } } @@ -306,6 +437,7 @@ func (s *appServerSession) runDigBench( applyDigBenchMeasurements(&result, telemetry) if session.Done { result.Won = session.State.Status == "completed" + publishDigBenchSnapshot(options.Snapshot, result) return result, nil } if turnFailure != "" { @@ -313,9 +445,51 @@ func (s *appServerSession) runDigBench( return result, nil } result.Failure = "Codex stopped before the DigBench game ended" + publishDigBenchSnapshot(options.Snapshot, result) return result, nil } +func publishDigBenchSnapshot(callback func(DigBenchResult), result DigBenchResult) { + if callback == nil { + return + } + result.Interactions = append([]BenchmarkInteraction(nil), result.Interactions...) + result.ResponseUsage = append([]BenchmarkResponseUsage(nil), result.ResponseUsage...) + callback(result) +} + +func appendDigBenchInteraction(result *DigBenchResult, startedAt time.Time, kind BenchmarkInteractionKind, content string) { + proxy := BenchmarkResult{Interactions: result.Interactions} + appendBenchmarkInteraction(&proxy, startedAt, kind, content) + result.Interactions = proxy.Interactions +} + +func digBenchToolSummary(params json.RawMessage) (tool, action string) { + var call struct { + Tool string `json:"tool"` + Arguments struct { + Action string `json:"action"` + } `json:"arguments"` + } + if json.Unmarshal(params, &call) != nil { + return "", "" + } + return call.Tool, call.Arguments.Action +} + +func formatDigBenchState(session digbench.Session) string { + state := struct { + StepIndex int `json:"step_index"` + LevelsBeaten int `json:"levels_beaten"` + State digbench.State `json:"state"` + }{StepIndex: session.StepIndex, LevelsBeaten: session.LevelsBeaten, State: session.State} + encoded, err := json.MarshalIndent(state, "", " ") + if err != nil { + return "DigBench state could not be encoded." + } + return string(encoded) +} + func emitDigBenchProgress(callback func(DigBenchProgress), phase DigBenchProgressPhase, result DigBenchResult, startedAt time.Time) { if callback == nil { return @@ -485,6 +659,31 @@ func digBenchTurnCompleted(params json.RawMessage, threadID, turnID string, fail return true } +func digBenchFinalResponse(params json.RawMessage, threadID, turnID, sessionID string) string { + var event struct { + ThreadID string `json:"threadId"` + Turn struct { + ID string `json:"id"` + Items []struct { + Type string `json:"type"` + Text string `json:"text"` + } `json:"items"` + } `json:"turn"` + } + if json.Unmarshal(params, &event) != nil || event.ThreadID != threadID || event.Turn.ID != turnID { + return "" + } + for _, item := range event.Turn.Items { + if item.Type == "agentMessage" && strings.TrimSpace(item.Text) != "" { + if sessionID != "" { + return strings.ReplaceAll(item.Text, sessionID, "[digbench-session]") + } + return item.Text + } + } + return "" +} + func applyDigBenchMeasurements(result *DigBenchResult, telemetry *benchmarkTelemetry) { var measurements BenchmarkResult telemetry.apply(&measurements) diff --git a/internal/codex/digbench_test.go b/internal/codex/digbench_test.go index ebd3e098..5a0795c3 100644 --- a/internal/codex/digbench_test.go +++ b/internal/codex/digbench_test.go @@ -3,6 +3,7 @@ package codex import ( "context" "encoding/json" + "errors" "strings" "testing" "time" @@ -64,6 +65,7 @@ func TestRunDigBenchBridgesScopedStepAndDetectsWin(t *testing.T) { benchmarkEnvelope{Method: "turn/completed", Params: rawJSON(map[string]any{ "threadId": "thread-1", "turn": map[string]any{ "id": "turn-1", "status": "failed", "error": map[string]string{"message": "debrief failed after terminal move"}, + "items": []any{map[string]string{"type": "agentMessage", "text": "The winning rule for session-1 was discovered."}}, }, })}, ) @@ -78,9 +80,11 @@ func TestRunDigBenchBridgesScopedStepAndDetectsWin(t *testing.T) { t.Cleanup(func() { openBenchmarkAppServer = original }) var progress []DigBenchProgress + var snapshots []DigBenchResult result, err := (Client{BenchmarkAPIKey: "benchmark-secret"}).RunDigBench(context.Background(), service, DigBenchOptions{ Game: "P-1", Model: "gpt-5.6-sol", Effort: "high", Timeout: time.Minute, ClientVersion: "test", Progress: func(event DigBenchProgress) { progress = append(progress, event) }, + Snapshot: func(result DigBenchResult) { snapshots = append(snapshots, result) }, }) if err != nil { t.Fatal(err) @@ -103,6 +107,14 @@ func TestRunDigBenchBridgesScopedStepAndDetectsWin(t *testing.T) { if final := progress[2]; final.Level != 3 || final.LevelsBeaten != 3 || final.MaxLevel != 3 || final.Steps != 1 || final.Status != "completed" || final.Elapsed < 0 { t.Fatalf("final progress = %#v", final) } + if len(snapshots) < 3 || len(result.Interactions) != 4 || result.Interactions[1].Kind != BenchmarkInteractionMove || result.Interactions[1].Content != "b" || result.Interactions[2].Kind != BenchmarkInteractionState || result.Interactions[3].Kind != BenchmarkInteractionResponse { + t.Fatalf("DigBench snapshots/interactions = %d / %#v", len(snapshots), result.Interactions) + } + for _, interaction := range result.Interactions { + if strings.Contains(interaction.Content, "session-1") { + t.Fatalf("session id leaked into transcript: %#v", interaction) + } + } requestLog := requests.String() for _, expected := range []string{`"dynamicTools"`, `"sandbox":"workspace-write"`, `"method":"turn/start"`, `"id":50`, `"success":true`, `\"status\":\"completed\"`} { if !strings.Contains(requestLog, expected) { @@ -111,6 +123,14 @@ func TestRunDigBenchBridgesScopedStepAndDetectsWin(t *testing.T) { } } +func TestClientBenchmarkTasksRequireDigBenchToken(t *testing.T) { + plain := (Client{}).BenchmarkTasks() + enabled := (Client{DigBenchToken: "secret"}).BenchmarkTasks() + if len(enabled) != len(plain)+1 || enabled[len(enabled)-1] != DigBenchTask() { + t.Fatalf("plain=%#v enabled=%#v", plain, enabled) + } +} + func TestNextPendingEnvelopeCanReportHeartbeat(t *testing.T) { server, _ := newFakeBenchmarkServer() heartbeat := make(chan time.Time, 1) @@ -121,6 +141,51 @@ func TestNextPendingEnvelopeCanReportHeartbeat(t *testing.T) { } } +func TestRunDigBenchInterruptsTurnWhenStopped(t *testing.T) { + maxLevel := 3 + service := &fakeDigBenchService{session: digbench.Session{ + Game: "P-1", SessionID: "session-1", + State: digbench.State{Status: "in_progress", Level: 1, MaxLevel: &maxLevel, Observation: "___", Actions: []string{"b"}}, + }} + server, requests := newFakeBenchmarkServer( + benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{"data": []any{map[string]any{ + "model": "gpt-5.6-sol", "displayName": "GPT-5.6 Sol", + "supportedReasoningEfforts": []any{map[string]string{"reasoningEffort": "high"}}, + }}})}, + benchmarkEnvelope{ID: rawJSON(2), Result: rawJSON(map[string]any{ + "thread": map[string]string{"id": "thread-1"}, "model": "gpt-5.6-sol", + })}, + benchmarkEnvelope{ID: rawJSON(3), Result: rawJSON(map[string]any{"turn": map[string]string{"id": "turn-1"}})}, + ) + server.experimentalAPI = true + original := openBenchmarkAppServer + openBenchmarkAppServer = func(context.Context, string, string) (*appServerSession, error) { return server, nil } + t.Cleanup(func() { openBenchmarkAppServer = original }) + + ctx, cancel := context.WithCancel(context.Background()) + result, err := (Client{}).RunDigBench(ctx, service, DigBenchOptions{ + Game: "P-1", Model: "gpt-5.6-sol", Effort: "high", Timeout: time.Minute, + Progress: func(progress DigBenchProgress) { + if progress.Phase == DigBenchProgressTurn { + cancel() + go func() { + time.Sleep(time.Millisecond) + server.envelopes <- benchmarkEnvelope{Method: "turn/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turn": map[string]any{"id": "turn-1", "status": "interrupted"}, + })} + server.envelopes <- benchmarkEnvelope{ID: rawJSON(4), Result: rawJSON(map[string]any{})} + }() + } + }, + }) + if !errors.Is(err, context.Canceled) || result.Failure != "" { + t.Fatalf("result=%#v error=%v", result, err) + } + if !strings.Contains(requests.String(), `"method":"turn/interrupt"`) { + t.Fatalf("turn interrupt was not requested: %s", requests.String()) + } +} + func TestDigBenchToolRejectsAnotherSession(t *testing.T) { service := &fakeDigBenchService{session: digbench.Session{SessionID: "session-1"}} current := service.session diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index 1ea2f31a..0dee8bd8 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -171,11 +171,30 @@ func (m Model) benchmarkDetailLines(width int, colors palette) []string { outcome = "PASS" outcomeStyle = lipgloss.NewStyle().Bold(true).Foreground(colors.primary) } + if result.Provider == "digbench" && !m.benchmarkDetailActive && !result.Stopped { + if result.Correct { + outcome = "WIN" + } else if result.Failure != "" { + outcome = "INCOMPLETE" + } else { + outcome = "LOSS" + } + } lines := []string{ outcomeStyle.Render(fitTableCell("RESULT // "+outcome, width)), colors.label().Render(fitTableCell("MODEL // "+model+" // EFFORT // "+strings.ToUpper(result.Effort), width)), colors.label().Render(fitTableCell("TASK // "+result.TaskName+" // TIME // "+formatBenchmarkDuration(result.Duration), width)), } + if result.Provider == "digbench" { + level := fmt.Sprintf("%d", result.CurrentLevel) + if result.MaxLevel > 0 { + level = fmt.Sprintf("%d/%d", result.CurrentLevel, result.MaxLevel) + } + lines = append(lines, colors.label().Render(fitTableCell(fmt.Sprintf( + "DIGBENCH // LEVEL %s // BEATEN %d // STEPS %d // STATUS %s", + level, result.LevelsBeaten, result.Steps, result.GameStatus, + ), width))) + } usage := "TOKENS // N/A" if result.UsageKnown { usage = "TOKENS // " + benchmarkUsageDetail(result) @@ -261,6 +280,15 @@ func (m Model) benchmarkDetailClipboardText() string { } else if result.Correct { status = "PASS" } + if result.Provider == "digbench" && !m.benchmarkDetailActive && !result.Stopped { + if result.Correct { + status = "WIN" + } else if result.Failure != "" { + status = "INCOMPLETE" + } else { + status = "LOSS" + } + } model := result.DisplayName if model == "" { model = result.Model @@ -277,6 +305,14 @@ func (m Model) benchmarkDetailClipboardText() string { fmt.Fprintf(&output, "EFFORT: %s\n", strings.ToUpper(result.Effort)) fmt.Fprintf(&output, "TASK: %s\n", result.TaskName) fmt.Fprintf(&output, "TIME: %s\n", formatBenchmarkDuration(result.Duration)) + if result.Provider == "digbench" { + level := fmt.Sprintf("%d", result.CurrentLevel) + if result.MaxLevel > 0 { + level = fmt.Sprintf("%d/%d", result.CurrentLevel, result.MaxLevel) + } + fmt.Fprintf(&output, "DIGBENCH: LEVEL %s // BEATEN %d // STEPS %d // STATUS %s\n", + level, result.LevelsBeaten, result.Steps, result.GameStatus) + } if result.UsageKnown { fmt.Fprintf(&output, "TOKENS: %s\n", benchmarkUsageDetail(result)) } else { @@ -633,6 +669,7 @@ func (m Model) renderBenchmarkSegments(segments []benchmarkControlSegment, width func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { tasks := m.benchmarkTasks() + allTasks := m.benchmarkRunAllTasks() selected := codex.BenchmarkTask{Name: "NO TASKS"} if len(tasks) > 0 { selected = tasks[m.benchmarkSelectedTask%len(tasks)] @@ -653,13 +690,16 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { } selectedLabel := "[ (B) RUN SELECTED ]" - allTurns := m.benchmarkCombinations * len(tasks) + allTurns := m.benchmarkCombinations * len(allTasks) allLabel := fmt.Sprintf("[ (A) RUN ALL // %d ]", allTurns) scopeLabel := fmt.Sprintf("[ (S) SCOPE // %d ]", m.benchmarkCombinations) stopLabel := "[ (X) STOP ]" if m.benchmarkPlanning { allLabel = "[ DISCOVERING TURNS… ]" } + if selected.External && m.benchmarkCombinations != 1 { + selectedLabel = "[ SELECT 1 PAIR IN SCOPE ]" + } if m.benchmarkAllArmed { allLabel = fmt.Sprintf("[ CONFIRM // %d TURNS ]", allTurns) } @@ -693,7 +733,7 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { } primary := []benchmarkControlSegment{ {text: selectedLabel, button: footerButtonBenchmarkSelected, enabled: m.benchmarkCanRunSelected() && len(tasks) > 0}, - {text: allLabel, button: footerButtonBenchmarkAll, enabled: benchmarkRunAllAvailable(running, m.benchmarkCombinations, len(tasks))}, + {text: allLabel, button: footerButtonBenchmarkAll, enabled: benchmarkRunAllAvailable(running, m.benchmarkCombinations, len(allTasks))}, } secondary := []benchmarkControlSegment{ {text: scopeLabel, button: footerButtonBenchmarkScope, enabled: !running && len(m.benchmarkPlan.Models) > 0}, @@ -816,12 +856,21 @@ func (m Model) renderBenchmarkStatus(width, height int, colors palette) string { colors.dimmed().Render(ansi.Truncate(detail, max(width-4, 1), "")), } if height >= 5 { - lines = append(lines, colors.dimmed().Render(ansi.Truncate("HERMETIC STARLARK // BOUNDED STEPS PER CASE", max(width-4, 1), ""))) + boundary := "HERMETIC STARLARK // BOUNDED STEPS PER CASE" + if m.benchmarkSelectedTaskExternal() || strings.HasPrefix(m.benchmarkCurrentTask, "DIGBENCH") { + boundary = "EXTERNAL DIGBENCH // PERSISTED REMOTE SESSION // RANDOM SEED" + } + lines = append(lines, colors.dimmed().Render(ansi.Truncate(boundary, max(width-4, 1), ""))) } lines = lines[:min(len(lines), max(height-2, 0))] return frameSized(width, max(height-2, 1), "ALGORITHM TRIAL", strings.Join(lines, "\n"), color, colors) } +func (m Model) benchmarkSelectedTaskExternal() bool { + tasks := m.benchmarkTasks() + return len(tasks) > 0 && tasks[m.benchmarkSelectedTask%len(tasks)].External +} + func latestBenchmarkFailure(results []codex.BenchmarkResult) string { for index := len(results) - 1; index >= 0; index-- { if !results[index].Correct && results[index].Failure != "" { @@ -1136,6 +1185,15 @@ func benchmarkResultValues(result codex.BenchmarkResult, rankings map[string]int } else if result.Correct { outcome = "PASS" } + if result.Provider == "digbench" && !inProgress && !result.Stopped { + if result.Correct { + outcome = "WIN" + } else if result.Failure != "" { + outcome = "INCOMPLETE" + } else { + outcome = "LOSS" + } + } cost := "N/A" if result.CostKnown { cost = fmt.Sprintf("~$%.4f", result.CostUSD) @@ -1149,7 +1207,7 @@ func benchmarkResultValues(result codex.BenchmarkResult, rankings map[string]int model += "→" + result.ActualModel } rank := "—" - if value := rankings[benchmarkCombinationKey(result)]; !inProgress && !result.Stopped && value > 0 { + if value := rankings[benchmarkCombinationKey(result)]; result.Provider == "" && !inProgress && !result.Stopped && value > 0 { rank = fmt.Sprintf("#%d", value) } return []string{ diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index 5b35e1c1..71802c4c 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -588,6 +588,47 @@ func TestBenchmarkScopeAreaHonorsAllocatedSize(t *testing.T) { } } +func TestDigBenchTaskRequiresOnePairAndIsExcludedFromRunAll(t *testing.T) { + client := codex.Client{DigBenchToken: "secret"} + model := Model{benchmarkRunner: client, benchmarkScopedRunner: client, benchmarkCombinations: 2} + tasks := model.benchmarkTasks() + model.benchmarkSelectedTask = len(tasks) - 1 + if !tasks[model.benchmarkSelectedTask].External || model.benchmarkCanRunSelected() { + t.Fatalf("DigBench should be visible but disabled with two pairs: %#v", tasks) + } + model.benchmarkCombinations = 1 + if !model.benchmarkCanRunSelected() { + t.Fatal("DigBench was not enabled with exactly one selected pair") + } + for _, task := range model.benchmarkRunAllTasks() { + if task.External { + t.Fatalf("external task included in Run All: %#v", task) + } + } +} + +func TestDigBenchDetailShowsProgressAndTranscript(t *testing.T) { + result := codex.BenchmarkResult{ + TaskID: codex.BenchmarkDigBenchP1, TaskName: "DIGBENCH P-1", Provider: "digbench", + Model: "gpt-5.6-sol", DisplayName: "GPT-5.6 Sol", Effort: "high", Correct: true, + CurrentLevel: 14, LevelsBeaten: 14, MaxLevel: 14, Steps: 553, GameStatus: "completed", + Interactions: []codex.BenchmarkInteraction{ + {Kind: codex.BenchmarkInteractionMove, Content: "move_right"}, + {Kind: codex.BenchmarkInteractionState, Content: `{"observation":"WIN"}`}, + }, + } + model := Model{benchmarkDetail: &result} + output := ansi.Strip(strings.Join(model.benchmarkDetailLines(100, paletteFor(themeHacker)), "\n")) + for _, want := range []string{"RESULT // WIN", "LEVEL 14/14", "BEATEN 14", "STEPS 553", "MOVE //", "move_right", `"observation":"WIN"`} { + if !strings.Contains(output, want) { + t.Fatalf("DigBench detail missing %q:\n%s", want, output) + } + } + if copied := model.benchmarkDetailClipboardText(); !strings.Contains(copied, "RESULT: WIN") || !strings.Contains(copied, "DIGBENCH: LEVEL 14/14") { + t.Fatalf("DigBench clipboard text missing progress:\n%s", copied) + } +} + func TestBenchmarkTableClipsOlderRows(t *testing.T) { model := Model{benchmarkState: benchmarkFinished} for index := 0; index < 20; index++ { diff --git a/internal/ui/model.go b/internal/ui/model.go index da21f080..3f7cc803 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -36,6 +36,10 @@ type ScopedBenchmarkRunner interface { RunBenchmarkSuiteScoped(context.Context, []codex.BenchmarkTaskID, codex.BenchmarkScope, func(codex.BenchmarkEvent)) } +type BenchmarkTaskProvider interface { + BenchmarkTasks() []codex.BenchmarkTask +} + type Model struct { fetcher Fetcher usageFetcher TokenUsageFetcher @@ -921,7 +925,7 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { } } case footerButtonBenchmarkAll: - tasks := m.benchmarkTasks() + tasks := m.benchmarkRunAllTasks() if m.meterView == viewBenchmark && benchmarkRunAllAvailable(m.benchmarkRunActive(), m.benchmarkCombinations, len(tasks)) { if !m.benchmarkAllArmed { m.benchmarkAllArmed = true @@ -1126,7 +1130,15 @@ func (m Model) benchmarkRunActive() bool { } func (m Model) benchmarkCanRunSelected() bool { - return !m.benchmarkRunActive() && (m.benchmarkScopedRunner == nil || m.benchmarkCombinations > 0) + if m.benchmarkRunActive() || (m.benchmarkScopedRunner != nil && m.benchmarkCombinations == 0) { + return false + } + tasks := m.benchmarkTasks() + if len(tasks) == 0 { + return false + } + selected := tasks[m.benchmarkSelectedTask%len(tasks)] + return !selected.External || m.benchmarkCombinations == 1 } func (m Model) benchmarkPlanNeeded() bool { @@ -1178,9 +1190,23 @@ func (m *Model) selectBenchmarkTask(direction int) { } func (m Model) benchmarkTasks() []codex.BenchmarkTask { + if provider, ok := m.benchmarkRunner.(BenchmarkTaskProvider); ok { + return provider.BenchmarkTasks() + } return codex.BenchmarkTasks() } +func (m Model) benchmarkRunAllTasks() []codex.BenchmarkTask { + tasks := m.benchmarkTasks() + selected := make([]codex.BenchmarkTask, 0, len(tasks)) + for _, task := range tasks { + if !task.External { + selected = append(selected, task) + } + } + return selected +} + func (m *Model) setBenchmarkFilter(filter benchmarkResultFilter) { m.benchmarkFilter = filter m.benchmarkScroll = 0 diff --git a/main.go b/main.go index 6b6027fc..d9fbde53 100644 --- a/main.go +++ b/main.go @@ -249,13 +249,13 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { fmt.Fprintln(stderr, "codexometer: --digbench-game cannot be combined with --demo") return 2 } - token := strings.TrimSpace(os.Getenv("DIGBENCH_API_TOKEN")) - if token == "" { - fmt.Fprintln(stderr, "codexometer: DIGBENCH_API_TOKEN is required for --digbench-game") + token, tokenErr := takeDigBenchToken() + if tokenErr != nil { + fmt.Fprintln(stderr, "codexometer:", tokenErr) return 1 } - if err := os.Unsetenv("DIGBENCH_API_TOKEN"); err != nil { - fmt.Fprintln(stderr, "codexometer: remove DIGBENCH_API_TOKEN from child environment:", err) + if token == "" { + fmt.Fprintln(stderr, "codexometer: DIGBENCH_API_TOKEN is required for --digbench-game") return 1 } benchmarkAPIKey, benchmarkAPIKeySource, err := takeBenchmarkAPIKey() @@ -296,7 +296,12 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { fmt.Fprintln(stderr, "codexometer:", err) return 1 } - client := codex.Client{Binary: *codexPath, BenchmarkAPIKey: benchmarkAPIKey} + digBenchToken, err := takeDigBenchToken() + if err != nil { + fmt.Fprintln(stderr, "codexometer:", err) + return 1 + } + client := codex.Client{Binary: *codexPath, BenchmarkAPIKey: benchmarkAPIKey, DigBenchToken: digBenchToken} if liveUsage, err := codex.NewLiveUsageReader(""); err == nil { client.LiveUsage = liveUsage } @@ -350,6 +355,14 @@ func takeBenchmarkAPIKey() (key, source string, err error) { return key, source, nil } +func takeDigBenchToken() (string, error) { + token := strings.TrimSpace(os.Getenv("DIGBENCH_API_TOKEN")) + if err := os.Unsetenv("DIGBENCH_API_TOKEN"); err != nil { + return "", fmt.Errorf("remove DIGBENCH_API_TOKEN from child environment: %w", err) + } + return token, nil +} + func formatDigBenchResult(result codex.DigBenchResult) string { outcome := "LOSS" if result.Won { diff --git a/main_test.go b/main_test.go index de14a970..b9aa5de7 100644 --- a/main_test.go +++ b/main_test.go @@ -218,6 +218,26 @@ func TestRunPassesOpenAIAPIKeyToUIBenchmarks(t *testing.T) { } } +func TestRunPassesDigBenchTokenToUIWithoutLeavingItInEnvironment(t *testing.T) { + t.Setenv("DIGBENCH_API_TOKEN", "digbench-secret") + var stdout, stderr bytes.Buffer + deps := dependencies{ + startUI: func(fetcher ui.Fetcher, _ time.Duration, _ bool) error { + client, ok := fetcher.(codex.Client) + if !ok || client.DigBenchToken != "digbench-secret" { + t.Fatalf("DigBench token was not attached to Codex client") + } + if os.Getenv("DIGBENCH_API_TOKEN") != "" { + t.Fatal("DIGBENCH_API_TOKEN remained in the inherited environment") + } + return nil + }, + } + if code := run(nil, &stdout, &stderr, deps); code != 0 { + t.Fatalf("code=%d stdout=%q stderr=%q", code, stdout.String(), stderr.String()) + } +} + func TestRunDigBenchRequiresToken(t *testing.T) { t.Setenv("DIGBENCH_API_TOKEN", "") var stdout, stderr bytes.Buffer From 39aefe69636387a9caefc434954dcdf2a0cab924 Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 22 Aug 2026 12:42:34 +0100 Subject: [PATCH 06/18] FEAT: discover and scope DigBench games --- README.md | 21 ++++---- internal/codex/benchmark.go | 14 +++-- internal/codex/benchmark_tasks.go | 11 ++-- internal/codex/client.go | 6 ++- internal/codex/digbench.go | 88 ++++++++++++++++++++----------- internal/codex/digbench_test.go | 41 +++++++++++++- internal/digbench/client.go | 2 +- internal/digbench/client_test.go | 16 ++++++ internal/ui/benchmark.go | 57 +++++++++++++++++++- internal/ui/benchmark_test.go | 47 +++++++++++++++-- internal/ui/model.go | 21 +++++++- main.go | 37 +++++++++++-- main_test.go | 11 +++- 13 files changed, 303 insertions(+), 69 deletions(-) diff --git a/README.md b/README.md index db80972f..8ee85001 100644 --- a/README.md +++ b/README.md @@ -807,15 +807,18 @@ Neither key is written to preferences or accepted as a command-line argument. Codexometer includes a deliberately narrow integration for [DigBench](https://digbench.ai/), an external benchmark of discovering unknown rules in interactive text games. Supplying `DIGBENCH_API_TOKEN` adds -**DIGBENCH P-1** to the Benchmark tab's task selector. Select exactly one -compatible model/reasoning-effort pair on the **Scope** screen, choose that -task, and use **Run Selected**. DigBench is deliberately excluded from **Run -All** because every invocation creates a persisted remote session with a random -seed. +**DIGBENCH** to the Benchmark tab's task selector. At launch, Codexometer calls +authenticated `GET /games` and uses every game name returned by DigBench; no +`P-x` catalog is compiled into Codexometer. Select DigBench, open **Scope**, and +use its additional game-checkbox group to check all, clear all, or choose any +subset. DigBench also requires exactly one compatible model/reasoning-effort +pair. **Run Selected** displays the exact remote-session count and requires a +second confirmation before running the selected games sequentially. DigBench is +excluded from **Run All** because every game invocation creates a persisted +remote session with a random seed. Create a token from the [DigBench token page](https://digbench.ai/account/tokens) -(sign-in is a passwordless email link) and place it in the environment. The TUI -currently exposes the proof-of-concept game `P-1`: +(sign-in is a passwordless email link) and place it in the environment: ```sh export DIGBENCH_API_TOKEN="" @@ -855,8 +858,8 @@ the scoped dynamic-tool bridge. Step calls are safely retried using DigBench's idempotent `step_index` protocol; session creation is never automatically retried because that endpoint does not document idempotency. -In the TUI, the run appears immediately in the existing result table and can be -opened while it is in progress. Its benchmark-only detail view reports +In the TUI, each selected game run appears immediately in the existing result +table and can be opened while it is in progress. Its benchmark-only detail view reports authoritative level, beaten-level, step, and status counters, followed by every captured move and the sanitized DigBench state returned for that move. The **Copy** control exports that complete captured view. DigBench session IDs, diff --git a/internal/codex/benchmark.go b/internal/codex/benchmark.go index 688a601e..2da785ff 100644 --- a/internal/codex/benchmark.go +++ b/internal/codex/benchmark.go @@ -169,6 +169,7 @@ type BenchmarkEvent struct { type BenchmarkPlan struct { Models []BenchmarkModelOption Efforts []string + Games []string } // BenchmarkModelOption is one selectable model and its supported efforts. @@ -183,11 +184,12 @@ type BenchmarkModelOption struct { type BenchmarkScope struct { Models []string Efforts []string + Games []string } // AllScope selects every model and effort in the plan. func (p BenchmarkPlan) AllScope() BenchmarkScope { - scope := BenchmarkScope{Efforts: append([]string(nil), p.Efforts...)} + scope := BenchmarkScope{Efforts: append([]string(nil), p.Efforts...), Games: append([]string(nil), p.Games...)} for _, model := range p.Models { scope.Models = append(scope.Models, model.Model) } @@ -311,7 +313,9 @@ func (c Client) BenchmarkPlan(ctx context.Context) (BenchmarkPlan, error) { if err != nil { return BenchmarkPlan{}, err } - return benchmarkPlan(models), nil + plan := benchmarkPlan(models) + plan.Games = append([]string(nil), c.DigBenchGames...) + return plan, nil } // RunBenchmarkSuite runs each selected deterministic task once for every @@ -334,13 +338,13 @@ func (c Client) runBenchmarkSuite(ctx context.Context, taskIDs []BenchmarkTaskID emit = func(BenchmarkEvent) {} } if len(taskIDs) == 1 { - if game, ok := digBenchGame(taskIDs[0]); ok { - c.runDigBenchBenchmarkSuite(ctx, taskIDs[0], game, emit, scopes...) + if isDigBenchTask(taskIDs[0]) { + c.runDigBenchBenchmarkSuite(ctx, taskIDs[0], emit, scopes...) return } } for _, id := range taskIDs { - if _, external := digBenchGame(id); external { + if isDigBenchTask(id) { emit(benchmarkTerminalEvent(ctx, 0, 0, 0, errors.New("DigBench must be run separately from deterministic benchmarks"))) return } diff --git a/internal/codex/benchmark_tasks.go b/internal/codex/benchmark_tasks.go index c018be36..be102224 100644 --- a/internal/codex/benchmark_tasks.go +++ b/internal/codex/benchmark_tasks.go @@ -19,7 +19,7 @@ const ( BenchmarkDependencyScheduler BenchmarkTaskID = "dependency-scheduler" BenchmarkVersionResolver BenchmarkTaskID = "version-resolver" BenchmarkEventProcessor BenchmarkTaskID = "event-processor" - BenchmarkDigBenchP1 BenchmarkTaskID = "digbench-p-1" + BenchmarkDigBench BenchmarkTaskID = "digbench" ) // BenchmarkTask is the public description used by the terminal selector. @@ -126,14 +126,11 @@ func BenchmarkTasks() []BenchmarkTask { // current integration. It is omitted from Run All because every invocation // creates a persisted remote session with a random seed. func DigBenchTask() BenchmarkTask { - return BenchmarkTask{ID: BenchmarkDigBenchP1, Name: "DIGBENCH P-1", External: true} + return BenchmarkTask{ID: BenchmarkDigBench, Name: "DIGBENCH", External: true} } -func digBenchGame(id BenchmarkTaskID) (string, bool) { - if id == BenchmarkDigBenchP1 { - return "P-1", true - } - return "", false +func isDigBenchTask(id BenchmarkTaskID) bool { + return id == BenchmarkDigBench } func resolveBenchmarkTasks(ids []BenchmarkTaskID) ([]benchmarkDefinition, error) { diff --git a/internal/codex/client.go b/internal/codex/client.go index 20ab2e0f..62b297ee 100644 --- a/internal/codex/client.go +++ b/internal/codex/client.go @@ -24,9 +24,11 @@ type Client struct { // BenchmarkAPIKey is used only by isolated benchmark app-server sessions. // Fetch and local monitoring continue to use the prevailing Codex login. BenchmarkAPIKey string - // DigBenchToken is retained in memory only and enables the external P-1 - // option in the Benchmark tab. + // DigBenchToken is retained in memory only and enables the external games + // returned by launch-time discovery in the Benchmark tab. DigBenchToken string + // DigBenchGames is the launch-time GET /games result available to the TUI. + DigBenchGames []string } // FetchTokenUsage reads live telemetry from locally observed Codex sessions. diff --git a/internal/codex/digbench.go b/internal/codex/digbench.go index 4a460072..e79ea7df 100644 --- a/internal/codex/digbench.go +++ b/internal/codex/digbench.go @@ -90,17 +90,21 @@ var newDigBenchService = func(token string) digBenchService { return digbench.Client{Token: token} } +var runDigBenchTrial = func(ctx context.Context, client Client, service digBenchService, options DigBenchOptions) (DigBenchResult, error) { + return client.RunDigBench(ctx, service, options) +} + // BenchmarkTasks exposes the external proof-of-concept only when this process // received a DigBench token. Run All continues to use deterministic tasks only. func (c Client) BenchmarkTasks() []BenchmarkTask { tasks := BenchmarkTasks() - if strings.TrimSpace(c.DigBenchToken) != "" { + if strings.TrimSpace(c.DigBenchToken) != "" && len(c.DigBenchGames) > 0 { tasks = append(tasks, DigBenchTask()) } return tasks } -func (c Client) runDigBenchBenchmarkSuite(ctx context.Context, taskID BenchmarkTaskID, game string, emit func(BenchmarkEvent), scopes ...BenchmarkScope) { +func (c Client) runDigBenchBenchmarkSuite(ctx context.Context, taskID BenchmarkTaskID, emit func(BenchmarkEvent), scopes ...BenchmarkScope) { if strings.TrimSpace(c.DigBenchToken) == "" { emit(benchmarkTerminalEvent(ctx, 0, 0, 0, errors.New("DIGBENCH_API_TOKEN is required for DigBench"))) return @@ -130,40 +134,60 @@ func (c Client) runDigBenchBenchmarkSuite(ctx context.Context, taskID BenchmarkT emit(benchmarkTerminalEvent(ctx, 0, 0, 0, fmt.Errorf("DigBench requires exactly one selected model/effort pair; scope contains %d", len(selected)))) return } - choice := selected[0] - event := BenchmarkEvent{Total: 1, Combinations: 1, CurrentTaskID: taskID, CurrentTask: "DIGBENCH " + game, CurrentModel: choice.name, CurrentEffort: choice.effort} - pending := BenchmarkResult{ - TaskID: taskID, TaskName: "DIGBENCH " + game, Provider: "digbench", - Model: choice.model, DisplayName: choice.name, ActualModel: choice.model, Effort: choice.effort, - GameStatus: "connecting", - } - event.Active = &pending - emit(event) - result, runErr := c.RunDigBench(ctx, newDigBenchService(c.DigBenchToken), DigBenchOptions{ - Game: game, Model: choice.model, Effort: choice.effort, - Snapshot: func(snapshot DigBenchResult) { - active := benchmarkResultFromDigBench(taskID, snapshot) - event.Active = &active - emit(event) - }, - }) - if result.Game == "" { - result.Game = game + availableGames := stringSet(plan.Games) + games := make([]string, 0, len(scope.Games)) + for _, game := range scope.Games { + if availableGames[game] { + games = append(games, game) + } } - if result.Model == "" { - result.Model, result.DisplayName, result.ActualModel, result.Effort = choice.model, choice.name, choice.model, choice.effort + if len(games) == 0 { + emit(benchmarkTerminalEvent(ctx, 0, 0, 0, errors.New("select at least one DigBench game"))) + return } - converted := benchmarkResultFromDigBench(taskID, result) - if errors.Is(ctx.Err(), context.Canceled) { - markBenchmarkStopped(&converted) - event.Active, event.Result, event.Stopped = nil, &converted, true + choice := selected[0] + total, completed := len(games), 0 + emit(BenchmarkEvent{Total: total, Combinations: 1}) + for _, game := range games { + event := BenchmarkEvent{Total: total, Completed: completed, Combinations: 1, CurrentTaskID: taskID, CurrentTask: "DIGBENCH " + game, CurrentModel: choice.name, CurrentEffort: choice.effort} + pending := BenchmarkResult{ + TaskID: taskID, TaskName: "DIGBENCH " + game, Provider: "digbench", + Model: choice.model, DisplayName: choice.name, ActualModel: choice.model, Effort: choice.effort, + GameStatus: "connecting", + } + event.Active = &pending emit(event) - emit(BenchmarkEvent{Total: 1, Combinations: 1, Stopped: true, Done: true}) - return + result, runErr := runDigBenchTrial(ctx, c, newDigBenchService(c.DigBenchToken), DigBenchOptions{ + Game: game, Model: choice.model, Effort: choice.effort, + Snapshot: func(snapshot DigBenchResult) { + active := benchmarkResultFromDigBench(taskID, snapshot) + event.Active = &active + emit(event) + }, + }) + if result.Game == "" { + result.Game = game + } + if result.Model == "" { + result.Model, result.DisplayName, result.ActualModel, result.Effort = choice.model, choice.name, choice.model, choice.effort + } + converted := benchmarkResultFromDigBench(taskID, result) + if errors.Is(ctx.Err(), context.Canceled) { + markBenchmarkStopped(&converted) + event.Active, event.Result, event.Stopped = nil, &converted, true + emit(event) + emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: 1, Stopped: true, Done: true}) + return + } + completed++ + event.Completed, event.Active, event.Result = completed, nil, &converted + emit(event) + if runErr != nil { + emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: 1, Done: true, Err: runErr}) + return + } } - event.Completed, event.Active, event.Result = 1, nil, &converted - emit(event) - emit(BenchmarkEvent{Total: 1, Completed: 1, Combinations: 1, Done: true, Err: runErr}) + emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: 1, Done: true}) } func benchmarkResultFromDigBench(taskID BenchmarkTaskID, result DigBenchResult) BenchmarkResult { diff --git a/internal/codex/digbench_test.go b/internal/codex/digbench_test.go index 5a0795c3..757fb67f 100644 --- a/internal/codex/digbench_test.go +++ b/internal/codex/digbench_test.go @@ -125,12 +125,51 @@ func TestRunDigBenchBridgesScopedStepAndDetectsWin(t *testing.T) { func TestClientBenchmarkTasksRequireDigBenchToken(t *testing.T) { plain := (Client{}).BenchmarkTasks() - enabled := (Client{DigBenchToken: "secret"}).BenchmarkTasks() + enabled := (Client{DigBenchToken: "secret", DigBenchGames: []string{"P-1"}}).BenchmarkTasks() if len(enabled) != len(plain)+1 || enabled[len(enabled)-1] != DigBenchTask() { t.Fatalf("plain=%#v enabled=%#v", plain, enabled) } } +func TestDigBenchBenchmarkSuiteRunsSelectedDiscoveredGames(t *testing.T) { + server, _ := newFakeBenchmarkServer(benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{"data": []any{map[string]any{ + "model": "model", "displayName": "Model", + "supportedReasoningEfforts": []any{map[string]string{"reasoningEffort": "high"}}, + }}})}) + originalOpen := openBenchmarkAppServer + openBenchmarkAppServer = func(context.Context, string, string) (*appServerSession, error) { return server, nil } + t.Cleanup(func() { openBenchmarkAppServer = originalOpen }) + + originalRun := runDigBenchTrial + var games []string + runDigBenchTrial = func(_ context.Context, _ Client, _ digBenchService, options DigBenchOptions) (DigBenchResult, error) { + games = append(games, options.Game) + result := DigBenchResult{Game: options.Game, Model: options.Model, DisplayName: "Model", ActualModel: options.Model, Effort: options.Effort, Won: true, Status: "completed"} + options.Snapshot(result) + return result, nil + } + t.Cleanup(func() { runDigBenchTrial = originalRun }) + + var events []BenchmarkEvent + client := Client{DigBenchToken: "secret", DigBenchGames: []string{"P-1", "P-2", "P-3"}} + client.RunBenchmarkSuiteScoped(context.Background(), []BenchmarkTaskID{BenchmarkDigBench}, BenchmarkScope{ + Models: []string{"model"}, Efforts: []string{"high"}, Games: []string{"P-2", "P-3"}, + }, func(event BenchmarkEvent) { events = append(events, event) }) + if len(games) != 2 || games[0] != "P-2" || games[1] != "P-3" { + t.Fatalf("selected games run = %#v", games) + } + results := 0 + for _, event := range events { + if event.Result != nil { + results++ + } + } + final := events[len(events)-1] + if results != 2 || !final.Done || final.Total != 2 || final.Completed != 2 || final.Err != nil { + t.Fatalf("events = %#v", events) + } +} + func TestNextPendingEnvelopeCanReportHeartbeat(t *testing.T) { server, _ := newFakeBenchmarkServer() heartbeat := make(chan time.Time, 1) diff --git a/internal/digbench/client.go b/internal/digbench/client.go index ba8b5664..9d51c16d 100644 --- a/internal/digbench/client.go +++ b/internal/digbench/client.go @@ -98,7 +98,7 @@ func (e *APIError) Error() string { func (c Client) ListGames(ctx context.Context) (GamesResponse, error) { var response GamesResponse - err := c.do(ctx, http.MethodGet, "/games", nil, true, false, &response) + err := c.do(ctx, http.MethodGet, "/games", nil, true, true, &response) return response, err } diff --git a/internal/digbench/client_test.go b/internal/digbench/client_test.go index 17cfcbe7..399854f3 100644 --- a/internal/digbench/client_test.go +++ b/internal/digbench/client_test.go @@ -44,6 +44,22 @@ func TestStartSessionUsesBearerAndDecodesState(t *testing.T) { } } +func TestListGamesUsesBearerAndReturnsCompleteCatalog(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.Method != http.MethodGet || request.URL.Path != "/games" || request.Header.Get("Authorization") != "Bearer secret" { + t.Fatalf("request = %s %s headers=%#v", request.Method, request.URL.Path, request.Header) + } + writer.Header().Set("Content-Type", "application/json") + _, _ = writer.Write([]byte(`{"games":["P-1","P-2","P-17"],"game_details":[{"name":"P-1","tier":1}]}`)) + })) + defer server.Close() + + response, err := (Client{BaseURL: server.URL, Token: "secret", HTTPClient: server.Client()}).ListGames(context.Background()) + if err != nil || len(response.Games) != 3 || response.Games[2] != "P-17" { + t.Fatalf("response=%#v error=%v", response, err) + } +} + func TestStepUsesSessionScopeRetriesAndDetectsWin(t *testing.T) { var calls atomic.Int32 server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index 0dee8bd8..05a94057 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -396,6 +396,8 @@ const ( benchmarkScopeModel benchmarkScopeAllEfforts benchmarkScopeEffort + benchmarkScopeAllGames + benchmarkScopeGame ) type benchmarkScopeItem struct { @@ -421,8 +423,12 @@ func (m Model) renderBenchmarkScope(width, height int, colors palette) string { for len(lines) < bodyHeight { lines = append(lines, strings.Repeat(" ", innerWidth)) } - title := fmt.Sprintf("BENCHMARK SCOPE // %d MODELS // %d EFFORTS // %d PAIRS // SPACE TOGGLE // ESC DONE", + title := fmt.Sprintf("BENCHMARK SCOPE // %d MODELS // %d EFFORTS // %d PAIRS", len(m.benchmarkScope.Models), len(m.benchmarkScope.Efforts), m.benchmarkCombinations) + if m.benchmarkSelectedTaskExternal() { + title += fmt.Sprintf(" // %d/%d GAMES", len(m.benchmarkScope.Games), len(m.benchmarkPlan.Games)) + } + title += " // SPACE TOGGLE // ESC DONE" return frameSized(width, bodyHeight, ansi.Truncate(title, max(innerWidth-4, 1), ""), strings.Join(lines, "\n"), colors.primary, colors) } @@ -459,7 +465,7 @@ func (m Model) renderBenchmarkScopeItem(item benchmarkScopeItem, index, width in if item.selected { style = lipgloss.NewStyle().Foreground(colors.primary) } - if item.kind == benchmarkScopeDone || item.kind == benchmarkScopeAllModels || item.kind == benchmarkScopeAllEfforts { + if item.kind == benchmarkScopeDone || item.kind == benchmarkScopeAllModels || item.kind == benchmarkScopeAllEfforts || item.kind == benchmarkScopeAllGames { style = style.Bold(true).Foreground(colors.accent) } return style.Render(fitTableCell(label, width)) @@ -495,6 +501,21 @@ func (m Model) benchmarkScopeItems() []benchmarkScopeItem { label: " " + scopeCheckLabel(selected) + " " + strings.ToUpper(effort), }) } + if m.benchmarkSelectedTaskExternal() { + allGames := len(m.benchmarkPlan.Games) > 0 && len(m.benchmarkScope.Games) == len(m.benchmarkPlan.Games) + items = append(items, benchmarkScopeItem{ + kind: benchmarkScopeAllGames, selected: allGames, + label: scopeCheckLabel(allGames) + " DIGBENCH GAMES // " + scopeAllAction(allGames), + }) + selectedGames := stringSetUI(m.benchmarkScope.Games) + for _, game := range m.benchmarkPlan.Games { + selected := selectedGames[game] + items = append(items, benchmarkScopeItem{ + kind: benchmarkScopeGame, value: game, selected: selected, + label: " " + scopeCheckLabel(selected) + " " + strings.ToUpper(game), + }) + } + } return items } @@ -585,9 +606,18 @@ func (m *Model) toggleBenchmarkScopeCursor() { } case benchmarkScopeEffort: m.benchmarkScope.Efforts = toggleScopeValue(m.benchmarkScope.Efforts, item.value) + case benchmarkScopeAllGames: + if item.selected { + m.benchmarkScope.Games = nil + } else { + m.benchmarkScope.Games = m.benchmarkPlan.AllScope().Games + } + case benchmarkScopeGame: + m.benchmarkScope.Games = toggleScopeValue(m.benchmarkScope.Games, item.value) } m.benchmarkCombinations = m.benchmarkPlan.CombinationCount(m.benchmarkScope) m.benchmarkAllArmed = false + m.benchmarkSelectedArmed = false } func toggleScopeValue(values []string, value string) []string { @@ -699,12 +729,27 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { } if selected.External && m.benchmarkCombinations != 1 { selectedLabel = "[ SELECT 1 PAIR IN SCOPE ]" + } else if selected.External && len(m.benchmarkScope.Games) == 0 { + selectedLabel = "[ SELECT DIGBENCH GAMES ]" + } else if selected.External { + selectedLabel = fmt.Sprintf("[ (B) RUN DIGBENCH // %d ]", len(m.benchmarkScope.Games)) + if m.benchmarkSelectedArmed { + selectedLabel = fmt.Sprintf("[ CONFIRM // %d REMOTE SESSIONS ]", len(m.benchmarkScope.Games)) + } } if m.benchmarkAllArmed { allLabel = fmt.Sprintf("[ CONFIRM // %d TURNS ]", allTurns) } if lipgloss.Width(selectedLabel)+lipgloss.Width(allLabel)+1 > width { selectedLabel = "[B:RUN]" + if selected.External { + selectedLabel = fmt.Sprintf("[B:DIG %d]", len(m.benchmarkScope.Games)) + if m.benchmarkCombinations != 1 || len(m.benchmarkScope.Games) == 0 { + selectedLabel = "[B:SCOPE]" + } else if m.benchmarkSelectedArmed { + selectedLabel = fmt.Sprintf("[B:CONFIRM %d]", len(m.benchmarkScope.Games)) + } + } allLabel = fmt.Sprintf("[A:SUITE %d]", allTurns) if m.benchmarkPlanning { allLabel = "[A:WAIT]" @@ -715,6 +760,14 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { } if lipgloss.Width(selectedLabel)+lipgloss.Width(allLabel)+1 > width { selectedLabel = "[RUN]" + if selected.External { + selectedLabel = fmt.Sprintf("[D:%d]", len(m.benchmarkScope.Games)) + if m.benchmarkCombinations != 1 || len(m.benchmarkScope.Games) == 0 { + selectedLabel = "[SCOPE]" + } else if m.benchmarkSelectedArmed { + selectedLabel = fmt.Sprintf("[D:%d?]", len(m.benchmarkScope.Games)) + } + } allLabel = fmt.Sprintf("[ALL:%d]", allTurns) if m.benchmarkPlanning { allLabel = "[A:…]" diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index 71802c4c..d38cb6df 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -589,8 +589,12 @@ func TestBenchmarkScopeAreaHonorsAllocatedSize(t *testing.T) { } func TestDigBenchTaskRequiresOnePairAndIsExcludedFromRunAll(t *testing.T) { - client := codex.Client{DigBenchToken: "secret"} - model := Model{benchmarkRunner: client, benchmarkScopedRunner: client, benchmarkCombinations: 2} + client := codex.Client{DigBenchToken: "secret", DigBenchGames: []string{"P-1", "P-2"}} + model := Model{ + benchmarkRunner: client, benchmarkScopedRunner: client, benchmarkCombinations: 2, + benchmarkPlan: codex.BenchmarkPlan{Games: []string{"P-1", "P-2"}}, + benchmarkScope: codex.BenchmarkScope{Games: []string{"P-1", "P-2"}}, + } tasks := model.benchmarkTasks() model.benchmarkSelectedTask = len(tasks) - 1 if !tasks[model.benchmarkSelectedTask].External || model.benchmarkCanRunSelected() { @@ -607,9 +611,46 @@ func TestDigBenchTaskRequiresOnePairAndIsExcludedFromRunAll(t *testing.T) { } } +func TestDigBenchScopeFiltersDiscoveredGamesAndConfirmsRemoteSessions(t *testing.T) { + plan := codex.BenchmarkPlan{ + Models: []codex.BenchmarkModelOption{{Model: "model", DisplayName: "Model", Efforts: []string{"high"}}}, + Efforts: []string{"high"}, Games: []string{"P-1", "P-2", "P-3"}, + } + client := codex.Client{DigBenchToken: "secret", DigBenchGames: plan.Games} + model := Model{ + benchmarkRunner: client, benchmarkScopedRunner: client, benchmarkPlan: plan, benchmarkScope: plan.AllScope(), + benchmarkCombinations: 1, benchmarkSelectedTask: len(client.BenchmarkTasks()) - 1, meterView: viewBenchmark, + } + items := model.benchmarkScopeItems() + var p2 int + for index, item := range items { + if item.kind == benchmarkScopeGame && item.value == "P-2" { + p2 = index + } + } + if p2 == 0 { + t.Fatalf("discovered games missing from Scope: %#v", items) + } + model.benchmarkScopeCursor = p2 + model.toggleBenchmarkScopeCursor() + if len(model.benchmarkScope.Games) != 2 || slices.Contains(model.benchmarkScope.Games, "P-2") { + t.Fatalf("game checkbox did not narrow scope: %#v", model.benchmarkScope.Games) + } + updated, command := model.Update(key('b')) + model = updated.(Model) + if !model.benchmarkSelectedArmed || model.benchmarkState == benchmarkRunning || command == nil { + t.Fatal("DigBench did not require confirmation before creating remote sessions") + } + updated, command = model.Update(key('b')) + model = updated.(Model) + if model.benchmarkSelectedArmed || model.benchmarkState != benchmarkRunning || model.benchmarkTotal != 2 || command == nil { + t.Fatalf("confirmed DigBench run did not start selected games: state=%d total=%d", model.benchmarkState, model.benchmarkTotal) + } +} + func TestDigBenchDetailShowsProgressAndTranscript(t *testing.T) { result := codex.BenchmarkResult{ - TaskID: codex.BenchmarkDigBenchP1, TaskName: "DIGBENCH P-1", Provider: "digbench", + TaskID: codex.BenchmarkDigBench, TaskName: "DIGBENCH P-1", Provider: "digbench", Model: "gpt-5.6-sol", DisplayName: "GPT-5.6 Sol", Effort: "high", Correct: true, CurrentLevel: 14, LevelsBeaten: 14, MaxLevel: 14, Steps: 553, GameStatus: "completed", Interactions: []codex.BenchmarkInteraction{ diff --git a/internal/ui/model.go b/internal/ui/model.go index 3f7cc803..a98d7fb2 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -90,6 +90,7 @@ type Model struct { benchmarkSelectedTask int benchmarkFilter benchmarkResultFilter benchmarkAllArmed bool + benchmarkSelectedArmed bool benchmarkConfirmSequence uint64 benchmarkScroll int benchmarkSort benchmarkSortColumn @@ -804,6 +805,7 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { case benchmarkConfirmExpiredMsg: if message.sequence == m.benchmarkConfirmSequence { m.benchmarkAllArmed = false + m.benchmarkSelectedArmed = false } } return m, nil @@ -918,9 +920,17 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { } case footerButtonBenchmarkSelected: if m.meterView == viewBenchmark && m.benchmarkCanRunSelected() { - m.benchmarkAllArmed = false tasks := m.benchmarkTasks() if len(tasks) > 0 { + selected := tasks[m.benchmarkSelectedTask%len(tasks)] + if selected.External && !m.benchmarkSelectedArmed { + m.benchmarkSelectedArmed = true + m.benchmarkConfirmSequence++ + sequence := m.benchmarkConfirmSequence + return m, tea.Tick(5*time.Second, func(time.Time) tea.Msg { return benchmarkConfirmExpiredMsg{sequence: sequence} }) + } + m.benchmarkSelectedArmed = false + m.benchmarkAllArmed = false return m.startBenchmark([]codex.BenchmarkTaskID{tasks[m.benchmarkSelectedTask%len(tasks)].ID}) } } @@ -964,6 +974,7 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { if m.meterView == viewBenchmark && m.benchmarkState == benchmarkRunning { m.benchmarkState = benchmarkStopping m.benchmarkAllArmed = false + m.benchmarkSelectedArmed = false m.cancelBenchmark() } } @@ -1138,7 +1149,7 @@ func (m Model) benchmarkCanRunSelected() bool { return false } selected := tasks[m.benchmarkSelectedTask%len(tasks)] - return !selected.External || m.benchmarkCombinations == 1 + return !selected.External || (m.benchmarkCombinations == 1 && len(m.benchmarkScope.Games) > 0) } func (m Model) benchmarkPlanNeeded() bool { @@ -1156,6 +1167,9 @@ func (m Model) startBenchmark(tasks []codex.BenchmarkTaskID) (Model, tea.Cmd) { } m.benchmarkResults = nil m.benchmarkTotal = m.benchmarkCombinations * len(tasks) + if len(tasks) == 1 && tasks[0] == codex.BenchmarkDigBench { + m.benchmarkTotal = len(m.benchmarkScope.Games) + } m.benchmarkCompleted = 0 m.benchmarkCurrentModel = "" m.benchmarkCurrentEffort = "" @@ -1173,6 +1187,8 @@ func (m Model) startBenchmark(tasks []codex.BenchmarkTaskID) (Model, tea.Cmd) { m.benchmarkScopeOpen = false m.benchmarkScopeHover = -1 m.benchmarkState = benchmarkRunning + m.benchmarkAllArmed = false + m.benchmarkSelectedArmed = false ctx, cancel := context.WithCancel(context.Background()) m.benchmarkCancel = cancel events := make(chan codex.BenchmarkEvent, 2) @@ -1187,6 +1203,7 @@ func (m *Model) selectBenchmarkTask(direction int) { } m.benchmarkSelectedTask = (m.benchmarkSelectedTask + direction + len(tasks)) % len(tasks) m.benchmarkAllArmed = false + m.benchmarkSelectedArmed = false } func (m Model) benchmarkTasks() []codex.BenchmarkTask { diff --git a/main.go b/main.go index d9fbde53..ba4545cd 100644 --- a/main.go +++ b/main.go @@ -193,9 +193,10 @@ func main() { } type dependencies struct { - checkAuth func(context.Context, string) (codex.Snapshot, error) - runDigBench func(context.Context, string, string, string, codex.DigBenchOptions) (codex.DigBenchResult, error) - startUI func(ui.Fetcher, time.Duration, bool) error + checkAuth func(context.Context, string) (codex.Snapshot, error) + listDigBenchGames func(context.Context, string) ([]string, error) + runDigBench func(context.Context, string, string, string, codex.DigBenchOptions) (codex.DigBenchResult, error) + startUI func(ui.Fetcher, time.Duration, bool) error } func defaultDependencies() dependencies { @@ -203,6 +204,10 @@ func defaultDependencies() dependencies { checkAuth: func(ctx context.Context, binary string) (codex.Snapshot, error) { return (codex.Client{Binary: binary}).Fetch(ctx) }, + listDigBenchGames: func(ctx context.Context, token string) ([]string, error) { + response, err := (digbench.Client{Token: token}).ListGames(ctx) + return response.Games, err + }, runDigBench: func(ctx context.Context, binary, token, apiKey string, options codex.DigBenchOptions) (codex.DigBenchResult, error) { return (codex.Client{Binary: binary, BenchmarkAPIKey: apiKey}).RunDigBench(ctx, digbench.Client{Token: token}, options) }, @@ -301,7 +306,18 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { fmt.Fprintln(stderr, "codexometer:", err) return 1 } - client := codex.Client{Binary: *codexPath, BenchmarkAPIKey: benchmarkAPIKey, DigBenchToken: digBenchToken} + var digBenchGames []string + if digBenchToken != "" && deps.listDigBenchGames != nil { + discoveryCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + digBenchGames, err = deps.listDigBenchGames(discoveryCtx, digBenchToken) + cancel() + if err != nil { + fmt.Fprintln(stderr, "codexometer: DigBench game discovery unavailable:", err) + digBenchGames = nil + } + } + digBenchGames = normalizeDigBenchGames(digBenchGames) + client := codex.Client{Binary: *codexPath, BenchmarkAPIKey: benchmarkAPIKey, DigBenchToken: digBenchToken, DigBenchGames: digBenchGames} if liveUsage, err := codex.NewLiveUsageReader(""); err == nil { client.LiveUsage = liveUsage } @@ -363,6 +379,19 @@ func takeDigBenchToken() (string, error) { return token, nil } +func normalizeDigBenchGames(games []string) []string { + seen := make(map[string]bool, len(games)) + normalized := make([]string, 0, len(games)) + for _, game := range games { + game = strings.TrimSpace(game) + if game != "" && !seen[game] { + seen[game] = true + normalized = append(normalized, game) + } + } + return normalized +} + func formatDigBenchResult(result codex.DigBenchResult) string { outcome := "LOSS" if result.Won { diff --git a/main_test.go b/main_test.go index b9aa5de7..4bf42439 100644 --- a/main_test.go +++ b/main_test.go @@ -222,11 +222,20 @@ func TestRunPassesDigBenchTokenToUIWithoutLeavingItInEnvironment(t *testing.T) { t.Setenv("DIGBENCH_API_TOKEN", "digbench-secret") var stdout, stderr bytes.Buffer deps := dependencies{ + listDigBenchGames: func(_ context.Context, token string) ([]string, error) { + if token != "digbench-secret" { + t.Fatalf("game discovery token = %q", token) + } + return []string{"P-2", "P-1", "P-2"}, nil + }, startUI: func(fetcher ui.Fetcher, _ time.Duration, _ bool) error { client, ok := fetcher.(codex.Client) if !ok || client.DigBenchToken != "digbench-secret" { t.Fatalf("DigBench token was not attached to Codex client") } + if len(client.DigBenchGames) != 2 || client.DigBenchGames[0] != "P-2" || client.DigBenchGames[1] != "P-1" { + t.Fatalf("DigBench games were not normalized: %#v", client.DigBenchGames) + } if os.Getenv("DIGBENCH_API_TOKEN") != "" { t.Fatal("DIGBENCH_API_TOKEN remained in the inherited environment") } @@ -249,7 +258,7 @@ func TestRunDigBenchRequiresToken(t *testing.T) { func TestDefaultDependenciesAreConfigured(t *testing.T) { deps := defaultDependencies() - if deps.checkAuth == nil || deps.runDigBench == nil || deps.startUI == nil { + if deps.checkAuth == nil || deps.listDigBenchGames == nil || deps.runDigBench == nil || deps.startUI == nil { t.Fatal("default dependencies are incomplete") } } From d51709ba0089c607328fe4c19d57d28aa9eb15a0 Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 22 Aug 2026 12:59:25 +0100 Subject: [PATCH 07/18] FEAT: refine benchmark detail controls --- internal/ui/benchmark.go | 44 +++++++++++++++++++++++------------ internal/ui/benchmark_test.go | 21 ++++++++++++++++- internal/ui/model.go | 8 +++++++ internal/ui/view.go | 30 +++++++++++++++++++++++- 4 files changed, 86 insertions(+), 17 deletions(-) diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index 05a94057..5c289dfa 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -54,7 +54,10 @@ type benchmarkControlSegment struct { active bool } -const benchmarkDetailCopyLabel = "[ (C) COPY ]" +const ( + benchmarkDetailCopyLabel = "[ (C) COPY ]" + benchmarkDetailCloseLabel = "[ (X) CLOSE ]" +) func layoutBenchmarkArea(width, height int) benchmarkGeometry { width = max(width, 1) @@ -143,8 +146,17 @@ func (m Model) renderBenchmarkDetail(width, height int, colors palette) string { if m.benchmarkDetailActive { detailState = "LIVE RUN DETAIL // IN PROGRESS" } - title := fmt.Sprintf("%s // BENCHMARK-ONLY // LINES %d-%d/%d // ESC BACK", detailState, min(scroll+1, len(lines)), end, len(lines)) - return frameSizedWithTitleAction(width, bodyHeight, ansi.Truncate(title, max(innerWidth-4, 1), ""), m.renderBenchmarkDetailCopy(colors), strings.Join(visible, "\n"), colors.primary, colors) + title := fmt.Sprintf("%s // BENCHMARK-ONLY // LINES %d-%d/%d", detailState, min(scroll+1, len(lines)), end, len(lines)) + return frameSizedWithActions( + width, + bodyHeight, + ansi.Truncate(title, max(innerWidth-4, 1), ""), + m.renderBenchmarkDetailControl(benchmarkDetailCloseLabel, footerButtonBenchmarkClose, colors), + m.renderBenchmarkDetailControl(benchmarkDetailCopyLabel, footerButtonBenchmarkCopy, colors), + strings.Join(visible, "\n"), + colors.primary, + colors, + ) } func (m Model) benchmarkDetailLines(width int, colors palette) []string { @@ -256,15 +268,15 @@ func (m Model) benchmarkDetailResult() (codex.BenchmarkResult, bool) { return result, true } -func (m Model) renderBenchmarkDetailCopy(colors palette) string { +func (m Model) renderBenchmarkDetailControl(label string, button footerButtonID, colors palette) string { style := lipgloss.NewStyle().Foreground(colors.dim).Background(colors.background) - if m.hoveredButton == footerButtonBenchmarkCopy { + if m.hoveredButton == button { style = style.Bold(true).Foreground(colors.accent) } - if m.flashedButton == footerButtonBenchmarkCopy { + if m.flashedButton == button { style = style.Bold(true).Foreground(colors.background).Background(colors.primary) } - return style.Render(benchmarkDetailCopyLabel) + return style.Render(label) } func (m Model) benchmarkDetailClipboardText() string { @@ -1596,7 +1608,7 @@ func (m Model) benchmarkButtonAt(x, y int) footerButtonID { return footerButtonNone } if m.benchmarkDetail != nil { - return m.benchmarkDetailCopyAt(x, y) + return m.benchmarkDetailButtonAt(x, y) } dashboard := m.dashboardLayout() layout := layoutBenchmarkArea(dashboard.contentWidth, dashboard.meterHeight) @@ -1617,18 +1629,20 @@ func (m Model) benchmarkButtonAt(x, y int) footerButtonID { return footerButtonNone } -func (m Model) benchmarkDetailCopyAt(x, y int) footerButtonID { +func (m Model) benchmarkDetailButtonAt(x, y int) footerButtonID { if m.meterView != viewBenchmark || m.benchmarkDetail == nil || x < 0 || y < 0 { return footerButtonNone } dashboard := m.dashboardLayout() - labelWidth := lipgloss.Width(benchmarkDetailCopyLabel) - if dashboard.contentWidth < labelWidth+8 || y != dashboard.meterY { - return footerButtonNone - } localX := x - 2 - start := dashboard.contentWidth - labelWidth - 2 - if localX >= start && localX < start+labelWidth { + closeWidth := lipgloss.Width(benchmarkDetailCloseLabel) + closeStart := dashboard.contentWidth - closeWidth - 2 + if dashboard.contentWidth >= closeWidth+8 && y == dashboard.meterY && localX >= closeStart && localX < closeStart+closeWidth { + return footerButtonBenchmarkClose + } + copyWidth := lipgloss.Width(benchmarkDetailCopyLabel) + copyStart := dashboard.contentWidth - copyWidth - 2 + if dashboard.contentWidth >= copyWidth+4 && y == dashboard.meterY+dashboard.meterHeight-1 && localX >= copyStart && localX < copyStart+copyWidth { return footerButtonBenchmarkCopy } return footerButtonNone diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index d38cb6df..65377947 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -146,7 +146,7 @@ func TestBenchmarkRowClickOpensScrollableBenchmarkOnlyDetail(t *testing.T) { t.Fatal("benchmark row click did not open its detail") } output := ansi.Strip(model.render()) - for _, want := range []string{"RUN DETAIL", benchmarkDetailCopyLabel, "RESULT // PASS", "Detail Model", "TOTAL 4321", "PROMPT //", "Solve the benchmark-only prompt", "RESPONSE //", "safe benchmark response"} { + for _, want := range []string{"RUN DETAIL", benchmarkDetailCloseLabel, benchmarkDetailCopyLabel, "RESULT // PASS", "Detail Model", "TOTAL 4321", "PROMPT //", "Solve the benchmark-only prompt", "RESPONSE //", "safe benchmark response"} { if !strings.Contains(output, want) { t.Fatalf("benchmark detail missing %q:\n%s", want, output) } @@ -158,6 +158,13 @@ func TestBenchmarkRowClickOpensScrollableBenchmarkOnlyDetail(t *testing.T) { t.Fatalf("benchmark detail height = %d, want %d", got, model.height) } copyX, copyY := renderedTextStart(t, model, benchmarkDetailCopyLabel) + closeX, closeY := renderedTextStart(t, model, benchmarkDetailCloseLabel) + if closeY != model.dashboardLayout().meterY { + t.Fatalf("Close control y = %d, want top frame y = %d", closeY, model.dashboardLayout().meterY) + } + if copyY != model.dashboardLayout().meterY+model.dashboardLayout().meterHeight-1 { + t.Fatalf("Copy control y = %d, want bottom frame y = %d", copyY, model.dashboardLayout().meterY+model.dashboardLayout().meterHeight-1) + } updated, command = model.Update(tea.MouseMotionMsg{X: copyX, Y: copyY}) model = updated.(Model) if command != nil || model.hoveredButton != footerButtonBenchmarkCopy { @@ -182,6 +189,18 @@ func TestBenchmarkRowClickOpensScrollableBenchmarkOnlyDetail(t *testing.T) { if model.benchmarkDetailScroll == 0 { t.Fatal("Page Down did not scroll a long benchmark detail") } + updated, command = model.Update(tea.MouseClickMsg{X: closeX, Y: closeY, Button: tea.MouseLeft}) + model = updated.(Model) + if command == nil || model.benchmarkDetail != nil || model.benchmarkSelectedRun != benchmarkRunKey(result) { + t.Fatal("Close control did not return to the selected matrix row") + } + model.openBenchmarkDetail(result) + updated, command = model.Update(tea.KeyPressMsg{Code: 'x', Text: "x"}) + model = updated.(Model) + if command == nil || model.benchmarkDetail != nil { + t.Fatal("X did not close the benchmark detail") + } + model.openBenchmarkDetail(result) updated, command = model.Update(specialKey(tea.KeyEscape)) model = updated.(Model) if command != nil || model.benchmarkDetail != nil || model.benchmarkSelectedRun != benchmarkRunKey(result) { diff --git a/internal/ui/model.go b/internal/ui/model.go index a98d7fb2..d14a2a0c 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -314,6 +314,7 @@ const ( footerButtonBenchmarkRankBalanced footerButtonBenchmarkRankSpeed footerButtonBenchmarkCopy + footerButtonBenchmarkClose footerButtonBenchmarkScope footerButtonBenchmarkStop ) @@ -403,6 +404,9 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { } case "x": if m.meterView == viewBenchmark { + if m.benchmarkDetail != nil { + return m.pressFooterButton(footerButtonBenchmarkClose) + } return m.pressFooterButton(footerButtonBenchmarkStop) } case "d": @@ -966,6 +970,10 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { if m.meterView == viewBenchmark && m.benchmarkDetail != nil { return m, tea.SetClipboard(m.benchmarkDetailClipboardText()) } + case footerButtonBenchmarkClose: + if m.meterView == viewBenchmark && m.benchmarkDetail != nil { + m.closeBenchmarkDetail() + } case footerButtonBenchmarkScope: if m.meterView == viewBenchmark && !m.benchmarkRunActive() && len(m.benchmarkPlan.Models) > 0 { m.openBenchmarkScope() diff --git a/internal/ui/view.go b/internal/ui/view.go index 6d91c252..1b08dff9 100644 --- a/internal/ui/view.go +++ b/internal/ui/view.go @@ -231,6 +231,10 @@ func frameSized(width, height int, title, body string, color imagecolor.Color, c } func frameSizedWithTitleAction(width, height int, title, action, body string, color imagecolor.Color, colors palette) string { + return frameSizedWithActions(width, height, title, action, "", body, color, colors) +} + +func frameSizedWithActions(width, height int, title, titleAction, footerAction, body string, color imagecolor.Color, colors palette) string { width = max(width, 1) style := lipgloss.NewStyle(). Width(width). @@ -246,7 +250,13 @@ func frameSizedWithTitleAction(width, height int, title, action, body string, co // reserving one extra row for that border. style = style.Height(height + 1) } - return renderFrameTitleWithAction(width, title, action, color, colors) + "\n" + style.Render(body) + renderedBody := style.Render(body) + if footerAction != "" { + lines := strings.Split(renderedBody, "\n") + lines[len(lines)-1] = renderFrameFooterWithAction(width, footerAction, color, colors) + renderedBody = strings.Join(lines, "\n") + } + return renderFrameTitleWithAction(width, title, titleAction, color, colors) + "\n" + renderedBody } func renderFrameTitle(width int, title string, color imagecolor.Color, colors palette) string { @@ -291,6 +301,24 @@ func renderFrameTitleWithAction(width int, title, action string, color imagecolo return borderStyle.Render(prefix) + titleStyle.Render(title) + borderStyle.Render(middle) + suffix } +func renderFrameFooterWithAction(width int, action string, color imagecolor.Color, colors palette) string { + width = max(width, 1) + border := lipgloss.RoundedBorder() + borderStyle := lipgloss.NewStyle().Foreground(color).Background(colors.background) + if width == 1 { + return borderStyle.Render(border.Bottom) + } + if width == 2 { + return borderStyle.Render(border.BottomLeft + border.BottomRight) + } + actionWidth := lipgloss.Width(action) + if actionWidth == 0 || width < actionWidth+4 { + return borderStyle.Render(border.BottomLeft + strings.Repeat(border.Bottom, width-2) + border.BottomRight) + } + middleWidth := width - actionWidth - 4 + return borderStyle.Render(border.BottomLeft+strings.Repeat(border.Bottom, middleWidth)+" ") + action + borderStyle.Render(" "+border.BottomRight) +} + func countdown(at time.Time) string { return countdownFrom(time.Now(), at) } From 468148c5cfdaf486c7b39aedaf25f808e297c9a0 Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 22 Aug 2026 13:18:04 +0100 Subject: [PATCH 08/18] PERF: cache benchmark detail transcripts --- internal/ui/benchmark.go | 106 +++++++++++++++++++++---- internal/ui/benchmark_test.go | 142 ++++++++++++++++++++++++++++++++++ internal/ui/model.go | 46 +++++++++++ 3 files changed, 278 insertions(+), 16 deletions(-) diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index 5c289dfa..f9795d7b 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -54,6 +54,17 @@ type benchmarkControlSegment struct { active bool } +type benchmarkDetailTranscriptCache struct { + valid bool + run string + width int + theme themeID + correct bool + interactionCount int + lastInteraction codex.BenchmarkInteraction + lines []string +} + const ( benchmarkDetailCopyLabel = "[ (C) COPY ]" benchmarkDetailCloseLabel = "[ (X) CLOSE ]" @@ -134,11 +145,12 @@ func (m Model) renderBenchmarkDetail(width, height int, colors palette) string { } innerWidth := max(width-4, 1) bodyHeight := max(height-2, 1) - lines := m.benchmarkDetailLines(innerWidth, colors) - maximum := max(len(lines)-bodyHeight, 0) + header, transcript := m.benchmarkDetailSections(innerWidth, colors) + lineCount := len(header) + len(transcript) + maximum := max(lineCount-bodyHeight, 0) scroll := min(max(m.benchmarkDetailScroll, 0), maximum) - end := min(scroll+bodyHeight, len(lines)) - visible := lines[scroll:end] + end := min(scroll+bodyHeight, lineCount) + visible := benchmarkDetailLineRange(header, transcript, scroll, end) for len(visible) < bodyHeight { visible = append(visible, strings.Repeat(" ", innerWidth)) } @@ -146,7 +158,7 @@ func (m Model) renderBenchmarkDetail(width, height int, colors palette) string { if m.benchmarkDetailActive { detailState = "LIVE RUN DETAIL // IN PROGRESS" } - title := fmt.Sprintf("%s // BENCHMARK-ONLY // LINES %d-%d/%d", detailState, min(scroll+1, len(lines)), end, len(lines)) + title := fmt.Sprintf("%s // BENCHMARK-ONLY // LINES %d-%d/%d", detailState, min(scroll+1, lineCount), end, lineCount) return frameSizedWithActions( width, bodyHeight, @@ -164,6 +176,23 @@ func (m Model) benchmarkDetailLines(width int, colors palette) []string { if !ok { return nil } + header := benchmarkDetailHeaderLines(result, m.benchmarkDetailActive, width, colors) + transcript := m.benchmarkDetailTranscriptLines(result, width, colors) + lines := make([]string, 0, len(header)+len(transcript)) + lines = append(lines, header...) + lines = append(lines, transcript...) + return lines +} + +func (m Model) benchmarkDetailSections(width int, colors palette) ([]string, []string) { + result, ok := m.benchmarkDetailResult() + if !ok { + return nil, nil + } + return benchmarkDetailHeaderLines(result, m.benchmarkDetailActive, width, colors), m.benchmarkDetailTranscriptLines(result, width, colors) +} + +func benchmarkDetailHeaderLines(result codex.BenchmarkResult, active bool, width int, colors palette) []string { model := result.DisplayName if model == "" { model = result.Model @@ -176,14 +205,14 @@ func (m Model) benchmarkDetailLines(width int, colors palette) []string { if result.Stopped { outcome = "STOPPED" outcomeStyle = lipgloss.NewStyle().Bold(true).Foreground(colors.warning) - } else if m.benchmarkDetailActive { + } else if active { outcome = "IN PROGRESS" outcomeStyle = lipgloss.NewStyle().Bold(true).Foreground(colors.accent) } else if result.Correct { outcome = "PASS" outcomeStyle = lipgloss.NewStyle().Bold(true).Foreground(colors.primary) } - if result.Provider == "digbench" && !m.benchmarkDetailActive && !result.Stopped { + if result.Provider == "digbench" && !active && !result.Stopped { if result.Correct { outcome = "WIN" } else if result.Failure != "" { @@ -227,20 +256,37 @@ func (m Model) benchmarkDetailLines(width int, colors palette) []string { lines = append(lines, lipgloss.NewStyle().Foreground(colors.danger).Render(fitTableCell(label+result.Failure, width))) } lines = append(lines, colors.dimmed().Render(strings.Repeat("─", width))) + return lines +} + +func (m Model) benchmarkDetailTranscriptLines(result codex.BenchmarkResult, width int, colors palette) []string { if len(result.Interactions) == 0 { - lines = append(lines, - colors.label().Render(fitTableCell("BENCHMARK TRANSCRIPT // UNAVAILABLE", width)), - colors.dimmed().Render(fitTableCell("This result predates detail capture or was supplied by demo data.", width)), - ) - return lines + return benchmarkDetailUnavailableLines(width, colors) + } + cache := m.benchmarkDetailCache + if cache.matches(result, width, m.theme) { + return cache.lines } - for index, interaction := range result.Interactions { + return buildBenchmarkDetailTranscriptLines(result.Interactions, 0, width, colors, result.Correct) +} + +func benchmarkDetailUnavailableLines(width int, colors palette) []string { + return []string{ + colors.label().Render(fitTableCell("BENCHMARK TRANSCRIPT // UNAVAILABLE", width)), + colors.dimmed().Render(fitTableCell("This result predates detail capture or was supplied by demo data.", width)), + } +} + +func buildBenchmarkDetailTranscriptLines(interactions []codex.BenchmarkInteraction, start, width int, colors palette, correct bool) []string { + lines := make([]string, 0, max(len(interactions)-start, 0)*3) + for index := start; index < len(interactions); index++ { + interaction := interactions[index] if index > 0 { lines = append(lines, colors.dimmed().Render(strings.Repeat("─", width))) } heading := fmt.Sprintf("%s // +%s", strings.ToUpper(string(interaction.Kind)), formatBenchmarkDuration(interaction.Elapsed)) headingStyle := colors.label() - if interaction.Kind == codex.BenchmarkInteractionVerifier && !result.Correct { + if interaction.Kind == codex.BenchmarkInteractionVerifier && !correct { headingStyle = lipgloss.NewStyle().Bold(true).Foreground(colors.danger) } lines = append(lines, headingStyle.Render(fitTableCell(heading, width))) @@ -255,6 +301,34 @@ func (m Model) benchmarkDetailLines(width int, colors palette) []string { return lines } +func (cache benchmarkDetailTranscriptCache) matches(result codex.BenchmarkResult, width int, theme themeID) bool { + if !cache.valid || cache.run != benchmarkDetailCacheKey(result) || cache.width != width || cache.theme != theme || cache.correct != result.Correct || cache.interactionCount != len(result.Interactions) { + return false + } + return cache.interactionCount == 0 || cache.lastInteraction == result.Interactions[cache.interactionCount-1] +} + +func benchmarkDetailCacheKey(result codex.BenchmarkResult) string { + return benchmarkRunKey(result) + "\x00" + strings.ToLower(result.Provider) + "\x00" + strings.ToLower(result.TaskName) +} + +func benchmarkDetailLineRange(header, transcript []string, start, end int) []string { + if start >= end { + return nil + } + visible := make([]string, 0, end-start) + if start < len(header) { + headerEnd := min(end, len(header)) + visible = append(visible, header[start:headerEnd]...) + } + transcriptStart := max(start-len(header), 0) + transcriptEnd := min(max(end-len(header), 0), len(transcript)) + if transcriptStart < transcriptEnd { + visible = append(visible, transcript[transcriptStart:transcriptEnd]...) + } + return visible +} + func (m Model) benchmarkDetailResult() (codex.BenchmarkResult, bool) { if m.benchmarkDetail == nil { return codex.BenchmarkResult{}, false @@ -396,8 +470,8 @@ func (m Model) benchmarkDetailMaximumScroll() int { return 0 } layout := m.dashboardLayout() - lines := m.benchmarkDetailLines(max(layout.contentWidth-4, 1), paletteFor(m.theme)) - return max(len(lines)-max(layout.meterHeight-2, 1), 0) + header, transcript := m.benchmarkDetailSections(max(layout.contentWidth-4, 1), paletteFor(m.theme)) + return max(len(header)+len(transcript)-max(layout.meterHeight-2, 1), 0) } type benchmarkScopeItemKind int diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index 65377947..391164d1 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -230,6 +230,148 @@ func TestBenchmarkDetailCopyShortcutExportsContentOutsideViewport(t *testing.T) } } +func TestBenchmarkDetailTranscriptCacheScrollsAppendsAndInvalidates(t *testing.T) { + interactions := make([]codex.BenchmarkInteraction, 0, 128) + for index := range 128 { + interactions = append(interactions, codex.BenchmarkInteraction{ + Elapsed: time.Duration(index) * time.Second, + Kind: codex.BenchmarkInteractionState, + Content: fmt.Sprintf(`{"step":%d,"observation":%q}`, index, strings.Repeat("terrain ", 12)), + }) + } + active := codex.BenchmarkResult{ + TaskID: "digbench", TaskName: "DIGBENCH P-9", Model: "model", DisplayName: "Model", Effort: "high", + Provider: "digbench", Interactions: interactions, + } + model := Model{ + snapshot: codex.DemoSnapshot(), width: 100, height: 30, meterView: viewBenchmark, + benchmarkActive: &active, + } + model.openBenchmarkDetail(active, true) + cache := model.benchmarkDetailCache + if !cache.valid || cache.interactionCount != len(interactions) || len(cache.lines) == 0 { + t.Fatalf("initial transcript cache = %#v", cache) + } + + model.scrollBenchmarkDetail(3) + _ = model.renderBenchmarkDetail(model.dashboardLayout().contentWidth, model.dashboardLayout().meterHeight, paletteFor(model.theme)) + if !slices.Equal(model.benchmarkDetailCache.lines, cache.lines) { + t.Fatal("scroll rebuilt or changed the prepared transcript") + } + + progress := active + progress.Interactions = append(append([]codex.BenchmarkInteraction(nil), active.Interactions...), codex.BenchmarkInteraction{ + Elapsed: 129 * time.Second, + Kind: codex.BenchmarkInteractionMove, + Content: "move_north", + }) + updated, _ := model.Update(benchmarkEventMsg{ok: true, event: codex.BenchmarkEvent{Active: &progress, Total: 1}}) + model = updated.(Model) + if model.benchmarkDetailCache.interactionCount != len(progress.Interactions) { + t.Fatalf("incremental cache interactions = %d, want %d", model.benchmarkDetailCache.interactionCount, len(progress.Interactions)) + } + if len(model.benchmarkDetailCache.lines) <= len(cache.lines) || !slices.Equal(model.benchmarkDetailCache.lines[:len(cache.lines)], cache.lines) { + t.Fatal("live update did not append to the prepared transcript") + } + assertBenchmarkDetailCacheMatchesFullFormat(t, model) + + oldWidth := model.benchmarkDetailCache.width + updated, _ = model.Update(tea.WindowSizeMsg{Width: model.width + 20, Height: model.height}) + model = updated.(Model) + if !model.benchmarkDetailCache.valid || model.benchmarkDetailCache.width == oldWidth { + t.Fatal("terminal resize did not rebuild the transcript cache for the new width") + } + assertBenchmarkDetailCacheMatchesFullFormat(t, model) + + oldTheme := model.theme + model, _ = model.activateFooterButton(footerButtonTheme) + if model.theme == oldTheme || model.benchmarkDetailCache.theme != model.theme { + t.Fatal("theme change did not rebuild the transcript cache") + } + assertBenchmarkDetailCacheMatchesFullFormat(t, model) + + finished := progress + finished.Correct = true + finished.Interactions = append(append([]codex.BenchmarkInteraction(nil), progress.Interactions...), codex.BenchmarkInteraction{ + Elapsed: 130 * time.Second, + Kind: codex.BenchmarkInteractionVerifier, + Content: "Game won.", + }) + updated, _ = model.Update(benchmarkEventMsg{ok: true, event: codex.BenchmarkEvent{Result: &finished, Total: 1, Completed: 1}}) + model = updated.(Model) + if model.benchmarkDetailActive || !model.benchmarkDetailCache.correct || model.benchmarkDetailCache.interactionCount != len(finished.Interactions) { + t.Fatal("final result did not refresh pass-sensitive transcript styling") + } + assertBenchmarkDetailCacheMatchesFullFormat(t, model) +} + +func TestBenchmarkDetailLineRangeMatchesCombinedSections(t *testing.T) { + header := []string{"h0", "h1", "h2"} + transcript := []string{"t0", "t1", "t2", "t3"} + combined := append(append([]string(nil), header...), transcript...) + for start := 0; start <= len(combined); start++ { + for end := start; end <= len(combined); end++ { + if got, want := benchmarkDetailLineRange(header, transcript, start, end), combined[start:end]; !slices.Equal(got, want) { + t.Fatalf("range %d:%d = %#v, want %#v", start, end, got, want) + } + } + } +} + +func assertBenchmarkDetailCacheMatchesFullFormat(t *testing.T, model Model) { + t.Helper() + layout := model.dashboardLayout() + width := max(layout.contentWidth-4, 1) + colors := paletteFor(model.theme) + got := model.benchmarkDetailLines(width, colors) + uncached := model + uncached.benchmarkDetailCache = benchmarkDetailTranscriptCache{} + want := uncached.benchmarkDetailLines(width, colors) + if !slices.Equal(got, want) { + t.Fatal("cached transcript differs from a complete format") + } +} + +func BenchmarkBenchmarkDetailLongTranscript(b *testing.B) { + interactions := make([]codex.BenchmarkInteraction, 0, 512) + for index := range 512 { + interactions = append(interactions, codex.BenchmarkInteraction{ + Elapsed: time.Duration(index) * time.Second, + Kind: codex.BenchmarkInteractionState, + Content: fmt.Sprintf(`{"step":%d,"observation":%q}`, index, strings.Repeat("unknown terrain ", 24)), + }) + } + result := codex.BenchmarkResult{ + TaskID: "digbench", TaskName: "DIGBENCH P-9", Model: "model", DisplayName: "Model", Effort: "high", + Provider: "digbench", Interactions: interactions, + } + model := Model{snapshot: codex.DemoSnapshot(), width: 120, height: 36, meterView: viewBenchmark} + model.openBenchmarkDetail(result) + layout := model.dashboardLayout() + colors := paletteFor(model.theme) + + b.Run("cached_viewport", func(b *testing.B) { + b.ReportAllocs() + for index := 0; index < b.N; index++ { + model.benchmarkDetailScroll = index % max(model.benchmarkDetailMaximumScroll(), 1) + if output := model.renderBenchmarkDetail(layout.contentWidth, layout.meterHeight, colors); output == "" { + b.Fatal("empty detail") + } + } + }) + b.Run("complete_format_baseline", func(b *testing.B) { + uncached := model + uncached.benchmarkDetailCache = benchmarkDetailTranscriptCache{} + width := max(layout.contentWidth-4, 1) + b.ReportAllocs() + for range b.N { + if lines := uncached.benchmarkDetailLines(width, colors); len(lines) == 0 { + b.Fatal("empty detail") + } + } + }) +} + func TestBenchmarkDetailOmitsEmptyUsageSource(t *testing.T) { result := codex.BenchmarkResult{ TaskName: "DEMO", Model: "model", DisplayName: "Model", Effort: "low", Correct: true, diff --git a/internal/ui/model.go b/internal/ui/model.go index d14a2a0c..d8885a8a 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -108,6 +108,7 @@ type Model struct { benchmarkDetail *codex.BenchmarkResult benchmarkDetailActive bool benchmarkDetailScroll int + benchmarkDetailCache benchmarkDetailTranscriptCache monitorState monitorState monitorStartedAt time.Time @@ -640,6 +641,7 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { case tea.WindowSizeMsg: m.width = message.Width m.height = message.Height + m.prepareBenchmarkDetailTranscript() case fetchedMsg: m.loading = false m.err = message.err @@ -762,6 +764,7 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { } if m.benchmarkDetailActive && m.benchmarkDetail != nil && benchmarkRunKey(*m.benchmarkDetail) == benchmarkRunKey(active) { m.benchmarkDetail = &active + m.prepareBenchmarkDetailTranscript() } } if event.Result != nil { @@ -774,6 +777,7 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { if m.benchmarkDetailActive && m.benchmarkDetail != nil && benchmarkRunKey(*m.benchmarkDetail) == benchmarkRunKey(result) { m.benchmarkDetail = &result m.benchmarkDetailActive = false + m.prepareBenchmarkDetailTranscript() } m.benchmarkActive = nil m.benchmarkActiveSince = time.Time{} @@ -873,6 +877,7 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { switch button { case footerButtonTheme: m.theme = m.theme.next() + m.prepareBenchmarkDetailTranscript() m.persistPreferences() case footerButtonView: if m.meterView.isQuota() { @@ -1192,6 +1197,7 @@ func (m Model) startBenchmark(tasks []codex.BenchmarkTaskID) (Model, tea.Cmd) { m.benchmarkDetail = nil m.benchmarkDetailActive = false m.benchmarkDetailScroll = 0 + m.benchmarkDetailCache = benchmarkDetailTranscriptCache{} m.benchmarkScopeOpen = false m.benchmarkScopeHover = -1 m.benchmarkState = benchmarkRunning @@ -1358,6 +1364,7 @@ func (m *Model) openBenchmarkDetail(result codex.BenchmarkResult, active ...bool m.benchmarkDetail = &result m.benchmarkDetailActive = len(active) > 0 && active[0] m.benchmarkDetailScroll = 0 + m.prepareBenchmarkDetailTranscript() m.benchmarkRunHovered = false m.benchmarkHoveredRun = "" } @@ -1366,16 +1373,55 @@ func (m *Model) closeBenchmarkDetail() { m.benchmarkDetail = nil m.benchmarkDetailActive = false m.benchmarkDetailScroll = 0 + m.benchmarkDetailCache = benchmarkDetailTranscriptCache{} } func (m *Model) scrollBenchmarkDetail(rows int) { if m.benchmarkDetail == nil { return } + m.prepareBenchmarkDetailTranscript() maximum := m.benchmarkDetailMaximumScroll() m.benchmarkDetailScroll = min(max(m.benchmarkDetailScroll+rows, 0), maximum) } +func (m *Model) prepareBenchmarkDetailTranscript() { + if m.benchmarkDetail == nil { + m.benchmarkDetailCache = benchmarkDetailTranscriptCache{} + return + } + result, ok := m.benchmarkDetailResult() + if !ok { + m.benchmarkDetailCache = benchmarkDetailTranscriptCache{} + return + } + layout := m.dashboardLayout() + width := max(layout.contentWidth-4, 1) + cache := &m.benchmarkDetailCache + run := benchmarkDetailCacheKey(result) + canAppend := cache.valid && cache.run == run && cache.width == width && cache.theme == m.theme && cache.correct == result.Correct && cache.interactionCount <= len(result.Interactions) + if canAppend && cache.interactionCount > 0 && cache.lastInteraction != result.Interactions[cache.interactionCount-1] { + canAppend = false + } + colors := paletteFor(m.theme) + if !canAppend { + cache.lines = buildBenchmarkDetailTranscriptLines(result.Interactions, 0, width, colors, result.Correct) + cache.interactionCount = len(result.Interactions) + } else if cache.interactionCount < len(result.Interactions) { + cache.lines = append(cache.lines, buildBenchmarkDetailTranscriptLines(result.Interactions, cache.interactionCount, width, colors, result.Correct)...) + cache.interactionCount = len(result.Interactions) + } + cache.valid = true + cache.run = run + cache.width = width + cache.theme = m.theme + cache.correct = result.Correct + cache.lastInteraction = codex.BenchmarkInteraction{} + if cache.interactionCount > 0 { + cache.lastInteraction = result.Interactions[cache.interactionCount-1] + } +} + func (m *Model) scrollBenchmarkDetailPage(direction int) { m.scrollBenchmarkDetail(direction * m.benchmarkDetailPageSize()) } From ef2c4805bc1d2fde0acdb11032dc4d64af8aa600 Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 22 Aug 2026 13:19:05 +0100 Subject: [PATCH 09/18] FEAT: add benchmark detail navigation keys --- internal/ui/benchmark_test.go | 15 +++++++++++++++ internal/ui/model.go | 11 +++++++++++ 2 files changed, 26 insertions(+) diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index 391164d1..cebdc12c 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -189,6 +189,21 @@ func TestBenchmarkRowClickOpensScrollableBenchmarkOnlyDetail(t *testing.T) { if model.benchmarkDetailScroll == 0 { t.Fatal("Page Down did not scroll a long benchmark detail") } + updated, _ = model.Update(specialKey(tea.KeyPgUp)) + model = updated.(Model) + if model.benchmarkDetailScroll != 0 { + t.Fatalf("Page Up did not return to the first detail page: scroll=%d", model.benchmarkDetailScroll) + } + updated, _ = model.Update(specialKey(tea.KeyEnd)) + model = updated.(Model) + if want := model.benchmarkDetailMaximumScroll(); want == 0 || model.benchmarkDetailScroll != want { + t.Fatalf("End detail scroll = %d, want %d", model.benchmarkDetailScroll, want) + } + updated, _ = model.Update(specialKey(tea.KeyHome)) + model = updated.(Model) + if model.benchmarkDetailScroll != 0 { + t.Fatalf("Home did not return to the first detail line: scroll=%d", model.benchmarkDetailScroll) + } updated, command = model.Update(tea.MouseClickMsg{X: closeX, Y: closeY, Button: tea.MouseLeft}) model = updated.(Model) if command == nil || model.benchmarkDetail != nil || model.benchmarkSelectedRun != benchmarkRunKey(result) { diff --git a/internal/ui/model.go b/internal/ui/model.go index d8885a8a..af34ce4a 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -522,6 +522,17 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { m.scrollMonitorPage(1) return m, nil } + case "home": + if m.meterView == viewBenchmark && m.benchmarkDetail != nil { + m.benchmarkDetailScroll = 0 + return m, nil + } + case "end": + if m.meterView == viewBenchmark && m.benchmarkDetail != nil { + m.prepareBenchmarkDetailTranscript() + m.benchmarkDetailScroll = m.benchmarkDetailMaximumScroll() + return m, nil + } case "p": if m.meterView == viewMonitor { return m.pressFooterButton(footerButtonMonitorStop) From ca432d43e661d670c02ae4ed501fb6e448012290 Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 22 Aug 2026 13:20:39 +0100 Subject: [PATCH 10/18] FEAT: show live DigBench game progress --- internal/ui/benchmark.go | 6 ++++++ internal/ui/benchmark_test.go | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index f9795d7b..219602ea 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -1319,6 +1319,12 @@ func benchmarkResultValues(result codex.BenchmarkResult, rankings map[string]int outcome := "FAIL" if inProgress { outcome = "IN PROGRESS" + if result.Provider == "digbench" { + game := strings.TrimSpace(strings.TrimPrefix(result.TaskName, "DIGBENCH")) + if game != "" { + outcome = fmt.Sprintf("IN PROGRESS (%s, %d)", game, result.CurrentLevel) + } + } } else if result.Stopped { outcome = "STOPPED" } else if result.Correct { diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index cebdc12c..cb735a0e 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -1126,6 +1126,18 @@ func TestBenchmarkResultValuesDistinguishUnknownFromObservedZero(t *testing.T) { } } +func TestBenchmarkResultValuesShowLiveDigBenchGameAndLevel(t *testing.T) { + result := codex.BenchmarkResult{ + Provider: "digbench", TaskName: "DIGBENCH P-1", CurrentLevel: 4, + } + if got := benchmarkResultValues(result, nil, true)[4]; got != "IN PROGRESS (P-1, 4)" { + t.Fatalf("live DigBench result = %q", got) + } + if got := benchmarkResultValues(result, nil)[4]; got != "LOSS" { + t.Fatalf("completed DigBench result changed to %q", got) + } +} + func TestBenchmarkColumnsRespondToHeadingsValuesAndAvailableWidth(t *testing.T) { results := []codex.BenchmarkResult{{ Model: "gpt-5.6-luna", DisplayName: "GPT-5.6 Luna", Effort: "ultra", TaskName: "SHORTEST PATH", From d219c3654caf6adca0b316f854178f4b84bd71aa Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 22 Aug 2026 13:30:38 +0100 Subject: [PATCH 11/18] FEAT: add Scope frame close control --- internal/ui/benchmark.go | 30 +++++++++++++++++++++++++----- internal/ui/benchmark_test.go | 20 +++++++++++++++++++- internal/ui/model.go | 11 +++++++++-- 3 files changed, 53 insertions(+), 8 deletions(-) diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index 219602ea..b286cee2 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -515,7 +515,15 @@ func (m Model) renderBenchmarkScope(width, height int, colors palette) string { title += fmt.Sprintf(" // %d/%d GAMES", len(m.benchmarkScope.Games), len(m.benchmarkPlan.Games)) } title += " // SPACE TOGGLE // ESC DONE" - return frameSized(width, bodyHeight, ansi.Truncate(title, max(innerWidth-4, 1), ""), strings.Join(lines, "\n"), colors.primary, colors) + return frameSizedWithTitleAction( + width, + bodyHeight, + ansi.Truncate(title, max(innerWidth-4, 1), ""), + m.renderBenchmarkDetailControl(benchmarkDetailCloseLabel, footerButtonBenchmarkClose, colors), + strings.Join(lines, "\n"), + colors.primary, + colors, + ) } func (m Model) renderBenchmarkScopeItem(item benchmarkScopeItem, index, width int, colors palette, selectedEfforts map[string]bool) string { @@ -1685,6 +1693,9 @@ func (m Model) benchmarkButtonAt(x, y int) footerButtonID { return footerButtonNone } if m.benchmarkScopeOpen { + if m.benchmarkCloseButtonAt(x, y) { + return footerButtonBenchmarkClose + } return footerButtonNone } if m.benchmarkDetail != nil { @@ -1714,12 +1725,10 @@ func (m Model) benchmarkDetailButtonAt(x, y int) footerButtonID { return footerButtonNone } dashboard := m.dashboardLayout() - localX := x - 2 - closeWidth := lipgloss.Width(benchmarkDetailCloseLabel) - closeStart := dashboard.contentWidth - closeWidth - 2 - if dashboard.contentWidth >= closeWidth+8 && y == dashboard.meterY && localX >= closeStart && localX < closeStart+closeWidth { + if m.benchmarkCloseButtonAt(x, y) { return footerButtonBenchmarkClose } + localX := x - 2 copyWidth := lipgloss.Width(benchmarkDetailCopyLabel) copyStart := dashboard.contentWidth - copyWidth - 2 if dashboard.contentWidth >= copyWidth+4 && y == dashboard.meterY+dashboard.meterHeight-1 && localX >= copyStart && localX < copyStart+copyWidth { @@ -1728,6 +1737,17 @@ func (m Model) benchmarkDetailButtonAt(x, y int) footerButtonID { return footerButtonNone } +func (m Model) benchmarkCloseButtonAt(x, y int) bool { + if m.meterView != viewBenchmark || (!m.benchmarkScopeOpen && m.benchmarkDetail == nil) || x < 0 || y < 0 { + return false + } + dashboard := m.dashboardLayout() + labelWidth := lipgloss.Width(benchmarkDetailCloseLabel) + localX := x - 2 + start := dashboard.contentWidth - labelWidth - 2 + return dashboard.contentWidth >= labelWidth+8 && y == dashboard.meterY && localX >= start && localX < start+labelWidth +} + func benchmarkSegmentButtonAt(localX int, segments []benchmarkControlSegment) footerButtonID { segmentX := 2 for _, segment := range segments { diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index cb735a0e..d714e8ce 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -677,11 +677,29 @@ func TestBenchmarkScopeScreenSelectsModelsAndEffortsForRun(t *testing.T) { t.Fatal("Scope hotkey did not open the all-selected scope screen") } screen := ansi.Strip(model.renderBenchmarkArea(96, 19, paletteFor(themeHacker))) - for _, want := range []string{"BENCHMARK SCOPE", "(D) DONE", "[x] MODELS // CLEAR ALL", "Model A", "Model B", "[x] REASONING LEVELS // CLEAR ALL", "LOW", "HIGH"} { + for _, want := range []string{"BENCHMARK SCOPE", benchmarkDetailCloseLabel, "(D) DONE", "[x] MODELS // CLEAR ALL", "Model A", "Model B", "[x] REASONING LEVELS // CLEAR ALL", "LOW", "HIGH"} { if !strings.Contains(screen, want) { t.Fatalf("scope screen missing %q:\n%s", want, screen) } } + closeX, closeY := renderedTextStart(t, model, benchmarkDetailCloseLabel) + if closeY != model.dashboardLayout().meterY { + t.Fatalf("Scope Close y = %d, want top frame y = %d", closeY, model.dashboardLayout().meterY) + } + updated, command = model.Update(tea.MouseClickMsg{X: closeX, Y: closeY, Button: tea.MouseLeft}) + model = updated.(Model) + if command == nil || model.benchmarkScopeOpen { + t.Fatal("Scope Close control did not return to Benchmark") + } + updated, _ = model.Update(key('s')) + model = updated.(Model) + updated, command = model.Update(key('x')) + model = updated.(Model) + if command == nil || model.benchmarkScopeOpen { + t.Fatal("X did not close Scope") + } + updated, _ = model.Update(key('s')) + model = updated.(Model) clickScopeItem := func(index int) { t.Helper() diff --git a/internal/ui/model.go b/internal/ui/model.go index af34ce4a..43ee752e 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -405,6 +405,9 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { } case "x": if m.meterView == viewBenchmark { + if m.benchmarkScopeOpen { + return m.pressFooterButton(footerButtonBenchmarkClose) + } if m.benchmarkDetail != nil { return m.pressFooterButton(footerButtonBenchmarkClose) } @@ -987,8 +990,12 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { return m, tea.SetClipboard(m.benchmarkDetailClipboardText()) } case footerButtonBenchmarkClose: - if m.meterView == viewBenchmark && m.benchmarkDetail != nil { - m.closeBenchmarkDetail() + if m.meterView == viewBenchmark { + if m.benchmarkScopeOpen { + m.closeBenchmarkScope() + } else if m.benchmarkDetail != nil { + m.closeBenchmarkDetail() + } } case footerButtonBenchmarkScope: if m.meterView == viewBenchmark && !m.benchmarkRunActive() && len(m.benchmarkPlan.Models) > 0 { From e1704d8d56392f0917d7c0a19f18a04563917504 Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 22 Aug 2026 14:03:21 +0100 Subject: [PATCH 12/18] FEAT: add benchmark suite scopes --- README.md | 71 ++++++----- internal/codex/benchmark_tasks.go | 5 +- internal/codex/digbench.go | 85 ++++++------- internal/codex/digbench_test.go | 19 +-- internal/ui/benchmark.go | 151 ++++++++++++++--------- internal/ui/benchmark_test.go | 198 ++++++++++++++++++++++++------ internal/ui/model.go | 173 +++++++++++++++++++------- 7 files changed, 484 insertions(+), 218 deletions(-) diff --git a/README.md b/README.md index 8ee85001..643d10d6 100644 --- a/README.md +++ b/README.md @@ -349,7 +349,7 @@ codexometer --codex /path/to/codex | `v` | Cycle the active Quota view | | `s` | Start recording (Monitor) or open Benchmark Scope | | `p` | Stop and take a final up-to-date reading (Monitor view only) | -| `b` | Run the selected challenge (Benchmark view only) | +| `b` | Run the selected benchmark scope (Benchmark view only) | | `a` | Arm, then confirm, Run All (Benchmark view only) | | `x` | Stop the active benchmark suite and retain its incomplete trial | | `d` | Close the Benchmark Scope screen | @@ -804,17 +804,19 @@ Neither key is written to preferences or accepted as a command-line argument. ### Experimental DigBench agentic run -Codexometer includes a deliberately narrow integration for +Codexometer includes an experimental integration for [DigBench](https://digbench.ai/), an external benchmark of discovering unknown rules in interactive text games. Supplying `DIGBENCH_API_TOKEN` adds -**DIGBENCH** to the Benchmark tab's task selector. At launch, Codexometer calls +**DIGBENCH** to the Benchmark tab's **Suite** selector alongside +**CODEXOMETER CORE**. At launch, Codexometer calls authenticated `GET /games` and uses every game name returned by DigBench; no -`P-x` catalog is compiled into Codexometer. Select DigBench, open **Scope**, and -use its additional game-checkbox group to check all, clear all, or choose any -subset. DigBench also requires exactly one compatible model/reasoning-effort -pair. **Run Selected** displays the exact remote-session count and requires a -second confirmation before running the selected games sequentially. DigBench is -excluded from **Run All** because every game invocation creates a persisted +`P-x` catalog is compiled into Codexometer. Select the DigBench suite, open +**Scope**, and use its game, model, and reasoning-level checkboxes to check all, +clear all, or choose any subset. **Run Scope** executes every selected game +against every selected compatible model/reasoning-effort pair. **Run All** +executes every discovered game against every compatible pair. Both controls +display the exact remote-session count and require a second confirmation before +creating those sessions, because every game/pair invocation creates a persisted remote session with a random seed. Create a token from the [DigBench token page](https://digbench.ai/account/tokens) @@ -882,28 +884,35 @@ fair deterministic cross-model ranking. ### Deterministic benchmark -The Benchmark tab discovers models visible to the active benchmark -authentication and their supported reasoning efforts through `model/list`. -Initially every compatible -model/effort pair is selected. Press `s` or click **Scope** to open a separate -selection screen: every model and reasoning level has its own checkbox, and -each group has a **Check All** control that changes to **Clear All** when the -whole group is selected. The supported reasoning levels shown beside each -model dim immediately when they fall outside the selected scope. Click a row, -or use `Up`/`Down` and `Space`/`Enter`, then click **Done** or press `d`/`Esc` -to return. Unsupported model/effort intersections are never counted or run. - -Select any challenge with the arrow buttons; the selector reserves a stable -responsive track for the longest name, so its controls do not move as the -selection changes. Press `b` or click **Run Selected** to run that challenge -against the selected scope. **Run All** runs the complete challenge catalog -against that same scope. Because that means `challenge count × selected -model/effort pair count` model turns, Codexometer displays the exact total and -requires a second confirmation within five seconds. A fresh, ephemeral, -read-only app-server thread is used for each trial, so benchmark history does -not clutter normal Codex sessions. The turns still consume the same account -quota shown by Codexometer unless a benchmark API key is supplied; with a key, -they use standard usage-based API billing instead. +The Benchmark tab groups its built-in deterministic challenges under the +**CODEXOMETER CORE** suite. Use the **Suite** arrows to switch to another +available source such as **DIGBENCH**; external suites are hidden when their +credentials or launch-time catalog are unavailable. The selector reserves a +stable responsive track for the longest suite name, so its controls do not move +as the selection changes. + +Codexometer discovers models visible to the active benchmark authentication and +their supported reasoning efforts through `model/list`. Initially every Core +benchmark and every compatible model/effort pair is selected. Press `s` or +click **Scope** to open a separate selection screen: every Core benchmark, +model, and reasoning level has its own checkbox, and each group has a **Check +All** control that changes to **Clear All** when the whole group is selected. +The supported reasoning levels shown beside each model dim immediately when +they fall outside the selected scope. Click a row, or use `Up`/`Down` and +`Space`/`Enter`, then click **Done** or press `d`/`Esc` to return. Unsupported +model/effort intersections are never counted or run. + +Press `b` or click **Run Scope** to execute each selected benchmark against +every selected compatible model/effort pair. The button is enabled whenever +that scope contains at least one benchmark and one compatible pair, and its +label shows the resulting turn count. **Run All** deliberately ignores the +scope and executes every benchmark in the active suite against every compatible +model/effort pair. Codexometer displays that exact total and requires a second +confirmation within five seconds. A fresh, ephemeral, read-only app-server +thread is used for each Core trial, so benchmark history does not clutter normal +Codex sessions. The turns still consume the same account quota shown by +Codexometer unless a benchmark API key is supplied; with a key, they use +standard usage-based API billing instead. Each model/effort trial has a five-minute deadline. If an in-flight turn reaches that deadline, Codexometer requests `turn/interrupt`, waits for the matching diff --git a/internal/codex/benchmark_tasks.go b/internal/codex/benchmark_tasks.go index be102224..99960555 100644 --- a/internal/codex/benchmark_tasks.go +++ b/internal/codex/benchmark_tasks.go @@ -122,9 +122,8 @@ func BenchmarkTasks() []BenchmarkTask { return tasks } -// DigBenchTask returns the deliberately narrow external game exposed by the -// current integration. It is omitted from Run All because every invocation -// creates a persisted remote session with a random seed. +// DigBenchTask returns the external suite entry exposed when games are +// available from the DigBench API. func DigBenchTask() BenchmarkTask { return BenchmarkTask{ID: BenchmarkDigBench, Name: "DIGBENCH", External: true} } diff --git a/internal/codex/digbench.go b/internal/codex/digbench.go index e79ea7df..17b9a0dd 100644 --- a/internal/codex/digbench.go +++ b/internal/codex/digbench.go @@ -94,8 +94,8 @@ var runDigBenchTrial = func(ctx context.Context, client Client, service digBench return client.RunDigBench(ctx, service, options) } -// BenchmarkTasks exposes the external proof-of-concept only when this process -// received a DigBench token. Run All continues to use deterministic tasks only. +// BenchmarkTasks exposes the external suite only when this process received a +// DigBench token and discovered at least one game. func (c Client) BenchmarkTasks() []BenchmarkTask { tasks := BenchmarkTasks() if strings.TrimSpace(c.DigBenchToken) != "" && len(c.DigBenchGames) > 0 { @@ -130,8 +130,8 @@ func (c Client) runDigBenchBenchmarkSuite(ctx context.Context, taskID BenchmarkT } } } - if len(selected) != 1 { - emit(benchmarkTerminalEvent(ctx, 0, 0, 0, fmt.Errorf("DigBench requires exactly one selected model/effort pair; scope contains %d", len(selected)))) + if len(selected) == 0 { + emit(benchmarkTerminalEvent(ctx, 0, 0, 0, errors.New("selected DigBench scope has no compatible model/effort pairs"))) return } availableGames := stringSet(plan.Games) @@ -145,49 +145,50 @@ func (c Client) runDigBenchBenchmarkSuite(ctx context.Context, taskID BenchmarkT emit(benchmarkTerminalEvent(ctx, 0, 0, 0, errors.New("select at least one DigBench game"))) return } - choice := selected[0] - total, completed := len(games), 0 - emit(BenchmarkEvent{Total: total, Combinations: 1}) + total, completed := len(games)*len(selected), 0 + emit(BenchmarkEvent{Total: total, Combinations: len(selected)}) for _, game := range games { - event := BenchmarkEvent{Total: total, Completed: completed, Combinations: 1, CurrentTaskID: taskID, CurrentTask: "DIGBENCH " + game, CurrentModel: choice.name, CurrentEffort: choice.effort} - pending := BenchmarkResult{ - TaskID: taskID, TaskName: "DIGBENCH " + game, Provider: "digbench", - Model: choice.model, DisplayName: choice.name, ActualModel: choice.model, Effort: choice.effort, - GameStatus: "connecting", - } - event.Active = &pending - emit(event) - result, runErr := runDigBenchTrial(ctx, c, newDigBenchService(c.DigBenchToken), DigBenchOptions{ - Game: game, Model: choice.model, Effort: choice.effort, - Snapshot: func(snapshot DigBenchResult) { - active := benchmarkResultFromDigBench(taskID, snapshot) - event.Active = &active + for _, choice := range selected { + event := BenchmarkEvent{Total: total, Completed: completed, Combinations: len(selected), CurrentTaskID: taskID, CurrentTask: "DIGBENCH " + game, CurrentModel: choice.name, CurrentEffort: choice.effort} + pending := BenchmarkResult{ + TaskID: taskID, TaskName: "DIGBENCH " + game, Provider: "digbench", + Model: choice.model, DisplayName: choice.name, ActualModel: choice.model, Effort: choice.effort, + GameStatus: "connecting", + } + event.Active = &pending + emit(event) + result, runErr := runDigBenchTrial(ctx, c, newDigBenchService(c.DigBenchToken), DigBenchOptions{ + Game: game, Model: choice.model, Effort: choice.effort, + Snapshot: func(snapshot DigBenchResult) { + active := benchmarkResultFromDigBench(taskID, snapshot) + event.Active = &active + emit(event) + }, + }) + if result.Game == "" { + result.Game = game + } + if result.Model == "" { + result.Model, result.DisplayName, result.ActualModel, result.Effort = choice.model, choice.name, choice.model, choice.effort + } + converted := benchmarkResultFromDigBench(taskID, result) + if errors.Is(ctx.Err(), context.Canceled) { + markBenchmarkStopped(&converted) + event.Active, event.Result, event.Stopped = nil, &converted, true emit(event) - }, - }) - if result.Game == "" { - result.Game = game - } - if result.Model == "" { - result.Model, result.DisplayName, result.ActualModel, result.Effort = choice.model, choice.name, choice.model, choice.effort - } - converted := benchmarkResultFromDigBench(taskID, result) - if errors.Is(ctx.Err(), context.Canceled) { - markBenchmarkStopped(&converted) - event.Active, event.Result, event.Stopped = nil, &converted, true + emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: len(selected), Stopped: true, Done: true}) + return + } + completed++ + event.Completed, event.Active, event.Result = completed, nil, &converted emit(event) - emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: 1, Stopped: true, Done: true}) - return - } - completed++ - event.Completed, event.Active, event.Result = completed, nil, &converted - emit(event) - if runErr != nil { - emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: 1, Done: true, Err: runErr}) - return + if runErr != nil { + emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: len(selected), Done: true, Err: runErr}) + return + } } } - emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: 1, Done: true}) + emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: len(selected), Done: true}) } func benchmarkResultFromDigBench(taskID BenchmarkTaskID, result DigBenchResult) BenchmarkResult { diff --git a/internal/codex/digbench_test.go b/internal/codex/digbench_test.go index 757fb67f..c4c13d89 100644 --- a/internal/codex/digbench_test.go +++ b/internal/codex/digbench_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "slices" "strings" "testing" "time" @@ -134,16 +135,19 @@ func TestClientBenchmarkTasksRequireDigBenchToken(t *testing.T) { func TestDigBenchBenchmarkSuiteRunsSelectedDiscoveredGames(t *testing.T) { server, _ := newFakeBenchmarkServer(benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{"data": []any{map[string]any{ "model": "model", "displayName": "Model", - "supportedReasoningEfforts": []any{map[string]string{"reasoningEffort": "high"}}, + "supportedReasoningEfforts": []any{ + map[string]string{"reasoningEffort": "high"}, + map[string]string{"reasoningEffort": "medium"}, + }, }}})}) originalOpen := openBenchmarkAppServer openBenchmarkAppServer = func(context.Context, string, string) (*appServerSession, error) { return server, nil } t.Cleanup(func() { openBenchmarkAppServer = originalOpen }) originalRun := runDigBenchTrial - var games []string + var trials []string runDigBenchTrial = func(_ context.Context, _ Client, _ digBenchService, options DigBenchOptions) (DigBenchResult, error) { - games = append(games, options.Game) + trials = append(trials, options.Game+"/"+options.Effort) result := DigBenchResult{Game: options.Game, Model: options.Model, DisplayName: "Model", ActualModel: options.Model, Effort: options.Effort, Won: true, Status: "completed"} options.Snapshot(result) return result, nil @@ -153,10 +157,11 @@ func TestDigBenchBenchmarkSuiteRunsSelectedDiscoveredGames(t *testing.T) { var events []BenchmarkEvent client := Client{DigBenchToken: "secret", DigBenchGames: []string{"P-1", "P-2", "P-3"}} client.RunBenchmarkSuiteScoped(context.Background(), []BenchmarkTaskID{BenchmarkDigBench}, BenchmarkScope{ - Models: []string{"model"}, Efforts: []string{"high"}, Games: []string{"P-2", "P-3"}, + Models: []string{"model"}, Efforts: []string{"high", "medium"}, Games: []string{"P-2", "P-3"}, }, func(event BenchmarkEvent) { events = append(events, event) }) - if len(games) != 2 || games[0] != "P-2" || games[1] != "P-3" { - t.Fatalf("selected games run = %#v", games) + wantTrials := []string{"P-2/high", "P-2/medium", "P-3/high", "P-3/medium"} + if !slices.Equal(trials, wantTrials) { + t.Fatalf("selected trials run = %#v, want %#v", trials, wantTrials) } results := 0 for _, event := range events { @@ -165,7 +170,7 @@ func TestDigBenchBenchmarkSuiteRunsSelectedDiscoveredGames(t *testing.T) { } } final := events[len(events)-1] - if results != 2 || !final.Done || final.Total != 2 || final.Completed != 2 || final.Err != nil { + if results != 4 || !final.Done || final.Total != 4 || final.Completed != 4 || final.Combinations != 2 || final.Err != nil { t.Fatalf("events = %#v", events) } } diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index b286cee2..7187eb67 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -484,8 +484,23 @@ const ( benchmarkScopeEffort benchmarkScopeAllGames benchmarkScopeGame + benchmarkScopeAllTasks + benchmarkScopeTask ) +type benchmarkSuiteID int + +const ( + benchmarkSuiteCore benchmarkSuiteID = iota + benchmarkSuiteDigBench +) + +type benchmarkSuite struct { + id benchmarkSuiteID + name string + external bool +} + type benchmarkScopeItem struct { kind benchmarkScopeItemKind value string @@ -511,8 +526,10 @@ func (m Model) renderBenchmarkScope(width, height int, colors palette) string { } title := fmt.Sprintf("BENCHMARK SCOPE // %d MODELS // %d EFFORTS // %d PAIRS", len(m.benchmarkScope.Models), len(m.benchmarkScope.Efforts), m.benchmarkCombinations) - if m.benchmarkSelectedTaskExternal() { + if m.benchmarkSelectedSuiteExternal() { title += fmt.Sprintf(" // %d/%d GAMES", len(m.benchmarkScope.Games), len(m.benchmarkPlan.Games)) + } else { + title += fmt.Sprintf(" // %d/%d BENCHMARKS", len(m.benchmarkSelectedCoreTaskIDs()), len(m.benchmarkCoreTasks())) } title += " // SPACE TOGGLE // ESC DONE" return frameSizedWithTitleAction( @@ -559,7 +576,7 @@ func (m Model) renderBenchmarkScopeItem(item benchmarkScopeItem, index, width in if item.selected { style = lipgloss.NewStyle().Foreground(colors.primary) } - if item.kind == benchmarkScopeDone || item.kind == benchmarkScopeAllModels || item.kind == benchmarkScopeAllEfforts || item.kind == benchmarkScopeAllGames { + if item.kind == benchmarkScopeDone || item.kind == benchmarkScopeAllModels || item.kind == benchmarkScopeAllEfforts || item.kind == benchmarkScopeAllGames || item.kind == benchmarkScopeAllTasks { style = style.Bold(true).Foreground(colors.accent) } return style.Render(fitTableCell(label, width)) @@ -595,7 +612,7 @@ func (m Model) benchmarkScopeItems() []benchmarkScopeItem { label: " " + scopeCheckLabel(selected) + " " + strings.ToUpper(effort), }) } - if m.benchmarkSelectedTaskExternal() { + if m.benchmarkSelectedSuiteExternal() { allGames := len(m.benchmarkPlan.Games) > 0 && len(m.benchmarkScope.Games) == len(m.benchmarkPlan.Games) items = append(items, benchmarkScopeItem{ kind: benchmarkScopeAllGames, selected: allGames, @@ -609,6 +626,21 @@ func (m Model) benchmarkScopeItems() []benchmarkScopeItem { label: " " + scopeCheckLabel(selected) + " " + strings.ToUpper(game), }) } + } else { + coreTasks := m.benchmarkCoreTasks() + selectedTaskIDs := benchmarkTaskIDSet(m.benchmarkSelectedCoreTaskIDs()) + allTasks := len(coreTasks) > 0 && len(selectedTaskIDs) == len(coreTasks) + items = append(items, benchmarkScopeItem{ + kind: benchmarkScopeAllTasks, selected: allTasks, + label: scopeCheckLabel(allTasks) + " CORE BENCHMARKS // " + scopeAllAction(allTasks), + }) + for _, task := range coreTasks { + selected := selectedTaskIDs[task.ID] + items = append(items, benchmarkScopeItem{ + kind: benchmarkScopeTask, value: string(task.ID), selected: selected, + label: " " + scopeCheckLabel(selected) + " " + task.Name, + }) + } } return items } @@ -639,6 +671,9 @@ func (m *Model) openBenchmarkScope() { if m.benchmarkRunActive() || len(m.benchmarkPlan.Models) == 0 { return } + if !m.benchmarkScopeTasksReady { + m.selectAllCoreBenchmarkTasks() + } m.benchmarkScopeOpen = true m.benchmarkScopeHover = -1 m.benchmarkScopeCursor = min(max(m.benchmarkScopeCursor, 0), max(len(m.benchmarkScopeItems())-1, 0)) @@ -708,12 +743,39 @@ func (m *Model) toggleBenchmarkScopeCursor() { } case benchmarkScopeGame: m.benchmarkScope.Games = toggleScopeValue(m.benchmarkScope.Games, item.value) + case benchmarkScopeAllTasks: + if item.selected { + m.benchmarkScopeTasks = nil + } else { + m.selectAllCoreBenchmarkTasks() + } + m.benchmarkScopeTasksReady = true + case benchmarkScopeTask: + m.benchmarkScopeTasks = toggleBenchmarkTaskID(m.benchmarkSelectedCoreTaskIDs(), codex.BenchmarkTaskID(item.value)) + m.benchmarkScopeTasksReady = true } m.benchmarkCombinations = m.benchmarkPlan.CombinationCount(m.benchmarkScope) m.benchmarkAllArmed = false m.benchmarkSelectedArmed = false } +func toggleBenchmarkTaskID(values []codex.BenchmarkTaskID, value codex.BenchmarkTaskID) []codex.BenchmarkTaskID { + for index, existing := range values { + if existing == value { + return append(append([]codex.BenchmarkTaskID(nil), values[:index]...), values[index+1:]...) + } + } + return append(append([]codex.BenchmarkTaskID(nil), values...), value) +} + +func benchmarkTaskIDSet(values []codex.BenchmarkTaskID) map[codex.BenchmarkTaskID]bool { + set := make(map[codex.BenchmarkTaskID]bool, len(values)) + for _, value := range values { + set[value] = true + } + return set +} + func toggleScopeValue(values []string, value string) []string { for index, existing := range values { if existing == value { @@ -792,57 +854,49 @@ func (m Model) renderBenchmarkSegments(segments []benchmarkControlSegment, width } func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { - tasks := m.benchmarkTasks() - allTasks := m.benchmarkRunAllTasks() - selected := codex.BenchmarkTask{Name: "NO TASKS"} - if len(tasks) > 0 { - selected = tasks[m.benchmarkSelectedTask%len(tasks)] - } + suites := m.benchmarkSuites() + selected := m.benchmarkSelectedSuiteOption() running := m.benchmarkRunActive() selectorMiddleWidth := 0 - for _, task := range tasks { - selectorMiddleWidth = max(selectorMiddleWidth, lipgloss.Width("TASK // "+task.Name)) + for _, suite := range suites { + selectorMiddleWidth = max(selectorMiddleWidth, lipgloss.Width("SUITE // "+suite.name)) } selectorMiddleWidth = min(selectorMiddleWidth, max(width-8, 1)) - selector := []benchmarkControlSegment{{text: ansi.Truncate(selected.Name, width, ""), enabled: true}} + selector := []benchmarkControlSegment{{text: ansi.Truncate(selected.name, width, ""), enabled: true}} if width >= 9 { selector = []benchmarkControlSegment{ - {text: "[◀]", button: footerButtonBenchmarkPrevious, enabled: !running}, - {text: fitTableCell("TASK // "+selected.Name, selectorMiddleWidth), enabled: true}, - {text: "[▶]", button: footerButtonBenchmarkNext, enabled: !running}, + {text: "[◀]", button: footerButtonBenchmarkPrevious, enabled: !running && len(suites) > 1}, + {text: fitTableCell("SUITE // "+selected.name, selectorMiddleWidth), enabled: true}, + {text: "[▶]", button: footerButtonBenchmarkNext, enabled: !running && len(suites) > 1}, } } - selectedLabel := "[ (B) RUN SELECTED ]" - allTurns := m.benchmarkCombinations * len(allTasks) + scopeTurns := m.benchmarkScopeTurnCount() + allTurns := m.benchmarkAllTurnCount() + selectedLabel := fmt.Sprintf("[ (B) RUN SCOPE // %d ]", scopeTurns) allLabel := fmt.Sprintf("[ (A) RUN ALL // %d ]", allTurns) scopeLabel := fmt.Sprintf("[ (S) SCOPE // %d ]", m.benchmarkCombinations) stopLabel := "[ (X) STOP ]" if m.benchmarkPlanning { allLabel = "[ DISCOVERING TURNS… ]" } - if selected.External && m.benchmarkCombinations != 1 { - selectedLabel = "[ SELECT 1 PAIR IN SCOPE ]" - } else if selected.External && len(m.benchmarkScope.Games) == 0 { - selectedLabel = "[ SELECT DIGBENCH GAMES ]" - } else if selected.External { - selectedLabel = fmt.Sprintf("[ (B) RUN DIGBENCH // %d ]", len(m.benchmarkScope.Games)) + if selected.external { + selectedLabel = fmt.Sprintf("[ (B) RUN SCOPE // %d REMOTE ]", scopeTurns) if m.benchmarkSelectedArmed { - selectedLabel = fmt.Sprintf("[ CONFIRM // %d REMOTE SESSIONS ]", len(m.benchmarkScope.Games)) + selectedLabel = fmt.Sprintf("[ CONFIRM // %d REMOTE SESSIONS ]", scopeTurns) } } if m.benchmarkAllArmed { - allLabel = fmt.Sprintf("[ CONFIRM // %d TURNS ]", allTurns) + unit := "TURNS" + if selected.external { + unit = "REMOTE SESSIONS" + } + allLabel = fmt.Sprintf("[ CONFIRM // %d %s ]", allTurns, unit) } if lipgloss.Width(selectedLabel)+lipgloss.Width(allLabel)+1 > width { - selectedLabel = "[B:RUN]" - if selected.External { - selectedLabel = fmt.Sprintf("[B:DIG %d]", len(m.benchmarkScope.Games)) - if m.benchmarkCombinations != 1 || len(m.benchmarkScope.Games) == 0 { - selectedLabel = "[B:SCOPE]" - } else if m.benchmarkSelectedArmed { - selectedLabel = fmt.Sprintf("[B:CONFIRM %d]", len(m.benchmarkScope.Games)) - } + selectedLabel = fmt.Sprintf("[B:SCOPE %d]", scopeTurns) + if selected.external && m.benchmarkSelectedArmed { + selectedLabel = fmt.Sprintf("[B:CONFIRM %d]", scopeTurns) } allLabel = fmt.Sprintf("[A:SUITE %d]", allTurns) if m.benchmarkPlanning { @@ -853,14 +907,9 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { } } if lipgloss.Width(selectedLabel)+lipgloss.Width(allLabel)+1 > width { - selectedLabel = "[RUN]" - if selected.External { - selectedLabel = fmt.Sprintf("[D:%d]", len(m.benchmarkScope.Games)) - if m.benchmarkCombinations != 1 || len(m.benchmarkScope.Games) == 0 { - selectedLabel = "[SCOPE]" - } else if m.benchmarkSelectedArmed { - selectedLabel = fmt.Sprintf("[D:%d?]", len(m.benchmarkScope.Games)) - } + selectedLabel = fmt.Sprintf("[S:%d]", scopeTurns) + if selected.external && m.benchmarkSelectedArmed { + selectedLabel = fmt.Sprintf("[S:%d?]", scopeTurns) } allLabel = fmt.Sprintf("[ALL:%d]", allTurns) if m.benchmarkPlanning { @@ -879,8 +928,8 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { stopLabel = "[STOP]" } primary := []benchmarkControlSegment{ - {text: selectedLabel, button: footerButtonBenchmarkSelected, enabled: m.benchmarkCanRunSelected() && len(tasks) > 0}, - {text: allLabel, button: footerButtonBenchmarkAll, enabled: benchmarkRunAllAvailable(running, m.benchmarkCombinations, len(allTasks))}, + {text: selectedLabel, button: footerButtonBenchmarkSelected, enabled: m.benchmarkCanRunSelected() && len(suites) > 0}, + {text: allLabel, button: footerButtonBenchmarkAll, enabled: benchmarkRunAllAvailable(running, allTurns, len(m.benchmarkAllTasks()))}, } secondary := []benchmarkControlSegment{ {text: scopeLabel, button: footerButtonBenchmarkScope, enabled: !running && len(m.benchmarkPlan.Models) > 0}, @@ -1004,7 +1053,7 @@ func (m Model) renderBenchmarkStatus(width, height int, colors palette) string { } if height >= 5 { boundary := "HERMETIC STARLARK // BOUNDED STEPS PER CASE" - if m.benchmarkSelectedTaskExternal() || strings.HasPrefix(m.benchmarkCurrentTask, "DIGBENCH") { + if m.benchmarkSelectedSuiteExternal() || strings.HasPrefix(m.benchmarkCurrentTask, "DIGBENCH") { boundary = "EXTERNAL DIGBENCH // PERSISTED REMOTE SESSION // RANDOM SEED" } lines = append(lines, colors.dimmed().Render(ansi.Truncate(boundary, max(width-4, 1), ""))) @@ -1013,11 +1062,6 @@ func (m Model) renderBenchmarkStatus(width, height int, colors palette) string { return frameSized(width, max(height-2, 1), "ALGORITHM TRIAL", strings.Join(lines, "\n"), color, colors) } -func (m Model) benchmarkSelectedTaskExternal() bool { - tasks := m.benchmarkTasks() - return len(tasks) > 0 && tasks[m.benchmarkSelectedTask%len(tasks)].External -} - func latestBenchmarkFailure(results []codex.BenchmarkResult) string { for index := len(results) - 1; index >= 0; index-- { if !results[index].Correct && results[index].Failure != "" { @@ -1087,7 +1131,7 @@ func (m Model) renderBenchmarkTable(width, height int, colors palette) string { lines = append(lines, style.Render(row.text)) } if len(visibleResults) == 0 && m.benchmarkActive == nil && len(lines) < bodyHeight { - message := "RUN SELECTED OR RUN ALL TO BEGIN // THIS CONSUMES CODEX QUOTA" + message := "RUN SCOPE OR RUN ALL TO BEGIN // THIS CONSUMES CODEX QUOTA" if m.benchmarkRunActive() { message = "WAITING FOR FIRST RESULT" } else if len(m.benchmarkResults) > 0 { @@ -1192,11 +1236,8 @@ func benchmarkRunKey(result codex.BenchmarkResult) string { if model == "" { model = result.DisplayName } - task := string(result.TaskID) - if task == "" { - task = result.TaskName - } - return strings.ToLower(model) + "\x00" + strings.ToLower(result.Effort) + "\x00" + strings.ToLower(task) + return strings.ToLower(model) + "\x00" + strings.ToLower(result.Effort) + "\x00" + + strings.ToLower(string(result.TaskID)) + "\x00" + strings.ToLower(result.TaskName) } func benchmarkTableColumns(width int, results []codex.BenchmarkResult, activeKeys ...string) []benchmarkColumn { diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index d714e8ce..ff6ec824 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -29,6 +29,15 @@ type benchmarkScopedCaptureFetcher struct { stubFetcher plan codex.BenchmarkPlan scopes chan codex.BenchmarkScope + tasks chan []codex.BenchmarkTaskID +} + +type benchmarkDigBenchCaptureFetcher struct { + benchmarkScopedCaptureFetcher +} + +func (benchmarkDigBenchCaptureFetcher) BenchmarkTasks() []codex.BenchmarkTask { + return append(codex.BenchmarkTasks(), codex.DigBenchTask()) } func (f benchmarkScopedCaptureFetcher) BenchmarkCombinationCount(context.Context) (int, error) { @@ -43,7 +52,10 @@ func (f benchmarkScopedCaptureFetcher) RunBenchmarkSuite(ctx context.Context, ta f.RunBenchmarkSuiteScoped(ctx, tasks, f.plan.AllScope(), emit) } -func (f benchmarkScopedCaptureFetcher) RunBenchmarkSuiteScoped(_ context.Context, _ []codex.BenchmarkTaskID, scope codex.BenchmarkScope, emit func(codex.BenchmarkEvent)) { +func (f benchmarkScopedCaptureFetcher) RunBenchmarkSuiteScoped(_ context.Context, tasks []codex.BenchmarkTaskID, scope codex.BenchmarkScope, emit func(codex.BenchmarkEvent)) { + if f.tasks != nil { + f.tasks <- append([]codex.BenchmarkTaskID(nil), tasks...) + } f.scopes <- scope emit(codex.BenchmarkEvent{Done: true, Combinations: f.plan.CombinationCount(scope)}) } @@ -91,7 +103,7 @@ func TestBenchmarkViewRendersResponsiveResultsTable(t *testing.T) { }, } output := ansi.Strip(model.renderBenchmarkArea(96, 19, paletteFor(themeHacker))) - for _, want := range []string{"(B) RUN SELECTED", "MERGE RANGES", "SHOW //", "HERMETIC STARLARK", "1/2 PASS", "PASS", "FAIL", "4.3K", "~$0.0412", "N/A"} { + for _, want := range []string{"(B) RUN SCOPE", "CODEXOMETER CORE", "MERGE RANGES", "SHOW //", "HERMETIC STARLARK", "1/2 PASS", "PASS", "FAIL", "4.3K", "~$0.0412", "N/A"} { if !strings.Contains(output, want) { t.Fatalf("benchmark view missing %q:\n%s", want, output) } @@ -106,10 +118,10 @@ func TestBenchmarkViewRendersResponsiveResultsTable(t *testing.T) { lines := strings.Split(controls, "\n") selectorLine, runLine := -1, -1 for index, line := range lines { - if strings.Contains(line, "TASK //") { + if strings.Contains(line, "SUITE //") { selectorLine = index } - if strings.Contains(line, "(B) RUN SELECTED") { + if strings.Contains(line, "(B) RUN SCOPE") { runLine = index } } @@ -491,7 +503,7 @@ func TestBenchmarkAreaHonorsEveryAllocatedHeight(t *testing.T) { if geometry.tableHeight < 3 && strings.Contains(output, "RESULT MATRIX") { t.Fatalf("table rendered in an allocation too short for its frame:\n%s", output) } - if height == 4 && !strings.Contains(output, "RUN SELECTED") && !strings.Contains(output, "B:RUN") { + if height == 4 && !strings.Contains(output, "RUN SCOPE") && !strings.Contains(output, "B:SCOPE") { t.Fatalf("compact controls dropped an action before their spacer:\n%s", output) } }) @@ -554,6 +566,7 @@ func TestBenchmarkHotkeyRunsSuiteAndCollectsEvents(t *testing.T) { model.snapshot = codex.DemoSnapshot() model.loading = false model.meterView = viewBenchmark + model.benchmarkCombinations = 2 updated, command := model.Update(key('b')) model = updated.(Model) @@ -595,6 +608,7 @@ func TestBenchmarkButtonSupportsHoverAndClick(t *testing.T) { model.loading = false model.width, model.height = 100, 30 model.meterView = viewBenchmark + model.benchmarkCombinations = 2 x, y := benchmarkControlCoordinates(t, model, footerButtonBenchmarkSelected) mouse := tea.MouseMotionMsg{X: x, Y: y} updated, command := model.Update(mouse) @@ -662,7 +676,8 @@ func TestBenchmarkScopeScreenSelectsModelsAndEffortsForRun(t *testing.T) { Efforts: []string{"low", "high"}, } scopes := make(chan codex.BenchmarkScope, 1) - fetcher := benchmarkScopedCaptureFetcher{stubFetcher: stubFetcher{snapshot: codex.DemoSnapshot()}, plan: plan, scopes: scopes} + taskRuns := make(chan []codex.BenchmarkTaskID, 1) + fetcher := benchmarkScopedCaptureFetcher{stubFetcher: stubFetcher{snapshot: codex.DemoSnapshot()}, plan: plan, scopes: scopes, tasks: taskRuns} model := New(fetcher, time.Minute) model.snapshot = codex.DemoSnapshot() model.loading = false @@ -677,7 +692,7 @@ func TestBenchmarkScopeScreenSelectsModelsAndEffortsForRun(t *testing.T) { t.Fatal("Scope hotkey did not open the all-selected scope screen") } screen := ansi.Strip(model.renderBenchmarkArea(96, 19, paletteFor(themeHacker))) - for _, want := range []string{"BENCHMARK SCOPE", benchmarkDetailCloseLabel, "(D) DONE", "[x] MODELS // CLEAR ALL", "Model A", "Model B", "[x] REASONING LEVELS // CLEAR ALL", "LOW", "HIGH"} { + for _, want := range []string{"BENCHMARK SCOPE", benchmarkDetailCloseLabel, "(D) DONE", "[x] MODELS // CLEAR ALL", "Model A", "Model B", "[x] REASONING LEVELS // CLEAR ALL", "LOW", "HIGH", "[x] CORE BENCHMARKS // CLEAR ALL", "MERGE RANGES", "LRU CACHE"} { if !strings.Contains(screen, want) { t.Fatalf("scope screen missing %q:\n%s", want, screen) } @@ -711,6 +726,9 @@ func TestBenchmarkScopeScreenSelectsModelsAndEffortsForRun(t *testing.T) { if model.benchmarkCombinations != 0 || len(model.benchmarkScope.Models) != 0 || model.benchmarkPlanNeeded() { t.Fatalf("model Clear All did not clear scope: %#v", model.benchmarkScope) } + if model.benchmarkCanRunSelected() { + t.Fatal("Run Scope remained enabled without a compatible model/effort pair") + } clickScopeItem(1) // Check All models. if model.benchmarkCombinations != 3 || len(model.benchmarkScope.Models) != 2 { t.Fatalf("model Check All did not restore scope: %#v", model.benchmarkScope) @@ -739,6 +757,25 @@ func TestBenchmarkScopeScreenSelectsModelsAndEffortsForRun(t *testing.T) { t.Fatalf("reasoning Check All did not restore efforts: %#v", model.benchmarkScope) } clickScopeItem(6) // Keep the final launched scope to low only. + findScopeItem := func(kind benchmarkScopeItemKind, value string) int { + t.Helper() + for index, item := range model.benchmarkScopeItems() { + if item.kind == kind && item.value == value { + return index + } + } + t.Fatalf("scope item kind=%d value=%q not found", kind, value) + return -1 + } + clickScopeItem(findScopeItem(benchmarkScopeAllTasks, "")) // Clear all core benchmarks. + if model.benchmarkCanRunSelected() { + t.Fatal("Run Scope remained enabled without a selected core benchmark") + } + clickScopeItem(findScopeItem(benchmarkScopeTask, string(codex.BenchmarkMergeRanges))) + clickScopeItem(findScopeItem(benchmarkScopeTask, string(codex.BenchmarkLRUCache))) + if got := model.benchmarkScopeTurnCount(); got != 2 { + t.Fatalf("selected core scope turns = %d, want 2", got) + } clickScopeItem(0) if model.benchmarkScopeOpen { @@ -763,6 +800,9 @@ func TestBenchmarkScopeScreenSelectsModelsAndEffortsForRun(t *testing.T) { if len(got.Models) != 1 || got.Models[0] != "model-a" || len(got.Efforts) != 1 || got.Efforts[0] != "low" { t.Fatalf("runner received scope %#v", got) } + if gotTasks := <-taskRuns; !slices.Equal(gotTasks, []codex.BenchmarkTaskID{codex.BenchmarkMergeRanges, codex.BenchmarkLRUCache}) { + t.Fatalf("runner received core tasks %#v", gotTasks) + } } func TestBenchmarkScopeAreaHonorsAllocatedSize(t *testing.T) { @@ -782,26 +822,25 @@ func TestBenchmarkScopeAreaHonorsAllocatedSize(t *testing.T) { } } -func TestDigBenchTaskRequiresOnePairAndIsExcludedFromRunAll(t *testing.T) { +func TestDigBenchSuiteSupportsScopedAndAllCombinations(t *testing.T) { client := codex.Client{DigBenchToken: "secret", DigBenchGames: []string{"P-1", "P-2"}} model := Model{ benchmarkRunner: client, benchmarkScopedRunner: client, benchmarkCombinations: 2, - benchmarkPlan: codex.BenchmarkPlan{Games: []string{"P-1", "P-2"}}, - benchmarkScope: codex.BenchmarkScope{Games: []string{"P-1", "P-2"}}, + benchmarkPlan: codex.BenchmarkPlan{ + Models: []codex.BenchmarkModelOption{{Model: "model", Efforts: []string{"low", "high"}}}, + Efforts: []string{"low", "high"}, Games: []string{"P-1", "P-2"}, + }, + benchmarkScope: codex.BenchmarkScope{Models: []string{"model"}, Efforts: []string{"low", "high"}, Games: []string{"P-1", "P-2"}}, } - tasks := model.benchmarkTasks() - model.benchmarkSelectedTask = len(tasks) - 1 - if !tasks[model.benchmarkSelectedTask].External || model.benchmarkCanRunSelected() { - t.Fatalf("DigBench should be visible but disabled with two pairs: %#v", tasks) + model.benchmarkSelectedSuite = 1 + if !model.benchmarkSelectedSuiteExternal() || !model.benchmarkCanRunSelected() { + t.Fatalf("DigBench suite should support two scoped pairs: %#v", model.benchmarkSuites()) } - model.benchmarkCombinations = 1 - if !model.benchmarkCanRunSelected() { - t.Fatal("DigBench was not enabled with exactly one selected pair") + if model.benchmarkScopeTurnCount() != 4 || model.benchmarkAllTurnCount() != 4 { + t.Fatalf("DigBench turn counts scope/all = %d/%d", model.benchmarkScopeTurnCount(), model.benchmarkAllTurnCount()) } - for _, task := range model.benchmarkRunAllTasks() { - if task.External { - t.Fatalf("external task included in Run All: %#v", task) - } + if tasks := model.benchmarkAllTasks(); len(tasks) != 1 || tasks[0] != codex.BenchmarkDigBench { + t.Fatalf("DigBench Run All tasks = %#v", tasks) } } @@ -813,7 +852,7 @@ func TestDigBenchScopeFiltersDiscoveredGamesAndConfirmsRemoteSessions(t *testing client := codex.Client{DigBenchToken: "secret", DigBenchGames: plan.Games} model := Model{ benchmarkRunner: client, benchmarkScopedRunner: client, benchmarkPlan: plan, benchmarkScope: plan.AllScope(), - benchmarkCombinations: 1, benchmarkSelectedTask: len(client.BenchmarkTasks()) - 1, meterView: viewBenchmark, + benchmarkCombinations: 1, benchmarkSelectedSuite: 1, meterView: viewBenchmark, } items := model.benchmarkScopeItems() var p2 int @@ -1203,21 +1242,27 @@ func TestBenchmarkColumnsRespondToHeadingsValuesAndAvailableWidth(t *testing.T) } } -func TestBenchmarkTaskSelectorRunAllGuardAndExactTurnCount(t *testing.T) { - model := New(benchmarkStubFetcher{stubFetcher: stubFetcher{snapshot: codex.DemoSnapshot()}}, time.Minute) +func TestBenchmarkSuiteSelectorRunAllGuardAndExactTurnCount(t *testing.T) { + client := codex.Client{DigBenchToken: "secret", DigBenchGames: []string{"P-1", "P-2"}} + model := New(client, time.Minute) model.snapshot = codex.DemoSnapshot() model.loading = false model.width, model.height = 100, 30 model.meterView = viewBenchmark - model.benchmarkCombinations = 33 + model.benchmarkPlan = codex.BenchmarkPlan{ + Models: []codex.BenchmarkModelOption{{Model: "model", Efforts: []string{"low", "high"}}}, + Efforts: []string{"low", "high"}, Games: []string{"P-1", "P-2"}, + } + model.benchmarkScope = model.benchmarkPlan.AllScope() + model.benchmarkCombinations = 2 updated, _ := model.Update(specialKey(tea.KeyRight)) model = updated.(Model) - if model.benchmarkSelectedTask != 1 { - t.Fatalf("right arrow selected task %d, want 1", model.benchmarkSelectedTask) + if model.benchmarkSelectedSuite != 1 { + t.Fatalf("right arrow selected suite %d, want 1", model.benchmarkSelectedSuite) } controls := ansi.Strip(model.renderBenchmarkControls(60, 8, paletteFor(themeHacker))) - if !strings.Contains(controls, "LRU CACHE") || !strings.Contains(controls, "231") { + if !strings.Contains(controls, "DIGBENCH") || !strings.Contains(controls, "4") { t.Fatalf("selector or exact all-turn count missing:\n%s", controls) } @@ -1227,7 +1272,7 @@ func TestBenchmarkTaskSelectorRunAllGuardAndExactTurnCount(t *testing.T) { t.Fatal("first Run All press did not arm confirmation without running") } controls = ansi.Strip(model.renderBenchmarkControls(60, 8, paletteFor(themeHacker))) - if !strings.Contains(controls, "CONFIRM") || !strings.Contains(controls, "231") { + if !strings.Contains(controls, "CONFIRM") || !strings.Contains(controls, "4") { t.Fatalf("confirmation label missing exact turn count:\n%s", controls) } updated, command = model.Update(key('a')) @@ -1237,8 +1282,9 @@ func TestBenchmarkTaskSelectorRunAllGuardAndExactTurnCount(t *testing.T) { } } -func TestBenchmarkSelectorAnchorsButtonsToLongestTaskName(t *testing.T) { - model := Model{} +func TestBenchmarkSelectorAnchorsButtonsToLongestSuiteName(t *testing.T) { + client := codex.Client{DigBenchToken: "secret", DigBenchGames: []string{"P-1"}} + model := Model{benchmarkRunner: client} buttonX := func(segments []benchmarkControlSegment, target footerButtonID) int { x := 0 for _, segment := range segments { @@ -1251,8 +1297,8 @@ func TestBenchmarkSelectorAnchorsButtonsToLongestTaskName(t *testing.T) { } first := model.benchmarkControlLines(60)[0] previousX, nextX := buttonX(first, footerButtonBenchmarkPrevious), buttonX(first, footerButtonBenchmarkNext) - for range model.benchmarkTasks() { - model.selectBenchmarkTask(1) + for range model.benchmarkSuites() { + model.selectBenchmarkSuite(1) selector := model.benchmarkControlLines(60)[0] if got := buttonX(selector, footerButtonBenchmarkPrevious); got != previousX { t.Fatalf("previous button moved from %d to %d", previousX, got) @@ -1262,12 +1308,12 @@ func TestBenchmarkSelectorAnchorsButtonsToLongestTaskName(t *testing.T) { } } - clickable := Model{snapshot: codex.DemoSnapshot(), width: 100, height: 30, meterView: viewBenchmark} + clickable := Model{snapshot: codex.DemoSnapshot(), width: 100, height: 30, meterView: viewBenchmark, benchmarkRunner: client} nextX, nextY := benchmarkControlCoordinates(t, clickable, footerButtonBenchmarkNext) - for range clickable.benchmarkTasks() { - clickable.selectBenchmarkTask(1) + for range clickable.benchmarkSuites() { + clickable.selectBenchmarkSuite(1) if got := clickable.footerButtonAt(nextX, nextY); got != footerButtonBenchmarkNext { - t.Fatalf("anchored next-button coordinate hit %d after selecting task %d", got, clickable.benchmarkSelectedTask) + t.Fatalf("anchored next-button coordinate hit %d after selecting suite %d", got, clickable.benchmarkSelectedSuite) } } } @@ -1303,6 +1349,84 @@ func TestBenchmarkRunAllLaunchesUnifiedCatalog(t *testing.T) { } } +func TestBenchmarkRunAllIgnoresCoreScope(t *testing.T) { + plan := codex.BenchmarkPlan{ + Models: []codex.BenchmarkModelOption{ + {Model: "model-a", Efforts: []string{"low", "high"}}, + {Model: "model-b", Efforts: []string{"high"}}, + }, + Efforts: []string{"low", "high"}, + } + scopes := make(chan codex.BenchmarkScope, 1) + tasks := make(chan []codex.BenchmarkTaskID, 1) + runner := benchmarkScopedCaptureFetcher{plan: plan, scopes: scopes, tasks: tasks} + model := Model{ + benchmarkRunner: runner, benchmarkScopedRunner: runner, meterView: viewBenchmark, + benchmarkPlan: plan, benchmarkScope: codex.BenchmarkScope{ + Models: []string{"model-a"}, Efforts: []string{"low"}, + }, + benchmarkCombinations: 1, benchmarkScopeTasks: []codex.BenchmarkTaskID{codex.BenchmarkLRUCache}, + benchmarkScopeTasksReady: true, + } + + model, _ = model.activateFooterButton(footerButtonBenchmarkAll) + model, command := model.activateFooterButton(footerButtonBenchmarkAll) + if command == nil || model.benchmarkTotal != plan.CombinationCount(plan.AllScope())*len(codex.BenchmarkTasks()) { + t.Fatalf("Run All total = %d", model.benchmarkTotal) + } + _ = command() + if got := <-scopes; !slices.Equal(got.Models, plan.AllScope().Models) || !slices.Equal(got.Efforts, plan.AllScope().Efforts) { + t.Fatalf("Run All scope = %#v, want %#v", got, plan.AllScope()) + } + wantTasks := make([]codex.BenchmarkTaskID, 0, len(codex.BenchmarkTasks())) + for _, task := range codex.BenchmarkTasks() { + wantTasks = append(wantTasks, task.ID) + } + if got := <-tasks; !slices.Equal(got, wantTasks) { + t.Fatalf("Run All tasks = %#v, want %#v", got, wantTasks) + } +} + +func TestDigBenchRunAllUsesEveryGameAndPair(t *testing.T) { + plan := codex.BenchmarkPlan{ + Models: []codex.BenchmarkModelOption{{Model: "model", Efforts: []string{"low", "high"}}}, + Efforts: []string{"low", "high"}, Games: []string{"P-1", "P-2", "P-3"}, + } + scopes := make(chan codex.BenchmarkScope, 1) + tasks := make(chan []codex.BenchmarkTaskID, 1) + base := benchmarkScopedCaptureFetcher{plan: plan, scopes: scopes, tasks: tasks} + runner := benchmarkDigBenchCaptureFetcher{benchmarkScopedCaptureFetcher: base} + model := Model{ + benchmarkRunner: runner, benchmarkScopedRunner: runner, meterView: viewBenchmark, + benchmarkPlan: plan, benchmarkScope: codex.BenchmarkScope{ + Models: []string{"model"}, Efforts: []string{"low"}, Games: []string{"P-2"}, + }, + benchmarkCombinations: 1, benchmarkSelectedSuite: 1, + } + + model, _ = model.activateFooterButton(footerButtonBenchmarkAll) + model, command := model.activateFooterButton(footerButtonBenchmarkAll) + if command == nil || model.benchmarkTotal != 6 { + t.Fatalf("DigBench Run All total = %d, want 6", model.benchmarkTotal) + } + _ = command() + if got := <-scopes; !slices.Equal(got.Models, plan.AllScope().Models) || !slices.Equal(got.Efforts, plan.AllScope().Efforts) || !slices.Equal(got.Games, plan.Games) { + t.Fatalf("DigBench Run All scope = %#v, want %#v", got, plan.AllScope()) + } + if got := <-tasks; !slices.Equal(got, []codex.BenchmarkTaskID{codex.BenchmarkDigBench}) { + t.Fatalf("DigBench Run All tasks = %#v", got) + } +} + +func TestBenchmarkRunKeySeparatesDigBenchGames(t *testing.T) { + base := codex.BenchmarkResult{TaskID: codex.BenchmarkDigBench, Model: "model", Effort: "high"} + p1, p2 := base, base + p1.TaskName, p2.TaskName = "DIGBENCH P-1", "DIGBENCH P-2" + if benchmarkRunKey(p1) == benchmarkRunKey(p2) { + t.Fatal("DigBench games share a result-table run key") + } +} + func TestBenchmarkRunAllAvailabilityRequiresTasksAndCombinations(t *testing.T) { for _, test := range []struct { name string diff --git a/internal/ui/model.go b/internal/ui/model.go index 43ee752e..2b0f61d6 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -87,7 +87,9 @@ type Model struct { benchmarkScopeCursor int benchmarkScopeScroll int benchmarkScopeHover int - benchmarkSelectedTask int + benchmarkSelectedSuite int + benchmarkScopeTasks []codex.BenchmarkTaskID + benchmarkScopeTasksReady bool benchmarkFilter benchmarkResultFilter benchmarkAllArmed bool benchmarkSelectedArmed bool @@ -821,6 +823,7 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { if len(message.plan.Models) > 0 { m.benchmarkPlan = message.plan m.benchmarkScope = message.plan.AllScope() + m.selectAllCoreBenchmarkTasks() } m.benchmarkCombinations = message.combinations } @@ -935,31 +938,33 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { } case footerButtonBenchmarkPrevious: if !m.benchmarkRunActive() { - m.selectBenchmarkTask(-1) + m.selectBenchmarkSuite(-1) } case footerButtonBenchmarkNext: if !m.benchmarkRunActive() { - m.selectBenchmarkTask(1) + m.selectBenchmarkSuite(1) } case footerButtonBenchmarkSelected: if m.meterView == viewBenchmark && m.benchmarkCanRunSelected() { - tasks := m.benchmarkTasks() - if len(tasks) > 0 { - selected := tasks[m.benchmarkSelectedTask%len(tasks)] - if selected.External && !m.benchmarkSelectedArmed { - m.benchmarkSelectedArmed = true - m.benchmarkConfirmSequence++ - sequence := m.benchmarkConfirmSequence - return m, tea.Tick(5*time.Second, func(time.Time) tea.Msg { return benchmarkConfirmExpiredMsg{sequence: sequence} }) - } - m.benchmarkSelectedArmed = false - m.benchmarkAllArmed = false - return m.startBenchmark([]codex.BenchmarkTaskID{tasks[m.benchmarkSelectedTask%len(tasks)].ID}) + tasks := m.benchmarkScopedTasks() + if m.benchmarkSelectedSuiteExternal() && !m.benchmarkSelectedArmed { + m.benchmarkSelectedArmed = true + m.benchmarkConfirmSequence++ + sequence := m.benchmarkConfirmSequence + return m, tea.Tick(5*time.Second, func(time.Time) tea.Msg { return benchmarkConfirmExpiredMsg{sequence: sequence} }) } + m.benchmarkSelectedArmed = false + m.benchmarkAllArmed = false + return m.startBenchmark(tasks, m.benchmarkScope) } case footerButtonBenchmarkAll: - tasks := m.benchmarkRunAllTasks() - if m.meterView == viewBenchmark && benchmarkRunAllAvailable(m.benchmarkRunActive(), m.benchmarkCombinations, len(tasks)) { + tasks := m.benchmarkAllTasks() + allScope := m.benchmarkPlan.AllScope() + allCombinations := m.benchmarkPlan.CombinationCount(allScope) + if m.benchmarkScopedRunner == nil { + allCombinations = m.benchmarkCombinations + } + if m.meterView == viewBenchmark && benchmarkRunAllAvailable(m.benchmarkRunActive(), allCombinations, len(tasks)) { if !m.benchmarkAllArmed { m.benchmarkAllArmed = true m.benchmarkConfirmSequence++ @@ -967,11 +972,7 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { return m, tea.Tick(5*time.Second, func(time.Time) tea.Msg { return benchmarkConfirmExpiredMsg{sequence: sequence} }) } m.benchmarkAllArmed = false - ids := make([]codex.BenchmarkTaskID, 0, len(tasks)) - for _, task := range tasks { - ids = append(ids, task.ID) - } - return m.startBenchmark(ids) + return m.startBenchmark(tasks, allScope) } case footerButtonBenchmarkFilterAll: m.setBenchmarkFilter(benchmarkFilterAll) @@ -1172,15 +1173,10 @@ func (m Model) benchmarkRunActive() bool { } func (m Model) benchmarkCanRunSelected() bool { - if m.benchmarkRunActive() || (m.benchmarkScopedRunner != nil && m.benchmarkCombinations == 0) { + if m.benchmarkRunActive() || m.benchmarkCombinations == 0 { return false } - tasks := m.benchmarkTasks() - if len(tasks) == 0 { - return false - } - selected := tasks[m.benchmarkSelectedTask%len(tasks)] - return !selected.External || (m.benchmarkCombinations == 1 && len(m.benchmarkScope.Games) > 0) + return len(m.benchmarkScopedTasks()) > 0 && (!m.benchmarkSelectedSuiteExternal() || len(m.benchmarkScope.Games) > 0) } func (m Model) benchmarkPlanNeeded() bool { @@ -1190,16 +1186,20 @@ func (m Model) benchmarkPlanNeeded() bool { return m.benchmarkCombinations == 0 } -func (m Model) startBenchmark(tasks []codex.BenchmarkTaskID) (Model, tea.Cmd) { +func (m Model) startBenchmark(tasks []codex.BenchmarkTaskID, scope codex.BenchmarkScope) (Model, tea.Cmd) { if m.benchmarkRunner == nil { m.benchmarkState = benchmarkFinished m.benchmarkError = "benchmark runner unavailable" return m, nil } m.benchmarkResults = nil - m.benchmarkTotal = m.benchmarkCombinations * len(tasks) + combinations := m.benchmarkPlan.CombinationCount(scope) + if m.benchmarkScopedRunner == nil { + combinations = m.benchmarkCombinations + } + m.benchmarkTotal = combinations * len(tasks) if len(tasks) == 1 && tasks[0] == codex.BenchmarkDigBench { - m.benchmarkTotal = len(m.benchmarkScope.Games) + m.benchmarkTotal = combinations * len(scope.Games) } m.benchmarkCompleted = 0 m.benchmarkCurrentModel = "" @@ -1225,15 +1225,17 @@ func (m Model) startBenchmark(tasks []codex.BenchmarkTaskID) (Model, tea.Cmd) { m.benchmarkCancel = cancel events := make(chan codex.BenchmarkEvent, 2) m.benchmarkEvents = events - return m, launchBenchmark(ctx, m.benchmarkRunner, tasks, m.benchmarkScope, events) + return m, launchBenchmark(ctx, m.benchmarkRunner, tasks, scope, events) } -func (m *Model) selectBenchmarkTask(direction int) { - tasks := m.benchmarkTasks() - if len(tasks) == 0 { +func (m *Model) selectBenchmarkSuite(direction int) { + suites := m.benchmarkSuites() + if len(suites) == 0 { return } - m.benchmarkSelectedTask = (m.benchmarkSelectedTask + direction + len(tasks)) % len(tasks) + m.benchmarkSelectedSuite = (m.benchmarkSelectedSuite + direction + len(suites)) % len(suites) + m.benchmarkScopeCursor = 0 + m.benchmarkScopeScroll = 0 m.benchmarkAllArmed = false m.benchmarkSelectedArmed = false } @@ -1245,15 +1247,100 @@ func (m Model) benchmarkTasks() []codex.BenchmarkTask { return codex.BenchmarkTasks() } -func (m Model) benchmarkRunAllTasks() []codex.BenchmarkTask { - tasks := m.benchmarkTasks() - selected := make([]codex.BenchmarkTask, 0, len(tasks)) - for _, task := range tasks { +func (m Model) benchmarkCoreTasks() []codex.BenchmarkTask { + var tasks []codex.BenchmarkTask + for _, task := range m.benchmarkTasks() { if !task.External { - selected = append(selected, task) + tasks = append(tasks, task) } } - return selected + return tasks +} + +func (m Model) benchmarkSuites() []benchmarkSuite { + suites := []benchmarkSuite{{id: benchmarkSuiteCore, name: "CODEXOMETER CORE"}} + for _, task := range m.benchmarkTasks() { + if task.ID == codex.BenchmarkDigBench && task.External { + return append(suites, benchmarkSuite{id: benchmarkSuiteDigBench, name: "DIGBENCH", external: true}) + } + } + return suites +} + +func (m Model) benchmarkSelectedSuiteOption() benchmarkSuite { + suites := m.benchmarkSuites() + if len(suites) == 0 { + return benchmarkSuite{name: "NO SUITES"} + } + return suites[m.benchmarkSelectedSuite%len(suites)] +} + +func (m Model) benchmarkSelectedSuiteExternal() bool { + return m.benchmarkSelectedSuiteOption().external +} + +func (m Model) benchmarkSelectedCoreTaskIDs() []codex.BenchmarkTaskID { + if m.benchmarkScopeTasksReady { + return append([]codex.BenchmarkTaskID(nil), m.benchmarkScopeTasks...) + } + ids := make([]codex.BenchmarkTaskID, 0, len(m.benchmarkCoreTasks())) + for _, task := range m.benchmarkCoreTasks() { + ids = append(ids, task.ID) + } + return ids +} + +func (m *Model) selectAllCoreBenchmarkTasks() { + m.benchmarkScopeTasks = nil + for _, task := range m.benchmarkCoreTasks() { + m.benchmarkScopeTasks = append(m.benchmarkScopeTasks, task.ID) + } + m.benchmarkScopeTasksReady = true +} + +func (m Model) benchmarkScopedTasks() []codex.BenchmarkTaskID { + if m.benchmarkSelectedSuiteExternal() { + return []codex.BenchmarkTaskID{codex.BenchmarkDigBench} + } + selected := benchmarkTaskIDSet(m.benchmarkSelectedCoreTaskIDs()) + var tasks []codex.BenchmarkTaskID + for _, task := range m.benchmarkCoreTasks() { + if selected[task.ID] { + tasks = append(tasks, task.ID) + } + } + return tasks +} + +func (m Model) benchmarkAllTasks() []codex.BenchmarkTaskID { + if m.benchmarkSelectedSuiteExternal() { + return []codex.BenchmarkTaskID{codex.BenchmarkDigBench} + } + var tasks []codex.BenchmarkTaskID + for _, task := range m.benchmarkCoreTasks() { + tasks = append(tasks, task.ID) + } + return tasks +} + +func (m Model) benchmarkScopeTurnCount() int { + items := len(m.benchmarkScopedTasks()) + if m.benchmarkSelectedSuiteExternal() { + items = len(m.benchmarkScope.Games) + } + return m.benchmarkCombinations * items +} + +func (m Model) benchmarkAllTurnCount() int { + combinations := m.benchmarkPlan.CombinationCount(m.benchmarkPlan.AllScope()) + if m.benchmarkScopedRunner == nil { + combinations = m.benchmarkCombinations + } + items := len(m.benchmarkAllTasks()) + if m.benchmarkSelectedSuiteExternal() { + items = len(m.benchmarkPlan.Games) + } + return combinations * items } func (m *Model) setBenchmarkFilter(filter benchmarkResultFilter) { From 509ed2789af84941be5558ceb8eebe963dc224a6 Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 22 Aug 2026 14:08:47 +0100 Subject: [PATCH 13/18] FEAT: split built-in benchmark suites --- README.md | 53 +++++++------- internal/codex/benchmark_tasks.go | 24 ++++--- internal/codex/benchmark_test.go | 9 +++ internal/ui/benchmark.go | 33 +++------ internal/ui/benchmark_test.go | 114 +++++++++++++++++++++++++----- internal/ui/model.go | 51 +++++++------ 6 files changed, 192 insertions(+), 92 deletions(-) diff --git a/README.md b/README.md index 643d10d6..d159d639 100644 --- a/README.md +++ b/README.md @@ -807,8 +807,9 @@ Neither key is written to preferences or accepted as a command-line argument. Codexometer includes an experimental integration for [DigBench](https://digbench.ai/), an external benchmark of discovering unknown rules in interactive text games. Supplying `DIGBENCH_API_TOKEN` adds -**DIGBENCH** to the Benchmark tab's **Suite** selector alongside -**CODEXOMETER CORE**. At launch, Codexometer calls +**DIGBENCH** to the Benchmark tab's **Suite** selector alongside the always +available **CODEXOMETER CORE** and **CODEXOMETER EXTENDED** suites. At launch, +Codexometer calls authenticated `GET /games` and uses every game name returned by DigBench; no `P-x` catalog is compiled into Codexometer. Select the DigBench suite, open **Scope**, and use its game, model, and reasoning-level checkboxes to check all, @@ -884,19 +885,23 @@ fair deterministic cross-model ranking. ### Deterministic benchmark -The Benchmark tab groups its built-in deterministic challenges under the -**CODEXOMETER CORE** suite. Use the **Suite** arrows to switch to another -available source such as **DIGBENCH**; external suites are hidden when their -credentials or launch-time catalog are unavailable. The selector reserves a -stable responsive track for the longest suite name, so its controls do not move -as the selection changes. +The Benchmark tab groups its built-in deterministic challenges into two +always-available suites: **CODEXOMETER CORE** contains the original Easy and +Moderate set, while **CODEXOMETER EXTENDED** contains the later Hard set. The +**Suite** arrows therefore always switch between at least two choices. A third +**DIGBENCH** choice appears when its credentials and launch-time catalog are +available. The selector reserves a stable responsive track for the longest +suite name, so its controls do not move as the selection changes. Codexometer discovers models visible to the active benchmark authentication and -their supported reasoning efforts through `model/list`. Initially every Core -benchmark and every compatible model/effort pair is selected. Press `s` or -click **Scope** to open a separate selection screen: every Core benchmark, -model, and reasoning level has its own checkbox, and each group has a **Check -All** control that changes to **Clear All** when the whole group is selected. +their supported reasoning efforts through `model/list`. Initially every +benchmark in each built-in suite and every compatible model/effort pair is +selected. Press `s` or click **Scope** to open a separate selection screen: +every benchmark in the active suite, model, and reasoning level has its own +checkbox, and each group has a **Check All** control that changes to **Clear +All** when the whole group is selected. Core and Extended retain independent +benchmark selections when you switch between them. + The supported reasoning levels shown beside each model dim immediately when they fall outside the selected scope. Click a row, or use `Up`/`Down` and `Space`/`Enter`, then click **Done** or press `d`/`Esc` to return. Unsupported @@ -909,8 +914,8 @@ label shows the resulting turn count. **Run All** deliberately ignores the scope and executes every benchmark in the active suite against every compatible model/effort pair. Codexometer displays that exact total and requires a second confirmation within five seconds. A fresh, ephemeral, read-only app-server -thread is used for each Core trial, so benchmark history does not clutter normal -Codex sessions. The turns still consume the same account quota shown by +thread is used for each built-in trial, so benchmark history does not clutter +normal Codex sessions. The turns still consume the same account quota shown by Codexometer unless a benchmark API key is supplied; with a key, they use standard usage-based API billing instead. @@ -959,15 +964,15 @@ operating system and terminal's normal retention behavior. Every trial asks the model to return one named Starlark function: -| Challenge | Difficulty | Required behavior | Verification set | -| --- | --- | --- | --- | -| **Merge Ranges** | Easy | Sort inclusive integer ranges and merge every overlapping or adjacent pair into a canonical union. It must handle empty input, duplicates, nesting, negatives, and arbitrary order. | 8 hand-written edge cases + 48 reproducibly generated cases | -| **LRU Cache** | Moderate | Process integer `put` and `get` operations, update recency, evict the least-recently-used entry, and return both get results and final entries in most-recently-used order. Capacity zero is valid. | 5 hand-written edge cases + 40 reproducibly generated cases | -| **Expression** | Moderate | Evaluate tokenized non-negative integers with `+`, `-`, `*`, parentheses, normal precedence, and left associativity—without `eval`. | 8 hand-written edge cases + 40 reproducibly generated expressions | -| **Shortest Path** | Moderate | Return the minimum four-direction move count through a rectangular blocked/open grid, or `-1` when no route exists. | 5 hand-written edge cases + 40 reproducibly generated mazes | -| **Dependency Scheduler** | Hard | Find the minimum makespan for a small dependency DAG with job durations and a limited number of identical workers. Correct solutions must reason about precedence, concurrency, and cases where immediately starting every available job is not optimal. | 6 hand-written edge cases + 8 reproducibly generated DAGs | -| **Version Resolver** | Hard | Select one version per package while satisfying inclusive dependency ranges and exact conflicts, then return the lexicographically greatest valid solution. | 5 hand-written edge cases + 12 reproducibly generated catalogs | -| **Event Processor** | Hard | Reorder ledger events by sequence and apply idempotency, transfers, freezes, reversals, failure precedence, and a canonical audit result. | 5 hand-written edge cases + 10 reproducibly generated event streams | +| Suite | Challenge | Difficulty | Required behavior | Verification set | +| --- | --- | --- | --- | --- | +| Core | **Merge Ranges** | Easy | Sort inclusive integer ranges and merge every overlapping or adjacent pair into a canonical union. It must handle empty input, duplicates, nesting, negatives, and arbitrary order. | 8 hand-written edge cases + 48 reproducibly generated cases | +| Core | **LRU Cache** | Moderate | Process integer `put` and `get` operations, update recency, evict the least-recently-used entry, and return both get results and final entries in most-recently-used order. Capacity zero is valid. | 5 hand-written edge cases + 40 reproducibly generated cases | +| Core | **Expression** | Moderate | Evaluate tokenized non-negative integers with `+`, `-`, `*`, parentheses, normal precedence, and left associativity—without `eval`. | 8 hand-written edge cases + 40 reproducibly generated expressions | +| Core | **Shortest Path** | Moderate | Return the minimum four-direction move count through a rectangular blocked/open grid, or `-1` when no route exists. | 5 hand-written edge cases + 40 reproducibly generated mazes | +| Extended | **Dependency Scheduler** | Hard | Find the minimum makespan for a small dependency DAG with job durations and a limited number of identical workers. Correct solutions must reason about precedence, concurrency, and cases where immediately starting every available job is not optimal. | 6 hand-written edge cases + 8 reproducibly generated DAGs | +| Extended | **Version Resolver** | Hard | Select one version per package while satisfying inclusive dependency ranges and exact conflicts, then return the lexicographically greatest valid solution. | 5 hand-written edge cases + 12 reproducibly generated catalogs | +| Extended | **Event Processor** | Hard | Reorder ledger events by sequence and apply idempotency, transfers, freezes, reversals, failure precedence, and a canonical audit result. | 5 hand-written edge cases + 10 reproducibly generated event streams | The difficulty labels are documentation rather than part of the terminal names. Hard challenges deliberately combine more rules or require bounded search, which diff --git a/internal/codex/benchmark_tasks.go b/internal/codex/benchmark_tasks.go index 99960555..08531117 100644 --- a/internal/codex/benchmark_tasks.go +++ b/internal/codex/benchmark_tasks.go @@ -11,6 +11,9 @@ import ( // BenchmarkTaskID is the stable identifier for a deterministic benchmark. type BenchmarkTaskID string +// BenchmarkSuiteID identifies the catalog that owns a benchmark task. +type BenchmarkSuiteID string + const ( BenchmarkMergeRanges BenchmarkTaskID = "merge-ranges" BenchmarkLRUCache BenchmarkTaskID = "lru-cache" @@ -20,12 +23,17 @@ const ( BenchmarkVersionResolver BenchmarkTaskID = "version-resolver" BenchmarkEventProcessor BenchmarkTaskID = "event-processor" BenchmarkDigBench BenchmarkTaskID = "digbench" + + BenchmarkSuiteCore BenchmarkSuiteID = "core" + BenchmarkSuiteExtended BenchmarkSuiteID = "extended" + BenchmarkSuiteDigBench BenchmarkSuiteID = "digbench" ) // BenchmarkTask is the public description used by the terminal selector. type BenchmarkTask struct { ID BenchmarkTaskID Name string + Suite BenchmarkSuiteID External bool } @@ -38,7 +46,7 @@ type benchmarkDefinition struct { var benchmarkTaskDefinitions = []benchmarkDefinition{ { - task: BenchmarkTask{ID: BenchmarkMergeRanges, Name: "MERGE RANGES"}, + task: BenchmarkTask{ID: BenchmarkMergeRanges, Name: "MERGE RANGES", Suite: BenchmarkSuiteCore}, function: "merge_ranges", prompt: `Write Starlark code defining this function: @@ -48,7 +56,7 @@ The input is a list of inclusive integer ranges, each represented by a two-item verify: verifyMergeRanges, }, { - task: BenchmarkTask{ID: BenchmarkLRUCache, Name: "LRU CACHE"}, + task: BenchmarkTask{ID: BenchmarkLRUCache, Name: "LRU CACHE", Suite: BenchmarkSuiteCore}, function: "lru_cache", prompt: `Write Starlark code defining this function: @@ -58,7 +66,7 @@ Simulate a least-recently-used cache. Each operation is ["put", key, value] or [ verify: verifyLRUCache, }, { - task: BenchmarkTask{ID: BenchmarkExpressionParser, Name: "EXPRESSION"}, + task: BenchmarkTask{ID: BenchmarkExpressionParser, Name: "EXPRESSION", Suite: BenchmarkSuiteCore}, function: "evaluate_expression", prompt: `Write Starlark code defining this function: @@ -68,7 +76,7 @@ The input is a valid token list containing non-negative base-10 integer literals verify: verifyExpressionParser, }, { - task: BenchmarkTask{ID: BenchmarkShortestPath, Name: "SHORTEST PATH"}, + task: BenchmarkTask{ID: BenchmarkShortestPath, Name: "SHORTEST PATH", Suite: BenchmarkSuiteCore}, function: "shortest_path", prompt: `Write Starlark code defining this function: @@ -78,7 +86,7 @@ The grid is a non-empty rectangular list of lists containing 0 for open cells an verify: verifyShortestPath, }, { - task: BenchmarkTask{ID: BenchmarkDependencyScheduler, Name: "DEPENDENCY SCHEDULER"}, + task: BenchmarkTask{ID: BenchmarkDependencyScheduler, Name: "DEPENDENCY SCHEDULER", Suite: BenchmarkSuiteExtended}, function: "minimum_schedule_time", prompt: `Write Starlark code defining this function: @@ -88,7 +96,7 @@ There are at most seven jobs and one to three workers. Each job is [duration, de verify: verifyDependencyScheduler, }, { - task: BenchmarkTask{ID: BenchmarkVersionResolver, Name: "VERSION RESOLVER"}, + task: BenchmarkTask{ID: BenchmarkVersionResolver, Name: "VERSION RESOLVER", Suite: BenchmarkSuiteExtended}, function: "resolve_versions", prompt: `Write Starlark code defining this function: @@ -98,7 +106,7 @@ The catalog contains one to five packages, each with two or three version record verify: verifyVersionResolver, }, { - task: BenchmarkTask{ID: BenchmarkEventProcessor, Name: "EVENT PROCESSOR"}, + task: BenchmarkTask{ID: BenchmarkEventProcessor, Name: "EVENT PROCESSOR", Suite: BenchmarkSuiteExtended}, function: "process_ledger", prompt: `Write Starlark code defining this function: @@ -125,7 +133,7 @@ func BenchmarkTasks() []BenchmarkTask { // DigBenchTask returns the external suite entry exposed when games are // available from the DigBench API. func DigBenchTask() BenchmarkTask { - return BenchmarkTask{ID: BenchmarkDigBench, Name: "DIGBENCH", External: true} + return BenchmarkTask{ID: BenchmarkDigBench, Name: "DIGBENCH", Suite: BenchmarkSuiteDigBench, External: true} } func isDigBenchTask(id BenchmarkTaskID) bool { diff --git a/internal/codex/benchmark_test.go b/internal/codex/benchmark_test.go index c5d2fdbc..43d705e7 100644 --- a/internal/codex/benchmark_test.go +++ b/internal/codex/benchmark_test.go @@ -166,6 +166,15 @@ func TestBenchmarkTaskCatalogAndSelection(t *testing.T) { if len(tasks) != 7 || tasks[0].ID != BenchmarkMergeRanges || tasks[3].ID != BenchmarkShortestPath || tasks[6].ID != BenchmarkEventProcessor { t.Fatalf("task catalog = %#v", tasks) } + for index, task := range tasks { + wantSuite := BenchmarkSuiteCore + if index >= 4 { + wantSuite = BenchmarkSuiteExtended + } + if task.Suite != wantSuite { + t.Fatalf("task %s suite = %s, want %s", task.ID, task.Suite, wantSuite) + } + } definitions, err := resolveBenchmarkTasks([]BenchmarkTaskID{BenchmarkShortestPath, BenchmarkLRUCache, BenchmarkLRUCache}) if err != nil || len(definitions) != 2 || definitions[0].task.ID != BenchmarkLRUCache || definitions[1].task.ID != BenchmarkShortestPath { t.Fatalf("resolved tasks = %#v, %v", definitions, err) diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index 7187eb67..74af9762 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -488,15 +488,8 @@ const ( benchmarkScopeTask ) -type benchmarkSuiteID int - -const ( - benchmarkSuiteCore benchmarkSuiteID = iota - benchmarkSuiteDigBench -) - type benchmarkSuite struct { - id benchmarkSuiteID + id codex.BenchmarkSuiteID name string external bool } @@ -529,7 +522,7 @@ func (m Model) renderBenchmarkScope(width, height int, colors palette) string { if m.benchmarkSelectedSuiteExternal() { title += fmt.Sprintf(" // %d/%d GAMES", len(m.benchmarkScope.Games), len(m.benchmarkPlan.Games)) } else { - title += fmt.Sprintf(" // %d/%d BENCHMARKS", len(m.benchmarkSelectedCoreTaskIDs()), len(m.benchmarkCoreTasks())) + title += fmt.Sprintf(" // %d/%d BENCHMARKS", len(m.benchmarkSelectedTaskIDs()), len(m.benchmarkTasksForSuite(m.benchmarkSelectedSuiteOption().id))) } title += " // SPACE TOGGLE // ESC DONE" return frameSizedWithTitleAction( @@ -627,14 +620,15 @@ func (m Model) benchmarkScopeItems() []benchmarkScopeItem { }) } } else { - coreTasks := m.benchmarkCoreTasks() - selectedTaskIDs := benchmarkTaskIDSet(m.benchmarkSelectedCoreTaskIDs()) - allTasks := len(coreTasks) > 0 && len(selectedTaskIDs) == len(coreTasks) + suite := m.benchmarkSelectedSuiteOption() + suiteTasks := m.benchmarkTasksForSuite(suite.id) + selectedTaskIDs := benchmarkTaskIDSet(m.benchmarkSelectedTaskIDs()) + allTasks := len(suiteTasks) > 0 && len(selectedTaskIDs) == len(suiteTasks) items = append(items, benchmarkScopeItem{ kind: benchmarkScopeAllTasks, selected: allTasks, - label: scopeCheckLabel(allTasks) + " CORE BENCHMARKS // " + scopeAllAction(allTasks), + label: scopeCheckLabel(allTasks) + " " + strings.TrimPrefix(suite.name, "CODEXOMETER ") + " BENCHMARKS // " + scopeAllAction(allTasks), }) - for _, task := range coreTasks { + for _, task := range suiteTasks { selected := selectedTaskIDs[task.ID] items = append(items, benchmarkScopeItem{ kind: benchmarkScopeTask, value: string(task.ID), selected: selected, @@ -671,9 +665,6 @@ func (m *Model) openBenchmarkScope() { if m.benchmarkRunActive() || len(m.benchmarkPlan.Models) == 0 { return } - if !m.benchmarkScopeTasksReady { - m.selectAllCoreBenchmarkTasks() - } m.benchmarkScopeOpen = true m.benchmarkScopeHover = -1 m.benchmarkScopeCursor = min(max(m.benchmarkScopeCursor, 0), max(len(m.benchmarkScopeItems())-1, 0)) @@ -745,14 +736,12 @@ func (m *Model) toggleBenchmarkScopeCursor() { m.benchmarkScope.Games = toggleScopeValue(m.benchmarkScope.Games, item.value) case benchmarkScopeAllTasks: if item.selected { - m.benchmarkScopeTasks = nil + m.setBenchmarkSelectedTaskIDs(nil) } else { - m.selectAllCoreBenchmarkTasks() + m.selectAllBenchmarkTasks() } - m.benchmarkScopeTasksReady = true case benchmarkScopeTask: - m.benchmarkScopeTasks = toggleBenchmarkTaskID(m.benchmarkSelectedCoreTaskIDs(), codex.BenchmarkTaskID(item.value)) - m.benchmarkScopeTasksReady = true + m.setBenchmarkSelectedTaskIDs(toggleBenchmarkTaskID(m.benchmarkSelectedTaskIDs(), codex.BenchmarkTaskID(item.value))) } m.benchmarkCombinations = m.benchmarkPlan.CombinationCount(m.benchmarkScope) m.benchmarkAllArmed = false diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index ff6ec824..a9562a6a 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -93,6 +93,16 @@ func (f benchmarkStubFetcher) RunBenchmarkSuite(ctx context.Context, tasks []cod emit(codex.BenchmarkEvent{Total: len(f.results), Completed: len(f.results), Done: true}) } +func benchmarkTaskIDsForSuite(suite codex.BenchmarkSuiteID) []codex.BenchmarkTaskID { + var ids []codex.BenchmarkTaskID + for _, task := range codex.BenchmarkTasks() { + if task.Suite == suite { + ids = append(ids, task.ID) + } + } + return ids +} + func TestBenchmarkViewRendersResponsiveResultsTable(t *testing.T) { model := Model{ width: 100, height: 30, meterView: viewBenchmark, @@ -832,7 +842,7 @@ func TestDigBenchSuiteSupportsScopedAndAllCombinations(t *testing.T) { }, benchmarkScope: codex.BenchmarkScope{Models: []string{"model"}, Efforts: []string{"low", "high"}, Games: []string{"P-1", "P-2"}}, } - model.benchmarkSelectedSuite = 1 + model.benchmarkSelectedSuite = 2 if !model.benchmarkSelectedSuiteExternal() || !model.benchmarkCanRunSelected() { t.Fatalf("DigBench suite should support two scoped pairs: %#v", model.benchmarkSuites()) } @@ -844,6 +854,71 @@ func TestDigBenchSuiteSupportsScopedAndAllCombinations(t *testing.T) { } } +func TestBenchmarkSuitesSplitBuiltInCatalogAndConditionallyAddDigBench(t *testing.T) { + plain := Model{benchmarkRunner: codex.Client{}} + suites := plain.benchmarkSuites() + if len(suites) != 2 || suites[0].id != codex.BenchmarkSuiteCore || suites[1].id != codex.BenchmarkSuiteExtended { + t.Fatalf("built-in suites = %#v", suites) + } + if got := benchmarkTaskIDsForSuite(codex.BenchmarkSuiteCore); !slices.Equal(got, []codex.BenchmarkTaskID{ + codex.BenchmarkMergeRanges, codex.BenchmarkLRUCache, codex.BenchmarkExpressionParser, codex.BenchmarkShortestPath, + }) { + t.Fatalf("Core catalog = %#v", got) + } + if got := benchmarkTaskIDsForSuite(codex.BenchmarkSuiteExtended); !slices.Equal(got, []codex.BenchmarkTaskID{ + codex.BenchmarkDependencyScheduler, codex.BenchmarkVersionResolver, codex.BenchmarkEventProcessor, + }) { + t.Fatalf("Extended catalog = %#v", got) + } + selector := plain.benchmarkControlLines(80)[0] + if !selector[0].enabled || !selector[len(selector)-1].enabled { + t.Fatalf("built-in suite selector arrows were not enabled: %#v", selector) + } + + enabled := Model{benchmarkRunner: codex.Client{DigBenchToken: "secret", DigBenchGames: []string{"P-1"}}} + suites = enabled.benchmarkSuites() + if len(suites) != 3 || suites[2].id != codex.BenchmarkSuiteDigBench || !suites[2].external { + t.Fatalf("credentialed suites = %#v", suites) + } +} + +func TestBuiltInSuitesRetainIndependentBenchmarkScopes(t *testing.T) { + model := Model{benchmarkSelectedSuite: 1} + findItem := func(kind benchmarkScopeItemKind, value string) int { + t.Helper() + for index, item := range model.benchmarkScopeItems() { + if item.kind == kind && item.value == value { + return index + } + } + t.Fatalf("scope item kind=%d value=%q not found", kind, value) + return -1 + } + + items := model.benchmarkScopeItems() + if items[findItem(benchmarkScopeAllTasks, "")].label != "[x] EXTENDED BENCHMARKS // CLEAR ALL" { + t.Fatalf("Extended scope heading = %q", items[findItem(benchmarkScopeAllTasks, "")].label) + } + model.benchmarkScopeCursor = findItem(benchmarkScopeAllTasks, "") + model.toggleBenchmarkScopeCursor() + model.benchmarkScopeCursor = findItem(benchmarkScopeTask, string(codex.BenchmarkDependencyScheduler)) + model.toggleBenchmarkScopeCursor() + + model.selectBenchmarkSuite(-1) + model.benchmarkScopeCursor = findItem(benchmarkScopeAllTasks, "") + model.toggleBenchmarkScopeCursor() + model.benchmarkScopeCursor = findItem(benchmarkScopeTask, string(codex.BenchmarkMergeRanges)) + model.toggleBenchmarkScopeCursor() + if got := model.benchmarkSelectedTaskIDs(); !slices.Equal(got, []codex.BenchmarkTaskID{codex.BenchmarkMergeRanges}) { + t.Fatalf("Core scope = %#v", got) + } + + model.selectBenchmarkSuite(1) + if got := model.benchmarkSelectedTaskIDs(); !slices.Equal(got, []codex.BenchmarkTaskID{codex.BenchmarkDependencyScheduler}) { + t.Fatalf("Extended scope was not retained: %#v", got) + } +} + func TestDigBenchScopeFiltersDiscoveredGamesAndConfirmsRemoteSessions(t *testing.T) { plan := codex.BenchmarkPlan{ Models: []codex.BenchmarkModelOption{{Model: "model", DisplayName: "Model", Efforts: []string{"high"}}}, @@ -852,7 +927,7 @@ func TestDigBenchScopeFiltersDiscoveredGamesAndConfirmsRemoteSessions(t *testing client := codex.Client{DigBenchToken: "secret", DigBenchGames: plan.Games} model := Model{ benchmarkRunner: client, benchmarkScopedRunner: client, benchmarkPlan: plan, benchmarkScope: plan.AllScope(), - benchmarkCombinations: 1, benchmarkSelectedSuite: 1, meterView: viewBenchmark, + benchmarkCombinations: 1, benchmarkSelectedSuite: 2, meterView: viewBenchmark, } items := model.benchmarkScopeItems() var p2 int @@ -1262,6 +1337,15 @@ func TestBenchmarkSuiteSelectorRunAllGuardAndExactTurnCount(t *testing.T) { t.Fatalf("right arrow selected suite %d, want 1", model.benchmarkSelectedSuite) } controls := ansi.Strip(model.renderBenchmarkControls(60, 8, paletteFor(themeHacker))) + if !strings.Contains(controls, "CODEXOMETER EXTENDED") || !strings.Contains(controls, "6") { + t.Fatalf("extended selector or exact all-turn count missing:\n%s", controls) + } + updated, _ = model.Update(specialKey(tea.KeyRight)) + model = updated.(Model) + if model.benchmarkSelectedSuite != 2 { + t.Fatalf("second right arrow selected suite %d, want 2", model.benchmarkSelectedSuite) + } + controls = ansi.Strip(model.renderBenchmarkControls(60, 8, paletteFor(themeHacker))) if !strings.Contains(controls, "DIGBENCH") || !strings.Contains(controls, "4") { t.Fatalf("selector or exact all-turn count missing:\n%s", controls) } @@ -1318,7 +1402,7 @@ func TestBenchmarkSelectorAnchorsButtonsToLongestSuiteName(t *testing.T) { } } -func TestBenchmarkRunAllLaunchesUnifiedCatalog(t *testing.T) { +func TestBenchmarkRunAllLaunchesCoreCatalog(t *testing.T) { captured := make(chan []codex.BenchmarkTaskID, 1) fetcher := benchmarkCaptureFetcher{stubFetcher: stubFetcher{snapshot: codex.DemoSnapshot()}, tasks: captured} model := New(fetcher, time.Minute) @@ -1334,11 +1418,7 @@ func TestBenchmarkRunAllLaunchesUnifiedCatalog(t *testing.T) { } _ = command() got := <-captured - wantTasks := codex.BenchmarkTasks() - want := make([]codex.BenchmarkTaskID, 0, len(wantTasks)) - for _, task := range wantTasks { - want = append(want, task.ID) - } + want := benchmarkTaskIDsForSuite(codex.BenchmarkSuiteCore) if len(got) != len(want) { t.Fatalf("launched tasks = %v, want %v", got, want) } @@ -1365,25 +1445,23 @@ func TestBenchmarkRunAllIgnoresCoreScope(t *testing.T) { benchmarkPlan: plan, benchmarkScope: codex.BenchmarkScope{ Models: []string{"model-a"}, Efforts: []string{"low"}, }, - benchmarkCombinations: 1, benchmarkScopeTasks: []codex.BenchmarkTaskID{codex.BenchmarkLRUCache}, - benchmarkScopeTasksReady: true, + benchmarkCombinations: 1, benchmarkScopeTasks: map[codex.BenchmarkSuiteID][]codex.BenchmarkTaskID{ + codex.BenchmarkSuiteCore: {codex.BenchmarkLRUCache}, + }, } model, _ = model.activateFooterButton(footerButtonBenchmarkAll) model, command := model.activateFooterButton(footerButtonBenchmarkAll) - if command == nil || model.benchmarkTotal != plan.CombinationCount(plan.AllScope())*len(codex.BenchmarkTasks()) { + coreTasks := benchmarkTaskIDsForSuite(codex.BenchmarkSuiteCore) + if command == nil || model.benchmarkTotal != plan.CombinationCount(plan.AllScope())*len(coreTasks) { t.Fatalf("Run All total = %d", model.benchmarkTotal) } _ = command() if got := <-scopes; !slices.Equal(got.Models, plan.AllScope().Models) || !slices.Equal(got.Efforts, plan.AllScope().Efforts) { t.Fatalf("Run All scope = %#v, want %#v", got, plan.AllScope()) } - wantTasks := make([]codex.BenchmarkTaskID, 0, len(codex.BenchmarkTasks())) - for _, task := range codex.BenchmarkTasks() { - wantTasks = append(wantTasks, task.ID) - } - if got := <-tasks; !slices.Equal(got, wantTasks) { - t.Fatalf("Run All tasks = %#v, want %#v", got, wantTasks) + if got := <-tasks; !slices.Equal(got, coreTasks) { + t.Fatalf("Run All tasks = %#v, want %#v", got, coreTasks) } } @@ -1401,7 +1479,7 @@ func TestDigBenchRunAllUsesEveryGameAndPair(t *testing.T) { benchmarkPlan: plan, benchmarkScope: codex.BenchmarkScope{ Models: []string{"model"}, Efforts: []string{"low"}, Games: []string{"P-2"}, }, - benchmarkCombinations: 1, benchmarkSelectedSuite: 1, + benchmarkCombinations: 1, benchmarkSelectedSuite: 2, } model, _ = model.activateFooterButton(footerButtonBenchmarkAll) diff --git a/internal/ui/model.go b/internal/ui/model.go index 2b0f61d6..7b9b01e4 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -88,8 +88,7 @@ type Model struct { benchmarkScopeScroll int benchmarkScopeHover int benchmarkSelectedSuite int - benchmarkScopeTasks []codex.BenchmarkTaskID - benchmarkScopeTasksReady bool + benchmarkScopeTasks map[codex.BenchmarkSuiteID][]codex.BenchmarkTaskID benchmarkFilter benchmarkResultFilter benchmarkAllArmed bool benchmarkSelectedArmed bool @@ -823,7 +822,6 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { if len(message.plan.Models) > 0 { m.benchmarkPlan = message.plan m.benchmarkScope = message.plan.AllScope() - m.selectAllCoreBenchmarkTasks() } m.benchmarkCombinations = message.combinations } @@ -1247,10 +1245,10 @@ func (m Model) benchmarkTasks() []codex.BenchmarkTask { return codex.BenchmarkTasks() } -func (m Model) benchmarkCoreTasks() []codex.BenchmarkTask { +func (m Model) benchmarkTasksForSuite(suite codex.BenchmarkSuiteID) []codex.BenchmarkTask { var tasks []codex.BenchmarkTask for _, task := range m.benchmarkTasks() { - if !task.External { + if task.Suite == suite { tasks = append(tasks, task) } } @@ -1258,10 +1256,13 @@ func (m Model) benchmarkCoreTasks() []codex.BenchmarkTask { } func (m Model) benchmarkSuites() []benchmarkSuite { - suites := []benchmarkSuite{{id: benchmarkSuiteCore, name: "CODEXOMETER CORE"}} + suites := []benchmarkSuite{ + {id: codex.BenchmarkSuiteCore, name: "CODEXOMETER CORE"}, + {id: codex.BenchmarkSuiteExtended, name: "CODEXOMETER EXTENDED"}, + } for _, task := range m.benchmarkTasks() { if task.ID == codex.BenchmarkDigBench && task.External { - return append(suites, benchmarkSuite{id: benchmarkSuiteDigBench, name: "DIGBENCH", external: true}) + return append(suites, benchmarkSuite{id: codex.BenchmarkSuiteDigBench, name: "DIGBENCH", external: true}) } } return suites @@ -1279,32 +1280,42 @@ func (m Model) benchmarkSelectedSuiteExternal() bool { return m.benchmarkSelectedSuiteOption().external } -func (m Model) benchmarkSelectedCoreTaskIDs() []codex.BenchmarkTaskID { - if m.benchmarkScopeTasksReady { - return append([]codex.BenchmarkTaskID(nil), m.benchmarkScopeTasks...) +func (m Model) benchmarkSelectedTaskIDs() []codex.BenchmarkTaskID { + suite := m.benchmarkSelectedSuiteOption().id + if tasks, ok := m.benchmarkScopeTasks[suite]; ok { + return append([]codex.BenchmarkTaskID(nil), tasks...) } - ids := make([]codex.BenchmarkTaskID, 0, len(m.benchmarkCoreTasks())) - for _, task := range m.benchmarkCoreTasks() { + ids := make([]codex.BenchmarkTaskID, 0, len(m.benchmarkTasksForSuite(suite))) + for _, task := range m.benchmarkTasksForSuite(suite) { ids = append(ids, task.ID) } return ids } -func (m *Model) selectAllCoreBenchmarkTasks() { - m.benchmarkScopeTasks = nil - for _, task := range m.benchmarkCoreTasks() { - m.benchmarkScopeTasks = append(m.benchmarkScopeTasks, task.ID) +func (m *Model) setBenchmarkSelectedTaskIDs(tasks []codex.BenchmarkTaskID) { + selected := make(map[codex.BenchmarkSuiteID][]codex.BenchmarkTaskID, len(m.benchmarkScopeTasks)+1) + for suite, existing := range m.benchmarkScopeTasks { + selected[suite] = append([]codex.BenchmarkTaskID(nil), existing...) + } + selected[m.benchmarkSelectedSuiteOption().id] = append([]codex.BenchmarkTaskID(nil), tasks...) + m.benchmarkScopeTasks = selected +} + +func (m *Model) selectAllBenchmarkTasks() { + var tasks []codex.BenchmarkTaskID + for _, task := range m.benchmarkTasksForSuite(m.benchmarkSelectedSuiteOption().id) { + tasks = append(tasks, task.ID) } - m.benchmarkScopeTasksReady = true + m.setBenchmarkSelectedTaskIDs(tasks) } func (m Model) benchmarkScopedTasks() []codex.BenchmarkTaskID { if m.benchmarkSelectedSuiteExternal() { return []codex.BenchmarkTaskID{codex.BenchmarkDigBench} } - selected := benchmarkTaskIDSet(m.benchmarkSelectedCoreTaskIDs()) + selected := benchmarkTaskIDSet(m.benchmarkSelectedTaskIDs()) var tasks []codex.BenchmarkTaskID - for _, task := range m.benchmarkCoreTasks() { + for _, task := range m.benchmarkTasksForSuite(m.benchmarkSelectedSuiteOption().id) { if selected[task.ID] { tasks = append(tasks, task.ID) } @@ -1317,7 +1328,7 @@ func (m Model) benchmarkAllTasks() []codex.BenchmarkTaskID { return []codex.BenchmarkTaskID{codex.BenchmarkDigBench} } var tasks []codex.BenchmarkTaskID - for _, task := range m.benchmarkCoreTasks() { + for _, task := range m.benchmarkTasksForSuite(m.benchmarkSelectedSuiteOption().id) { tasks = append(tasks, task.ID) } return tasks From e9430c9386ad6327e3ba6e1739443e57afe951fb Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 22 Aug 2026 14:34:44 +0100 Subject: [PATCH 14/18] FEAT: expand DigBench workflow transcripts --- README.md | 23 +++-- internal/codex/benchmark.go | 15 +-- internal/codex/digbench.go | 160 +++++++++++++++++++++++++++----- internal/codex/digbench_test.go | 77 ++++++++++++++- internal/ui/benchmark.go | 5 + internal/ui/benchmark_test.go | 9 +- 6 files changed, 246 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index d159d639..4c39e3e8 100644 --- a/README.md +++ b/README.md @@ -862,13 +862,18 @@ idempotent `step_index` protocol; session creation is never automatically retried because that endpoint does not document idempotency. In the TUI, each selected game run appears immediately in the existing result -table and can be opened while it is in progress. Its benchmark-only detail view reports -authoritative level, beaten-level, step, and status counters, followed by every -captured move and the sanitized DigBench state returned for that move. The -**Copy** control exports that complete captured view. DigBench session IDs, -credentials, request headers, and Codex reasoning are never included. **Stop** -requests interruption of the active Codex turn, retains the captured moves, and -marks the row stopped. +table and can be opened while it is in progress. Its benchmark-only detail view +shows every Codexometer-authored developer instruction, the complete game prompt +with the session ID redacted, and the dynamic-tool definitions. It then presents +each game exchange as a sanitized **Tool Request** and full **Tool Response**, +followed by the concise **Move** and authoritative **State** representation, so +the solving workflow remains readable without losing protocol detail. The final +model response completes the transcript. The **Copy** control exports that +complete captured view. DigBench session IDs, credentials, request headers, +temporary paths, local scratch-work commands, internal app-server context, Codex +platform instructions, and Codex reasoning are never included. **Stop** requests +interruption of the active Codex turn, retains the captured transcript, and marks +the row stopped. The headless command prints the selected game, model, effort, and billing source before connecting. It then reports remote-session creation, Codex-turn startup, @@ -951,8 +956,8 @@ the visible scroll window. Copy uses the terminal's OSC 52 clipboard support, which is not available in every terminal. This transcript is deliberately benchmark-only. It is populated directly by -the ephemeral thread that Codexometer created for that trial, bounded to 16 -entries of at most 64 KiB each and 128 KiB total, retained only in process +the ephemeral thread that Codexometer created for that trial, bounded to 4,096 +entries of at most 64 KiB each and 1 MiB total, retained only in process memory, and discarded when a new suite starts or Codexometer exits. It does not subscribe to or read ordinary Codex conversations, and it excludes reasoning events, credentials, request headers, and internal app-server IDs. diff --git a/internal/codex/benchmark.go b/internal/codex/benchmark.go index 2da785ff..5425b6b5 100644 --- a/internal/codex/benchmark.go +++ b/internal/codex/benchmark.go @@ -99,12 +99,15 @@ type BenchmarkResponseUsage struct { type BenchmarkInteractionKind string const ( - BenchmarkInteractionPrompt BenchmarkInteractionKind = "prompt" - BenchmarkInteractionResponse BenchmarkInteractionKind = "response" - BenchmarkInteractionPolicy BenchmarkInteractionKind = "policy" - BenchmarkInteractionVerifier BenchmarkInteractionKind = "verifier" - BenchmarkInteractionMove BenchmarkInteractionKind = "move" - BenchmarkInteractionState BenchmarkInteractionKind = "state" + BenchmarkInteractionPrompt BenchmarkInteractionKind = "prompt" + BenchmarkInteractionResponse BenchmarkInteractionKind = "response" + BenchmarkInteractionPolicy BenchmarkInteractionKind = "policy" + BenchmarkInteractionTools BenchmarkInteractionKind = "tools" + BenchmarkInteractionTool BenchmarkInteractionKind = "tool request" + BenchmarkInteractionToolResponse BenchmarkInteractionKind = "tool response" + BenchmarkInteractionVerifier BenchmarkInteractionKind = "verifier" + BenchmarkInteractionMove BenchmarkInteractionKind = "move" + BenchmarkInteractionState BenchmarkInteractionKind = "state" ) // BenchmarkInteraction is content emitted only by a benchmark turn that diff --git a/internal/codex/digbench.go b/internal/codex/digbench.go index 17b9a0dd..bea32624 100644 --- a/internal/codex/digbench.go +++ b/internal/codex/digbench.go @@ -15,6 +15,7 @@ import ( const ( defaultDigBenchTimeout = 30 * time.Minute defaultDigBenchProgressInterval = 15 * time.Second + digBenchDeveloperInstructions = "Play only the assigned DigBench session. Use its scoped tools for game access, keep useful notes in the isolated workspace if needed, and stop calling tools as soon as the game is done." ) // DigBenchProgressPhase identifies a safe, content-free runner milestone. @@ -273,7 +274,7 @@ func (s *appServerSession) runDigBench( "model": combination.model.Model, "cwd": temporary, "approvalPolicy": "never", "sandbox": "workspace-write", "ephemeral": true, "serviceName": "codexometer-digbench", - "developerInstructions": "Play only the assigned DigBench session. Use its scoped tools for game access, keep useful notes in the isolated workspace if needed, and stop calling tools as soon as the game is done.", + "developerInstructions": digBenchDeveloperInstructions, "dynamicTools": digBenchDynamicTools(), } if s.experimentalRawEvents { @@ -311,10 +312,14 @@ func (s *appServerSession) runDigBench( if err != nil { return result, fmt.Errorf("start DigBench game: %w", err) } + assignedSessionID := session.SessionID applyDigBenchSession(&result, session) startedAt := time.Now() - appendDigBenchInteraction(&result, startedAt, BenchmarkInteractionState, formatDigBenchState(session)) + appendDigBenchInteraction(&result, time.Time{}, BenchmarkInteractionPolicy, digBenchDeveloperInstructions) + appendDigBenchInteraction(&result, time.Time{}, BenchmarkInteractionPrompt, digBenchTranscriptPrompt(session)) + appendDigBenchInteraction(&result, time.Time{}, BenchmarkInteractionTools, formatDigBenchTools()) + appendDigBenchInteraction(&result, startedAt, BenchmarkInteractionState, formatDigBenchState(session, assignedSessionID)) publishDigBenchSnapshot(options.Snapshot, result) emitDigBenchProgress(options.Progress, DigBenchProgressSession, result, startedAt) turnParams := map[string]any{ @@ -397,17 +402,20 @@ func (s *appServerSession) runDigBench( if envelope.Method != "item/tool/call" { return result, fmt.Errorf("unsupported Codex app-server request %q", envelope.Method) } - tool, action := digBenchToolSummary(envelope.Params) + tool, action, stepIndex := digBenchToolSummary(envelope.Params) response := handleDigBenchToolCall( runCtx, service, startedThread.Thread.ID, startedTurn.Turn.ID, - session.SessionID, envelope.Params, &session, + assignedSessionID, envelope.Params, &session, ) applyDigBenchSession(&result, session) - if response["success"] == true { + success := response["success"] == true + appendDigBenchInteraction(&result, startedAt, BenchmarkInteractionTool, formatDigBenchToolInteraction(tool, action, stepIndex, assignedSessionID, session.SessionID)) + appendDigBenchInteraction(&result, startedAt, BenchmarkInteractionToolResponse, formatDigBenchToolResponse(response, success, assignedSessionID, session.SessionID)) + if success { if tool == "step" { - appendDigBenchInteraction(&result, startedAt, BenchmarkInteractionMove, action) + appendDigBenchInteraction(&result, startedAt, BenchmarkInteractionMove, redactDigBenchText(action, assignedSessionID, session.SessionID)) } - appendDigBenchInteraction(&result, startedAt, BenchmarkInteractionState, formatDigBenchState(session)) + appendDigBenchInteraction(&result, startedAt, BenchmarkInteractionState, formatDigBenchState(session, assignedSessionID)) emitDigBenchProgress(options.Progress, DigBenchProgressUpdate, result, startedAt) publishDigBenchSnapshot(options.Snapshot, result) } @@ -450,7 +458,7 @@ func (s *appServerSession) runDigBench( case "turn/completed": completed = digBenchTurnCompleted(envelope.Params, startedThread.Thread.ID, startedTurn.Turn.ID, &turnFailure) if completed { - if final := digBenchFinalResponse(envelope.Params, startedThread.Thread.ID, startedTurn.Turn.ID, session.SessionID); final != "" { + if final := digBenchFinalResponse(envelope.Params, startedThread.Thread.ID, startedTurn.Turn.ID, assignedSessionID); final != "" { appendDigBenchInteraction(&result, startedAt, BenchmarkInteractionResponse, final) publishDigBenchSnapshot(options.Snapshot, result) } @@ -489,26 +497,111 @@ func appendDigBenchInteraction(result *DigBenchResult, startedAt time.Time, kind result.Interactions = proxy.Interactions } -func digBenchToolSummary(params json.RawMessage) (tool, action string) { +func digBenchToolSummary(params json.RawMessage) (tool, action string, stepIndex int) { var call struct { Tool string `json:"tool"` Arguments struct { - Action string `json:"action"` + Action string `json:"action"` + StepIndex int `json:"step_index"` } `json:"arguments"` } if json.Unmarshal(params, &call) != nil { - return "", "" + return "", "", 0 + } + return call.Tool, call.Arguments.Action, call.Arguments.StepIndex +} + +func formatDigBenchToolInteraction(tool, action string, stepIndex int, sensitiveValues ...string) string { + action = redactDigBenchText(action, sensitiveValues...) + switch tool { + case "step": + return fmt.Sprintf("STEP // SESSION_ID [REDACTED] // STEP_INDEX %d // ACTION %q", stepIndex, action) + case "get_session": + return "GET_SESSION // SESSION_ID [REDACTED] // AUTHORITATIVE STATE REFRESH" + default: + label := strings.ToUpper(tool) + if label == "" { + label = "UNKNOWN_TOOL" + } + return label + } +} + +func formatDigBenchToolResponse(response map[string]any, success bool, sensitiveValues ...string) string { + status := "REJECTED" + if success { + status = "ACCEPTED" + } + items, ok := response["contentItems"].([]map[string]string) + if !ok || len(items) == 0 { + return status + "\n(response unavailable)" + } + var payload any + if err := json.Unmarshal([]byte(items[0]["text"]), &payload); err != nil { + return status + "\n(response could not be safely decoded)" + } + payload = redactDigBenchTranscriptValue(payload, sensitiveValues...) + encoded, err := json.MarshalIndent(payload, "", " ") + if err != nil { + return status + "\n(response could not be safely encoded)" + } + return status + "\n" + string(encoded) +} + +func redactDigBenchTranscriptValue(value any, sensitiveValues ...string) any { + switch typed := value.(type) { + case map[string]any: + redacted := make(map[string]any, len(typed)) + for key, child := range typed { + normalized := strings.ToLower(strings.NewReplacer("_", "", "-", "").Replace(key)) + switch normalized { + case "sessionid", "threadid", "turnid", "callid", "responseid", "token", "apikey", "authorization": + redacted[key] = "[REDACTED]" + default: + redacted[key] = redactDigBenchTranscriptValue(child, sensitiveValues...) + } + } + return redacted + case []any: + redacted := make([]any, len(typed)) + for index, child := range typed { + redacted[index] = redactDigBenchTranscriptValue(child, sensitiveValues...) + } + return redacted + case string: + return redactDigBenchText(typed, sensitiveValues...) + default: + return value + } +} + +func redactDigBenchJSONValue(value any, sensitiveValues ...string) any { + encoded, err := json.Marshal(value) + if err != nil { + return "(value could not be safely encoded)" + } + var generic any + if err := json.Unmarshal(encoded, &generic); err != nil { + return "(value could not be safely decoded)" } - return call.Tool, call.Arguments.Action + return redactDigBenchTranscriptValue(generic, sensitiveValues...) } -func formatDigBenchState(session digbench.Session) string { - state := struct { - StepIndex int `json:"step_index"` - LevelsBeaten int `json:"levels_beaten"` - State digbench.State `json:"state"` - }{StepIndex: session.StepIndex, LevelsBeaten: session.LevelsBeaten, State: session.State} - encoded, err := json.MarshalIndent(state, "", " ") +func redactDigBenchText(value string, sensitiveValues ...string) string { + for _, sensitive := range sensitiveValues { + if sensitive != "" { + value = strings.ReplaceAll(value, sensitive, "[REDACTED]") + } + } + return value +} + +func formatDigBenchState(session digbench.Session, sensitiveValues ...string) string { + state := map[string]any{ + "step_index": session.StepIndex, "levels_beaten": session.LevelsBeaten, "state": session.State, + } + sensitiveValues = append(sensitiveValues, session.SessionID) + encoded, err := json.MarshalIndent(redactDigBenchJSONValue(state, sensitiveValues...), "", " ") if err != nil { return "DigBench state could not be encoded." } @@ -554,7 +647,27 @@ func digBenchDynamicTools() []map[string]any { } func digBenchPrompt(session digbench.Session) string { - state, _ := json.Marshal(session.State) + return formatDigBenchPrompt(session, session.SessionID, false) +} + +func digBenchTranscriptPrompt(session digbench.Session) string { + return formatDigBenchPrompt(session, "[REDACTED]", true) +} + +func formatDigBenchTools() string { + encoded, err := json.MarshalIndent(digBenchDynamicTools(), "", " ") + if err != nil { + return "DigBench dynamic tool definitions could not be encoded." + } + return string(encoded) +} + +func formatDigBenchPrompt(session digbench.Session, sessionID string, redactState bool) string { + stateValue := any(session.State) + if redactState { + stateValue = redactDigBenchJSONValue(stateValue, session.SessionID) + } + state, _ := json.Marshal(stateValue) return fmt.Sprintf(`We are not going to tell you the rules of this game—you have to figure them out for yourself. The aim is to reach as high a level as possible. You advance by reaching unknown states. Each level has a limited number of steps; exhausting them or reaching certain states can cost a life. Losing all lives ends the game. @@ -568,7 +681,7 @@ Initial state: %s Each move must use exactly one string from the latest state's actions list and the latest returned step_index plus one. Infer the rules from state changes, keep useful notes if helpful, and continue at a deliberate but efficient pace until state.done is true. Then stop making moves and give a concise debrief of the mechanics, objective, strategy, and uncertainties.`, - session.SessionID, session.Game, session.StepIndex, session.StepIndex+1, state) + sessionID, session.Game, session.StepIndex, session.StepIndex+1, state) } func handleDigBenchToolCall( @@ -700,10 +813,7 @@ func digBenchFinalResponse(params json.RawMessage, threadID, turnID, sessionID s } for _, item := range event.Turn.Items { if item.Type == "agentMessage" && strings.TrimSpace(item.Text) != "" { - if sessionID != "" { - return strings.ReplaceAll(item.Text, sessionID, "[digbench-session]") - } - return item.Text + return redactDigBenchText(item.Text, sessionID, threadID, turnID) } } return "" diff --git a/internal/codex/digbench_test.go b/internal/codex/digbench_test.go index c4c13d89..696a4087 100644 --- a/internal/codex/digbench_test.go +++ b/internal/codex/digbench_test.go @@ -108,9 +108,29 @@ func TestRunDigBenchBridgesScopedStepAndDetectsWin(t *testing.T) { if final := progress[2]; final.Level != 3 || final.LevelsBeaten != 3 || final.MaxLevel != 3 || final.Steps != 1 || final.Status != "completed" || final.Elapsed < 0 { t.Fatalf("final progress = %#v", final) } - if len(snapshots) < 3 || len(result.Interactions) != 4 || result.Interactions[1].Kind != BenchmarkInteractionMove || result.Interactions[1].Content != "b" || result.Interactions[2].Kind != BenchmarkInteractionState || result.Interactions[3].Kind != BenchmarkInteractionResponse { + if len(snapshots) < 3 || len(result.Interactions) != 9 || + result.Interactions[0].Kind != BenchmarkInteractionPolicy || + result.Interactions[1].Kind != BenchmarkInteractionPrompt || + result.Interactions[2].Kind != BenchmarkInteractionTools || + result.Interactions[3].Kind != BenchmarkInteractionState || + result.Interactions[4].Kind != BenchmarkInteractionTool || + result.Interactions[5].Kind != BenchmarkInteractionToolResponse || + result.Interactions[6].Kind != BenchmarkInteractionMove || result.Interactions[6].Content != "b" || + result.Interactions[7].Kind != BenchmarkInteractionState || + result.Interactions[8].Kind != BenchmarkInteractionResponse { t.Fatalf("DigBench snapshots/interactions = %d / %#v", len(snapshots), result.Interactions) } + if !strings.Contains(result.Interactions[0].Content, "Play only the assigned DigBench session") || + !strings.Contains(result.Interactions[1].Content, `session_id="[REDACTED]"`) || + !strings.Contains(result.Interactions[1].Content, "Creative mode") || + !strings.Contains(result.Interactions[2].Content, `"get_session"`) || + !strings.Contains(result.Interactions[2].Content, `"inputSchema"`) || + result.Interactions[4].Content != `STEP // SESSION_ID [REDACTED] // STEP_INDEX 1 // ACTION "b"` || + !strings.Contains(result.Interactions[5].Content, "ACCEPTED") || + !strings.Contains(result.Interactions[5].Content, `"session_id": "[REDACTED]"`) || + !strings.Contains(result.Interactions[5].Content, `"framework_version": "engine-1"`) { + t.Fatalf("DigBench authored context = %#v", result.Interactions[:6]) + } for _, interaction := range result.Interactions { if strings.Contains(interaction.Content, "session-1") { t.Fatalf("session id leaked into transcript: %#v", interaction) @@ -124,6 +144,61 @@ func TestRunDigBenchBridgesScopedStepAndDetectsWin(t *testing.T) { } } +func TestDigBenchTranscriptPromptRedactsOnlyRuntimeSessionID(t *testing.T) { + maxLevel := 3 + session := digbench.Session{ + Game: "P-1", SessionID: "session-secret", StepIndex: 4, + State: digbench.State{Status: "in_progress", Level: 2, MaxLevel: &maxLevel, Observation: "session-secret sees ___", Actions: []string{"b", "session-secret-action"}}, + } + runtimePrompt := digBenchPrompt(session) + transcriptPrompt := digBenchTranscriptPrompt(session) + if !strings.Contains(runtimePrompt, `session_id="session-secret"`) { + t.Fatalf("runtime prompt lost assigned session: %q", runtimePrompt) + } + if strings.Contains(transcriptPrompt, "session-secret") || !strings.Contains(transcriptPrompt, `session_id="[REDACTED]"`) { + t.Fatalf("transcript prompt did not safely redact session: %q", transcriptPrompt) + } + for _, shared := range []string{`game="P-1"`, "Starting step_index: 4", "Your first move must use step_index 5"} { + if !strings.Contains(runtimePrompt, shared) || !strings.Contains(transcriptPrompt, shared) { + t.Fatalf("prompt variants do not share %q", shared) + } + } + if !strings.Contains(runtimePrompt, `"observation":"session-secret sees ___"`) || !strings.Contains(transcriptPrompt, `"observation":"[REDACTED] sees ___"`) || !strings.Contains(transcriptPrompt, `"[REDACTED]-action"`) { + t.Fatalf("state strings were not safely represented: %q", transcriptPrompt) + } + state := formatDigBenchState(session) + if strings.Contains(state, "session-secret") || !strings.Contains(state, `"observation": "[REDACTED] sees ___"`) { + t.Fatalf("state transcript leaked session ID: %s", state) + } +} + +func TestDigBenchToolResponseTranscriptRedactsSensitiveIdentifiers(t *testing.T) { + response := digBenchToolResponse(map[string]any{ + "session_id": "session-secret", + "threadId": "thread-secret", + "token": "token-secret", + "state": map[string]any{ + "observation": "session-secret reached the door", + "actions": []any{"left", "right"}, + }, + }, nil) + formatted := formatDigBenchToolResponse(response, true, "session-secret") + for _, secret := range []string{"session-secret", "thread-secret", "token-secret"} { + if strings.Contains(formatted, secret) { + t.Fatalf("tool response leaked %q: %s", secret, formatted) + } + } + for _, visible := range []string{"ACCEPTED", `"session_id": "[REDACTED]"`, `"threadId": "[REDACTED]"`, `"token": "[REDACTED]"`, `"actions"`, `"left"`} { + if !strings.Contains(formatted, visible) { + t.Fatalf("sanitized tool response missing %q: %s", visible, formatted) + } + } + rejected := formatDigBenchToolResponse(digBenchToolResponse(nil, errors.New("session-secret was rejected")), false, "session-secret") + if !strings.Contains(rejected, "REJECTED") || !strings.Contains(rejected, "[REDACTED] was rejected") || strings.Contains(rejected, "session-secret") { + t.Fatalf("rejected tool response was not safely documented: %s", rejected) + } +} + func TestClientBenchmarkTasksRequireDigBenchToken(t *testing.T) { plain := (Client{}).BenchmarkTasks() enabled := (Client{DigBenchToken: "secret", DigBenchGames: []string{"P-1"}}).BenchmarkTasks() diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index 74af9762..dbe4df73 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -235,6 +235,10 @@ func benchmarkDetailHeaderLines(result codex.BenchmarkResult, active bool, width "DIGBENCH // LEVEL %s // BEATEN %d // STEPS %d // STATUS %s", level, result.LevelsBeaten, result.Steps, result.GameStatus, ), width))) + lines = append(lines, colors.dimmed().Render(fitTableCell( + "WORKFLOW // POLICY → PROMPT → TOOLS → TOOL REQUEST/RESPONSE → MOVE → STATE → FINAL RESPONSE", + width, + ))) } usage := "TOKENS // N/A" if result.UsageKnown { @@ -398,6 +402,7 @@ func (m Model) benchmarkDetailClipboardText() string { } fmt.Fprintf(&output, "DIGBENCH: LEVEL %s // BEATEN %d // STEPS %d // STATUS %s\n", level, result.LevelsBeaten, result.Steps, result.GameStatus) + output.WriteString("WORKFLOW: POLICY -> PROMPT -> TOOLS -> TOOL REQUEST/RESPONSE -> MOVE -> STATE -> FINAL RESPONSE\n") } if result.UsageKnown { fmt.Fprintf(&output, "TOKENS: %s\n", benchmarkUsageDetail(result)) diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index a9562a6a..9494642c 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -962,18 +962,23 @@ func TestDigBenchDetailShowsProgressAndTranscript(t *testing.T) { Model: "gpt-5.6-sol", DisplayName: "GPT-5.6 Sol", Effort: "high", Correct: true, CurrentLevel: 14, LevelsBeaten: 14, MaxLevel: 14, Steps: 553, GameStatus: "completed", Interactions: []codex.BenchmarkInteraction{ + {Kind: codex.BenchmarkInteractionPolicy, Content: "Play only the assigned DigBench session."}, + {Kind: codex.BenchmarkInteractionPrompt, Content: `session_id="[REDACTED]"; infer the rules`}, + {Kind: codex.BenchmarkInteractionTools, Content: `[{"name":"step"}]`}, + {Kind: codex.BenchmarkInteractionTool, Content: `STEP // SESSION_ID [REDACTED] // STEP_INDEX 553 // ACTION "move_right"`}, + {Kind: codex.BenchmarkInteractionToolResponse, Content: "ACCEPTED\n{\"session_id\":\"[REDACTED]\"}"}, {Kind: codex.BenchmarkInteractionMove, Content: "move_right"}, {Kind: codex.BenchmarkInteractionState, Content: `{"observation":"WIN"}`}, }, } model := Model{benchmarkDetail: &result} output := ansi.Strip(strings.Join(model.benchmarkDetailLines(100, paletteFor(themeHacker)), "\n")) - for _, want := range []string{"RESULT // WIN", "LEVEL 14/14", "BEATEN 14", "STEPS 553", "MOVE //", "move_right", `"observation":"WIN"`} { + for _, want := range []string{"RESULT // WIN", "LEVEL 14/14", "BEATEN 14", "STEPS 553", "WORKFLOW //", "POLICY //", "PROMPT //", "TOOLS //", "TOOL REQUEST //", "TOOL RESPONSE //", "[REDACTED]", "MOVE //", "move_right", `"observation":"WIN"`} { if !strings.Contains(output, want) { t.Fatalf("DigBench detail missing %q:\n%s", want, output) } } - if copied := model.benchmarkDetailClipboardText(); !strings.Contains(copied, "RESULT: WIN") || !strings.Contains(copied, "DIGBENCH: LEVEL 14/14") { + if copied := model.benchmarkDetailClipboardText(); !strings.Contains(copied, "RESULT: WIN") || !strings.Contains(copied, "DIGBENCH: LEVEL 14/14") || !strings.Contains(copied, "WORKFLOW: POLICY -> PROMPT") || !strings.Contains(copied, "[PROMPT +0.0s]") || !strings.Contains(copied, "[TOOLS +0.0s]") { t.Fatalf("DigBench clipboard text missing progress:\n%s", copied) } } From 614fd3a6dc314ac486d565f39d7cd9bf9b468b33 Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 22 Aug 2026 14:40:53 +0100 Subject: [PATCH 15/18] DOCS: align benchmark workflow guide --- README.md | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 4c39e3e8..8947cb3d 100644 --- a/README.md +++ b/README.md @@ -320,10 +320,12 @@ state—not the contents—of Codex's per-thread writer lock. Message text—inc the final response carried beside timing metadata—reasoning, commands, tool results, and credentials are ignored and never retained from ordinary Codex sessions. The sole content-reading exception is a benchmark turn explicitly -started by Codexometer: its known prompt and visible structured response are -kept in bounded process memory for the Benchmark run detail view. Reasoning -events, credentials, request headers, and internal thread, turn, or response -IDs are not captured. +started by Codexometer. Its Codexometer-authored policy and prompt, visible +structured response, and—only for DigBench—sanitized game-tool requests and +responses are kept in bounded process memory for the Benchmark run detail view. +Reasoning events, platform instructions, credentials, request headers, +temporary paths, local scratch-work commands, and internal thread, turn, call, +or response IDs are not captured. When the managed shared daemon is available, Codexometer also keeps a local app-server subscription for already-loaded thread IDs. From that stream it @@ -353,7 +355,7 @@ codexometer --codex /path/to/codex | `a` | Arm, then confirm, Run All (Benchmark view only) | | `x` | Stop the active benchmark suite and retain its incomplete trial | | `d` | Close the Benchmark Scope screen | -| `[` / `]`, `Left` / `Right` | Select the previous or next challenge | +| `[` / `]`, `Left` / `Right` | Select the previous or next benchmark suite | | `f` | Show all, passed, or failed benchmark results | | `w` | Cycle Cost, Balanced, and Speed benchmark ranking weights | | `Up` / `Down` | Select a Benchmark row, or scroll its open detail | @@ -613,10 +615,11 @@ The other top-level views are: When the terminal cannot fit every root, use Page Up, Page Down, or the mouse wheel to page through the rows. Stop performs an immediate final local read instead of relying on the latest graph sample. -- **Benchmark** — runs a selected hermetic coding challenge, or the complete - challenge catalog, against every visible model and each reasoning effort - that model advertises. Results arrive sequentially in a ranked table with - task, pass/fail, wall time, tokens, and estimated standard API-equivalent cost. +- **Benchmark** — runs the selected scope from the active Core, Extended, or + conditional DigBench suite, or the active suite's complete catalog, against + the selected or complete set of compatible model/reasoning-effort pairs. + Results arrive sequentially in a ranked table with task, outcome, wall time, + tokens, and estimated standard API-equivalent cost. Filter the table to all, passed, or failed trials. Scroll a long result matrix with Page Up, Page Down, or the mouse wheel. Click any column-heading button to sort by that field; click it again to reverse the order. @@ -868,8 +871,10 @@ with the session ID redacted, and the dynamic-tool definitions. It then presents each game exchange as a sanitized **Tool Request** and full **Tool Response**, followed by the concise **Move** and authoritative **State** representation, so the solving workflow remains readable without losing protocol detail. The final -model response completes the transcript. The **Copy** control exports that -complete captured view. DigBench session IDs, credentials, request headers, +model response completes the visible +`Policy → Prompt → Tools → Tool Request → Tool Response → Move → State → Final Response` +workflow. The **Copy** control exports that complete captured view. DigBench +session IDs, credentials, request headers, temporary paths, local scratch-work commands, internal app-server context, Codex platform instructions, and Codex reasoning are never included. **Stop** requests interruption of the active Codex turn, retains the captured transcript, and marks From 412c63eb06f6ec6f27fa7d422190d89f84df5fd0 Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 22 Aug 2026 14:48:08 +0100 Subject: [PATCH 16/18] FIX: preserve DigBench live run identity --- internal/codex/digbench.go | 37 ++++++++++++++++++++++++++------- internal/codex/digbench_test.go | 27 ++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 8 deletions(-) diff --git a/internal/codex/digbench.go b/internal/codex/digbench.go index bea32624..d342dc3c 100644 --- a/internal/codex/digbench.go +++ b/internal/codex/digbench.go @@ -161,17 +161,13 @@ func (c Client) runDigBenchBenchmarkSuite(ctx context.Context, taskID BenchmarkT result, runErr := runDigBenchTrial(ctx, c, newDigBenchService(c.DigBenchToken), DigBenchOptions{ Game: game, Model: choice.model, Effort: choice.effort, Snapshot: func(snapshot DigBenchResult) { + fillDigBenchIdentity(&snapshot, game, choice.model, choice.name, choice.effort) active := benchmarkResultFromDigBench(taskID, snapshot) event.Active = &active emit(event) }, }) - if result.Game == "" { - result.Game = game - } - if result.Model == "" { - result.Model, result.DisplayName, result.ActualModel, result.Effort = choice.model, choice.name, choice.model, choice.effort - } + fillDigBenchIdentity(&result, game, choice.model, choice.name, choice.effort) converted := benchmarkResultFromDigBench(taskID, result) if errors.Is(ctx.Err(), context.Canceled) { markBenchmarkStopped(&converted) @@ -192,6 +188,24 @@ func (c Client) runDigBenchBenchmarkSuite(ctx context.Context, taskID BenchmarkT emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: len(selected), Done: true}) } +func fillDigBenchIdentity(result *DigBenchResult, game, model, displayName, effort string) { + if strings.TrimSpace(result.Game) == "" { + result.Game = game + } + if strings.TrimSpace(result.Model) == "" { + result.Model = model + } + if strings.TrimSpace(result.DisplayName) == "" { + result.DisplayName = displayName + } + if strings.TrimSpace(result.ActualModel) == "" { + result.ActualModel = model + } + if strings.TrimSpace(result.Effort) == "" { + result.Effort = effort + } +} + func benchmarkResultFromDigBench(taskID BenchmarkTaskID, result DigBenchResult) BenchmarkResult { return BenchmarkResult{ TaskID: taskID, TaskName: "DIGBENCH " + result.Game, @@ -759,12 +773,19 @@ func digBenchToolResponse(value any, err error) map[string]any { } func applyDigBenchSession(result *DigBenchResult, session digbench.Session) { - result.Game = session.Game + // Step responses may omit identity and other session-static metadata. Treat + // those fields as incremental updates so a valid initial session cannot lose + // the game name used by live UI snapshots. + if strings.TrimSpace(session.Game) != "" { + result.Game = session.Game + } result.Status = session.State.Status result.CurrentLevel = session.State.Level result.LevelsBeaten = session.LevelsBeaten result.Steps = session.StepIndex - result.Seed = session.Seed + if session.Seed != nil { + result.Seed = session.Seed + } if session.State.MaxLevel != nil { result.MaxLevel = *session.State.MaxLevel } diff --git a/internal/codex/digbench_test.go b/internal/codex/digbench_test.go index 696a4087..e662ab50 100644 --- a/internal/codex/digbench_test.go +++ b/internal/codex/digbench_test.go @@ -223,6 +223,9 @@ func TestDigBenchBenchmarkSuiteRunsSelectedDiscoveredGames(t *testing.T) { var trials []string runDigBenchTrial = func(_ context.Context, _ Client, _ digBenchService, options DigBenchOptions) (DigBenchResult, error) { trials = append(trials, options.Game+"/"+options.Effort) + // DigBench step payloads do not need to repeat session-static identity. + // The suite must still publish a stable active row for this snapshot. + options.Snapshot(DigBenchResult{Status: "in_progress", CurrentLevel: 2}) result := DigBenchResult{Game: options.Game, Model: options.Model, DisplayName: "Model", ActualModel: options.Model, Effort: options.Effort, Won: true, Status: "completed"} options.Snapshot(result) return result, nil @@ -240,6 +243,11 @@ func TestDigBenchBenchmarkSuiteRunsSelectedDiscoveredGames(t *testing.T) { } results := 0 for _, event := range events { + if event.Active != nil { + if event.Active.Provider != "digbench" || !strings.HasPrefix(event.Active.TaskName, "DIGBENCH P-") || event.Active.Model == "" || event.Active.DisplayName == "" || event.Active.Effort == "" { + t.Fatalf("active DigBench identity was not preserved: %#v", *event.Active) + } + } if event.Result != nil { results++ } @@ -250,6 +258,25 @@ func TestDigBenchBenchmarkSuiteRunsSelectedDiscoveredGames(t *testing.T) { } } +func TestApplyDigBenchSessionPreservesStaticMetadataFromInitialSession(t *testing.T) { + seed := int64(42) + framework := "engine-1" + maxLevel := 14 + result := DigBenchResult{Game: "P-1", Seed: &seed, FrameworkVersion: framework, MaxLevel: maxLevel} + + applyDigBenchSession(&result, digbench.Session{ + SessionID: "session-1", StepIndex: 211, LevelsBeaten: 6, + State: digbench.State{Status: "in_progress", Level: 7}, + }) + + if result.Game != "P-1" || result.Seed == nil || *result.Seed != seed || result.FrameworkVersion != framework || result.MaxLevel != maxLevel { + t.Fatalf("partial session erased static metadata: %#v", result) + } + if result.Status != "in_progress" || result.CurrentLevel != 7 || result.LevelsBeaten != 6 || result.Steps != 211 { + t.Fatalf("partial session did not update progress: %#v", result) + } +} + func TestNextPendingEnvelopeCanReportHeartbeat(t *testing.T) { server, _ := newFakeBenchmarkServer() heartbeat := make(chan time.Time, 1) From 119695ebc09c71ca3c0bbaf47d1099aa816e90fd Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 22 Aug 2026 15:28:36 +0100 Subject: [PATCH 17/18] FIX: address DigBench review findings --- internal/codex/digbench.go | 128 +++++++++++++++++++++++--------- internal/codex/digbench_test.go | 103 +++++++++++++++++++++++++ internal/ui/benchmark.go | 25 ++++++- internal/ui/benchmark_test.go | 26 +++++++ main.go | 49 ++++++------ main_test.go | 31 ++++++++ 6 files changed, 299 insertions(+), 63 deletions(-) diff --git a/internal/codex/digbench.go b/internal/codex/digbench.go index d342dc3c..abb69708 100644 --- a/internal/codex/digbench.go +++ b/internal/codex/digbench.go @@ -18,6 +18,8 @@ const ( digBenchDeveloperInstructions = "Play only the assigned DigBench session. Use its scoped tools for game access, keep useful notes in the isolated workspace if needed, and stop calling tools as soon as the game is done." ) +var errDigBenchTimeout = errors.New("DigBench timeout reached") + // DigBenchProgressPhase identifies a safe, content-free runner milestone. type DigBenchProgressPhase string @@ -168,6 +170,10 @@ func (c Client) runDigBenchBenchmarkSuite(ctx context.Context, taskID BenchmarkT }, }) fillDigBenchIdentity(&result, game, choice.model, choice.name, choice.effort) + if runErr != nil && result.Failure == "" && !errors.Is(ctx.Err(), context.Canceled) { + result.Failure = redactDigBenchText(runErr.Error()) + } + result.Failure = redactDigBenchText(result.Failure) converted := benchmarkResultFromDigBench(taskID, result) if errors.Is(ctx.Err(), context.Canceled) { markBenchmarkStopped(&converted) @@ -235,24 +241,26 @@ func (c Client) RunDigBench(ctx context.Context, service digBenchService, option if options.Timeout <= 0 { options.Timeout = defaultDigBenchTimeout } + runCtx, cancel := context.WithTimeoutCause(ctx, options.Timeout, errDigBenchTimeout) + defer cancel() - server, err := openBenchmarkAppServer(ctx, c.Binary, c.BenchmarkAPIKey) + server, err := openBenchmarkAppServer(runCtx, c.Binary, c.BenchmarkAPIKey) if err != nil { - return DigBenchResult{}, err + return DigBenchResult{}, sanitizeDigBenchError(err) } defer server.close() if !server.experimentalAPI { return DigBenchResult{}, errors.New("DigBench requires a Codex CLI with experimental dynamic-tool support") } - models, err := server.models(ctx) + models, err := server.models(runCtx) if err != nil { - return DigBenchResult{}, err + return DigBenchResult{}, sanitizeDigBenchError(err) } combination, err := findDigBenchCombination(models, options.Model, options.Effort) if err != nil { return DigBenchResult{}, err } - return server.runDigBench(ctx, service, combination, options) + return server.runDigBench(runCtx, service, combination, options) } func findDigBenchCombination(models []benchmarkModel, modelID, effort string) (benchmarkCombination, error) { @@ -269,20 +277,29 @@ func (s *appServerSession) runDigBench( service digBenchService, combination benchmarkCombination, options DigBenchOptions, -) (DigBenchResult, error) { - result := DigBenchResult{ +) (result DigBenchResult, runErr error) { + result = DigBenchResult{ Game: options.Game, Model: combination.model.Model, DisplayName: combination.model.DisplayName, Effort: combination.effort, ActualModel: combination.model.Model, } - runCtx, cancel := context.WithTimeout(ctx, options.Timeout) - defer cancel() + sensitiveValues := make([]string, 0, 5) + defer func() { + if runErr != nil { + runErr = sanitizeDigBenchError(runErr, sensitiveValues...) + if result.Failure == "" && !errors.Is(runErr, context.Canceled) { + result.Failure = runErr.Error() + } + } + result.Failure = redactDigBenchText(result.Failure, sensitiveValues...) + }() temporary, err := os.MkdirTemp("", "codexometer-digbench-") if err != nil { return result, fmt.Errorf("create isolated DigBench workspace: %w", err) } defer os.RemoveAll(temporary) + sensitiveValues = append(sensitiveValues, temporary) threadParams := map[string]any{ "model": combination.model.Model, "cwd": temporary, @@ -294,11 +311,11 @@ func (s *appServerSession) runDigBench( if s.experimentalRawEvents { threadParams["experimentalRawEvents"] = true } - threadResult, err := s.call(runCtx, "thread/start", threadParams, nil) + threadResult, err := s.call(ctx, "thread/start", threadParams, nil) if err != nil && s.experimentalRawEvents && experimentalAPIUnsupported(err) { s.experimentalRawEvents = false delete(threadParams, "experimentalRawEvents") - threadResult, err = s.call(runCtx, "thread/start", threadParams, nil) + threadResult, err = s.call(ctx, "thread/start", threadParams, nil) } if err != nil { return result, fmt.Errorf("start DigBench Codex thread: %w", err) @@ -312,6 +329,7 @@ func (s *appServerSession) runDigBench( if err := json.Unmarshal(threadResult, &startedThread); err != nil || startedThread.Thread.ID == "" { return result, errors.New("Codex returned an invalid DigBench thread") } + sensitiveValues = append(sensitiveValues, startedThread.Thread.ID) if startedThread.Model != "" { result.ActualModel = startedThread.Model } @@ -322,11 +340,12 @@ func (s *appServerSession) runDigBench( if modelVersion != "" { startRequest.ModelVersion = &modelVersion } - session, err := service.StartSession(runCtx, startRequest) + session, err := service.StartSession(ctx, startRequest) if err != nil { return result, fmt.Errorf("start DigBench game: %w", err) } assignedSessionID := session.SessionID + sensitiveValues = append(sensitiveValues, assignedSessionID) applyDigBenchSession(&result, session) startedAt := time.Now() @@ -343,7 +362,7 @@ func (s *appServerSession) runDigBench( if combination.effort != "default" && combination.effort != "" { turnParams["effort"] = combination.effort } - turnResponse, err := s.call(runCtx, "turn/start", turnParams, nil) + turnResponse, err := s.call(ctx, "turn/start", turnParams, nil) if err != nil { return result, fmt.Errorf("start DigBench turn: %w", err) } @@ -355,6 +374,7 @@ func (s *appServerSession) runDigBench( if err := json.Unmarshal(turnResponse, &startedTurn); err != nil || startedTurn.Turn.ID == "" { return result, errors.New("Codex returned an invalid DigBench turn") } + sensitiveValues = append(sensitiveValues, startedTurn.Turn.ID) emitDigBenchProgress(options.Progress, DigBenchProgressTurn, result, startedAt) publishDigBenchSnapshot(options.Snapshot, result) @@ -364,17 +384,18 @@ func (s *appServerSession) runDigBench( progressTicker := time.NewTicker(defaultDigBenchProgressInterval) defer progressTicker.Stop() for !completed { - envelope, heartbeat, envelopeErr := s.nextPendingEnvelopeOrHeartbeat(runCtx, progressTicker.C) + envelope, heartbeat, envelopeErr := s.nextPendingEnvelopeOrHeartbeat(ctx, progressTicker.C) if heartbeat { emitDigBenchProgress(options.Progress, DigBenchProgressHeartbeat, result, startedAt) continue } if envelopeErr != nil { result.Duration = time.Since(startedAt) - if errors.Is(ctx.Err(), context.Canceled) { + if errors.Is(context.Cause(ctx), errDigBenchTimeout) { + result.Failure = fmt.Sprintf("DigBench run timed out after %s", options.Timeout) cleanupCompleted := false handle := func(method string, params json.RawMessage) bool { - if method == "turn/completed" && digBenchTurnCompleted(params, startedThread.Thread.ID, startedTurn.Turn.ID, &turnFailure) { + if method == "turn/completed" && digBenchTurnCompleted(params, startedThread.Thread.ID, startedTurn.Turn.ID, &turnFailure, sensitiveValues...) { cleanupCompleted = true return true } @@ -383,32 +404,35 @@ func (s *appServerSession) runDigBench( cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), s.benchmarkInterruptTimeout()) interruptErr := s.interruptBenchmarkTurn(cleanupCtx, startedThread.Thread.ID, startedTurn.Turn.ID, &cleanupCompleted, handle) cleanupCancel() - applyDigBenchMeasurements(&result, telemetry) if interruptErr != nil { - result.Failure = "remote interruption could not be confirmed: " + interruptErr.Error() + result.Failure += "; cleanup failed: " + redactDigBenchText(interruptErr.Error(), sensitiveValues...) + return result, fmt.Errorf("interrupt timed-out DigBench turn: %w", interruptErr) + } + applyDigBenchMeasurements(&result, telemetry) + if session.Done { + result.Failure = "" } publishDigBenchSnapshot(options.Snapshot, result) - return result, ctx.Err() + return result, nil } - if recoverableBenchmarkTimeout(ctx, runCtx, envelopeErr) { - result.Failure = fmt.Sprintf("DigBench run timed out after %s", options.Timeout) + if ctx.Err() != nil { cleanupCompleted := false handle := func(method string, params json.RawMessage) bool { - if method == "turn/completed" && digBenchTurnCompleted(params, startedThread.Thread.ID, startedTurn.Turn.ID, &turnFailure) { + if method == "turn/completed" && digBenchTurnCompleted(params, startedThread.Thread.ID, startedTurn.Turn.ID, &turnFailure, sensitiveValues...) { cleanupCompleted = true return true } return false } - if interruptErr := s.interruptBenchmarkTurn(ctx, startedThread.Thread.ID, startedTurn.Turn.ID, &cleanupCompleted, handle); interruptErr != nil { - return result, fmt.Errorf("interrupt timed-out DigBench turn: %w", interruptErr) - } + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), s.benchmarkInterruptTimeout()) + interruptErr := s.interruptBenchmarkTurn(cleanupCtx, startedThread.Thread.ID, startedTurn.Turn.ID, &cleanupCompleted, handle) + cleanupCancel() applyDigBenchMeasurements(&result, telemetry) - if session.Done { - result.Failure = "" + if interruptErr != nil { + result.Failure = "remote interruption could not be confirmed: " + redactDigBenchText(interruptErr.Error(), sensitiveValues...) } publishDigBenchSnapshot(options.Snapshot, result) - return result, nil + return result, ctx.Err() } return result, envelopeErr } @@ -418,7 +442,7 @@ func (s *appServerSession) runDigBench( } tool, action, stepIndex := digBenchToolSummary(envelope.Params) response := handleDigBenchToolCall( - runCtx, service, startedThread.Thread.ID, startedTurn.Turn.ID, + ctx, service, startedThread.Thread.ID, startedTurn.Turn.ID, assignedSessionID, envelope.Params, &session, ) applyDigBenchSession(&result, session) @@ -470,9 +494,9 @@ func (s *appServerSession) runDigBench( result.ActualModel = event.ToModel } case "turn/completed": - completed = digBenchTurnCompleted(envelope.Params, startedThread.Thread.ID, startedTurn.Turn.ID, &turnFailure) + completed = digBenchTurnCompleted(envelope.Params, startedThread.Thread.ID, startedTurn.Turn.ID, &turnFailure, sensitiveValues...) if completed { - if final := digBenchFinalResponse(envelope.Params, startedThread.Thread.ID, startedTurn.Turn.ID, assignedSessionID); final != "" { + if final := digBenchFinalResponse(envelope.Params, startedThread.Thread.ID, startedTurn.Turn.ID, sensitiveValues...); final != "" { appendDigBenchInteraction(&result, startedAt, BenchmarkInteractionResponse, final) publishDigBenchSnapshot(options.Snapshot, result) } @@ -607,7 +631,37 @@ func redactDigBenchText(value string, sensitiveValues ...string) string { value = strings.ReplaceAll(value, sensitive, "[REDACTED]") } } - return value + return strings.Map(func(character rune) rune { + // Preserve formatting whitespace, but neutralize terminal C0/C1 control + // bytes so benchmark content cannot inject ANSI or OSC sequences into the + // detail renderer or clipboard output. + if character == '\n' || character == '\t' { + return character + } + if character < 0x20 || (character >= 0x7f && character <= 0x9f) { + return -1 + } + return character + }, value) +} + +type sanitizedDigBenchError struct { + cause error + message string +} + +func (e *sanitizedDigBenchError) Error() string { return e.message } +func (e *sanitizedDigBenchError) Unwrap() error { return e.cause } + +func sanitizeDigBenchError(err error, sensitiveValues ...string) error { + if err == nil { + return nil + } + message := redactDigBenchText(err.Error(), sensitiveValues...) + if message == err.Error() { + return err + } + return &sanitizedDigBenchError{cause: err, message: message} } func formatDigBenchState(session digbench.Session, sensitiveValues ...string) string { @@ -795,7 +849,7 @@ func applyDigBenchSession(result *DigBenchResult, session digbench.Session) { result.Won = session.Done && session.State.Done && session.State.Status == "completed" } -func digBenchTurnCompleted(params json.RawMessage, threadID, turnID string, failure *string) bool { +func digBenchTurnCompleted(params json.RawMessage, threadID, turnID string, failure *string, sensitiveValues ...string) bool { var event struct { ThreadID string `json:"threadId"` Turn struct { @@ -810,15 +864,15 @@ func digBenchTurnCompleted(params json.RawMessage, threadID, turnID string, fail return false } if event.Turn.Status != "completed" { - *failure = "turn " + event.Turn.Status + *failure = "turn " + redactDigBenchText(event.Turn.Status, sensitiveValues...) if event.Turn.Error != nil && event.Turn.Error.Message != "" { - *failure += ": " + event.Turn.Error.Message + *failure += ": " + redactDigBenchText(event.Turn.Error.Message, sensitiveValues...) } } return true } -func digBenchFinalResponse(params json.RawMessage, threadID, turnID, sessionID string) string { +func digBenchFinalResponse(params json.RawMessage, threadID, turnID string, sensitiveValues ...string) string { var event struct { ThreadID string `json:"threadId"` Turn struct { @@ -834,7 +888,7 @@ func digBenchFinalResponse(params json.RawMessage, threadID, turnID, sessionID s } for _, item := range event.Turn.Items { if item.Type == "agentMessage" && strings.TrimSpace(item.Text) != "" { - return redactDigBenchText(item.Text, sessionID, threadID, turnID) + return redactDigBenchText(item.Text, sensitiveValues...) } } return "" diff --git a/internal/codex/digbench_test.go b/internal/codex/digbench_test.go index e662ab50..7afd7366 100644 --- a/internal/codex/digbench_test.go +++ b/internal/codex/digbench_test.go @@ -144,6 +144,26 @@ func TestRunDigBenchBridgesScopedStepAndDetectsWin(t *testing.T) { } } +func TestRunDigBenchTimeoutIncludesAppServerStartup(t *testing.T) { + original := openBenchmarkAppServer + openBenchmarkAppServer = func(ctx context.Context, _, _ string) (*appServerSession, error) { + <-ctx.Done() + return nil, ctx.Err() + } + t.Cleanup(func() { openBenchmarkAppServer = original }) + + startedAt := time.Now() + _, err := (Client{}).RunDigBench(context.Background(), &fakeDigBenchService{}, DigBenchOptions{ + Game: "P-1", Model: "model", Effort: "high", Timeout: 10 * time.Millisecond, + }) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("startup timeout error = %v", err) + } + if elapsed := time.Since(startedAt); elapsed > time.Second { + t.Fatalf("startup exceeded configured timeout by too much: %s", elapsed) + } +} + func TestDigBenchTranscriptPromptRedactsOnlyRuntimeSessionID(t *testing.T) { maxLevel := 3 session := digbench.Session{ @@ -199,6 +219,52 @@ func TestDigBenchToolResponseTranscriptRedactsSensitiveIdentifiers(t *testing.T) } } +func TestDigBenchRuntimeTextSanitizationCoversFailuresAndFinalResponse(t *testing.T) { + const ( + sessionID = "session-secret" + threadID = "thread-secret" + turnID = "turn-secret" + workspace = "/tmp/codexometer-digbench-secret" + ) + unsafe := sessionID + " " + threadID + " " + turnID + " " + workspace + "\x1b]52;c;payload\a\nkept\tformat" + + redacted := redactDigBenchText(unsafe, sessionID, threadID, turnID, workspace) + assertSafeDigBenchText(t, redacted, sessionID, threadID, turnID, workspace) + if !strings.Contains(redacted, "\nkept\tformat") { + t.Fatalf("intentional formatting whitespace was removed: %q", redacted) + } + + completed := rawJSON(map[string]any{ + "threadId": threadID, + "turn": map[string]any{ + "id": turnID, "status": "failed", + "error": map[string]string{"message": unsafe}, + "items": []any{map[string]string{"type": "agentMessage", "text": unsafe}}, + }, + }) + failure := "" + if !digBenchTurnCompleted(completed, threadID, turnID, &failure, sessionID, threadID, turnID, workspace) { + t.Fatal("matching failed turn was not recognized") + } + assertSafeDigBenchText(t, failure, sessionID, threadID, turnID, workspace) + final := digBenchFinalResponse(completed, threadID, turnID, sessionID, threadID, turnID, workspace) + assertSafeDigBenchText(t, final, sessionID, threadID, turnID, workspace) +} + +func assertSafeDigBenchText(t *testing.T, value string, sensitiveValues ...string) { + t.Helper() + for _, sensitive := range sensitiveValues { + if strings.Contains(value, sensitive) { + t.Fatalf("runtime value %q leaked in %q", sensitive, value) + } + } + for _, character := range value { + if character != '\n' && character != '\t' && (character < 0x20 || (character >= 0x7f && character <= 0x9f)) { + t.Fatalf("terminal control U+%04X remained in %q", character, value) + } + } +} + func TestClientBenchmarkTasksRequireDigBenchToken(t *testing.T) { plain := (Client{}).BenchmarkTasks() enabled := (Client{DigBenchToken: "secret", DigBenchGames: []string{"P-1"}}).BenchmarkTasks() @@ -258,6 +324,43 @@ func TestDigBenchBenchmarkSuiteRunsSelectedDiscoveredGames(t *testing.T) { } } +func TestDigBenchBenchmarkSuitePersistsSanitizedRunnerErrorsAsIncomplete(t *testing.T) { + server, _ := newFakeBenchmarkServer(benchmarkEnvelope{ + ID: rawJSON(1), + Result: rawJSON(map[string]any{"data": []any{map[string]any{ + "model": "model", "displayName": "Model", + "supportedReasoningEfforts": []any{map[string]string{"reasoningEffort": "high"}}, + }}}), + }) + originalOpen := openBenchmarkAppServer + openBenchmarkAppServer = func(context.Context, string, string) (*appServerSession, error) { return server, nil } + t.Cleanup(func() { openBenchmarkAppServer = originalOpen }) + + originalRun := runDigBenchTrial + runDigBenchTrial = func(_ context.Context, _ Client, _ digBenchService, options DigBenchOptions) (DigBenchResult, error) { + return DigBenchResult{Game: options.Game, Model: options.Model, Effort: options.Effort}, errors.New("transport \x1b]52;c;payload\a failed") + } + t.Cleanup(func() { runDigBenchTrial = originalRun }) + + var events []BenchmarkEvent + client := Client{DigBenchToken: "secret", DigBenchGames: []string{"P-1"}} + client.RunBenchmarkSuiteScoped(context.Background(), []BenchmarkTaskID{BenchmarkDigBench}, BenchmarkScope{ + Models: []string{"model"}, Efforts: []string{"high"}, Games: []string{"P-1"}, + }, func(event BenchmarkEvent) { events = append(events, event) }) + + var result *BenchmarkResult + for _, event := range events { + if event.Result != nil { + copy := *event.Result + result = © + } + } + if result == nil || result.Correct || result.Failure == "" { + t.Fatalf("failed trial was not persisted as incomplete: %#v", result) + } + assertSafeDigBenchText(t, result.Failure) +} + func TestApplyDigBenchSessionPreservesStaticMetadataFromInitialSession(t *testing.T) { seed := int64(42) framework := "engine-1" diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index dbe4df73..e79e1f3e 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -1395,7 +1395,7 @@ func benchmarkResultValues(result codex.BenchmarkResult, rankings map[string]int model += "→" + result.ActualModel } rank := "—" - if value := rankings[benchmarkCombinationKey(result)]; result.Provider == "" && !inProgress && !result.Stopped && value > 0 { + if value, ranked := benchmarkResultRank(result, rankings); ranked && !inProgress && !result.Stopped { rank = fmt.Sprintf("#%d", value) } return []string{ @@ -1425,7 +1425,18 @@ func sortedBenchmarkResults(results []codex.BenchmarkResult, column benchmarkSor } sort.SliceStable(ordered, func(left, right int) bool { if column == benchmarkSortRank { - comparison := compareInt(rankings[benchmarkCombinationKey(ordered[left])], rankings[benchmarkCombinationKey(ordered[right])]) + leftRank, leftRanked := benchmarkResultRank(ordered[left], rankings) + rightRank, rightRanked := benchmarkResultRank(ordered[right], rankings) + if leftRanked != rightRanked { + // Rank is not meaningful for external/randomized suites. Keep those + // rows unranked and after ranked deterministic results regardless of + // sort direction. + return leftRanked + } + if !leftRanked { + return false + } + comparison := compareInt(leftRank, rightRank) if descending { return comparison > 0 } @@ -1446,6 +1457,14 @@ func sortedBenchmarkResults(results []codex.BenchmarkResult, column benchmarkSor return ordered } +func benchmarkResultRank(result codex.BenchmarkResult, rankings map[string]int) (int, bool) { + if result.Provider != "" || result.Stopped { + return 0, false + } + value := rankings[benchmarkCombinationKey(result)] + return value, value > 0 +} + type benchmarkRankSummary struct { key string passes int @@ -1476,7 +1495,7 @@ func benchmarkRankings(results []codex.BenchmarkResult, modes ...benchmarkRankMo } byKey := make(map[string]*benchmarkRankSummary) for _, result := range results { - if result.Stopped { + if result.Stopped || result.Provider != "" { continue } key := benchmarkCombinationKey(result) diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index 9494642c..1365aa2b 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -1214,6 +1214,32 @@ func TestBenchmarkRankingPrioritizesCorrectnessThenMeasuredEfficiency(t *testing } } +func TestBenchmarkRankIgnoresExternalSuiteResults(t *testing.T) { + external := []codex.BenchmarkResult{ + {Provider: "digbench", Model: "slow", DisplayName: "Slow", Effort: "high", TaskName: "DIGBENCH P-1", Correct: true, Duration: time.Minute, CostKnown: true, CostUSD: 1}, + {Provider: "digbench", Model: "fast", DisplayName: "Fast", Effort: "high", TaskName: "DIGBENCH P-2", Duration: time.Second, CostKnown: true, CostUSD: 0.01}, + } + rankings := benchmarkRankings(external) + if len(rankings) != 0 { + t.Fatalf("external results received hidden rankings: %v", rankings) + } + ordered := sortedBenchmarkResults(external, benchmarkSortRank, false, rankings) + if ordered[0].DisplayName != "Slow" || ordered[1].DisplayName != "Fast" { + t.Fatalf("rank sort reordered unranked external trials: %#v", ordered) + } + + deterministic := codex.BenchmarkResult{Model: "fast", DisplayName: "Fast", Effort: "high", Correct: true, Duration: time.Second, CostKnown: true, CostUSD: 0.01} + mixed := append([]codex.BenchmarkResult{external[1]}, deterministic) + rankings = benchmarkRankings(mixed) + if _, ranked := benchmarkResultRank(external[1], rankings); ranked { + t.Fatalf("external result inherited deterministic combination rank: %v", rankings) + } + ordered = sortedBenchmarkResults(mixed, benchmarkSortRank, true, rankings) + if ordered[0].Provider != "" || ordered[1].Provider != "digbench" { + t.Fatalf("unranked external result was not kept after ranked results: %#v", ordered) + } +} + func TestBenchmarkRankWeightingSwitchesBetweenCostAndSpeed(t *testing.T) { results := []codex.BenchmarkResult{ {Model: "cheap", Effort: "low", Correct: true, Duration: 30 * time.Second, CostKnown: true, CostUSD: 0.01}, diff --git a/main.go b/main.go index ba4545cd..7cb21ae1 100644 --- a/main.go +++ b/main.go @@ -240,6 +240,20 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { fmt.Fprintln(stdout, "codexometer "+version.Current()) return 0 } + // Capture credentials for the benchmark components, then remove them before + // any path that can launch Codex. This keeps auth checks and quota reads on + // the user's prevailing Codex login instead of leaking or implicitly using a + // benchmarking credential through the child environment. + benchmarkAPIKey, benchmarkAPIKeySource, err := takeBenchmarkAPIKey() + if err != nil { + fmt.Fprintln(stderr, "codexometer:", err) + return 1 + } + digBenchToken, err := takeDigBenchToken() + if err != nil { + fmt.Fprintln(stderr, "codexometer:", err) + return 1 + } if *checkAuth { snapshot, err := deps.checkAuth(context.Background(), *codexPath) if err != nil { @@ -254,20 +268,10 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { fmt.Fprintln(stderr, "codexometer: --digbench-game cannot be combined with --demo") return 2 } - token, tokenErr := takeDigBenchToken() - if tokenErr != nil { - fmt.Fprintln(stderr, "codexometer:", tokenErr) - return 1 - } - if token == "" { + if digBenchToken == "" { fmt.Fprintln(stderr, "codexometer: DIGBENCH_API_TOKEN is required for --digbench-game") return 1 } - benchmarkAPIKey, benchmarkAPIKeySource, err := takeBenchmarkAPIKey() - if err != nil { - fmt.Fprintln(stderr, "codexometer:", err) - return 1 - } if deps.runDigBench == nil { fmt.Fprintln(stderr, "codexometer: DigBench runner unavailable") return 1 @@ -278,7 +282,7 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { } fmt.Fprintf(stderr, "Starting DigBench %s with %s/%s; this creates a persisted remote session and uses %s.\n", strings.TrimSpace(*digBenchGame), strings.TrimSpace(*digBenchModel), strings.TrimSpace(*digBenchEffort), billing) - result, err := deps.runDigBench(context.Background(), *codexPath, token, benchmarkAPIKey, codex.DigBenchOptions{ + result, err := deps.runDigBench(context.Background(), *codexPath, digBenchToken, benchmarkAPIKey, codex.DigBenchOptions{ Game: strings.TrimSpace(*digBenchGame), Model: strings.TrimSpace(*digBenchModel), Effort: strings.TrimSpace(*digBenchEffort), Timeout: *digBenchTimeout, ClientVersion: version.Current(), Progress: func(progress codex.DigBenchProgress) { @@ -296,16 +300,6 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { return 0 } - benchmarkAPIKey, _, err := takeBenchmarkAPIKey() - if err != nil { - fmt.Fprintln(stderr, "codexometer:", err) - return 1 - } - digBenchToken, err := takeDigBenchToken() - if err != nil { - fmt.Fprintln(stderr, "codexometer:", err) - return 1 - } var digBenchGames []string if digBenchToken != "" && deps.listDigBenchGames != nil { discoveryCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second) @@ -384,7 +378,7 @@ func normalizeDigBenchGames(games []string) []string { normalized := make([]string, 0, len(games)) for _, game := range games { game = strings.TrimSpace(game) - if game != "" && !seen[game] { + if game != "" && !containsTerminalControl(game) && !seen[game] { seen[game] = true normalized = append(normalized, game) } @@ -392,6 +386,15 @@ func normalizeDigBenchGames(games []string) []string { return normalized } +func containsTerminalControl(value string) bool { + for _, character := range value { + if character < 0x20 || (character >= 0x7f && character <= 0x9f) { + return true + } + } + return false +} + func formatDigBenchResult(result codex.DigBenchResult) string { outcome := "LOSS" if result.Won { diff --git a/main_test.go b/main_test.go index 4bf42439..56bcb5ca 100644 --- a/main_test.go +++ b/main_test.go @@ -56,6 +56,27 @@ func TestRunAuthCheckSuccessAndFailure(t *testing.T) { } } +func TestRunAuthCheckScrubsBenchmarkCredentialsBeforeLaunchingCodex(t *testing.T) { + t.Setenv("DIGBENCH_API_TOKEN", "digbench-secret") + t.Setenv("CODEXOMETER_BENCHMARK_API_KEY", "benchmark-secret") + t.Setenv("OPENAI_API_KEY", "fallback-secret") + var stdout, stderr bytes.Buffer + deps := dependencies{ + checkAuth: func(context.Context, string) (codex.Snapshot, error) { + for _, name := range []string{"DIGBENCH_API_TOKEN", "CODEXOMETER_BENCHMARK_API_KEY", "OPENAI_API_KEY"} { + if value := os.Getenv(name); value != "" { + t.Fatalf("%s remained in the auth-check child environment", name) + } + } + return codex.DemoSnapshot(), nil + }, + } + + if code := run([]string{"--check-auth"}, &stdout, &stderr, deps); code != 0 { + t.Fatalf("code=%d stdout=%q stderr=%q", code, stdout.String(), stderr.String()) + } +} + func TestRunStartsDemoWithSelectedOptions(t *testing.T) { var stdout, stderr bytes.Buffer called := false @@ -247,6 +268,16 @@ func TestRunPassesDigBenchTokenToUIWithoutLeavingItInEnvironment(t *testing.T) { } } +func TestNormalizeDigBenchGamesRejectsTerminalControls(t *testing.T) { + games := normalizeDigBenchGames([]string{ + " P-1 ", "P-1", "P-2\nFORGED", "P-3\x1b]52;c;payload\a", "P-4\u0085FORGED", "P-5", + }) + want := []string{"P-1", "P-5"} + if len(games) != len(want) || games[0] != want[0] || games[1] != want[1] { + t.Fatalf("normalized games = %#v, want %#v", games, want) + } +} + func TestRunDigBenchRequiresToken(t *testing.T) { t.Setenv("DIGBENCH_API_TOKEN", "") var stdout, stderr bytes.Buffer From cc8ef9de36ec10111aebaa7be54954d01a753593 Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 22 Aug 2026 15:36:39 +0100 Subject: [PATCH 18/18] FIX: retain successful DigBench responses --- internal/digbench/client.go | 9 +++---- internal/digbench/client_test.go | 40 ++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/internal/digbench/client.go b/internal/digbench/client.go index 9d51c16d..68261519 100644 --- a/internal/digbench/client.go +++ b/internal/digbench/client.go @@ -206,16 +206,17 @@ func (c Client) do(ctx context.Context, method, path string, body any, bearer, r return fmt.Errorf("call DigBench API: %w", err) } data, readErr := io.ReadAll(io.LimitReader(response.Body, maxResponseSize+1)) - closeErr := response.Body.Close() + // Once the complete response has been read, a transport-level Close error + // cannot invalidate the status or body. In particular, StartSession is not + // retryable: discarding its decoded response here could orphan a remote + // session whose creation already succeeded. + _ = response.Body.Close() if readErr != nil { if retry && attempt+1 < attempts { continue } return fmt.Errorf("read DigBench response: %w", readErr) } - if closeErr != nil { - return fmt.Errorf("close DigBench response: %w", closeErr) - } if len(data) > maxResponseSize { return errors.New("DigBench response exceeds 1 MiB") } diff --git a/internal/digbench/client_test.go b/internal/digbench/client_test.go index 399854f3..4facf0d0 100644 --- a/internal/digbench/client_test.go +++ b/internal/digbench/client_test.go @@ -107,6 +107,46 @@ func TestStartSessionDoesNotRetryAnAmbiguousFailure(t *testing.T) { } } +func TestStartSessionKeepsValidResponseWhenBodyCloseFails(t *testing.T) { + client := Client{ + BaseURL: "https://digbench.test", Token: "secret", + HTTPClient: &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) { + if request.Method != http.MethodPost || request.URL.Path != "/sessions" { + t.Fatalf("request = %s %s", request.Method, request.URL.Path) + } + return &http.Response{ + StatusCode: http.StatusOK, + Header: make(http.Header), + Body: closeErrorBody{Reader: strings.NewReader(`{ + "session_id":"session-1","game":"P-1","step_index":0, + "done":false,"levels_beaten":0, + "state":{"status":"in_progress","done":false,"level":1} + }`)}, + Request: request, + }, nil + })}, + } + + session, err := client.StartSession(context.Background(), StartRequest{Game: "P-1"}) + if err != nil || session.SessionID != "session-1" || session.Game != "P-1" { + t.Fatalf("session=%#v error=%v", session, err) + } +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (roundTrip roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) { + return roundTrip(request) +} + +type closeErrorBody struct { + io.Reader +} + +func (closeErrorBody) Close() error { + return errors.New("simulated response close failure") +} + func TestSessionValidationRejectsContradictoryOutcome(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { _, _ = writer.Write([]byte(`{