Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

refactor(agent): run Codex and Claude cold starts through the warm-pool turn lifecycle (MUL-9916) (#11250)

Jiayuan Zhang96a8195ef139
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index aa2104eb2a..f64bd5ec65 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -8,6 +8,7 @@ import (
"fmt"
"io"
"log/slog"
+ "maps"
"os"
"os/exec"
"path/filepath"
@@ -15,7 +16,6 @@ import (
"strings"
"sync"
"sync/atomic"
- "syscall"
"time"
"github.com/multica-ai/multica/server/pkg/taskfailure"
@@ -58,9 +58,6 @@ type claudeBackend struct {
}
func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {
- if b.cfg.WarmPool != nil {
- return b.executeWarm(ctx, prompt, opts)
- }
execPath := b.cfg.ExecutablePath
if execPath == "" {
execPath = "claude"
@@ -72,70 +69,34 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
timeout := opts.Timeout
runCtx, cancel := runContext(ctx, timeout)
- args := buildClaudeArgs(opts, b.cfg.Logger)
-
- // If the caller provided an MCP config, write it to a temp file and pass
- // --mcp-config <path> so the agent uses a controlled set of MCP servers
- // instead of inheriting from the outer Claude Code session.
- var mcpConfigPath string
- var mcpFileCleanup func() // non-nil while this function owns the temp file
- if hasManagedMcpConfig(opts.McpConfig) {
- path, err := writeMcpConfigToTemp(opts.McpConfig)
+ // Getting a process is the only step that depends on the warm pool. A
+ // pooled spawn must outlive runCtx so it can be parked after the turn; a
+ // one-shot spawn is bound to it.
+ pooled := b.cfg.WarmPool != nil
+ var proc *claudeProcess
+ var fingerprint string
+ if pooled {
+ fingerprint = b.warmFingerprint(execPath, opts)
+ proc = b.acquireWarmProcess(opts.ResumeSessionID, fingerprint)
+ }
+ warmHit := proc != nil
+ var usageSnapshot *claudeUsageSnapshot
+ if !warmHit {
+ spawnCtx := runCtx
+ if pooled {
+ spawnCtx = context.Background()
+ }
+ var err error
+ proc, usageSnapshot, err = b.spawnClaudeProcess(spawnCtx, execPath, opts, pooled, fingerprint)
if err != nil {
cancel()
return nil, err
}
- mcpConfigPath = path
- mcpFileCleanup = func() { cleanupMcpConfigTemp(mcpConfigPath) }
- args = append(args, "--mcp-config", mcpConfigPath)
- }
- // Clean up the temp file if we return before the goroutine takes ownership.
- defer func() {
- if mcpFileCleanup != nil {
- mcpFileCleanup()
- }
- }()
-
- cmd := b.cfg.commandAt(execPath).exec(runCtx, args...)
- hideAgentWindow(cmd)
- // Take over context cancellation: the default kills the whole group the
- // instant runCtx is done. We instead drive a graceful group-wide
- // SIGTERM→SIGKILL from the cancellation goroutine below and close stdout
- // only after the tree has been signalled. Returning nil keeps os/exec from
- // racing us with its own kill; WaitDelay remains the hard backstop.
- cmd.Cancel = func() error { return nil }
- b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(args))
- cmd.WaitDelay = 10 * time.Second
- if opts.Cwd != "" {
- cmd.Dir = opts.Cwd
- }
- cmd.Env = buildEnv(b.cfg.Env)
- if err := claudeRootSudoPreflight(args, cmd.Env); err != nil {
- cancel()
- return nil, err
}
- var usageSnapshot *claudeUsageSnapshot
- if opts.ResumeSessionID != "" {
- snapshot, snapshotErr := captureClaudeUsageSnapshot(cmd.Env, cmd.Dir, opts.ResumeSessionID)
- if snapshotErr != nil {
- b.cfg.Logger.Warn("claude usage baseline unavailable; ignoring reported session totals, keeping per-run stream usage", "error", snapshotErr)
- } else {
- usageSnapshot = snapshot
- }
- }
+ msgCh := make(chan Message, 256)
+ resCh := make(chan Result, 1)
- stdout, err := cmd.StdoutPipe()
- if err != nil {
- cancel()
- return nil, fmt.Errorf("claude stdout pipe: %w", err)
- }
- stdin, err := cmd.StdinPipe()
- if err != nil {
- cancel()
- return nil, fmt.Errorf("claude stdin pipe: %w", err)
- }
- inputWriter := &claudeInputWriter{w: stdin}
var supplements *claudeSupplementSession
if opts.EnableTaskSupplement {
supplements = newClaudeSupplementSession(runCtx)
@@ -144,39 +105,49 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
if initializer == nil && opts.SkillInvocation != nil {
initializer = newClaudeSupplementSession(runCtx)
}
- var closeStdinOnce sync.Once
- closeStdin := func() {
- closeStdinOnce.Do(func() { _ = stdin.Close() })
- if initializer != nil {
- initializer.end()
- }
- }
- // Capture stderr into both the daemon log (as before) and a bounded tail
- // buffer so we can include the last few KB in Result.Error when claude
- // exits unexpectedly. Without the tail, an exit-code-only failure looks
- // like "claude exited with error: exit status 3" — which is useless for
- // root-causing V8 aborts, Bun panics, or any other CLI-side crash.
- stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[claude:stderr] "), agentStderrTailBytes)
- cmd.Stderr = stderrBuf
- if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
- closeStdin()
- cancel()
- return nil, fmt.Errorf("start claude: %w", err)
+ // A reused process reports cumulative session totals, so its result usage
+ // is measured against what the previous turn already reported.
+ var baselineUsage map[string]TokenUsage
+ if warmHit && len(proc.lastCumulativeModelUsage) > 0 {
+ baselineUsage = maps.Clone(proc.lastCumulativeModelUsage)
+ }
+
+ turn := &claudeTurn{
+ backend: b,
+ proc: proc,
+ cancel: cancel,
+ opts: opts,
+ msgCh: msgCh,
+ coalescer: newClaudeStreamCoalescer(msgCh, nil),
+ supplements: supplements,
+ initializer: initializer,
+ usageSnapshot: usageSnapshot,
+ baselineUsage: baselineUsage,
+ rateLimits: newRateLimitTracker(opts.OnRateLimits),
+ controlErrors: make(chan error, 1),
+ resultCh: make(chan struct{}),
+ usage: make(map[string]TokenUsage),
+ seenUsage: make(map[string]struct{}),
+ }
+ if warmHit {
+ turn.sessionID = proc.sessionID
+ }
+ proc.setActiveTurn(turn)
+ if warmHit {
+ b.cfg.Logger.Info("claude warm session reused",
+ "pid", proc.cmd.Process.Pid,
+ "session_id", proc.sessionID,
+ "cwd", opts.Cwd,
+ "model", opts.Model,
+ )
+ trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: proc.sessionID})
+ } else {
+ // Start reading only once the turn is attached so no early event is
+ // dropped.
+ go proc.readStdout()
}
- b.cfg.Logger.Info("claude started", "pid", cmd.Process.Pid, "cwd", opts.Cwd, "model", opts.Model)
-
- // The process started — transfer temp file ownership to the goroutine.
- mcpFileCleanup = nil
-
- msgCh := make(chan Message, 256)
- resCh := make(chan Result, 1)
-
- // procDone closes once cmd.Wait() returns, letting the cancellation handler
- // skip a process that already exited and avoid signalling a dead/reused pid.
- procDone := make(chan struct{})
-
// writeClaudeInput runs in its own goroutine so it cannot deadlock
// against the stdout reader. With --verbose --output-format stream-json
// the CLI emits a startup banner before reading its first stdin frame;
@@ -193,22 +164,34 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
// timeout.
writeDone := make(chan error, 1)
go func() {
+ slashCommandsAllowed := !slashCommandsDisabled(b.cfg.LaunchPrefix, opts.ExtraArgs, opts.CustomArgs)
var commands map[string]bool
- if initializer != nil {
- if initErr := initializer.initialize(inputWriter, opts.HandshakeTimeout, opts.EnableTaskSupplement); initErr != nil {
+ switch {
+ case warmHit:
+ // The process answered initialize on its first turn; it does not
+ // accept a second handshake.
+ if proc.initialized && slashCommandsAllowed {
+ commands = proc.initializedCommands
+ }
+ case initializer != nil:
+ if initErr := initializer.initialize(proc.inputWriter, opts.HandshakeTimeout, opts.EnableTaskSupplement); initErr != nil {
b.cfg.Logger.Warn("Claude initialization unavailable; continuing with text input", "error", initErr)
initializer.end()
- } else if !slashCommandsDisabled(b.cfg.LaunchPrefix, opts.ExtraArgs, opts.CustomArgs) {
- commands = initializer.availableCommands()
+ } else {
+ proc.initialized = true
+ proc.initializedCommands = initializer.availableCommands()
+ if slashCommandsAllowed {
+ commands = proc.initializedCommands
+ }
}
}
blocks := []string{prompt}
if opts.SkillInvocation != nil {
blocks = opts.SkillInvocation.claudeTextBlocks(commands)
}
- err := writeClaudeInput(inputWriter, blocks...)
+ err := writeClaudeInput(proc.inputWriter, blocks...)
if err != nil {
- closeStdin()
+ turn.closeInput()
if supplements != nil {
cancel()
}
@@ -220,242 +203,58 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
defer cancel()
defer close(msgCh)
defer close(resCh)
- if mcpConfigPath != "" {
- defer cleanupMcpConfigTemp(mcpConfigPath)
- }
startTime := time.Now()
- var lastAssistantText string
- var finalResultText string
- sawResult := false
- resultIsError := false
- terminalReasonError := ""
- var sessionID string
- var lastUsageResult *claudeSDKMessage
- sawAsyncLaunch := false
- usage := make(map[string]TokenUsage)
- seenUsage := make(map[string]struct{})
- rateLimits := newRateLimitTracker(opts.OnRateLimits)
- eventCount := 0
- invalidEventCount := 0
- assistantEventCount := 0
- toolUseCount := 0
- unreadableAssistantCount := 0
- controlErrors := make(chan error, 1)
- var controlWrites sync.WaitGroup
- var controlMu sync.Mutex
- pendingControls := 0
- closeRequested := false
- closeAfterControls := func() {
- if initializer != nil {
- initializer.end()
- }
- controlMu.Lock()
- defer controlMu.Unlock()
- closeRequested = true
- if pendingControls == 0 {
- closeStdin()
- }
- }
- var stopAfterErrorResultOnce sync.Once
- // stopAfterErrorResult terminates a claude that outlives its error
- // result past the grace period, the same way cancellation does.
- stopAfterErrorResult := func() {
- select {
- case <-procDone:
- return
- case <-time.After(claudeErrorResultGrace()):
- }
- b.cfg.Logger.Warn("claude still running after an error result; terminating process group", "pid", cmd.Process.Pid)
- signalProcessGroup(cmd, syscall.SIGTERM)
- if !waitProcessGroupGone(cmd, claudeTerminateGrace()) {
- signalProcessGroup(cmd, syscall.SIGKILL)
- }
- _ = stdout.Close()
- }
-
- // On cancellation / timeout, terminate claude (and every MCP server and
- // tool subprocess it spawned) BEFORE unblocking the scanner. EOF stdin
- // to nudge a clean exit, then SIGTERM the whole process group, give it a
- // grace period, and SIGKILL the group if any member is still alive.
- // SIGKILL is uncatchable, so once delivered no group member can write
- // again — only then is it safe to close the stdout read end as a
- // last-resort unblock for a scanner a wedged descendant still keeps
- // open. WaitDelay is the final backstop (#5918).
- go func() {
- select {
- case <-procDone:
- return // finished on its own; nothing to terminate
- case <-runCtx.Done():
- }
- closeStdin()
- if cmd.Process != nil {
- signalProcessGroup(cmd, syscall.SIGTERM)
- // Escalate to a group SIGKILL unless the WHOLE process group has
- // exited within the grace window. This must key off the process
- // group, not procDone: procDone only means cmd.Wait() returned
- // for the leader, so a SIGTERM-ignoring descendant that does not
- // hold claude's stdout would let the leader exit, close procDone,
- // and skip the SIGKILL — leaking exactly the orphan this fix
- // targets. waitProcessGroupGone returns as soon as the group is
- // empty, so the graceful case adds no latency.
- if !waitProcessGroupGone(cmd, claudeTerminateGrace()) {
- signalProcessGroup(cmd, syscall.SIGKILL)
- }
- }
- _ = stdout.Close()
- }()
-
- scanner := newAgentStreamScanner(stdout)
- streamCoalescer := newClaudeStreamCoalescer(msgCh, nil)
-
- for scanner.Scan() {
- line := strings.TrimSpace(scanner.Text())
- if line == "" {
- continue
- }
-
- var msg claudeSDKMessage
- if err := json.Unmarshal([]byte(line), &msg); err != nil {
- invalidEventCount++
- continue
- }
- eventCount++
- switch msg.Type {
- case "stream_event":
- if msg.ParentToolUseID == "" {
- streamCoalescer.handleEvent(msg.Event)
- }
- case "assistant":
- assistantEventCount++
- turn := b.handleAssistantWithStream(msg, msgCh, usage, seenUsage, streamCoalescer)
- toolUseCount += turn.toolUses
- if !turn.understood {
- unreadableAssistantCount++
- }
- lastAssistantText = turn.resolveFallback(lastAssistantText)
- case "user":
- streamCoalescer.flushAll()
- if b.handleUser(msg, msgCh) {
- sawAsyncLaunch = true
- }
- case "rate_limit_event":
- if update, ok := parseClaudeRateLimitEvent(msg.RateLimitInfo); ok {
- rateLimits.apply(update)
- }
- case "system":
- if msg.SessionID != "" {
- sessionID = msg.SessionID
- }
- trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: sessionID})
- case "result":
- streamCoalescer.flushAll()
- sawResult = true
- finalResultText = msg.ResultText
- resultIsError = msg.IsError
- terminalReasonError = claudeTerminalReasonFailure(msg.TerminalReason, msg.ResultText)
- sessionID = msg.SessionID
- // A resume whose baseline capture failed cannot trust the
- // result's modelUsage: newer Claude Code restores the session's
- // cumulative counters on resume, so the reported total may span
- // every prior task (GH #9564), and without a baseline there is
- // no way to verify it is per-run. Keep the stream-derived
- // per-run usage in that case; the reported totals are recorded
- // in lastUsageResult only for the resume-rejected recapture
- // below, where the run is known to have started a fresh session
- // whose totals are its own.
- unverifiableBaseline := usageSnapshot == nil && opts.ResumeSessionID != ""
- var baseline map[string]TokenUsage
- if usageSnapshot != nil {
- baseline = usageSnapshot.baseline
- }
- if resultUsage, authoritative := claudeResultUsageSince(msg, opts.Model, baseline); authoritative {
- usageMsg := msg
- lastUsageResult = &usageMsg
- if !unverifiableBaseline {
- usage = resultUsage
- }
- }
- // Keep draining stdout while accepted control replies finish writing.
- // Once those replies drain, stdin closes; requests arriving after that
- // cannot be answered.
- closeAfterControls()
- if resultIsError || terminalReasonError != "" {
- stopAfterErrorResultOnce.Do(func() { go stopAfterErrorResult() })
- }
- case "log":
- if msg.Log != nil {
- trySend(msgCh, Message{
- Type: MessageLog,
- Level: msg.Log.Level,
- Content: msg.Log.Message,
- })
- }
- case "control_request":
- var reply func(io.Writer) error
- if supplements != nil {
- reply, _ = supplements.prepareHook(msg)
- }
- controlMu.Lock()
- pendingControls++
- controlMu.Unlock()
- controlWrites.Add(1)
- go func(msg claudeSDKMessage, reply func(io.Writer) error) {
- defer controlWrites.Done()
- defer func() {
- controlMu.Lock()
- defer controlMu.Unlock()
- pendingControls--
- if closeRequested && pendingControls == 0 {
- closeStdin()
- }
- }()
- if reply == nil {
- b.handleControlRequest(msg, inputWriter)
- return
- }
- if err := reply(inputWriter); err != nil {
- select {
- case controlErrors <- err:
- default:
- }
- cancel()
- }
- }(msg, reply)
- case "control_response":
- if initializer != nil {
- initializer.handleResponse(msg.Response)
- }
- }
- }
- streamCoalescer.flushAll()
- scanErr := scanner.Err()
- if scanErr != nil {
- // Scanner stopped consuming stdout. Close the pipe before Wait so a
- // child still writing a malformed/oversized event cannot deadlock on
- // the full OS pipe; the scanner error remains the primary failure.
- _ = stdout.Close()
- }
-
- closeStdin()
-
- // Wait for process exit, then release the cancellation handler.
- exitErr := cmd.Wait()
- close(procDone)
- // The leader is reaped; drop ownership. On Windows that closes the Job
- // Object, which kills anything still inside it — precisely what should
- // happen to a descendant that outlived the CLI (GH #7522).
- releaseProcessGroup(cmd)
- duration := time.Since(startTime)
- // writeDone is buffered (cap 1) and the writer always sends — by the
- // time cmd has exited, the prompt write has either succeeded, hit a
- // broken pipe, or been unblocked by the kill that ended cmd.
+ // A pooled process stays up between turns, so its turn ends at the
+ // result event. A one-shot process closes stdin after its result and
+ // the turn lasts until it exits, so anything it emits meanwhile still
+ // streams.
+ var resultSeen <-chan struct{}
+ if proc.pooled {
+ resultSeen = turn.resultCh
+ }
+ cancelledOrTimedOut := false
+ select {
+ case <-resultSeen:
+ case <-proc.procDone:
+ case <-runCtx.Done():
+ cancelledOrTimedOut = true
+ proc.terminate()
+ <-proc.procDone
+ }
+ turn.endInitializer()
+ // Detach before reading the turn's state or waiting on its control
+ // writes: a pooled process keeps emitting after its result event.
+ proc.setActiveTurn(nil)
+
+ turn.mu.Lock()
+ turn.coalescer.flushAll()
+ sawResult := turn.sawResult
+ resultIsError := turn.resultIsError
+ terminalReasonError := turn.terminalReasonError
+ sawAsyncLaunch := turn.sawAsyncLaunch
+ sessionID := turn.sessionID
+ lastAssistantText := turn.lastAssistantText
+ finalResultText := turn.finalResultText
+ lastUsageResult := turn.lastUsageResult
+ lastRawModelUsage := turn.lastRawModelUsage
+ usage := turn.usage
+ eventCount := turn.eventCount
+ invalidEventCount := turn.invalidEventCount
+ assistantEventCount := turn.assistantEventCount
+ toolUseCount := turn.toolUseCount
+ unreadableAssistantCount := turn.unreadableAssistantCount
+ turn.mu.Unlock()
+
+ // writeDone is buffered (cap 1) and the writer always sends — by now
+ // the prompt write has either succeeded, hit a broken pipe, or been
+ // unblocked by the kill that ended the process.
+ turn.controlWrites.Wait()
writeErr := <-writeDone
- controlWrites.Wait()
if writeErr == nil {
select {
- case writeErr = <-controlErrors:
+ case writeErr = <-turn.controlErrors:
default:
}
}
@@ -465,6 +264,36 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
terminalReasonError = fmt.Sprintf("claude input/control protocol failed: %v", writeErr)
}
+ proc.clearTaskEnv()
+
+ scanErr, exitErr := proc.getErrors()
+ parked := proc.pooled &&
+ sawResult &&
+ !resultIsError &&
+ terminalReasonError == "" &&
+ !sawAsyncLaunch &&
+ !cancelledOrTimedOut &&
+ writeErr == nil &&
+ scanErr == nil &&
+ runCtx.Err() == nil &&
+ sessionID != "" &&
+ proc.Alive()
+ if parked {
+ proc.sessionID = sessionID
+ if len(lastRawModelUsage) > 0 {
+ proc.lastCumulativeModelUsage = lastRawModelUsage
+ }
+ b.cfg.WarmPool.Park("claude", sessionID, proc)
+ } else {
+ // A pooled CLI still waiting for its next user frame exits on this
+ // stdin EOF instead of blocking for the error result grace window.
+ // A one-shot process has already exited; this releases its temp files.
+ proc.Close()
+ scanErr, exitErr = proc.getErrors()
+ }
+
+ duration := time.Since(startTime)
+
if !sawResult && usageSnapshot != nil {
appendedUsage, found, snapshotErr := usageSnapshot.appendedCostStateUsage()
switch {
@@ -497,12 +326,11 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
completionGuardError,
)
- // cmd.Wait() has returned — os/exec's stderr copy goroutine has
- // observed every byte claude wrote to stderr before exiting, so
- // stderrBuf.Tail() is safe to sample now. Attach the tail to any
- // non-empty failure message; callers upstream surface this as the
- // task's error field, which is the only place users see it.
- stderrTail := stderrBuf.Tail()
+ // Attach the stderr tail to any non-empty failure message; callers
+ // upstream surface this as the task's error field, which is the only
+ // place users see it. A process that exited has been reaped, so
+ // os/exec's stderr copy goroutine has observed every byte.
+ stderrTail := proc.stderrBuf.Tail()
if finalError != "" {
finalError = withAgentStderr(finalError, "claude", stderrTail)
}
@@ -524,7 +352,13 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
anthropicBaseURLConfigured: strings.TrimSpace(b.cfg.Env["ANTHROPIC_BASE_URL"]) != "",
})
- b.cfg.Logger.Info("claude finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
+ b.cfg.Logger.Info("claude finished",
+ "pid", proc.cmd.Process.Pid,
+ "warm_hit", warmHit,
+ "parked", parked,
+ "status", finalStatus,
+ "duration", duration.Round(time.Millisecond).String(),
+ )
// The account-binding 400 arrives in the result event (finalError);
// "no conversation found" is printed to stderr. Check both.
@@ -563,6 +397,214 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
return session, nil
}
+// claudeTurn is one turn's stream state. The process's stdout reader feeds it
+// events; Execute's lifecycle goroutine reads the outcome once the turn ends.
+type claudeTurn struct {
+ backend *claudeBackend
+ proc *claudeProcess
+ cancel context.CancelFunc
+ opts ExecOptions
+ msgCh chan Message
+ coalescer *claudeStreamCoalescer
+ supplements *claudeSupplementSession
+ initializer *claudeSupplementSession
+ usageSnapshot *claudeUsageSnapshot
+ baselineUsage map[string]TokenUsage
+ rateLimits *rateLimitTracker
+ controlWrites sync.WaitGroup
+ controlErrors chan error
+ resultCh chan struct{}
+ resultOnce sync.Once
+ stopAfterErrorResultOnce sync.Once
+
+ controlMu sync.Mutex
+ pendingControls int
+ closeRequested bool
+
+ mu sync.Mutex
+ lastAssistantText string
+ finalResultText string
+ sawResult bool
+ resultIsError bool
+ terminalReasonError string
+ sessionID string
+ lastUsageResult *claudeSDKMessage
+ lastRawModelUsage map[string]TokenUsage
+ sawAsyncLaunch bool
+ usage map[string]TokenUsage
+ seenUsage map[string]struct{}
+ eventCount int
+ invalidEventCount int
+ assistantEventCount int
+ toolUseCount int
+ unreadableAssistantCount int
+}
+
+func (t *claudeTurn) handleMessage(msg claudeSDKMessage) {
+ t.mu.Lock()
+ t.eventCount++
+ switch msg.Type {
+ case "stream_event":
+ if msg.ParentToolUseID == "" {
+ t.coalescer.handleEvent(msg.Event)
+ }
+ t.mu.Unlock()
+ case "assistant":
+ t.assistantEventCount++
+ turn := t.backend.handleAssistantWithStream(msg, t.msgCh, t.usage, t.seenUsage, t.coalescer)
+ t.toolUseCount += turn.toolUses
+ if !turn.understood {
+ t.unreadableAssistantCount++
+ }
+ t.lastAssistantText = turn.resolveFallback(t.lastAssistantText)
+ t.mu.Unlock()
+ case "user":
+ t.coalescer.flushAll()
+ if t.backend.handleUser(msg, t.msgCh) {
+ t.sawAsyncLaunch = true
+ }
+ t.mu.Unlock()
+ case "rate_limit_event":
+ rl := t.rateLimits
+ t.mu.Unlock()
+ if update, ok := parseClaudeRateLimitEvent(msg.RateLimitInfo); ok {
+ rl.apply(update)
+ }
+ case "system":
+ if msg.SessionID != "" {
+ t.sessionID = msg.SessionID
+ }
+ sid := t.sessionID
+ t.mu.Unlock()
+ trySend(t.msgCh, Message{Type: MessageStatus, Status: "running", SessionID: sid})
+ case "result":
+ t.coalescer.flushAll()
+ t.sawResult = true
+ t.finalResultText = msg.ResultText
+ t.resultIsError = msg.IsError
+ t.terminalReasonError = claudeTerminalReasonFailure(msg.TerminalReason, msg.ResultText)
+ if msg.SessionID != "" {
+ t.sessionID = msg.SessionID
+ }
+ if len(msg.ModelUsage) > 0 {
+ t.lastRawModelUsage = claudeModelUsage(msg.ModelUsage)
+ }
+ // A resume whose baseline capture failed cannot trust the result's
+ // modelUsage: newer Claude Code restores the session's cumulative
+ // counters on resume, so the reported total may span every prior task
+ // (GH #9564), and without a baseline there is no way to verify it is
+ // per-run. Keep the stream-derived per-run usage in that case; the
+ // reported totals are recorded in lastUsageResult only for the
+ // resume-rejected recapture, where the run is known to have started a
+ // fresh session whose totals are its own.
+ unverifiableBaseline := t.usageSnapshot == nil && t.baselineUsage == nil && t.opts.ResumeSessionID != ""
+ baseline := t.baselineUsage
+ if baseline == nil && t.usageSnapshot != nil {
+ baseline = t.usageSnapshot.baseline
+ }
+ if resultUsage, authoritative := claudeResultUsageSince(msg, t.opts.Model, baseline); authoritative {
+ usageMsg := msg
+ t.lastUsageResult = &usageMsg
+ if !unverifiableBaseline {
+ t.usage = resultUsage
+ }
+ }
+ failed := t.resultIsError || t.terminalReasonError != ""
+ t.mu.Unlock()
+ t.resultOnce.Do(func() { close(t.resultCh) })
+ if !t.proc.pooled {
+ // Keep draining stdout while accepted control replies finish
+ // writing. Once those replies drain, stdin closes; requests
+ // arriving after that cannot be answered.
+ t.closeInputAfterControls()
+ if failed {
+ t.stopAfterErrorResultOnce.Do(func() { go t.proc.stopAfterErrorResult() })
+ }
+ }
+ case "log":
+ t.mu.Unlock()
+ if msg.Log != nil {
+ trySend(t.msgCh, Message{
+ Type: MessageLog,
+ Level: msg.Log.Level,
+ Content: msg.Log.Message,
+ })
+ }
+ case "control_request":
+ supplements := t.supplements
+ t.mu.Unlock()
+ var reply func(io.Writer) error
+ if supplements != nil {
+ reply, _ = supplements.prepareHook(msg)
+ }
+ t.controlMu.Lock()
+ t.pendingControls++
+ t.controlMu.Unlock()
+ t.controlWrites.Add(1)
+ go func(msg claudeSDKMessage, reply func(io.Writer) error) {
+ defer t.controlWrites.Done()
+ defer t.controlReplied()
+ if reply == nil {
+ t.backend.handleControlRequest(msg, t.proc.inputWriter)
+ return
+ }
+ if err := reply(t.proc.inputWriter); err != nil {
+ select {
+ case t.controlErrors <- err:
+ default:
+ }
+ t.cancel()
+ }
+ }(msg, reply)
+ case "control_response":
+ init := t.initializer
+ t.mu.Unlock()
+ if init != nil {
+ init.handleResponse(msg.Response)
+ }
+ default:
+ t.mu.Unlock()
+ }
+}
+
+func (t *claudeTurn) noteInvalidEvent() {
+ t.mu.Lock()
+ t.invalidEventCount++
+ t.mu.Unlock()
+}
+
+func (t *claudeTurn) endInitializer() {
+ if t.initializer != nil {
+ t.initializer.end()
+ }
+}
+
+// closeInput EOFs the process's stdin and ends the initializer so a handshake
+// still waiting for its reply gives up.
+func (t *claudeTurn) closeInput() {
+ t.proc.closeStdin()
+ t.endInitializer()
+}
+
+func (t *claudeTurn) closeInputAfterControls() {
+ t.endInitializer()
+ t.controlMu.Lock()
+ defer t.controlMu.Unlock()
+ t.closeRequested = true
+ if t.pendingControls == 0 {
+ t.closeInput()
+ }
+}
+
+func (t *claudeTurn) controlReplied() {
+ t.controlMu.Lock()
+ defer t.controlMu.Unlock()
+ t.pendingControls--
+ if t.closeRequested && t.pendingControls == 0 {
+ t.closeInput()
+ }
+}
+
func (b *claudeBackend) handleAssistant(msg claudeSDKMessage, ch chan<- Message, usage map[string]TokenUsage, seenUsage map[string]struct{}) assistantTurn {
return b.handleAssistantWithStream(msg, ch, usage, seenUsage, nil)
}
diff --git a/server/pkg/agent/claude_pool.go b/server/pkg/agent/claude_pool.go
deleted file mode 100644
index 47e2635604..0000000000
--- a/server/pkg/agent/claude_pool.go
+++ /dev/null
@@ -1,729 +0,0 @@
-package agent
-
-import (
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "log/slog"
- "os"
- "os/exec"
- "path/filepath"
- "strings"
- "sync"
- "sync/atomic"
- "syscall"
- "time"
-)
-
-type claudeWarmTurn struct {
- backend *claudeBackend
- runCtx context.Context
- cancel context.CancelFunc
- opts ExecOptions
- msgCh chan Message
- coalescer *claudeStreamCoalescer
- inputWriter *claudeInputWriter
- supplements *claudeSupplementSession
- initializer *claudeSupplementSession
- usageSnapshot *claudeUsageSnapshot
- baselineUsage map[string]TokenUsage
- rateLimits *rateLimitTracker
- controlWrites sync.WaitGroup
- controlErrors chan error
- resultCh chan struct{}
- resultOnce sync.Once
-
- mu sync.Mutex
- lastAssistantText string
- finalResultText string
- sawResult bool
- resultIsError bool
- terminalReasonError string
- sessionID string
- lastUsageResult *claudeSDKMessage
- lastRawModelUsage map[string]TokenUsage
- sawAsyncLaunch bool
- usage map[string]TokenUsage
- seenUsage map[string]struct{}
- eventCount int
- invalidEventCount int
- assistantEventCount int
- toolUseCount int
- unreadableAssistantCount int
-}
-
-func (t *claudeWarmTurn) handleMessage(msg claudeSDKMessage) {
- t.mu.Lock()
- t.eventCount++
- switch msg.Type {
- case "stream_event":
- if msg.ParentToolUseID == "" {
- t.coalescer.handleEvent(msg.Event)
- }
- t.mu.Unlock()
- case "assistant":
- t.assistantEventCount++
- turn := t.backend.handleAssistantWithStream(msg, t.msgCh, t.usage, t.seenUsage, t.coalescer)
- t.toolUseCount += turn.toolUses
- if !turn.understood {
- t.unreadableAssistantCount++
- }
- t.lastAssistantText = turn.resolveFallback(t.lastAssistantText)
- t.mu.Unlock()
- case "user":
- t.coalescer.flushAll()
- if t.backend.handleUser(msg, t.msgCh) {
- t.sawAsyncLaunch = true
- }
- t.mu.Unlock()
- case "rate_limit_event":
- rl := t.rateLimits
- t.mu.Unlock()
- if update, ok := parseClaudeRateLimitEvent(msg.RateLimitInfo); ok {
- rl.apply(update)
- }
- case "system":
- if msg.SessionID != "" {
- t.sessionID = msg.SessionID
- }
- sid := t.sessionID
- t.mu.Unlock()
- trySend(t.msgCh, Message{Type: MessageStatus, Status: "running", SessionID: sid})
- case "result":
- t.coalescer.flushAll()
- t.sawResult = true
- t.finalResultText = msg.ResultText
- t.resultIsError = msg.IsError
- t.terminalReasonError = claudeTerminalReasonFailure(msg.TerminalReason, msg.ResultText)
- if msg.SessionID != "" {
- t.sessionID = msg.SessionID
- }
- if len(msg.ModelUsage) > 0 {
- t.lastRawModelUsage = claudeModelUsage(msg.ModelUsage)
- }
- unverifiableBaseline := t.usageSnapshot == nil && t.baselineUsage == nil && t.opts.ResumeSessionID != ""
- baseline := t.baselineUsage
- if baseline == nil && t.usageSnapshot != nil {
- baseline = t.usageSnapshot.baseline
- }
- if resultUsage, authoritative := claudeResultUsageSince(msg, t.opts.Model, baseline); authoritative {
- usageMsg := msg
- t.lastUsageResult = &usageMsg
- if !unverifiableBaseline {
- t.usage = resultUsage
- }
- }
- t.mu.Unlock()
- t.resultOnce.Do(func() { close(t.resultCh) })
- case "log":
- t.mu.Unlock()
- if msg.Log != nil {
- trySend(t.msgCh, Message{
- Type: MessageLog,
- Level: msg.Log.Level,
- Content: msg.Log.Message,
- })
- }
- case "control_request":
- supplements := t.supplements
- t.mu.Unlock()
- var reply func(io.Writer) error
- if supplements != nil {
- reply, _ = supplements.prepareHook(msg)
- }
- t.controlWrites.Add(1)
- go func(msg claudeSDKMessage, reply func(io.Writer) error) {
- defer t.controlWrites.Done()
- if reply == nil {
- t.backend.handleControlRequest(msg, t.inputWriter)
- return
- }
- if err := reply(t.inputWriter); err != nil {
- select {
- case t.controlErrors <- err:
- default:
- }
- t.cancel()
- }
- }(msg, reply)
- case "control_response":
- init := t.initializer
- t.mu.Unlock()
- if init != nil {
- init.handleResponse(msg.Response)
- }
- default:
- t.mu.Unlock()
- }
-}
-
-func (t *claudeWarmTurn) noteInvalidEvent() {
- t.mu.Lock()
- t.invalidEventCount++
- t.mu.Unlock()
-}
-
-type warmClaudeProcess struct {
- fingerprint string
- sessionID string
- cmd *exec.Cmd
- stdin io.WriteCloser
- inputWriter *claudeInputWriter
- stdout io.ReadCloser
- stderrBuf *stderrTail
- procDone chan struct{}
- mcpConfigPath string
- sessionDir string
- taskEnvFile string
- sessionTempDir string
- logger *slog.Logger
- initialized bool
- initializedCommands map[string]bool
- lastCumulativeModelUsage map[string]TokenUsage
-
- turnMu sync.Mutex
- activeTurn *claudeWarmTurn
- scanErr error
- exitErr error
-
- closed atomic.Bool
- closeOnce sync.Once
-}
-
-func (p *warmClaudeProcess) Fingerprint() string { return p.fingerprint }
-
-func (p *warmClaudeProcess) Alive() bool {
- if p.closed.Load() {
- return false
- }
- select {
- case <-p.procDone:
- return false
- default:
- return true
- }
-}
-
-func (p *warmClaudeProcess) setActiveTurn(t *claudeWarmTurn) {
- p.turnMu.Lock()
- p.activeTurn = t
- p.turnMu.Unlock()
-}
-
-func (p *warmClaudeProcess) getErrors() (scanErr, exitErr error) {
- p.turnMu.Lock()
- defer p.turnMu.Unlock()
- return p.scanErr, p.exitErr
-}
-
-func (p *warmClaudeProcess) Close() bool {
- p.closeOnce.Do(func() {
- p.closed.Store(true)
- _ = ClearTaskEnvFile(p.taskEnvFile)
- _ = p.stdin.Close()
-
- // Give the CLI a brief window to exit cleanly on stdin EOF before
- // signalling the process group, mirroring claudeBackend.Execute.
- select {
- case <-p.procDone:
- case <-time.After(1500 * time.Millisecond):
- if p.cmd.Process != nil {
- signalProcessGroup(p.cmd, syscall.SIGTERM)
- if !waitProcessGroupGone(p.cmd, claudeTerminateGrace()) {
- signalProcessGroup(p.cmd, syscall.SIGKILL)
- }
- }
- _ = p.stdout.Close()
- <-p.procDone
- }
-
- if p.mcpConfigPath != "" {
- cleanupMcpConfigTemp(p.mcpConfigPath)
- }
- if p.sessionDir != "" {
- _ = os.RemoveAll(p.sessionDir)
- }
- })
- return true
-}
-
-func (p *warmClaudeProcess) terminateImmediately() {
- p.closed.Store(true)
- _ = p.stdin.Close()
- if p.cmd.Process != nil {
- signalProcessGroup(p.cmd, syscall.SIGTERM)
- if !waitProcessGroupGone(p.cmd, claudeTerminateGrace()) {
- signalProcessGroup(p.cmd, syscall.SIGKILL)
- }
- }
- _ = p.stdout.Close()
-}
-
-func (b *claudeBackend) executeWarm(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {
- execPath := b.cfg.ExecutablePath
- if execPath == "" {
- execPath = "claude"
- }
- if _, err := exec.LookPath(execPath); err != nil {
- return nil, fmt.Errorf("claude executable not found at %q: %w", execPath, err)
- }
-
- timeout := opts.Timeout
- runCtx, cancel := runContext(ctx, timeout)
-
- // Build fingerprint args without --resume so a Turn-1 spawned process and
- // a Turn-2 resumed request for the same session share an identical key.
- optsForFP := opts
- optsForFP.ResumeSessionID = ""
- argsForFP := buildClaudeArgs(optsForFP, b.cfg.Logger)
- var configFiles []string
- if opts.ClaudeSettingsPath != "" {
- configFiles = append(configFiles, opts.ClaudeSettingsPath)
- }
- fingerprint := computeWarmSessionFingerprint(WarmSessionFingerprintInput{
- Provider: "claude",
- Executable: execPath,
- LaunchPrefix: b.cfg.LaunchPrefix,
- Args: argsForFP,
- Cwd: opts.Cwd,
- Model: opts.Model,
- ThinkingLevel: opts.ThinkingLevel,
- McpConfig: opts.McpConfig,
- ConfigFiles: configFiles,
- BriefHash: opts.WarmPoolBriefHash,
- Env: b.cfg.Env,
- ExtraFlags: []string{fmt.Sprintf("supplement=%t", opts.EnableTaskSupplement)},
- })
-
- var warmProc *warmClaudeProcess
- warmHit := false
- if opts.ResumeSessionID != "" {
- if acquired := b.cfg.WarmPool.Acquire("claude", opts.ResumeSessionID, fingerprint); acquired != nil {
- if candidate, ok := acquired.(*warmClaudeProcess); ok {
- if err := WriteTaskEnvFile(candidate.taskEnvFile, b.cfg.Env); err != nil {
- b.cfg.Logger.Warn("warm claude: failed to refresh task env overlay; evicting", "error", err)
- candidate.Close()
- } else {
- warmProc = candidate
- warmHit = true
- }
- } else {
- acquired.Close()
- }
- }
- }
-
- var usageSnapshot *claudeUsageSnapshot
- if !warmHit {
- var err error
- warmProc, usageSnapshot, err = b.spawnWarmClaudeProcess(execPath, opts, fingerprint)
- if err != nil {
- cancel()
- return nil, err
- }
- }
-
- msgCh := make(chan Message, 256)
- resCh := make(chan Result, 1)
-
- var supplements *claudeSupplementSession
- if opts.EnableTaskSupplement {
- supplements = newClaudeSupplementSession(runCtx)
- }
- initializer := supplements
- if initializer == nil && opts.SkillInvocation != nil {
- initializer = newClaudeSupplementSession(runCtx)
- }
-
- var baselineUsage map[string]TokenUsage
- if warmHit && len(warmProc.lastCumulativeModelUsage) > 0 {
- baselineUsage = make(map[string]TokenUsage, len(warmProc.lastCumulativeModelUsage))
- for k, v := range warmProc.lastCumulativeModelUsage {
- baselineUsage[k] = v
- }
- }
-
- turn := &claudeWarmTurn{
- backend: b,
- runCtx: runCtx,
- cancel: cancel,
- opts: opts,
- msgCh: msgCh,
- coalescer: newClaudeStreamCoalescer(msgCh, nil),
- inputWriter: warmProc.inputWriter,
- supplements: supplements,
- initializer: initializer,
- usageSnapshot: usageSnapshot,
- baselineUsage: baselineUsage,
- rateLimits: newRateLimitTracker(opts.OnRateLimits),
- controlErrors: make(chan error, 1),
- resultCh: make(chan struct{}),
- usage: make(map[string]TokenUsage),
- seenUsage: make(map[string]struct{}),
- }
- if warmHit {
- turn.sessionID = warmProc.sessionID
- }
- warmProc.setActiveTurn(turn)
-
- if warmHit {
- b.cfg.Logger.Info("claude warm session reused",
- "pid", warmProc.cmd.Process.Pid,
- "session_id", warmProc.sessionID,
- "cwd", opts.Cwd,
- "model", opts.Model,
- )
- trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: warmProc.sessionID})
- }
-
- writeDone := make(chan error, 1)
- go func() {
- var commands map[string]bool
- if warmHit {
- if warmProc.initialized && !slashCommandsDisabled(b.cfg.LaunchPrefix, opts.ExtraArgs, opts.CustomArgs) {
- commands = warmProc.initializedCommands
- }
- } else if initializer != nil {
- if initErr := initializer.initialize(warmProc.inputWriter, opts.HandshakeTimeout, opts.EnableTaskSupplement); initErr != nil {
- b.cfg.Logger.Warn("Claude initialization unavailable; continuing with text input", "error", initErr)
- initializer.end()
- } else {
- warmProc.initialized = true
- warmProc.initializedCommands = initializer.availableCommands()
- if !slashCommandsDisabled(b.cfg.LaunchPrefix, opts.ExtraArgs, opts.CustomArgs) {
- commands = warmProc.initializedCommands
- }
- }
- }
- blocks := []string{prompt}
- if opts.SkillInvocation != nil {
- blocks = opts.SkillInvocation.claudeTextBlocks(commands)
- }
- err := writeClaudeInput(warmProc.inputWriter, blocks...)
- if err != nil {
- if supplements != nil {
- cancel()
- }
- }
- writeDone <- err
- }()
-
- go func() {
- defer cancel()
- defer close(msgCh)
- defer close(resCh)
-
- startTime := time.Now()
-
- // Wait for either the turn's result event, process exit, or context
- // cancellation/timeout.
- var cancelledOrTimedOut bool
- select {
- case <-turn.resultCh:
- case <-warmProc.procDone:
- case <-runCtx.Done():
- cancelledOrTimedOut = true
- warmProc.terminateImmediately()
- <-warmProc.procDone
- }
-
- if initializer != nil {
- initializer.end()
- }
-
- turn.mu.Lock()
- turn.coalescer.flushAll()
- sawResult := turn.sawResult
- resultIsError := turn.resultIsError
- terminalReasonError := turn.terminalReasonError
- sawAsyncLaunch := turn.sawAsyncLaunch
- sessionID := turn.sessionID
- lastAssistantText := turn.lastAssistantText
- finalResultText := turn.finalResultText
- lastUsageResult := turn.lastUsageResult
- lastRawModelUsage := turn.lastRawModelUsage
- usage := turn.usage
- eventCount := turn.eventCount
- invalidEventCount := turn.invalidEventCount
- assistantEventCount := turn.assistantEventCount
- toolUseCount := turn.toolUseCount
- unreadableAssistantCount := turn.unreadableAssistantCount
- turn.mu.Unlock()
-
- turn.controlWrites.Wait()
- writeErr := <-writeDone
- if writeErr == nil {
- select {
- case writeErr = <-turn.controlErrors:
- default:
- }
- }
-
- if supplements != nil && writeErr != nil && ctx.Err() == nil && terminalReasonError == "" && !errors.Is(runCtx.Err(), context.DeadlineExceeded) {
- terminalReasonError = fmt.Sprintf("claude input/control protocol failed: %v", writeErr)
- }
-
- // Detach the turn before deciding to park or close.
- warmProc.setActiveTurn(nil)
- _ = ClearTaskEnvFile(warmProc.taskEnvFile)
-
- scanErr, exitErr := warmProc.getErrors()
- canPark := sawResult &&
- !resultIsError &&
- terminalReasonError == "" &&
- !sawAsyncLaunch &&
- !cancelledOrTimedOut &&
- writeErr == nil &&
- scanErr == nil &&
- runCtx.Err() == nil &&
- sessionID != "" &&
- warmProc.Alive()
-
- if canPark {
- warmProc.sessionID = sessionID
- if len(lastRawModelUsage) > 0 {
- warmProc.lastCumulativeModelUsage = lastRawModelUsage
- }
- b.cfg.WarmPool.Park("claude", sessionID, warmProc)
- } else {
- // Close stdin immediately so a persistent stream-json CLI waiting for
- // the next user frame exits on EOF instead of blocking for the error
- // result grace window.
- warmProc.Close()
- scanErr, exitErr = warmProc.getErrors()
- }
-
- duration := time.Since(startTime)
-
- if !sawResult && usageSnapshot != nil {
- appendedUsage, found, snapshotErr := usageSnapshot.appendedCostStateUsage()
- switch {
- case snapshotErr != nil:
- b.cfg.Logger.Warn("claude final cost state unavailable; keeping stream usage fallback", "error", snapshotErr)
- case found:
- usage = subtractClaudeUsage(appendedUsage, usageSnapshot.baseline)
- }
- }
-
- completionGuardError := ""
- if sawAsyncLaunch {
- completionGuardError = "claude launched an async background task; Multica-managed runs require foreground execution"
- }
- finalStatus, finalOutput, finalError := finalizeStreamResult(
- "claude",
- timeout,
- runCtx.Err(),
- writeErr,
- exitErr,
- sessionID,
- streamTerminalState{
- lastAssistantText: lastAssistantText,
- finalResultText: finalResultText,
- sawResult: sawResult,
- resultIsError: resultIsError,
- scanErr: scanErr,
- terminalReasonError: terminalReasonError,
- },
- completionGuardError,
- )
-
- stderrTail := warmProc.stderrBuf.Tail()
- if finalError != "" {
- finalError = withAgentStderr(finalError, "claude", stderrTail)
- }
- logStreamProtocolObservation(b.cfg.Logger, streamProtocolObservation{
- provider: "claude",
- cliVersion: b.cfg.CLIVersion,
- model: opts.Model,
- exitCode: streamProcessExitCode(exitErr),
- eventCount: eventCount,
- invalidEventCount: invalidEventCount,
- assistantEventCount: assistantEventCount,
- toolUseCount: toolUseCount,
- sawResult: sawResult,
- resultIsError: resultIsError,
- resultBytes: len(finalResultText),
- lastAssistantBytes: len(lastAssistantText),
- scannerError: scanErr != nil,
- unreadableAssistantCount: unreadableAssistantCount,
- anthropicBaseURLConfigured: strings.TrimSpace(b.cfg.Env["ANTHROPIC_BASE_URL"]) != "",
- })
-
- b.cfg.Logger.Info("claude finished",
- "pid", warmProc.cmd.Process.Pid,
- "warm_hit", warmHit,
- "parked", canPark,
- "status", finalStatus,
- "duration", duration.Round(time.Millisecond).String(),
- )
-
- resumeRejected := resumeWasRejected(opts.ResumeSessionID, sessionID, finalStatus == "failed", finalError, stderrTail)
- reportedSessionID := resolveSessionID(opts.ResumeSessionID, sessionID, finalStatus == "failed", finalError, stderrTail)
- if resumeRejected {
- if lastUsageResult != nil {
- if resultUsage, authoritative := claudeResultUsageSince(*lastUsageResult, opts.Model, nil); authoritative {
- usage = resultUsage
- }
- }
- b.cfg.Logger.Info("claude resume was rejected; dropping session id and signalling fresh-session retry",
- "requested_resume", opts.ResumeSessionID,
- "emitted_session", sessionID,
- )
- }
-
- resCh <- Result{
- Status: finalStatus,
- Output: finalOutput,
- Error: finalError,
- DurationMs: duration.Milliseconds(),
- SessionID: reportedSessionID,
- Usage: usage,
- ResumeRejected: resumeRejected,
- }
- }()
-
- session := &Session{Messages: msgCh, Result: resCh}
- if supplements != nil {
- session.Supplement = supplements.supplement
- session.SupplementReady = supplements.ready
- }
- return session, nil
-}
-
-func (b *claudeBackend) spawnWarmClaudeProcess(execPath string, opts ExecOptions, fingerprint string) (*warmClaudeProcess, *claudeUsageSnapshot, error) {
- sessionDir, err := os.MkdirTemp("", "multica-claude-warm-*")
- if err != nil {
- return nil, nil, fmt.Errorf("create warm claude session dir: %w", err)
- }
- sessionTempDir := filepath.Join(sessionDir, "tmp")
- if err := os.MkdirAll(sessionTempDir, 0o700); err != nil {
- _ = os.RemoveAll(sessionDir)
- return nil, nil, fmt.Errorf("create warm claude temp dir: %w", err)
- }
- taskEnvFile := filepath.Join(sessionDir, "task-env.json")
- if err := WriteTaskEnvFile(taskEnvFile, b.cfg.Env); err != nil {
- _ = os.RemoveAll(sessionDir)
- return nil, nil, fmt.Errorf("write warm claude task env overlay: %w", err)
- }
-
- args := buildClaudeArgs(opts, b.cfg.Logger)
- var mcpConfigPath string
- if hasManagedMcpConfig(opts.McpConfig) {
- path, err := writeMcpConfigToTemp(opts.McpConfig)
- if err != nil {
- _ = os.RemoveAll(sessionDir)
- return nil, nil, err
- }
- mcpConfigPath = path
- args = append(args, "--mcp-config", mcpConfigPath)
- }
-
- cleanupOnErr := func() {
- if mcpConfigPath != "" {
- cleanupMcpConfigTemp(mcpConfigPath)
- }
- _ = os.RemoveAll(sessionDir)
- }
-
- cmd := b.cfg.commandAt(execPath).exec(context.Background(), args...)
- hideAgentWindow(cmd)
- cmd.Cancel = func() error { return nil }
- b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(args))
- cmd.WaitDelay = 10 * time.Second
- if opts.Cwd != "" {
- cmd.Dir = opts.Cwd
- }
- cmd.Env = buildEnv(PreparePooledChildEnv(b.cfg.Env, taskEnvFile, sessionTempDir))
- if err := claudeRootSudoPreflight(args, cmd.Env); err != nil {
- cleanupOnErr()
- return nil, nil, err
- }
-
- var usageSnapshot *claudeUsageSnapshot
- if opts.ResumeSessionID != "" {
- snapshot, snapshotErr := captureClaudeUsageSnapshot(cmd.Env, cmd.Dir, opts.ResumeSessionID)
- if snapshotErr != nil {
- b.cfg.Logger.Warn("claude usage baseline unavailable; ignoring reported session totals, keeping per-run stream usage", "error", snapshotErr)
- } else {
- usageSnapshot = snapshot
- }
- }
-
- stdout, err := cmd.StdoutPipe()
- if err != nil {
- cleanupOnErr()
- return nil, nil, fmt.Errorf("claude stdout pipe: %w", err)
- }
- stdin, err := cmd.StdinPipe()
- if err != nil {
- cleanupOnErr()
- return nil, nil, fmt.Errorf("claude stdin pipe: %w", err)
- }
- stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[claude:stderr] "), agentStderrTailBytes)
- cmd.Stderr = stderrBuf
-
- if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
- _ = stdin.Close()
- cleanupOnErr()
- return nil, nil, fmt.Errorf("start claude: %w", err)
- }
-
- b.cfg.Logger.Info("claude started", "warm_pool", true, "pid", cmd.Process.Pid, "cwd", opts.Cwd, "model", opts.Model)
-
- proc := &warmClaudeProcess{
- fingerprint: fingerprint,
- cmd: cmd,
- stdin: stdin,
- inputWriter: &claudeInputWriter{w: stdin},
- stdout: stdout,
- stderrBuf: stderrBuf,
- procDone: make(chan struct{}),
- mcpConfigPath: mcpConfigPath,
- sessionDir: sessionDir,
- taskEnvFile: taskEnvFile,
- sessionTempDir: sessionTempDir,
- logger: b.cfg.Logger,
- }
-
- go func() {
- defer close(proc.procDone)
- scanner := newAgentStreamScanner(stdout)
- for scanner.Scan() {
- line := strings.TrimSpace(scanner.Text())
- if line == "" {
- continue
- }
- var msg claudeSDKMessage
- if err := json.Unmarshal([]byte(line), &msg); err != nil {
- proc.turnMu.Lock()
- turn := proc.activeTurn
- proc.turnMu.Unlock()
- if turn != nil {
- turn.noteInvalidEvent()
- }
- continue
- }
- proc.turnMu.Lock()
- turn := proc.activeTurn
- proc.turnMu.Unlock()
- if turn != nil {
- turn.handleMessage(msg)
- }
- }
- scanErr := scanner.Err()
- if scanErr != nil {
- _ = stdout.Close()
- }
- _ = stdin.Close()
- exitErr := cmd.Wait()
- releaseProcessGroup(cmd)
- proc.turnMu.Lock()
- proc.scanErr = scanErr
- proc.exitErr = exitErr
- proc.turnMu.Unlock()
- }()
-
- return proc, usageSnapshot, nil
-}
diff --git a/server/pkg/agent/claude_process.go b/server/pkg/agent/claude_process.go
new file mode 100644
index 0000000000..feb3edd112
--- /dev/null
+++ b/server/pkg/agent/claude_process.go
@@ -0,0 +1,377 @@
+package agent
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "syscall"
+ "time"
+)
+
+// claudeProcess is one Claude Code stream-json process. A run either spawns
+// one or, when the warm pool is enabled, acquires one an earlier turn of the
+// same session parked; the turn lifecycle in Execute is the same for both.
+//
+// A pooled process outlives the turn that spawned it: it reads volatile task
+// credentials from a per-session overlay file and owns a private session dir.
+// A one-shot process inherits the task env directly and exits with its turn.
+type claudeProcess struct {
+ pooled bool
+ fingerprint string
+ sessionID string
+ cmd *exec.Cmd
+ stdin io.WriteCloser
+ stdinOnce sync.Once
+ inputWriter *claudeInputWriter
+ stdout io.ReadCloser
+ stderrBuf *stderrTail
+ procDone chan struct{}
+ mcpConfigPath string
+ sessionDir string
+ taskEnvFile string
+ logger *slog.Logger
+ initialized bool
+ initializedCommands map[string]bool
+ lastCumulativeModelUsage map[string]TokenUsage
+
+ turnMu sync.Mutex
+ activeTurn *claudeTurn
+ scanErr error
+ exitErr error
+
+ closed atomic.Bool
+ closeOnce sync.Once
+}
+
+func (p *claudeProcess) Fingerprint() string { return p.fingerprint }
+
+func (p *claudeProcess) Alive() bool {
+ if p.closed.Load() {
+ return false
+ }
+ select {
+ case <-p.procDone:
+ return false
+ default:
+ return true
+ }
+}
+
+func (p *claudeProcess) setActiveTurn(t *claudeTurn) {
+ p.turnMu.Lock()
+ p.activeTurn = t
+ p.turnMu.Unlock()
+}
+
+// dispatch hands an event to the active turn while holding turnMu, so once
+// setActiveTurn(nil) returns no event can touch the finished turn's channels
+// or WaitGroup. The handlers never block and never take turnMu.
+func (p *claudeProcess) dispatch(deliver func(*claudeTurn)) {
+ p.turnMu.Lock()
+ defer p.turnMu.Unlock()
+ if p.activeTurn != nil {
+ deliver(p.activeTurn)
+ }
+}
+
+func (p *claudeProcess) getErrors() (scanErr, exitErr error) {
+ p.turnMu.Lock()
+ defer p.turnMu.Unlock()
+ return p.scanErr, p.exitErr
+}
+
+func (p *claudeProcess) closeStdin() {
+ p.stdinOnce.Do(func() { _ = p.stdin.Close() })
+}
+
+// clearTaskEnv drops the finished turn's credentials from a pooled process's
+// overlay so nothing it does while idle can act as that task.
+func (p *claudeProcess) clearTaskEnv() {
+ if p.taskEnvFile != "" {
+ _ = ClearTaskEnvFile(p.taskEnvFile)
+ }
+}
+
+// Close shuts the process down and removes its temp files. It is also the
+// release step for a one-shot process that has already exited.
+func (p *claudeProcess) Close() bool {
+ p.closeOnce.Do(func() {
+ p.closed.Store(true)
+ p.clearTaskEnv()
+ p.closeStdin()
+
+ // Give the CLI a brief window to exit cleanly on stdin EOF before
+ // signalling the process group.
+ select {
+ case <-p.procDone:
+ case <-time.After(1500 * time.Millisecond):
+ if p.cmd.Process != nil {
+ p.signalProcessTree()
+ }
+ <-p.procDone
+ }
+
+ if p.mcpConfigPath != "" {
+ cleanupMcpConfigTemp(p.mcpConfigPath)
+ }
+ if p.sessionDir != "" {
+ _ = os.RemoveAll(p.sessionDir)
+ }
+ })
+ return true
+}
+
+// terminate stops the process on cancellation or timeout. It EOFs stdin to
+// nudge a clean exit, then signals the whole process group so every MCP server
+// and tool subprocess claude spawned goes with it.
+func (p *claudeProcess) terminate() {
+ p.closed.Store(true)
+ p.closeStdin()
+ if p.cmd.Process != nil {
+ p.signalProcessTree()
+ }
+}
+
+// stopAfterErrorResult terminates a one-shot claude that outlives its error
+// result past the grace period, the same way cancellation does.
+func (p *claudeProcess) stopAfterErrorResult() {
+ select {
+ case <-p.procDone:
+ return
+ case <-time.After(claudeErrorResultGrace()):
+ }
+ p.logger.Warn("claude still running after an error result; terminating process group", "pid", p.cmd.Process.Pid)
+ p.signalProcessTree()
+}
+
+// signalProcessTree SIGTERMs the process group, escalates to SIGKILL unless
+// the whole group exits within the grace window, then closes stdout to unblock
+// a reader a wedged descendant still holds open.
+//
+// The escalation keys off the process group, not procDone: procDone only means
+// cmd.Wait() returned for the leader, so a SIGTERM-ignoring descendant that
+// does not hold claude's stdout would otherwise skip the SIGKILL and leak.
+// SIGKILL is uncatchable, so once delivered no group member can write again
+// and closing stdout is safe. WaitDelay is the final backstop (#5918).
+func (p *claudeProcess) signalProcessTree() {
+ signalProcessGroup(p.cmd, syscall.SIGTERM)
+ if !waitProcessGroupGone(p.cmd, claudeTerminateGrace()) {
+ signalProcessGroup(p.cmd, syscall.SIGKILL)
+ }
+ _ = p.stdout.Close()
+}
+
+func (b *claudeBackend) spawnClaudeProcess(ctx context.Context, execPath string, opts ExecOptions, pooled bool, fingerprint string) (*claudeProcess, *claudeUsageSnapshot, error) {
+ var sessionDir, taskEnvFile string
+ childEnv := b.cfg.Env
+ if pooled {
+ var err error
+ sessionDir, err = os.MkdirTemp("", "multica-claude-warm-*")
+ if err != nil {
+ return nil, nil, fmt.Errorf("create warm claude session dir: %w", err)
+ }
+ sessionTempDir := filepath.Join(sessionDir, "tmp")
+ if err := os.MkdirAll(sessionTempDir, 0o700); err != nil {
+ _ = os.RemoveAll(sessionDir)
+ return nil, nil, fmt.Errorf("create warm claude temp dir: %w", err)
+ }
+ taskEnvFile = filepath.Join(sessionDir, "task-env.json")
+ if err := WriteTaskEnvFile(taskEnvFile, b.cfg.Env); err != nil {
+ _ = os.RemoveAll(sessionDir)
+ return nil, nil, fmt.Errorf("write warm claude task env overlay: %w", err)
+ }
+ childEnv = PreparePooledChildEnv(b.cfg.Env, taskEnvFile, sessionTempDir)
+ }
+
+ args := buildClaudeArgs(opts, b.cfg.Logger)
+
+ // If the caller provided an MCP config, write it to a temp file and pass
+ // --mcp-config <path> so the agent uses a controlled set of MCP servers
+ // instead of inheriting from the outer Claude Code session.
+ var mcpConfigPath string
+ if hasManagedMcpConfig(opts.McpConfig) {
+ path, err := writeMcpConfigToTemp(opts.McpConfig)
+ if err != nil {
+ if sessionDir != "" {
+ _ = os.RemoveAll(sessionDir)
+ }
+ return nil, nil, err
+ }
+ mcpConfigPath = path
+ args = append(args, "--mcp-config", mcpConfigPath)
+ }
+
+ cleanupOnErr := func() {
+ if mcpConfigPath != "" {
+ cleanupMcpConfigTemp(mcpConfigPath)
+ }
+ if sessionDir != "" {
+ _ = os.RemoveAll(sessionDir)
+ }
+ }
+
+ cmd := b.cfg.commandAt(execPath).exec(ctx, args...)
+ hideAgentWindow(cmd)
+ // Take over context cancellation: the default kills the whole group the
+ // instant ctx is done. claudeProcess.terminate instead drives a graceful
+ // group-wide SIGTERM→SIGKILL and closes stdout only after the tree has been
+ // signalled. Returning nil keeps os/exec from racing it with its own kill;
+ // WaitDelay remains the hard backstop.
+ cmd.Cancel = func() error { return nil }
+ b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(args))
+ cmd.WaitDelay = 10 * time.Second
+ if opts.Cwd != "" {
+ cmd.Dir = opts.Cwd
+ }
+ cmd.Env = buildEnv(childEnv)
+ if err := claudeRootSudoPreflight(args, cmd.Env); err != nil {
+ cleanupOnErr()
+ return nil, nil, err
+ }
+
+ var usageSnapshot *claudeUsageSnapshot
+ if opts.ResumeSessionID != "" {
+ snapshot, snapshotErr := captureClaudeUsageSnapshot(cmd.Env, cmd.Dir, opts.ResumeSessionID)
+ if snapshotErr != nil {
+ b.cfg.Logger.Warn("claude usage baseline unavailable; ignoring reported session totals, keeping per-run stream usage", "error", snapshotErr)
+ } else {
+ usageSnapshot = snapshot
+ }
+ }
+
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ cleanupOnErr()
+ return nil, nil, fmt.Errorf("claude stdout pipe: %w", err)
+ }
+ stdin, err := cmd.StdinPipe()
+ if err != nil {
+ cleanupOnErr()
+ return nil, nil, fmt.Errorf("claude stdin pipe: %w", err)
+ }
+ // Capture stderr into both the daemon log and a bounded tail buffer so we
+ // can include the last few KB in Result.Error when claude exits
+ // unexpectedly. Without the tail, an exit-code-only failure looks like
+ // "claude exited with error: exit status 3" — which is useless for
+ // root-causing V8 aborts, Bun panics, or any other CLI-side crash.
+ stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[claude:stderr] "), agentStderrTailBytes)
+ cmd.Stderr = stderrBuf
+
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
+ _ = stdin.Close()
+ cleanupOnErr()
+ return nil, nil, fmt.Errorf("start claude: %w", err)
+ }
+
+ b.cfg.Logger.Info("claude started", "warm_pool", pooled, "pid", cmd.Process.Pid, "cwd", opts.Cwd, "model", opts.Model)
+
+ proc := &claudeProcess{
+ pooled: pooled,
+ fingerprint: fingerprint,
+ cmd: cmd,
+ stdin: stdin,
+ inputWriter: &claudeInputWriter{w: stdin},
+ stdout: stdout,
+ stderrBuf: stderrBuf,
+ procDone: make(chan struct{}),
+ mcpConfigPath: mcpConfigPath,
+ sessionDir: sessionDir,
+ taskEnvFile: taskEnvFile,
+ logger: b.cfg.Logger,
+ }
+ return proc, usageSnapshot, nil
+}
+
+// readStdout routes every stdout event to the active turn for the life of the
+// process, then reaps it. procDone closes only after the exit status is
+// recorded. The caller starts it once the first turn is attached.
+func (p *claudeProcess) readStdout() {
+ defer close(p.procDone)
+ scanner := newAgentStreamScanner(p.stdout)
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ if line == "" {
+ continue
+ }
+ var msg claudeSDKMessage
+ if err := json.Unmarshal([]byte(line), &msg); err != nil {
+ p.dispatch((*claudeTurn).noteInvalidEvent)
+ continue
+ }
+ p.dispatch(func(turn *claudeTurn) { turn.handleMessage(msg) })
+ }
+ scanErr := scanner.Err()
+ if scanErr != nil {
+ // Scanner stopped consuming stdout. Close the pipe before Wait so a
+ // child still writing a malformed/oversized event cannot deadlock on
+ // the full OS pipe; the scanner error remains the primary failure.
+ _ = p.stdout.Close()
+ }
+ p.closeStdin()
+ exitErr := p.cmd.Wait()
+ // The leader is reaped; drop ownership. On Windows that closes the Job
+ // Object, which kills anything still inside it — precisely what should
+ // happen to a descendant that outlived the CLI (GH #7522).
+ releaseProcessGroup(p.cmd)
+ p.turnMu.Lock()
+ p.scanErr = scanErr
+ p.exitErr = exitErr
+ p.turnMu.Unlock()
+}
+
+// warmFingerprint hashes every session-immutable launch input. It omits
+// --resume so the process a first turn spawned and the follow-up turn that
+// resumes its session share one key.
+func (b *claudeBackend) warmFingerprint(execPath string, opts ExecOptions) string {
+ optsForFP := opts
+ optsForFP.ResumeSessionID = ""
+ var configFiles []string
+ if opts.ClaudeSettingsPath != "" {
+ configFiles = append(configFiles, opts.ClaudeSettingsPath)
+ }
+ return computeWarmSessionFingerprint(WarmSessionFingerprintInput{
+ Provider: "claude",
+ Executable: execPath,
+ LaunchPrefix: b.cfg.LaunchPrefix,
+ Args: buildClaudeArgs(optsForFP, b.cfg.Logger),
+ Cwd: opts.Cwd,
+ Model: opts.Model,
+ ThinkingLevel: opts.ThinkingLevel,
+ McpConfig: opts.McpConfig,
+ ConfigFiles: configFiles,
+ BriefHash: opts.WarmPoolBriefHash,
+ Env: b.cfg.Env,
+ ExtraFlags: []string{fmt.Sprintf("supplement=%t", opts.EnableTaskSupplement)},
+ })
+}
+
+// acquireWarmProcess checks out the process parked for sessionID and hands it
+// this task's credentials, or returns nil when the run must spawn.
+func (b *claudeBackend) acquireWarmProcess(sessionID, fingerprint string) *claudeProcess {
+ if sessionID == "" {
+ return nil
+ }
+ acquired := b.cfg.WarmPool.Acquire("claude", sessionID, fingerprint)
+ if acquired == nil {
+ return nil
+ }
+ proc, ok := acquired.(*claudeProcess)
+ if !ok {
+ acquired.Close()
+ return nil
+ }
+ if err := WriteTaskEnvFile(proc.taskEnvFile, b.cfg.Env); err != nil {
+ b.cfg.Logger.Warn("warm claude: failed to refresh task env overlay; evicting", "error", err)
+ proc.Close()
+ return nil
+ }
+ return proc
+}
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index 325cda2cc9..3883f29047 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -6,7 +6,6 @@ import (
"encoding/json"
"errors"
"fmt"
- "io"
"log/slog"
"os"
"os/exec"
@@ -1080,9 +1079,6 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
}
func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts ExecOptions, attempt int) (*Session, error) {
- if b.cfg.WarmPool != nil {
- return b.executeWarmOnce(ctx, prompt, opts, attempt)
- }
execPath := b.cfg.ExecutablePath
if execPath == "" {
execPath = "codex"
@@ -1161,85 +1157,39 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
})
}
codexArgs := buildCodexArgs(opts, b.cfg.Logger)
- // Keep the app-server alive long enough to handle turn/interrupt when the
- // task context is cancelled. The lifecycle goroutine remains governed by
- // runCtx and explicitly stops this process context during bounded cleanup.
- processCtx, stopProcess := context.WithCancel(context.WithoutCancel(runCtx))
- cmd := runtimeCmd.exec(processCtx, codexArgs...)
- hideAgentWindow(cmd)
- // Run codex in its own process group so a cancel-on-stuck cleanup
- // reaches the whole tree — the codex Node wrapper plus the native
- // Rust app-server it spawns — not just the direct child. Without
- // this, killing the leader leaves grandchildren as orphans that
- // keep consuming memory until the OS reaps them; see #4520, where a
- // scanner overflow during thread/resume otherwise leaked Codex
- // processes indefinitely. configureProcessGroup is a no-op on
- // Windows.
- // Override the default exec.CommandContext cancel behaviour. The
- // default sends SIGKILL only to cmd.Process (the leader); we instead
- // signal the whole process group so descendants die too. Returning
- // nil keeps exec from logging a spurious error; cmd.WaitDelay below
- // still backstops cmd.Wait() if the kill leaves an open pipe.
- cmd.Cancel = func() error {
- if cmd.Process != nil {
- signalProcessGroup(cmd, syscall.SIGKILL)
- }
- return nil
- }
- // Bound the wait after the context is cancelled so a stuck child (or an
- // open pipe held by a grandchild) can't hang cmd.Wait() forever. Matches
- // the other long-lived backends (claude, copilot, cursor, …).
- cmd.WaitDelay = codexProcessWaitDelay()
- b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(codexArgs, trustAgentCommandPositional(0, "app-server")))
- if opts.Cwd != "" {
- cmd.Dir = opts.Cwd
- }
- cmd.Env = buildEnv(b.cfg.Env)
- stdout, err := cmd.StdoutPipe()
- if err != nil {
- cancel()
- stopProcess()
- return nil, fmt.Errorf("codex stdout pipe: %w", err)
- }
- stdin, err := cmd.StdinPipe()
- if err != nil {
- cancel()
- stopProcess()
- return nil, fmt.Errorf("codex stdin pipe: %w", err)
- }
- // Codex stderr can contain auth/provider diagnostics. Capture a bounded
- // tail and emit it only through the sanitizer in the cleanup event.
- stderrBuf := newStderrTail(io.Discard, codexStderrTailBytes)
- cmd.Stderr = stderrBuf
-
- // Start and take ownership of the process tree in one step. On Windows the
- // child is created suspended and placed in a Job Object before it runs, so
- // the cleanup below reaches the Node wrapper, the native app-server, and the
- // sandbox helpers underneath them rather than just the direct child. On Unix
- // the process group configured above already covers that and this is a plain
- // Start. Ownership that cannot be taken is logged, not fatal; a child that
- // cannot be resumed is killed and reported here.
- if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
- cancel()
- stopProcess()
- return nil, fmt.Errorf("start codex: %w", err)
- }
- activeLaunches := activeCodexLaunches.Add(1)
- for {
- maxSeen := maxActiveCodexLaunchesObserved.Load()
- if activeLaunches <= maxSeen || maxActiveCodexLaunchesObserved.CompareAndSwap(maxSeen, activeLaunches) {
- break
+ // Getting a process is the only step that depends on the warm pool.
+ pooled := b.cfg.WarmPool != nil
+ var proc *codexProcess
+ var fingerprint string
+ if pooled {
+ fingerprint = b.warmFingerprint(execPath, runtimeCmd, codexArgs, opts)
+ proc = b.acquireWarmProcess(opts.ResumeSessionID, fingerprint)
+ }
+ warmHit := proc != nil
+ var activeLaunches int64
+ if warmHit {
+ activeLaunches = activeCodexLaunches.Load()
+ proc.client.handshakeTimeout = handshakeTimeout
+ proc.client.threadHandshakeTimeout = threadHandshakeTimeout
+ proc.client.attempt = attempt
+ proc.client.activeLaunches = activeLaunches
+ } else {
+ var err error
+ proc, err = b.spawnCodexProcess(runtimeCmd, codexArgs, opts, pooled, fingerprint, handshakeTimeout, threadHandshakeTimeout, attempt)
+ if err != nil {
+ cancel()
+ return nil, err
}
+ activeLaunches = proc.client.activeLaunches
}
- launchStarted := time.Now()
+ c := proc.client
+
codexVersion := strings.TrimSpace(b.cfg.CodexVersion)
if codexVersion == "" {
codexVersion = "unknown"
}
- b.cfg.Logger.Info("codex lifecycle", "phase", "spawn", "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID, "pid", cmd.Process.Pid, "process_group", cmd.Process.Pid, "cwd", opts.Cwd, "attempt", attempt, "active_launches", activeLaunches, "codex_version", codexVersion, "daemon_version", b.cfg.DaemonVersion)
-
msgCh := make(chan Message, 256)
resCh := make(chan Result, 1)
semanticActivityCh := make(chan string, 256)
@@ -1257,12 +1207,8 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
var semanticObserved atomic.Bool
turnNotificationGate := &codexTurnNotificationGate{}
firstItemWait := &codexFirstItemWaitObservation{}
-
- // turnDone is set before starting the reader goroutine so there is no
- // race between the lifecycle goroutine writing and the reader reading.
turnDone := make(chan bool, 1) // true = aborted
- var c *codexClient
observeMessage := func(msg Message) {
logCodexAgentMessage(b.cfg.Logger, msg)
activity := describeCodexSemanticActivity(msg)
@@ -1275,26 +1221,23 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
}
}
- c = &codexClient{
+ c.attachTurnHooks(codexTurnHooks{
cfg: b.cfg,
- stdin: stdin,
- pending: make(map[int]*pendingRPC),
- processDone: make(chan struct{}),
- handshakeTimeout: handshakeTimeout,
- threadHandshakeTimeout: threadHandshakeTimeout,
- pid: cmd.Process.Pid,
- attempt: attempt,
- activeLaunches: activeLaunches,
- notificationProtocol: "unknown",
acceptNotification: turnNotificationGate.accept,
guardianRateLimitCircuit: &codexGuardianRateLimitCircuit{},
rateLimits: newRateLimitTracker(opts.OnRateLimits),
+ // A reused thread keeps its cumulative usage total so this turn's
+ // usage is the delta since the previous turn.
+ preserveUsageBaseline: warmHit,
onGuardianRateLimit: func() {
guardianRateLimitTripped.Store(true)
b.cfg.Logger.Warn("codex Guardian approval rate-limit circuit opened",
"task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID,
"failure_count", codexGuardianRateLimitThreshold)
- guardianRateLimitTrip <- struct{}{}
+ select {
+ case guardianRateLimitTrip <- struct{}{}:
+ default:
+ }
},
onDiscardedNotification: func(string, map[string]any) {
// Any app-server notification proves the process made semantic
@@ -1341,281 +1284,166 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
default:
}
},
- }
-
- // Start reading stdout in background
- readerDone := make(chan struct{})
- go func() {
- defer close(readerDone)
- scanner := newAgentStreamScanner(stdout)
- for scanner.Scan() {
- line := strings.TrimSpace(scanner.Text())
- if line == "" {
- continue
- }
- c.handleLine(line)
- }
- // A cancelled or crashed app-server may close stdout without an
- // item/completed snapshot. Preserve every complete delta JSON event
- // already parsed; an incomplete final JSON token is ignored by
- // handleLine and can never enter this buffer.
- c.flushAgentMessageDeltas()
- if err := scanner.Err(); err != nil {
- // %w on BOTH: callers match errCodexProcessExited to decide the
- // process is gone, and bufio.ErrTooLong to tell "we could not read
- // the response" apart from "codex died". startOrResumeThread needs
- // that distinction to report an oversized resume as a rejected
- // resume rather than a crash (MUL-5722).
- c.markProcessExited(fmt.Errorf("%w: %w", errCodexProcessExited, err))
- return
- }
- c.markProcessExited(errCodexProcessExited)
- }()
-
- // drainAndWait closes stdin and joins the process exactly once. Read stderrBuf
- // only after it returns, when os/exec's copy goroutines have finished.
- //
- // Wait for readerDone before cmd.Wait so Wait cannot close a pipe under an active
- // read. Bound both reader shutdown and process reaping. Scanner overflow can leave
- // the child blocked on unread stdout, so cancellation and WaitDelay must also
- // cover that path instead of relying on stdin EOF to stop the child.
- var waitOnce sync.Once
- var cleanupConfirmed bool
- var waitReturned bool
- var cleanupWaitErr error
- drainAndWait := func() {
- waitOnce.Do(func() {
- stdin.Close()
-
- grace := codexGracefulShutdown()
- waitCh := make(chan struct{})
- var startWait sync.Once
- startProcessWait := func() {
- startWait.Do(func() {
- go func() {
- cleanupWaitErr = cmd.Wait()
- close(waitCh)
- }()
- })
- }
-
- // Phase 1: let the reader finish before invoking cmd.Wait().
- select {
- case <-readerDone:
- // reader drained cleanly (codex shutdown closed stdout)
- // or aborted early (e.g. scanner overflow). Either way it
- // is now safe to call cmd.Wait().
- case <-time.After(grace):
- // codex did not close stdout within the grace window. Force
- // the shutdown via context cancellation — cmd.Cancel
- // group-kills the tree, the reader unblocks when stdout
- // EOFs, and we proceed to phase 2.
- b.cfg.Logger.Warn("codex did not close stdout after stdin EOF; forcing shutdown",
- "pid", cmd.Process.Pid,
- "grace", grace.String(),
- )
- stopProcess()
- // On Windows, Cancel terminates only the direct child. A
- // descendant may keep inherited stdout open indefinitely. Start
- // Wait now so os/exec's WaitDelay closes the pipe after its
- // bounded deadline and lets the reader finish.
- startProcessWait()
- <-waitCh
- select {
- case <-readerDone:
- case <-time.After(grace):
- b.cfg.Logger.Warn("codex stdout reader remained open after bounded process wait",
- "pid", cmd.Process.Pid,
- "grace", grace.String(),
- )
- }
- }
-
- // Phase 2: bound cmd.Wait() in case the process is still alive
- // (scanner-overflow case: reader exited early on its own while
- // codex stayed blocked writing into a full stdout pipe).
- startProcessWait()
- select {
- case <-waitCh:
- waitReturned = true
- // reaped cleanly.
- case <-time.After(grace):
- b.cfg.Logger.Warn("codex process still alive after reader exited; forcing shutdown",
- "pid", cmd.Process.Pid,
- "grace", grace.String(),
- )
- stopProcess()
- // WaitDelay (10s) is the final backstop: even if the
- // group-kill races with an open pipe held by a
- // descendant, cmd.Wait() returns within WaitDelay of the
- // cancel.
- <-waitCh
- waitReturned = true
- }
- // Wait returning with a ProcessState is the os/exec reap boundary.
- // On Unix, ProcessState.Exited reports false for a process terminated
- // by SIGKILL even though Wait successfully reaped it.
- cleanupConfirmed = waitReturned && cmd.ProcessState != nil && waitProcessGroupGone(cmd, grace)
- if codexCleanupConfirmationOverride.Load() < 0 {
- cleanupConfirmed = false
- }
- b.cfg.Logger.Info("codex lifecycle",
- "phase", "cleanup",
- "task_id", b.cfg.TaskID,
- "runtime_id", b.cfg.RuntimeID,
- "pid", cmd.Process.Pid,
- "process_group", cmd.Process.Pid,
- "attempt", attempt,
- "latency", time.Since(launchStarted).Round(time.Millisecond).String(),
- "reaped", cleanupConfirmed,
- "exit_status", codexProcessExitStatus(cmd.ProcessState),
- "wait_error", cleanupWaitErr,
- "stderr_bytes", stderrBuf.TotalBytes(),
- "stderr_truncated", stderrBuf.TotalBytes() > codexStderrTailBytes,
- )
- // The tree has been reaped and observed; drop ownership. This is
- // the only safe point to do so on Windows, where releasing kills
- // whatever is still inside the job — which is precisely what should
- // happen to anything that outlived the reap above. waitOnce makes it
- // exactly-once per launch attempt.
- releaseProcessGroup(cmd)
- })
+ })
+ if !warmHit {
+ go proc.readStdout()
}
// Drive the session lifecycle in a goroutine.
- // Shutdown sequence: lifecycle goroutine closes stdin + cancels context →
- // codex process exits → reader goroutine's scanner.Scan() returns false →
- // readerDone closes → lifecycle goroutine collects final output and sends Result.
+ // Shutdown sequence: the turn ends → the process is parked, or Close
+ // closes stdin → codex exits → the reader's scanner.Scan() returns false →
+ // readerDone closes → the lifecycle goroutine collects final output and
+ // sends Result.
go func() {
- defer activeCodexLaunches.Add(-1)
defer cancel()
- defer stopProcess()
defer close(msgCh)
defer close(resCh)
- defer drainAndWait()
startTime := time.Now()
finalStatus := "completed"
var finalError string
+ var threadID string
+ var resumed bool
- // 1. Initialize handshake
- initializeStarted := time.Now()
- b.cfg.Logger.Info("codex lifecycle", "phase", "initialize_sent", "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID, "pid", cmd.Process.Pid, "attempt", attempt, "active_launches", activeLaunches)
- _, err := c.request(runCtx, "initialize", map[string]any{
- "clientInfo": map[string]any{
- "name": "multica-agent-sdk",
- "title": "Multica Agent SDK",
- "version": "0.2.0",
- },
- "capabilities": map[string]any{
- "experimentalApi": true,
- },
- })
- if err != nil {
- initializeLatency := time.Since(initializeStarted)
- var handshakeErr *codexHandshakeTimeoutError
- timedOut := errors.As(err, &handshakeErr) && handshakeErr.Method == "initialize"
- if timedOut {
- // A timed-out initialize may still complete after the host gives up.
- // Kill the whole process group before waiting so a leader that exits
- // on stdin EOF cannot leave detached-stdio descendants behind.
- signalProcessGroup(cmd, syscall.SIGKILL)
- } else if runCtx.Err() != nil {
- // processCtx deliberately outlives runCtx so active turns can use
- // turn/interrupt. Initialize has no interruptible turn, so a parent
- // cancellation must take the fast process-tree cleanup path.
- stopProcess()
- }
- drainAndWait() // flush os/exec stderr goroutine before sampling Tail
- finalStatus = "failed"
- finalError = fmt.Sprintf("codex initialize failed: %v", err)
- contextEnded := errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)
- if !timedOut && !contextEnded {
- // Timeout stderr is untrusted provider output and may echo opaque
- // Config.Env/auth values that pattern sanitization cannot identify.
- // The same applies when the parent task deadline/cancellation wins
- // the race against the per-RPC handshake timeout.
- // Keep it out of persisted/user-visible Results; cleanup lifecycle
- // still records bounded byte/truncation metadata.
- finalError = withAgentStderr(finalError, "codex", sanitizeCodexDiagnostic(stderrBuf.Tail()))
- }
- retrySafe := timedOut && !semanticObserved.Load() && cleanupConfirmed && codexInitializeRetrySupported()
- if timedOut && !cleanupConfirmed {
- finalError += "; retry suppressed: process cleanup/reap not confirmed"
- } else if timedOut && cleanupConfirmed && !codexInitializeRetrySupported() {
- finalError += "; retry suppressed: process-tree cleanup cannot be confirmed on this platform"
- }
- b.cfg.Logger.Warn("codex lifecycle", "phase", "initialize_failure", "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID, "pid", cmd.Process.Pid, "attempt", attempt, "latency", initializeLatency.Round(time.Millisecond).String(), "semantic_activity", semanticObserved.Load(), "cleanup_confirmed", cleanupConfirmed, "retry_safe", retrySafe)
- resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), codexInitializeRetrySafe: retrySafe}
- return
+ closeProc := func() bool {
+ proc.endTurn()
+ return proc.Close()
}
- b.cfg.Logger.Info("codex lifecycle", "phase", "initialize_response", "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID, "pid", cmd.Process.Pid, "attempt", attempt, "latency", time.Since(initializeStarted).Round(time.Millisecond).String())
- c.notify("initialized")
- // 2. Start a new thread, or resume the prior one for this issue. When
- // resume fails (thread GCed on the server, schema drift, etc.) we fall
- // back to a fresh thread so the task still makes progress.
- threadID, resumed, err := c.startOrResumeThread(runCtx, opts, b.cfg.Logger)
- if err != nil {
- var handshakeErr *codexHandshakeTimeoutError
- timedOut := errors.As(err, &handshakeErr) && isCodexThreadSetupRPC(handshakeErr.Method)
- if timedOut {
- // A timed-out thread setup has an uncertain provider outcome. Kill
- // the whole process group before waiting so a leader that exits on
- // EOF cannot leave detached-stdio descendants behind.
- signalProcessGroup(cmd, syscall.SIGKILL)
- } else if runCtx.Err() != nil {
- // No turn exists during thread start/resume, so there is nothing to
- // interrupt and no reason to spend the graceful shutdown budget.
- stopProcess()
- }
- drainAndWait() // flush os/exec stderr goroutine before sampling Tail
- finalStatus = "failed"
- stderrTail := sanitizeCodexDiagnostic(stderrBuf.Tail())
- finalError = err.Error()
- // No turn has started, so a reaped process tree makes the timeout safe
- // for the daemon's bounded retry path.
- retrySafe := timedOut && cleanupConfirmed
- if retrySafe {
- finalStatus = "timeout"
- } else if timedOut {
- finalError += "; retry suppressed: process cleanup/reap not confirmed"
+ if warmHit {
+ // The parked process already holds this thread loaded; skip the
+ // handshake and thread setup entirely.
+ threadID = proc.threadID
+ resumed = true
+ c.setThreadID(threadID)
+ b.cfg.Logger.Info("codex warm session reused",
+ "task_id", b.cfg.TaskID,
+ "runtime_id", b.cfg.RuntimeID,
+ "pid", proc.cmd.Process.Pid,
+ "thread_id", threadID,
+ )
+ trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: threadID})
+ } else {
+ // 1. Initialize handshake
+ initializeStarted := time.Now()
+ b.cfg.Logger.Info("codex lifecycle", "phase", "initialize_sent", "warm_pool", pooled, "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID, "pid", proc.cmd.Process.Pid, "attempt", attempt, "active_launches", activeLaunches)
+ _, err := c.request(runCtx, "initialize", map[string]any{
+ "clientInfo": map[string]any{
+ "name": "multica-agent-sdk",
+ "title": "Multica Agent SDK",
+ "version": "0.2.0",
+ },
+ "capabilities": map[string]any{
+ "experimentalApi": true,
+ },
+ })
+ if err != nil {
+ initializeLatency := time.Since(initializeStarted)
+ var handshakeErr *codexHandshakeTimeoutError
+ timedOut := errors.As(err, &handshakeErr) && handshakeErr.Method == "initialize"
+ if timedOut {
+ // A timed-out initialize may still complete after the host gives up.
+ // Kill the whole process group before waiting so a leader that exits
+ // on stdin EOF cannot leave detached-stdio descendants behind.
+ signalProcessGroup(proc.cmd, syscall.SIGKILL)
+ } else if runCtx.Err() != nil {
+ // The process context deliberately outlives runCtx so active turns
+ // can use turn/interrupt. Initialize has no interruptible turn, so a
+ // parent cancellation must take the fast process-tree cleanup path.
+ proc.stopProcess()
+ }
+ cleanupConfirmed := closeProc() // flush os/exec stderr goroutine before sampling Tail
+ finalStatus = "failed"
+ finalError = fmt.Sprintf("codex initialize failed: %v", err)
+ contextEnded := errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)
+ if !timedOut && !contextEnded {
+ // Timeout stderr is untrusted provider output and may echo opaque
+ // Config.Env/auth values that pattern sanitization cannot identify.
+ // The same applies when the parent task deadline/cancellation wins
+ // the race against the per-RPC handshake timeout.
+ // Keep it out of persisted/user-visible Results; cleanup lifecycle
+ // still records bounded byte/truncation metadata.
+ finalError = withAgentStderr(finalError, "codex", sanitizeCodexDiagnostic(proc.stderrBuf.Tail()))
+ }
+ retrySafe := timedOut && !semanticObserved.Load() && cleanupConfirmed && codexInitializeRetrySupported()
+ if timedOut && !cleanupConfirmed {
+ finalError += "; retry suppressed: process cleanup/reap not confirmed"
+ } else if timedOut && cleanupConfirmed && !codexInitializeRetrySupported() {
+ finalError += "; retry suppressed: process-tree cleanup cannot be confirmed on this platform"
+ }
+ b.cfg.Logger.Warn("codex lifecycle", "phase", "initialize_failure", "warm_pool", pooled, "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID, "pid", proc.cmd.Process.Pid, "attempt", attempt, "latency", initializeLatency.Round(time.Millisecond).String(), "semantic_activity", semanticObserved.Load(), "cleanup_confirmed", cleanupConfirmed, "retry_safe", retrySafe)
+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), codexInitializeRetrySafe: retrySafe}
+ return
}
- if c.threadSetupMethod != "" {
- classification := classifyCodexStartupStderr(stderrTail, timedOut)
- b.cfg.Logger.Warn("codex lifecycle",
- "phase", strings.ReplaceAll(c.threadSetupMethod, "/", "_")+"_failure",
- "task_id", b.cfg.TaskID,
- "runtime_id", b.cfg.RuntimeID,
- "pid", cmd.Process.Pid,
- "attempt", attempt,
- "active_launches", activeLaunches,
- "method", c.threadSetupMethod,
- "latency", time.Since(c.threadSetupStarted).Round(time.Millisecond).String(),
- "latency_ms", time.Since(c.threadSetupStarted).Milliseconds(),
- "cleanup_confirmed", cleanupConfirmed,
- "reaped", cleanupConfirmed,
- "retry_safe", retrySafe,
- "retry_attempted", false,
- "stderr_model_refresh_failure_count", classification.modelRefreshFailure,
- "stderr_model_refresh_timeout_count", classification.modelRefreshTimeout,
- "stderr_mcp_init_transport_count", classification.mcpInitTransport,
- "stderr_bare_timeout_count", classification.bareTimeout,
- )
+ b.cfg.Logger.Info("codex lifecycle", "phase", "initialize_response", "warm_pool", pooled, "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID, "pid", proc.cmd.Process.Pid, "attempt", attempt, "latency", time.Since(initializeStarted).Round(time.Millisecond).String())
+ c.notify("initialized")
+
+ // 2. Start a new thread, or resume the prior one for this issue. When
+ // resume fails (thread GCed on the server, schema drift, etc.) we fall
+ // back to a fresh thread so the task still makes progress.
+ threadID, resumed, err = c.startOrResumeThread(runCtx, opts, b.cfg.Logger)
+ if err != nil {
+ var handshakeErr *codexHandshakeTimeoutError
+ timedOut := errors.As(err, &handshakeErr) && isCodexThreadSetupRPC(handshakeErr.Method)
+ if timedOut {
+ // A timed-out thread setup has an uncertain provider outcome. Kill
+ // the whole process group before waiting so a leader that exits on
+ // EOF cannot leave detached-stdio descendants behind.
+ signalProcessGroup(proc.cmd, syscall.SIGKILL)
+ } else if runCtx.Err() != nil {
+ // No turn exists during thread start/resume, so there is nothing to
+ // interrupt and no reason to spend the graceful shutdown budget.
+ proc.stopProcess()
+ }
+ cleanupConfirmed := closeProc() // flush os/exec stderr goroutine before sampling Tail
+ finalStatus = "failed"
+ stderrTail := sanitizeCodexDiagnostic(proc.stderrBuf.Tail())
+ finalError = err.Error()
+ // No turn has started, so a reaped process tree makes the timeout safe
+ // for the daemon's bounded retry path.
+ retrySafe := timedOut && cleanupConfirmed
+ if retrySafe {
+ finalStatus = "timeout"
+ } else if timedOut {
+ finalError += "; retry suppressed: process cleanup/reap not confirmed"
+ }
+ if c.threadSetupMethod != "" {
+ classification := classifyCodexStartupStderr(stderrTail, timedOut)
+ b.cfg.Logger.Warn("codex lifecycle",
+ "phase", strings.ReplaceAll(c.threadSetupMethod, "/", "_")+"_failure",
+ "warm_pool", pooled,
+ "task_id", b.cfg.TaskID,
+ "runtime_id", b.cfg.RuntimeID,
+ "pid", proc.cmd.Process.Pid,
+ "attempt", attempt,
+ "active_launches", activeLaunches,
+ "method", c.threadSetupMethod,
+ "latency", time.Since(c.threadSetupStarted).Round(time.Millisecond).String(),
+ "latency_ms", time.Since(c.threadSetupStarted).Milliseconds(),
+ "cleanup_confirmed", cleanupConfirmed,
+ "reaped", cleanupConfirmed,
+ "retry_safe", retrySafe,
+ "retry_attempted", false,
+ "stderr_model_refresh_failure_count", classification.modelRefreshFailure,
+ "stderr_model_refresh_timeout_count", classification.modelRefreshTimeout,
+ "stderr_mcp_init_transport_count", classification.mcpInitTransport,
+ "stderr_bare_timeout_count", classification.bareTimeout,
+ )
+ }
+ resCh <- Result{
+ Status: finalStatus,
+ Error: finalError,
+ DurationMs: time.Since(startTime).Milliseconds(),
+ ResumeRejected: isCodexResumeOverflow(opts, err),
+ }
+ return
}
- resCh <- Result{
- Status: finalStatus,
- Error: finalError,
- DurationMs: time.Since(startTime).Milliseconds(),
- ResumeRejected: isCodexResumeOverflow(opts, err),
+ c.setThreadID(threadID)
+ if resumed {
+ b.cfg.Logger.Info("codex thread resumed", "thread_id", threadID)
+ } else {
+ b.cfg.Logger.Info("codex thread started", "thread_id", threadID)
}
- return
- }
- c.setThreadID(threadID)
- if resumed {
- b.cfg.Logger.Info("codex thread resumed", "thread_id", threadID)
- } else {
- b.cfg.Logger.Info("codex thread started", "thread_id", threadID)
}
// 3. Send turn and wait for completion. When a resume was expected but we
@@ -1648,7 +1476,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
firstItemWait.finish(
time.Now(),
outcome,
- classifyCodexStartupStderr(stderrBuf.Tail(), strings.HasSuffix(outcome, "_timeout")),
+ classifyCodexStartupStderr(proc.stderrBuf.Tail(), strings.HasSuffix(outcome, "_timeout")),
)
}
finishTurn := func(aborted bool) {
@@ -1685,21 +1513,21 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
}
}
turnNotificationGate.arm()
- _, err = c.request(runCtx, "turn/start", turnParams)
+ _, err := c.request(runCtx, "turn/start", turnParams)
if err != nil {
if runCtx.Err() != nil {
finishRunContextDone()
if !interruptCodexTurn(c, threadID, turnDone, opts.TurnInterruptTimeout, b.cfg.Logger) {
- stopProcess()
+ proc.stopProcess()
}
} else {
select {
case aborted := <-turnDone:
finishTurn(aborted)
default:
- drainAndWait() // flush os/exec stderr goroutine before sampling Tail
+ closeProc() // flush os/exec stderr goroutine before sampling Tail
finalStatus = "failed"
- finalError = withAgentStderr(fmt.Sprintf("codex turn/start failed: %v", err), "codex", sanitizeCodexDiagnostic(stderrBuf.Tail()))
+ finalError = withAgentStderr(fmt.Sprintf("codex turn/start failed: %v", err), "codex", sanitizeCodexDiagnostic(proc.stderrBuf.Tail()))
resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}
return
}
@@ -1735,7 +1563,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
finalStatus = "failed"
finalError = codexGuardianRateLimitError
if !interruptCodexTurn(c, threadID, turnDone, opts.TurnInterruptTimeout, b.cfg.Logger) {
- stopProcess()
+ proc.stopProcess()
}
case activity := <-semanticActivityCh:
lastSemanticActivity = time.Now()
@@ -1769,7 +1597,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
Model: opts.Model,
}
b.cfg.Logger.Warn(CodexFirstTurnNoProgressMarker,
- "pid", cmd.Process.Pid,
+ "pid", proc.cmd.Process.Pid,
"thread_id", threadID,
"turn_id", turnID,
"timeout", firstTurnNoProgressTimeout.String(),
@@ -1789,7 +1617,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
Model: opts.Model,
}
b.cfg.Logger.Warn(CodexSemanticInactivityMarker,
- "pid", cmd.Process.Pid,
+ "pid", proc.cmd.Process.Pid,
"thread_id", threadID,
"turn_id", turnID,
"timeout", semanticInactivityTimeout.String(),
@@ -1799,7 +1627,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
case <-runCtx.Done():
finishRunContextDone()
if !interruptCodexTurn(c, threadID, turnDone, opts.TurnInterruptTimeout, b.cfg.Logger) {
- stopProcess()
+ proc.stopProcess()
}
case <-c.processDone:
select {
@@ -1829,21 +1657,42 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
}
duration := time.Since(startTime)
- b.cfg.Logger.Info("codex finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
-
- // Run cleanup. drainAndWait handles the graceful-then-cancel pattern
- // in two bounded phases (see its declaration): wait for the reader,
- // then wait for cmd.Wait(), force-cancelling either if the grace
- // window expires. A clean shutdown lets codex flush OTEL telemetry;
- // a stuck process is killed via the process-group SIGKILL.
- drainAndWait()
+ b.cfg.Logger.Info("codex finished", "pid", proc.cmd.Process.Pid, "warm_hit", warmHit, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
+
+ proc.endTurn()
+ parked := proc.pooled &&
+ finalStatus == "completed" &&
+ finalError == "" &&
+ !guardianRateLimitTripped.Load() &&
+ processExitErr == nil &&
+ threadID != "" &&
+ proc.Alive() &&
+ runCtx.Err() == nil
+
+ var u TokenUsage
+ var cleanupConfirmed bool
+ if parked {
+ // Read usage before parking: the next turn to acquire the process
+ // resets it.
+ u = c.turnUsage()
+ proc.threadID = threadID
+ b.cfg.WarmPool.Park("codex", threadID, proc)
+ } else {
+ // Close handles the graceful-then-cancel pattern in two bounded
+ // phases: wait for the reader, then wait for cmd.Wait(), force-
+ // cancelling either if the grace window expires. A clean shutdown
+ // lets codex flush OTEL telemetry; a stuck process is killed via the
+ // process-group SIGKILL.
+ cleanupConfirmed = proc.Close()
+ u = c.turnUsage()
+ }
if processExitErr != nil {
- finalError = withAgentStderr(processExitErr.Error(), "codex", sanitizeCodexDiagnostic(stderrBuf.Tail()))
+ finalError = withAgentStderr(processExitErr.Error(), "codex", sanitizeCodexDiagnostic(proc.stderrBuf.Tail()))
}
- stderrTail := sanitizeCodexDiagnostic(stderrBuf.Tail())
+ stderrTail := sanitizeCodexDiagnostic(proc.stderrBuf.Tail())
if timeoutDiagnostic.Kind != codexTimeoutNone {
- timeoutDiagnostic.CodexVersion = detectCodexVersionForDiagnostics(context.Background(), b.cfg.commandAt(execPath), cmd.Env, b.cfg.Logger)
+ timeoutDiagnostic.CodexVersion = detectCodexVersionForDiagnostics(context.Background(), b.cfg.commandAt(execPath), proc.cmd.Env, b.cfg.Logger)
finalError = buildCodexTimeoutDiagnosticError(timeoutDiagnostic, stderrTail)
}
@@ -1860,7 +1709,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
cleanupConfirmed && codexInitializeRetrySupported()
if startupRefreshRetrySafe {
b.cfg.Logger.Warn("codex startup model catalog refresh failure is retry safe",
- "pid", cmd.Process.Pid,
+ "pid", proc.cmd.Process.Pid,
"thread_id", threadID,
"attempt", attempt,
)
@@ -1880,9 +1729,11 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
}
fields := []any{
"phase", "first_item_wait",
+ "warm_pool", pooled,
+ "warm_hit", warmHit,
"task_id", b.cfg.TaskID,
"runtime_id", b.cfg.RuntimeID,
- "pid", cmd.Process.Pid,
+ "pid", proc.cmd.Process.Pid,
"attempt", attempt,
"active_launches", activeLaunches,
"method", "turn/start",
@@ -1917,19 +1768,12 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
finalOutput := codexDeliverableOutput(output)
outputMu.Unlock()
- // Build usage map from accumulated codex usage.
- // First check JSON-RPC notifications (often empty for Codex).
- var usageMap map[string]TokenUsage
- c.usageMu.Lock()
- u := c.usage
- c.usageMu.Unlock()
-
// Codex sometimes omits usage from JSON-RPC notifications, and can also
// omit the configured model when the agent relies on Codex's default.
// Scan the per-task session JSONL for either missing value. Session usage
// is only a fallback, so it must never replace a JSON-RPC usage sample.
taskCodexHome := strings.TrimSpace(b.cfg.Env["CODEX_HOME"])
- usageMap = codexResultUsageMap(startTime, taskCodexHome, threadID, resumed, opts.Model, u)
+ usageMap := codexResultUsageMap(startTime, taskCodexHome, threadID, resumed, opts.Model, u)
resCh <- Result{
Status: finalStatus,
diff --git a/server/pkg/agent/codex_pool.go b/server/pkg/agent/codex_pool.go
deleted file mode 100644
index ffa5a0e1a9..0000000000
--- a/server/pkg/agent/codex_pool.go
+++ /dev/null
@@ -1,986 +0,0 @@
-package agent
-
-import (
- "context"
- "errors"
- "fmt"
- "io"
- "log/slog"
- "os"
- "os/exec"
- "path/filepath"
- "strings"
- "sync"
- "sync/atomic"
- "syscall"
- "time"
-)
-
-// codexSyncWriter serializes concurrent writes to a Codex app-server stdin pipe
-// (lifecycle RPCs, server-request approval replies from the stdout reader, and
-// mid-turn turn/steer calls).
-type codexSyncWriter struct {
- mu sync.Mutex
- w io.WriteCloser
-}
-
-func (w *codexSyncWriter) Write(p []byte) (int, error) {
- w.mu.Lock()
- defer w.mu.Unlock()
- return w.w.Write(p)
-}
-
-func (w *codexSyncWriter) Close() error {
- w.mu.Lock()
- defer w.mu.Unlock()
- return w.w.Close()
-}
-
-type codexTurnHooks struct {
- cfg Config
- acceptNotification func(method string, params map[string]any) bool
- onDiscardedNotification func(method string, params map[string]any)
- onMessage func(Message)
- onAgentMessageChunk func(text string) bool
- onAgentMessage func(text, phase string)
- onFinalAnswer func(text string)
- onSemanticActivity func(description string)
- onTurnDone func(aborted bool)
- guardianRateLimitCircuit *codexGuardianRateLimitCircuit
- onGuardianRateLimit func()
- rateLimits *rateLimitTracker
- preserveUsageBaseline bool
-}
-
-func (c *codexClient) attachTurnHooks(h codexTurnHooks) {
- c.hookMu.Lock()
- defer c.hookMu.Unlock()
-
- c.cfg = h.cfg
- c.acceptNotification = h.acceptNotification
- c.onDiscardedNotification = h.onDiscardedNotification
- c.onMessage = h.onMessage
- c.onAgentMessageChunk = h.onAgentMessageChunk
- c.onAgentMessage = h.onAgentMessage
- c.onFinalAnswer = h.onFinalAnswer
- c.onSemanticActivity = h.onSemanticActivity
- c.onTurnDone = h.onTurnDone
- c.guardianRateLimitCircuit = h.guardianRateLimitCircuit
- c.onGuardianRateLimit = h.onGuardianRateLimit
- c.rateLimits = h.rateLimits
-
- c.agentMessageStreams = nil
- c.agentMessageOrder = nil
- c.turnCompleted = false
- c.setActiveTurnID("")
-
- c.turnErrorMu.Lock()
- c.turnError = ""
- c.turnErrorMu.Unlock()
-
- c.usageMu.Lock()
- c.usage = TokenUsage{}
- if !h.preserveUsageBaseline {
- c.usageTotal = codexRawTokenUsage{}
- c.usageTotalSet = false
- }
- c.usageMu.Unlock()
-}
-
-func (c *codexClient) detachTurnHooks() {
- c.hookMu.Lock()
- defer c.hookMu.Unlock()
-
- c.flushAgentMessageDeltas()
- c.acceptNotification = func(string, map[string]any) bool { return false }
- c.onDiscardedNotification = nil
- c.onMessage = nil
- c.onAgentMessageChunk = nil
- c.onAgentMessage = nil
- c.onFinalAnswer = nil
- c.onSemanticActivity = nil
- c.onTurnDone = nil
- c.onGuardianRateLimit = nil
- c.rateLimits = nil
- c.agentMessageStreams = nil
- c.agentMessageOrder = nil
- c.setActiveTurnID("")
-}
-
-func (c *codexClient) flushAgentMessageDeltasLocked() {
- c.hookMu.Lock()
- c.flushAgentMessageDeltas()
- c.hookMu.Unlock()
-}
-
-type warmCodexProcess struct {
- fingerprint string
- threadID string
- cmd *exec.Cmd
- stdin *codexSyncWriter
- stderrBuf *stderrTail
- client *codexClient
- stopProcess context.CancelFunc
- readerDone chan struct{}
- sessionDir string
- taskEnvFile string
- sessionTempDir string
- launchStarted time.Time
- logger *slog.Logger
-
- closed atomic.Bool
- closeOnce sync.Once
- cleanupConfirmed bool
-}
-
-func (p *warmCodexProcess) Fingerprint() string { return p.fingerprint }
-
-func (p *warmCodexProcess) Alive() bool {
- if p.closed.Load() {
- return false
- }
- if p.client.getProcessErr() != nil {
- return false
- }
- select {
- case <-p.readerDone:
- return false
- default:
- return true
- }
-}
-
-func (p *warmCodexProcess) Close() bool {
- p.closeOnce.Do(func() {
- p.closed.Store(true)
- _ = ClearTaskEnvFile(p.taskEnvFile)
- _ = p.stdin.Close()
-
- grace := codexGracefulShutdown()
- waitCh := make(chan struct{})
- var waitErr error
- var startWait sync.Once
- startProcessWait := func() {
- startWait.Do(func() {
- go func() {
- waitErr = p.cmd.Wait()
- close(waitCh)
- }()
- })
- }
-
- select {
- case <-p.readerDone:
- case <-time.After(grace):
- if p.logger != nil {
- p.logger.Warn("warm codex did not close stdout after stdin EOF; forcing shutdown",
- "pid", p.cmd.Process.Pid,
- "grace", grace.String(),
- )
- }
- p.stopProcess()
- startProcessWait()
- <-waitCh
- select {
- case <-p.readerDone:
- case <-time.After(grace):
- }
- }
-
- startProcessWait()
- var waitReturned bool
- select {
- case <-waitCh:
- waitReturned = true
- case <-time.After(grace):
- if p.logger != nil {
- p.logger.Warn("warm codex still alive after reader exited; forcing shutdown",
- "pid", p.cmd.Process.Pid,
- "grace", grace.String(),
- )
- }
- p.stopProcess()
- <-waitCh
- waitReturned = true
- }
-
- p.cleanupConfirmed = waitReturned && p.cmd.ProcessState != nil && waitProcessGroupGone(p.cmd, grace)
- if codexCleanupConfirmationOverride.Load() < 0 {
- p.cleanupConfirmed = false
- }
- if p.logger != nil {
- p.logger.Info("codex lifecycle",
- "phase", "cleanup",
- "warm_pool", true,
- "pid", p.cmd.Process.Pid,
- "process_group", p.cmd.Process.Pid,
- "latency", time.Since(p.launchStarted).Round(time.Millisecond).String(),
- "reaped", p.cleanupConfirmed,
- "exit_status", codexProcessExitStatus(p.cmd.ProcessState),
- "wait_error", waitErr,
- "stderr_bytes", p.stderrBuf.TotalBytes(),
- "stderr_truncated", p.stderrBuf.TotalBytes() > codexStderrTailBytes,
- )
- }
- releaseProcessGroup(p.cmd)
- p.stopProcess()
- activeCodexLaunches.Add(-1)
- if p.sessionDir != "" {
- _ = os.RemoveAll(p.sessionDir)
- }
- })
- return p.cleanupConfirmed
-}
-
-func (b *codexBackend) executeWarmOnce(ctx context.Context, prompt string, opts ExecOptions, attempt int) (*Session, error) {
- execPath := b.cfg.ExecutablePath
- if execPath == "" {
- execPath = "codex"
- }
- if _, err := exec.LookPath(execPath); err != nil {
- return nil, fmt.Errorf("codex executable not found at %q: %w", execPath, err)
- }
-
- timeout := opts.Timeout
- semanticInactivityTimeout := opts.SemanticInactivityTimeout
- if semanticInactivityTimeout == 0 {
- semanticInactivityTimeout = defaultCodexSemanticInactivityTimeout
- }
- handshakeTimeout, threadHandshakeTimeout := resolveCodexHandshakeTimeouts(opts)
- runCtx, cancel := runContext(ctx, timeout)
-
- codexHome := strings.TrimSpace(b.cfg.Env["CODEX_HOME"])
- if codexHome != "" {
- if err := ensureCodexMcpConfig(filepath.Join(codexHome, "config.toml"), opts.McpConfig, b.cfg.Logger); err != nil {
- cancel()
- return nil, fmt.Errorf("apply codex mcp_config: %w", err)
- }
- } else if hasManagedCodexMcpConfig(opts.McpConfig) {
- cancel()
- return nil, fmt.Errorf("codex: mcp_config is set but CODEX_HOME env var is not configured; cannot apply managed MCP")
- }
-
- runtimeCmd := b.cfg.commandAt(execPath)
- if codexHome != "" {
- opts.ExtraArgs = filterCodexShellEnvConfigOverrides(opts.ExtraArgs, b.cfg.Logger)
- opts.CustomArgs = filterCodexShellEnvConfigOverrides(opts.CustomArgs, b.cfg.Logger)
- runtimeCmd = runtimeCmd.withFilteredPrefix(func(prefix []string) []string {
- return filterCodexShellEnvConfigOverrides(prefix, b.cfg.Logger)
- })
- }
- if hasManagedCodexMcpConfig(opts.McpConfig) {
- runtimeCmd = runtimeCmd.withFilteredPrefix(func(prefix []string) []string {
- return filterCodexCustomConfigOverrides(prefix, b.cfg.Logger)
- })
- }
- if opts.ServiceTier == codexFastServiceTier {
- runtimeCmd = runtimeCmd.withFilteredPrefix(func(prefix []string) []string {
- return stripCodexFastModeConflicts(prefix, b.cfg.Logger)
- })
- }
- codexArgs := buildCodexArgs(opts, b.cfg.Logger)
-
- var configFiles []string
- if codexHome != "" {
- configFiles = append(configFiles, filepath.Join(codexHome, "config.toml"))
- }
- fingerprint := computeWarmSessionFingerprint(WarmSessionFingerprintInput{
- Provider: "codex",
- Executable: execPath,
- LaunchPrefix: runtimeCmd.Prefix,
- Args: codexArgs,
- Cwd: opts.Cwd,
- Model: opts.Model,
- ThinkingLevel: opts.ThinkingLevel,
- ServiceTier: opts.ServiceTier,
- McpConfig: opts.McpConfig,
- ConfigFiles: configFiles,
- BriefHash: opts.WarmPoolBriefHash,
- Env: b.cfg.Env,
- })
-
- var warmProc *warmCodexProcess
- warmHit := false
- if opts.ResumeSessionID != "" {
- if acquired := b.cfg.WarmPool.Acquire("codex", opts.ResumeSessionID, fingerprint); acquired != nil {
- if candidate, ok := acquired.(*warmCodexProcess); ok {
- if err := WriteTaskEnvFile(candidate.taskEnvFile, b.cfg.Env); err != nil {
- b.cfg.Logger.Warn("warm codex: failed to refresh task env overlay; evicting", "error", err)
- candidate.Close()
- } else {
- warmProc = candidate
- warmHit = true
- }
- } else {
- acquired.Close()
- }
- }
- }
-
- var activeLaunches int64
- if !warmHit {
- var err error
- warmProc, activeLaunches, err = b.spawnWarmCodexProcess(runtimeCmd, codexArgs, opts, fingerprint, handshakeTimeout, threadHandshakeTimeout, attempt)
- if err != nil {
- cancel()
- return nil, err
- }
- } else {
- activeLaunches = activeCodexLaunches.Load()
- warmProc.client.handshakeTimeout = handshakeTimeout
- warmProc.client.threadHandshakeTimeout = threadHandshakeTimeout
- warmProc.client.attempt = attempt
- warmProc.client.activeLaunches = activeLaunches
- }
-
- codexVersion := strings.TrimSpace(b.cfg.CodexVersion)
- if codexVersion == "" {
- codexVersion = "unknown"
- }
-
- msgCh := make(chan Message, 256)
- resCh := make(chan Result, 1)
- semanticActivityCh := make(chan string, 256)
- guardianRateLimitTrip := make(chan struct{}, 1)
- var guardianRateLimitTripped atomic.Bool
-
- var outputMu sync.Mutex
- var output codexOutputSelection
- var semanticObserved atomic.Bool
- turnNotificationGate := &codexTurnNotificationGate{}
- firstItemWait := &codexFirstItemWaitObservation{}
- turnDone := make(chan bool, 1)
-
- c := warmProc.client
- observeMessage := func(msg Message) {
- logCodexAgentMessage(b.cfg.Logger, msg)
- activity := describeCodexSemanticActivity(msg)
- if activity == "status:running" {
- firstItemWait.start(time.Now(), c.activeTurnID())
- }
- trySendString(semanticActivityCh, activity)
- if activity != "" {
- semanticObserved.Store(true)
- }
- }
-
- c.attachTurnHooks(codexTurnHooks{
- cfg: b.cfg,
- acceptNotification: turnNotificationGate.accept,
- guardianRateLimitCircuit: &codexGuardianRateLimitCircuit{},
- rateLimits: newRateLimitTracker(opts.OnRateLimits),
- preserveUsageBaseline: warmHit,
- onGuardianRateLimit: func() {
- guardianRateLimitTripped.Store(true)
- b.cfg.Logger.Warn("codex Guardian approval rate-limit circuit opened",
- "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID,
- "failure_count", codexGuardianRateLimitThreshold)
- select {
- case guardianRateLimitTrip <- struct{}{}:
- default:
- }
- },
- onDiscardedNotification: func(string, map[string]any) {
- semanticObserved.Store(true)
- },
- onMessage: func(msg Message) {
- observeMessage(msg)
- trySend(msgCh, msg)
- },
- onAgentMessageChunk: func(text string) bool {
- msg := Message{Type: MessageText, Content: text}
- observeMessage(msg)
- return trySend(msgCh, msg)
- },
- onAgentMessage: func(text, phase string) {
- outputMu.Lock()
- output.observeAgentMessage(text, phase)
- outputMu.Unlock()
- },
- onFinalAnswer: func(text string) {
- outputMu.Lock()
- output.observeFinalAnswer(text)
- outputMu.Unlock()
- },
- onSemanticActivity: func(description string) {
- semanticObserved.Store(true)
- b.cfg.Logger.Debug("codex semantic activity observed", "activity", description)
- trySendString(semanticActivityCh, description)
- },
- onTurnDone: func(aborted bool) {
- select {
- case turnDone <- aborted:
- default:
- }
- },
- })
-
- go func() {
- defer cancel()
- defer close(msgCh)
- defer close(resCh)
-
- startTime := time.Now()
- finalStatus := "completed"
- var finalError string
- var threadID string
- var resumed bool
-
- closeWarmProc := func() bool {
- c.detachTurnHooks()
- return warmProc.Close()
- }
-
- if warmHit {
- threadID = warmProc.threadID
- resumed = true
- c.setThreadID(threadID)
- b.cfg.Logger.Info("codex warm session reused",
- "task_id", b.cfg.TaskID,
- "runtime_id", b.cfg.RuntimeID,
- "pid", warmProc.cmd.Process.Pid,
- "thread_id", threadID,
- )
- trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: threadID})
- } else {
- // 1. Initialize handshake
- initializeStarted := time.Now()
- b.cfg.Logger.Info("codex lifecycle", "phase", "initialize_sent", "warm_pool", true, "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID, "pid", warmProc.cmd.Process.Pid, "attempt", attempt, "active_launches", activeLaunches)
- _, err := c.request(runCtx, "initialize", map[string]any{
- "clientInfo": map[string]any{
- "name": "multica-agent-sdk",
- "title": "Multica Agent SDK",
- "version": "0.2.0",
- },
- "capabilities": map[string]any{
- "experimentalApi": true,
- },
- })
- if err != nil {
- initializeLatency := time.Since(initializeStarted)
- var handshakeErr *codexHandshakeTimeoutError
- timedOut := errors.As(err, &handshakeErr) && handshakeErr.Method == "initialize"
- if timedOut {
- signalProcessGroup(warmProc.cmd, syscall.SIGKILL)
- } else if runCtx.Err() != nil {
- warmProc.stopProcess()
- }
- cleanupConfirmed := closeWarmProc()
- finalStatus = "failed"
- finalError = fmt.Sprintf("codex initialize failed: %v", err)
- contextEnded := errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)
- if !timedOut && !contextEnded {
- finalError = withAgentStderr(finalError, "codex", sanitizeCodexDiagnostic(warmProc.stderrBuf.Tail()))
- }
- retrySafe := timedOut && !semanticObserved.Load() && cleanupConfirmed && codexInitializeRetrySupported()
- if timedOut && !cleanupConfirmed {
- finalError += "; retry suppressed: process cleanup/reap not confirmed"
- } else if timedOut && cleanupConfirmed && !codexInitializeRetrySupported() {
- finalError += "; retry suppressed: process-tree cleanup cannot be confirmed on this platform"
- }
- b.cfg.Logger.Warn("codex lifecycle", "phase", "initialize_failure", "warm_pool", true, "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID, "pid", warmProc.cmd.Process.Pid, "attempt", attempt, "latency", initializeLatency.Round(time.Millisecond).String(), "semantic_activity", semanticObserved.Load(), "cleanup_confirmed", cleanupConfirmed, "retry_safe", retrySafe)
- resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), codexInitializeRetrySafe: retrySafe}
- return
- }
- b.cfg.Logger.Info("codex lifecycle", "phase", "initialize_response", "warm_pool", true, "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID, "pid", warmProc.cmd.Process.Pid, "attempt", attempt, "latency", time.Since(initializeStarted).Round(time.Millisecond).String())
- c.notify("initialized")
-
- // 2. Start or resume thread
- threadID, resumed, err = c.startOrResumeThread(runCtx, opts, b.cfg.Logger)
- if err != nil {
- var handshakeErr *codexHandshakeTimeoutError
- timedOut := errors.As(err, &handshakeErr) && isCodexThreadSetupRPC(handshakeErr.Method)
- if timedOut {
- signalProcessGroup(warmProc.cmd, syscall.SIGKILL)
- } else if runCtx.Err() != nil {
- warmProc.stopProcess()
- }
- cleanupConfirmed := closeWarmProc()
- finalStatus = "failed"
- stderrTail := sanitizeCodexDiagnostic(warmProc.stderrBuf.Tail())
- finalError = err.Error()
- retrySafe := timedOut && cleanupConfirmed
- if retrySafe {
- finalStatus = "timeout"
- } else if timedOut {
- finalError += "; retry suppressed: process cleanup/reap not confirmed"
- }
- if c.threadSetupMethod != "" {
- classification := classifyCodexStartupStderr(stderrTail, timedOut)
- b.cfg.Logger.Warn("codex lifecycle",
- "phase", strings.ReplaceAll(c.threadSetupMethod, "/", "_")+"_failure",
- "warm_pool", true,
- "task_id", b.cfg.TaskID,
- "runtime_id", b.cfg.RuntimeID,
- "pid", warmProc.cmd.Process.Pid,
- "attempt", attempt,
- "active_launches", activeLaunches,
- "method", c.threadSetupMethod,
- "latency", time.Since(c.threadSetupStarted).Round(time.Millisecond).String(),
- "latency_ms", time.Since(c.threadSetupStarted).Milliseconds(),
- "cleanup_confirmed", cleanupConfirmed,
- "reaped", cleanupConfirmed,
- "retry_safe", retrySafe,
- "retry_attempted", false,
- "stderr_model_refresh_failure_count", classification.modelRefreshFailure,
- "stderr_model_refresh_timeout_count", classification.modelRefreshTimeout,
- "stderr_mcp_init_transport_count", classification.mcpInitTransport,
- "stderr_bare_timeout_count", classification.bareTimeout,
- )
- }
- resCh <- Result{
- Status: finalStatus,
- Error: finalError,
- DurationMs: time.Since(startTime).Milliseconds(),
- ResumeRejected: isCodexResumeOverflow(opts, err),
- }
- return
- }
- c.setThreadID(threadID)
- if resumed {
- b.cfg.Logger.Info("codex thread resumed", "thread_id", threadID)
- } else {
- b.cfg.Logger.Info("codex thread started", "thread_id", threadID)
- }
- }
-
- // 3. Send turn and wait for completion
- turnPrompt := b.skillTurnPrompt(runCtx, c, prompt, opts)
- turnParams := map[string]any{
- "threadId": threadID,
- "input": codexTurnInput(turnPrompt, opts.ResumeExpected, resumed, opts.ResumeContinuityNotice),
- }
- applyCodexReasoningEffort(turnParams, opts.ThinkingLevel)
- applyCodexServiceTier(turnParams, opts.ServiceTier)
- waitingForTurn := true
- var timeoutDiagnostic codexTimeoutDiagnostic
- var processExitErr error
- finishFirstItemWait := func(outcome string) {
- firstItemWait.finish(
- time.Now(),
- outcome,
- classifyCodexStartupStderr(warmProc.stderrBuf.Tail(), strings.HasSuffix(outcome, "_timeout")),
- )
- }
- finishTurn := func(aborted bool) {
- waitingForTurn = false
- switch {
- case aborted:
- finishFirstItemWait("turn_aborted")
- finalStatus = "aborted"
- if errMsg := c.getTurnError(); errMsg != "" {
- finalError = errMsg
- } else {
- finalError = "turn was aborted"
- }
- default:
- if errMsg := c.getTurnError(); errMsg != "" {
- finishFirstItemWait("turn_failed")
- finalStatus = "failed"
- finalError = errMsg
- } else {
- finishFirstItemWait("turn_completed")
- }
- }
- }
- finishRunContextDone := func() {
- waitingForTurn = false
- if runCtx.Err() == context.DeadlineExceeded {
- finishFirstItemWait("execution_timeout")
- finalStatus = "timeout"
- finalError = fmt.Sprintf("codex timed out after %s", timeout)
- } else {
- finishFirstItemWait("cancelled")
- finalStatus = "aborted"
- finalError = "execution cancelled"
- }
- }
- turnNotificationGate.arm()
- _, err := c.request(runCtx, "turn/start", turnParams)
- if err != nil {
- if runCtx.Err() != nil {
- finishRunContextDone()
- if !interruptCodexTurn(c, threadID, turnDone, opts.TurnInterruptTimeout, b.cfg.Logger) {
- warmProc.stopProcess()
- }
- } else {
- select {
- case aborted := <-turnDone:
- finishTurn(aborted)
- default:
- closeWarmProc()
- finalStatus = "failed"
- finalError = withAgentStderr(fmt.Sprintf("codex turn/start failed: %v", err), "codex", sanitizeCodexDiagnostic(warmProc.stderrBuf.Tail()))
- resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}
- return
- }
- }
- }
-
- lastSemanticActivity := time.Now()
- lastSemanticActivityDescription := "turn/start"
- semanticTimer := time.NewTimer(semanticInactivityTimeout)
- defer semanticTimer.Stop()
-
- firstTurnNoProgressTimeout := codexFirstTurnNoProgressTimeout(semanticInactivityTimeout, opts.FirstTurnNoProgressTimeout)
- var firstTurnNoProgressTimer *time.Timer
- var firstTurnNoProgressTimerC <-chan time.Time
- firstTurnStarted := false
- firstTurnProgressObserved := false
- stopFirstTurnNoProgressTimer := func() {
- if firstTurnNoProgressTimer == nil {
- return
- }
- stopTimer(firstTurnNoProgressTimer)
- firstTurnNoProgressTimerC = nil
- }
- defer stopFirstTurnNoProgressTimer()
-
- for waitingForTurn {
- select {
- case aborted := <-turnDone:
- finishTurn(aborted)
- case <-guardianRateLimitTrip:
- waitingForTurn = false
- finishFirstItemWait("guardian_rate_limit")
- finalStatus = "failed"
- finalError = codexGuardianRateLimitError
- if !interruptCodexTurn(c, threadID, turnDone, opts.TurnInterruptTimeout, b.cfg.Logger) {
- warmProc.stopProcess()
- }
- case activity := <-semanticActivityCh:
- lastSemanticActivity = time.Now()
- lastSemanticActivityDescription = activity
- resetTimer(semanticTimer, semanticInactivityTimeout)
- if activity == "status:running" && !firstTurnStarted {
- firstTurnStarted = true
- firstItemWait.start(time.Now(), c.activeTurnID())
- firstTurnNoProgressTimer = time.NewTimer(firstTurnNoProgressTimeout)
- firstTurnNoProgressTimerC = firstTurnNoProgressTimer.C
- } else if firstTurnStarted && !firstTurnProgressObserved && isCodexFirstTurnProgressActivity(activity) {
- firstTurnProgressObserved = true
- if activity == "error:terminal" {
- finishFirstItemWait("turn_failed")
- } else {
- finishFirstItemWait("progress")
- }
- stopFirstTurnNoProgressTimer()
- }
- case <-firstTurnNoProgressTimerC:
- waitingForTurn = false
- finishFirstItemWait("no_progress_timeout")
- finalStatus = "timeout"
- turnID := c.activeTurnID()
- timeoutDiagnostic = codexTimeoutDiagnostic{
- Kind: codexTimeoutFirstTurnNoProgress,
- Timeout: firstTurnNoProgressTimeout,
- LastActivity: lastSemanticActivityDescription,
- ThreadID: threadID,
- TurnID: turnID,
- Model: opts.Model,
- }
- b.cfg.Logger.Warn(CodexFirstTurnNoProgressMarker,
- "pid", warmProc.cmd.Process.Pid,
- "thread_id", threadID,
- "turn_id", turnID,
- "timeout", firstTurnNoProgressTimeout.String(),
- "last_activity", lastSemanticActivityDescription,
- )
- case <-semanticTimer.C:
- waitingForTurn = false
- finishFirstItemWait("semantic_inactivity_timeout")
- finalStatus = "timeout"
- turnID := c.activeTurnID()
- timeoutDiagnostic = codexTimeoutDiagnostic{
- Kind: codexTimeoutSemanticInactivity,
- Timeout: semanticInactivityTimeout,
- LastActivity: lastSemanticActivityDescription,
- ThreadID: threadID,
- TurnID: turnID,
- Model: opts.Model,
- }
- b.cfg.Logger.Warn(CodexSemanticInactivityMarker,
- "pid", warmProc.cmd.Process.Pid,
- "thread_id", threadID,
- "turn_id", turnID,
- "timeout", semanticInactivityTimeout.String(),
- "last_activity", lastSemanticActivityDescription,
- "idle_for", time.Since(lastSemanticActivity).Round(time.Millisecond).String(),
- )
- case <-runCtx.Done():
- finishRunContextDone()
- if !interruptCodexTurn(c, threadID, turnDone, opts.TurnInterruptTimeout, b.cfg.Logger) {
- warmProc.stopProcess()
- }
- case <-c.processDone:
- select {
- case aborted := <-turnDone:
- finishTurn(aborted)
- default:
- if runCtx.Err() != nil {
- finishRunContextDone()
- } else {
- waitingForTurn = false
- finishFirstItemWait("process_exit")
- finalStatus = "failed"
- processExitErr = c.getProcessErr()
- if processExitErr == nil {
- processExitErr = errCodexProcessExited
- }
- finalError = processExitErr.Error()
- }
- }
- }
- }
- if guardianRateLimitTripped.Load() {
- finalStatus = "failed"
- finalError = codexGuardianRateLimitError
- }
-
- duration := time.Since(startTime)
- b.cfg.Logger.Info("codex finished", "pid", warmProc.cmd.Process.Pid, "warm_hit", warmHit, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
-
- // Flush any buffered agent message deltas and capture outputs/usage
- // before detaching hooks and parking or closing the process.
- c.detachTurnHooks()
- _ = ClearTaskEnvFile(warmProc.taskEnvFile)
-
- outputMu.Lock()
- finalOutput := codexDeliverableOutput(output)
- outputMu.Unlock()
-
- c.usageMu.Lock()
- u := c.usage
- c.usageMu.Unlock()
-
- canPark := finalStatus == "completed" &&
- finalError == "" &&
- !guardianRateLimitTripped.Load() &&
- processExitErr == nil &&
- threadID != "" &&
- warmProc.Alive() &&
- runCtx.Err() == nil
-
- var cleanupConfirmed bool
- if canPark {
- warmProc.threadID = threadID
- b.cfg.WarmPool.Park("codex", threadID, warmProc)
- } else {
- cleanupConfirmed = warmProc.Close()
- }
-
- if processExitErr != nil {
- finalError = withAgentStderr(processExitErr.Error(), "codex", sanitizeCodexDiagnostic(warmProc.stderrBuf.Tail()))
- }
- stderrTail := sanitizeCodexDiagnostic(warmProc.stderrBuf.Tail())
- if timeoutDiagnostic.Kind != codexTimeoutNone {
- timeoutDiagnostic.CodexVersion = detectCodexVersionForDiagnostics(context.Background(), b.cfg.commandAt(execPath), warmProc.cmd.Env, b.cfg.Logger)
- finalError = buildCodexTimeoutDiagnosticError(timeoutDiagnostic, stderrTail)
- }
-
- startupRefreshRetrySafe := !canPark &&
- timeoutDiagnostic.Kind == codexTimeoutFirstTurnNoProgress &&
- !firstTurnProgressObserved &&
- strings.Contains(stderrTail, codexModelCatalogRefreshFailureSignal) &&
- cleanupConfirmed && codexInitializeRetrySupported()
-
- if waitLatency, firstTurnID, outcome, classification, ok := firstItemWait.snapshot(); ok {
- if waitLatency < 0 {
- waitLatency = 0
- }
- if strings.HasSuffix(outcome, "_timeout") {
- classification = classifyCodexStartupStderr(stderrTail, true)
- }
- fields := []any{
- "phase", "first_item_wait",
- "warm_pool", true,
- "warm_hit", warmHit,
- "task_id", b.cfg.TaskID,
- "runtime_id", b.cfg.RuntimeID,
- "pid", warmProc.cmd.Process.Pid,
- "attempt", attempt,
- "active_launches", activeLaunches,
- "method", "turn/start",
- "thread_id", threadID,
- "turn_id", firstTurnID,
- "outcome", outcome,
- "latency", waitLatency.Round(time.Millisecond).String(),
- "latency_ms", waitLatency.Milliseconds(),
- "timeout", firstTurnNoProgressTimeout.String(),
- "semantic_inactivity_timeout", semanticInactivityTimeout.String(),
- "codex_version", codexVersion,
- "daemon_version", b.cfg.DaemonVersion,
- "cleanup_confirmed", cleanupConfirmed,
- "reaped", cleanupConfirmed,
- "retry_safe", startupRefreshRetrySafe,
- "stderr_model_refresh_failure_count", classification.modelRefreshFailure,
- "stderr_model_refresh_timeout_count", classification.modelRefreshTimeout,
- "stderr_mcp_init_transport_count", classification.mcpInitTransport,
- "stderr_bare_timeout_count", classification.bareTimeout,
- }
- switch outcome {
- case "progress", "turn_completed":
- b.cfg.Logger.Info("codex lifecycle", fields...)
- default:
- b.cfg.Logger.Warn("codex lifecycle", fields...)
- }
- }
-
- taskCodexHome := strings.TrimSpace(b.cfg.Env["CODEX_HOME"])
- usageMap := codexResultUsageMap(startTime, taskCodexHome, threadID, resumed, opts.Model, u)
-
- resCh <- Result{
- Status: finalStatus,
- Output: finalOutput,
- Error: finalError,
- SessionID: threadID,
- DurationMs: duration.Milliseconds(),
- Usage: usageMap,
- codexStartupRefreshRetrySafe: startupRefreshRetrySafe,
- }
- }()
-
- supplement := func(supplementCtx context.Context, instruction string) error {
- return supplementCodexTurn(supplementCtx, c, instruction)
- }
- supplementReady := func() bool {
- return c.getThreadID() != "" && c.activeTurnID() != ""
- }
- return &Session{Supplement: supplement, SupplementReady: supplementReady, Messages: msgCh, Result: resCh}, nil
-}
-
-func (b *codexBackend) spawnWarmCodexProcess(
- runtimeCmd Command,
- codexArgs []string,
- opts ExecOptions,
- fingerprint string,
- handshakeTimeout time.Duration,
- threadHandshakeTimeout time.Duration,
- attempt int,
-) (*warmCodexProcess, int64, error) {
- sessionDir, err := os.MkdirTemp("", "multica-codex-warm-*")
- if err != nil {
- return nil, 0, fmt.Errorf("create warm codex session dir: %w", err)
- }
- sessionTempDir := filepath.Join(sessionDir, "tmp")
- if err := os.MkdirAll(sessionTempDir, 0o700); err != nil {
- _ = os.RemoveAll(sessionDir)
- return nil, 0, fmt.Errorf("create warm codex temp dir: %w", err)
- }
- taskEnvFile := filepath.Join(sessionDir, "task-env.json")
- if err := WriteTaskEnvFile(taskEnvFile, b.cfg.Env); err != nil {
- _ = os.RemoveAll(sessionDir)
- return nil, 0, fmt.Errorf("write warm codex task env overlay: %w", err)
- }
-
- processCtx, stopProcess := context.WithCancel(context.Background())
- cmd := runtimeCmd.exec(processCtx, codexArgs...)
- hideAgentWindow(cmd)
- cmd.Cancel = func() error {
- if cmd.Process != nil {
- signalProcessGroup(cmd, syscall.SIGKILL)
- }
- return nil
- }
- cmd.WaitDelay = codexProcessWaitDelay()
- b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(codexArgs, trustAgentCommandPositional(0, "app-server")))
- if opts.Cwd != "" {
- cmd.Dir = opts.Cwd
- }
- cmd.Env = buildEnv(PreparePooledChildEnv(b.cfg.Env, taskEnvFile, sessionTempDir))
-
- stdout, err := cmd.StdoutPipe()
- if err != nil {
- stopProcess()
- _ = os.RemoveAll(sessionDir)
- return nil, 0, fmt.Errorf("codex stdout pipe: %w", err)
- }
- stdinPipe, err := cmd.StdinPipe()
- if err != nil {
- stopProcess()
- _ = os.RemoveAll(sessionDir)
- return nil, 0, fmt.Errorf("codex stdin pipe: %w", err)
- }
- stdin := &codexSyncWriter{w: stdinPipe}
- stderrBuf := newStderrTail(io.Discard, codexStderrTailBytes)
- cmd.Stderr = stderrBuf
-
- if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
- stopProcess()
- _ = os.RemoveAll(sessionDir)
- return nil, 0, fmt.Errorf("start codex: %w", err)
- }
- activeLaunches := activeCodexLaunches.Add(1)
- for {
- maxSeen := maxActiveCodexLaunchesObserved.Load()
- if activeLaunches <= maxSeen || maxActiveCodexLaunchesObserved.CompareAndSwap(maxSeen, activeLaunches) {
- break
- }
- }
- launchStarted := time.Now()
- codexVersion := strings.TrimSpace(b.cfg.CodexVersion)
- if codexVersion == "" {
- codexVersion = "unknown"
- }
- b.cfg.Logger.Info("codex lifecycle",
- "phase", "spawn",
- "warm_pool", true,
- "task_id", b.cfg.TaskID,
- "runtime_id", b.cfg.RuntimeID,
- "pid", cmd.Process.Pid,
- "process_group", cmd.Process.Pid,
- "cwd", opts.Cwd,
- "attempt", attempt,
- "active_launches", activeLaunches,
- "codex_version", codexVersion,
- "daemon_version", b.cfg.DaemonVersion,
- )
-
- c := &codexClient{
- cfg: b.cfg,
- stdin: stdin,
- pending: make(map[int]*pendingRPC),
- processDone: make(chan struct{}),
- handshakeTimeout: handshakeTimeout,
- threadHandshakeTimeout: threadHandshakeTimeout,
- pid: cmd.Process.Pid,
- attempt: attempt,
- activeLaunches: activeLaunches,
- notificationProtocol: "unknown",
- acceptNotification: func(string, map[string]any) bool { return false },
- }
-
- readerDone := make(chan struct{})
- go func() {
- defer close(readerDone)
- scanner := newAgentStreamScanner(stdout)
- for scanner.Scan() {
- line := strings.TrimSpace(scanner.Text())
- if line == "" {
- continue
- }
- c.handleLine(line)
- }
- c.flushAgentMessageDeltasLocked()
- if err := scanner.Err(); err != nil {
- c.markProcessExited(fmt.Errorf("%w: %w", errCodexProcessExited, err))
- return
- }
- c.markProcessExited(errCodexProcessExited)
- }()
-
- return &warmCodexProcess{
- fingerprint: fingerprint,
- cmd: cmd,
- stdin: stdin,
- stderrBuf: stderrBuf,
- client: c,
- stopProcess: stopProcess,
- readerDone: readerDone,
- sessionDir: sessionDir,
- taskEnvFile: taskEnvFile,
- sessionTempDir: sessionTempDir,
- launchStarted: launchStarted,
- logger: b.cfg.Logger,
- }, activeLaunches, nil
-}
diff --git a/server/pkg/agent/codex_process.go b/server/pkg/agent/codex_process.go
new file mode 100644
index 0000000000..6beb628f68
--- /dev/null
+++ b/server/pkg/agent/codex_process.go
@@ -0,0 +1,534 @@
+package agent
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "syscall"
+ "time"
+)
+
+// codexSyncWriter serializes concurrent writes to a Codex app-server stdin pipe
+// (lifecycle RPCs, server-request approval replies from the stdout reader, and
+// mid-turn turn/steer calls).
+type codexSyncWriter struct {
+ mu sync.Mutex
+ w io.WriteCloser
+}
+
+func (w *codexSyncWriter) Write(p []byte) (int, error) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ return w.w.Write(p)
+}
+
+func (w *codexSyncWriter) Close() error {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ return w.w.Close()
+}
+
+type codexTurnHooks struct {
+ cfg Config
+ acceptNotification func(method string, params map[string]any) bool
+ onDiscardedNotification func(method string, params map[string]any)
+ onMessage func(Message)
+ onAgentMessageChunk func(text string) bool
+ onAgentMessage func(text, phase string)
+ onFinalAnswer func(text string)
+ onSemanticActivity func(description string)
+ onTurnDone func(aborted bool)
+ guardianRateLimitCircuit *codexGuardianRateLimitCircuit
+ onGuardianRateLimit func()
+ rateLimits *rateLimitTracker
+ preserveUsageBaseline bool
+}
+
+func (c *codexClient) attachTurnHooks(h codexTurnHooks) {
+ c.hookMu.Lock()
+ defer c.hookMu.Unlock()
+
+ c.cfg = h.cfg
+ c.acceptNotification = h.acceptNotification
+ c.onDiscardedNotification = h.onDiscardedNotification
+ c.onMessage = h.onMessage
+ c.onAgentMessageChunk = h.onAgentMessageChunk
+ c.onAgentMessage = h.onAgentMessage
+ c.onFinalAnswer = h.onFinalAnswer
+ c.onSemanticActivity = h.onSemanticActivity
+ c.onTurnDone = h.onTurnDone
+ c.guardianRateLimitCircuit = h.guardianRateLimitCircuit
+ c.onGuardianRateLimit = h.onGuardianRateLimit
+ c.rateLimits = h.rateLimits
+
+ c.agentMessageStreams = nil
+ c.agentMessageOrder = nil
+ c.turnCompleted = false
+ c.setActiveTurnID("")
+
+ c.turnErrorMu.Lock()
+ c.turnError = ""
+ c.turnErrorMu.Unlock()
+
+ c.usageMu.Lock()
+ c.usage = TokenUsage{}
+ if !h.preserveUsageBaseline {
+ c.usageTotal = codexRawTokenUsage{}
+ c.usageTotalSet = false
+ }
+ c.usageMu.Unlock()
+}
+
+func (c *codexClient) detachTurnHooks() {
+ c.hookMu.Lock()
+ defer c.hookMu.Unlock()
+
+ c.flushAgentMessageDeltas()
+ c.acceptNotification = func(string, map[string]any) bool { return false }
+ c.onDiscardedNotification = nil
+ c.onMessage = nil
+ c.onAgentMessageChunk = nil
+ c.onAgentMessage = nil
+ c.onFinalAnswer = nil
+ c.onSemanticActivity = nil
+ c.onTurnDone = nil
+ c.onGuardianRateLimit = nil
+ c.rateLimits = nil
+ c.agentMessageStreams = nil
+ c.agentMessageOrder = nil
+ c.setActiveTurnID("")
+}
+
+func (c *codexClient) flushAgentMessageDeltasLocked() {
+ c.hookMu.Lock()
+ c.flushAgentMessageDeltas()
+ c.hookMu.Unlock()
+}
+
+func (c *codexClient) turnUsage() TokenUsage {
+ c.usageMu.Lock()
+ defer c.usageMu.Unlock()
+ return c.usage
+}
+
+// codexProcess is one Codex app-server process. A run either spawns one or,
+// when the warm pool is enabled, acquires one an earlier turn of the same
+// thread parked; the turn lifecycle in executeOnce is the same for both.
+//
+// A pooled process outlives the turn that spawned it: it reads volatile task
+// credentials from a per-session overlay file and owns a private session dir.
+// A one-shot process inherits the task env directly and is reaped with its
+// turn.
+type codexProcess struct {
+ pooled bool
+ fingerprint string
+ threadID string
+ cmd *exec.Cmd
+ stdin *codexSyncWriter
+ stdout io.ReadCloser
+ stderrBuf *stderrTail
+ client *codexClient
+ stopProcess context.CancelFunc
+ readerDone chan struct{}
+ sessionDir string
+ taskEnvFile string
+ attempt int
+ launchStarted time.Time
+ logger *slog.Logger
+
+ closed atomic.Bool
+ closeOnce sync.Once
+ cleanupConfirmed bool
+}
+
+func (p *codexProcess) Fingerprint() string { return p.fingerprint }
+
+func (p *codexProcess) Alive() bool {
+ if p.closed.Load() {
+ return false
+ }
+ if p.client.getProcessErr() != nil {
+ return false
+ }
+ select {
+ case <-p.readerDone:
+ return false
+ default:
+ return true
+ }
+}
+
+// clearTaskEnv drops the finished turn's credentials from a pooled process's
+// overlay so nothing it does while idle can act as that task.
+func (p *codexProcess) clearTaskEnv() {
+ if p.taskEnvFile != "" {
+ _ = ClearTaskEnvFile(p.taskEnvFile)
+ }
+}
+
+// endTurn stops a pooled process from feeding the finished turn before it is
+// parked or closed. A one-shot process keeps its hooks until it is reaped, so
+// whatever it flushes on the way out still reaches the run.
+func (p *codexProcess) endTurn() {
+ if !p.pooled {
+ return
+ }
+ p.client.detachTurnHooks()
+ p.clearTaskEnv()
+}
+
+// Close closes stdin and joins the process exactly once, reporting whether
+// the whole process tree was confirmed reaped. Read stderrBuf only after it
+// returns, when os/exec's copy goroutines have finished.
+//
+// Wait for readerDone before cmd.Wait so Wait cannot close a pipe under an
+// active read. Bound both reader shutdown and process reaping. Scanner
+// overflow can leave the child blocked on unread stdout, so cancellation and
+// WaitDelay must also cover that path instead of relying on stdin EOF to stop
+// the child.
+func (p *codexProcess) Close() bool {
+ p.closeOnce.Do(func() {
+ p.closed.Store(true)
+ p.clearTaskEnv()
+ _ = p.stdin.Close()
+
+ grace := codexGracefulShutdown()
+ waitCh := make(chan struct{})
+ var waitErr error
+ var startWait sync.Once
+ startProcessWait := func() {
+ startWait.Do(func() {
+ go func() {
+ waitErr = p.cmd.Wait()
+ close(waitCh)
+ }()
+ })
+ }
+
+ // Phase 1: let the reader finish before invoking cmd.Wait().
+ select {
+ case <-p.readerDone:
+ // reader drained cleanly (codex shutdown closed stdout) or aborted
+ // early (e.g. scanner overflow). Either way it is now safe to call
+ // cmd.Wait().
+ case <-time.After(grace):
+ // codex did not close stdout within the grace window. Force the
+ // shutdown via context cancellation — cmd.Cancel group-kills the
+ // tree, the reader unblocks when stdout EOFs, and we proceed to
+ // phase 2.
+ p.logger.Warn("codex did not close stdout after stdin EOF; forcing shutdown",
+ "pid", p.cmd.Process.Pid,
+ "grace", grace.String(),
+ )
+ p.stopProcess()
+ // On Windows, Cancel terminates only the direct child. A descendant
+ // may keep inherited stdout open indefinitely. Start Wait now so
+ // os/exec's WaitDelay closes the pipe after its bounded deadline and
+ // lets the reader finish.
+ startProcessWait()
+ <-waitCh
+ select {
+ case <-p.readerDone:
+ case <-time.After(grace):
+ p.logger.Warn("codex stdout reader remained open after bounded process wait",
+ "pid", p.cmd.Process.Pid,
+ "grace", grace.String(),
+ )
+ }
+ }
+
+ // Phase 2: bound cmd.Wait() in case the process is still alive
+ // (scanner-overflow case: reader exited early on its own while codex
+ // stayed blocked writing into a full stdout pipe).
+ startProcessWait()
+ var waitReturned bool
+ select {
+ case <-waitCh:
+ waitReturned = true
+ case <-time.After(grace):
+ p.logger.Warn("codex process still alive after reader exited; forcing shutdown",
+ "pid", p.cmd.Process.Pid,
+ "grace", grace.String(),
+ )
+ p.stopProcess()
+ // WaitDelay is the final backstop: even if the group-kill races
+ // with an open pipe held by a descendant, cmd.Wait() returns within
+ // WaitDelay of the cancel.
+ <-waitCh
+ waitReturned = true
+ }
+
+ // Wait returning with a ProcessState is the os/exec reap boundary. On
+ // Unix, ProcessState.Exited reports false for a process terminated by
+ // SIGKILL even though Wait successfully reaped it.
+ p.cleanupConfirmed = waitReturned && p.cmd.ProcessState != nil && waitProcessGroupGone(p.cmd, grace)
+ if codexCleanupConfirmationOverride.Load() < 0 {
+ p.cleanupConfirmed = false
+ }
+ p.logger.Info("codex lifecycle",
+ "phase", "cleanup",
+ "warm_pool", p.pooled,
+ "pid", p.cmd.Process.Pid,
+ "process_group", p.cmd.Process.Pid,
+ "attempt", p.attempt,
+ "latency", time.Since(p.launchStarted).Round(time.Millisecond).String(),
+ "reaped", p.cleanupConfirmed,
+ "exit_status", codexProcessExitStatus(p.cmd.ProcessState),
+ "wait_error", waitErr,
+ "stderr_bytes", p.stderrBuf.TotalBytes(),
+ "stderr_truncated", p.stderrBuf.TotalBytes() > codexStderrTailBytes,
+ )
+ // The tree has been reaped and observed; drop ownership. This is the
+ // only safe point to do so on Windows, where releasing kills whatever
+ // is still inside the job — which is precisely what should happen to
+ // anything that outlived the reap above.
+ releaseProcessGroup(p.cmd)
+ p.stopProcess()
+ activeCodexLaunches.Add(-1)
+ if p.sessionDir != "" {
+ _ = os.RemoveAll(p.sessionDir)
+ }
+ })
+ return p.cleanupConfirmed
+}
+
+func (b *codexBackend) spawnCodexProcess(
+ runtimeCmd Command,
+ codexArgs []string,
+ opts ExecOptions,
+ pooled bool,
+ fingerprint string,
+ handshakeTimeout time.Duration,
+ threadHandshakeTimeout time.Duration,
+ attempt int,
+) (*codexProcess, error) {
+ var sessionDir, taskEnvFile string
+ childEnv := b.cfg.Env
+ if pooled {
+ var err error
+ sessionDir, err = os.MkdirTemp("", "multica-codex-warm-*")
+ if err != nil {
+ return nil, fmt.Errorf("create warm codex session dir: %w", err)
+ }
+ sessionTempDir := filepath.Join(sessionDir, "tmp")
+ if err := os.MkdirAll(sessionTempDir, 0o700); err != nil {
+ _ = os.RemoveAll(sessionDir)
+ return nil, fmt.Errorf("create warm codex temp dir: %w", err)
+ }
+ taskEnvFile = filepath.Join(sessionDir, "task-env.json")
+ if err := WriteTaskEnvFile(taskEnvFile, b.cfg.Env); err != nil {
+ _ = os.RemoveAll(sessionDir)
+ return nil, fmt.Errorf("write warm codex task env overlay: %w", err)
+ }
+ childEnv = PreparePooledChildEnv(b.cfg.Env, taskEnvFile, sessionTempDir)
+ }
+ cleanupOnErr := func() {
+ if sessionDir != "" {
+ _ = os.RemoveAll(sessionDir)
+ }
+ }
+
+ // The process context is never tied to the task: the app-server must stay
+ // alive long enough to handle turn/interrupt when the task context is
+ // cancelled, and a pooled one outlives the task entirely. The lifecycle
+ // goroutine stops it explicitly during bounded cleanup.
+ processCtx, stopProcess := context.WithCancel(context.Background())
+ cmd := runtimeCmd.exec(processCtx, codexArgs...)
+ hideAgentWindow(cmd)
+ // Run codex in its own process group so a cancel-on-stuck cleanup
+ // reaches the whole tree — the codex Node wrapper plus the native
+ // Rust app-server it spawns — not just the direct child. Without
+ // this, killing the leader leaves grandchildren as orphans that
+ // keep consuming memory until the OS reaps them; see #4520, where a
+ // scanner overflow during thread/resume otherwise leaked Codex
+ // processes indefinitely. configureProcessGroup is a no-op on
+ // Windows.
+ // Override the default exec.CommandContext cancel behaviour. The
+ // default sends SIGKILL only to cmd.Process (the leader); we instead
+ // signal the whole process group so descendants die too. Returning
+ // nil keeps exec from logging a spurious error; cmd.WaitDelay below
+ // still backstops cmd.Wait() if the kill leaves an open pipe.
+ cmd.Cancel = func() error {
+ if cmd.Process != nil {
+ signalProcessGroup(cmd, syscall.SIGKILL)
+ }
+ return nil
+ }
+ // Bound the wait after the context is cancelled so a stuck child (or an
+ // open pipe held by a grandchild) can't hang cmd.Wait() forever. Matches
+ // the other long-lived backends (claude, copilot, cursor, …).
+ cmd.WaitDelay = codexProcessWaitDelay()
+ b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(codexArgs, trustAgentCommandPositional(0, "app-server")))
+ if opts.Cwd != "" {
+ cmd.Dir = opts.Cwd
+ }
+ cmd.Env = buildEnv(childEnv)
+
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ stopProcess()
+ cleanupOnErr()
+ return nil, fmt.Errorf("codex stdout pipe: %w", err)
+ }
+ stdinPipe, err := cmd.StdinPipe()
+ if err != nil {
+ stopProcess()
+ cleanupOnErr()
+ return nil, fmt.Errorf("codex stdin pipe: %w", err)
+ }
+ stdin := &codexSyncWriter{w: stdinPipe}
+ // Codex stderr can contain auth/provider diagnostics. Capture a bounded
+ // tail and emit it only through the sanitizer in the cleanup event.
+ stderrBuf := newStderrTail(io.Discard, codexStderrTailBytes)
+ cmd.Stderr = stderrBuf
+
+ // Start and take ownership of the process tree in one step. On Windows the
+ // child is created suspended and placed in a Job Object before it runs, so
+ // the cleanup reaches the Node wrapper, the native app-server, and the
+ // sandbox helpers underneath them rather than just the direct child. On Unix
+ // the process group configured above already covers that and this is a plain
+ // Start. Ownership that cannot be taken is logged, not fatal; a child that
+ // cannot be resumed is killed and reported here.
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
+ stopProcess()
+ cleanupOnErr()
+ return nil, fmt.Errorf("start codex: %w", err)
+ }
+ activeLaunches := activeCodexLaunches.Add(1)
+ for {
+ maxSeen := maxActiveCodexLaunchesObserved.Load()
+ if activeLaunches <= maxSeen || maxActiveCodexLaunchesObserved.CompareAndSwap(maxSeen, activeLaunches) {
+ break
+ }
+ }
+ launchStarted := time.Now()
+ codexVersion := strings.TrimSpace(b.cfg.CodexVersion)
+ if codexVersion == "" {
+ codexVersion = "unknown"
+ }
+ b.cfg.Logger.Info("codex lifecycle",
+ "phase", "spawn",
+ "warm_pool", pooled,
+ "task_id", b.cfg.TaskID,
+ "runtime_id", b.cfg.RuntimeID,
+ "pid", cmd.Process.Pid,
+ "process_group", cmd.Process.Pid,
+ "cwd", opts.Cwd,
+ "attempt", attempt,
+ "active_launches", activeLaunches,
+ "codex_version", codexVersion,
+ "daemon_version", b.cfg.DaemonVersion,
+ )
+
+ c := &codexClient{
+ cfg: b.cfg,
+ stdin: stdin,
+ pending: make(map[int]*pendingRPC),
+ processDone: make(chan struct{}),
+ handshakeTimeout: handshakeTimeout,
+ threadHandshakeTimeout: threadHandshakeTimeout,
+ pid: cmd.Process.Pid,
+ attempt: attempt,
+ activeLaunches: activeLaunches,
+ notificationProtocol: "unknown",
+ acceptNotification: func(string, map[string]any) bool { return false },
+ }
+
+ return &codexProcess{
+ pooled: pooled,
+ fingerprint: fingerprint,
+ cmd: cmd,
+ stdin: stdin,
+ stdout: stdout,
+ stderrBuf: stderrBuf,
+ client: c,
+ stopProcess: stopProcess,
+ readerDone: make(chan struct{}),
+ sessionDir: sessionDir,
+ taskEnvFile: taskEnvFile,
+ attempt: attempt,
+ launchStarted: launchStarted,
+ logger: b.cfg.Logger,
+ }, nil
+}
+
+// readStdout dispatches every stdout line to the client for the life of the
+// process. The caller starts it once the first turn's hooks are attached.
+func (p *codexProcess) readStdout() {
+ defer close(p.readerDone)
+ c := p.client
+ scanner := newAgentStreamScanner(p.stdout)
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ if line == "" {
+ continue
+ }
+ c.handleLine(line)
+ }
+ // A cancelled or crashed app-server may close stdout without an
+ // item/completed snapshot. Preserve every complete delta JSON event
+ // already parsed; an incomplete final JSON token is ignored by handleLine
+ // and can never enter this buffer.
+ c.flushAgentMessageDeltasLocked()
+ if err := scanner.Err(); err != nil {
+ // %w on BOTH: callers match errCodexProcessExited to decide the
+ // process is gone, and bufio.ErrTooLong to tell "we could not read
+ // the response" apart from "codex died". startOrResumeThread needs
+ // that distinction to report an oversized resume as a rejected
+ // resume rather than a crash (MUL-5722).
+ c.markProcessExited(fmt.Errorf("%w: %w", errCodexProcessExited, err))
+ return
+ }
+ c.markProcessExited(errCodexProcessExited)
+}
+
+func (b *codexBackend) warmFingerprint(execPath string, runtimeCmd Command, codexArgs []string, opts ExecOptions) string {
+ var configFiles []string
+ if codexHome := strings.TrimSpace(b.cfg.Env["CODEX_HOME"]); codexHome != "" {
+ configFiles = append(configFiles, filepath.Join(codexHome, "config.toml"))
+ }
+ return computeWarmSessionFingerprint(WarmSessionFingerprintInput{
+ Provider: "codex",
+ Executable: execPath,
+ LaunchPrefix: runtimeCmd.Prefix,
+ Args: codexArgs,
+ Cwd: opts.Cwd,
+ Model: opts.Model,
+ ThinkingLevel: opts.ThinkingLevel,
+ ServiceTier: opts.ServiceTier,
+ McpConfig: opts.McpConfig,
+ ConfigFiles: configFiles,
+ BriefHash: opts.WarmPoolBriefHash,
+ Env: b.cfg.Env,
+ })
+}
+
+// acquireWarmProcess checks out the process parked for threadID and hands it
+// this task's credentials, or returns nil when the run must spawn.
+func (b *codexBackend) acquireWarmProcess(threadID, fingerprint string) *codexProcess {
+ if threadID == "" {
+ return nil
+ }
+ acquired := b.cfg.WarmPool.Acquire("codex", threadID, fingerprint)
+ if acquired == nil {
+ return nil
+ }
+ proc, ok := acquired.(*codexProcess)
+ if !ok {
+ acquired.Close()
+ return nil
+ }
+ if err := WriteTaskEnvFile(proc.taskEnvFile, b.cfg.Env); err != nil {
+ b.cfg.Logger.Warn("warm codex: failed to refresh task env overlay; evicting", "error", err)
+ proc.Close()
+ return nil
+ }
+ return proc
+}
diff --git a/server/pkg/agent/testdata/real_workload/followup/expr/ternary_test.go b/server/pkg/agent/testdata/real_workload/followup/expr/ternary_test.go
new file mode 100644
index 0000000000..d39d606f1f
--- /dev/null
+++ b/server/pkg/agent/testdata/real_workload/followup/expr/ternary_test.go
@@ -0,0 +1,44 @@
+package expr
+
+import (
+ "errors"
+ "testing"
+)
+
+func TestTernary(t *testing.T) {
+ cases := []struct {
+ src string
+ env Env
+ want float64
+ }{
+ {"1 ? 2 : 3", nil, 2},
+ {"0 ? 2 : 3", nil, 3},
+ {"1 < 2 ? 10 : 20", nil, 10},
+ {"0 ? 1 : 0 ? 2 : 3", nil, 3},
+ {"1 ? 0 ? 4 : 5 : 6", nil, 5},
+ {"x > 0 ? x : -x", Env{"x": -4}, 4},
+ {"1 ? 2 : 1 / 0", nil, 2},
+ {"0 ? missing : 7", nil, 7},
+ {"(1 ? 2 : 3) * 10", nil, 20},
+ {"1 || 0 ? 8 : 9", nil, 8},
+ }
+ for _, c := range cases {
+ got, err := Eval(c.src, c.env)
+ if err != nil {
+ t.Fatalf("Eval(%q): %v", c.src, err)
+ }
+ if got != c.want {
+ t.Fatalf("Eval(%q) = %v, want %v", c.src, got, c.want)
+ }
+ }
+}
+
+func TestTernarySyntaxErrors(t *testing.T) {
+ for src, pos := range map[string]int{"1 ? 2": 5, "1 ? : 2": 4, "? 1 : 2": 0} {
+ _, err := Eval(src, nil)
+ var se *SyntaxError
+ if !errors.As(err, &se) || se.Pos != pos {
+ t.Fatalf("Eval(%q) error = %v, want syntax error at %d", src, err, pos)
+ }
+ }
+}
diff --git a/server/pkg/agent/testdata/real_workload/followup/ledger/interest_test.go b/server/pkg/agent/testdata/real_workload/followup/ledger/interest_test.go
new file mode 100644
index 0000000000..d48ec6c84d
--- /dev/null
+++ b/server/pkg/agent/testdata/real_workload/followup/ledger/interest_test.go
@@ -0,0 +1,32 @@
+package ledger
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestApplyInterestRoundsHalfToEven(t *testing.T) {
+ in := Book{"a": 12345, "b": 100, "c": 300, "d": 0, "e": 250}
+ got := ApplyInterest(in, 150)
+ want := Book{"a": 12530, "b": 102, "c": 304, "d": 0, "e": 254}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("ApplyInterest(150bp) = %v, want %v", got, want)
+ }
+ half := ApplyInterest(Book{"x": 100, "y": 300, "z": 500}, 50)
+ if want := (Book{"x": 100, "y": 302, "z": 502}); !reflect.DeepEqual(half, want) {
+ t.Fatalf("ApplyInterest(50bp) = %v, want %v (0.5 -> 0, 1.5 -> 2, 2.5 -> 2)", half, want)
+ }
+ if in["a"] != 12345 {
+ t.Fatal("ApplyInterest must not modify its input")
+ }
+}
+
+func TestInterestThenReport(t *testing.T) {
+ got := Report(ApplyInterest(Book{"alice": 100000000}, 25))
+ want := "" +
+ "alice 1,002,500.00\n" +
+ "TOTAL 1,002,500.00\n"
+ if got != want {
+ t.Fatalf("Report =\n%s\nwant\n%s", got, want)
+ }
+}
diff --git a/server/pkg/agent/testdata/real_workload/project/expr/expr.go b/server/pkg/agent/testdata/real_workload/project/expr/expr.go
new file mode 100644
index 0000000000..dd2ef6f766
--- /dev/null
+++ b/server/pkg/agent/testdata/real_workload/project/expr/expr.go
@@ -0,0 +1,26 @@
+// Package expr evaluates arithmetic and logical expressions.
+//
+// Grammar, loosest to tightest: || && (comparisons) + - * / % unary(- !) ^.
+// ^ is right-associative. Comparisons and logic yield 1 or 0, any non-zero
+// value is true, and && / || short-circuit.
+package expr
+
+import "errors"
+
+// Env holds variable values.
+type Env map[string]float64
+
+// ErrDivByZero is returned for division or modulo by zero.
+var ErrDivByZero = errors.New("division by zero")
+
+// SyntaxError reports malformed input at byte offset Pos.
+type SyntaxError struct {
+ Pos int
+ Msg string
+}
+
+func (e *SyntaxError) Error() string { panic("not implemented") }
+
+// Eval parses and evaluates src. Builtin functions: min, max (one or more
+// arguments), abs, sqrt (exactly one argument).
+func Eval(src string, env Env) (float64, error) { panic("not implemented") }
diff --git a/server/pkg/agent/testdata/real_workload/project/expr/expr_test.go b/server/pkg/agent/testdata/real_workload/project/expr/expr_test.go
new file mode 100644
index 0000000000..6cdb79513b
--- /dev/null
+++ b/server/pkg/agent/testdata/real_workload/project/expr/expr_test.go
@@ -0,0 +1,139 @@
+package expr
+
+import (
+ "errors"
+ "math"
+ "strings"
+ "testing"
+)
+
+func TestEvalArithmetic(t *testing.T) {
+ cases := []struct {
+ src string
+ want float64
+ }{
+ {"1", 1},
+ {"1.5 + 2.25", 3.75},
+ {"2 + 3 * 4", 14},
+ {"(2 + 3) * 4", 20},
+ {"10 - 4 - 3", 3},
+ {"20 / 4 / 5", 1},
+ {"7 % 4", 3},
+ {"2 ^ 3 ^ 2", 512},
+ {"-2 ^ 2", -4},
+ {"(-2) ^ 2", 4},
+ {"--3", 3},
+ {"-(1 + 2) * 3", -9},
+ {" 4\t*\n2 ", 8},
+ }
+ for _, c := range cases {
+ got, err := Eval(c.src, nil)
+ if err != nil {
+ t.Fatalf("Eval(%q): %v", c.src, err)
+ }
+ if math.Abs(got-c.want) > 1e-9 {
+ t.Fatalf("Eval(%q) = %v, want %v", c.src, got, c.want)
+ }
+ }
+}
+
+func TestEvalVariablesAndFunctions(t *testing.T) {
+ env := Env{"x": 3, "rate_2": 0.5}
+ cases := []struct {
+ src string
+ want float64
+ }{
+ {"x * x", 9},
+ {"rate_2 * 10", 5},
+ {"min(4, x, 7)", 3},
+ {"max(1, x * 3, 2)", 9},
+ {"abs(-x)", 3},
+ {"sqrt(16) + 1", 5},
+ {"max(min(1, 2), abs(-5))", 5},
+ }
+ for _, c := range cases {
+ got, err := Eval(c.src, env)
+ if err != nil {
+ t.Fatalf("Eval(%q): %v", c.src, err)
+ }
+ if math.Abs(got-c.want) > 1e-9 {
+ t.Fatalf("Eval(%q) = %v, want %v", c.src, got, c.want)
+ }
+ }
+}
+
+func TestEvalLogic(t *testing.T) {
+ cases := []struct {
+ src string
+ want float64
+ }{
+ {"1 < 2", 1},
+ {"2 <= 1", 0},
+ {"3 == 3", 1},
+ {"3 != 3", 0},
+ {"1 < 2 && 2 < 3", 1},
+ {"1 > 2 || 0", 0},
+ {"!0", 1},
+ {"!5", 0},
+ {"0 && 1 / 0", 0},
+ {"1 || unknown", 1},
+ {"1 + 1 == 2 && 2 * 2 >= 4", 1},
+ }
+ for _, c := range cases {
+ got, err := Eval(c.src, nil)
+ if err != nil {
+ t.Fatalf("Eval(%q): %v", c.src, err)
+ }
+ if got != c.want {
+ t.Fatalf("Eval(%q) = %v, want %v", c.src, got, c.want)
+ }
+ }
+}
+
+func TestEvalErrors(t *testing.T) {
+ if _, err := Eval("1 / (2 - 2)", nil); !errors.Is(err, ErrDivByZero) {
+ t.Fatalf("division by zero error = %v, want ErrDivByZero", err)
+ }
+ if _, err := Eval("5 % 0", nil); !errors.Is(err, ErrDivByZero) {
+ t.Fatalf("modulo by zero error = %v, want ErrDivByZero", err)
+ }
+ if _, err := Eval("y + 1", Env{"x": 1}); err == nil || !strings.Contains(err.Error(), "unknown variable y") {
+ t.Fatalf("unknown variable error = %v", err)
+ }
+ if _, err := Eval("nope(1)", nil); err == nil || !strings.Contains(err.Error(), "unknown function nope") {
+ t.Fatalf("unknown function error = %v", err)
+ }
+ if _, err := Eval("abs(1, 2)", nil); err == nil || !strings.Contains(err.Error(), "abs") {
+ t.Fatalf("arity error = %v", err)
+ }
+ if _, err := Eval("min()", nil); err == nil {
+ t.Fatal("min() with no arguments must fail")
+ }
+}
+
+func TestEvalSyntaxErrorPositions(t *testing.T) {
+ cases := []struct {
+ src string
+ pos int
+ }{
+ {"1 + * 2", 4},
+ {"(1 + 2", 6},
+ {"1 2", 2},
+ {"3 $ 4", 2},
+ {"", 0},
+ {"max(1,", 6},
+ }
+ for _, c := range cases {
+ _, err := Eval(c.src, nil)
+ var se *SyntaxError
+ if !errors.As(err, &se) {
+ t.Fatalf("Eval(%q) error = %v, want *SyntaxError", c.src, err)
+ }
+ if se.Pos != c.pos {
+ t.Fatalf("Eval(%q) syntax error at %d (%s), want %d", c.src, se.Pos, se.Msg, c.pos)
+ }
+ if !strings.HasPrefix(se.Error(), "syntax error at ") {
+ t.Fatalf("SyntaxError.Error() = %q", se.Error())
+ }
+ }
+}
diff --git a/server/pkg/agent/testdata/real_workload/project/go.mod b/server/pkg/agent/testdata/real_workload/project/go.mod
new file mode 100644
index 0000000000..256a6f6616
--- /dev/null
+++ b/server/pkg/agent/testdata/real_workload/project/go.mod
@@ -0,0 +1,3 @@
+module workbench
+
+go 1.22
diff --git a/server/pkg/agent/testdata/real_workload/project/ledger/ledger.go b/server/pkg/agent/testdata/real_workload/project/ledger/ledger.go
new file mode 100644
index 0000000000..7d48e65f85
--- /dev/null
+++ b/server/pkg/agent/testdata/real_workload/project/ledger/ledger.go
@@ -0,0 +1,55 @@
+// Package ledger parses a plain-text journal and computes account balances.
+//
+// Each non-blank, non-comment line is one of:
+//
+// 2026-01-02 deposit <to> <amount>
+// 2026-01-02 withdraw <from> <amount>
+// 2026-01-02 transfer <from> <to> <amount>
+//
+// Amounts are positive with at most two decimals.
+package ledger
+
+import (
+ "io"
+ "time"
+)
+
+type Kind string
+
+const (
+ Deposit Kind = "deposit"
+ Withdraw Kind = "withdraw"
+ Transfer Kind = "transfer"
+)
+
+type Txn struct {
+ Line int
+ Date time.Time
+ Kind Kind
+ From, To string
+ Cents int64
+}
+
+type ParseError struct {
+ Line int
+ Msg string
+}
+
+func (e *ParseError) Error() string { panic("not implemented") }
+
+// Book maps account names to balances in cents.
+type Book map[string]int64
+
+type Rejection struct {
+ Line int
+ Reason string
+}
+
+func Parse(r io.Reader) ([]Txn, error) { panic("not implemented") }
+
+// Apply replays txns in order. A transaction that would overdraw an account,
+// or that spends from an account no deposit has created yet, is rejected.
+func Apply(txns []Txn) (Book, []Rejection) { panic("not implemented") }
+
+// Report renders balances sorted by account name, followed by a TOTAL line.
+func Report(b Book) string { panic("not implemented") }
diff --git a/server/pkg/agent/testdata/real_workload/project/ledger/ledger_test.go b/server/pkg/agent/testdata/real_workload/project/ledger/ledger_test.go
new file mode 100644
index 0000000000..e37375a395
--- /dev/null
+++ b/server/pkg/agent/testdata/real_workload/project/ledger/ledger_test.go
@@ -0,0 +1,113 @@
+package ledger
+
+import (
+ "errors"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+const journal = `# opening balances
+2026-01-02 deposit alice 1200.50
+2026-01-02 deposit bob 75
+
+2026-01-03 transfer alice bob 200.25
+2026-01-04 withdraw bob 300
+2026-01-05 withdraw carol 1
+2026-01-06 transfer bob alice 275.25
+2026-01-07 deposit carol 1000000.01
+`
+
+func TestParse(t *testing.T) {
+ txns, err := Parse(strings.NewReader(journal))
+ if err != nil {
+ t.Fatalf("Parse: %v", err)
+ }
+ if len(txns) != 7 {
+ t.Fatalf("parsed %d transactions, want 7", len(txns))
+ }
+ first := txns[0]
+ if first.Line != 2 || first.Kind != Deposit || first.To != "alice" || first.Cents != 120050 || first.Date.Format("2006-01-02") != "2026-01-02" {
+ t.Fatalf("first = %+v", first)
+ }
+ tr := txns[2]
+ if tr.Line != 5 || tr.Kind != Transfer || tr.From != "alice" || tr.To != "bob" || tr.Cents != 20025 {
+ t.Fatalf("transfer = %+v", tr)
+ }
+ w := txns[3]
+ if w.Kind != Withdraw || w.From != "bob" || w.To != "" || w.Cents != 30000 {
+ t.Fatalf("withdraw = %+v", w)
+ }
+}
+
+func TestParseErrors(t *testing.T) {
+ cases := []struct {
+ src string
+ line int
+ msg string
+ }{
+ {"2026-01-02 deposit alice 1.234", 1, "amount"},
+ {"2026-01-02 deposit alice -5", 1, "amount"},
+ {"2026-01-02 deposit alice 0", 1, "amount"},
+ {"# ok\n2026-13-02 deposit alice 5", 2, "date"},
+ {"2026-01-02 refund alice 5", 1, "kind"},
+ {"2026-01-02 transfer alice 5", 1, "fields"},
+ {"2026-01-02 transfer alice alice 5", 1, "same account"},
+ {"2026-01-02 deposit alice 5 extra", 1, "fields"},
+ }
+ for _, c := range cases {
+ _, err := Parse(strings.NewReader(c.src))
+ var pe *ParseError
+ if !errors.As(err, &pe) {
+ t.Fatalf("Parse(%q) error = %v, want *ParseError", c.src, err)
+ }
+ if pe.Line != c.line || !strings.Contains(pe.Msg, c.msg) {
+ t.Fatalf("Parse(%q) = line %d %q, want line %d containing %q", c.src, pe.Line, pe.Msg, c.line, c.msg)
+ }
+ if !strings.HasPrefix(pe.Error(), "line ") {
+ t.Fatalf("ParseError.Error() = %q", pe.Error())
+ }
+ }
+}
+
+func TestApply(t *testing.T) {
+ txns, err := Parse(strings.NewReader(journal))
+ if err != nil {
+ t.Fatal(err)
+ }
+ book, rejected := Apply(txns)
+ wantBook := Book{"alice": 120050 - 20025 + 27525, "bob": 7500 + 20025 - 27525, "carol": 100000001}
+ if !reflect.DeepEqual(book, wantBook) {
+ t.Fatalf("book = %v, want %v", book, wantBook)
+ }
+ wantRejected := []Rejection{
+ {Line: 6, Reason: "insufficient funds"},
+ {Line: 7, Reason: "unknown account"},
+ }
+ if !reflect.DeepEqual(rejected, wantRejected) {
+ t.Fatalf("rejected = %+v, want %+v", rejected, wantRejected)
+ }
+}
+
+func TestApplyTransferToNewAccount(t *testing.T) {
+ txns, err := Parse(strings.NewReader("2026-02-01 deposit a 10\n2026-02-02 transfer a z 4"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ book, rejected := Apply(txns)
+ if len(rejected) != 0 || book["a"] != 600 || book["z"] != 400 {
+ t.Fatalf("book=%v rejected=%v", book, rejected)
+ }
+}
+
+func TestReport(t *testing.T) {
+ book := Book{"carol": 100000001, "alice": 127550, "bob": 0}
+ want := "" +
+ "alice 1,275.50\n" +
+ "bob 0.00\n" +
+ "carol 1,000,000.01\n" +
+ "TOTAL 1,001,275.51\n"
+ if got := Report(book); got != want {
+ t.Fatalf("Report() =\n%s\nwant\n%s", got, want)
+ }
+}
diff --git a/server/pkg/agent/testdata/real_workload/project/lru/lru.go b/server/pkg/agent/testdata/real_workload/project/lru/lru.go
new file mode 100644
index 0000000000..56aa784ffe
--- /dev/null
+++ b/server/pkg/agent/testdata/real_workload/project/lru/lru.go
@@ -0,0 +1,39 @@
+// Package lru is a concurrency-safe LRU cache with an optional TTL.
+package lru
+
+import "time"
+
+// Reason says why an entry left the cache.
+type Reason int
+
+const (
+ Capacity Reason = iota
+ Expired
+)
+
+func (r Reason) String() string { panic("not implemented") }
+
+// Cache is safe for concurrent use.
+type Cache[K comparable, V any] struct{}
+
+// New returns a cache holding at most capacity entries. A ttl of zero means
+// entries never expire; otherwise an entry expires ttl after it was last Set.
+func New[K comparable, V any](capacity int, ttl time.Duration, now func() time.Time) *Cache[K, V] {
+ panic("not implemented")
+}
+
+// OnEvict registers a callback for capacity evictions and expirations.
+// Delete and replacing a value do not call it.
+func (c *Cache[K, V]) OnEvict(fn func(K, V, Reason)) { panic("not implemented") }
+
+func (c *Cache[K, V]) Set(k K, v V) { panic("not implemented") }
+
+func (c *Cache[K, V]) Get(k K) (V, bool) { panic("not implemented") }
+
+func (c *Cache[K, V]) Delete(k K) bool { panic("not implemented") }
+
+// Len returns the number of live entries.
+func (c *Cache[K, V]) Len() int { panic("not implemented") }
+
+// Keys returns live keys, most recently used first.
+func (c *Cache[K, V]) Keys() []K { panic("not implemented") }
diff --git a/server/pkg/agent/testdata/real_workload/project/lru/lru_test.go b/server/pkg/agent/testdata/real_workload/project/lru/lru_test.go
new file mode 100644
index 0000000000..a2ab6a9b26
--- /dev/null
+++ b/server/pkg/agent/testdata/real_workload/project/lru/lru_test.go
@@ -0,0 +1,163 @@
+package lru
+
+import (
+ "fmt"
+ "reflect"
+ "sync"
+ "testing"
+ "time"
+)
+
+type fakeClock struct {
+ mu sync.Mutex
+ now time.Time
+}
+
+func (f *fakeClock) Now() time.Time {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.now
+}
+
+func (f *fakeClock) Advance(d time.Duration) {
+ f.mu.Lock()
+ f.now = f.now.Add(d)
+ f.mu.Unlock()
+}
+
+type eviction struct {
+ key string
+ value int
+ reason Reason
+}
+
+func TestCapacityEvictsLeastRecentlyUsed(t *testing.T) {
+ clock := &fakeClock{now: time.Unix(1000, 0)}
+ c := New[string, int](2, 0, clock.Now)
+ var evicted []eviction
+ c.OnEvict(func(k string, v int, r Reason) { evicted = append(evicted, eviction{k, v, r}) })
+
+ c.Set("a", 1)
+ c.Set("b", 2)
+ if v, ok := c.Get("a"); !ok || v != 1 {
+ t.Fatalf("Get(a) = %v, %v", v, ok)
+ }
+ c.Set("c", 3)
+ if _, ok := c.Get("b"); ok {
+ t.Fatal("b should have been evicted")
+ }
+ if got, want := c.Keys(), []string{"c", "a"}; !reflect.DeepEqual(got, want) {
+ t.Fatalf("Keys() = %v, want %v", got, want)
+ }
+ if want := []eviction{{"b", 2, Capacity}}; !reflect.DeepEqual(evicted, want) {
+ t.Fatalf("evictions = %v, want %v", evicted, want)
+ }
+}
+
+func TestSetReplacesWithoutEviction(t *testing.T) {
+ c := New[string, int](2, 0, time.Now)
+ calls := 0
+ c.OnEvict(func(string, int, Reason) { calls++ })
+ c.Set("a", 1)
+ c.Set("b", 2)
+ c.Set("a", 10)
+ if c.Len() != 2 {
+ t.Fatalf("Len() = %d, want 2", c.Len())
+ }
+ if v, _ := c.Get("a"); v != 10 {
+ t.Fatalf("Get(a) = %d, want 10", v)
+ }
+ if got, want := c.Keys(), []string{"a", "b"}; !reflect.DeepEqual(got, want) {
+ t.Fatalf("Keys() = %v, want %v", got, want)
+ }
+ if calls != 0 {
+ t.Fatalf("replacing a value fired %d evictions", calls)
+ }
+}
+
+func TestDeleteDoesNotFireEviction(t *testing.T) {
+ c := New[string, int](3, 0, time.Now)
+ calls := 0
+ c.OnEvict(func(string, int, Reason) { calls++ })
+ c.Set("a", 1)
+ if !c.Delete("a") {
+ t.Fatal("Delete(a) = false")
+ }
+ if c.Delete("a") {
+ t.Fatal("second Delete(a) = true")
+ }
+ if calls != 0 || c.Len() != 0 {
+ t.Fatalf("calls=%d len=%d", calls, c.Len())
+ }
+}
+
+func TestTTLExpiry(t *testing.T) {
+ clock := &fakeClock{now: time.Unix(1000, 0)}
+ c := New[string, int](10, time.Minute, clock.Now)
+ var evicted []eviction
+ c.OnEvict(func(k string, v int, r Reason) { evicted = append(evicted, eviction{k, v, r}) })
+
+ c.Set("a", 1)
+ clock.Advance(30 * time.Second)
+ c.Set("b", 2)
+ if _, ok := c.Get("a"); !ok {
+ t.Fatal("a expired too early")
+ }
+ clock.Advance(31 * time.Second)
+ if _, ok := c.Get("a"); ok {
+ t.Fatal("a should expire one minute after it was set, reads do not extend it")
+ }
+ if got, want := c.Keys(), []string{"b"}; !reflect.DeepEqual(got, want) {
+ t.Fatalf("Keys() = %v, want %v", got, want)
+ }
+ clock.Advance(30 * time.Second)
+ if c.Len() != 0 {
+ t.Fatalf("Len() = %d after everything expired", c.Len())
+ }
+ want := []eviction{{"a", 1, Expired}, {"b", 2, Expired}}
+ if !reflect.DeepEqual(evicted, want) {
+ t.Fatalf("evictions = %v, want %v", evicted, want)
+ }
+}
+
+func TestSetRefreshesTTL(t *testing.T) {
+ clock := &fakeClock{now: time.Unix(1000, 0)}
+ c := New[string, int](10, time.Minute, clock.Now)
+ c.Set("a", 1)
+ clock.Advance(50 * time.Second)
+ c.Set("a", 2)
+ clock.Advance(50 * time.Second)
+ if v, ok := c.Get("a"); !ok || v != 2 {
+ t.Fatalf("Get(a) = %v, %v; Set must restart the TTL", v, ok)
+ }
+}
+
+func TestReasonString(t *testing.T) {
+ if Capacity.String() != "capacity" || Expired.String() != "expired" {
+ t.Fatalf("Reason strings = %q, %q", Capacity.String(), Expired.String())
+ }
+}
+
+func TestConcurrentAccess(t *testing.T) {
+ c := New[string, int](64, time.Hour, time.Now)
+ var wg sync.WaitGroup
+ for g := 0; g < 8; g++ {
+ wg.Add(1)
+ go func(g int) {
+ defer wg.Done()
+ for i := 0; i < 500; i++ {
+ k := fmt.Sprintf("k%d", (g*31+i)%100)
+ c.Set(k, i)
+ c.Get(k)
+ if i%7 == 0 {
+ c.Delete(k)
+ }
+ c.Keys()
+ }
+ }(g)
+ }
+ wg.Wait()
+ if c.Len() > 64 {
+ t.Fatalf("Len() = %d exceeds capacity", c.Len())
+ }
+}
diff --git a/server/pkg/agent/testdata/real_workload/project/semver/semver.go b/server/pkg/agent/testdata/real_workload/project/semver/semver.go
new file mode 100644
index 0000000000..5b5277eb55
--- /dev/null
+++ b/server/pkg/agent/testdata/real_workload/project/semver/semver.go
@@ -0,0 +1,23 @@
+// Package semver parses Semantic Versioning 2.0.0 versions and matches them
+// against npm-style constraints.
+package semver
+
+type Version struct {
+ Major, Minor, Patch int
+ Pre []string
+ Build string
+}
+
+// Parse accepts an optional leading "v".
+func Parse(s string) (Version, error) { panic("not implemented") }
+
+func (v Version) String() string { panic("not implemented") }
+
+// Compare returns -1, 0 or 1 by SemVer precedence; build metadata is ignored.
+func Compare(a, b Version) int { panic("not implemented") }
+
+// Match reports whether v satisfies constraint. Space-separated comparators
+// (=, >, >=, <, <=, ^, ~, or a bare version) are ANDed, and "||" separates
+// alternatives. A prerelease version only matches a group in which some
+// comparator has a prerelease on the same major.minor.patch.
+func Match(constraint string, v Version) (bool, error) { panic("not implemented") }
diff --git a/server/pkg/agent/testdata/real_workload/project/semver/semver_test.go b/server/pkg/agent/testdata/real_workload/project/semver/semver_test.go
new file mode 100644
index 0000000000..96f5ecaabf
--- /dev/null
+++ b/server/pkg/agent/testdata/real_workload/project/semver/semver_test.go
@@ -0,0 +1,97 @@
+package semver
+
+import (
+ "sort"
+ "testing"
+)
+
+func mustParse(t *testing.T, s string) Version {
+ t.Helper()
+ v, err := Parse(s)
+ if err != nil {
+ t.Fatalf("Parse(%q): %v", s, err)
+ }
+ return v
+}
+
+func TestParseAndString(t *testing.T) {
+ for _, s := range []string{"1.2.3", "0.0.0", "10.20.30", "1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-0.3.7", "1.0.0+build.5", "1.0.0-rc.1+sha.abc"} {
+ if got := mustParse(t, s).String(); got != s {
+ t.Fatalf("String(Parse(%q)) = %q", s, got)
+ }
+ }
+ if got := mustParse(t, "v2.0.1").String(); got != "2.0.1" {
+ t.Fatalf("leading v: %q", got)
+ }
+ for _, bad := range []string{"", "1", "1.2", "1.2.3.4", "01.2.3", "1.02.3", "1.2.3-", "1.2.3-01", "1.2.3-a..b", "a.b.c", "1.2.-3"} {
+ if _, err := Parse(bad); err == nil {
+ t.Fatalf("Parse(%q) succeeded, want error", bad)
+ }
+ }
+}
+
+func TestPrecedence(t *testing.T) {
+ ordered := []string{
+ "1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-alpha.beta", "1.0.0-beta", "1.0.0-beta.2",
+ "1.0.0-beta.11", "1.0.0-rc.1", "1.0.0", "1.0.1", "1.1.0", "2.0.0",
+ }
+ vs := make([]Version, len(ordered))
+ for i, s := range ordered {
+ vs[i] = mustParse(t, s)
+ }
+ shuffled := []Version{vs[7], vs[2], vs[10], vs[0], vs[5], vs[9], vs[1], vs[8], vs[4], vs[3], vs[6]}
+ sort.Slice(shuffled, func(i, j int) bool { return Compare(shuffled[i], shuffled[j]) < 0 })
+ for i := range shuffled {
+ if shuffled[i].String() != ordered[i] {
+ t.Fatalf("position %d = %s, want %s", i, shuffled[i], ordered[i])
+ }
+ }
+ if Compare(mustParse(t, "1.0.0+a"), mustParse(t, "1.0.0+b")) != 0 {
+ t.Fatal("build metadata must not affect precedence")
+ }
+}
+
+func TestMatch(t *testing.T) {
+ cases := []struct {
+ constraint string
+ version string
+ want bool
+ }{
+ {"1.2.3", "1.2.3", true},
+ {"=1.2.3", "1.2.4", false},
+ {">1.2.3", "1.2.4", true},
+ {">=1.2.3 <2.0.0", "1.9.9", true},
+ {">=1.2.3 <2.0.0", "2.0.0", false},
+ {"<=1.0.0", "1.0.0", true},
+ {"^1.2.3", "1.9.0", true},
+ {"^1.2.3", "2.0.0", false},
+ {"^1.2.3", "1.2.2", false},
+ {"^0.2.3", "0.2.9", true},
+ {"^0.2.3", "0.3.0", false},
+ {"^0.0.3", "0.0.3", true},
+ {"^0.0.3", "0.0.4", false},
+ {"~1.2.3", "1.2.9", true},
+ {"~1.2.3", "1.3.0", false},
+ {"~1.2", "1.2.0", true},
+ {"~1.2", "1.3.0", false},
+ {"^1.2.3 || ^3.0.0", "3.1.0", true},
+ {"^1.2.3 || ^3.0.0", "2.5.0", false},
+ {"^1.2.3", "1.5.0-beta", false},
+ {">=1.2.3-alpha <1.3.0", "1.2.3-beta", true},
+ {">=1.2.3-alpha <1.3.0", "1.2.4-beta", false},
+ }
+ for _, c := range cases {
+ got, err := Match(c.constraint, mustParse(t, c.version))
+ if err != nil {
+ t.Fatalf("Match(%q, %s): %v", c.constraint, c.version, err)
+ }
+ if got != c.want {
+ t.Fatalf("Match(%q, %s) = %v, want %v", c.constraint, c.version, got, c.want)
+ }
+ }
+ for _, bad := range []string{"", ">>1.0.0", "^", "1.0.0 ||", "~x"} {
+ if _, err := Match(bad, mustParse(t, "1.0.0")); err == nil {
+ t.Fatalf("Match(%q) succeeded, want error", bad)
+ }
+ }
+}
diff --git a/server/pkg/agent/warm_pool_parity_test.go b/server/pkg/agent/warm_pool_parity_test.go
new file mode 100644
index 0000000000..338b8cb8bd
--- /dev/null
+++ b/server/pkg/agent/warm_pool_parity_test.go
@@ -0,0 +1,339 @@
+package agent
+
+import (
+ "context"
+ "io"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+)
+
+// The warm pool only changes where a turn's process comes from and whether it
+// is parked afterwards. These tests run one conversation with the pool
+// disabled (MULTICA_WARM_POOL=0 or a custom runtime profile) and enabled
+// (a pool miss on the first turn, pool hits after it) and hold every run to
+// the same expectations.
+
+type parityTurn struct {
+ taskID string
+ prompt string
+ resume bool
+ wantErr string
+}
+
+var parityConversation = []parityTurn{
+ {taskID: "task-1", prompt: "first turn"},
+ {taskID: "task-2", prompt: "second turn", resume: true},
+ {taskID: "task-3", prompt: "please fail", resume: true, wantErr: "rate limit exceeded"},
+}
+
+type parityOutcome struct {
+ result Result
+ text string
+ statusSessionIDs []string
+}
+
+func collectParityOutcome(t *testing.T, sess *Session) parityOutcome {
+ t.Helper()
+ var out parityOutcome
+ var text strings.Builder
+ timeout := time.After(20 * time.Second)
+ for {
+ select {
+ case msg, ok := <-sess.Messages:
+ if !ok {
+ select {
+ case out.result = <-sess.Result:
+ case <-timeout:
+ t.Fatal("timed out waiting for result")
+ }
+ out.text = text.String()
+ return out
+ }
+ switch msg.Type {
+ case MessageText:
+ text.WriteString(msg.Content)
+ case MessageStatus:
+ if msg.SessionID != "" {
+ out.statusSessionIDs = append(out.statusSessionIDs, msg.SessionID)
+ }
+ }
+ case <-timeout:
+ t.Fatal("timed out waiting for messages")
+ }
+ }
+}
+
+// assertParityOutcome is the one set of expectations every mode must meet.
+func assertParityOutcome(t *testing.T, turn parityTurn, got parityOutcome, sessionID, model, wantText string, wantUsage TokenUsage) {
+ t.Helper()
+ res := got.result
+ if turn.wantErr != "" {
+ if res.Status != "failed" {
+ t.Fatalf("%s: status = %q, want failed (result %+v)", turn.taskID, res.Status, res)
+ }
+ if !strings.Contains(res.Error, turn.wantErr) {
+ t.Fatalf("%s: error = %q, want it to contain %q", turn.taskID, res.Error, turn.wantErr)
+ }
+ return
+ }
+ if res.Status != "completed" || res.Error != "" {
+ t.Fatalf("%s: result = %+v, want completed", turn.taskID, res)
+ }
+ if res.SessionID != sessionID {
+ t.Fatalf("%s: session id = %q, want %q", turn.taskID, res.SessionID, sessionID)
+ }
+ if res.ResumeRejected {
+ t.Fatalf("%s: resume reported rejected", turn.taskID)
+ }
+ if res.Output != wantText {
+ t.Fatalf("%s: output = %q, want %q", turn.taskID, res.Output, wantText)
+ }
+ if got.text != wantText {
+ t.Fatalf("%s: streamed text = %q, want %q", turn.taskID, got.text, wantText)
+ }
+ if !slices.Contains(got.statusSessionIDs, sessionID) {
+ t.Fatalf("%s: no running status carried session %q (got %v)", turn.taskID, sessionID, got.statusSessionIDs)
+ }
+ if u := res.Usage[model]; u.InputTokens != wantUsage.InputTokens || u.OutputTokens != wantUsage.OutputTokens {
+ t.Fatalf("%s: usage = %+v, want %+v", turn.taskID, res.Usage, wantUsage)
+ }
+}
+
+func TestClaudeColdAndWarmTurnsShareLifecycle(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fake binary requires a POSIX shell")
+ }
+ const sessionID = "claude-parity-1"
+ const model = "claude-opus-5-5"
+
+ // One process serves turns until stdin closes. Per-turn usage rides on the
+ // assistant event and cumulative process totals on the result, the way
+ // Claude Code reports them. The task id comes from the pooled overlay file
+ // when there is one, otherwise from the inherited environment.
+ script := `#!/bin/sh
+printf '%s\n' "$$" >> "$SPAWN_LOG"
+turn=0
+while IFS= read -r line; do
+ case "$line" in
+ *'"type":"user"'*)
+ turn=$((turn + 1))
+ tid="$MULTICA_TASK_ID"
+ if [ -n "$MULTICA_TASK_ENV_FILE" ]; then
+ tid=$(sed -n 's/.*"MULTICA_TASK_ID":"\([^"]*\)".*/\1/p' "$MULTICA_TASK_ENV_FILE")
+ fi
+ if [ "$turn" = "1" ]; then
+ printf '{"type":"system","subtype":"init","session_id":"` + sessionID + `"}\n'
+ fi
+ case "$line" in
+ *'please fail'*)
+ printf '{"type":"result","subtype":"error","session_id":"` + sessionID + `","result":"rate limit exceeded","is_error":true}\n'
+ continue
+ ;;
+ esac
+ printf '{"type":"stream_event","event":{"type":"message_start","message":{"id":"msg-%s"}}}\n' "$turn"
+ printf '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hello "}}}\n'
+ printf '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"%s"}}}\n' "$tid"
+ printf '{"type":"stream_event","event":{"type":"message_stop"}}\n'
+ printf '{"type":"assistant","message":{"id":"msg-%s","role":"assistant","model":"` + model + `","usage":{"input_tokens":50,"output_tokens":15},"content":[{"type":"text","text":"hello %s"}]}}\n' "$turn" "$tid"
+ printf '{"type":"result","subtype":"success","session_id":"` + sessionID + `","result":"hello %s","is_error":false,"modelUsage":{"` + model + `":{"inputTokens":%d,"outputTokens":%d}}}\n' "$tid" $((turn * 50)) $((turn * 15))
+ ;;
+ esac
+done
+`
+
+ for _, mode := range []struct {
+ name string
+ pooled bool
+ wantSpawns int
+ }{
+ {name: "pool disabled", pooled: false, wantSpawns: len(parityConversation)},
+ {name: "pool miss then hit", pooled: true, wantSpawns: 1},
+ } {
+ t.Run(mode.name, func(t *testing.T) {
+ dir := t.TempDir()
+ spawnLog := filepath.Join(dir, "spawns.log")
+ fakeClaude := filepath.Join(dir, "claude")
+ writeTestExecutable(t, fakeClaude, []byte(script))
+ // A resumable session has a transcript on disk; a fresh process
+ // resuming it measures the result's totals against that file.
+ configDir := filepath.Join(dir, "claude-config")
+ projectDir := filepath.Join(configDir, "projects", "parity")
+ if err := os.MkdirAll(projectDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(projectDir, sessionID+".jsonl"), nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ var pool *WarmSessionPool
+ if mode.pooled {
+ pool = NewWarmSessionPool(WarmSessionPoolConfig{
+ IdleTTL: 30 * time.Second,
+ MaxIdle: 4,
+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ })
+ defer pool.Close()
+ }
+
+ for _, turn := range parityConversation {
+ b, err := New("claude", Config{
+ ExecutablePath: fakeClaude,
+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ TaskID: turn.taskID,
+ WarmPool: pool,
+ Env: map[string]string{
+ "SPAWN_LOG": spawnLog,
+ "CLAUDE_CONFIG_DIR": configDir,
+ "MULTICA_TOKEN": "mat_" + turn.taskID,
+ "MULTICA_TASK_ID": turn.taskID,
+ "MULTICA_AGENT_ID": "agent-parity",
+ },
+ })
+ if err != nil {
+ t.Fatalf("New(claude): %v", err)
+ }
+ opts := ExecOptions{Cwd: dir, Model: model, Timeout: 15 * time.Second}
+ if turn.resume {
+ opts.ResumeSessionID = sessionID
+ }
+ sess, err := b.Execute(context.Background(), turn.prompt, opts)
+ if err != nil {
+ t.Fatalf("Execute(%s): %v", turn.taskID, err)
+ }
+ got := collectParityOutcome(t, sess)
+ assertParityOutcome(t, turn, got, sessionID, model, "hello "+turn.taskID, TokenUsage{InputTokens: 50, OutputTokens: 15})
+ }
+
+ spawns, err := os.ReadFile(spawnLog)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n := len(splitNonEmptyLines(string(spawns))); n != mode.wantSpawns {
+ t.Fatalf("claude spawned %d times, want %d", n, mode.wantSpawns)
+ }
+ if pool.Len() != 0 {
+ t.Fatalf("pool holds %d sessions after the failed turn, want 0", pool.Len())
+ }
+ })
+ }
+}
+
+func TestCodexColdAndWarmTurnsShareLifecycle(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fake binary requires a POSIX shell")
+ }
+ const threadID = "thr-parity-1"
+ const model = "gpt-6.1-sol"
+
+ // One app-server serves turns until stdin closes and reports cumulative
+ // thread usage, so a reused process must report only the per-turn delta.
+ script := `#!/bin/sh
+printf '%s\n' "$$" >> "$SPAWN_LOG"
+turn_num=0
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"userAgent":"fake-codex"}}\n' "$id"
+ ;;
+ *'"method":"thread/start"'*|*'"method":"thread/resume"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"thread":{"id":"` + threadID + `"}}}\n' "$id"
+ ;;
+ *'"method":"turn/start"'*)
+ turn_num=$((turn_num + 1))
+ tid="$MULTICA_TASK_ID"
+ if [ -n "$MULTICA_TASK_ENV_FILE" ]; then
+ tid=$(sed -n 's/.*"MULTICA_TASK_ID":"\([^"]*\)".*/\1/p' "$MULTICA_TASK_ENV_FILE")
+ fi
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"turn":{"id":"turn-%s"}}}\n' "$id" "$turn_num"
+ printf '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"` + threadID + `","turn":{"id":"turn-%s"}}}\n' "$turn_num"
+ case "$line" in
+ *'please fail'*)
+ printf '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"` + threadID + `","turn":{"id":"turn-%s","status":"failed","error":{"message":"rate limit exceeded"}}}}\n' "$turn_num"
+ continue
+ ;;
+ esac
+ printf '{"jsonrpc":"2.0","method":"thread/tokenUsage/updated","params":{"threadId":"` + threadID + `","turnId":"turn-%s","tokenUsage":{"total":{"inputTokens":%d,"outputTokens":%d},"last":{"inputTokens":100,"outputTokens":10}}}}\n' "$turn_num" $((turn_num * 100)) $((turn_num * 10))
+ printf '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"` + threadID + `","turnId":"turn-%s","item":{"type":"agentMessage","id":"msg-%s","phase":"final_answer","text":"hello %s"}}}\n' "$turn_num" "$turn_num" "$tid"
+ printf '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"` + threadID + `","turn":{"id":"turn-%s","status":"completed"}}}\n' "$turn_num"
+ ;;
+ esac
+done
+`
+
+ for _, mode := range []struct {
+ name string
+ pooled bool
+ wantSpawns int
+ }{
+ {name: "pool disabled", pooled: false, wantSpawns: len(parityConversation)},
+ {name: "pool miss then hit", pooled: true, wantSpawns: 1},
+ } {
+ t.Run(mode.name, func(t *testing.T) {
+ dir := t.TempDir()
+ spawnLog := filepath.Join(dir, "spawns.log")
+ fakeCodex := filepath.Join(dir, "codex")
+ writeTestExecutable(t, fakeCodex, []byte(script))
+ codexHome := filepath.Join(dir, "codex-home")
+ if err := os.MkdirAll(codexHome, 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ var pool *WarmSessionPool
+ if mode.pooled {
+ pool = NewWarmSessionPool(WarmSessionPoolConfig{
+ IdleTTL: 30 * time.Second,
+ MaxIdle: 4,
+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ })
+ defer pool.Close()
+ }
+
+ for _, turn := range parityConversation {
+ b, err := New("codex", Config{
+ ExecutablePath: fakeCodex,
+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ TaskID: turn.taskID,
+ WarmPool: pool,
+ Env: map[string]string{
+ "SPAWN_LOG": spawnLog,
+ "CODEX_HOME": codexHome,
+ "MULTICA_TOKEN": "mat_" + turn.taskID,
+ "MULTICA_TASK_ID": turn.taskID,
+ "MULTICA_AGENT_ID": "agent-parity",
+ },
+ })
+ if err != nil {
+ t.Fatalf("New(codex): %v", err)
+ }
+ opts := ExecOptions{Cwd: dir, Model: model, Timeout: 15 * time.Second}
+ if turn.resume {
+ opts.ResumeSessionID = threadID
+ }
+ sess, err := b.Execute(context.Background(), turn.prompt, opts)
+ if err != nil {
+ t.Fatalf("Execute(%s): %v", turn.taskID, err)
+ }
+ got := collectParityOutcome(t, sess)
+ assertParityOutcome(t, turn, got, threadID, model, "hello "+turn.taskID, TokenUsage{InputTokens: 100, OutputTokens: 10})
+ }
+
+ spawns, err := os.ReadFile(spawnLog)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n := len(splitNonEmptyLines(string(spawns))); n != mode.wantSpawns {
+ t.Fatalf("codex spawned %d times, want %d", n, mode.wantSpawns)
+ }
+ if pool.Len() != 0 {
+ t.Fatalf("pool holds %d sessions after the failed turn, want 0", pool.Len())
+ }
+ })
+ }
+}
diff --git a/server/pkg/agent/warm_pool_real_integration_test.go b/server/pkg/agent/warm_pool_real_integration_test.go
new file mode 100644
index 0000000000..cb0597e8d5
--- /dev/null
+++ b/server/pkg/agent/warm_pool_real_integration_test.go
@@ -0,0 +1,113 @@
+//go:build agentintegration
+
+package agent
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "os"
+ "strings"
+ "testing"
+ "time"
+)
+
+// Runs a real two-turn conversation with the warm pool disabled and enabled.
+// Turn 2 resumes turn 1 and must recall its code word, so it proves the resume
+// worked in both modes; the pooled run must also serve turn 2 from the parked
+// process.
+//
+// MULTICA_RUN_REAL_AGENT_SMOKE=1 go test -tags agentintegration -run 'RealWarmPoolParity' -v ./pkg/agent/
+//
+// MULTICA_REAL_PARITY_MODEL optionally overrides the provider's default model.
+func TestCodexRealWarmPoolParity(t *testing.T) {
+ runRealWarmPoolParity(t, "codex")
+}
+
+func TestClaudeRealWarmPoolParity(t *testing.T) {
+ runRealWarmPoolParity(t, "claude")
+}
+
+func runRealWarmPoolParity(t *testing.T, provider string) {
+ requireRealAgentSmoke(t)
+ model := os.Getenv("MULTICA_REAL_PARITY_MODEL")
+ codeWord := fmt.Sprintf("PINEAPPLE-%d", time.Now().UnixNano()%100000)
+
+ for _, pooled := range []bool{false, true} {
+ name := "pool disabled"
+ if pooled {
+ name = "pool miss then hit"
+ }
+ t.Run(name, func(t *testing.T) {
+ var logs synchronizedBuffer
+ logger := slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelInfo}))
+ var pool *WarmSessionPool
+ if pooled {
+ pool = NewWarmSessionPool(WarmSessionPoolConfig{IdleTTL: 5 * time.Minute, MaxIdle: 2, Logger: logger})
+ defer pool.Close()
+ }
+ dir := t.TempDir()
+
+ runTurn := func(taskID, prompt, resume string) Result {
+ t.Helper()
+ b, err := New(provider, Config{
+ Logger: logger,
+ TaskID: taskID,
+ WarmPool: pool,
+ Env: map[string]string{"MULTICA_TASK_ID": taskID},
+ })
+ if err != nil {
+ t.Fatalf("New(%s): %v", provider, err)
+ }
+ started := time.Now()
+ sess, err := b.Execute(context.Background(), prompt, ExecOptions{
+ Cwd: dir,
+ Model: model,
+ ResumeSessionID: resume,
+ Timeout: 4 * time.Minute,
+ })
+ if err != nil {
+ t.Fatalf("Execute(%s): %v", taskID, err)
+ }
+ var text strings.Builder
+ for msg := range sess.Messages {
+ if msg.Type == MessageText {
+ text.WriteString(msg.Content)
+ }
+ }
+ res := <-sess.Result
+ t.Logf("%s: status=%s session=%s duration=%s usage=%+v output=%q streamed=%q error=%q",
+ taskID, res.Status, res.SessionID, time.Since(started).Round(time.Millisecond), res.Usage, res.Output, text.String(), res.Error)
+ if res.Status != "completed" {
+ t.Fatalf("%s: status = %q, error = %q", taskID, res.Status, res.Error)
+ }
+ if res.SessionID == "" {
+ t.Fatalf("%s: no session id", taskID)
+ }
+ if len(res.Usage) == 0 {
+ t.Fatalf("%s: no usage reported", taskID)
+ }
+ if strings.TrimSpace(text.String()) == "" {
+ t.Fatalf("%s: nothing streamed", taskID)
+ }
+ return res
+ }
+
+ r1 := runTurn("task-1", "Remember the code word "+codeWord+". Reply with exactly: OK", "")
+ if pooled && pool.Len() != 1 {
+ t.Fatalf("pool holds %d sessions after turn 1, want 1", pool.Len())
+ }
+ r2 := runTurn("task-2", "What was the code word I gave you? Reply with only the code word.", r1.SessionID)
+ if r2.SessionID != r1.SessionID {
+ t.Fatalf("turn 2 session = %q, want resumed %q", r2.SessionID, r1.SessionID)
+ }
+ if !strings.Contains(r2.Output, codeWord) {
+ t.Fatalf("turn 2 output = %q, want it to recall %q", r2.Output, codeWord)
+ }
+ reused := strings.Contains(logs.String(), provider+" warm session reused")
+ if reused != pooled {
+ t.Fatalf("warm session reused = %v, want %v", reused, pooled)
+ }
+ })
+ }
+}
diff --git a/server/pkg/agent/warm_pool_real_workload_integration_test.go b/server/pkg/agent/warm_pool_real_workload_integration_test.go
new file mode 100644
index 0000000000..e940c8f7b7
--- /dev/null
+++ b/server/pkg/agent/warm_pool_real_workload_integration_test.go
@@ -0,0 +1,330 @@
+//go:build agentintegration
+
+package agent
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io/fs"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+// Drives a real agent through a long coding task: implement four stubbed Go
+// packages against their tests, then, in a resumed turn, satisfy two new test
+// files. The harness checks the result independently by running the tests
+// itself and confirming the agent left every test file untouched. Scenarios:
+//
+// - "pool disabled": every turn spawns a fresh process.
+// - "pool miss then hit": turn 1 spawns and parks, turn 2 reuses it.
+// - "cancel then resume": turn 1 is cancelled mid-task and must not be
+// parked; turn 2 resumes the session in a new process and finishes.
+//
+// Each scenario takes several minutes per turn and consumes real quota:
+//
+// MULTICA_RUN_REAL_AGENT_SMOKE=1 go test -tags agentintegration -timeout 120m \
+// -run 'TestCodexRealWorkload/pool_disabled' -v ./pkg/agent/
+//
+// MULTICA_REAL_PARITY_MODEL optionally overrides the model, and
+// MULTICA_REAL_WORKLOAD_CANCEL_AFTER (default 2m) sets when the cancel
+// scenario cancels turn 1.
+func TestCodexRealWorkload(t *testing.T) {
+ runRealWorkload(t, "codex")
+}
+
+func TestClaudeRealWorkload(t *testing.T) {
+ runRealWorkload(t, "claude")
+}
+
+const (
+ realWorkloadFixture = "testdata/real_workload"
+
+ realWorkloadBuildPrompt = "This Go module has four packages: expr, lru, ledger and semver. " +
+ "Each package has a *_test.go file that specifies the required behavior and a stub file whose functions panic. " +
+ "Implement every package so that `go test -race ./...` passes. Do not modify, rename or delete any existing *_test.go file. " +
+ "Then add your own tests in new files named extra_test.go so that every package reaches at least 90% statement coverage " +
+ "under `go test -cover ./...`, and make `go vet ./...` and `gofmt -l .` clean. " +
+ "Run the checks yourself and keep iterating until they all pass. Finish with a short summary of what you implemented."
+
+ realWorkloadFollowupPrompt = "I added two test files: expr/ternary_test.go and ledger/interest_test.go. " +
+ "Extend the code you wrote in the previous turn so they pass, keeping every existing test green " +
+ "and every package at 90% or more statement coverage; you may edit your own extra_test.go files but no other *_test.go file. " +
+ "Run `go test -race -cover ./...` before you finish. " +
+ "In your final reply, also name which of the four packages from the previous turn was the hardest and why."
+
+ realWorkloadContinuePrompt = "You were interrupted before finishing. Continue the same task: " +
+ "make `go test -race ./...` pass and bring every package to 90% or more statement coverage with tests in new extra_test.go files, " +
+ "without modifying any provided *_test.go file, then summarize what you implemented."
+)
+
+type realWorkloadTurn struct {
+ Scenario string `json:"scenario"`
+ Turn string `json:"turn"`
+ Status string `json:"status"`
+ Error string `json:"error,omitempty"`
+ Seconds float64 `json:"seconds"`
+ SessionID string `json:"session_id"`
+ WarmReused bool `json:"warm_reused"`
+ Messages map[string]int `json:"messages"`
+ ToolCalls int `json:"tool_calls"`
+ ToolResults int `json:"tool_results"`
+ Unanswered int `json:"tool_calls_without_result"`
+ StreamedText int `json:"streamed_text_bytes"`
+ OutputBytes int `json:"output_bytes"`
+ Usage TokenUsage `json:"usage"`
+ Models []string `json:"models"`
+ TestsPass bool `json:"tests_pass"`
+ Coverage map[string]float64 `json:"coverage"`
+ TestsTouched []string `json:"tests_touched,omitempty"`
+ PoolLen int `json:"pool_len"`
+ Tools map[string]int `json:"tools"`
+}
+
+func runRealWorkload(t *testing.T, provider string) {
+ requireRealAgentSmoke(t)
+ model := os.Getenv("MULTICA_REAL_PARITY_MODEL")
+ cancelAfter := 2 * time.Minute
+ if raw := os.Getenv("MULTICA_REAL_WORKLOAD_CANCEL_AFTER"); raw != "" {
+ d, err := time.ParseDuration(raw)
+ if err != nil {
+ t.Fatalf("MULTICA_REAL_WORKLOAD_CANCEL_AFTER: %v", err)
+ }
+ cancelAfter = d
+ }
+
+ for _, scenario := range []string{"pool disabled", "pool miss then hit", "cancel then resume"} {
+ t.Run(scenario, func(t *testing.T) {
+ pooled := scenario != "pool disabled"
+ var logs synchronizedBuffer
+ logger := slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelInfo}))
+ var pool *WarmSessionPool
+ if pooled {
+ pool = NewWarmSessionPool(WarmSessionPoolConfig{IdleTTL: 30 * time.Minute, MaxIdle: 2, Logger: logger})
+ defer pool.Close()
+ }
+
+ root := t.TempDir()
+ project := filepath.Join(root, "project")
+ copyFixtureTree(t, filepath.Join(realWorkloadFixture, "project"), project)
+ goEnv := map[string]string{
+ "GOCACHE": filepath.Join(project, ".cache", "go-build"),
+ "GOTMPDIR": filepath.Join(project, ".cache", "tmp"),
+ "GOTOOLCHAIN": "local",
+ "GOFLAGS": "-mod=mod",
+ }
+ if err := os.MkdirAll(goEnv["GOTMPDIR"], 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ reusedLogs := 0
+ runTurn := func(turn, prompt, resume string, ctx context.Context) (Result, realWorkloadTurn) {
+ t.Helper()
+ env := map[string]string{"MULTICA_TASK_ID": scenario + "/" + turn}
+ for k, v := range goEnv {
+ env[k] = v
+ }
+ b, err := New(provider, Config{Logger: logger, TaskID: turn, WarmPool: pool, Env: env})
+ if err != nil {
+ t.Fatalf("New(%s): %v", provider, err)
+ }
+ started := time.Now()
+ sess, err := b.Execute(ctx, prompt, ExecOptions{
+ Cwd: project,
+ Model: model,
+ ResumeSessionID: resume,
+ Timeout: 45 * time.Minute,
+ })
+ if err != nil {
+ t.Fatalf("Execute(%s): %v", turn, err)
+ }
+ rec := realWorkloadTurn{Scenario: scenario, Turn: turn, Messages: map[string]int{}, Tools: map[string]int{}}
+ open := map[string]bool{}
+ for msg := range sess.Messages {
+ rec.Messages[string(msg.Type)]++
+ switch msg.Type {
+ case MessageText:
+ rec.StreamedText += len(msg.Content)
+ case MessageToolUse:
+ rec.ToolCalls++
+ rec.Tools[msg.Tool]++
+ if msg.CallID != "" {
+ open[msg.CallID] = true
+ }
+ case MessageToolResult:
+ rec.ToolResults++
+ delete(open, msg.CallID)
+ case MessageError:
+ t.Logf("%s: error message: %s", turn, msg.Content)
+ }
+ }
+ res := <-sess.Result
+ rec.Seconds = time.Since(started).Round(time.Second).Seconds()
+ rec.Status, rec.Error, rec.SessionID = res.Status, res.Error, res.SessionID
+ rec.OutputBytes = len(res.Output)
+ rec.Unanswered = len(open)
+ for m, u := range res.Usage {
+ rec.Models = append(rec.Models, m)
+ rec.Usage.InputTokens += u.InputTokens
+ rec.Usage.OutputTokens += u.OutputTokens
+ rec.Usage.CacheReadTokens += u.CacheReadTokens
+ rec.Usage.CacheWriteTokens += u.CacheWriteTokens
+ }
+ now := strings.Count(logs.String(), provider+" warm session reused")
+ rec.WarmReused = now > reusedLogs
+ reusedLogs = now
+ if pool != nil {
+ rec.PoolLen = pool.Len()
+ }
+ rec.TestsTouched = changedTestFiles(t, project)
+ rec.TestsPass, rec.Coverage = runProjectTests(t, project, goEnv)
+ line, _ := json.Marshal(rec)
+ t.Logf("REAL_WORKLOAD %s %s", provider, line)
+ t.Logf("%s final output:\n%s", turn, res.Output)
+ return res, rec
+ }
+
+ requireCompleted := func(rec realWorkloadTurn) {
+ t.Helper()
+ if rec.Status != "completed" {
+ t.Fatalf("%s: status = %q, error = %q", rec.Turn, rec.Status, rec.Error)
+ }
+ if rec.SessionID == "" || rec.Usage == (TokenUsage{}) || rec.StreamedText == 0 || rec.ToolCalls == 0 {
+ t.Fatalf("%s: incomplete result %+v", rec.Turn, rec)
+ }
+ if len(rec.TestsTouched) > 0 {
+ t.Fatalf("%s: agent modified test files %v", rec.Turn, rec.TestsTouched)
+ }
+ if !rec.TestsPass {
+ t.Fatalf("%s: go test fails after the turn", rec.Turn)
+ }
+ for _, pkg := range []string{"expr", "ledger", "lru", "semver"} {
+ if rec.Coverage[pkg] < 90 {
+ t.Fatalf("%s: %s coverage = %.1f%%, want >= 90%%", rec.Turn, pkg, rec.Coverage[pkg])
+ }
+ }
+ }
+
+ var first Result
+ var firstRec realWorkloadTurn
+ if scenario == "cancel then resume" {
+ ctx, cancel := context.WithCancel(context.Background())
+ stop := time.AfterFunc(cancelAfter, cancel)
+ first, firstRec = runTurn("turn-1", realWorkloadBuildPrompt, "", ctx)
+ stop.Stop()
+ cancel()
+ if firstRec.Status == "completed" {
+ t.Fatalf("turn 1 completed before the %s cancel; lower MULTICA_REAL_WORKLOAD_CANCEL_AFTER", cancelAfter)
+ }
+ if firstRec.SessionID == "" {
+ t.Fatal("cancelled turn reported no session id to resume")
+ }
+ if firstRec.PoolLen != 0 {
+ t.Fatalf("cancelled turn left %d sessions parked", firstRec.PoolLen)
+ }
+ } else {
+ first, firstRec = runTurn("turn-1", realWorkloadBuildPrompt, "", context.Background())
+ requireCompleted(firstRec)
+ if firstRec.WarmReused {
+ t.Fatal("turn 1 reused a warm session")
+ }
+ if pooled && firstRec.PoolLen != 1 {
+ t.Fatalf("pool holds %d sessions after turn 1, want 1", firstRec.PoolLen)
+ }
+ }
+
+ prompt := realWorkloadFollowupPrompt
+ if scenario == "cancel then resume" {
+ prompt = realWorkloadContinuePrompt
+ } else {
+ copyFixtureTree(t, filepath.Join(realWorkloadFixture, "followup"), project)
+ }
+ _, secondRec := runTurn("turn-2", prompt, first.SessionID, context.Background())
+ requireCompleted(secondRec)
+ if secondRec.SessionID != first.SessionID {
+ t.Fatalf("turn 2 session = %q, want resumed %q", secondRec.SessionID, first.SessionID)
+ }
+ if want := scenario == "pool miss then hit"; secondRec.WarmReused != want {
+ t.Fatalf("turn 2 warm reuse = %v, want %v", secondRec.WarmReused, want)
+ }
+ })
+ }
+}
+
+func copyFixtureTree(t *testing.T, src, dst string) {
+ t.Helper()
+ err := filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ rel, _ := filepath.Rel(src, path)
+ target := filepath.Join(dst, rel)
+ if d.IsDir() {
+ return os.MkdirAll(target, 0o755)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(target, data, 0o644)
+ })
+ if err != nil {
+ t.Fatalf("copy fixture %s: %v", src, err)
+ }
+}
+
+// changedTestFiles lists fixture test files the agent altered or removed.
+func changedTestFiles(t *testing.T, project string) []string {
+ t.Helper()
+ var changed []string
+ for _, dir := range []string{"project", "followup"} {
+ src := filepath.Join(realWorkloadFixture, dir)
+ _ = filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
+ if err != nil || d.IsDir() || !strings.HasSuffix(path, "_test.go") {
+ return err
+ }
+ rel, _ := filepath.Rel(src, path)
+ want, _ := os.ReadFile(path)
+ got, readErr := os.ReadFile(filepath.Join(project, rel))
+ if dir == "followup" && os.IsNotExist(readErr) {
+ return nil
+ }
+ if readErr != nil || !bytes.Equal(got, want) {
+ changed = append(changed, rel)
+ }
+ return nil
+ })
+ }
+ return changed
+}
+
+// runProjectTests runs the project's tests and returns per-package coverage.
+func runProjectTests(t *testing.T, project string, goEnv map[string]string) (bool, map[string]float64) {
+ t.Helper()
+ cmd := exec.Command("go", "test", "-race", "-count=1", "-cover", "./...")
+ cmd.Dir = project
+ cmd.Env = os.Environ()
+ for k, v := range goEnv {
+ cmd.Env = append(cmd.Env, k+"="+v)
+ }
+ out, err := cmd.CombinedOutput()
+ coverage := map[string]float64{}
+ for _, m := range coverageLine.FindAllStringSubmatch(string(out), -1) {
+ pct, _ := strconv.ParseFloat(m[2], 64)
+ coverage[m[1]] = pct
+ }
+ if err != nil {
+ t.Logf("go test in %s failed: %v\n%s", project, err, out)
+ return false, coverage
+ }
+ return true, coverage
+}
+
+var coverageLine = regexp.MustCompile(`(?m)^ok\s+workbench/(\w+)\s.*coverage: ([0-9.]+)% of statements`)
diff --git a/server/pkg/agent/warm_pool_test.go b/server/pkg/agent/warm_pool_test.go
index e2b52a09dd..e7032191d8 100644
--- a/server/pkg/agent/warm_pool_test.go
+++ b/server/pkg/agent/warm_pool_test.go
@@ -3,6 +3,7 @@ package agent
import (
"context"
"encoding/json"
+ "fmt"
"io"
"log/slog"
"os"
@@ -303,7 +304,7 @@ done
// Verify idle task-env file holds NO live token while parked.
pool.mu.Lock()
- parked := pool.entries[warmPoolKey{provider: "codex", sessionID: "thr-warm-1"}].proc.(*warmCodexProcess)
+ parked := pool.entries[warmPoolKey{provider: "codex", sessionID: "thr-warm-1"}].proc.(*codexProcess)
envFilePath := parked.taskEnvFile
pool.mu.Unlock()
idleData, err := os.ReadFile(envFilePath)
@@ -596,6 +597,80 @@ done
}
}
+// A pooled turn ends at its result event while the process keeps writing.
+// Events that land during the turn's teardown must not reach the finished
+// turn: its message channel is about to close and its control-write
+// WaitGroup is being waited on.
+func TestClaudeWarmPoolIgnoresEventsAfterResult(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fake binary requires a POSIX shell")
+ }
+
+ dir := t.TempDir()
+ fakeClaude := filepath.Join(dir, "claude")
+ script := `#!/bin/sh
+turn=0
+while IFS= read -r line; do
+ case "$line" in
+ *'"type":"user"'*)
+ turn=$((turn + 1))
+ printf '{"type":"system","subtype":"init","session_id":"claude-trailing-1"}\n'
+ printf '{"type":"assistant","message":{"id":"msg-%s","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"turn %s"}]}}\n' "$turn" "$turn"
+ printf '{"type":"result","subtype":"success","session_id":"claude-trailing-1","result":"turn %s","is_error":false}\n' "$turn"
+ i=0
+ while [ "$i" -lt 40 ]; do
+ printf '{"type":"system","subtype":"status","session_id":"claude-trailing-1"}\n'
+ printf '{"type":"log","log":{"level":"info","message":"after result %s"}}\n' "$i"
+ printf '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"late"}}}\n'
+ printf '{"type":"assistant","message":{"id":"late-%s-%s","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"late"}]}}\n' "$turn" "$i"
+ printf '{"type":"control_request","request_id":"late-%s-%s","request":{"subtype":"can_use_tool","tool_name":"Bash","input":{}}}\n' "$turn" "$i"
+ i=$((i + 1))
+ done
+ ;;
+ esac
+done
+`
+ writeTestExecutable(t, fakeClaude, []byte(script))
+
+ pool := NewWarmSessionPool(WarmSessionPoolConfig{
+ IdleTTL: 30 * time.Second,
+ MaxIdle: 4,
+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ })
+ defer pool.Close()
+
+ resume := ""
+ for i := 1; i <= 40; i++ {
+ taskID := fmt.Sprintf("task-trailing-%d", i)
+ b, err := New("claude", Config{
+ ExecutablePath: fakeClaude,
+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ TaskID: taskID,
+ WarmPool: pool,
+ Env: map[string]string{"MULTICA_TASK_ID": taskID},
+ })
+ if err != nil {
+ t.Fatalf("New(claude): %v", err)
+ }
+ sess, err := b.Execute(context.Background(), "go", ExecOptions{
+ Cwd: dir,
+ Model: "claude-opus-5-5",
+ ResumeSessionID: resume,
+ Timeout: 10 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("Execute(%s): %v", taskID, err)
+ }
+ for range sess.Messages {
+ }
+ res := <-sess.Result
+ if res.Status != "completed" || res.SessionID != "claude-trailing-1" {
+ t.Fatalf("%s result = %+v", taskID, res)
+ }
+ resume = res.SessionID
+ }
+}
+
func TestClaudeStreamCoalescerLeadingCoalescingAndReconciliation(t *testing.T) {
t.Parallel()