gunk-dev/the-valley

hidden_test.go

sourcec14b0e68e9c3main's published tip history
49.9 KiB
1package cmd
2
3import (
4 "context"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "regexp"
9 "strings"
10 "testing"
11
12 "the-valley/flow/internal/event"
13 "the-valley/flow/internal/git"
14 "the-valley/flow/internal/run"
15)
16
17func TestFinalizeWorktreeCleanup(t *testing.T) {
18 t.Run("clears worktree from state after cleanup", func(t *testing.T) {
19 dir := t.TempDir()
20 stateDir := filepath.Join(dir, "runs")
21 if err := os.MkdirAll(stateDir, 0755); err != nil {
22 t.Fatal(err)
23 }
24
25 // Create a real git repo with a worktree so we can verify removal.
26 repoDir := filepath.Join(dir, "repo")
27 initGitRepo(t, repoDir)
28
29 wtPath := filepath.Join(dir, "wt")
30 runGitCmd(t, repoDir, "worktree", "add", wtPath, "-b", "agent/test-branch")
31
32 // Verify worktree exists before cleanup.
33 if _, err := os.Stat(wtPath); err != nil {
34 t.Fatalf("worktree should exist before cleanup: %v", err)
35 }
36
37 state := &run.State{
38 ID: "test-run",
39 Branch: "agent/test-branch",
40 Worktree: wtPath,
41 CloneDir: &repoDir,
42 }
43 store := &testStateStore{dir: stateDir, state: state}
44
45 // Simulate the cleanup logic from _finalize.
46 cleanupWorktree(context.Background(), store, git.NewExecClient(), state, false)
47
48 if state.Worktree != "" {
49 t.Errorf("expected Worktree to be cleared, got %q", state.Worktree)
50 }
51 if _, err := os.Stat(wtPath); !os.IsNotExist(err) {
52 t.Error("expected worktree directory to be removed")
53 }
54 })
55
56 t.Run("idempotent when worktree already removed", func(t *testing.T) {
57 dir := t.TempDir()
58 stateDir := filepath.Join(dir, "runs")
59 if err := os.MkdirAll(stateDir, 0755); err != nil {
60 t.Fatal(err)
61 }
62
63 repoDir := filepath.Join(dir, "repo")
64 initGitRepo(t, repoDir)
65
66 state := &run.State{
67 ID: "test-run",
68 Branch: "agent/gone-branch",
69 Worktree: filepath.Join(dir, "already-gone"),
70 CloneDir: &repoDir,
71 }
72 store := &testStateStore{dir: stateDir, state: state}
73
74 // Should not panic or fail — just clears state.
75 cleanupWorktree(context.Background(), store, git.NewExecClient(), state, false)
76
77 if state.Worktree != "" {
78 t.Errorf("expected Worktree to be cleared, got %q", state.Worktree)
79 }
80 })
81
82 t.Run("keeps a branch with unpushed commits", func(t *testing.T) {
83 _, repo, worktree, branch := setupBareRemote(t)
84 runGitCmd(t, worktree, "add", "-A")
85 runGitCmd(t, worktree, "commit", "-m", "local only")
86 state := &run.State{ID: "test-run", Branch: branch, Worktree: worktree, CloneDir: &repo}
87 store := &testStateStore{dir: t.TempDir(), state: state}
88
89 cleanupWorktree(context.Background(), store, git.NewExecClient(), state, false)
90
91 if _, err := gitOut(t, repo, "rev-parse", "--verify", "refs/heads/"+branch); err != nil {
92 t.Errorf("unpushed branch was deleted: %v", err)
93 }
94 })
95
96 t.Run("keeps a branch whose origin copy was deleted", func(t *testing.T) {
97 origin, repo, worktree, branch := setupBareRemote(t)
98 commitAndPush(t, worktree, branch)
99 runGitCmd(t, origin, "branch", "-D", branch) // no fetch: origin/<branch> is stale
100 state := &run.State{ID: "test-run", Branch: branch, Worktree: worktree, CloneDir: &repo}
101 store := &testStateStore{dir: t.TempDir(), state: state}
102
103 cleanupWorktree(context.Background(), store, git.NewExecClient(), state, false)
104
105 if _, err := gitOut(t, repo, "rev-parse", "--verify", "refs/heads/"+branch); err != nil {
106 t.Errorf("branch deleted on a stale origin ref: %v", err)
107 }
108 })
109
110 t.Run("no-op when worktree field is empty", func(t *testing.T) {
111 state := &run.State{ID: "test-run", Worktree: ""}
112 store := &testStateStore{state: state}
113
114 cleanupWorktree(context.Background(), store, git.NewExecClient(), state, false)
115
116 if state.Worktree != "" {
117 t.Errorf("expected empty worktree, got %q", state.Worktree)
118 }
119 })
120}
121
122// initGitRepo creates a bare-minimum git repo with one commit.
123func initGitRepo(t *testing.T, dir string) {
124 t.Helper()
125 if err := os.MkdirAll(dir, 0755); err != nil {
126 t.Fatal(err)
127 }
128 runGitCmd(t, dir, "init")
129 runGitCmd(t, dir, "commit", "--allow-empty", "-m", "init")
130}
131
132// repoWithOrigin creates an empty git repo whose origin is origin.
133func repoWithOrigin(t *testing.T, origin string) string {
134 t.Helper()
135 dir := t.TempDir()
136 runGitCmd(t, dir, "init", "-q")
137 runGitCmd(t, dir, "remote", "add", "origin", origin)
138 return dir
139}
140
141// runGitCmd runs a git command in the given directory.
142func runGitCmd(t *testing.T, dir string, args ...string) {
143 t.Helper()
144 cmd := exec.Command("git", args...)
145 cmd.Dir = dir
146 cmd.Env = append(os.Environ(),
147 "GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@test",
148 "GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@test",
149 )
150 out, err := cmd.CombinedOutput()
151 if err != nil {
152 t.Fatalf("git %v failed: %v\n%s", args, err, out)
153 }
154}
155
156func TestKillAgentPane(t *testing.T) {
157 paneID := "%42"
158
159 t.Run("kills pane and clears state", func(t *testing.T) {
160 state := &run.State{ID: "test-run", TmuxPane: &paneID}
161 store := &testStateStore{state: state}
162 tc := &fakeTmux{killedPanes: []string{}}
163
164 killAgentPane(context.Background(), store, tc, state)
165
166 if len(tc.killedPanes) != 1 || tc.killedPanes[0] != paneID {
167 t.Errorf("expected KillPane(%q), got %v", paneID, tc.killedPanes)
168 }
169 if state.TmuxPane != nil {
170 t.Errorf("expected TmuxPane to be nil, got %v", *state.TmuxPane)
171 }
172 })
173
174 t.Run("no-op when TmuxPane is nil", func(t *testing.T) {
175 state := &run.State{ID: "test-run", TmuxPane: nil}
176 store := &testStateStore{state: state}
177 tc := &fakeTmux{}
178
179 killAgentPane(context.Background(), store, tc, state)
180
181 if len(tc.killedPanes) != 0 {
182 t.Errorf("expected no KillPane calls, got %v", tc.killedPanes)
183 }
184 })
185}
186
187func TestExtractPRNumberFromURL(t *testing.T) {
188 tests := []struct {
189 name string
190 url string
191 want string
192 }{
193 {
194 name: "standard PR URL",
195 url: "https://github.com/owner/repo/pull/123",
196 want: "123",
197 },
198 {
199 name: "PR URL with trailing slash",
200 url: "https://github.com/owner/repo/pull/456/",
201 want: "456",
202 },
203 {
204 name: "PR URL with query params",
205 url: "https://github.com/owner/repo/pull/789?diff=split",
206 want: "789",
207 },
208 {
209 name: "PR URL with fragment",
210 url: "https://github.com/owner/repo/pull/42#discussion_r123",
211 want: "42",
212 },
213 {
214 name: "PR URL with files path",
215 url: "https://github.com/owner/repo/pull/99/files",
216 want: "99",
217 },
218 {
219 name: "not a PR URL",
220 url: "https://github.com/owner/repo/issues/123",
221 want: "",
222 },
223 {
224 name: "empty string",
225 url: "",
226 want: "",
227 },
228 {
229 name: "no number after pull",
230 url: "https://github.com/owner/repo/pull/",
231 want: "",
232 },
233 {
234 name: "large PR number",
235 url: "https://github.com/owner/repo/pull/12345",
236 want: "12345",
237 },
238 }
239
240 for _, tt := range tests {
241 t.Run(tt.name, func(t *testing.T) {
242 got := extractPRNumberFromURL(tt.url)
243 if got != tt.want {
244 t.Errorf("extractPRNumberFromURL(%q) = %q, want %q", tt.url, got, tt.want)
245 }
246 })
247 }
248}
249
250func TestExtractPRURL(t *testing.T) {
251 tests := []struct {
252 name string
253 text string
254 want string
255 }{
256 {
257 name: "URL in sentence",
258 text: "I created a PR at https://github.com/owner/repo/pull/42 for review.",
259 want: "https://github.com/owner/repo/pull/42",
260 },
261 {
262 name: "URL with trailing period",
263 text: "See https://github.com/owner/repo/pull/99.",
264 want: "https://github.com/owner/repo/pull/99",
265 },
266 {
267 name: "no PR URL",
268 text: "This is just some text without a PR link.",
269 want: "",
270 },
271 {
272 name: "issue URL not matched",
273 text: "Check https://github.com/owner/repo/issues/10 for details.",
274 want: "",
275 },
276 {
277 name: "empty text",
278 text: "",
279 want: "",
280 },
281 {
282 name: "URL only",
283 text: "https://github.com/owner/repo/pull/1",
284 want: "https://github.com/owner/repo/pull/1",
285 },
286 {
287 name: "markdown link",
288 text: "Created [PR #42](https://github.com/owner/repo/pull/42) for review.",
289 want: "https://github.com/owner/repo/pull/42",
290 },
291 {
292 name: "angle brackets",
293 text: "PR created: <https://github.com/owner/repo/pull/7>",
294 want: "https://github.com/owner/repo/pull/7",
295 },
296 {
297 name: "parenthesized URL",
298 text: "See the PR (https://github.com/owner/repo/pull/55) for details.",
299 want: "https://github.com/owner/repo/pull/55",
300 },
301 {
302 name: "URL with trailing comma",
303 text: "https://github.com/owner/repo/pull/10, which fixes the bug",
304 want: "https://github.com/owner/repo/pull/10",
305 },
306 {
307 name: "http URL",
308 text: "http://github.com/owner/repo/pull/3",
309 want: "http://github.com/owner/repo/pull/3",
310 },
311 {
312 name: "bare gh pr create output",
313 text: "https://github.com/owner/repo/pull/42\n",
314 want: "https://github.com/owner/repo/pull/42",
315 },
316 }
317
318 for _, tt := range tests {
319 t.Run(tt.name, func(t *testing.T) {
320 got := extractPRURL(tt.text)
321 if got != tt.want {
322 t.Errorf("extractPRURL(%q) = %q, want %q", tt.text, got, tt.want)
323 }
324 })
325 }
326}
327
328func TestIsAllowedPRURL(t *testing.T) {
329 httpsClone := repoWithOrigin(t, "https://github.com/acme/widget.git")
330 sshClone := repoWithOrigin(t, "git@github.com:acme/widget.git")
331 localClone := repoWithOrigin(t, "/srv/git/widget.git")
332 slugTarget := "acme/widget"
333 otherTarget := "acme/corp"
334 bareTarget := "widget"
335 // launch records a local-path origin as a path, not owner/repo.
336 pathTarget := "/srv/git/widget"
337 const widgetPR = "https://github.com/acme/widget/pull/123"
338 const foreignPR = "https://github.com/other/repo/pull/123"
339
340 tests := []struct {
341 name string
342 state *run.State
343 candidate string
344 want bool
345 }{
346 {
347 name: "owner/repo TargetRepo matches",
348 state: &run.State{TargetRepo: &slugTarget, CloneDir: &localClone},
349 candidate: widgetPR,
350 want: true,
351 },
352 {
353 name: "owner/repo TargetRepo matches case-insensitively",
354 state: &run.State{TargetRepo: &slugTarget, CloneDir: &localClone},
355 candidate: "https://github.com/ACME/Widget/pull/123",
356 want: true,
357 },
358 {
359 name: "owner/repo TargetRepo wins over clone origin",
360 state: &run.State{TargetRepo: &otherTarget, CloneDir: &httpsClone},
361 candidate: widgetPR,
362 want: false,
363 },
364 {
365 name: "bare TargetRepo falls back to clone origin",
366 state: &run.State{TargetRepo: &bareTarget, CloneDir: &httpsClone},
367 candidate: widgetPR,
368 want: true,
369 },
370 {
371 name: "bare TargetRepo rejects foreign repo",
372 state: &run.State{TargetRepo: &bareTarget, CloneDir: &httpsClone},
373 candidate: foreignPR,
374 want: false,
375 },
376 {
377 name: "path TargetRepo falls back to clone origin",
378 state: &run.State{TargetRepo: &pathTarget, CloneDir: &httpsClone},
379 candidate: foreignPR,
380 want: false,
381 },
382 {
383 name: "ssh origin matches",
384 state: &run.State{CloneDir: &sshClone},
385 candidate: widgetPR,
386 want: true,
387 },
388 {
389 name: "ssh origin rejects foreign repo",
390 state: &run.State{CloneDir: &sshClone},
391 candidate: foreignPR,
392 want: false,
393 },
394 {
395 name: "local-path origin accepts any real slug",
396 state: &run.State{TargetRepo: &pathTarget, CloneDir: &localClone},
397 candidate: foreignPR,
398 want: true,
399 },
400 {
401 name: "local-path origin still rejects placeholder",
402 state: &run.State{TargetRepo: &pathTarget, CloneDir: &localClone},
403 candidate: "https://github.com/owner/repo/pull/123",
404 want: false,
405 },
406 {
407 name: "rejects placeholder owner/repo",
408 state: &run.State{TargetRepo: &slugTarget},
409 candidate: "https://github.com/owner/repo/pull/123",
410 want: false,
411 },
412 {
413 name: "rejects placeholder OWNER/REPO",
414 state: &run.State{TargetRepo: &slugTarget},
415 candidate: "https://github.com/OWNER/REPO/pull/123",
416 want: false,
417 },
418 {
419 name: "rejects placeholder <owner>/<repo>",
420 state: &run.State{TargetRepo: &slugTarget},
421 candidate: "https://github.com/<owner>/<repo>/pull/123",
422 want: false,
423 },
424 {
425 name: "rejects placeholder org/repo",
426 state: &run.State{TargetRepo: &slugTarget},
427 candidate: "https://github.com/org/repo/pull/123",
428 want: false,
429 },
430 {
431 name: "rejects placeholder user/repo",
432 state: &run.State{TargetRepo: &slugTarget},
433 candidate: "https://github.com/user/repo/pull/123",
434 want: false,
435 },
436 {
437 name: "empty candidate",
438 state: &run.State{TargetRepo: &slugTarget},
439 candidate: "",
440 want: false,
441 },
442 {
443 name: "malformed candidate without repo",
444 state: &run.State{TargetRepo: &slugTarget},
445 candidate: "https://github.com/pull/123",
446 want: false,
447 },
448 }
449
450 for _, tt := range tests {
451 t.Run(tt.name, func(t *testing.T) {
452 got := isAllowedPRURL(prURLTargetSlug(tt.state), tt.candidate)
453 if got != tt.want {
454 t.Errorf("isAllowedPRURL(%q) = %v, want %v", tt.candidate, got, tt.want)
455 }
456 })
457 }
458}
459
460func TestFinalizeFromLog(t *testing.T) {
461 for _, tc := range []struct {
462 name string
463 prefix string
464 suffix string
465 }{
466 {name: "session limit success with is_error"},
467 {name: "session limit clears earlier failure", prefix: `{"type":"result","subtype":"error_during_execution","is_error":true}` + "\n"},
468 {name: "session limit survives nonzero klaus_exit", suffix: "\n" + `{"type":"klaus_exit","exit_code":1}`},
469 {name: "session limit survives nonzero flow_exit", suffix: "\n" + `{"type":"flow_exit","exit_code":1}`},
470 } {
471 t.Run(tc.name, func(t *testing.T) {
472 const sessionID = "79dcfb08-4de4-45f4-b7db-056bccbc3a00"
473 logContent := tc.prefix + `{"type":"result","subtype":"success","is_error":true,"session_id":"` + sessionID + `","total_cost_usd":1.2,"duration_ms":100}` + tc.suffix
474 state, store := setupFinalizeTest(t, logContent)
475 subtype, err := finalizeFromLog(store, state)
476 if err != nil {
477 t.Fatal(err)
478 }
479 if subtype != "success" || state.FailureReason != nil {
480 t.Fatalf("subtype = %q, FailureReason = %v; want success without failure", subtype, state.FailureReason)
481 }
482 assertCost(t, state, 1.2)
483 assertDuration(t, state, 100)
484 if state.ClaudeSessionID == nil || *state.ClaudeSessionID != sessionID {
485 t.Fatalf("ClaudeSessionID = %v, want %q", state.ClaudeSessionID, sessionID)
486 }
487 })
488 }
489
490 t.Run("extracts PR URL from assistant text", func(t *testing.T) {
491 logContent := `{"type":"system","subtype":"init","model":"claude-sonnet-4-5-20250929"}
492{"type":"assistant","message":{"content":[{"type":"text","text":"I'll create the PR now."}]}}
493{"type":"assistant","message":{"content":[{"type":"text","text":"Created PR at https://github.com/maintainer/klaus/pull/42"}]}}
494{"type":"result","total_cost_usd":1.5,"duration_ms":30000}
495`
496 state, store := setupFinalizeTest(t, logContent)
497 if _, err := finalizeFromLog(store, state); err != nil {
498 t.Fatalf("finalizeFromLog() error: %v", err)
499 }
500 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/42")
501 assertCost(t, state, 1.5)
502 assertDuration(t, state, 30000)
503 if state.ResolvedModel != "claude-sonnet-4-5-20250929" {
504 t.Errorf("ResolvedModel = %q, want the init event's model", state.ResolvedModel)
505 }
506 })
507
508 t.Run("extracts PR URL from tool_result event", func(t *testing.T) {
509 logContent := `{"type":"system","subtype":"init","model":"claude-sonnet-4-5-20250929"}
510{"type":"assistant","message":{"content":[{"type":"tool_use","name":"Bash","input":{"command":"gh pr create --title test"}}]}}
511{"type":"tool_result","content":"https://github.com/maintainer/klaus/pull/99\n"}
512{"type":"assistant","message":{"content":[{"type":"text","text":"Done! I created the PR."}]}}
513{"type":"result","total_cost_usd":2.0,"duration_ms":45000}
514`
515 state, store := setupFinalizeTest(t, logContent)
516 if _, err := finalizeFromLog(store, state); err != nil {
517 t.Fatalf("finalizeFromLog() error: %v", err)
518 }
519 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/99")
520 })
521
522 t.Run("extracts PR URL from user message with tool_result content", func(t *testing.T) {
523 logContent := `{"type":"system","subtype":"init","model":"claude-sonnet-4-5-20250929"}
524{"type":"user","message":{"content":[{"type":"tool_result","content":"https://github.com/maintainer/klaus/pull/7\n"}]}}
525{"type":"result","total_cost_usd":1.0,"duration_ms":10000}
526`
527 state, store := setupFinalizeTest(t, logContent)
528 if _, err := finalizeFromLog(store, state); err != nil {
529 t.Fatalf("finalizeFromLog() error: %v", err)
530 }
531 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/7")
532 })
533
534 t.Run("handles markdown link in assistant text", func(t *testing.T) {
535 logContent := `{"type":"assistant","message":{"content":[{"type":"text","text":"Created [PR #42](https://github.com/maintainer/klaus/pull/42) for review."}]}}
536{"type":"result","total_cost_usd":1.0,"duration_ms":5000}
537`
538 state, store := setupFinalizeTest(t, logContent)
539 if _, err := finalizeFromLog(store, state); err != nil {
540 t.Fatalf("finalizeFromLog() error: %v", err)
541 }
542 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/42")
543 })
544
545 t.Run("survives malformed JSONL lines", func(t *testing.T) {
546 logContent := `{"type":"system","subtype":"init"}
547not valid json at all
548{"truncated":
549{"type":"assistant","message":{"content":[{"type":"text","text":"PR: https://github.com/maintainer/klaus/pull/5"}]}}
550{"type":"result","total_cost_usd":0.5,"duration_ms":2000}
551`
552 state, store := setupFinalizeTest(t, logContent)
553 if _, err := finalizeFromLog(store, state); err != nil {
554 t.Fatalf("finalizeFromLog() error: %v", err)
555 }
556 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/5")
557 assertCost(t, state, 0.5)
558 })
559
560 t.Run("no PR URL in log", func(t *testing.T) {
561 logContent := `{"type":"assistant","message":{"content":[{"type":"text","text":"Just doing some work."}]}}
562{"type":"result","total_cost_usd":0.1,"duration_ms":1000}
563`
564 state, store := setupFinalizeTest(t, logContent)
565 if _, err := finalizeFromLog(store, state); err != nil {
566 t.Fatalf("finalizeFromLog() error: %v", err)
567 }
568 if state.PRURL != nil {
569 t.Errorf("expected nil PRURL, got %q", *state.PRURL)
570 }
571 })
572
573 t.Run("last PR URL wins", func(t *testing.T) {
574 logContent := `{"type":"assistant","message":{"content":[{"type":"text","text":"First PR: https://github.com/maintainer/klaus/pull/1"}]}}
575{"type":"assistant","message":{"content":[{"type":"text","text":"Recreated PR: https://github.com/maintainer/klaus/pull/2"}]}}
576{"type":"result","total_cost_usd":1.0,"duration_ms":5000}
577`
578 state, store := setupFinalizeTest(t, logContent)
579 if _, err := finalizeFromLog(store, state); err != nil {
580 t.Fatalf("finalizeFromLog() error: %v", err)
581 }
582 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/2")
583 })
584
585 t.Run("preserves PRURL set before finalization", func(t *testing.T) {
586 // Simulates --pr mode: launch.go sets state.PRURL to the real PR
587 // before the agent runs. The agent's tool output contains unrelated
588 // PR URLs (e.g. from source code, test fixtures, or comments) that
589 // would otherwise clobber the correct value.
590 logContent := `{"type":"assistant","message":{"content":[{"type":"text","text":"Looking at https://github.com/other/repo/pull/999 for reference"}]}}
591{"type":"tool_result","content":"see https://github.com/some/fixture/pull/123 in test data"}
592{"type":"result","total_cost_usd":1.0,"duration_ms":5000}
593`
594 state, store := setupFinalizeTest(t, logContent)
595 existing := "https://github.com/maintainer/klaus/pull/42"
596 state.PRURL = &existing
597
598 if _, err := finalizeFromLog(store, state); err != nil {
599 t.Fatalf("finalizeFromLog() error: %v", err)
600 }
601 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/42")
602 })
603
604 t.Run("marks FailureReason on error_during_execution result", func(t *testing.T) {
605 // Mirrors the real crash: a cross-worktree --resume that exits
606 // instantly with no turns. _finalize must not treat this as success.
607 logContent := `{"type":"system","subtype":"init"}
608{"type":"result","subtype":"error_during_execution","is_error":true,"num_turns":0,"total_cost_usd":0,"errors":["No conversation found with session ID: deadbeef"]}
609`
610 state, store := setupFinalizeTest(t, logContent)
611 subtype, err := finalizeFromLog(store, state)
612 if err != nil {
613 t.Fatalf("finalizeFromLog() error: %v", err)
614 }
615 if subtype != "error_during_execution" {
616 t.Errorf("subtype = %q, want error_during_execution", subtype)
617 }
618 if state.FailureReason == nil {
619 t.Fatal("expected FailureReason to be set, got nil")
620 }
621 if !strings.Contains(*state.FailureReason, "error_during_execution") {
622 t.Errorf("FailureReason = %q, want it to mention the subtype", *state.FailureReason)
623 }
624 if !strings.Contains(*state.FailureReason, "No conversation found") {
625 t.Errorf("FailureReason = %q, want it to include the first error", *state.FailureReason)
626 }
627 // A crashed run had no PR; PRURL must stay nil.
628 if state.PRURL != nil {
629 t.Errorf("expected nil PRURL on crash, got %q", *state.PRURL)
630 }
631 })
632
633 t.Run("marks FailureReason when is_error is true without a subtype", func(t *testing.T) {
634 logContent := `{"type":"result","is_error":true,"total_cost_usd":0.2,"duration_ms":1000}
635`
636 state, store := setupFinalizeTest(t, logContent)
637 if _, err := finalizeFromLog(store, state); err != nil {
638 t.Fatalf("finalizeFromLog() error: %v", err)
639 }
640 if state.FailureReason == nil {
641 t.Fatal("expected FailureReason to be set when is_error is true")
642 }
643 })
644
645 t.Run("successful result leaves FailureReason nil and records cost", func(t *testing.T) {
646 logContent := `{"type":"assistant","message":{"content":[{"type":"text","text":"Done: https://github.com/maintainer/klaus/pull/12"}]}}
647{"type":"result","subtype":"success","is_error":false,"num_turns":7,"total_cost_usd":1.25,"duration_ms":20000}
648`
649 state, store := setupFinalizeTest(t, logContent)
650 if _, err := finalizeFromLog(store, state); err != nil {
651 t.Fatalf("finalizeFromLog() error: %v", err)
652 }
653 if state.FailureReason != nil {
654 t.Errorf("expected nil FailureReason on success, got %q", *state.FailureReason)
655 }
656 assertCost(t, state, 1.25)
657 assertDuration(t, state, 20000)
658 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/12")
659 })
660
661 t.Run("extracts PRURL from log when not set before finalization", func(t *testing.T) {
662 // Simulates new-PR mode: state.PRURL is nil until the agent runs
663 // `gh pr create`. Regex extraction fills it in from the log.
664 logContent := `{"type":"assistant","message":{"content":[{"type":"text","text":"Creating PR now."}]}}
665{"type":"tool_result","content":"https://github.com/maintainer/klaus/pull/77\n"}
666{"type":"result","total_cost_usd":1.0,"duration_ms":5000}
667`
668 state, store := setupFinalizeTest(t, logContent)
669 if state.PRURL != nil {
670 t.Fatalf("test precondition: expected nil PRURL before finalize")
671 }
672
673 if _, err := finalizeFromLog(store, state); err != nil {
674 t.Fatalf("finalizeFromLog() error: %v", err)
675 }
676 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/77")
677 })
678
679 // A run that delivers by pushing its branch takes no PR URL from its log,
680 // as launch recorded or, in state that predates the record, as its origin
681 // decides; a run that delivers by PR takes its own.
682 t.Run("delivery decides whether the log's PR URL is the run's", func(t *testing.T) {
683 const prURL = "https://github.com/maintainer/klaus/pull/7"
684 logContent := `{"type":"user","message":{"content":[{"type":"tool_result","content":"fixture: ` + prURL + `\n"}]}}
685{"type":"assistant","message":{"content":[{"type":"text","text":"The knot links ` + prURL + `"}]}}
686{"type":"result","subtype":"success","total_cost_usd":1.0,"duration_ms":5000}
687`
688 githubClone := repoWithOrigin(t, "https://github.com/maintainer/klaus.git")
689 valleyClone := repoWithOrigin(t, "git@10.0.2.1:the-valley.git")
690 for _, tc := range []struct {
691 name, delivery, clone string
692 wantPR bool
693 }{
694 {name: "recorded push", delivery: run.DeliveryPush, clone: githubClone},
695 {name: "unrecorded, origin not on GitHub", clone: valleyClone},
696 {name: "recorded PR", delivery: run.DeliveryPR, clone: githubClone, wantPR: true},
697 {name: "unrecorded, origin on GitHub", clone: githubClone, wantPR: true},
698 } {
699 t.Run(tc.name, func(t *testing.T) {
700 state, store := setupFinalizeTest(t, logContent)
701 state.Delivery, state.CloneDir = tc.delivery, &tc.clone
702 if _, err := finalizeFromLog(store, state); err != nil {
703 t.Fatal(err)
704 }
705 if tc.wantPR {
706 assertPRURL(t, state, prURL)
707 } else if state.PRURL != nil {
708 t.Errorf("PRURL = %q, want none for a run that delivers by push", *state.PRURL)
709 }
710 })
711 }
712 })
713
714 t.Run("rejects placeholder PR URL in assistant text", func(t *testing.T) {
715 logContent := `{"type":"system","subtype":"init","model":"claude-sonnet-4-5-20250929"}
716{"type":"assistant","message":{"content":[{"type":"text","text":"You can create a PR like https://github.com/owner/repo/pull/123 for review."}]}}
717{"type":"result","total_cost_usd":0.5,"duration_ms":10000}
718`
719 state, store := setupFinalizeTest(t, logContent)
720 if _, err := finalizeFromLog(store, state); err != nil {
721 t.Fatalf("finalizeFromLog() error: %v", err)
722 }
723 if state.PRURL != nil {
724 t.Errorf("expected nil PRURL for placeholder URL, got %q", *state.PRURL)
725 }
726 })
727
728 t.Run("prefers tool_result matching TargetRepo over assistant text from foreign repo", func(t *testing.T) {
729 logContent := `{"type":"system","subtype":"init","model":"claude-sonnet-4-5-20250929"}
730{"type":"assistant","message":{"content":[{"type":"text","text":"Check https://github.com/someone-else/other/pull/9 for example"}]}}
731{"type":"tool_result","content":"https://github.com/maintainer/klaus/pull/310\n"}
732{"type":"result","total_cost_usd":1.0,"duration_ms":15000}
733`
734 state, store := setupFinalizeTest(t, logContent)
735 target := "maintainer/klaus"
736 state.TargetRepo = &target
737 if _, err := finalizeFromLog(store, state); err != nil {
738 t.Fatalf("finalizeFromLog() error: %v", err)
739 }
740 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/310")
741 })
742
743 t.Run("rejects placeholders in tool_result", func(t *testing.T) {
744 for _, placeholder := range []string{
745 "https://github.com/owner/repo/pull/123",
746 "https://github.com/OWNER/REPO/pull/123",
747 "https://github.com/<owner>/<repo>/pull/123",
748 "https://github.com/org/repo/pull/123",
749 "https://github.com/user/repo/pull/123",
750 } {
751 logContent := `{"type":"tool_result","content":"` + placeholder + `\n"}
752{"type":"result","total_cost_usd":0.5,"duration_ms":5000}
753`
754 state, store := setupFinalizeTest(t, logContent)
755 if _, err := finalizeFromLog(store, state); err != nil {
756 t.Fatalf("finalizeFromLog() error: %v", err)
757 }
758 if state.PRURL != nil {
759 t.Errorf("expected nil PRURL for placeholder %q, got %q", placeholder, *state.PRURL)
760 }
761 }
762 })
763}
764
765func TestExtractClaudeSessionID(t *testing.T) {
766 t.Run("extracts session_id from result event", func(t *testing.T) {
767 logContent := `{"type":"system","subtype":"init","model":"claude-sonnet-4-5-20250929"}
768{"type":"assistant","message":{"content":[{"type":"text","text":"Working on it..."}]}}
769{"type":"result","session_id":"a1b2c3d4-e5f6-7890-abcd-ef1234567890","total_cost_usd":1.5,"duration_ms":30000}
770`
771 logFile := writeTestLog(t, logContent)
772 got := ExtractClaudeSessionID(logFile)
773 if got != "a1b2c3d4-e5f6-7890-abcd-ef1234567890" {
774 t.Errorf("ExtractClaudeSessionID() = %q, want UUID", got)
775 }
776 })
777
778 t.Run("returns empty when no result event", func(t *testing.T) {
779 logContent := `{"type":"system","subtype":"init"}
780{"type":"assistant","message":{"content":[{"type":"text","text":"Hello"}]}}
781`
782 logFile := writeTestLog(t, logContent)
783 got := ExtractClaudeSessionID(logFile)
784 if got != "" {
785 t.Errorf("ExtractClaudeSessionID() = %q, want empty", got)
786 }
787 })
788
789 t.Run("returns empty when result has no session_id", func(t *testing.T) {
790 logContent := `{"type":"result","total_cost_usd":0.5,"duration_ms":1000}
791`
792 logFile := writeTestLog(t, logContent)
793 got := ExtractClaudeSessionID(logFile)
794 if got != "" {
795 t.Errorf("ExtractClaudeSessionID() = %q, want empty", got)
796 }
797 })
798
799 t.Run("returns empty for nonexistent file", func(t *testing.T) {
800 got := ExtractClaudeSessionID("/nonexistent/path/log.jsonl")
801 if got != "" {
802 t.Errorf("ExtractClaudeSessionID() = %q, want empty", got)
803 }
804 })
805
806 t.Run("survives malformed lines", func(t *testing.T) {
807 logContent := `not json
808{"truncated":
809{"type":"result","session_id":"deadbeef-1234-5678-9abc-def012345678","total_cost_usd":0.1}
810`
811 logFile := writeTestLog(t, logContent)
812 got := ExtractClaudeSessionID(logFile)
813 if got != "deadbeef-1234-5678-9abc-def012345678" {
814 t.Errorf("ExtractClaudeSessionID() = %q, want UUID", got)
815 }
816 })
817}
818
819func TestEmitFinalizeEvents(t *testing.T) {
820 cost := 1.5
821 dur := int64(30000)
822 prURL := "https://github.com/owner/repo/pull/42"
823
824 t.Run("failed run emits needs-attention and nothing else", func(t *testing.T) {
825 baseDir := t.TempDir()
826 reason := "error_during_execution: No conversation found"
827 state := &run.State{
828 ID: "20260628-0900-fail",
829 CostUSD: &cost,
830 DurationMS: &dur,
831 PRURL: &prURL, // even with a stale URL, no pr-created on crash
832 FailureReason: &reason,
833 }
834
835 emitFinalizeEvents(baseDir, state, nil)
836
837 types := eventTypesFor(t, baseDir, state.ID)
838 if len(types) != 1 || types[0] != event.AgentNeedsAttention {
839 t.Fatalf("expected only %q, got %v", event.AgentNeedsAttention, types)
840 }
841 })
842
843 t.Run("successful run with PR emits completed and pr-created", func(t *testing.T) {
844 baseDir := t.TempDir()
845 state := &run.State{
846 ID: "20260628-0901-ok",
847 CostUSD: &cost,
848 DurationMS: &dur,
849 PRURL: &prURL,
850 }
851
852 emitFinalizeEvents(baseDir, state, nil)
853
854 types := eventTypesFor(t, baseDir, state.ID)
855 if !containsEvent(types, event.AgentCompleted) {
856 t.Errorf("expected %q in %v", event.AgentCompleted, types)
857 }
858 if !containsEvent(types, event.AgentPRCreated) {
859 t.Errorf("expected %q in %v", event.AgentPRCreated, types)
860 }
861 if containsEvent(types, event.AgentNeedsAttention) {
862 t.Errorf("did not expect %q in %v", event.AgentNeedsAttention, types)
863 }
864 })
865
866 t.Run("successful run without PR emits completed only", func(t *testing.T) {
867 baseDir := t.TempDir()
868 state := &run.State{
869 ID: "20260628-0902-nopr",
870 CostUSD: &cost,
871 DurationMS: &dur,
872 }
873
874 emitFinalizeEvents(baseDir, state, nil)
875
876 types := eventTypesFor(t, baseDir, state.ID)
877 if len(types) != 1 || types[0] != event.AgentCompleted {
878 t.Fatalf("expected only %q, got %v", event.AgentCompleted, types)
879 }
880 })
881}
882
883func eventTypesFor(t *testing.T, baseDir, runID string) []string {
884 t.Helper()
885 evts, err := event.NewLog(baseDir).Read()
886 if err != nil {
887 t.Fatalf("reading event log: %v", err)
888 }
889 var types []string
890 for _, e := range evts {
891 if e.RunID == runID {
892 types = append(types, e.Type)
893 }
894 }
895 return types
896}
897
898func containsEvent(types []string, want string) bool {
899 for _, ty := range types {
900 if ty == want {
901 return true
902 }
903 }
904 return false
905}
906
907func writeTestLog(t *testing.T, content string) string {
908 t.Helper()
909 logFile := filepath.Join(t.TempDir(), "test.jsonl")
910 if err := os.WriteFile(logFile, []byte(content), 0644); err != nil {
911 t.Fatalf("writing log file: %v", err)
912 }
913 return logFile
914}
915
916// setupFinalizeTest creates a temporary log file and state for testing finalizeFromLog.
917func setupFinalizeTest(t *testing.T, logContent string) (*run.State, run.StateStore) {
918 t.Helper()
919 dir := t.TempDir()
920
921 logFile := filepath.Join(dir, "test.jsonl")
922 if err := os.WriteFile(logFile, []byte(logContent), 0644); err != nil {
923 t.Fatalf("writing log file: %v", err)
924 }
925
926 stateDir := filepath.Join(dir, "runs")
927 if err := os.MkdirAll(stateDir, 0755); err != nil {
928 t.Fatalf("creating state dir: %v", err)
929 }
930
931 // Fixture origin so PR URL checks don't depend on this checkout.
932 cloneDir := repoWithOrigin(t, "https://github.com/maintainer/klaus.git")
933 state := &run.State{
934 ID: "test-run",
935 LogFile: &logFile,
936 CloneDir: &cloneDir,
937 }
938
939 store := &testStateStore{dir: stateDir, state: state}
940 return state, store
941}
942
943// testStateStore is a minimal StateStore for testing.
944type testStateStore struct {
945 dir string
946 state *run.State
947}
948
949func (s *testStateStore) Save(state *run.State) error {
950 s.state = state
951 return nil
952}
953
954func (s *testStateStore) Load(id string) (*run.State, error) {
955 return s.state, nil
956}
957
958func (s *testStateStore) List() ([]*run.State, error) {
959 return []*run.State{s.state}, nil
960}
961
962func (s *testStateStore) Delete(id string) error {
963 return nil
964}
965
966func (s *testStateStore) StateDir() string {
967 return s.dir
968}
969
970func (s *testStateStore) LogDir() string {
971 return s.dir
972}
973
974func (s *testStateStore) EnsureDirs() error {
975 return nil
976}
977
978// TestEmitFinalizeEventsNilState covers the gemini #277 follow-up: the finalize
979// path must no-op rather than dereference a nil run state.
980func TestEmitFinalizeEventsNilState(t *testing.T) {
981 // Should return early without panicking.
982 emitFinalizeEvents(t.TempDir(), nil, nil)
983}
984
985func assertPRURL(t *testing.T, state *run.State, want string) {
986 t.Helper()
987 if state.PRURL == nil {
988 t.Fatalf("expected PRURL %q, got nil", want)
989 }
990 if *state.PRURL != want {
991 t.Errorf("PRURL = %q, want %q", *state.PRURL, want)
992 }
993}
994
995func assertCost(t *testing.T, state *run.State, want float64) {
996 t.Helper()
997 if state.CostUSD == nil {
998 t.Fatalf("expected CostUSD %v, got nil", want)
999 }
1000 if *state.CostUSD != want {
1001 t.Errorf("CostUSD = %v, want %v", *state.CostUSD, want)
1002 }
1003}
1004
1005func assertDuration(t *testing.T, state *run.State, want int64) {
1006 t.Helper()
1007 if state.DurationMS == nil {
1008 t.Fatalf("expected DurationMS %v, got nil", want)
1009 }
1010 if *state.DurationMS != want {
1011 t.Errorf("DurationMS = %v, want %v", *state.DurationMS, want)
1012 }
1013}
1014
1015const salvageChangeID = "zzzzyyyyxxxxwwwwvvvvuuuuttttssss"
1016
1017// finalizeRealRepo runs _finalize for a run on worktree/branch with the given
1018// log and the delivery launch recorded ("" for state that predates it). gh is
1019// stubbed (empty output); git is real.
1020func finalizeRealRepo(t *testing.T, repo, worktree, branch, logContent, delivery string) (*run.HomeDirStore, *run.State, *fakeRunner) {
1021 t.Helper()
1022 sessionID := "20260918-1205-salvage-session"
1023 t.Setenv("HOME", t.TempDir())
1024 t.Setenv(sessionIDEnv, sessionID)
1025 store, err := run.NewHomeDirStore(sessionID)
1026 if err != nil {
1027 t.Fatalf("NewHomeDirStore: %v", err)
1028 }
1029 if err := store.EnsureDirs(); err != nil {
1030 t.Fatalf("EnsureDirs: %v", err)
1031 }
1032 runID := "20260918-1205-salvage"
1033 logFile := filepath.Join(store.LogDir(), runID+".jsonl")
1034 if err := os.WriteFile(logFile, []byte(logContent), 0644); err != nil {
1035 t.Fatalf("writing log: %v", err)
1036 }
1037 state := &run.State{
1038 ID: runID,
1039 ChangeID: salvageChangeID,
1040 Prompt: "rename the thing",
1041 Branch: branch,
1042 Worktree: worktree,
1043 CreatedAt: "2026-09-18T12:05:00Z",
1044 LogFile: &logFile,
1045 CloneDir: &repo,
1046 Delivery: delivery,
1047 }
1048 if err := store.Save(state); err != nil {
1049 t.Fatalf("saving state: %v", err)
1050 }
1051
1052 r := &fakeRunner{}
1053 prev := budgetPauseRunner
1054 budgetPauseRunner = r
1055 t.Cleanup(func() { budgetPauseRunner = prev })
1056
1057 finalizeCmd.SetContext(context.Background())
1058 if err := finalizeCmd.RunE(finalizeCmd, []string{runID}); err != nil {
1059 t.Fatalf("_finalize: %v", err)
1060 }
1061 final, err := store.Load(runID)
1062 if err != nil {
1063 t.Fatalf("loading state: %v", err)
1064 }
1065 return store, final, r
1066}
1067
1068func runEvents(t *testing.T, baseDir, runID string) map[string]map[string]interface{} {
1069 t.Helper()
1070 evts, err := event.NewLog(baseDir).Read()
1071 if err != nil {
1072 t.Fatalf("reading events: %v", err)
1073 }
1074 byType := map[string]map[string]interface{}{}
1075 for _, e := range evts {
1076 if e.RunID == runID {
1077 byType[e.Type] = e.Data
1078 }
1079 }
1080 return byType
1081}
1082
1083func gitOut(t *testing.T, dir string, args ...string) (string, error) {
1084 t.Helper()
1085 out, err := exec.Command("git", append([]string{"-C", dir}, args...)...).CombinedOutput()
1086 return strings.TrimSpace(string(out)), err
1087}
1088
1089// Regression for #299: a session-limit stop (subtype success, no PR) must not
1090// destroy the agent's uncommitted work or its branch.
1091func TestFinalizeSalvagesRunWithoutPR(t *testing.T) {
1092 sessionLimitLog := `{"type":"assistant","message":{"content":[{"type":"text","text":"VM test passes."}]}}
1093{"type":"result","subtype":"success","is_error":true,"result":"You've hit your session limit · resets 4:20pm","total_cost_usd":3.1,"duration_ms":2100000}
1094{"type":"klaus_exit","exit_code":1}
1095`
1096 t.Run("commits, pushes, and keeps the branch", func(t *testing.T) {
1097 origin, repo, worktree, branch := setupBareRemote(t)
1098
1099 store, state, r := finalizeRealRepo(t, repo, worktree, branch, sessionLimitLog, "")
1100
1101 if _, err := gitOut(t, repo, "rev-parse", "--verify", "refs/heads/"+branch); err != nil {
1102 t.Errorf("local branch deleted: %v", err)
1103 }
1104 files, err := gitOut(t, origin, "show", "--name-only", "--format=%s", branch)
1105 if err != nil {
1106 t.Fatalf("branch missing on origin: %v (%s)", err, files)
1107 }
1108 if !strings.Contains(files, "wip: klaus finalize salvage "+state.ID) || !strings.Contains(files, "wip.txt") {
1109 t.Errorf("origin tip should be the WIP commit with wip.txt, got:\n%s", files)
1110 }
1111 // The salvage commit skips hooks, so finalize adds the trailers itself.
1112 trailers, _ := gitOut(t, origin, "log", "-1", "--format=%(trailers:only,unfold)", branch)
1113 if want := "Change-Id: " + salvageChangeID + "\nKlaus-Run: " + state.ID; trailers != want {
1114 t.Errorf("salvage commit trailers = %q, want %q", trailers, want)
1115 }
1116 if _, err := os.Stat(worktree); !os.IsNotExist(err) {
1117 t.Errorf("worktree should be removed once the branch is safe, stat err = %v", err)
1118 }
1119 if state.NeedsAttention == nil || !strings.Contains(*state.NeedsAttention, branch) {
1120 t.Errorf("NeedsAttention should name the branch, got %v", state.NeedsAttention)
1121 }
1122 if len(r.ghCalls) != 0 {
1123 t.Errorf("salvage must not touch GitHub, got gh calls %v", r.ghCalls)
1124 }
1125
1126 evts := runEvents(t, store.BaseDir(), state.ID)
1127 if _, ok := evts[event.AgentCompleted]; ok {
1128 t.Error("agent:completed must not be emitted for a salvaged run")
1129 }
1130 na, ok := evts[event.AgentNeedsAttention]
1131 if !ok {
1132 t.Fatalf("expected agent:needs-attention, got %v", evts)
1133 }
1134 if na["branch"] != branch || na["pushed"] != true || na["reason"] != "session_limit" {
1135 t.Errorf("needs-attention data = %v", na)
1136 }
1137 if _, ok := evts[event.AgentBranchPushed]; ok {
1138 t.Error("a salvaged run must not emit agent:branch-pushed")
1139 }
1140 if got := determineStatus(context.Background(), state, &fakeTmux{}); got != "needs-attention" {
1141 t.Errorf("status = %q, want needs-attention", got)
1142 }
1143 })
1144
1145 // Salvage commits every untracked file .gitignore doesn't exclude: a
1146 // script the agent never committed, or a binary fixture, may be the work.
1147 // Build output belongs in the worker's $KLAUS_SCRATCH instead.
1148 t.Run("untracked script and binary are salvaged", func(t *testing.T) {
1149 origin, repo, worktree, branch := setupBareRemote(t)
1150 writeWorktreeFile(t, worktree, "scripts/gen.sh", []byte("#!/bin/sh\necho gen\n"), 0o755)
1151 writeWorktreeFile(t, worktree, "testdata/golden.png", binaryContent(2<<20), 0o644)
1152 writeWorktreeFile(t, worktree, ".gitignore", []byte("/out/\n"), 0o644)
1153 writeWorktreeFile(t, worktree, "out/tool", binaryContent(1024), 0o755)
1154
1155 _, state, _ := finalizeRealRepo(t, repo, worktree, branch, sessionLimitLog, "")
1156
1157 if subj, _ := gitOut(t, origin, "log", "-1", "--format=%s", branch); subj != "wip: klaus finalize salvage "+state.ID {
1158 t.Fatalf("origin tip = %q, want the salvage commit", subj)
1159 }
1160 tree, _ := gitOut(t, origin, "ls-tree", "-r", branch)
1161 for _, want := range []string{"100755 blob .*\tscripts/gen.sh", "100644 blob .*\ttestdata/golden.png", "\twip.txt", "\t.gitignore"} {
1162 if !regexp.MustCompile(`(?m)` + want + `$`).MatchString(tree) {
1163 t.Errorf("salvage commit lacks %q; the branch holds:\n%s", want, tree)
1164 }
1165 }
1166 if strings.Contains(tree, "out/tool") {
1167 t.Errorf("an ignored file was salvaged; the branch holds:\n%s", tree)
1168 }
1169 })
1170
1171 t.Run("push failure keeps the local branch", func(t *testing.T) {
1172 origin, repo, worktree, branch := setupBareRemote(t)
1173 runGitCmd(t, repo, "remote", "set-url", "origin", origin+"-gone")
1174
1175 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, sessionLimitLog, "")
1176
1177 files, err := gitOut(t, repo, "show", "--name-only", "--format=%s", "refs/heads/"+branch)
1178 if err != nil {
1179 t.Fatalf("local branch deleted after failed push: %v", err)
1180 }
1181 if !strings.Contains(files, "wip.txt") {
1182 t.Errorf("local branch should carry the WIP commit, got:\n%s", files)
1183 }
1184 na := runEvents(t, store.BaseDir(), state.ID)[event.AgentNeedsAttention]
1185 if na == nil || na["pushed"] != false || na["branch"] != branch {
1186 t.Errorf("needs-attention data = %v", na)
1187 }
1188 })
1189
1190 cleanLog := `{"type":"result","subtype":"success","result":"Pushed the branch.","total_cost_usd":1,"duration_ms":1000}
1191`
1192 t.Run("pushed branch with uncommitted changes is salvaged on top", func(t *testing.T) {
1193 origin, repo, worktree, branch := setupBareRemote(t)
1194 commitAndPush(t, worktree, branch)
1195 if err := os.WriteFile(filepath.Join(worktree, "late.txt"), []byte("after push\n"), 0644); err != nil {
1196 t.Fatal(err)
1197 }
1198
1199 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, cleanLog, "")
1200
1201 evts := runEvents(t, store.BaseDir(), state.ID)
1202 if na := evts[event.AgentNeedsAttention]; na == nil || na["pushed"] != true || na["reason"] != "no_pr" {
1203 t.Errorf("needs-attention data = %v", na)
1204 }
1205 if _, ok := evts[event.AgentBranchPushed]; ok {
1206 t.Error("a salvaged run must not emit agent:branch-pushed")
1207 }
1208 if subj, _ := gitOut(t, origin, "log", "-1", "--format=%s", branch); subj != "wip: klaus finalize salvage "+state.ID {
1209 t.Errorf("origin tip = %q, want the salvage WIP commit", subj)
1210 }
1211 })
1212
1213 // A stale origin/<branch> must not count as pushed.
1214 t.Run("remote branch deleted since last fetch is pushed again", func(t *testing.T) {
1215 origin, repo, worktree, branch := setupBareRemote(t)
1216 commitAndPush(t, worktree, branch)
1217 runGitCmd(t, origin, "branch", "-D", branch) // no fetch: origin/<branch> is stale
1218
1219 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, cleanLog, "")
1220
1221 local, _ := gitOut(t, repo, "rev-parse", "refs/heads/"+branch)
1222 if remote, err := gitOut(t, origin, "rev-parse", "--verify", "refs/heads/"+branch); err != nil || remote != local {
1223 t.Fatalf("branch not re-pushed: origin=%q (%v), local=%q", remote, err, local)
1224 }
1225 na := runEvents(t, store.BaseDir(), state.ID)[event.AgentNeedsAttention]
1226 if na == nil || na["pushed"] != true {
1227 t.Errorf("needs-attention data = %v", na)
1228 }
1229 })
1230
1231 t.Run("unreachable origin with stale ref reports pushed false", func(t *testing.T) {
1232 origin, repo, worktree, branch := setupBareRemote(t)
1233 commitAndPush(t, worktree, branch)
1234 runGitCmd(t, repo, "remote", "set-url", "origin", origin+"-gone")
1235
1236 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, cleanLog, "")
1237
1238 if _, err := gitOut(t, repo, "rev-parse", "--verify", "refs/heads/"+branch); err != nil {
1239 t.Errorf("local branch deleted: %v", err)
1240 }
1241 na := runEvents(t, store.BaseDir(), state.ID)[event.AgentNeedsAttention]
1242 if na == nil || na["pushed"] != false {
1243 t.Errorf("unverified remote must report pushed=false, got %v", na)
1244 }
1245 })
1246}
1247
1248// binaryContent is n bytes that git takes for binary (they hold NULs).
1249func binaryContent(n int) []byte {
1250 b := make([]byte, n)
1251 for i := range b {
1252 b[i] = byte(i % 7)
1253 }
1254 return b
1255}
1256
1257func writeWorktreeFile(t *testing.T, worktree, rel string, data []byte, mode os.FileMode) {
1258 t.Helper()
1259 path := filepath.Join(worktree, rel)
1260 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
1261 t.Fatal(err)
1262 }
1263 if err := os.WriteFile(path, data, mode); err != nil {
1264 t.Fatal(err)
1265 }
1266 if err := os.Chmod(path, mode); err != nil { // WriteFile's mode is masked by umask
1267 t.Fatal(err)
1268 }
1269}
1270
1271// commitAndPush commits the worktree's changes and pushes the branch, leaving
1272// origin/<branch> equal to the local tip.
1273func commitAndPush(t *testing.T, worktree, branch string) {
1274 t.Helper()
1275 runGitCmd(t, worktree, "add", "-A")
1276 runGitCmd(t, worktree, "commit", "-m", "feat: done")
1277 runGitCmd(t, worktree, "push", "-u", "origin", branch)
1278}
1279
1280func TestFinalizeWithPRDeletesBranch(t *testing.T) {
1281 _, repo, worktree, branch := setupBareRemote(t)
1282 commitAndPush(t, worktree, branch)
1283 prLog := `{"type":"assistant","message":{"content":[{"type":"text","text":"Opened https://github.com/acme/widget/pull/9"}]}}
1284{"type":"result","subtype":"success","total_cost_usd":1,"duration_ms":1000}
1285`
1286 // The bare remote's path isn't a GitHub URL; launch recorded a PR run,
1287 // as it does for a repo on GitHub.
1288 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, prLog, run.DeliveryPR)
1289
1290 if _, err := gitOut(t, repo, "rev-parse", "--verify", "refs/heads/"+branch); err == nil {
1291 t.Error("local branch should be deleted after a PR run")
1292 }
1293 if state.NeedsAttention != nil {
1294 t.Errorf("NeedsAttention = %q, want nil", *state.NeedsAttention)
1295 }
1296 evts := runEvents(t, store.BaseDir(), state.ID)
1297 if _, ok := evts[event.AgentNeedsAttention]; ok {
1298 t.Error("PR run must not emit agent:needs-attention")
1299 }
1300 if _, ok := evts[event.AgentCompleted]; !ok {
1301 t.Error("expected agent:completed")
1302 }
1303 if _, ok := evts[event.AgentPRCreated]; !ok {
1304 t.Error("expected agent:pr-created")
1305 }
1306 if _, ok := evts[event.AgentBranchPushed]; ok {
1307 t.Error("PR run must not emit agent:branch-pushed")
1308 }
1309 if state.PushedSHA != nil {
1310 t.Errorf("PushedSHA = %q, want nil for a PR run", *state.PushedSHA)
1311 }
1312}
1313
1314// Regression for #281: a direct-push run (branch pushed, no PR) must be
1315// visible as agent:branch-pushed and awaiting-integration.
1316func TestFinalizeDirectPush(t *testing.T) {
1317 cleanLog := `{"type":"result","subtype":"success","result":"Pushed the branch.","total_cost_usd":1,"duration_ms":1000}
1318`
1319 t.Run("pushed branch emits branch-pushed and records the SHA", func(t *testing.T) {
1320 origin, repo, worktree, branch := setupBareRemote(t)
1321 commitAndPush(t, worktree, branch)
1322 head, err := gitOut(t, origin, "rev-parse", "refs/heads/"+branch)
1323 if err != nil {
1324 t.Fatalf("branch missing on origin: %v", err)
1325 }
1326
1327 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, cleanLog, "")
1328
1329 if state.PushedBranch == nil || *state.PushedBranch != branch || state.PushedSHA == nil || *state.PushedSHA != head {
1330 t.Errorf("recorded push = %q@%q, want %s@%s", strOrNil(state.PushedBranch), strOrNil(state.PushedSHA), branch, head)
1331 }
1332 if state.NeedsAttention != nil {
1333 t.Errorf("NeedsAttention = %q, want nil", *state.NeedsAttention)
1334 }
1335 if got := determineStatus(context.Background(), state, &fakeTmux{}); got != "awaiting-integration" {
1336 t.Errorf("status = %q, want awaiting-integration", got)
1337 }
1338
1339 evts := runEvents(t, store.BaseDir(), state.ID)
1340 bp, ok := evts[event.AgentBranchPushed]
1341 if !ok {
1342 t.Fatalf("expected agent:branch-pushed, got %v", evts)
1343 }
1344 if bp["branch"] != branch || bp["sha"] != head || bp["repo"] != origin {
1345 t.Errorf("branch-pushed data = %v, want branch %s sha %s repo %s", bp, branch, head, origin)
1346 }
1347 if _, ok := evts[event.AgentCompleted]; !ok {
1348 t.Error("expected agent:completed")
1349 }
1350 for _, typ := range []string{event.AgentNeedsAttention, event.AgentPRCreated} {
1351 if _, ok := evts[typ]; ok {
1352 t.Errorf("unexpected %s", typ)
1353 }
1354 }
1355
1356 // The remote branch is the record: no WIP commit, local branch gone.
1357 if subj, _ := gitOut(t, origin, "log", "-1", "--format=%s", branch); subj != "feat: done" {
1358 t.Errorf("origin tip = %q, want the agent's commit", subj)
1359 }
1360 if _, err := gitOut(t, repo, "rev-parse", "--verify", "refs/heads/"+branch); err == nil {
1361 t.Error("local branch should be deleted once origin has it")
1362 }
1363 })
1364
1365 // A GitHub PR URL the agent came across, as a test fixture, doesn't make
1366 // a direct-push run a PR run, whether launch recorded the delivery or the
1367 // state predates the record.
1368 for name, delivery := range map[string]string{"recorded": run.DeliveryPush, "unrecorded": ""} {
1369 t.Run("a PR URL in the log is not the run's, delivery "+name, func(t *testing.T) {
1370 _, repo, worktree, branch := setupBareRemote(t)
1371 commitAndPush(t, worktree, branch)
1372 const fixturePR = "https://github.com/acme/widget/pull/7"
1373 fixtureLog := `{"type":"user","message":{"content":[{"type":"tool_result","content":"--- FAIL: want ` + fixturePR + `"}]}}
1374{"type":"assistant","message":{"content":[{"type":"text","text":"The knot links ` + fixturePR + `; fixing the test."}]}}
1375` + cleanLog
1376
1377 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, fixtureLog, delivery)
1378
1379 if state.PRURL != nil {
1380 t.Errorf("PRURL = %q, want none", *state.PRURL)
1381 }
1382 if state.PushedBranch == nil || *state.PushedBranch != branch || state.NeedsAttention != nil {
1383 t.Errorf("pushed branch = %q, needs attention = %q; want %s pushed and nothing to salvage",
1384 strOrNil(state.PushedBranch), strOrNil(state.NeedsAttention), branch)
1385 }
1386 evts := runEvents(t, store.BaseDir(), state.ID)
1387 if _, ok := evts[event.AgentPRCreated]; ok {
1388 t.Error("unexpected agent:pr-created")
1389 }
1390 if _, ok := evts[event.AgentBranchPushed]; !ok {
1391 t.Errorf("expected agent:branch-pushed, got %v", evts)
1392 }
1393 })
1394 }
1395
1396 t.Run("failed WIP commit keeps the worktree", func(t *testing.T) {
1397 if os.Geteuid() == 0 {
1398 t.Skip("root can read the unreadable file, so git add succeeds")
1399 }
1400 _, repo, worktree, branch := setupBareRemote(t)
1401 commitAndPush(t, worktree, branch)
1402 unreadable := filepath.Join(worktree, "unreadable.txt")
1403 if err := os.WriteFile(unreadable, []byte("uncommitted\n"), 0o000); err != nil {
1404 t.Fatal(err)
1405 }
1406
1407 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, cleanLog, "")
1408
1409 if _, err := os.Stat(unreadable); err != nil {
1410 t.Errorf("uncommitted file lost: %v", err)
1411 }
1412 evts := runEvents(t, store.BaseDir(), state.ID)
1413 if _, ok := evts[event.AgentNeedsAttention]; !ok {
1414 t.Errorf("expected agent:needs-attention, got %v", evts)
1415 }
1416 if _, ok := evts[event.AgentBranchPushed]; ok {
1417 t.Error("a dirty run must not emit agent:branch-pushed")
1418 }
1419 })
1420
1421 t.Run("nothing pushed emits no branch-pushed", func(t *testing.T) {
1422 _, repo, worktree, branch := setupBareRemote(t)
1423 if err := os.Remove(filepath.Join(worktree, "wip.txt")); err != nil {
1424 t.Fatal(err)
1425 }
1426
1427 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, cleanLog, "")
1428
1429 evts := runEvents(t, store.BaseDir(), state.ID)
1430 if _, ok := evts[event.AgentBranchPushed]; ok {
1431 t.Errorf("unexpected agent:branch-pushed: %v", evts)
1432 }
1433 if _, ok := evts[event.AgentCompleted]; !ok {
1434 t.Error("expected agent:completed")
1435 }
1436 if state.PushedBranch != nil || state.PushedSHA != nil {
1437 t.Errorf("recorded push = %q@%q, want none", strOrNil(state.PushedBranch), strOrNil(state.PushedSHA))
1438 }
1439 if got := determineStatus(context.Background(), state, &fakeTmux{}); got != "exited" {
1440 t.Errorf("status = %q, want exited", got)
1441 }
1442 })
1443}
1444
1445func strOrNil(p *string) string {
1446 if p == nil {
1447 return "<nil>"
1448 }
1449 return *p
1450}