gunk-dev/the-valley

consult_snapshot_test.go

source6a6791929c36main's published tip history
8.6 KiB
1package cmd
2
3import (
4 "encoding/json"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "strings"
9 "testing"
10
11 "the-valley/flow/internal/consult"
12 "the-valley/flow/internal/event"
13 "the-valley/flow/internal/jobs"
14)
15
16func snapshotGit(t *testing.T, dir string, args ...string) string {
17 t.Helper()
18 c := exec.Command("git", append([]string{"-c", "user.name=Test", "-c", "user.email=test@example.com", "-c", "init.defaultBranch=main"}, args...)...)
19 c.Dir = dir
20 out, err := c.CombinedOutput()
21 if err != nil {
22 t.Fatalf("git %v: %s, %v", args, out, err)
23 }
24 return strings.TrimSpace(string(out))
25}
26
27// commitToOrigin commits main.txt holding content on main in the seed clone
28// and pushes it to origin, returning the commit.
29func commitToOrigin(t *testing.T, seed, content string) string {
30 t.Helper()
31 if err := os.WriteFile(filepath.Join(seed, "main.txt"), []byte(content+"\n"), 0o644); err != nil {
32 t.Fatal(err)
33 }
34 snapshotGit(t, seed, "add", "main.txt")
35 snapshotGit(t, seed, "commit", "-qm", content)
36 snapshotGit(t, seed, "push", "-q", "origin", "HEAD:main")
37 return snapshotGit(t, seed, "rev-parse", "HEAD")
38}
39
40// TestConsultRepoReadsOriginSnapshot runs the real klaus against a bare
41// origin and a registered clone checked out on a stale branch, with a stub
42// backend that records where it ran and what it read.
43func TestConsultRepoReadsOriginSnapshot(t *testing.T) {
44 bin := klausBinary(t)
45 e := newConsultEnv(t, bin, "session-consult-snapshot")
46 root, err := filepath.EvalSymlinks(t.TempDir())
47 if err != nil {
48 t.Fatal(err)
49 }
50 origin, seed, clone := filepath.Join(root, "origin.git"), filepath.Join(root, "seed"), filepath.Join(root, "clone")
51 snapshotGit(t, root, "init", "-q", "--bare", origin)
52 snapshotGit(t, root, "clone", "-q", origin, seed)
53 c1 := commitToOrigin(t, seed, "v1")
54 snapshotGit(t, root, "clone", "-q", origin, clone)
55 snapshotGit(t, clone, "checkout", "-qb", "stale")
56 if err := os.WriteFile(filepath.Join(clone, "stale.txt"), []byte("old agent work\n"), 0o644); err != nil {
57 t.Fatal(err)
58 }
59 snapshotGit(t, clone, "add", "stale.txt")
60 snapshotGit(t, clone, "commit", "-qm", "stale")
61 reg, _ := json.Marshal(map[string]interface{}{"projects": map[string]string{"widget": clone}})
62 if err := os.MkdirAll(filepath.Join(e.home, ".klaus"), 0o755); err != nil {
63 t.Fatal(err)
64 }
65 if err := os.WriteFile(filepath.Join(e.home, ".klaus", "projects.json"), reg, 0o644); err != nil {
66 t.Fatal(err)
67 }
68
69 rec := t.TempDir()
70 e.stub(t, "codex", `rec=`+rec+`
71pwd -P > "$rec/dir"
72ls -A > "$rec/files"
73cat main.txt > "$rec/main.txt"
74cat > "$rec/prompt"
75echo an answer
76echo 'session id: snapshot-thread' >&2
77`)
78 read := func(name string) string {
79 t.Helper()
80 data, err := os.ReadFile(filepath.Join(rec, name))
81 if err != nil {
82 t.Fatal(err)
83 }
84 return strings.TrimSpace(string(data))
85 }
86 // turn runs a consult and checks the backend read origin's main at commit
87 // in dir, with a prompt headed by the workspace line.
88 turn := func(t *testing.T, commit, content, dir string, args ...string) string {
89 t.Helper()
90 out, err := e.run(t, args...)
91 if err != nil {
92 t.Fatalf("consult %v: %s, %v", args, out, err)
93 }
94 if got := read("dir"); got != dir {
95 t.Errorf("backend ran in %s, want %s", got, dir)
96 }
97 if got := read("main.txt"); got != content {
98 t.Errorf("main.txt = %q, want %q", got, content)
99 }
100 if strings.Contains(read("files"), "stale.txt") {
101 t.Errorf("backend saw the clone's stale branch: %s", read("files"))
102 }
103 want := "Workspace: widget at origin/main " + commit
104 if first, _, _ := strings.Cut(read("prompt"), "\n"); first != want {
105 t.Errorf("prompt starts %q, want %q", first, want)
106 }
107 return out
108 }
109 store := consult.NewStore(e.sessionDir())
110 snap, err := store.WorkspaceDir("design")
111 if err != nil {
112 t.Fatal(err)
113 }
114
115 turn(t, c1, "v1", snap, "--backend", "codex", "--thread", "design", "--repo", "widget", "first question")
116 saved, err := store.Load("design")
117 if err != nil || saved.Repo != "widget" || saved.Commit != c1 || saved.Dir != snap {
118 t.Fatalf("saved thread: %+v, %v", saved, err)
119 }
120 var started event.Event
121 for _, evt := range e.events(t) {
122 if evt.Type == event.ConsultStarted {
123 started = evt
124 }
125 }
126 if started.Data["commit"] != c1 || started.Data["repo"] != "widget" {
127 t.Errorf("consult:started data = %+v", started.Data)
128 }
129 job, err := jobs.NewStore(e.sessionDir()).Load(started.RunID)
130 if err != nil || job.Commit != c1 || job.Repo != "widget" {
131 t.Errorf("job record: %+v, %v", job, err)
132 }
133 if branch := snapshotGit(t, clone, "branch", "--show-current"); branch != "stale" {
134 t.Errorf("clone moved to %s", branch)
135 }
136
137 c2 := commitToOrigin(t, seed, "v2")
138 turn(t, c2, "v2", snap, "--thread", "design", "second question")
139 if log, _ := os.ReadFile(filepath.Join(store.Dir, "design.log")); !strings.Contains(string(log), `"repo_revision":"`+c2+`"`) {
140 t.Errorf("turn 2 doesn't record %s: %s", c2, log)
141 }
142
143 // A snapshot deleted behind git's back is pruned and made again.
144 if err := os.RemoveAll(snap); err != nil {
145 t.Fatal(err)
146 }
147 turn(t, c2, "v2", snap, "--thread", "design", "--repo", "widget", "third question")
148
149 t.Run("dir reads as it stands", func(t *testing.T) {
150 if out, err := e.run(t, "--backend", "codex", "--dir", clone, "question"); err != nil {
151 t.Fatalf("consult: %s, %v", out, err)
152 }
153 if read("dir") != clone || !strings.Contains(read("files"), "stale.txt") || strings.HasPrefix(read("prompt"), "Workspace:") {
154 t.Errorf("--dir read %s with %s, prompt %q", read("dir"), read("files"), read("prompt"))
155 }
156 })
157
158 t.Run("one-shot snapshot is removed", func(t *testing.T) {
159 c3 := commitToOrigin(t, seed, "v3")
160 parent := filepath.Join(e.home, ".klaus", "consult-snapshots")
161 out, err := e.run(t, "--backend", "codex", "--repo", "widget", "question")
162 if err != nil {
163 t.Fatalf("consult: %s, %v", out, err)
164 }
165 if dir := read("dir"); !strings.HasPrefix(dir, parent+"/") || filepath.Base(dir) != "widget" || read("main.txt") != "v3" || !strings.Contains(read("prompt"), c3) {
166 t.Errorf("one-shot read %s: %s, prompt %q", dir, read("main.txt"), read("prompt"))
167 }
168 if left, _ := os.ReadDir(parent); len(left) != 0 {
169 t.Errorf("one-shot snapshot left behind: %v", left)
170 }
171 if list := snapshotGit(t, clone, "worktree", "list", "--porcelain"); strings.Contains(list, parent) {
172 t.Errorf("clone still lists the one-shot snapshot:\n%s", list)
173 }
174 // A dot name stays inside its own directory, sparing other snapshots.
175 other := filepath.Join(parent, "consult-other")
176 if err := os.MkdirAll(other, 0o755); err != nil {
177 t.Fatal(err)
178 }
179 if out, err := e.run(t, "--backend", "codex", "--repo", "..", "question"); err == nil {
180 t.Errorf("--repo .. succeeded: %s", out)
181 }
182 if _, err := os.Stat(other); err != nil {
183 t.Errorf("--repo .. removed another snapshot: %v", err)
184 }
185 os.RemoveAll(other)
186 })
187
188 t.Run("panel members share a snapshot", func(t *testing.T) {
189 for _, kind := range []string{"claude", "agy"} {
190 e.stub(t, kind, "pwd -P > "+rec+"/dir."+kind+"\ncat >/dev/null\necho an answer\n")
191 }
192 out, err := e.run(t, "--panel", "--repo", "widget", "question")
193 if err != nil {
194 t.Fatalf("panel: %s, %v", out, err)
195 }
196 // KLAUS_BACKEND=agy, so the panel is codex and claude.
197 if read("dir.claude") != read("dir") || filepath.Base(read("dir")) != "widget" {
198 t.Errorf("panel members read %s and %s", read("dir"), read("dir.claude"))
199 }
200 })
201
202 t.Run("offline fetch reads the last snapshot", func(t *testing.T) {
203 if saved, _ = store.Load("design"); saved.Commit != c2 {
204 t.Fatalf("thread commit = %s, want %s", saved.Commit, c2)
205 }
206 if err := os.Rename(origin, origin+".off"); err != nil {
207 t.Fatal(err)
208 }
209 defer os.Rename(origin+".off", origin)
210 out := turn(t, c2, "v2", snap, "--thread", "design", "offline question")
211 if !strings.Contains(out, "warning: fetching origin/main of project \"widget\" failed") || !strings.Contains(out, "reading the last snapshot, at "+c2) {
212 t.Errorf("no fallback warning: %s", out)
213 }
214 out, err := e.run(t, "--backend", "codex", "--repo", "widget", "question")
215 if err == nil || !strings.Contains(out, "there is no earlier snapshot to read") {
216 t.Errorf("one-shot without a snapshot: %s, %v", out, err)
217 }
218 })
219
220 t.Run("cleanup removes the thread snapshot", func(t *testing.T) {
221 c := exec.Command(bin, "cleanup", "--all")
222 c.Env = e.command().Env
223 out, err := c.CombinedOutput()
224 if err != nil || !strings.Contains(string(out), "Removed consult thread design's snapshot") {
225 t.Fatalf("cleanup: %s, %v", out, err)
226 }
227 if _, err := os.Stat(snap); !os.IsNotExist(err) {
228 t.Errorf("snapshot still at %s: %v", snap, err)
229 }
230 if list := snapshotGit(t, clone, "worktree", "list", "--porcelain"); strings.Contains(list, snap) {
231 t.Errorf("clone still lists the snapshot:\n%s", list)
232 }
233 })
234}