package thin import ( "bytes" "context" "encoding/json" "errors" "fmt" "log/slog" "os" "path/filepath" "strconv" "strings" "testing" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/codex" "amadan.net/oficina/equipo/internal/wire" ) // codexStartFixture is a Codex source home and a coordinator on it whose // start fails before any process: refresh is the test's. func codexStartFixture(t *testing.T, stateDir string, refresh func(context.Context, provider.Binding) (provider.Identity, error)) (Coordinator, *bytes.Buffer) { t.Helper() root := t.TempDir() home := filepath.Join(root, "codex-1") id := provider.Identity{AccountID: "person@example.com", HomeID: "home-1", ProviderVersion: codex.Version} raw, _ := json.Marshal(id) if os.Mkdir(home, 0700) != nil || os.WriteFile(filepath.Join(home, provider.IdentityFile), raw, 0600) != nil || os.WriteFile(filepath.Join(home, "auth.json"), []byte(`{"tokens":{}}`), 0600) != nil { t.Fatal("home") } db := filepath.Join(root, "state") if stateDir == "" { stateDir = db } scratch := filepath.Join(root, "scratch") for _, d := range []string{db, scratch} { if err := os.MkdirAll(d, 0700); err != nil { t.Fatal(err) } } state, err := OpenState(context.Background(), db) if err != nil { t.Fatal(err) } t.Cleanup(func() { state.Close() }) var logs bytes.Buffer o := ClaudeOptions{Runner: runner.Config{StateDir: stateDir, ScratchRoot: scratch}, State: state, SessionRoot: filepath.Join(root, "sessions"), Refresh: refresh, Logger: slog.New(slog.NewTextHandler(&logs, nil))} b := runner.AccountBinding{ID: "codex-1", LocalID: "codex-1", Provider: "codex", Family: "gpt", Model: "gpt-test", PersonID: "p@example.com", ProviderHome: home, AccountID: id.AccountID, ExpectedIdentity: id, Kind: "subscription"} c, err := OpenCodex(o, CodexOptions{}, "p@example.com", b) if err != nil { t.Fatal(err) } t.Cleanup(c.Close) return c, &logs } func codexTurn(c Coordinator) TurnResult { return c.Turn(context.Background(), TurnInput{Person: "p@example.com", Lane: wire.LaneCoordinator, TurnID: "t1", Attempt: 1, Text: "hello"}, func(string) {}) } // A failed start says where it failed, as a fixed step name beside the // sanitized error (2026-11-22: staging logged only *errors.errorString). func TestCodexStartLogsItsStep(t *testing.T) { ok := func(_ context.Context, b provider.Binding) (provider.Identity, error) { return b.Expected, nil } cases := []struct { name, want, reason string stateDir string refresh func(context.Context, provider.Binding) (provider.Identity, error) }{ {name: "refresh refused", want: `err="refresh: provider_identity_mismatch"`, reason: "account_unavailable", refresh: func(context.Context, provider.Binding) (provider.Identity, error) { return provider.Identity{}, provider.ErrIdentity }}, {name: "sign in again", want: `err="refresh: account.sign_in_again"`, reason: "sign_in_again", refresh: func(context.Context, provider.Binding) (provider.Identity, error) { return provider.Identity{}, provider.ErrLoginRequired }}, // Any other error is still only its type, now with its step. {name: "tool socket", want: `err="tool_socket: *fs.PathError"`, reason: "account_unavailable", refresh: ok, stateDir: filepath.Join(t.TempDir(), "missing")}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { c, logs := codexStartFixture(t, tc.stateDir, tc.refresh) res := codexTurn(c) if res.Reason != tc.reason { t.Fatalf("reason %q, want %q", res.Reason, tc.reason) } if !strings.Contains(logs.String(), `msg="codex coordinator start" `+tc.want) { t.Fatalf("log %q, want %s", logs.String(), tc.want) } }) } } var errSecretWords = errors.New("secret words /home/someone") // A step name never carries the error's own words. func TestSanitizeStepKeepsOnlyTheCode(t *testing.T) { err := atStep("tool_socket", errSecretWords) if got := sanitize(err); got != "tool_socket: *errors.errorString" { t.Fatalf("logged %q", got) } if got := sanitize(atStep("copy", atStep("refresh", provider.ErrIdentity))); got != "refresh: provider_identity_mismatch" { t.Fatalf("logged %q", got) } } const secretCanary = "secret-canary-sk-0000" // secretErrors carry the canary in their own text: wrapped around a // cancellation, a deadline or a provider code, and joined. func secretErrors() []struct { err error want string } { return []struct { err error want string }{ {fmt.Errorf("%s: %w", secretCanary, context.Canceled), "cancelled"}, {fmt.Errorf("%s: %w", secretCanary, context.DeadlineExceeded), "deadline"}, {errors.Join(errors.New(secretCanary), context.Canceled), "*errors.errorString; cancelled"}, {errors.Join(fmt.Errorf("%s: %w", secretCanary, context.DeadlineExceeded), errors.New(secretCanary)), "deadline; *errors.errorString"}, {fmt.Errorf("%s: %w", secretCanary, errors.Join(errors.New(secretCanary), context.Canceled)), "*errors.errorString; cancelled"}, } } // The sanitizer emits fixed codes and types only, never an error's own // text, wrapped or joined (Astra review of bf4c4ff4). func TestSanitizeNeverPrintsErrorText(t *testing.T) { for _, tc := range secretErrors() { got := sanitize(atStep("refresh", tc.err)) if strings.Contains(got, secretCanary) || got != "refresh: "+tc.want { t.Errorf("sanitize(%q) = %q, want %q", tc.err, got, "refresh: "+tc.want) } } } // Both coordinators' start logs share the sanitizer: a secret in a // refresh error never reaches either log. func TestStartLogsNeverPrintErrorText(t *testing.T) { for _, tc := range secretErrors() { refresh := func(context.Context, provider.Binding) (provider.Identity, error) { return provider.Identity{}, tc.err } c, logs := codexStartFixture(t, "", refresh) codexTurn(c) if strings.Contains(logs.String(), secretCanary) || !strings.Contains(logs.String(), `msg="codex coordinator start" err=`+slogValue("refresh: "+tc.want)) { t.Errorf("codex log %q, want refresh: %s", logs.String(), tc.want) } c, logs = claudeStartFixture(t, refresh) codexTurn(c) if strings.Contains(logs.String(), secretCanary) || !strings.Contains(logs.String(), `msg="coordinator start" err=`+slogValue(tc.want)) { t.Errorf("claude log %q, want %s", logs.String(), tc.want) } } } // slogValue is v as the text handler writes it: quoted when it must be. func slogValue(v string) string { if strings.ContainsAny(v, " ;\"=") { return strconv.Quote(v) } return v } // claudeStartFixture is a Claude source home and a coordinator on it whose // start fails at the test's refresh. func claudeStartFixture(t *testing.T, refresh func(context.Context, provider.Binding) (provider.Identity, error)) (Coordinator, *bytes.Buffer) { t.Helper() root := t.TempDir() home := filepath.Join(root, "claude-a") id := provider.Identity{AccountID: "person@example.com", HomeID: "home-a", ProviderVersion: provider.ClaudeVersion} raw, _ := json.Marshal(id) if os.Mkdir(home, 0700) != nil || os.WriteFile(filepath.Join(home, provider.IdentityFile), raw, 0600) != nil || os.WriteFile(filepath.Join(home, ".credentials.json"), []byte(`{}`), 0600) != nil { t.Fatal("home") } db, scratch := filepath.Join(root, "state"), filepath.Join(root, "scratch") for _, d := range []string{db, scratch} { if err := os.MkdirAll(d, 0700); err != nil { t.Fatal(err) } } state, err := OpenState(context.Background(), db) if err != nil { t.Fatal(err) } t.Cleanup(func() { state.Close() }) var logs bytes.Buffer o := ClaudeOptions{Runner: runner.Config{StateDir: db, ScratchRoot: scratch}, State: state, SessionRoot: filepath.Join(root, "sessions"), Refresh: refresh, Logger: slog.New(slog.NewTextHandler(&logs, nil))} b := runner.AccountBinding{ID: "claude-a", LocalID: "claude-a", Provider: "claude", Family: "claude", Model: "claude-test", PersonID: "p@example.com", ProviderHome: home, AccountID: id.AccountID, ExpectedIdentity: id, Kind: "subscription"} c, err := OpenClaude(o, "p@example.com", b) if err != nil { t.Fatal(err) } t.Cleanup(c.Close) return c, &logs }