fix(session): lock external session adoption · Entire

fix(session): lock external session adoption

654c16a→main·

peyton-alt·3w ago·2 files·+291 added/-13 removed

Sessions

90af7f32f5e5View transcript

[?
Adopt Active Sessions Across Repos and WorktreesCodex·GPT-5.5·3 steps](/content/gh/entireio/cli/session/019ef6af-f809-76d3-8c95-7d7f0bc0c5ef#timeline-90af7f32f5e5/index.html)

Changes

2

6 unmodified lines
7
8
9
10
11
12
13
3 unmodified lines
17
18
19
20
21
22
23
24
25
26
27
72 unmodified lines
100
101
102
100
103
104
105
106
107
108
109
110
111
112
113
114
115
9 unmodified lines
125
126
127
116
117
118
119
128
129
130
131
132
133
134
135
136
137
138
139
140
141
121
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
123
124
125
126
127
128
129
183
184
185
186
58 unmodified lines

245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304

6 unmodified lines

"fmt"
    "io"
    "maps"
    "os"
    "os/exec"
    "path/filepath"
    "slices"
3 unmodified lines

"github.com/entireio/cli/cmd/entire/cli/agent"
    "github.com/entireio/cli/cmd/entire/cli/checkpoint/id"
    "github.com/entireio/cli/cmd/entire/cli/internal/flock"
    "github.com/entireio/cli/cmd/entire/cli/paths"
    "github.com/entireio/cli/cmd/entire/cli/session"
    "github.com/entireio/cli/cmd/entire/cli/strategy"
    "github.com/entireio/cli/cmd/entire/cli/validation"
    "github.com/entireio/cli/cmd/entire/cli/versioninfo"
    "github.com/spf13/cobra"
)
72 unmodified lines

if sameSessionStore {
        adopted, filesTouched, err = adoptFromSameSessionStore(ctx, sourceWorktree, sourceState, opts)
    } else {
        adopted, filesTouched, err = adoptFromExternalSessionStore(ctx, targetStore, sourceState, opts)
        adopted, filesTouched, err = adoptFromExternalSessionStore(
            ctx,
            sourceStore,
            sourceWorktree,
            sourceCommonDir,
            targetStore,
            targetCommonDir,
            sourceState.SessionID,
            opts,
        )
    }
    if err != nil {
        return err

}

return nil
}

func adoptFromExternalSessionStore(ctx context.Context, targetStore *session.StateStore, sourceState *session.State, opts adoptOptions) (*session.State, []string, error) {
    adopted, filesTouched, err := buildAdoptedSessionState(ctx, sourceState)
    if err != nil {
        return nil, nil, err

}

func adoptFromExternalSessionStore(
    ctx context.Context,
    sourceStore *session.StateStore,
    sourceWorktree string,
    sourceCommonDir string,
    targetStore *session.StateStore,
    targetCommonDir string,
    sessionID string,
    opts adoptOptions,
) (*session.State, []string, error) {
    sourceWorktreeID, worktreeIDErr := paths.GetWorktreeID(sourceWorktree)
    if worktreeIDErr != nil {
        sourceWorktreeID = ""
    }
    existing, err := targetStore.Load(ctx, adopted.SessionID)

var adopted *session.State
    var filesTouched []string
    err := withAdoptSessionLocks(ctx, sessionID, []string{sourceCommonDir, targetCommonDir}, func() error {
        sourceState, err := sourceStore.Load(ctx, sessionID)
        if err != nil {
            return fmt.Errorf("load source session state: %w", err)
        }
        if sourceState == nil {
            return fmt.Errorf("session %s was not found in %s", sessionID, sourceWorktree)
        }
        if !isAdoptableSourceSession(sourceState) {
            return fmt.Errorf("session %s is ended or fully condensed and cannot be adopted", sessionID)
        }
        if !sessionBelongsToSourceWorktree(sourceState, sourceWorktree, sourceWorktreeID) {
            return fmt.Errorf("session %s belongs to %s, not %s",
                sessionID, adoptSessionWorktreeLabel(sourceState), sourceWorktree)
        }
        if err := validateAdoptSourceTranscript(sourceState, sourceWorktree); err != nil {
            return err
        }

next, touched, err := buildAdoptedSessionState(ctx, sourceState)
        if err != nil {
            return err
        }
        existing, err := targetStore.Load(ctx, next.SessionID)
        if err != nil {
            return fmt.Errorf("load current session state: %w", err)
        }
        if existing != nil && !opts.Force {
            return fmt.Errorf("session %s is already tracked in this repo; rerun with --force to replace it", next.SessionID)
        }
        if err := targetStore.Save(ctx, next); err != nil {
            return fmt.Errorf("save adopted session state: %w", err)
        }
        adopted = next
        filesTouched = touched
        return nil
    })
    if err != nil {
        return nil, nil, fmt.Errorf("load current session state: %w", err)
    }
    if existing != nil && !opts.Force {
        return nil, nil, fmt.Errorf("session %s is already tracked in this repo; rerun with --force to replace it", adopted.SessionID)
    }
    if err := targetStore.Save(ctx, adopted); err != nil {
        return nil, nil, fmt.Errorf("save adopted session state: %w", err)
        return nil, nil, err
    }
    return adopted, filesTouched, nil
}
58 unmodified lines

return nil
}

