Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-4874: fix(execenv): seed Codex model cache in task homes (#5449)
Wangjue Yao5664c0d7551e
diff --git a/server/internal/daemon/execenv/codex_home.go b/server/internal/daemon/execenv/codex_home.goindex 6879fd0eab..00edd875b7 100644--- a/server/internal/daemon/execenv/codex_home.go+++ b/server/internal/daemon/execenv/codex_home.go@@ -21,13 +21,28 @@ var codexSymlinkedFiles = []string{}// Files to copy from the shared ~/.codex/ into the per-task CODEX_HOME.-// Copies are isolated — changes don't affect the shared home.+// Copies are isolated — task-local config and cache refreshes don't mutate+// the shared home.var codexCopiedFiles = []string{"config.json","config.toml","instructions.md",}+const (+ codexModelsCacheFile = "models_cache.json"+ codexModelsCacheBindingFile = ".models_cache_config.sha256"+)++// Files whose contents select the model provider/catalog used by Codex. The+// task-local models cache is only reusable while this source configuration+// remains unchanged. A model_catalog_json referenced by config.toml is folded+// into the binding separately by codexModelsCacheConfigFingerprint.+var codexModelsCacheConfigFiles = []string{+ "config.json",+ "config.toml",+}+// CodexHomeOptions carries optional inputs for prepareCodexHomeWithOpts that// affect the generated per-task config.toml.type CodexHomeOptions struct {@@ -84,6 +99,10 @@ func prepareCodexHome(codexHome string, logger *slog.Logger) error {// daemon-managed sandbox block picked by codexSandboxPolicyFor.func prepareCodexHomeWithOpts(codexHome string, opts CodexHomeOptions, logger *slog.Logger) error {sharedHome := resolveSharedCodexHome()+ freshHome := false+ if _, err := os.Lstat(codexHome); os.IsNotExist(err) {+ freshHome = true+ }if err := os.MkdirAll(codexHome, 0o755); err != nil {return fmt.Errorf("create codex-home dir: %w", err)@@ -111,7 +130,7 @@ func prepareCodexHomeWithOpts(codexHome string, opts CodexHomeOptions, logger *s// into a stale local copy.logCodexAuthState(filepath.Join(codexHome, "auth.json"), logger)- // Sync config files from the shared source (isolated per task).+ // Sync isolated files from the shared source.for _, name := range codexCopiedFiles {src := filepath.Join(sharedHome, name)dst := filepath.Join(codexHome, name)@@ -119,7 +138,6 @@ func prepareCodexHomeWithOpts(codexHome string, opts CodexHomeOptions, logger *slogger.Warn("execenv: codex-home sync failed", "file", name, "error", err)}}-// Drop `[[skills.config]]` entries inherited from the user's// ~/.codex/config.toml. Codex Desktop writes plugin-backed skills with a// `name` and no `path`, which the CLI's stricter TOML parser rejects with@@ -134,6 +152,18 @@ func prepareCodexHomeWithOpts(codexHome string, opts CodexHomeOptions, logger *sreturn fmt.Errorf("sync codex model_catalog_json: %w", err)}+ // Seed the shared model cache only for a fresh task home. On reuse, keep a+ // task-local cache that Codex may have refreshed, but only while the source+ // provider/catalog configuration is still the one that cache was bound to.+ // If binding fails, discard the optional cache so Codex refreshes it instead+ // of potentially using models from the wrong provider.+ if err := syncCodexModelsCache(codexHome, sharedHome, freshHome); err != nil {+ logger.Warn("execenv: codex-home models cache sync failed; discarding cache", "error", err)+ if removeErr := os.RemoveAll(filepath.Join(codexHome, codexModelsCacheFile)); removeErr != nil {+ return fmt.Errorf("sync codex models cache: %v; discard unsafe cache: %w", err, removeErr)+ }+ }+if err := exposeSharedCodexPluginCache(codexHome, sharedHome); err != nil {logger.Warn("execenv: codex-home plugin cache exposure failed", "error", err)}@@ -730,6 +760,162 @@ func syncCodexModelCatalog(codexHome, sharedHome string) error {return nil}+// syncCodexModelsCache seeds models_cache.json once for a fresh task home and+// binds it to the shared provider/catalog configuration. Codex can replace the+// task-local cache after startup, so an unchanged binding preserves whatever+// the task last wrote rather than restoring a potentially stale shared copy.+//+// A changed or missing binding makes an existing cache unsafe: Codex's cache+// format (as of 0.144.x) records the client version and fetch time but not the+// provider identity. Reusing that cache after config.toml switches providers+// can therefore pair provider B with provider A's model catalog. Drop it and+// let Codex fetch a catalog for the new effective configuration. We+// deliberately do not seed the shared cache in this case because it carries+// the same provider-identity ambiguity.+func syncCodexModelsCache(codexHome, sharedHome string, freshHome bool) error {+ fingerprint, err := codexModelsCacheConfigFingerprint(sharedHome)+ if err != nil {+ return err+ }++ bindingPath := filepath.Join(codexHome, codexModelsCacheBindingFile)+ previous, bound, err := readCodexModelsCacheBinding(bindingPath)+ if err != nil {+ return err+ }++ cachePath := filepath.Join(codexHome, codexModelsCacheFile)+ cacheInfo, cacheErr := os.Lstat(cachePath)+ cacheExists := cacheErr == nil+ if cacheErr != nil && !os.IsNotExist(cacheErr) {+ return fmt.Errorf("stat codex models cache %s: %w", cachePath, cacheErr)+ }++ if bound && previous == fingerprint {+ // The cache belongs to the current config. Preserve both an existing+ // task-refreshed cache and an intentional absence after a failed fetch;+ // seeding on reuse could reintroduce an unbound shared snapshot.+ if cacheExists && !cacheInfo.Mode().IsRegular() {+ if err := os.RemoveAll(cachePath); err != nil {+ return fmt.Errorf("remove non-regular codex models cache %s: %w", cachePath, err)+ }+ }+ return nil+ }++ if cacheExists {+ if err := os.RemoveAll(cachePath); err != nil {+ return fmt.Errorf("remove unbound codex models cache %s: %w", cachePath, err)+ }+ }++ if freshHome && !bound && !cacheExists {+ // A shared snapshot is useful on the one path where the task home itself+ // did not exist yet; subsequent task-local refreshes stay isolated. An+ // existing legacy home without a binding never seeds because its prior+ // effective configuration is unknown even when its cache is absent.+ if err := seedCopiedFile(filepath.Join(sharedHome, codexModelsCacheFile), cachePath); err != nil {+ return fmt.Errorf("seed codex models cache: %w", err)+ }+ }++ if err := writeCodexModelsCacheBinding(bindingPath, fingerprint); err != nil {+ return err+ }+ return nil+}++// codexModelsCacheConfigFingerprint hashes the shared config files plus the+// contents of any model_catalog_json they reference. The digest is stored in+// the isolated task home; no config contents or credentials are persisted.+func codexModelsCacheConfigFingerprint(sharedHome string) (string, error) {+ h := sha256.New()+ var configTOML []byte++ for _, name := range codexModelsCacheConfigFiles {+ path := filepath.Join(sharedHome, name)+ data, err := os.ReadFile(path)+ if os.IsNotExist(err) {+ fmt.Fprintf(h, "%s\x00missing\x00", name)+ continue+ }+ if err != nil {+ return "", fmt.Errorf("read codex model cache config %s: %w", path, err)+ }+ fmt.Fprintf(h, "%s\x00%d\x00", name, len(data))+ _, _ = h.Write(data)+ if name == "config.toml" {+ configTOML = data+ }+ }++ if len(configTOML) > 0 {+ var cfg struct {+ ModelCatalogJSON string `toml:"model_catalog_json"`+ }+ if err := toml.Unmarshal(configTOML, &cfg); err != nil {+ return "", fmt.Errorf("parse codex model cache config %s: %w", filepath.Join(sharedHome, "config.toml"), err)+ }+ catalogPath := strings.TrimSpace(cfg.ModelCatalogJSON)+ if catalogPath != "" {+ resolved, err := resolveCodexConfigPath(catalogPath, sharedHome)+ if err != nil {+ return "", err+ }+ data, err := os.ReadFile(resolved)+ if err != nil {+ return "", fmt.Errorf("read model_catalog_json %s: %w", resolved, err)+ }+ fmt.Fprintf(h, "model_catalog_json\x00%d\x00", len(data))+ _, _ = h.Write(data)+ }+ }++ return hex.EncodeToString(h.Sum(nil)), nil+}++// readCodexModelsCacheBinding returns bound=false for a missing or non-regular+// marker. Non-regular paths are removed so a reused task cannot redirect the+// later binding write outside its isolated CODEX_HOME.+func readCodexModelsCacheBinding(path string) (fingerprint string, bound bool, err error) {+ fi, err := os.Lstat(path)+ if os.IsNotExist(err) {+ return "", false, nil+ }+ if err != nil {+ return "", false, fmt.Errorf("stat codex models cache binding %s: %w", path, err)+ }+ if !fi.Mode().IsRegular() {+ if err := os.RemoveAll(path); err != nil {+ return "", false, fmt.Errorf("remove non-regular codex models cache binding %s: %w", path, err)+ }+ return "", false, nil+ }+ data, err := os.ReadFile(path)+ if err != nil {+ return "", false, fmt.Errorf("read codex models cache binding %s: %w", path, err)+ }+ return strings.TrimSpace(string(data)), true, nil+}++func writeCodexModelsCacheBinding(path, fingerprint string) error {+ if err := os.RemoveAll(path); err != nil {+ return fmt.Errorf("remove prior codex models cache binding %s: %w", path, err)+ }+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)+ if err != nil {+ return fmt.Errorf("create codex models cache binding %s: %w", path, err)+ }+ if _, err := io.WriteString(f, fingerprint+"\n"); err != nil {+ _ = f.Close()+ return fmt.Errorf("write codex models cache binding %s: %w", path, err)+ }+ if err := f.Close(); err != nil {+ return fmt.Errorf("close codex models cache binding %s: %w", path, err)+ }+ return nil+}+func resolveCodexConfigPath(configPath, sharedHome string) (string, error) {if filepath.IsAbs(configPath) {return filepath.Clean(configPath), nil@@ -885,6 +1071,31 @@ func syncCopiedFile(src, dst string) error {return copyFile(src, dst)}+// seedCopiedFile copies src only when dst has no task-local regular file.+// Unlike syncCopiedFile, it never overwrites or removes a cache refreshed by a+// prior run. Non-regular destinations are removed defensively so a reused task+// cannot turn the cache path into a link outside its isolated CODEX_HOME.+func seedCopiedFile(src, dst string) error {+ if fi, err := os.Lstat(dst); err == nil {+ if fi.Mode().IsRegular() {+ return nil+ }+ if err := os.RemoveAll(dst); err != nil {+ return fmt.Errorf("remove non-regular dst %s: %w", dst, err)+ }+ } else if !os.IsNotExist(err) {+ return fmt.Errorf("stat dst %s: %w", dst, err)+ }++ if _, err := os.Stat(src); err != nil {+ if os.IsNotExist(err) {+ return nil+ }+ return fmt.Errorf("stat src %s: %w", src, err)+ }+ return copyFile(src, dst)+}+// copyFile copies src to dst unconditionally.func copyFile(src, dst string) error {in, err := os.Open(src)diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex 12473acfb1..abf5a555ab 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -1986,6 +1986,7 @@ func TestPrepareCodexHomeSeedsFromShared(t *testing.T) {os.WriteFile(filepath.Join(sharedHome, "config.json"), []byte(`{"model":"o3"}`), 0o644)os.WriteFile(filepath.Join(sharedHome, "config.toml"), []byte(`model = "o3"`), 0o644)os.WriteFile(filepath.Join(sharedHome, "instructions.md"), []byte("Be helpful."), 0o644)+ os.WriteFile(filepath.Join(sharedHome, "models_cache.json"), []byte(`{"models":["gpt-test"]}`), 0o644)sharedPluginCache := filepath.Join(sharedHome, "plugins", "cache")if err := os.MkdirAll(filepath.Join(sharedPluginCache, "superpowers"), 0o755); err != nil {t.Fatalf("create shared plugin cache: %v", err)@@ -1993,6 +1994,13 @@ func TestPrepareCodexHomeSeedsFromShared(t *testing.T) {if err := os.WriteFile(filepath.Join(sharedPluginCache, "superpowers", "SKILL.md"), []byte("Use superpowers."), 0o644); err != nil {t.Fatalf("write shared plugin skill: %v", err)}+ sharedMarketplace := filepath.Join(sharedHome, ".tmp", "marketplaces", "test-marketplace")+ if err := os.MkdirAll(sharedMarketplace, 0o755); err != nil {+ t.Fatalf("create shared marketplace cache: %v", err)+ }+ if err := os.WriteFile(filepath.Join(sharedMarketplace, "manifest.json"), []byte(`{"name":"test"}`), 0o644); err != nil {+ t.Fatalf("write shared marketplace manifest: %v", err)+ }// Point CODEX_HOME to our fake shared home.t.Setenv("CODEX_HOME", sharedHome)@@ -2068,6 +2076,21 @@ func TestPrepareCodexHomeSeedsFromShared(t *testing.T) {t.Errorf("instructions.md content = %q", data)}+ // models_cache.json is a task-local snapshot so Codex can skip a cold model+ // catalog refresh without letting a task mutate the user's shared cache.+ modelsCachePath := filepath.Join(codexHome, "models_cache.json")+ fi, err = os.Lstat(modelsCachePath)+ if err != nil {+ t.Fatalf("models_cache.json not found: %v", err)+ }+ if fi.Mode()&os.ModeSymlink != 0 {+ t.Error("models_cache.json should be copied, not symlinked")+ }+ data, _ = os.ReadFile(modelsCachePath)+ if string(data) != `{"models":["gpt-test"]}` {+ t.Errorf("models_cache.json content = %q", data)+ }+// plugin cache should be exposed at the same relative path in codex-home.pluginSkillPath := filepath.Join(codexHome, "plugins", "cache", "superpowers", "SKILL.md")data, err = os.ReadFile(pluginSkillPath)@@ -2077,6 +2100,13 @@ func TestPrepareCodexHomeSeedsFromShared(t *testing.T) {if string(data) != "Use superpowers." {t.Errorf("plugin cache skill content = %q", data)}++ // Marketplace checkouts contain executable plugin code and must not be+ // linked into a task home where one task could mutate another task's state.+ marketplacePath := filepath.Join(codexHome, ".tmp", "marketplaces")+ if _, err := os.Lstat(marketplacePath); !os.IsNotExist(err) {+ t.Fatalf("shared marketplace cache exposed in task home: %v", err)+ }}func TestPrepareCodexHomeCopiesRelativeModelCatalog(t *testing.T) {@@ -2189,7 +2219,8 @@ func TestPrepareCodexHomeSkipsMissingFiles(t *testing.T) {t.Fatalf("prepareCodexHome failed: %v", err)}- // Directory should contain a task-local sessions dir + auto-generated config.toml.+ // Directory should contain task-local sessions, the model-cache config+ // binding, and auto-generated config.toml.entries, err := os.ReadDir(codexHome)if err != nil {t.Fatalf("failed to read codex-home: %v", err)@@ -2207,8 +2238,11 @@ func TestPrepareCodexHomeSkipsMissingFiles(t *testing.T) {if !entryNames["plugins"] {t.Error("expected plugins directory for plugin cache exposure")}+ if !entryNames[codexModelsCacheBindingFile] {+ t.Error("expected models cache config binding")+ }for name := range entryNames {- if name != "sessions" && name != "config.toml" && name != "plugins" {+ if name != "sessions" && name != "config.toml" && name != "plugins" && name != codexModelsCacheBindingFile {t.Errorf("unexpected entry: %s", name)}}@@ -2858,6 +2892,291 @@ func TestReuseRestoresCodexPluginCache(t *testing.T) {}}+func TestReusePreservesTaskLocalModelsCacheWhenSharedMissing(t *testing.T) {+ // Cannot use t.Parallel() with t.Setenv.++ sharedHome := t.TempDir()+ t.Setenv("CODEX_HOME", sharedHome)++ env, err := Prepare(PrepareParams{+ WorkspacesRoot: t.TempDir(),+ WorkspaceID: "ws-codex-model-cache-missing",+ TaskID: "b5f6a7b8-c9d0-1234-efab-567890123456",+ AgentName: "Codex Agent",+ Provider: "codex",+ Task: TaskContextForEnv{IssueID: "reuse-model-cache-missing"},+ }, testLogger())+ if err != nil {+ t.Fatalf("Prepare failed: %v", err)+ }+ defer env.Cleanup(true)++ modelsCache := filepath.Join(env.CodexHome, "models_cache.json")+ if err := os.WriteFile(modelsCache, []byte(`{"source":"task"}`), 0o644); err != nil {+ t.Fatalf("write task-local models cache: %v", err)+ }++ reused := Reuse(ReuseParams{+ WorkDir: env.WorkDir,+ Provider: "codex",+ Task: TaskContextForEnv{IssueID: "reuse-model-cache-missing"},+ }, testLogger())+ if reused == nil {+ t.Fatal("Reuse returned nil")+ }++ data, err := os.ReadFile(filepath.Join(reused.CodexHome, "models_cache.json"))+ if err != nil {+ t.Fatalf("task-local models cache removed on reuse: %v", err)+ }+ if string(data) != `{"source":"task"}` {+ t.Fatalf("task-local models cache = %q, want task-generated cache", data)+ }+}++func TestReusePreservesTaskLocalModelsCacheOverStaleSharedSnapshot(t *testing.T) {+ // Cannot use t.Parallel() with t.Setenv.++ sharedHome := t.TempDir()+ if err := os.WriteFile(filepath.Join(sharedHome, "models_cache.json"), []byte(`{"source":"shared"}`), 0o644); err != nil {+ t.Fatalf("write shared models cache: %v", err)+ }+ t.Setenv("CODEX_HOME", sharedHome)++ env, err := Prepare(PrepareParams{+ WorkspacesRoot: t.TempDir(),+ WorkspaceID: "ws-codex-model-cache-stale",+ TaskID: "c5f6a7b8-c9d0-1234-efab-567890123456",+ AgentName: "Codex Agent",+ Provider: "codex",+ Task: TaskContextForEnv{IssueID: "reuse-model-cache-stale"},+ }, testLogger())+ if err != nil {+ t.Fatalf("Prepare failed: %v", err)+ }+ defer env.Cleanup(true)++ modelsCache := filepath.Join(env.CodexHome, "models_cache.json")+ if err := os.WriteFile(modelsCache, []byte(`{"source":"task"}`), 0o644); err != nil {+ t.Fatalf("refresh task-local models cache: %v", err)+ }++ reused := Reuse(ReuseParams{+ WorkDir: env.WorkDir,+ Provider: "codex",+ Task: TaskContextForEnv{IssueID: "reuse-model-cache-stale"},+ }, testLogger())+ if reused == nil {+ t.Fatal("Reuse returned nil")+ }++ data, err := os.ReadFile(filepath.Join(reused.CodexHome, "models_cache.json"))+ if err != nil {+ t.Fatalf("read reused task-local models cache: %v", err)+ }+ if string(data) != `{"source":"task"}` {+ t.Fatalf("task-local models cache = %q, want refreshed task cache", data)+ }+}++func TestReuseInvalidatesTaskLocalModelsCacheWhenProviderConfigChanges(t *testing.T) {+ // Cannot use t.Parallel() with t.Setenv.++ sharedHome := t.TempDir()+ configPath := filepath.Join(sharedHome, "config.toml")+ if err := os.WriteFile(configPath, []byte(`model_provider = "provider-a"`), 0o644); err != nil {+ t.Fatalf("write provider A config: %v", err)+ }+ sharedCache := filepath.Join(sharedHome, "models_cache.json")+ if err := os.WriteFile(sharedCache, []byte(`{"source":"shared-a"}`), 0o644); err != nil {+ t.Fatalf("write provider A shared cache: %v", err)+ }+ t.Setenv("CODEX_HOME", sharedHome)++ env, err := Prepare(PrepareParams{+ WorkspacesRoot: t.TempDir(),+ WorkspaceID: "ws-codex-model-cache-provider-change",+ TaskID: "d5f6a7b8-c9d0-1234-efab-567890123456",+ AgentName: "Codex Agent",+ Provider: "codex",+ Task: TaskContextForEnv{IssueID: "reuse-model-cache-provider-change"},+ }, testLogger())+ if err != nil {+ t.Fatalf("Prepare failed: %v", err)+ }+ defer env.Cleanup(true)++ modelsCache := filepath.Join(env.CodexHome, "models_cache.json")+ if err := os.WriteFile(modelsCache, []byte(`{"source":"task-a"}`), 0o644); err != nil {+ t.Fatalf("refresh provider A task cache: %v", err)+ }+ if err := os.WriteFile(configPath, []byte(`model_provider = "provider-b"`), 0o644); err != nil {+ t.Fatalf("write provider B config: %v", err)+ }+ // Even a changed shared snapshot is not safe to copy: Codex's cache format+ // does not say which provider produced it.+ if err := os.WriteFile(sharedCache, []byte(`{"source":"shared-b"}`), 0o644); err != nil {+ t.Fatalf("write provider B shared cache: %v", err)+ }++ reused := Reuse(ReuseParams{+ WorkDir: env.WorkDir,+ Provider: "codex",+ Task: TaskContextForEnv{IssueID: "reuse-model-cache-provider-change"},+ }, testLogger())+ if reused == nil {+ t.Fatal("Reuse returned nil")+ }+ if _, err := os.Lstat(modelsCache); !os.IsNotExist(err) {+ t.Fatalf("provider A models cache survived provider change: %v", err)+ }+ data, err := os.ReadFile(filepath.Join(reused.CodexHome, "config.toml"))+ if err != nil {+ t.Fatalf("read provider B task config: %v", err)+ }+ if !strings.Contains(string(data), `model_provider = "provider-b"`) {+ t.Fatalf("task config did not switch to provider B: %q", data)+ }++ // Once Codex refreshes the cache for provider B, another reuse with the+ // unchanged binding must preserve it over the shared snapshot.+ if err := os.WriteFile(modelsCache, []byte(`{"source":"task-b"}`), 0o644); err != nil {+ t.Fatalf("write provider B task cache: %v", err)+ }+ if Reuse(ReuseParams{+ WorkDir: env.WorkDir,+ Provider: "codex",+ Task: TaskContextForEnv{IssueID: "reuse-model-cache-provider-change"},+ }, testLogger()) == nil {+ t.Fatal("second Reuse returned nil")+ }+ data, err = os.ReadFile(modelsCache)+ if err != nil {+ t.Fatalf("read provider B task cache: %v", err)+ }+ if string(data) != `{"source":"task-b"}` {+ t.Fatalf("provider B task cache = %q, want task-refreshed cache", data)+ }+}++func TestReuseInvalidatesTaskLocalModelsCacheWhenModelCatalogChanges(t *testing.T) {+ // Cannot use t.Parallel() with t.Setenv.++ sharedHome := t.TempDir()+ if err := os.WriteFile(filepath.Join(sharedHome, "config.toml"), []byte(`model_catalog_json = "catalog.json"`), 0o644); err != nil {+ t.Fatalf("write model catalog config: %v", err)+ }+ catalogPath := filepath.Join(sharedHome, "catalog.json")+ if err := os.WriteFile(catalogPath, []byte(`{"models":[{"slug":"model-a"}]}`), 0o644); err != nil {+ t.Fatalf("write model catalog A: %v", err)+ }+ if err := os.WriteFile(filepath.Join(sharedHome, "models_cache.json"), []byte(`{"source":"shared"}`), 0o644); err != nil {+ t.Fatalf("write shared cache: %v", err)+ }+ t.Setenv("CODEX_HOME", sharedHome)++ env, err := Prepare(PrepareParams{+ WorkspacesRoot: t.TempDir(),+ WorkspaceID: "ws-codex-model-catalog-change",+ TaskID: "e5f6a7b8-c9d0-1234-efab-567890123456",+ AgentName: "Codex Agent",+ Provider: "codex",+ Task: TaskContextForEnv{IssueID: "reuse-model-catalog-change"},+ }, testLogger())+ if err != nil {+ t.Fatalf("Prepare failed: %v", err)+ }+ defer env.Cleanup(true)++ modelsCache := filepath.Join(env.CodexHome, "models_cache.json")+ if err := os.WriteFile(modelsCache, []byte(`{"source":"task-a"}`), 0o644); err != nil {+ t.Fatalf("refresh task cache: %v", err)+ }+ if err := os.WriteFile(catalogPath, []byte(`{"models":[{"slug":"model-b"}]}`), 0o644); err != nil {+ t.Fatalf("write model catalog B: %v", err)+ }++ reused := Reuse(ReuseParams{+ WorkDir: env.WorkDir,+ Provider: "codex",+ Task: TaskContextForEnv{IssueID: "reuse-model-catalog-change"},+ }, testLogger())+ if reused == nil {+ t.Fatal("Reuse returned nil")+ }+ if _, err := os.Lstat(modelsCache); !os.IsNotExist(err) {+ t.Fatalf("models cache survived model catalog change: %v", err)+ }+ data, err := os.ReadFile(filepath.Join(reused.CodexHome, "catalog.json"))+ if err != nil {+ t.Fatalf("read refreshed task model catalog: %v", err)+ }+ if string(data) != `{"models":[{"slug":"model-b"}]}` {+ t.Fatalf("task model catalog = %q", data)+ }+}++func TestReuseInvalidatesUnboundLegacyModelsCache(t *testing.T) {+ // Cannot use t.Parallel() with t.Setenv.++ sharedHome := t.TempDir()+ if err := os.WriteFile(filepath.Join(sharedHome, "config.toml"), []byte(`model_provider = "provider-a"`), 0o644); err != nil {+ t.Fatalf("write provider config: %v", err)+ }+ t.Setenv("CODEX_HOME", sharedHome)++ env, err := Prepare(PrepareParams{+ WorkspacesRoot: t.TempDir(),+ WorkspaceID: "ws-codex-model-cache-legacy",+ TaskID: "f5f6a7b8-c9d0-1234-efab-567890123456",+ AgentName: "Codex Agent",+ Provider: "codex",+ Task: TaskContextForEnv{IssueID: "reuse-model-cache-legacy"},+ }, testLogger())+ if err != nil {+ t.Fatalf("Prepare failed: %v", err)+ }+ defer env.Cleanup(true)++ modelsCache := filepath.Join(env.CodexHome, "models_cache.json")+ if err := os.WriteFile(modelsCache, []byte(`{"source":"legacy"}`), 0o644); err != nil {+ t.Fatalf("write legacy task cache: %v", err)+ }+ if err := os.Remove(filepath.Join(env.CodexHome, codexModelsCacheBindingFile)); err != nil {+ t.Fatalf("remove cache binding to simulate pre-fix home: %v", err)+ }++ if Reuse(ReuseParams{+ WorkDir: env.WorkDir,+ Provider: "codex",+ Task: TaskContextForEnv{IssueID: "reuse-model-cache-legacy"},+ }, testLogger()) == nil {+ t.Fatal("Reuse returned nil")+ }+ if _, err := os.Lstat(modelsCache); !os.IsNotExist(err) {+ t.Fatalf("unbound legacy cache survived reuse: %v", err)+ }++ // An existing pre-fix home without a cache is still not a fresh home. Do+ // not attach a newly observed shared snapshot to an unknown prior config.+ if err := os.Remove(filepath.Join(env.CodexHome, codexModelsCacheBindingFile)); err != nil {+ t.Fatalf("remove cache binding again: %v", err)+ }+ if err := os.WriteFile(filepath.Join(sharedHome, "models_cache.json"), []byte(`{"source":"shared"}`), 0o644); err != nil {+ t.Fatalf("write shared cache: %v", err)+ }+ if Reuse(ReuseParams{+ WorkDir: env.WorkDir,+ Provider: "codex",+ Task: TaskContextForEnv{IssueID: "reuse-model-cache-legacy"},+ }, testLogger()) == nil {+ t.Fatal("second Reuse returned nil")+ }+ if _, err := os.Lstat(modelsCache); !os.IsNotExist(err) {+ t.Fatalf("shared cache seeded into existing unbound home: %v", err)+ }+}+func TestReuseWritesMissingCodexWorkspaceSkills(t *testing.T) {// Cannot use t.Parallel() with t.Setenv.