Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
KAP-867: retry safe Codex initialize timeouts
milymarkovic983545b34d59
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 1fe4e1dfc6..bea576437e 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -4185,6 +4185,10 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iCLIVersion: resolvedVersion,Env: agentEnv,Logger: d.logger,+ TaskID: task.ID,+ RuntimeID: task.RuntimeID,+ DaemonVersion: d.cfg.CLIVersion,+ CodexVersion: codexVersion,})if err != nil {return TaskResult{}, fmt.Errorf("create agent backend: %w", err)diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 49d84a1269..deb944f616 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -141,6 +141,11 @@ type Result struct {DurationMs int64SessionID stringUsage map[string]TokenUsage // keyed by model name+ // codexInitializeRetrySafe is provider-internal evidence that an+ // initialize timeout happened before semantic activity and after the+ // process tree was reaped. It is intentionally not part of the public+ // result contract.+ codexInitializeRetrySafe bool}// Config configures a Backend instance.@@ -149,6 +154,10 @@ type Config struct {CLIVersion string // detected version paired with ExecutablePath; observation only, never used to choose behaviorEnv map[string]string // extra environment variablesLogger *slog.Logger+ TaskID string+ RuntimeID string+ DaemonVersion string+ CodexVersion string}// New creates a Backend for the given agent type.diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex e201203f28..0c8ada0c59 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -6,6 +6,7 @@ import ("encoding/json""errors""fmt"+ "io""log/slog""os""os/exec"@@ -18,6 +19,8 @@ import ("sync/atomic""syscall""time"++ "github.com/multica-ai/multica/server/pkg/redact")// codexBlockedArgs are flags hardcoded by the daemon that must not be@@ -58,6 +61,35 @@ const (// instead of burning two full grace windows per cleanup phase. Mirrors// the opencodeTerminateGraceNanos hook.var codexGracefulShutdownTimeoutNanos atomic.Int64+var activeCodexLaunches atomic.Int64+var maxActiveCodexLaunchesObserved atomic.Int64+var codexCleanupConfirmationOverride atomic.Int32++var (+ codexAuthorizationHeaderRe = regexp.MustCompile(`(?im)(authorization\s*:\s*)[^\r\n]+`)+ codexJSONSecretRe = regexp.MustCompile(`(?i)("(?:token|auth|authorization|api[_-]?key|secret|password)"\s*:\s*)"(?:\\.|[^"\\])*"`)+ codexDiagnosticSecretRe = regexp.MustCompile(`(?i)(authorization|auth|api[_-]?key|token|secret|password)(\s*[:=]\s*)([^\s,;]+)`)+)++func sanitizeCodexDiagnostic(value string) string {+ value = strings.Map(func(r rune) rune {+ if r < 0x20 && r != '\n' && r != '\t' {+ return -1+ }+ return r+ }, value)+ value = codexAuthorizationHeaderRe.ReplaceAllString(value, `$1[REDACTED]`)+ value = codexJSONSecretRe.ReplaceAllString(value, `$1"[REDACTED]"`)+ value = codexDiagnosticSecretRe.ReplaceAllString(value, `$1$2[REDACTED]`)+ return redact.Text(value)+}++func codexProcessExitStatus(state *os.ProcessState) any {+ if state == nil {+ return nil+ }+ return state.String()+}func codexGracefulShutdown() time.Duration {if n := codexGracefulShutdownTimeoutNanos.Load(); n > 0 {@@ -566,6 +598,53 @@ func isCodexBareTomlKey(s string) bool {}func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {+ firstSession, err := b.executeOnce(ctx, prompt, opts, 1)+ if err != nil {+ return nil, err+ }+ msgCh := make(chan Message, 256)+ resCh := make(chan Result, 1)++ go func() {+ defer close(msgCh)+ defer close(resCh)+ session := firstSession+ for attempt := 1; attempt <= 2; attempt++ {+ if attempt > 1 {+ var err error+ session, err = b.executeOnce(ctx, prompt, opts, attempt)+ if err != nil {+ resCh <- Result{Status: "failed", Error: err.Error()}+ return+ }+ }+ for msg := range session.Messages {+ msgCh <- msg+ }+ result, ok := <-session.Result+ if !ok {+ resCh <- Result{Status: "failed", Error: "codex attempt closed without result"}+ return+ }+ if !result.codexInitializeRetrySafe || attempt == 2 {+ resCh <- result+ return+ }+ backoff := 75*time.Millisecond + time.Duration(time.Now().UnixNano()%50)*time.Millisecond+ b.cfg.Logger.Warn("codex initialize retry scheduled", "attempt", attempt, "next_attempt", attempt+1, "backoff", backoff.String())+ select {+ case <-ctx.Done():+ resCh <- result+ return+ case <-time.After(backoff):+ }+ }+ }()++ return &Session{Messages: msgCh, Result: resCh}, nil+}++func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts ExecOptions, attempt int) (*Session, error) {execPath := b.cfg.ExecutablePathif execPath == "" {execPath = "codex"@@ -657,15 +736,29 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpticancel()return nil, fmt.Errorf("codex stdin pipe: %w", err)}- stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[codex:stderr] "), codexStderrTailBytes)+ // 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 = stderrBufif err := cmd.Start(); err != nil {cancel()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 started app-server", "pid", cmd.Process.Pid, "cwd", opts.Cwd)+ 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)@@ -673,6 +766,7 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptivar outputMu sync.Mutexvar output strings.Builder+ var semanticObserved atomic.Bool// turnDone is set before starting the reader goroutine so there is no// race between the lifecycle goroutine writing and the reader reading.@@ -694,8 +788,12 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti}trySend(msgCh, msg)trySendString(semanticActivityCh, describeCodexSemanticActivity(msg))+ if describeCodexSemanticActivity(msg) != "" {+ semanticObserved.Store(true)+ }},onSemanticActivity: func(description string) {+ semanticObserved.Store(true)b.cfg.Logger.Debug("codex semantic activity observed", "activity", description)trySendString(semanticActivityCh, description)},@@ -770,6 +868,9 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti// cmd.WaitDelay then guarantees cmd.Wait() returns even if pipes// stay open.var waitOnce sync.Once+ var cleanupConfirmed bool+ var waitReturned bool+ var cleanupWaitErr errordrainAndWait := func() {waitOnce.Do(func() {stdin.Close()@@ -800,11 +901,12 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti// codex stayed blocked writing into a full stdout pipe).waitCh := make(chan struct{})go func() {- _ = cmd.Wait()+ cleanupWaitErr = cmd.Wait()close(waitCh)}()select {case <-waitCh:+ waitReturned = true// reaped cleanly.case <-time.After(grace):b.cfg.Logger.Warn("codex process still alive after reader exited; forcing shutdown",@@ -817,7 +919,30 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti// 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+ 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,+ "stderr_tail", sanitizeCodexDiagnostic(stderrBuf.Tail()),+ )})}@@ -826,6 +951,7 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti// codex process exits → reader goroutine's scanner.Scan() returns false →// readerDone closes → lifecycle goroutine collects final output and sends Result.go func() {+ defer activeCodexLaunches.Add(-1)defer cancel()defer close(msgCh)defer close(resCh)@@ -836,6 +962,8 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptivar finalError string// 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",@@ -847,12 +975,22 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti},})if err != nil {+ initializeLatency := time.Since(initializeStarted)drainAndWait() // flush os/exec stderr goroutine before sampling TailfinalStatus = "failed"- finalError = withAgentStderr(fmt.Sprintf("codex initialize failed: %v", err), "codex", stderrBuf.Tail())- resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ finalError = withAgentStderr(fmt.Sprintf("codex initialize failed: %v", err), "codex", sanitizeCodexDiagnostic(stderrBuf.Tail()))+ var handshakeErr *codexHandshakeTimeoutError+ retrySafe := errors.As(err, &handshakeErr) && handshakeErr.Method == "initialize" && !semanticObserved.Load() && cleanupConfirmed && codexInitializeRetrySupported()+ if errors.As(err, &handshakeErr) && handshakeErr.Method == "initialize" && !cleanupConfirmed {+ finalError += "; retry suppressed: process cleanup/reap not confirmed"+ } else if errors.As(err, &handshakeErr) && handshakeErr.Method == "initialize" && 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}+ 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@@ -862,7 +1000,7 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptiif err != nil {drainAndWait() // flush os/exec stderr goroutine before sampling TailfinalStatus = "failed"- finalError = withAgentStderr(err.Error(), "codex", stderrBuf.Tail())+ finalError = withAgentStderr(err.Error(), "codex", sanitizeCodexDiagnostic(stderrBuf.Tail()))resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}return}@@ -918,7 +1056,7 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptidefault:drainAndWait() // flush os/exec stderr goroutine before sampling TailfinalStatus = "failed"- finalError = withAgentStderr(fmt.Sprintf("codex turn/start failed: %v", err), "codex", stderrBuf.Tail())+ finalError = withAgentStderr(fmt.Sprintf("codex turn/start failed: %v", err), "codex", sanitizeCodexDiagnostic(stderrBuf.Tail()))resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}return}@@ -1039,11 +1177,11 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptidrainAndWait()if processExitErr != nil {- finalError = withAgentStderr(processExitErr.Error(), "codex", stderrBuf.Tail())+ finalError = withAgentStderr(processExitErr.Error(), "codex", sanitizeCodexDiagnostic(stderrBuf.Tail()))}if timeoutDiagnostic.Kind != codexTimeoutNone {timeoutDiagnostic.CodexVersion = detectCodexVersionForDiagnostics(context.Background(), execPath, cmd.Env, b.cfg.Logger)- finalError = buildCodexTimeoutDiagnosticError(timeoutDiagnostic, stderrBuf.Tail())+ finalError = buildCodexTimeoutDiagnosticError(timeoutDiagnostic, sanitizeCodexDiagnostic(stderrBuf.Tail()))}outputMu.Lock()@@ -1270,6 +1408,7 @@ func isCodexFirstTurnProgressActivity(activity string) bool {}func buildCodexTimeoutDiagnosticError(diag codexTimeoutDiagnostic, stderrTail string) string {+ stderrTail = sanitizeCodexDiagnostic(stderrTail)var msg stringswitch diag.Kind {case codexTimeoutFirstTurnNoProgress:diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.goindex 70fb6a759b..ba5e6bd0b3 100644--- a/server/pkg/agent/codex_test.go+++ b/server/pkg/agent/codex_test.go@@ -1685,6 +1685,256 @@ func TestCodexExecuteStartupRPCsHaveBoundedHandshakeTimeout(t *testing.T) {}}+func TestCodexExecuteRetriesInitializeTimeoutOnceAfterCleanup(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ countPath := filepath.Join(t.TempDir(), "launch-count")+ fakePath := writeFakeCodexAppServer(t, ""++ `count=0; test -f `+countPath+` && count=$(cat `+countPath+`)`+"\n"++ `count=$((count + 1)); echo "$count" > `+countPath+"\n"++ `read line`+"\n"++ `if test "$count" -eq 1; then sleep 5; exit 0; fi`+"\n"++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"++ `read line`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-retried"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-retried","turn":{"id":"turn-1","status":"completed"}}}'`+"\n")++ result := executeFakeCodex(t, fakePath, ExecOptions{+ Timeout: 10 * time.Second,+ HandshakeTimeout: 100 * time.Millisecond,+ SemanticInactivityTimeout: time.Second,+ })+ if result.Status != "completed" {+ t.Fatalf("expected retry to complete, got status=%q error=%q", result.Status, result.Error)+ }+ data, err := os.ReadFile(countPath)+ if err != nil {+ t.Fatalf("read launch count: %v", err)+ }+ if got := strings.TrimSpace(string(data)); got != "2" {+ t.Fatalf("launch count = %q, want 2", got)+ }+}++func TestCodexExecuteInitializeRetrySafetyGates(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ t.Run("both attempts time out", func(t *testing.T) {+ countPath := filepath.Join(t.TempDir(), "launch-count")+ fakePath := writeFakeCodexAppServer(t, ""++ `count=0; test -f `+countPath+` && count=$(cat `+countPath+`)`+"\n"++ `count=$((count + 1)); echo "$count" > `+countPath+"\n"++ `read line`+"\n"++ `sleep 1`+"\n")+ result := executeFakeCodex(t, fakePath, ExecOptions{Timeout: 5 * time.Second, HandshakeTimeout: 50 * time.Millisecond})+ if result.Status != "failed" || !strings.Contains(result.Error, CodexHandshakeTimeoutMarker) {+ t.Fatalf("expected final initialize timeout, got status=%q error=%q", result.Status, result.Error)+ }+ data, _ := os.ReadFile(countPath)+ if got := strings.TrimSpace(string(data)); got != "2" {+ t.Fatalf("launch count = %q, want 2", got)+ }+ })++ t.Run("semantic activity suppresses retry", func(t *testing.T) {+ countPath := filepath.Join(t.TempDir(), "launch-count")+ fakePath := writeFakeCodexAppServer(t, ""++ `echo x >> `+countPath+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","method":"item/started","params":{"threadId":"unexpected","item":{"type":"commandExecution","id":"cmd-1","command":"true"}}}'`+"\n"++ `sleep 1`+"\n")+ result := executeFakeCodex(t, fakePath, ExecOptions{Timeout: 5 * time.Second, HandshakeTimeout: 50 * time.Millisecond})+ if result.Status != "failed" {+ t.Fatalf("expected failed, got %q", result.Status)+ }+ data, _ := os.ReadFile(countPath)+ if got := strings.Count(string(data), "x"); got != 1 {+ t.Fatalf("launch count = %d, want 1", got)+ }+ })++ t.Run("unconfirmed cleanup suppresses retry", func(t *testing.T) {+ codexCleanupConfirmationOverride.Store(-1)+ defer codexCleanupConfirmationOverride.Store(0)+ countPath := filepath.Join(t.TempDir(), "launch-count")+ fakePath := writeFakeCodexAppServer(t, ""++ `echo x >> `+countPath+"\n"++ `read line`+"\n"++ `sleep 1`+"\n")+ result := executeFakeCodex(t, fakePath, ExecOptions{Timeout: 5 * time.Second, HandshakeTimeout: 50 * time.Millisecond})+ if !strings.Contains(result.Error, "retry suppressed: process cleanup/reap not confirmed") {+ t.Fatalf("expected cleanup reason, got %q", result.Error)+ }+ data, _ := os.ReadFile(countPath)+ if got := strings.Count(string(data), "x"); got != 1 {+ t.Fatalf("launch count = %d, want 1", got)+ }+ })+}++func TestCodexExecuteDoesNotSerializeConcurrentLaunches(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }+ fakePath := writeFakeCodexAppServer(t, ""++ `read line`+"\n"++ `sleep 0.4`+"\n"++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"++ `read line`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-concurrent"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-concurrent","turn":{"id":"turn-1","status":"completed"}}}'`+"\n")++ maxActiveCodexLaunchesObserved.Store(0)+ results := make(chan Result, 2)+ for i := 0; i < 2; i++ {+ go func() {+ backend, _ := New("codex", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ session, err := backend.Execute(context.Background(), "prompt", ExecOptions{Timeout: 5 * time.Second})+ if err != nil {+ results <- Result{Status: "failed", Error: err.Error()}+ return+ }+ go func() {+ for range session.Messages {+ }+ }()+ results <- <-session.Result+ }()+ }+ for i := 0; i < 2; i++ {+ if result := <-results; result.Status != "completed" {+ t.Fatalf("concurrent result failed: %+v", result)+ }+ }+ if got := maxActiveCodexLaunchesObserved.Load(); got < 2 {+ t.Fatalf("launches appear serialized: max active=%d", got)+ }+}++func TestSanitizeCodexDiagnosticRedactsSecrets(t *testing.T) {+ got := sanitizeCodexDiagnostic("Authorization: Bearer bearer-token\n" ++ `{"token":"json-token","auth": "json-auth", "api_key":"json-key"}` ++ "\npassword=plain-secret\x00")+ for _, secret := range []string{"bearer-token", "json-token", "json-auth", "json-key", "plain-secret"} {+ if strings.Contains(got, secret) {+ t.Fatalf("sanitized diagnostic leaked %q: %q", secret, got)+ }+ }+}++func TestCodexExecuteRedactsStderrFromResultAndLogs(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }+ const (+ bearer = "bearer-secret-value"+ jsonToken = "json-secret-value"+ standalone = "sk-abcdefghijklmnopqrstuvwxyz123456"+ )+ fakePath := writeFakeCodexAppServer(t, ""++ `echo 'Authorization: Bearer `+bearer+`' >&2`+"\n"++ `echo '{"token":"`+jsonToken+`"}' >&2`+"\n"++ `echo '`+standalone+`' >&2`+"\n"++ `exit 2`+"\n")+ var logs bytes.Buffer+ logger := slog.New(slog.NewJSONHandler(&logs, nil))+ backend, err := New("codex", Config{ExecutablePath: fakePath, Logger: logger})+ if err != nil {+ t.Fatal(err)+ }+ session, err := backend.Execute(context.Background(), "prompt", ExecOptions{Timeout: 5 * time.Second})+ if err != nil {+ t.Fatal(err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ result := <-session.Result+ combined := result.Error + "\n" + logs.String()+ for _, secret := range []string{bearer, jsonToken, standalone} {+ if strings.Contains(combined, secret) {+ t.Fatalf("stderr secret leaked: %q in %q", secret, combined)+ }+ }+}++func TestCodexExecuteDoesNotProbeVersionBeforeInitialize(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }+ fakePath := writeFakeCodexAppServer(t, ""++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"++ `read line`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-fast-init"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-fast-init","turn":{"id":"turn-1","status":"completed"}}}'`+"\n")+ data, err := os.ReadFile(fakePath)+ if err != nil {+ t.Fatal(err)+ }+ data = bytes.Replace(data, []byte(`echo "codex-cli 0.0.0-test"; exit 0`), []byte(`sleep 2; echo "codex-cli 0.0.0-test"; exit 0`), 1)+ writeTestExecutable(t, fakePath, data)++ backend, err := New("codex", Config{ExecutablePath: fakePath, Logger: slog.Default(), CodexVersion: "cached-test-version"})+ if err != nil {+ t.Fatal(err)+ }+ started := time.Now()+ session, err := backend.Execute(context.Background(), "prompt", ExecOptions{Timeout: 5 * time.Second})+ if err != nil {+ t.Fatal(err)+ }+ if elapsed := time.Since(started); elapsed > 500*time.Millisecond {+ t.Fatalf("Execute blocked on version probe before initialize: %s", elapsed)+ }+ go func() {+ for range session.Messages {+ }+ }()+ if result := <-session.Result; result.Status != "completed" {+ t.Fatalf("result=%+v", result)+ }+}++func TestCodexExecuteRetriesAfterSignaledProcessIsReaped(t *testing.T) {+ if runtime.GOOS != "linux" {+ t.Skip("Linux signal/reap semantics regression")+ }+ codexGracefulShutdownTimeoutNanos.Store(int64(100 * time.Millisecond))+ defer codexGracefulShutdownTimeoutNanos.Store(0)+ countPath := filepath.Join(t.TempDir(), "launch-count")+ fakePath := writeFakeCodexAppServer(t, ""++ `count=0; test -f `+countPath+` && count=$(cat `+countPath+`)`+"\n"++ `count=$((count + 1)); echo "$count" > `+countPath+"\n"++ `read line`+"\n"++ `if test "$count" -eq 1; then exec sleep 30; fi`+"\n"++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"++ `read line`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-signaled"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-signaled","turn":{"id":"turn-1","status":"completed"}}}'`+"\n")+ result := executeFakeCodex(t, fakePath, ExecOptions{Timeout: 5 * time.Second, HandshakeTimeout: 50 * time.Millisecond})+ if result.Status != "completed" {+ t.Fatalf("signaled/reaped first attempt should retry: %+v", result)+ }+}+func TestCodexExecuteTimesOutWhenTurnStopsAfterToolResult(t *testing.T) {t.Parallel()if runtime.GOOS == "windows" {diff --git a/server/pkg/agent/proc_other.go b/server/pkg/agent/proc_other.goindex 18f5d1849d..4c43c521e0 100644--- a/server/pkg/agent/proc_other.go+++ b/server/pkg/agent/proc_other.go@@ -24,6 +24,8 @@ func configureProcessGroup(cmd *exec.Cmd) {cmd.SysProcAttr.Setpgid = true}+func codexInitializeRetrySupported() bool { return true }+// signalProcessGroup sends sig to the whole process group led by p (when the// command was started with configureProcessGroup), falling back to the single// process if the group send fails. Targeting the group (negative pid) reachesdiff --git a/server/pkg/agent/proc_windows.go b/server/pkg/agent/proc_windows.goindex d53c83d947..c862cc606b 100644--- a/server/pkg/agent/proc_windows.go+++ b/server/pkg/agent/proc_windows.go@@ -37,6 +37,10 @@ func hideAgentWindow(cmd *exec.Cmd) {// hideAgentWindow plus exec.CommandContext / WaitDelay terminating the child.func configureProcessGroup(cmd *exec.Cmd) {}+// codexInitializeRetrySupported remains false until Codex children are owned+// by a Job Object and descendant termination can be positively confirmed.+func codexInitializeRetrySupported() bool { return false }+// signalProcessGroup terminates the process on Windows. Windows has no// SIGTERM/SIGKILL distinction or process-group signalling, so the signal is// ignored and the process is killed directly (TerminateProcess via Kill). Thediff --git a/server/pkg/agent/proc_windows_test.go b/server/pkg/agent/proc_windows_test.goindex 58a55b481c..7594813e08 100644--- a/server/pkg/agent/proc_windows_test.go+++ b/server/pkg/agent/proc_windows_test.go@@ -63,3 +63,9 @@ func TestHideAgentWindowPreservesExistingSysProcAttr(t *testing.T) {t.Error("CREATE_NEW_CONSOLE should be OR'd into existing flags")}}++func TestCodexInitializeRetrySuppressedWithoutConfirmedTreeCleanup(t *testing.T) {+ if codexInitializeRetrySupported() {+ t.Fatal("Codex initialize retry must remain disabled until Windows descendant cleanup is positively confirmed")+ }+}diff --git a/server/pkg/agent/stderr_tail.go b/server/pkg/agent/stderr_tail.goindex b123922920..8a39b56f5b 100644--- a/server/pkg/agent/stderr_tail.go+++ b/server/pkg/agent/stderr_tail.go@@ -27,8 +27,9 @@ type stderrTail struct {inner io.Writermax int- mu sync.Mutex- buf []byte+ mu sync.Mutex+ buf []byte+ total int64}func newStderrTail(inner io.Writer, max int) *stderrTail {@@ -43,6 +44,7 @@ func (s *stderrTail) Write(p []byte) (int, error) {return 0, err}s.mu.Lock()+ s.total += int64(len(p))s.buf = append(s.buf, p...)if len(s.buf) > s.max {s.buf = s.buf[len(s.buf)-s.max:]@@ -51,6 +53,12 @@ func (s *stderrTail) Write(p []byte) (int, error) {return len(p), nil}+func (s *stderrTail) TotalBytes() int64 {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.total+}+// Tail returns the captured stderr with leading/trailing whitespace// trimmed; empty string means nothing was written or everything was// whitespace.