gunk-dev/the-valley

hidden.go

source6a7605f70901main's published tip history
42.2 KiB
1package cmd
2
3import (
4 "bufio"
5 "context"
6 "encoding/json"
7 "fmt"
8 "log/slog"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "regexp"
13 "strconv"
14 "strings"
15 "time"
16
17 "the-valley/flow/internal/config"
18 "the-valley/flow/internal/draft"
19 "the-valley/flow/internal/event"
20 "the-valley/flow/internal/git"
21 "the-valley/flow/internal/github"
22 "the-valley/flow/internal/location"
23 "the-valley/flow/internal/run"
24 "the-valley/flow/internal/scan"
25 "the-valley/flow/internal/stream"
26 "the-valley/flow/internal/tmux"
27 "the-valley/flow/internal/valley"
28 "github.com/spf13/cobra"
29)
30
31// budgetPauseRunner is overridable in tests to capture gh/git calls without
32// touching the network. Production uses draft.ExecRunner{}.
33var budgetPauseRunner draft.Runner = draft.ExecRunner{}
34
35var formatStreamCmd = &cobra.Command{
36 Use: "_format-stream",
37 Short: "Format backend JSONL stream from stdin",
38 Hidden: true,
39 RunE: func(cmd *cobra.Command, args []string) error {
40 sandbox, _ := cmd.Flags().GetBool("sandbox")
41 watch, flush := streamCheckEvents(sandbox)
42 err := stream.FormatStreamWatching(os.Stdin, os.Stdout, watch)
43 flush()
44 return err
45 },
46}
47
48// streamCheckEvents returns a watcher that emits check:started and
49// check:completed for the checks in the stream of the run whose pane this
50// is (flowenv.RunID), or nil outside one, and a flush for the end of the stream.
51// Those are the stream's build, test and lint commands, and the _pre-review
52// checks a sandbox run's _pre-review reports in its output (a sandbox run
53// says so with sandbox). Launch saves the run's state just after its pane
54// starts, so events wait until it is found. At the end of the stream they
55// wait up to paneRunSaveWait more, then go out under the run's ID without
56// it.
57func streamCheckEvents(sandbox bool) (*stream.CheckWatcher, func()) {
58 p := currentPaneRun()
59 if p == nil {
60 return nil, func() {}
61 }
62 type pendingEvent struct {
63 typ string
64 data map[string]interface{}
65 }
66 var pending []pendingEvent
67 send := func() {
68 for _, e := range pending {
69 p.emit(e.typ, e.data)
70 }
71 pending = nil
72 }
73 emit := func(eventType string, data map[string]interface{}) {
74 pending = append(pending, pendingEvent{eventType, data})
75 if p.load() {
76 send()
77 }
78 }
79 flush := func() {
80 if len(pending) > 0 {
81 p.awaitState()
82 send()
83 }
84 }
85 checkData := func(c stream.Check) map[string]interface{} {
86 data := map[string]interface{}{"kind": c.Kind, "command": c.Command, "source": "stream", "started_at": eventTime(c.Start)}
87 if c.IncludesPreReview {
88 data["includes_pre_review"] = true
89 }
90 return data
91 }
92 return &stream.CheckWatcher{
93 Sandbox: sandbox,
94 OnStart: func(c stream.Check) { emit(event.CheckStarted, checkData(c)) },
95 OnEnd: func(c stream.Check, end time.Time, success *bool) {
96 data := checkData(c)
97 data["ended_at"] = eventTime(end)
98 data["duration_ms"] = end.Sub(c.Start).Milliseconds()
99 if success != nil {
100 data["success"] = *success
101 }
102 emit(event.CheckCompleted, data)
103 },
104 // A reported check arrives whole, so it starts and ends here.
105 OnReport: func(data map[string]interface{}) {
106 started := map[string]interface{}{"via": "stream"}
107 for _, k := range []string{"kind", "command", "source", "started_at"} {
108 if v, ok := data[k]; ok {
109 started[k] = v
110 }
111 }
112 emit(event.CheckStarted, started)
113 data["via"] = "stream"
114 emit(event.CheckCompleted, data)
115 },
116 }, flush
117}
118
119var finalizeCmd = &cobra.Command{
120 Use: "_finalize <run-id>",
121 Short: "Finalize a completed run",
122 Hidden: true,
123 Args: cobra.ExactArgs(1),
124 RunE: func(cmd *cobra.Command, args []string) error {
125 id := args[0]
126 finalizeStart := time.Now()
127
128 store, err := sessionStore()
129 if err != nil {
130 return nil // silently ignore if session not set
131 }
132
133 state, err := store.Load(id)
134 if err != nil {
135 return nil // silently ignore if state not found
136 }
137
138 // Track whether _finalize discovered the PR URL for the first time
139 // in this run. We emit agent:pr-created even on budget pause so the
140 // pipeline starts tracking the (now-draft) PR.
141 hadPRURLBefore := state.PRURL != nil && *state.PRURL != ""
142
143 // Parse log for cost/duration/PR URL and result subtype.
144 var resultSubtype string
145 if state.LogFile != nil {
146 subtype, err := finalizeFromLog(store, state)
147 if err != nil {
148 fmt.Fprintf(os.Stderr, "warning: finalize: %v\n", err)
149 }
150 resultSubtype = subtype
151 }
152
153 ctx := cmd.Context()
154 baseDir := ""
155 if hds, ok := store.(*run.HomeDirStore); ok {
156 baseDir = hds.BaseDir()
157 }
158 launchHead := state.HeadSHA
159 if head := gitHead(ctx, state.Worktree); head != "" {
160 state.HeadSHA = head
161 }
162 if baseDir != "" {
163 emitAgentPhase(baseDir, state, finalizeStart)
164 }
165
166 // Decide: did this run end normally, or did it exhaust its budget?
167 paused := handleBudgetPauseIfNeeded(ctx, baseDir, state, resultSubtype, hadPRURLBefore)
168
169 // A worker that ended its turn mid-build leaves no PR; say why before
170 // cleanup interrupts the build.
171 if !paused && (state.PRURL == nil || *state.PRURL == "") && state.FailureReason == nil && state.Worktree != "" {
172 procs, err := lingeringProcesses(state.Worktree)
173 if err != nil {
174 fmt.Fprintf(os.Stderr, "warning: finalize: background work could not be looked for: %v\n", err)
175 }
176 if len(procs) > 0 {
177 reason := "background work still running (" + strings.Join(procs, ", ") + ")"
178 state.FailureReason = &reason
179 }
180 }
181
182 // A worker that wrote the files its clone shares reached every other
183 // worktree's git, and the operator's.
184 if baseDir != "" {
185 checkSharedGit(ctx, baseDir, state)
186 }
187
188 // Sync to data ref — use the target repo's clone dir if available,
189 // otherwise fall back to the current git repo.
190 var syncRoot string
191 if state.CloneDir != nil {
192 syncRoot = *state.CloneDir
193 } else {
194 syncRoot, err = git.RepoRoot()
195 if err != nil {
196 return nil
197 }
198 }
199
200 cfg, err := config.Load(syncRoot)
201 if err != nil {
202 return nil
203 }
204
205 gitClient := git.NewExecClient()
206 noPR := state.PRURL == nil || *state.PRURL == ""
207
208 // No PR (or a crash): the worktree may hold the only copy of the work.
209 var salvage *salvageResult
210 if !paused && (noPR || state.FailureReason != nil) {
211 salvage = salvageUnfinishedWork(ctx, budgetPauseRunner, gitClient, state, cfg.DefaultBranch)
212 }
213 // Without a PR, the branch on origin is the only record of the work
214 // (direct-push repos). Look it up before cleanup deletes the local
215 // branch, so status and the dashboard never ask the remote. A failed
216 // salvage push already showed origin lacks the branch's tip.
217 if !paused && noPR && (salvage == nil || salvage.pushed) {
218 recordPushedBranch(ctx, gitClient, state)
219 }
220 // The agent may have pushed another change, on another branch,
221 // than the one launch recorded.
222 if !paused && noPR && salvage == nil {
223 recordPushedChange(ctx, baseDir, state, launchHead, cfg.DefaultBranch)
224 }
225 // Work of runs that needed attention, which the head this run left
226 // on origin holds, is this run's to carry on.
227 if !paused && (salvage == nil || salvage.pushed) {
228 recordFinalTakeovers(ctx, gitClient, state)
229 }
230 // Persist before the data-ref sync, which reads the state file.
231 if err := store.Save(state); err != nil {
232 slog.Warn("failed to save state before sync", "id", state.ID, "err", err)
233 }
234
235 // For a normal (non-budget, non-crashed) completion against an
236 // existing paused PR, clear the budget-paused label so the dashboard
237 // reflects that the follow-up agent shipped its work. A crashed
238 // follow-up must NOT clear the label — the PR still needs work.
239 if !paused && state.FailureReason == nil && baseDir != "" {
240 clearLabelIfResumed(ctx, baseDir, state)
241 }
242
243 // Emit terminal events for the run. For paused runs, agent:completed
244 // is intentionally suppressed in favor of agent:paused, since the
245 // run is not "done" — it's parked in a draft PR awaiting continuation.
246 // A crashed or salvaged run emits agent:needs-attention instead of
247 // falsely reporting agent:completed / agent:pr-created.
248 if baseDir != "" && !paused {
249 emitFinalizeEvents(baseDir, state, salvage)
250 }
251 // A pushed branch in a repo that delivers to a valley becomes a
252 // version of the run's change: ready, or a draft awaiting review.
253 // This runs once agent:branch-pushed is out, so a slow or refusing
254 // valley never holds that up.
255 if !paused && salvage == nil && markChangeReady(ctx, baseDir, state, readiesAtFinalize(ctx, state, cfg)) {
256 if err := store.Save(state); err != nil {
257 slog.Warn("failed to save state after valley ready", "id", state.ID, "err", err)
258 }
259 }
260 // The knot the run was launched for gets the change, or a comment
261 // on what became of the run, and loses the run's claim.
262 if finishKnot(ctx, branchDir(state), state, paused, salvage) {
263 if err := store.Save(state); err != nil {
264 slog.Warn("failed to save state after the knot's finish", "id", state.ID, "err", err)
265 }
266 }
267 syncRunToDataRef(ctx, syncRoot, store, gitClient, cfg.DataRef, cfg.PushDataRef, state)
268
269 if salvage != nil && salvage.dirty {
270 // WIP commit failed; removing the worktree would discard it.
271 fmt.Fprintf(os.Stderr, "warning: keeping worktree %s: uncommitted changes could not be committed\n", state.Worktree)
272 } else {
273 settleProseJobs(baseDir, state.ID, state.Worktree)
274 cleanupWorktree(ctx, store, gitClient, state, salvage != nil)
275 }
276
277 // Killing the pane ends this process, so the phase ends first.
278 if baseDir != "" {
279 emitRunEvent(baseDir, state, event.PhaseCompleted, phaseData(event.PhaseFinalize, finalizeStart, time.Now()))
280 }
281
282 // Kill the tmux pane — _finalize is the last command in the pipeline,
283 // so this is safe. The pane would otherwise stay open indefinitely.
284 killAgentPane(ctx, store, tmux.NewExecClient(), state)
285
286 return nil
287 },
288}
289
290// checkSharedGit compares the files state's clone shares across worktrees
291// with launch's snapshot, and on a difference records the changed files on
292// state, emits agent:shared-git-changed and says so on stderr.
293func checkSharedGit(ctx context.Context, baseDir string, state *run.State) {
294 sg := state.SharedGit
295 if sg == nil || sg.Dir == "" {
296 return
297 }
298 changed := git.SharedChanges(sg.Files, git.SharedSnapshot(ctx, sg.Dir))
299 if len(changed) == 0 {
300 return
301 }
302 sg.Changed = changed
303 fmt.Fprintf(os.Stderr, "warning: the clone's shared git files changed while run %s ran: %s (in %s)\n", state.ID, strings.Join(changed, ", "), sg.Dir)
304 emitRunEvent(baseDir, state, event.AgentSharedGitChanged, map[string]interface{}{
305 "id": state.ID,
306 "dir": sg.Dir,
307 "files": changed,
308 })
309}
310
311// emitFinalizeEvents emits the terminal events for a finalized, non-paused
312// run. A salvaged or crashed run (FailureReason set) emits
313// agent:needs-attention and nothing else, so a pipeline never mistakes it for
314// a completed, PR-creating run. A normal run emits agent:completed plus
315// agent:pr-created when a PR URL is known, or agent:branch-pushed when its
316// branch is on origin without a PR.
317func emitFinalizeEvents(baseDir string, state *run.State, salvage *salvageResult) {
318 if state == nil || baseDir == "" {
319 return
320 }
321 if salvage != nil {
322 data := map[string]interface{}{
323 "id": state.ID,
324 "branch": state.Branch,
325 "pushed": salvage.pushed,
326 "reason": salvage.reason,
327 }
328 if salvage.dirty {
329 data["worktree"] = state.Worktree
330 }
331 emitRunEvent(baseDir, state, event.AgentNeedsAttention, data)
332 return
333 }
334 if state.FailureReason != nil {
335 emitRunEvent(baseDir, state, event.AgentNeedsAttention, map[string]interface{}{
336 "id": state.ID,
337 "reason": *state.FailureReason,
338 })
339 return
340 }
341
342 completedData := map[string]interface{}{"id": state.ID}
343 if state.CostUSD != nil {
344 completedData["cost_usd"] = *state.CostUSD
345 }
346 if state.DurationMS != nil {
347 completedData["duration_ms"] = *state.DurationMS
348 }
349 emitRunEvent(baseDir, state, event.AgentCompleted, completedData)
350
351 if state.PRURL != nil && *state.PRURL != "" {
352 emitRunEvent(baseDir, state, event.AgentPRCreated, map[string]interface{}{
353 "id": state.ID,
354 "pr_url": *state.PRURL,
355 "pr_number": extractPRNumberFromURL(*state.PRURL),
356 })
357 } else if state.PushedBranch != nil && state.PushedSHA != nil {
358 emitRunEvent(baseDir, state, event.AgentBranchPushed, map[string]interface{}{
359 "id": state.ID,
360 "repo": pushedRepo(state),
361 "branch": *state.PushedBranch,
362 "sha": *state.PushedSHA,
363 })
364 }
365}
366
367// recordPushedBranch sets PushedBranch and PushedSHA when origin has the
368// run's branch, and PushedSubject when the pushed commit is local, as it is
369// when the agent pushed from its worktree. An unreachable remote records
370// nothing.
371func recordPushedBranch(ctx context.Context, gc git.Client, state *run.State) {
372 if state.Branch == "" {
373 return
374 }
375 dir := branchDir(state)
376 if dir == "" {
377 return
378 }
379 sha, err := gc.RemoteBranchSHA(ctx, dir, state.Branch)
380 if err != nil {
381 slog.Warn("could not check origin for the run's branch", "id", state.ID, "branch", state.Branch, "err", err)
382 return
383 }
384 if sha == "" {
385 return
386 }
387 branch := state.Branch
388 state.PushedBranch = &branch
389 state.PushedSHA = &sha
390 state.PushedSubject = commitSubject(ctx, dir, sha)
391}
392
393// branchDir is where to look at a run's branch: its worktree while it
394// exists, else the checkout it belongs to.
395func branchDir(state *run.State) string {
396 if _, err := os.Stat(state.Worktree); err == nil {
397 return state.Worktree
398 }
399 return runRepoDir(state)
400}
401
402// markChangeReady marks a pushed run's head ready as a version of the run's
403// change when the run's repo delivers to a valley (valley.Detect): it runs
404// `valley ready`, bounded by valley.ReadyTimeout, records the version on the
405// run and emits agent:change-ready. With ready false (ready_at_finalize off)
406// it then returns the change to draft at once with `valley unready`, bounded
407// by valley.UnreadyTimeout, so the version awaits review rather than
408// approval, and emits agent:change-draft instead; the valley has no verb
409// that records a version as a draft. A valley that doesn't list unready
410// isn't asked to ready the head at all. A refusal or other failure is
411// recorded on the run as a short reason and never fails finalize. It
412// reports whether it recorded anything; a repo that isn't a valley's
413// records nothing.
414func markChangeReady(ctx context.Context, baseDir string, state *run.State, ready bool) bool {
415 if state.PushedBranch == nil || state.PushedSHA == nil || state.FailureReason != nil ||
416 (state.PRURL != nil && *state.PRURL != "") {
417 return false
418 }
419 dir, branch, head := branchDir(state), *state.PushedBranch, *state.PushedSHA
420 if !valley.Detect(ctx, dir, branch, head) {
421 return false
422 }
423 rec := &run.Valley{Title: commitSubject(ctx, dir, head)}
424 state.Valley = rec
425 switch {
426 case state.ChangeID == "":
427 rec.Error = "valley ready not run: the run has no change ID"
428 case !ready && !valley.HasUnready(ctx):
429 rec.Error = "valley ready not run: ready_at_finalize is off, and the valley has no unready to leave the change a draft"
430 default:
431 r, err := valley.Ready(ctx, dir, state.ChangeID, head, branch)
432 if err != nil {
433 rec.Error = err.Error()
434 break
435 }
436 rec.Repo, rec.Handle, rec.Version = r.Repo, r.Handle, r.Version
437 if ready {
438 break
439 }
440 // A change the valley says wasn't ready is a draft all the same.
441 if _, err := valley.Unready(ctx, dir, state.ChangeID); err != nil {
442 rec.Error = "marked ready, but not returned to draft for review: " + err.Error()
443 } else {
444 rec.Draft = true
445 }
446 }
447 if rec.Error != "" {
448 slog.Warn("could not record the change", "id", state.ID, "draft", rec.Draft, "err", rec.Error)
449 fmt.Fprintf(os.Stderr, "warning: could not record the change: %s\n", rec.Error)
450 }
451 if rec.Handle == "" || baseDir == "" {
452 return true
453 }
454 typ := event.AgentChangeReady
455 if rec.Draft {
456 typ = event.AgentChangeDraft
457 }
458 emitRunEvent(baseDir, state, typ, changeEventData(state, head))
459 return true
460}
461
462// changeEventData is what agent:change-ready and agent:change-draft carry:
463// the version of the run's change that its pushed head, head, became.
464func changeEventData(state *run.State, head string) map[string]interface{} {
465 rec := state.Valley
466 return map[string]interface{}{
467 "id": state.ID,
468 "repo": rec.Repo,
469 "change_id": state.ChangeID,
470 "handle": rec.Handle,
471 "version": rec.Version,
472 "title": rec.Title,
473 "head": head,
474 }
475}
476
477// readiesAtFinalize reports whether finalize marks the run's change ready
478// (ready_at_finalize), as the config of the checkout the run's worktree
479// belongs to says, over ~/.klaus/config.json: its clone, or the main
480// checkout of its worktree. The worktree's own config is the agent's to
481// change, so it never decides. cfg, finalize's config, stands in when that
482// checkout can't be found or its config read.
483func readiesAtFinalize(ctx context.Context, state *run.State, cfg config.Config) bool {
484 dir := ""
485 if state.CloneDir != nil {
486 dir = *state.CloneDir
487 } else if state.Worktree != "" {
488 out, err := exec.CommandContext(ctx, "git", "-C", state.Worktree, "rev-parse", "--git-common-dir").Output()
489 if common := strings.TrimSpace(string(out)); err == nil && filepath.Base(common) == ".git" {
490 if !filepath.IsAbs(common) {
491 common = filepath.Join(state.Worktree, common)
492 }
493 dir = filepath.Dir(common)
494 }
495 }
496 if dir == "" {
497 return cfg.ReadiesAtFinalize()
498 }
499 own, err := config.Load(dir)
500 if err != nil {
501 slog.Warn("could not read the run's project config", "id", state.ID, "dir", dir, "err", err)
502 return cfg.ReadiesAtFinalize()
503 }
504 return own.ReadiesAtFinalize()
505}
506
507// commitSubject returns the subject of commit sha in dir, or "".
508func commitSubject(ctx context.Context, dir, sha string) string {
509 out, err := exec.CommandContext(ctx, "git", "-C", dir, "log", "-1", "--format=%s", sha).Output()
510 if err != nil {
511 return ""
512 }
513 return strings.TrimSpace(string(out))
514}
515
516// pushedRepo names the repo a pushed branch lives in: the run's target repo,
517// or else the origin URL of its clone.
518func pushedRepo(state *run.State) string {
519 if state.TargetRepo != nil && *state.TargetRepo != "" {
520 return *state.TargetRepo
521 }
522 if dir := runRepoDir(state); dir != "" {
523 return gitRemoteURL(dir)
524 }
525 return ""
526}
527
528// runRepoDir returns the checkout a run's worktree belongs to: its clone, or
529// else the current repo. Returns "" when neither is known.
530func runRepoDir(state *run.State) string {
531 if state.CloneDir != nil {
532 return *state.CloneDir
533 }
534 root, _ := git.RepoRoot()
535 return root
536}
537
538// handleBudgetPauseIfNeeded decides whether the just-finalized run hit its
539// budget cap, and if so commits/pushes the WIP, ensures a draft PR with
540// the budget-paused label, and emits agent:paused (plus agent:pr-created
541// if a PR was newly discovered or created).
542//
543// Returns true if the budget-pause flow was taken (so the caller can
544// suppress the normal agent:completed event).
545func handleBudgetPauseIfNeeded(ctx context.Context, baseDir string, state *run.State, resultSubtype string, hadPRURLBefore bool) bool {
546 if !isBudgetExhausted(state, resultSubtype) {
547 return false
548 }
549 if state.Worktree == "" {
550 // Nothing to push: worktree already cleaned up. Best-effort skip.
551 return false
552 }
553
554 budgetUSD := 0.0
555 if state.Budget != nil {
556 if v, err := strconv.ParseFloat(*state.Budget, 64); err == nil {
557 budgetUSD = v
558 }
559 }
560 cost := 0.0
561 if state.CostUSD != nil {
562 cost = *state.CostUSD
563 }
564
565 repo := ""
566 if state.TargetRepo != nil {
567 repo = *state.TargetRepo
568 }
569 if !strings.Contains(repo, "/") {
570 // Bare project name — gh can't use it. Let gh infer from the
571 // worktree's remote.
572 repo = ""
573 }
574
575 existingPR := ""
576 if state.PR != nil {
577 existingPR = *state.PR
578 }
579
580 in := draft.PauseInput{
581 RunID: state.ID,
582 ChangeID: state.ChangeID,
583 Worktree: state.Worktree,
584 Branch: state.Branch,
585 Repo: repo,
586 Prompt: state.Prompt,
587 CostUSD: cost,
588 BudgetUSD: budgetUSD,
589 ExistingPR: existingPR,
590 }
591
592 out, err := draft.HandleBudgetPause(ctx, budgetPauseRunner, in)
593 if err != nil {
594 fmt.Fprintf(os.Stderr, "warning: budget-pause flow failed: %v\n", err)
595 // Fall through: emit no agent:paused event, treat as a regular
596 // (failed) completion so the caller's normal-event branch fires.
597 return false
598 }
599
600 // Persist the discovered PR URL so the dashboard picks up the draft PR.
601 if out.PRURL != "" {
602 state.PRURL = &out.PRURL
603 }
604 if out.PRNumber != "" {
605 pr := out.PRNumber
606 state.PR = &pr
607 }
608
609 if baseDir != "" {
610 data := map[string]interface{}{
611 "id": state.ID,
612 "pr_number": out.PRNumber,
613 "pr_url": out.PRURL,
614 "cost_usd": cost,
615 "budget_usd": budgetUSD,
616 "reason": "budget_exhausted",
617 }
618 emitRunEvent(baseDir, state, event.AgentPaused, data)
619
620 // If this is the first time klaus has seen the PR URL for this run
621 // (either because the agent created it on this final flush, or
622 // because we just created it), emit agent:pr-created so the
623 // pipeline starts tracking it.
624 if !hadPRURLBefore && out.PRURL != "" {
625 emitRunEvent(baseDir, state, event.AgentPRCreated, map[string]interface{}{
626 "id": state.ID,
627 "pr_url": out.PRURL,
628 "pr_number": out.PRNumber,
629 })
630 }
631 }
632 return true
633}
634
635// isBudgetExhausted decides whether the just-completed run terminated
636// because it hit the budget cap. The signal is: claude did NOT emit a
637// success result event AND observed cost is at least 95% of the budget cap.
638//
639// When the result event is "success", we trust claude and never treat the
640// run as paused even if cost is near cap.
641//
642// When the result event is absent (early kill, crash, stream truncation)
643// OR has a non-success subtype, we apply the 95% heuristic. This avoids
644// false positives where cost ramped fast for an unrelated reason.
645func isBudgetExhausted(state *run.State, resultSubtype string) bool {
646 if state.Budget == nil || state.CostUSD == nil {
647 return false
648 }
649 cap, err := strconv.ParseFloat(*state.Budget, 64)
650 if err != nil || cap <= 0 {
651 return false
652 }
653 if resultSubtype == "success" {
654 return false
655 }
656 return draft.BudgetExhausted(*state.CostUSD, cap)
657}
658
659// clearLabelIfResumed removes any budget-paused label spellings present on the
660// run's PR, and emits agent:resumed once so the dashboard reflects the pause
661// being resolved. Called only on successful (non-paused) finalize.
662func clearLabelIfResumed(ctx context.Context, baseDir string, state *run.State) {
663 if state.PR == nil || *state.PR == "" {
664 return
665 }
666 repo := ""
667 if state.TargetRepo != nil && strings.Contains(*state.TargetRepo, "/") {
668 repo = *state.TargetRepo
669 }
670 workdir := state.Worktree
671 if workdir == "" && state.CloneDir != nil {
672 workdir = *state.CloneDir
673 }
674
675 labels, err := draft.BudgetPausedLabels(ctx, budgetPauseRunner, workdir, repo, *state.PR)
676 if err != nil || len(labels) == 0 {
677 return
678 }
679 if err := draft.ClearBudgetPausedLabels(ctx, budgetPauseRunner, workdir, repo, *state.PR, labels); err != nil {
680 fmt.Fprintf(os.Stderr, "warning: clearing budget-paused label: %v\n", err)
681 return
682 }
683
684 data := map[string]interface{}{
685 "id": state.ID,
686 "pr_number": *state.PR,
687 }
688 if state.PRURL != nil {
689 data["pr_url"] = *state.PRURL
690 }
691 emitRunEvent(baseDir, state, event.AgentResumed, data)
692}
693
694// salvageResult describes unfinished work finalize preserved.
695type salvageResult struct {
696 reason string // no_pr, session_limit, or the crash's FailureReason
697 pushed bool // branch tip is on origin
698 dirty bool // WIP commit failed; worktree still holds uncommitted changes
699}
700
701// salvageUnfinishedWork commits a dirty worktree as WIP and best-effort pushes
702// the branch; cleanupWorktree then keeps any branch still unpushed. Returns nil
703// when there is no work beyond the default branch, or when a clean, PR-less
704// run already pushed all of it (a direct-push finish, which awaits
705// integration rather than attention). Never pushes onto a known PR, so WIP
706// can't land on a live review.
707func salvageUnfinishedWork(ctx context.Context, r draft.Runner, gc git.Client, state *run.State, defaultBranch string) *salvageResult {
708 wt, branch := state.Worktree, state.Branch
709 if wt == "" || branch == "" {
710 return nil
711 }
712 if _, err := os.Stat(wt); err != nil {
713 return nil
714 }
715
716 res := &salvageResult{reason: "no_pr"}
717 if state.FailureReason != nil {
718 res.reason = *state.FailureReason
719 }
720 if state.LogFile != nil && hitSessionLimit(*state.LogFile) {
721 res.reason = "session_limit"
722 }
723
724 committed, err := draft.CommitWIP(ctx, r, wt, "wip: "+location.Self()+" finalize salvage "+state.ID, git.Provenance{RunID: state.ID, ChangeID: state.ChangeID})
725 if err != nil {
726 fmt.Fprintf(os.Stderr, "warning: salvage WIP commit: %v\n", err)
727 res.dirty = true
728 }
729 // Unknown ahead count (error) is treated as work.
730 if ahead, err := gc.CommitsAhead(ctx, wt, "origin/"+defaultBranch, branch); err == nil && ahead == 0 && !res.dirty {
731 return nil
732 }
733
734 hasPR := state.PRURL != nil && *state.PRURL != ""
735 if ok, err := gc.BranchPushed(ctx, wt, branch); err == nil && ok {
736 if !committed && !res.dirty && !hasPR && res.reason == "no_pr" {
737 return nil // the agent pushed its finished work itself
738 }
739 res.pushed = true // origin tip == local tip
740 } else if !hasPR {
741 if _, err := r.Git(ctx, wt, "push", "-u", "origin", branch); err != nil {
742 fmt.Fprintf(os.Stderr, "warning: salvage push of %s: %v\n", branch, err)
743 } else {
744 res.pushed = true
745 }
746 }
747
748 where := "local only"
749 if res.pushed {
750 where = "pushed"
751 }
752 note := fmt.Sprintf("%s; branch %s preserved (%s)", res.reason, branch, where)
753 if res.dirty {
754 note += "; uncommitted changes left in " + wt
755 }
756 state.NeedsAttention = &note
757 return res
758}
759
760// sessionLimitRegex matches Claude usage-limit stops, e.g.
761// "You've hit your session limit · resets 4:20pm".
762var sessionLimitRegex = regexp.MustCompile(`(?i)hit your (session |weekly |usage )?limit|usage limit reached`)
763
764// hitSessionLimit reports whether the log's last result event is a
765// usage-limit stop (reported as subtype success, so no budget pause).
766func hitSessionLimit(logPath string) bool {
767 f, err := os.Open(logPath)
768 if err != nil {
769 return false
770 }
771 defer f.Close()
772
773 scanner := bufio.NewScanner(f)
774 scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)
775 hit := false
776 for scanner.Scan() {
777 var ev struct {
778 Type string `json:"type"`
779 Result string `json:"result"`
780 }
781 if json.Unmarshal(stream.NormalizeLine(scanner.Bytes()), &ev) != nil || ev.Type != "result" {
782 continue
783 }
784 hit = sessionLimitRegex.MatchString(ev.Result)
785 }
786 return hit
787}
788
789// cleanupWorktree removes the agent's worktree, its scratch directory and its
790// local branch after completion. The state file and logs are preserved. The
791// branch is kept when keepBranch is set or branchDeletable can't prove its
792// work is safe. It is idempotent — if the worktree is already gone, the state
793// is still cleared.
794func cleanupWorktree(ctx context.Context, store run.StateStore, gitClient git.Client, state *run.State, keepBranch bool) {
795 if state.Worktree == "" {
796 return
797 }
798 gitRoot := ""
799 if state.CloneDir != nil {
800 gitRoot = *state.CloneDir
801 } else {
802 gitRoot, _ = git.RepoRoot()
803 }
804 if gitRoot == "" {
805 return
806 }
807 if err := gitClient.WorktreeRemove(ctx, gitRoot, state.Worktree); err != nil {
808 fmt.Fprintf(os.Stderr, "warning: worktree cleanup: %v\n", err)
809 }
810 removeScratchDir(store, state.ID)
811 if state.Branch != "" && !keepBranch {
812 if ok, err := branchDeletable(ctx, gitClient, gitRoot, state.Branch); !ok {
813 slog.Warn("keeping branch: work not verified on origin", "id", state.ID, "branch", state.Branch, "err", err)
814 } else if err := gitClient.BranchDelete(ctx, gitRoot, state.Branch); err != nil {
815 slog.Warn("failed to delete branch during cleanup", "id", state.ID, "branch", state.Branch, "err", err)
816 }
817 }
818 state.Worktree = ""
819 if err := store.Save(state); err != nil {
820 slog.Warn("failed to save state after worktree cleanup", "id", state.ID, "err", err)
821 }
822}
823
824// removeScratchDir removes a run's scratch directory (workerScratchDir).
825func removeScratchDir(store run.StateStore, runID string) {
826 dir := workerScratchDir(store, runID)
827 if filepath.Dir(dir) != filepath.Join(filepath.Dir(store.LogDir()), "scratch") {
828 return // an empty or malformed ID would name the scratch root or beyond
829 }
830 if err := os.RemoveAll(dir); err != nil {
831 slog.Warn("failed to remove scratch directory", "id", runID, "dir", dir, "err", err)
832 }
833}
834
835// branchDeletable: no commits beyond origin/<default>, or origin's live tip
836// equals the local tip. Unverifiable (error) means keep.
837func branchDeletable(ctx context.Context, gc git.Client, root, branch string) (bool, error) {
838 cfg, _ := config.Load(root)
839 if n, err := gc.CommitsAhead(ctx, root, "origin/"+cfg.DefaultBranch, branch); err == nil && n == 0 {
840 return true, nil
841 }
842 return gc.BranchPushed(ctx, root, branch)
843}
844
845// killAgentPane kills the tmux pane associated with the agent. State is
846// saved before the pane is killed because _finalize runs inside the pane
847// itself — killing the pane first would terminate the process before the
848// state save executes.
849func killAgentPane(ctx context.Context, store run.StateStore, tc tmux.Client, state *run.State) {
850 if state.TmuxPane == nil {
851 return
852 }
853 paneID := *state.TmuxPane
854 state.TmuxPane = nil
855 if err := store.Save(state); err != nil {
856 slog.Warn("failed to save state before pane cleanup", "id", state.ID, "err", err)
857 }
858 if err := tc.KillPane(ctx, paneID); err != nil {
859 slog.Warn("failed to kill agent pane", "id", state.ID, "pane", paneID, "err", err)
860 }
861}
862
863// finalizeFromLog parses the agent's JSONL log, mutates state with the
864// observed cost / duration / PR URL, and returns the subtype of the last
865// "result" event (e.g. "success", "error_max_turns", or empty if no
866// result event was emitted). The subtype lets the caller distinguish a
867// successful completion from a budget-cap kill.
868func finalizeFromLog(store run.StateStore, state *run.State) (string, error) {
869 f, err := os.Open(*state.LogFile)
870 if err != nil {
871 return "", err
872 }
873 defer f.Close()
874
875 // Preserve PRURL set at launch time (e.g. --pr mode).
876 // Only extract from logs when no URL is already known; otherwise the
877 // regex can clobber the correct value with a false match from agent
878 // tool output (source code, test fixtures, etc.).
879 existingPRURL := ""
880 if state.PRURL != nil {
881 existingPRURL = *state.PRURL
882 }
883
884 // Use line-by-line scanning for robust JSONL parsing.
885 // json.NewDecoder can corrupt its internal state on malformed lines,
886 // causing subsequent events to be silently skipped.
887 scanner := bufio.NewScanner(f)
888 scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)
889
890 var resultSubtype string
891 sawResult := false
892 var exactPRURL string
893 var assistantPRURL string
894 prTarget := prURLTargetSlug(state)
895 for scanner.Scan() {
896 line := stream.NormalizeLine(scanner.Bytes())
897 if len(line) == 0 {
898 continue
899 }
900
901 var ev struct {
902 Type string `json:"type"`
903 ExitCode int `json:"exit_code"`
904 Subtype string `json:"subtype"`
905 SessionID string `json:"session_id"`
906 Model string `json:"model"`
907 TotalCostUSD float64 `json:"total_cost_usd"`
908 DurationMS int64 `json:"duration_ms"`
909 IsError bool `json:"is_error"`
910 NumTurns int `json:"num_turns"`
911 Errors []string `json:"errors"`
912 Message *struct {
913 Content []struct {
914 Type string `json:"type"`
915 Text string `json:"text"`
916 Content string `json:"content"`
917 } `json:"content"`
918 } `json:"message"`
919 // Top-level content for tool_result events
920 Content string `json:"content"`
921 }
922 if err := json.Unmarshal(line, &ev); err != nil {
923 continue
924 }
925
926 if ev.SessionID != "" && !isClaudeRun(state) {
927 state.BackendSessionID = stringPtr(ev.SessionID)
928 }
929 if ev.Type == "system" && ev.Subtype == "init" && ev.Model != "" && isClaudeRun(state) {
930 state.ResolvedModel = ev.Model
931 }
932 switch ev.Type {
933 case "klaus_exit", "flow_exit":
934 // Claude structured results distinguish a limit stop from a crash.
935 // Preserve that classification even when the process exits nonzero.
936 if isClaudeRun(state) && sawResult {
937 break
938 }
939 if ev.ExitCode != 0 {
940 reason := fmt.Sprintf("%s exited with status %d", state.Backend, ev.ExitCode)
941 state.FailureReason = &reason
942 resultSubtype = "error_during_execution"
943 }
944 case "result":
945 sawResult = true
946 if ev.Content != "" {
947 for _, url := range prURLExtractRegex.FindAllString(ev.Content, -1) {
948 if isAllowedPRURL(prTarget, url) {
949 exactPRURL = url
950 }
951 }
952 }
953 if ev.TotalCostUSD > 0 {
954 state.CostUSD = &ev.TotalCostUSD
955 }
956 if ev.DurationMS > 0 {
957 state.DurationMS = &ev.DurationMS
958 }
959 if ev.Subtype != "" {
960 resultSubtype = ev.Subtype
961 }
962 // Claude session limits can report success with is_error set.
963 limitStop := isClaudeRun(state) && (ev.Subtype == "error_max_budget_usd" || ev.Subtype == "error_max_turns")
964 if ev.Subtype != "success" && !limitStop && (ev.IsError || ev.Subtype == "error_during_execution") {
965 reason := ev.Subtype
966 if reason == "" {
967 reason = "error"
968 }
969 if len(ev.Errors) > 0 && ev.Errors[0] != "" {
970 reason += ": " + ev.Errors[0]
971 }
972 state.FailureReason = &reason
973 } else {
974 // Clean results and limit stops clear earlier failures.
975 state.FailureReason = nil
976 }
977 // Record the Claude conversation UUID so a later budget-paused
978 // resume can restore the trajectory and run claude --resume.
979 if ev.SessionID != "" && isClaudeRun(state) {
980 sid := ev.SessionID
981 state.ClaudeSessionID = &sid
982 }
983 case "assistant":
984 if ev.Message != nil {
985 for _, block := range ev.Message.Content {
986 if block.Type == "text" {
987 text := block.Text
988 if text == "" {
989 text = block.Content
990 }
991 for _, url := range prURLExtractRegex.FindAllString(text, -1) {
992 if isAllowedPRURL(prTarget, url) {
993 assistantPRURL = url
994 }
995 }
996 }
997 }
998 }
999 case "tool_result":
1000 if ev.Content != "" {
1001 for _, url := range prURLExtractRegex.FindAllString(ev.Content, -1) {
1002 if isAllowedPRURL(prTarget, url) {
1003 exactPRURL = url
1004 }
1005 }
1006 }
1007 fallthrough
1008 default:
1009 if ev.Message != nil {
1010 for _, block := range ev.Message.Content {
1011 if block.Type == "tool_result" || ev.Type == "tool_result" {
1012 text := block.Content
1013 if text == "" {
1014 text = block.Text
1015 }
1016 for _, url := range prURLExtractRegex.FindAllString(text, -1) {
1017 if isAllowedPRURL(prTarget, url) {
1018 exactPRURL = url
1019 }
1020 }
1021 }
1022 }
1023 }
1024 }
1025 }
1026
1027 switch {
1028 case existingPRURL != "":
1029 state.PRURL = &existingPRURL
1030 case deliversByPush(state):
1031 // A run that delivers by pushing its branch has no PR: any PR URL in
1032 // its log is one the agent came across, such as a test fixture.
1033 case exactPRURL != "":
1034 state.PRURL = &exactPRURL
1035 case assistantPRURL != "":
1036 state.PRURL = &assistantPRURL
1037 }
1038
1039 if err := scanner.Err(); err != nil {
1040 reason := fmt.Sprintf("reading backend log: %v", err)
1041 state.FailureReason = &reason
1042 resultSubtype = "error_during_execution"
1043 }
1044 if !isClaudeRun(state) {
1045 if !sawResult && state.FailureReason == nil {
1046 reason := "backend exited without a terminal result event"
1047 state.FailureReason = &reason
1048 resultSubtype = "error_during_execution"
1049 }
1050 elapsed := int64(1)
1051 if started, err := time.Parse(time.RFC3339, state.CreatedAt); err == nil {
1052 elapsed = max(int64(1), time.Since(started).Milliseconds())
1053 }
1054 if state.DurationMS == nil {
1055 state.DurationMS = &elapsed
1056 }
1057 }
1058 return resultSubtype, store.Save(state)
1059}
1060
1061// prURLExtractRegex matches GitHub PR URLs in free-form text, including
1062// inside markdown links, angle brackets, or adjacent punctuation.
1063var prURLExtractRegex = regexp.MustCompile(`https?://github\.com/[^\s"<>\]]+/pull/\d+`)
1064
1065func extractPRURL(text string) string {
1066 return prURLExtractRegex.FindString(text)
1067}
1068
1069// prURLTargetSlug returns the "owner/repo" a run's PR URL must belong to: the
1070// run's TargetRepo when it is an owner/repo reference, otherwise the origin
1071// remote of the run's clone (or the current checkout). It returns "" when
1072// neither is a GitHub repo — e.g. TargetRepo is a project name or local path
1073// and origin is not a GitHub URL.
1074func prURLTargetSlug(state *run.State) string {
1075 if state != nil && state.TargetRepo != nil {
1076 if slug := repoSlug(*state.TargetRepo); slug != "" {
1077 return slug
1078 }
1079 }
1080 dir := ""
1081 if state != nil && state.CloneDir != nil {
1082 dir = *state.CloneDir
1083 } else {
1084 dir, _ = git.RepoRoot()
1085 }
1086 return repoSlugForDir(dir)
1087}
1088
1089// deliversByPush reports whether state's run delivers by pushing its branch,
1090// with no PR, as launch recorded it. State that predates the record is
1091// decided from the run's checkout, as launch decides (runDelivery).
1092func deliversByPush(state *run.State) bool {
1093 delivery := state.Delivery
1094 if delivery == "" {
1095 delivery = runDelivery(state.Type == "pr-fix", runRepoDir(state))
1096 }
1097 return delivery == run.DeliveryPush
1098}
1099
1100// isAllowedPRURL reports whether candidateURL may be recorded as a run's PR.
1101// Literal placeholder slugs (owner/repo and friends) are always rejected. When
1102// target (see prURLTargetSlug) is known the URL must belong to that repo; when
1103// it is unknown any other URL is accepted. A run whose origin is not a GitHub
1104// URL delivers by push and records no PR from its log at all (deliversByPush).
1105func isAllowedPRURL(target, candidateURL string) bool {
1106 slug := github.OwnerRepoFromPRURL(candidateURL)
1107 if slug == "" {
1108 return false
1109 }
1110 switch strings.ToLower(slug) {
1111 case "owner/repo", "<owner>/<repo>", "org/repo", "user/repo":
1112 return false
1113 }
1114 return target == "" || strings.EqualFold(slug, target)
1115}
1116
1117var prURLRegex = regexp.MustCompile(`/pull/(\d+)`)
1118
1119// extractPRNumberFromURL extracts the PR number from a GitHub PR URL.
1120// For example, "https://github.com/owner/repo/pull/123" returns "123".
1121func extractPRNumberFromURL(prURL string) string {
1122 matches := prURLRegex.FindStringSubmatch(prURL)
1123 if len(matches) < 2 {
1124 return ""
1125 }
1126 return matches[1]
1127}
1128
1129// claudeSessionExists returns true if a Claude session JSONL file with the
1130// given UUID exists under ~/.claude/projects/. Claude stores each session at
1131// ~/.claude/projects/<encoded-project-dir>/<session-uuid>.jsonl; if the file
1132// has been cleaned up, "claude --resume <uuid>" exits at startup with 0 turns.
1133func claudeSessionExists(sessionUUID string) bool {
1134 if sessionUUID == "" {
1135 return false
1136 }
1137 // Validate the UUID before interpolating into a filepath.Glob pattern:
1138 // reject anything containing glob metacharacters or path separators so a
1139 // crafted log entry can't escape the projects directory or match
1140 // unintended files.
1141 for _, r := range sessionUUID {
1142 if !((r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-') {
1143 return false
1144 }
1145 }
1146 home, err := os.UserHomeDir()
1147 if err != nil {
1148 return false
1149 }
1150 pattern := filepath.Join(home, ".claude", "projects", "*", sessionUUID+".jsonl")
1151 matches, err := filepath.Glob(pattern)
1152 if err != nil {
1153 return false
1154 }
1155 return len(matches) > 0
1156}
1157
1158// ExtractClaudeSessionID parses a Claude stream-json JSONL log file and
1159// returns the session_id from the "result" event. Returns empty string if
1160// not found or on any error.
1161func ExtractClaudeSessionID(logPath string) string {
1162 f, err := os.Open(logPath)
1163 if err != nil {
1164 return ""
1165 }
1166 defer f.Close()
1167
1168 scanner := bufio.NewScanner(f)
1169 scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)
1170
1171 var ev struct {
1172 Type string `json:"type"`
1173 SessionID string `json:"session_id"`
1174 }
1175 for scanner.Scan() {
1176 line := scanner.Bytes()
1177 if len(line) == 0 {
1178 continue
1179 }
1180 if err := json.Unmarshal(line, &ev); err != nil {
1181 continue
1182 }
1183 if ev.Type == "result" && ev.SessionID != "" {
1184 return ev.SessionID
1185 }
1186 }
1187 return ""
1188}
1189
1190// syncRunToDataRef commits the run's state, log and resumable conversation to
1191// the data ref in root. It pushes the ref to origin only when push is set
1192// (config push_data_ref): the ref is world-readable on a public repo, so by
1193// default it stays in the local clone, where trajectory replay reads it. The
1194// run records what became of the push.
1195func syncRunToDataRef(ctx context.Context, root string, store run.StateStore, gitClient git.Client, dataRef string, push bool, state *run.State) {
1196 stateFile := store.StateDir() + "/" + state.ID + ".json"
1197 files := map[string]string{
1198 "runs/" + state.ID + ".json": stateFile,
1199 }
1200
1201 // The run's own remotes are already in the clone's config, so a log that
1202 // names them discloses nothing new.
1203 allowedHosts := remoteHosts(ctx, root)
1204
1205 // Check log sensitivity before including. The scan applies even when the
1206 // ref stays local: a later push publishes the ref's whole history.
1207 if state.LogFile != nil {
1208 logF, err := os.Open(*state.LogFile)
1209 if err == nil {
1210 findings := scan.CheckSensitivityAllowing(logF, allowedHosts)
1211 logF.Close()
1212
1213 if len(findings) == 0 {
1214 files["logs/"+state.ID+".jsonl"] = *state.LogFile
1215 } else {
1216 fmt.Fprintf(os.Stderr, "warning: keeping log for %s off the data ref: potentially sensitive data detected\n", state.ID)
1217 for _, f := range findings {
1218 fmt.Fprintf(os.Stderr, " - %s\n", f.Category)
1219 }
1220 fmt.Fprintf(os.Stderr, " Use 'valley flow push-log %s' to store it after review.\n", state.ID)
1221 }
1222 }
1223 }
1224
1225 // Also capture the resume-able Claude conversation file. This is distinct
1226 // from the stream-json log above: claude --resume reads this file (under
1227 // ~/.claude/projects/...), not the stdout stream we tee into logs/. Storing
1228 // it lets 'klaus launch --pr' continue a budget-paused conversation.
1229 if convPath := findResumeConversation(state); convPath != "" {
1230 if cf, err := os.Open(convPath); err == nil {
1231 findings := scan.CheckSensitivityAllowing(cf, allowedHosts)
1232 cf.Close()
1233 if len(findings) == 0 {
1234 files["sessions/"+state.ID+".jsonl"] = convPath
1235 } else {
1236 fmt.Fprintf(os.Stderr, "warning: keeping conversation for %s off the data ref: potentially sensitive data detected\n", state.ID)
1237 }
1238 }
1239 }
1240
1241 commit, err := gitClient.SyncToDataRef(ctx, root, dataRef, "Run "+state.ID, files)
1242 if err != nil {
1243 fmt.Fprintf(os.Stderr, "warning: sync to data ref: %v\n", err)
1244 return
1245 }
1246 recordDataRefPush(ctx, store, gitClient, root, dataRef, commit, push, state)
1247}
1248
1249// remoteHosts returns the hosts of dir's git remotes (git remote -v), or nil
1250// when they can't be read.
1251func remoteHosts(ctx context.Context, dir string) []string {
1252 out, err := exec.CommandContext(ctx, "git", "-C", dir, "remote", "-v").Output()
1253 if err != nil {
1254 return nil
1255 }
1256 var hosts []string
1257 for _, line := range strings.Split(string(out), "\n") {
1258 f := strings.Fields(line)
1259 if len(f) < 2 {
1260 continue
1261 }
1262 if h := scan.RemoteHost(f[1]); h != "" {
1263 hosts = append(hosts, h)
1264 }
1265 }
1266 return hosts
1267}
1268
1269func init() {
1270 formatStreamCmd.Flags().Bool("sandbox", false, "The agent runs on a sandbox host: take _pre-review's checks from its output in the stream")
1271 rootCmd.AddCommand(formatStreamCmd)
1272 rootCmd.AddCommand(finalizeCmd)
1273}