gunk-dev/the-valley

config_test.go

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