func withAdoptSessionLocks(ctx context.Context, sessionID string, commonDirs []string, fn func() error) error {
    lockPaths := make([]string, 0, len(commonDirs))
    seen := make(map[string]struct{}, len(commonDirs))
    for _, commonDir := range commonDirs {
        lockPath, err := adoptSessionLockPath(commonDir, sessionID)
        if err != nil {
            return err
        }
        if _, ok := seen[lockPath]; ok {
            continue
        }
        seen[lockPath] = struct{}{}
        lockPaths = append(lockPaths, lockPath)
    }
    sort.Strings(lockPaths)

releases := make([]func(), 0, len(lockPaths))
    for _, lockPath := range lockPaths {
        if err := ctx.Err(); err != nil {
            releaseAdoptSessionLocks(releases)
            return fmt.Errorf("adopt session lock canceled: %w", err)
        }
        release, err := flock.Acquire(lockPath)
        if err != nil {
            releaseAdoptSessionLocks(releases)
            return fmt.Errorf("acquire session state lock: %w", err)
        }
        releases = append(releases, release)
    }
    defer releaseAdoptSessionLocks(releases)

return fn()
}

func releaseAdoptSessionLocks(releases []func()) {
    for i := len(releases) - 1; i >= 0; i-- {
        releases[i]()
    }
}

func adoptSessionLockPath(commonDir, sessionID string) (string, error) {
    if strings.TrimSpace(commonDir) == "" {
        return "", errors.New("resolve session state lock: empty git common dir")
    }
    if err := validation.ValidateSessionID(sessionID); err != nil {
        return "", fmt.Errorf("invalid session ID: %w", err)
    }
    lockDir := filepath.Join(commonDir, "entire-session-locks")
    if err := os.MkdirAll(lockDir, 0o750); err != nil {
        return "", fmt.Errorf("create session lock directory: %w", err)
    }
    return filepath.Join(lockDir, sessionID+".lock"), nil
}

func stateStoreForWorktree(ctx context.Context, worktreePath string) (*session.StateStore, string, string, error) {
    absWorktree, err := filepath.Abs(worktreePath)
    if err != nil {

Mcmd/entire/cli/session_adopt.go+121/-13

13 unmodified lines

14
15
16
17
18
19
20
137 unmodified lines

158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332

13 unmodified lines

"github.com/entireio/cli/cmd/entire/cli/agent"
    "github.com/entireio/cli/cmd/entire/cli/checkpoint/id"
    "github.com/entireio/cli/cmd/entire/cli/internal/flock"
    "github.com/entireio/cli/cmd/entire/cli/paths"
    "github.com/entireio/cli/cmd/entire/cli/session"
    "github.com/entireio/cli/cmd/entire/cli/strategy" 
137 unmodified lines

}
}

