gunk-dev/the-valley

launch.go

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