gunk-dev/the-valley

hidden_test.go

source30e24c82839bmain's published tip history
49.8 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 exit", suffix: "\n" + `{"type":"klaus_exit","exit_code":1}`},
469 } {
470 t.Run(tc.name, func(t *testing.T) {
471 const sessionID = "79dcfb08-4de4-45f4-b7db-056bccbc3a00"
472 logContent := tc.prefix + `{"type":"result","subtype":"success","is_error":true,"session_id":"` + sessionID + `","total_cost_usd":1.2,"duration_ms":100}` + tc.suffix
473 state, store := setupFinalizeTest(t, logContent)
474 subtype, err := finalizeFromLog(store, state)
475 if err != nil {
476 t.Fatal(err)
477 }
478 if subtype != "success" || state.FailureReason != nil {
479 t.Fatalf("subtype = %q, FailureReason = %v; want success without failure", subtype, state.FailureReason)
480 }
481 assertCost(t, state, 1.2)
482 assertDuration(t, state, 100)
483 if state.ClaudeSessionID == nil || *state.ClaudeSessionID != sessionID {
484 t.Fatalf("ClaudeSessionID = %v, want %q", state.ClaudeSessionID, sessionID)
485 }
486 })
487 }
488
489 t.Run("extracts PR URL from assistant text", func(t *testing.T) {
490 logContent := `{"type":"system","subtype":"init","model":"claude-sonnet-4-5-20250929"}
491{"type":"assistant","message":{"content":[{"type":"text","text":"I'll create the PR now."}]}}
492{"type":"assistant","message":{"content":[{"type":"text","text":"Created PR at https://github.com/maintainer/klaus/pull/42"}]}}
493{"type":"result","total_cost_usd":1.5,"duration_ms":30000}
494`
495 state, store := setupFinalizeTest(t, logContent)
496 if _, err := finalizeFromLog(store, state); err != nil {
497 t.Fatalf("finalizeFromLog() error: %v", err)
498 }
499 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/42")
500 assertCost(t, state, 1.5)
501 assertDuration(t, state, 30000)
502 if state.ResolvedModel != "claude-sonnet-4-5-20250929" {
503 t.Errorf("ResolvedModel = %q, want the init event's model", state.ResolvedModel)
504 }
505 })
506
507 t.Run("extracts PR URL from tool_result event", func(t *testing.T) {
508 logContent := `{"type":"system","subtype":"init","model":"claude-sonnet-4-5-20250929"}
509{"type":"assistant","message":{"content":[{"type":"tool_use","name":"Bash","input":{"command":"gh pr create --title test"}}]}}
510{"type":"tool_result","content":"https://github.com/maintainer/klaus/pull/99\n"}
511{"type":"assistant","message":{"content":[{"type":"text","text":"Done! I created the PR."}]}}
512{"type":"result","total_cost_usd":2.0,"duration_ms":45000}
513`
514 state, store := setupFinalizeTest(t, logContent)
515 if _, err := finalizeFromLog(store, state); err != nil {
516 t.Fatalf("finalizeFromLog() error: %v", err)
517 }
518 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/99")
519 })
520
521 t.Run("extracts PR URL from user message with tool_result content", func(t *testing.T) {
522 logContent := `{"type":"system","subtype":"init","model":"claude-sonnet-4-5-20250929"}
523{"type":"user","message":{"content":[{"type":"tool_result","content":"https://github.com/maintainer/klaus/pull/7\n"}]}}
524{"type":"result","total_cost_usd":1.0,"duration_ms":10000}
525`
526 state, store := setupFinalizeTest(t, logContent)
527 if _, err := finalizeFromLog(store, state); err != nil {
528 t.Fatalf("finalizeFromLog() error: %v", err)
529 }
530 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/7")
531 })
532
533 t.Run("handles markdown link in assistant text", func(t *testing.T) {
534 logContent := `{"type":"assistant","message":{"content":[{"type":"text","text":"Created [PR #42](https://github.com/maintainer/klaus/pull/42) for review."}]}}
535{"type":"result","total_cost_usd":1.0,"duration_ms":5000}
536`
537 state, store := setupFinalizeTest(t, logContent)
538 if _, err := finalizeFromLog(store, state); err != nil {
539 t.Fatalf("finalizeFromLog() error: %v", err)
540 }
541 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/42")
542 })
543
544 t.Run("survives malformed JSONL lines", func(t *testing.T) {
545 logContent := `{"type":"system","subtype":"init"}
546not valid json at all
547{"truncated":
548{"type":"assistant","message":{"content":[{"type":"text","text":"PR: https://github.com/maintainer/klaus/pull/5"}]}}
549{"type":"result","total_cost_usd":0.5,"duration_ms":2000}
550`
551 state, store := setupFinalizeTest(t, logContent)
552 if _, err := finalizeFromLog(store, state); err != nil {
553 t.Fatalf("finalizeFromLog() error: %v", err)
554 }
555 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/5")
556 assertCost(t, state, 0.5)
557 })
558
559 t.Run("no PR URL in log", func(t *testing.T) {
560 logContent := `{"type":"assistant","message":{"content":[{"type":"text","text":"Just doing some work."}]}}
561{"type":"result","total_cost_usd":0.1,"duration_ms":1000}
562`
563 state, store := setupFinalizeTest(t, logContent)
564 if _, err := finalizeFromLog(store, state); err != nil {
565 t.Fatalf("finalizeFromLog() error: %v", err)
566 }
567 if state.PRURL != nil {
568 t.Errorf("expected nil PRURL, got %q", *state.PRURL)
569 }
570 })
571
572 t.Run("last PR URL wins", func(t *testing.T) {
573 logContent := `{"type":"assistant","message":{"content":[{"type":"text","text":"First PR: https://github.com/maintainer/klaus/pull/1"}]}}
574{"type":"assistant","message":{"content":[{"type":"text","text":"Recreated PR: https://github.com/maintainer/klaus/pull/2"}]}}
575{"type":"result","total_cost_usd":1.0,"duration_ms":5000}
576`
577 state, store := setupFinalizeTest(t, logContent)
578 if _, err := finalizeFromLog(store, state); err != nil {
579 t.Fatalf("finalizeFromLog() error: %v", err)
580 }
581 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/2")
582 })
583
584 t.Run("preserves PRURL set before finalization", func(t *testing.T) {
585 // Simulates --pr mode: launch.go sets state.PRURL to the real PR
586 // before the agent runs. The agent's tool output contains unrelated
587 // PR URLs (e.g. from source code, test fixtures, or comments) that
588 // would otherwise clobber the correct value.
589 logContent := `{"type":"assistant","message":{"content":[{"type":"text","text":"Looking at https://github.com/other/repo/pull/999 for reference"}]}}
590{"type":"tool_result","content":"see https://github.com/some/fixture/pull/123 in test data"}
591{"type":"result","total_cost_usd":1.0,"duration_ms":5000}
592`
593 state, store := setupFinalizeTest(t, logContent)
594 existing := "https://github.com/maintainer/klaus/pull/42"
595 state.PRURL = &existing
596
597 if _, err := finalizeFromLog(store, state); err != nil {
598 t.Fatalf("finalizeFromLog() error: %v", err)
599 }
600 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/42")
601 })
602
603 t.Run("marks FailureReason on error_during_execution result", func(t *testing.T) {
604 // Mirrors the real crash: a cross-worktree --resume that exits
605 // instantly with no turns. _finalize must not treat this as success.
606 logContent := `{"type":"system","subtype":"init"}
607{"type":"result","subtype":"error_during_execution","is_error":true,"num_turns":0,"total_cost_usd":0,"errors":["No conversation found with session ID: deadbeef"]}
608`
609 state, store := setupFinalizeTest(t, logContent)
610 subtype, err := finalizeFromLog(store, state)
611 if err != nil {
612 t.Fatalf("finalizeFromLog() error: %v", err)
613 }
614 if subtype != "error_during_execution" {
615 t.Errorf("subtype = %q, want error_during_execution", subtype)
616 }
617 if state.FailureReason == nil {
618 t.Fatal("expected FailureReason to be set, got nil")
619 }
620 if !strings.Contains(*state.FailureReason, "error_during_execution") {
621 t.Errorf("FailureReason = %q, want it to mention the subtype", *state.FailureReason)
622 }
623 if !strings.Contains(*state.FailureReason, "No conversation found") {
624 t.Errorf("FailureReason = %q, want it to include the first error", *state.FailureReason)
625 }
626 // A crashed run had no PR; PRURL must stay nil.
627 if state.PRURL != nil {
628 t.Errorf("expected nil PRURL on crash, got %q", *state.PRURL)
629 }
630 })
631
632 t.Run("marks FailureReason when is_error is true without a subtype", func(t *testing.T) {
633 logContent := `{"type":"result","is_error":true,"total_cost_usd":0.2,"duration_ms":1000}
634`
635 state, store := setupFinalizeTest(t, logContent)
636 if _, err := finalizeFromLog(store, state); err != nil {
637 t.Fatalf("finalizeFromLog() error: %v", err)
638 }
639 if state.FailureReason == nil {
640 t.Fatal("expected FailureReason to be set when is_error is true")
641 }
642 })
643
644 t.Run("successful result leaves FailureReason nil and records cost", func(t *testing.T) {
645 logContent := `{"type":"assistant","message":{"content":[{"type":"text","text":"Done: https://github.com/maintainer/klaus/pull/12"}]}}
646{"type":"result","subtype":"success","is_error":false,"num_turns":7,"total_cost_usd":1.25,"duration_ms":20000}
647`
648 state, store := setupFinalizeTest(t, logContent)
649 if _, err := finalizeFromLog(store, state); err != nil {
650 t.Fatalf("finalizeFromLog() error: %v", err)
651 }
652 if state.FailureReason != nil {
653 t.Errorf("expected nil FailureReason on success, got %q", *state.FailureReason)
654 }
655 assertCost(t, state, 1.25)
656 assertDuration(t, state, 20000)
657 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/12")
658 })
659
660 t.Run("extracts PRURL from log when not set before finalization", func(t *testing.T) {
661 // Simulates new-PR mode: state.PRURL is nil until the agent runs
662 // `gh pr create`. Regex extraction fills it in from the log.
663 logContent := `{"type":"assistant","message":{"content":[{"type":"text","text":"Creating PR now."}]}}
664{"type":"tool_result","content":"https://github.com/maintainer/klaus/pull/77\n"}
665{"type":"result","total_cost_usd":1.0,"duration_ms":5000}
666`
667 state, store := setupFinalizeTest(t, logContent)
668 if state.PRURL != nil {
669 t.Fatalf("test precondition: expected nil PRURL before finalize")
670 }
671
672 if _, err := finalizeFromLog(store, state); err != nil {
673 t.Fatalf("finalizeFromLog() error: %v", err)
674 }
675 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/77")
676 })
677
678 // A run that delivers by pushing its branch takes no PR URL from its log,
679 // as launch recorded or, in state that predates the record, as its origin
680 // decides; a run that delivers by PR takes its own.
681 t.Run("delivery decides whether the log's PR URL is the run's", func(t *testing.T) {
682 const prURL = "https://github.com/maintainer/klaus/pull/7"
683 logContent := `{"type":"user","message":{"content":[{"type":"tool_result","content":"fixture: ` + prURL + `\n"}]}}
684{"type":"assistant","message":{"content":[{"type":"text","text":"The knot links ` + prURL + `"}]}}
685{"type":"result","subtype":"success","total_cost_usd":1.0,"duration_ms":5000}
686`
687 githubClone := repoWithOrigin(t, "https://github.com/maintainer/klaus.git")
688 valleyClone := repoWithOrigin(t, "git@10.0.2.1:the-valley.git")
689 for _, tc := range []struct {
690 name, delivery, clone string
691 wantPR bool
692 }{
693 {name: "recorded push", delivery: run.DeliveryPush, clone: githubClone},
694 {name: "unrecorded, origin not on GitHub", clone: valleyClone},
695 {name: "recorded PR", delivery: run.DeliveryPR, clone: githubClone, wantPR: true},
696 {name: "unrecorded, origin on GitHub", clone: githubClone, wantPR: true},
697 } {
698 t.Run(tc.name, func(t *testing.T) {
699 state, store := setupFinalizeTest(t, logContent)
700 state.Delivery, state.CloneDir = tc.delivery, &tc.clone
701 if _, err := finalizeFromLog(store, state); err != nil {
702 t.Fatal(err)
703 }
704 if tc.wantPR {
705 assertPRURL(t, state, prURL)
706 } else if state.PRURL != nil {
707 t.Errorf("PRURL = %q, want none for a run that delivers by push", *state.PRURL)
708 }
709 })
710 }
711 })
712
713 t.Run("rejects placeholder PR URL in assistant text", func(t *testing.T) {
714 logContent := `{"type":"system","subtype":"init","model":"claude-sonnet-4-5-20250929"}
715{"type":"assistant","message":{"content":[{"type":"text","text":"You can create a PR like https://github.com/owner/repo/pull/123 for review."}]}}
716{"type":"result","total_cost_usd":0.5,"duration_ms":10000}
717`
718 state, store := setupFinalizeTest(t, logContent)
719 if _, err := finalizeFromLog(store, state); err != nil {
720 t.Fatalf("finalizeFromLog() error: %v", err)
721 }
722 if state.PRURL != nil {
723 t.Errorf("expected nil PRURL for placeholder URL, got %q", *state.PRURL)
724 }
725 })
726
727 t.Run("prefers tool_result matching TargetRepo over assistant text from foreign repo", func(t *testing.T) {
728 logContent := `{"type":"system","subtype":"init","model":"claude-sonnet-4-5-20250929"}
729{"type":"assistant","message":{"content":[{"type":"text","text":"Check https://github.com/someone-else/other/pull/9 for example"}]}}
730{"type":"tool_result","content":"https://github.com/maintainer/klaus/pull/310\n"}
731{"type":"result","total_cost_usd":1.0,"duration_ms":15000}
732`
733 state, store := setupFinalizeTest(t, logContent)
734 target := "maintainer/klaus"
735 state.TargetRepo = &target
736 if _, err := finalizeFromLog(store, state); err != nil {
737 t.Fatalf("finalizeFromLog() error: %v", err)
738 }
739 assertPRURL(t, state, "https://github.com/maintainer/klaus/pull/310")
740 })
741
742 t.Run("rejects placeholders in tool_result", func(t *testing.T) {
743 for _, placeholder := range []string{
744 "https://github.com/owner/repo/pull/123",
745 "https://github.com/OWNER/REPO/pull/123",
746 "https://github.com/<owner>/<repo>/pull/123",
747 "https://github.com/org/repo/pull/123",
748 "https://github.com/user/repo/pull/123",
749 } {
750 logContent := `{"type":"tool_result","content":"` + placeholder + `\n"}
751{"type":"result","total_cost_usd":0.5,"duration_ms":5000}
752`
753 state, store := setupFinalizeTest(t, logContent)
754 if _, err := finalizeFromLog(store, state); err != nil {
755 t.Fatalf("finalizeFromLog() error: %v", err)
756 }
757 if state.PRURL != nil {
758 t.Errorf("expected nil PRURL for placeholder %q, got %q", placeholder, *state.PRURL)
759 }
760 }
761 })
762}
763
764func TestExtractClaudeSessionID(t *testing.T) {
765 t.Run("extracts session_id from result event", func(t *testing.T) {
766 logContent := `{"type":"system","subtype":"init","model":"claude-sonnet-4-5-20250929"}
767{"type":"assistant","message":{"content":[{"type":"text","text":"Working on it..."}]}}
768{"type":"result","session_id":"a1b2c3d4-e5f6-7890-abcd-ef1234567890","total_cost_usd":1.5,"duration_ms":30000}
769`
770 logFile := writeTestLog(t, logContent)
771 got := ExtractClaudeSessionID(logFile)
772 if got != "a1b2c3d4-e5f6-7890-abcd-ef1234567890" {
773 t.Errorf("ExtractClaudeSessionID() = %q, want UUID", got)
774 }
775 })
776
777 t.Run("returns empty when no result event", func(t *testing.T) {
778 logContent := `{"type":"system","subtype":"init"}
779{"type":"assistant","message":{"content":[{"type":"text","text":"Hello"}]}}
780`
781 logFile := writeTestLog(t, logContent)
782 got := ExtractClaudeSessionID(logFile)
783 if got != "" {
784 t.Errorf("ExtractClaudeSessionID() = %q, want empty", got)
785 }
786 })
787
788 t.Run("returns empty when result has no session_id", func(t *testing.T) {
789 logContent := `{"type":"result","total_cost_usd":0.5,"duration_ms":1000}
790`
791 logFile := writeTestLog(t, logContent)
792 got := ExtractClaudeSessionID(logFile)
793 if got != "" {
794 t.Errorf("ExtractClaudeSessionID() = %q, want empty", got)
795 }
796 })
797
798 t.Run("returns empty for nonexistent file", func(t *testing.T) {
799 got := ExtractClaudeSessionID("/nonexistent/path/log.jsonl")
800 if got != "" {
801 t.Errorf("ExtractClaudeSessionID() = %q, want empty", got)
802 }
803 })
804
805 t.Run("survives malformed lines", func(t *testing.T) {
806 logContent := `not json
807{"truncated":
808{"type":"result","session_id":"deadbeef-1234-5678-9abc-def012345678","total_cost_usd":0.1}
809`
810 logFile := writeTestLog(t, logContent)
811 got := ExtractClaudeSessionID(logFile)
812 if got != "deadbeef-1234-5678-9abc-def012345678" {
813 t.Errorf("ExtractClaudeSessionID() = %q, want UUID", got)
814 }
815 })
816}
817
818func TestEmitFinalizeEvents(t *testing.T) {
819 cost := 1.5
820 dur := int64(30000)
821 prURL := "https://github.com/owner/repo/pull/42"
822
823 t.Run("failed run emits needs-attention and nothing else", func(t *testing.T) {
824 baseDir := t.TempDir()
825 reason := "error_during_execution: No conversation found"
826 state := &run.State{
827 ID: "20260628-0900-fail",
828 CostUSD: &cost,
829 DurationMS: &dur,
830 PRURL: &prURL, // even with a stale URL, no pr-created on crash
831 FailureReason: &reason,
832 }
833
834 emitFinalizeEvents(baseDir, state, nil)
835
836 types := eventTypesFor(t, baseDir, state.ID)
837 if len(types) != 1 || types[0] != event.AgentNeedsAttention {
838 t.Fatalf("expected only %q, got %v", event.AgentNeedsAttention, types)
839 }
840 })
841
842 t.Run("successful run with PR emits completed and pr-created", func(t *testing.T) {
843 baseDir := t.TempDir()
844 state := &run.State{
845 ID: "20260628-0901-ok",
846 CostUSD: &cost,
847 DurationMS: &dur,
848 PRURL: &prURL,
849 }
850
851 emitFinalizeEvents(baseDir, state, nil)
852
853 types := eventTypesFor(t, baseDir, state.ID)
854 if !containsEvent(types, event.AgentCompleted) {
855 t.Errorf("expected %q in %v", event.AgentCompleted, types)
856 }
857 if !containsEvent(types, event.AgentPRCreated) {
858 t.Errorf("expected %q in %v", event.AgentPRCreated, types)
859 }
860 if containsEvent(types, event.AgentNeedsAttention) {
861 t.Errorf("did not expect %q in %v", event.AgentNeedsAttention, types)
862 }
863 })
864
865 t.Run("successful run without PR emits completed only", func(t *testing.T) {
866 baseDir := t.TempDir()
867 state := &run.State{
868 ID: "20260628-0902-nopr",
869 CostUSD: &cost,
870 DurationMS: &dur,
871 }
872
873 emitFinalizeEvents(baseDir, state, nil)
874
875 types := eventTypesFor(t, baseDir, state.ID)
876 if len(types) != 1 || types[0] != event.AgentCompleted {
877 t.Fatalf("expected only %q, got %v", event.AgentCompleted, types)
878 }
879 })
880}
881
882func eventTypesFor(t *testing.T, baseDir, runID string) []string {
883 t.Helper()
884 evts, err := event.NewLog(baseDir).Read()
885 if err != nil {
886 t.Fatalf("reading event log: %v", err)
887 }
888 var types []string
889 for _, e := range evts {
890 if e.RunID == runID {
891 types = append(types, e.Type)
892 }
893 }
894 return types
895}
896
897func containsEvent(types []string, want string) bool {
898 for _, ty := range types {
899 if ty == want {
900 return true
901 }
902 }
903 return false
904}
905
906func writeTestLog(t *testing.T, content string) string {
907 t.Helper()
908 logFile := filepath.Join(t.TempDir(), "test.jsonl")
909 if err := os.WriteFile(logFile, []byte(content), 0644); err != nil {
910 t.Fatalf("writing log file: %v", err)
911 }
912 return logFile
913}
914
915// setupFinalizeTest creates a temporary log file and state for testing finalizeFromLog.
916func setupFinalizeTest(t *testing.T, logContent string) (*run.State, run.StateStore) {
917 t.Helper()
918 dir := t.TempDir()
919
920 logFile := filepath.Join(dir, "test.jsonl")
921 if err := os.WriteFile(logFile, []byte(logContent), 0644); err != nil {
922 t.Fatalf("writing log file: %v", err)
923 }
924
925 stateDir := filepath.Join(dir, "runs")
926 if err := os.MkdirAll(stateDir, 0755); err != nil {
927 t.Fatalf("creating state dir: %v", err)
928 }
929
930 // Fixture origin so PR URL checks don't depend on this checkout.
931 cloneDir := repoWithOrigin(t, "https://github.com/maintainer/klaus.git")
932 state := &run.State{
933 ID: "test-run",
934 LogFile: &logFile,
935 CloneDir: &cloneDir,
936 }
937
938 store := &testStateStore{dir: stateDir, state: state}
939 return state, store
940}
941
942// testStateStore is a minimal StateStore for testing.
943type testStateStore struct {
944 dir string
945 state *run.State
946}
947
948func (s *testStateStore) Save(state *run.State) error {
949 s.state = state
950 return nil
951}
952
953func (s *testStateStore) Load(id string) (*run.State, error) {
954 return s.state, nil
955}
956
957func (s *testStateStore) List() ([]*run.State, error) {
958 return []*run.State{s.state}, nil
959}
960
961func (s *testStateStore) Delete(id string) error {
962 return nil
963}
964
965func (s *testStateStore) StateDir() string {
966 return s.dir
967}
968
969func (s *testStateStore) LogDir() string {
970 return s.dir
971}
972
973func (s *testStateStore) EnsureDirs() error {
974 return nil
975}
976
977// TestEmitFinalizeEventsNilState covers the gemini #277 follow-up: the finalize
978// path must no-op rather than dereference a nil run state.
979func TestEmitFinalizeEventsNilState(t *testing.T) {
980 // Should return early without panicking.
981 emitFinalizeEvents(t.TempDir(), nil, nil)
982}
983
984func assertPRURL(t *testing.T, state *run.State, want string) {
985 t.Helper()
986 if state.PRURL == nil {
987 t.Fatalf("expected PRURL %q, got nil", want)
988 }
989 if *state.PRURL != want {
990 t.Errorf("PRURL = %q, want %q", *state.PRURL, want)
991 }
992}
993
994func assertCost(t *testing.T, state *run.State, want float64) {
995 t.Helper()
996 if state.CostUSD == nil {
997 t.Fatalf("expected CostUSD %v, got nil", want)
998 }
999 if *state.CostUSD != want {
1000 t.Errorf("CostUSD = %v, want %v", *state.CostUSD, want)
1001 }
1002}
1003
1004func assertDuration(t *testing.T, state *run.State, want int64) {
1005 t.Helper()
1006 if state.DurationMS == nil {
1007 t.Fatalf("expected DurationMS %v, got nil", want)
1008 }
1009 if *state.DurationMS != want {
1010 t.Errorf("DurationMS = %v, want %v", *state.DurationMS, want)
1011 }
1012}
1013
1014const salvageChangeID = "zzzzyyyyxxxxwwwwvvvvuuuuttttssss"
1015
1016// finalizeRealRepo runs _finalize for a run on worktree/branch with the given
1017// log and the delivery launch recorded ("" for state that predates it). gh is
1018// stubbed (empty output); git is real.
1019func finalizeRealRepo(t *testing.T, repo, worktree, branch, logContent, delivery string) (*run.HomeDirStore, *run.State, *fakeRunner) {
1020 t.Helper()
1021 sessionID := "20260918-1205-salvage-session"
1022 t.Setenv("HOME", t.TempDir())
1023 t.Setenv(sessionIDEnv, sessionID)
1024 store, err := run.NewHomeDirStore(sessionID)
1025 if err != nil {
1026 t.Fatalf("NewHomeDirStore: %v", err)
1027 }
1028 if err := store.EnsureDirs(); err != nil {
1029 t.Fatalf("EnsureDirs: %v", err)
1030 }
1031 runID := "20260918-1205-salvage"
1032 logFile := filepath.Join(store.LogDir(), runID+".jsonl")
1033 if err := os.WriteFile(logFile, []byte(logContent), 0644); err != nil {
1034 t.Fatalf("writing log: %v", err)
1035 }
1036 state := &run.State{
1037 ID: runID,
1038 ChangeID: salvageChangeID,
1039 Prompt: "rename the thing",
1040 Branch: branch,
1041 Worktree: worktree,
1042 CreatedAt: "2026-09-18T12:05:00Z",
1043 LogFile: &logFile,
1044 CloneDir: &repo,
1045 Delivery: delivery,
1046 }
1047 if err := store.Save(state); err != nil {
1048 t.Fatalf("saving state: %v", err)
1049 }
1050
1051 r := &fakeRunner{}
1052 prev := budgetPauseRunner
1053 budgetPauseRunner = r
1054 t.Cleanup(func() { budgetPauseRunner = prev })
1055
1056 finalizeCmd.SetContext(context.Background())
1057 if err := finalizeCmd.RunE(finalizeCmd, []string{runID}); err != nil {
1058 t.Fatalf("_finalize: %v", err)
1059 }
1060 final, err := store.Load(runID)
1061 if err != nil {
1062 t.Fatalf("loading state: %v", err)
1063 }
1064 return store, final, r
1065}
1066
1067func runEvents(t *testing.T, baseDir, runID string) map[string]map[string]interface{} {
1068 t.Helper()
1069 evts, err := event.NewLog(baseDir).Read()
1070 if err != nil {
1071 t.Fatalf("reading events: %v", err)
1072 }
1073 byType := map[string]map[string]interface{}{}
1074 for _, e := range evts {
1075 if e.RunID == runID {
1076 byType[e.Type] = e.Data
1077 }
1078 }
1079 return byType
1080}
1081
1082func gitOut(t *testing.T, dir string, args ...string) (string, error) {
1083 t.Helper()
1084 out, err := exec.Command("git", append([]string{"-C", dir}, args...)...).CombinedOutput()
1085 return strings.TrimSpace(string(out)), err
1086}
1087
1088// Regression for #299: a session-limit stop (subtype success, no PR) must not
1089// destroy the agent's uncommitted work or its branch.
1090func TestFinalizeSalvagesRunWithoutPR(t *testing.T) {
1091 sessionLimitLog := `{"type":"assistant","message":{"content":[{"type":"text","text":"VM test passes."}]}}
1092{"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}
1093{"type":"klaus_exit","exit_code":1}
1094`
1095 t.Run("commits, pushes, and keeps the branch", func(t *testing.T) {
1096 origin, repo, worktree, branch := setupBareRemote(t)
1097
1098 store, state, r := finalizeRealRepo(t, repo, worktree, branch, sessionLimitLog, "")
1099
1100 if _, err := gitOut(t, repo, "rev-parse", "--verify", "refs/heads/"+branch); err != nil {
1101 t.Errorf("local branch deleted: %v", err)
1102 }
1103 files, err := gitOut(t, origin, "show", "--name-only", "--format=%s", branch)
1104 if err != nil {
1105 t.Fatalf("branch missing on origin: %v (%s)", err, files)
1106 }
1107 if !strings.Contains(files, "wip: klaus finalize salvage "+state.ID) || !strings.Contains(files, "wip.txt") {
1108 t.Errorf("origin tip should be the WIP commit with wip.txt, got:\n%s", files)
1109 }
1110 // The salvage commit skips hooks, so finalize adds the trailers itself.
1111 trailers, _ := gitOut(t, origin, "log", "-1", "--format=%(trailers:only,unfold)", branch)
1112 if want := "Change-Id: " + salvageChangeID + "\nKlaus-Run: " + state.ID; trailers != want {
1113 t.Errorf("salvage commit trailers = %q, want %q", trailers, want)
1114 }
1115 if _, err := os.Stat(worktree); !os.IsNotExist(err) {
1116 t.Errorf("worktree should be removed once the branch is safe, stat err = %v", err)
1117 }
1118 if state.NeedsAttention == nil || !strings.Contains(*state.NeedsAttention, branch) {
1119 t.Errorf("NeedsAttention should name the branch, got %v", state.NeedsAttention)
1120 }
1121 if len(r.ghCalls) != 0 {
1122 t.Errorf("salvage must not touch GitHub, got gh calls %v", r.ghCalls)
1123 }
1124
1125 evts := runEvents(t, store.BaseDir(), state.ID)
1126 if _, ok := evts[event.AgentCompleted]; ok {
1127 t.Error("agent:completed must not be emitted for a salvaged run")
1128 }
1129 na, ok := evts[event.AgentNeedsAttention]
1130 if !ok {
1131 t.Fatalf("expected agent:needs-attention, got %v", evts)
1132 }
1133 if na["branch"] != branch || na["pushed"] != true || na["reason"] != "session_limit" {
1134 t.Errorf("needs-attention data = %v", na)
1135 }
1136 if _, ok := evts[event.AgentBranchPushed]; ok {
1137 t.Error("a salvaged run must not emit agent:branch-pushed")
1138 }
1139 if got := determineStatus(context.Background(), state, &fakeTmux{}); got != "needs-attention" {
1140 t.Errorf("status = %q, want needs-attention", got)
1141 }
1142 })
1143
1144 // Salvage commits every untracked file .gitignore doesn't exclude: a
1145 // script the agent never committed, or a binary fixture, may be the work.
1146 // Build output belongs in the worker's $KLAUS_SCRATCH instead.
1147 t.Run("untracked script and binary are salvaged", func(t *testing.T) {
1148 origin, repo, worktree, branch := setupBareRemote(t)
1149 writeWorktreeFile(t, worktree, "scripts/gen.sh", []byte("#!/bin/sh\necho gen\n"), 0o755)
1150 writeWorktreeFile(t, worktree, "testdata/golden.png", binaryContent(2<<20), 0o644)
1151 writeWorktreeFile(t, worktree, ".gitignore", []byte("/out/\n"), 0o644)
1152 writeWorktreeFile(t, worktree, "out/tool", binaryContent(1024), 0o755)
1153
1154 _, state, _ := finalizeRealRepo(t, repo, worktree, branch, sessionLimitLog, "")
1155
1156 if subj, _ := gitOut(t, origin, "log", "-1", "--format=%s", branch); subj != "wip: klaus finalize salvage "+state.ID {
1157 t.Fatalf("origin tip = %q, want the salvage commit", subj)
1158 }
1159 tree, _ := gitOut(t, origin, "ls-tree", "-r", branch)
1160 for _, want := range []string{"100755 blob .*\tscripts/gen.sh", "100644 blob .*\ttestdata/golden.png", "\twip.txt", "\t.gitignore"} {
1161 if !regexp.MustCompile(`(?m)` + want + `$`).MatchString(tree) {
1162 t.Errorf("salvage commit lacks %q; the branch holds:\n%s", want, tree)
1163 }
1164 }
1165 if strings.Contains(tree, "out/tool") {
1166 t.Errorf("an ignored file was salvaged; the branch holds:\n%s", tree)
1167 }
1168 })
1169
1170 t.Run("push failure keeps the local branch", func(t *testing.T) {
1171 origin, repo, worktree, branch := setupBareRemote(t)
1172 runGitCmd(t, repo, "remote", "set-url", "origin", origin+"-gone")
1173
1174 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, sessionLimitLog, "")
1175
1176 files, err := gitOut(t, repo, "show", "--name-only", "--format=%s", "refs/heads/"+branch)
1177 if err != nil {
1178 t.Fatalf("local branch deleted after failed push: %v", err)
1179 }
1180 if !strings.Contains(files, "wip.txt") {
1181 t.Errorf("local branch should carry the WIP commit, got:\n%s", files)
1182 }
1183 na := runEvents(t, store.BaseDir(), state.ID)[event.AgentNeedsAttention]
1184 if na == nil || na["pushed"] != false || na["branch"] != branch {
1185 t.Errorf("needs-attention data = %v", na)
1186 }
1187 })
1188
1189 cleanLog := `{"type":"result","subtype":"success","result":"Pushed the branch.","total_cost_usd":1,"duration_ms":1000}
1190`
1191 t.Run("pushed branch with uncommitted changes is salvaged on top", func(t *testing.T) {
1192 origin, repo, worktree, branch := setupBareRemote(t)
1193 commitAndPush(t, worktree, branch)
1194 if err := os.WriteFile(filepath.Join(worktree, "late.txt"), []byte("after push\n"), 0644); err != nil {
1195 t.Fatal(err)
1196 }
1197
1198 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, cleanLog, "")
1199
1200 evts := runEvents(t, store.BaseDir(), state.ID)
1201 if na := evts[event.AgentNeedsAttention]; na == nil || na["pushed"] != true || na["reason"] != "no_pr" {
1202 t.Errorf("needs-attention data = %v", na)
1203 }
1204 if _, ok := evts[event.AgentBranchPushed]; ok {
1205 t.Error("a salvaged run must not emit agent:branch-pushed")
1206 }
1207 if subj, _ := gitOut(t, origin, "log", "-1", "--format=%s", branch); subj != "wip: klaus finalize salvage "+state.ID {
1208 t.Errorf("origin tip = %q, want the salvage WIP commit", subj)
1209 }
1210 })
1211
1212 // A stale origin/<branch> must not count as pushed.
1213 t.Run("remote branch deleted since last fetch is pushed again", func(t *testing.T) {
1214 origin, repo, worktree, branch := setupBareRemote(t)
1215 commitAndPush(t, worktree, branch)
1216 runGitCmd(t, origin, "branch", "-D", branch) // no fetch: origin/<branch> is stale
1217
1218 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, cleanLog, "")
1219
1220 local, _ := gitOut(t, repo, "rev-parse", "refs/heads/"+branch)
1221 if remote, err := gitOut(t, origin, "rev-parse", "--verify", "refs/heads/"+branch); err != nil || remote != local {
1222 t.Fatalf("branch not re-pushed: origin=%q (%v), local=%q", remote, err, local)
1223 }
1224 na := runEvents(t, store.BaseDir(), state.ID)[event.AgentNeedsAttention]
1225 if na == nil || na["pushed"] != true {
1226 t.Errorf("needs-attention data = %v", na)
1227 }
1228 })
1229
1230 t.Run("unreachable origin with stale ref reports pushed false", func(t *testing.T) {
1231 origin, repo, worktree, branch := setupBareRemote(t)
1232 commitAndPush(t, worktree, branch)
1233 runGitCmd(t, repo, "remote", "set-url", "origin", origin+"-gone")
1234
1235 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, cleanLog, "")
1236
1237 if _, err := gitOut(t, repo, "rev-parse", "--verify", "refs/heads/"+branch); err != nil {
1238 t.Errorf("local branch deleted: %v", err)
1239 }
1240 na := runEvents(t, store.BaseDir(), state.ID)[event.AgentNeedsAttention]
1241 if na == nil || na["pushed"] != false {
1242 t.Errorf("unverified remote must report pushed=false, got %v", na)
1243 }
1244 })
1245}
1246
1247// binaryContent is n bytes that git takes for binary (they hold NULs).
1248func binaryContent(n int) []byte {
1249 b := make([]byte, n)
1250 for i := range b {
1251 b[i] = byte(i % 7)
1252 }
1253 return b
1254}
1255
1256func writeWorktreeFile(t *testing.T, worktree, rel string, data []byte, mode os.FileMode) {
1257 t.Helper()
1258 path := filepath.Join(worktree, rel)
1259 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
1260 t.Fatal(err)
1261 }
1262 if err := os.WriteFile(path, data, mode); err != nil {
1263 t.Fatal(err)
1264 }
1265 if err := os.Chmod(path, mode); err != nil { // WriteFile's mode is masked by umask
1266 t.Fatal(err)
1267 }
1268}
1269
1270// commitAndPush commits the worktree's changes and pushes the branch, leaving
1271// origin/<branch> equal to the local tip.
1272func commitAndPush(t *testing.T, worktree, branch string) {
1273 t.Helper()
1274 runGitCmd(t, worktree, "add", "-A")
1275 runGitCmd(t, worktree, "commit", "-m", "feat: done")
1276 runGitCmd(t, worktree, "push", "-u", "origin", branch)
1277}
1278
1279func TestFinalizeWithPRDeletesBranch(t *testing.T) {
1280 _, repo, worktree, branch := setupBareRemote(t)
1281 commitAndPush(t, worktree, branch)
1282 prLog := `{"type":"assistant","message":{"content":[{"type":"text","text":"Opened https://github.com/acme/widget/pull/9"}]}}
1283{"type":"result","subtype":"success","total_cost_usd":1,"duration_ms":1000}
1284`
1285 // The bare remote's path isn't a GitHub URL; launch recorded a PR run,
1286 // as it does for a repo on GitHub.
1287 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, prLog, run.DeliveryPR)
1288
1289 if _, err := gitOut(t, repo, "rev-parse", "--verify", "refs/heads/"+branch); err == nil {
1290 t.Error("local branch should be deleted after a PR run")
1291 }
1292 if state.NeedsAttention != nil {
1293 t.Errorf("NeedsAttention = %q, want nil", *state.NeedsAttention)
1294 }
1295 evts := runEvents(t, store.BaseDir(), state.ID)
1296 if _, ok := evts[event.AgentNeedsAttention]; ok {
1297 t.Error("PR run must not emit agent:needs-attention")
1298 }
1299 if _, ok := evts[event.AgentCompleted]; !ok {
1300 t.Error("expected agent:completed")
1301 }
1302 if _, ok := evts[event.AgentPRCreated]; !ok {
1303 t.Error("expected agent:pr-created")
1304 }
1305 if _, ok := evts[event.AgentBranchPushed]; ok {
1306 t.Error("PR run must not emit agent:branch-pushed")
1307 }
1308 if state.PushedSHA != nil {
1309 t.Errorf("PushedSHA = %q, want nil for a PR run", *state.PushedSHA)
1310 }
1311}
1312
1313// Regression for #281: a direct-push run (branch pushed, no PR) must be
1314// visible as agent:branch-pushed and awaiting-integration.
1315func TestFinalizeDirectPush(t *testing.T) {
1316 cleanLog := `{"type":"result","subtype":"success","result":"Pushed the branch.","total_cost_usd":1,"duration_ms":1000}
1317`
1318 t.Run("pushed branch emits branch-pushed and records the SHA", func(t *testing.T) {
1319 origin, repo, worktree, branch := setupBareRemote(t)
1320 commitAndPush(t, worktree, branch)
1321 head, err := gitOut(t, origin, "rev-parse", "refs/heads/"+branch)
1322 if err != nil {
1323 t.Fatalf("branch missing on origin: %v", err)
1324 }
1325
1326 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, cleanLog, "")
1327
1328 if state.PushedBranch == nil || *state.PushedBranch != branch || state.PushedSHA == nil || *state.PushedSHA != head {
1329 t.Errorf("recorded push = %q@%q, want %s@%s", strOrNil(state.PushedBranch), strOrNil(state.PushedSHA), branch, head)
1330 }
1331 if state.NeedsAttention != nil {
1332 t.Errorf("NeedsAttention = %q, want nil", *state.NeedsAttention)
1333 }
1334 if got := determineStatus(context.Background(), state, &fakeTmux{}); got != "awaiting-integration" {
1335 t.Errorf("status = %q, want awaiting-integration", got)
1336 }
1337
1338 evts := runEvents(t, store.BaseDir(), state.ID)
1339 bp, ok := evts[event.AgentBranchPushed]
1340 if !ok {
1341 t.Fatalf("expected agent:branch-pushed, got %v", evts)
1342 }
1343 if bp["branch"] != branch || bp["sha"] != head || bp["repo"] != origin {
1344 t.Errorf("branch-pushed data = %v, want branch %s sha %s repo %s", bp, branch, head, origin)
1345 }
1346 if _, ok := evts[event.AgentCompleted]; !ok {
1347 t.Error("expected agent:completed")
1348 }
1349 for _, typ := range []string{event.AgentNeedsAttention, event.AgentPRCreated} {
1350 if _, ok := evts[typ]; ok {
1351 t.Errorf("unexpected %s", typ)
1352 }
1353 }
1354
1355 // The remote branch is the record: no WIP commit, local branch gone.
1356 if subj, _ := gitOut(t, origin, "log", "-1", "--format=%s", branch); subj != "feat: done" {
1357 t.Errorf("origin tip = %q, want the agent's commit", subj)
1358 }
1359 if _, err := gitOut(t, repo, "rev-parse", "--verify", "refs/heads/"+branch); err == nil {
1360 t.Error("local branch should be deleted once origin has it")
1361 }
1362 })
1363
1364 // A GitHub PR URL the agent came across, as a test fixture, doesn't make
1365 // a direct-push run a PR run, whether launch recorded the delivery or the
1366 // state predates the record.
1367 for name, delivery := range map[string]string{"recorded": run.DeliveryPush, "unrecorded": ""} {
1368 t.Run("a PR URL in the log is not the run's, delivery "+name, func(t *testing.T) {
1369 _, repo, worktree, branch := setupBareRemote(t)
1370 commitAndPush(t, worktree, branch)
1371 const fixturePR = "https://github.com/acme/widget/pull/7"
1372 fixtureLog := `{"type":"user","message":{"content":[{"type":"tool_result","content":"--- FAIL: want ` + fixturePR + `"}]}}
1373{"type":"assistant","message":{"content":[{"type":"text","text":"The knot links ` + fixturePR + `; fixing the test."}]}}
1374` + cleanLog
1375
1376 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, fixtureLog, delivery)
1377
1378 if state.PRURL != nil {
1379 t.Errorf("PRURL = %q, want none", *state.PRURL)
1380 }
1381 if state.PushedBranch == nil || *state.PushedBranch != branch || state.NeedsAttention != nil {
1382 t.Errorf("pushed branch = %q, needs attention = %q; want %s pushed and nothing to salvage",
1383 strOrNil(state.PushedBranch), strOrNil(state.NeedsAttention), branch)
1384 }
1385 evts := runEvents(t, store.BaseDir(), state.ID)
1386 if _, ok := evts[event.AgentPRCreated]; ok {
1387 t.Error("unexpected agent:pr-created")
1388 }
1389 if _, ok := evts[event.AgentBranchPushed]; !ok {
1390 t.Errorf("expected agent:branch-pushed, got %v", evts)
1391 }
1392 })
1393 }
1394
1395 t.Run("failed WIP commit keeps the worktree", func(t *testing.T) {
1396 if os.Geteuid() == 0 {
1397 t.Skip("root can read the unreadable file, so git add succeeds")
1398 }
1399 _, repo, worktree, branch := setupBareRemote(t)
1400 commitAndPush(t, worktree, branch)
1401 unreadable := filepath.Join(worktree, "unreadable.txt")
1402 if err := os.WriteFile(unreadable, []byte("uncommitted\n"), 0o000); err != nil {
1403 t.Fatal(err)
1404 }
1405
1406 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, cleanLog, "")
1407
1408 if _, err := os.Stat(unreadable); err != nil {
1409 t.Errorf("uncommitted file lost: %v", err)
1410 }
1411 evts := runEvents(t, store.BaseDir(), state.ID)
1412 if _, ok := evts[event.AgentNeedsAttention]; !ok {
1413 t.Errorf("expected agent:needs-attention, got %v", evts)
1414 }
1415 if _, ok := evts[event.AgentBranchPushed]; ok {
1416 t.Error("a dirty run must not emit agent:branch-pushed")
1417 }
1418 })
1419
1420 t.Run("nothing pushed emits no branch-pushed", func(t *testing.T) {
1421 _, repo, worktree, branch := setupBareRemote(t)
1422 if err := os.Remove(filepath.Join(worktree, "wip.txt")); err != nil {
1423 t.Fatal(err)
1424 }
1425
1426 store, state, _ := finalizeRealRepo(t, repo, worktree, branch, cleanLog, "")
1427
1428 evts := runEvents(t, store.BaseDir(), state.ID)
1429 if _, ok := evts[event.AgentBranchPushed]; ok {
1430 t.Errorf("unexpected agent:branch-pushed: %v", evts)
1431 }
1432 if _, ok := evts[event.AgentCompleted]; !ok {
1433 t.Error("expected agent:completed")
1434 }
1435 if state.PushedBranch != nil || state.PushedSHA != nil {
1436 t.Errorf("recorded push = %q@%q, want none", strOrNil(state.PushedBranch), strOrNil(state.PushedSHA))
1437 }
1438 if got := determineStatus(context.Background(), state, &fakeTmux{}); got != "exited" {
1439 t.Errorf("status = %q, want exited", got)
1440 }
1441 })
1442}
1443
1444func strOrNil(p *string) string {
1445 if p == nil {
1446 return "<nil>"
1447 }
1448 return *p
1449}