| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "os/exec" |
| 6 | "path/filepath" |
| 7 | "regexp" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | |
| 11 | "the-valley/flow/internal/backend" |
| 12 | "the-valley/flow/internal/config" |
| 13 | "the-valley/flow/internal/project" |
| 14 | "the-valley/flow/internal/run" |
| 15 | "github.com/spf13/pflag" |
| 16 | ) |
| 17 | |
| 18 | func TestFormatPaneTitle(t *testing.T) { |
| 19 | tests := []struct { |
| 20 | name string |
| 21 | id string |
| 22 | issue string |
| 23 | prompt string |
| 24 | want string |
| 25 | }{ |
| 26 | { |
| 27 | name: "with issue uses #issue prefix", |
| 28 | id: "20260306-1720-176a", |
| 29 | issue: "23", |
| 30 | prompt: "fix the failing tests in pkg/auth", |
| 31 | want: "#23 fix the failing tests in pkg/auth", |
| 32 | }, |
| 33 | { |
| 34 | name: "a knot is named as given, without #", |
| 35 | id: "20260306-1720-176a", |
| 36 | issue: "the-valley:oc-897917f", |
| 37 | prompt: "work the knot", |
| 38 | want: "the-valley:oc-897917f work the knot", |
| 39 | }, |
| 40 | { |
| 41 | name: "no issue uses short id prefix", |
| 42 | id: "20260306-1720-176a", |
| 43 | issue: "", |
| 44 | prompt: "refactor the config loader", |
| 45 | want: "176a refactor the config loader", |
| 46 | }, |
| 47 | { |
| 48 | name: "short prompt preserved fully", |
| 49 | id: "20260306-1720-176a", |
| 50 | issue: "5", |
| 51 | prompt: "fix typo", |
| 52 | want: "#5 fix typo", |
| 53 | }, |
| 54 | { |
| 55 | name: "short id kept as-is", |
| 56 | id: "abcd", |
| 57 | issue: "", |
| 58 | prompt: "test", |
| 59 | want: "abcd test", |
| 60 | }, |
| 61 | { |
| 62 | name: "very short id kept as-is", |
| 63 | id: "ab", |
| 64 | issue: "", |
| 65 | prompt: "test", |
| 66 | want: "ab test", |
| 67 | }, |
| 68 | { |
| 69 | name: "empty prompt with issue", |
| 70 | id: "20260306-1720-176a", |
| 71 | issue: "10", |
| 72 | prompt: "", |
| 73 | want: "#10", |
| 74 | }, |
| 75 | { |
| 76 | name: "whitespace prompt", |
| 77 | id: "20260306-1720-176a", |
| 78 | issue: "", |
| 79 | prompt: " ", |
| 80 | want: "176a", |
| 81 | }, |
| 82 | { |
| 83 | name: "long prompt truncated at word boundary", |
| 84 | id: "20260306-1720-176a", |
| 85 | issue: "34", |
| 86 | prompt: "Implement a klaus merge command for combining worktrees", |
| 87 | want: "#34 Implement a klaus merge command for", |
| 88 | }, |
| 89 | { |
| 90 | name: "exactly 40 char prompt not truncated", |
| 91 | id: "20260306-1720-176a", |
| 92 | issue: "", |
| 93 | prompt: "1234567890123456789012345678901234567890", |
| 94 | want: "176a 1234567890123456789012345678901234567890", |
| 95 | }, |
| 96 | { |
| 97 | name: "41 char prompt truncated at word boundary", |
| 98 | id: "20260306-1720-176a", |
| 99 | issue: "", |
| 100 | prompt: "fix the authentication flow in the server", |
| 101 | want: "176a fix the authentication flow in the", |
| 102 | }, |
| 103 | { |
| 104 | name: "issue present ignores id", |
| 105 | id: "20260306-1720-176a", |
| 106 | issue: "99", |
| 107 | prompt: "update README", |
| 108 | want: "#99 update README", |
| 109 | }, |
| 110 | } |
| 111 | |
| 112 | for _, tt := range tests { |
| 113 | t.Run(tt.name, func(t *testing.T) { |
| 114 | got := FormatPaneTitle(tt.id, tt.issue, tt.prompt) |
| 115 | if got != tt.want { |
| 116 | t.Errorf("FormatPaneTitle(%q, %q, %q) = %q, want %q", |
| 117 | tt.id, tt.issue, tt.prompt, got, tt.want) |
| 118 | } |
| 119 | }) |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | func TestLaunchResolvesProjectName(t *testing.T) { |
| 124 | // Test that a bare name (no /) is resolved from the project registry. |
| 125 | // We test the resolution logic directly since the full launch flow needs tmux. |
| 126 | tmpDir := t.TempDir() |
| 127 | regPath := filepath.Join(tmpDir, "projects.json") |
| 128 | |
| 129 | reg := &project.Registry{ |
| 130 | Projects: map[string]string{ |
| 131 | "my-project": "/home/user/src/my-project", |
| 132 | }, |
| 133 | } |
| 134 | if err := reg.SaveTo(regPath); err != nil { |
| 135 | t.Fatalf("SaveTo: %v", err) |
| 136 | } |
| 137 | |
| 138 | loaded, err := project.LoadFrom(regPath) |
| 139 | if err != nil { |
| 140 | t.Fatalf("LoadFrom: %v", err) |
| 141 | } |
| 142 | |
| 143 | // Simulate the launch resolution: if repoRef has no "/" and matches a project, use it |
| 144 | repoRef := "my-project" |
| 145 | var projectLocalPath string |
| 146 | if !strings.Contains(repoRef, "/") { |
| 147 | if localPath, ok := loaded.Get(repoRef); ok { |
| 148 | projectLocalPath = localPath |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | if projectLocalPath != "/home/user/src/my-project" { |
| 153 | t.Errorf("expected project path /home/user/src/my-project, got %q", projectLocalPath) |
| 154 | } |
| 155 | |
| 156 | // An owner/repo format should NOT be resolved as a project name |
| 157 | repoRef = "owner/repo" |
| 158 | projectLocalPath = "" |
| 159 | if !strings.Contains(repoRef, "/") { |
| 160 | if localPath, ok := loaded.Get(repoRef); ok { |
| 161 | projectLocalPath = localPath |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | if projectLocalPath != "" { |
| 166 | t.Errorf("owner/repo should not resolve as project name, got %q", projectLocalPath) |
| 167 | } |
| 168 | |
| 169 | // An unregistered project name should not resolve |
| 170 | repoRef = "unknown-project" |
| 171 | projectLocalPath = "" |
| 172 | if !strings.Contains(repoRef, "/") { |
| 173 | if localPath, ok := loaded.Get(repoRef); ok { |
| 174 | projectLocalPath = localPath |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | if projectLocalPath != "" { |
| 179 | t.Errorf("unregistered project should not resolve, got %q", projectLocalPath) |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | func TestLaunchErrorMessageMentionsProjectAdd(t *testing.T) { |
| 184 | // Verify the error message hints at 'klaus project add' |
| 185 | errMsg := "no target repo — use --repo owner/repo, 'klaus target owner/repo', or 'klaus project add' to register a project" |
| 186 | if !strings.Contains(errMsg, "klaus project add") { |
| 187 | t.Error("error message should mention 'klaus project add'") |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | func TestBuildPaneCommand(t *testing.T) { |
| 192 | worktree := "/tmp/worktrees/repo/abc123" |
| 193 | claudeCmd := "claude -p 'do stuff'" |
| 194 | logFile := "/tmp/logs/abc123.jsonl" |
| 195 | promptFile := "/tmp/prompts/20260306-1720-176a.md" |
| 196 | selfBin := "klaus" |
| 197 | id := "20260306-1720-176a" |
| 198 | |
| 199 | t.Run("builds correct pipeline without auto-watch", func(t *testing.T) { |
| 200 | cmd := buildPaneCommand(worktree, claudeCmd, promptFile, logFile, selfBin, "", id) |
| 201 | if !strings.Contains(cmd, "_finalize") { |
| 202 | t.Error("expected _finalize in pipeline, got:", cmd) |
| 203 | } |
| 204 | if strings.Contains(cmd, "_auto-watch") { |
| 205 | t.Error("expected no _auto-watch in pipeline, got:", cmd) |
| 206 | } |
| 207 | }) |
| 208 | |
| 209 | t.Run("redirects the prompt file into the backend command only", func(t *testing.T) { |
| 210 | cmd := buildPaneCommand(worktree, claudeCmd, promptFile, logFile, selfBin, "", id) |
| 211 | if !strings.Contains(cmd, "( "+claudeCmd+" < '"+promptFile+"'; klaus_backend_exit=$?") { |
| 212 | t.Error("expected stdin redirect on the backend command, got:", cmd) |
| 213 | } |
| 214 | if strings.Count(cmd, "<") != 1 { |
| 215 | t.Error("expected exactly one redirect, got:", cmd) |
| 216 | } |
| 217 | }) |
| 218 | |
| 219 | t.Run("cross-repo includes finalize prefix", func(t *testing.T) { |
| 220 | prefix := "cd '/host/repo' && " |
| 221 | cmd := buildPaneCommand(worktree, claudeCmd, promptFile, logFile, selfBin, prefix, id) |
| 222 | if !strings.Contains(cmd, "cd '/host/repo' && klaus _finalize") { |
| 223 | t.Error("expected finalize prefix before _finalize, got:", cmd) |
| 224 | } |
| 225 | }) |
| 226 | |
| 227 | t.Run("exports KLAUS_SESSION_ID via tmuxSessionEnvPrefix", func(t *testing.T) { |
| 228 | t.Setenv(sessionIDEnv, "session-20260306-1720-abc1") |
| 229 | cmd := buildPaneCommand(worktree, claudeCmd, promptFile, logFile, selfBin, "", id) |
| 230 | if !strings.Contains(cmd, "export KLAUS_SESSION_ID='session-20260306-1720-abc1'") { |
| 231 | t.Error("expected KLAUS_SESSION_ID export in pane command, got:", cmd) |
| 232 | } |
| 233 | }) |
| 234 | |
| 235 | t.Run("no KLAUS_SESSION_ID export when env unset", func(t *testing.T) { |
| 236 | t.Setenv(sessionIDEnv, "") |
| 237 | cmd := buildPaneCommand(worktree, claudeCmd, promptFile, logFile, selfBin, "", id) |
| 238 | if strings.Contains(cmd, "KLAUS_SESSION_ID") { |
| 239 | t.Error("expected no KLAUS_SESSION_ID export when session ID is empty, got:", cmd) |
| 240 | } |
| 241 | }) |
| 242 | } |
| 243 | |
| 244 | func TestPRFixPromptInstructsPushOnly(t *testing.T) { |
| 245 | dir := t.TempDir() // no .klaus/pr-fix-prompt.md — uses default |
| 246 | |
| 247 | vars := config.PromptVars{ |
| 248 | RunID: "20260312-1820-abcd", |
| 249 | Issue: "42", |
| 250 | PR: "99", |
| 251 | Branch: "feature/my-branch", |
| 252 | RepoName: "test-repo", |
| 253 | } |
| 254 | |
| 255 | prompt, err := config.RenderPRFixPrompt(dir, vars) |
| 256 | if err != nil { |
| 257 | t.Fatalf("RenderPRFixPrompt() error: %v", err) |
| 258 | } |
| 259 | |
| 260 | // Must instruct push-only, no PR creation |
| 261 | if !strings.Contains(prompt, "Do NOT create a new PR") { |
| 262 | t.Error("pr-fix prompt must instruct agent not to create a new PR") |
| 263 | } |
| 264 | if !strings.Contains(prompt, "git push") { |
| 265 | t.Error("pr-fix prompt must instruct agent to push") |
| 266 | } |
| 267 | if !strings.Contains(prompt, "PR #99") { |
| 268 | t.Error("pr-fix prompt must mention the PR number") |
| 269 | } |
| 270 | if !strings.Contains(prompt, "feature/my-branch") { |
| 271 | t.Error("pr-fix prompt must mention the branch name") |
| 272 | } |
| 273 | if !strings.Contains(prompt, "#42") { |
| 274 | t.Error("pr-fix prompt must mention the issue when provided") |
| 275 | } |
| 276 | if !strings.Contains(prompt, "20260312-1820-abcd") { |
| 277 | t.Error("pr-fix prompt must contain run ID") |
| 278 | } |
| 279 | // Should NOT contain "Create a PR" or "gh pr create" |
| 280 | if strings.Contains(prompt, "gh pr create") { |
| 281 | t.Error("pr-fix prompt must not mention gh pr create") |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | func TestPRFixPromptNoIssue(t *testing.T) { |
| 286 | dir := t.TempDir() |
| 287 | |
| 288 | vars := config.PromptVars{ |
| 289 | RunID: "20260312-1820-abcd", |
| 290 | PR: "99", |
| 291 | Branch: "feature/my-branch", |
| 292 | } |
| 293 | |
| 294 | prompt, err := config.RenderPRFixPrompt(dir, vars) |
| 295 | if err != nil { |
| 296 | t.Fatalf("RenderPRFixPrompt() error: %v", err) |
| 297 | } |
| 298 | |
| 299 | // Without an issue, the issue reference should not appear |
| 300 | if strings.Contains(prompt, "issue #") { |
| 301 | t.Error("pr-fix prompt should not mention issue when none is provided") |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | func TestResolveRepoTarget_SessionTargetUsedWhenNoFlag(t *testing.T) { |
| 306 | reg := &project.Registry{ |
| 307 | Projects: map[string]string{ |
| 308 | "app": "/home/user/hack/app", |
| 309 | }, |
| 310 | } |
| 311 | |
| 312 | repoRef, projectLocalPath := resolveRepoTarget("", "app", reg) |
| 313 | |
| 314 | if repoRef != "app" { |
| 315 | t.Errorf("repoRef = %q, want %q", repoRef, "app") |
| 316 | } |
| 317 | if projectLocalPath != "/home/user/hack/app" { |
| 318 | t.Errorf("projectLocalPath = %q, want %q", projectLocalPath, "/home/user/hack/app") |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | func TestResolveRepoTarget_RepoFlagOverridesSessionTarget(t *testing.T) { |
| 323 | reg := &project.Registry{ |
| 324 | Projects: map[string]string{ |
| 325 | "app": "/home/user/hack/app", |
| 326 | "other-project": "/home/user/hack/other-project", |
| 327 | }, |
| 328 | } |
| 329 | |
| 330 | repoRef, projectLocalPath := resolveRepoTarget("other-project", "app", reg) |
| 331 | |
| 332 | if repoRef != "other-project" { |
| 333 | t.Errorf("repoRef = %q, want %q", repoRef, "other-project") |
| 334 | } |
| 335 | if projectLocalPath != "/home/user/hack/other-project" { |
| 336 | t.Errorf("projectLocalPath = %q, want %q", projectLocalPath, "/home/user/hack/other-project") |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | func TestResolveRepoTarget_SessionTargetWorksEvenWithHostRoot(t *testing.T) { |
| 341 | // This tests the bug fix from issue #103. |
| 342 | // The old code only checked session target when hostRoot was empty. |
| 343 | // With the new resolveRepoTarget() function, session target is always |
| 344 | // used when repoFlag is empty, regardless of whether the caller has a |
| 345 | // hostRoot. The caller (RunE) only falls back to hostRoot after |
| 346 | // resolveRepoTarget returns empty values. |
| 347 | reg := &project.Registry{ |
| 348 | Projects: map[string]string{ |
| 349 | "app": "/home/user/hack/app", |
| 350 | }, |
| 351 | } |
| 352 | |
| 353 | repoRef, projectLocalPath := resolveRepoTarget("", "app", reg) |
| 354 | |
| 355 | if repoRef != "app" { |
| 356 | t.Errorf("repoRef = %q, want %q", repoRef, "app") |
| 357 | } |
| 358 | if projectLocalPath != "/home/user/hack/app" { |
| 359 | t.Errorf("projectLocalPath = %q, want %q", projectLocalPath, "/home/user/hack/app") |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | func TestResolveRepoTarget_OwnerRepoParsedCorrectly(t *testing.T) { |
| 364 | reg := &project.Registry{ |
| 365 | Projects: map[string]string{ |
| 366 | "app": "/home/user/hack/app", |
| 367 | }, |
| 368 | } |
| 369 | |
| 370 | repoRef, projectLocalPath := resolveRepoTarget("", "maintainer/app", reg) |
| 371 | |
| 372 | if repoRef != "maintainer/app" { |
| 373 | t.Errorf("repoRef = %q, want %q", repoRef, "maintainer/app") |
| 374 | } |
| 375 | if projectLocalPath != "" { |
| 376 | t.Errorf("projectLocalPath = %q, want empty (owner/repo should not resolve as project name)", projectLocalPath) |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | func TestResolveRepoTarget_EmptyTargetFallsThrough(t *testing.T) { |
| 381 | reg := &project.Registry{ |
| 382 | Projects: map[string]string{ |
| 383 | "app": "/home/user/hack/app", |
| 384 | }, |
| 385 | } |
| 386 | |
| 387 | repoRef, projectLocalPath := resolveRepoTarget("", "", reg) |
| 388 | |
| 389 | if repoRef != "" { |
| 390 | t.Errorf("repoRef = %q, want empty", repoRef) |
| 391 | } |
| 392 | if projectLocalPath != "" { |
| 393 | t.Errorf("projectLocalPath = %q, want empty", projectLocalPath) |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | func TestResolveRepoTarget_NilRegistry(t *testing.T) { |
| 398 | repoRef, projectLocalPath := resolveRepoTarget("", "app", nil) |
| 399 | |
| 400 | if repoRef != "app" { |
| 401 | t.Errorf("repoRef = %q, want %q", repoRef, "app") |
| 402 | } |
| 403 | if projectLocalPath != "" { |
| 404 | t.Errorf("projectLocalPath = %q, want empty (nil registry should not resolve)", projectLocalPath) |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | func TestBuildSandboxPaneCommand(t *testing.T) { |
| 409 | host := "klaus-worker-0" |
| 410 | worktree := "/tmp/klaus-sessions/repo/abc123" |
| 411 | claudeCmd := "claude -p 'do stuff'" |
| 412 | logFile := "/tmp/logs/abc123.jsonl" |
| 413 | promptFile := "/tmp/prompts/20260328-1915-e4b3.md" |
| 414 | selfBin := "klaus" |
| 415 | id := "20260328-1915-e4b3" |
| 416 | |
| 417 | t.Run("wraps claude in SSH", func(t *testing.T) { |
| 418 | t.Setenv(sessionIDEnv, "") |
| 419 | cmd := buildSandboxPaneCommand(host, worktree, claudeCmd, promptFile, logFile, selfBin, "", id) |
| 420 | if !strings.Contains(cmd, "ssh 'klaus-worker-0'") { |
| 421 | t.Error("expected ssh to sandbox host, got:", cmd) |
| 422 | } |
| 423 | if !strings.Contains(cmd, shellQuote(remoteRunEnvPrefix(id)+"cd "+shellQuote(worktree)+" && "+claudeCmd)) { |
| 424 | t.Error("expected the run's ID and cd to worktree on remote, got:", cmd) |
| 425 | } |
| 426 | }) |
| 427 | |
| 428 | t.Run("feeds the local prompt file to ssh's stdin", func(t *testing.T) { |
| 429 | t.Setenv(sessionIDEnv, "") |
| 430 | cmd := buildSandboxPaneCommand(host, worktree, claudeCmd, promptFile, logFile, selfBin, "", id) |
| 431 | remote := shellQuote(remoteRunEnvPrefix(id) + "cd " + shellQuote(worktree) + " && " + claudeCmd) |
| 432 | if !strings.Contains(cmd, "( ssh 'klaus-worker-0' "+remote+" < '"+promptFile+"'; klaus_backend_exit=$?") { |
| 433 | t.Error("expected stdin redirect on the ssh command, got:", cmd) |
| 434 | } |
| 435 | }) |
| 436 | |
| 437 | t.Run("tee and format run locally", func(t *testing.T) { |
| 438 | t.Setenv(sessionIDEnv, "") |
| 439 | cmd := buildSandboxPaneCommand(host, worktree, claudeCmd, promptFile, logFile, selfBin, "", id) |
| 440 | if !strings.Contains(cmd, "| tee") { |
| 441 | t.Error("expected tee in local pipeline, got:", cmd) |
| 442 | } |
| 443 | if !strings.Contains(cmd, "| klaus _format-stream --sandbox;") { |
| 444 | t.Error("expected _format-stream --sandbox in local pipeline, got:", cmd) |
| 445 | } |
| 446 | if !strings.Contains(cmd, "_finalize") { |
| 447 | t.Error("expected _finalize in local pipeline, got:", cmd) |
| 448 | } |
| 449 | }) |
| 450 | |
| 451 | t.Run("rsyncs results back after finalize", func(t *testing.T) { |
| 452 | t.Setenv(sessionIDEnv, "") |
| 453 | cmd := buildSandboxPaneCommand(host, worktree, claudeCmd, promptFile, logFile, selfBin, "", id) |
| 454 | if !strings.Contains(cmd, "rsync -az") { |
| 455 | t.Error("expected rsync back in command, got:", cmd) |
| 456 | } |
| 457 | // rsync should reference host:worktree/ -> worktree/ |
| 458 | if !strings.Contains(cmd, "'klaus-worker-0':'/tmp/klaus-sessions/repo/abc123'/") { |
| 459 | t.Error("expected rsync from host:worktree, got:", cmd) |
| 460 | } |
| 461 | }) |
| 462 | |
| 463 | } |
| 464 | |
| 465 | // However hostile or long the prompt, the command handed to tmux carries only |
| 466 | // its path: nothing in it can be expanded by the shell or by tmux formats. |
| 467 | func TestAgentPaneCommandKeepsPromptOut(t *testing.T) { |
| 468 | t.Setenv(sessionIDEnv, "") |
| 469 | prompt := "it's `whoami` $(touch /tmp/pwned) ${HOME} #{pane_id} \"quoted\"\n" + strings.Repeat("x", 40000) |
| 470 | const promptPath = "/home/u/.klaus/sessions/s/prompts/20260918-1440-abcd.md" |
| 471 | for _, kind := range []backend.Kind{backend.Claude, backend.Codex, backend.Agy} { |
| 472 | for _, host := range []string{"", "sandbox-0"} { |
| 473 | t.Run(string(kind)+"/host="+host, func(t *testing.T) { |
| 474 | o := backend.Options{SystemPrompt: "sys", SystemPromptFile: "/p/20260918-1440-abcd.system.md", Prompt: prompt, RunID: "20260918-1440-abcd", Budget: "5"} |
| 475 | cmd, err := agentPaneCommand(kind, o, promptPath, host, "/wt", "/logs/x.jsonl", "", "20260918-1440-abcd", workerDirs{tmux: "/tmux/20260918-1440-abcd", scratch: "/scratch/20260918-1440-abcd"}) |
| 476 | if err != nil { |
| 477 | t.Fatal(err) |
| 478 | } |
| 479 | for _, frag := range []string{"whoami", "$(touch", "${HOME}", "#{pane_id}", "xxxx"} { |
| 480 | if strings.Contains(cmd, frag) { |
| 481 | t.Fatalf("prompt fragment %q in pane command: %s", frag, cmd) |
| 482 | } |
| 483 | } |
| 484 | if !strings.Contains(cmd, " < '"+promptPath+"'; klaus_backend_exit=$?") { |
| 485 | t.Fatalf("prompt file not redirected into the backend: %s", cmd) |
| 486 | } |
| 487 | if strings.Contains(cmd, "--append-system-prompt-file") == (host != "" || kind != backend.Claude) { |
| 488 | t.Fatalf("system prompt file only works for a local claude: %s", cmd) |
| 489 | } |
| 490 | }) |
| 491 | } |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | func TestAgentPaneCommandSizeGuard(t *testing.T) { |
| 496 | t.Setenv(sessionIDEnv, "") |
| 497 | big := strings.Repeat("y", maxPaneCommandBytes) |
| 498 | for _, tc := range []struct { |
| 499 | name, host, want string |
| 500 | kind backend.Kind |
| 501 | o backend.Options |
| 502 | }{ |
| 503 | {name: "claude reads a big system prompt from its file", kind: backend.Claude, o: backend.Options{SystemPrompt: big, SystemPromptFile: "/p/s.md", Prompt: big}}, |
| 504 | {name: "sandbox claude inlines the system prompt", kind: backend.Claude, host: "sandbox-0", o: backend.Options{SystemPrompt: big, SystemPromptFile: "/p/s.md"}, want: "the worker system prompt is 12000 bytes and goes inline for sandbox runs; shorten .klaus/prompt.md (.klaus/pr-fix-prompt.md for --pr), or use --local"}, |
| 505 | {name: "codex inlines the system prompt", kind: backend.Codex, o: backend.Options{SystemPrompt: big, Prompt: big}, want: "the worker system prompt is 12000 bytes and goes inline for codex runs"}, |
| 506 | {name: "agy reads both prompts on stdin", kind: backend.Agy, o: backend.Options{SystemPrompt: big, Prompt: big}}, |
| 507 | {name: "sandbox agy reads both prompts on stdin", kind: backend.Agy, host: "sandbox-0", o: backend.Options{SystemPrompt: big, Prompt: big}}, |
| 508 | } { |
| 509 | t.Run(tc.name, func(t *testing.T) { |
| 510 | cmd, err := agentPaneCommand(tc.kind, tc.o, "/p/prompt.md", tc.host, "/wt", "/logs/x.jsonl", "", "id", workerDirs{tmux: "/tmux/id", scratch: "/scratch/id"}) |
| 511 | if tc.want == "" { |
| 512 | if err != nil || len(cmd) > maxPaneCommandBytes { |
| 513 | t.Fatalf("err = %v, len = %d", err, len(cmd)) |
| 514 | } |
| 515 | return |
| 516 | } |
| 517 | if err == nil { |
| 518 | t.Fatalf("expected the size guard to fire, got a %d-byte command", len(cmd)) |
| 519 | } |
| 520 | if !regexp.MustCompile(`agent pane command is \d+ bytes, over the 12000-byte limit`).MatchString(err.Error()) || !strings.Contains(err.Error(), tc.want) { |
| 521 | t.Fatalf("unexpected error: %v", err) |
| 522 | } |
| 523 | }) |
| 524 | } |
| 525 | } |
| 526 | |
| 527 | func TestLaunchCmdHasSandboxFlags(t *testing.T) { |
| 528 | f := launchCmd.Flags().Lookup("local") |
| 529 | if f == nil { |
| 530 | t.Fatal("expected --local flag to be registered on launch command") |
| 531 | } |
| 532 | if f.DefValue != "false" { |
| 533 | t.Errorf("--local default value should be 'false', got %q", f.DefValue) |
| 534 | } |
| 535 | |
| 536 | h := launchCmd.Flags().Lookup("host") |
| 537 | if h == nil { |
| 538 | t.Fatal("expected --host flag to be registered on launch command") |
| 539 | } |
| 540 | if h.DefValue != "" { |
| 541 | t.Errorf("--host default value should be empty, got %q", h.DefValue) |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | func TestBuildClaudeCommand_SessionNaming(t *testing.T) { |
| 546 | cmd := buildClaudeCommand("sys prompt", "5", "do stuff", "20260405-1200-abcd", "", "", "") |
| 547 | if !strings.Contains(cmd, "'-n' '20260405-1200-abcd'") { |
| 548 | t.Errorf("expected -n flag with run ID, got: %s", cmd) |
| 549 | } |
| 550 | if strings.Contains(cmd, "--resume") { |
| 551 | t.Error("expected no --resume flag when resumeSessionName is empty") |
| 552 | } |
| 553 | if strings.Contains(cmd, "--fork-session") { |
| 554 | t.Error("expected no --fork-session flag when resumeSessionName is empty") |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | func TestBuildClaudeCommand_WithResume(t *testing.T) { |
| 559 | cmd := buildClaudeCommand("sys prompt", "5", "fix CI", "20260405-1200-efgh", "20260405-1100-abcd", "", "") |
| 560 | if !strings.Contains(cmd, "'-n' '20260405-1200-efgh'") { |
| 561 | t.Errorf("expected -n flag with new run ID, got: %s", cmd) |
| 562 | } |
| 563 | if !strings.Contains(cmd, "'--resume' '20260405-1100-abcd'") { |
| 564 | t.Errorf("expected --resume flag with original session name, got: %s", cmd) |
| 565 | } |
| 566 | if !strings.Contains(cmd, "--fork-session") { |
| 567 | t.Errorf("expected --fork-session flag, got: %s", cmd) |
| 568 | } |
| 569 | } |
| 570 | |
| 571 | func TestBuildClaudeCommand_ModelAndEffort(t *testing.T) { |
| 572 | t.Run("both passed through when set", func(t *testing.T) { |
| 573 | cmd := buildClaudeCommand("sys", "5", "do stuff", "20260805-0900-abcd", "", "claude-sonnet-5", "low") |
| 574 | if !strings.Contains(cmd, "'--model' 'claude-sonnet-5'") { |
| 575 | t.Errorf("expected --model flag, got: %s", cmd) |
| 576 | } |
| 577 | if !strings.Contains(cmd, "'--effort' 'low'") { |
| 578 | t.Errorf("expected --effort flag, got: %s", cmd) |
| 579 | } |
| 580 | }) |
| 581 | |
| 582 | t.Run("absent when unset so claude's own resolution applies", func(t *testing.T) { |
| 583 | cmd := buildClaudeCommand("sys", "5", "do stuff", "20260805-0900-abcd", "", "", "") |
| 584 | if strings.Contains(cmd, "--model") { |
| 585 | t.Errorf("expected no --model flag when unset, got: %s", cmd) |
| 586 | } |
| 587 | if strings.Contains(cmd, "--effort") { |
| 588 | t.Errorf("expected no --effort flag when unset, got: %s", cmd) |
| 589 | } |
| 590 | }) |
| 591 | } |
| 592 | |
| 593 | func TestValidateEffort(t *testing.T) { |
| 594 | for _, valid := range []string{"", "low", "medium", "high", "xhigh", "max"} { |
| 595 | if err := validateEffort(valid); err != nil { |
| 596 | t.Errorf("validateEffort(%q) = %v, want nil", valid, err) |
| 597 | } |
| 598 | } |
| 599 | err := validateEffort("turbo") |
| 600 | if err == nil { |
| 601 | t.Fatal("validateEffort(\"turbo\") = nil, want error") |
| 602 | } |
| 603 | // The error must name the valid values. |
| 604 | for _, want := range []string{"turbo", "low", "medium", "high", "xhigh", "max"} { |
| 605 | if !strings.Contains(err.Error(), want) { |
| 606 | t.Errorf("error %q should mention %q", err, want) |
| 607 | } |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | func TestLaunchCmdHasResumeFromFlag(t *testing.T) { |
| 612 | f := launchCmd.Flags().Lookup("resume-from") |
| 613 | if f == nil { |
| 614 | t.Fatal("expected --resume-from flag to be registered on launch command") |
| 615 | } |
| 616 | if f.DefValue != "" { |
| 617 | t.Errorf("--resume-from default value should be empty, got %q", f.DefValue) |
| 618 | } |
| 619 | } |
| 620 | |
| 621 | func TestClaudeSessionExists(t *testing.T) { |
| 622 | home := t.TempDir() |
| 623 | t.Setenv("HOME", home) |
| 624 | |
| 625 | projDir := filepath.Join(home, ".claude", "projects", "-some-encoded-dir") |
| 626 | if err := os.MkdirAll(projDir, 0o755); err != nil { |
| 627 | t.Fatalf("MkdirAll: %v", err) |
| 628 | } |
| 629 | |
| 630 | const presentUUID = "79dcfb08-4de4-45f4-b7db-056bccbc3a00" |
| 631 | if err := os.WriteFile(filepath.Join(projDir, presentUUID+".jsonl"), []byte("{}\n"), 0o644); err != nil { |
| 632 | t.Fatalf("WriteFile: %v", err) |
| 633 | } |
| 634 | |
| 635 | if !claudeSessionExists(presentUUID) { |
| 636 | t.Errorf("claudeSessionExists(%q) = false, want true", presentUUID) |
| 637 | } |
| 638 | if claudeSessionExists("00000000-0000-0000-0000-000000000000") { |
| 639 | t.Error("claudeSessionExists(missing UUID) = true, want false") |
| 640 | } |
| 641 | if claudeSessionExists("") { |
| 642 | t.Error("claudeSessionExists(\"\") = true, want false") |
| 643 | } |
| 644 | |
| 645 | // Reject inputs containing glob metacharacters or path separators even if |
| 646 | // matching files happen to exist on disk. |
| 647 | for _, bad := range []string{"*", "?", "../" + presentUUID, presentUUID + "/..", "[a-z]" + presentUUID[5:], presentUUID + "\x00"} { |
| 648 | if claudeSessionExists(bad) { |
| 649 | t.Errorf("claudeSessionExists(%q) = true, want false (invalid characters)", bad) |
| 650 | } |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | func TestResolveResumeID(t *testing.T) { |
| 655 | const sessionID = "79dcfb08-4de4-45f4-b7db-056bccbc3a00" |
| 656 | for _, tc := range []struct { |
| 657 | name string |
| 658 | kind backend.Kind |
| 659 | reason string |
| 660 | missing bool |
| 661 | missingID bool |
| 662 | blockStage bool |
| 663 | }{ |
| 664 | {name: "Claude resumes after success failure reason", kind: backend.Claude, reason: "success"}, |
| 665 | {name: "Claude resumes after crash", kind: backend.Claude, reason: "error_during_execution"}, |
| 666 | {name: "Claude missing transcript starts fresh", kind: backend.Claude, reason: "success", missing: true}, |
| 667 | {name: "Claude missing session ID starts fresh", kind: backend.Claude, reason: "success", missingID: true}, |
| 668 | {name: "Claude staging failure starts fresh", kind: backend.Claude, reason: "success", blockStage: true}, |
| 669 | {name: "Codex resumes after success failure reason", kind: backend.Codex, reason: "success"}, |
| 670 | {name: "Codex resumes after crash", kind: backend.Codex, reason: "codex exited with status 1"}, |
| 671 | {name: "Codex missing session ID starts fresh", kind: backend.Codex, reason: "success", missingID: true}, |
| 672 | } { |
| 673 | t.Run(tc.name, func(t *testing.T) { |
| 674 | home := t.TempDir() |
| 675 | t.Setenv("HOME", home) |
| 676 | t.Setenv("USERPROFILE", home) |
| 677 | store := run.NewHomeDirStoreFromPath(filepath.Join(home, ".klaus", "session-test")) |
| 678 | if err := store.EnsureDirs(); err != nil { |
| 679 | t.Fatal(err) |
| 680 | } |
| 681 | prior := &run.State{ |
| 682 | ID: "prior-run", Backend: string(tc.kind), |
| 683 | Worktree: filepath.Join(home, "old-worktree"), FailureReason: &tc.reason, |
| 684 | } |
| 685 | worktree := filepath.Join(home, "new-worktree") |
| 686 | if tc.kind == backend.Claude { |
| 687 | logFile := filepath.Join(store.LogDir(), prior.ID+".jsonl") |
| 688 | prior.LogFile = &logFile |
| 689 | log := `{"type":"result","session_id":"` + sessionID + `"}` |
| 690 | if tc.missingID { |
| 691 | log = `{"type":"result"}` |
| 692 | } |
| 693 | if err := os.WriteFile(logFile, []byte(log+"\n"), 0o600); err != nil { |
| 694 | t.Fatal(err) |
| 695 | } |
| 696 | if !tc.missing { |
| 697 | src := claudeConversationPath(prior.Worktree, sessionID) |
| 698 | if err := os.MkdirAll(filepath.Dir(src), 0o755); err != nil { |
| 699 | t.Fatal(err) |
| 700 | } |
| 701 | if err := os.WriteFile(src, []byte(`{"sessionId":"`+sessionID+`"}`+"\n"), 0o600); err != nil { |
| 702 | t.Fatal(err) |
| 703 | } |
| 704 | } |
| 705 | if tc.blockStage { |
| 706 | if err := os.WriteFile(filepath.Dir(claudeConversationPath(worktree, sessionID)), nil, 0o600); err != nil { |
| 707 | t.Fatal(err) |
| 708 | } |
| 709 | } |
| 710 | } else if !tc.missingID { |
| 711 | prior.BackendSessionID = strPtr(sessionID) |
| 712 | } |
| 713 | if err := store.Save(prior); err != nil { |
| 714 | t.Fatal(err) |
| 715 | } |
| 716 | prior, err := store.Load(prior.ID) |
| 717 | if err != nil { |
| 718 | t.Fatal(err) |
| 719 | } |
| 720 | stderr, err := os.CreateTemp(home, "stderr") |
| 721 | if err != nil { |
| 722 | t.Fatal(err) |
| 723 | } |
| 724 | defer stderr.Close() |
| 725 | originalStderr := os.Stderr |
| 726 | os.Stderr = stderr |
| 727 | t.Cleanup(func() { os.Stderr = originalStderr }) |
| 728 | got := resolveResumeID(prior, tc.kind, worktree) |
| 729 | want := sessionID |
| 730 | if tc.missing || tc.missingID || tc.blockStage { |
| 731 | want = "" |
| 732 | } |
| 733 | if got != want { |
| 734 | t.Fatalf("resolveResumeID = %q, want %q", got, want) |
| 735 | } |
| 736 | warning, err := os.ReadFile(stderr.Name()) |
| 737 | if err != nil { |
| 738 | t.Fatal(err) |
| 739 | } |
| 740 | if strings.Contains(string(warning), "failed (success)") { |
| 741 | t.Fatalf("misleading warning: %s", warning) |
| 742 | } |
| 743 | if want != "" { |
| 744 | if !strings.Contains(string(warning), "ended with "+tc.reason+"; resuming") { |
| 745 | t.Errorf("missing resume warning: %s", warning) |
| 746 | } |
| 747 | if tc.kind == backend.Claude { |
| 748 | src, err := os.ReadFile(claudeConversationPath(prior.Worktree, sessionID)) |
| 749 | if err != nil { |
| 750 | t.Fatal(err) |
| 751 | } |
| 752 | dest, err := os.ReadFile(claudeConversationPath(worktree, sessionID)) |
| 753 | if err != nil || string(src) != string(dest) { |
| 754 | t.Fatalf("transcript was not staged intact: %v", err) |
| 755 | } |
| 756 | } |
| 757 | } |
| 758 | args := tc.kind.Worker(backend.Options{ResumeID: got}) |
| 759 | command := backend.ShellCommand(args) |
| 760 | if strings.Contains(command, sessionID) != (want != "") { |
| 761 | t.Errorf("unexpected resume command: %s", command) |
| 762 | } |
| 763 | }) |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | func TestResumeHandlesNilRunState(t *testing.T) { |
| 768 | for _, kind := range []backend.Kind{backend.Claude, backend.Codex} { |
| 769 | if got := resolveResumeID(nil, kind, t.TempDir()); got != "" { |
| 770 | t.Errorf("resolveResumeID(nil, %s) = %q, want empty", kind, got) |
| 771 | } |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | // TestStageResumeTranscript covers Bug 1: 'claude --resume' scopes |
| 776 | // conversation transcripts by working directory, so a resume launched in a new |
| 777 | // worktree can't find the prior conversation. stageResumeTranscript copies the |
| 778 | // transcript into the new worktree's project dir before launch, and falls back |
| 779 | // to a fresh session (no --resume) when the source transcript is absent. |
| 780 | func TestStageResumeTranscript(t *testing.T) { |
| 781 | const uuid = "79dcfb08-4de4-45f4-b7db-056bccbc3a00" |
| 782 | |
| 783 | t.Run("copies transcript into new worktree project dir", func(t *testing.T) { |
| 784 | home := t.TempDir() |
| 785 | t.Setenv("HOME", home) |
| 786 | t.Setenv("USERPROFILE", home) |
| 787 | |
| 788 | oldWorktree := "/tmp/klaus-sessions/klaus/old-run" |
| 789 | newWorktree := "/tmp/klaus-sessions/klaus/new-run" |
| 790 | |
| 791 | // Write the prior conversation transcript into the OLD worktree's |
| 792 | // project dir, the way claude itself would. |
| 793 | src := claudeConversationPath(oldWorktree, uuid) |
| 794 | if err := os.MkdirAll(filepath.Dir(src), 0o755); err != nil { |
| 795 | t.Fatalf("MkdirAll src: %v", err) |
| 796 | } |
| 797 | if err := os.WriteFile(src, []byte(`{"sessionId":"`+uuid+`"}`+"\n"), 0o644); err != nil { |
| 798 | t.Fatalf("WriteFile src: %v", err) |
| 799 | } |
| 800 | |
| 801 | prevState := &run.State{ |
| 802 | ID: "20260628-1000-old", |
| 803 | Worktree: oldWorktree, |
| 804 | ClaudeSessionID: strPtr(uuid), |
| 805 | } |
| 806 | |
| 807 | if !stageResumeTranscript(prevState, uuid, newWorktree) { |
| 808 | t.Fatal("stageResumeTranscript = false, want true when source transcript exists") |
| 809 | } |
| 810 | |
| 811 | dest := claudeConversationPath(newWorktree, uuid) |
| 812 | if _, err := os.Stat(dest); err != nil { |
| 813 | t.Fatalf("expected transcript copied to %q: %v", dest, err) |
| 814 | } |
| 815 | |
| 816 | // With staging done, the launched command resumes the session. |
| 817 | cmd := buildClaudeCommand("sys", "5", "fix conflicts", "20260628-1001-new", uuid, "", "") |
| 818 | if !strings.Contains(cmd, "'--resume' '"+uuid+"'") { |
| 819 | t.Errorf("expected --resume after successful staging, got: %s", cmd) |
| 820 | } |
| 821 | }) |
| 822 | |
| 823 | t.Run("falls back to fresh session when source transcript is absent", func(t *testing.T) { |
| 824 | home := t.TempDir() |
| 825 | t.Setenv("HOME", home) |
| 826 | t.Setenv("USERPROFILE", home) |
| 827 | |
| 828 | prevState := &run.State{ |
| 829 | ID: "20260628-1000-old", |
| 830 | Worktree: "/tmp/klaus-sessions/klaus/old-run", |
| 831 | ClaudeSessionID: strPtr(uuid), |
| 832 | } |
| 833 | |
| 834 | newWorktree := "/tmp/klaus-sessions/klaus/new-run" |
| 835 | if stageResumeTranscript(prevState, uuid, newWorktree) { |
| 836 | t.Fatal("stageResumeTranscript = true, want false when source transcript is missing") |
| 837 | } |
| 838 | |
| 839 | // The caller leaves resolvedResume empty, so no --resume flag. |
| 840 | cmd := buildClaudeCommand("sys", "5", "fix conflicts", "20260628-1001-new", "", "", "") |
| 841 | if strings.Contains(cmd, "--resume") { |
| 842 | t.Errorf("expected no --resume when staging failed, got: %s", cmd) |
| 843 | } |
| 844 | }) |
| 845 | } |
| 846 | |
| 847 | func TestLaunchCmdHasPRFlag(t *testing.T) { |
| 848 | // Verify the --pr flag is registered on the launch command |
| 849 | f := launchCmd.Flags().Lookup("pr") |
| 850 | if f == nil { |
| 851 | t.Fatal("expected --pr flag to be registered on launch command") |
| 852 | } |
| 853 | if f.DefValue != "" { |
| 854 | t.Errorf("--pr default value should be empty, got %q", f.DefValue) |
| 855 | } |
| 856 | } |
| 857 | |
| 858 | // TestSessionPromptDocumentsEveryLaunchFlag keeps the coordinator system prompt |
| 859 | // in step with the CLI. A coordinator only knows the flags its prompt names: the |
| 860 | // prompt once listed four of them, so --resume-from was invisible and agents were |
| 861 | // killed and re-briefed cold when they could have been continued. |
| 862 | func TestSessionPromptDocumentsEveryLaunchFlag(t *testing.T) { |
| 863 | flagToken := regexp.MustCompile(`--[a-z][a-z0-9-]*`) |
| 864 | |
| 865 | for _, tc := range []struct { |
| 866 | name string |
| 867 | repoName string |
| 868 | }{ |
| 869 | {"in a repo", "klaus"}, |
| 870 | {"scratch workspace", ""}, |
| 871 | } { |
| 872 | t.Run(tc.name, func(t *testing.T) { |
| 873 | // Empty repoRoot: no .klaus/session-prompt.md, so the built-in |
| 874 | // template renders. |
| 875 | prompt, err := config.RenderSessionPrompt(t.TempDir(), config.PromptVars{ |
| 876 | RunID: "20260731-1804-b437", |
| 877 | Branch: "agent/20260731-1804-b437", |
| 878 | RepoName: tc.repoName, |
| 879 | }) |
| 880 | if err != nil { |
| 881 | t.Fatalf("rendering session prompt: %v", err) |
| 882 | } |
| 883 | |
| 884 | documented := map[string]bool{} |
| 885 | for _, tok := range flagToken.FindAllString(prompt, -1) { |
| 886 | documented[tok] = true |
| 887 | } |
| 888 | |
| 889 | launchCmd.Flags().VisitAll(func(f *pflag.Flag) { |
| 890 | if !documented["--"+f.Name] { |
| 891 | t.Errorf("klaus launch --%s is not documented in the coordinator session prompt", f.Name) |
| 892 | } |
| 893 | }) |
| 894 | }) |
| 895 | } |
| 896 | } |
| 897 | |
| 898 | func TestResolvePrompt(t *testing.T) { |
| 899 | dir := t.TempDir() |
| 900 | file := filepath.Join(dir, "prompt.md") |
| 901 | // Backticks and $VAR are exactly what a shell-quoted prompt loses. |
| 902 | body := "Fix `ValidateToken()` in internal/auth/verify.go\n\nUse $HOME, not ~.\n" |
| 903 | if err := os.WriteFile(file, []byte(body), 0o644); err != nil { |
| 904 | t.Fatal(err) |
| 905 | } |
| 906 | |
| 907 | t.Run("file contents are used verbatim", func(t *testing.T) { |
| 908 | got, err := resolvePrompt(nil, file) |
| 909 | if err != nil { |
| 910 | t.Fatalf("resolvePrompt: %v", err) |
| 911 | } |
| 912 | if got != body { |
| 913 | t.Errorf("prompt = %q, want %q", got, body) |
| 914 | } |
| 915 | }) |
| 916 | |
| 917 | t.Run("positional argument still works", func(t *testing.T) { |
| 918 | got, err := resolvePrompt([]string{"do the thing"}, "") |
| 919 | if err != nil { |
| 920 | t.Fatalf("resolvePrompt: %v", err) |
| 921 | } |
| 922 | if got != "do the thing" { |
| 923 | t.Errorf("prompt = %q", got) |
| 924 | } |
| 925 | }) |
| 926 | |
| 927 | t.Run("both sources is an error", func(t *testing.T) { |
| 928 | _, err := resolvePrompt([]string{"do the thing"}, file) |
| 929 | if err == nil || !strings.Contains(err.Error(), "--prompt-file") { |
| 930 | t.Errorf("err = %v, want an error naming --prompt-file", err) |
| 931 | } |
| 932 | }) |
| 933 | |
| 934 | t.Run("neither source is an error", func(t *testing.T) { |
| 935 | _, err := resolvePrompt(nil, "") |
| 936 | if err == nil || !strings.Contains(err.Error(), "--prompt-file") { |
| 937 | t.Errorf("err = %v, want an error naming --prompt-file", err) |
| 938 | } |
| 939 | }) |
| 940 | |
| 941 | t.Run("missing file is an error", func(t *testing.T) { |
| 942 | if _, err := resolvePrompt(nil, filepath.Join(dir, "nope.md")); err == nil { |
| 943 | t.Error("expected an error for a missing prompt file") |
| 944 | } |
| 945 | }) |
| 946 | |
| 947 | t.Run("whitespace-only file is an error", func(t *testing.T) { |
| 948 | blank := filepath.Join(dir, "blank.md") |
| 949 | if err := os.WriteFile(blank, []byte(" \n\t\n"), 0o644); err != nil { |
| 950 | t.Fatal(err) |
| 951 | } |
| 952 | if _, err := resolvePrompt(nil, blank); err == nil { |
| 953 | t.Error("expected an error for an empty prompt file") |
| 954 | } |
| 955 | }) |
| 956 | } |
| 957 | |
| 958 | // These compatibility helpers delegate the Claude contract to the backend package. |
| 959 | func validateEffort(effort string) error { return backend.Claude.ValidateEffort(effort) } |
| 960 | func buildClaudeCommand(sysPrompt, budget, prompt, runID, resumeID, model, effort string) string { |
| 961 | args := backend.Claude.Worker(backend.Options{SystemPrompt: sysPrompt, Budget: budget, Prompt: prompt, RunID: runID, ResumeID: resumeID, Model: model, Effort: effort}) |
| 962 | return backend.ShellCommand(args) |
| 963 | } |
| 964 | |
| 965 | // TestIsDirectPushRepo decides delivery from real repos' origin remotes: only |
| 966 | // a github.com origin gets the PR flow. |
| 967 | func TestIsDirectPushRepo(t *testing.T) { |
| 968 | tests := []struct { |
| 969 | origin string |
| 970 | want bool |
| 971 | }{ |
| 972 | {"git@github.com:o/r.git", false}, |
| 973 | {"git@github.com:o/r", false}, |
| 974 | {"https://github.com/o/r", false}, |
| 975 | {"https://github.com/o/r.git", false}, |
| 976 | {"https://github.com/o/r/", false}, |
| 977 | {"ssh://git@github.com/o/r.git", false}, |
| 978 | {"git@10.0.2.1:site.git", true}, |
| 979 | {"git@valley-host:the-valley.git", true}, |
| 980 | {"file:///srv/git/widget.git", true}, |
| 981 | {"/srv/git/widget.git", true}, |
| 982 | // Not github.com, though ParseRepoRef alone accepts the scp form. |
| 983 | {"git@gitlab.com:o/r.git", true}, |
| 984 | {"https://gitlab.com/o/r.git", true}, |
| 985 | {"https://github.com.evil.example/o/r", true}, |
| 986 | {"git@github.com.evil.example:o/r.git", true}, |
| 987 | // No owner/repo after the host. |
| 988 | {"https://github.com/", true}, |
| 989 | {"git@github.com:../evil.git", true}, |
| 990 | // A bare owner/repo is a relative path as a remote, not GitHub. |
| 991 | {"o/r", true}, |
| 992 | } |
| 993 | for _, tt := range tests { |
| 994 | t.Run(tt.origin, func(t *testing.T) { |
| 995 | dir := initRepo(t, filepath.Join(t.TempDir(), "repo"), tt.origin) |
| 996 | if got := isDirectPushRepo(dir); got != tt.want { |
| 997 | t.Errorf("isDirectPushRepo(origin %q) = %v, want %v", tt.origin, got, tt.want) |
| 998 | } |
| 999 | }) |
| 1000 | } |
| 1001 | |
| 1002 | t.Run("no origin", func(t *testing.T) { |
| 1003 | dir := initRepo(t, filepath.Join(t.TempDir(), "repo"), "/srv/git/widget.git") |
| 1004 | if out, err := exec.Command("git", "-C", dir, "remote", "remove", "origin").CombinedOutput(); err != nil { |
| 1005 | t.Fatalf("git remote remove: %v\n%s", err, out) |
| 1006 | } |
| 1007 | if !isDirectPushRepo(dir) { |
| 1008 | t.Error("a repo without origin cannot open a PR; want direct push") |
| 1009 | } |
| 1010 | }) |
| 1011 | } |
| 1012 | |
| 1013 | // TestDefaultPromptFollowsOriginDelivery renders the default worker prompt the |
| 1014 | // way launch does, for a GitHub origin and a valley-style origin. |
| 1015 | func TestDefaultPromptFollowsOriginDelivery(t *testing.T) { |
| 1016 | render := func(origin string) string { |
| 1017 | t.Helper() |
| 1018 | dir := initRepo(t, filepath.Join(t.TempDir(), "repo"), origin) |
| 1019 | prompt, err := config.RenderPrompt(dir, config.PromptVars{ |
| 1020 | RunID: "20261011-1905-7f6906fc", |
| 1021 | Issue: "42", |
| 1022 | Branch: "agent/20261011-1905-7f6906fc", |
| 1023 | Reviewer: "octocat", |
| 1024 | DirectPush: isDirectPushRepo(dir), |
| 1025 | }) |
| 1026 | if err != nil { |
| 1027 | t.Fatalf("RenderPrompt: %v", err) |
| 1028 | } |
| 1029 | return prompt |
| 1030 | } |
| 1031 | github := render("git@github.com:maintainer/klaus.git") |
| 1032 | valley := render("git@10.0.2.1:site.git") |
| 1033 | |
| 1034 | for _, want := range []string{"6. Create a PR.", "Fixes #42", "Use --reviewer octocat"} { |
| 1035 | if !strings.Contains(github, want) { |
| 1036 | t.Errorf("GitHub prompt missing %q:\n%s", want, github) |
| 1037 | } |
| 1038 | if strings.Contains(valley, want) { |
| 1039 | t.Errorf("direct-push prompt should not contain %q:\n%s", want, valley) |
| 1040 | } |
| 1041 | } |
| 1042 | for _, want := range []string{"Do not create a PR", "head SHA", "the operator reviews from your final report", "Reference issue #42"} { |
| 1043 | if !strings.Contains(valley, want) { |
| 1044 | t.Errorf("direct-push prompt missing %q:\n%s", want, valley) |
| 1045 | } |
| 1046 | if strings.Contains(github, want) { |
| 1047 | t.Errorf("GitHub prompt should not contain %q:\n%s", want, github) |
| 1048 | } |
| 1049 | } |
| 1050 | // Shared in both modes. |
| 1051 | for _, want := range []string{ |
| 1052 | "Run: 20261011-1905-7f6906fc", |
| 1053 | "`git push -u origin HEAD`", |
| 1054 | "Before pushing, run `klaus _pre-review`", |
| 1055 | "Never commit directly to the default branch", |
| 1056 | "## Documentation", |
| 1057 | "Do not include any AI attribution", |
| 1058 | } { |
| 1059 | for name, prompt := range map[string]string{"GitHub": github, "direct-push": valley} { |
| 1060 | if !strings.Contains(prompt, want) { |
| 1061 | t.Errorf("%s prompt missing %q:\n%s", name, want, prompt) |
| 1062 | } |
| 1063 | } |
| 1064 | } |
| 1065 | if strings.Contains(github+valley, "before creating a PR") { |
| 1066 | t.Error("shared sections should say \"before pushing\", not \"before creating a PR\"") |
| 1067 | } |
| 1068 | } |