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