gunk-dev/the-valley

consult_test.go

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