gunk-dev/the-valley

settings_test.go

source672eff5ffaecmain's published tip history
8.2 KiB
1//go:build e2e
2
3package e2e
4
5import (
6 "encoding/json"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "strings"
11 "testing"
12 "time"
13
14 "the-valley/flow/internal/run"
15)
16
17// claudeSettingsArg returns the value of the one --settings in argv, as the
18// fake claude recorded it, failing unless there is exactly one.
19func (h *Harness) claudeSettingsArg(argv string) string {
20 h.t.Helper()
21 args := strings.Split(argv, "\n")
22 var values []string
23 for i, a := range args {
24 if a == "--settings" && i+1 < len(args) {
25 values = append(values, args[i+1])
26 }
27 }
28 if len(values) != 1 {
29 h.t.Fatalf("claude should get exactly one --settings, got %q:\n%s", values, argv)
30 }
31 return values[0]
32}
33
34// claudeSettings is what claude's --settings carries.
35type claudeSettings struct {
36 Attribution struct {
37 Commit, PR *string
38 SessionURL *bool `json:"sessionUrl"`
39 }
40 StatusLine struct{ Type, Command string }
41}
42
43// assertAttributionOff checks that settings, as data, turns attribution off.
44func (h *Harness) assertAttributionOff(data []byte) claudeSettings {
45 h.t.Helper()
46 var settings claudeSettings
47 if err := json.Unmarshal(data, &settings); err != nil {
48 h.t.Fatalf("parsing --settings: %v\n%s", err, data)
49 }
50 if a := settings.Attribution; a.Commit == nil || *a.Commit != "" || a.PR == nil || *a.PR != "" || a.SessionURL == nil || *a.SessionURL {
51 h.t.Errorf("--settings should turn attribution off:\n%s", data)
52 }
53 return settings
54}
55
56// assertWorkerSettings checks that a worker's argv carries exactly one
57// --settings, the inline settings that turn attribution off.
58func (h *Harness) assertWorkerSettings(argv string) {
59 h.t.Helper()
60 h.assertAttributionOff([]byte(h.claudeSettingsArg(argv)))
61}
62
63// assertSettingsOutside checks that a coordinator's argv loads its one
64// --settings from a file outside dir that turns attribution off and carries
65// a status line naming repo.
66func (h *Harness) assertSettingsOutside(argv, dir, repo string) {
67 h.t.Helper()
68 path := h.claudeSettingsArg(argv)
69 if !filepath.IsAbs(path) {
70 h.t.Fatalf("claude should load --settings from a file, got %q:\n%s", path, argv)
71 }
72 if rel, err := filepath.Rel(dir, path); err != nil || !strings.HasPrefix(rel, "..") {
73 h.t.Errorf("--settings %s is inside the worktree %s", path, dir)
74 }
75 data, err := os.ReadFile(path)
76 if err != nil {
77 h.t.Fatalf("reading --settings file: %v", err)
78 }
79 settings := h.assertAttributionOff(data)
80 if settings.StatusLine.Type != "command" || !strings.Contains(settings.StatusLine.Command, repo) {
81 h.t.Errorf("the --settings file should carry a status line naming %s:\n%s", repo, data)
82 }
83}
84
85// assertCleanWorktree checks that klaus left nothing in dir for git to see,
86// and no .claude/ of its own.
87func (h *Harness) assertCleanWorktree(dir string) {
88 h.t.Helper()
89 if _, err := os.Stat(filepath.Join(dir, ".claude")); !os.IsNotExist(err) {
90 h.t.Errorf("klaus should write no .claude/ into %s (stat: %v)", dir, err)
91 }
92 if out := h.GitOutput(dir, "status", "--porcelain", "--untracked-files=all"); out != "" {
93 h.t.Errorf("git status in %s should be clean:\n%s", dir, out)
94 }
95}
96
97// TestWorkerSettingsStayOutOfTheWorktree launches a Claude worker in a valley
98// repo that neither tracks nor ignores .claude/. The worker gets no status
99// line, only the inline settings that turn attribution off, so its worktree
100// holds nothing git sees. The agent commits only its own file and pushes, as
101// run 20261016-1252-85a0e972's did; finalize then has nothing to salvage,
102// records the branch as pushed, and marks the change ready.
103func TestWorkerSettingsStayOutOfTheWorktree(t *testing.T) {
104 t.Parallel()
105 h := NewHarness(t)
106 h.installValleyStub()
107 h.joinValley()
108 if err := exec.Command("git", "-C", h.RepoDir, "check-ignore", "-q", ".claude/settings.json").Run(); err == nil {
109 t.Fatal("the sandbox repo must not ignore .claude/")
110 }
111 h.WriteDefaultClaudeOutput(`{"type":"result","subtype":"success","total_cost_usd":0.5,"duration_ms":1000,"session_id":"` + changeSession + `"}` + "\n")
112
113 st, _ := h.launchRun("add a health check endpoint")
114 h.WaitForClaudeStart(30 * time.Second)
115 h.assertCleanWorktree(st.Worktree)
116 h.assertWorkerSettings(h.ClaudeArgv())
117
118 if err := os.WriteFile(filepath.Join(st.Worktree, "health.go"), []byte("package health\n"), 0o644); err != nil {
119 t.Fatal(err)
120 }
121 h.git(st.Worktree, "add", "health.go")
122 h.git(st.Worktree, "commit", "-qm", "Add a health check")
123 h.git(st.Worktree, "push", "-q", "-u", "origin", "HEAD")
124 head := h.GitOutput(st.Worktree, "rev-parse", "HEAD")
125
126 st = h.finishRun(st.ID)
127 if st.NeedsAttention != nil {
128 t.Errorf("finalize should salvage nothing: %s", *st.NeedsAttention)
129 }
130 if tip := h.GitOutput(h.OriginDir, "rev-parse", "refs/heads/"+st.Branch); tip != head {
131 t.Errorf("origin's %s at %s (%s), want the agent's %s", st.Branch, tip,
132 h.GitOutput(h.OriginDir, "log", "-1", "--format=%s", tip), head)
133 }
134 if st.PushedBranch == nil || st.PushedSHA == nil {
135 t.Errorf("finalize should record %s as pushed at %s", st.Branch, head)
136 } else if *st.PushedBranch != st.Branch || *st.PushedSHA != head {
137 t.Errorf("pushed %s at %s, want %s at %s", *st.PushedBranch, *st.PushedSHA, st.Branch, head)
138 }
139 if calls := h.valleyCalls("ready"); len(calls) != 1 || st.Valley == nil || st.Valley.Handle != "nxvp" {
140 t.Errorf("finalize should mark the change ready: valley ready calls %q, recorded %+v", calls, st.Valley)
141 }
142}
143
144// TestLaunchLeavesARepoClaudeSettingsAlone launches a Claude worker in a repo
145// that tracks its own .claude/settings.json: the worktree's copy is left as
146// the repo has it, for Claude Code to load beneath klaus's inline settings.
147func TestLaunchLeavesARepoClaudeSettingsAlone(t *testing.T) {
148 t.Parallel()
149 h := NewHarness(t)
150 const repoSettings = `{"permissions":{"allow":["Bash(make:*)"]}}` + "\n"
151 if err := os.MkdirAll(filepath.Join(h.RepoDir, ".claude"), 0o755); err != nil {
152 t.Fatal(err)
153 }
154 if err := os.WriteFile(filepath.Join(h.RepoDir, ".claude", "settings.json"), []byte(repoSettings), 0o644); err != nil {
155 t.Fatal(err)
156 }
157 h.git(h.RepoDir, "add", ".claude/settings.json")
158 h.git(h.RepoDir, "commit", "-qm", "add claude settings")
159 h.git(h.RepoDir, "push", "-q", "origin", "main")
160
161 st, _ := h.launchRun("add a health check endpoint")
162 h.WaitForClaudeStart(30 * time.Second)
163 if got, err := os.ReadFile(filepath.Join(st.Worktree, ".claude", "settings.json")); err != nil || string(got) != repoSettings {
164 t.Errorf("the repo's .claude/settings.json = %q (%v), want it unmodified: %q", got, err, repoSettings)
165 }
166 if out := h.GitOutput(st.Worktree, "status", "--porcelain", "--untracked-files=all"); out != "" {
167 t.Errorf("git status should be clean:\n%s", out)
168 }
169 h.assertWorkerSettings(h.ClaudeArgv())
170 h.finishRun(st.ID)
171}
172
173// TestCoordinatorSettingsStayOutOfTheWorktree starts a Claude coordinator in
174// a repo, then resumes it: each time claude loads its status line from a file
175// in the session's state, and the coordinator's worktree stays clean.
176func TestCoordinatorSettingsStayOutOfTheWorktree(t *testing.T) {
177 t.Parallel()
178 h := NewHarness(t)
179 argsFile := filepath.Join(h.E2EDir, "coordinator.args")
180 h.WriteStub("claude", "#!/bin/sh\nprintf '%s\\n' \"$@\" > '"+argsFile+"'\n")
181
182 for _, verb := range []string{"new", "session"} {
183 os.Remove(argsFile)
184 res := h.RunKlaus(verb, "--backend", "claude")
185 if res.ExitCode != 0 {
186 t.Fatalf("klaus %s exited %d\nstdout:\n%s\nstderr:\n%s", verb, res.ExitCode, res.Stdout, res.Stderr)
187 }
188 var session *run.State
189 for _, id := range h.sessionIDs() {
190 if st, err := run.NewHomeDirStoreFromPath(filepath.Join(h.Home, ".klaus", "sessions", id)).Load(id); err == nil && st.Type == "session" {
191 session = st
192 }
193 }
194 if session == nil || session.Branch == "" {
195 t.Fatalf("klaus %s recorded no coordinator worktree: %+v", verb, session)
196 }
197 argv, err := os.ReadFile(argsFile)
198 if err != nil {
199 t.Fatalf("klaus %s did not start claude: %v", verb, err)
200 }
201 h.assertCleanWorktree(session.Worktree)
202 h.assertSettingsOutside(string(argv), session.Worktree, filepath.Base(h.RepoDir))
203 }
204}
205
206// sessionIDs lists the coordinator sessions under the temp HOME.
207func (h *Harness) sessionIDs() []string {
208 h.t.Helper()
209 entries, err := os.ReadDir(filepath.Join(h.Home, ".klaus", "sessions"))
210 if err != nil {
211 h.t.Fatal(err)
212 }
213 var ids []string
214 for _, e := range entries {
215 ids = append(ids, e.Name())
216 }
217 return ids
218}