Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ codex-switch current
# Detect or reconcile a login performed directly in Codex.
codex-switch sync --check
codex-switch sync

# Inspect Codex's local project migration after an app update.
codex-switch project status
```

Use `codex-switch doctor` before reporting a problem. Machine-readable output is
Expand Down Expand Up @@ -149,6 +152,8 @@ codex-switch current
codex-switch status
codex-switch sync [--check] [--prefer-live] [--as <alias>]
codex-switch doctor
codex-switch project status
codex-switch project repair [--force]
codex-switch use <alias>
codex-switch deactivate
codex-switch select
Expand Down Expand Up @@ -194,13 +199,26 @@ same safe reconciliation without rewriting `auth.json`, closing Codex, or
requiring a restart. A real switch to a different account still requires Codex
to be stopped.

Recent Codex desktop releases moved canonical thread-to-project membership into
the App Server state database while retaining a legacy desktop-side assignment
map. If that upstream migration is incomplete, `project status` reports it and
`project repair` reconciles the legacy IDs through the official App Server
protocol. A normal `use` automatically performs this repair when Codex is
closed. The operation is idempotent and creates a timestamped backup of
`.codex-global-state.json` before marking the migration complete.

## What a switch changes

Normal account switches modify only:

- `$CODEX_HOME/auth.json`
- `codex-switch`'s own state and encrypted vault

When Codex reports an incomplete local-project migration, a switch performed
while Codex is closed may additionally restore `threads.project_id` through the
official App Server and update the backed-up desktop migration checkpoint. It
does not copy projects or sessions into per-account homes.

An account-usage query may persist an officially refreshed credential generation
back to the encrypted vault. If the queried profile is active, the same
generation is safely reconciled into `$CODEX_HOME/auth.json`; no account selection
Expand All @@ -213,8 +231,8 @@ session into the shared `CODEX_HOME`.

Initialization may make a one-time, backed-up change to
`$CODEX_HOME/config.toml` to set `cli_auth_credentials_store = "file"`.
`codex-switch` does not rewrite session history or Codex configuration during a
switch.
`codex-switch` does not rewrite rollout/session history or Codex configuration
during a switch.

## Documentation

Expand Down
24 changes: 24 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@
refresh generations, and coordinates with switching through the same lock.
- `usagecache` stores credential-free successful snapshots separately from the
encrypted vault.
- `projectstate` detects the desktop's legacy-to-App-Server project migration,
restores canonical thread assignments through the official experimental App
Server API, and advances the desktop checkpoint only after every assignment
is confirmed.
- `atomicfile` publishes complete files and refuses symlink destinations.
- `doctor` reports only redacted, non-secret local facts.

Expand All @@ -56,6 +60,26 @@ The journal contains only profile IDs, hashes, and timestamps. If the process
stops after replacement but before state persistence, recovery compares the live
file with both hashes and completes the state transition.

## Local project compatibility repair

```text
acquire shared operation lock
-> read the desktop legacy project and thread-assignment maps
-> resolve legacy project IDs to App Server project IDs
-> require Codex to be closed
-> initialize App Server with experimental API capability
-> validate every target with project/list
-> apply and confirm thread/metadata/update(projectId) idempotently
-> back up .codex-global-state.json
-> mark thread assignment migration complete and clear its pending queue
```

The existing legacy assignment map remains intact because current desktop
releases still use it for sidebar ordering and reconciliation. A failed or
interrupted run does not advance the checkpoint, so the repair can safely be
retried. `--allow-running` is an expert recovery override because an open
desktop process can overwrite its state file from memory.

## Live-state reconciliation

```text
Expand Down
7 changes: 7 additions & 0 deletions docs/compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@ Usage querying initializes `codex app-server` and calls:
- `account/rateLimits/read`
- `account/usage/read`

Project migration repair was added for Codex CLI `0.167.0`. It negotiates the
App Server's `experimentalApi` capability and uses `project/list` plus
`thread/metadata/update` with `projectId`. Older clients are unaffected unless
their desktop state explicitly reports a pending App Server project migration;
in that case the command fails with an update hint instead of editing SQLite
directly.

`account wake` additionally requires the installed CLI's non-interactive
`codex exec` mode and its `--ephemeral`, `--ignore-user-config`,
`--ignore-rules`, and read-only sandbox options. The wake turn uses the CLI's
Expand Down
24 changes: 24 additions & 0 deletions docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,30 @@ credential after replacement.
`--allow-running` exists for recovery and expert use. It is not recommended for
ordinary switching.

