gunk-dev/the-valley

prose_test.go

source601b054bc28emain's published tip history
14.9 KiB
1//go:build e2e
2
3package e2e
4
5import (
6 "encoding/json"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "strings"
11 "testing"
12 "time"
13 "unicode/utf8"
14
15 "the-valley/flow/internal/git"
16)
17
18// stubProseBackends replaces agy, codex and claude with stubs that tell the
19// prose pass's rewrite and fact check, and the peer review, apart by their
20// prompt. Each logs its role to <name>.calls, its last prompt to
21// <name>.<role>.stdin and its arguments to <name>.<role>.args, then prints
22// <name>.<role> from E2EDir (a clean review by default). <name>.<role>.fail
23// makes it fail; <name>.<role>.sleep makes it hang. prose sets the repo's
24// pre_review.prose config; the peer reviewer is always claude, and the
25// author is author.
26func (h *Harness) stubProseBackends(author string, prose map[string]any) {
27 h.t.Helper()
28 for _, name := range []string{"agy", "codex", "claude"} {
29 h.WriteStub(name, `#!/usr/bin/env bash
30dir=`+h.E2EDir+`
31input=$(cat)
32case "$input" in
33 *"Fact-check these rewrites"*) role=check ;;
34 *"Rewrite the prose this change adds"*) role=write ;;
35 *) role=review ;;
36esac
37f="$dir/`+name+`.$role"
38echo "$role" >> "$dir/`+name+`.calls"
39printf '%s\n' "$input" > "$f.stdin"
40printf '%s\n' "$*" > "$f.args"
41[ -e "$f.sleep" ] && sleep 60
42[ -e "$f.fail" ] && { echo "boom" >&2; exit 3; }
43if [ -e "$f" ]; then cat "$f"; else echo '{"findings": [], "summary": "No issues found.", "ledger": [], "edits": [], "failures": []}'; fi
44`)
45 }
46 review := map[string]any{"review_backend": "claude"}
47 h.AmendRepoConfig(map[string]any{
48 "default_agent_backend": author,
49 "backends": map[string]any{"claude": review, "codex": review, "agy": review},
50 "pre_review": map[string]any{"prose": prose},
51 })
52}
53
54// stubAnswer sets what stub name answers in role.
55func (h *Harness) stubAnswer(name, role string, answer any) {
56 h.t.Helper()
57 data, err := json.Marshal(answer)
58 if err != nil {
59 h.t.Fatal(err)
60 }
61 h.writeE2E(name+"."+role, string(data))
62}
63
64func (h *Harness) writeE2E(name, content string) {
65 h.t.Helper()
66 if err := os.WriteFile(filepath.Join(h.E2EDir, name), []byte(content), 0o644); err != nil {
67 h.t.Fatal(err)
68 }
69}
70
71func (h *Harness) readE2E(name string) string {
72 data, _ := os.ReadFile(filepath.Join(h.E2EDir, name))
73 return string(data)
74}
75
76// commitFiles writes files in the sandbox repo and commits them on branch
77// work with message.
78func (h *Harness) commitFiles(files map[string]string, message string) {
79 h.t.Helper()
80 h.git(h.RepoDir, "checkout", "-qB", "work")
81 for name, content := range files {
82 p := filepath.Join(h.RepoDir, name)
83 if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
84 h.t.Fatal(err)
85 }
86 if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
87 h.t.Fatal(err)
88 }
89 }
90 h.git(h.RepoDir, "add", "-A")
91 h.git(h.RepoDir, "commit", "-qm", message)
92}
93
94const proseReadme = "# widget\n\nDeploy to the build host first, but only from main, once the smoke test passes.\n"
95
96// TestPreReviewProseChoosesFamilies: the writer is the first family in
97// pre_review.prose.order that isn't the author's, the fact checker the next,
98// else the author's; with no other family the pass is skipped.
99func TestPreReviewProseChoosesFamilies(t *testing.T) {
100 t.Parallel()
101 for _, tc := range []struct {
102 author, writer, checker string
103 order []string
104 skipped bool
105 }{
106 {author: "claude", writer: "agy", checker: "codex"},
107 {author: "agy", writer: "codex", checker: "claude"},
108 {author: "codex", writer: "agy", checker: "claude"},
109 {author: "claude", order: []string{"agy", "claude"}, writer: "agy", checker: "claude"},
110 {author: "codex", order: []string{"codex"}, skipped: true},
111 } {
112 t.Run(tc.author+"-"+strings.Join(tc.order, ","), func(t *testing.T) {
113 t.Parallel()
114 h := NewHarness(t)
115 prose := map[string]any{}
116 if tc.order != nil {
117 prose["order"] = tc.order
118 }
119 h.stubProseBackends(tc.author, prose)
120 h.commitFiles(map[string]string{"README.md": proseReadme}, "add deploy note")
121 if !tc.skipped {
122 h.stubAnswer(tc.writer, "write", map[string]any{"edits": []any{map[string]any{
123 "file": "README.md", "old": "Deploy to the build host first, but only from main, once the smoke test passes.",
124 "new": "Deploy to the build host first: only from main, after the smoke test passes."}}})
125 }
126
127 res := h.RunKlaus("_pre-review")
128 if res.ExitCode != 0 || !strings.Contains(res.Stdout, "All checks passed.") {
129 t.Fatalf("_pre-review exit %d\n%s%s", res.ExitCode, res.Stdout, res.Stderr)
130 }
131 if tc.skipped {
132 if !strings.Contains(res.Stdout, "Skipped: no model family other than the author's (codex) is installed.") {
133 t.Errorf("_pre-review didn't skip the pass:\n%s", res.Stdout)
134 }
135 return
136 }
137 if want := "Prose rewrite (writer: " + tc.writer + "; fact check: " + tc.checker + "; author: " + tc.author + ")"; !strings.Contains(res.Stdout, want) {
138 t.Errorf("output lacks %q:\n%s", want, res.Stdout)
139 }
140 if got := h.readE2E(tc.writer + ".calls"); !strings.Contains(got, "write") {
141 t.Errorf("%s wasn't asked to rewrite; calls: %q", tc.writer, got)
142 }
143 if got := h.readE2E(tc.checker + ".calls"); !strings.Contains(got, "check") {
144 t.Errorf("%s wasn't asked to fact-check; calls: %q", tc.checker, got)
145 }
146 if !strings.Contains(res.Stdout, "[1] README.md: passed") {
147 t.Errorf("the rewrite didn't pass:\n%s", res.Stdout)
148 }
149 })
150 }
151}
152
153// TestPreReviewProseRewrite: the writer, at agy's prose model, gets the
154// change's prose hunks and its commit message, not its code; a fact-check
155// failure surfaces against its rewrite and keeps it out of the patch, which
156// applies the rest. A file that isn't UTF-8 reaches the writer and the peer
157// reviewer named, as valid UTF-8. The pass is recorded as a prose job.
158func TestPreReviewProseRewrite(t *testing.T) {
159 t.Parallel()
160 h := NewHarness(t)
161 h.stubProseBackends("claude", map[string]any{})
162 message := "Add a deploy note\n\nThe README now says where to deploy and when, because operators kept deploying straight to production from feature branches before the smoke test had finished running on the build host."
163 h.commitFiles(map[string]string{
164 "README.md": proseReadme,
165 "docs/guide.md": "# Guide\n\nIn order to be able to run the tool, you will need to install it first.\n",
166 "main.go": "package main\n\nfunc main() { println(\"secret code text\") }\n",
167 "docs/legacy.md": "# Caf\xe9\n", // Latin-1
168 }, message)
169 h.stubAnswer("agy", "write", map[string]any{
170 "ledger": []any{
171 map[string]any{"id": "C1", "where": "README.md", "claim": "deploy to the build host first"},
172 map[string]any{"id": "C2", "where": "README.md", "claim": "only from main", "conditions": []string{"after the smoke test"}},
173 },
174 "edits": []any{
175 map[string]any{"file": "README.md", "old": "Deploy to the build host first, but only from main, once the smoke test passes.", "new": "Deploy to the build host first.", "claims": []string{"C1", "C2"}},
176 map[string]any{"file": "COMMIT_EDITMSG", "old": "The README now says where to deploy and when, because operators kept deploying straight to production from feature branches before the smoke test had finished running on the build host.", "new": "Operators deployed from feature branches before the smoke test finished."},
177 map[string]any{"file": "docs/guide.md", "old": "In order to be able to run the tool, you will need to install it first.", "new": "Install the tool before running it."},
178 map[string]any{"file": "main.go", "old": "secret code text", "new": "other"},
179 map[string]any{"file": "README.md", "old": "# widget\n\nDeploy to the build host first, but only from main, once the smoke test passes.", "new": "Deploy from main."},
180 },
181 })
182 h.stubAnswer("codex", "check", map[string]any{"failures": []any{
183 map[string]any{"edit": 1, "claim": "C2", "problem": "dropped the condition: only from main, after the smoke test"},
184 }})
185
186 res := h.RunKlaus("_pre-review")
187 if res.ExitCode != 0 || !strings.Contains(res.Stdout, "All checks passed.") {
188 t.Fatalf("_pre-review exit %d\n%s%s", res.ExitCode, res.Stdout, res.Stderr)
189 }
190 prompt := h.readE2E("agy.write.stdin")
191 for _, want := range []string{"+Deploy to the build host first, but only from main", "+In order to be able to run the tool", "operators kept deploying straight to production", "Ledger: before rewriting", "Say what a reader can't easily infer"} {
192 if !strings.Contains(prompt, want) {
193 t.Errorf("the writer's prompt lacks %q:\n%s", want, prompt)
194 }
195 }
196 if strings.Contains(prompt, "secret code text") {
197 t.Errorf("the writer got a code file that isn't prose:\n%s", prompt)
198 }
199 if args := h.readE2E("agy.write.args"); !strings.Contains(args, "--model gemini-4-hydrogen-high") {
200 t.Errorf("the writer didn't run at agy's prose model: %s", args)
201 }
202 for _, f := range []string{"agy.write.stdin", "claude.review.stdin"} {
203 got := h.readE2E(f)
204 if !utf8.ValidString(got) || !strings.Contains(got, "+++ b/docs/legacy.md\n"+git.NotText+"\n") {
205 t.Errorf("%s isn't valid UTF-8 naming docs/legacy.md without its content:\n%q", f, got)
206 }
207 }
208 if check := h.readE2E("codex.check.stdin"); !strings.Contains(check, "only from main") || !strings.Contains(check, "Install the tool before running it.") {
209 t.Errorf("the fact check didn't get the ledger and rewrites:\n%s", check)
210 }
211 for _, want := range []string{
212 "[1] README.md: failed the fact check",
213 "✗ C2: dropped the condition: only from main, after the smoke test",
214 "[2] commit message: passed",
215 "[3] docs/guide.md: passed",
216 "[4] main.go: skipped: not prose this change adds",
217 "[5] README.md: skipped: it rewrites text the change didn't add",
218 "Say in your final report what you applied",
219 } {
220 if !strings.Contains(res.Stdout, want) {
221 t.Errorf("output lacks %q:\n%s", want, res.Stdout)
222 }
223 }
224
225 patch := field(res.Stdout, "Patch of the passing rewrites: git apply ")
226 msgFile := field(res.Stdout, "Commit message with its passing rewrites: git commit --amend -F ")
227 if patch == "" || msgFile == "" {
228 t.Fatalf("no patch or commit message file:\n%s", res.Stdout)
229 }
230 if out, err := exec.Command("git", "-C", h.RepoDir, "apply", patch).CombinedOutput(); err != nil {
231 t.Fatalf("git apply %s: %v\n%s", patch, err, out)
232 }
233 if got, _ := os.ReadFile(filepath.Join(h.RepoDir, "docs/guide.md")); !strings.Contains(string(got), "Install the tool before running it.") {
234 t.Errorf("the patch didn't rewrite docs/guide.md:\n%s", got)
235 }
236 if got, _ := os.ReadFile(filepath.Join(h.RepoDir, "README.md")); string(got) != proseReadme {
237 t.Errorf("the patch has the rewrite that failed the fact check:\n%s", got)
238 }
239 if got, _ := os.ReadFile(msgFile); !strings.HasPrefix(string(got), "Add a deploy note\n\nOperators deployed from feature branches") {
240 t.Errorf("commit message file = %q", got)
241 }
242
243 jobsOut := h.RunKlaus("jobs")
244 if !strings.Contains(jobsOut.Stdout, "prose") || !strings.Contains(jobsOut.Stdout, "agy") {
245 t.Fatalf("klaus jobs doesn't list the prose pass:\n%s%s", jobsOut.Stdout, jobsOut.Stderr)
246 }
247 id := strings.Fields(strings.Split(jobsOut.Stdout, "\n")[2])[0]
248 show := h.RunKlaus("jobs", "show", id)
249 if !strings.Contains(show.Stdout, "[1] README.md: failed the fact check") || !strings.Contains(show.Stdout, "agy gemini-4-hydrogen-high") {
250 t.Errorf("klaus jobs show lacks the proposal or the writer's model:\n%s%s", show.Stdout, show.Stderr)
251 }
252}
253
254// field is the rest of out's line that starts, after spaces, with prefix,
255// without the single quotes of a quoted path.
256func field(out, prefix string) string {
257 for _, l := range strings.Split(out, "\n") {
258 if rest, ok := strings.CutPrefix(strings.TrimSpace(l), prefix); ok {
259 return strings.Trim(rest, "'")
260 }
261 }
262 return ""
263}
264
265// TestPreReviewProseNeverBlocks: a writer that fails, hangs past
266// timeout_seconds or answers nonsense, or a fact check that fails, is
267// reported, offers no patch, and _pre-review passes.
268func TestPreReviewProseNeverBlocks(t *testing.T) {
269 t.Parallel()
270 for _, tc := range []struct {
271 name, file, content, want string
272 }{
273 {"fails", "agy.write.fail", "", "The rewrite failed: consult agy: exit status 3: boom"},
274 {"hangs", "agy.write.sleep", "", "The rewrite failed: consult agy timed out"},
275 {"nonsense", "agy.write", "I rewrote it nicely.", "The rewrite failed: agy's rewrite: no JSON object"},
276 {"check fails", "codex.check.fail", "", "The fact check failed: consult codex: exit status 3: boom"},
277 } {
278 t.Run(tc.name, func(t *testing.T) {
279 t.Parallel()
280 h := NewHarness(t)
281 h.stubProseBackends("claude", map[string]any{"timeout_seconds": 1})
282 h.commitFiles(map[string]string{"README.md": proseReadme}, "add deploy note")
283 h.stubAnswer("agy", "write", map[string]any{"edits": []any{map[string]any{
284 "file": "README.md", "old": "Deploy to the build host first, but only from main, once the smoke test passes.", "new": "Deploy from main."}}})
285 h.writeE2E(tc.file, tc.content) // the nonsense case replaces the answer
286
287 start := time.Now()
288 res := h.RunKlaus("_pre-review")
289 if res.ExitCode != 0 || !strings.Contains(res.Stdout, "All checks passed.") {
290 t.Fatalf("_pre-review exit %d\n%s%s", res.ExitCode, res.Stdout, res.Stderr)
291 }
292 if !strings.Contains(res.Stdout, tc.want) {
293 t.Errorf("output lacks %q:\n%s", tc.want, res.Stdout)
294 }
295 if strings.Contains(res.Stdout, "git apply") {
296 t.Errorf("a pass that didn't finish offered a patch:\n%s", res.Stdout)
297 }
298 if d := time.Since(start); d > 20*time.Second {
299 t.Errorf("_pre-review took %s with a 1s prose timeout", d)
300 }
301 })
302 }
303}
304
305// TestPreReviewProseConfig: enabled false turns the pass off; paths makes a
306// code file's added lines prose; a change with only code and a short commit
307// message is skipped.
308func TestPreReviewProseConfig(t *testing.T) {
309 t.Parallel()
310 code := map[string]string{"main.go": "package main\n\nfunc main() { println(\"Usage: widget [flags]\") }\n"}
311 for _, tc := range []struct {
312 name string
313 prose map[string]any
314 want string
315 writes bool
316 }{
317 {"off", map[string]any{"enabled": false}, "Prose rewrite: off (pre_review.prose.enabled).", false},
318 {"code only", map[string]any{}, "Skipped: no prose beyond a short commit message.", false},
319 {"paths", map[string]any{"paths": []string{"*.go"}}, "No rewrites proposed.", true},
320 } {
321 t.Run(tc.name, func(t *testing.T) {
322 t.Parallel()
323 h := NewHarness(t)
324 h.stubProseBackends("claude", tc.prose)
325 files := code
326 if tc.name == "off" {
327 files = map[string]string{"README.md": proseReadme}
328 }
329 h.commitFiles(files, "add usage")
330
331 res := h.RunKlaus("_pre-review")
332 if res.ExitCode != 0 || !strings.Contains(res.Stdout, "All checks passed.") {
333 t.Fatalf("_pre-review exit %d\n%s%s", res.ExitCode, res.Stdout, res.Stderr)
334 }
335 if !strings.Contains(res.Stdout, tc.want) {
336 t.Errorf("output lacks %q:\n%s", tc.want, res.Stdout)
337 }
338 calls := h.readE2E("agy.calls")
339 if strings.Contains(calls, "write") != tc.writes {
340 t.Errorf("agy calls %q; want a rewrite: %v", calls, tc.writes)
341 }
342 if tc.writes && !strings.Contains(h.readE2E("agy.write.stdin"), `+func main() { println("Usage: widget [flags]") }`) {
343 t.Errorf("the writer didn't get main.go:\n%s", h.readE2E("agy.write.stdin"))
344 }
345 })
346 }
347}