gunk-dev/the-valley

config_test.go

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