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