gunk-dev/the-valley

draft.go

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