| 1 | // Package draft handles the budget-pause persistence flow: when an agent |
| 2 | // exhausts its budget, klaus commits any work-in-progress to the agent's |
| 3 | // branch, pushes it, and ensures a draft PR exists carrying a |
| 4 | // "klaus:budget-paused" label plus an explanatory comment. |
| 5 | // |
| 6 | // The draft PR is the persistence layer for paused state — there is no |
| 7 | // in-process Status field. The pipeline FSM later reads the label off |
| 8 | // GitHub to surface the paused stage in the dashboard. |
| 9 | package draft |
| 10 | |
| 11 | import ( |
| 12 | "context" |
| 13 | "errors" |
| 14 | "fmt" |
| 15 | "os/exec" |
| 16 | "strings" |
| 17 | |
| 18 | "the-valley/flow/internal/event" |
| 19 | "the-valley/flow/internal/git" |
| 20 | ) |
| 21 | |
| 22 | // Runner abstracts the shell commands (git, gh) the pause flow needs. |
| 23 | // Tests inject a fake runner; production uses ExecRunner. |
| 24 | type Runner interface { |
| 25 | // Git runs a git command in workdir and returns stdout. Stderr is |
| 26 | // captured in the error. |
| 27 | Git(ctx context.Context, workdir string, args ...string) (string, error) |
| 28 | // GH runs a gh command (cwd irrelevant for most calls but accepted so |
| 29 | // PR-create can run inside the worktree). Returns stdout, with stderr |
| 30 | // captured in the error. |
| 31 | GH(ctx context.Context, workdir string, args ...string) (string, error) |
| 32 | } |
| 33 | |
| 34 | // ExecRunner runs real git/gh commands via os/exec. |
| 35 | type ExecRunner struct{} |
| 36 | |
| 37 | func (ExecRunner) Git(ctx context.Context, workdir string, args ...string) (string, error) { |
| 38 | c := exec.CommandContext(ctx, "git", args...) |
| 39 | c.Dir = workdir |
| 40 | out, err := c.Output() |
| 41 | if err != nil { |
| 42 | var stderr string |
| 43 | if ee, ok := err.(*exec.ExitError); ok { |
| 44 | stderr = string(ee.Stderr) |
| 45 | } |
| 46 | return string(out), fmt.Errorf("git %s: %w (stderr: %s)", strings.Join(args, " "), err, strings.TrimSpace(stderr)) |
| 47 | } |
| 48 | return string(out), nil |
| 49 | } |
| 50 | |
| 51 | func (ExecRunner) GH(ctx context.Context, workdir string, args ...string) (string, error) { |
| 52 | c := exec.CommandContext(ctx, "gh", args...) |
| 53 | c.Dir = workdir |
| 54 | out, err := c.Output() |
| 55 | if err != nil { |
| 56 | var stderr string |
| 57 | if ee, ok := err.(*exec.ExitError); ok { |
| 58 | stderr = string(ee.Stderr) |
| 59 | } |
| 60 | return string(out), fmt.Errorf("gh %s: %w (stderr: %s)", strings.Join(args, " "), err, strings.TrimSpace(stderr)) |
| 61 | } |
| 62 | return string(out), nil |
| 63 | } |
| 64 | |
| 65 | // PauseInput carries everything HandleBudgetPause needs to commit, push, |
| 66 | // and surface the paused state on GitHub. |
| 67 | type PauseInput struct { |
| 68 | RunID string // klaus run ID |
| 69 | ChangeID string // the run's change ID; empty when its state predates change IDs |
| 70 | Worktree string // path to the agent's worktree |
| 71 | Branch string // branch name to push |
| 72 | Repo string // owner/repo for gh commands; if empty, gh infers from cwd |
| 73 | Prompt string // original agent prompt (used in WIP commit + PR body) |
| 74 | CostUSD float64 // observed spend |
| 75 | BudgetUSD float64 // budget cap (0 if unknown) |
| 76 | ExistingPR string // PR number if known; empty means "discover or create" |
| 77 | } |
| 78 | |
| 79 | // PauseOutput reports what HandleBudgetPause observed/created. |
| 80 | type PauseOutput struct { |
| 81 | PRNumber string // the PR number (created or pre-existing) |
| 82 | PRURL string // the PR URL |
| 83 | CreatedNewPR bool // true if HandleBudgetPause created the PR |
| 84 | CommittedWIP bool // true if there were uncommitted changes that got committed |
| 85 | } |
| 86 | |
| 87 | // HandleBudgetPause performs the WIP-commit + push + draft-PR + label + comment |
| 88 | // dance for budget exhaustion. Returns details of what was created so the |
| 89 | // caller can emit corresponding events. |
| 90 | // |
| 91 | // The flow is idempotent on the GitHub side: re-running against an already- |
| 92 | // labeled draft PR will not create duplicate PRs but will add a duplicate |
| 93 | // comment. Callers should not retry on success. |
| 94 | func HandleBudgetPause(ctx context.Context, r Runner, in PauseInput) (PauseOutput, error) { |
| 95 | out := PauseOutput{} |
| 96 | |
| 97 | // Step 1: commit any uncommitted changes. |
| 98 | msg := fmt.Sprintf("WIP from klaus run %s (budget paused)\n\n%s", in.RunID, summarizePrompt(in.Prompt)) |
| 99 | committed, err := CommitWIP(ctx, r, in.Worktree, msg, git.Provenance{RunID: in.RunID, ChangeID: in.ChangeID}) |
| 100 | if err != nil { |
| 101 | return out, fmt.Errorf("committing WIP: %w", err) |
| 102 | } |
| 103 | out.CommittedWIP = committed |
| 104 | |
| 105 | // Step 2: push the branch (force-with-lease tolerates a prior push). |
| 106 | if err := pushBranch(ctx, r, in.Worktree, in.Branch); err != nil { |
| 107 | return out, fmt.Errorf("pushing branch: %w", err) |
| 108 | } |
| 109 | |
| 110 | // Step 3: ensure the budget-paused label exists in the repo. |
| 111 | if err := ensureLabel(ctx, r, in.Worktree, in.Repo); err != nil { |
| 112 | // Non-fatal: label creation failures shouldn't block the PR + comment. |
| 113 | // gh label create --force will fail loudly if there's an auth problem, |
| 114 | // but we still want to attempt PR creation. |
| 115 | _ = err |
| 116 | } |
| 117 | |
| 118 | // Step 4: find or create the PR. |
| 119 | prNumber, prURL, created, err := ensurePR(ctx, r, in) |
| 120 | if err != nil { |
| 121 | return out, fmt.Errorf("ensuring PR: %w", err) |
| 122 | } |
| 123 | out.PRNumber = prNumber |
| 124 | out.PRURL = prURL |
| 125 | out.CreatedNewPR = created |
| 126 | |
| 127 | // Step 5: apply the label. |
| 128 | if err := applyLabel(ctx, r, in.Worktree, in.Repo, prNumber); err != nil { |
| 129 | return out, fmt.Errorf("applying label: %w", err) |
| 130 | } |
| 131 | |
| 132 | // Step 6: post an explanatory PR comment. |
| 133 | if err := postComment(ctx, r, in, prNumber); err != nil { |
| 134 | return out, fmt.Errorf("posting comment: %w", err) |
| 135 | } |
| 136 | |
| 137 | return out, nil |
| 138 | } |
| 139 | |
| 140 | // ClearBudgetPausedLabel removes any budget-paused label spelling from the |
| 141 | // given PR. Used by _finalize on follow-up runs against a paused PR so the |
| 142 | // dashboard reflects that the pause was resolved. |
| 143 | // |
| 144 | // Idempotent: if a label isn't present, this is a no-op. |
| 145 | func ClearBudgetPausedLabel(ctx context.Context, r Runner, workdir, repo, prNumber string) error { |
| 146 | return ClearBudgetPausedLabels(ctx, r, workdir, repo, prNumber, []string{event.BudgetPausedLabel, event.FlowBudgetPausedLabel}) |
| 147 | } |
| 148 | |
| 149 | // ClearBudgetPausedLabels removes each given label from the PR, tolerating |
| 150 | // "not found" errors so removing an already-absent label is a no-op. |
| 151 | func ClearBudgetPausedLabels(ctx context.Context, r Runner, workdir, repo, prNumber string, labels []string) error { |
| 152 | var errs []error |
| 153 | for _, label := range labels { |
| 154 | args := []string{"pr", "edit", prNumber, "--remove-label", label} |
| 155 | if repo != "" { |
| 156 | args = []string{"pr", "edit", prNumber, "--repo", repo, "--remove-label", label} |
| 157 | } |
| 158 | _, err := r.GH(ctx, workdir, args...) |
| 159 | if err != nil && !strings.Contains(err.Error(), "not found") { |
| 160 | errs = append(errs, err) |
| 161 | } |
| 162 | } |
| 163 | return errors.Join(errs...) |
| 164 | } |
| 165 | |
| 166 | // BudgetPausedLabels returns whichever accepted budget-paused label spellings |
| 167 | // are currently present on the PR, deduplicated in the order reported by GitHub. |
| 168 | func BudgetPausedLabels(ctx context.Context, r Runner, workdir, repo, prNumber string) ([]string, error) { |
| 169 | args := []string{"pr", "view", prNumber, "--json", "labels", "-q", ".labels[].name"} |
| 170 | if repo != "" { |
| 171 | args = []string{"pr", "view", prNumber, "--repo", repo, "--json", "labels", "-q", ".labels[].name"} |
| 172 | } |
| 173 | stdout, err := r.GH(ctx, workdir, args...) |
| 174 | if err != nil { |
| 175 | return nil, err |
| 176 | } |
| 177 | var found []string |
| 178 | seen := map[string]bool{} |
| 179 | for _, line := range strings.Split(stdout, "\n") { |
| 180 | label := strings.TrimSpace(line) |
| 181 | if event.IsBudgetPausedLabel(label) && !seen[label] { |
| 182 | seen[label] = true |
| 183 | found = append(found, label) |
| 184 | } |
| 185 | } |
| 186 | return found, nil |
| 187 | } |
| 188 | |
| 189 | // HasBudgetPausedLabel reports whether the given PR currently carries either |
| 190 | // spelling of the budget-paused label. |
| 191 | func HasBudgetPausedLabel(ctx context.Context, r Runner, workdir, repo, prNumber string) (bool, error) { |
| 192 | labels, err := BudgetPausedLabels(ctx, r, workdir, repo, prNumber) |
| 193 | if err != nil { |
| 194 | return false, err |
| 195 | } |
| 196 | return len(labels) > 0, nil |
| 197 | } |
| 198 | |
| 199 | // ── internal helpers ──────────────────────────────────────────────────── |
| 200 | |
| 201 | // CommitWIP stages and commits every change in worktree with msg, followed by |
| 202 | // prov's trailers. Returns false without committing when the tree is clean. |
| 203 | // Hooks are skipped so a failing linter can't block salvaging work, which is |
| 204 | // why the trailers klaus's commit-msg hook would add are added here. |
| 205 | func CommitWIP(ctx context.Context, r Runner, worktree, msg string, prov git.Provenance) (bool, error) { |
| 206 | // git status --porcelain returns empty if clean. |
| 207 | status, err := r.Git(ctx, worktree, "status", "--porcelain") |
| 208 | if err != nil { |
| 209 | return false, err |
| 210 | } |
| 211 | if strings.TrimSpace(status) == "" { |
| 212 | return false, nil |
| 213 | } |
| 214 | if _, err := r.Git(ctx, worktree, "add", "-A"); err != nil { |
| 215 | return false, err |
| 216 | } |
| 217 | if t := prov.Trailers(); t != "" { |
| 218 | msg = strings.TrimRight(msg, "\n") + "\n\n" + t |
| 219 | } |
| 220 | if _, err := r.Git(ctx, worktree, "commit", "--no-verify", "-m", msg); err != nil { |
| 221 | return false, err |
| 222 | } |
| 223 | return true, nil |
| 224 | } |
| 225 | |
| 226 | func pushBranch(ctx context.Context, r Runner, workdir, branch string) error { |
| 227 | // --force-with-lease is safe whether the branch was pushed before or not; |
| 228 | // for first pushes git treats absent upstream as no constraint. |
| 229 | // Use --set-upstream so subsequent pushes Just Work. |
| 230 | _, err := r.Git(ctx, workdir, "push", "--force-with-lease", "--set-upstream", "origin", branch) |
| 231 | return err |
| 232 | } |
| 233 | |
| 234 | func ensureLabel(ctx context.Context, r Runner, workdir, repo string) error { |
| 235 | args := []string{"label", "create", event.BudgetPausedLabel, |
| 236 | "--force", |
| 237 | "--description", "Agent paused at budget cap; work-in-progress committed to this branch.", |
| 238 | "--color", "FBCA04", |
| 239 | } |
| 240 | if repo != "" { |
| 241 | args = []string{"label", "create", event.BudgetPausedLabel, |
| 242 | "--repo", repo, |
| 243 | "--force", |
| 244 | "--description", "Agent paused at budget cap; work-in-progress committed to this branch.", |
| 245 | "--color", "FBCA04", |
| 246 | } |
| 247 | } |
| 248 | _, err := r.GH(ctx, workdir, args...) |
| 249 | return err |
| 250 | } |
| 251 | |
| 252 | func ensurePR(ctx context.Context, r Runner, in PauseInput) (prNumber, prURL string, created bool, err error) { |
| 253 | if in.ExistingPR != "" { |
| 254 | num, url, lookupErr := lookupPR(ctx, r, in.Worktree, in.Repo, in.ExistingPR) |
| 255 | if lookupErr == nil && num != "" { |
| 256 | return num, url, false, nil |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | // Try to find a PR for the branch. |
| 261 | num, url, err := findPRForBranch(ctx, r, in.Worktree, in.Repo, in.Branch) |
| 262 | if err == nil && num != "" { |
| 263 | return num, url, false, nil |
| 264 | } |
| 265 | |
| 266 | // Create a draft PR. |
| 267 | title := titleFromPrompt(in.Prompt, in.RunID) |
| 268 | body := pauseBody(in) |
| 269 | args := []string{"pr", "create", "--draft", "--title", title, "--body", body, "--head", in.Branch} |
| 270 | if in.Repo != "" { |
| 271 | args = []string{"pr", "create", "--repo", in.Repo, "--draft", "--title", title, "--body", body, "--head", in.Branch} |
| 272 | } |
| 273 | stdout, err := r.GH(ctx, in.Worktree, args...) |
| 274 | if err != nil { |
| 275 | return "", "", false, err |
| 276 | } |
| 277 | url = strings.TrimSpace(stdout) |
| 278 | // gh pr create prints the URL on success. |
| 279 | num = extractPRNumberFromURL(url) |
| 280 | return num, url, true, nil |
| 281 | } |
| 282 | |
| 283 | func lookupPR(ctx context.Context, r Runner, workdir, repo, prNumber string) (string, string, error) { |
| 284 | args := []string{"pr", "view", prNumber, "--json", "number,url", "-q", ".number,.url"} |
| 285 | if repo != "" { |
| 286 | args = []string{"pr", "view", prNumber, "--repo", repo, "--json", "number,url", "-q", ".number,.url"} |
| 287 | } |
| 288 | stdout, err := r.GH(ctx, workdir, args...) |
| 289 | if err != nil { |
| 290 | return "", "", err |
| 291 | } |
| 292 | parts := strings.Split(strings.TrimSpace(stdout), "\n") |
| 293 | if len(parts) != 2 { |
| 294 | return "", "", fmt.Errorf("unexpected gh pr view output: %q", stdout) |
| 295 | } |
| 296 | return parts[0], parts[1], nil |
| 297 | } |
| 298 | |
| 299 | func findPRForBranch(ctx context.Context, r Runner, workdir, repo, branch string) (string, string, error) { |
| 300 | args := []string{"pr", "list", "--head", branch, "--state", "open", "--json", "number,url", "-q", ".[0].number,.[0].url"} |
| 301 | if repo != "" { |
| 302 | args = []string{"pr", "list", "--repo", repo, "--head", branch, "--state", "open", "--json", "number,url", "-q", ".[0].number,.[0].url"} |
| 303 | } |
| 304 | stdout, err := r.GH(ctx, workdir, args...) |
| 305 | if err != nil { |
| 306 | return "", "", err |
| 307 | } |
| 308 | out := strings.TrimSpace(stdout) |
| 309 | if out == "" { |
| 310 | return "", "", nil |
| 311 | } |
| 312 | parts := strings.Split(out, "\n") |
| 313 | if len(parts) != 2 || parts[0] == "" { |
| 314 | return "", "", nil |
| 315 | } |
| 316 | return parts[0], parts[1], nil |
| 317 | } |
| 318 | |
| 319 | func applyLabel(ctx context.Context, r Runner, workdir, repo, prNumber string) error { |
| 320 | args := []string{"pr", "edit", prNumber, "--add-label", event.BudgetPausedLabel} |
| 321 | if repo != "" { |
| 322 | args = []string{"pr", "edit", prNumber, "--repo", repo, "--add-label", event.BudgetPausedLabel} |
| 323 | } |
| 324 | _, err := r.GH(ctx, workdir, args...) |
| 325 | return err |
| 326 | } |
| 327 | |
| 328 | func postComment(ctx context.Context, r Runner, in PauseInput, prNumber string) error { |
| 329 | body := fmt.Sprintf( |
| 330 | "Agent paused at budget cap ($%.2f of $%.2f). Label `%s` set; latest commit is WIP. Use `valley flow launch --pr %s \"continue the work\"` to continue, or close to abandon.", |
| 331 | in.CostUSD, in.BudgetUSD, event.BudgetPausedLabel, prNumber, |
| 332 | ) |
| 333 | args := []string{"pr", "comment", prNumber, "--body", body} |
| 334 | if in.Repo != "" { |
| 335 | args = []string{"pr", "comment", prNumber, "--repo", in.Repo, "--body", body} |
| 336 | } |
| 337 | _, err := r.GH(ctx, in.Worktree, args...) |
| 338 | return err |
| 339 | } |
| 340 | |
| 341 | func titleFromPrompt(prompt, runID string) string { |
| 342 | first := strings.TrimSpace(prompt) |
| 343 | if idx := strings.IndexByte(first, '\n'); idx >= 0 { |
| 344 | first = first[:idx] |
| 345 | } |
| 346 | first = strings.TrimSpace(first) |
| 347 | if first == "" { |
| 348 | return fmt.Sprintf("klaus run %s (budget paused)", runID) |
| 349 | } |
| 350 | if len(first) > 72 { |
| 351 | first = strings.TrimSpace(first[:72]) |
| 352 | } |
| 353 | return "[budget-paused] " + first |
| 354 | } |
| 355 | |
| 356 | func pauseBody(in PauseInput) string { |
| 357 | return fmt.Sprintf( |
| 358 | "This PR was opened by flow when the agent for run `%s` exhausted its budget cap.\n\n"+ |
| 359 | "- **Cost so far:** $%.2f of $%.2f\n"+ |
| 360 | "- **Branch:** `%s`\n"+ |
| 361 | "- **Status:** draft, labeled `%s`\n\n"+ |
| 362 | "## Original prompt\n\n%s\n\n"+ |
| 363 | "## Continue the work\n\n"+ |
| 364 | "Run `valley flow launch --pr <number> \"continue the work\"` to dispatch a fresh agent against this branch. "+ |
| 365 | "The new agent will see the WIP commit and pick up from there.\n\n"+ |
| 366 | "To abandon, close this PR.\n", |
| 367 | in.RunID, in.CostUSD, in.BudgetUSD, in.Branch, event.BudgetPausedLabel, summarizePrompt(in.Prompt), |
| 368 | ) |
| 369 | } |
| 370 | |
| 371 | func summarizePrompt(prompt string) string { |
| 372 | s := strings.TrimSpace(prompt) |
| 373 | if s == "" { |
| 374 | return "(no prompt recorded)" |
| 375 | } |
| 376 | if len(s) > 500 { |
| 377 | return s[:500] + "…" |
| 378 | } |
| 379 | return s |
| 380 | } |
| 381 | |
| 382 | func extractPRNumberFromURL(url string) string { |
| 383 | idx := strings.LastIndex(url, "/pull/") |
| 384 | if idx < 0 { |
| 385 | return "" |
| 386 | } |
| 387 | tail := url[idx+len("/pull/"):] |
| 388 | end := strings.IndexAny(tail, "/?# \n\t") |
| 389 | if end < 0 { |
| 390 | return strings.TrimSpace(tail) |
| 391 | } |
| 392 | return strings.TrimSpace(tail[:end]) |
| 393 | } |
| 394 | |
| 395 | // BudgetExhausted reports whether the observed cost is close enough to the |
| 396 | // budget cap to treat as exhaustion. The heuristic is 95% of cap; callers |
| 397 | // pair this with a check of claude's result event subtype to avoid false |
| 398 | // positives (e.g. a successful completion that happened to land near cap). |
| 399 | func BudgetExhausted(cost, cap float64) bool { |
| 400 | if cap <= 0 { |
| 401 | return false |
| 402 | } |
| 403 | return cost >= 0.95*cap |
| 404 | } |