From 8e4b12508a5d25f1418fb83289372b828404bcca Mon Sep 17 00:00:00 2001 From: Silkage Date: Mon, 9 Nov 2026 12:09:24 +0800 Subject: [PATCH] fix: keep local projects visible across account switches --- README.md | 22 +- docs/architecture.md | 9 +- docs/compatibility.md | 6 +- docs/troubleshooting.md | 24 +- internal/app/app.go | 40 ++- internal/config/paths.go | 22 +- internal/projectstate/projectstate.go | 276 ++++++++++++++++++++- internal/projectstate/projectstate_test.go | 102 ++++++++ 8 files changed, 447 insertions(+), 54 deletions(-) diff --git a/README.md b/README.md index 4f17544..b3d612b 100644 --- a/README.md +++ b/README.md @@ -200,12 +200,13 @@ 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. +the App Server state database while the desktop still consumes a local project +catalog during startup. `codex-switch` keeps a credential-free shared catalog +under `CODEX_SWITCH_HOME`. A normal `use` captures that catalog when it is +healthy and restores it when an account change removes the desktop projection; +it then reconciles any pending legacy IDs through the official App Server +protocol. No separate `project repair` is required in the normal closed-app +switch flow. Every desktop-state change is backed up before replacement. ## What a switch changes @@ -214,10 +215,11 @@ 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. +When Codex reports an incomplete or missing local-project projection, a switch +performed while Codex is closed may additionally restore the credential-free +desktop project catalog, 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 diff --git a/docs/architecture.md b/docs/architecture.md index ce44b58..3e8f00f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -31,10 +31,11 @@ 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. +- `projectstate` maintains a credential-free shared local-project catalog, + restores a missing desktop projection after account changes, reconciles + 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. diff --git a/docs/compatibility.md b/docs/compatibility.md index e72d45e..38f03b7 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -69,8 +69,10 @@ 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 +Project migration repair was added for Codex CLI `0.167.0`. It preserves the +desktop's credential-free project projection independently of the active +account. When canonical assignments also need repair, 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 diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index dfb5066..af7bf48 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -55,27 +55,31 @@ 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: +Recent Codex releases store the desktop project catalog and canonical +thread-to-project membership separately. An account change can leave the +canonical projects intact while removing the desktop projection, or a migration +can leave 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: +Normal `codex-switch account use ` repairs both states automatically when +Codex is closed. If a prior manual login already caused drift, fully quit +Codex/ChatGPT and run once: ```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. +The repair restores the desktop projection from the shared catalog (or the most +recent codex-switch backup), then uses Codex App Server rather than editing its +SQLite database. It verifies the new project IDs, applies each assignment +idempotently, and backs up `.codex-global-state.json` before every replacement. +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 diff --git a/internal/app/app.go b/internal/app/app.go index 1683681..88ca351 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -637,13 +637,17 @@ func newUseCommand(options *Options) *cobra.Command { inspection, inspectErr := runtime.projectService(options.Version).Inspect() if inspectErr != nil { projectWarning = "Project migration status could not be inspected: " + inspectErr.Error() - } else if inspection.NeedsRepair { + } else { running, detectErr := process.DetectCodex() switch { case detectErr != nil: - projectWarning = "Project assignment migration is pending; run 'codex-switch project repair' after closing Codex." + if inspection.NeedsRepair { + projectWarning = "Shared project state needs repair; 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." + if inspection.NeedsRepair { + projectWarning = "Shared project state needs repair; 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) @@ -667,7 +671,12 @@ func newUseCommand(options *Options) *cobra.Command { } } if projectRepair != nil && projectRepair.Repaired { - message += fmt.Sprintf(" Repaired %d local project assignment(s).", projectRepair.AssignmentsRepaired) + if projectRepair.ProjectionRestored { + message += fmt.Sprintf(" Restored %d shared local project(s).", projectRepair.Projects) + } + if projectRepair.AssignmentsRepaired > 0 { + message += fmt.Sprintf(" Repaired %d local project assignment(s).", projectRepair.AssignmentsRepaired) + } } if projectWarning != "" { message += "\nWarning: " + projectWarning @@ -727,9 +736,11 @@ func newProjectRepairCommand(options *Options) *cobra.Command { if err != nil { return err } - message := "Project assignments are already consistent." + message := "Shared project state is already consistent." if result.Repaired { - message = fmt.Sprintf("Repaired %d local project assignment(s). Backup: %s", result.AssignmentsRepaired, result.Backup) + message = fmt.Sprintf("Restored %d shared local project(s) and repaired %d assignment(s). Backup: %s", result.Projects, result.AssignmentsRepaired, result.Backup) + } else if result.CatalogUpdated { + message = fmt.Sprintf("Saved %d shared local project(s) for future account switches.", result.Projects) } return options.render(result, message) }, @@ -749,8 +760,14 @@ func formatProjectInspection(inspection projectstate.Inspection) string { } 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) + projection := "present" + if inspection.ProjectionMissing { + projection = "missing (recoverable)" + } + return fmt.Sprintf("Projects: %d shared (%d desktop, %d saved)\nAssignments: %d shared (%d desktop, %d saved; %d resolvable, %d pending)\nDesktop projection: %s\nMigration: %s", + inspection.Projects, inspection.DesktopProjects, inspection.CatalogProjects, + inspection.LegacyAssignments, inspection.DesktopAssignments, inspection.CatalogAssignments, + inspection.ResolvableAssignments, inspection.PendingAssignments, projection, status) } func newDeactivateCommand(options *Options) *cobra.Command { @@ -1138,8 +1155,12 @@ func (options *Options) loadProjectRuntime() (runtimeState, error) { if err != nil { return runtimeState{}, err } + paths, err := appconfig.ResolvePaths(options.AppHome) + if err != nil { + return runtimeState{}, err + } bin, binErr := codexlogin.FindBinary(options.CodexBin) - return runtimeState{home: home, bin: bin, binErr: binErr}, nil + return runtimeState{home: home, paths: paths, bin: bin, binErr: binErr}, nil } func (runtime runtimeState) switcher() switcher.Service { @@ -1152,6 +1173,7 @@ func (runtime runtimeState) projectService(version string) projectstate.Service Binary: runtime.bin, BinaryError: runtime.binErr, ClientVersion: version, + CatalogPath: runtime.paths.ProjectCatalog, } } diff --git a/internal/config/paths.go b/internal/config/paths.go index 35fbd42..5a753d3 100644 --- a/internal/config/paths.go +++ b/internal/config/paths.go @@ -7,11 +7,12 @@ import ( ) type Paths struct { - Root string - Vault string - State string - Journal string - UsageCache string + Root string + Vault string + State string + Journal string + UsageCache string + ProjectCatalog string } func ResolvePaths(override string) (Paths, error) { @@ -31,11 +32,12 @@ func ResolvePaths(override string) (Paths, error) { return Paths{}, fmt.Errorf("resolve codex-switch home: %w", err) } return Paths{ - Root: abs, - Vault: filepath.Join(abs, "vault.v1.enc"), - State: filepath.Join(abs, "state.json"), - Journal: filepath.Join(abs, "switch.journal.json"), - UsageCache: filepath.Join(abs, "usage-cache.v1.json"), + Root: abs, + Vault: filepath.Join(abs, "vault.v1.enc"), + State: filepath.Join(abs, "state.json"), + Journal: filepath.Join(abs, "switch.journal.json"), + UsageCache: filepath.Join(abs, "usage-cache.v1.json"), + ProjectCatalog: filepath.Join(abs, "project-catalog.v1.json"), }, nil } diff --git a/internal/projectstate/projectstate.go b/internal/projectstate/projectstate.go index ad31d31..1164521 100644 --- a/internal/projectstate/projectstate.go +++ b/internal/projectstate/projectstate.go @@ -25,24 +25,43 @@ import ( const ( globalStateName = ".codex-global-state.json" maxGlobalStateSize = 32 << 20 + maxCatalogSize = 32 << 20 maxProtocolMessage = 8 << 20 + catalogVersion = 1 ) +var projectionKeys = []string{ + "local-projects", + "project-order", + "project-appearances", + "thread-project-assignments", + "thread-project-membership-host-ids", + "app-server-project-id-by-legacy-project-id-by-host", + "app-server-projects-migration-by-host", +} + type Inspection struct { Available bool `json:"available"` HostKey string `json:"hostKey,omitempty"` Projects int `json:"projects"` + DesktopProjects int `json:"desktopProjects"` + CatalogProjects int `json:"catalogProjects"` LegacyAssignments int `json:"legacyAssignments"` + DesktopAssignments int `json:"desktopAssignments"` + CatalogAssignments int `json:"catalogAssignments"` ResolvableAssignments int `json:"resolvableAssignments"` PendingAssignments int `json:"pendingAssignments"` ProjectsMigrated bool `json:"projectsMigrated"` ThreadAssignmentsMigrated bool `json:"threadAssignmentsMigrated"` + ProjectionMissing bool `json:"projectionMissing"` NeedsRepair bool `json:"needsRepair"` } type Result struct { Inspection Repaired bool `json:"repaired"` + ProjectionRestored bool `json:"projectionRestored"` + CatalogUpdated bool `json:"catalogUpdated"` AssignmentsRepaired int `json:"assignmentsRepaired"` Backup string `json:"backup,omitempty"` } @@ -52,9 +71,25 @@ type Service struct { Binary string BinaryError error ClientVersion string + CatalogPath string Runner *Runner } +type catalog struct { + Version int `json:"version"` + CapturedAt time.Time `json:"capturedAt"` + CodexHome string `json:"codexHome"` + Fields map[string]json.RawMessage `json:"fields"` +} + +type projection struct { + fields map[string]json.RawMessage + projects int + assignments int + resolvable int + source string +} + type assignment struct { ProjectKind string `json:"projectKind"` ProjectID string `json:"projectId"` @@ -89,11 +124,34 @@ func (service Service) Inspect() (Inspection, error) { document, err := load(service.Home.Path) if err != nil { if errors.Is(err, os.ErrNotExist) { - return Inspection{}, nil + return service.inspectRecovery(Inspection{HostKey: "local:" + service.Home.Path}) } return Inspection{}, err } - return document.inspection, nil + return service.inspectRecovery(document.inspection) +} + +func (service Service) inspectRecovery(inspection Inspection) (Inspection, error) { + inspection.DesktopProjects = inspection.Projects + inspection.DesktopAssignments = inspection.LegacyAssignments + recovered, err := service.findProjection() + if err != nil { + return Inspection{}, err + } + if recovered.projects == 0 { + return inspection, nil + } + inspection.Available = true + inspection.CatalogProjects = recovered.projects + inspection.CatalogAssignments = recovered.assignments + if inspection.DesktopProjects == 0 { + inspection.Projects = recovered.projects + inspection.LegacyAssignments = recovered.assignments + inspection.ResolvableAssignments = recovered.resolvable + inspection.ProjectionMissing = true + inspection.NeedsRepair = true + } + return inspection, nil } func (service Service) Repair(ctx context.Context, allowRunning, force bool) (Result, error) { @@ -106,16 +164,23 @@ func (service Service) Repair(ctx context.Context, allowRunning, force bool) (Re document, err := load(service.Home.Path) if err != nil { if errors.Is(err, os.ErrNotExist) { - return Result{}, nil + return Result{}, errors.New("codex desktop state does not exist yet; launch Codex once before restoring projects") } return Result{}, err } - result := Result{Inspection: document.inspection} - if !force && !document.inspection.NeedsRepair { - return result, nil + inspection, err := service.inspectRecovery(document.inspection) + if err != nil { + return Result{}, err } - if len(document.resolved) == 0 { - return result, errors.New("no resolvable local project assignments were found") + result := Result{Inspection: inspection} + if !force && !inspection.NeedsRepair { + if service.CatalogPath != "" && document.inspection.Projects > 0 { + if err := service.saveCatalog(document); err != nil { + return result, err + } + result.CatalogUpdated = true + } + return result, nil } if !allowRunning { running, detectErr := process.DetectCodex() @@ -126,6 +191,40 @@ func (service Service) Repair(ctx context.Context, allowRunning, force bool) (Re return result, fmt.Errorf("codex is still running (PID %d, %s); close it before repairing project assignments or explicitly pass --allow-running", running[0].PID, running[0].Command) } } + if inspection.ProjectionMissing { + recovered, recoveryErr := service.findProjection() + if recoveryErr != nil { + return result, recoveryErr + } + if recovered.projects == 0 { + return result, errors.New("the desktop project catalog is missing and no codex-switch snapshot or backup can restore it") + } + backup, restoreErr := document.restoreProjection(recovered) + if restoreErr != nil { + return result, restoreErr + } + result.Repaired = true + result.ProjectionRestored = true + result.Backup = backup + document, err = load(service.Home.Path) + if err != nil { + return result, err + } + } + if service.CatalogPath != "" && document.inspection.Projects > 0 { + if err := service.saveCatalog(document); err != nil { + return result, err + } + result.CatalogUpdated = true + } + if !force && !document.inspection.NeedsRepair { + result.Inspection = document.inspection + result.NeedsRepair = false + return result, nil + } + if len(document.resolved) == 0 { + return result, errors.New("no resolvable local project assignments were found") + } if service.BinaryError != nil { return result, service.BinaryError } @@ -146,7 +245,14 @@ func (service Service) Repair(ctx context.Context, allowRunning, force bool) (Re } result.Repaired = true result.AssignmentsRepaired = len(document.resolved) - result.Backup = backup + if result.Backup == "" { + result.Backup = backup + } + result.Inspection = document.inspection + result.DesktopProjects = len(document.projects) + result.Projects = len(document.projects) + result.DesktopAssignments = len(document.assignments) + result.LegacyAssignments = len(document.assignments) result.ThreadAssignmentsMigrated = true result.PendingAssignments = 0 result.NeedsRepair = false @@ -208,7 +314,9 @@ func load(home string) (document, error) { Available: available, HostKey: hostKey, Projects: len(projects), + DesktopProjects: len(projects), LegacyAssignments: len(assignments), + DesktopAssignments: len(assignments), ResolvableAssignments: len(resolved), PendingAssignments: len(migrationState.PendingThreadAssignmentIDs), ProjectsMigrated: migrationState.ProjectsMigrated, @@ -229,6 +337,156 @@ func load(home string) (document, error) { }, nil } +func (service Service) findProjection() (projection, error) { + if service.CatalogPath != "" { + data, err := atomicfile.ReadLimited(service.CatalogPath, maxCatalogSize) + if err == nil { + var saved catalog + if decodeErr := json.Unmarshal(data, &saved); decodeErr != nil { + return projection{}, fmt.Errorf("decode shared project catalog: %w", decodeErr) + } + if saved.Version != catalogVersion { + return projection{}, fmt.Errorf("unsupported shared project catalog version %d", saved.Version) + } + if saved.CodexHome == service.Home.Path { + result, decodeErr := projectionFromFields(saved.Fields, service.CatalogPath) + if decodeErr != nil { + return projection{}, decodeErr + } + if result.projects > 0 { + return result, nil + } + } + } else if !errors.Is(err, os.ErrNotExist) { + return projection{}, fmt.Errorf("read shared project catalog: %w", err) + } + } + + pattern := filepath.Join(service.Home.Path, globalStateName+".codex-switch.bak.*") + backups, err := filepath.Glob(pattern) + if err != nil { + return projection{}, fmt.Errorf("find Codex project backups: %w", err) + } + sort.Sort(sort.Reverse(sort.StringSlice(backups))) + for _, backup := range backups { + data, readErr := atomicfile.ReadLimited(backup, maxGlobalStateSize) + if readErr != nil { + continue + } + var raw map[string]json.RawMessage + if decodeErr := json.Unmarshal(data, &raw); decodeErr != nil { + continue + } + result, decodeErr := projectionFromFields(raw, backup) + if decodeErr == nil && result.projects > 0 { + return result, nil + } + } + return projection{}, nil +} + +func projectionFromFields(source map[string]json.RawMessage, name string) (projection, error) { + fields := make(map[string]json.RawMessage, len(projectionKeys)) + for _, key := range projectionKeys { + if value := source[key]; len(value) > 0 { + fields[key] = append(json.RawMessage(nil), value...) + } + } + var projects map[string]json.RawMessage + if value := fields["local-projects"]; len(value) > 0 { + if err := json.Unmarshal(value, &projects); err != nil { + return projection{}, fmt.Errorf("decode local projects from %s: %w", name, err) + } + } + var assignments map[string]assignment + if value := fields["thread-project-assignments"]; len(value) > 0 { + if err := json.Unmarshal(value, &assignments); err != nil { + return projection{}, fmt.Errorf("decode project assignments from %s: %w", name, err) + } + } + var mappings map[string]map[string]string + if value := fields["app-server-project-id-by-legacy-project-id-by-host"]; len(value) > 0 { + if err := json.Unmarshal(value, &mappings); err != nil { + return projection{}, fmt.Errorf("decode project ID mappings from %s: %w", name, err) + } + } + mapped := map[string]bool{} + for _, byLegacyID := range mappings { + for legacyID, serverID := range byLegacyID { + if legacyID != "" && serverID != "" { + mapped[legacyID] = true + } + } + } + resolvable := 0 + for threadID, item := range assignments { + if threadID != "" && item.ProjectKind == "local" && mapped[item.ProjectID] { + resolvable++ + } + } + return projection{fields: fields, projects: len(projects), assignments: len(assignments), resolvable: resolvable, source: name}, nil +} + +func (service Service) saveCatalog(document document) error { + fields := make(map[string]json.RawMessage, len(projectionKeys)) + for _, key := range projectionKeys { + if value := document.raw[key]; len(value) > 0 { + fields[key] = append(json.RawMessage(nil), value...) + } + } + saved := catalog{ + Version: catalogVersion, + CapturedAt: time.Now().UTC(), + CodexHome: service.Home.Path, + Fields: fields, + } + data, err := json.MarshalIndent(saved, "", " ") + if err != nil { + return fmt.Errorf("encode shared project catalog: %w", err) + } + data = append(data, '\n') + if err := atomicfile.Write(service.CatalogPath, data, 0o600); err != nil { + return fmt.Errorf("save shared project catalog: %w", err) + } + return nil +} + +func (document *document) restoreProjection(recovered projection) (string, error) { + if recovered.projects == 0 { + return "", errors.New("project recovery source is empty") + } + for _, key := range projectionKeys { + value := recovered.fields[key] + if len(value) == 0 { + continue + } + if key == "app-server-projects-migration-by-host" && len(document.raw[key]) > 0 { + continue + } + document.raw[key] = append(json.RawMessage(nil), value...) + } + output, err := json.Marshal(document.raw) + if err != nil { + return "", err + } + output = append(output, '\n') + original, err := atomicfile.ReadLimited(document.statePath, maxGlobalStateSize) + if err != nil { + return "", err + } + if atomicfile.Hash(original) != document.originalHash { + return "", errors.New("codex global state changed while restoring the project catalog; close Codex and retry") + } + backup := fmt.Sprintf("%s.codex-switch.bak.%s", document.statePath, time.Now().UTC().Format("20060102T150405.000000000Z")) + if err := atomicfile.Write(backup, original, 0o600); err != nil { + return "", fmt.Errorf("back up global state: %w", err) + } + if err := atomicfile.Write(document.statePath, output, 0o600); err != nil { + return "", fmt.Errorf("restore desktop project catalog from %s: %w", recovered.source, err) + } + return backup, nil +} + func (document *document) markMigrated() (string, error) { migrationState, ok := document.migrations[document.hostKey] if !ok { diff --git a/internal/projectstate/projectstate_test.go b/internal/projectstate/projectstate_test.go index 6a692ef..74b279e 100644 --- a/internal/projectstate/projectstate_test.go +++ b/internal/projectstate/projectstate_test.go @@ -101,6 +101,83 @@ func TestRepairIsNoopAfterMigration(t *testing.T) { } } +func TestRepairRestoresDesktopProjectionFromSharedCatalog(t *testing.T) { + homePath := t.TempDir() + appPath := t.TempDir() + writeGlobalState(t, homePath) + document, err := load(homePath) + if err != nil { + t.Fatal(err) + } + if _, err := document.markMigrated(); err != nil { + t.Fatal(err) + } + service := Service{ + Home: codexhome.Home{Path: homePath}, + CatalogPath: filepath.Join(appPath, "project-catalog.v1.json"), + } + result, err := service.Repair(context.Background(), true, false) + if err != nil { + t.Fatal(err) + } + if !result.CatalogUpdated { + t.Fatalf("shared catalog was not captured: %#v", result) + } + removeProjection(t, homePath) + + inspection, err := service.Inspect() + if err != nil { + t.Fatal(err) + } + if !inspection.ProjectionMissing || !inspection.NeedsRepair || inspection.Projects != 1 || inspection.DesktopProjects != 0 || inspection.CatalogProjects != 1 { + t.Fatalf("missing projection was not detected: %#v", inspection) + } + result, err = service.Repair(context.Background(), true, false) + if err != nil { + t.Fatal(err) + } + if !result.Repaired || !result.ProjectionRestored || result.AssignmentsRepaired != 0 { + t.Fatalf("projection was not restored: %#v", result) + } + after, err := service.Inspect() + if err != nil { + t.Fatal(err) + } + if after.ProjectionMissing || after.DesktopProjects != 1 || after.DesktopAssignments != 2 { + t.Fatalf("restored projection is incomplete: %#v", after) + } +} + +func TestRepairRecoversProjectionFromTimestampedBackup(t *testing.T) { + homePath := t.TempDir() + writeGlobalState(t, homePath) + document, err := load(homePath) + if err != nil { + t.Fatal(err) + } + if _, err := document.markMigrated(); err != nil { + t.Fatal(err) + } + statePath := filepath.Join(homePath, globalStateName) + healthy, err := os.ReadFile(statePath) + if err != nil { + t.Fatal(err) + } + if err := atomicfile.Write(statePath+".codex-switch.bak.99999999T999999.000000000Z", healthy, 0o600); err != nil { + t.Fatal(err) + } + removeProjection(t, homePath) + + service := Service{Home: codexhome.Home{Path: homePath}, CatalogPath: filepath.Join(t.TempDir(), "project-catalog.v1.json")} + result, err := service.Repair(context.Background(), true, false) + if err != nil { + t.Fatal(err) + } + if !result.ProjectionRestored || !result.CatalogUpdated || result.Projects != 1 { + t.Fatalf("backup recovery failed: %#v", result) + } +} + func TestProjectStateHelperProcess(t *testing.T) { if os.Getenv("GO_WANT_PROJECT_STATE_HELPER") != "1" { return @@ -177,3 +254,28 @@ func writeGlobalState(t *testing.T, homePath string) { t.Fatal(fmt.Errorf("write test global state: %w", err)) } } + +func removeProjection(t *testing.T, homePath string) { + t.Helper() + statePath := filepath.Join(homePath, globalStateName) + data, err := os.ReadFile(statePath) + if err != nil { + t.Fatal(err) + } + var raw map[string]json.RawMessage + if err := json.Unmarshal(data, &raw); err != nil { + t.Fatal(err) + } + for _, key := range projectionKeys { + if key != "app-server-projects-migration-by-host" { + delete(raw, key) + } + } + data, err = json.Marshal(raw) + if err != nil { + t.Fatal(err) + } + if err := atomicfile.Write(statePath, append(data, '\n'), 0o600); err != nil { + t.Fatal(err) + } +}