gunk-dev/the-valley

launch.go

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