gunk-dev/the-valley

draft.go

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