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