gunk-dev/the-valley

location_test.go

source6a7605f70901main's published tip history
17.1 KiB
1package location
2
3import (
4 "errors"
5 "os"
6 "path/filepath"
7 "reflect"
8 "strings"
9 "testing"
10)
11
12func testLayout(t *testing.T) Layout {
13 t.Helper()
14 home := t.TempDir()
15 return Layout{Home: home, StateHome: filepath.Join(home, ".local", "state")}
16}
17
18func write(t *testing.T, path, data string) {
19 t.Helper()
20 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
21 t.Fatal(err)
22 }
23 if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
24 t.Fatal(err)
25 }
26}
27
28func mkdir(t *testing.T, path string) {
29 t.Helper()
30 if err := os.MkdirAll(path, 0o755); err != nil {
31 t.Fatal(err)
32 }
33}
34
35func TestParseGeneration(t *testing.T) {
36 for in, want := range map[string]Generation{"": Legacy, "legacy": Legacy, "bridge": Bridge, "flow": Flow} {
37 if got, err := ParseGeneration(in); err != nil || got != want {
38 t.Errorf("ParseGeneration(%q) = %q, %v; want %q", in, got, err, want)
39 }
40 }
41 for _, in := range []string{"Legacy", "w1", " flow"} {
42 if _, err := ParseGeneration(in); err == nil {
43 t.Errorf("ParseGeneration(%q) accepted it", in)
44 }
45 }
46 if Legacy.Next() != Bridge || Bridge.Next() != Flow || Flow.Next() != "" {
47 t.Errorf("Next: %q %q %q", Legacy.Next(), Bridge.Next(), Flow.Next())
48 }
49}
50
51// A declaration is the file under the flow names when one is there, else
52// the legacy file, one file at a time.
53func TestDeclarationsFallBackPerFile(t *testing.T) {
54 l := testLayout(t)
55 legacy, flow := filepath.Join(l.Home, ".klaus", "config.json"), filepath.Join(l.Home, ".valley", "flow", "config.json")
56 check := func(want string) {
57 t.Helper()
58 if got, err := l.HostConfig(); err != nil || got != want {
59 t.Errorf("HostConfig() = %q, %v; want %q", got, err, want)
60 }
61 }
62 check(legacy)
63 write(t, legacy, "{}")
64 check(legacy)
65 write(t, flow, "{}")
66 check(flow)
67
68 repo := t.TempDir()
69 write(t, filepath.Join(repo, ".klaus", "config.json"), "{}")
70 write(t, filepath.Join(repo, ".klaus", "prompt.md"), "old")
71 write(t, filepath.Join(repo, ".valley", "flow", "prompt.md"), "new")
72 for name, want := range map[string]string{
73 ProjectConfig: filepath.Join(repo, ".klaus", "config.json"),
74 WorkerPrompt: filepath.Join(repo, ".valley", "flow", "prompt.md"),
75 Principles: filepath.Join(repo, ".klaus", "principles.md"),
76 } {
77 if got, err := ProjectFile(repo, name); err != nil || got != want {
78 t.Errorf("ProjectFile(%s) = %q, %v; want %q", name, got, err, want)
79 }
80 }
81}
82
83// A file under the flow names that can't be read is still the one: the
84// reader's error is never a fall back to the legacy file, and a symlink
85// to nothing, which a reader would take for no file, is an error.
86func TestDeclarationPresentButBroken(t *testing.T) {
87 repo := t.TempDir()
88 write(t, filepath.Join(repo, ".klaus", "prompt.md"), "old")
89 flow := filepath.Join(repo, ".valley", "flow", "prompt.md")
90 mkdir(t, flow) // a directory: present, and unreadable as a file
91 if got, err := ProjectFile(repo, WorkerPrompt); err != nil || got != flow {
92 t.Errorf("ProjectFile = %q, %v; want %q", got, err, flow)
93 }
94 if err := os.Remove(flow); err != nil {
95 t.Fatal(err)
96 }
97 if err := os.Symlink(filepath.Join(repo, "nowhere"), flow); err != nil {
98 t.Fatal(err)
99 }
100 if got, err := ProjectFile(repo, WorkerPrompt); err == nil {
101 t.Errorf("ProjectFile with a dangling symlink = %q, want an error", got)
102 }
103
104 // A flow root that is not a directory can't be checked: an error.
105 other := t.TempDir()
106 write(t, filepath.Join(other, ".valley"), "a file")
107 write(t, filepath.Join(other, ".klaus", "prompt.md"), "old")
108 if got, err := ProjectFile(other, WorkerPrompt); err == nil {
109 t.Errorf("ProjectFile under a .valley file = %q, want an error", got)
110 }
111}
112
113func TestSingleValuedState(t *testing.T) {
114 l := testLayout(t)
115 legacy, flow := filepath.Join(l.Home, ".klaus", "projects.json"), filepath.Join(l.Home, ".valley", "flow", "projects.json")
116
117 // With neither, new state goes where the generation puts it.
118 for g, want := range map[Generation]string{Legacy: legacy, Bridge: flow, Flow: flow} {
119 gl := l
120 gl.Gen = g
121 if got, err := gl.Registry(); err != nil || got != want {
122 t.Errorf("%s: Registry() with none = %q, %v; want %q", g, got, err, want)
123 }
124 }
125 // With one, it is the one there, whatever the generation.
126 write(t, legacy, "{}")
127 for _, g := range Generations {
128 gl := l
129 gl.Gen = g
130 if got, err := gl.Registry(); err != nil || got != legacy {
131 t.Errorf("%s: Registry() with the legacy file = %q, %v; want %q", g, got, err, legacy)
132 }
133 }
134 if err := os.Remove(legacy); err != nil {
135 t.Fatal(err)
136 }
137
138 write(t, flow, "{}")
139 if got, err := l.Registry(); err != nil || got != flow {
140 t.Errorf("Registry() with the flow file = %q, %v; want %q", got, err, flow)
141 }
142
143 write(t, legacy, "{}")
144 _, err := l.Registry()
145 var conflict *ConflictError
146 if !errors.As(err, &conflict) || !reflect.DeepEqual(conflict.Paths, []string{legacy, flow}) {
147 t.Fatalf("Registry() with both = %v, want a ConflictError naming both", err)
148 }
149 if !strings.Contains(err.Error(), legacy) || !strings.Contains(err.Error(), flow) {
150 t.Errorf("conflict message names neither path: %v", err)
151 }
152
153 // One file under both names is one registry.
154 if err := os.Remove(flow); err != nil {
155 t.Fatal(err)
156 }
157 if err := os.Symlink(legacy, flow); err != nil {
158 t.Fatal(err)
159 }
160 if got, err := l.Registry(); err != nil || got != legacy {
161 t.Errorf("Registry() through a symlink = %q, %v; want %q", got, err, legacy)
162 }
163 // A symlink names the file it points at, so a save renames over the
164 // file rather than the link.
165 if err := os.Remove(legacy); err != nil {
166 t.Fatal(err)
167 }
168 write(t, filepath.Join(l.Home, "real.json"), "{}")
169 if err := os.Symlink(filepath.Join(l.Home, "real.json"), legacy); err != nil {
170 t.Fatal(err)
171 }
172 if err := os.Remove(flow); err != nil {
173 t.Fatal(err)
174 }
175 if err := os.Symlink(legacy, flow); err != nil {
176 t.Fatal(err)
177 }
178 if got, err := l.Registry(); err != nil || got != filepath.Join(l.Home, "real.json") {
179 t.Errorf("Registry() through symlinks = %q, %v; want the file itself", got, err)
180 }
181 if err := os.Remove(legacy); err != nil {
182 t.Fatal(err)
183 }
184 if err := os.Rename(filepath.Join(l.Home, "real.json"), legacy); err != nil {
185 t.Fatal(err)
186 }
187
188 // A hard link is two names a save would part: refused.
189 if err := os.Remove(flow); err != nil {
190 t.Fatal(err)
191 }
192 if err := os.Link(legacy, flow); err != nil {
193 t.Fatal(err)
194 }
195 if _, err := l.Registry(); !errors.As(err, &conflict) {
196 t.Errorf("Registry() through a hard link = %v, want a ConflictError", err)
197 }
198
199 // Self-update's legacy state is under the state directory.
200 state := filepath.Join(l.StateHome, "klaus", "self-update.json")
201 write(t, state, "{}")
202 if got, err := l.SelfUpdateState(); err != nil || got != state {
203 t.Errorf("SelfUpdateState() = %q, %v; want %q", got, err, state)
204 }
205 write(t, filepath.Join(l.Home, ".valley", "flow", "self-update.json"), "{}")
206 if _, err := l.SelfUpdateState(); !errors.As(err, &conflict) {
207 t.Errorf("SelfUpdateState() with both = %v, want a ConflictError", err)
208 }
209
210 mkdir(t, filepath.Join(l.Home, ".valley", "flow", "memory"))
211 if got, err := l.Memory(); err != nil || got != filepath.Join(l.Home, ".valley", "flow", "memory") {
212 t.Errorf("Memory() = %q, %v", got, err)
213 }
214}
215
216// Legacy allocates the legacy names, and bridge and flow the flow names for
217// home and project state, keeping the plumbing's legacy names; the host
218// config decides the generation when the layout doesn't, and a bad one
219// allocates nothing.
220func TestAllocation(t *testing.T) {
221 l := testLayout(t)
222 repo := t.TempDir()
223 home := func(name string, flow bool) string {
224 if flow {
225 return filepath.Join(l.Home, ".valley", "flow", name)
226 }
227 return filepath.Join(l.Home, ".klaus", name)
228 }
229 for _, g := range Generations {
230 write(t, filepath.Join(l.Home, ".klaus", "config.json"), `{"naming_generation": "`+string(g)+`"}`)
231 if got, err := l.Generation(); err != nil || got != g {
232 t.Errorf("Generation() = %q, %v; want %q", got, err, g)
233 }
234 flow := g != Legacy
235 if got := Allocates(g); got != map[bool]Generation{false: Legacy, true: Bridge}[flow] {
236 t.Errorf("Allocates(%s) = %s", g, got)
237 }
238 for name, f := range map[string]func() (string, error){
239 "sessions": l.NewSessionsRoot,
240 "sync.log": l.SyncLog,
241 "consult-snapshots": l.ConsultSnapshots,
242 "memory": l.Memory,
243 "projects.json": l.Registry,
244 } {
245 if got, err := f(); err != nil || got != home(name, flow) {
246 t.Errorf("%s: %s = %q, %v; want %q", g, name, got, err, home(name, flow))
247 }
248 }
249 if dir, err := l.NewSession("session-x"); err != nil || dir != filepath.Join(home("sessions", flow), "session-x") {
250 t.Errorf("%s: NewSession = %q, %v", g, dir, err)
251 }
252 state := filepath.Join(l.StateHome, "klaus", "self-update.json")
253 if flow {
254 state = home("self-update.json", true)
255 }
256 if got, err := l.SelfUpdateState(); err != nil || got != state {
257 t.Errorf("%s: SelfUpdateState = %q, %v; want %q", g, got, err, state)
258 }
259 project := filepath.Join(repo, ".klaus", "prompt.md")
260 if flow {
261 project = filepath.Join(repo, ".valley", "flow", "prompt.md")
262 }
263 if got, err := l.ScaffoldProjectFile(repo, WorkerPrompt); err != nil || got != project {
264 t.Errorf("%s: ScaffoldProjectFile = %q, %v; want %q", g, got, err, project)
265 }
266 // The plumbing older builds share keeps its legacy names.
267 if got, err := l.StandaloneStore("/repo/.git"); err != nil || got != filepath.Join("/repo/.git", "klaus") {
268 t.Errorf("%s: StandaloneStore = %q, %v", g, got, err)
269 }
270 if got := AgentsSession("session-x"); got != "klaus-agents-session-x" {
271 t.Errorf("%s: AgentsSession = %q", g, got)
272 }
273 }
274
275 // A sync log under the other name stays where it is; appends go to the
276 // one the generation names, and both are listed.
277 write(t, home("sync.log", false), "old\n")
278 if got, err := l.SyncLog(); err != nil || got != home("sync.log", true) {
279 t.Errorf("SyncLog under flow with a legacy log = %q, %v", got, err)
280 }
281 write(t, home("sync.log", true), "new\n")
282 if got := l.SyncLogs(); !reflect.DeepEqual(got, []string{home("sync.log", false), home("sync.log", true)}) {
283 t.Errorf("SyncLogs = %v", got)
284 }
285 // So do consult snapshot directories.
286 write(t, filepath.Join(home("consult-snapshots", true), "s", "f"), "")
287 if got := l.ConsultSnapshotDirs(); !reflect.DeepEqual(got, []string{home("consult-snapshots", true)}) {
288 t.Errorf("ConsultSnapshotDirs = %v", got)
289 }
290
291 write(t, filepath.Join(l.Home, ".valley", "flow", "config.json"), `{"naming_generation": "w2"}`)
292 if _, err := l.NewSession("session-y"); err == nil || !strings.Contains(err.Error(), "w2") {
293 t.Errorf("NewSession under a bad generation = %v, want its error", err)
294 }
295 write(t, filepath.Join(l.Home, ".valley", "flow", "config.json"), `{"naming_generation": `)
296 if _, err := l.ConsultSnapshots(); err == nil {
297 t.Error("ConsultSnapshots under a malformed host config succeeded")
298 }
299}
300
301// What a command writes fresh outside flow's state follows the running
302// user's host setting, and the legacy names when it can't be read.
303func TestWritesFollowsTheHost(t *testing.T) {
304 home := t.TempDir()
305 t.Setenv("HOME", home)
306 cases := []struct {
307 config string
308 gen Generation
309 temp, base, self, command string
310 }{
311 {"", Legacy, "klaus-merge-*", "klaus-sessions", "klaus", "klaus ready"},
312 {`{"naming_generation": "legacy"}`, Legacy, "klaus-merge-*", "klaus-sessions", "klaus", "klaus ready"},
313 {`{"naming_generation": "bridge"}`, Bridge, "valley-flow-merge-*", "valley-flow-sessions", "flow", "valley flow ready"},
314 {`{"naming_generation": "flow"}`, Bridge, "valley-flow-merge-*", "valley-flow-sessions", "flow", "valley flow ready"},
315 {`{"naming_generation": "w2"}`, Legacy, "klaus-merge-*", "klaus-sessions", "klaus", "klaus ready"},
316 }
317 for _, tc := range cases {
318 path := filepath.Join(home, ".klaus", "config.json")
319 if tc.config == "" {
320 _ = os.Remove(path)
321 } else {
322 write(t, path, tc.config)
323 }
324 if got := Writes(); got != tc.gen {
325 t.Errorf("%s: Writes() = %s, want %s", tc.config, got, tc.gen)
326 }
327 if got := TempPattern("merge-*"); got != tc.temp {
328 t.Errorf("%s: TempPattern = %q, want %q", tc.config, got, tc.temp)
329 }
330 if got := WorktreeBase(Writes()); got != filepath.Join(os.TempDir(), tc.base) {
331 t.Errorf("%s: WorktreeBase = %q", tc.config, got)
332 }
333 if got := Self(); got != tc.self {
334 t.Errorf("%s: Self() = %q, want %q", tc.config, got, tc.self)
335 }
336 if got := Command("ready"); got != tc.command {
337 t.Errorf("%s: Command(ready) = %q, want %q", tc.config, got, tc.command)
338 }
339 }
340}
341
342func TestSessions(t *testing.T) {
343 l := testLayout(t)
344 oldRoot, newRoot := l.SessionRoots()[0], l.SessionRoots()[1]
345 mkdir(t, filepath.Join(oldRoot, "session-1"))
346 mkdir(t, filepath.Join(newRoot, "session-2"))
347 write(t, filepath.Join(newRoot, "stray.txt"), "")
348
349 got, err := l.Sessions()
350 want := []Session{{"session-1", filepath.Join(oldRoot, "session-1")}, {"session-2", filepath.Join(newRoot, "session-2")}}
351 if err != nil || !reflect.DeepEqual(got, want) {
352 t.Fatalf("Sessions() = %v, %v; want %v", got, err, want)
353 }
354 if dir, err := l.Session("session-2"); err != nil || dir != want[1].Dir {
355 t.Errorf("Session(session-2) = %q, %v", dir, err)
356 }
357
358 // An unknown ID fails, and creates nothing.
359 if _, err := l.Session("session-9"); !errors.Is(err, ErrUnknownSession) {
360 t.Errorf("Session(unknown) = %v, want ErrUnknownSession", err)
361 }
362 for _, root := range l.SessionRoots() {
363 if _, err := os.Stat(filepath.Join(root, "session-9")); !os.IsNotExist(err) {
364 t.Errorf("looking up an unknown session made %s", root)
365 }
366 }
367 for _, id := range []string{"", ".", "..", "../session-1", "a/b"} {
368 if _, err := l.Session(id); err == nil || errors.Is(err, ErrUnknownSession) {
369 t.Errorf("Session(%q) = %v, want it refused", id, err)
370 }
371 }
372 if _, err := l.NewSession("session-2"); err == nil {
373 t.Error("NewSession of an existing ID succeeded")
374 }
375
376 // The same ID under both roots names no session, and the error names both.
377 mkdir(t, filepath.Join(newRoot, "session-1"))
378 got, err = l.Sessions()
379 var conflict *ConflictError
380 if !errors.As(err, &conflict) || !reflect.DeepEqual(conflict.Paths, []string{filepath.Join(oldRoot, "session-1"), filepath.Join(newRoot, "session-1")}) {
381 t.Fatalf("Sessions() with a duplicate: err = %v", err)
382 }
383 if !reflect.DeepEqual(got, want[1:]) {
384 t.Errorf("Sessions() with a duplicate = %v, want the rest: %v", got, want[1:])
385 }
386 if _, err := l.Session("session-1"); !errors.As(err, &conflict) {
387 t.Errorf("Session(duplicate) = %v, want a ConflictError", err)
388 }
389
390 // One directory under both roots is one session.
391 if err := os.Remove(filepath.Join(newRoot, "session-1")); err != nil {
392 t.Fatal(err)
393 }
394 if err := os.Symlink(filepath.Join(oldRoot, "session-1"), filepath.Join(newRoot, "session-1")); err != nil {
395 t.Fatal(err)
396 }
397 if dir, err := l.Session("session-1"); err != nil || dir != filepath.Join(oldRoot, "session-1") {
398 t.Errorf("Session through a symlink = %q, %v", dir, err)
399 }
400 // A symlinked session is listed as it is looked up.
401 mkdir(t, filepath.Join(l.Home, "elsewhere", "session-3"))
402 if err := os.Symlink(filepath.Join(l.Home, "elsewhere", "session-3"), filepath.Join(newRoot, "session-3")); err != nil {
403 t.Fatal(err)
404 }
405 got, err = l.Sessions()
406 ids := map[string]int{}
407 for _, s := range got {
408 ids[s.ID]++
409 }
410 if err != nil || ids["session-1"] != 1 || ids["session-3"] != 1 {
411 t.Errorf("Sessions() = %v, %v; want session-1 once and the symlinked session-3", got, err)
412 }
413}
414
415func TestScaffoldWritesWhereItReads(t *testing.T) {
416 l := testLayout(t)
417 repo := t.TempDir()
418 if got, err := l.ScaffoldProjectFile(repo, ProjectConfig); err != nil || got != filepath.Join(repo, ".klaus", "config.json") {
419 t.Errorf("ScaffoldProjectFile with none = %q, %v", got, err)
420 }
421 write(t, filepath.Join(repo, ".valley", "flow", "config.json"), "{}")
422 if got, err := l.ScaffoldProjectFile(repo, ProjectConfig); err != nil || got != filepath.Join(repo, ".valley", "flow", "config.json") {
423 t.Errorf("ScaffoldProjectFile with the flow file = %q, %v", got, err)
424 }
425 write(t, filepath.Join(l.Home, ".valley", "flow", "config.json"), "{}")
426 if got, err := l.ScaffoldHostConfig(); err != nil || got != filepath.Join(l.Home, ".valley", "flow", "config.json") {
427 t.Errorf("ScaffoldHostConfig = %q, %v", got, err)
428 }
429}
430
431// New state needs only the generation: a legacy host config that can't be
432// read or parsed sets none, as flow never read it to allocate, while one
433// under the flow names that can't be is an error.
434func TestGenerationReadsLegacyHostConfigAsBefore(t *testing.T) {
435 l := testLayout(t)
436 legacy, flow := filepath.Join(l.Home, ".klaus", "config.json"), filepath.Join(l.Home, ".valley", "flow", "config.json")
437 write(t, legacy, "{")
438 if g, err := l.Generation(); err != nil || g != Legacy {
439 t.Errorf("Generation() with a malformed legacy host config = %q, %v; want legacy", g, err)
440 }
441 if _, err := l.NewSessionsRoot(); err != nil {
442 t.Errorf("NewSessionsRoot() with a malformed legacy host config: %v", err)
443 }
444 write(t, legacy, `{"naming_generation": "w1"}`)
445 if _, err := l.Generation(); err == nil {
446 t.Error("Generation() accepted naming_generation w1")
447 }
448 mkdir(t, flow)
449 if _, err := l.Generation(); err == nil {
450 t.Error("Generation() with an unreadable host config under the flow names fell back")
451 }
452 if !FlowNamed(flow) || FlowNamed(legacy) {
453 t.Errorf("FlowNamed: %s %v, %s %v", flow, FlowNamed(flow), legacy, FlowNamed(legacy))
454 }
455}