gunk-dev/the-valley

hidden.go

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