| 1 | package config |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "os" |
| 7 | "os/exec" |
| 8 | "path/filepath" |
| 9 | "reflect" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | ) |
| 13 | |
| 14 | var wantWorktreeBase = filepath.Join(os.TempDir(), "klaus-sessions") |
| 15 | |
| 16 | func TestDefaults(t *testing.T) { |
| 17 | cfg := Defaults() |
| 18 | if cfg.WorktreeBase != wantWorktreeBase { |
| 19 | t.Errorf("WorktreeBase = %q, want %q", cfg.WorktreeBase, wantWorktreeBase) |
| 20 | } |
| 21 | if cfg.DefaultBudget != "5.00" { |
| 22 | t.Errorf("DefaultBudget = %q, want 5.00", cfg.DefaultBudget) |
| 23 | } |
| 24 | if cfg.DataRef != "refs/klaus/data" { |
| 25 | t.Errorf("DataRef = %q, want refs/klaus/data", cfg.DataRef) |
| 26 | } |
| 27 | if cfg.DefaultBranch != "main" { |
| 28 | t.Errorf("DefaultBranch = %q, want main", cfg.DefaultBranch) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | func TestLoadNoFile(t *testing.T) { |
| 33 | cfg, err := Load(t.TempDir()) |
| 34 | if err != nil { |
| 35 | t.Fatalf("Load() error: %v", err) |
| 36 | } |
| 37 | // Should return defaults |
| 38 | if cfg.WorktreeBase != wantWorktreeBase { |
| 39 | t.Errorf("WorktreeBase = %q, want %q", cfg.WorktreeBase, wantWorktreeBase) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | func TestLoadWithFile(t *testing.T) { |
| 44 | dir := t.TempDir() |
| 45 | klausDir := filepath.Join(dir, ".klaus") |
| 46 | os.MkdirAll(klausDir, 0o755) |
| 47 | |
| 48 | custom := Config{ |
| 49 | WorktreeBase: "/tmp/custom", |
| 50 | DefaultBudget: "10.00", |
| 51 | DataRef: "refs/custom/data", |
| 52 | DefaultBranch: "develop", |
| 53 | } |
| 54 | data, _ := json.Marshal(custom) |
| 55 | os.WriteFile(filepath.Join(klausDir, "config.json"), data, 0o644) |
| 56 | |
| 57 | cfg, err := Load(dir) |
| 58 | if err != nil { |
| 59 | t.Fatalf("Load() error: %v", err) |
| 60 | } |
| 61 | if cfg.WorktreeBase != "/tmp/custom" { |
| 62 | t.Errorf("WorktreeBase = %q, want /tmp/custom", cfg.WorktreeBase) |
| 63 | } |
| 64 | if cfg.DefaultBudget != "10.00" { |
| 65 | t.Errorf("DefaultBudget = %q, want 10.00", cfg.DefaultBudget) |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | func TestLoadPartialOverride(t *testing.T) { |
| 70 | dir := t.TempDir() |
| 71 | klausDir := filepath.Join(dir, ".klaus") |
| 72 | os.MkdirAll(klausDir, 0o755) |
| 73 | |
| 74 | // Only override one field |
| 75 | os.WriteFile(filepath.Join(klausDir, "config.json"), []byte(`{"default_budget":"20.00"}`), 0o644) |
| 76 | |
| 77 | cfg, err := Load(dir) |
| 78 | if err != nil { |
| 79 | t.Fatalf("Load() error: %v", err) |
| 80 | } |
| 81 | if cfg.DefaultBudget != "20.00" { |
| 82 | t.Errorf("DefaultBudget = %q, want 20.00", cfg.DefaultBudget) |
| 83 | } |
| 84 | // Other fields should be zero values since we unmarshal into defaults then overwrite |
| 85 | // Actually since we start with defaults and unmarshal over them, non-specified fields |
| 86 | // keep their zero values in the JSON case. Let's verify: |
| 87 | if cfg.WorktreeBase != "" { |
| 88 | // JSON unmarshal replaces the struct, so unset fields get zero values |
| 89 | // This is expected behavior โ users should specify all fields or use Init |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | func TestRenderPromptDefault(t *testing.T) { |
| 94 | dir := t.TempDir() // no .klaus/prompt.md |
| 95 | |
| 96 | vars := PromptVars{ |
| 97 | RunID: "20260210-1430-a3f2", |
| 98 | Issue: "42", |
| 99 | Branch: "agent/20260210-1430-a3f2", |
| 100 | RepoName: "test-repo", |
| 101 | } |
| 102 | |
| 103 | prompt, err := RenderPrompt(dir, vars) |
| 104 | if err != nil { |
| 105 | t.Fatalf("RenderPrompt() error: %v", err) |
| 106 | } |
| 107 | |
| 108 | if !strings.Contains(prompt, "Run: 20260210-1430-a3f2") { |
| 109 | t.Error("prompt should contain run ID") |
| 110 | } |
| 111 | if !strings.Contains(prompt, "Fixes #42") { |
| 112 | t.Error("prompt should contain issue reference") |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | func TestRenderPromptNoIssue(t *testing.T) { |
| 117 | dir := t.TempDir() |
| 118 | |
| 119 | vars := PromptVars{ |
| 120 | RunID: "20260210-1430-a3f2", |
| 121 | } |
| 122 | |
| 123 | prompt, err := RenderPrompt(dir, vars) |
| 124 | if err != nil { |
| 125 | t.Fatalf("RenderPrompt() error: %v", err) |
| 126 | } |
| 127 | |
| 128 | if strings.Contains(prompt, "Fixes") { |
| 129 | t.Error("prompt should not contain Fixes when no issue") |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | func TestRenderPromptCustomTemplate(t *testing.T) { |
| 134 | dir := t.TempDir() |
| 135 | klausDir := filepath.Join(dir, ".klaus") |
| 136 | os.MkdirAll(klausDir, 0o755) |
| 137 | |
| 138 | tmpl := "Agent {{.RunID}} on branch {{.Branch}} for repo {{.RepoName}}" |
| 139 | os.WriteFile(filepath.Join(klausDir, "prompt.md"), []byte(tmpl), 0o644) |
| 140 | |
| 141 | vars := PromptVars{ |
| 142 | RunID: "test-123", |
| 143 | Branch: "agent/test-123", |
| 144 | RepoName: "myrepo", |
| 145 | } |
| 146 | |
| 147 | prompt, err := RenderPrompt(dir, vars) |
| 148 | if err != nil { |
| 149 | t.Fatalf("RenderPrompt() error: %v", err) |
| 150 | } |
| 151 | |
| 152 | want := "Agent test-123 on branch agent/test-123 for repo myrepo" |
| 153 | if prompt != want { |
| 154 | t.Errorf("prompt = %q, want %q", prompt, want) |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | func TestRenderSessionPromptDefault(t *testing.T) { |
| 159 | dir := t.TempDir() // no .klaus/session-prompt.md |
| 160 | |
| 161 | vars := PromptVars{ |
| 162 | RunID: "session-20260210-1430-a3f2", |
| 163 | Branch: "session/session-20260210-1430-a3f2", |
| 164 | RepoName: "test-repo", |
| 165 | } |
| 166 | |
| 167 | prompt, err := RenderSessionPrompt(dir, vars) |
| 168 | if err != nil { |
| 169 | t.Fatalf("RenderSessionPrompt() error: %v", err) |
| 170 | } |
| 171 | |
| 172 | if !strings.Contains(prompt, "session-20260210-1430-a3f2") { |
| 173 | t.Error("prompt should contain session ID") |
| 174 | } |
| 175 | if !strings.Contains(prompt, "session/session-20260210-1430-a3f2") { |
| 176 | t.Error("prompt should contain branch name") |
| 177 | } |
| 178 | if !strings.Contains(prompt, "test-repo") { |
| 179 | t.Error("prompt should contain repo name") |
| 180 | } |
| 181 | if !strings.Contains(prompt, "valley flow launch") { |
| 182 | t.Error("prompt should contain valley flow launch instruction") |
| 183 | } |
| 184 | if !strings.Contains(prompt, "valley flow status") { |
| 185 | t.Error("prompt should contain valley flow status instruction") |
| 186 | } |
| 187 | if !strings.Contains(prompt, "valley flow logs") { |
| 188 | t.Error("prompt should contain valley flow logs instruction") |
| 189 | } |
| 190 | if !strings.Contains(prompt, "valley flow cleanup") { |
| 191 | t.Error("prompt should contain valley flow cleanup instruction") |
| 192 | } |
| 193 | if strings.Contains(prompt, "- **Approve and merge** PRs") { |
| 194 | t.Error("prompt should not instruct coordinator to approve PRs") |
| 195 | } |
| 196 | if !strings.Contains(prompt, "PR approval is strictly a human operator task") { |
| 197 | t.Error("prompt should state that PR approval is strictly a human operator task") |
| 198 | } |
| 199 | if !strings.Contains(prompt, "Never run `valley flow approve`") { |
| 200 | t.Error("prompt should instruct coordinator to never run valley flow approve") |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | func TestRenderSessionPromptCustomTemplate(t *testing.T) { |
| 205 | dir := t.TempDir() |
| 206 | klausDir := filepath.Join(dir, ".klaus") |
| 207 | os.MkdirAll(klausDir, 0o755) |
| 208 | |
| 209 | tmpl := "Session {{.RunID}} on branch {{.Branch}} for {{.RepoName}}" |
| 210 | os.WriteFile(filepath.Join(klausDir, "session-prompt.md"), []byte(tmpl), 0o644) |
| 211 | |
| 212 | vars := PromptVars{ |
| 213 | RunID: "session-abc", |
| 214 | Branch: "session/session-abc", |
| 215 | RepoName: "myrepo", |
| 216 | } |
| 217 | |
| 218 | prompt, err := RenderSessionPrompt(dir, vars) |
| 219 | if err != nil { |
| 220 | t.Fatalf("RenderSessionPrompt() error: %v", err) |
| 221 | } |
| 222 | |
| 223 | want := "Session session-abc on branch session/session-abc for myrepo" |
| 224 | if prompt != want { |
| 225 | t.Errorf("prompt = %q, want %q", prompt, want) |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | func TestRenderPRFixPromptDefault(t *testing.T) { |
| 230 | dir := t.TempDir() // no .klaus/pr-fix-prompt.md |
| 231 | |
| 232 | vars := PromptVars{ |
| 233 | RunID: "20260312-1820-abcd", |
| 234 | PR: "99", |
| 235 | Branch: "feature/my-branch", |
| 236 | RepoName: "test-repo", |
| 237 | Issue: "42", |
| 238 | } |
| 239 | |
| 240 | prompt, err := RenderPRFixPrompt(dir, vars) |
| 241 | if err != nil { |
| 242 | t.Fatalf("RenderPRFixPrompt() error: %v", err) |
| 243 | } |
| 244 | |
| 245 | if !strings.Contains(prompt, "PR #99") { |
| 246 | t.Error("prompt should contain PR number") |
| 247 | } |
| 248 | if !strings.Contains(prompt, "Do NOT create a new PR") { |
| 249 | t.Error("prompt should instruct not to create a new PR") |
| 250 | } |
| 251 | if !strings.Contains(prompt, "feature/my-branch") { |
| 252 | t.Error("prompt should contain branch name") |
| 253 | } |
| 254 | if !strings.Contains(prompt, "#42") { |
| 255 | t.Error("prompt should reference issue when provided") |
| 256 | } |
| 257 | if !strings.Contains(prompt, "20260312-1820-abcd") { |
| 258 | t.Error("prompt should contain run ID") |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | func TestRenderPRFixPromptCustomTemplate(t *testing.T) { |
| 263 | dir := t.TempDir() |
| 264 | klausDir := filepath.Join(dir, ".klaus") |
| 265 | os.MkdirAll(klausDir, 0o755) |
| 266 | |
| 267 | tmpl := "Fix PR #{{.PR}} run {{.RunID}} on {{.Branch}}" |
| 268 | os.WriteFile(filepath.Join(klausDir, "pr-fix-prompt.md"), []byte(tmpl), 0o644) |
| 269 | |
| 270 | vars := PromptVars{ |
| 271 | RunID: "fix-abc", |
| 272 | PR: "55", |
| 273 | Branch: "feature/fix", |
| 274 | } |
| 275 | |
| 276 | prompt, err := RenderPRFixPrompt(dir, vars) |
| 277 | if err != nil { |
| 278 | t.Fatalf("RenderPRFixPrompt() error: %v", err) |
| 279 | } |
| 280 | |
| 281 | want := "Fix PR #55 run fix-abc on feature/fix" |
| 282 | if prompt != want { |
| 283 | t.Errorf("prompt = %q, want %q", prompt, want) |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | func TestRenderPromptFromFileReadError(t *testing.T) { |
| 288 | dir := t.TempDir() |
| 289 | klausDir := filepath.Join(dir, ".klaus") |
| 290 | os.MkdirAll(klausDir, 0o755) |
| 291 | |
| 292 | // Create a directory where a file is expected, causing a read error |
| 293 | os.MkdirAll(filepath.Join(klausDir, "prompt.md"), 0o755) |
| 294 | |
| 295 | vars := PromptVars{RunID: "test-123"} |
| 296 | _, err := RenderPrompt(dir, vars) |
| 297 | if err == nil { |
| 298 | t.Error("expected error when prompt.md is a directory") |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | // TestEveryWorkerGetsTheRules renders each kind of worker prompt as launch |
| 303 | // does (RenderWorkerPrompt). The mechanics (build rule, process rule, final |
| 304 | // report's headings) reach every kind, custom templates included, and the |
| 305 | // taste rules are not among them; only a valley change's run is told to keep |
| 306 | // the change's head message true to the whole change; and only a follow-up on |
| 307 | // an existing change or PR gets the default follow-up scope rule. |
| 308 | func TestEveryWorkerGetsTheRules(t *testing.T) { |
| 309 | shared := []string{ |
| 310 | "Never kill processes by a broad pattern", |
| 311 | "run `go vet ./...` or `go test ./...`, or build into $KLAUS_SCRATCH", |
| 312 | "**Intent:**", "**Decisions:**", "**Shape:**", "**What the implementation taught us:**", "**Checks:**", "**Diff summary:**", |
| 313 | } |
| 314 | // Taste (tests, carrying cost) is the house rules', not every worker's. |
| 315 | never := []string{"`go build ./...`", "Prefer integration and e2e tests", "end-to-end path", "re-prove upstream", "lifetime", "out of proportion"} |
| 316 | valleyFollowUp := []string{ |
| 317 | "Amend the change's head commit", |
| 318 | "end with a commit whose message describes the whole change", |
| 319 | "keep the head message accurate for the whole change", |
| 320 | "Push to the same branch with a lease on the head this run started from", |
| 321 | } |
| 322 | followUpScope := []string{ |
| 323 | "## Follow-up scope", |
| 324 | "Unless the brief says otherwise", |
| 325 | "Limit edits to the items in the brief, their tests, and sentences those changes make untrue.", |
| 326 | "needs new mechanism rather than a local change", |
| 327 | "Run one `klaus _pre-review` pass on the final head", |
| 328 | "state for each item in the brief whether it is closed and where", |
| 329 | "files and lines against the starting head", |
| 330 | } |
| 331 | custom := t.TempDir() |
| 332 | if err := os.MkdirAll(filepath.Join(custom, ".klaus"), 0o755); err != nil { |
| 333 | t.Fatal(err) |
| 334 | } |
| 335 | if err := os.WriteFile(filepath.Join(custom, ".klaus", "prompt.md"), []byte("House rules for {{.RunID}}.\n"), 0o644); err != nil { |
| 336 | t.Fatal(err) |
| 337 | } |
| 338 | if err := os.WriteFile(filepath.Join(custom, ".klaus", "pr-fix-prompt.md"), []byte("Custom PR fix for #{{.PR}} ({{.RunID}}).\n"), 0o644); err != nil { |
| 339 | t.Fatal(err) |
| 340 | } |
| 341 | head := strings.Repeat("a", 40) |
| 342 | valley := PromptVars{RunID: "r", Branch: "b", DirectPush: true, Change: "kkkk", Valley: true, Head: head} |
| 343 | for _, tc := range []struct { |
| 344 | name string |
| 345 | dir string |
| 346 | vars PromptVars |
| 347 | want, absent []string |
| 348 | }{ |
| 349 | {"plain", t.TempDir(), PromptVars{RunID: "r", Branch: "b"}, |
| 350 | nil, append(append([]string{}, valleyFollowUp...), followUpScope...)}, |
| 351 | {"plain direct push", t.TempDir(), PromptVars{RunID: "r", Branch: "b", DirectPush: true}, |
| 352 | nil, append(append([]string{}, valleyFollowUp...), followUpScope...)}, |
| 353 | {"plain custom template", custom, PromptVars{RunID: "r", Branch: "b", DirectPush: true}, |
| 354 | []string{"House rules for r.", "## Delivery"}, append(append([]string{}, valleyFollowUp...), followUpScope...)}, |
| 355 | {"--pr", t.TempDir(), PromptVars{RunID: "r", Branch: "b", PR: "7", Head: head}, |
| 356 | append([]string{"## Delivery", "You are continuing PR #7 on branch b", "`git diff --stat " + head + " HEAD`"}, followUpScope...), |
| 357 | valleyFollowUp}, |
| 358 | {"--pr overridden template", custom, PromptVars{RunID: "r", Branch: "b", PR: "7", Head: head}, |
| 359 | append([]string{"Custom PR fix for #7 (r).", "## Delivery", "`git diff --stat " + head + " HEAD`"}, followUpScope...), |
| 360 | valleyFollowUp}, |
| 361 | {"--change on a valley", t.TempDir(), valley, |
| 362 | append(append([]string{"5. Push your branch: as the Delivery section below directs", "`git diff --stat " + head + " HEAD`"}, valleyFollowUp...), followUpScope...), |
| 363 | []string{"push fast-forward", "git push -u origin HEAD"}}, |
| 364 | {"--change on GitHub", t.TempDir(), PromptVars{RunID: "r", Branch: "b", Change: "kkkk"}, |
| 365 | append([]string{"push fast-forward to the same branch and open the PR from it"}, followUpScope...), |
| 366 | append([]string{"git push -u origin HEAD", "git diff --stat"}, valleyFollowUp...)}, |
| 367 | {"--change overridden template", custom, valley, |
| 368 | append(append([]string{"House rules for r.", "## Delivery", |
| 369 | "--force-with-lease=refs/heads/b:" + head + " origin HEAD:refs/heads/b"}, valleyFollowUp...), followUpScope...), |
| 370 | []string{"git push -u origin HEAD"}}, |
| 371 | } { |
| 372 | t.Run(tc.name, func(t *testing.T) { |
| 373 | prompt, err := RenderWorkerPrompt(tc.dir, tc.vars) |
| 374 | if err != nil { |
| 375 | t.Fatal(err) |
| 376 | } |
| 377 | for _, want := range append(shared, tc.want...) { |
| 378 | if !strings.Contains(prompt, want) { |
| 379 | t.Errorf("prompt missing %q:\n%s", want, prompt) |
| 380 | } |
| 381 | } |
| 382 | for _, absent := range append(never, tc.absent...) { |
| 383 | if strings.Contains(prompt, absent) { |
| 384 | t.Errorf("prompt should not contain %q:\n%s", absent, prompt) |
| 385 | } |
| 386 | } |
| 387 | }) |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | func TestPreTrustWorktree(t *testing.T) { |
| 392 | // Use a temp dir as both the worktree and the home dir |
| 393 | homeDir := t.TempDir() |
| 394 | worktreeDir := t.TempDir() |
| 395 | |
| 396 | t.Setenv("HOME", homeDir) |
| 397 | |
| 398 | if err := PreTrustWorktree(worktreeDir); err != nil { |
| 399 | t.Fatalf("PreTrustWorktree() error: %v", err) |
| 400 | } |
| 401 | |
| 402 | // Check that the project directory was created |
| 403 | encoded := strings.NewReplacer(string(filepath.Separator), "-", ".", "-").Replace(worktreeDir) |
| 404 | indexPath := filepath.Join(homeDir, ".claude", "projects", encoded, "sessions-index.json") |
| 405 | |
| 406 | data, err := os.ReadFile(indexPath) |
| 407 | if err != nil { |
| 408 | t.Fatalf("reading sessions-index.json: %v", err) |
| 409 | } |
| 410 | |
| 411 | var index map[string]any |
| 412 | if err := json.Unmarshal(data, &index); err != nil { |
| 413 | t.Fatalf("parsing sessions-index.json: %v", err) |
| 414 | } |
| 415 | |
| 416 | if v, ok := index["version"].(float64); !ok || v != 1 { |
| 417 | t.Errorf("version = %v, want 1", index["version"]) |
| 418 | } |
| 419 | if p, ok := index["originalPath"].(string); !ok || p != worktreeDir { |
| 420 | t.Errorf("originalPath = %v, want %s", index["originalPath"], worktreeDir) |
| 421 | } |
| 422 | |
| 423 | // Check that ~/.claude.json has the trust entry |
| 424 | claudeJSON := filepath.Join(homeDir, ".claude.json") |
| 425 | cdata, err := os.ReadFile(claudeJSON) |
| 426 | if err != nil { |
| 427 | t.Fatalf("reading ~/.claude.json: %v", err) |
| 428 | } |
| 429 | |
| 430 | var config map[string]any |
| 431 | if err := json.Unmarshal(cdata, &config); err != nil { |
| 432 | t.Fatalf("parsing ~/.claude.json: %v", err) |
| 433 | } |
| 434 | |
| 435 | projects, ok := config["projects"].(map[string]any) |
| 436 | if !ok { |
| 437 | t.Fatal("~/.claude.json missing projects key") |
| 438 | } |
| 439 | entry, ok := projects[worktreeDir].(map[string]any) |
| 440 | if !ok { |
| 441 | t.Fatalf("~/.claude.json missing project entry for %s", worktreeDir) |
| 442 | } |
| 443 | if trusted, ok := entry["hasTrustDialogAccepted"].(bool); !ok || !trusted { |
| 444 | t.Errorf("hasTrustDialogAccepted = %v, want true", entry["hasTrustDialogAccepted"]) |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | func TestPreTrustWorktreeDottedPath(t *testing.T) { |
| 449 | homeDir := t.TempDir() |
| 450 | t.Setenv("HOME", homeDir) |
| 451 | |
| 452 | // Create a worktree path with dot-prefixed components like .klaus session workspaces |
| 453 | worktreeDir := filepath.Join(t.TempDir(), ".klaus", "sessions", "run-123") |
| 454 | if err := os.MkdirAll(worktreeDir, 0o755); err != nil { |
| 455 | t.Fatalf("creating worktree dir: %v", err) |
| 456 | } |
| 457 | |
| 458 | if err := PreTrustWorktree(worktreeDir); err != nil { |
| 459 | t.Fatalf("PreTrustWorktree() error: %v", err) |
| 460 | } |
| 461 | |
| 462 | // Dots should be replaced with hyphens, matching Claude Code's encoding |
| 463 | encoded := strings.NewReplacer(string(filepath.Separator), "-", ".", "-").Replace(worktreeDir) |
| 464 | indexPath := filepath.Join(homeDir, ".claude", "projects", encoded, "sessions-index.json") |
| 465 | |
| 466 | data, err := os.ReadFile(indexPath) |
| 467 | if err != nil { |
| 468 | t.Fatalf("reading sessions-index.json: %v", err) |
| 469 | } |
| 470 | |
| 471 | var index map[string]any |
| 472 | if err := json.Unmarshal(data, &index); err != nil { |
| 473 | t.Fatalf("parsing sessions-index.json: %v", err) |
| 474 | } |
| 475 | |
| 476 | if p, ok := index["originalPath"].(string); !ok || p != worktreeDir { |
| 477 | t.Errorf("originalPath = %v, want %s", index["originalPath"], worktreeDir) |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | func TestPreTrustWorktreeUsesConfigJSON(t *testing.T) { |
| 482 | homeDir := t.TempDir() |
| 483 | worktreeDir := t.TempDir() |
| 484 | t.Setenv("HOME", homeDir) |
| 485 | |
| 486 | // Create ~/.claude/.config.json so PreTrustWorktree prefers it |
| 487 | claudeDir := filepath.Join(homeDir, ".claude") |
| 488 | os.MkdirAll(claudeDir, 0o755) |
| 489 | existing := map[string]any{"someKey": "someValue", "projects": map[string]any{}} |
| 490 | data, _ := json.Marshal(existing) |
| 491 | os.WriteFile(filepath.Join(claudeDir, ".config.json"), data, 0o644) |
| 492 | |
| 493 | if err := PreTrustWorktree(worktreeDir); err != nil { |
| 494 | t.Fatalf("PreTrustWorktree() error: %v", err) |
| 495 | } |
| 496 | |
| 497 | // Should have written to .config.json, not .claude.json |
| 498 | cdata, err := os.ReadFile(filepath.Join(claudeDir, ".config.json")) |
| 499 | if err != nil { |
| 500 | t.Fatalf("reading .config.json: %v", err) |
| 501 | } |
| 502 | var config map[string]any |
| 503 | if err := json.Unmarshal(cdata, &config); err != nil { |
| 504 | t.Fatalf("parsing .config.json: %v", err) |
| 505 | } |
| 506 | |
| 507 | // Existing keys should be preserved |
| 508 | if config["someKey"] != "someValue" { |
| 509 | t.Error("existing keys in .config.json should be preserved") |
| 510 | } |
| 511 | |
| 512 | projects := config["projects"].(map[string]any) |
| 513 | entry := projects[worktreeDir].(map[string]any) |
| 514 | if trusted, ok := entry["hasTrustDialogAccepted"].(bool); !ok || !trusted { |
| 515 | t.Errorf("hasTrustDialogAccepted = %v, want true", entry["hasTrustDialogAccepted"]) |
| 516 | } |
| 517 | |
| 518 | // ~/.claude.json should NOT have been created |
| 519 | if _, err := os.Stat(filepath.Join(homeDir, ".claude.json")); err == nil { |
| 520 | t.Error("~/.claude.json should not exist when .config.json is used") |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | func TestPreTrustWorktreePreservesExistingEntry(t *testing.T) { |
| 525 | homeDir := t.TempDir() |
| 526 | worktreeDir := t.TempDir() |
| 527 | t.Setenv("HOME", homeDir) |
| 528 | |
| 529 | // Pre-populate ~/.claude.json with an existing project entry |
| 530 | existing := map[string]any{ |
| 531 | "projects": map[string]any{ |
| 532 | worktreeDir: map[string]any{ |
| 533 | "allowedTools": []any{"tool1"}, |
| 534 | "mcpServers": map[string]any{}, |
| 535 | }, |
| 536 | }, |
| 537 | } |
| 538 | data, _ := json.MarshalIndent(existing, "", " ") |
| 539 | os.WriteFile(filepath.Join(homeDir, ".claude.json"), data, 0o644) |
| 540 | |
| 541 | if err := PreTrustWorktree(worktreeDir); err != nil { |
| 542 | t.Fatalf("PreTrustWorktree() error: %v", err) |
| 543 | } |
| 544 | |
| 545 | cdata, err := os.ReadFile(filepath.Join(homeDir, ".claude.json")) |
| 546 | if err != nil { |
| 547 | t.Fatalf("reading config file: %v", err) |
| 548 | } |
| 549 | var config map[string]any |
| 550 | if err := json.Unmarshal(cdata, &config); err != nil { |
| 551 | t.Fatalf("unmarshaling config: %v", err) |
| 552 | } |
| 553 | projects := config["projects"].(map[string]any) |
| 554 | entry := projects[worktreeDir].(map[string]any) |
| 555 | |
| 556 | // Existing fields should be preserved |
| 557 | if tools, ok := entry["allowedTools"].([]any); !ok || len(tools) != 1 { |
| 558 | t.Error("existing allowedTools should be preserved") |
| 559 | } |
| 560 | if trusted, ok := entry["hasTrustDialogAccepted"].(bool); !ok || !trusted { |
| 561 | t.Error("hasTrustDialogAccepted should be true") |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | func TestPreTrustWorktreeIdempotent(t *testing.T) { |
| 566 | homeDir := t.TempDir() |
| 567 | worktreeDir := t.TempDir() |
| 568 | |
| 569 | t.Setenv("HOME", homeDir) |
| 570 | |
| 571 | // Call twice โ second call should not error |
| 572 | if err := PreTrustWorktree(worktreeDir); err != nil { |
| 573 | t.Fatalf("first PreTrustWorktree() error: %v", err) |
| 574 | } |
| 575 | if err := PreTrustWorktree(worktreeDir); err != nil { |
| 576 | t.Fatalf("second PreTrustWorktree() error: %v", err) |
| 577 | } |
| 578 | } |
| 579 | |
| 580 | func TestInit(t *testing.T) { |
| 581 | dir := t.TempDir() |
| 582 | |
| 583 | if _, _, err := Init(dir); err != nil { |
| 584 | t.Fatalf("Init() error: %v", err) |
| 585 | } |
| 586 | |
| 587 | // Verify config.json exists and is valid |
| 588 | configPath := filepath.Join(dir, ".klaus", "config.json") |
| 589 | data, err := os.ReadFile(configPath) |
| 590 | if err != nil { |
| 591 | t.Fatalf("reading config: %v", err) |
| 592 | } |
| 593 | var cfg Config |
| 594 | if err := json.Unmarshal(data, &cfg); err != nil { |
| 595 | t.Fatalf("parsing config: %v", err) |
| 596 | } |
| 597 | if cfg.WorktreeBase != wantWorktreeBase { |
| 598 | t.Errorf("config WorktreeBase = %q, want %q", cfg.WorktreeBase, wantWorktreeBase) |
| 599 | } |
| 600 | |
| 601 | // Verify prompt.md exists |
| 602 | promptPath := filepath.Join(dir, ".klaus", "prompt.md") |
| 603 | promptData, err := os.ReadFile(promptPath) |
| 604 | if err != nil { |
| 605 | t.Fatalf("reading prompt: %v", err) |
| 606 | } |
| 607 | if !strings.Contains(string(promptData), "{{.RunID}}") { |
| 608 | t.Error("prompt template should contain {{.RunID}}") |
| 609 | } |
| 610 | } |
| 611 | |
| 612 | func TestLoadEmptyRepoRoot(t *testing.T) { |
| 613 | // When repoRoot is empty, Load should return defaults (plus any global config) |
| 614 | cfg, err := Load("") |
| 615 | if err != nil { |
| 616 | t.Fatalf("Load(\"\") error: %v", err) |
| 617 | } |
| 618 | // Should have valid defaults |
| 619 | if cfg.DefaultBudget == "" { |
| 620 | t.Error("DefaultBudget should not be empty") |
| 621 | } |
| 622 | if cfg.DefaultBranch == "" { |
| 623 | t.Error("DefaultBranch should not be empty") |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | func TestLoadEmptyRepoRootWithGlobalWebhook(t *testing.T) { |
| 628 | // Simulate a global config with webhook settings by temporarily overriding HOME. |
| 629 | home := t.TempDir() |
| 630 | t.Setenv("HOME", home) |
| 631 | |
| 632 | klausDir := filepath.Join(home, ".klaus") |
| 633 | if err := os.MkdirAll(klausDir, 0o755); err != nil { |
| 634 | t.Fatal(err) |
| 635 | } |
| 636 | cfgJSON := `{"webhook": {"port": 9800, "path": "/hook"}}` |
| 637 | if err := os.WriteFile(filepath.Join(klausDir, "config.json"), []byte(cfgJSON), 0o644); err != nil { |
| 638 | t.Fatal(err) |
| 639 | } |
| 640 | |
| 641 | cfg, err := Load("") |
| 642 | if err != nil { |
| 643 | t.Fatalf("Load(\"\") error: %v", err) |
| 644 | } |
| 645 | if cfg.Webhook == nil { |
| 646 | t.Fatal("expected Webhook config to be loaded from global config, got nil") |
| 647 | } |
| 648 | if cfg.Webhook.Port != 9800 { |
| 649 | t.Errorf("Webhook.Port = %d, want 9800", cfg.Webhook.Port) |
| 650 | } |
| 651 | if cfg.Webhook.Path != "/hook" { |
| 652 | t.Errorf("Webhook.Path = %q, want %q", cfg.Webhook.Path, "/hook") |
| 653 | } |
| 654 | } |
| 655 | |
| 656 | func TestRenderSessionPromptNoRepo(t *testing.T) { |
| 657 | // When RepoName is empty, the no-repo variant of the session prompt is rendered |
| 658 | vars := PromptVars{ |
| 659 | RunID: "session-20260307-1430-a3f2", |
| 660 | } |
| 661 | |
| 662 | prompt, err := RenderSessionPrompt("", vars) |
| 663 | if err != nil { |
| 664 | t.Fatalf("RenderSessionPrompt() error: %v", err) |
| 665 | } |
| 666 | |
| 667 | if !strings.Contains(prompt, "session-20260307-1430-a3f2") { |
| 668 | t.Error("prompt should contain session ID") |
| 669 | } |
| 670 | if !strings.Contains(prompt, "scratch workspace") { |
| 671 | t.Error("prompt should mention scratch workspace when no repo") |
| 672 | } |
| 673 | if !strings.Contains(prompt, "--repo owner/repo") { |
| 674 | t.Error("prompt should mention --repo flag when no repo") |
| 675 | } |
| 676 | if strings.Contains(prompt, "isolated git worktree on branch") { |
| 677 | t.Error("prompt should not mention git worktree when no repo") |
| 678 | } |
| 679 | } |
| 680 | |
| 681 | func TestRenderSessionPromptWithRepo(t *testing.T) { |
| 682 | dir := t.TempDir() |
| 683 | vars := PromptVars{ |
| 684 | RunID: "session-20260307-1430-a3f2", |
| 685 | Branch: "session/session-20260307-1430-a3f2", |
| 686 | RepoName: "my-project", |
| 687 | } |
| 688 | |
| 689 | prompt, err := RenderSessionPrompt(dir, vars) |
| 690 | if err != nil { |
| 691 | t.Fatalf("RenderSessionPrompt() error: %v", err) |
| 692 | } |
| 693 | |
| 694 | if !strings.Contains(prompt, "isolated git worktree on branch") { |
| 695 | t.Error("prompt should mention git worktree when in a repo") |
| 696 | } |
| 697 | if !strings.Contains(prompt, "my-project") { |
| 698 | t.Error("prompt should contain repo name") |
| 699 | } |
| 700 | if strings.Contains(prompt, "scratch workspace") { |
| 701 | t.Error("prompt should not mention scratch workspace when in a repo") |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | func TestRenderSessionPromptWithProjects(t *testing.T) { |
| 706 | dir := t.TempDir() |
| 707 | |
| 708 | vars := PromptVars{ |
| 709 | RunID: "session-test", |
| 710 | Branch: "session/session-test", |
| 711 | RepoName: "test-repo", |
| 712 | Projects: "- klaus (/home/user/src/klaus)\n- other-project (/home/user/src/other-project)", |
| 713 | } |
| 714 | |
| 715 | prompt, err := RenderSessionPrompt(dir, vars) |
| 716 | if err != nil { |
| 717 | t.Fatalf("RenderSessionPrompt() error: %v", err) |
| 718 | } |
| 719 | |
| 720 | if !strings.Contains(prompt, "## Registered projects") { |
| 721 | t.Error("prompt should contain registered projects section when projects are present") |
| 722 | } |
| 723 | if !strings.Contains(prompt, "klaus (/home/user/src/klaus)") { |
| 724 | t.Error("prompt should contain project listing") |
| 725 | } |
| 726 | if !strings.Contains(prompt, "valley flow launch --repo <name>") { |
| 727 | t.Error("prompt should mention 'valley flow launch --repo <name>'") |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | func TestRenderSessionPromptWithoutProjects(t *testing.T) { |
| 732 | dir := t.TempDir() |
| 733 | |
| 734 | vars := PromptVars{ |
| 735 | RunID: "session-test", |
| 736 | Branch: "session/session-test", |
| 737 | RepoName: "test-repo", |
| 738 | } |
| 739 | |
| 740 | prompt, err := RenderSessionPrompt(dir, vars) |
| 741 | if err != nil { |
| 742 | t.Fatalf("RenderSessionPrompt() error: %v", err) |
| 743 | } |
| 744 | |
| 745 | if strings.Contains(prompt, "## Registered projects") { |
| 746 | t.Error("prompt should not contain registered projects section when no projects") |
| 747 | } |
| 748 | } |
| 749 | |
| 750 | func TestFormatProjectList(t *testing.T) { |
| 751 | t.Run("empty projects", func(t *testing.T) { |
| 752 | result := FormatProjectList(map[string]string{}, nil) |
| 753 | if result != "" { |
| 754 | t.Errorf("expected empty string for empty projects, got %q", result) |
| 755 | } |
| 756 | }) |
| 757 | |
| 758 | t.Run("nil projects", func(t *testing.T) { |
| 759 | result := FormatProjectList(nil, nil) |
| 760 | if result != "" { |
| 761 | t.Errorf("expected empty string for nil projects, got %q", result) |
| 762 | } |
| 763 | }) |
| 764 | |
| 765 | t.Run("single project no description", func(t *testing.T) { |
| 766 | result := FormatProjectList(map[string]string{ |
| 767 | "my-proj": "/tmp/my-proj", |
| 768 | }, nil) |
| 769 | if result != "- my-proj (/tmp/my-proj)" { |
| 770 | t.Errorf("unexpected format: %q", result) |
| 771 | } |
| 772 | }) |
| 773 | |
| 774 | t.Run("multiple projects sorted", func(t *testing.T) { |
| 775 | result := FormatProjectList(map[string]string{ |
| 776 | "zebra": "/tmp/zebra", |
| 777 | "alpha": "/tmp/alpha", |
| 778 | }, nil) |
| 779 | lines := strings.Split(result, "\n") |
| 780 | if len(lines) != 2 { |
| 781 | t.Fatalf("expected 2 lines, got %d: %q", len(lines), result) |
| 782 | } |
| 783 | if !strings.HasPrefix(lines[0], "- alpha") { |
| 784 | t.Errorf("expected first line to be alpha, got %q", lines[0]) |
| 785 | } |
| 786 | if !strings.HasPrefix(lines[1], "- zebra") { |
| 787 | t.Errorf("expected second line to be zebra, got %q", lines[1]) |
| 788 | } |
| 789 | }) |
| 790 | |
| 791 | t.Run("with description uses em dash", func(t *testing.T) { |
| 792 | result := FormatProjectList( |
| 793 | map[string]string{"my-proj": "/tmp/my-proj"}, |
| 794 | map[string]string{"my-proj": "Does the thing"}, |
| 795 | ) |
| 796 | want := "- my-proj (/tmp/my-proj) โ Does the thing" |
| 797 | if result != want { |
| 798 | t.Errorf("FormatProjectList = %q, want %q", result, want) |
| 799 | } |
| 800 | }) |
| 801 | |
| 802 | t.Run("description present for some projects", func(t *testing.T) { |
| 803 | result := FormatProjectList( |
| 804 | map[string]string{ |
| 805 | "alpha": "/tmp/alpha", |
| 806 | "zebra": "/tmp/zebra", |
| 807 | }, |
| 808 | map[string]string{"alpha": "First letter"}, |
| 809 | ) |
| 810 | lines := strings.Split(result, "\n") |
| 811 | if len(lines) != 2 { |
| 812 | t.Fatalf("expected 2 lines, got %d: %q", len(lines), result) |
| 813 | } |
| 814 | if lines[0] != "- alpha (/tmp/alpha) โ First letter" { |
| 815 | t.Errorf("alpha line = %q", lines[0]) |
| 816 | } |
| 817 | if lines[1] != "- zebra (/tmp/zebra)" { |
| 818 | t.Errorf("zebra line = %q", lines[1]) |
| 819 | } |
| 820 | }) |
| 821 | } |
| 822 | |
| 823 | func TestRenderPromptEmptyRepoRoot(t *testing.T) { |
| 824 | // With empty repoRoot, should use default template |
| 825 | vars := PromptVars{RunID: "test-123"} |
| 826 | prompt, err := RenderPrompt("", vars) |
| 827 | if err != nil { |
| 828 | t.Fatalf("RenderPrompt(\"\") error: %v", err) |
| 829 | } |
| 830 | if !strings.Contains(prompt, "Run: test-123") { |
| 831 | t.Error("prompt should contain run ID from default template") |
| 832 | } |
| 833 | } |
| 834 | |
| 835 | func TestRequiresApprovalDefault(t *testing.T) { |
| 836 | cfg := Defaults() |
| 837 | if !cfg.RequiresApproval() { |
| 838 | t.Error("RequiresApproval() should default to true") |
| 839 | } |
| 840 | } |
| 841 | |
| 842 | func TestRequiresApprovalExplicit(t *testing.T) { |
| 843 | f := false |
| 844 | cfg := Config{RequireApproval: &f} |
| 845 | if cfg.RequiresApproval() { |
| 846 | t.Error("RequiresApproval() should return false when set to false") |
| 847 | } |
| 848 | |
| 849 | tr := true |
| 850 | cfg2 := Config{RequireApproval: &tr} |
| 851 | if !cfg2.RequiresApproval() { |
| 852 | t.Error("RequiresApproval() should return true when set to true") |
| 853 | } |
| 854 | } |
| 855 | |
| 856 | func TestAutoMergesOnApprovalDefault(t *testing.T) { |
| 857 | cfg := Defaults() |
| 858 | if cfg.AutoMergesOnApproval() { |
| 859 | t.Error("AutoMergesOnApproval() should default to false") |
| 860 | } |
| 861 | } |
| 862 | |
| 863 | func TestAutoMergesOnApprovalExplicit(t *testing.T) { |
| 864 | tr := true |
| 865 | cfg := Config{AutoMergeOnApproval: &tr} |
| 866 | if !cfg.AutoMergesOnApproval() { |
| 867 | t.Error("AutoMergesOnApproval() should return true when set to true") |
| 868 | } |
| 869 | } |
| 870 | |
| 871 | func TestLoadSandboxHostConfig(t *testing.T) { |
| 872 | dir := t.TempDir() |
| 873 | klausDir := filepath.Join(dir, ".klaus") |
| 874 | os.MkdirAll(klausDir, 0o755) |
| 875 | |
| 876 | os.WriteFile(filepath.Join(klausDir, "config.json"), |
| 877 | []byte(`{"sandbox_host": "klaus-worker-0"}`), 0o644) |
| 878 | |
| 879 | cfg, err := Load(dir) |
| 880 | if err != nil { |
| 881 | t.Fatalf("Load() error: %v", err) |
| 882 | } |
| 883 | if cfg.SandboxHost != "klaus-worker-0" { |
| 884 | t.Errorf("SandboxHost = %q, want %q", cfg.SandboxHost, "klaus-worker-0") |
| 885 | } |
| 886 | } |
| 887 | |
| 888 | func TestSandboxHostDefaultEmpty(t *testing.T) { |
| 889 | cfg := Defaults() |
| 890 | if cfg.SandboxHost != "" { |
| 891 | t.Errorf("SandboxHost default should be empty, got %q", cfg.SandboxHost) |
| 892 | } |
| 893 | } |
| 894 | |
| 895 | func TestLoadPRReviewerConfig(t *testing.T) { |
| 896 | dir := t.TempDir() |
| 897 | klausDir := filepath.Join(dir, ".klaus") |
| 898 | os.MkdirAll(klausDir, 0o755) |
| 899 | |
| 900 | os.WriteFile(filepath.Join(klausDir, "config.json"), |
| 901 | []byte(`{"pr_reviewer": "bob"}`), 0o644) |
| 902 | |
| 903 | cfg, err := Load(dir) |
| 904 | if err != nil { |
| 905 | t.Fatalf("Load() error: %v", err) |
| 906 | } |
| 907 | if cfg.PRReviewer != "bob" { |
| 908 | t.Errorf("PRReviewer = %q, want %q", cfg.PRReviewer, "bob") |
| 909 | } |
| 910 | } |
| 911 | |
| 912 | func TestRenderPromptWithReviewer(t *testing.T) { |
| 913 | dir := t.TempDir() |
| 914 | vars := PromptVars{ |
| 915 | RunID: "test-123", |
| 916 | Reviewer: "alice", |
| 917 | } |
| 918 | |
| 919 | prompt, err := RenderPrompt(dir, vars) |
| 920 | if err != nil { |
| 921 | t.Fatalf("RenderPrompt() error: %v", err) |
| 922 | } |
| 923 | |
| 924 | if !strings.Contains(prompt, "--reviewer alice") { |
| 925 | t.Error("prompt should contain --reviewer alice when reviewer is set") |
| 926 | } |
| 927 | } |
| 928 | |
| 929 | func TestRenderPromptWithoutReviewer(t *testing.T) { |
| 930 | dir := t.TempDir() |
| 931 | vars := PromptVars{ |
| 932 | RunID: "test-123", |
| 933 | } |
| 934 | |
| 935 | prompt, err := RenderPrompt(dir, vars) |
| 936 | if err != nil { |
| 937 | t.Fatalf("RenderPrompt() error: %v", err) |
| 938 | } |
| 939 | |
| 940 | if strings.Contains(prompt, "--reviewer") { |
| 941 | t.Error("prompt should not contain --reviewer when reviewer is empty") |
| 942 | } |
| 943 | } |
| 944 | |
| 945 | func TestLoadApprovalConfig(t *testing.T) { |
| 946 | dir := t.TempDir() |
| 947 | klausDir := filepath.Join(dir, ".klaus") |
| 948 | os.MkdirAll(klausDir, 0o755) |
| 949 | |
| 950 | os.WriteFile(filepath.Join(klausDir, "config.json"), |
| 951 | []byte(`{"require_approval": false, "auto_merge_on_approval": true}`), 0o644) |
| 952 | |
| 953 | cfg, err := Load(dir) |
| 954 | if err != nil { |
| 955 | t.Fatalf("Load() error: %v", err) |
| 956 | } |
| 957 | if cfg.RequiresApproval() { |
| 958 | t.Error("RequiresApproval() should be false from config") |
| 959 | } |
| 960 | if !cfg.AutoMergesOnApproval() { |
| 961 | t.Error("AutoMergesOnApproval() should be true from config") |
| 962 | } |
| 963 | } |
| 964 | |
| 965 | func TestInitGlobal(t *testing.T) { |
| 966 | homeDir := t.TempDir() |
| 967 | t.Setenv("HOME", homeDir) |
| 968 | |
| 969 | configPath, err := InitGlobal() |
| 970 | if err != nil { |
| 971 | t.Fatalf("InitGlobal() error: %v", err) |
| 972 | } |
| 973 | if want := filepath.Join(homeDir, ".klaus", "config.json"); configPath != want { |
| 974 | t.Errorf("InitGlobal() wrote %s, want %s", configPath, want) |
| 975 | } |
| 976 | data, err := os.ReadFile(configPath) |
| 977 | if err != nil { |
| 978 | t.Fatalf("reading global config: %v", err) |
| 979 | } |
| 980 | |
| 981 | var cfg Config |
| 982 | if err := json.Unmarshal(data, &cfg); err != nil { |
| 983 | t.Fatalf("parsing global config: %v", err) |
| 984 | } |
| 985 | if cfg.WorktreeBase != wantWorktreeBase { |
| 986 | t.Errorf("config WorktreeBase = %q, want %q", cfg.WorktreeBase, wantWorktreeBase) |
| 987 | } |
| 988 | if cfg.DefaultBudget != "5.00" { |
| 989 | t.Errorf("config DefaultBudget = %q, want 5.00", cfg.DefaultBudget) |
| 990 | } |
| 991 | } |
| 992 | |
| 993 | func TestLinkSharedMemory(t *testing.T) { |
| 994 | homeDir := t.TempDir() |
| 995 | worktreeDir := t.TempDir() |
| 996 | t.Setenv("HOME", homeDir) |
| 997 | t.Setenv("USERPROFILE", homeDir) |
| 998 | |
| 999 | if err := LinkSharedMemory(worktreeDir); err != nil { |
| 1000 | t.Fatalf("LinkSharedMemory() error: %v", err) |
| 1001 | } |
| 1002 | |
| 1003 | sharedDir := filepath.Join(homeDir, ".klaus", "memory") |
| 1004 | if fi, err := os.Stat(sharedDir); err != nil || !fi.IsDir() { |
| 1005 | t.Fatalf("shared memory dir not created: %v", err) |
| 1006 | } |
| 1007 | |
| 1008 | encoded := encodeProjectPath(worktreeDir) |
| 1009 | memoryPath := filepath.Join(homeDir, ".claude", "projects", encoded, "memory") |
| 1010 | target, err := os.Readlink(memoryPath) |
| 1011 | if err != nil { |
| 1012 | t.Fatalf("memory path is not a symlink: %v", err) |
| 1013 | } |
| 1014 | if target != sharedDir { |
| 1015 | t.Errorf("symlink target = %q, want %q", target, sharedDir) |
| 1016 | } |
| 1017 | |
| 1018 | // Writing through the symlink lands in the shared dir |
| 1019 | if err := os.WriteFile(filepath.Join(memoryPath, "fact.md"), []byte("fact"), 0o644); err != nil { |
| 1020 | t.Fatalf("writing through symlink: %v", err) |
| 1021 | } |
| 1022 | if _, err := os.Stat(filepath.Join(sharedDir, "fact.md")); err != nil { |
| 1023 | t.Errorf("file written through symlink not in shared dir: %v", err) |
| 1024 | } |
| 1025 | } |
| 1026 | |
| 1027 | func TestLinkSharedMemoryIdempotent(t *testing.T) { |
| 1028 | homeDir := t.TempDir() |
| 1029 | worktreeDir := t.TempDir() |
| 1030 | t.Setenv("HOME", homeDir) |
| 1031 | t.Setenv("USERPROFILE", homeDir) |
| 1032 | |
| 1033 | if err := LinkSharedMemory(worktreeDir); err != nil { |
| 1034 | t.Fatalf("first LinkSharedMemory() error: %v", err) |
| 1035 | } |
| 1036 | if err := LinkSharedMemory(worktreeDir); err != nil { |
| 1037 | t.Fatalf("second LinkSharedMemory() error: %v", err) |
| 1038 | } |
| 1039 | |
| 1040 | sharedDir := filepath.Join(homeDir, ".klaus", "memory") |
| 1041 | encoded := encodeProjectPath(worktreeDir) |
| 1042 | memoryPath := filepath.Join(homeDir, ".claude", "projects", encoded, "memory") |
| 1043 | target, err := os.Readlink(memoryPath) |
| 1044 | if err != nil { |
| 1045 | t.Fatalf("memory path is not a symlink after re-link: %v", err) |
| 1046 | } |
| 1047 | if target != sharedDir { |
| 1048 | t.Errorf("symlink target = %q, want %q", target, sharedDir) |
| 1049 | } |
| 1050 | } |
| 1051 | |
| 1052 | func TestLinkSharedMemoryMigratesExistingDir(t *testing.T) { |
| 1053 | homeDir := t.TempDir() |
| 1054 | worktreeDir := t.TempDir() |
| 1055 | t.Setenv("HOME", homeDir) |
| 1056 | t.Setenv("USERPROFILE", homeDir) |
| 1057 | |
| 1058 | // Existing per-session memory dir with contents |
| 1059 | encoded := encodeProjectPath(worktreeDir) |
| 1060 | memoryPath := filepath.Join(homeDir, ".claude", "projects", encoded, "memory") |
| 1061 | if err := os.MkdirAll(memoryPath, 0o755); err != nil { |
| 1062 | t.Fatalf("creating old memory dir: %v", err) |
| 1063 | } |
| 1064 | os.WriteFile(filepath.Join(memoryPath, "MEMORY.md"), []byte("session index"), 0o644) |
| 1065 | os.WriteFile(filepath.Join(memoryPath, "fact.md"), []byte("session fact"), 0o644) |
| 1066 | os.WriteFile(filepath.Join(memoryPath, "collide.md"), []byte("session version"), 0o644) |
| 1067 | |
| 1068 | // Shared dir already has one colliding file |
| 1069 | sharedDir := filepath.Join(homeDir, ".klaus", "memory") |
| 1070 | if err := os.MkdirAll(sharedDir, 0o755); err != nil { |
| 1071 | t.Fatalf("creating shared dir: %v", err) |
| 1072 | } |
| 1073 | os.WriteFile(filepath.Join(sharedDir, "collide.md"), []byte("shared version"), 0o644) |
| 1074 | |
| 1075 | if err := LinkSharedMemory(worktreeDir); err != nil { |
| 1076 | t.Fatalf("LinkSharedMemory() error: %v", err) |
| 1077 | } |
| 1078 | |
| 1079 | // Non-colliding files migrated |
| 1080 | for name, want := range map[string]string{ |
| 1081 | "MEMORY.md": "session index", |
| 1082 | "fact.md": "session fact", |
| 1083 | "collide.md": "shared version", // existing shared file wins |
| 1084 | } { |
| 1085 | data, err := os.ReadFile(filepath.Join(sharedDir, name)) |
| 1086 | if err != nil { |
| 1087 | t.Fatalf("reading %s: %v", name, err) |
| 1088 | } |
| 1089 | if string(data) != want { |
| 1090 | t.Errorf("%s = %q, want %q", name, data, want) |
| 1091 | } |
| 1092 | } |
| 1093 | |
| 1094 | // Old dir replaced by symlink |
| 1095 | target, err := os.Readlink(memoryPath) |
| 1096 | if err != nil { |
| 1097 | t.Fatalf("memory path is not a symlink after migration: %v", err) |
| 1098 | } |
| 1099 | if target != sharedDir { |
| 1100 | t.Errorf("symlink target = %q, want %q", target, sharedDir) |
| 1101 | } |
| 1102 | } |
| 1103 | |
| 1104 | func TestLinkSharedMemoryDottedPath(t *testing.T) { |
| 1105 | homeDir := t.TempDir() |
| 1106 | t.Setenv("HOME", homeDir) |
| 1107 | t.Setenv("USERPROFILE", homeDir) |
| 1108 | |
| 1109 | worktreeDir := filepath.Join(t.TempDir(), ".klaus", "sessions", "session-123", "workspace") |
| 1110 | if err := os.MkdirAll(worktreeDir, 0o755); err != nil { |
| 1111 | t.Fatalf("creating worktree dir: %v", err) |
| 1112 | } |
| 1113 | |
| 1114 | if err := LinkSharedMemory(worktreeDir); err != nil { |
| 1115 | t.Fatalf("LinkSharedMemory() error: %v", err) |
| 1116 | } |
| 1117 | |
| 1118 | encoded := encodeProjectPath(worktreeDir) |
| 1119 | memoryPath := filepath.Join(homeDir, ".claude", "projects", encoded, "memory") |
| 1120 | if _, err := os.Readlink(memoryPath); err != nil { |
| 1121 | t.Fatalf("memory path for dotted worktree is not a symlink: %v", err) |
| 1122 | } |
| 1123 | } |
| 1124 | |
| 1125 | // forbidden_terms is private to the host: a repo's .klaus/config.json can |
| 1126 | // neither add to it nor empty an entry the host set. |
| 1127 | func TestLoadForbiddenTermsHostOnly(t *testing.T) { |
| 1128 | home := t.TempDir() |
| 1129 | t.Setenv("HOME", home) |
| 1130 | writeJSON := func(dir, data string) { |
| 1131 | t.Helper() |
| 1132 | if err := os.MkdirAll(filepath.Join(dir, ".klaus"), 0o755); err != nil { |
| 1133 | t.Fatal(err) |
| 1134 | } |
| 1135 | if err := os.WriteFile(filepath.Join(dir, ".klaus", "config.json"), []byte(data), 0o644); err != nil { |
| 1136 | t.Fatal(err) |
| 1137 | } |
| 1138 | } |
| 1139 | writeJSON(home, `{"forbidden_terms": {"example-project": {"terms": ["example-host"], "allow_paths": ["docs/hosts.md"]}}}`) |
| 1140 | repo := t.TempDir() |
| 1141 | writeJSON(repo, `{"default_branch": "trunk", "forbidden_terms": {"example-project": {"terms": []}, "acme/widget": {"terms": ["x"]}}}`) |
| 1142 | |
| 1143 | cfg, err := Load(repo) |
| 1144 | if err != nil { |
| 1145 | t.Fatalf("Load: %v", err) |
| 1146 | } |
| 1147 | if cfg.DefaultBranch != "trunk" { |
| 1148 | t.Errorf("DefaultBranch = %q, want the repo's trunk", cfg.DefaultBranch) |
| 1149 | } |
| 1150 | want := map[string]ForbiddenTermsConfig{"example-project": {Terms: []string{"example-host"}, AllowPaths: []string{"docs/hosts.md"}}} |
| 1151 | if !reflect.DeepEqual(cfg.ForbiddenTerms, want) { |
| 1152 | t.Errorf("ForbiddenTerms = %+v, want the host's %+v", cfg.ForbiddenTerms, want) |
| 1153 | } |
| 1154 | } |
| 1155 | |
| 1156 | // TestRestackPushQuotesTheBranch runs the push command a valley change's |
| 1157 | // prompt gives in a real shell, with git a function that prints its |
| 1158 | // arguments: a branch named with $(), ; and a quote reaches git as written |
| 1159 | // and runs nothing. |
| 1160 | func TestRestackPushQuotesTheBranch(t *testing.T) { |
| 1161 | dir := t.TempDir() |
| 1162 | head := strings.Repeat("a", 40) |
| 1163 | for _, branch := range []string{"add-a-greeting-1a2b3c4d", `x$(touch pwned);'y`} { |
| 1164 | prompt, err := RenderDelivery(PromptVars{RunID: "r", Branch: branch, DirectPush: true, Change: "kkkk", Valley: true, Head: head}) |
| 1165 | if err != nil { |
| 1166 | t.Fatal(err) |
| 1167 | } |
| 1168 | _, rest, _ := strings.Cut(prompt, "\n`git push ") |
| 1169 | line, _, _ := strings.Cut(rest, "`\n") |
| 1170 | cmd := exec.Command("sh", "-c", `git() { printf '%s\n' "$@"; }; git push `+line) |
| 1171 | cmd.Dir = dir |
| 1172 | out, err := cmd.Output() |
| 1173 | if err != nil { |
| 1174 | t.Fatalf("%s: running %q: %v", branch, line, err) |
| 1175 | } |
| 1176 | want := "push\n--force-with-lease=refs/heads/" + branch + ":" + head + "\norigin\nHEAD:refs/heads/" + branch + "\n" |
| 1177 | if string(out) != want { |
| 1178 | t.Errorf("git got %q, want %q", out, want) |
| 1179 | } |
| 1180 | if _, err := os.Stat(filepath.Join(dir, "pwned")); err == nil { |
| 1181 | t.Errorf("%s: the push command ran the branch name's $()", branch) |
| 1182 | } |
| 1183 | } |
| 1184 | } |
| 1185 | |
| 1186 | // The host and the repo config are each the file under .valley/flow when |
| 1187 | // one is there, else the .klaus one; a broken one there is an error, never |
| 1188 | // a fall back to the other. |
| 1189 | func TestLoadFindsConfigUnderEitherName(t *testing.T) { |
| 1190 | home, repo := t.TempDir(), t.TempDir() |
| 1191 | t.Setenv("HOME", home) |
| 1192 | writeFile := func(path, data string) { |
| 1193 | t.Helper() |
| 1194 | if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| 1195 | t.Fatal(err) |
| 1196 | } |
| 1197 | if err := os.WriteFile(path, []byte(data), 0o644); err != nil { |
| 1198 | t.Fatal(err) |
| 1199 | } |
| 1200 | } |
| 1201 | writeFile(filepath.Join(home, ".klaus", "config.json"), `{"default_budget": "1.00", "default_branch": "trunk"}`) |
| 1202 | writeFile(filepath.Join(home, ".valley", "flow", "config.json"), `{"default_budget": "2.00"}`) |
| 1203 | writeFile(filepath.Join(repo, ".klaus", "config.json"), `{"data_ref": "refs/old/data"}`) |
| 1204 | writeFile(filepath.Join(repo, ".valley", "flow", "config.json"), `{"data_ref": "refs/new/data"}`) |
| 1205 | |
| 1206 | cfg, err := Load(repo) |
| 1207 | if err != nil { |
| 1208 | t.Fatal(err) |
| 1209 | } |
| 1210 | if cfg.DefaultBudget != "2.00" || cfg.DefaultBranch != "main" || cfg.DataRef != "refs/new/data" { |
| 1211 | t.Errorf("Load read budget %q, branch %q, data ref %q; want each from the .valley/flow file alone", |
| 1212 | cfg.DefaultBudget, cfg.DefaultBranch, cfg.DataRef) |
| 1213 | } |
| 1214 | |
| 1215 | writeFile(filepath.Join(repo, ".valley", "flow", "config.json"), `{"data_ref": `) |
| 1216 | if _, err := Load(repo); err == nil || !strings.Contains(err.Error(), filepath.Join(".valley", "flow", "config.json")) { |
| 1217 | t.Errorf("Load with a malformed repo config under .valley/flow = %v, want its error", err) |
| 1218 | } |
| 1219 | writeFile(filepath.Join(home, ".valley", "flow", "config.json"), `{"default_budget": `) |
| 1220 | if _, err := Load(""); err == nil { |
| 1221 | t.Error("Load with a malformed host config under .valley/flow fell back") |
| 1222 | } |
| 1223 | } |
| 1224 | |
| 1225 | // init in a repo that keeps its config under .valley/flow writes it there, |
| 1226 | // and the prompt template, which it lacks, under .klaus. |
| 1227 | func TestInitBesideFlowConfig(t *testing.T) { |
| 1228 | t.Setenv("HOME", t.TempDir()) |
| 1229 | repo := t.TempDir() |
| 1230 | flowConfig := filepath.Join(repo, ".valley", "flow", "config.json") |
| 1231 | if err := os.MkdirAll(filepath.Dir(flowConfig), 0o755); err != nil { |
| 1232 | t.Fatal(err) |
| 1233 | } |
| 1234 | if err := os.WriteFile(flowConfig, []byte("{}"), 0o644); err != nil { |
| 1235 | t.Fatal(err) |
| 1236 | } |
| 1237 | configPath, promptPath, err := Init(repo) |
| 1238 | if err != nil { |
| 1239 | t.Fatalf("Init: %v", err) |
| 1240 | } |
| 1241 | if configPath != flowConfig || promptPath != filepath.Join(repo, ".klaus", "prompt.md") { |
| 1242 | t.Errorf("Init wrote %s and %s", configPath, promptPath) |
| 1243 | } |
| 1244 | } |
| 1245 | |
| 1246 | func TestNamingGenerationIsHostOnly(t *testing.T) { |
| 1247 | home, repo := t.TempDir(), t.TempDir() |
| 1248 | t.Setenv("HOME", home) |
| 1249 | for path, data := range map[string]string{ |
| 1250 | filepath.Join(home, ".klaus", "config.json"): `{"naming_generation": "bridge"}`, |
| 1251 | filepath.Join(repo, ".klaus", "config.json"): `{"naming_generation": "flow"}`, |
| 1252 | } { |
| 1253 | if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| 1254 | t.Fatal(err) |
| 1255 | } |
| 1256 | if err := os.WriteFile(path, []byte(data), 0o644); err != nil { |
| 1257 | t.Fatal(err) |
| 1258 | } |
| 1259 | } |
| 1260 | cfg, err := Load(repo) |
| 1261 | if err != nil { |
| 1262 | t.Fatal(err) |
| 1263 | } |
| 1264 | if cfg.Generation() != "bridge" { |
| 1265 | t.Errorf("Generation() = %q, want the host's bridge", cfg.Generation()) |
| 1266 | } |
| 1267 | |
| 1268 | if err := os.WriteFile(filepath.Join(home, ".klaus", "config.json"), []byte(`{"naming_generation": "w1"}`), 0o644); err != nil { |
| 1269 | t.Fatal(err) |
| 1270 | } |
| 1271 | if _, err := Load(""); err == nil || !strings.Contains(err.Error(), "w1") { |
| 1272 | t.Errorf("Load with naming_generation w1 = %v, want it refused", err) |
| 1273 | } |
| 1274 | } |
| 1275 | |
| 1276 | // With nothing under the flow names, a legacy file is read as flow always |
| 1277 | // read it: a host config that can't be read is skipped, and a repo config |
| 1278 | // that can't be read or parsed is an error but not a FlowFileError, which |
| 1279 | // a file under the flow names that can't be read is. |
| 1280 | func TestLoadReadsLegacyFilesAsBefore(t *testing.T) { |
| 1281 | home, repo := t.TempDir(), t.TempDir() |
| 1282 | t.Setenv("HOME", home) |
| 1283 | // A directory where the file is: unreadable as one, root included. |
| 1284 | for _, dir := range []string{filepath.Join(home, ".klaus", "config.json"), filepath.Join(repo, ".klaus")} { |
| 1285 | if err := os.MkdirAll(dir, 0o755); err != nil { |
| 1286 | t.Fatal(err) |
| 1287 | } |
| 1288 | } |
| 1289 | if cfg, err := Load(""); err != nil || cfg.DefaultBranch != Defaults().DefaultBranch { |
| 1290 | t.Errorf("Load with an unreadable legacy host config = %v; want the defaults", err) |
| 1291 | } |
| 1292 | if err := os.WriteFile(filepath.Join(repo, ".klaus", "config.json"), []byte("{"), 0o644); err != nil { |
| 1293 | t.Fatal(err) |
| 1294 | } |
| 1295 | var flowErr *FlowFileError |
| 1296 | if _, err := Load(repo); err == nil || errors.As(err, &flowErr) { |
| 1297 | t.Errorf("Load with a malformed legacy repo config = %v; want an error, not a FlowFileError", err) |
| 1298 | } |
| 1299 | |
| 1300 | if err := os.MkdirAll(filepath.Join(home, ".valley", "flow", "config.json"), 0o755); err != nil { |
| 1301 | t.Fatal(err) |
| 1302 | } |
| 1303 | if _, err := Load(""); !errors.As(err, &flowErr) { |
| 1304 | t.Errorf("Load with an unreadable host config under the flow names = %v; want a FlowFileError", err) |
| 1305 | } |
| 1306 | } |