gunk-dev/the-valley

watch_test.go

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