gunk-dev/the-valley

naming_test.go

source6a7605f70901main's published tip history
17.0 KiB
1//go:build e2e
2
3package e2e
4
5import (
6 "encoding/json"
7 "errors"
8 "fmt"
9 "os"
10 "path/filepath"
11 "strings"
12 "testing"
13 "time"
14
15 "the-valley/flow/internal/flowenv"
16 "the-valley/flow/internal/run"
17 "the-valley/flow/internal/selfupdate"
18)
19
20func writeE2EFile(t *testing.T, path, data string) {
21 t.Helper()
22 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
23 t.Fatal(err)
24 }
25 if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
26 t.Fatal(err)
27 }
28}
29
30// TestOperatesStateUnderFlowNames: a session, a project registry, a host
31// config, a repo config and self-update state that a later build put under
32// the flow names (~/.valley/flow, <repo>/.valley/flow) are found and kept
33// there by every command, whatever the naming generation, so a rollback to
34// this build keeps working on them.
35func TestOperatesStateUnderFlowNames(t *testing.T) {
36 t.Parallel()
37 h := NewHarness(t)
38 h.UseFlowNames()
39 flow := filepath.Join(h.Home, ".valley", "flow")
40 legacy := filepath.Join(h.Home, ".klaus")
41
42 writeE2EFile(t, filepath.Join(flow, "config.json"), `{"default_agent_model": "flow-host-model"}`+"\n")
43 writeE2EFile(t, filepath.Join(flow, "projects.json"), `{"projects_dir": "~/src", "projects": {"widget": "`+h.RepoDir+`"}}`+"\n")
44 writeE2EFile(t, filepath.Join(flow, "self-update.json"), `{"current": {"commit": "1111111", "store_path": "/nix/store/x-klaus"}, "updated_at": "2026-11-01T00:00:00Z"}`+"\n")
45 if err := os.Mkdir(filepath.Join(h.RepoDir, ".valley"), 0o755); err != nil {
46 t.Fatal(err)
47 }
48 h.git(h.RepoDir, "mv", ".klaus", filepath.Join(".valley", "flow"))
49 h.git(h.RepoDir, "commit", "-qm", "keep flow config under .valley/flow")
50 h.git(h.RepoDir, "push", "-q", "origin", "main")
51
52 run1 := func(args ...string) RunResult {
53 t.Helper()
54 res := h.RunKlaus(args...)
55 if res.ExitCode != 0 {
56 t.Fatalf("klaus %v exited %d\nstdout:\n%s\nstderr:\n%s", args, res.ExitCode, res.Stdout, res.Stderr)
57 }
58 return res
59 }
60
61 if res := run1("project", "list"); !strings.Contains(res.Stdout, "widget") {
62 t.Errorf("project list read no registry under the flow names:\n%s", res.Stdout)
63 }
64 other := filepath.Join(h.E2EDir, "other")
65 h.git("", "init", "-q", "-b", "main", other)
66 h.RegisterProject("acme/other", other)
67 if data, err := os.ReadFile(filepath.Join(flow, "projects.json")); err != nil || !strings.Contains(string(data), "other") {
68 t.Errorf("project add did not write the registry back where it read it: %s, %v", data, err)
69 }
70
71 run1("launch", "work under the flow names")
72 ids := h.RunIDs()
73 if len(ids) != 1 {
74 t.Fatalf("runs in the session under the flow names: %v", ids)
75 }
76 id := ids[0]
77 h.WaitForClaudeStart(15 * time.Second)
78 h.ReleaseClaude()
79 st := h.WaitForState(id, func(s *run.State) bool { return s.CostUSD != nil }, 60*time.Second)
80 if st.Model == nil || *st.Model != "flow-host-model" {
81 t.Errorf("run model %v: the host config under the flow names was not read", st.Model)
82 }
83 if st.TmuxSession != h.AgentsSession() {
84 t.Errorf("run recorded tmux session %q, want %q", st.TmuxSession, h.AgentsSession())
85 }
86 if st.LogFile == nil || !strings.HasPrefix(*st.LogFile, h.SessionDir()+string(filepath.Separator)) {
87 t.Errorf("run log %v is outside its session %s", st.LogFile, h.SessionDir())
88 }
89
90 if res := run1("status"); !strings.Contains(res.Stdout, id) {
91 t.Errorf("status does not list %s:\n%s", id, res.Stdout)
92 }
93
94 var report struct {
95 Places []struct {
96 Kind string `json:"kind"`
97 Paths []string `json:"paths"`
98 } `json:"places"`
99 Blockers []struct{ What string } `json:"blockers"`
100 }
101 res := run1("naming", "status", "--json")
102 if err := json.Unmarshal([]byte(res.Stdout), &report); err != nil {
103 t.Fatalf("naming status --json: %v\n%s", err, res.Stdout)
104 }
105 places := map[string][]string{}
106 for _, p := range report.Places {
107 places[p.Kind] = p.Paths
108 }
109 for kind, want := range map[string]string{
110 "host config": filepath.Join(flow, "config.json"),
111 "project registry": filepath.Join(flow, "projects.json"),
112 "self-update state": filepath.Join(flow, "self-update.json"),
113 "sessions": filepath.Join(flow, "sessions"),
114 } {
115 if got := places[kind]; len(got) != 1 || got[0] != want {
116 t.Errorf("naming status puts %s at %v, want %s", kind, got, want)
117 }
118 }
119
120 // Every self-update operation lists the profile first: one holding klaus.
121 h.WriteStub("nix", `#!/usr/bin/env bash
122case "$1 $2" in
123"profile list") echo '{"elements":{"klaus":{"storePaths":["/nix/store/x-klaus"]}},"version":3}';;
124*) echo "nix stub: unexpected $*" >&2; exit 2;;
125esac
126`)
127 run1("self-update", "--pin")
128 if su, err := selfupdate.LoadFile(filepath.Join(flow, "self-update.json")); err != nil || !su.Pinned || su.Current == nil {
129 t.Errorf("self-update --pin did not write the state where it found it: %+v, %v", su, err)
130 }
131
132 run1("cleanup", id)
133 if _, err := h.ReadState(id); !errors.Is(err, os.ErrNotExist) {
134 t.Errorf("cleanup left the run's state: %v", err)
135 }
136
137 // Nothing of these moved to, or was copied under, the legacy names.
138 for _, p := range []string{
139 filepath.Join(legacy, "sessions"),
140 filepath.Join(legacy, "projects.json"),
141 filepath.Join(legacy, "config.json"),
142 filepath.Join(h.Home, ".local", "state", "klaus", "self-update.json"),
143 filepath.Join(h.RepoDir, ".klaus"),
144 } {
145 if _, err := os.Stat(p); !errors.Is(err, os.ErrNotExist) {
146 t.Errorf("%s exists: state under the flow names was copied or moved", p)
147 }
148 }
149
150 // A registry under both names stops launch, naming both, rather than
151 // launching as if neither were there.
152 writeE2EFile(t, filepath.Join(legacy, "projects.json"), `{"projects": {}}`+"\n")
153 res = h.RunKlaus("launch", "with two registries")
154 if res.ExitCode == 0 || !strings.Contains(res.Stderr, filepath.Join(legacy, "projects.json")) || !strings.Contains(res.Stderr, filepath.Join(flow, "projects.json")) {
155 t.Errorf("launch with a registry under both names exited %d, want a refusal naming both\nstderr:\n%s", res.ExitCode, res.Stderr)
156 }
157}
158
159// TestBridgeGeneration: with naming_generation bridge, a new coordinator
160// session goes under the flow root and every command operates it, while a
161// session created earlier under legacy in the same home keeps its directory
162// and its recorded generation as it is listed, finalized and resumed; the
163// commit a worker makes carries Klaus-Run; and children get each flow
164// variable under both names with one value. Setting legacy again moves
165// nothing: the bridge session's run is still found, finalized and cleaned
166// up, and a new session goes under the legacy root.
167func TestBridgeGeneration(t *testing.T) {
168 t.Parallel()
169 h := NewHarness(t)
170 legacyRoot := filepath.Join(h.Home, ".klaus")
171 flowRoot := filepath.Join(h.Home, ".valley", "flow")
172 setGeneration := func(g string) {
173 writeE2EFile(t, filepath.Join(legacyRoot, "config.json"), `{"naming_generation": "`+g+`"}`+"\n")
174 }
175 in := func(id, root string) { h.SessionID, h.StateRoot = id, root }
176 ok := func(res RunResult, what string) RunResult {
177 t.Helper()
178 if res.ExitCode != 0 {
179 t.Fatalf("%s exited %d\nstdout:\n%s\nstderr:\n%s", what, res.ExitCode, res.Stdout, res.Stderr)
180 }
181 return res
182 }
183 waitFile := func(path string) {
184 t.Helper()
185 for deadline := time.Now().Add(30 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
186 if _, err := os.Stat(path); err == nil {
187 return
188 }
189 }
190 t.Fatalf("%s never appeared", path)
191 }
192
193 // Coordinators record their environment and exit. Workers record theirs
194 // and wait until their own run is released.
195 coordinatorEnv := filepath.Join(h.E2EDir, "coordinator.env")
196 h.WriteStub("codex", fmt.Sprintf("#!/bin/sh\nenv > %q\n", coordinatorEnv))
197 h.WriteStub("claude", fmt.Sprintf(`#!/usr/bin/env bash
198dir=%q
199run=${KLAUS_RUN_ID:-none}
200env > "$dir/worker.$run.env"
201[ -t 0 ] || cat > /dev/null
202: > "$dir/started.$run"
203for _ in {1..1800}; do
204 [ -f "$dir/release.$run" ] && break
205 sleep 0.1
206done
207cat "$dir/claude.output.jsonl"
208`, h.E2EDir))
209 release := func(id string) { writeE2EFile(t, filepath.Join(h.E2EDir, "release."+id), "") }
210 readEnv := func(path string) map[string]string {
211 t.Helper()
212 data, err := os.ReadFile(path)
213 if err != nil {
214 t.Fatal(err)
215 }
216 env := map[string]string{}
217 for _, line := range strings.Split(string(data), "\n") {
218 if k, v, found := strings.Cut(line, "="); found {
219 env[k] = v
220 }
221 }
222 return env
223 }
224 // both checks that a child got each flow variable under both names with
225 // one value, or under neither, and the ones in want with their values.
226 both := func(what string, env map[string]string, want map[flowenv.Var]string) {
227 t.Helper()
228 for _, v := range flowenv.All {
229 n, nok := env[v.New]
230 l, lok := env[v.Legacy]
231 if nok != lok || n != l {
232 t.Errorf("%s got %s=%q (%v) and %s=%q (%v)", what, v.New, n, nok, v.Legacy, l, lok)
233 }
234 if value, set := want[v]; set && (!nok || n != value) {
235 t.Errorf("%s got %s=%q (%v), want %q", what, v.New, n, nok, value)
236 }
237 }
238 }
239 sessions := func() map[string]string {
240 out := map[string]string{}
241 for _, root := range []string{legacyRoot, flowRoot} {
242 entries, _ := os.ReadDir(filepath.Join(root, "sessions"))
243 for _, e := range entries {
244 if strings.HasPrefix(e.Name(), "session-") {
245 out[e.Name()] = filepath.Join(root, "sessions", e.Name())
246 }
247 }
248 }
249 return out
250 }
251 record := func(dir string) *run.State {
252 t.Helper()
253 st, err := run.NewHomeDirStoreFromPath(dir).Load(filepath.Base(dir))
254 if err != nil {
255 t.Fatal(err)
256 }
257 return st
258 }
259 newSession := func() (string, string) {
260 t.Helper()
261 before := sessions()
262 ok(h.RunKlausIn(h.E2EDir, "new", "--backend", "codex"), "new")
263 for id, dir := range sessions() {
264 if _, seen := before[id]; !seen {
265 return id, dir
266 }
267 }
268 t.Fatalf("new made no session: %v", sessions())
269 return "", ""
270 }
271 windowName := func() string {
272 return strings.TrimSpace(h.tmux("display-message", "-p", "-t", h.InitialPane, "#{window_name}"))
273 }
274 finalized := func(s *run.State) bool { return s.CostUSD != nil && s.TmuxPane == nil }
275
276 // Under legacy: a session under the legacy root, whose coordinator and
277 // worker get the legacy names alone.
278 legacyID, legacyDir := newSession()
279 if legacyDir != filepath.Join(legacyRoot, "sessions", legacyID) || record(legacyDir).NamingGeneration != "legacy" {
280 t.Fatalf("legacy session at %s records %q", legacyDir, record(legacyDir).NamingGeneration)
281 }
282 if env := readEnv(coordinatorEnv); env[flowenv.SessionID.Legacy] != legacyID || env[flowenv.SessionID.New] != "" {
283 t.Errorf("legacy coordinator got %s=%q and %s=%q", flowenv.SessionID.Legacy, env[flowenv.SessionID.Legacy], flowenv.SessionID.New, env[flowenv.SessionID.New])
284 }
285 if got := windowName(); got != "klaus" {
286 t.Errorf("legacy window title %q", got)
287 }
288 in(legacyID, legacyRoot)
289 legacyRun := launchOne(t, h, "legacy work")
290 waitFile(filepath.Join(h.E2EDir, "started."+legacyRun.ID))
291 if env := readEnv(filepath.Join(h.E2EDir, "worker."+legacyRun.ID+".env")); env[flowenv.RunID.Legacy] != legacyRun.ID {
292 t.Errorf("legacy worker got %s=%q", flowenv.RunID.Legacy, env[flowenv.RunID.Legacy])
293 } else {
294 for _, v := range flowenv.All {
295 if _, set := env[v.New]; set {
296 t.Errorf("legacy worker got %s", v.New)
297 }
298 }
299 }
300
301 // Under bridge: a new session under the flow root, recording bridge,
302 // whose children get both names.
303 setGeneration("bridge")
304 bridgeID, bridgeDir := newSession()
305 if bridgeDir != filepath.Join(flowRoot, "sessions", bridgeID) {
306 t.Fatalf("bridge session at %s, want it under %s", bridgeDir, flowRoot)
307 }
308 if st := record(bridgeDir); st.NamingGeneration != "bridge" || st.CreatedBy == "" {
309 t.Errorf("bridge session records generation %q, creator %q", st.NamingGeneration, st.CreatedBy)
310 }
311 both("bridge coordinator", readEnv(coordinatorEnv), map[flowenv.Var]string{flowenv.SessionID: bridgeID, flowenv.Backend: "codex", flowenv.AgentBackend: "claude"})
312 if got := windowName(); got != "flow" {
313 t.Errorf("bridge window title %q", got)
314 }
315
316 in(bridgeID, flowRoot)
317 bridgeRun := launchOne(t, h, "bridge work")
318 waitFile(filepath.Join(h.E2EDir, "started."+bridgeRun.ID))
319 if bridgeRun.LogFile == nil || !strings.HasPrefix(*bridgeRun.LogFile, bridgeDir+string(filepath.Separator)) {
320 t.Errorf("bridge run's log %v is outside its session %s", bridgeRun.LogFile, bridgeDir)
321 }
322 // The repo config sets worktree_base: it is kept.
323 if !strings.HasPrefix(bridgeRun.Worktree, filepath.Join(filepath.Dir(h.RepoDir), "worktrees")+string(filepath.Separator)) {
324 t.Errorf("bridge worktree %s is outside the configured worktree_base", bridgeRun.Worktree)
325 }
326 both("bridge worker", readEnv(filepath.Join(h.E2EDir, "worker."+bridgeRun.ID+".env")), map[flowenv.Var]string{
327 flowenv.SessionID: bridgeID,
328 flowenv.RunID: bridgeRun.ID,
329 flowenv.Backend: "claude",
330 flowenv.Scratch: filepath.Join(bridgeDir, "scratch", bridgeRun.ID),
331 })
332 writeE2EFile(t, filepath.Join(bridgeRun.Worktree, "bridge.txt"), "bridge\n")
333 h.git(bridgeRun.Worktree, "add", "-A")
334 h.git(bridgeRun.Worktree, "commit", "-qm", "Add bridge work")
335 if got, want := h.GitOutput(bridgeRun.Worktree, "log", "-1", "--format=%(trailers:only,unfold)"), "Change-Id: "+bridgeRun.ChangeID+"\nKlaus-Run: "+bridgeRun.ID; got != want {
336 t.Errorf("bridge worker's commit trailers %q, want %q", got, want)
337 }
338
339 // Status, queue, watch, report and the dashboard operate the session.
340 if res := ok(h.RunKlaus("status"), "status"); !strings.Contains(res.Stdout, bridgeRun.ID) {
341 t.Errorf("status does not list %s:\n%s", bridgeRun.ID, res.Stdout)
342 }
343 ok(h.RunKlaus("queue"), "queue")
344 h.emitMerged(7)
345 if _, err := os.Stat(filepath.Join(bridgeDir, "events.jsonl")); err != nil {
346 t.Errorf("the bridge session's events are not in its directory: %v", err)
347 }
348 if prs, _ := h.watchOnce("valley flow watch --once --after 0"); strings.Join(prs, " ") != "7" {
349 t.Errorf("watch printed PRs %v, want [7]", prs)
350 }
351 ok(h.RunKlaus("report", "time", "--current", "--json"), "report time")
352 dash := strings.TrimSpace(h.tmux("new-session", "-d", "-s", "dash", "-x", "120", "-y", "20", "-c", h.RepoDir,
353 "-P", "-F", "#{pane_id}", "env "+flowenv.SessionID.New+"="+bridgeID+" klaus dashboard"))
354 var screen string
355 for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline) && !strings.Contains(screen, "bridge work"); time.Sleep(200 * time.Millisecond) {
356 screen = h.tmux("capture-pane", "-p", "-t", dash)
357 }
358 if !strings.Contains(screen, "bridge work") {
359 t.Errorf("the dashboard never showed the bridge session's run:\n%s", screen)
360 }
361 h.tmux("kill-session", "-t", "dash")
362
363 // The legacy session is listed, its run finalized in its directory,
364 // and resumed there, keeping its recorded generation.
365 in(legacyID, legacyRoot)
366 if res := ok(h.RunKlaus("status"), "legacy status"); !strings.Contains(res.Stdout, legacyRun.ID) {
367 t.Errorf("status does not list %s:\n%s", legacyRun.ID, res.Stdout)
368 }
369 release(legacyRun.ID)
370 h.WaitForState(legacyRun.ID, finalized, 60*time.Second)
371 if subjects := strings.Split(h.GitOutput(h.RepoDir, "log", "--reverse", "--format=%s", "refs/klaus/data"), "\n"); subjects[0] != "Initialize flow run data" {
372 t.Errorf("the data ref starts with %q", subjects[0])
373 }
374 ok(h.RunKlausIn(h.E2EDir, "session", "--resume", legacyID), "resume legacy session")
375 if _, err := os.Stat(filepath.Join(flowRoot, "sessions", legacyID)); !errors.Is(err, os.ErrNotExist) {
376 t.Errorf("resuming the legacy session under bridge made it under the flow root: %v", err)
377 }
378 if st := record(legacyDir); st.NamingGeneration != "legacy" {
379 t.Errorf("resumed legacy session records %q", st.NamingGeneration)
380 }
381 both("resumed legacy coordinator", readEnv(coordinatorEnv), map[flowenv.Var]string{flowenv.SessionID: legacyID})
382 ok(h.RunKlaus("cleanup", legacyRun.ID), "cleanup legacy run")
383
384 // Back to legacy: the bridge session's run finalizes and is cleaned up
385 // where it is, and new sessions go under the legacy root.
386 setGeneration("legacy")
387 in(bridgeID, flowRoot)
388 release(bridgeRun.ID)
389 h.WaitForState(bridgeRun.ID, finalized, 60*time.Second)
390 if res := ok(h.RunKlaus("status"), "status after legacy"); !strings.Contains(res.Stdout, bridgeRun.ID) {
391 t.Errorf("status under legacy does not list %s:\n%s", bridgeRun.ID, res.Stdout)
392 }
393 ok(h.RunKlausIn(h.E2EDir, "session", "--resume", bridgeID), "resume bridge session")
394 if st := record(bridgeDir); st.NamingGeneration != "bridge" {
395 t.Errorf("resumed bridge session records %q", st.NamingGeneration)
396 }
397 if env := readEnv(coordinatorEnv); env[flowenv.SessionID.Legacy] != bridgeID || env[flowenv.SessionID.New] != "" {
398 t.Errorf("the bridge session's coordinator under legacy got %s=%q and %s=%q", flowenv.SessionID.Legacy, env[flowenv.SessionID.Legacy], flowenv.SessionID.New, env[flowenv.SessionID.New])
399 }
400 ok(h.RunKlaus("cleanup", bridgeRun.ID), "cleanup bridge run")
401 if _, err := h.ReadState(bridgeRun.ID); !errors.Is(err, os.ErrNotExist) {
402 t.Errorf("cleanup left the bridge run's state: %v", err)
403 }
404 if _, err := os.Stat(filepath.Join(legacyRoot, "sessions", bridgeID)); !errors.Is(err, os.ErrNotExist) {
405 t.Errorf("the bridge session appeared under the legacy root: %v", err)
406 }
407 newID, newDir := newSession()
408 if newDir != filepath.Join(legacyRoot, "sessions", newID) || record(newDir).NamingGeneration != "legacy" {
409 t.Errorf("a new session under legacy is at %s, recording %q", newDir, record(newDir).NamingGeneration)
410 }
411}