Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): isolate Codex sessions per task to unblock initialize (MUL-4424) (#5360)
Bohan Jiang6cc553e5a379
diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex a6059e7f8b..ab702d69d1 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -60,10 +60,11 @@ const (DefaultHealthPort = 19514DefaultMaxConcurrentTasks = 20DefaultGCInterval = 1 * time.Hour- DefaultGCTTL = 24 * time.Hour // 1 day — AI-coding issues rarely stay open long- DefaultGCOrphanTTL = 72 * time.Hour // 3 days — orphans with no meta (crashes, pre-GC leftovers)- DefaultGCArtifactTTL = 12 * time.Hour // 12h — drop regenerable artifacts on completed but still-open issues- DefaultAutoUpdateCheckInterval = 6 * time.Hour // how often the daemon polls GitHub for a newer CLI release+ DefaultGCTTL = 24 * time.Hour // 1 day — AI-coding issues rarely stay open long+ DefaultGCOrphanTTL = 72 * time.Hour // 3 days — orphans with no meta (crashes, pre-GC leftovers)+ DefaultGCArtifactTTL = 12 * time.Hour // 12h — drop regenerable artifacts on completed but still-open issues+ DefaultGCCodexSessionTTL = 14 * 24 * time.Hour // 14 days — reclaim per-issue Codex session stores untouched this long+ DefaultAutoUpdateCheckInterval = 6 * time.Hour // how often the daemon polls GitHub for a newer CLI release)// DefaultGCArtifactPatterns lists basename matches that the GC loop treats as@@ -95,6 +96,7 @@ type Config struct {GCOrphanTTL time.Duration // clean orphan dirs with no meta, or dirs whose issue gc-check returns 404, once they exceed this age (default: 72h). The 404 path uses the same TTL — a scoped-down token can't instantly wipe live workspaces.GCArtifactTTL time.Duration // when a task has been completed for at least this long but its issue is still open, drop regenerable artifacts (default: 12h, set 0 to disable)GCArtifactPatterns []string // basename patterns whose subtrees are removed during artifact cleanup (default: node_modules, .next, .turbo)+ GCCodexSessionTTL time.Duration // reclaim a per-issue Codex session store (~/.codex/multica-sessions/<agent>/<issue>) untouched for at least this long, so a done/abandoned issue's conversation history does not accumulate forever (default: 14d, set 0 to disable)AutoUpdateEnabled bool // periodically check for a newer CLI release and self-update when idle (default: true on Multica Cloud, false on self-host)AutoUpdateCheckInterval time.Duration // how often the auto-update loop polls for a new release (default: 6h)PollInterval time.Duration@@ -498,6 +500,10 @@ func LoadConfig(overrides Overrides) (Config, error) {if err != nil {return Config{}, err}+ gcCodexSessionTTL, err := durationFromEnv("MULTICA_GC_CODEX_SESSION_TTL", DefaultGCCodexSessionTTL)+ if err != nil {+ return Config{}, err+ }gcArtifactPatterns := patternsFromEnv("MULTICA_GC_ARTIFACT_PATTERNS", DefaultGCArtifactPatterns)// Auto-update config: default -> env override -> CLI override.@@ -545,6 +551,7 @@ func LoadConfig(overrides Overrides) (Config, error) {GCOrphanTTL: gcOrphanTTL,GCArtifactTTL: gcArtifactTTL,GCArtifactPatterns: gcArtifactPatterns,+ GCCodexSessionTTL: gcCodexSessionTTL,AutoUpdateEnabled: autoUpdateEnabled,AutoUpdateCheckInterval: autoUpdateInterval,HealthPort: healthPort,diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 40898edd53..f60eae29dc 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -256,6 +256,11 @@ type Daemon struct {activeEnvRootsMu sync.MutexactiveEnvRoots map[string]int // env root path -> reference count (handles reuse paths marked twice)+ activeCodexStoresMu sync.Mutex+ activeCodexStoresCond *sync.Cond // signalled when an in-flight store deletion finishes, so a blocked markActive can proceed+ activeCodexStores map[string]int // per-issue Codex session store path -> live-task refcount; guards the store from GC mid-task (MUL-4424)+ deletingCodexStores map[string]bool // store paths a GC delete has reserved; markActive waits these out so a task never mounts a store mid-removal+// localPathLocks serialises agent tasks whose project resource is a// local_directory pinned to this daemon. Two tasks targeting the same// on-disk path run sequentially; the second blocks on the lock and is@@ -305,6 +310,8 @@ func New(cfg Config, logger *slog.Logger) *Daemon {resolvedPaths: make(map[string]healedAgent),wsHBLastAck: make(map[string]time.Time),activeEnvRoots: make(map[string]int),+ activeCodexStores: make(map[string]int),+ deletingCodexStores: make(map[string]bool),localPathLocks: NewLocalPathLocker(),runtimeGoneInflight: make(map[string]struct{}),reregisterNextAttempt: make(map[string]time.Time),@@ -314,6 +321,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {workspaceChanges: newWorkspaceChangeSignal(),wsRPC: newWSRPCClient(wsRPCResponseGrace),}+ d.activeCodexStoresCond = sync.NewCond(&d.activeCodexStoresMu)d.runner = taskRunnerFunc(d.runTask)d.runUpdateFn = d.runUpdatereturn d@@ -3490,10 +3498,38 @@ func gateResumeToReusedWorkdir(task *Task, taskCtx *execenv.TaskContextForEnv, e)task.PriorSessionID = ""taskCtx.PriorSessionResumed = false+ // The user expected this run to continue the prior conversation; surface+ // the loss in the brief instead of silently restarting (MUL-4424).+ taskCtx.PriorSessionResumeUnavailable = true}return reused}+// gateCodexResumeToRolloutPresence drops the prior Codex session when its+// rollout is not actually present in the task's CODEX_HOME sessions. A reused+// workdir keeps PriorSessionID (gateResumeToReusedWorkdir), but Codex session+// isolation (MUL-4424) means the rollout may be missing: a migrated legacy home+// that could not locate it, or a local_directory task whose shared history was+// pruned. Codex would then silently thread/start from scratch, so we clear the+// resume claim from both the backend (PriorSessionID) and the brief+// (PriorSessionResumed) instead of pretending the conversation continues.+// No-op for non-Codex providers or when there is nothing to resume.+func gateCodexResumeToRolloutPresence(task *Task, taskCtx *execenv.TaskContextForEnv, provider, codexHome string, taskLog *slog.Logger) {+ if provider != "codex" || task.PriorSessionID == "" || codexHome == "" {+ return+ }+ if execenv.CodexResumeRolloutPresent(codexHome, task.PriorSessionID) {+ return+ }+ taskLog.Warn("dropping prior codex session: rollout not present in task CODEX_HOME; starting a fresh thread",+ "session_id", task.PriorSessionID, "codex_home", codexHome)+ task.PriorSessionID = ""+ taskCtx.PriorSessionResumed = false+ // The user expected this run to continue the prior conversation; surface the+ // loss in the brief instead of silently restarting (MUL-4424).+ taskCtx.PriorSessionResumeUnavailable = true+}+func (d *Daemon) ensureTaskSkillBundles(ctx context.Context, task *Task) error {if task == nil || task.Agent == nil || len(task.Agent.SkillRefs) == 0 {return nil@@ -3884,12 +3920,24 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i}hermesEnv["HERMES_HOME"] = res.SourceHome}+ // Guard this task's per-issue Codex session store from the GC for the whole+ // task, starting before Prepare/Reuse mounts it — so a prune that samples the+ // store's stale (pre-remount) mtime cannot reclaim it out from under a resume+ // of a long-idle issue (MUL-4424). No-op for non-Codex tasks / no stable key.+ if provider == "codex" {+ if store := execenv.CodexSessionStorePath(d.cfg.Profile, task.AgentID, task.IssueID); store != "" {+ d.markActiveCodexStore(store)+ defer d.unmarkActiveCodexStore(store)+ }+ }if task.PriorWorkDir != "" && localAssignment == nil && !task.IsLeaderTask {env = execenv.Reuse(execenv.ReuseParams{WorkspacesRoot: d.cfg.WorkspacesRoot,+ Profile: d.cfg.Profile,WorkDir: task.PriorWorkDir,Provider: provider,CodexVersion: codexVersion,+ ResumeSessionID: task.PriorSessionID,OpenclawBin: openclawBin,McpConfig: effectiveMcpConfig,CursorMcpAuthSource: cursorMcpAuthSource,@@ -3904,6 +3952,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ivar err errorprepParams := execenv.PrepareParams{WorkspacesRoot: d.cfg.WorkspacesRoot,+ Profile: d.cfg.Profile,WorkspaceID: task.WorkspaceID,TaskID: task.ID,AgentName: agentName,@@ -3961,6 +4010,14 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i_ = d.client.ReportProgress(ctx, task.ID, fmt.Sprintf("Launching %s", provider), 1, 2)reused := gateResumeToReusedWorkdir(&task, &taskCtx, env.WorkDir, taskLog)+ // A reused workdir is necessary but not sufficient for a Codex resume: the+ // prior thread's rollout must actually be present in this task's CODEX_HOME+ // sessions (MUL-4424 isolates them). Drop the resume before the brief is+ // generated below if it isn't, so we never tell the agent it is continuing a+ // conversation Codex will silently restart from scratch.+ if reused {+ gateCodexResumeToRolloutPresence(&task, &taskCtx, provider, env.CodexHome, taskLog)+ }// Inject runtime-specific config (meta skill) so the agent discovers .agent_context/.runtimeBrief, err := execenv.InjectRuntimeConfig(env.WorkDir, provider, taskCtx)@@ -4186,11 +4243,17 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iSemanticInactivityTimeout: d.cfg.CodexSemanticInactivityTimeout,HandshakeTimeout: d.cfg.CodexHandshakeTimeout,ResumeSessionID: task.PriorSessionID,- ExtraArgs: extraArgs,- CustomArgs: customArgs,- McpConfig: mcpConfig,- ThinkingLevel: thinkingLevel,- OpenclawMode: openclawMode,+ // Post-gate intent: PriorSessionID here already reflects the pre-flight+ // resume gates (a dropped resume is surfaced via the brief instead). If it+ // survived to here, the backend must disclose to the user when the live+ // resume still fails — even across the fresh-session retry below, which+ // clears ResumeSessionID but not this (MUL-4424).+ ResumeExpected: task.PriorSessionID != "",+ ExtraArgs: extraArgs,+ CustomArgs: customArgs,+ McpConfig: mcpConfig,+ ThinkingLevel: thinkingLevel,+ OpenclawMode: openclawMode,}// Some providers do not reliably load the per-task runtime config files we// write into the task workdir:@@ -4926,6 +4989,59 @@ func (d *Daemon) isActiveEnvRoot(envRoot string) bool {return d.activeEnvRoots[envRoot] > 0}+// markActiveCodexStore records that a task is about to use the given per-issue+// Codex session store, so the GC never reclaims it mid-task — the store lives+// outside the env root, so isActiveEnvRoot does not cover it (MUL-4424). If a GC+// delete has already reserved this store, we wait for that removal to finish+// before claiming it, so a task never mounts a store mid-removal; the store is+// then recreated fresh by Prepare. Reference-counted like the env-root guard.+func (d *Daemon) markActiveCodexStore(store string) {+ if store == "" {+ return+ }+ d.activeCodexStoresMu.Lock()+ defer d.activeCodexStoresMu.Unlock()+ for d.deletingCodexStores[store] {+ d.activeCodexStoresCond.Wait()+ }+ d.activeCodexStores[store]+++}++func (d *Daemon) unmarkActiveCodexStore(store string) {+ if store == "" {+ return+ }+ d.activeCodexStoresMu.Lock()+ defer d.activeCodexStoresMu.Unlock()+ if d.activeCodexStores[store] <= 1 {+ delete(d.activeCodexStores, store)+ return+ }+ d.activeCodexStores[store]--+}++// reserveCodexStoreForDeletion atomically checks that no live task holds store+// and, if so, marks it reserved so no task can claim it until the caller runs+// the returned commit (after the actual removal). ok=false means a task holds it+// — do not delete. This is the exclusive protocol PruneCodexSessionStores needs:+// the "confirm inactive" and the mark happen under one lock acquisition, so a+// markActiveCodexStore either loses the check (store stays) or blocks on the+// reservation, closing the stat->remove race (MUL-4424).+func (d *Daemon) reserveCodexStoreForDeletion(store string) (commit func(), ok bool) {+ d.activeCodexStoresMu.Lock()+ defer d.activeCodexStoresMu.Unlock()+ if d.activeCodexStores[store] > 0 || d.deletingCodexStores[store] {+ return nil, false+ }+ d.deletingCodexStores[store] = true+ return func() {+ d.activeCodexStoresMu.Lock()+ delete(d.deletingCodexStores, store)+ d.activeCodexStoresCond.Broadcast()+ d.activeCodexStoresMu.Unlock()+ }, true+}+// shortID returns the first 8 characters of an ID for readable logs.func shortID(id string) string {if len(id) <= 8 {diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex e0e345dee7..9f7b741764 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -1115,6 +1115,56 @@ func newRepoReadyTestDaemon(t *testing.T, handler http.HandlerFunc) *Daemon {return d}+func TestGateCodexResumeToRolloutPresence(t *testing.T) {+ t.Parallel()++ // Seed a codex-home whose sessions dir holds exactly one rollout.+ codexHome := filepath.Join(t.TempDir(), "codex-home")+ present := filepath.Join(codexHome, "sessions", "2026", "07", "13",+ "rollout-2026-07-13T00-00-00-present-session.jsonl")+ if err := os.MkdirAll(filepath.Dir(present), 0o755); err != nil {+ t.Fatalf("mkdir sessions: %v", err)+ }+ if err := os.WriteFile(present, []byte("{}"), 0o644); err != nil {+ t.Fatalf("write rollout: %v", err)+ }++ tests := []struct {+ name string+ provider string+ sessionID string+ codexHome string+ wantSession string+ }{+ {name: "rollout present keeps resume", provider: "codex", sessionID: "present-session", codexHome: codexHome, wantSession: "present-session"},+ {name: "rollout absent drops resume", provider: "codex", sessionID: "gone-session", codexHome: codexHome, wantSession: ""},+ {name: "non-codex provider is a no-op", provider: "claude", sessionID: "present-session", codexHome: codexHome, wantSession: "present-session"},+ {name: "empty codex home is a no-op", provider: "codex", sessionID: "present-session", codexHome: "", wantSession: "present-session"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ task := Task{PriorSessionID: tt.sessionID}+ taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: tt.sessionID != ""}++ gateCodexResumeToRolloutPresence(&task, &taskCtx, tt.provider, tt.codexHome, slog.Default())++ if task.PriorSessionID != tt.wantSession {+ t.Fatalf("PriorSessionID = %q, want %q", task.PriorSessionID, tt.wantSession)+ }+ if taskCtx.PriorSessionResumed != (tt.wantSession != "") {+ t.Fatalf("PriorSessionResumed = %v, want %v", taskCtx.PriorSessionResumed, tt.wantSession != "")+ }+ // A dropped resume (had a session, now cleared) must be surfaced to+ // the user via the brief; a kept/no-op resume must not.+ wantUnavailable := tt.sessionID != "" && tt.wantSession == ""+ if taskCtx.PriorSessionResumeUnavailable != wantUnavailable {+ t.Fatalf("PriorSessionResumeUnavailable = %v, want %v", taskCtx.PriorSessionResumeUnavailable, wantUnavailable)+ }+ })+ }+}+func TestGateResumeToReusedWorkdir(t *testing.T) {t.Parallel()@@ -1176,10 +1226,108 @@ func TestGateResumeToReusedWorkdir(t *testing.T) {if taskCtx.PriorSessionResumed != (tt.wantSession != "") {t.Fatalf("PriorSessionResumed = %v, want %v", taskCtx.PriorSessionResumed, tt.wantSession != "")}+ // A dropped resume (had a session, now cleared) must be surfaced to+ // the user via the brief; a kept/no-op resume must not.+ wantUnavailable := tt.sessionID != "" && tt.wantSession == ""+ if taskCtx.PriorSessionResumeUnavailable != wantUnavailable {+ t.Fatalf("PriorSessionResumeUnavailable = %v, want %v", taskCtx.PriorSessionResumeUnavailable, wantUnavailable)+ }})}}+// newCodexStoreGuardDaemon builds a Daemon with only the per-issue Codex session+// store guard initialised — enough to exercise the reserve-vs-mark protocol.+func newCodexStoreGuardDaemon() *Daemon {+ d := &Daemon{+ activeCodexStores: map[string]int{},+ deletingCodexStores: map[string]bool{},+ }+ d.activeCodexStoresCond = sync.NewCond(&d.activeCodexStoresMu)+ return d+}++// A task that marks a store active before the GC reserves it must block the+// deletion — this is exactly Elon's mark-then-delete interleaving, which the old+// point-in-time active check allowed.+func TestCodexStoreGuard_MarkBeforeReserveBlocksDeletion(t *testing.T) {+ t.Parallel()+ d := newCodexStoreGuardDaemon()+ const store = "/stores/agent/issue"++ d.markActiveCodexStore(store)+ if _, ok := d.reserveCodexStoreForDeletion(store); ok {+ t.Fatal("reserve must refuse a store a live task already holds")+ }+ d.unmarkActiveCodexStore(store)++ commit, ok := d.reserveCodexStoreForDeletion(store)+ if !ok {+ t.Fatal("reserve should succeed once the store is inactive")+ }+ commit()+}++// The reverse interleaving: once the GC has reserved a store, a task's+// markActive must block until the removal commits (so it never mounts a store+// mid-removal), then proceed.+func TestCodexStoreGuard_ReserveBlocksMarkUntilCommit(t *testing.T) {+ t.Parallel()+ d := newCodexStoreGuardDaemon()+ const store = "/stores/agent/issue"++ commit, ok := d.reserveCodexStoreForDeletion(store)+ if !ok {+ t.Fatal("reserve should succeed on an inactive store")+ }++ marked := make(chan struct{})+ go func() {+ d.markActiveCodexStore(store)+ close(marked)+ }()++ select {+ case <-marked:+ t.Fatal("markActiveCodexStore must block while the store is reserved for deletion")+ case <-time.After(100 * time.Millisecond):+ }++ commit()++ select {+ case <-marked:+ case <-time.After(2 * time.Second):+ t.Fatal("markActiveCodexStore must proceed after the reservation is committed")+ }+ // The store is now active, so a fresh reserve must be refused.+ if _, ok := d.reserveCodexStoreForDeletion(store); ok {+ t.Fatal("store must be active after the blocked mark proceeds")+ }+}++// Two GC passes cannot both reserve the same store; the second is refused until+// the first commits.+func TestCodexStoreGuard_SecondReserveRefusedWhileDeleting(t *testing.T) {+ t.Parallel()+ d := newCodexStoreGuardDaemon()+ const store = "/stores/agent/issue"++ commit, ok := d.reserveCodexStoreForDeletion(store)+ if !ok {+ t.Fatal("first reserve should succeed")+ }+ if _, ok := d.reserveCodexStoreForDeletion(store); ok {+ t.Fatal("a second reserve must be refused while a removal is in flight")+ }+ commit()+ commit2, ok := d.reserveCodexStoreForDeletion(store)+ if !ok {+ t.Fatal("reserve should succeed again after the prior removal committed")+ }+ commit2()+}+func TestExecuteAndDrain_ResumeFailureFallback(t *testing.T) {t.Parallel()diff --git a/server/internal/daemon/execenv/codex_home.go b/server/internal/daemon/execenv/codex_home.goindex bd62c5f860..a2867fb8c6 100644--- a/server/internal/daemon/execenv/codex_home.go+++ b/server/internal/daemon/execenv/codex_home.go@@ -1,23 +1,19 @@package execenvimport (+ "crypto/sha256"+ "encoding/hex""fmt""io""log/slog""os""path/filepath""strings"+ "time""github.com/pelletier/go-toml/v2")-// Directories to symlink from the shared ~/.codex/ into the per-task CODEX_HOME.-// The shared directory is created if it doesn't exist, ensuring Codex session-// logs are always written to the global home where users can find them.-var codexSymlinkedDirs = []string{- "sessions",-}-// Files to symlink from the shared ~/.codex/ into the per-task CODEX_HOME.// Symlinks share state (e.g. auth tokens) so changes propagate automatically.var codexSymlinkedFiles = []string{@@ -44,6 +40,28 @@ type CodexHomeOptions struct {// Empty means use runtime.GOOS. Primarily exists so tests can exercise// both macOS and Linux paths deterministically.GOOS string+ // ResumeSessionID is the Codex thread/session ID this run intends to+ // resume, when any. It is consulted when populating the per-issue session+ // store (local_directory tasks) or migrating a legacy per-task home whose+ // sessions/ still symlinks the shared ~/.codex/sessions: the single rollout+ // for this ID is exposed so thread/resume can find it without pulling the+ // whole shared history back in. Empty means a fresh thread (no rollout to+ // expose). See prepareCodexSessionsDir (MUL-4424).+ ResumeSessionID string+ // IsLocalDirectory marks a local_directory task — one running in the user's+ // own project directory. These tasks get a fresh codex-home per task ID (the+ // daemon never reuses their workdir), so their sessions/ is pointed at the+ // per-issue store (SessionStoreKey) that survives across task IDs and holds+ // ONLY this issue's rollouts — never the machine's whole ~/.codex/sessions.+ // See prepareCodexSessionsDir (MUL-4424).+ IsLocalDirectory bool+ // SessionStoreKey is a stable, per-(agent, issue) relative path segment that+ // identifies this task's persistent Codex sessions store. It survives across+ // task IDs (unlike the task-scoped envRoot the GC reclaims) so a follow-up+ // run resumes the same thread. Empty when no stable key is available (e.g. a+ // task with no issue), in which case sessions/ stays task-local. See+ // codexSessionStoreDir and prepareCodexSessionsDir (MUL-4424).+ SessionStoreKey string}// prepareCodexHome is a thin wrapper around prepareCodexHomeWithOpts kept for@@ -65,13 +83,11 @@ func prepareCodexHomeWithOpts(codexHome string, opts CodexHomeOptions, logger *sreturn fmt.Errorf("create codex-home dir: %w", err)}- // Symlink shared directories (sessions) so logs stay in the global home.- for _, name := range codexSymlinkedDirs {- src := filepath.Join(sharedHome, name)- dst := filepath.Join(codexHome, name)- if err := ensureDirSymlink(src, dst); err != nil {- logger.Warn("execenv: codex-home dir symlink failed", "dir", name, "error", err)- }+ // Give the task its own local sessions/ directory instead of symlinking the+ // shared ~/.codex/sessions in — a huge shared history would otherwise stall+ // Codex's `initialize` state backfill (MUL-4424). See prepareCodexSessionsDir.+ if err := prepareCodexSessionsDir(codexHome, sharedHome, opts, logger); err != nil {+ logger.Warn("execenv: codex-home sessions dir prepare failed", "error", err)}// Symlink shared files (auth).@@ -159,6 +175,501 @@ func resolveSharedCodexHome() string {return filepath.Join(home, ".codex")}+// codexSessionStateGlobs are the session-derived SQLite state Codex builds+// inside a CODEX_HOME by indexing everything under sessions/. They are dropped+// during the legacy-symlink migration (prepareCodexSessionsDir) so Codex+// rebuilds them from the now task-local sessions instead of keeping the+// thousands of stale rows it backfilled from the shared ~/.codex/sessions+// history. Everything matched here is a rebuildable derived index — never+// authoritative data.+//+// Deliberately NOT listed: session_index.jsonl, which Codex 0.144.x uses as the+// authoritative store for thread-id → user-set thread name (name edits land in+// SQLite AND this file, never back in the rollout), so it cannot be rebuilt from+// rollouts; and sibling per-task DBs with different prefixes (goals_*, logs_*,+// memories_*) which are not session-derived. All are left intact.+var codexSessionStateGlobs = []string{+ "state_*.sqlite",+ "state_*.sqlite-shm",+ "state_*.sqlite-wal",+}++// codexSessionStoreRoot is the directory under the shared Codex home that holds+// the per-issue session stores. It sits beside the user's own `sessions/` so it+// shares that volume (making resume-rollout hard links zero-copy) but is never+// enumerated by a plain `codex` run, keeping Multica task history out of the+// user's own thread list.+const codexSessionStoreRoot = "multica-sessions"++// codexSessionStoreDir returns the persistent, per-(agent, issue) Codex sessions+// store for key, rooted on the shared Codex home's volume. It survives across+// task IDs (unlike the task-scoped envRoot the GC reclaims) and holds only that+// issue's rollouts. Empty key → "" (caller keeps sessions/ task-local).+func codexSessionStoreDir(sharedHome, key string) string {+ if key == "" {+ return ""+ }+ return filepath.Join(sharedHome, codexSessionStoreRoot, key)+}++// codexSessionStoreNamespace maps a daemon's profile to the directory segment+// that isolates its session stores from another profile-daemon's when several+// run on the same machine sharing one ~/.codex (profiles get separate daemon+// state but the same Codex home). Each daemon writes under, and only ever+// reclaims, its own namespace, so a staging daemon's GC can never delete a+// production task's live store and vice versa.+//+// The map MUST be collision-free (distinct profiles are distinct daemons and+// must never share a namespace) AND fixed-length (a profile can be as long as a+// filesystem segment allows, ~255 bytes, so any length-expanding encoding would+// overflow the 255-byte limit and fail to create the store dir). A lossy "drop+// unsafe characters" scheme collides ("" vs "default", "staging.prod" vs+// "stagingprod"); a full hex encoding doubles the length and overflows. So the+// empty (default) profile gets a reserved bare literal, and every named profile+// is the hex of its SHA-256 — a constant 64 hex chars, filesystem-safe and+// collision-resistant — under a "p_" prefix the bare literal can never collide+// with (MUL-4424).+func codexSessionStoreNamespace(profile string) string {+ if profile == "" {+ return "default"+ }+ sum := sha256.Sum256([]byte(profile))+ return "p_" + hex.EncodeToString(sum[:])+}++// codexSessionStoreKey builds the per-(profile, agent, issue) key for a task's+// persistent Codex sessions store. The agent/issue IDs are server-issued UUIDs;+// all three segments are sanitized to bare path segments defensively so a+// malformed value can never escape the store root. Returns "" when there is no+// issue to key on (the store is issue-scoped), leaving sessions/ task-local.+func codexSessionStoreKey(profile, agentID, issueID string) string {+ issue := sanitizeCodexPathSegment(issueID)+ if issue == "" {+ return ""+ }+ agent := sanitizeCodexPathSegment(agentID)+ if agent == "" {+ agent = "_"+ }+ return filepath.Join(codexSessionStoreNamespace(profile), agent, issue)+}++// sanitizeCodexPathSegment reduces s to the characters a UUID uses (hex plus+// dashes/underscores), dropping everything else so the result is always a single+// safe path segment — no separators, no "..", no drive letters.+func sanitizeCodexPathSegment(s string) string {+ var b strings.Builder+ for _, r := range s {+ switch {+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_':+ b.WriteRune(r)+ }+ }+ return b.String()+}++// PruneCodexSessionStores reclaims per-issue Codex session stores under the+// shared home's multica-sessions root that have not been touched within+// retention, bounding the lifetime of the conversation history each one holds.+//+// The stores deliberately live outside the task-scoped envRoot the task GC+// reclaims (so resume survives across task IDs), which means without this they+// would accumulate forever — a done or abandoned issue's prompts and full+// rollouts (one reporter saw a single 1.5 GiB rollout) would never be freed, and+// deleting the issue/agent/workspace would not remove them. A store's newest+// mtime is its last activity: Codex writes/extends a rollout as the thread+// advances, so an active or recently-resumed task keeps its store fresh and is+// never reclaimed; a store idle past retention is removed, giving deleted issues+// an eventual-reclamation guarantee. retention <= 0 disables pruning entirely.+//+// It scans ONLY the caller profile's namespace, so a daemon never reclaims a+// store owned by another profile-daemon sharing the same ~/.codex — the+// in-process reservation guard cannot span processes, and the namespace makes+// their store trees disjoint so it does not need to (MUL-4424).+//+// reserve (may be nil) atomically claims a store for deletion: it returns+// ok=false when a live task holds the store — leaving it — and otherwise returns+// a commit to run once removal finishes. Because the caller's reservation and a+// task's mark-active go through one lock in the same process, a store a task is+// about to mount is never removed out from under it — the confirm-inactive and+// the remove are effectively atomic, closing the stat->remove race a plain+// point-in-time active check leaves open. nil disables the guard (tests): every+// idle store is removed.+func PruneCodexSessionStores(profile string, retention time.Duration, now time.Time, reserve func(storeDir string) (commit func(), ok bool), logger *slog.Logger) (removed int, bytesFreed int64) {+ if retention <= 0 {+ return 0, 0+ }+ root := filepath.Join(resolveSharedCodexHome(), codexSessionStoreRoot, codexSessionStoreNamespace(profile))+ agents, err := os.ReadDir(root)+ if err != nil {+ return 0, 0 // not created yet, or unreadable — nothing to prune+ }+ for _, a := range agents {+ if !a.IsDir() {+ continue+ }+ agentDir := filepath.Join(root, a.Name())+ issues, err := os.ReadDir(agentDir)+ if err != nil {+ continue+ }+ kept := 0+ for _, is := range issues {+ if !is.IsDir() {+ continue+ }+ storeDir := filepath.Join(agentDir, is.Name())+ newest, size := codexStoreStat(storeDir)+ if newest.IsZero() || now.Sub(newest) <= retention {+ kept+++ continue+ }+ // Atomically reserve the store before removing it. A live task holds+ // it (or is mounting it right now) → skip; otherwise the reservation+ // blocks any task from claiming it until the removal + commit finish.+ var commit func()+ if reserve != nil {+ c, ok := reserve(storeDir)+ if !ok {+ kept+++ continue+ }+ commit = c+ }+ err := os.RemoveAll(storeDir)+ if commit != nil {+ commit()+ }+ if err != nil {+ logger.Warn("execenv: prune codex session store failed", "store", storeDir, "error", err)+ kept+++ continue+ }+ removed+++ bytesFreed += size+ }+ // Remove the agent dir once its last issue store is gone, so the tree+ // does not leave empty <agent>/ shells behind.+ if kept == 0 {+ _ = os.Remove(agentDir)+ }+ }+ return removed, bytesFreed+}++// codexStoreStat walks dir once, returning the newest modification time seen+// (the store's last activity) and its total byte size (for GC accounting).+func codexStoreStat(dir string) (newest time.Time, size int64) {+ _ = filepath.WalkDir(dir, func(_ string, d os.DirEntry, err error) error {+ if err != nil {+ return nil+ }+ info, ierr := d.Info()+ if ierr != nil {+ return nil+ }+ if info.ModTime().After(newest) {+ newest = info.ModTime()+ }+ if !d.IsDir() {+ size += info.Size()+ }+ return nil+ })+ return newest, size+}++// prepareCodexSessionsDir points codex-home/sessions at a sessions store that+// holds ONLY this task's own history, never the machine's whole+// ~/.codex/sessions.+//+// Background (MUL-4424): Codex 0.143+ backfills a per-home session-state DB by+// enumerating every rollout visible under sessions/ during `initialize`. When+// the per-task home symlinked the shared sessions dir in, a machine that had+// accumulated thousands of rollouts (one reporter hit ~2000 files / ~22 GiB)+// stalled `initialize` for tens of seconds — the app-server started but the+// task produced no output before it was cancelled. So we scope sessions/ to a+// single task/issue:+//+// - local_directory task: envRoot (and thus codex-home) is fresh per task ID+// and never reused, so sessions/ links to the per-issue store on the shared+// Codex volume — stable across task IDs, GC-safe, and holding only this+// issue's rollouts. See linkCodexSessionsToStore.+// - Fresh managed task: sessions/ is absent — create an empty local dir so+// backfill is trivial; the reused envRoot carries it to the next run.+// - Reused managed task whose sessions/ is already a real dir: it is+// authoritative — the prior run's rollout already lives here — leave it.+// - Reused managed task still holding a legacy symlink into the shared+// sessions (older build): migrate. With a resume, route it through the+// per-issue store (cross-volume-safe); without one, replace the symlink+// with an empty local dir. Either way drop the stale session-state DB so+// Codex rebuilds it from the scoped sessions.+func prepareCodexSessionsDir(codexHome, sharedHome string, opts CodexHomeOptions, logger *slog.Logger) error {+ dst := filepath.Join(codexHome, "sessions")+ sharedSessions := filepath.Join(sharedHome, "sessions")+ storeDir := codexSessionStoreDir(sharedHome, opts.SessionStoreKey)++ // local_directory tasks have no reusable envRoot, so their history can only+ // persist across task IDs in the per-issue store. The daemon still verifies+ // the specific rollout is present before claiming a resume (see+ // CodexResumeRolloutPresent), so a missing one no longer masquerades as one.+ if opts.IsLocalDirectory {+ if storeDir == "" {+ // No stable per-issue key (e.g. a non-issue task). Fall back to an+ // empty local dir rather than re-exposing the whole shared history.+ return os.MkdirAll(dst, 0o755)+ }+ return linkCodexSessionsToStore(dst, storeDir, sharedSessions, opts.ResumeSessionID, logger)+ }++ fi, err := os.Lstat(dst)+ switch {+ case os.IsNotExist(err):+ return os.MkdirAll(dst, 0o755) // fresh managed task — empty local dir+ case err != nil:+ return fmt.Errorf("stat sessions dir %s: %w", dst, err)+ }++ if fi.Mode()&os.ModeSymlink == 0 {+ // Already a real directory (task-local, authoritative). Ensure it+ // exists (no-op) and leave its contents alone.+ return os.MkdirAll(dst, 0o755)+ }++ // A symlink/junction. If it already points at this issue's store (a home+ // migrated with a resume on a prior reuse), it is authoritative — re-ensure+ // the store link and the resume rollout, then leave it.+ if storeDir != "" {+ if target, rlErr := os.Readlink(dst); rlErr == nil && sameCodexPath(target, storeDir) {+ return linkCodexSessionsToStore(dst, storeDir, sharedSessions, opts.ResumeSessionID, logger)+ }+ }++ // Legacy symlink into the shared ~/.codex/sessions — migrate it. Drop the+ // session-derived state so Codex re-indexes the scoped sessions instead of+ // the stale rows it built from the whole shared home.+ if err := os.Remove(dst); err != nil {+ return fmt.Errorf("remove legacy sessions symlink %s: %w", dst, err)+ }+ resetCodexSessionState(codexHome, logger)++ // With a resume, route through the per-issue store so the rollout is exposed+ // cross-volume-safely (hard link within the shared volume + a directory link+ // into the task home). Without a resume — or with no stable key — an empty+ // local dir is all a fresh thread needs.+ if opts.ResumeSessionID != "" && storeDir != "" {+ logger.Info("execenv: migrated codex-home sessions from shared symlink to per-issue store",+ "codex_home", codexHome, "resume_session", true)+ return linkCodexSessionsToStore(dst, storeDir, sharedSessions, opts.ResumeSessionID, logger)+ }+ logger.Info("execenv: migrated codex-home sessions from shared symlink to task-local dir",+ "codex_home", codexHome, "resume_session", false)+ return os.MkdirAll(dst, 0o755)+}++// linkCodexSessionsToStore points codex-home/sessions (dst) at the per-issue+// store (storeDir) via an idempotent directory link — a symlink on Unix, a+// junction on Windows — both of which cross filesystem volumes without special+// privilege. The store lives on the shared Codex home's volume, so linking the+// directory (rather than copying rollout files into the task home) is what makes+// resume exposure safe when WorkspacesRoot sits on a different disk than+// ~/.codex (MUL-4424, Windows cross-volume).+//+// When resuming and the store does not yet hold the rollout — e.g. the first run+// after upgrading from the old whole-shared-sessions layout, where the history+// still lives only under ~/.codex/sessions — it hard-links that rollout into the+// store. Both paths are on the shared volume, so the link is zero-copy and never+// puts a (possibly gigabyte) rollout on initialize's critical path.+func linkCodexSessionsToStore(dst, storeDir, sharedSessions, resumeID string, logger *slog.Logger) error {+ if err := os.MkdirAll(storeDir, 0o755); err != nil {+ return fmt.Errorf("create codex session store %s: %w", storeDir, err)+ }+ if resumeID != "" && len(findCodexRollouts(storeDir, resumeID)) == 0 {+ if err := exposeResumeRollout(sharedSessions, storeDir, resumeID, logger); err != nil {+ logger.Warn("execenv: bootstrap resume rollout into session store failed; task will fall back to a fresh thread",+ "session_id", resumeID, "error", err)+ }+ }+ if err := ensureCodexSessionsLink(dst, storeDir); err != nil {+ return err+ }+ // Stamp the store as just-used. Mounting it (MkdirAll, rollout lookup, link)+ // does not touch its mtime, so without this the GC's idle check would still+ // see a >TTL-old store and could reclaim it before the resumed turn writes its+ // first rollout — reopening a long-idle issue must not lose context. This is+ // the activity refresh; the daemon's in-process active-store guard closes the+ // remaining stat→remove race (MUL-4424).+ touchCodexSessionStore(storeDir, logger)+ return nil+}++// touchCodexSessionStore refreshes storeDir's modification time to now — the+// signal codexStoreStat reads as the store's last activity. Best-effort: a+// failed touch only risks an over-eager prune, which the active-store guard+// still prevents.+func touchCodexSessionStore(storeDir string, logger *slog.Logger) {+ now := time.Now()+ if err := os.Chtimes(storeDir, now, now); err != nil {+ logger.Warn("execenv: refresh codex session store activity failed", "store", storeDir, "error", err)+ }+}++// CodexSessionStorePath returns the per-issue Codex session store directory for+// (profile, agentID, issueID) on the shared home, or "" when there is no stable+// key. The daemon marks this path in-use for the duration of a task so+// PruneCodexSessionStores never reclaims a store mid-mount, closing the+// stat→remove race the mtime refresh alone cannot (MUL-4424).+func CodexSessionStorePath(profile, agentID, issueID string) string {+ key := codexSessionStoreKey(profile, agentID, issueID)+ if key == "" {+ return ""+ }+ return codexSessionStoreDir(resolveSharedCodexHome(), key)+}++// sameCodexPath reports whether two filesystem paths refer to the same location,+// tolerating separator/cleanliness differences. Used to detect a sessions link+// that already points at the per-issue store so a reused home is not re-migrated.+func sameCodexPath(a, b string) bool {+ return filepath.Clean(a) == filepath.Clean(b)+}++// resetCodexSessionState removes the rebuildable, session-derived Codex state+// files from a per-task CODEX_HOME so the next `initialize` re-derives them from+// the task-local sessions. Only session-derived indexes are touched; unrelated+// per-task DBs (goals_*, logs_*, memories_*) are left intact.+func resetCodexSessionState(codexHome string, logger *slog.Logger) {+ for _, pattern := range codexSessionStateGlobs {+ matches, err := filepath.Glob(filepath.Join(codexHome, pattern))+ if err != nil {+ continue+ }+ for _, m := range matches {+ if err := os.Remove(m); err != nil && !os.IsNotExist(err) {+ logger.Warn("execenv: codex-home reset session state failed", "path", m, "error", err)+ }+ }+ }+}++// ensureCodexSessionsLink points codex-home/sessions (dst) at the per-issue+// session store (src) via a directory link, creating the store if needed.+// Idempotent: a link already pointing at src is left as-is; anything else at dst+// (a real dir, a stale link, a legacy shared-sessions symlink) is replaced. The+// link crosses volumes without privilege (symlink on Unix, junction on Windows),+// so the store can live on the shared Codex volume while the task home lives+// under WorkspacesRoot (see linkCodexSessionsToStore).+func ensureCodexSessionsLink(dst, src string) error {+ if err := os.MkdirAll(src, 0o755); err != nil {+ return fmt.Errorf("create codex session store %s: %w", src, err)+ }+ if fi, err := os.Lstat(dst); err == nil {+ if fi.Mode()&os.ModeSymlink != 0 {+ if target, rlErr := os.Readlink(dst); rlErr == nil && sameCodexPath(target, src) {+ return nil+ }+ }+ if err := os.RemoveAll(dst); err != nil {+ return fmt.Errorf("remove stale sessions path %s: %w", dst, err)+ }+ }+ return createDirLink(src, dst)+}++// codexRolloutGlobs returns the glob patterns that match a session's rollout+// under a Codex sessions directory. It covers the layouts Codex 0.14x writes:+// date-nested (sessions/YYYY/MM/DD/) and flat (directly under sessions/), each+// as a plain .jsonl or a background-compressed .jsonl.zst.+func codexRolloutGlobs(sessionsDir, sessionID string) []string {+ name := "rollout-*-" + sessionID + ".jsonl*" // .jsonl and .jsonl.zst+ return []string{+ filepath.Join(sessionsDir, name),+ filepath.Join(sessionsDir, "*", "*", "*", name),+ }+}++// findCodexRollouts returns every rollout file for sessionID under sessionsDir,+// across the supported layouts.+func findCodexRollouts(sessionsDir, sessionID string) []string {+ if sessionsDir == "" || sessionID == "" {+ return nil+ }+ var out []string+ seen := map[string]bool{}+ for _, pattern := range codexRolloutGlobs(sessionsDir, sessionID) {+ matches, err := filepath.Glob(pattern)+ if err != nil {+ continue+ }+ for _, m := range matches {+ if !seen[m] {+ seen[m] = true+ out = append(out, m)+ }+ }+ }+ return out+}++// CodexResumeRolloutPresent reports whether sessionID's rollout is present in+// the task's codex-home sessions dir. The daemon uses this after preparing the+// environment to avoid claiming a resume Codex would silently restart from+// scratch — the rollout may be absent when a legacy home's migration could not+// locate it, or when a local_directory task's shared history has been pruned+// (MUL-4424).+func CodexResumeRolloutPresent(codexHome, sessionID string) bool {+ if codexHome == "" || sessionID == "" {+ return false+ }+ return len(findCodexRollouts(filepath.Join(codexHome, "sessions"), sessionID)) > 0+}++// exposeResumeRollout links sessionID's rollout(s) out of the shared sessions+// history into the task-local sessions dir, preserving the relative layout so+// thread/resume can find it. Covers plain and compressed rollouts in both the+// nested and flat layouts.+//+// It links rather than copies: a rollout can be large (one reporter saw a+// single 1.5 GiB file) and this runs on `initialize`'s critical path, so an+// unbounded copy would reintroduce the very stall we are fixing. See+// linkCodexRollout for the hard-link-then-symlink strategy; if neither works+// the caller treats the resume as unavailable and falls back to a fresh thread.+func exposeResumeRollout(sharedSessions, localSessions, sessionID string, logger *slog.Logger) error {+ matches := findCodexRollouts(sharedSessions, sessionID)+ if len(matches) == 0 {+ return fmt.Errorf("no rollout found for session %s under %s", sessionID, sharedSessions)+ }+ linked := 0+ for _, src := range matches {+ rel, err := filepath.Rel(sharedSessions, src)+ if err != nil {+ rel = filepath.Base(src)+ }+ dst := filepath.Join(localSessions, rel)+ if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {+ return fmt.Errorf("create rollout dir %s: %w", filepath.Dir(dst), err)+ }+ if err := linkCodexRollout(src, dst); err != nil {+ return fmt.Errorf("link rollout %s: %w", src, err)+ }+ linked+++ }+ logger.Info("execenv: exposed resume rollout into task-local sessions", "session_id", sessionID, "files", linked)+ return nil+}++// linkCodexRollout materialises src at dst without copying its bytes: a hard+// link first (zero-copy, needs no special privilege and works on Windows within+// a volume), falling back to a symlink across filesystems. It never copies — a+// rollout can be gigabytes and this runs on initialize's critical path, so a+// copy would reintroduce the stall MUL-4424 fixes.+func linkCodexRollout(src, dst string) error {+ if err := os.Link(src, dst); err == nil {+ return nil+ }+ return os.Symlink(src, dst)+}+func syncCodexModelCatalog(codexHome, sharedHome string) error {configPath := filepath.Join(codexHome, "config.toml")data, err := os.ReadFile(configPath)@@ -261,31 +772,6 @@ func exposeSharedCodexPluginCache(codexHome, sharedHome string) error {return nil}-// ensureDirSymlink creates a symlink dst → src for a directory.-// Unlike ensureSymlink, it creates the source directory if it doesn't exist,-// so Codex can write to it immediately.-func ensureDirSymlink(src, dst string) error {- if err := os.MkdirAll(src, 0o755); err != nil {- return fmt.Errorf("create shared dir %s: %w", src, err)- }-- // Check if dst already exists.- if fi, err := os.Lstat(dst); err == nil {- if fi.Mode()&os.ModeSymlink != 0 {- target, err := os.Readlink(dst)- if err == nil && target == src {- return nil // already correct- }- os.Remove(dst)- } else {- // Regular file/dir exists — don't overwrite.- return nil- }- }-- return createDirLink(src, dst)-}-// ensureSymlink ensures dst tracks src. If src doesn't exist, it's a no-op.// If dst is already a symlink pointing at src, it's a no-op. Otherwise — a// wrong-target symlink, a broken symlink, or a regular file left over from adiff --git a/server/internal/daemon/execenv/codex_home_link_test.go b/server/internal/daemon/execenv/codex_home_link_test.goindex f05bc8ee5f..69356249b0 100644--- a/server/internal/daemon/execenv/codex_home_link_test.go+++ b/server/internal/daemon/execenv/codex_home_link_test.go@@ -3,108 +3,9 @@ package execenvimport ("os""path/filepath"- "runtime""testing")-func assertDirLinkTarget(t *testing.T, dst, src string) {- t.Helper()-- target, err := os.Readlink(dst)- if err == nil {- if target != src {- t.Errorf("link target = %q, want %q", target, src)- }- return- }- if runtime.GOOS == "windows" {- if fi, statErr := os.Stat(dst); statErr != nil || !fi.IsDir() {- t.Fatalf("expected accessible linked directory, stat err: %v", statErr)- }- return- }- t.Fatalf("Readlink: %v", err)-}--func TestEnsureDirSymlink_CreatesLink(t *testing.T) {- t.Parallel()- dir := t.TempDir()-- src := filepath.Join(dir, "shared-sessions")- dst := filepath.Join(dir, "task-sessions")-- if err := ensureDirSymlink(src, dst); err != nil {- t.Fatalf("ensureDirSymlink: %v", err)- }-- // Source dir should be created.- if fi, err := os.Stat(src); err != nil || !fi.IsDir() {- t.Fatal("expected source directory to be created")- }-- // dst should resolve to src, or be an accessible junction on Windows.- assertDirLinkTarget(t, dst, src)-}--func TestEnsureDirSymlink_Idempotent(t *testing.T) {- t.Parallel()- dir := t.TempDir()-- src := filepath.Join(dir, "shared")- dst := filepath.Join(dir, "link")-- if err := ensureDirSymlink(src, dst); err != nil {- t.Fatalf("first call: %v", err)- }- if err := ensureDirSymlink(src, dst); err != nil {- t.Fatalf("second call: %v", err)- }-- assertDirLinkTarget(t, dst, src)-}--func TestEnsureDirSymlink_ReplacesWrongTarget(t *testing.T) {- t.Parallel()- dir := t.TempDir()-- oldSrc := filepath.Join(dir, "old")- newSrc := filepath.Join(dir, "new")- dst := filepath.Join(dir, "link")-- os.MkdirAll(oldSrc, 0o755)- if err := os.Symlink(oldSrc, dst); err != nil {- if runtime.GOOS == "windows" {- t.Skipf("directory symlink unavailable on this Windows session: %v", err)- }- t.Fatalf("seed wrong symlink: %v", err)- }-- if err := ensureDirSymlink(newSrc, dst); err != nil {- t.Fatalf("ensureDirSymlink: %v", err)- }-- assertDirLinkTarget(t, dst, newSrc)-}--func TestEnsureDirSymlink_SkipsExistingRegularDir(t *testing.T) {- t.Parallel()- dir := t.TempDir()-- src := filepath.Join(dir, "shared")- dst := filepath.Join(dir, "existing")- os.MkdirAll(dst, 0o755)-- if err := ensureDirSymlink(src, dst); err != nil {- t.Fatalf("ensureDirSymlink: %v", err)- }-- // Should not be replaced — still a regular directory.- fi, _ := os.Lstat(dst)- if fi.Mode()&os.ModeSymlink != 0 {- t.Error("expected regular dir to be preserved, not replaced with symlink")- }-}-func TestEnsureSymlink_SkipsWhenSourceMissing(t *testing.T) {t.Parallel()dir := t.TempDir()diff --git a/server/internal/daemon/execenv/codex_home_sessions_test.go b/server/internal/daemon/execenv/codex_home_sessions_test.gonew file mode 100644index 0000000000..2e482817a8--- /dev/null+++ b/server/internal/daemon/execenv/codex_home_sessions_test.go@@ -0,0 +1,790 @@+package execenv++import (+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+ "time"+)++// seedFakeRollout writes a fake Codex rollout for sessionID under+// sharedSessions/YYYY/MM/DD, mirroring Codex's real layout, and returns its path.+func seedFakeRollout(t *testing.T, sharedSessions, y, m, d, sessionID string, size int) string {+ t.Helper()+ dir := filepath.Join(sharedSessions, y, m, d)+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatalf("mkdir rollout dir: %v", err)+ }+ path := filepath.Join(dir, "rollout-"+y+"-"+m+"-"+d+"T00-00-00-"+sessionID+".jsonl")+ body := make([]byte, size)+ for i := range body {+ body[i] = 'x'+ }+ if err := os.WriteFile(path, body, 0o644); err != nil {+ t.Fatalf("write rollout: %v", err)+ }+ return path+}++// seedLegacySessionsSymlink recreates the pre-MUL-4424 layout: codex-home's+// sessions is a symlink into the shared ~/.codex/sessions. Skips on Windows+// sessions where symlink creation is unavailable.+func seedLegacySessionsSymlink(t *testing.T, codexHome, sharedSessions string) {+ t.Helper()+ if err := os.MkdirAll(codexHome, 0o755); err != nil {+ t.Fatalf("mkdir codex-home: %v", err)+ }+ if err := os.MkdirAll(sharedSessions, 0o755); err != nil {+ t.Fatalf("mkdir shared sessions: %v", err)+ }+ if err := os.Symlink(sharedSessions, filepath.Join(codexHome, "sessions")); err != nil {+ if runtime.GOOS == "windows" {+ t.Skipf("directory symlink unavailable on this Windows session: %v", err)+ }+ t.Fatalf("seed legacy sessions symlink: %v", err)+ }+}++func TestPrepareCodexSessionsDir_FreshCreatesEmptyLocalDir(t *testing.T) {+ t.Parallel()+ codexHome := filepath.Join(t.TempDir(), "codex-home")+ if err := os.MkdirAll(codexHome, 0o755); err != nil {+ t.Fatalf("mkdir codex-home: %v", err)+ }+ sharedHome := t.TempDir()++ if err := prepareCodexSessionsDir(codexHome, sharedHome, CodexHomeOptions{}, testLogger()); err != nil {+ t.Fatalf("prepareCodexSessionsDir: %v", err)+ }++ sessions := filepath.Join(codexHome, "sessions")+ fi, err := os.Lstat(sessions)+ if err != nil {+ t.Fatalf("sessions not created: %v", err)+ }+ if fi.Mode()&os.ModeSymlink != 0 {+ t.Error("fresh sessions must be a real dir, not a symlink")+ }+ if !fi.IsDir() {+ t.Error("fresh sessions must be a directory")+ }+ entries, _ := os.ReadDir(sessions)+ if len(entries) != 0 {+ t.Errorf("fresh sessions must be empty, has %d entries", len(entries))+ }+}++func TestPrepareCodexSessionsDir_RealDirIsAuthoritative(t *testing.T) {+ t.Parallel()+ codexHome := filepath.Join(t.TempDir(), "codex-home")+ sessions := filepath.Join(codexHome, "sessions", "2026", "07", "13")+ if err := os.MkdirAll(sessions, 0o755); err != nil {+ t.Fatalf("mkdir sessions: %v", err)+ }+ // A rollout the prior (isolated) run already wrote into the task-local dir.+ own := filepath.Join(sessions, "rollout-2026-07-13T00-00-00-own-session.jsonl")+ if err := os.WriteFile(own, []byte("keep me"), 0o644); err != nil {+ t.Fatalf("write own rollout: %v", err)+ }++ if err := prepareCodexSessionsDir(codexHome, t.TempDir(), CodexHomeOptions{}, testLogger()); err != nil {+ t.Fatalf("prepareCodexSessionsDir: %v", err)+ }++ // The task-local dir is authoritative — its contents must survive untouched.+ if data, err := os.ReadFile(own); err != nil || string(data) != "keep me" {+ t.Errorf("task-local rollout must be preserved, got err=%v data=%q", err, data)+ }+ fi, _ := os.Lstat(filepath.Join(codexHome, "sessions"))+ if fi.Mode()&os.ModeSymlink != 0 {+ t.Error("authoritative sessions must remain a real dir")+ }+}++func TestPrepareCodexSessionsDir_MigratesLegacySymlinkNoResume(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ codexHome := filepath.Join(root, "codex-home")+ sharedSessions := filepath.Join(root, "shared", "sessions")+ // Simulate a machine with accumulated global history.+ seedFakeRollout(t, sharedSessions, "2026", "07", "13", "other-session-a", 16)+ seedFakeRollout(t, sharedSessions, "2026", "07", "12", "other-session-b", 16)+ seedLegacySessionsSymlink(t, codexHome, sharedSessions)++ // Session-derived state that indexed the whole global history, plus an+ // unrelated per-task DB that must NOT be touched.+ writeFile(t, filepath.Join(codexHome, "state_5.sqlite"), "stale")+ writeFile(t, filepath.Join(codexHome, "state_5.sqlite-wal"), "stale")+ writeFile(t, filepath.Join(codexHome, "session_index.jsonl"), "names")+ writeFile(t, filepath.Join(codexHome, "goals_1.sqlite"), "keep")++ if err := prepareCodexSessionsDir(codexHome, filepath.Dir(sharedSessions), CodexHomeOptions{}, testLogger()); err != nil {+ t.Fatalf("prepareCodexSessionsDir: %v", err)+ }++ sessions := filepath.Join(codexHome, "sessions")+ fi, err := os.Lstat(sessions)+ if err != nil {+ t.Fatalf("sessions missing after migration: %v", err)+ }+ if fi.Mode()&os.ModeSymlink != 0 {+ t.Error("legacy symlink must be replaced with a real dir")+ }+ // No resume requested -> none of the global history is pulled in.+ entries, _ := os.ReadDir(sessions)+ if len(entries) != 0 {+ t.Errorf("non-resume migration must yield an empty sessions dir, has %d entries", len(entries))+ }+ // The global history itself must be left intact.+ if _, err := os.Stat(filepath.Join(sharedSessions, "2026", "07", "13", "rollout-2026-07-13T00-00-00-other-session-a.jsonl")); err != nil {+ t.Errorf("shared history must not be deleted: %v", err)+ }+ // Rebuildable SQLite state dropped; the thread-name index and unrelated DBs+ // are preserved.+ assertAbsent(t, filepath.Join(codexHome, "state_5.sqlite"))+ assertAbsent(t, filepath.Join(codexHome, "state_5.sqlite-wal"))+ assertPresent(t, filepath.Join(codexHome, "session_index.jsonl"))+ assertPresent(t, filepath.Join(codexHome, "goals_1.sqlite"))+}++func TestPrepareCodexSessionsDir_MigrateWithResumeRoutesThroughStore(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ sharedHome := filepath.Join(root, "shared")+ codexHome := filepath.Join(root, "codex-home")+ sharedSessions := filepath.Join(sharedHome, "sessions")+ resumeID := "019f59d9-a6aa-7a53-b173-1eccc4b4c873"+ resumeSrc := seedFakeRollout(t, sharedSessions, "2026", "07", "13", resumeID, 32)+ seedFakeRollout(t, sharedSessions, "2026", "07", "11", "unrelated-session", 32)+ seedLegacySessionsSymlink(t, codexHome, sharedSessions)+ writeFile(t, filepath.Join(codexHome, "state_5.sqlite"), "stale")++ key := filepath.Join("agent-1", "issue-1")+ err := prepareCodexSessionsDir(codexHome, sharedHome, CodexHomeOptions{ResumeSessionID: resumeID, SessionStoreKey: key}, testLogger())+ if err != nil {+ t.Fatalf("prepareCodexSessionsDir: %v", err)+ }++ // sessions/ is now a directory link to the per-issue store on the shared+ // volume — the cross-volume-safe exposure (a same-volume hard link into the+ // store + a directory link into the task home), never a task-local file copy.+ sessions := filepath.Join(codexHome, "sessions")+ assertSessionsLinkedToStore(t, sessions, codexSessionStoreDir(sharedHome, key))++ // The resume rollout is present in the task home (through the link) and+ // materialised as a zero-copy hard link from the shared history.+ if !CodexResumeRolloutPresent(codexHome, resumeID) {+ t.Fatal("resume rollout must be visible in the task CODEX_HOME after migration")+ }+ stored := filepath.Join(codexSessionStoreDir(sharedHome, key), "2026", "07", "13", filepath.Base(resumeSrc))+ assertZeroCopyLink(t, resumeSrc, stored)+ // The unrelated session must NOT be pulled in.+ if CodexResumeRolloutPresent(codexHome, "unrelated-session") {+ t.Error("unrelated shared history must not be exposed to the task")+ }+ // Stale state dropped so Codex rebuilds from the scoped store.+ assertAbsent(t, filepath.Join(codexHome, "state_5.sqlite"))+}++func TestExposeResumeRollout_NoMatchReturnsError(t *testing.T) {+ t.Parallel()+ shared := filepath.Join(t.TempDir(), "sessions")+ if err := os.MkdirAll(shared, 0o755); err != nil {+ t.Fatalf("mkdir: %v", err)+ }+ local := filepath.Join(t.TempDir(), "sessions")+ if err := os.MkdirAll(local, 0o755); err != nil {+ t.Fatalf("mkdir: %v", err)+ }+ if err := exposeResumeRollout(shared, local, "missing-session", testLogger()); err == nil {+ t.Error("expected error when no rollout matches the resume session ID")+ }+}++func TestExposeResumeRollout_LinksLargeFileWithoutCopying(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ shared := filepath.Join(root, "shared", "sessions")+ local := filepath.Join(root, "local", "sessions")+ if err := os.MkdirAll(local, 0o755); err != nil {+ t.Fatalf("mkdir local: %v", err)+ }+ // A deliberately large rollout — copying it onto the critical path is+ // exactly what MUL-4424 forbids.+ const big = 4 << 20 // 4 MiB+ src := seedFakeRollout(t, shared, "2026", "07", "13", "big-session", big)++ if err := exposeResumeRollout(shared, local, "big-session", testLogger()); err != nil {+ t.Fatalf("exposeResumeRollout: %v", err)+ }++ // Must share an inode with the source — a hard link (or symlink) — never a+ // 4 MiB copy. A hard link needs no special privilege and works on Windows+ // within a volume, so this path is exercised identically on CI.+ dst := filepath.Join(local, "2026", "07", "13", "rollout-2026-07-13T00-00-00-big-session.jsonl")+ if _, err := os.Lstat(dst); err != nil {+ t.Fatalf("exposed rollout missing: %v", err)+ }+ assertZeroCopyLink(t, src, dst)+}++func TestResetCodexSessionState_OnlyRemovesSessionDerived(t *testing.T) {+ t.Parallel()+ home := t.TempDir()+ sessionDerived := []string{+ "state_5.sqlite", "state_5.sqlite-shm", "state_5.sqlite-wal",+ "state_6.sqlite",+ }+ preserved := []string{+ // session_index.jsonl holds thread-name mappings not rebuildable from+ // rollouts, so it must survive the SQLite-only reset.+ "session_index.jsonl",+ "goals_1.sqlite", "logs_2.sqlite", "memories_1.sqlite",+ "config.toml", "auth.json", "models_cache.json",+ }+ for _, n := range append(append([]string{}, sessionDerived...), preserved...) {+ writeFile(t, filepath.Join(home, n), "x")+ }++ resetCodexSessionState(home, testLogger())++ for _, n := range sessionDerived {+ assertAbsent(t, filepath.Join(home, n))+ }+ for _, n := range preserved {+ assertPresent(t, filepath.Join(home, n))+ }+}++func TestPrepareCodexSessionsDir_MigratePreservesSessionIndex(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ codexHome := filepath.Join(root, "codex-home")+ sharedSessions := filepath.Join(root, "shared", "sessions")+ seedFakeRollout(t, sharedSessions, "2026", "07", "13", "some-session", 16)+ seedLegacySessionsSymlink(t, codexHome, sharedSessions)+ writeFile(t, filepath.Join(codexHome, "state_5.sqlite"), "stale")+ writeFile(t, filepath.Join(codexHome, "session_index.jsonl"), `{"id":"x","thread_name":"My thread"}`)++ if err := prepareCodexSessionsDir(codexHome, filepath.Dir(sharedSessions), CodexHomeOptions{}, testLogger()); err != nil {+ t.Fatalf("prepareCodexSessionsDir: %v", err)+ }++ // SQLite state is rebuilt; the thread-name index (not rebuildable from+ // rollouts) is preserved.+ assertAbsent(t, filepath.Join(codexHome, "state_5.sqlite"))+ assertPresent(t, filepath.Join(codexHome, "session_index.jsonl"))+ if data, _ := os.ReadFile(filepath.Join(codexHome, "session_index.jsonl")); string(data) != `{"id":"x","thread_name":"My thread"}` {+ t.Errorf("session_index.jsonl content changed: %q", data)+ }+}++func TestExposeResumeRollout_FindsCompressedAndFlatLayouts(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ shared := filepath.Join(root, "shared", "sessions")+ local := filepath.Join(root, "local", "sessions")+ if err := os.MkdirAll(local, 0o755); err != nil {+ t.Fatalf("mkdir local: %v", err)+ }+ // Codex background-compresses cold rollouts to .jsonl.zst and also supports+ // a flat layout (rollout directly under sessions/). Both are legit history.+ compressed := seedRolloutAt(t, filepath.Join(shared, "2026", "07", "13", "rollout-2026-07-13T00-00-00-zst-session.jsonl.zst"), 8)+ flat := seedRolloutAt(t, filepath.Join(shared, "rollout-2026-07-13T00-00-00-flat-session.jsonl"), 8)++ for _, tc := range []struct {+ id, src, rel string+ }{+ {"zst-session", compressed, filepath.Join("2026", "07", "13", "rollout-2026-07-13T00-00-00-zst-session.jsonl.zst")},+ {"flat-session", flat, "rollout-2026-07-13T00-00-00-flat-session.jsonl"},+ } {+ if err := exposeResumeRollout(shared, local, tc.id, testLogger()); err != nil {+ t.Fatalf("expose %s: %v", tc.id, err)+ }+ assertZeroCopyLink(t, tc.src, filepath.Join(local, tc.rel))+ }+}++func TestCodexResumeRolloutPresent(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ codexHome := filepath.Join(root, "codex-home")+ sessions := filepath.Join(codexHome, "sessions")+ seedRolloutAt(t, filepath.Join(sessions, "2026", "07", "13", "rollout-2026-07-13T00-00-00-nested.jsonl"), 8)+ seedRolloutAt(t, filepath.Join(sessions, "rollout-2026-07-13T00-00-00-flat.jsonl.zst"), 8)++ for _, id := range []string{"nested", "flat"} {+ if !CodexResumeRolloutPresent(codexHome, id) {+ t.Errorf("expected rollout %q to be found", id)+ }+ }+ if CodexResumeRolloutPresent(codexHome, "absent") {+ t.Error("absent session must not be reported present")+ }+ if CodexResumeRolloutPresent("", "nested") || CodexResumeRolloutPresent(codexHome, "") {+ t.Error("empty codexHome/sessionID must be reported absent")+ }+}++func TestPrepareCodexSessionsDir_LocalDirectoryUsesPerIssueStore(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ codexHome := filepath.Join(root, "codex-home")+ if err := os.MkdirAll(codexHome, 0o755); err != nil {+ t.Fatalf("mkdir codex-home: %v", err)+ }+ sharedHome := filepath.Join(root, "shared")+ // A machine with accumulated global history that must NOT be exposed to the task.+ seedFakeRollout(t, filepath.Join(sharedHome, "sessions"), "2026", "07", "13", "other-a", 16)+ seedFakeRollout(t, filepath.Join(sharedHome, "sessions"), "2026", "07", "12", "other-b", 16)++ key := filepath.Join("agent-1", "issue-1")+ if err := prepareCodexSessionsDir(codexHome, sharedHome, CodexHomeOptions{IsLocalDirectory: true, SessionStoreKey: key}, testLogger()); err != nil {+ t.Fatalf("prepareCodexSessionsDir: %v", err)+ }++ // sessions/ links the per-issue store, not the shared ~/.codex/sessions.+ sessions := filepath.Join(codexHome, "sessions")+ assertSessionsLinkedToStore(t, sessions, codexSessionStoreDir(sharedHome, key))+ // The store holds only this issue's history — the machine's global rollouts+ // are invisible, so `initialize` never enumerates them (the MUL-4424 stall).+ entries, _ := os.ReadDir(sessions)+ if len(entries) != 0 {+ t.Errorf("per-issue store must start empty, has %d entries (whole-history leak?)", len(entries))+ }+ if CodexResumeRolloutPresent(codexHome, "other-a") {+ t.Error("machine-global history must not be visible to a local_directory task")+ }+}++// With no stable per-issue key (e.g. a non-issue task), a local_directory task+// must NOT collapse back to exposing the whole shared history — it falls back to+// an empty local dir.+func TestPrepareCodexSessionsDir_LocalDirectoryNoKeyFallsBackToEmptyDir(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ codexHome := filepath.Join(root, "codex-home")+ if err := os.MkdirAll(codexHome, 0o755); err != nil {+ t.Fatalf("mkdir codex-home: %v", err)+ }+ sharedHome := filepath.Join(root, "shared")+ seedFakeRollout(t, filepath.Join(sharedHome, "sessions"), "2026", "07", "13", "other", 16)++ if err := prepareCodexSessionsDir(codexHome, sharedHome, CodexHomeOptions{IsLocalDirectory: true}, testLogger()); err != nil {+ t.Fatalf("prepareCodexSessionsDir: %v", err)+ }+ sessions := filepath.Join(codexHome, "sessions")+ fi, err := os.Lstat(sessions)+ if err != nil {+ t.Fatalf("sessions not created: %v", err)+ }+ if fi.Mode()&os.ModeSymlink != 0 {+ t.Error("no-key local_directory must not link the shared history")+ }+ if CodexResumeRolloutPresent(codexHome, "other") {+ t.Error("machine-global history must not be visible")+ }+}++// Two consecutive local_directory tasks share one project dir but get a fresh+// codex-home each (the daemon never reuses their workdir). The second run must+// still see the first run's rollout via the per-issue store — this is the+// regression Elon's review flagged.+func TestPrepareCodexSessionsDir_LocalDirectoryResumeAcrossTaskIDs(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ sharedHome := filepath.Join(root, "shared")+ sessionID := "019f59d9-a6aa-7a53-b173-1eccc4b4c873"+ key := filepath.Join("agent-1", "issue-1")++ // Round 1: a fresh per-task codex-home links the per-issue store.+ home1 := filepath.Join(root, "task-1", "codex-home")+ if err := os.MkdirAll(home1, 0o755); err != nil {+ t.Fatalf("mkdir home1: %v", err)+ }+ if err := prepareCodexSessionsDir(home1, sharedHome, CodexHomeOptions{IsLocalDirectory: true, SessionStoreKey: key}, testLogger()); err != nil {+ t.Fatalf("round 1 prepare: %v", err)+ }+ // Codex writes the round-1 rollout through the link into the store.+ seedRolloutAt(t, filepath.Join(home1, "sessions", "2026", "07", "13", "rollout-2026-07-13T00-00-00-"+sessionID+".jsonl"), 32)++ // Round 2: a brand-new task ID → brand-new codex-home, same issue key.+ home2 := filepath.Join(root, "task-2", "codex-home")+ if err := os.MkdirAll(home2, 0o755); err != nil {+ t.Fatalf("mkdir home2: %v", err)+ }+ if err := prepareCodexSessionsDir(home2, sharedHome, CodexHomeOptions{IsLocalDirectory: true, SessionStoreKey: key, ResumeSessionID: sessionID}, testLogger()); err != nil {+ t.Fatalf("round 2 prepare: %v", err)+ }++ // The round-2 home must resolve the round-1 rollout through the shared store —+ // otherwise the daemon would silently drop the conversation.+ if !CodexResumeRolloutPresent(home2, sessionID) {+ t.Fatal("round-2 local_directory task cannot see round-1 rollout — context would be silently lost")+ }+}++// A managed home migrated on a prior reuse already links the per-issue store; a+// subsequent reuse must treat that link as authoritative and not re-migrate it.+func TestPrepareCodexSessionsDir_ReusedStoreLinkIsAuthoritative(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ sharedHome := filepath.Join(root, "shared")+ codexHome := filepath.Join(root, "codex-home")+ if err := os.MkdirAll(codexHome, 0o755); err != nil {+ t.Fatalf("mkdir codex-home: %v", err)+ }+ key := filepath.Join("agent-1", "issue-1")+ storeDir := codexSessionStoreDir(sharedHome, key)+ if err := os.MkdirAll(storeDir, 0o755); err != nil {+ t.Fatalf("mkdir store: %v", err)+ }+ if err := os.Symlink(storeDir, filepath.Join(codexHome, "sessions")); err != nil {+ if runtime.GOOS == "windows" {+ t.Skipf("directory symlink unavailable on this Windows session: %v", err)+ }+ t.Fatalf("seed store link: %v", err)+ }+ sessionID := "019f59d9-a6aa-7a53-b173-1eccc4b4c873"+ seedRolloutAt(t, filepath.Join(storeDir, "2026", "07", "13", "rollout-2026-07-13T00-00-00-"+sessionID+".jsonl"), 16)++ if err := prepareCodexSessionsDir(codexHome, sharedHome, CodexHomeOptions{SessionStoreKey: key, ResumeSessionID: sessionID}, testLogger()); err != nil {+ t.Fatalf("prepareCodexSessionsDir: %v", err)+ }++ assertSessionsLinkedToStore(t, filepath.Join(codexHome, "sessions"), storeDir)+ if !CodexResumeRolloutPresent(codexHome, sessionID) {+ t.Error("existing store rollout must remain resumable after reuse")+ }+}++// PruneCodexSessionStores must reclaim per-issue stores idle past retention,+// keep recently-touched ones (active/resumable tasks), isolate issues from one+// another, and be disable-able — the data lifecycle Elon's review required so+// the persistent store can't grow forever (MUL-4424).+func TestPruneCodexSessionStores(t *testing.T) {+ home := t.TempDir()+ t.Setenv("CODEX_HOME", home)+ // Stores live under the profile namespace; the default profile is "".+ storeRoot := filepath.Join(home, codexSessionStoreRoot, codexSessionStoreNamespace(""))++ freshStore := filepath.Join(storeRoot, "agent-1", "issue-fresh")+ staleStore := filepath.Join(storeRoot, "agent-1", "issue-stale")+ otherStore := filepath.Join(storeRoot, "agent-2", "issue-x")+ seedRolloutAt(t, filepath.Join(freshStore, "2026", "07", "14", "rollout-2026-07-14T00-00-00-a.jsonl"), 16)+ seedRolloutAt(t, filepath.Join(staleStore, "2026", "06", "01", "rollout-2026-06-01T00-00-00-b.jsonl"), 16)+ seedRolloutAt(t, filepath.Join(otherStore, "2026", "07", "14", "rollout-2026-07-14T00-00-00-c.jsonl"), 16)++ now := time.Now()+ retention := 14 * 24 * time.Hour+ // Age only the stale store's whole tree well past retention.+ chtimesTree(t, staleStore, now.Add(-30*24*time.Hour))++ removed, bytes := PruneCodexSessionStores("", retention, now, nil, testLogger())+ if removed != 1 {+ t.Fatalf("removed = %d, want 1 (only the store idle past retention)", removed)+ }+ if bytes <= 0 {+ t.Errorf("bytesFreed = %d, want > 0", bytes)+ }+ // The stale store is gone; the fresh one and the other agent's store survive+ // (per-issue isolation), and agent-1 stays because issue-fresh remains.+ assertAbsent(t, staleStore)+ assertPresent(t, freshStore)+ assertPresent(t, otherStore)+ assertPresent(t, filepath.Join(storeRoot, "agent-1"))++ // retention <= 0 disables pruning even for an aged store.+ chtimesTree(t, freshStore, now.Add(-30*24*time.Hour))+ if removed, _ := PruneCodexSessionStores("", 0, now, nil, testLogger()); removed != 0 {+ t.Errorf("retention<=0 must disable pruning, removed=%d", removed)+ }+ assertPresent(t, freshStore)+}++// TestPruneCodexSessionStores_ReopenedStoreNotReclaimed is Elon's blocker repro:+// a store idle past the TTL that a user reopens must NOT be reclaimed by a GC+// cycle that fires before the resumed turn writes its first rollout — mounting+// the store refreshes its activity (MUL-4424).+func TestPruneCodexSessionStores_ReopenedStoreNotReclaimed(t *testing.T) {+ home := t.TempDir()+ t.Setenv("CODEX_HOME", home)+ storeDir := codexSessionStoreDir(home, codexSessionStoreKey("", "agent-1", "issue-old"))+ sessionID := "019f59d9-a6aa-7a53-b173-1eccc4b4c873"+ // A long-idle (30-day) store that still holds a resumable rollout.+ seedRolloutAt(t, filepath.Join(storeDir, "2026", "06", "01", "rollout-2026-06-01T00-00-00-"+sessionID+".jsonl"), 16)+ chtimesTree(t, storeDir, time.Now().Add(-30*24*time.Hour))++ // The user reopens the issue: a fresh task home remounts the store to resume.+ codexHome := filepath.Join(home, "task", "codex-home")+ if err := os.MkdirAll(codexHome, 0o755); err != nil {+ t.Fatalf("mkdir codex-home: %v", err)+ }+ if err := linkCodexSessionsToStore(filepath.Join(codexHome, "sessions"), storeDir, filepath.Join(home, "sessions"), sessionID, testLogger()); err != nil {+ t.Fatalf("linkCodexSessionsToStore: %v", err)+ }+ if !CodexResumeRolloutPresent(codexHome, sessionID) {+ t.Fatal("resume rollout must be visible after remount")+ }++ // A GC cycle now — before the resumed turn writes anything — must keep it.+ if removed, _ := PruneCodexSessionStores("", 14*24*time.Hour, time.Now(), nil, testLogger()); removed != 0 {+ t.Fatalf("removed = %d, want 0 (a just-reopened store must survive GC)", removed)+ }+ assertPresent(t, storeDir)+ if !CodexResumeRolloutPresent(codexHome, sessionID) {+ t.Error("resume rollout must still be present after GC")+ }+}++// TestPruneCodexSessionStores_ActiveStoreNotReclaimed proves the reservation+// guard closes the stat->remove race: a store idle on disk that reserve refuses+// (a live task holds it) is skipped, then reclaimed once reservable. The+// daemon's atomic reserve-vs-mark protocol is unit-tested separately.+func TestPruneCodexSessionStores_ActiveStoreNotReclaimed(t *testing.T) {+ home := t.TempDir()+ t.Setenv("CODEX_HOME", home)+ storeDir := codexSessionStoreDir(home, codexSessionStoreKey("", "agent-1", "issue-active"))+ seedRolloutAt(t, filepath.Join(storeDir, "2026", "06", "01", "rollout-2026-06-01T00-00-00-x.jsonl"), 16)+ // Idle past retention on disk (no remount refresh), but currently in use.+ chtimesTree(t, storeDir, time.Now().Add(-30*24*time.Hour))++ // reserve refuses the in-use store (ok=false) and allows anything else.+ held := func(p string) (func(), bool) {+ if sameCodexPath(p, storeDir) {+ return nil, false+ }+ return func() {}, true+ }+ if removed, _ := PruneCodexSessionStores("", 14*24*time.Hour, time.Now(), held, testLogger()); removed != 0 {+ t.Fatalf("removed = %d, want 0 (a reserved/in-use store must never be reclaimed)", removed)+ }+ assertPresent(t, storeDir)++ // Once reservable, the same idle store is reclaimed.+ if removed, _ := PruneCodexSessionStores("", 14*24*time.Hour, time.Now(), nil, testLogger()); removed != 1 {+ t.Fatalf("removed = %d, want 1 (idle store reclaimed when reservable)", removed)+ }+ assertAbsent(t, storeDir)+}++// TestPruneCodexSessionStores_IsolatesProfiles is Elon's cross-profile blocker:+// two profile-daemons share one ~/.codex, so one daemon's GC must never reclaim+// another profile's store — the in-process reservation guard cannot span+// processes, but the per-profile namespace makes their store trees disjoint so a+// GC only ever sees, and reclaims, its own (MUL-4424).+func TestPruneCodexSessionStores_IsolatesProfiles(t *testing.T) {+ home := t.TempDir()+ t.Setenv("CODEX_HOME", home)+ // A store owned by the "staging" profile daemon, idle past retention.+ stagingStore := codexSessionStoreDir(home, codexSessionStoreKey("staging", "agent-1", "issue-1"))+ seedRolloutAt(t, filepath.Join(stagingStore, "2026", "06", "01", "rollout-2026-06-01T00-00-00-s.jsonl"), 16)+ chtimesTree(t, stagingStore, time.Now().Add(-30*24*time.Hour))++ // The production (default) daemon prunes — it must NOT touch staging's store,+ // even with no guard, because staging is a different namespace it never scans.+ if removed, _ := PruneCodexSessionStores("", 14*24*time.Hour, time.Now(), nil, testLogger()); removed != 0 {+ t.Fatalf("removed = %d, want 0 — another profile's store must be out of scope", removed)+ }+ assertPresent(t, stagingStore)++ // The staging daemon prunes its own namespace → reclaims its idle store.+ if removed, _ := PruneCodexSessionStores("staging", 14*24*time.Hour, time.Now(), nil, testLogger()); removed != 1 {+ t.Fatalf("removed = %d, want 1 — the owning profile reclaims its idle store", removed)+ }+ assertAbsent(t, stagingStore)+}++// TestCodexSessionStoreNamespaceInjective guards the profile->namespace map+// against the collisions Elon flagged: the CLI treats these profile pairs as+// distinct daemons, so they must never share a store namespace (a lossy+// character-dropping scheme merged them). MUL-4424.+func TestCodexSessionStoreNamespaceInjective(t *testing.T) {+ t.Parallel()+ pairs := [][2]string{+ {"", "default"}, // empty (default) vs a profile literally named "default"+ {"staging.prod", "stagingprod"}, // punctuation must not be dropped into a collision+ {"a-b", "a_b"},+ {"prod", "Prod"},+ {"p_default", "default"}, // an encoded-looking name must not alias another+ }+ for _, p := range pairs {+ if a, b := codexSessionStoreNamespace(p[0]), codexSessionStoreNamespace(p[1]); a == b {+ t.Errorf("profiles %q and %q collide in namespace %q", p[0], p[1], a)+ }+ }+ // Deterministic for a fixed profile.+ if codexSessionStoreNamespace("staging") != codexSessionStoreNamespace("staging") {+ t.Error("namespace must be deterministic for a fixed profile")+ }+}++// TestCodexSessionStoreNamespace_FitsDirectorySegment guards Elon's round-8+// blocker: a profile the CLI can persist as its own config-dir segment (up to+// the ~255-byte filesystem limit) must yield a namespace that also fits one+// segment and is creatable — a length-expanding encoding (full hex) overflowed+// at 127 bytes. MUL-4424.+func TestCodexSessionStoreNamespace_FitsDirectorySegment(t *testing.T) {+ t.Parallel()+ base := t.TempDir()+ for _, profile := range []string{"", "staging", strings.Repeat("a", 127), strings.Repeat("z", 255)} {+ ns := codexSessionStoreNamespace(profile)+ if len(ns) > 255 {+ t.Errorf("profile (len %d) -> namespace (len %d) exceeds the 255-byte single-segment limit", len(profile), len(ns))+ }+ if err := os.MkdirAll(filepath.Join(base, ns), 0o755); err != nil {+ t.Errorf("namespace for profile (len %d) could not be created: %v", len(profile), err)+ }+ }+}++// TestPruneCodexSessionStores_NoCrossProfileCollision proves the injective+// namespace holds end-to-end: profiles the CLI treats as distinct never reclaim+// each other's stores, including the "" vs "default" and punctuation cases that+// a lossy sanitizer collapsed (Elon's round-7 repro). MUL-4424.+func TestPruneCodexSessionStores_NoCrossProfileCollision(t *testing.T) {+ for _, pair := range [][2]string{{"", "default"}, {"staging.prod", "stagingprod"}} {+ home := t.TempDir()+ t.Setenv("CODEX_HOME", home)+ a, b := pair[0], pair[1]+ storeA := codexSessionStoreDir(home, codexSessionStoreKey(a, "agent", "issue"))+ storeB := codexSessionStoreDir(home, codexSessionStoreKey(b, "agent", "issue"))+ seedRolloutAt(t, filepath.Join(storeA, "2026", "06", "01", "rollout-2026-06-01T00-00-00-a.jsonl"), 16)+ seedRolloutAt(t, filepath.Join(storeB, "2026", "06", "01", "rollout-2026-06-01T00-00-00-b.jsonl"), 16)+ chtimesTree(t, storeA, time.Now().Add(-30*24*time.Hour))+ chtimesTree(t, storeB, time.Now().Add(-30*24*time.Hour))++ // Pruning profile a reclaims a's store only — b's must survive.+ if removed, _ := PruneCodexSessionStores(a, 14*24*time.Hour, time.Now(), nil, testLogger()); removed != 1 {+ t.Fatalf("prune %q removed=%d, want 1", a, removed)+ }+ assertAbsent(t, storeA)+ assertPresent(t, storeB)++ // Then pruning profile b reclaims b's store.+ if removed, _ := PruneCodexSessionStores(b, 14*24*time.Hour, time.Now(), nil, testLogger()); removed != 1 {+ t.Fatalf("prune %q removed=%d, want 1", b, removed)+ }+ assertAbsent(t, storeB)+ }+}++// TestPruneCodexSessionStores_RemovesEmptyAgentDir confirms an agent directory+// is cleaned up once its last issue store ages out, so the tree doesn't leave+// empty <agent>/ shells behind.+func TestPruneCodexSessionStores_RemovesEmptyAgentDir(t *testing.T) {+ home := t.TempDir()+ t.Setenv("CODEX_HOME", home)+ storeRoot := filepath.Join(home, codexSessionStoreRoot, codexSessionStoreNamespace(""))+ onlyStore := filepath.Join(storeRoot, "agent-lonely", "issue-1")+ seedRolloutAt(t, filepath.Join(onlyStore, "2026", "06", "01", "rollout-2026-06-01T00-00-00-x.jsonl"), 16)++ now := time.Now()+ chtimesTree(t, onlyStore, now.Add(-30*24*time.Hour))+ if removed, _ := PruneCodexSessionStores("", 14*24*time.Hour, now, nil, testLogger()); removed != 1 {+ t.Fatalf("removed = %d, want 1", removed)+ }+ assertAbsent(t, filepath.Join(storeRoot, "agent-lonely"))+}++// chtimesTree sets the atime/mtime of every entry under root to ts.+func chtimesTree(t *testing.T, root string, ts time.Time) {+ t.Helper()+ err := filepath.WalkDir(root, func(path string, _ os.DirEntry, err error) error {+ if err != nil {+ return err+ }+ return os.Chtimes(path, ts, ts)+ })+ if err != nil {+ t.Fatalf("chtimes tree %s: %v", root, err)+ }+}++func seedRolloutAt(t *testing.T, path string, size int) string {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatalf("mkdir rollout dir: %v", err)+ }+ body := make([]byte, size)+ for i := range body {+ body[i] = 'x'+ }+ if err := os.WriteFile(path, body, 0o644); err != nil {+ t.Fatalf("write rollout: %v", err)+ }+ return path+}++// assertSessionsLinkedToStore verifies codex-home/sessions is a directory link+// that resolves to the per-issue store (storeDir), i.e. the task home reaches+// only that issue's history and not the machine-global ~/.codex/sessions.+func assertSessionsLinkedToStore(t *testing.T, sessions, storeDir string) {+ t.Helper()+ fi, err := os.Lstat(sessions)+ if err != nil {+ t.Fatalf("sessions link missing: %v", err)+ }+ if runtime.GOOS != "windows" {+ if fi.Mode()&os.ModeSymlink == 0 {+ t.Fatalf("sessions must link the per-issue store, got mode %v", fi.Mode())+ }+ if target, _ := os.Readlink(sessions); filepath.Clean(target) != filepath.Clean(storeDir) {+ t.Errorf("sessions link target = %q, want store %q", target, storeDir)+ }+ }+ realSessions, err := filepath.EvalSymlinks(sessions)+ if err != nil {+ t.Fatalf("eval sessions link: %v", err)+ }+ realStore, err := filepath.EvalSymlinks(storeDir)+ if err != nil {+ t.Fatalf("eval store: %v", err)+ }+ if realSessions != realStore {+ t.Errorf("sessions resolves to %q, want store %q", realSessions, realStore)+ }+}++// assertZeroCopyLink verifies dst resolves to the same inode as src — a hard+// link or symlink, never a byte copy.+func assertZeroCopyLink(t *testing.T, src, dst string) {+ t.Helper()+ si, err := os.Stat(src)+ if err != nil {+ t.Fatalf("stat src %s: %v", src, err)+ }+ di, err := os.Stat(dst)+ if err != nil {+ t.Fatalf("stat dst %s: %v", dst, err)+ }+ if !os.SameFile(si, di) {+ t.Errorf("%s is a copy of %s, expected a zero-copy hard/sym link", dst, src)+ }+}++func writeFile(t *testing.T, path, content string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatalf("mkdir for %s: %v", path, err)+ }+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {+ t.Fatalf("write %s: %v", path, err)+ }+}++func assertAbsent(t *testing.T, path string) {+ t.Helper()+ if _, err := os.Lstat(path); !os.IsNotExist(err) {+ t.Errorf("expected %s to be removed, err=%v", filepath.Base(path), err)+ }+}++func assertPresent(t *testing.T, path string) {+ t.Helper()+ if _, err := os.Lstat(path); err != nil {+ t.Errorf("expected %s to be preserved: %v", filepath.Base(path), err)+ }+}diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex 6aa2a91c90..14805edbc4 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -39,9 +39,13 @@ type PrepareParams struct {WorkspaceID string // workspace UUID — tasks are grouped under thisTaskID string // task UUID — used for directory nameAgentName string // for git branch naming only- Provider string // agent provider (determines runtime config and skill injection paths)- CodexVersion string // detected Codex CLI version (only used when Provider == "codex")- OpenclawBin string // resolved openclaw CLI path (only used when Provider == "openclaw"); empty = look up on PATH+ // Profile is the daemon's profile name (empty = default). It namespaces the+ // per-issue Codex session store so a second profile-daemon sharing the same+ // ~/.codex cannot see or GC this daemon's stores (MUL-4424).+ Profile string+ Provider string // agent provider (determines runtime config and skill injection paths)+ CodexVersion string // detected Codex CLI version (only used when Provider == "codex")+ OpenclawBin string // resolved openclaw CLI path (only used when Provider == "openclaw"); empty = look up on PATH// McpConfig is the agent's saved `mcp_config` JSON, forwarded to the// provider-specific config preparer when that provider materialises MCP// via a per-task config file. Cursor and OpenClaw consume it here; other@@ -93,29 +97,37 @@ type TaskContextForEnv struct {// telling it "one comment" and the other "one per thread". Same-thread// follow-ups collapse to a single group upstream, so this stays empty and// the single-parent path is used (no duplicate replies).- CommentReplyTargets []ThreadReplyTarget- NewCommentCount int // issue-wide comments since this agent's last run (excludes its own and the injected trigger)- NewCommentsSince string // RFC3339 anchor (last run's started_at) the count is measured from; empty on cold start- PriorSessionResumed bool // true when the daemon will resume an existing provider session for this task- AgentID string // unique ID of the dispatched agent- AgentName string- AgentInstructions string // agent identity/persona instructions, injected into CLAUDE.md- AgentSkills []SkillContextForEnv- Repos []RepoContextForEnv // workspace repos available for checkout- ProjectID string // issue's project, when present- ProjectTitle string // human-readable project title- ProjectDescription string // durable project-level context, rendered into the brief's Project Context section- ProjectResources []ProjectResourceForEnv // resources attached to the project- ChatSessionID string // non-empty for chat tasks- AutopilotRunID string // non-empty for autopilot run_only tasks- AutopilotID string- AutopilotTitle string- AutopilotDescription string- AutopilotSource string- AutopilotTriggerPayload string- QuickCreatePrompt string // non-empty for quick-create tasks- HandoffNote string // assignment handoff instruction; rendered into issue_context.md (MUL-3375)- IsSquadLeader bool // true when the agent is acting as a squad leader (may exit silently on no_action)+ CommentReplyTargets []ThreadReplyTarget+ NewCommentCount int // issue-wide comments since this agent's last run (excludes its own and the injected trigger)+ NewCommentsSince string // RFC3339 anchor (last run's started_at) the count is measured from; empty on cold start+ PriorSessionResumed bool // true when the daemon will resume an existing provider session for this task+ // PriorSessionResumeUnavailable is true when this task carried a prior+ // session the daemon expected to resume but could NOT (the reused workdir was+ // gone, or the Codex rollout was not present in the task CODEX_HOME). The+ // brief surfaces this so the agent tells the user its previous conversation+ // context is gone and this run starts fresh — turning a silent context loss+ // into a user-visible one (MUL-4424). Distinct from an ordinary cold start,+ // which never had a prior session to lose.+ PriorSessionResumeUnavailable bool+ AgentID string // unique ID of the dispatched agent+ AgentName string+ AgentInstructions string // agent identity/persona instructions, injected into CLAUDE.md+ AgentSkills []SkillContextForEnv+ Repos []RepoContextForEnv // workspace repos available for checkout+ ProjectID string // issue's project, when present+ ProjectTitle string // human-readable project title+ ProjectDescription string // durable project-level context, rendered into the brief's Project Context section+ ProjectResources []ProjectResourceForEnv // resources attached to the project+ ChatSessionID string // non-empty for chat tasks+ AutopilotRunID string // non-empty for autopilot run_only tasks+ AutopilotID string+ AutopilotTitle string+ AutopilotDescription string+ AutopilotSource string+ AutopilotTriggerPayload string+ QuickCreatePrompt string // non-empty for quick-create tasks+ HandoffNote string // assignment handoff instruction; rendered into issue_context.md (MUL-3375)+ IsSquadLeader bool // true when the agent is acting as a squad leader (may exit silently on no_action)// WorkspaceContext is the workspace-level system prompt (workspace.context// in the DB). Rendered into the brief as `## Workspace Context` when// non-empty so every agent in the workspace sees the same shared context,@@ -288,7 +300,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {// For Codex, set up a per-task CODEX_HOME seeded from ~/.codex/ with skills.if params.Provider == "codex" {codexHome := filepath.Join(envRoot, "codex-home")- if err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{CodexVersion: params.CodexVersion}, logger); err != nil {+ if err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{CodexVersion: params.CodexVersion, IsLocalDirectory: params.LocalWorkDir != "", SessionStoreKey: codexSessionStoreKey(params.Profile, params.Task.AgentID, params.Task.IssueID)}, logger); err != nil {return nil, fmt.Errorf("execenv: prepare codex-home: %w", err)}if err := hydrateCodexSkills(codexHome, params.Task.AgentSkills, logger); err != nil {@@ -363,7 +375,14 @@ type ReuseParams struct {WorkDir stringProvider stringCodexVersion string // only used when Provider == "codex"- OpenclawBin string // only used when Provider == "openclaw"; empty = PATH lookup+ // ResumeSessionID is the prior Codex thread/session ID this reused task+ // intends to resume, when any. Only consulted when Provider == "codex" and+ // only used while migrating a legacy per-task home whose sessions/ still+ // symlinks the shared ~/.codex/sessions — the single rollout for this ID is+ // exposed into the new task-local sessions dir so thread/resume still finds+ // it. Empty means a fresh thread. See prepareCodexSessionsDir (MUL-4424).+ ResumeSessionID string+ OpenclawBin string // only used when Provider == "openclaw"; empty = PATH lookup// McpConfig is the agent's saved `mcp_config` JSON. Reused on reuse so a// freshly-saved managed set re-materialises into the wrapper before the// task starts — without this a stale wrapper from a prior run would keep@@ -374,6 +393,10 @@ type ReuseParams struct {// OpenclawGateway is the per-task Gateway pin re-applied on reuse so the// agent picks up any runtime_config changes saved since the prior run.OpenclawGateway OpenclawGatewayPin+ // Profile is the daemon's profile name (empty = default), mirroring+ // PrepareParams.Profile so a reused task keys its per-issue Codex session+ // store into the same profile namespace (MUL-4424).+ Profile string// LocalDirectory is true when the reused WorkDir is a user-supplied// directory (the local_directory flow). The flag is propagated into// the returned Environment so downstream callers (notably the GC@@ -481,7 +504,7 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {// config (especially sandbox/network access) is up to date.if params.Provider == "codex" {codexHome := filepath.Join(env.RootDir, "codex-home")- if err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{CodexVersion: params.CodexVersion}, logger); err != nil {+ if err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{CodexVersion: params.CodexVersion, ResumeSessionID: params.ResumeSessionID, IsLocalDirectory: params.LocalDirectory, SessionStoreKey: codexSessionStoreKey(params.Profile, params.Task.AgentID, params.Task.IssueID)}, logger); err != nil {logger.Warn("execenv: refresh codex-home failed", "error", err)} else {env.CodexHome = codexHomediff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex bb59aa6945..0176907945 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -1938,25 +1938,18 @@ func TestPrepareCodexHomeSeedsFromShared(t *testing.T) {t.Fatalf("prepareCodexHome failed: %v", err)}- // sessions should be a symlink to the shared sessions dir.+ // sessions should be a real, task-local directory — NOT a symlink into the+ // shared home (MUL-4424). A fresh home gets an empty local dir.sessionsPath := filepath.Join(codexHome, "sessions")fi, err := os.Lstat(sessionsPath)if err != nil {t.Fatalf("sessions not found: %v", err)}- sessionsIsLink := fi.Mode()&os.ModeSymlink != 0- if !sessionsIsLink && runtime.GOOS != "windows" {- t.Error("sessions should be a symlink")+ if fi.Mode()&os.ModeSymlink != 0 {+ t.Error("sessions should be a task-local directory, not a symlink into the shared home")}- if sessionsIsLink {- sessTarget, _ := os.Readlink(sessionsPath)- if sessTarget != filepath.Join(sharedHome, "sessions") {- t.Errorf("sessions symlink target = %q, want %q", sessTarget, filepath.Join(sharedHome, "sessions"))- }- } else if fi.IsDir() {- if _, err := os.Stat(sessionsPath); err != nil {- t.Fatalf("sessions link target should be accessible: %v", err)- }+ if !fi.IsDir() {+ t.Error("sessions should be a directory")}// auth.json should be a symlink.@@ -2132,7 +2125,7 @@ func TestPrepareCodexHomeSkipsMissingFiles(t *testing.T) {t.Fatalf("prepareCodexHome failed: %v", err)}- // Directory should contain sessions symlink + auto-generated config.toml.+ // Directory should contain a task-local sessions dir + auto-generated config.toml.entries, err := os.ReadDir(codexHome)if err != nil {t.Fatalf("failed to read codex-home: %v", err)@@ -2142,7 +2135,7 @@ func TestPrepareCodexHomeSkipsMissingFiles(t *testing.T) {entryNames[e.Name()] = true}if !entryNames["sessions"] {- t.Error("expected sessions symlink")+ t.Error("expected sessions directory")}if !entryNames["config.toml"] {t.Error("expected config.toml (auto-generated for network access)")@@ -2155,14 +2148,18 @@ func TestPrepareCodexHomeSkipsMissingFiles(t *testing.T) {t.Errorf("unexpected entry: %s", name)}}- // sessions should be a symlink to the shared sessions dir.+ // sessions should be a real, task-local directory — not a symlink into the+ // shared home (MUL-4424).sessionsPath := filepath.Join(codexHome, "sessions")fi, err := os.Lstat(sessionsPath)if err != nil {t.Fatalf("sessions not found: %v", err)}- if fi.Mode()&os.ModeSymlink == 0 && runtime.GOOS != "windows" {- t.Error("sessions should be a symlink")+ if fi.Mode()&os.ModeSymlink != 0 {+ t.Error("sessions should be a task-local directory, not a symlink")+ }+ if !fi.IsDir() {+ t.Error("sessions should be a directory")}if _, err := os.Stat(filepath.Join(codexHome, "plugins", "cache")); err != nil {t.Fatalf("missing shared plugin cache exposure should still be tolerated and created: %v", err)diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex fcf271d638..a07b58f576 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -304,6 +304,19 @@ func writeInstructionPrecedence(b *strings.Builder) {b.WriteString("Never treat this runtime workflow as permission to change issue status, investigate, implement, or otherwise act beyond your Agent Identity.\n\n")}+// writeSessionContinuityNotice warns the agent — and, through it, the user —+// when a resume the task expected could not be honored. The daemon has already+// cleared the resume flags, so without this the run would silently reappear as a+// brand-new conversation; here we make the loss explicit and ask the agent to+// disclose it in its reply (MUL-4424). No-op unless a resume was actually lost.+func writeSessionContinuityNotice(b *strings.Builder, ctx TaskContextForEnv) {+ if !ctx.PriorSessionResumeUnavailable {+ return+ }+ b.WriteString("## Session Continuity Notice\n\n")+ b.WriteString("This run was meant to continue an earlier conversation, but that session's context could NOT be restored — you are starting fresh with no memory of the previous turns. Rebuild context from the issue/thread before acting. **When you reply, tell the user up front (one short sentence) that the previous conversation context was unavailable and this is a new session**, so they understand why the thread did not carry over.\n\n")+}+// writeWorkflowHeader emits the unconditional `### Workflow` heading.func writeWorkflowHeader(b *strings.Builder) {b.WriteString("### Workflow\n\n")@@ -529,6 +542,7 @@ func buildMetaSkillContentSlim(provider string, ctx TaskContextForEnv) string {writeHeader(&b)writeBackgroundTaskSafetySlim(&b)writeAgentIdentity(&b, ctx)+ writeSessionContinuityNotice(&b, ctx)writeRequestingUser(&b, ctx)writeTaskInitiator(&b, ctx)writeWorkspaceContext(&b, ctx)diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.goindex 0f297880d1..0c6d59cee2 100644--- a/server/internal/daemon/execenv/runtime_config_test.go+++ b/server/internal/daemon/execenv/runtime_config_test.go@@ -264,6 +264,32 @@ func TestCommentTriggeredBriefResumedNoDeltaSkipsDefaultThreadRead(t *testing.T)}}+// When the daemon could not honor an expected resume, the brief must make the+// context loss user-visible by instructing the agent to disclose it — not leave+// it as a silent restart (MUL-4424).+func TestBriefSurfacesResumeUnavailable(t *testing.T) {+ t.Parallel()+ const issueID = "11111111-2222-3333-4444-555555555555"+ base := TaskContextForEnv{IssueID: issueID, TriggerCommentID: "trigger-1", TriggerThreadID: "thread-1"}++ lost := base+ lost.PriorSessionResumeUnavailable = true+ out := buildMetaSkillContent("codex", lost)+ for _, want := range []string{+ "## Session Continuity Notice",+ "could NOT be restored",+ "tell the user up front",+ } {+ if !strings.Contains(out, want) {+ t.Errorf("resume-unavailable brief missing %q\n---\n%s", want, out)+ }+ }++ if strings.Contains(buildMetaSkillContent("codex", base), "Session Continuity Notice") {+ t.Error("brief must not show the continuity notice when no resume was lost")+ }+}+// Assignment-triggered briefs are the high-risk path for role conflicts:// non-executor agents still need issue context, but the runtime workflow must// not turn status changes, investigation, implementation, or delegation intodiff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.goindex d30fff1630..0dd003c23f 100644--- a/server/internal/daemon/gc.go+++ b/server/internal/daemon/gc.go@@ -54,6 +54,7 @@ type gcStats struct {skipped int // task dirs left untouchedartifactDirs int // task dirs that had at least one artifact reclaimedartifactRemoved int // count of removed artifact subdirs+ storesReclaimed int // per-issue Codex session stores reclaimed past their TTLbytesReclaimed int64 // total bytes freed in this cyclebyPattern map[string]int // basename -> reclaim count, for visibility}@@ -82,13 +83,22 @@ func (d *Daemon) runGC(ctx context.Context) {// Prune stale worktree references from all bare repo caches.d.pruneRepoWorktrees(root)- if stats.cleaned > 0 || stats.orphaned > 0 || stats.artifactDirs > 0 {+ // Reclaim per-issue Codex session stores idle past their TTL. These live+ // under the shared ~/.codex home (outside WorkspacesRoot) so resume survives+ // the task GC, which means they need their own bounded lifecycle (MUL-4424).+ if storesRemoved, storeBytes := execenv.PruneCodexSessionStores(d.cfg.Profile, d.cfg.GCCodexSessionTTL, time.Now(), d.reserveCodexStoreForDeletion, d.logger); storesRemoved > 0 {+ stats.storesReclaimed += storesRemoved+ stats.bytesReclaimed += storeBytes+ }++ if stats.cleaned > 0 || stats.orphaned > 0 || stats.artifactDirs > 0 || stats.storesReclaimed > 0 {d.logger.Info("gc: cycle complete","cleaned", stats.cleaned,"orphaned", stats.orphaned,"skipped", stats.skipped,"artifact_dirs", stats.artifactDirs,"artifact_removed", stats.artifactRemoved,+ "codex_session_stores_reclaimed", stats.storesReclaimed,"bytes_reclaimed", stats.bytesReclaimed,"by_pattern", stats.byPattern,)diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 4e41cfd759..e2450ceb88 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -36,10 +36,17 @@ type ExecOptions struct {// protocol transport. It is currently consumed by Codex app-server;// zero uses the provider default rather than disabling the bound.HandshakeTimeout time.Duration- ResumeSessionID string // if non-empty, resume a previous agent session- ExtraArgs []string // daemon-wide default CLI arguments appended before CustomArgs; currently read by claude and codex backends only- CustomArgs []string // per-agent CLI arguments appended after ExtraArgs- McpConfig json.RawMessage // if non-nil, MCP server config to pass via --mcp-config+ ResumeSessionID string // if non-empty, resume a previous agent session+ // ResumeExpected records that this task intended to continue a prior+ // conversation, independent of ResumeSessionID (which a fallback retry may+ // clear). When it is true but the backend ends up on a fresh thread — the+ // live resume RPC was rejected, or a transport failure forced a fresh retry —+ // the backend surfaces a continuity notice to the user instead of silently+ // restarting. Currently honoured by the codex backend (MUL-4424).+ ResumeExpected bool+ ExtraArgs []string // daemon-wide default CLI arguments appended before CustomArgs; currently read by claude and codex backends only+ CustomArgs []string // per-agent CLI arguments appended after ExtraArgs+ McpConfig json.RawMessage // if non-nil, MCP server config to pass via --mcp-config// ThinkingLevel is the runtime-native reasoning/effort value (e.g.// Claude's "low|medium|high|xhigh|max", Codex's "none|minimal|low|// medium|high|xhigh", OpenCode's model variant names). Empty meansdiff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex 86c64e1607..e201203f28 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -873,12 +873,16 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptib.cfg.Logger.Info("codex thread started", "thread_id", threadID)}- // 3. Send turn and wait for completion+ // 3. Send turn and wait for completion. When a resume was expected but we+ // ended up on a fresh thread (the live thread/resume RPC was rejected — a+ // corrupt/incompatible rollout, server-side thread GC, schema drift — or a+ // transport failure forced a fresh retry), prepend a continuity notice so+ // the agent tells the user the prior conversation could not be restored.+ // The daemon's pre-flight gates only catch cases detectable before launch;+ // this covers the ones only the live resume reveals (MUL-4424).turnParams := map[string]any{"threadId": threadID,- "input": []map[string]any{- {"type": "text", "text": prompt},- },+ "input": codexTurnInput(prompt, opts.ResumeExpected, resumed),}// Per-turn reasoning override. Mirrors the per-thread injection in// startOrResumeThread; keeping both in sync is enforced by the@@ -1054,9 +1058,12 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptic.usageMu.Unlock()// Fallback: if no usage from JSON-RPC, scan Codex session JSONL logs.- // Codex writes token_count events to ~/.codex/sessions/YYYY/MM/DD/*.jsonl.+ // Codex writes token_count events to $CODEX_HOME/sessions/YYYY/MM/DD/*.jsonl;+ // scan this backend's per-task CODEX_HOME, since sessions are isolated+ // there rather than in the shared ~/.codex/sessions (MUL-4424).if u.InputTokens == 0 && u.OutputTokens == 0 {- if scanned := scanCodexSessionUsage(startTime); scanned != nil {+ taskCodexHome := strings.TrimSpace(b.cfg.Env["CODEX_HOME"])+ if scanned := scanCodexSessionUsage(startTime, taskCodexHome); scanned != nil {u = scanned.usageif scanned.model != "" && opts.Model == "" {opts.Model = scanned.model@@ -1085,6 +1092,27 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptireturn &Session{Messages: msgCh, Result: resCh}, nil}+// codexResumeUnavailableNotice is prepended to the first turn's input when a+// resume was expected but Codex ended up on a fresh thread. It mirrors the+// daemon brief's Session Continuity Notice so the disclosure is identical+// whether the loss is detected pre-launch (daemon gate) or only by the live+// thread/resume RPC (MUL-4424).+const codexResumeUnavailableNotice = "[System notice] You were expected to continue an earlier conversation, but restoring that session failed and this is a fresh thread with no memory of the previous turns. Rebuild context from the issue/thread, and when you reply, tell the user up front (one short sentence) that the previous conversation context could not be restored and this is a new session.\n\n"++// codexTurnInput builds the input content for the first turn/start. When a+// resume was expected (resumeExpected) but the backend landed on a fresh thread+// (!resumed), it prepends codexResumeUnavailableNotice so the user learns the+// prior context was lost instead of the run silently continuing as new. The+// notice is folded into the same text block as the prompt to stay within the+// single-text-block turn input Codex already accepts.+func codexTurnInput(prompt string, resumeExpected, resumed bool) []map[string]any {+ text := prompt+ if resumeExpected && !resumed {+ text = codexResumeUnavailableNotice + prompt+ }+ return []map[string]any{{"type": "text", "text": text}}+}+// startOrResumeThread picks between Codex's thread/resume and thread/start// based on opts.ResumeSessionID. When a prior thread ID is provided it first// tries thread/resume; recoverable protocol errors (unknown thread, schema@@ -2079,9 +2107,11 @@ type codexSessionUsage struct {// scanCodexSessionUsage scans Codex session JSONL files written after startTime// to extract token usage. Codex writes token_count events to-// ~/.codex/sessions/YYYY/MM/DD/*.jsonl.-func scanCodexSessionUsage(startTime time.Time) *codexSessionUsage {- root := codexSessionRoot()+// $CODEX_HOME/sessions/YYYY/MM/DD/*.jsonl. codexHome is the backend's per-task+// CODEX_HOME; sessions are isolated there rather than in the shared+// ~/.codex/sessions (MUL-4424), so usage must be read from it.+func scanCodexSessionUsage(startTime time.Time, codexHome string) *codexSessionUsage {+ root := codexSessionRoot(codexHome)if root == "" {return nil}@@ -2117,9 +2147,15 @@ func scanCodexSessionUsage(startTime time.Time) *codexSessionUsage {return &result}-// codexSessionRoot returns the Codex sessions directory.-func codexSessionRoot() string {- if codexHome := os.Getenv("CODEX_HOME"); codexHome != "" {+// codexSessionRoot returns the Codex sessions directory. It prefers the+// explicit per-task codexHome the backend is running with (so usage is read+// from the same task-local sessions Codex actually wrote to), then the ambient+// CODEX_HOME, then ~/.codex.+func codexSessionRoot(codexHome string) string {+ if codexHome = strings.TrimSpace(codexHome); codexHome == "" {+ codexHome = os.Getenv("CODEX_HOME")+ }+ if codexHome != "" {dir := filepath.Join(codexHome, "sessions")if info, err := os.Stat(dir); err == nil && info.IsDir() {return dirdiff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.goindex cc7c8b200e..70fb6a759b 100644--- a/server/pkg/agent/codex_test.go+++ b/server/pkg/agent/codex_test.go@@ -715,6 +715,61 @@ func TestParseCodexSessionFileSubtractsCachedInput(t *testing.T) {}}+// The per-task CODEX_HOME must win over the ambient env / global home so usage+// is read from the same task-local sessions Codex actually wrote to (MUL-4424).+func TestCodexSessionRootPrefersExplicitTaskHome(t *testing.T) {+ // Cannot use t.Parallel() with t.Setenv.+ envHome := t.TempDir()+ taskHome := t.TempDir()+ if err := os.MkdirAll(filepath.Join(envHome, "sessions"), 0o755); err != nil {+ t.Fatalf("mkdir env sessions: %v", err)+ }+ if err := os.MkdirAll(filepath.Join(taskHome, "sessions"), 0o755); err != nil {+ t.Fatalf("mkdir task sessions: %v", err)+ }+ t.Setenv("CODEX_HOME", envHome)++ if got, want := codexSessionRoot(taskHome), filepath.Join(taskHome, "sessions"); got != want {+ t.Errorf("explicit task home ignored: got %q, want %q", got, want)+ }+ if got, want := codexSessionRoot(""), filepath.Join(envHome, "sessions"); got != want {+ t.Errorf("empty task home should fall back to ambient CODEX_HOME: got %q, want %q", got, want)+ }+}++func TestScanCodexSessionUsageReadsPerTaskHome(t *testing.T) {+ t.Parallel()+ taskHome := t.TempDir()+ startTime := time.Now().Add(-time.Minute)+ dateDir := filepath.Join(taskHome, "sessions",+ fmt.Sprintf("%04d", startTime.Year()),+ fmt.Sprintf("%02d", int(startTime.Month())),+ fmt.Sprintf("%02d", startTime.Day()),+ )+ if err := os.MkdirAll(dateDir, 0o755); err != nil {+ t.Fatalf("mkdir date dir: %v", err)+ }+ content := strings.Join([]string{+ `{"timestamp":"2026-07-13T00:00:00.000Z","type":"turn_context","payload":{"model":"gpt-5.6-sol"}}`,+ `{"timestamp":"2026-07-13T00:00:01.000Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":500,"output_tokens":20},"model":"gpt-5.6-sol"}}}`,+ "",+ }, "\n")+ if err := os.WriteFile(filepath.Join(dateDir, "rollout.jsonl"), []byte(content), 0o644); err != nil {+ t.Fatalf("write session file: %v", err)+ }++ got := scanCodexSessionUsage(startTime, taskHome)+ if got == nil {+ t.Fatal("expected usage scanned from the per-task home")+ }+ if got.usage.InputTokens != 500 || got.usage.OutputTokens != 20 {+ t.Errorf("usage = %+v, want input=500 output=20", got.usage)+ }+ if got.model != "gpt-5.6-sol" {+ t.Errorf("model = %q, want gpt-5.6-sol", got.model)+ }+}+func TestCodexRawItemCommandExecution(t *testing.T) {t.Parallel()@@ -1268,6 +1323,44 @@ func TestCodexStartOrResumeThreadFallsBackOnResumeError(t *testing.T) {}}+// codexTurnInput carries the user-visible disclosure when a resume was expected+// but the backend landed on a fresh thread. Paired with+// TestCodexStartOrResumeThreadFallsBackOnResumeError (which proves the live+// thread/resume RPC returns resumed=false on a recoverable error), this proves+// the real fallback surfaces the notice while a successful resume does not+// (MUL-4424).+func TestCodexTurnInput(t *testing.T) {+ t.Parallel()++ const prompt = "do the task"+ text := func(input []map[string]any) string {+ if len(input) != 1 {+ t.Fatalf("expected a single input block, got %d", len(input))+ }+ s, _ := input[0]["text"].(string)+ return s+ }++ // Resume expected but the backend fell back to a fresh thread → disclose,+ // and the original prompt must still be delivered.+ fallback := text(codexTurnInput(prompt, true, false))+ if !strings.Contains(fallback, "previous conversation context could not be restored") {+ t.Errorf("expected continuity notice on resume fallback, got:\n%s", fallback)+ }+ if !strings.HasSuffix(fallback, prompt) {+ t.Errorf("prompt must survive alongside the notice, got:\n%s", fallback)+ }++ // Successful resume, or an ordinary fresh start with no resume expected →+ // no notice, prompt delivered verbatim.+ if got := text(codexTurnInput(prompt, true, true)); got != prompt {+ t.Errorf("successful resume must not add a notice, got:\n%s", got)+ }+ if got := text(codexTurnInput(prompt, false, false)); got != prompt {+ t.Errorf("fresh start must not add a notice, got:\n%s", got)+ }+}+func TestCodexStartOrResumeThreadDoesNotFallBackAfterProcessExit(t *testing.T) {t.Parallel()