gunk-dev/the-valley

config_test.go

source9ee95920e399main's published tip history
36.4 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 (RenderWorkerPrompt). The mechanics (build rule, process rule, final
303// report's headings) reach every kind, custom templates included, and the
304// taste rules are not among them; only a valley change's run is told to keep
305// the change's head message true to the whole change; and only a follow-up on
306// an existing change or PR gets the default follow-up scope rule.
307func TestEveryWorkerGetsTheRules(t *testing.T) {
308 shared := []string{
309 "Never kill processes by a broad pattern",
310 "run `go vet ./...` or `go test ./...`, or build into $KLAUS_SCRATCH",
311 "**Intent:**", "**Decisions:**", "**Shape:**", "**What the implementation taught us:**", "**Checks:**", "**Diff summary:**",
312 }
313 // Taste (tests, carrying cost) is the house rules', not every worker's.
314 never := []string{"`go build ./...`", "Prefer integration and e2e tests", "end-to-end path", "re-prove upstream", "lifetime", "out of proportion"}
315 valleyFollowUp := []string{
316 "Amend the change's head commit",
317 "end with a commit whose message describes the whole change",
318 "keep the head message accurate for the whole change",
319 "Push to the same branch with a lease on the head this run started from",
320 }
321 followUpScope := []string{
322 "## Follow-up scope",
323 "Unless the brief says otherwise",
324 "Limit edits to the items in the brief, their tests, and sentences those changes make untrue.",
325 "needs new mechanism rather than a local change",
326 "Run one `klaus _pre-review` pass on the final head",
327 "state for each item in the brief whether it is closed and where",
328 "files and lines against the starting head",
329 }
330 custom := t.TempDir()
331 if err := os.MkdirAll(filepath.Join(custom, ".klaus"), 0o755); err != nil {
332 t.Fatal(err)
333 }
334 if err := os.WriteFile(filepath.Join(custom, ".klaus", "prompt.md"), []byte("House rules for {{.RunID}}.\n"), 0o644); err != nil {
335 t.Fatal(err)
336 }
337 if err := os.WriteFile(filepath.Join(custom, ".klaus", "pr-fix-prompt.md"), []byte("Custom PR fix for #{{.PR}} ({{.RunID}}).\n"), 0o644); err != nil {
338 t.Fatal(err)
339 }
340 head := strings.Repeat("a", 40)
341 valley := PromptVars{RunID: "r", Branch: "b", DirectPush: true, Change: "kkkk", Valley: true, Head: head}
342 for _, tc := range []struct {
343 name string
344 dir string
345 vars PromptVars
346 want, absent []string
347 }{
348 {"plain", t.TempDir(), PromptVars{RunID: "r", Branch: "b"},
349 nil, append(append([]string{}, valleyFollowUp...), followUpScope...)},
350 {"plain direct push", t.TempDir(), PromptVars{RunID: "r", Branch: "b", DirectPush: true},
351 nil, append(append([]string{}, valleyFollowUp...), followUpScope...)},
352 {"plain custom template", custom, PromptVars{RunID: "r", Branch: "b", DirectPush: true},
353 []string{"House rules for r.", "## Delivery"}, append(append([]string{}, valleyFollowUp...), followUpScope...)},
354 {"--pr", t.TempDir(), PromptVars{RunID: "r", Branch: "b", PR: "7", Head: head},
355 append([]string{"## Delivery", "You are continuing PR #7 on branch b", "`git diff --stat " + head + " HEAD`"}, followUpScope...),
356 valleyFollowUp},
357 {"--pr overridden template", custom, PromptVars{RunID: "r", Branch: "b", PR: "7", Head: head},
358 append([]string{"Custom PR fix for #7 (r).", "## Delivery", "`git diff --stat " + head + " HEAD`"}, followUpScope...),
359 valleyFollowUp},
360 {"--change on a valley", t.TempDir(), valley,
361 append(append([]string{"5. Push your branch: as the Delivery section below directs", "`git diff --stat " + head + " HEAD`"}, valleyFollowUp...), followUpScope...),
362 []string{"push fast-forward", "git push -u origin HEAD"}},
363 {"--change on GitHub", t.TempDir(), PromptVars{RunID: "r", Branch: "b", Change: "kkkk"},
364 append([]string{"push fast-forward to the same branch and open the PR from it"}, followUpScope...),
365 append([]string{"git push -u origin HEAD", "git diff --stat"}, valleyFollowUp...)},
366 {"--change overridden template", custom, valley,
367 append(append([]string{"House rules for r.", "## Delivery",
368 "--force-with-lease=refs/heads/b:" + head + " origin HEAD:refs/heads/b"}, valleyFollowUp...), followUpScope...),
369 []string{"git push -u origin HEAD"}},
370 } {
371 t.Run(tc.name, func(t *testing.T) {
372 prompt, err := RenderWorkerPrompt(tc.dir, tc.vars)
373 if err != nil {
374 t.Fatal(err)
375 }
376 for _, want := range append(shared, tc.want...) {
377 if !strings.Contains(prompt, want) {
378 t.Errorf("prompt missing %q:\n%s", want, prompt)
379 }
380 }
381 for _, absent := range append(never, tc.absent...) {
382 if strings.Contains(prompt, absent) {
383 t.Errorf("prompt should not contain %q:\n%s", absent, prompt)
384 }
385 }
386 })
387 }
388}
389
390func TestPreTrustWorktree(t *testing.T) {
391 // Use a temp dir as both the worktree and the home dir
392 homeDir := t.TempDir()
393 worktreeDir := t.TempDir()
394
395 t.Setenv("HOME", homeDir)
396
397 if err := PreTrustWorktree(worktreeDir); err != nil {
398 t.Fatalf("PreTrustWorktree() error: %v", err)
399 }
400
401 // Check that the project directory was created
402 encoded := strings.NewReplacer(string(filepath.Separator), "-", ".", "-").Replace(worktreeDir)
403 indexPath := filepath.Join(homeDir, ".claude", "projects", encoded, "sessions-index.json")
404
405 data, err := os.ReadFile(indexPath)
406 if err != nil {
407 t.Fatalf("reading sessions-index.json: %v", err)
408 }
409
410 var index map[string]any
411 if err := json.Unmarshal(data, &index); err != nil {
412 t.Fatalf("parsing sessions-index.json: %v", err)
413 }
414
415 if v, ok := index["version"].(float64); !ok || v != 1 {
416 t.Errorf("version = %v, want 1", index["version"])
417 }
418 if p, ok := index["originalPath"].(string); !ok || p != worktreeDir {
419 t.Errorf("originalPath = %v, want %s", index["originalPath"], worktreeDir)
420 }
421
422 // Check that ~/.claude.json has the trust entry
423 claudeJSON := filepath.Join(homeDir, ".claude.json")
424 cdata, err := os.ReadFile(claudeJSON)
425 if err != nil {
426 t.Fatalf("reading ~/.claude.json: %v", err)
427 }
428
429 var config map[string]any
430 if err := json.Unmarshal(cdata, &config); err != nil {
431 t.Fatalf("parsing ~/.claude.json: %v", err)
432 }
433
434 projects, ok := config["projects"].(map[string]any)
435 if !ok {
436 t.Fatal("~/.claude.json missing projects key")
437 }
438 entry, ok := projects[worktreeDir].(map[string]any)
439 if !ok {
440 t.Fatalf("~/.claude.json missing project entry for %s", worktreeDir)
441 }
442 if trusted, ok := entry["hasTrustDialogAccepted"].(bool); !ok || !trusted {
443 t.Errorf("hasTrustDialogAccepted = %v, want true", entry["hasTrustDialogAccepted"])
444 }
445}
446
447func TestPreTrustWorktreeDottedPath(t *testing.T) {
448 homeDir := t.TempDir()
449 t.Setenv("HOME", homeDir)
450
451 // Create a worktree path with dot-prefixed components like .klaus session workspaces
452 worktreeDir := filepath.Join(t.TempDir(), ".klaus", "sessions", "run-123")
453 if err := os.MkdirAll(worktreeDir, 0o755); err != nil {
454 t.Fatalf("creating worktree dir: %v", err)
455 }
456
457 if err := PreTrustWorktree(worktreeDir); err != nil {
458 t.Fatalf("PreTrustWorktree() error: %v", err)
459 }
460
461 // Dots should be replaced with hyphens, matching Claude Code's encoding
462 encoded := strings.NewReplacer(string(filepath.Separator), "-", ".", "-").Replace(worktreeDir)
463 indexPath := filepath.Join(homeDir, ".claude", "projects", encoded, "sessions-index.json")
464
465 data, err := os.ReadFile(indexPath)
466 if err != nil {
467 t.Fatalf("reading sessions-index.json: %v", err)
468 }
469
470 var index map[string]any
471 if err := json.Unmarshal(data, &index); err != nil {
472 t.Fatalf("parsing sessions-index.json: %v", err)
473 }
474
475 if p, ok := index["originalPath"].(string); !ok || p != worktreeDir {
476 t.Errorf("originalPath = %v, want %s", index["originalPath"], worktreeDir)
477 }
478}
479
480func TestPreTrustWorktreeUsesConfigJSON(t *testing.T) {
481 homeDir := t.TempDir()
482 worktreeDir := t.TempDir()
483 t.Setenv("HOME", homeDir)
484
485 // Create ~/.claude/.config.json so PreTrustWorktree prefers it
486 claudeDir := filepath.Join(homeDir, ".claude")
487 os.MkdirAll(claudeDir, 0o755)
488 existing := map[string]any{"someKey": "someValue", "projects": map[string]any{}}
489 data, _ := json.Marshal(existing)
490 os.WriteFile(filepath.Join(claudeDir, ".config.json"), data, 0o644)
491
492 if err := PreTrustWorktree(worktreeDir); err != nil {
493 t.Fatalf("PreTrustWorktree() error: %v", err)
494 }
495
496 // Should have written to .config.json, not .claude.json
497 cdata, err := os.ReadFile(filepath.Join(claudeDir, ".config.json"))
498 if err != nil {
499 t.Fatalf("reading .config.json: %v", err)
500 }
501 var config map[string]any
502 if err := json.Unmarshal(cdata, &config); err != nil {
503 t.Fatalf("parsing .config.json: %v", err)
504 }
505
506 // Existing keys should be preserved
507 if config["someKey"] != "someValue" {
508 t.Error("existing keys in .config.json should be preserved")
509 }
510
511 projects := config["projects"].(map[string]any)
512 entry := projects[worktreeDir].(map[string]any)
513 if trusted, ok := entry["hasTrustDialogAccepted"].(bool); !ok || !trusted {
514 t.Errorf("hasTrustDialogAccepted = %v, want true", entry["hasTrustDialogAccepted"])
515 }
516
517 // ~/.claude.json should NOT have been created
518 if _, err := os.Stat(filepath.Join(homeDir, ".claude.json")); err == nil {
519 t.Error("~/.claude.json should not exist when .config.json is used")
520 }
521}
522
523func TestPreTrustWorktreePreservesExistingEntry(t *testing.T) {
524 homeDir := t.TempDir()
525 worktreeDir := t.TempDir()
526 t.Setenv("HOME", homeDir)
527
528 // Pre-populate ~/.claude.json with an existing project entry
529 existing := map[string]any{
530 "projects": map[string]any{
531 worktreeDir: map[string]any{
532 "allowedTools": []any{"tool1"},
533 "mcpServers": map[string]any{},
534 },
535 },
536 }
537 data, _ := json.MarshalIndent(existing, "", " ")
538 os.WriteFile(filepath.Join(homeDir, ".claude.json"), data, 0o644)
539
540 if err := PreTrustWorktree(worktreeDir); err != nil {
541 t.Fatalf("PreTrustWorktree() error: %v", err)
542 }
543
544 cdata, err := os.ReadFile(filepath.Join(homeDir, ".claude.json"))
545 if err != nil {
546 t.Fatalf("reading config file: %v", err)
547 }
548 var config map[string]any
549 if err := json.Unmarshal(cdata, &config); err != nil {
550 t.Fatalf("unmarshaling config: %v", err)
551 }
552 projects := config["projects"].(map[string]any)
553 entry := projects[worktreeDir].(map[string]any)
554
555 // Existing fields should be preserved
556 if tools, ok := entry["allowedTools"].([]any); !ok || len(tools) != 1 {
557 t.Error("existing allowedTools should be preserved")
558 }
559 if trusted, ok := entry["hasTrustDialogAccepted"].(bool); !ok || !trusted {
560 t.Error("hasTrustDialogAccepted should be true")
561 }
562}
563
564func TestPreTrustWorktreeIdempotent(t *testing.T) {
565 homeDir := t.TempDir()
566 worktreeDir := t.TempDir()
567
568 t.Setenv("HOME", homeDir)
569
570 // Call twice โ€” second call should not error
571 if err := PreTrustWorktree(worktreeDir); err != nil {
572 t.Fatalf("first PreTrustWorktree() error: %v", err)
573 }
574 if err := PreTrustWorktree(worktreeDir); err != nil {
575 t.Fatalf("second PreTrustWorktree() error: %v", err)
576 }
577}
578
579func TestInit(t *testing.T) {
580 dir := t.TempDir()
581
582 if err := Init(dir); err != nil {
583 t.Fatalf("Init() error: %v", err)
584 }
585
586 // Verify config.json exists and is valid
587 configPath := filepath.Join(dir, ".klaus", "config.json")
588 data, err := os.ReadFile(configPath)
589 if err != nil {
590 t.Fatalf("reading config: %v", err)
591 }
592 var cfg Config
593 if err := json.Unmarshal(data, &cfg); err != nil {
594 t.Fatalf("parsing config: %v", err)
595 }
596 if cfg.WorktreeBase != wantWorktreeBase {
597 t.Errorf("config WorktreeBase = %q, want %q", cfg.WorktreeBase, wantWorktreeBase)
598 }
599
600 // Verify prompt.md exists
601 promptPath := filepath.Join(dir, ".klaus", "prompt.md")
602 promptData, err := os.ReadFile(promptPath)
603 if err != nil {
604 t.Fatalf("reading prompt: %v", err)
605 }
606 if !strings.Contains(string(promptData), "{{.RunID}}") {
607 t.Error("prompt template should contain {{.RunID}}")
608 }
609}
610
611func TestLoadEmptyRepoRoot(t *testing.T) {
612 // When repoRoot is empty, Load should return defaults (plus any global config)
613 cfg, err := Load("")
614 if err != nil {
615 t.Fatalf("Load(\"\") error: %v", err)
616 }
617 // Should have valid defaults
618 if cfg.DefaultBudget == "" {
619 t.Error("DefaultBudget should not be empty")
620 }
621 if cfg.DefaultBranch == "" {
622 t.Error("DefaultBranch should not be empty")
623 }
624}
625
626func TestLoadEmptyRepoRootWithGlobalWebhook(t *testing.T) {
627 // Simulate a global config with webhook settings by temporarily overriding HOME.
628 home := t.TempDir()
629 t.Setenv("HOME", home)
630
631 klausDir := filepath.Join(home, ".klaus")
632 if err := os.MkdirAll(klausDir, 0o755); err != nil {
633 t.Fatal(err)
634 }
635 cfgJSON := `{"webhook": {"port": 9800, "path": "/hook"}}`
636 if err := os.WriteFile(filepath.Join(klausDir, "config.json"), []byte(cfgJSON), 0o644); err != nil {
637 t.Fatal(err)
638 }
639
640 cfg, err := Load("")
641 if err != nil {
642 t.Fatalf("Load(\"\") error: %v", err)
643 }
644 if cfg.Webhook == nil {
645 t.Fatal("expected Webhook config to be loaded from global config, got nil")
646 }
647 if cfg.Webhook.Port != 9800 {
648 t.Errorf("Webhook.Port = %d, want 9800", cfg.Webhook.Port)
649 }
650 if cfg.Webhook.Path != "/hook" {
651 t.Errorf("Webhook.Path = %q, want %q", cfg.Webhook.Path, "/hook")
652 }
653}
654
655func TestRenderSessionPromptNoRepo(t *testing.T) {
656 // When RepoName is empty, the no-repo variant of the session prompt is rendered
657 vars := PromptVars{
658 RunID: "session-20260307-1430-a3f2",
659 }
660
661 prompt, err := RenderSessionPrompt("", vars)
662 if err != nil {
663 t.Fatalf("RenderSessionPrompt() error: %v", err)
664 }
665
666 if !strings.Contains(prompt, "session-20260307-1430-a3f2") {
667 t.Error("prompt should contain session ID")
668 }
669 if !strings.Contains(prompt, "scratch workspace") {
670 t.Error("prompt should mention scratch workspace when no repo")
671 }
672 if !strings.Contains(prompt, "--repo owner/repo") {
673 t.Error("prompt should mention --repo flag when no repo")
674 }
675 if strings.Contains(prompt, "isolated git worktree on branch") {
676 t.Error("prompt should not mention git worktree when no repo")
677 }
678}
679
680func TestRenderSessionPromptWithRepo(t *testing.T) {
681 dir := t.TempDir()
682 vars := PromptVars{
683 RunID: "session-20260307-1430-a3f2",
684 Branch: "session/session-20260307-1430-a3f2",
685 RepoName: "my-project",
686 }
687
688 prompt, err := RenderSessionPrompt(dir, vars)
689 if err != nil {
690 t.Fatalf("RenderSessionPrompt() error: %v", err)
691 }
692
693 if !strings.Contains(prompt, "isolated git worktree on branch") {
694 t.Error("prompt should mention git worktree when in a repo")
695 }
696 if !strings.Contains(prompt, "my-project") {
697 t.Error("prompt should contain repo name")
698 }
699 if strings.Contains(prompt, "scratch workspace") {
700 t.Error("prompt should not mention scratch workspace when in a repo")
701 }
702}
703
704func TestRenderSessionPromptWithProjects(t *testing.T) {
705 dir := t.TempDir()
706
707 vars := PromptVars{
708 RunID: "session-test",
709 Branch: "session/session-test",
710 RepoName: "test-repo",
711 Projects: "- klaus (/home/user/src/klaus)\n- other-project (/home/user/src/other-project)",
712 }
713
714 prompt, err := RenderSessionPrompt(dir, vars)
715 if err != nil {
716 t.Fatalf("RenderSessionPrompt() error: %v", err)
717 }
718
719 if !strings.Contains(prompt, "## Registered projects") {
720 t.Error("prompt should contain registered projects section when projects are present")
721 }
722 if !strings.Contains(prompt, "klaus (/home/user/src/klaus)") {
723 t.Error("prompt should contain project listing")
724 }
725 if !strings.Contains(prompt, "valley flow launch --repo <name>") {
726 t.Error("prompt should mention 'valley flow launch --repo <name>'")
727 }
728}
729
730func TestRenderSessionPromptWithoutProjects(t *testing.T) {
731 dir := t.TempDir()
732
733 vars := PromptVars{
734 RunID: "session-test",
735 Branch: "session/session-test",
736 RepoName: "test-repo",
737 }
738
739 prompt, err := RenderSessionPrompt(dir, vars)
740 if err != nil {
741 t.Fatalf("RenderSessionPrompt() error: %v", err)
742 }
743
744 if strings.Contains(prompt, "## Registered projects") {
745 t.Error("prompt should not contain registered projects section when no projects")
746 }
747}
748
749func TestFormatProjectList(t *testing.T) {
750 t.Run("empty projects", func(t *testing.T) {
751 result := FormatProjectList(map[string]string{}, nil)
752 if result != "" {
753 t.Errorf("expected empty string for empty projects, got %q", result)
754 }
755 })
756
757 t.Run("nil projects", func(t *testing.T) {
758 result := FormatProjectList(nil, nil)
759 if result != "" {
760 t.Errorf("expected empty string for nil projects, got %q", result)
761 }
762 })
763
764 t.Run("single project no description", func(t *testing.T) {
765 result := FormatProjectList(map[string]string{
766 "my-proj": "/tmp/my-proj",
767 }, nil)
768 if result != "- my-proj (/tmp/my-proj)" {
769 t.Errorf("unexpected format: %q", result)
770 }
771 })
772
773 t.Run("multiple projects sorted", func(t *testing.T) {
774 result := FormatProjectList(map[string]string{
775 "zebra": "/tmp/zebra",
776 "alpha": "/tmp/alpha",
777 }, nil)
778 lines := strings.Split(result, "\n")
779 if len(lines) != 2 {
780 t.Fatalf("expected 2 lines, got %d: %q", len(lines), result)
781 }
782 if !strings.HasPrefix(lines[0], "- alpha") {
783 t.Errorf("expected first line to be alpha, got %q", lines[0])
784 }
785 if !strings.HasPrefix(lines[1], "- zebra") {
786 t.Errorf("expected second line to be zebra, got %q", lines[1])
787 }
788 })
789
790 t.Run("with description uses em dash", func(t *testing.T) {
791 result := FormatProjectList(
792 map[string]string{"my-proj": "/tmp/my-proj"},
793 map[string]string{"my-proj": "Does the thing"},
794 )
795 want := "- my-proj (/tmp/my-proj) โ€” Does the thing"
796 if result != want {
797 t.Errorf("FormatProjectList = %q, want %q", result, want)
798 }
799 })
800
801 t.Run("description present for some projects", func(t *testing.T) {
802 result := FormatProjectList(
803 map[string]string{
804 "alpha": "/tmp/alpha",
805 "zebra": "/tmp/zebra",
806 },
807 map[string]string{"alpha": "First letter"},
808 )
809 lines := strings.Split(result, "\n")
810 if len(lines) != 2 {
811 t.Fatalf("expected 2 lines, got %d: %q", len(lines), result)
812 }
813 if lines[0] != "- alpha (/tmp/alpha) โ€” First letter" {
814 t.Errorf("alpha line = %q", lines[0])
815 }
816 if lines[1] != "- zebra (/tmp/zebra)" {
817 t.Errorf("zebra line = %q", lines[1])
818 }
819 })
820}
821
822func TestRenderPromptEmptyRepoRoot(t *testing.T) {
823 // With empty repoRoot, should use default template
824 vars := PromptVars{RunID: "test-123"}
825 prompt, err := RenderPrompt("", vars)
826 if err != nil {
827 t.Fatalf("RenderPrompt(\"\") error: %v", err)
828 }
829 if !strings.Contains(prompt, "Run: test-123") {
830 t.Error("prompt should contain run ID from default template")
831 }
832}
833
834func TestRequiresApprovalDefault(t *testing.T) {
835 cfg := Defaults()
836 if !cfg.RequiresApproval() {
837 t.Error("RequiresApproval() should default to true")
838 }
839}
840
841func TestRequiresApprovalExplicit(t *testing.T) {
842 f := false
843 cfg := Config{RequireApproval: &f}
844 if cfg.RequiresApproval() {
845 t.Error("RequiresApproval() should return false when set to false")
846 }
847
848 tr := true
849 cfg2 := Config{RequireApproval: &tr}
850 if !cfg2.RequiresApproval() {
851 t.Error("RequiresApproval() should return true when set to true")
852 }
853}
854
855func TestAutoMergesOnApprovalDefault(t *testing.T) {
856 cfg := Defaults()
857 if cfg.AutoMergesOnApproval() {
858 t.Error("AutoMergesOnApproval() should default to false")
859 }
860}
861
862func TestAutoMergesOnApprovalExplicit(t *testing.T) {
863 tr := true
864 cfg := Config{AutoMergeOnApproval: &tr}
865 if !cfg.AutoMergesOnApproval() {
866 t.Error("AutoMergesOnApproval() should return true when set to true")
867 }
868}
869
870func TestLoadSandboxHostConfig(t *testing.T) {
871 dir := t.TempDir()
872 klausDir := filepath.Join(dir, ".klaus")
873 os.MkdirAll(klausDir, 0o755)
874
875 os.WriteFile(filepath.Join(klausDir, "config.json"),
876 []byte(`{"sandbox_host": "klaus-worker-0"}`), 0o644)
877
878 cfg, err := Load(dir)
879 if err != nil {
880 t.Fatalf("Load() error: %v", err)
881 }
882 if cfg.SandboxHost != "klaus-worker-0" {
883 t.Errorf("SandboxHost = %q, want %q", cfg.SandboxHost, "klaus-worker-0")
884 }
885}
886
887func TestSandboxHostDefaultEmpty(t *testing.T) {
888 cfg := Defaults()
889 if cfg.SandboxHost != "" {
890 t.Errorf("SandboxHost default should be empty, got %q", cfg.SandboxHost)
891 }
892}
893
894func TestLoadPRReviewerConfig(t *testing.T) {
895 dir := t.TempDir()
896 klausDir := filepath.Join(dir, ".klaus")
897 os.MkdirAll(klausDir, 0o755)
898
899 os.WriteFile(filepath.Join(klausDir, "config.json"),
900 []byte(`{"pr_reviewer": "bob"}`), 0o644)
901
902 cfg, err := Load(dir)
903 if err != nil {
904 t.Fatalf("Load() error: %v", err)
905 }
906 if cfg.PRReviewer != "bob" {
907 t.Errorf("PRReviewer = %q, want %q", cfg.PRReviewer, "bob")
908 }
909}
910
911func TestRenderPromptWithReviewer(t *testing.T) {
912 dir := t.TempDir()
913 vars := PromptVars{
914 RunID: "test-123",
915 Reviewer: "alice",
916 }
917
918 prompt, err := RenderPrompt(dir, vars)
919 if err != nil {
920 t.Fatalf("RenderPrompt() error: %v", err)
921 }
922
923 if !strings.Contains(prompt, "--reviewer alice") {
924 t.Error("prompt should contain --reviewer alice when reviewer is set")
925 }
926}
927
928func TestRenderPromptWithoutReviewer(t *testing.T) {
929 dir := t.TempDir()
930 vars := PromptVars{
931 RunID: "test-123",
932 }
933
934 prompt, err := RenderPrompt(dir, vars)
935 if err != nil {
936 t.Fatalf("RenderPrompt() error: %v", err)
937 }
938
939 if strings.Contains(prompt, "--reviewer") {
940 t.Error("prompt should not contain --reviewer when reviewer is empty")
941 }
942}
943
944func TestLoadApprovalConfig(t *testing.T) {
945 dir := t.TempDir()
946 klausDir := filepath.Join(dir, ".klaus")
947 os.MkdirAll(klausDir, 0o755)
948
949 os.WriteFile(filepath.Join(klausDir, "config.json"),
950 []byte(`{"require_approval": false, "auto_merge_on_approval": true}`), 0o644)
951
952 cfg, err := Load(dir)
953 if err != nil {
954 t.Fatalf("Load() error: %v", err)
955 }
956 if cfg.RequiresApproval() {
957 t.Error("RequiresApproval() should be false from config")
958 }
959 if !cfg.AutoMergesOnApproval() {
960 t.Error("AutoMergesOnApproval() should be true from config")
961 }
962}
963
964func TestInitGlobal(t *testing.T) {
965 homeDir := t.TempDir()
966 t.Setenv("HOME", homeDir)
967
968 if err := InitGlobal(); err != nil {
969 t.Fatalf("InitGlobal() error: %v", err)
970 }
971
972 configPath := filepath.Join(homeDir, ".klaus", "config.json")
973 data, err := os.ReadFile(configPath)
974 if err != nil {
975 t.Fatalf("reading global config: %v", err)
976 }
977
978 var cfg Config
979 if err := json.Unmarshal(data, &cfg); err != nil {
980 t.Fatalf("parsing global config: %v", err)
981 }
982 if cfg.WorktreeBase != wantWorktreeBase {
983 t.Errorf("config WorktreeBase = %q, want %q", cfg.WorktreeBase, wantWorktreeBase)
984 }
985 if cfg.DefaultBudget != "5.00" {
986 t.Errorf("config DefaultBudget = %q, want 5.00", cfg.DefaultBudget)
987 }
988}
989
990func TestLinkSharedMemory(t *testing.T) {
991 homeDir := t.TempDir()
992 worktreeDir := t.TempDir()
993 t.Setenv("HOME", homeDir)
994 t.Setenv("USERPROFILE", homeDir)
995
996 if err := LinkSharedMemory(worktreeDir); err != nil {
997 t.Fatalf("LinkSharedMemory() error: %v", err)
998 }
999
1000 sharedDir := filepath.Join(homeDir, ".klaus", "memory")
1001 if fi, err := os.Stat(sharedDir); err != nil || !fi.IsDir() {
1002 t.Fatalf("shared memory dir not created: %v", err)
1003 }
1004
1005 encoded := encodeProjectPath(worktreeDir)
1006 memoryPath := filepath.Join(homeDir, ".claude", "projects", encoded, "memory")
1007 target, err := os.Readlink(memoryPath)
1008 if err != nil {
1009 t.Fatalf("memory path is not a symlink: %v", err)
1010 }
1011 if target != sharedDir {
1012 t.Errorf("symlink target = %q, want %q", target, sharedDir)
1013 }
1014
1015 // Writing through the symlink lands in the shared dir
1016 if err := os.WriteFile(filepath.Join(memoryPath, "fact.md"), []byte("fact"), 0o644); err != nil {
1017 t.Fatalf("writing through symlink: %v", err)
1018 }
1019 if _, err := os.Stat(filepath.Join(sharedDir, "fact.md")); err != nil {
1020 t.Errorf("file written through symlink not in shared dir: %v", err)
1021 }
1022}
1023
1024func TestLinkSharedMemoryIdempotent(t *testing.T) {
1025 homeDir := t.TempDir()
1026 worktreeDir := t.TempDir()
1027 t.Setenv("HOME", homeDir)
1028 t.Setenv("USERPROFILE", homeDir)
1029
1030 if err := LinkSharedMemory(worktreeDir); err != nil {
1031 t.Fatalf("first LinkSharedMemory() error: %v", err)
1032 }
1033 if err := LinkSharedMemory(worktreeDir); err != nil {
1034 t.Fatalf("second LinkSharedMemory() error: %v", err)
1035 }
1036
1037 sharedDir := filepath.Join(homeDir, ".klaus", "memory")
1038 encoded := encodeProjectPath(worktreeDir)
1039 memoryPath := filepath.Join(homeDir, ".claude", "projects", encoded, "memory")
1040 target, err := os.Readlink(memoryPath)
1041 if err != nil {
1042 t.Fatalf("memory path is not a symlink after re-link: %v", err)
1043 }
1044 if target != sharedDir {
1045 t.Errorf("symlink target = %q, want %q", target, sharedDir)
1046 }
1047}
1048
1049func TestLinkSharedMemoryMigratesExistingDir(t *testing.T) {
1050 homeDir := t.TempDir()
1051 worktreeDir := t.TempDir()
1052 t.Setenv("HOME", homeDir)
1053 t.Setenv("USERPROFILE", homeDir)
1054
1055 // Existing per-session memory dir with contents
1056 encoded := encodeProjectPath(worktreeDir)
1057 memoryPath := filepath.Join(homeDir, ".claude", "projects", encoded, "memory")
1058 if err := os.MkdirAll(memoryPath, 0o755); err != nil {
1059 t.Fatalf("creating old memory dir: %v", err)
1060 }
1061 os.WriteFile(filepath.Join(memoryPath, "MEMORY.md"), []byte("session index"), 0o644)
1062 os.WriteFile(filepath.Join(memoryPath, "fact.md"), []byte("session fact"), 0o644)
1063 os.WriteFile(filepath.Join(memoryPath, "collide.md"), []byte("session version"), 0o644)
1064
1065 // Shared dir already has one colliding file
1066 sharedDir := filepath.Join(homeDir, ".klaus", "memory")
1067 if err := os.MkdirAll(sharedDir, 0o755); err != nil {
1068 t.Fatalf("creating shared dir: %v", err)
1069 }
1070 os.WriteFile(filepath.Join(sharedDir, "collide.md"), []byte("shared version"), 0o644)
1071
1072 if err := LinkSharedMemory(worktreeDir); err != nil {
1073 t.Fatalf("LinkSharedMemory() error: %v", err)
1074 }
1075
1076 // Non-colliding files migrated
1077 for name, want := range map[string]string{
1078 "MEMORY.md": "session index",
1079 "fact.md": "session fact",
1080 "collide.md": "shared version", // existing shared file wins
1081 } {
1082 data, err := os.ReadFile(filepath.Join(sharedDir, name))
1083 if err != nil {
1084 t.Fatalf("reading %s: %v", name, err)
1085 }
1086 if string(data) != want {
1087 t.Errorf("%s = %q, want %q", name, data, want)
1088 }
1089 }
1090
1091 // Old dir replaced by symlink
1092 target, err := os.Readlink(memoryPath)
1093 if err != nil {
1094 t.Fatalf("memory path is not a symlink after migration: %v", err)
1095 }
1096 if target != sharedDir {
1097 t.Errorf("symlink target = %q, want %q", target, sharedDir)
1098 }
1099}
1100
1101func TestLinkSharedMemoryDottedPath(t *testing.T) {
1102 homeDir := t.TempDir()
1103 t.Setenv("HOME", homeDir)
1104 t.Setenv("USERPROFILE", homeDir)
1105
1106 worktreeDir := filepath.Join(t.TempDir(), ".klaus", "sessions", "session-123", "workspace")
1107 if err := os.MkdirAll(worktreeDir, 0o755); err != nil {
1108 t.Fatalf("creating worktree dir: %v", err)
1109 }
1110
1111 if err := LinkSharedMemory(worktreeDir); err != nil {
1112 t.Fatalf("LinkSharedMemory() error: %v", err)
1113 }
1114
1115 encoded := encodeProjectPath(worktreeDir)
1116 memoryPath := filepath.Join(homeDir, ".claude", "projects", encoded, "memory")
1117 if _, err := os.Readlink(memoryPath); err != nil {
1118 t.Fatalf("memory path for dotted worktree is not a symlink: %v", err)
1119 }
1120}
1121
1122// forbidden_terms is private to the host: a repo's .klaus/config.json can
1123// neither add to it nor empty an entry the host set.
1124func TestLoadForbiddenTermsHostOnly(t *testing.T) {
1125 home := t.TempDir()
1126 t.Setenv("HOME", home)
1127 writeJSON := func(dir, data string) {
1128 t.Helper()
1129 if err := os.MkdirAll(filepath.Join(dir, ".klaus"), 0o755); err != nil {
1130 t.Fatal(err)
1131 }
1132 if err := os.WriteFile(filepath.Join(dir, ".klaus", "config.json"), []byte(data), 0o644); err != nil {
1133 t.Fatal(err)
1134 }
1135 }
1136 writeJSON(home, `{"forbidden_terms": {"example-project": {"terms": ["example-host"], "allow_paths": ["docs/hosts.md"]}}}`)
1137 repo := t.TempDir()
1138 writeJSON(repo, `{"default_branch": "trunk", "forbidden_terms": {"example-project": {"terms": []}, "acme/widget": {"terms": ["x"]}}}`)
1139
1140 cfg, err := Load(repo)
1141 if err != nil {
1142 t.Fatalf("Load: %v", err)
1143 }
1144 if cfg.DefaultBranch != "trunk" {
1145 t.Errorf("DefaultBranch = %q, want the repo's trunk", cfg.DefaultBranch)
1146 }
1147 want := map[string]ForbiddenTermsConfig{"example-project": {Terms: []string{"example-host"}, AllowPaths: []string{"docs/hosts.md"}}}
1148 if !reflect.DeepEqual(cfg.ForbiddenTerms, want) {
1149 t.Errorf("ForbiddenTerms = %+v, want the host's %+v", cfg.ForbiddenTerms, want)
1150 }
1151}
1152
1153// TestRestackPushQuotesTheBranch runs the push command a valley change's
1154// prompt gives in a real shell, with git a function that prints its
1155// arguments: a branch named with $(), ; and a quote reaches git as written
1156// and runs nothing.
1157func TestRestackPushQuotesTheBranch(t *testing.T) {
1158 dir := t.TempDir()
1159 head := strings.Repeat("a", 40)
1160 for _, branch := range []string{"add-a-greeting-1a2b3c4d", `x$(touch pwned);'y`} {
1161 prompt, err := RenderDelivery(PromptVars{RunID: "r", Branch: branch, DirectPush: true, Change: "kkkk", Valley: true, Head: head})
1162 if err != nil {
1163 t.Fatal(err)
1164 }
1165 _, rest, _ := strings.Cut(prompt, "\n`git push ")
1166 line, _, _ := strings.Cut(rest, "`\n")
1167 cmd := exec.Command("sh", "-c", `git() { printf '%s\n' "$@"; }; git push `+line)
1168 cmd.Dir = dir
1169 out, err := cmd.Output()
1170 if err != nil {
1171 t.Fatalf("%s: running %q: %v", branch, line, err)
1172 }
1173 want := "push\n--force-with-lease=refs/heads/" + branch + ":" + head + "\norigin\nHEAD:refs/heads/" + branch + "\n"
1174 if string(out) != want {
1175 t.Errorf("git got %q, want %q", out, want)
1176 }
1177 if _, err := os.Stat(filepath.Join(dir, "pwned")); err == nil {
1178 t.Errorf("%s: the push command ran the branch name's $()", branch)
1179 }
1180 }
1181}