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