| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "strconv" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "syscall" |
| 17 | "testing" |
| 18 | "time" |
| 19 | |
| 20 | "the-valley/flow/internal/event" |
| 21 | ) |
| 22 | |
| 23 | // TestWatchFilterMatches is a pure unit test for the genuinely-tricky filter |
| 24 | // helper. Everything else about 'klaus watch' is exercised via the real |
| 25 | // binary integration test below. |
| 26 | func TestWatchFilterMatches(t *testing.T) { |
| 27 | cases := []struct { |
| 28 | name string |
| 29 | include []string |
| 30 | exclude []string |
| 31 | eventType string |
| 32 | want bool |
| 33 | }{ |
| 34 | { |
| 35 | name: "empty include uses default filter; type in default included", |
| 36 | eventType: event.AgentPRCreated, |
| 37 | want: true, |
| 38 | }, |
| 39 | { |
| 40 | name: "empty include uses default filter; type not in default excluded", |
| 41 | eventType: event.AgentStarted, |
| 42 | want: false, |
| 43 | }, |
| 44 | { |
| 45 | name: "explicit include narrows to listed types", |
| 46 | include: []string{event.PRMerged}, |
| 47 | eventType: event.PRMerged, |
| 48 | want: true, |
| 49 | }, |
| 50 | { |
| 51 | name: "explicit include excludes everything else", |
| 52 | include: []string{event.PRMerged}, |
| 53 | eventType: event.AgentPRCreated, |
| 54 | want: false, |
| 55 | }, |
| 56 | { |
| 57 | name: "filter-out subtracts from default", |
| 58 | exclude: []string{event.PRApproved}, |
| 59 | eventType: event.PRApproved, |
| 60 | want: false, |
| 61 | }, |
| 62 | { |
| 63 | name: "filter-out subtracts from explicit include too", |
| 64 | include: []string{event.PRMerged, event.PRApproved}, |
| 65 | exclude: []string{event.PRApproved}, |
| 66 | eventType: event.PRApproved, |
| 67 | want: false, |
| 68 | }, |
| 69 | { |
| 70 | name: "blank entries in filter are ignored", |
| 71 | include: []string{"", " ", event.PRMerged}, |
| 72 | eventType: event.PRMerged, |
| 73 | want: true, |
| 74 | }, |
| 75 | { |
| 76 | name: "agent:branch-pushed is in default filter", |
| 77 | eventType: event.AgentBranchPushed, |
| 78 | want: true, |
| 79 | }, |
| 80 | { |
| 81 | name: "agent:needs-attention is in default filter", |
| 82 | eventType: event.AgentNeedsAttention, |
| 83 | want: true, |
| 84 | }, |
| 85 | { |
| 86 | name: "reserved type ci:failed is in default filter", |
| 87 | eventType: "ci:failed", |
| 88 | want: true, |
| 89 | }, |
| 90 | } |
| 91 | |
| 92 | for _, tc := range cases { |
| 93 | t.Run(tc.name, func(t *testing.T) { |
| 94 | f := buildFilter(tc.include, tc.exclude, nil) |
| 95 | got := f.matches(tc.eventType) |
| 96 | if got != tc.want { |
| 97 | t.Errorf("matches(%q) with include=%v exclude=%v = %v, want %v", |
| 98 | tc.eventType, tc.include, tc.exclude, got, tc.want) |
| 99 | } |
| 100 | }) |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | // TestTruncateLine verifies the genuinely tricky parts of truncateLine: rune |
| 105 | // (not byte) slicing so multi-byte UTF-8 characters survive truncation, and |
| 106 | // whitespace collapsing via strings.Fields. |
| 107 | func TestTruncateLine(t *testing.T) { |
| 108 | cases := []struct { |
| 109 | name string |
| 110 | in string |
| 111 | max int |
| 112 | want string |
| 113 | }{ |
| 114 | {"shorter than max passes through", "hello", 10, "hello"}, |
| 115 | {"collapses internal whitespace", "a\nb\tc d", 20, "a b c d"}, |
| 116 | {"trims leading and trailing whitespace", " hi ", 20, "hi"}, |
| 117 | {"truncates ASCII with ellipsis", "abcdefghij", 5, "abcd…"}, |
| 118 | {"counts runes not bytes for length check", "héllo", 5, "héllo"}, |
| 119 | {"truncates multi-byte runes without splitting", "日本語テスト", 4, "日本語…"}, |
| 120 | {"max==1 returns one rune (no ellipsis room)", "日本語", 1, "日"}, |
| 121 | } |
| 122 | for _, tc := range cases { |
| 123 | t.Run(tc.name, func(t *testing.T) { |
| 124 | got := truncateLine(tc.in, tc.max) |
| 125 | if got != tc.want { |
| 126 | t.Errorf("truncateLine(%q, %d) = %q, want %q", tc.in, tc.max, got, tc.want) |
| 127 | } |
| 128 | }) |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | // klausBinary lazily builds the real klaus binary and returns its path. All |
| 133 | // integration tests below run klaus as a subprocess so we exercise the full |
| 134 | // command surface including SIGTERM handling, line-buffered stdout, and |
| 135 | // fsnotify-driven streaming. |
| 136 | func klausBinary(t *testing.T) string { |
| 137 | t.Helper() |
| 138 | binDir := t.TempDir() |
| 139 | bin := filepath.Join(binDir, "klaus") |
| 140 | // internal/cmd is two levels below the module root. |
| 141 | cwd, err := os.Getwd() |
| 142 | if err != nil { |
| 143 | t.Fatalf("getwd: %v", err) |
| 144 | } |
| 145 | modRoot := filepath.Dir(filepath.Dir(cwd)) |
| 146 | build := exec.Command("go", "build", "-o", bin, "./cmd/klaus") |
| 147 | build.Dir = modRoot |
| 148 | build.Stderr = os.Stderr |
| 149 | if err := build.Run(); err != nil { |
| 150 | t.Fatalf("go build klaus: %v", err) |
| 151 | } |
| 152 | return bin |
| 153 | } |
| 154 | |
| 155 | type watchProc struct { |
| 156 | cmd *exec.Cmd |
| 157 | stdout *bufio.Scanner |
| 158 | stderr *bytes.Buffer |
| 159 | done chan error |
| 160 | } |
| 161 | |
| 162 | func startWatch(t *testing.T, bin, sessionID, home string, args ...string) *watchProc { |
| 163 | t.Helper() |
| 164 | all := append([]string{"watch", "--session-id", sessionID}, args...) |
| 165 | ctx, cancel := context.WithCancel(context.Background()) |
| 166 | t.Cleanup(cancel) |
| 167 | cmd := exec.CommandContext(ctx, bin, all...) |
| 168 | cmd.Env = append(os.Environ(), "HOME="+home) |
| 169 | |
| 170 | stdout, err := cmd.StdoutPipe() |
| 171 | if err != nil { |
| 172 | t.Fatalf("StdoutPipe: %v", err) |
| 173 | } |
| 174 | var stderr bytes.Buffer |
| 175 | cmd.Stderr = &stderr |
| 176 | |
| 177 | if err := cmd.Start(); err != nil { |
| 178 | t.Fatalf("starting klaus watch: %v", err) |
| 179 | } |
| 180 | |
| 181 | done := make(chan error, 1) |
| 182 | go func() { |
| 183 | done <- cmd.Wait() |
| 184 | }() |
| 185 | |
| 186 | scanner := bufio.NewScanner(stdout) |
| 187 | scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024) |
| 188 | return &watchProc{cmd: cmd, stdout: scanner, stderr: &stderr, done: done} |
| 189 | } |
| 190 | |
| 191 | func (p *watchProc) nextLine(t *testing.T, timeout time.Duration) string { |
| 192 | t.Helper() |
| 193 | type result struct { |
| 194 | line string |
| 195 | ok bool |
| 196 | } |
| 197 | ch := make(chan result, 1) |
| 198 | go func() { |
| 199 | ok := p.stdout.Scan() |
| 200 | ch <- result{line: p.stdout.Text(), ok: ok} |
| 201 | }() |
| 202 | select { |
| 203 | case r := <-ch: |
| 204 | if !r.ok { |
| 205 | t.Fatalf("klaus watch stdout closed (stderr: %s)", p.stderr.String()) |
| 206 | } |
| 207 | return r.line |
| 208 | case <-time.After(timeout): |
| 209 | t.Fatalf("timed out waiting for line from klaus watch (stderr: %s)", p.stderr.String()) |
| 210 | return "" |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | // stopSIGTERM sends SIGTERM and verifies the process exits cleanly. |
| 215 | func (p *watchProc) stopSIGTERM(t *testing.T) { |
| 216 | t.Helper() |
| 217 | if err := p.cmd.Process.Signal(syscall.SIGTERM); err != nil { |
| 218 | t.Fatalf("sending SIGTERM: %v", err) |
| 219 | } |
| 220 | select { |
| 221 | case err := <-p.done: |
| 222 | if err != nil { |
| 223 | // Exit triggered by signal handler is expected to be clean (nil). |
| 224 | // signal.NotifyContext + RunE returning nil yields exit code 0. |
| 225 | t.Fatalf("klaus watch exited with error after SIGTERM: %v (stderr: %s)", err, p.stderr.String()) |
| 226 | } |
| 227 | case <-time.After(5 * time.Second): |
| 228 | _ = p.cmd.Process.Kill() |
| 229 | t.Fatalf("klaus watch did not exit within 5s after SIGTERM (stderr: %s)", p.stderr.String()) |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | // emitter is a helper that appends events to events.jsonl using the same |
| 234 | // writer the rest of klaus uses. |
| 235 | type emitter struct { |
| 236 | log *event.Log |
| 237 | } |
| 238 | |
| 239 | func newEmitter(sessionDir string) *emitter { |
| 240 | return &emitter{log: event.NewLog(sessionDir)} |
| 241 | } |
| 242 | |
| 243 | func (e *emitter) emit(t *testing.T, runID, typ string, data map[string]interface{}) { |
| 244 | t.Helper() |
| 245 | if err := e.log.Emit(event.New(runID, typ, data)); err != nil { |
| 246 | t.Fatalf("emit event: %v", err) |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | func setupSessionDir(t *testing.T) (home, sessionID, sessionDir string) { |
| 251 | t.Helper() |
| 252 | home = t.TempDir() |
| 253 | sessionID = "test-watch-session" |
| 254 | sessionDir = filepath.Join(home, ".klaus", "sessions", sessionID) |
| 255 | if err := os.MkdirAll(sessionDir, 0o755); err != nil { |
| 256 | t.Fatalf("mkdir session dir: %v", err) |
| 257 | } |
| 258 | return |
| 259 | } |
| 260 | |
| 261 | // touchEventsFile pre-creates an empty events.jsonl so 'klaus watch' moves |
| 262 | // past its waitForFile phase without racing with a concurrent first emit. |
| 263 | // Production users hit the same race only if the file is created mid-startup, |
| 264 | // which is harmless — the wait loop polls every 500ms and picks it up. |
| 265 | func touchEventsFile(t *testing.T, sessionDir string) { |
| 266 | t.Helper() |
| 267 | f, err := os.OpenFile(filepath.Join(sessionDir, "events.jsonl"), os.O_CREATE|os.O_WRONLY, 0o644) |
| 268 | if err != nil { |
| 269 | t.Fatalf("creating events.jsonl: %v", err) |
| 270 | } |
| 271 | f.Close() |
| 272 | } |
| 273 | |
| 274 | func TestWatchStreamsNewEvents(t *testing.T) { |
| 275 | bin := klausBinary(t) |
| 276 | home, sessionID, sessionDir := setupSessionDir(t) |
| 277 | em := newEmitter(sessionDir) |
| 278 | |
| 279 | // Pre-write one event that should NOT appear (default: tail mode). |
| 280 | em.emit(t, "old-run", event.PRMerged, map[string]interface{}{"pr_number": "1"}) |
| 281 | |
| 282 | p := startWatch(t, bin, sessionID, home) |
| 283 | |
| 284 | // Give the subprocess a moment to seek to EOF and arm fsnotify. |
| 285 | time.Sleep(300 * time.Millisecond) |
| 286 | |
| 287 | em.emit(t, "85", event.PRMerged, map[string]interface{}{"pr_number": "85"}) |
| 288 | line := p.nextLine(t, 5*time.Second) |
| 289 | if !strings.Contains(line, "pr:merged") { |
| 290 | t.Errorf("expected pr:merged line, got %q", line) |
| 291 | } |
| 292 | if !strings.Contains(line, "PR #85 merged") { |
| 293 | t.Errorf("expected formatted PR #85 merged summary, got %q", line) |
| 294 | } |
| 295 | |
| 296 | em.emit(t, "85", event.AgentPRCreated, map[string]interface{}{ |
| 297 | "pr_number": "85", |
| 298 | "pr_url": "https://github.com/owner/repo/pull/85", |
| 299 | }) |
| 300 | line = p.nextLine(t, 5*time.Second) |
| 301 | if !strings.Contains(line, "agent:pr-created") { |
| 302 | t.Errorf("expected agent:pr-created line, got %q", line) |
| 303 | } |
| 304 | if !strings.Contains(line, "https://github.com/owner/repo/pull/85") { |
| 305 | t.Errorf("expected PR URL in line, got %q", line) |
| 306 | } |
| 307 | |
| 308 | p.stopSIGTERM(t) |
| 309 | } |
| 310 | |
| 311 | func TestWatchSinceStartReplays(t *testing.T) { |
| 312 | bin := klausBinary(t) |
| 313 | home, sessionID, sessionDir := setupSessionDir(t) |
| 314 | em := newEmitter(sessionDir) |
| 315 | |
| 316 | em.emit(t, "1", event.PRMerged, map[string]interface{}{"pr_number": "1"}) |
| 317 | em.emit(t, "2", event.PRMerged, map[string]interface{}{"pr_number": "2"}) |
| 318 | |
| 319 | p := startWatch(t, bin, sessionID, home, "--since-start") |
| 320 | |
| 321 | line1 := p.nextLine(t, 5*time.Second) |
| 322 | if !strings.Contains(line1, "PR #1 merged") { |
| 323 | t.Errorf("expected first replayed event for PR #1, got %q", line1) |
| 324 | } |
| 325 | line2 := p.nextLine(t, 5*time.Second) |
| 326 | if !strings.Contains(line2, "PR #2 merged") { |
| 327 | t.Errorf("expected second replayed event for PR #2, got %q", line2) |
| 328 | } |
| 329 | |
| 330 | p.stopSIGTERM(t) |
| 331 | } |
| 332 | |
| 333 | func TestWatchFilterFlag(t *testing.T) { |
| 334 | bin := klausBinary(t) |
| 335 | home, sessionID, sessionDir := setupSessionDir(t) |
| 336 | em := newEmitter(sessionDir) |
| 337 | |
| 338 | touchEventsFile(t, sessionDir) |
| 339 | // --filter narrows to only pr:merged |
| 340 | p := startWatch(t, bin, sessionID, home, "--filter", event.PRMerged) |
| 341 | time.Sleep(300 * time.Millisecond) |
| 342 | |
| 343 | // This one should be filtered out — default would include it. |
| 344 | em.emit(t, "9", event.AgentPRCreated, map[string]interface{}{ |
| 345 | "pr_number": "9", "pr_url": "https://example.com/pull/9", |
| 346 | }) |
| 347 | // This one passes the filter. |
| 348 | em.emit(t, "9", event.PRMerged, map[string]interface{}{"pr_number": "9"}) |
| 349 | |
| 350 | line := p.nextLine(t, 5*time.Second) |
| 351 | if !strings.Contains(line, "pr:merged") { |
| 352 | t.Errorf("expected pr:merged after filtering, got %q", line) |
| 353 | } |
| 354 | if strings.Contains(line, "agent:pr-created") { |
| 355 | t.Errorf("did not expect agent:pr-created to leak past --filter, got %q", line) |
| 356 | } |
| 357 | |
| 358 | p.stopSIGTERM(t) |
| 359 | } |
| 360 | |
| 361 | func TestWatchFilterOutFlag(t *testing.T) { |
| 362 | bin := klausBinary(t) |
| 363 | home, sessionID, sessionDir := setupSessionDir(t) |
| 364 | em := newEmitter(sessionDir) |
| 365 | |
| 366 | touchEventsFile(t, sessionDir) |
| 367 | p := startWatch(t, bin, sessionID, home, "--filter-out", event.PRApproved) |
| 368 | time.Sleep(300 * time.Millisecond) |
| 369 | |
| 370 | em.emit(t, "12", event.PRApproved, map[string]interface{}{"pr_number": "12"}) |
| 371 | em.emit(t, "12", event.PRMerged, map[string]interface{}{"pr_number": "12"}) |
| 372 | |
| 373 | line := p.nextLine(t, 5*time.Second) |
| 374 | if strings.Contains(line, "pr:approved") { |
| 375 | t.Errorf("pr:approved should have been excluded, got %q", line) |
| 376 | } |
| 377 | if !strings.Contains(line, "pr:merged") { |
| 378 | t.Errorf("expected pr:merged to pass through filter-out, got %q", line) |
| 379 | } |
| 380 | |
| 381 | p.stopSIGTERM(t) |
| 382 | } |
| 383 | |
| 384 | func TestWatchJSONPassthrough(t *testing.T) { |
| 385 | bin := klausBinary(t) |
| 386 | home, sessionID, sessionDir := setupSessionDir(t) |
| 387 | em := newEmitter(sessionDir) |
| 388 | |
| 389 | touchEventsFile(t, sessionDir) |
| 390 | p := startWatch(t, bin, sessionID, home, "--json") |
| 391 | time.Sleep(300 * time.Millisecond) |
| 392 | |
| 393 | em.emit(t, "42", event.PRMerged, map[string]interface{}{ |
| 394 | "pr_number": "42", |
| 395 | "pr_url": "https://github.com/owner/repo/pull/42", |
| 396 | }) |
| 397 | |
| 398 | line := p.nextLine(t, 5*time.Second) |
| 399 | var evt event.Event |
| 400 | if err := json.Unmarshal([]byte(line), &evt); err != nil { |
| 401 | t.Fatalf("expected valid JSON line, got %q: %v", line, err) |
| 402 | } |
| 403 | if evt.Type != event.PRMerged { |
| 404 | t.Errorf("type = %q, want %q", evt.Type, event.PRMerged) |
| 405 | } |
| 406 | if evt.RunID != "42" { |
| 407 | t.Errorf("run_id = %q, want %q", evt.RunID, "42") |
| 408 | } |
| 409 | if evt.Data["pr_number"] != "42" { |
| 410 | t.Errorf("pr_number = %v, want 42", evt.Data["pr_number"]) |
| 411 | } |
| 412 | |
| 413 | // Verify byte-for-byte equivalence to the original line in the events file. |
| 414 | // The emitter appends a single JSON object per line so reading the file |
| 415 | // gives us the exact line klaus watch should have emitted. |
| 416 | raw, err := os.ReadFile(filepath.Join(sessionDir, "events.jsonl")) |
| 417 | if err != nil { |
| 418 | t.Fatalf("reading events.jsonl: %v", err) |
| 419 | } |
| 420 | srcLines := strings.Split(strings.TrimRight(string(raw), "\n"), "\n") |
| 421 | if len(srcLines) != 1 { |
| 422 | t.Fatalf("expected 1 source line, got %d", len(srcLines)) |
| 423 | } |
| 424 | if line != srcLines[0] { |
| 425 | t.Errorf("watch --json output not byte-equivalent to source\n got: %q\n want: %q", line, srcLines[0]) |
| 426 | } |
| 427 | |
| 428 | p.stopSIGTERM(t) |
| 429 | } |
| 430 | |
| 431 | func TestWatchExitsOnSIGTERMCleanly(t *testing.T) { |
| 432 | bin := klausBinary(t) |
| 433 | home, sessionID, _ := setupSessionDir(t) |
| 434 | // No emits — just confirm SIGTERM during idle wait causes clean exit. |
| 435 | |
| 436 | p := startWatch(t, bin, sessionID, home) |
| 437 | time.Sleep(200 * time.Millisecond) |
| 438 | p.stopSIGTERM(t) |
| 439 | } |
| 440 | |
| 441 | func TestWatchRequiresSessionID(t *testing.T) { |
| 442 | bin := klausBinary(t) |
| 443 | cmd := exec.Command(bin, "watch") |
| 444 | // Clear KLAUS_SESSION_ID from the env in case the test runner has one set. |
| 445 | env := []string{} |
| 446 | for _, e := range os.Environ() { |
| 447 | if strings.HasPrefix(e, "KLAUS_SESSION_ID=") { |
| 448 | continue |
| 449 | } |
| 450 | env = append(env, e) |
| 451 | } |
| 452 | cmd.Env = env |
| 453 | var stderr bytes.Buffer |
| 454 | cmd.Stderr = &stderr |
| 455 | cmd.Stdout = io.Discard |
| 456 | err := cmd.Run() |
| 457 | if err == nil { |
| 458 | t.Fatalf("expected klaus watch to fail without KLAUS_SESSION_ID, succeeded") |
| 459 | } |
| 460 | if !strings.Contains(stderr.String(), "must be run inside a klaus session") { |
| 461 | t.Errorf("expected helpful error message about missing session, got: %s", stderr.String()) |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | func TestWatchListTypes(t *testing.T) { |
| 466 | bin := klausBinary(t) |
| 467 | cmd := exec.Command(bin, "watch", "--list-types") |
| 468 | var stdout bytes.Buffer |
| 469 | cmd.Stdout = &stdout |
| 470 | cmd.Stderr = os.Stderr |
| 471 | if err := cmd.Run(); err != nil { |
| 472 | t.Fatalf("klaus watch --list-types failed: %v", err) |
| 473 | } |
| 474 | out := stdout.String() |
| 475 | if !strings.Contains(out, "Live event types") { |
| 476 | t.Errorf("expected 'Live event types' heading, got: %s", out) |
| 477 | } |
| 478 | if !strings.Contains(out, "Reserved event types") { |
| 479 | t.Errorf("expected 'Reserved event types' heading, got: %s", out) |
| 480 | } |
| 481 | if !strings.Contains(out, event.PRMerged) { |
| 482 | t.Errorf("expected pr:merged in output, got: %s", out) |
| 483 | } |
| 484 | if !strings.Contains(out, "ci:failed") { |
| 485 | t.Errorf("expected ci:failed (reserved) in output, got: %s", out) |
| 486 | } |
| 487 | live, _, _ := strings.Cut(out, "Reserved event types") |
| 488 | if !strings.Contains(live, event.ConsultStarted) { |
| 489 | t.Errorf("expected consult:started among live types, got: %s", out) |
| 490 | } |
| 491 | if !strings.Contains(live, event.AgentBranchPushed) { |
| 492 | t.Errorf("expected agent:branch-pushed among live types, got: %s", out) |
| 493 | } |
| 494 | _, def, _ := strings.Cut(out, "Default filter:") |
| 495 | for _, typ := range []string{event.AgentBranchPushed, event.AgentNeedsAttention} { |
| 496 | if !strings.Contains(def, typ) { |
| 497 | t.Errorf("expected %s in the default filter, got: %s", typ, def) |
| 498 | } |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | // Sanity check that multiple emissions arrive in order. |
| 503 | func TestWatchPreservesOrder(t *testing.T) { |
| 504 | bin := klausBinary(t) |
| 505 | home, sessionID, sessionDir := setupSessionDir(t) |
| 506 | em := newEmitter(sessionDir) |
| 507 | |
| 508 | touchEventsFile(t, sessionDir) |
| 509 | p := startWatch(t, bin, sessionID, home, "--filter", event.PRMerged) |
| 510 | time.Sleep(300 * time.Millisecond) |
| 511 | |
| 512 | const n = 5 |
| 513 | var wg sync.WaitGroup |
| 514 | wg.Add(1) |
| 515 | go func() { |
| 516 | defer wg.Done() |
| 517 | for i := 0; i < n; i++ { |
| 518 | em.emit(t, "ord", event.PRMerged, map[string]interface{}{"pr_number": strconv.Itoa(i)}) |
| 519 | time.Sleep(50 * time.Millisecond) |
| 520 | } |
| 521 | }() |
| 522 | |
| 523 | for i := 0; i < n; i++ { |
| 524 | line := p.nextLine(t, 5*time.Second) |
| 525 | want := "PR #" + strconv.Itoa(i) + " merged" |
| 526 | if !strings.Contains(line, want) { |
| 527 | t.Errorf("line %d: expected %q in %q", i, want, line) |
| 528 | } |
| 529 | } |
| 530 | wg.Wait() |
| 531 | p.stopSIGTERM(t) |
| 532 | } |
| 533 | |
| 534 | // TestWatchStreamsPipelineStalled checks that a stalled pipeline reaches a |
| 535 | // coordinator through the default filter — the whole point of emitting the |
| 536 | // event once per stall instead of flooding pr:approved (issue #292). |
| 537 | func TestWatchStreamsPipelineStalled(t *testing.T) { |
| 538 | bin := klausBinary(t) |
| 539 | home, sessionID, sessionDir := setupSessionDir(t) |
| 540 | touchEventsFile(t, sessionDir) |
| 541 | em := newEmitter(sessionDir) |
| 542 | |
| 543 | p := startWatch(t, bin, sessionID, home) |
| 544 | time.Sleep(300 * time.Millisecond) |
| 545 | |
| 546 | em.emit(t, "734", event.PipelineStalled, map[string]interface{}{ |
| 547 | "pr_number": "734", |
| 548 | "reason": "auto-merge failed after 3 attempts", |
| 549 | "pr_url": "https://github.com/owner/repo/pull/734", |
| 550 | }) |
| 551 | |
| 552 | line := p.nextLine(t, 5*time.Second) |
| 553 | if !strings.Contains(line, "pipeline:stalled") { |
| 554 | t.Errorf("expected pipeline:stalled line, got %q", line) |
| 555 | } |
| 556 | if !strings.Contains(line, "PR #734 stalled — auto-merge failed after 3 attempts") { |
| 557 | t.Errorf("expected formatted stall summary, got %q", line) |
| 558 | } |
| 559 | |
| 560 | p.stopSIGTERM(t) |
| 561 | } |
| 562 | |
| 563 | // The default filter (no --filter) must surface a direct-push finish (#281). |
| 564 | func TestWatchStreamsBranchPushed(t *testing.T) { |
| 565 | bin := klausBinary(t) |
| 566 | home, sessionID, sessionDir := setupSessionDir(t) |
| 567 | touchEventsFile(t, sessionDir) |
| 568 | em := newEmitter(sessionDir) |
| 569 | |
| 570 | p := startWatch(t, bin, sessionID, home) |
| 571 | time.Sleep(300 * time.Millisecond) |
| 572 | |
| 573 | em.emit(t, "20261005-0300-abcd", event.AgentBranchPushed, map[string]interface{}{ |
| 574 | "repo": "the-valley", |
| 575 | "branch": "agent/20261005-0300-abcd", |
| 576 | "sha": "0123456789abcdef0123456789abcdef01234567", |
| 577 | }) |
| 578 | |
| 579 | line := p.nextLine(t, 5*time.Second) |
| 580 | if !strings.Contains(line, "agent:branch-pushed") { |
| 581 | t.Errorf("expected agent:branch-pushed line, got %q", line) |
| 582 | } |
| 583 | if !strings.Contains(line, "branch agent/20261005-0300-abcd@0123456 pushed, awaiting integration (the-valley)") { |
| 584 | t.Errorf("expected formatted branch-pushed summary, got %q", line) |
| 585 | } |
| 586 | |
| 587 | p.stopSIGTERM(t) |
| 588 | } |
| 589 | |
| 590 | // TestWatchStreamsChangeTransitions: a valley change's transitions pass the |
| 591 | // default filter, each on a line that names the change's version, as |
| 592 | // pr:merged names its PR. |
| 593 | func TestWatchStreamsChangeTransitions(t *testing.T) { |
| 594 | bin := klausBinary(t) |
| 595 | home, sessionID, sessionDir := setupSessionDir(t) |
| 596 | em := newEmitter(sessionDir) |
| 597 | change := func(version int, extra ...string) map[string]interface{} { |
| 598 | d := map[string]interface{}{"repo": "site", "handle": "nxvp", "change_id": "nxvpkkkkkkkkkkkkkkkkkkkkkkkkkkkk", |
| 599 | "version": version, "head": strings.Repeat("1", 40), "title": "Tune the cache"} |
| 600 | for i := 0; i+1 < len(extra); i += 2 { |
| 601 | d[extra[i]] = extra[i+1] |
| 602 | } |
| 603 | return d |
| 604 | } |
| 605 | em.emit(t, "nxvp", event.ChangeApproved, change(1)) |
| 606 | em.emit(t, "nxvp", event.ChangeStale, change(1)) |
| 607 | em.emit(t, "nxvp", event.ChangeNewVersion, change(2, "uploader", "restacker")) |
| 608 | em.emit(t, "nxvp", event.ChangeRejected, change(2)) |
| 609 | em.emit(t, "nxvp", event.ChangeFailed, change(2)) |
| 610 | em.emit(t, "nxvp", event.ChangeWithdrawn, change(2)) |
| 611 | em.emit(t, "nxvp", event.ChangeIntegrated, change(2, "landed_commit", strings.Repeat("2", 40))) |
| 612 | |
| 613 | out, stderr, err := runKlaus(t, bin, home, "watch", "--session-id", sessionID, "--once", "--since-start") |
| 614 | if err != nil { |
| 615 | t.Fatalf("watch: %v\n%s", err, stderr) |
| 616 | } |
| 617 | lines := strings.Split(strings.TrimSpace(out), "\n") |
| 618 | want := []string{ |
| 619 | "nxvp change:approved site nxvp v1 approved: Tune the cache", |
| 620 | "nxvp change:stale site nxvp v1 stale: Tune the cache", |
| 621 | "nxvp change:new-version site nxvp v2 new version at 1111111 by restacker: Tune the cache", |
| 622 | "nxvp change:rejected site nxvp v2 rejected: Tune the cache", |
| 623 | "nxvp change:failed site nxvp v2 failed: Tune the cache", |
| 624 | "nxvp change:withdrawn site nxvp v2 withdrawn: Tune the cache", |
| 625 | "nxvp change:integrated site nxvp v2 integrated as 2222222: Tune the cache", |
| 626 | } |
| 627 | if len(lines) != len(want)+1 { |
| 628 | t.Fatalf("watch printed %d lines, want %d events and its next: line:\n%s", len(lines), len(want), out) |
| 629 | } |
| 630 | for i, w := range want { |
| 631 | if !strings.HasSuffix(lines[i], w) { |
| 632 | t.Errorf("line %d = %q, want it to end %q", i, lines[i], w) |
| 633 | } |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | // runKlaus runs the real binary with HOME set, waiting up to 10s for it to |
| 638 | // exit, and returns its stdout, stderr and exit error. |
| 639 | func runKlaus(t *testing.T, bin, home string, args ...string) (string, string, error) { |
| 640 | t.Helper() |
| 641 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 642 | defer cancel() |
| 643 | cmd := exec.CommandContext(ctx, bin, args...) |
| 644 | cmd.Env = append(os.Environ(), "HOME="+home) |
| 645 | var stdout, stderr bytes.Buffer |
| 646 | cmd.Stdout, cmd.Stderr = &stdout, &stderr |
| 647 | err := cmd.Run() |
| 648 | if ctx.Err() != nil { |
| 649 | t.Fatalf("klaus %v didn't exit within 10s\nstdout:\n%s\nstderr:\n%s", args, stdout.String(), stderr.String()) |
| 650 | } |
| 651 | return stdout.String(), stderr.String(), err |
| 652 | } |
| 653 | |
| 654 | // TestWatchOnceJSONKeepsFlags: --once --json prints the matching events as |
| 655 | // they are in the file, then an object with the offset past them and the |
| 656 | // command that reads on from it with the same filters, which wakes only for |
| 657 | // an event that passes them. |
| 658 | func TestWatchOnceJSONKeepsFlags(t *testing.T) { |
| 659 | bin := klausBinary(t) |
| 660 | home, sessionID, sessionDir := setupSessionDir(t) |
| 661 | em := newEmitter(sessionDir) |
| 662 | em.emit(t, "r1", event.PRMerged, map[string]interface{}{"pr_number": "1"}) |
| 663 | em.emit(t, "r2", event.AgentStarted, nil) |
| 664 | em.emit(t, "r2", event.PRMerged, map[string]interface{}{"pr_number": "2"}) |
| 665 | eventsPath := filepath.Join(sessionDir, "events.jsonl") |
| 666 | |
| 667 | type trailer struct { |
| 668 | After int64 `json:"after"` |
| 669 | Next string `json:"next"` |
| 670 | } |
| 671 | check := func(out string, wantPR string) trailer { |
| 672 | t.Helper() |
| 673 | raw, err := os.ReadFile(eventsPath) |
| 674 | if err != nil { |
| 675 | t.Fatal(err) |
| 676 | } |
| 677 | lines := strings.Split(strings.TrimSuffix(out, "\n"), "\n") |
| 678 | if len(lines) != 2 { |
| 679 | t.Fatalf("want one event and the trailer, got:\n%s", out) |
| 680 | } |
| 681 | var evt event.Event |
| 682 | if err := json.Unmarshal([]byte(lines[0]), &evt); err != nil || evt.RunID != "r2" || evt.Data["pr_number"] != wantPR { |
| 683 | t.Fatalf("want r2's merge of PR %s, got %q (%v)", wantPR, lines[0], err) |
| 684 | } |
| 685 | if !strings.Contains(string(raw), lines[0]+"\n") { |
| 686 | t.Errorf("event line %q isn't as it is in the file", lines[0]) |
| 687 | } |
| 688 | var tr trailer |
| 689 | if err := json.Unmarshal([]byte(lines[1]), &tr); err != nil { |
| 690 | t.Fatalf("trailer %q: %v", lines[1], err) |
| 691 | } |
| 692 | want := fmt.Sprintf("klaus watch --once --after %d --session-id %s --filter pr:merged --run r2 --json", len(raw), sessionID) |
| 693 | if tr.After != int64(len(raw)) || tr.Next != want { |
| 694 | t.Errorf("trailer = %+v, want after %d, next %q", tr, len(raw), want) |
| 695 | } |
| 696 | return tr |
| 697 | } |
| 698 | |
| 699 | out, stderr, err := runKlaus(t, bin, home, "watch", "--session-id", sessionID, "--once", "--since-start", "--json", "--filter", event.PRMerged, "--run", "r2") |
| 700 | if err != nil { |
| 701 | t.Fatalf("watch --once: %v\n%s", err, stderr) |
| 702 | } |
| 703 | tr := check(out, "2") |
| 704 | |
| 705 | // r1's merge doesn't pass --run r2; r2's does. |
| 706 | em.emit(t, "r1", event.PRMerged, map[string]interface{}{"pr_number": "3"}) |
| 707 | em.emit(t, "r2", event.PRMerged, map[string]interface{}{"pr_number": "4"}) |
| 708 | out, stderr, err = runKlaus(t, bin, home, strings.Fields(tr.Next)[1:]...) |
| 709 | if err != nil { |
| 710 | t.Fatalf("%s: %v\n%s", tr.Next, err, stderr) |
| 711 | } |
| 712 | check(out, "4") |
| 713 | } |
| 714 | |
| 715 | // TestWatchOnceRejectsBadCursors: an --after that can't have come from a |
| 716 | // next: line is an error, not a silent re-read or skip. |
| 717 | func TestWatchOnceRejectsBadCursors(t *testing.T) { |
| 718 | bin := klausBinary(t) |
| 719 | home, sessionID, sessionDir := setupSessionDir(t) |
| 720 | newEmitter(sessionDir).emit(t, "r1", event.PRMerged, map[string]interface{}{"pr_number": "1"}) |
| 721 | |
| 722 | for _, tc := range []struct { |
| 723 | args []string |
| 724 | want string |
| 725 | }{ |
| 726 | {[]string{"--after", "0"}, "--after needs --once"}, |
| 727 | {[]string{"--once", "--since-start", "--after", "0"}, "mutually exclusive"}, |
| 728 | {[]string{"--once", "--after", "100000"}, "past the end"}, |
| 729 | {[]string{"--once", "--after", "3"}, "not at the start of a line"}, |
| 730 | } { |
| 731 | _, stderr, err := runKlaus(t, bin, home, append([]string{"watch", "--session-id", sessionID}, tc.args...)...) |
| 732 | if err == nil || !strings.Contains(stderr, tc.want) { |
| 733 | t.Errorf("watch %v: err %v, stderr %q; want a failure saying %q", tc.args, err, stderr, tc.want) |
| 734 | } |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | // TestWatchOnceEndsWhenTheFileIsReplaced: an offset into the events file |
| 739 | // means nothing in a file put in its place, so a waiting --once watch fails |
| 740 | // instead of waiting on the old one forever. |
| 741 | func TestWatchOnceEndsWhenTheFileIsReplaced(t *testing.T) { |
| 742 | bin := klausBinary(t) |
| 743 | home, sessionID, sessionDir := setupSessionDir(t) |
| 744 | touchEventsFile(t, sessionDir) |
| 745 | p := startWatch(t, bin, sessionID, home, "--once") |
| 746 | time.Sleep(300 * time.Millisecond) |
| 747 | |
| 748 | replacement := filepath.Join(sessionDir, "events.jsonl.new") |
| 749 | if err := os.WriteFile(replacement, nil, 0o644); err != nil { |
| 750 | t.Fatal(err) |
| 751 | } |
| 752 | if err := os.Rename(replacement, filepath.Join(sessionDir, "events.jsonl")); err != nil { |
| 753 | t.Fatal(err) |
| 754 | } |
| 755 | select { |
| 756 | case err := <-p.done: |
| 757 | if err == nil || !strings.Contains(p.stderr.String(), "was replaced or removed") { |
| 758 | t.Fatalf("watch --once exited with %v, stderr %q; want a failure saying the file was replaced", err, p.stderr.String()) |
| 759 | } |
| 760 | case <-time.After(5 * time.Second): |
| 761 | t.Fatal("watch --once kept waiting on a replaced events file") |
| 762 | } |
| 763 | } |