| 1 | package draft |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | |
| 11 | "the-valley/flow/internal/event" |
| 12 | ) |
| 13 | |
| 14 | // recorderRunner is a Runner that captures every git/gh call and lets each |
| 15 | // test stub specific responses by command-prefix match. |
| 16 | type recorderRunner struct { |
| 17 | gitCalls []recorded |
| 18 | ghCalls []recorded |
| 19 | gitStubs []stub |
| 20 | ghStubs []stub |
| 21 | } |
| 22 | |
| 23 | type recorded struct { |
| 24 | workdir string |
| 25 | args []string |
| 26 | } |
| 27 | |
| 28 | type stub struct { |
| 29 | // match: substrings that must all appear in the joined args (space-separated) |
| 30 | match []string |
| 31 | out string |
| 32 | err error |
| 33 | } |
| 34 | |
| 35 | func (r *recorderRunner) addGitStub(match []string, out string, err error) { |
| 36 | r.gitStubs = append(r.gitStubs, stub{match: match, out: out, err: err}) |
| 37 | } |
| 38 | func (r *recorderRunner) addGHStub(match []string, out string, err error) { |
| 39 | r.ghStubs = append(r.ghStubs, stub{match: match, out: out, err: err}) |
| 40 | } |
| 41 | |
| 42 | func (r *recorderRunner) Git(_ context.Context, workdir string, args ...string) (string, error) { |
| 43 | r.gitCalls = append(r.gitCalls, recorded{workdir, args}) |
| 44 | joined := strings.Join(args, " ") |
| 45 | for _, s := range r.gitStubs { |
| 46 | if allContain(joined, s.match) { |
| 47 | return s.out, s.err |
| 48 | } |
| 49 | } |
| 50 | return "", nil |
| 51 | } |
| 52 | |
| 53 | func (r *recorderRunner) GH(_ context.Context, workdir string, args ...string) (string, error) { |
| 54 | r.ghCalls = append(r.ghCalls, recorded{workdir, args}) |
| 55 | joined := strings.Join(args, " ") |
| 56 | for _, s := range r.ghStubs { |
| 57 | if allContain(joined, s.match) { |
| 58 | return s.out, s.err |
| 59 | } |
| 60 | } |
| 61 | return "", nil |
| 62 | } |
| 63 | |
| 64 | func allContain(s string, parts []string) bool { |
| 65 | for _, p := range parts { |
| 66 | if !strings.Contains(s, p) { |
| 67 | return false |
| 68 | } |
| 69 | } |
| 70 | return true |
| 71 | } |
| 72 | |
| 73 | // argsContainAll reports whether every part appears as a standalone arg. |
| 74 | // Matches by exact arg equality so "pr" doesn't fuzzy-match "progress". |
| 75 | func argsContainAll(args, parts []string) bool { |
| 76 | for _, p := range parts { |
| 77 | found := false |
| 78 | for _, a := range args { |
| 79 | if a == p { |
| 80 | found = true |
| 81 | break |
| 82 | } |
| 83 | } |
| 84 | if !found { |
| 85 | return false |
| 86 | } |
| 87 | } |
| 88 | return true |
| 89 | } |
| 90 | |
| 91 | func (r *recorderRunner) findGitCall(parts ...string) *recorded { |
| 92 | for i := range r.gitCalls { |
| 93 | if argsContainAll(r.gitCalls[i].args, parts) { |
| 94 | return &r.gitCalls[i] |
| 95 | } |
| 96 | } |
| 97 | return nil |
| 98 | } |
| 99 | |
| 100 | func (r *recorderRunner) findGHCall(parts ...string) *recorded { |
| 101 | for i := range r.ghCalls { |
| 102 | if argsContainAll(r.ghCalls[i].args, parts) { |
| 103 | return &r.ghCalls[i] |
| 104 | } |
| 105 | } |
| 106 | return nil |
| 107 | } |
| 108 | |
| 109 | func TestHandleBudgetPause_CreatesNewPRWithDirtyWorktree(t *testing.T) { |
| 110 | r := &recorderRunner{} |
| 111 | // Dirty worktree. |
| 112 | r.addGitStub([]string{"status", "--porcelain"}, " M foo.go\n", nil) |
| 113 | // findPRForBranch returns nothing (no existing PR). |
| 114 | r.addGHStub([]string{"pr", "list", "--head"}, "", nil) |
| 115 | // gh pr create returns the new PR URL. |
| 116 | r.addGHStub([]string{"pr", "create"}, "https://github.com/owner/repo/pull/42\n", nil) |
| 117 | |
| 118 | in := PauseInput{ |
| 119 | RunID: "20260101-1200-aaaa", |
| 120 | Worktree: "/tmp/wt", |
| 121 | Branch: "agent/20260101-1200-aaaa", |
| 122 | Repo: "owner/repo", |
| 123 | Prompt: "fix the auth bug", |
| 124 | CostUSD: 4.95, |
| 125 | BudgetUSD: 5.00, |
| 126 | } |
| 127 | out, err := HandleBudgetPause(context.Background(), r, in) |
| 128 | if err != nil { |
| 129 | t.Fatalf("HandleBudgetPause error: %v", err) |
| 130 | } |
| 131 | |
| 132 | if !out.CommittedWIP { |
| 133 | t.Error("expected CommittedWIP=true for dirty worktree") |
| 134 | } |
| 135 | if !out.CreatedNewPR { |
| 136 | t.Error("expected CreatedNewPR=true when no PR existed") |
| 137 | } |
| 138 | if out.PRNumber != "42" { |
| 139 | t.Errorf("expected PRNumber=42, got %q", out.PRNumber) |
| 140 | } |
| 141 | if out.PRURL != "https://github.com/owner/repo/pull/42" { |
| 142 | t.Errorf("expected PRURL set, got %q", out.PRURL) |
| 143 | } |
| 144 | |
| 145 | // Verify the WIP commit happened. |
| 146 | if r.findGitCall("add", "-A") == nil { |
| 147 | t.Error("expected git add -A call") |
| 148 | } |
| 149 | if c := r.findGitCall("commit", "-m"); c == nil { |
| 150 | t.Error("expected git commit call") |
| 151 | } else { |
| 152 | // Commit message should reference the run ID. |
| 153 | if !strings.Contains(strings.Join(c.args, " "), "20260101-1200-aaaa") { |
| 154 | t.Errorf("commit message should include run ID, got %v", c.args) |
| 155 | } |
| 156 | } |
| 157 | // Verify the push. |
| 158 | if c := r.findGitCall("push", "--force-with-lease"); c == nil { |
| 159 | t.Error("expected git push --force-with-lease call") |
| 160 | } |
| 161 | // Verify label create. |
| 162 | if c := r.findGHCall("label", "create", event.BudgetPausedLabel); c == nil { |
| 163 | t.Error("expected gh label create call") |
| 164 | } |
| 165 | // Verify PR create with --draft. |
| 166 | if c := r.findGHCall("pr", "create", "--draft"); c == nil { |
| 167 | t.Error("expected gh pr create --draft call") |
| 168 | } |
| 169 | // Verify label apply. |
| 170 | if c := r.findGHCall("pr", "edit", "42", "--add-label"); c == nil { |
| 171 | t.Error("expected gh pr edit --add-label call") |
| 172 | } |
| 173 | // Verify PR comment. |
| 174 | if c := r.findGHCall("pr", "comment", "42"); c == nil { |
| 175 | t.Error("expected gh pr comment call") |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | func TestHandleBudgetPause_UsesExistingPR(t *testing.T) { |
| 180 | r := &recorderRunner{} |
| 181 | // Clean worktree. |
| 182 | r.addGitStub([]string{"status", "--porcelain"}, "", nil) |
| 183 | // lookupPR returns the existing PR. |
| 184 | r.addGHStub([]string{"pr", "view", "99", "--json"}, "99\nhttps://github.com/owner/repo/pull/99\n", nil) |
| 185 | |
| 186 | in := PauseInput{ |
| 187 | RunID: "20260101-1200-bbbb", |
| 188 | Worktree: "/tmp/wt", |
| 189 | Branch: "agent/20260101-1200-bbbb", |
| 190 | Repo: "owner/repo", |
| 191 | Prompt: "do the thing", |
| 192 | CostUSD: 4.99, |
| 193 | BudgetUSD: 5.00, |
| 194 | ExistingPR: "99", |
| 195 | } |
| 196 | out, err := HandleBudgetPause(context.Background(), r, in) |
| 197 | if err != nil { |
| 198 | t.Fatalf("HandleBudgetPause error: %v", err) |
| 199 | } |
| 200 | |
| 201 | if out.CommittedWIP { |
| 202 | t.Error("expected CommittedWIP=false for clean worktree") |
| 203 | } |
| 204 | if out.CreatedNewPR { |
| 205 | t.Error("expected CreatedNewPR=false when PR existed") |
| 206 | } |
| 207 | if out.PRNumber != "99" { |
| 208 | t.Errorf("expected PRNumber=99, got %q", out.PRNumber) |
| 209 | } |
| 210 | |
| 211 | // Should NOT have called pr create. |
| 212 | if r.findGHCall("pr", "create") != nil { |
| 213 | t.Error("should not call gh pr create when PR already exists") |
| 214 | } |
| 215 | // Should still apply label and comment. |
| 216 | if r.findGHCall("pr", "edit", "99", "--add-label") == nil { |
| 217 | t.Error("expected label apply on existing PR") |
| 218 | } |
| 219 | if r.findGHCall("pr", "comment", "99") == nil { |
| 220 | t.Error("expected PR comment on existing PR") |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | func TestClearBudgetPausedLabel_NoOpWhenAbsent(t *testing.T) { |
| 225 | r := &recorderRunner{} |
| 226 | // gh succeeds with no output — label not present is not an error for gh |
| 227 | // pr edit --remove-label, so we treat it as success. |
| 228 | if err := ClearBudgetPausedLabel(context.Background(), r, "/tmp/wt", "owner/repo", "42"); err != nil { |
| 229 | t.Fatalf("unexpected error: %v", err) |
| 230 | } |
| 231 | if c := r.findGHCall("pr", "edit", "42", "--remove-label", "klaus:budget-paused"); c == nil { |
| 232 | t.Error("expected gh pr edit --remove-label klaus:budget-paused call") |
| 233 | } |
| 234 | if c := r.findGHCall("pr", "edit", "42", "--remove-label", "flow:budget-paused"); c == nil { |
| 235 | t.Error("expected gh pr edit --remove-label flow:budget-paused call") |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | func TestClearBudgetPausedLabel_ToleratesNotFound(t *testing.T) { |
| 240 | r := &recorderRunner{} |
| 241 | r.addGHStub([]string{"--remove-label"}, "", fmt.Errorf("label not found")) |
| 242 | if err := ClearBudgetPausedLabel(context.Background(), r, "/tmp/wt", "owner/repo", "42"); err != nil { |
| 243 | t.Errorf("expected 'not found' to be tolerated, got %v", err) |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | func TestClearBudgetPausedLabels(t *testing.T) { |
| 248 | r := &recorderRunner{} |
| 249 | if err := ClearBudgetPausedLabels(context.Background(), r, "/tmp/wt", "owner/repo", "42", []string{"flow:budget-paused"}); err != nil { |
| 250 | t.Fatalf("unexpected error: %v", err) |
| 251 | } |
| 252 | if c := r.findGHCall("pr", "edit", "42", "--remove-label", "flow:budget-paused"); c == nil { |
| 253 | t.Error("expected gh pr edit --remove-label flow:budget-paused call") |
| 254 | } |
| 255 | if c := r.findGHCall("pr", "edit", "42", "--remove-label", "klaus:budget-paused"); c != nil { |
| 256 | t.Errorf("did not expect removal of absent label, got %v", c) |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | func TestHasBudgetPausedLabel(t *testing.T) { |
| 261 | tests := []struct { |
| 262 | name string |
| 263 | output string |
| 264 | want bool |
| 265 | wantLabels []string |
| 266 | wantErr bool |
| 267 | }{ |
| 268 | {"legacy label present", "klaus:budget-paused\nother\n", true, []string{"klaus:budget-paused"}, false}, |
| 269 | {"new label present", "flow:budget-paused\nother\n", true, []string{"flow:budget-paused"}, false}, |
| 270 | {"both labels present", "klaus:budget-paused\nflow:budget-paused\n", true, []string{"klaus:budget-paused", "flow:budget-paused"}, false}, |
| 271 | {"duplicate label deduplicated", "flow:budget-paused\nflow:budget-paused\n", true, []string{"flow:budget-paused"}, false}, |
| 272 | {"label absent", "other\nfoo\n", false, nil, false}, |
| 273 | {"no labels", "", false, nil, false}, |
| 274 | {"only the label", "klaus:budget-paused", true, []string{"klaus:budget-paused"}, false}, |
| 275 | } |
| 276 | for _, tt := range tests { |
| 277 | t.Run(tt.name, func(t *testing.T) { |
| 278 | r := &recorderRunner{} |
| 279 | r.addGHStub([]string{"pr", "view"}, tt.output, nil) |
| 280 | got, err := HasBudgetPausedLabel(context.Background(), r, "/tmp/wt", "owner/repo", "42") |
| 281 | if (err != nil) != tt.wantErr { |
| 282 | t.Errorf("err = %v, wantErr %v", err, tt.wantErr) |
| 283 | } |
| 284 | if got != tt.want { |
| 285 | t.Errorf("got %v, want %v", got, tt.want) |
| 286 | } |
| 287 | labels, err := BudgetPausedLabels(context.Background(), r, "/tmp/wt", "owner/repo", "42") |
| 288 | if (err != nil) != tt.wantErr { |
| 289 | t.Errorf("BudgetPausedLabels err = %v, wantErr %v", err, tt.wantErr) |
| 290 | } |
| 291 | if strings.Join(labels, ",") != strings.Join(tt.wantLabels, ",") { |
| 292 | t.Errorf("BudgetPausedLabels = %v, want %v", labels, tt.wantLabels) |
| 293 | } |
| 294 | }) |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | func TestBudgetExhausted(t *testing.T) { |
| 299 | tests := []struct { |
| 300 | cost float64 |
| 301 | cap float64 |
| 302 | want bool |
| 303 | }{ |
| 304 | {4.75, 5.00, true}, // at 95% |
| 305 | {4.95, 5.00, true}, // at 99% |
| 306 | {5.10, 5.00, true}, // overshoot |
| 307 | {4.00, 5.00, false}, // at 80% |
| 308 | {0.01, 5.00, false}, // tiny |
| 309 | {4.95, 0, false}, // unknown cap |
| 310 | {4.95, -1, false}, // bogus cap |
| 311 | } |
| 312 | for _, tt := range tests { |
| 313 | got := BudgetExhausted(tt.cost, tt.cap) |
| 314 | if got != tt.want { |
| 315 | t.Errorf("BudgetExhausted(%v, %v) = %v, want %v", tt.cost, tt.cap, got, tt.want) |
| 316 | } |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | func TestExtractPRNumberFromURL(t *testing.T) { |
| 321 | tests := []struct { |
| 322 | url string |
| 323 | want string |
| 324 | }{ |
| 325 | {"https://github.com/owner/repo/pull/42", "42"}, |
| 326 | {"https://github.com/owner/repo/pull/42\n", "42"}, |
| 327 | {"https://github.com/owner/repo/pull/123/files", "123"}, |
| 328 | {"not a url", ""}, |
| 329 | {"", ""}, |
| 330 | } |
| 331 | for _, tt := range tests { |
| 332 | got := extractPRNumberFromURL(tt.url) |
| 333 | if got != tt.want { |
| 334 | t.Errorf("extractPRNumberFromURL(%q) = %q, want %q", tt.url, got, tt.want) |
| 335 | } |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | func TestTitleFromPrompt(t *testing.T) { |
| 340 | tests := []struct { |
| 341 | prompt string |
| 342 | runID string |
| 343 | want string |
| 344 | }{ |
| 345 | {"fix the auth bug", "id", "[budget-paused] fix the auth bug"}, |
| 346 | {"line one\nline two", "id", "[budget-paused] line one"}, |
| 347 | {"", "myid", "klaus run myid (budget paused)"}, |
| 348 | {strings.Repeat("x", 100), "id", "[budget-paused] " + strings.Repeat("x", 72)}, |
| 349 | } |
| 350 | for _, tt := range tests { |
| 351 | got := titleFromPrompt(tt.prompt, tt.runID) |
| 352 | if got != tt.want { |
| 353 | t.Errorf("titleFromPrompt(%q, %q) = %q, want %q", tt.prompt, tt.runID, got, tt.want) |
| 354 | } |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | // Under the bridge naming generation, the WIP commit and the fallback draft |
| 359 | // title a budget pause writes call flow by its flow name. |
| 360 | func TestBudgetPauseTextUnderBridge(t *testing.T) { |
| 361 | home := t.TempDir() |
| 362 | t.Setenv("HOME", home) |
| 363 | if err := os.MkdirAll(filepath.Join(home, ".klaus"), 0o755); err != nil { |
| 364 | t.Fatal(err) |
| 365 | } |
| 366 | if err := os.WriteFile(filepath.Join(home, ".klaus", "config.json"), []byte(`{"naming_generation": "bridge"}`), 0o644); err != nil { |
| 367 | t.Fatal(err) |
| 368 | } |
| 369 | if got := titleFromPrompt("", "myid"); got != "flow run myid (budget paused)" { |
| 370 | t.Errorf("fallback title %q", got) |
| 371 | } |
| 372 | r := &recorderRunner{} |
| 373 | r.addGitStub([]string{"status", "--porcelain"}, " M foo.go\n", nil) |
| 374 | r.addGHStub([]string{"pr", "list", "--head"}, "", nil) |
| 375 | r.addGHStub([]string{"pr", "create"}, "https://github.com/owner/repo/pull/42\n", nil) |
| 376 | if _, err := HandleBudgetPause(context.Background(), r, PauseInput{RunID: "20260101-1200-aaaa", Worktree: "/tmp/wt", Branch: "agent/x", Repo: "owner/repo", Prompt: "fix it", CostUSD: 4.95, BudgetUSD: 5}); err != nil { |
| 377 | t.Fatal(err) |
| 378 | } |
| 379 | c := r.findGitCall("commit", "-m") |
| 380 | if c == nil || !strings.Contains(strings.Join(c.args, " "), "WIP from flow run 20260101-1200-aaaa (budget paused)") { |
| 381 | t.Errorf("WIP commit %v, want it from flow", c) |
| 382 | } |
| 383 | } |