gunk-dev/the-valley

runevents_test.go

source88a5a486b52fmain's published tip history
12.0 KiB
1package cmd
2
3import (
4 "io/fs"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "strconv"
9 "strings"
10 "testing"
11
12 "the-valley/flow/internal/event"
13 "the-valley/flow/internal/run"
14)
15
16// TestFormatStreamEmitsCheckEvents pipes a Claude stream through the real
17// klaus _format-stream, as an agent's pane does, and checks it reports the
18// stream's test run as a check of the pane's run (KLAUS_RUN_ID), with the
19// run's keys, and nothing for _pre-review, which reports itself. A command
20// line that runs go vet and then _pre-review is a lint check that says it
21// includes the pre-review. Outside a run's pane it reports nothing.
22func TestFormatStreamEmitsCheckEvents(t *testing.T) {
23 bin := klausBinary(t)
24 home := t.TempDir()
25 const session, id = "session-20261020-1200-abcd", "20261020-1200-0badc0de"
26 store := run.NewHomeDirStoreFromPath(filepath.Join(home, ".klaus", "sessions", session))
27 pr, prURL := "12", "https://github.com/acme/widget/pull/12"
28 if err := store.Save(&run.State{ID: id, ChangeID: "kkkkllllmmmmnnnnooooppppqqqqrrrr", PR: &pr, PRURL: &prURL,
29 DispatchReason: event.DispatchCIFix, HeadSHA: "0123456789abcdef0123456789abcdef01234567", CreatedAt: "2026-10-20T12:00:00Z"}); err != nil {
30 t.Fatal(err)
31 }
32 stream := strings.Join([]string{
33 `{"type":"assistant","message":{"content":[{"type":"tool_use","id":"t1","name":"Bash","input":{"command":"go test ./..."}}]}}`,
34 `{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"t1","is_error":false,"content":"ok"}]}}`,
35 `{"type":"assistant","message":{"content":[{"type":"tool_use","id":"t2","name":"Bash","input":{"command":"klaus _pre-review"}}]}}`,
36 `{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"t2","is_error":false,"content":"All checks passed."}]}}`,
37 `{"type":"assistant","message":{"content":[{"type":"tool_use","id":"t3","name":"Bash","input":{"command":"go vet ./... && klaus _pre-review"}}]}}`,
38 `{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"t3","is_error":true,"content":"1 high+ finding"}]}}`,
39 `{"type":"result","subtype":"success","total_cost_usd":0.1,"duration_ms":1000}`,
40 }, "\n") + "\n"
41
42 format := func(runID string) string {
43 c := exec.Command(bin, "_format-stream")
44 c.Env = append(os.Environ(), "HOME="+home, sessionIDEnv+"="+session, runIDEnv+"="+runID)
45 c.Stdin = strings.NewReader(stream)
46 out, err := c.CombinedOutput()
47 if err != nil {
48 t.Fatalf("_format-stream: %v\n%s", err, out)
49 }
50 return string(out)
51 }
52
53 if out := format(id); !strings.Contains(out, "▶ Bash: go test ./...") {
54 t.Errorf("_format-stream should still format the stream:\n%s", out)
55 }
56 evts, err := event.NewLog(store.BaseDir()).Read()
57 if err != nil {
58 t.Fatal(err)
59 }
60 var types []string
61 for _, e := range evts {
62 types = append(types, e.Type)
63 }
64 if got, want := strings.Join(types, " "), "check:started check:completed check:started check:completed"; got != want {
65 t.Fatalf("want check:started and check:completed for go test and go vet, got %+v", evts)
66 }
67 for i, e := range evts {
68 if e.RunID != id {
69 t.Errorf("%s on run %q, want %s", e.Type, e.RunID, id)
70 }
71 check := map[string]interface{}{"kind": "test", "command": "go test ./...", "includes_pre_review": nil}
72 if i >= 2 {
73 check = map[string]interface{}{"kind": "lint", "command": "go vet ./... && klaus _pre-review", "includes_pre_review": true}
74 }
75 for k, want := range map[string]interface{}{
76 "kind": check["kind"], "command": check["command"], "includes_pre_review": check["includes_pre_review"], "source": "stream",
77 "repo_key": "acme/widget", "pr_number": "12", "key": "acme/widget#12",
78 "change_id": "kkkkllllmmmmnnnnooooppppqqqqrrrr", "dispatch_reason": "ci-fix",
79 "head_sha": "0123456789abcdef0123456789abcdef01234567",
80 } {
81 if e.Data[k] != want {
82 t.Errorf("%s %s = %v, want %v", e.Type, k, e.Data[k], want)
83 }
84 }
85 }
86 if done := evts[1].Data; done["success"] != true || done["duration_ms"] == nil || done["ended_at"] == nil {
87 t.Errorf("check:completed should carry success, duration_ms and ended_at: %+v", done)
88 }
89 if done := evts[3].Data; done["success"] != false {
90 t.Errorf("the go vet and _pre-review line failed: %+v", done)
91 }
92
93 format("")
94 if after, _ := event.NewLog(store.BaseDir()).Read(); len(after) != len(evts) {
95 t.Errorf("_format-stream outside a run's pane emitted %+v", after[len(evts):])
96 }
97}
98
99// TestPreReviewEmitsCheckEvents runs the real klaus _pre-review in a run's
100// pane (KLAUS_RUN_ID) on a branch with nothing to review, once with a linter
101// that passes and once with one that fails, and checks each run is a
102// pre-review check of that run, which says how it ended, even when
103// _pre-review exits 1.
104func TestPreReviewEmitsCheckEvents(t *testing.T) {
105 bin := klausBinary(t)
106 home := t.TempDir()
107 const session, id = "session-20261020-1300-abcd", "20261020-1300-feedface"
108 store := run.NewHomeDirStoreFromPath(filepath.Join(home, ".klaus", "sessions", session))
109 if err := store.Save(&run.State{ID: id, ChangeID: "kkkkllllmmmmnnnnooooppppqqqqrrrr", RepoKey: "valley:widget",
110 DispatchReason: event.DispatchLaunch, CreatedAt: "2026-10-20T13:00:00Z"}); err != nil {
111 t.Fatal(err)
112 }
113 repo := t.TempDir()
114 gitIn := func(args ...string) {
115 t.Helper()
116 c := exec.Command("git", append([]string{"-C", repo, "-c", "user.name=t", "-c", "user.email=t@example.com"}, args...)...)
117 if out, err := c.CombinedOutput(); err != nil {
118 t.Fatalf("git %v: %v\n%s", args, err, out)
119 }
120 }
121 gitIn("init", "-q", "-b", "main")
122 gitIn("commit", "-q", "--allow-empty", "-m", "base")
123
124 preReview := func(linter string) error {
125 if err := os.MkdirAll(filepath.Join(repo, ".klaus"), 0o755); err != nil {
126 t.Fatal(err)
127 }
128 cfg := `{"pre_review": {"linters": [` + strconv.Quote(linter) + `]}}`
129 if err := os.WriteFile(filepath.Join(repo, ".klaus", "config.json"), []byte(cfg), 0o644); err != nil {
130 t.Fatal(err)
131 }
132 c := exec.Command(bin, "_pre-review", "--dir", repo)
133 c.Env = append(os.Environ(), "HOME="+home, sessionIDEnv+"="+session, runIDEnv+"="+id, "KLAUS_BACKEND=claude")
134 out, err := c.CombinedOutput()
135 t.Logf("_pre-review with %s:\n%s", linter, out)
136 return err
137 }
138
139 if err := preReview("true"); err != nil {
140 t.Fatalf("_pre-review with a passing linter: %v", err)
141 }
142 if err := preReview("false"); err == nil {
143 t.Fatal("_pre-review with a failing linter should exit 1")
144 }
145
146 evts, err := event.NewLog(store.BaseDir()).Read()
147 if err != nil {
148 t.Fatal(err)
149 }
150 var types []string
151 for _, e := range evts {
152 types = append(types, e.Type)
153 if e.RunID != id || e.Data["kind"] != "pre-review" || e.Data["source"] != "pre-review" ||
154 e.Data["repo_key"] != "valley:widget" || e.Data["key"] != "valley:widget@kkkkllllmmmmnnnnooooppppqqqqrrrr" || e.Data["dispatch_reason"] != "launch" {
155 t.Errorf("%s: %+v", e.Type, e.Data)
156 }
157 }
158 if got, want := strings.Join(types, " "), "check:started check:completed check:started check:completed"; got != want {
159 t.Fatalf("events %s, want %s", got, want)
160 }
161 if d := evts[1].Data; d["success"] != true || d["lint_failed"] != false || d["findings"] != float64(0) || d["duration_ms"] == nil {
162 t.Errorf("passing _pre-review completed with %+v", d)
163 }
164 if d := evts[3].Data; d["success"] != false || d["lint_failed"] != true {
165 t.Errorf("failing _pre-review completed with %+v", d)
166 }
167}
168
169// TestSandboxPreReviewReachesTheRun runs a sandbox run's real pane command:
170// ssh is a stub that runs the remote command as another host would, with its
171// own HOME and none of the pane's environment, and the agent is a script
172// that streams a call to the real klaus _pre-review and its output. The
173// sandbox has no event log for the run, so _pre-review reports its check in
174// its output, and the pane's _format-stream records it on the run. When the
175// agent cuts the output, as with tail, _format-stream times the call from
176// the stream instead. Nothing is written on the sandbox's side.
177func TestSandboxPreReviewReachesTheRun(t *testing.T) {
178 bin := klausBinary(t)
179 for _, tc := range []struct {
180 name, filter string
181 want map[string]interface{}
182 }{
183 {"reported", "", map[string]interface{}{"source": "pre-review", "via": "stream", "command": "klaus _pre-review", "findings": float64(0), "lint_failed": false}},
184 {"output cut", " | tail -1", map[string]interface{}{"source": "stream", "via": nil, "findings": nil}},
185 } {
186 t.Run(tc.name, func(t *testing.T) {
187 dir, home, remoteHome := t.TempDir(), t.TempDir(), t.TempDir()
188 const session, id = "session-20261021-0100-abcd", "20261021-0100-5a4db0c5"
189 store := run.NewHomeDirStoreFromPath(filepath.Join(home, ".klaus", "sessions", session))
190 if err := store.Save(&run.State{ID: id, ChangeID: "kkkkllllmmmmnnnnooooppppqqqqrrrr", RepoKey: "acme/widget",
191 DispatchReason: event.DispatchLaunch, CreatedAt: "2026-10-21T01:00:00Z"}); err != nil {
192 t.Fatal(err)
193 }
194 worktree := filepath.Join(dir, "worktree")
195 for _, args := range [][]string{{"init", "-q", "-b", "main", worktree}, {"-C", worktree, "-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-q", "--allow-empty", "-m", "base"}} {
196 if out, err := exec.Command("git", args...).CombinedOutput(); err != nil {
197 t.Fatalf("git %v: %v\n%s", args, err, out)
198 }
199 }
200 if err := os.MkdirAll(filepath.Join(worktree, ".klaus"), 0o755); err != nil {
201 t.Fatal(err)
202 }
203 if err := os.WriteFile(filepath.Join(worktree, ".klaus", "config.json"), []byte(`{"pre_review": {"linters": ["true"]}}`), 0o644); err != nil {
204 t.Fatal(err)
205 }
206
207 stubs := filepath.Join(dir, "bin")
208 if err := os.Mkdir(stubs, 0o755); err != nil {
209 t.Fatal(err)
210 }
211 preReview := "klaus _pre-review --dir " + worktree + tc.filter
212 agent := `#!/bin/sh
213cat >/dev/null
214echo '{"type":"assistant","message":{"content":[{"type":"tool_use","id":"t1","name":"Bash","input":{"command":"` + preReview + `"}}]}}'
215out=$(` + preReview + ` 2>&1)
216esc=$(printf '%s\n' "$out" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/ /\\t/g' | awk '{printf "%s\\n", $0}')
217printf '{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"t1","is_error":false,"content":"%s"}]}}\n' "$esc"
218echo '{"type":"result","subtype":"success","total_cost_usd":0.1,"duration_ms":1000}'
219`
220 for name, script := range map[string]string{
221 "ssh": "#!/bin/sh\nshift\nexec env -u " + runIDEnv + " -u " + sessionIDEnv + " HOME=" + shellQuote(remoteHome) + " sh -c \"$1\"\n",
222 "rsync": "#!/bin/sh\nexit 0\n",
223 "klaus": "#!/bin/sh\n[ \"$1\" = _finalize ] && exit 0\nexec " + shellQuote(bin) + " \"$@\"\n",
224 "agent": agent,
225 } {
226 if err := os.WriteFile(filepath.Join(stubs, name), []byte(script), 0o755); err != nil {
227 t.Fatal(err)
228 }
229 }
230
231 t.Setenv(sessionIDEnv, session)
232 command := buildSandboxPaneCommand("sandbox-0", worktree, "KLAUS_BACKEND=claude agent", "", filepath.Join(dir, "log.jsonl"), "klaus", "", id)
233 c := exec.Command("sh", "-c", command)
234 c.Env = append(os.Environ(), "HOME="+home, "PATH="+stubs+":"+os.Getenv("PATH"))
235 out, err := c.CombinedOutput()
236 if err != nil {
237 t.Fatalf("pane command: %v\n%s", err, out)
238 }
239 log, _ := os.ReadFile(filepath.Join(dir, "log.jsonl"))
240 t.Logf("stream:\n%s", log)
241
242 evts, err := event.NewLog(store.BaseDir()).Read()
243 if err != nil {
244 t.Fatal(err)
245 }
246 if len(evts) != 2 || evts[0].Type != event.CheckStarted || evts[1].Type != event.CheckCompleted {
247 t.Fatalf("want check:started and check:completed for the pre-review, got %+v", evts)
248 }
249 done := evts[1].Data
250 want := map[string]interface{}{"kind": "pre-review", "success": true, "repo_key": "acme/widget", "dispatch_reason": "launch",
251 "key": "acme/widget@kkkkllllmmmmnnnnooooppppqqqqrrrr"}
252 for k, v := range tc.want {
253 want[k] = v
254 }
255 for k, v := range want {
256 if done[k] != v {
257 t.Errorf("check:completed %s = %v, want %v", k, done[k], v)
258 }
259 }
260 if evts[1].RunID != id || done["duration_ms"] == nil || done["started_at"] == nil || done["ended_at"] == nil {
261 t.Errorf("check:completed on %s with %+v", evts[1].RunID, done)
262 }
263
264 filepath.WalkDir(remoteHome, func(path string, d fs.DirEntry, err error) error {
265 if err == nil && !d.IsDir() {
266 t.Errorf("the sandbox side wrote %s", path)
267 }
268 return nil
269 })
270 })
271 }
272}