## Projects are empty or change after switching accounts

Recent Codex releases store projects and thread-to-project membership
separately. A desktop migration can create the projects successfully while
leaving every canonical thread `projectId` empty. Inspect the redacted status:

```bash
codex-switch project status
codex-switch doctor
```

If repair is needed, fully quit Codex/ChatGPT and run:

```bash
codex-switch project repair
```

The repair uses Codex App Server rather than editing its SQLite database. It
keeps the desktop's legacy project map, verifies the new project IDs, applies
each assignment idempotently, and backs up `.codex-global-state.json` before
advancing the migration checkpoint. Use `--force` to reapply all retained
assignments after a later Codex regression. Avoid `--allow-running` unless the
desktop cannot be stopped; its in-memory state may overwrite the repair.

## Active account is unmanaged

Inspect it and preserve it before switching:
Expand Down
124 changes: 123 additions & 1 deletion internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import (
appconfig "github.com/SilkageNet/codex-switch/internal/config"
"github.com/SilkageNet/codex-switch/internal/doctor"
"github.com/SilkageNet/codex-switch/internal/launcher"
"github.com/SilkageNet/codex-switch/internal/process"
"github.com/SilkageNet/codex-switch/internal/projectstate"
"github.com/SilkageNet/codex-switch/internal/secretstore"
appstate "github.com/SilkageNet/codex-switch/internal/state"
"github.com/SilkageNet/codex-switch/internal/switcher"
Expand Down Expand Up @@ -106,6 +108,7 @@ func NewCommand(version string) *cobra.Command {
newStatusCommand(options),
newSyncCommand(options),
newDoctorCommand(options),
newProjectCommand(options),
newUseCommand(options),
newDeactivateCommand(options),
newSelectCommand(options),
Expand Down Expand Up @@ -629,6 +632,28 @@ func newUseCommand(options *Options) *cobra.Command {
if err != nil {
return err
}
var projectRepair *projectstate.Result
var projectWarning string
inspection, inspectErr := runtime.projectService(options.Version).Inspect()
if inspectErr != nil {
projectWarning = "Project migration status could not be inspected: " + inspectErr.Error()
} else if inspection.NeedsRepair {
running, detectErr := process.DetectCodex()
switch {
case detectErr != nil:
projectWarning = "Project assignment migration is pending; run 'codex-switch project repair' after closing Codex."
case allowRunning || len(running) > 0:
projectWarning = "Project assignment migration is pending; run 'codex-switch project repair' after closing Codex."
default:
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
repaired, repairErr := runtime.projectService(options.Version).Repair(ctx, false, false)
cancel()
if repairErr != nil {
return fmt.Errorf("account switched to %s but project assignment migration failed: %w", result.Alias, repairErr)
}
projectRepair = &repaired
}
}
if launch {
if err := launcher.Codex(); err != nil {
return fmt.Errorf("account switched but Codex could not be launched: %w", err)
Expand All @@ -641,14 +666,93 @@ func newUseCommand(options *Options) *cobra.Command {
message = fmt.Sprintf("Account %s is already active. Reconciled changes made outside codex-switch; no restart is required.", result.Alias)
}
}
return options.render(result, message)
if projectRepair != nil && projectRepair.Repaired {
message += fmt.Sprintf(" Repaired %d local project assignment(s).", projectRepair.AssignmentsRepaired)
}
if projectWarning != "" {
message += "\nWarning: " + projectWarning
}
view := struct {
switcher.Result
ProjectMigration *projectstate.Result `json:"projectMigration,omitempty"`
Warning string `json:"warning,omitempty"`
}{Result: result, ProjectMigration: projectRepair, Warning: projectWarning}
return options.render(view, message)
},
}
command.Flags().BoolVar(&allowRunning, "allow-running", false, "switch even when a Codex process is detected")
command.Flags().BoolVar(&launch, "launch", false, "launch Codex after switching")
return command
}

func newProjectCommand(options *Options) *cobra.Command {
command := &cobra.Command{Use: "project", Aliases: []string{"projects"}, Short: "Inspect and repair shared local project state"}
command.AddCommand(newProjectStatusCommand(options), newProjectRepairCommand(options))
return command
}

func newProjectStatusCommand(options *Options) *cobra.Command {
return &cobra.Command{
Use: "status",
Short: "Inspect Codex project assignment migration",
RunE: func(*cobra.Command, []string) error {
runtime, err := options.loadProjectRuntime()
if err != nil {
return err
}
inspection, err := runtime.projectService(options.Version).Inspect()
if err != nil {
return err
}
message := formatProjectInspection(inspection)
return options.render(inspection, message)
},
}
}

func newProjectRepairCommand(options *Options) *cobra.Command {
var allowRunning bool
var force bool
command := &cobra.Command{
Use: "repair",
Short: "Reconcile legacy project assignments through Codex App Server",
RunE: func(*cobra.Command, []string) error {
runtime, err := options.loadProjectRuntime()
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
result, err := runtime.projectService(options.Version).Repair(ctx, allowRunning, force)
if err != nil {
return err
}
message := "Project assignments are already consistent."
if result.Repaired {
message = fmt.Sprintf("Repaired %d local project assignment(s). Backup: %s", result.AssignmentsRepaired, result.Backup)
}
return options.render(result, message)
},
}
command.Flags().BoolVar(&allowRunning, "allow-running", false, "repair while Codex is running (may be overwritten by the desktop app)")
command.Flags().BoolVar(&force, "force", false, "reapply every resolvable legacy project assignment")
return command
}

func formatProjectInspection(inspection projectstate.Inspection) string {
if !inspection.Available {
return "Codex has no local app-server project migration state for this CODEX_HOME."
}
status := "complete"
if inspection.NeedsRepair {
status = "repair needed"
} else if !inspection.ThreadAssignmentsMigrated {
status = "not applicable"
}
return fmt.Sprintf("Projects: %d\nAssignments: %d (%d resolvable, %d pending)\nMigration: %s",
inspection.Projects, inspection.LegacyAssignments, inspection.ResolvableAssignments, inspection.PendingAssignments, status)
}

func newDeactivateCommand(options *Options) *cobra.Command {
var allowRunning bool
command := &cobra.Command{
Expand Down Expand Up @@ -1029,10 +1133,28 @@ func (options *Options) loadRuntimeForDoctor() (runtimeState, error) {
return runtimeState{home: home, paths: paths, manager: vault.New(paths.Vault, store), bin: bin, binErr: binErr}, nil
}

func (options *Options) loadProjectRuntime() (runtimeState, error) {
home, err := codexhome.Resolve(options.CodexHome)
if err != nil {
return runtimeState{}, err
}
bin, binErr := codexlogin.FindBinary(options.CodexBin)
return runtimeState{home: home, bin: bin, binErr: binErr}, nil
}

func (runtime runtimeState) switcher() switcher.Service {
return switcher.Service{Home: runtime.home, Paths: runtime.paths, Vault: runtime.manager}
}

func (runtime runtimeState) projectService(version string) projectstate.Service {
return projectstate.Service{
Home: runtime.home,
Binary: runtime.bin,
BinaryError: runtime.binErr,
ClientVersion: version,
}
}

func (runtime runtimeState) usageService(version string) accountusage.Service {
return accountusage.Service{
Home: runtime.home,
Expand Down
11 changes: 11 additions & 0 deletions internal/doctor/doctor.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/SilkageNet/codex-switch/internal/codexlogin"
appconfig "github.com/SilkageNet/codex-switch/internal/config"
"github.com/SilkageNet/codex-switch/internal/process"
"github.com/SilkageNet/codex-switch/internal/projectstate"
"github.com/SilkageNet/codex-switch/internal/switcher"
"github.com/SilkageNet/codex-switch/internal/vault"
)
Expand Down Expand Up @@ -43,6 +44,16 @@ func Run(home codexhome.Home, paths appconfig.Paths, manager *vault.Manager, cod
add("codex_home", "error", fmt.Sprintf("cannot inspect %s: %v", home.Path, err))
}

if inspection, err := (projectstate.Service{Home: home}).Inspect(); err != nil {
add("project_assignments", "warning", err.Error())
} else if !inspection.Available {
add("project_assignments", "ok", "no local app-server migration state")
} else if inspection.NeedsRepair {
add("project_assignments", "warning", fmt.Sprintf("%d assignment(s) pending; run codex-switch project repair after closing Codex", inspection.PendingAssignments))
} else {
add("project_assignments", "ok", fmt.Sprintf("%d assignment(s), migration complete", inspection.ResolvableAssignments))
}

if mode, err := home.CredentialStore(); err != nil {
add("credential_store", "error", err.Error())
} else if mode != codexhome.StoreFile {
Expand Down
Loading
Loading