gunk-dev/the-valley

consult_test.go

source6a6791929c36main's published tip history
10.3 KiB
1package cmd
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "strings"
14 "testing"
15 "time"
16
17 "the-valley/flow/internal/consult"
18)
19
20func TestConsultThreadIntegration(t *testing.T) {
21 home := t.TempDir()
22 t.Setenv("HOME", home)
23 t.Setenv(sessionIDEnv, "session-consult-test")
24 t.Setenv("KLAUS_BACKEND", "claude")
25 // The session exists: a consult looks it up, never creates it.
26 if err := os.MkdirAll(filepath.Join(home, ".klaus", "sessions", "session-consult-test"), 0o755); err != nil {
27 t.Fatal(err)
28 }
29 dir := t.TempDir()
30 for _, args := range [][]string{{"init", "-q"}, {"-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "--allow-empty", "-qm", "initial"}} {
31 c := exec.Command("git", args...)
32 c.Dir = dir
33 if output, err := c.CombinedOutput(); err != nil {
34 t.Fatalf("git: %s, %v", output, err)
35 }
36 }
37 rev, err := exec.Command("git", "-C", dir, "rev-parse", "--short", "HEAD").Output()
38 if err != nil {
39 t.Fatal(err)
40 }
41 logPath := filepath.Join(home, ".klaus", "sessions", "session-consult-test", "consults", "design.log")
42 t.Setenv("CONSULT_TEST_LOG", logPath)
43 stub := filepath.Join(t.TempDir(), "backend")
44 script := `#!/bin/sh
45case "$(tail -n 1 "$CONSULT_TEST_LOG")" in
46 *'"status":"pending"'*) ;;
47 *) echo missing-pending >&2; exit 19 ;;
48esac
49printf '%s\n' "$@"
50printf 'session id: fake-thread-id\n' >&2
51cat
52`
53 if err := os.WriteFile(stub, []byte(script), 0700); err != nil {
54 t.Fatal(err)
55 }
56 old := consult.LookupBinary
57 t.Cleanup(func() { consult.LookupBinary = old })
58 consult.LookupBinary = func(name string) (string, error) {
59 if name != "codex" {
60 return "", os.ErrNotExist
61 }
62 return stub, nil
63 }
64 run := func(args ...string) (string, error) {
65 c := newConsultCmd()
66 var output bytes.Buffer
67 c.SetOut(&output)
68 c.SetErr(&output)
69 c.SetArgs(args)
70 err := c.Execute()
71 return output.String(), err
72 }
73 first, err := run("--backend", "codex", "--thread", "design", "--dir", dir, "--role", "critic", "first question")
74 if err != nil || !strings.Contains(first, "first question") {
75 t.Fatalf("first: %s, %v", first, err)
76 }
77 store := consult.NewStore(filepath.Join(home, ".klaus", "sessions", "session-consult-test"))
78 saved, err := store.Load("design")
79 if err != nil || saved.BackendSessionID != "fake-thread-id" || saved.Turns != 1 {
80 t.Fatalf("saved: %+v, %v", saved, err)
81 }
82 second, err := run("--thread", "design", "second question")
83 if err != nil || !strings.Contains(second, "resume\nfake-thread-id") {
84 t.Fatalf("second: %s, %v", second, err)
85 }
86 saved, err = store.Load("design")
87 if err != nil || saved.Turns != 2 {
88 t.Fatalf("second save: %+v, %v", saved, err)
89 }
90 log, err := os.ReadFile(filepath.Join(store.Dir, "design.log"))
91 if err != nil || !strings.Contains(string(log), "first question") || !strings.Contains(string(log), "second question") {
92 t.Fatalf("log: %s, %v", log, err)
93 }
94 var turns []consult.Turn
95 for _, line := range bytes.Split(bytes.TrimSpace(log), []byte("\n")) {
96 var turn consult.Turn
97 if err := json.Unmarshal(line, &turn); err != nil {
98 t.Fatal(err)
99 }
100 turns = append(turns, turn)
101 }
102 if len(turns) != 2 || turns[0].Status != "ok" || turns[0].SessionIDSource != "stderr" || turns[0].RepoRevision != strings.TrimSpace(string(rev)) || turns[1].ResumeID != "fake-thread-id" || turns[1].SessionIDSource != "stderr" {
103 t.Fatalf("turn metadata: %+v", turns)
104 }
105 list, err := run("--list")
106 if err != nil || !strings.Contains(list, "design\tcodex\t2\t") {
107 t.Fatalf("list: %s, %v", list, err)
108 }
109 if _, err := run("--thread", "design", "--backend", "agy", "question"); err == nil {
110 t.Fatal("backend change accepted")
111 }
112 events, err := os.ReadFile(filepath.Join(filepath.Dir(store.Dir), "events.jsonl"))
113 if err != nil || strings.Count(string(events), "consult:completed") != 2 {
114 t.Fatalf("events: %s, %v", events, err)
115 }
116 if _, err := os.Stat(filepath.Join(filepath.Dir(store.Dir), "runs")); !os.IsNotExist(err) {
117 t.Fatal("consult created run state")
118 }
119 if err := os.WriteFile(stub, []byte("#!/bin/sh\necho backend-failed >&2\nexit 7\n"), 0700); err != nil {
120 t.Fatal(err)
121 }
122 failed, err := run("--backend", "codex", "--dir", dir, "question")
123 if err == nil || !strings.Contains(failed, "backend-failed") {
124 t.Fatalf("failure: %s, %v", failed, err)
125 }
126 failed, err = run("--thread", "design", "failed question")
127 if err == nil {
128 t.Fatal("failed thread accepted")
129 }
130 log, _ = os.ReadFile(logPath)
131 if !strings.Contains(string(log), `"status":"error: `) || !strings.Contains(string(log), `"turn":3`) {
132 t.Fatalf("failed transcript: %s", log)
133 }
134 raw, err := os.ReadFile(filepath.Join(filepath.Dir(logPath), "design.3.raw"))
135 if err != nil || !strings.Contains(string(raw), "backend-failed") {
136 t.Fatalf("raw failure: %s, %v", raw, err)
137 }
138 if err := os.WriteFile(stub, []byte("#!/bin/sh\necho answer-without-id\necho diagnostic-without-id >&2\n"), 0700); err != nil {
139 t.Fatal(err)
140 }
141 _, err = run("--backend", "codex", "--thread", "missing-id", "--dir", dir, "question")
142 rawPath := filepath.Join(filepath.Dir(logPath), "missing-id.1.raw")
143 if err == nil {
144 t.Fatal("missing ID accepted")
145 }
146 for _, part := range []string{"codex", "stderr", "stdout-json", "text", rawPath} {
147 if !strings.Contains(err.Error(), part) {
148 t.Fatalf("missing diagnostic %q: %v", part, err)
149 }
150 }
151 raw, err = os.ReadFile(rawPath)
152 if err != nil || !strings.Contains(string(raw), "answer-without-id") || !strings.Contains(string(raw), "diagnostic-without-id") {
153 t.Fatalf("raw extraction failure: %s, %v", raw, err)
154 }
155 if _, err := run("--backend", "codex", "--thread", "missing-id", "--dir", dir, "retry question"); err == nil {
156 t.Fatal("missing ID retry accepted")
157 }
158 if _, err := os.Stat(filepath.Join(filepath.Dir(logPath), "missing-id.2.raw")); err != nil {
159 t.Fatal(err)
160 }
161 if err := os.WriteFile(stub, []byte(`#!/bin/sh
162if [ "$1" = exec ]; then
163 echo unfinished-output
164 sleep 30
165else
166 echo fast-answer
167fi
168`), 0700); err != nil {
169 t.Fatal(err)
170 }
171 consult.LookupBinary = func(name string) (string, error) { return stub, nil }
172 t.Setenv("KLAUS_BACKEND", "agy")
173 started := time.Now()
174 output, err := run("--panel", "--dir", dir, "--timeout", "200ms", "question")
175 if !errors.Is(err, context.DeadlineExceeded) || time.Since(started) > 3*time.Second {
176 t.Fatalf("timeout: %s, %v", output, err)
177 }
178 if !strings.Contains(output, "## codex (default)\n\ntimed out") || !strings.Contains(output, "fast-answer") || strings.Contains(output, "unfinished-output") {
179 t.Fatalf("panel: %s", output)
180 }
181 if _, err := run("--backend", "codex", "--timeout", "0", "question"); err == nil {
182 t.Fatal("zero deadline accepted")
183 }
184
185}
186
187// Headless agy can't open a path outside its workspace, so each --file
188// reaches it whole on stdin, with the question, under a header naming its
189// path. Runs the real binary against a stand-in agy that records its input;
190// the attachments total more than the 128KB a single exec argument may hold.
191func TestConsultAgyGetsAttachedFiles(t *testing.T) {
192 bin := klausBinary(t)
193 workspace, err := filepath.EvalSymlinks(t.TempDir())
194 if err != nil {
195 t.Fatal(err)
196 }
197 outside, record := t.TempDir(), t.TempDir()
198 plan, review := filepath.Join(outside, "plan.md"), filepath.Join(outside, "review.md")
199 planText := "# The plan\n" + strings.Repeat("a step of the plan\n", 150*1024/19)
200 reviewText := "The review ends without a newline"
201 for path, text := range map[string]string{plan: planText, review: reviewText} {
202 if err := os.WriteFile(path, []byte(text), 0o600); err != nil {
203 t.Fatal(err)
204 }
205 }
206 argvFile, stdinFile := filepath.Join(record, "argv"), filepath.Join(record, "stdin")
207 e := newConsultEnv(t, bin, "")
208 e.stub(t, "agy", fmt.Sprintf("printf '%%s\\n' \"$@\" > %s\ncat > %s\necho the answer\n", shellQuote(argvFile), shellQuote(stdinFile)))
209
210 out, err := e.run(t, "--backend", "agy", "--dir", workspace, "--file", plan, "--file", review, "Does the review hold?")
211 if err != nil || !strings.Contains(out, "the answer") {
212 t.Fatalf("consult: %s, %v", out, err)
213 }
214 stdin, err := os.ReadFile(stdinFile)
215 if err != nil {
216 t.Fatal(err)
217 }
218 for _, want := range []string{
219 fmt.Sprintf("Inspect the repository at %q.", workspace),
220 "\n\nDoes the review hold?\n\n2 files are attached below, each in full",
221 "===== BEGIN ATTACHED FILE 1 of 2: " + plan + " =====\n" + planText + "===== END ATTACHED FILE 1 of 2: " + plan + " =====",
222 "===== BEGIN ATTACHED FILE 2 of 2: " + review + " =====\n" + reviewText + "\n===== END ATTACHED FILE 2 of 2: " + review + " =====",
223 } {
224 if !strings.Contains(string(stdin), want) {
225 t.Errorf("agy's stdin lacks %.200q", want)
226 }
227 }
228 argv, _ := os.ReadFile(argvFile)
229 if strings.Contains(string(argv), "a step of the plan") || strings.Contains(string(argv), reviewText) || strings.Contains(string(argv), "\n--print\n") {
230 t.Errorf("attachments in agy's argv: %.300s", argv)
231 }
232
233 // Past the total, the consult is refused and agy never runs.
234 extra := filepath.Join(outside, "extra.md")
235 if err := os.WriteFile(extra, bytes.Repeat([]byte("x"), 60*1024), 0o600); err != nil {
236 t.Fatal(err)
237 }
238 os.Remove(stdinFile)
239 out, err = e.run(t, "--backend", "agy", "--dir", workspace, "--file", plan, "--file", extra, "Does the review hold?")
240 if err == nil || !strings.Contains(out, "--file attachments exceed the 200KB total: "+extra) {
241 t.Fatalf("over the total: %s, %v", out, err)
242 }
243 if _, err := os.Stat(stdinFile); !os.IsNotExist(err) {
244 t.Fatal("agy ran for a refused consult")
245 }
246}
247
248// A snapshot takes main when its project config can't be loaded, unless
249// the file that can't is under the flow names: that stops the snapshot.
250func TestRepoSnapshotStopsAtBrokenFlowConfig(t *testing.T) {
251 home, clone := t.TempDir(), t.TempDir()
252 t.Setenv("HOME", home)
253 writeJSON(t, filepath.Join(home, ".klaus", "projects.json"), map[string]any{"projects": map[string]string{"widget": clone}})
254 for _, tc := range []struct {
255 file, want string
256 }{
257 {filepath.Join(clone, ".klaus", "config.json"), "origin/main"},
258 {filepath.Join(clone, ".valley", "flow", "config.json"), filepath.Join(clone, ".valley", "flow", "config.json")},
259 } {
260 if err := os.MkdirAll(filepath.Dir(tc.file), 0o755); err != nil {
261 t.Fatal(err)
262 }
263 if err := os.WriteFile(tc.file, []byte("{"), 0o644); err != nil {
264 t.Fatal(err)
265 }
266 _, err := prepareRepoSnapshot(context.Background(), "widget", t.TempDir(), io.Discard)
267 if err == nil || !strings.Contains(err.Error(), tc.want) {
268 t.Errorf("snapshot with a malformed %s: %v; want an error naming %s", tc.file, err, tc.want)
269 }
270 }
271}