| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "os" |
| 7 | "os/exec" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | |
| 12 | "the-valley/flow/internal/draft" |
| 13 | "the-valley/flow/internal/git" |
| 14 | "the-valley/flow/internal/run" |
| 15 | ) |
| 16 | |
| 17 | // initReplayTestRepo creates a real git repo with an initial commit. |
| 18 | func initReplayTestRepo(t *testing.T) string { |
| 19 | t.Helper() |
| 20 | dir := t.TempDir() |
| 21 | steps := [][]string{ |
| 22 | {"git", "init", "--initial-branch=main", dir}, |
| 23 | {"git", "-C", dir, "config", "user.email", "test@test.com"}, |
| 24 | {"git", "-C", dir, "config", "user.name", "Test"}, |
| 25 | } |
| 26 | if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("# test\n"), 0o644); err != nil { |
| 27 | t.Fatal(err) |
| 28 | } |
| 29 | steps = append(steps, |
| 30 | []string{"git", "-C", dir, "add", "README.md"}, |
| 31 | []string{"git", "-C", dir, "commit", "-m", "initial"}, |
| 32 | ) |
| 33 | for _, args := range steps { |
| 34 | if out, err := exec.Command(args[0], args[1:]...).CombinedOutput(); err != nil { |
| 35 | t.Fatalf("setup %v: %v\n%s", args, err, out) |
| 36 | } |
| 37 | } |
| 38 | return dir |
| 39 | } |
| 40 | |
| 41 | // makeConversationJSONL builds a small conversation-format trajectory (the |
| 42 | // schema claude --resume reads) carrying the given sessionId and cwd. |
| 43 | func makeConversationJSONL(sessionID, cwd string) string { |
| 44 | lines := []string{ |
| 45 | fmt.Sprintf(`{"type":"user","cwd":%q,"sessionId":%q,"version":"2.1.158","gitBranch":"feature-x","uuid":"11111111-1111-1111-1111-111111111111","parentUuid":null,"isSidechain":false,"message":{"role":"user","content":"do the thing"}}`, cwd, sessionID), |
| 46 | fmt.Sprintf(`{"type":"assistant","cwd":%q,"sessionId":%q,"version":"2.1.158","uuid":"22222222-2222-2222-2222-222222222222","parentUuid":"11111111-1111-1111-1111-111111111111","message":{"role":"assistant","content":[{"type":"text","text":"working on it"}]}}`, cwd, sessionID), |
| 47 | } |
| 48 | return strings.Join(lines, "\n") + "\n" |
| 49 | } |
| 50 | |
| 51 | // storeTrajectoryOnDataRef writes a conversation trajectory onto refs/klaus/data |
| 52 | // at sessions/<runID>.jsonl using the real data-ref machinery. |
| 53 | func storeTrajectoryOnDataRef(t *testing.T, repo, dataRef, runID, content string) { |
| 54 | t.Helper() |
| 55 | tmp := filepath.Join(t.TempDir(), "traj.jsonl") |
| 56 | if err := os.WriteFile(tmp, []byte(content), 0o644); err != nil { |
| 57 | t.Fatal(err) |
| 58 | } |
| 59 | files := map[string]string{"sessions/" + runID + ".jsonl": tmp} |
| 60 | if _, err := git.SyncToDataRef(context.Background(), repo, dataRef, "Run "+runID, files); err != nil { |
| 61 | t.Fatalf("SyncToDataRef: %v", err) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | // TestReplayRoundTripEndToEnd exercises the full replay path against a REAL |
| 66 | // refs/klaus/data blob: store a conversation trajectory, then resolve a |
| 67 | // budget-paused replay and assert klaus restores the JSONL into the new |
| 68 | // worktree's project dir and that the downstream claude command resumes it. |
| 69 | func TestReplayRoundTripEndToEnd(t *testing.T) { |
| 70 | home := t.TempDir() |
| 71 | t.Setenv("HOME", home) |
| 72 | t.Setenv("USERPROFILE", home) // os.UserHomeDir checks USERPROFILE first on Windows |
| 73 | |
| 74 | repo := initReplayTestRepo(t) |
| 75 | const dataRef = "refs/klaus/data" |
| 76 | const runID = "20260601-1000-aaaa" |
| 77 | const branch = "feature-x" |
| 78 | const sessionID = "6623bdcf-1dce-4da0-86b3-a46743d208e8" |
| 79 | |
| 80 | // New worktree the resumed agent will run in. The trajectory's original |
| 81 | // cwd is intentionally different to mimic the cross-worktree handoff. |
| 82 | worktree := filepath.Join(home, "worktrees", runID+"-resume") |
| 83 | origCwd := filepath.Join(home, "worktrees", runID) |
| 84 | traj := makeConversationJSONL(sessionID, origCwd) |
| 85 | storeTrajectoryOnDataRef(t, repo, dataRef, runID, traj) |
| 86 | |
| 87 | // Record the paused run in the store, keyed to the PR branch. |
| 88 | baseDir := filepath.Join(home, ".klaus", "sessions", "session-test") |
| 89 | store := run.NewHomeDirStoreFromPath(baseDir) |
| 90 | if err := store.EnsureDirs(); err != nil { |
| 91 | t.Fatalf("EnsureDirs: %v", err) |
| 92 | } |
| 93 | sid := sessionID |
| 94 | if err := store.Save(&run.State{ |
| 95 | ID: runID, |
| 96 | Branch: branch, |
| 97 | Prompt: "do the thing", |
| 98 | CreatedAt: "2026-06-01T10:00:00Z", |
| 99 | ClaudeSessionID: &sid, |
| 100 | }); err != nil { |
| 101 | t.Fatalf("Save: %v", err) |
| 102 | } |
| 103 | |
| 104 | decision := resolveReplay(context.Background(), replayParams{ |
| 105 | GitClient: git.NewExecClient(), |
| 106 | Store: store, |
| 107 | RepoRoot: repo, |
| 108 | DataRef: dataRef, |
| 109 | Worktree: worktree, |
| 110 | PRBranch: branch, |
| 111 | PRNumber: "42", |
| 112 | ForceReplay: true, // skip the gh paused-label check in this unit |
| 113 | ThresholdKB: 300, |
| 114 | }) |
| 115 | |
| 116 | if decision.SessionUUID != sessionID { |
| 117 | t.Fatalf("SessionUUID = %q, want %q (reason: %s)", decision.SessionUUID, sessionID, decision.Reason) |
| 118 | } |
| 119 | if decision.SourceRunID != runID { |
| 120 | t.Errorf("SourceRunID = %q, want %q", decision.SourceRunID, runID) |
| 121 | } |
| 122 | |
| 123 | // The trajectory must be restored into the NEW worktree's project dir, |
| 124 | // byte-for-byte, under <sessionID>.jsonl — exactly where claude --resume |
| 125 | // looks when invoked from that worktree. |
| 126 | dest := claudeConversationPath(worktree, sessionID) |
| 127 | got, err := os.ReadFile(dest) |
| 128 | if err != nil { |
| 129 | t.Fatalf("restored trajectory not found at %s: %v", dest, err) |
| 130 | } |
| 131 | if string(got) != traj { |
| 132 | t.Errorf("restored trajectory mismatch:\n got %q\nwant %q", got, traj) |
| 133 | } |
| 134 | |
| 135 | // The downstream claude command resumes the restored session. |
| 136 | cmd := buildClaudeCommand("sys", "5", "continue", "20260601-1100-bbbb", decision.SessionUUID, "", "") |
| 137 | if !strings.Contains(cmd, "'--resume' '"+sessionID+"'") { |
| 138 | t.Errorf("claude command missing --resume %s: %s", sessionID, cmd) |
| 139 | } |
| 140 | if !strings.Contains(cmd, "--fork-session") { |
| 141 | t.Errorf("claude command missing --fork-session: %s", cmd) |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | // TestReplayFallbacks covers the miss paths that must drop back to a fresh |
| 146 | // agent (empty SessionUUID with an explanatory reason). |
| 147 | func TestReplayFallbacks(t *testing.T) { |
| 148 | home := t.TempDir() |
| 149 | t.Setenv("HOME", home) |
| 150 | t.Setenv("USERPROFILE", home) // os.UserHomeDir checks USERPROFILE first on Windows |
| 151 | repo := initReplayTestRepo(t) |
| 152 | const dataRef = "refs/klaus/data" |
| 153 | const branch = "feature-x" |
| 154 | worktree := filepath.Join(home, "wt") |
| 155 | |
| 156 | newStore := func() run.StateStore { |
| 157 | baseDir := filepath.Join(t.TempDir(), "session") |
| 158 | s := run.NewHomeDirStoreFromPath(baseDir) |
| 159 | if err := s.EnsureDirs(); err != nil { |
| 160 | t.Fatalf("EnsureDirs: %v", err) |
| 161 | } |
| 162 | return s |
| 163 | } |
| 164 | |
| 165 | t.Run("no prior run for branch", func(t *testing.T) { |
| 166 | d := resolveReplay(context.Background(), replayParams{ |
| 167 | GitClient: git.NewExecClient(), Store: newStore(), RepoRoot: repo, |
| 168 | DataRef: dataRef, Worktree: worktree, PRBranch: branch, PRNumber: "1", |
| 169 | ForceReplay: true, ThresholdKB: 300, |
| 170 | }) |
| 171 | if d.SessionUUID != "" { |
| 172 | t.Errorf("expected fresh fallback, got resume %q", d.SessionUUID) |
| 173 | } |
| 174 | }) |
| 175 | |
| 176 | t.Run("trajectory missing from data ref", func(t *testing.T) { |
| 177 | store := newStore() |
| 178 | _ = store.Save(&run.State{ID: "20260601-1000-cccc", Branch: branch, CreatedAt: "2026-06-01T10:00:00Z"}) |
| 179 | d := resolveReplay(context.Background(), replayParams{ |
| 180 | GitClient: git.NewExecClient(), Store: store, RepoRoot: repo, |
| 181 | DataRef: dataRef, Worktree: worktree, PRBranch: branch, PRNumber: "1", |
| 182 | ForceReplay: true, ThresholdKB: 300, |
| 183 | }) |
| 184 | if d.SessionUUID != "" { |
| 185 | t.Errorf("expected fresh fallback when blob absent, got %q (%s)", d.SessionUUID, d.Reason) |
| 186 | } |
| 187 | }) |
| 188 | |
| 189 | t.Run("oversized trajectory falls back unless forced", func(t *testing.T) { |
| 190 | const runID = "20260601-1000-dddd" |
| 191 | const sessionID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" |
| 192 | store := newStore() |
| 193 | _ = store.Save(&run.State{ID: runID, Branch: branch, CreatedAt: "2026-06-01T10:00:00Z"}) |
| 194 | |
| 195 | // Build a trajectory larger than a 1KB threshold. |
| 196 | big := makeConversationJSONL(sessionID, filepath.Join(home, "orig")) + strings.Repeat("x", 4096) + "\n" |
| 197 | storeTrajectoryOnDataRef(t, repo, dataRef, runID, big) |
| 198 | |
| 199 | // Paused PR confirmed via a fake runner so the gate passes; threshold |
| 200 | // then forces the fallback because --replay is not set. |
| 201 | orig := budgetPauseRunner |
| 202 | budgetPauseRunner = fakeLabelRunner{labels: "klaus:budget-paused\n"} |
| 203 | defer func() { budgetPauseRunner = orig }() |
| 204 | |
| 205 | d := resolveReplay(context.Background(), replayParams{ |
| 206 | GitClient: git.NewExecClient(), Store: store, RepoRoot: repo, |
| 207 | DataRef: dataRef, Worktree: worktree, PRBranch: branch, PRNumber: "1", |
| 208 | ForceReplay: false, ThresholdKB: 1, |
| 209 | }) |
| 210 | if d.SessionUUID != "" { |
| 211 | t.Errorf("expected fresh fallback for oversized trajectory, got %q", d.SessionUUID) |
| 212 | } |
| 213 | if !strings.Contains(d.Reason, "threshold") { |
| 214 | t.Errorf("reason should mention threshold, got %q", d.Reason) |
| 215 | } |
| 216 | |
| 217 | // --replay (ForceReplay) bypasses the size threshold. |
| 218 | d2 := resolveReplay(context.Background(), replayParams{ |
| 219 | GitClient: git.NewExecClient(), Store: store, RepoRoot: repo, |
| 220 | DataRef: dataRef, Worktree: worktree, PRBranch: branch, PRNumber: "1", |
| 221 | ForceReplay: true, ThresholdKB: 1, |
| 222 | }) |
| 223 | if d2.SessionUUID != sessionID { |
| 224 | t.Errorf("--replay should bypass threshold and resume, got %q (%s)", d2.SessionUUID, d2.Reason) |
| 225 | } |
| 226 | }) |
| 227 | |
| 228 | t.Run("not paused falls back without forcing", func(t *testing.T) { |
| 229 | const runID = "20260601-1000-eeee" |
| 230 | const sessionID = "ffffffff-0000-1111-2222-333333333333" |
| 231 | store := newStore() |
| 232 | _ = store.Save(&run.State{ID: runID, Branch: branch, CreatedAt: "2026-06-01T10:00:00Z"}) |
| 233 | storeTrajectoryOnDataRef(t, repo, dataRef, runID, makeConversationJSONL(sessionID, home)) |
| 234 | |
| 235 | orig := budgetPauseRunner |
| 236 | budgetPauseRunner = fakeLabelRunner{labels: "some-other-label\n"} // not paused |
| 237 | defer func() { budgetPauseRunner = orig }() |
| 238 | |
| 239 | d := resolveReplay(context.Background(), replayParams{ |
| 240 | GitClient: git.NewExecClient(), Store: store, RepoRoot: repo, |
| 241 | DataRef: dataRef, Worktree: worktree, PRBranch: branch, PRNumber: "1", |
| 242 | ForceReplay: false, ThresholdKB: 300, |
| 243 | }) |
| 244 | if d.SessionUUID != "" { |
| 245 | t.Errorf("expected fresh fallback when PR not paused, got %q", d.SessionUUID) |
| 246 | } |
| 247 | }) |
| 248 | } |
| 249 | |
| 250 | func TestEncodeProjectPath(t *testing.T) { |
| 251 | // Claude replaces both '/' and '.' with '-'. These cases are derived from |
| 252 | // real ~/.claude/projects/ directory names on this machine. |
| 253 | tests := []struct { |
| 254 | cwd string |
| 255 | want string |
| 256 | }{ |
| 257 | {"/tmp/klaus-sessions/k/2026.06", "-tmp-klaus-sessions-k-2026-06"}, |
| 258 | { |
| 259 | "/tmp/klaus-sessions/klaus/20260627-1721-bcde1ba8", |
| 260 | "-tmp-klaus-sessions-klaus-20260627-1721-bcde1ba8", |
| 261 | }, |
| 262 | { |
| 263 | // '/.klaus' becomes '--klaus' because both '/' and '.' map to '-'. |
| 264 | "/home/maintainer/.klaus/sessions/abc-workspace", |
| 265 | "-home-maintainer--klaus-sessions-abc-workspace", |
| 266 | }, |
| 267 | } |
| 268 | for _, tt := range tests { |
| 269 | if got := encodeProjectPath(tt.cwd); got != tt.want { |
| 270 | t.Errorf("encodeProjectPath(%q) = %q, want %q", tt.cwd, got, tt.want) |
| 271 | } |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | func TestExtractConversationSessionID(t *testing.T) { |
| 276 | blob := makeConversationJSONL("9a9a9a9a-0000-0000-0000-000000000000", "/x") |
| 277 | if got := extractConversationSessionID([]byte(blob)); got != "9a9a9a9a-0000-0000-0000-000000000000" { |
| 278 | t.Errorf("extractConversationSessionID = %q", got) |
| 279 | } |
| 280 | if got := extractConversationSessionID([]byte("not json\n{}\n")); got != "" { |
| 281 | t.Errorf("expected empty for blob without sessionId, got %q", got) |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | // fakeLabelRunner is a draft.Runner that returns canned gh output for the |
| 286 | // label lookup and is a no-op for git. |
| 287 | type fakeLabelRunner struct { |
| 288 | labels string |
| 289 | err error |
| 290 | } |
| 291 | |
| 292 | func (f fakeLabelRunner) Git(ctx context.Context, workdir string, args ...string) (string, error) { |
| 293 | return "", nil |
| 294 | } |
| 295 | |
| 296 | func (f fakeLabelRunner) GH(ctx context.Context, workdir string, args ...string) (string, error) { |
| 297 | return f.labels, f.err |
| 298 | } |
| 299 | |
| 300 | var _ draft.Runner = fakeLabelRunner{} |