| 1 | //go:build e2e |
| 2 | |
| 3 | package e2e |
| 4 | |
| 5 | import ( |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "the-valley/flow/internal/event" |
| 13 | ) |
| 14 | |
| 15 | // TestWorkerScratchDir: a launched worker gets KLAUS_SCRATCH, an existing |
| 16 | // directory outside its worktree, and builds its binary there as its standing |
| 17 | // rules say. With nothing left in the worktree there is nothing to salvage, |
| 18 | // and finalize removes the scratch directory with the worktree. |
| 19 | func TestWorkerScratchDir(t *testing.T) { |
| 20 | t.Parallel() |
| 21 | h := NewHarness(t) |
| 22 | h.WriteDefaultClaudeOutput(`{"type":"result","subtype":"success","total_cost_usd":0.01,"duration_ms":10,"session_id":"11111111-2222-4333-8444-555555555555"}` + "\n") |
| 23 | h.WriteStub("claude", strings.Replace(h.claudeStubScript(), `cat "$dir/claude.output.jsonl"`, |
| 24 | `printf '%s\n' "${KLAUS_SCRATCH-unset}" > "$dir/worker.scratch" |
| 25 | if [ -d "${KLAUS_SCRATCH-}" ]; then echo yes > "$dir/worker.scratch-exists"; fi |
| 26 | head -c 2097152 /dev/zero > "$KLAUS_SCRATCH/restack" |
| 27 | cat "$dir/claude.output.jsonl"`, 1)) |
| 28 | |
| 29 | st := launchOne(t, h, "fix the restack command") |
| 30 | h.WaitForClaudeStart(30 * time.Second) |
| 31 | releaseBackendWorkers(t, h) |
| 32 | final, err := h.ReadState(st.ID) |
| 33 | if err != nil { |
| 34 | t.Fatal(err) |
| 35 | } |
| 36 | |
| 37 | read := func(name string) string { |
| 38 | b, _ := os.ReadFile(filepath.Join(h.E2EDir, name)) |
| 39 | return strings.TrimSpace(string(b)) |
| 40 | } |
| 41 | scratch := filepath.Join(h.Home, ".klaus", "sessions", h.SessionID, "scratch", st.ID) |
| 42 | if got := read("worker.scratch"); got != scratch { |
| 43 | t.Fatalf("worker's KLAUS_SCRATCH = %q, want %q", got, scratch) |
| 44 | } |
| 45 | if rel, err := filepath.Rel(st.Worktree, scratch); err != nil || !strings.HasPrefix(rel, "..") { |
| 46 | t.Errorf("scratch directory %s is inside the worktree %s", scratch, st.Worktree) |
| 47 | } |
| 48 | if read("worker.scratch-exists") != "yes" { |
| 49 | t.Errorf("scratch directory %s did not exist while the worker ran", scratch) |
| 50 | } |
| 51 | if _, err := os.Stat(scratch); !os.IsNotExist(err) { |
| 52 | t.Errorf("finalize left the scratch directory %s: stat err = %v", scratch, err) |
| 53 | } |
| 54 | |
| 55 | if final.NeedsAttention != nil { |
| 56 | t.Errorf("a binary built in scratch made the run need attention: %q", *final.NeedsAttention) |
| 57 | } |
| 58 | for _, e := range h.runEvents(st.ID) { |
| 59 | if e.Type == event.AgentNeedsAttention { |
| 60 | t.Errorf("unexpected agent:needs-attention: %v", e.Data) |
| 61 | } |
| 62 | } |
| 63 | if refs := h.GitOutput(h.OriginDir, "for-each-ref", "refs/heads/"+st.Branch); refs != "" { |
| 64 | t.Errorf("nothing to salvage, but %s was pushed: %s", st.Branch, refs) |
| 65 | } |
| 66 | } |