gunk-dev/the-valley

launch.go

source28abc5737165main's published tip history
71.4 KiB
1package cmd
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "strings"
11 "time"
12
13 "the-valley/flow/internal/backend"
14 "the-valley/flow/internal/config"
15 "the-valley/flow/internal/draft"
16 "the-valley/flow/internal/event"
17 "the-valley/flow/internal/git"
18 gh "the-valley/flow/internal/github"
19 "the-valley/flow/internal/integration"
20 "the-valley/flow/internal/nix"
21 "the-valley/flow/internal/project"
22 "the-valley/flow/internal/run"
23 "the-valley/flow/internal/tmux"
24 "the-valley/flow/internal/valley"
25 "github.com/spf13/cobra"
26)
27
28var launchCmd = &cobra.Command{
29 Use: "launch \"<prompt>\" | --prompt-file <path> [flags]",
30 Short: "Launch an autonomous Claude Code agent",
31 Long: `Creates a git worktree, launches Claude Code in autonomous mode in a new
32tmux pane, and tracks the run state. Must be run inside a tmux session.
33
34The agent's pane goes into a detached tmux session (klaus-agents-<session-id>),
35so your window is never split — watch agents with the dashboard, 'valley flow status',
36and 'valley flow logs'. Because the tmux server owns that session, agents keep running
37if the coordinator exits. Set agent_display to "pane" in .klaus/config.json to
38split the current window instead.
39
40A local worker runs without $TMUX or $TMUX_PANE, with TMUX_TMPDIR set to its
41run's own empty directory (tmux/<run-id> in the session directory), so a tmux
42command it runs, 'tmux kill-server' included, can't reach the server the
43agents' panes and your session live on. flow commands it runs still reach
44that server through KLAUS_TMUX_SOCKET. It also gets KLAUS_SCRATCH, its run's
45own directory outside the worktree (scratch/<run-id> in the session
46directory) for build output and other scratch files; finalize removes it with
47the worktree. A sandbox worker gets neither.
48
49A local worker gets launch's own PATH: tmux gives a pane the PATH of the
50client that creates it. Launch fails, before creating a worktree, when a
51command the worker runs by name isn't on that PATH: the backend's CLI and,
52for agy, bash, which runs every command agy's run_command tool runs. The
53error names the command and the PATH it searched.
54
55Just before the agent starts, launch snapshots the files the clone shares
56across its worktrees and that decide what git does there: its config (less
57the branch tracking git push -u writes), info/attributes and hooks. Finalize
58compares them; on a difference it emits agent:shared-git-changed naming the
59files, and valley flow status shows the run needs-attention with a line naming
60them. A worker can't be kept from writing them: it runs as you.
61
62The prompt comes either from the positional argument or from --prompt-file
63<path>; exactly one of the two is required. Prefer --prompt-file for long or
64technical prompts: in zsh a backtick inside a double-quoted argument is command
65substitution, so code spans in a shell-quoted prompt are silently mangled before
66flow ever sees them. File contents are used verbatim.
67
68Either way flow saves the prompt to prompts/<run-id>.md in the session
69directory, kept as the record of the brief, and every worker reads it on stdin,
70so a prompt of any length fits. agy, which has no system prompt flag, reads the
71system prompt ahead of it, from prompts/<run-id>.input.md. If what still goes
72on the tmux command line (the worker system prompt for codex and sandbox claude
73runs) exceeds tmux's limit, launch fails before creating a worktree.
74
75Use --repo to launch an agent against a different repository. If the name
76matches a registered project (no owner/ prefix), the project's local path is
77used directly. Otherwise, the repo is cloned from GitHub.
78
79The agent is told to deliver by opening a PR when the target repo's origin is
80on github.com. For any other origin (a plain ssh or local remote) it is told to
81push its branch and not open a PR, and to end with a report of the branch, head
82SHA, diff summary and checks run, for the operator to integrate from.
83
84On a valley project, --issue takes a knot from the project's plan graph
85instead of a GitHub issue: its ID (oc-, bd-, ida- or qn- and 7 hex digits),
86or <project>:<id> for a knot in another project's graph on the same valley.
87The repo must deliver to a valley, as finalize decides it, whose 'valley help'
88lists knot; flow reads and writes knots only through 'valley knot'. Launch
89reads the knot, which must be an active outcome or bug, names the branch from
90its title, and appends the knot, its parent chain and its comments to the
91brief in a delimited "Project notes (untrusted)" block, as data the agent is
92told never to take as instructions. Just before the agent starts it claims the
93knot for the run ('valley knot claim <id> --run <run-id>'). A knot claimed by
94a run that is still running, or by a run flow doesn't know, is refused; the
95claim of a run flow knows has ended is released and taken over. At finalize,
96a run whose pushed head the valley took links its change to the knot ('valley
97knot link <id> --change valley:<repo>/<change-id>'); a run that failed,
98paused or pushed nothing the valley took comments on the knot instead. Either
99way the run's claim is cleared. Once the dashboard sees the change landed, it
100comments on the knot with the landed commit, and sets it done (an outcome) or
101closed (a bug) only if every change it links has landed, none of its children
102is active and no other run claims it. Other knots that link the change get
103the comment alone. A knot can't be combined with --pr.
104
105An agent that opens a PR is told to request review from pr_reviewer. When
106pr_reviewer is unset, launch picks a collaborator with push access to the
107target repo, leaving out bots and the gh user the agent runs as (the PR's
108author): the repo owner if they are one, else the only one. When none is
109found, or a gh call fails, launch warns and the agent requests no review.
110
111Use --pr to push fixes to an existing PR's branch instead of creating a new
112PR. The agent will commit and push to the PR branch directly. This is also
113how you resume a budget-paused PR: relaunch against the paused PR and the
114follow-up picks up from the WIP commit flow left on the branch. When the
115follow-up agent's _finalize runs, the 'klaus:budget-paused' label is cleared
116automatically.
117
118Use --change <ref> to continue a change in a repo that delivers without PRs
119(origin not on GitHub), as --pr continues a PR. <ref> is a run ID, a full
120change ID or a valley handle. A run ID names that run's change. A change ID or
121handle names the change of the runs recorded in any session for the target
122repo whose change ID it is or starts, or whose recorded valley handle it is;
123when no run matches and the repo delivers to a valley that lists changes,
124'valley changes --json' is asked. A ref that names several changes is an error
125listing them. The worktree tracks the change's branch on origin: its active
126version's when the valley lists one, else the branch its newest run pushed.
127Launch fails, naming the change and its last known head, when that branch
128isn't on origin. The run keeps the change ID, returns the change to draft as
129below, continues the conversation of the change's most recent run when its
130backend can (below), and is told to push fast-forward to the same branch;
131finalize marks the new head ready. In a repo that delivers to a valley,
132which lands a change as one commit under its head commit's message, the
133agent is instead told to amend the change's head commit or end with a commit
134whose message describes the whole change, never to merge another branch into
135it, to rebase it onto origin/main when the brief asks it to or the change
136conflicts with origin/main, and to push it to the same branch with 'git push
137--force-with-lease=refs/heads/<branch>:<head> origin
138HEAD:refs/heads/<branch>', <head> being the branch's tip on origin when
139launch checked it, which the worktree starts from. Finalize marks the rebased
140head ready as the next version of the same change. Every backend keeps the
141branch, the change ID and the provenance trailers; only the conversation
142differs: Claude replays the stored conversation, on any machine that has the
143data ref, Codex forks its own session on the same machine, and agy starts
144fresh.
145With --resume-from, that run's conversation is used, and --change still picks
146the branch and the change ID. When that conversation can't be resumed, the
147agent starts fresh rather than replaying another, for --pr as for --change, and
148the replay: line says so.
149
150--pr and --change, and --resume-from when it continues its run's branch
151(below), refuse while a run in any session is still running on the branch
152they would work on, or on the change they continue (for --pr, the change of
153the run that opened the PR), in the target repo, naming that run. Wait for
154it to finish, or stop it and clean it up ('valley flow cleanup --force <run>',
155which removes its worktree with any uncommitted work), then launch again.
156Launch never removes a worktree to make way: while one has the branch
157checked out, whether a run's or your own checkout, it refuses, naming it
158and saying whether it holds uncommitted changes or commits origin lacks;
159clean that run up, or remove the worktree yourself, first. Nor does it
160discard commits on the local branch that aren't on origin/<branch>: it
161refuses, naming the branch. --force-takeover launches past a run still
162working on the branch or change, and resets the local branch to origin's
163tip, discarding such commits; it never removes a worktree either. A new
164run's worktree path must not exist. These launches, in one clone, take a
165lock from the check for a running holder through the new run's
166registration, so two of them can't both pass it: the second waits up to 5
167minutes, saying so, then finds the first run and refuses.
168
169A run without --pr or --change gets a new branch named <slug>-<tail>. The tail
170is the random end of the run ID (bd92f081 for 20261011-1843-bd92f081). The slug
171comes from the --issue title (a GitHub issue's or a knot's), else the prompt's first '# ' heading, else its
172first non-empty line: a leading '<repo-name>:' is dropped, the text is
173lowercased, each run of characters outside [a-z0-9] becomes one '-', and it is
174cut at a word boundary to at most 40 characters. A brief that opens with a
175descriptive '# title' names its branch. When no slug comes out, or git rejects
176the name, the branch is agent/<run-id>. Use --branch <name> to name it exactly:
177the name must pass 'git check-ref-format --branch' and must not exist locally or
178on origin.
179--branch, --pr and --change are mutually exclusive.
180
181Every commit the agent makes carries two provenance trailers, added by a
182commit-msg hook scoped to its worktree: 'Change-Id: <change id>' and
183'Klaus-Run: <run id>'. A --pr run keeps the change ID of the run that opened the
184PR, a --change run that of the change it names, a --resume-from run that of the
185run it resumes; any other run gets a new one. The trailers label commits for
186finding and auditing; they grant nothing.
187
188A pre-commit hook in the same worktree runs the project's formatter and
189stages the formatted files again: the format command line from the project's
190flow config, else 'nix fmt' when the flake has a formatter for the current
191system, else nothing.
192
193A run that keeps an existing change in a repo that delivers to a valley
194returns the change to draft before its agent starts ('valley unready
195<change-id>', within 30 seconds), so it can't be approved while the agent
196replaces it; finalize marks the pushed head ready again. This happens only
197when 'valley help' lists unready. A change that wasn't ready is left as is,
198and a failure is recorded on the run and printed as a warning; neither stops
199the launch.
200
201Use --resume-from <run-id> to continue a previous run's Claude conversation in
202a fresh worktree, paused or not — the follow-up keeps what the earlier agent
203learned instead of re-exploring the repo. Prior errors produce a warning but do
204not prevent resume. It starts fresh if the transcript cannot be located or
205staged.
206
207Without --pr, --change or --branch, a --resume-from run continues the branch
208its run pushed without a PR, as when finalize salvaged that run's work at a
209usage limit, when the branch is still that change's and nothing took the
210change further: the run is in the target repo (by name and, where both are
211known, by GitHub owner); no run of the change has a PR; origin has the
212branch; no run of another change worked on the branch, and origin's tip
213carries no other change's Change-Id; the change's branch (its valley's
214active version's, else its newest push's) is still that branch; that branch
215has that run's push in its history, or a later head of the change that
216rewrote it, as a restack does: a later run's push there, or the head the
217change's branch was found at; and, for a repo on GitHub, no PR, open or not,
218has the branch as its head (asked with 'gh api'). The run keeps the change ID, its
219worktree tracks origin's branch, and it is told to push fast-forward to it
220(and, where the repo takes PRs, to open the PR from it), as --change does; it
221refuses as --change does (above). Otherwise, as when GitHub can't be asked,
222the run gets a new branch instead and the resume: line of the launch output
223says why. A run that pushed no branch, or opened a PR, gets a new branch too.
224
225A --pr, --change or --resume-from run that continues a branch records, as
226took_over, the runs of its change that needed attention and whose pushed
227heads its starting head contains (the takes on: line names them), and
228finalize adds those whose pushed heads the head a run left on origin
229contains. Such a run carries their attention from then on: valley flow status
230shows them superseded once it is running or finished, and if it in turn
231ended needing attention or failing, it shows needs-attention itself, even
232once its PR is merged, closed or out of reach. A --resume-from run on a new
233branch takes nothing on.
234
235For a budget-paused PR, and for any --change run, flow continues the
236conversation of the most recent run on it by default (trajectory replay),
237avoiding a cold re-exploration of the repo. Only that run counts: an older
238conversation never saw the work after it. A Claude run restores a Claude
239run's stored conversation and runs 'claude --resume'; the conversation is read
240from the local clone's data ref, which is pushed to origin only when
241push_data_ref is true, so by default replay works on the machine that ran the
242earlier agent. A Codex run forks a Codex run's local session ('codex exec
243fork'), on the same machine. agy workers can't resume a conversation. The run
244starts fresh, and the replay: line names the run and says why, when that run
245used another backend, its conversation was kept off the data ref as
246potentially sensitive or is on another machine, it is over the size
247threshold, or its session is unknown. Use --no-replay to force a fresh agent,
248--replay (Claude only) to force replay (bypassing the size threshold), and
249--replay-threshold-kb to tune the per-launch size cap.
250
251Use --backend to select claude, codex, or agy independently of the coordinator.
252The saved session worker selection overrides default_agent_backend in config.
253Use --model and --effort to override backends.<backend>.model / effort. Legacy
254default_agent_model / default_agent_effort apply only to Claude. Models are
255passed through verbatim; each CLI validates its own identifiers. agy accepts
256low/medium/high effort; Codex also accepts minimal/xhigh, Claude xhigh/max.
257Dollar budgets and stored trajectory replay are Claude-only. Codex forks a
258recorded local thread with --resume-from, or on --pr and --change follow-ups
259of a Codex run; agy worker follow-ups start fresh.
260
261Use --reason to say why the run is dispatched, such as docs-timer for a
262timer's launch: lowercase letters, digits and hyphens. It is recorded on the
263run and its events (dispatch_reason). Without it the reason is launch,
264pr-follow-up (--pr), budget-resume (--pr on a budget-paused PR),
265change-follow-up (--change) or resume (--resume-from); the pipeline's fix
266agents pass ci-fix, review-fix, review-comment-fix or conflict-fix, and
267valley flow restack-conflicts passes restack-conflict. 'valley flow report time'
268sums runs and follow-ups by reason.
269
270A dispatcher that checked a change before launching a run on it passes what
271it checked, and launch starts no worker unless the change still stands so.
272With --change naming a full change ID, --expect-owner, --expect-branch,
273--expect-head and --expect-draft each require of the change, as 'valley
274changes --json' lists it: its record's owner; its active version's branch,
275which must also be the branch launch works on; its active version's head,
276which must also be origin's tip of that branch and the worktree's start;
277and that it is a draft. Under the lock it takes for continuing a branch,
278launch fetches origin's branch and asks the valley, and checks them just
279before it creates the worktree; it asks both again, after it has returned
280the change to draft and set everything else up, just before the worker
281starts. It fails closed: a valley or origin it can't ask, runs it can't read
282to find a live holder, a change that isn't as expected, and a 'valley
283unready' that fails or that the valley on PATH doesn't offer each fail the
284launch. valley flow restack-conflicts launches each resolution run this way.
285
286--run-id names the run, in the form run IDs take (YYYYMMDD-HHMM- and 8 hex
287digits), for a dispatcher that records the run before launching it; launch
288refuses an ID a recorded run has. A launch with --run-id that fails before
289starting its worker exits with status 3, so the dispatcher knows no run
290started under the ID; any other failure exits with status 1. A worker whose
291run launch can't record is stopped, so every worker that runs is recorded.
292
293When sandbox_host is configured in ~/.klaus/config.json, agents run remotely
294via SSH on the sandbox host. The worktree is synced before launch and results
295are synced back after completion. Use --local to force local execution, or
296--host to override the configured sandbox host.`,
297 Args: cobra.MaximumNArgs(1),
298 RunE: func(cmd *cobra.Command, args []string) (err error) {
299 // A dispatcher that named the run learns from the exit status
300 // whether a worker may have started.
301 var workerStarting bool
302 defer func() {
303 if err != nil && !workerStarting && cmd.Flags().Changed("run-id") {
304 err = &exitError{code: exitNoWorker, err: err}
305 }
306 }()
307 promptFile, _ := cmd.Flags().GetString("prompt-file")
308 prompt, err := resolvePrompt(args, promptFile)
309 if err != nil {
310 return err
311 }
312 issue, _ := cmd.Flags().GetString("issue")
313 budget, _ := cmd.Flags().GetString("budget")
314 repoRef, _ := cmd.Flags().GetString("repo")
315 prNumber, _ := cmd.Flags().GetString("pr")
316 forceLocal, _ := cmd.Flags().GetBool("local")
317 hostOverride, _ := cmd.Flags().GetString("host")
318 resumeFrom, _ := cmd.Flags().GetString("resume-from")
319 model, _ := cmd.Flags().GetString("model")
320 effort, _ := cmd.Flags().GetString("effort")
321 replayFlag, _ := cmd.Flags().GetBool("replay")
322 noReplay, _ := cmd.Flags().GetBool("no-replay")
323 replayThresholdKB, _ := cmd.Flags().GetInt("replay-threshold-kb")
324 branchFlag, _ := cmd.Flags().GetString("branch")
325 changeRef, _ := cmd.Flags().GetString("change")
326 forceTakeover, _ := cmd.Flags().GetBool("force-takeover")
327 reasonFlag, _ := cmd.Flags().GetString("reason")
328 runIDFlag, _ := cmd.Flags().GetString("run-id")
329 var expect changeExpectation
330 expect.Owner, _ = cmd.Flags().GetString("expect-owner")
331 expect.Branch, _ = cmd.Flags().GetString("expect-branch")
332 expect.Head, _ = cmd.Flags().GetString("expect-head")
333 expect.Draft, _ = cmd.Flags().GetBool("expect-draft")
334 setupStart := time.Now()
335 ctx := cmd.Context()
336 tmuxClient := tmux.NewExecClient()
337
338 if !tmux.InSession() {
339 return fmt.Errorf("valley flow launch must be run inside a tmux session")
340 }
341
342 if replayFlag && noReplay {
343 return fmt.Errorf("--replay and --no-replay are mutually exclusive")
344 }
345 if cmd.Flags().Changed("change") && changeRef == "" {
346 return fmt.Errorf("--change needs a run ID, change ID or valley handle")
347 }
348 if err := checkContinuation(prNumber, changeRef, cmd.Flags().Changed("branch")); err != nil {
349 return err
350 }
351 knotRef, isKnot := valley.ParseKnotRef(issue)
352 if isKnot && prNumber != "" {
353 return fmt.Errorf("--issue %s names a valley knot, and --pr continues a GitHub PR; a knot is worked in a valley project", issue)
354 }
355 if err := checkDispatchReason(reasonFlag); err != nil {
356 return err
357 }
358 if err := expect.validate(changeRef); err != nil {
359 return err
360 }
361 if cmd.Flags().Changed("run-id") && !validRunID(runIDFlag) {
362 return fmt.Errorf("--run-id %q isn't a run ID: YYYYMMDD-HHMM- and 8 hex digits", runIDFlag)
363 }
364 if forceTakeover && prNumber == "" && changeRef == "" && resumeFrom == "" {
365 return fmt.Errorf("--force-takeover takes over a PR's or a change's branch; use it with --pr, --change or --resume-from")
366 }
367 if cmd.Flags().Changed("branch") {
368 if err := git.CheckBranchName(ctx, branchFlag); err != nil {
369 return fmt.Errorf("--branch: %w", err)
370 }
371 }
372
373 // Host repo — optional when --repo is specified or session target is set
374 hostRoot, _ := git.RepoRoot()
375 gitClient := git.NewExecClient()
376
377 // Load session target (if any) to feed into resolution
378 var sessionTarget string
379 if s, storeErr := sessionStore(); storeErr == nil {
380 if hds, ok := s.(*run.HomeDirStore); ok {
381 if target, loadErr := run.LoadTarget(hds.BaseDir()); loadErr == nil {
382 sessionTarget = target
383 }
384 }
385 }
386
387 // Resolve which repo to use. Priority: --repo > session target > hostRoot
388 reg, _ := project.Load()
389 repoRef, projectLocalPath := resolveRepoTarget(repoRef, sessionTarget, reg)
390
391 if hostRoot == "" && repoRef == "" && projectLocalPath == "" {
392 return fmt.Errorf("no target repo — use --repo owner/repo, 'valley flow target owner/repo', or 'valley flow project add' to register a project")
393 }
394
395 hostCfg, err := config.Load(hostRoot)
396 if err != nil {
397 return err
398 }
399
400 kind, err := resolveAgentBackend(cmd, hostCfg)
401 if err != nil {
402 return err
403 }
404 if kind != backend.Claude {
405 if cmd.Flags().Changed("budget") {
406 return fmt.Errorf("--budget is only supported by the claude backend")
407 }
408 if replayFlag {
409 return fmt.Errorf("--replay is only supported by the claude backend")
410 }
411 if hostCfg.DefaultBudget != "" {
412 fmt.Fprintf(os.Stderr, "%s does not enforce dollar budgets; default_budget does not apply\n", kind)
413 }
414 }
415 if budget == "" {
416 budget = hostCfg.DefaultBudget
417 }
418 defaults := hostCfg.AgentDefaults(string(kind))
419 if model == "" {
420 model = defaults.Model
421 }
422 if effort == "" {
423 effort = defaults.Effort
424 }
425 if err := kind.ValidateEffort(effort); err != nil {
426 return err
427 }
428 if err := config.ValidateAgentDisplay(hostCfg.AgentDisplay); err != nil {
429 return err
430 }
431
432 store, err := sessionStore()
433 if err != nil {
434 return err
435 }
436 if err := store.EnsureDirs(); err != nil {
437 return err
438 }
439
440 id := runIDFlag
441 if id == "" {
442 if id, err = run.GenID(); err != nil {
443 return err
444 }
445 } else if all, err := run.ListAllSessions(); err != nil {
446 return fmt.Errorf("--run-id: reading the recorded runs: %w", err)
447 } else if findRun(all, id) != nil {
448 return fmt.Errorf("--run-id: a run %s is already recorded", id)
449 }
450
451 // Determine the target repo for git operations.
452 // When --repo is set, we clone the target and use it for worktree/branch ops.
453 // When --repo matches a registered project, use the local path directly.
454 // State is always tracked in the host repo.
455 var (
456 repoRoot string // repo dir for git ops (clone or host)
457 repoName string
458 defaultBranch string
459 targetRepo *string
460 cloneDirPtr *string
461 // projectCfg is the target repo's config, which sets its
462 // formatter.
463 projectCfg = hostCfg
464 )
465
466 if projectLocalPath != "" {
467 // Registered project — use local path directly, no cloning
468 repoRoot = projectLocalPath
469 repoName = filepath.Base(projectLocalPath)
470
471 defaultBranch = "main"
472 targetCfg, loadErr := config.Load(projectLocalPath)
473 if loadErr != nil {
474 fmt.Fprintf(os.Stderr, "warning: could not load config from project %s: %v\n", repoRef, loadErr)
475 } else {
476 projectCfg = targetCfg
477 if targetCfg.DefaultBranch != "" {
478 defaultBranch = targetCfg.DefaultBranch
479 }
480 }
481
482 // Store as target for state tracking
483 targetRepo = &repoRef
484 cloneDirPtr = &projectLocalPath
485 } else if repoRef != "" {
486 owner, repo, cloneURL, err := git.ParseRepoRef(repoRef)
487 if err != nil {
488 return fmt.Errorf("parsing repo reference: %w", err)
489 }
490
491 cloneDir := filepath.Join(hostCfg.WorktreeBase, ".repos", owner, repo)
492
493 fmt.Printf("Cloning/fetching %s/%s...\n", owner, repo)
494 if err := gitClient.EnsureClone(ctx, cloneURL, cloneDir); err != nil {
495 return fmt.Errorf("cloning %s: %w", repoRef, err)
496 }
497
498 repoRoot = cloneDir
499 repoName = repo
500 cloneDirPtr = &cloneDir
501 targetRepo = &repoRef
502
503 // Use target repo config for default_branch if available
504 defaultBranch = "main"
505 targetCfg, loadErr := config.Load(cloneDir)
506 if loadErr != nil {
507 fmt.Fprintf(os.Stderr, "warning: could not load config from target repo %s: %v\n", repoRef, loadErr)
508 } else {
509 projectCfg = targetCfg
510 if targetCfg.DefaultBranch != "" {
511 defaultBranch = targetCfg.DefaultBranch
512 }
513 }
514 } else {
515 repoRoot = hostRoot
516 repoName = filepath.Base(hostRoot)
517 defaultBranch = hostCfg.DefaultBranch
518 }
519
520 worktree := filepath.Join(hostCfg.WorktreeBase, repoName, id)
521
522 // Background-sync registered project clones so the agent's worktree
523 // branches from fresh main. Non-blocking; results go to ~/.klaus/sync.log.
524 // Exclude repoRoot to avoid racing with the foreground fetch below.
525 kickoffBackgroundSync("launch", repoRoot)
526
527 // Fetch all refs so the worktree starts from the latest state.
528 // Skip when EnsureClone was already called — it fetches with the
529 // same flags (--prune --tags), so a second fetch is redundant.
530 if repoRef == "" || projectLocalPath != "" {
531 if err := gitClient.FetchAll(ctx, repoRoot); err != nil {
532 return fmt.Errorf("fetching origin: %w", err)
533 }
534 }
535
536 // Normalize target repo name against the project registry so that
537 // "site", "maintainer/site", and full URLs all resolve to the same
538 // canonical name in the dashboard.
539 normalizedTarget := normalizeTargetRepo(targetRepo, hostRoot)
540
541 // A knot is read, and its claim checked, before anything is created.
542 var knot *knotWork
543 if isKnot {
544 knot, err = prepareKnot(ctx, tmuxClient, repoRoot, repoName, "origin/"+defaultBranch, knotRef)
545 if err != nil {
546 return fmt.Errorf("--issue: %w", err)
547 }
548 }
549
550 // When --pr or --change is set, track the PR's or the change's
551 // branch instead of creating a new one; so does --resume-from, on
552 // the branch its run pushed, when nothing took the change further.
553 var branch string
554 var isPRFix bool
555 var prURL string
556 var onChange *changeTarget
557 var resumeNote string // why a --resume-from run gets a new branch
558 // The valley's changes of the target repo, for a launch that
559 // continues a change.
560 listValley := func() (*valley.Changes, error) {
561 if !valley.Detect(ctx, repoRoot, "", "origin/"+defaultBranch) {
562 return nil, errNoValley
563 }
564 return valley.ListRepo(ctx, repoRoot)
565 }
566
567 if prNumber != "" {
568 ghRepo := resolveGHRepo(repoRef, repoRoot)
569 ghClient := gh.NewGHCLIClient(ghRepo)
570 prBranch, err := ghClient.GetBranch(ctx, prNumber)
571 if err != nil {
572 return fmt.Errorf("getting PR branch: %w", err)
573 }
574 branch = prBranch
575 isPRFix = true
576
577 // Look up the PR URL for state tracking
578 prURL, err = ghClient.GetURL(ctx, prNumber)
579 if err != nil {
580 fmt.Fprintf(os.Stderr, "warning: could not get PR URL for #%s: %v\n", prNumber, err)
581 }
582 } else if changeRef != "" {
583 if !isDirectPushRepo(repoRoot) {
584 return fmt.Errorf("--change continues a change in a repo that delivers without PRs, and %s's origin is on GitHub; use --pr to continue a PR", repoName)
585 }
586 states, _ := run.ListAllSessions()
587 onChange, err = resolveChange(changeRef, changeSources{Runs: states, Repo: targetName(normalizedTarget), Valley: listValley})
588 if err != nil {
589 return fmt.Errorf("--change: %w", err)
590 }
591 branch = onChange.Branch
592 } else if branchFlag != "" {
593 // A new run's branch must be new: reusing one would build on, or
594 // reset, whatever work it already holds.
595 const pickAnother = "pick a new name, or use --pr or --change to continue an existing PR's or change's branch"
596 if git.RefExists(ctx, repoRoot, "refs/heads/"+branchFlag) {
597 return fmt.Errorf("branch %q already exists in %s; %s", branchFlag, repoName, pickAnother)
598 }
599 sha, err := gitClient.RemoteBranchSHA(ctx, repoRoot, branchFlag)
600 if err != nil {
601 return fmt.Errorf("checking origin for branch %q: %w", branchFlag, err)
602 }
603 if sha != "" {
604 return fmt.Errorf("branch %q already exists on origin; %s", branchFlag, pickAnother)
605 }
606 branch = branchFlag
607 } else {
608 if resumeFrom != "" {
609 states, _ := run.ListAllSessions()
610 src := changeSources{Runs: states, Repo: targetName(normalizedTarget), Valley: listValley, Slug: repoSlugForDir(repoRoot)}
611 if src.Slug != "" {
612 src.PRs = func(branch string) ([]string, error) {
613 return gh.NewGHCLIClient(src.Slug).PRsForBranch(ctx, src.Slug, branch)
614 }
615 }
616 onChange, resumeNote = resumeTarget(ctx, repoRoot, resumeFrom, src)
617 }
618 if onChange != nil {
619 branch = onChange.Branch
620 } else {
621 var issueTitle string
622 if knot != nil {
623 issueTitle = knot.Knot.Title
624 } else if issue != "" {
625 title, err := gh.NewGHCLIClient(resolveGHRepo(repoRef, repoRoot)).GetIssueTitle(ctx, issue)
626 if err != nil {
627 fmt.Fprintf(os.Stderr, "warning: could not fetch the title of issue %s for the branch name: %v\n", issue, err)
628 }
629 issueTitle = title
630 }
631 branch = defaultBranchName(ctx, id, repoName, issueTitle, prompt)
632 }
633 }
634 // The flag that has the launch continue a branch, for its errors.
635 continuing := "--change"
636 switch {
637 case isPRFix:
638 continuing = "--pr"
639 case changeRef == "" && onChange != nil:
640 continuing = "--resume-from"
641 }
642
643 // Creating the worktree resets the branch, so a run still working on
644 // the branch, or on the change, keeps it unless the operator takes
645 // over, and a worktree that has it checked out is never removed,
646 // even then. The check and the new run's registration happen under
647 // one lock, so two launches continuing a branch can't both pass it.
648 if isPRFix || onChange != nil {
649 release, err := lockContinuation(ctx, repoRoot)
650 if err != nil {
651 return fmt.Errorf("%s: %w", continuing, err)
652 }
653 defer release()
654 if !forceTakeover {
655 if err := checkNoLiveHolder(ctx, tmuxClient, branch, prURL, normalizedTarget, onChange); err != nil {
656 return fmt.Errorf("%s: %w", continuing, err)
657 }
658 }
659 }
660 if onChange != nil {
661 // A dispatcher's expectations are of origin as it is, not as
662 // the fetch before the lock found it.
663 if expect.set() && onChange.Branch != "" {
664 if err := git.FetchRemoteBranch(ctx, repoRoot, onChange.Branch); err != nil {
665 return fmt.Errorf("--change: fetching origin's %s: %w", onChange.Branch, err)
666 }
667 }
668 if err := onChange.checkBranch(ctx, repoRoot); err != nil {
669 return fmt.Errorf("%s: %w", continuing, err)
670 }
671 }
672
673 // The brief carries the knot as project notes, data rather than
674 // instructions.
675 if knot != nil {
676 prompt += knot.notes()
677 }
678
679 // Build system prompt (from target repo's .klaus/prompt.md if it exists)
680 delivery := runDelivery(isPRFix, repoRoot)
681 directPush := delivery == run.DeliveryPush
682 var vars config.PromptVars
683 if isPRFix {
684 vars = config.PromptVars{
685 RunID: id,
686 Issue: issue,
687 PR: prNumber,
688 Branch: branch,
689 RepoName: repoName,
690 Head: git.RefCommit(ctx, repoRoot, "refs/remotes/origin/"+branch),
691 }
692 } else {
693 // Only a run that opens a GitHub PR requests a review.
694 var reviewer string
695 if !directPush {
696 var warning string
697 reviewer, warning = gh.NewReviewerResolver().Resolve(ctx, repoSlugForDir(repoRoot), hostCfg.PRReviewer)
698 if warning != "" {
699 fmt.Fprintf(os.Stderr, "warning: %s\n", warning)
700 }
701 }
702 vars = config.PromptVars{
703 RunID: id,
704 Issue: issue,
705 Branch: branch,
706 RepoName: repoName,
707 Reviewer: reviewer,
708 DirectPush: directPush,
709 }
710 if knot != nil {
711 vars.Issue, vars.Knot = "", knotRef.String()
712 }
713 if onChange != nil {
714 vars.Change = onChange.Name
715 vars.Head = onChange.Tip
716 // A valley change may be restacked onto main, its rebase
717 // pushed with a lease on the commit the worktree starts at.
718 if directPush && valley.Detect(ctx, repoRoot, "", "origin/"+defaultBranch) {
719 vars.Valley = true
720 }
721 }
722 }
723 // A follow-up's prompt names the commit its worktree starts at, for
724 // its lease and the round's size. Until the worktree exists,
725 // origin's tip stands in to size the prompt; a fetch meanwhile can
726 // move that tip, so the prompt is rendered again from the
727 // worktree's HEAD.
728 rules := loadHouseRules(ctx, repoRoot, hostCfg, reg, os.Stdout)
729 renderSystemPrompt := func() (string, error) {
730 p, err := config.RenderWorkerPrompt(repoRoot, vars)
731 if err != nil {
732 return "", fmt.Errorf("rendering prompt: %w", err)
733 }
734 return rules.Append(p), nil
735 }
736 sysPrompt, err := renderSystemPrompt()
737 if err != nil {
738 return err
739 }
740
741 logFile := filepath.Join(store.LogDir(), id+".jsonl")
742 promptPath := filepath.Join(run.PromptDir(store), id+".md")
743 sysPromptPath := filepath.Join(run.PromptDir(store), id+".system.md")
744 // The worker reads its input on stdin. agy's, with the system prompt
745 // ahead of the brief, gets a file of its own.
746 inputPath := promptPath
747 if kind.Stdin(sysPrompt, prompt) != prompt {
748 inputPath = filepath.Join(run.PromptDir(store), id+".input.md")
749 }
750 dirs := workerDirs{tmux: workerTmuxDir(store, id), scratch: workerScratchDir(store, id)}
751 workerOpts := backend.Options{
752 SystemPrompt: sysPrompt, SystemPromptFile: sysPromptPath, Budget: budget, Prompt: prompt,
753 RunID: id, Model: model, Effort: effort,
754 }
755
756 // For cross-repo launches with a host repo, finalize must run from the
757 // host repo context so that data-ref sync works correctly.
758 var finalizePrefix string
759 if targetRepo != nil && hostRoot != "" {
760 finalizePrefix = fmt.Sprintf("cd %s && ", shellQuote(hostRoot))
761 }
762 // Determine sandbox host: --host flag > config sandbox_host, unless --local.
763 // Reachability is settled before the size check so the check is exact.
764 sandboxHost := hostCfg.SandboxHost
765 if hostOverride != "" {
766 sandboxHost = hostOverride
767 }
768 if forceLocal {
769 sandboxHost = ""
770 }
771 if sandboxHost != "" && !CheckSandboxReachable(sandboxHost) {
772 fmt.Fprintf(os.Stderr, "warning: sandbox %s unreachable, falling back to local execution\n", sandboxHost)
773 sandboxHost = ""
774 }
775 // Fail before a worktree exists. A resume ID (Claude session or Codex
776 // thread, both UUIDs) is only known later, so size one in; a sandbox
777 // run can still fall back to local, so the local command must fit too.
778 sizeCheck := workerOpts
779 if resumeFrom != "" || isPRFix || onChange != nil {
780 sizeCheck.ResumeID = "00000000-0000-0000-0000-000000000000"
781 }
782 hosts := []string{sandboxHost}
783 if sandboxHost != "" {
784 hosts = append(hosts, "")
785 }
786 for _, host := range hosts {
787 if _, err := agentPaneCommand(kind, sizeCheck, inputPath, host, worktree, logFile, finalizePrefix, id, dirs); err != nil {
788 return err
789 }
790 }
791 // A local worker that can't run its commands doesn't start: an agy
792 // worker without bash can edit files and nothing else. A sandbox
793 // worker runs on its host's PATH.
794 if sandboxHost == "" {
795 if err := checkWorkerPath(kind, worktree); err != nil {
796 return err
797 }
798 }
799
800 switch {
801 case isPRFix:
802 fmt.Printf("Launching agent %s (PR #%s fix)...\n", id, prNumber)
803 case onChange != nil:
804 fmt.Printf("Launching agent %s (continuing change %s)...\n", id, onChange.Name)
805 default:
806 fmt.Printf("Launching agent %s...\n", id)
807 }
808 if targetRepo != nil {
809 fmt.Printf(" target: %s\n", *targetRepo)
810 }
811 if isPRFix || onChange != nil {
812 // A dispatcher's expectations hold, the valley asked now and
813 // origin's branch as fetched under the lock, before anything
814 // is created.
815 if expect.set() {
816 if err := expect.check(onChange, onChange.Tip, listValley); err != nil {
817 return fmt.Errorf("--change: %w", err)
818 }
819 }
820 // Create worktree tracking the PR's or the change's branch
821 if err := gitClient.WorktreeAddTrack(ctx, repoRoot, worktree, branch, forceTakeover); err != nil {
822 var lw *git.LocalWorkError
823 var inUse *git.WorktreeInUseError
824 switch {
825 case errors.As(err, &lw):
826 return fmt.Errorf("%s: creating worktree: %w; push or remove that work, or pass --force-takeover to discard it", continuing, err)
827 case errors.As(err, &inUse):
828 states, _ := run.ListAllSessions()
829 return fmt.Errorf("%s: %w", continuing, occupantError(branch, inUse.Path, inUse.Work, worktreeOwner(states, inUse.Path)))
830 }
831 return fmt.Errorf("%s: creating worktree: %w", continuing, err)
832 }
833 } else {
834 if err := gitClient.WorktreeAdd(ctx, repoRoot, worktree, branch, "origin/"+defaultBranch); err != nil {
835 return fmt.Errorf("creating worktree: %w", err)
836 }
837 }
838
839 // Clean up the worktree if the launch fails after this point.
840 // This prevents stale worktrees from blocking future dispatch retries.
841 var launchSucceeded bool
842 var keepWorktree bool // a worker may run in it
843 var knotRec *run.Knot // the knot's record once launch claimed it
844 defer func() {
845 if !launchSucceeded && !keepWorktree {
846 if knotRec != nil {
847 releaseKnot(context.Background(), repoRoot, knotRec, id)
848 }
849 fmt.Fprintf(os.Stderr, "cleaning up worktree after failed launch: %s\n", worktree)
850 if rmErr := gitClient.WorktreeRemove(context.Background(), repoRoot, worktree); rmErr != nil {
851 fmt.Fprintf(os.Stderr, "warning: failed to remove worktree %s: %v\n", worktree, rmErr)
852 }
853 os.Remove(promptPath)
854 os.Remove(sysPromptPath)
855 os.Remove(dirs.tmux)
856 os.Remove(dirs.scratch)
857 }
858 }()
859
860 if expect.Head != "" {
861 if head := gitHead(ctx, worktree); head != expect.Head {
862 return fmt.Errorf("--change: the worktree starts at %s, not the expected head %s", shortSHA(head), shortSHA(expect.Head))
863 }
864 }
865 if isPRFix || onChange != nil {
866 if vars.Head = gitHead(ctx, worktree); vars.Head == "" {
867 return fmt.Errorf("%s: reading the worktree's head", continuing)
868 }
869 if sysPrompt, err = renderSystemPrompt(); err != nil {
870 return err
871 }
872 workerOpts.SystemPrompt = sysPrompt
873 }
874
875 fmt.Printf(" worktree: %s\n", worktree)
876 fmt.Printf(" branch: %s\n", branch)
877 switch {
878 case continuing == "--resume-from":
879 fmt.Printf(" resume: continuing the branch run %s pushed\n", resumeFrom)
880 case resumeNote != "":
881 fmt.Printf(" resume: new branch: %s\n", resumeNote)
882 }
883 if directPush {
884 fmt.Printf(" delivery: push branch, no PR (origin is not on GitHub)\n")
885 }
886
887 change, err := chooseChangeID(ctx, store, changeIDInput{
888 IsPRFix: isPRFix,
889 PRURL: prURL,
890 PRBranch: branch,
891 TargetRepo: normalizedTarget,
892 ResumeFrom: resumeFrom,
893 Change: onChange,
894 Worktree: worktree,
895 DefaultBranch: defaultBranch,
896 })
897 if err != nil {
898 return fmt.Errorf("choosing change ID: %w", err)
899 }
900 fmt.Printf(" change: %s (%s)\n", change.ID, change.From)
901
902 // The runs of the change needing attention whose pushed work the
903 // branch holds are this run's to carry on.
904 var tookOver []string
905 if isPRFix || onChange != nil {
906 states, _ := run.ListAllSessions()
907 holder := &run.State{ID: id}
908 candidates := takeoverCandidates(states, holder, change.ID, targetName(normalizedTarget), change.Repo)
909 tookOver = recordTakeovers(ctx, worktree, "HEAD", holder, candidates)
910 if len(tookOver) > 0 {
911 fmt.Printf(" takes on: the work of %s, which needed attention\n", strings.Join(tookOver, ", "))
912 }
913 }
914
915 // Every commit the agent makes carries the provenance trailers, so a
916 // run that cannot stamp them does not start.
917 format := formatCommand(ctx, projectCfg, worktree)
918 if err := gitClient.InstallHooks(ctx, worktree, git.Provenance{RunID: id, ChangeID: change.ID}, format); err != nil {
919 return fmt.Errorf("installing git hooks: %w", err)
920 }
921 if len(format) > 0 {
922 fmt.Printf(" format: %s\n", strings.Join(format, " "))
923 }
924
925 // A follow-up on a valley change takes it back to draft before the
926 // agent starts, so the operator can't approve a head it is replacing.
927 unready := unreadyChange(ctx, worktree, change)
928 // A dispatcher's expectations need the change a draft.
929 if expect.set() {
930 switch {
931 case unready == nil:
932 return fmt.Errorf("--change: could not return change %s to draft: the valley on PATH has no unready, or the worktree's head carries no valley policy", onChange.Name)
933 case unready.Error != "":
934 return fmt.Errorf("--change: could not return change %s to draft: %s", onChange.Name, unready.Error)
935 }
936 }
937
938 // A --pr launch on a budget-paused PR resumes it.
939 var budgetPaused bool
940 if isPRFix {
941 paused, perr := draft.HasBudgetPausedLabel(ctx, draft.ExecRunner{}, worktree, resolveGHRepo(repoRef, repoRoot), prNumber)
942 budgetPaused = perr == nil && paused
943 }
944
945 // Set up Nix dev environment if flake.nix exists
946 nix.SetupDevEnvironment(worktree)
947
948 if err := run.WritePromptFile(promptPath, prompt); err != nil {
949 return err
950 }
951 if err := run.WritePromptFile(sysPromptPath, sysPrompt); err != nil {
952 return err
953 }
954 if inputPath != promptPath {
955 if err := run.WritePromptFile(inputPath, kind.Stdin(sysPrompt, prompt)); err != nil {
956 return err
957 }
958 }
959
960 // The conversation the worker continues. --resume-from names it: a
961 // Claude transcript staged into the new worktree, or a local Codex
962 // thread to fork. Otherwise a run that continues a budget-paused PR
963 // (issue #261), or a change (--change), continues that of the most
964 // recent run on it, when the new run's backend can (resolveReplay):
965 // a Claude conversation is restored from the data ref for claude
966 // --resume, a Codex session is forked, and agy starts fresh. Any miss
967 // starts a fresh agent. Replay restores onto the local machine, so it
968 // only applies to local execution: a run destined for a sandbox host
969 // starts fresh there. An explicit --resume-from that can't be resumed
970 // starts fresh rather than replaying another conversation.
971 intendsSandbox := sandboxHost != ""
972 var resolvedResume, replayedFromRunID string
973 if resumeFrom != "" && (kind == backend.Claude || kind == backend.Codex && !intendsSandbox) {
974 if prior, err := store.Load(resumeFrom); err == nil {
975 resolvedResume = resolveResumeID(prior, kind, worktree)
976 }
977 }
978 if (isPRFix || onChange != nil) && !intendsSandbox {
979 switch {
980 case resumeFrom != "" && resolvedResume != "":
981 fmt.Printf(" replay: resuming conversation from run %s (--resume-from)\n", resumeFrom)
982 case resumeFrom != "":
983 fmt.Printf(" replay: fresh agent (--resume-from %s: its conversation can't be resumed)\n", resumeFrom)
984 default:
985 threshold := replayThresholdKB
986 if threshold == 0 {
987 threshold = hostCfg.ReplayThresholdKB
988 }
989 decision := replayDecision{Reason: "--no-replay"}
990 if !noReplay {
991 decision = resolveReplay(ctx, replayParams{
992 Kind: kind,
993 GitClient: gitClient,
994 Store: store,
995 RepoRoot: repoRoot,
996 DataRef: hostCfg.DataRef,
997 Worktree: worktree,
998 PRBranch: branch,
999 PRNumber: prNumber,
1000 GHRepo: resolveGHRepo(repoRef, repoRoot),
1001 Change: onChange,
1002 ForceReplay: replayFlag,
1003 ThresholdKB: threshold,
1004 })
1005 }
1006 if decision.SessionUUID != "" {
1007 resolvedResume = decision.SessionUUID
1008 replayedFromRunID = decision.SourceRunID
1009 fmt.Printf(" replay: %s\n", decision.Reason)
1010 } else {
1011 fmt.Printf(" replay: fresh agent (%s)\n", decision.Reason)
1012 }
1013 }
1014 }
1015
1016 // Build the selected backend command.
1017 if kind != backend.Claude && resumeFrom != "" && resolvedResume == "" {
1018 if onChange != nil || isPRFix {
1019 fmt.Fprintf(os.Stderr, "warning: %s starts a fresh worker conversation on the branch\n", kind)
1020 } else {
1021 fmt.Fprintf(os.Stderr, "warning: %s starts a fresh worker conversation; prior branch changes remain available with --pr or --change\n", kind)
1022 }
1023 }
1024 workerOpts.ResumeID = resolvedResume
1025
1026 // Sync worktree to the sandbox before launching
1027 var useSandbox bool
1028 var sandboxHostName string
1029 if sandboxHost != "" {
1030 if err := syncWorktreeToSandbox(sandboxHost, worktree); err != nil {
1031 fmt.Fprintf(os.Stderr, "warning: sandbox sync failed, falling back to local: %v\n", err)
1032 if err := checkWorkerPath(kind, worktree); err != nil {
1033 return err
1034 }
1035 } else {
1036 useSandbox = true
1037 sandboxHostName = sandboxHost
1038 }
1039 }
1040
1041 paneCmd, err := agentPaneCommand(kind, workerOpts, inputPath, sandboxHostName, worktree, logFile, finalizePrefix, id, dirs)
1042 if err != nil {
1043 return err
1044 }
1045 if !useSandbox {
1046 // Owner-only, like the prompts: the tmux directory will hold any
1047 // tmux socket the worker opens.
1048 if err := os.MkdirAll(dirs.tmux, 0o700); err != nil {
1049 return fmt.Errorf("creating the worker's tmux directory: %w", err)
1050 }
1051 if err := os.MkdirAll(dirs.scratch, 0o700); err != nil {
1052 return fmt.Errorf("creating the worker's scratch directory: %w", err)
1053 }
1054 }
1055
1056 // The knot is the run's before its agent starts.
1057 if knot != nil {
1058 if err := knot.claim(ctx, repoRoot, id); err != nil {
1059 return fmt.Errorf("--issue: claiming %s: %w", knotRef, err)
1060 }
1061 knotRec = knot.record()
1062 }
1063
1064 // What the clone shares across worktrees, as the agent finds it.
1065 sharedGit := snapshotSharedGit(ctx, worktree)
1066
1067 // A dispatcher's expectations hold still as the worker starts,
1068 // after everything else: the valley and origin, asked now. Nothing
1069 // here excludes another client meanwhile, but the change is a
1070 // draft, which approve refuses, and the worker's push is leased
1071 // on the head it starts from.
1072 if expect.set() {
1073 tip, err := gitClient.RemoteBranchSHA(ctx, repoRoot, branch)
1074 if err != nil {
1075 return fmt.Errorf("--change: asking origin for %s: %w", branch, err)
1076 }
1077 if err := expect.check(onChange, tip, listValley); err != nil {
1078 return fmt.Errorf("--change: %w", err)
1079 }
1080 }
1081
1082 // Launch the agent's tmux pane. Detached by default (its own window in
1083 // the agents session); splitFrom is non-empty only when agent_display
1084 // is "pane" and the coordinator's window was split.
1085 workerStarting = true
1086 paneID, splitFrom, err := startAgentPane(ctx, tmuxClient, hostCfg.AgentDisplayMode(),
1087 id, worktree, paneCmd, FormatPaneTitle(id, issue, prompt))
1088 if err != nil {
1089 return err
1090 }
1091
1092 // Keep the dashboard pane pinned at the bottom. RebalanceLayout uses
1093 // even-vertical which treats all panes equally, so the dashboard may
1094 // end up in the middle. Load the session state to find the dashboard
1095 // pane, then swap it to the last position if needed.
1096 if splitFrom != "" {
1097 pinDashboardToBottom(ctx, splitFrom, store, tmuxClient)
1098 }
1099
1100 // Write state
1101 agentStart := time.Now()
1102 createdAt := agentStart.Format(time.RFC3339)
1103 issuePtr := stringPtr(issue)
1104 var budgetPtr *string
1105 if kind == backend.Claude {
1106 budgetPtr = &budget
1107 }
1108 logFilePtr := &logFile
1109
1110 var hostPtr *string
1111 if useSandbox {
1112 hostPtr = &sandboxHostName
1113 }
1114
1115 state := &run.State{
1116 Backend: string(kind),
1117 ID: id,
1118 Prompt: prompt,
1119 Issue: issuePtr,
1120 PR: stringPtr(prNumber),
1121 Branch: branch,
1122 Worktree: worktree,
1123 TmuxPane: &paneID,
1124 Budget: budgetPtr,
1125 LogFile: logFilePtr,
1126 CreatedAt: createdAt,
1127 Host: hostPtr,
1128 TargetRepo: normalizedTarget,
1129 CloneDir: cloneDirPtr,
1130 SessionName: &id,
1131 Model: stringPtr(model),
1132 Effort: stringPtr(effort),
1133 ChangeID: change.ID,
1134 TookOver: tookOver,
1135 Unready: unready,
1136 ChangeRepo: change.Repo,
1137 Delivery: delivery,
1138 Knot: knotRec,
1139 HeadSHA: gitHead(ctx, worktree),
1140 SharedGit: sharedGit,
1141 HouseRules: rules.Record(),
1142 }
1143 state.DispatchReason = dispatchReason(reasonFlag, isPRFix, budgetPaused, changeRef != "", resumeFrom)
1144 state.RepoKey = launchRepoKey(ctx, state, repoRoot)
1145 if resumeFrom != "" {
1146 state.OriginalRunID = &resumeFrom
1147 } else if replayedFromRunID != "" {
1148 state.OriginalRunID = &replayedFromRunID
1149 }
1150 if isPRFix {
1151 state.Type = "pr-fix"
1152 if prURL != "" {
1153 state.PRURL = &prURL
1154 }
1155 }
1156
1157 if err := store.Save(state); err != nil {
1158 // A worker no recorded run names escapes every check for one
1159 // (a live holder, a dispatcher's pending launch): stop it. One
1160 // that can't be stopped keeps its worktree.
1161 if kerr := tmuxClient.KillPane(context.Background(), paneID); kerr != nil {
1162 keepWorktree = true
1163 return fmt.Errorf("saving state: %w; and its worker in pane %s couldn't be stopped: %v", err, paneID, kerr)
1164 }
1165 return fmt.Errorf("saving state: %w; its worker was stopped", err)
1166 }
1167
1168 // Emit agent:started event
1169 if hds, ok := store.(*run.HomeDirStore); ok {
1170 startedData := map[string]interface{}{
1171 "id": id,
1172 "prompt": prompt,
1173 "model": runBackendModel(state),
1174 }
1175 if issue != "" {
1176 startedData["issue"] = issue
1177 }
1178 if normalizedTarget != nil {
1179 startedData["target_repo"] = *normalizedTarget
1180 }
1181 emitRunEvent(hds.BaseDir(), state, event.AgentStarted, startedData)
1182
1183 // If this is a launch against a budget-paused PR, emit
1184 // agent:resumed so the coordinator (and dashboard) know the
1185 // pause is being acted on.
1186 if budgetPaused && prNumber != "" {
1187 emitRunEvent(hds.BaseDir(), state, event.AgentResumed, map[string]interface{}{
1188 "id": id,
1189 "pr_number": prNumber,
1190 "pr_url": prURL,
1191 })
1192 }
1193
1194 // Setup ends, and the agent's work begins, as its pane starts.
1195 emitRunEvent(hds.BaseDir(), state, event.PhaseCompleted, phaseData(event.PhaseSetup, setupStart, agentStart))
1196 emitRunEvent(hds.BaseDir(), state, event.PhaseStarted, map[string]interface{}{
1197 "phase": event.PhaseAgent,
1198 "started_at": createdAt,
1199 })
1200 }
1201
1202 fmt.Printf(" pane: %s\n", paneID)
1203 if useSandbox {
1204 fmt.Printf(" host: %s (sandbox)\n", sandboxHostName)
1205 } else {
1206 fmt.Printf(" host: local\n")
1207 }
1208 if kind == backend.Claude {
1209 fmt.Printf(" budget: $%s\n", budget)
1210 } else {
1211 fmt.Println(" budget: unavailable for this backend")
1212 }
1213 if model != "" {
1214 fmt.Printf(" model: %s\n", model)
1215 }
1216 if effort != "" {
1217 fmt.Printf(" effort: %s\n", effort)
1218 }
1219 fmt.Printf(" backend: %s\n", kind)
1220 fmt.Printf(" log: %s\n", logFile)
1221 fmt.Println()
1222 fmt.Printf("Agent %s is running. Use 'valley flow status' to check progress.\n", id)
1223 launchSucceeded = true
1224 return nil
1225 },
1226}
1227
1228// unreadyChange returns the change a follow-up run continues to draft on the
1229// valley its repo delivers to, so approve refuses the change while the agent
1230// works on it; finalize marks the pushed head ready again. It runs `valley
1231// unready`, bounded by valley.UnreadyTimeout, only for an inherited change in
1232// a repo whose worktree HEAD carries the valley's policy, and only when the
1233// valley on PATH lists unready (valley.DetectUnready). A change that wasn't
1234// ready is noted; a failure is recorded and printed as a warning. Neither
1235// fails the launch. It returns nil when it didn't run valley.
1236func unreadyChange(ctx context.Context, worktree string, change changeChoice) *run.Unready {
1237 if !change.Inherited {
1238 return nil
1239 }
1240 head, err := exec.CommandContext(ctx, "git", "-C", worktree, "rev-parse", "HEAD").Output()
1241 if err != nil || !valley.DetectUnready(ctx, worktree, strings.TrimSpace(string(head))) {
1242 return nil
1243 }
1244 rec := &run.Unready{ChangeID: change.ID}
1245 switch r, err := valley.Unready(ctx, worktree, change.ID); {
1246 case err != nil:
1247 rec.Error = err.Error()
1248 fmt.Fprintf(os.Stderr, "warning: could not return the change to draft: %s\n", rec.Error)
1249 case r.Draft:
1250 rec.Repo, rec.Handle = r.Repo, r.Handle
1251 fmt.Printf(" valley: %s %s is a draft until the agent pushes\n", r.Repo, r.Handle)
1252 default:
1253 rec.Note = r.Note
1254 fmt.Printf(" valley: the change wasn't ready: %s\n", r.Note)
1255 }
1256 return rec
1257}
1258
1259// checkNoLiveHolder returns an error naming the run when a live run, in any
1260// session, holds the branch a --pr or --change launch is about to work on,
1261// or the change it continues, in the target repo. A --pr launch's change is
1262// that of the run that opened the PR (prChangeSource). Runs it can't read
1263// are an error too: it can't say none of them holds the branch.
1264func checkNoLiveHolder(ctx context.Context, tc tmux.Client, branch, prURL string, target *string, onChange *changeTarget) error {
1265 states, err := run.ListAllSessions()
1266 if err != nil {
1267 return fmt.Errorf("reading the recorded runs, to find one still working on branch %s: %w", branch, err)
1268 }
1269 repos := []string{targetName(target)}
1270 var changeID string
1271 if onChange != nil {
1272 changeID = onChange.ID
1273 repos = append(repos, onChange.Repo)
1274 } else if s := prChangeSource(states, prURL, branch, target); s != nil {
1275 changeID = s.ChangeID
1276 repos = append(repos, integration.RepoName(s))
1277 }
1278 td := run.TmuxDepsFor(ctx, tc)
1279 s := liveHolder(states, func(s *run.State) bool { return s.IsAgentRunningWith(td) }, branch, changeID, repos...)
1280 what := "change " + changeID
1281 switch {
1282 case s == nil:
1283 return nil
1284 case onChange != nil && s.ChangeID == onChange.ID:
1285 what = "change " + onChange.Name
1286 case s.Branch == branch:
1287 what = "branch " + branch
1288 }
1289 return fmt.Errorf("run %s is still working on %s; wait for it to finish, or stop it and clean it up (valley flow cleanup --force %s, which discards its uncommitted work) and launch again; --force-takeover launches past it, but never removes a worktree that has the branch checked out", s.ID, what, s.ID)
1290}
1291
1292// snapshotSharedGit records the files worktree's clone shares across its
1293// worktrees, for finalize to compare; nil when git can't find the clone.
1294func snapshotSharedGit(ctx context.Context, worktree string) *run.SharedGit {
1295 dir, err := git.SharedGitDir(ctx, worktree)
1296 if err != nil {
1297 fmt.Fprintf(os.Stderr, "warning: can't snapshot the clone's shared git files: %v\n", err)
1298 return nil
1299 }
1300 return &run.SharedGit{Dir: dir, Files: git.SharedSnapshot(ctx, dir)}
1301}
1302
1303// checkWorkerPath fails when a command kind's local worker, which runs in
1304// worktree, runs by name isn't on the PATH it gets. That is launch's own:
1305// tmux gives a pane the PATH of the client that creates it, here klaus
1306// launch, before the pane's shell starts.
1307func checkWorkerPath(kind backend.Kind, worktree string) error {
1308 if err := kind.CheckPath(os.Getenv("PATH"), worktree); err != nil {
1309 return fmt.Errorf("%w; a worker gets the PATH valley flow launch runs with, so launch it with one that has the command", err)
1310 }
1311 return nil
1312}
1313
1314// resolveResumeID preserves resumable conversations even after an error.
1315func resolveResumeID(prior *run.State, kind backend.Kind, worktree string) string {
1316 if prior == nil {
1317 return ""
1318 }
1319 var resumeID string
1320 switch kind {
1321 case backend.Claude:
1322 if prior.LogFile == nil || (prior.Backend != "" && prior.Backend != string(kind)) {
1323 return ""
1324 }
1325 resumeID = ExtractClaudeSessionID(*prior.LogFile)
1326 if resumeID != "" && !stageResumeTranscript(prior, resumeID, worktree) {
1327 fmt.Fprintf(os.Stderr, "warning: could not stage prior Claude conversation %s for resume, starting fresh\n", resumeID)
1328 return ""
1329 }
1330 case backend.Codex:
1331 if prior.Backend != string(kind) || prior.Host != nil || prior.BackendSessionID == nil {
1332 return ""
1333 }
1334 resumeID = *prior.BackendSessionID
1335 }
1336 if resumeID != "" && prior.FailureReason != nil {
1337 fmt.Fprintf(os.Stderr, "warning: prior run %s ended with %s; resuming its conversation\n", prior.ID, *prior.FailureReason)
1338 }
1339 return resumeID
1340}
1341
1342// resolvePrompt requires exactly one prompt source and preserves file contents.
1343func resolvePrompt(args []string, promptFile string) (string, error) {
1344 switch {
1345 case len(args) > 0 && promptFile != "":
1346 return "", fmt.Errorf("prompt given twice: pass it as an argument or with --prompt-file, not both")
1347 case promptFile != "":
1348 data, err := os.ReadFile(promptFile)
1349 if err != nil {
1350 return "", fmt.Errorf("reading prompt file: %w", err)
1351 }
1352 if strings.TrimSpace(string(data)) == "" {
1353 return "", fmt.Errorf("prompt file %s is empty", promptFile)
1354 }
1355 return string(data), nil
1356 case len(args) > 0:
1357 return args[0], nil
1358 default:
1359 return "", fmt.Errorf("no prompt: pass it as an argument or with --prompt-file <path>")
1360 }
1361}
1362
1363// maxPaneCommandBytes caps the command handed to tmux new-window/split-window.
1364// tmux rejects a request over its 16KB imsg limit (MAX_IMSGSIZE) with "command
1365// too long", and the pane's other arguments share that budget.
1366const maxPaneCommandBytes = 12000
1367
1368// agentPaneCommand builds a worker's pane command; sandboxHost "" runs locally.
1369// The backend reads inputFile, which holds kind.Stdin(o.SystemPrompt,
1370// o.Prompt), on stdin, so the prompt's length never counts against tmux's
1371// limit. A local worker runs under workerEnv(dirs), out of reach of the
1372// pane's tmux server; a sandbox worker runs on another host, which has no way
1373// to it, and gets neither directory.
1374func agentPaneCommand(kind backend.Kind, o backend.Options, inputFile, sandboxHost, worktree, logFile, finalizePrefix, id string, dirs workerDirs) (string, error) {
1375 if sandboxHost != "" {
1376 // The remote side cannot read local files; only stdin crosses ssh.
1377 o.SystemPromptFile = ""
1378 }
1379 args := kind.Worker(o)
1380 // Propagate worker identity to nested klaus commands such as _pre-review.
1381 agentCmd := "KLAUS_BACKEND=" + string(kind) + " " + backend.ShellCommand(args)
1382 const selfBin = "klaus" // assumes klaus is in PATH
1383 var paneCmd string
1384 if sandboxHost != "" {
1385 paneCmd = buildSandboxPaneCommand(sandboxHost, worktree, agentCmd, inputFile, logFile, selfBin, finalizePrefix, id)
1386 } else {
1387 if dirs.tmux == "" {
1388 // An empty TMUX_TMPDIR is tmux's default, likely the shared server's.
1389 return "", fmt.Errorf("no private tmux directory for the %s worker", kind)
1390 }
1391 if dirs.scratch == "" {
1392 // An empty KLAUS_SCRATCH puts "$KLAUS_SCRATCH/<name>" at the root.
1393 return "", fmt.Errorf("no scratch directory for the %s worker", kind)
1394 }
1395 paneCmd = buildPaneCommand(worktree, workerEnv(dirs)+agentCmd, inputFile, logFile, selfBin, finalizePrefix, id)
1396 }
1397 if len(paneCmd) <= maxPaneCommandBytes {
1398 return paneCmd, nil
1399 }
1400 msg := fmt.Sprintf("agent pane command is %d bytes, over the %d-byte limit for a tmux command", len(paneCmd), maxPaneCommandBytes)
1401 // Codex, and Claude without its file flag, take the system prompt in
1402 // argv; agy reads it on stdin with the prompt.
1403 if kind == backend.Codex || kind == backend.Claude && o.SystemPromptFile == "" {
1404 where, fix := string(kind), "shorten .klaus/prompt.md (.klaus/pr-fix-prompt.md for --pr)"
1405 if kind == backend.Claude {
1406 where, fix = "sandbox", fix+", or use --local, where claude reads it from a file"
1407 }
1408 return "", fmt.Errorf("%s: the worker system prompt is %d bytes and goes inline for %s runs; %s", msg, len(o.SystemPrompt), where, fix)
1409 }
1410 return "", fmt.Errorf("%s", msg)
1411}
1412
1413func withExitEvent(command string) string {
1414 return "( " + command + "; klaus_backend_exit=$?; printf '\\n{\"type\":\"klaus_exit\",\"exit_code\":%s}\\n' \"$klaus_backend_exit\" )"
1415}
1416
1417// stdinFrom redirects promptFile into the command it follows; "" leaves stdin alone.
1418func stdinFrom(promptFile string) string {
1419 if promptFile == "" {
1420 return ""
1421 }
1422 return " < " + shellQuote(promptFile)
1423}
1424
1425func buildPaneCommand(worktree, agentCmd, promptFile, logFile, selfBin, finalizePrefix, id string) string {
1426 return fmt.Sprintf(
1427 "%s%scd %s && %s | tee %s | %s _format-stream; %s%s _finalize %s",
1428 tmuxSessionEnvPrefix(),
1429 runEnvPrefix(id),
1430 shellQuote(worktree),
1431 withExitEvent(agentCmd+stdinFrom(promptFile)),
1432 shellQuote(logFile),
1433 selfBin,
1434 finalizePrefix,
1435 selfBin,
1436 shellQuote(id),
1437 )
1438}
1439
1440func shellQuote(s string) string {
1441 // Use single quotes, escaping any existing single quotes
1442 return "'" + strings.ReplaceAll(s, "'", "'\\''") + "'"
1443}
1444
1445// FormatPaneTitle builds a compact pane title for an agent.
1446// Format with issue: "#<issue> <short-desc>"
1447// Format with a knot: "<knot> <short-desc>"
1448// Format without issue: "<short-id> <short-desc>"
1449// Short desc is up to 40 characters of the prompt, trimmed to a word boundary.
1450func FormatPaneTitle(id, issue, prompt string) string {
1451 const (
1452 shortIDLength = 4
1453 maxDescLength = 40
1454 )
1455
1456 var title string
1457 if _, ok := valley.ParseKnotRef(issue); ok {
1458 title = issue
1459 } else if issue != "" {
1460 title = "#" + issue
1461 } else {
1462 title = id
1463 if len(id) > shortIDLength {
1464 title = id[len(id)-shortIDLength:]
1465 }
1466 }
1467
1468 desc := strings.TrimSpace(prompt)
1469 if len(desc) > maxDescLength {
1470 desc = desc[:maxDescLength]
1471 // Trim to last word boundary
1472 if i := strings.LastIndex(desc, " "); i > 0 {
1473 desc = desc[:i]
1474 }
1475 }
1476 if desc != "" {
1477 title += " " + desc
1478 }
1479
1480 return title
1481}
1482
1483func stringPtr(s string) *string {
1484 if s == "" {
1485 return nil
1486 }
1487 return &s
1488}
1489
1490// normalizeTargetRepo resolves the target repo to a canonical short name.
1491// If targetRepo is set, normalizes it against registered projects.
1492// If targetRepo is nil but hostRoot is a git repo matching a registered project,
1493// uses the project name instead of leaving it nil (which shows as "(local)").
1494func normalizeTargetRepo(targetRepo *string, hostRoot string) *string {
1495 reg, _ := project.Load()
1496
1497 if targetRepo != nil && *targetRepo != "" {
1498 n := project.NormalizeRepoName(*targetRepo, reg)
1499 return &n
1500 }
1501
1502 // No explicit target — try to detect from the host repo's git remote
1503 if hostRoot != "" && reg != nil {
1504 remote := gitRemoteURL(hostRoot)
1505 if remote != "" {
1506 n := project.NormalizeRepoName(remote, reg)
1507 return &n
1508 }
1509 }
1510
1511 return targetRepo
1512}
1513
1514// resolveRepoTarget determines which repo to use for the agent worktree.
1515// Priority: explicit --repo flag > session target > (caller falls back to hostRoot).
1516// If the resolved ref matches a registered project name (no "/" in the ref),
1517// projectLocalPath is set to the project's local directory.
1518func resolveRepoTarget(repoFlag, sessionTarget string, reg *project.Registry) (repoRef, projectLocalPath string) {
1519 repoRef = repoFlag
1520
1521 // If no --repo flag, use the session target. This takes priority over the
1522 // current git repo (hostRoot) because the coordinator session may be
1523 // running inside one repo while targeting another.
1524 if repoRef == "" && sessionTarget != "" {
1525 repoRef = sessionTarget
1526 }
1527
1528 // Resolve against project registry: bare names (no "/") may map to a
1529 // local clone, avoiding a fresh GitHub clone.
1530 if repoRef != "" && !strings.Contains(repoRef, "/") && reg != nil {
1531 if localPath, ok := reg.Get(repoRef); ok {
1532 projectLocalPath = localPath
1533 }
1534 }
1535
1536 return repoRef, projectLocalPath
1537}
1538
1539// formatCommand returns the formatter klaus's pre-commit hook runs in
1540// worktree: cfg's format, else nix fmt when the worktree's flake has a
1541// formatter for the current system, else none. Launch decides it once, so
1542// commits don't evaluate the flake.
1543func formatCommand(ctx context.Context, cfg config.Config, worktree string) []string {
1544 if len(cfg.Format) > 0 {
1545 return cfg.Format
1546 }
1547 if nix.HasFormatter(ctx, worktree) {
1548 return []string{"nix", "fmt"}
1549 }
1550 return nil
1551}
1552
1553// isDirectPushRepo reports whether agents deliver to repoRoot by pushing their
1554// branch for the operator to integrate, rather than opening a PR: true unless
1555// its origin is a github.com URL. Sandbox runs sync a worktree made from
1556// repoRoot, so they are decided the same way.
1557func isDirectPushRepo(repoRoot string) bool {
1558 return !git.IsGitHubRemote(gitRemoteURL(repoRoot))
1559}
1560
1561// runDelivery decides how a run on repoRoot delivers its work: a run that
1562// continues a PR (--pr) delivers to that PR, and any other run pushes its
1563// branch when repoRoot is a direct-push repo, or else opens a PR. Launch
1564// records it on the run; finalize decides state that predates the record
1565// the same way.
1566func runDelivery(isPRFix bool, repoRoot string) string {
1567 if !isPRFix && isDirectPushRepo(repoRoot) {
1568 return run.DeliveryPush
1569 }
1570 return run.DeliveryPR
1571}
1572
1573// resolveGHRepo returns an owner/repo string suitable for --repo flags on gh CLI calls.
1574// If repoRef already contains '/' (owner/repo format), it is returned directly.
1575// Otherwise, it extracts owner/repo from the git remote of repoRoot.
1576func resolveGHRepo(repoRef, repoRoot string) string {
1577 if strings.Contains(repoRef, "/") {
1578 return repoRef
1579 }
1580 if repoRoot != "" {
1581 remote := gitRemoteURL(repoRoot)
1582 if remote != "" {
1583 // Parse owner/repo from remote URL (e.g. git@github.com:owner/repo.git or https://...)
1584 owner, repo, _, err := git.ParseRepoRef(remote)
1585 if err == nil {
1586 return owner + "/" + repo
1587 }
1588 }
1589 }
1590 return ""
1591}
1592
1593// CheckSandboxReachable tests whether a sandbox host is reachable via SSH.
1594func CheckSandboxReachable(host string) bool {
1595 cmd := exec.Command("ssh", "-o", "ConnectTimeout=3", "-o", "BatchMode=yes", host, "true")
1596 return cmd.Run() == nil
1597}
1598
1599// syncWorktreeToSandbox syncs a local worktree to a sandbox host via rsync.
1600func syncWorktreeToSandbox(host, worktree string) error {
1601 // Create remote directory
1602 mkdirCmd := exec.Command("ssh", host, fmt.Sprintf("mkdir -p %s", shellQuote(worktree)))
1603 if out, err := mkdirCmd.CombinedOutput(); err != nil {
1604 return fmt.Errorf("creating remote dir: %w: %s", err, string(out))
1605 }
1606
1607 // Sync worktree contents
1608 rsyncCmd := exec.Command("rsync", "-az", "--delete", worktree+"/", fmt.Sprintf("%s:%s/", host, worktree))
1609 if out, err := rsyncCmd.CombinedOutput(); err != nil {
1610 return fmt.Errorf("rsync to sandbox: %w: %s", err, string(out))
1611 }
1612
1613 return nil
1614}
1615
1616func buildSandboxPaneCommand(host, worktree, agentCmd, promptFile, logFile, selfBin, finalizePrefix, id string) string {
1617 // Run the agent on sandbox via SSH, pipe output locally through tee + formatter,
1618 // then finalize locally and rsync results back. ssh forwards the local
1619 // prompt file as the remote command's stdin. The remote command gets the
1620 // run's ID too: the sandbox has no event log for the run, so _pre-review
1621 // there reports its check in its output, which the stream brings back to
1622 // _format-stream --sandbox.
1623 rsyncBack := fmt.Sprintf("rsync -az %s:%s/ %s/",
1624 shellQuote(host), shellQuote(worktree), shellQuote(worktree))
1625 remoteCmd := remoteRunEnvPrefix(id) + "cd " + shellQuote(worktree) + " && " + agentCmd
1626 return fmt.Sprintf(
1627 "%s%s%s | tee %s | %s _format-stream --sandbox; %s%s _finalize %s; %s",
1628 tmuxSessionEnvPrefix(),
1629 runEnvPrefix(id),
1630 withExitEvent("ssh "+shellQuote(host)+" "+shellQuote(remoteCmd)+stdinFrom(promptFile)),
1631 shellQuote(logFile),
1632 selfBin,
1633 finalizePrefix,
1634 selfBin,
1635 shellQuote(id),
1636 rsyncBack,
1637 )
1638}
1639
1640// pinDashboardToBottom ensures the dashboard pane is the last (bottom-most)
1641// pane in the window. This is called after RebalanceLayout which may have
1642// moved the dashboard out of position.
1643func pinDashboardToBottom(ctx context.Context, currentPane string, store run.StateStore, tc tmux.Client) {
1644 // Load the session state directly via KLAUS_SESSION_ID
1645 sessionID := os.Getenv("KLAUS_SESSION_ID")
1646 if sessionID == "" {
1647 return
1648 }
1649 s, err := store.Load(sessionID)
1650 if err != nil || s.Type != "session" || s.DashboardPane == nil {
1651 return
1652 }
1653 dashPane := *s.DashboardPane
1654
1655 panes, err := tc.ListWindowPanes(ctx, currentPane)
1656 if err != nil || len(panes) < 2 {
1657 return
1658 }
1659
1660 lastPane := panes[len(panes)-1]
1661 if lastPane == dashPane {
1662 return // already at the bottom
1663 }
1664
1665 // Ensure the dashboard is actually in this window before swapping
1666 var found bool
1667 for _, p := range panes {
1668 if p == dashPane {
1669 found = true
1670 break
1671 }
1672 }
1673 if !found {
1674 return
1675 }
1676
1677 if err := tc.SwapPane(ctx, dashPane, lastPane); err != nil {
1678 fmt.Fprintf(os.Stderr, "warning: could not pin dashboard to bottom: %v\n", err)
1679 }
1680
1681 // Pin the coordinator pane to the top. After even-vertical rebalancing,
1682 // agents may end up above the coordinator.
1683 if s.TmuxPane != nil {
1684 panes, err = tc.ListWindowPanes(ctx, currentPane)
1685 if err == nil && len(panes) > 1 && panes[0] != *s.TmuxPane {
1686 for _, p := range panes {
1687 if p == *s.TmuxPane {
1688 _ = tc.SwapPane(ctx, p, panes[0])
1689 break
1690 }
1691 }
1692 }
1693 }
1694}
1695
1696func init() {
1697 launchCmd.Flags().String("backend", "", "Worker backend: claude, codex, or agy (default from session/config)")
1698 launchCmd.Flags().String("prompt-file", "", "Read the prompt from a file instead of the positional argument: verbatim (no shell mangling of backticks) and any length; mutually exclusive with it")
1699 launchCmd.Flags().String("issue", "", "GitHub issue number to reference; on a valley project, a knot to work: oc-, bd-, ida- or qn- and 7 hex digits, or <project>:<id> (claimed for the run, linked to its change, closed once it lands)")
1700 launchCmd.Flags().String("pr", "", "Push fixes to an existing PR's branch instead of creating a new PR (also the way to resume a budget-paused PR — the agent picks up from the WIP commit)")
1701 launchCmd.Flags().String("budget", "", "Claude only: max spend in USD (default from config)")
1702 launchCmd.Flags().String("repo", "", "Target repo: registered project name, owner/repo, or full URL")
1703 launchCmd.Flags().Bool("local", false, "Force local execution even when sandbox is configured")
1704 launchCmd.Flags().String("host", "", "Override sandbox host (ignores config sandbox_host)")
1705 launchCmd.Flags().String("resume-from", "", "Resume from a previous agent's session (run ID); without --pr, --change or --branch, continue the branch it pushed without a PR when nothing took its change further")
1706 launchCmd.Flags().String("change", "", "Continue an existing change in a repo without PRs, named by run ID, change ID or valley handle: work on its branch and keep its change ID, on any backend; Claude replays the latest run's stored conversation, Codex forks its own session on the same machine, agy starts fresh; not with --pr or --branch")
1707 launchCmd.Flags().Bool("force-takeover", false, "With --pr, --change or a --resume-from that continues its run's branch, launch even while another run is still working on the branch or change, and discard commits on the local branch that origin lacks; never removes a worktree that has the branch checked out (valley flow cleanup that run first)")
1708 launchCmd.Flags().String("branch", "", "Name of the new run's branch (default: <slug>-<run-id tail>, the slug taken from the --issue title or the prompt's first '# ' heading or line); not with --pr or --change")
1709 launchCmd.Flags().Bool("replay", false, "Force trajectory replay for --pr or --change (continue the prior conversation, bypassing the size threshold, and for --pr the budget-paused check)")
1710 launchCmd.Flags().Bool("no-replay", false, "Disable trajectory replay for --pr or --change; dispatch a fresh agent instead")
1711 launchCmd.Flags().Int("replay-threshold-kb", 0, "Max stored trajectory size (KB) eligible for replay; 0 uses config replay_threshold_kb (default 300)")
1712 launchCmd.Flags().String("model", "", "Model for the selected backend (default from backends.<backend>.model; legacy default_agent_model for Claude)")
1713 launchCmd.Flags().String("effort", "", "Reasoning effort for the selected backend (default from backends.<backend>.effort; valid levels depend on backend)")
1714 launchCmd.Flags().String("reason", "", "Why this run is dispatched, recorded on the run and its events, e.g. docs-timer (default: launch, pr-follow-up, change-follow-up, budget-resume or resume, from the other flags)")
1715 launchCmd.Flags().String("run-id", "", "Name the run (YYYYMMDD-HHMM- and 8 hex digits) instead of minting an ID, for a dispatcher that records it first; refused if a run has it. Failing before the worker starts then exits with status 3")
1716 launchCmd.Flags().String("expect-owner", "", "With --change <change-id>: launch only if the valley lists the change with this record owner")
1717 launchCmd.Flags().String("expect-branch", "", "With --change <change-id>: launch only if the change's active version, and the launch, are on this branch")
1718 launchCmd.Flags().String("expect-head", "", "With --change <change-id>: launch only if the change's active version, origin's branch and the new worktree are at this commit (full SHA)")
1719 launchCmd.Flags().Bool("expect-draft", false, "With --change <change-id>: launch only if the valley lists the change as a draft, before the worktree and again as the worker starts")
1720 rootCmd.AddCommand(launchCmd)
1721}