fix: harden session adopt review cases · Entire
fix: harden session adopt review cases
Sessions
616df3aa9473View transcript
Changes
2
cmd/entire/cli
Msession_adopt.go+16/-4
- Msession_adopt_test.go+162
1
2
3
4
5
6
7
105 unmodified lines
113
114
115
115
116
117
118
119
117
120
121
122
123
26 unmodified lines
150
151
152
150
153
154
155
156
29 unmodified lines
186
187
188
186
189
190
191
192
3 unmodified lines
196
197
198
199
200
201
202
203
204
205
206
207
208
45 unmodified lines
254
255
256
257
258
259
260
261
package cli
import (
"bytes"
"context"
"errors"
"fmt"
105 unmodified lines
}
cmd := exec.CommandContext(ctx, "git", "-C", absWorktree, "rev-parse", "--show-toplevel", "--git-common-dir")
output, err := cmd.CombinedOutput()
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, err := cmd.Output()
if err != nil {
msg := strings.TrimSpace(string(output))
msg := strings.TrimSpace(stderr.String())
if msg != "" {
return nil, "", "", fmt.Errorf("resolve source git directory: %s: %w", msg, err)
}
26 unmodified lines
if sourceState == nil {
return nil, fmt.Errorf("session %s was not found in %s", sessionID, sourceWorktree)
}
if sourceState.Phase == session.PhaseEnded || sourceState.FullyCondensed {
if !isAdoptableSourceSession(sourceState) {
return nil, fmt.Errorf("session %s is ended or fully condensed and cannot be adopted", sessionID)
}
return sourceState, nil
}
29 unmodified lines
}
func isRecentAdoptCandidate(state *session.State) bool {
if state == nil || state.Phase == session.PhaseEnded || state.FullyCondensed {
if !isAdoptableSourceSession(state) {
return false
}
lastSeen := sessionLastSeen(state)
3 unmodified lines
return time.Since(lastSeen) <= adoptRecentWindow
}
func isAdoptableSourceSession(state *session.State) bool {
return state != nil &&
state.Phase != session.PhaseEnded &&
state.EndedAt == nil &&
!state.FullyCondensed
}
func sessionLastSeen(state *session.State) time.Time {
if state.LastInteractionTime != nil {
return *state.LastInteractionTime
45 unmodified lines
adopted.WorktreeID = worktreeID
adopted.Branch = branch
adopted.LastInteractionTime = &now
adopted.Phase = session.PhaseActive
adopted.EndedAt = nil
adopted.FilesTouched = filesTouched
// Reset target-local checkpoint bookkeeping. Source checkpoint IDs can point
Mcmd/entire/cli/session_adopt.go+16/-4
6 unmodified lines
7
8
9
10
11
12
13
158 unmodified lines
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
199 unmodified lines
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
6 unmodified lines
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
158 unmodified lines
}
}
func TestSessionAdopt_IdleSourceSurvivesPrepareCommitMsgTrailer(t *testing.T) {
sourceRepo := setupAdoptRepo(t)
targetRepo := setupAdoptRepo(t)
sessionID := "test-adopt-idle-source"
targetRelPath := "src/idle.go"
targetAbsPath := filepath.Join(targetRepo, targetRelPath)
transcriptPath := filepath.Join(sourceRepo, ".claude", sessionID+".jsonl")
if err := os.MkdirAll(filepath.Dir(transcriptPath), 0o750); err != nil {
t.Fatal(err)
}
transcript := `{"type":"human","message":{"content":"write idle.go"}}
{"type":"assistant","message":{"content":[{"type":"tool_use","name":"Write","input":{"file_path":"` + targetAbsPath + `","content":"package src\n"}}]}}
`
if err := os.WriteFile(transcriptPath, []byte(transcript), 0o600); err != nil {
t.Fatal(err)
}
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.PhaseIdle,
BaseCommit: testutil.GetHeadHash(t, sourceRepo),
AttributionBaseCommit: testutil.GetHeadHash(t, sourceRepo),
WorktreePath: sourceRepo,
TranscriptPath: transcriptPath,
LastPrompt: "write idle.go",
}); err != nil {
t.Fatal(err)
}
testutil.WriteFile(t, targetRepo, targetRelPath, "package src\n")
testutil.GitAdd(t, targetRepo, targetRelPath)
t.Chdir(targetRepo)
var out bytes.Buffer
err := runAdopt(context.Background(), &out, sessionID, adoptOptions{
FromWorktree: sourceRepo,
Force: true,
})
if err != nil {
t.Fatalf("runAdopt failed: %v", err)
}
targetStore, err := session.NewStateStore(context.Background())
if err != nil {
t.Fatal(err)
}
adopted, err := targetStore.Load(context.Background(), sessionID)
if err != nil {
t.Fatal(err)
}
if adopted == nil {
t.Fatal("expected adopted session state")
}
if adopted.Phase != session.PhaseActive {
t.Fatalf("Phase = %q, want active so commit hooks do not sweep adopted state", adopted.Phase)
}
if adopted.EndedAt != nil {
t.Fatalf("EndedAt = %v, want nil", adopted.EndedAt)
}
commitMsgFile := filepath.Join(targetRepo, "COMMIT_EDITMSG")
if err := os.WriteFile(commitMsgFile, []byte("add idle feature\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := strategy.NewManualCommitStrategy().PrepareCommitMsg(context.Background(), commitMsgFile, ""); err != nil {
t.Fatalf("PrepareCommitMsg failed: %v", err)
}
content, err := os.ReadFile(commitMsgFile)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(content), "Entire-Checkpoint:") {
t.Fatalf("commit message = %q, want Entire-Checkpoint trailer", string(content))
}
}
func TestSessionAdopt_RejectsEndedAtSourceSession(t *testing.T) {
sourceRepo := setupAdoptRepo(t)
targetRepo := setupAdoptRepo(t)
sessionID := "test-adopt-ended-at"
endedAt := time.Now().Add(-30 * time.Second)
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,
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)
var out bytes.Buffer
err := runAdopt(context.Background(), &out, sessionID, adoptOptions{
FromWorktree: sourceRepo,
Force: true,
})
if err == nil {
t.Fatal("runAdopt succeeded, want ended-session refusal")
}
if !strings.Contains(err.Error(), "ended or fully condensed") {
t.Fatalf("runAdopt error = %v, want ended-session refusal", err)
}
_, err = selectAdoptSourceSession(context.Background(), sourceStore, sourceRepo, "")
if err == nil {
t.Fatal("selectAdoptSourceSession succeeded, want no recent active sessions")
}
if !strings.Contains(err.Error(), "no recent active sessions") {
t.Fatalf("selectAdoptSourceSession error = %v, want no recent active sessions", err)
}
}
func TestSessionAdopt_ResetsSourceCheckpointWindow(t *testing.T) {
sourceRepo := setupAdoptRepo(t)
targetRepo := setupAdoptRepo(t)
199 unmodified lines
}
}
func TestStateStoreForWorktreeIgnoresGitStderrOnSuccess(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses a POSIX shell script fake git")
}
fakeBin := t.TempDir()
fakeGit := filepath.Join(fakeBin, "git")
script := `#!/bin/sh
printf 'advice: noisy git warning\n' >&2
printf '%s\n%s\n' "$FAKE_WORKTREE_ROOT" "$FAKE_GIT_COMMON_DIR"
`
if err := os.WriteFile(fakeGit, []byte(script), 0o755); err != nil {
t.Fatal(err)
}
sourceRoot := filepath.Join(t.TempDir(), "source")
commonDir := filepath.Join(t.TempDir(), "common.git")
t.Setenv("PATH", fakeBin+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("FAKE_WORKTREE_ROOT", sourceRoot)
t.Setenv("FAKE_GIT_COMMON_DIR", commonDir)
_, gotSourceRoot, gotCommonDir, err := stateStoreForWorktree(context.Background(), ".")
if err != nil {
t.Fatalf("stateStoreForWorktree failed: %v", err)
}
if gotSourceRoot != sourceRoot {
t.Fatalf("sourceRoot = %q, want %q", gotSourceRoot, sourceRoot)
}
if gotCommonDir != filepath.Clean(commonDir) {
t.Fatalf("commonDir = %q, want %q", gotCommonDir, filepath.Clean(commonDir))
}
}
func TestSessionAdopt_RejectsSameGitCommonDir(t *testing.T) {
sourceRepo := setupAdoptRepo(t)
targetWorktree := filepath.Join(t.TempDir(), "target-worktree")