func TestSessionAdopt_ExternalStoreRejectsSourceEndedAfterInitialSelection(t *testing.T) {
    sourceRepo := setupAdoptRepo(t)
    targetRepo := setupAdoptRepo(t)

_sessionID := "test-adopt-external-source-stale"
     lastInteraction := time.Now().Add(-1 * time.Minute)
    sourceStore := session.NewStateStoreWithDir(filepath.Join(sourceRepo, ".git", session.SessionStateDirName))
    if err := sourceStore.Save(context.Background(), &session.State{
        SessionID:             sessionID,
        AgentType:             agent.AgentTypeClaudeCode,
        StartedAt:             time.Now().Add(-5 * time.Minute),
        LastInteractionTime:   &lastInteraction,
        Phase:                 session.PhaseActive,
        BaseCommit:            testutil.GetHeadHash(t, sourceRepo),
        AttributionBaseCommit: testutil.GetHeadHash(t, sourceRepo),
        WorktreePath:          sourceRepo,
    }); err != nil {
        t.Fatal(err)
    }
    if _, err := selectAdoptSourceSession(context.Background(), sourceStore, sourceRepo, sessionID); err != nil {
        t.Fatalf("initial source selection failed: %v", err)
    }

endedAt := time.Now()
    if err := sourceStore.Save(context.Background(), &session.State{
        SessionID:             sessionID,
        AgentType:             agent.AgentTypeClaudeCode,
        StartedAt:             time.Now().Add(-5 * time.Minute),
        LastInteractionTime:   &lastInteraction,
        EndedAt:               &endedAt,
        Phase:                 session.PhaseIdle,
        BaseCommit:            testutil.GetHeadHash(t, sourceRepo),
        AttributionBaseCommit: testutil.GetHeadHash(t, sourceRepo),
        WorktreePath:          sourceRepo,
    }); err != nil {
        t.Fatal(err)
    }

testutil.WriteFile(t, targetRepo, "feature.txt", "agent change\n")
    t.Chdir(targetRepo)
    targetStore, err := session.NewStateStore(context.Background())
    if err != nil {
        t.Fatal(err)
    }
    _, _, sourceCommonDir, err := stateStoreForWorktree(context.Background(), sourceRepo)
    if err != nil {
        t.Fatal(err)
    }
    _, _, targetCommonDir, err := stateStoreForWorktree(context.Background(), targetRepo)
    if err != nil {
        t.Fatal(err)
    }

_, _, err = adoptFromExternalSessionStore(
        context.Background(),
        sourceStore,
        sourceRepo,
        sourceCommonDir,
        targetStore,
        targetCommonDir,
        sessionID,
        adoptOptions{Force: true},
    )
    if err == nil {
        t.Fatal("adoptFromExternalSessionStore succeeded from stale ended source, want refusal")
    }
    if !strings.Contains(err.Error(), "ended or fully condensed") {
        t.Fatalf("adoptFromExternalSessionStore error = %v, want ended-session refusal", err)
    }
}

func TestSessionAdopt_ExternalStoreChecksTargetStateAfterLockWait(t *testing.T) {
    sourceRepo := setupAdoptRepo(t)
    targetRepo := setupAdoptRepo(t)

_sessionID := "test-adopt-external-target-race"
     lastInteraction := time.Now().Add(-1 * time.Minute)
    sourceStore := session.NewStateStoreWithDir(filepath.Join(sourceRepo, ".git", session.SessionStateDirName))
    if err := sourceStore.Save(context.Background(), &session.State{
        SessionID:             sessionID,
        AgentType:             agent.AgentTypeClaudeCode,
        StartedAt:             time.Now().Add(-5 * time.Minute),
        LastInteractionTime:   &lastInteraction,
        Phase:                 session.PhaseActive,
        BaseCommit:            testutil.GetHeadHash(t, sourceRepo),
        AttributionBaseCommit: testutil.GetHeadHash(t, sourceRepo),
        WorktreePath:          sourceRepo,
    }); err != nil {
        t.Fatal(err)
    }

lockPath, err := adoptSessionLockPath(targetCommonDir, sessionID)
    if err != nil {
        t.Fatal(err)
    }
    release, err := flock.Acquire(lockPath)
    if err != nil {
        t.Fatal(err)
    }

done := make(chan error, 1)
    go func() {
        _, _, adoptErr := adoptFromExternalSessionStore(
            context.Background(),
            sourceStore,
            sourceRepo,
            sourceCommonDir,
            targetStore,
            targetCommonDir,
            sessionID,
            adoptOptions{},
        )
        done <- adoptErr
    }()

select {
    case err := <-done:
        release()
        t.Fatalf("adoptFromExternalSessionStore finished before target lock released: %v", err)
    case <-time.After(100 * time.Millisecond):
    }

if err := targetStore.Save(context.Background(), &session.State{
        SessionID:             sessionID,
        AgentType:             agent.AgentTypeClaudeCode,
        StartedAt:             time.Now(),
        Phase:                 session.PhaseActive,
        BaseCommit:            testutil.GetHeadHash(t, targetRepo),
        AttributionBaseCommit: testutil.GetHeadHash(t, targetRepo),
        WorktreePath:          targetRepo,
        LastPrompt:            "concurrent target state",
    }); err != nil {
        release()
        t.Fatal(err)
    }
    release()

err = <-done
    if err == nil {
        t.Fatal("adoptFromExternalSessionStore succeeded, want existing target refusal")
    }
    if !strings.Contains(err.Error(), "already tracked in this repo") {
        t.Fatalf("adoptFromExternalSessionStore error = %v, want existing-state refusal", err)
    }

loaded, err := targetStore.Load(context.Background(), sessionID)
    if err != nil {
        t.Fatal(err)
    }
    if loaded.LastPrompt != "concurrent target state" {
        t.Fatalf("target state LastPrompt = %q, want concurrent target state", loaded.LastPrompt)
    }
}

func TestSessionAdopt_EnablesPrepareCommitMsgTrailer(t *testing.T) {
    sourceRepo := setupAdoptRepo(t)
    targetRepo := setupAdoptRepo(t)