gunk-dev/the-valley

checks.go

sourceccb7354855a5main's published tip history
12.8 KiB
1package stream
2
3import (
4 "encoding/json"
5 "regexp"
6 "strings"
7 "time"
8
9 "the-valley/flow/internal/event"
10)
11
12// Check is a build, test or lint command an agent ran, as its stream shows
13// it.
14type Check struct {
15 // Kind is event.CheckBuild, event.CheckTest or event.CheckLint, or
16 // event.CheckPreReview for a sandbox run's _pre-review timed from the
17 // stream.
18 Kind string
19 Command string // the command's first line
20 Start time.Time
21 // IncludesPreReview says the command line also runs klaus _pre-review,
22 // which reports its own check: that part of the check's time is the
23 // pre-review's.
24 IncludesPreReview bool
25}
26
27// ReportPrefix starts a line a klaus command prints to report a check of the
28// run it runs in when it can't reach the run's event log, as on a sandbox
29// host: the prefix, then the check:completed event's data as JSON. The line
30// reaches the pane's _format-stream in the tool result of the agent's call.
31const ReportPrefix = "klaus-check-completed: "
32
33// CheckWatcher finds the checks in an agent's stream as it arrives, and times
34// each from the line that calls its command to the line with its result.
35// Claude's calls and results carry IDs, so parallel calls pair up; Codex's
36// and agy's don't, and pair in order. Lines go to Observe as NormalizeLine
37// makes them.
38type CheckWatcher struct {
39 OnStart func(c Check)
40 // OnEnd gets success when the result says, nil when it doesn't.
41 OnEnd func(c Check, end time.Time, success *bool)
42 // OnReport gets the check:completed data of each check reported in the
43 // result of a call that runs klaus _pre-review (ReportPrefix lines).
44 OnReport func(data map[string]interface{})
45 // Sandbox says the agent runs on a sandbox host, where _pre-review
46 // reports in its output. A call that runs it and no other check, whose
47 // result reports nothing (the output was cut, or the host's klaus
48 // predates reports), is timed from the stream as a pre-review check
49 // instead. A line that runs another check first may have stopped before
50 // _pre-review, so it gets none.
51 Sandbox bool
52
53 byID map[string]*Check
54 queue []*Check // calls without IDs, in order; nil for a call the watcher doesn't time
55}
56
57// Observe takes one normalized stream line, seen at now.
58func (w *CheckWatcher) Observe(line []byte, now time.Time) {
59 var ev struct {
60 Type string `json:"type"`
61 Content json.RawMessage `json:"content"`
62 Message *struct {
63 Content []struct {
64 Type string `json:"type"`
65 ID string `json:"id"`
66 Input json.RawMessage `json:"input"`
67 ToolUseID string `json:"tool_use_id"`
68 IsError *bool `json:"is_error"`
69 Content json.RawMessage `json:"content"`
70 } `json:"content"`
71 } `json:"message"`
72 }
73 if json.Unmarshal(line, &ev) != nil {
74 return
75 }
76 switch ev.Type {
77 case "assistant":
78 if ev.Message == nil {
79 return
80 }
81 for _, b := range ev.Message.Content {
82 if b.Type != "tool_use" {
83 continue
84 }
85 c := callCheck(b.Input, now)
86 if b.ID == "" {
87 w.queue = append(w.queue, c)
88 } else if c != nil {
89 if w.byID == nil {
90 w.byID = map[string]*Check{}
91 }
92 w.byID[b.ID] = c
93 }
94 if c != nil && c.Kind != "" && w.OnStart != nil {
95 w.OnStart(*c)
96 }
97 }
98 case "user":
99 if ev.Message == nil {
100 return
101 }
102 for _, b := range ev.Message.Content {
103 c, ok := w.byID[b.ToolUseID]
104 if b.Type != "tool_result" || !ok {
105 continue
106 }
107 delete(w.byID, b.ToolUseID)
108 var success *bool
109 if b.IsError != nil {
110 passed := !*b.IsError
111 success = &passed
112 }
113 w.end(c, now, success, b.Content)
114 }
115 case "tool_result":
116 if len(w.queue) == 0 {
117 return
118 }
119 c := w.queue[0]
120 w.queue = w.queue[1:]
121 if c != nil {
122 w.end(c, now, nil, ev.Content)
123 }
124 }
125}
126
127// callCheck returns what the watcher times of a tool call: the check its
128// command runs, with Kind "" for one that runs only klaus _pre-review. It is
129// nil for a call that runs neither, or runs in the background, where its
130// result comes back before it ends.
131func callCheck(input json.RawMessage, now time.Time) *Check {
132 cmd, background := toolCommand(input)
133 if cmd == "" || background {
134 return nil
135 }
136 kind, preReview := CheckKind(cmd), RunsPreReview(cmd)
137 if kind == "" && !preReview {
138 return nil
139 }
140 return &Check{Kind: kind, Command: firstLine(cmd), Start: now, IncludesPreReview: preReview}
141}
142
143// end ends a call at its result: its check, then the pre-review checks its
144// output reports.
145func (w *CheckWatcher) end(c *Check, now time.Time, success *bool, output json.RawMessage) {
146 if c.Kind != "" && w.OnEnd != nil {
147 w.OnEnd(*c, now, success)
148 }
149 if !c.IncludesPreReview {
150 return
151 }
152 reports := checkReports(resultText(output))
153 for _, r := range reports {
154 if w.OnReport != nil {
155 w.OnReport(r)
156 }
157 }
158 if len(reports) == 0 && w.Sandbox && c.Kind == "" {
159 p := Check{Kind: event.CheckPreReview, Command: c.Command, Start: c.Start}
160 if w.OnStart != nil {
161 w.OnStart(p)
162 }
163 if w.OnEnd != nil {
164 w.OnEnd(p, now, success)
165 }
166 }
167}
168
169// resultText is a tool result's output: a string, or Claude's text blocks.
170func resultText(raw json.RawMessage) string {
171 var s string
172 if json.Unmarshal(raw, &s) == nil {
173 return s
174 }
175 var blocks []struct {
176 Type string `json:"type"`
177 Text string `json:"text"`
178 }
179 if json.Unmarshal(raw, &blocks) != nil {
180 return ""
181 }
182 var b strings.Builder
183 for _, bl := range blocks {
184 if bl.Type == "text" {
185 b.WriteString(bl.Text)
186 b.WriteByte('\n')
187 }
188 }
189 return b.String()
190}
191
192// checkReports returns the data of the checks output reports (ReportPrefix).
193func checkReports(output string) []map[string]interface{} {
194 var reports []map[string]interface{}
195 for _, line := range strings.Split(output, "\n") {
196 i := strings.Index(line, ReportPrefix)
197 if i < 0 {
198 continue
199 }
200 var data map[string]interface{}
201 if json.Unmarshal([]byte(strings.TrimSpace(line[i+len(ReportPrefix):])), &data) != nil {
202 continue
203 }
204 if kind, _ := data["kind"].(string); kind != "" {
205 reports = append(reports, data)
206 }
207 }
208 return reports
209}
210
211// toolCommand returns the shell command a tool call runs, "" for a call that
212// runs none, and whether it runs in the background, where its result comes
213// back before it ends. Claude and Codex name it command; agy's names vary.
214func toolCommand(input json.RawMessage) (string, bool) {
215 var in struct {
216 Command string `json:"command"`
217 CommandLine string `json:"CommandLine"`
218 Cmd string `json:"cmd"`
219 Background bool `json:"run_in_background"`
220 }
221 if len(input) == 0 || json.Unmarshal(input, &in) != nil {
222 return "", false
223 }
224 for _, c := range []string{in.Command, in.CommandLine, in.Cmd} {
225 if c != "" {
226 return c, in.Background
227 }
228 }
229 return "", false
230}
231
232func firstLine(s string) string {
233 s = strings.TrimSpace(s)
234 if i := strings.IndexByte(s, '\n'); i >= 0 {
235 s = s[:i]
236 }
237 if len(s) > 200 {
238 s = s[:200]
239 }
240 return s
241}
242
243// checkCommands are the command lines CheckKind knows, by the words they
244// start with. make is decided by its target.
245var checkCommands = []struct {
246 kind string
247 words []string
248}{
249 {event.CheckTest, []string{"go", "test"}},
250 {event.CheckTest, []string{"cargo", "test"}},
251 {event.CheckTest, []string{"cargo", "nextest"}},
252 {event.CheckTest, []string{"npm", "test"}},
253 {event.CheckTest, []string{"npm", "run", "test"}},
254 {event.CheckTest, []string{"yarn", "test"}},
255 {event.CheckTest, []string{"pnpm", "test"}},
256 {event.CheckTest, []string{"bun", "test"}},
257 {event.CheckTest, []string{"deno", "test"}},
258 {event.CheckTest, []string{"pytest"}},
259 {event.CheckTest, []string{"python", "-m", "pytest"}},
260 {event.CheckTest, []string{"python3", "-m", "pytest"}},
261 {event.CheckTest, []string{"npx", "jest"}},
262 {event.CheckTest, []string{"npx", "vitest"}},
263 {event.CheckTest, []string{"jest"}},
264 {event.CheckTest, []string{"vitest"}},
265 {event.CheckTest, []string{"nix", "flake", "check"}},
266 {event.CheckTest, []string{"mvn", "test"}},
267 {event.CheckTest, []string{"gradle", "test"}},
268 {event.CheckTest, []string{"./gradlew", "test"}},
269 {event.CheckTest, []string{"bazel", "test"}},
270 {event.CheckTest, []string{"dotnet", "test"}},
271 {event.CheckTest, []string{"mix", "test"}},
272 {event.CheckTest, []string{"ctest"}},
273 {event.CheckTest, []string{"tox"}},
274 {event.CheckTest, []string{"rspec"}},
275 {event.CheckLint, []string{"go", "vet"}},
276 {event.CheckLint, []string{"golangci-lint"}},
277 {event.CheckLint, []string{"staticcheck"}},
278 {event.CheckLint, []string{"cargo", "clippy"}},
279 {event.CheckLint, []string{"npm", "run", "lint"}},
280 {event.CheckLint, []string{"yarn", "lint"}},
281 {event.CheckLint, []string{"pnpm", "lint"}},
282 {event.CheckLint, []string{"eslint"}},
283 {event.CheckLint, []string{"npx", "eslint"}},
284 {event.CheckLint, []string{"ruff"}},
285 {event.CheckLint, []string{"flake8"}},
286 {event.CheckLint, []string{"mypy"}},
287 {event.CheckLint, []string{"pylint"}},
288 {event.CheckLint, []string{"shellcheck"}},
289 {event.CheckBuild, []string{"go", "build"}},
290 {event.CheckBuild, []string{"cargo", "build"}},
291 {event.CheckBuild, []string{"cargo", "check"}},
292 {event.CheckBuild, []string{"npm", "run", "build"}},
293 {event.CheckBuild, []string{"yarn", "build"}},
294 {event.CheckBuild, []string{"pnpm", "build"}},
295 {event.CheckBuild, []string{"tsc"}},
296 {event.CheckBuild, []string{"npx", "tsc"}},
297 {event.CheckBuild, []string{"nix", "build"}},
298 {event.CheckBuild, []string{"mvn", "package"}},
299 {event.CheckBuild, []string{"mvn", "compile"}},
300 {event.CheckBuild, []string{"gradle", "build"}},
301 {event.CheckBuild, []string{"./gradlew", "build"}},
302 {event.CheckBuild, []string{"bazel", "build"}},
303 {event.CheckBuild, []string{"dotnet", "build"}},
304 {event.CheckBuild, []string{"docker", "build"}},
305 {event.CheckBuild, []string{"cmake", "--build"}},
306}
307
308// checkRank orders kinds for a command line that runs several: a test run
309// usually takes longest, so it names the line.
310var checkRank = map[string]int{event.CheckBuild: 1, event.CheckLint: 2, event.CheckTest: 3}
311
312var segmentSep = regexp.MustCompile(`&&|\|\||[;|\n]`)
313
314// CheckKind returns the kind of check a shell command line runs, or "" when
315// it runs none CheckKind knows. Each command in the line counts (split at
316// &&, ||, ;, | and newlines), after any leading VAR=value assignments and
317// wrappers such as time, timeout or nix develop -c; the line takes the
318// highest kind among them, test over lint over build. klaus _pre-review is no
319// kind here: it reports itself (see RunsPreReview).
320func CheckKind(line string) string {
321 best := ""
322 for _, f := range lineCommands(line) {
323 if k := commandKind(f); checkRank[k] > checkRank[best] {
324 best = k
325 }
326 }
327 return best
328}
329
330// RunsPreReview reports whether a shell command line runs klaus _pre-review,
331// alone or among other commands.
332func RunsPreReview(line string) bool {
333 for _, f := range lineCommands(line) {
334 if len(f) > 1 && (f[0] == "klaus" || strings.HasSuffix(f[0], "/klaus")) && f[1] == "_pre-review" {
335 return true
336 }
337 }
338 return false
339}
340
341// lineCommands splits a command line into its commands' words, without the
342// wrappers before each.
343func lineCommands(line string) [][]string {
344 var cmds [][]string
345 for _, seg := range segmentSep.Split(line, -1) {
346 f := strings.Fields(seg)
347 for i := range f {
348 f[i] = strings.TrimRight(f[i], ")}")
349 }
350 if f = stripWrappers(f); len(f) > 0 {
351 cmds = append(cmds, f)
352 }
353 }
354 return cmds
355}
356
357// stripWrappers drops what runs before the command proper.
358func stripWrappers(f []string) []string {
359 for len(f) > 0 {
360 w := strings.TrimLeft(f[0], "({")
361 switch {
362 case w == "":
363 f = f[1:]
364 case w != f[0]:
365 f = append([]string{w}, f[1:]...)
366 case strings.Contains(w, "=") && !strings.HasPrefix(w, "-"):
367 f = f[1:] // VAR=value
368 case w == "time" || w == "env" || w == "command" || w == "exec" || w == "nice" || w == "sudo":
369 f = f[1:]
370 case w == "timeout" && len(f) > 1:
371 f = f[2:]
372 case w == "nix" && len(f) > 2 && f[1] == "develop" && (f[2] == "-c" || f[2] == "--command"):
373 f = f[3:]
374 default:
375 return f
376 }
377 }
378 return f
379}
380
381func commandKind(f []string) string {
382 if len(f) == 0 {
383 return ""
384 }
385 if f[0] == "make" || f[0] == "gmake" {
386 return makeKind(f[1:])
387 }
388 for _, c := range checkCommands {
389 if hasWords(f, c.words) {
390 return c.kind
391 }
392 }
393 return ""
394}
395
396func hasWords(f, words []string) bool {
397 if len(f) < len(words) {
398 return false
399 }
400 for i, w := range words {
401 if f[i] != w {
402 return false
403 }
404 }
405 return true
406}
407
408// makeKind decides a make run by its first target: test… and check… are
409// tests, lint… and vet… lint, anything else (the default target included)
410// a build.
411func makeKind(args []string) string {
412 for i := 0; i < len(args); i++ {
413 a := args[i]
414 switch {
415 case a == "-C" || a == "-f" || a == "-j" && i+1 < len(args) && !strings.HasPrefix(args[i+1], "-"):
416 i++
417 continue
418 case strings.HasPrefix(a, "-") || strings.Contains(a, "="):
419 continue
420 case strings.HasPrefix(a, "test") || strings.HasPrefix(a, "check"):
421 return event.CheckTest
422 case strings.HasPrefix(a, "lint") || strings.HasPrefix(a, "vet"):
423 return event.CheckLint
424 }
425 return event.CheckBuild
426 }
427 return event.CheckBuild
428}