gunk-dev/the-valley

watch.go

source28abc5737165main's published tip history
34.1 KiB
1package cmd
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "os/signal"
12 "path/filepath"
13 "sort"
14 "strconv"
15 "strings"
16 "syscall"
17 "time"
18
19 "github.com/fsnotify/fsnotify"
20 "the-valley/flow/internal/event"
21 "the-valley/flow/internal/run"
22 "github.com/spf13/cobra"
23)
24
25// defaultWatchFilter is the set of event types emitted as notifications when
26// 'klaus watch' is run with no --filter flags. It intentionally includes some
27// types that aren't emitted yet (reserved entries) so the filter remains
28// forward-compatible as the pipeline grows.
29var defaultWatchFilter = []string{
30 event.ConsultStarted, // live
31 event.ConsultCompleted, // live
32 event.ReviewStarted, // live
33 event.ReviewCompleted, // live
34 event.AgentPRCreated, // live
35 event.AgentBranchPushed, // live
36 event.AgentChangeReady, // live
37 event.AgentChangeDraft, // live
38 event.AgentNeedsAttention, // live
39 "agent:error", // reserved
40 event.PRApproved, // live
41 event.PRMerged, // live
42 event.PipelineStalled, // live
43 event.ChangeRestackDispatched, // live
44 event.ChangeRestackStalled, // live
45 event.ChangeApproved, // live
46 event.ChangeIntegrated, // live
47 event.ChangeStale, // live
48 event.ChangeRejected, // live
49 event.ChangeFailed, // live
50 event.ChangeWithdrawn, // live
51 event.ChangeNewVersion, // live
52 event.ChangeChecksFailed, // live
53 event.ChangeChecksPassed, // live
54 "ci:failed", // reserved (closest live equivalent: agent:ci-failed)
55 "ci:passed", // reserved (closest live equivalent: agent:ci-passed)
56 "pr:comment", // reserved
57}
58
59// knownEventTypes maps event types to a one-line description and whether the
60// type is currently emitted somewhere in klaus ("live") or reserved for future
61// use. --list-types renders this table.
62var knownEventTypes = []eventTypeInfo{
63 {event.ConsultStarted, "live", "A read-only model consultation started"},
64 {event.ConsultCompleted, "live", "A read-only model consultation finished (success, failure, timeout or interrupt)"},
65 {event.ReviewStarted, "live", "A cross-model PR review (valley flow review) started"},
66 {event.ReviewCompleted, "live", "A cross-model PR review finished (success, failure, timeout or interrupt)"},
67 {event.AgentStarted, "live", "An agent run started"},
68 {event.AgentCompleted, "live", "An agent run finished (success or failure)"},
69 {event.AgentPRCreated, "live", "An agent published a PR"},
70 {event.AgentBranchPushed, "live", "An agent finished with its branch on origin and no PR (awaiting integration)"},
71 {event.AgentChangeReady, "live", "Finalize, or valley flow ready, marked a pushed branch ready on its valley as a version of the run's change (awaiting approval)"},
72 {event.AgentChangeDraft, "live", "Finalize recorded a pushed branch on its valley as a version of the run's change but left it a draft (awaiting review; ready_at_finalize off)"},
73 {event.AgentCIPassed, "live", "CI passed on an agent-owned PR"},
74 {event.AgentCIFailed, "live", "CI failed on an agent-owned PR"},
75 {event.AgentNeedsAttention, "live", "An agent stopped and needs operator input"},
76 {event.PRAwaitingApproval, "live", "A PR is ready for human approval"},
77 {event.PRApproved, "live", "A PR was approved"},
78 {event.PRMerged, "live", "A PR merged"},
79 {event.PRApprovalChanged, "live", "Flow-internal approval state for a PR changed (e.g. via valley flow approve)"},
80 {event.PipelineStalled, "live", "The pipeline gave up on a PR after exhausting its retry budget"},
81 {event.ChangeRestackDispatched, "live", "flow launched a run to resolve a restack conflict the valley reported on a change flow owns"},
82 {event.ChangeRestackStalled, "live", "The change needs the coordinator: flow will not resolve its restack conflict (attempts spent, unready or launch failed, or left alone: sits on other changes, or the conflict is in a change below)"},
83 {event.ChangeApproved, "live", "A ready version of a valley change got an integration request (the operator approved it)"},
84 {event.ChangeIntegrated, "live", "A valley change landed"},
85 {event.ChangeStale, "live", "The integrator found a valley change's approved version stale"},
86 {event.ChangeRejected, "live", "The integrator rejected a valley change's approved version"},
87 {event.ChangeFailed, "live", "The integrator failed to land a valley change's approved version"},
88 {event.ChangeWithdrawn, "live", "A valley change was withdrawn"},
89 {event.ChangeNewVersion, "live", "A valley change got a version this session didn't record (the valley's restacker, or a human)"},
90 {event.ChangeChecksFailed, "live", "The valley host's check worker failed a required check of a ready change's active version (a valley change's agent:ci-failed)"},
91 {event.ChangeChecksPassed, "live", "Every required check of a ready valley change's active version passed (a valley change's agent:ci-passed)"},
92 {event.AgentSharedGitChanged, "live", "A run's clone's shared git files (config, info/attributes, hooks) changed while it ran; the run needs attention"},
93 {event.PhaseStarted, "live", "A run entered a phase (agent, finalize); not in the default filter"},
94 {event.PhaseCompleted, "live", "A run finished a phase (setup, agent, finalize), with its duration; not in the default filter"},
95 {event.CheckStarted, "live", "An agent started a check flow can see (_pre-review, or a build, test or lint command); not in the default filter"},
96 {event.CheckCompleted, "live", "An agent's check finished, with its duration; not in the default filter"},
97 {"agent:error", "reserved", "Reserved for unrecoverable agent failures (not currently emitted; use agent:needs-attention)"},
98 {"ci:failed", "reserved", "Reserved short name (currently emitted as agent:ci-failed)"},
99 {"ci:passed", "reserved", "Reserved short name (currently emitted as agent:ci-passed)"},
100 {"pr:comment", "reserved", "Reserved for trusted-reviewer comment notifications (not currently emitted)"},
101}
102
103type eventTypeInfo struct {
104 Type string
105 Status string // "live" or "reserved"
106 Desc string
107}
108
109var watchCmd = &cobra.Command{
110 Use: "watch",
111 Short: "Stream session pipeline events as a real-time channel",
112 Long: `Stream structured pipeline events from the current flow session as a
113line-buffered text channel. Designed for Claude Code's Monitor tool — each
114matching event becomes one notification.
115
116Events are read from ~/.klaus/sessions/$KLAUS_SESSION_ID/events.jsonl,
117followed via fsnotify, and emitted to stdout one line at a time. The default
118filter selects events the coordinator typically wants to react to:
119
120 agent:pr-created, agent:branch-pushed, agent:change-ready,
121 agent:change-draft, agent:needs-attention, agent:error,
122 pr:approved, pr:merged, pipeline:stalled,
123 change:approved, change:integrated, change:stale, change:rejected,
124 change:failed, change:withdrawn, change:new-version,
125 change:checks-failed, change:checks-passed,
126 change:restack-dispatched, change:restack-stalled,
127 consult:started, consult:completed, review:started, review:completed,
128 ci:failed, ci:passed, pr:comment
129
130A valley change's transitions (change:approved, change:integrated,
131change:stale, change:rejected, change:failed, change:withdrawn,
132change:new-version, change:checks-failed and change:checks-passed) report its life as pr:approved and pr:merged report a
133PR's: the dashboard reads them off the valley's listing in its integration
134check, once a minute, and reports each transition once, under the change's
135handle. Without a dashboard nothing reports them; valley flow status only reads.
136A change the dashboard sees for the first time is recorded as it stands,
137without events.
138
139Some of those types are reserved (not currently emitted) but kept in the
140default filter so this command stays forward-compatible. Run 'valley flow watch
141--list-types' to see which types are live vs reserved.
142
143Passing --filter REPLACES the default. --filter-out is always subtracted.
144Both flags are repeatable and use OR semantics within each flag. --run keeps
145only the events of the given runs (repeatable; a pipeline event's run is its
146PR's number, and a valley change's transition's, change:approved and the
147like, is the change's handle).
148
149valley flow session creates the events file when it creates or resumes a session.
150In a session that has none yet, watch waits for it as long as the session's
151directory exists, then reads it from the start. An unknown session ID is an
152error.
153
154--once is for a coordinator whose background tasks hand it their output only
155when they exit (agy, for one): it waits until at least one matching event has
156arrived, prints every matching event that has, and exits 0. Its last line is
157the command that waits for the events after those, with the stream's position
158in --after, e.g.
159
160 next: valley flow watch --once --after 18342
161
162(with --json, a JSON object: {"after":18342,"next":"valley flow watch ..."}).
163Starting each watch from the last one's next: line delivers every event once:
164--after is a byte offset into events.jsonl, so events that land between two
165watches are past it, and running the same command again prints the same
166events. Without --after, --once starts at the end of the file (at its start
167with --since-start). Interrupted before any event, it prints just the next:
168line. An --after past the end of the file or inside a line is an error, and
169so is an events file replaced or removed while --once waits on it.`,
170 Example: ` # Default filter, follow new events from now:
171 valley flow watch
172
173 # Only react when a PR merges:
174 valley flow watch --filter pr:merged
175
176 # Default filter minus pr:approved (e.g. don't notify on self-approvals):
177 valley flow watch --filter-out pr:approved
178
179 # Replay everything in the file, then keep following:
180 valley flow watch --since-start
181
182 # Raw JSONL passthrough for downstream tools:
183 valley flow watch --json
184
185 # Wait for the next events, print them and exit; then run the next: line:
186 valley flow watch --once
187 valley flow watch --once --after 18342
188
189 # Wait for one run's next event:
190 valley flow watch --once --run 20261026-1701-445ec227`,
191 RunE: runWatch,
192}
193
194func init() {
195 watchCmd.Flags().StringSlice("filter", nil, "Event type to include (repeatable, OR semantics). Replaces the default filter when set.")
196 watchCmd.Flags().StringSlice("filter-out", nil, "Event type to exclude (repeatable). Applied after --filter.")
197 watchCmd.Flags().StringSlice("run", nil, "Run ID whose events to include (repeatable; a PR number for pipeline events, a change's handle for its transitions).")
198 watchCmd.Flags().Bool("since-start", false, "Emit events already in the file before tailing new ones.")
199 watchCmd.Flags().Bool("once", false, "Wait for at least one matching event, print every one that has arrived and the command that waits for the next, then exit.")
200 watchCmd.Flags().Int64("after", 0, "With --once: the byte offset in events.jsonl to read from, as printed on the last watch's next: line.")
201 watchCmd.Flags().Bool("json", false, "Emit raw JSONL lines instead of human-formatted summaries.")
202 watchCmd.Flags().Bool("list-types", false, "Print known event types (live and reserved) and exit.")
203 watchCmd.Flags().String("session-id", "", "Override $KLAUS_SESSION_ID (mainly for testing).")
204 rootCmd.AddCommand(watchCmd)
205}
206
207func runWatch(cmd *cobra.Command, args []string) error {
208 listTypes, _ := cmd.Flags().GetBool("list-types")
209 if listTypes {
210 printKnownEventTypes(cmd.OutOrStdout())
211 return nil
212 }
213
214 filterIn, _ := cmd.Flags().GetStringSlice("filter")
215 filterOut, _ := cmd.Flags().GetStringSlice("filter-out")
216 runs, _ := cmd.Flags().GetStringSlice("run")
217 sinceStart, _ := cmd.Flags().GetBool("since-start")
218 once, _ := cmd.Flags().GetBool("once")
219 after, _ := cmd.Flags().GetInt64("after")
220 hasAfter := cmd.Flags().Changed("after")
221 asJSON, _ := cmd.Flags().GetBool("json")
222 sessionOverride, _ := cmd.Flags().GetString("session-id")
223
224 if hasAfter && !once {
225 return fmt.Errorf("--after needs --once")
226 }
227 if hasAfter && sinceStart {
228 return fmt.Errorf("--after and --since-start are mutually exclusive")
229 }
230 if after < 0 {
231 return fmt.Errorf("--after must not be negative")
232 }
233
234 sessionID := sessionOverride
235 if sessionID == "" {
236 sessionID = os.Getenv(sessionIDEnv)
237 }
238 if sessionID == "" {
239 return fmt.Errorf("valley flow watch must be run inside a flow session (KLAUS_SESSION_ID is not set; use --session-id to override)")
240 }
241
242 sessionsDir, err := run.SessionsDir()
243 if err != nil {
244 return err
245 }
246 cmd.SilenceUsage = true // flags are valid; later errors are not usage errors
247
248 sessionDir := filepath.Join(sessionsDir, sessionID)
249 if _, err := os.Stat(sessionDir); errors.Is(err, os.ErrNotExist) {
250 return fmt.Errorf("unknown session %s: %s does not exist", sessionID, sessionDir)
251 } else if err != nil {
252 return fmt.Errorf("stat session dir: %w", err)
253 }
254 eventsPath := event.NewLog(sessionDir).Path()
255
256 flt := buildFilter(filterIn, filterOut, runs)
257
258 ctx, stop := signal.NotifyContext(cmd.Context(), syscall.SIGINT, syscall.SIGTERM)
259 defer stop()
260
261 if once {
262 start := int64(-1) // the end of the file
263 if sinceStart {
264 start = 0
265 }
266 if hasAfter {
267 start = after
268 }
269 next := func(cursor int64) string {
270 return nextWatchCommand(sessionOverride, filterIn, filterOut, runs, asJSON, cursor)
271 }
272 return watchOnce(ctx, eventsPath, flt, start, asJSON, next, cmd.OutOrStdout())
273 }
274 return streamEvents(ctx, eventsPath, flt, sinceStart, asJSON, cmd.OutOrStdout())
275}
276
277// watchFilter decides whether a given event should be emitted.
278type watchFilter struct {
279 include map[string]struct{} // empty means "match anything"
280 exclude map[string]struct{}
281 runs map[string]struct{} // empty means every run
282}
283
284func buildFilter(includeFlags, excludeFlags, runFlags []string) watchFilter {
285 include := includeFlags
286 if len(include) == 0 {
287 include = defaultWatchFilter
288 }
289 inc := make(map[string]struct{}, len(include))
290 for _, t := range include {
291 t = strings.TrimSpace(t)
292 if t == "" {
293 continue
294 }
295 inc[t] = struct{}{}
296 }
297 exc := make(map[string]struct{}, len(excludeFlags))
298 for _, t := range excludeFlags {
299 t = strings.TrimSpace(t)
300 if t == "" {
301 continue
302 }
303 exc[t] = struct{}{}
304 }
305 runs := make(map[string]struct{}, len(runFlags))
306 for _, r := range runFlags {
307 r = strings.TrimSpace(r)
308 if r == "" {
309 continue
310 }
311 runs[r] = struct{}{}
312 }
313 return watchFilter{include: inc, exclude: exc, runs: runs}
314}
315
316// accepts reports whether evt passes both the type and the run filters.
317func (f watchFilter) accepts(evt event.Event) bool {
318 if len(f.runs) > 0 {
319 if _, ok := f.runs[evt.RunID]; !ok {
320 return false
321 }
322 }
323 return f.matches(evt.Type)
324}
325
326func (f watchFilter) matches(eventType string) bool {
327 if _, blocked := f.exclude[eventType]; blocked {
328 return false
329 }
330 if len(f.include) == 0 {
331 return true
332 }
333 _, ok := f.include[eventType]
334 return ok
335}
336
337// streamEvents waits for the events file to exist, then follows it with
338// fsnotify until ctx is cancelled. New lines that pass the filter are written
339// to out as either formatted summaries or raw JSON. A file it had to wait for
340// is new, so it reads that one from the start.
341func streamEvents(ctx context.Context, path string, flt watchFilter, sinceStart, asJSON bool, out io.Writer) error {
342 if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
343 sinceStart = true
344 }
345 if err := waitForFile(ctx, path); err != nil {
346 return err
347 }
348 // If ctx was cancelled during the wait, exit cleanly without trying to
349 // open the file (it may never have appeared).
350 if ctx.Err() != nil {
351 return nil
352 }
353
354 dir := filepath.Dir(path)
355 watcher, err := fsnotify.NewWatcher()
356 if err != nil {
357 return fmt.Errorf("creating file watcher: %w", err)
358 }
359 defer watcher.Close()
360 if err := watcher.Add(dir); err != nil {
361 return fmt.Errorf("watching %s: %w", dir, err)
362 }
363
364 f, err := os.Open(path)
365 if err != nil {
366 return fmt.Errorf("opening events file: %w", err)
367 }
368 defer func() {
369 if f != nil {
370 f.Close()
371 }
372 }()
373
374 currentInode := statInode(path)
375
376 if !sinceStart {
377 if _, err := f.Seek(0, io.SeekEnd); err != nil {
378 return fmt.Errorf("seeking to end of events file: %w", err)
379 }
380 }
381
382 // Buffer for accumulating partial lines across reads.
383 var pending []byte
384
385 drain := func() error {
386 buf := make([]byte, 32*1024)
387 for {
388 n, err := f.Read(buf)
389 if n > 0 {
390 pending = append(pending, buf[:n]...)
391 for {
392 idx := bytes.IndexByte(pending, '\n')
393 if idx < 0 {
394 break
395 }
396 line := pending[:idx]
397 pending = pending[idx+1:]
398 if len(line) == 0 {
399 continue
400 }
401 if _, err := emitLine(line, flt, asJSON, out); err != nil {
402 return err
403 }
404 }
405 }
406 if err == io.EOF {
407 return nil
408 }
409 if err != nil {
410 return fmt.Errorf("reading events file: %w", err)
411 }
412 }
413 }
414
415 if err := drain(); err != nil {
416 return err
417 }
418
419 reopen := func() error {
420 if f != nil {
421 f.Close()
422 }
423 nf, err := os.Open(path)
424 if err != nil {
425 return err
426 }
427 f = nf
428 pending = pending[:0]
429 currentInode = statInode(path)
430 return nil
431 }
432
433 // Even with fsnotify, a periodic inode/size check catches edge cases
434 // (e.g. file replaced after a notification was missed).
435 const poll = 500 * time.Millisecond
436 ticker := time.NewTicker(poll)
437 defer ticker.Stop()
438
439 for {
440 select {
441 case <-ctx.Done():
442 return nil
443 case ev, ok := <-watcher.Events:
444 if !ok {
445 return nil
446 }
447 if filepath.Clean(ev.Name) != filepath.Clean(path) {
448 continue
449 }
450 if ev.Op&(fsnotify.Create|fsnotify.Rename|fsnotify.Remove) != 0 {
451 if _, err := os.Stat(path); err == nil {
452 if err := reopen(); err != nil {
453 return fmt.Errorf("reopening events file after rotation: %w", err)
454 }
455 if err := drain(); err != nil {
456 return err
457 }
458 }
459 continue
460 }
461 if ev.Op&(fsnotify.Write|fsnotify.Chmod) != 0 {
462 if err := drain(); err != nil {
463 return err
464 }
465 }
466 case werr, ok := <-watcher.Errors:
467 if !ok {
468 return nil
469 }
470 // Watcher errors are non-fatal — log to stderr and keep going.
471 fmt.Fprintf(os.Stderr, "valley flow watch: watcher error: %v\n", werr)
472 case <-ticker.C:
473 // Defensive: catch missed write notifications and inode swaps.
474 newInode := statInode(path)
475 if newInode != 0 && newInode != currentInode {
476 if err := reopen(); err != nil {
477 return fmt.Errorf("reopening events file after inode change: %w", err)
478 }
479 }
480 if err := drain(); err != nil {
481 return err
482 }
483 }
484 }
485}
486
487// emitLine writes line to out if it is an event that passes flt, and
488// reports whether it did.
489func emitLine(line []byte, flt watchFilter, asJSON bool, out io.Writer) (bool, error) {
490 var evt event.Event
491 if err := json.Unmarshal(line, &evt); err != nil {
492 // Skip malformed lines silently — matches event.Log.Read behavior.
493 return false, nil
494 }
495 if !flt.accepts(evt) {
496 return false, nil
497 }
498 return true, writeEvent(line, evt, asJSON, out)
499}
500
501func writeEvent(line []byte, evt event.Event, asJSON bool, out io.Writer) error {
502 if asJSON {
503 if _, err := out.Write(line); err != nil {
504 return err
505 }
506 _, err := out.Write([]byte{'\n'})
507 return err
508 }
509 if _, err := fmt.Fprintln(out, formatEvent(evt)); err != nil {
510 return err
511 }
512 return nil
513}
514
515// formatEvent renders a single event as a one-line summary. Output shape:
516//
517// HH:MM:SS <run_id> <type> <one-line summary>
518func formatEvent(evt event.Event) string {
519 ts := evt.Timestamp
520 if parsed, err := time.Parse(time.RFC3339, evt.Timestamp); err == nil {
521 ts = parsed.Local().Format("15:04:05")
522 }
523 runID := evt.RunID
524 if runID == "" {
525 runID = "-"
526 }
527 return fmt.Sprintf("%s %s %-22s %s", ts, runID, evt.Type, eventSummary(evt))
528}
529
530func eventSummary(evt event.Event) string {
531 d := evt.Data
532 get := func(k string) string {
533 if d == nil {
534 return ""
535 }
536 v, ok := d[k]
537 if !ok || v == nil {
538 return ""
539 }
540 switch x := v.(type) {
541 case string:
542 return x
543 case float64:
544 // JSON numbers come back as float64 — trim trailing .0 for integer-ish values.
545 if x == float64(int64(x)) {
546 return fmt.Sprintf("%d", int64(x))
547 }
548 return fmt.Sprintf("%g", x)
549 default:
550 return fmt.Sprintf("%v", v)
551 }
552 }
553
554 prNum := get("pr_number")
555 prURL := get("pr_url")
556
557 switch evt.Type {
558 case event.ConsultStarted, event.ConsultCompleted:
559 parts := []string{get("backend")}
560 if m := get("model"); m != "" {
561 parts[0] += "/" + m
562 }
563 for _, k := range []string{"effort", "role"} {
564 if v := get(k); v != "" {
565 parts = append(parts, v)
566 }
567 }
568 for _, k := range []string{"thread", "repo"} {
569 if v := get(k); v != "" {
570 parts = append(parts, k+"="+v)
571 }
572 }
573 if get("panel") == "true" {
574 parts = append(parts, "panel")
575 }
576 head := strings.Join(parts, " ")
577 if evt.Type == event.ConsultStarted {
578 return truncateLine(head+": "+get("prompt"), 160)
579 }
580 status := "ok"
581 if get("success") != "true" {
582 status = "failed"
583 if e := get("error"); e != "" {
584 status += ": " + e
585 }
586 }
587 return truncateLine(fmt.Sprintf("%s (%sms) %s", head, get("duration_ms"), status), 160)
588 case event.ReviewStarted, event.ReviewCompleted:
589 head := get("backend")
590 if m := get("model"); m != "" {
591 head += "/" + m
592 }
593 head += " " + get("repo") + "#" + prNum
594 if get("post") == "true" {
595 head += " post"
596 }
597 if evt.Type == event.ReviewStarted {
598 return head
599 }
600 status := "ok: " + get("findings") + " findings"
601 if get("success") != "true" {
602 status = "failed"
603 if e := get("error"); e != "" {
604 status += ": " + e
605 }
606 }
607 return truncateLine(fmt.Sprintf("%s (%sms) %s", head, get("duration_ms"), status), 160)
608 case event.AgentStarted:
609 prompt := get("prompt")
610 if m := get("model"); m != "" {
611 prompt = "[" + m + "] " + prompt
612 }
613 if prompt != "" {
614 return truncateLine(prompt, 80)
615 }
616 return "agent started"
617 case event.AgentCompleted:
618 cost := get("cost_usd")
619 if cost != "" {
620 return fmt.Sprintf("agent completed (cost $%s)", cost)
621 }
622 return "agent completed"
623 case event.AgentPRCreated:
624 if prNum != "" && prURL != "" {
625 return fmt.Sprintf("PR #%s: %s", prNum, prURL)
626 }
627 if prURL != "" {
628 return prURL
629 }
630 return "PR created"
631 case event.AgentBranchPushed:
632 msg := "branch " + get("branch")
633 if sha := get("sha"); sha != "" {
634 msg += "@" + shortSHA(sha)
635 }
636 msg += " pushed, awaiting integration"
637 if repo := get("repo"); repo != "" {
638 msg += " (" + repo + ")"
639 }
640 return msg
641 case event.AgentChangeReady, event.AgentChangeDraft:
642 msg := strings.TrimSpace(get("repo") + " " + get("handle"))
643 if v := get("version"); v != "" {
644 msg += " v" + v
645 }
646 if evt.Type == event.AgentChangeDraft {
647 msg += " draft, awaiting review"
648 } else {
649 msg += " ready, awaiting approval"
650 }
651 if title := get("title"); title != "" {
652 msg += ": " + title
653 }
654 return truncateLine(msg, 160)
655 case event.AgentCIPassed:
656 if prNum != "" {
657 return fmt.Sprintf("CI passed on PR #%s", prNum)
658 }
659 return "CI passed"
660 case event.AgentCIFailed:
661 if prNum != "" {
662 return fmt.Sprintf("CI failed on PR #%s", prNum)
663 }
664 return "CI failed"
665 case event.AgentNeedsAttention:
666 msg := "needs attention"
667 if reason := get("reason"); reason != "" {
668 msg += " — " + reason
669 }
670 if branch := get("branch"); branch != "" {
671 msg += fmt.Sprintf(" (branch %s)", branch)
672 }
673 return msg
674 case event.PRAwaitingApproval:
675 if prNum != "" {
676 return fmt.Sprintf("PR #%s awaiting approval", prNum)
677 }
678 return "PR awaiting approval"
679 case event.PRApproved:
680 if prNum != "" {
681 return fmt.Sprintf("PR #%s approved", prNum)
682 }
683 return "PR approved"
684 case event.PRMerged:
685 if prNum != "" {
686 return fmt.Sprintf("PR #%s merged", prNum)
687 }
688 return "PR merged"
689 case event.ChangeApproved, event.ChangeIntegrated, event.ChangeStale, event.ChangeRejected,
690 event.ChangeFailed, event.ChangeWithdrawn, event.ChangeNewVersion,
691 event.ChangeChecksFailed, event.ChangeChecksPassed:
692 msg := strings.TrimSpace(get("repo") + " " + get("handle"))
693 if v := get("version"); v != "" {
694 msg += " v" + v
695 }
696 switch evt.Type {
697 case event.ChangeIntegrated:
698 msg += " integrated"
699 if c := get("landed_commit"); c != "" {
700 msg += " as " + shortSHA(c)
701 }
702 case event.ChangeChecksFailed:
703 msg += " checks failed"
704 if names := checkNames(evt.Data["failed"]); names != "" {
705 msg += ": " + names
706 }
707 case event.ChangeChecksPassed:
708 msg += " checks passed"
709 case event.ChangeNewVersion:
710 msg += " new version"
711 if h := get("head"); h != "" {
712 msg += " at " + shortSHA(h)
713 }
714 if u := get("uploader"); u != "" {
715 msg += " by " + u
716 }
717 default:
718 msg += " " + strings.TrimPrefix(evt.Type, "change:")
719 }
720 if title := get("title"); title != "" {
721 msg += ": " + title
722 }
723 return truncateLine(msg, 160)
724 case event.PhaseStarted:
725 return get("phase")
726 case event.PhaseCompleted:
727 return fmt.Sprintf("%s (%sms)", get("phase"), get("duration_ms"))
728 case event.CheckStarted:
729 return truncateLine(get("kind")+": "+get("command"), 160)
730 case event.CheckCompleted:
731 status := "ok"
732 if get("success") == "false" {
733 status = "failed"
734 }
735 return truncateLine(fmt.Sprintf("%s (%sms) %s: %s", get("kind"), get("duration_ms"), status, get("command")), 160)
736 case event.ChangeRestackDispatched, event.ChangeRestackStalled:
737 msg := strings.TrimSpace(get("repo") + " " + get("handle"))
738 if v := get("version"); v != "" {
739 msg += " v" + v
740 }
741 if evt.Type == event.ChangeRestackDispatched {
742 msg += fmt.Sprintf(": resolving its restack conflict (attempt %s of %s)", get("attempt"), get("max_attempts"))
743 } else {
744 msg += ": restack conflict left unresolved — " + get("reason")
745 }
746 return truncateLine(msg, 160)
747 case event.PipelineStalled:
748 reason := get("reason")
749 switch {
750 case prNum != "" && reason != "":
751 return fmt.Sprintf("PR #%s stalled — %s", prNum, reason)
752 case prNum != "":
753 return fmt.Sprintf("PR #%s stalled", prNum)
754 case reason != "":
755 return fmt.Sprintf("pipeline stalled — %s", reason)
756 }
757 return "pipeline stalled"
758 }
759
760 // Generic fallback: list known fields in a stable order.
761 if d == nil {
762 return ""
763 }
764 keys := make([]string, 0, len(d))
765 for k := range d {
766 keys = append(keys, k)
767 }
768 sort.Strings(keys)
769 parts := make([]string, 0, len(keys))
770 for _, k := range keys {
771 v := get(k)
772 if v == "" {
773 continue
774 }
775 parts = append(parts, fmt.Sprintf("%s=%s", k, v))
776 }
777 return strings.Join(parts, " ")
778}
779
780func truncateLine(s string, max int) string {
781 s = strings.Join(strings.Fields(s), " ")
782 runes := []rune(s)
783 if len(runes) <= max {
784 return s
785 }
786 if max <= 1 {
787 return string(runes[:max])
788 }
789 return string(runes[:max-1]) + "…"
790}
791
792// waitForFile blocks until path exists, polling every 500ms, for as long as
793// the session directory holding it does: a session created before klaus made
794// the file at session start has none until its first event. It returns nil
795// once the file exists or ctx is cancelled, and an error if the session
796// directory is removed.
797func waitForFile(ctx context.Context, path string) error {
798 for {
799 if _, err := os.Stat(path); err == nil {
800 return nil
801 } else if !errors.Is(err, os.ErrNotExist) {
802 return fmt.Errorf("stat events file: %w", err)
803 }
804 if err := checkSessionDir(path); err != nil {
805 return err
806 }
807 select {
808 case <-ctx.Done():
809 return nil
810 case <-time.After(500 * time.Millisecond):
811 }
812 }
813}
814
815// checkSessionDir returns an error if the session directory holding the
816// events file at path no longer exists.
817func checkSessionDir(path string) error {
818 dir := filepath.Dir(path)
819 if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
820 return fmt.Errorf("session directory %s was removed", dir)
821 } else if err != nil {
822 return fmt.Errorf("stat session dir: %w", err)
823 }
824 return nil
825}
826
827// watchOnce is klaus watch --once. It reads the events file from byte offset
828// start (the end of the file if start is negative) and waits until at least
829// one complete line there is an event that passes flt. It writes every such
830// event in the file at that moment to out, then the next: line, built by
831// next from the offset just past the last complete line it read. The offset
832// only ever advances past whole lines, all of which it has written or
833// filtered out, so starting the next watch from it neither repeats nor skips
834// an event. Cancelling ctx ends the wait early with just the next: line.
835func watchOnce(ctx context.Context, path string, flt watchFilter, start int64, asJSON bool, next func(int64) string, out io.Writer) error {
836 cursor := int64(0)
837 if start > 0 {
838 cursor = start
839 }
840 trailer := func() error {
841 cmdline := next(cursor)
842 if asJSON {
843 data, err := json.Marshal(struct {
844 After int64 `json:"after"`
845 Next string `json:"next"`
846 }{cursor, cmdline})
847 if err != nil {
848 return err
849 }
850 _, err = fmt.Fprintln(out, string(data))
851 return err
852 }
853 _, err := fmt.Fprintln(out, "next: "+cmdline)
854 return err
855 }
856
857 // Watch the directory before reading, so a write that lands between a
858 // read and the wait still wakes the loop.
859 watcher, err := fsnotify.NewWatcher()
860 if err != nil {
861 return fmt.Errorf("creating file watcher: %w", err)
862 }
863 defer watcher.Close()
864 if err := watcher.Add(filepath.Dir(path)); err != nil {
865 return fmt.Errorf("watching %s: %w", filepath.Dir(path), err)
866 }
867
868 f, err := os.Open(path)
869 if errors.Is(err, os.ErrNotExist) {
870 // No file yet, so the end of the file is its start: every event
871 // that lands in it is new.
872 if start < 0 {
873 start = 0
874 }
875 if err := waitForFile(ctx, path); err != nil {
876 return err
877 }
878 if ctx.Err() != nil {
879 return trailer()
880 }
881 f, err = os.Open(path)
882 }
883 if err != nil {
884 return fmt.Errorf("opening events file: %w", err)
885 }
886 defer f.Close()
887 info, err := f.Stat()
888 if err != nil {
889 return fmt.Errorf("stat events file: %w", err)
890 }
891 var inode uint64
892 if sys, ok := info.Sys().(*syscall.Stat_t); ok {
893 inode = sys.Ino
894 }
895 switch {
896 case start < 0:
897 cursor = info.Size()
898 case start > info.Size():
899 return fmt.Errorf("--after %d is past the end of %s (%d bytes): pass the offset from the last watch's next: line", start, path, info.Size())
900 case start > 0:
901 // An offset from a next: line is always just past a newline.
902 b := make([]byte, 1)
903 if _, err := f.ReadAt(b, start-1); err != nil {
904 return fmt.Errorf("reading events file: %w", err)
905 }
906 if b[0] != '\n' {
907 return fmt.Errorf("--after %d is not at the start of a line in %s: pass the offset from the last watch's next: line", start, path)
908 }
909 }
910 if _, err := f.Seek(cursor, io.SeekStart); err != nil {
911 return fmt.Errorf("seeking events file: %w", err)
912 }
913
914 // read consumes every complete line from the cursor on, writing those
915 // that pass flt, and reports how many it wrote. A partial last line,
916 // still being written, stays in pending, short of the cursor.
917 var pending []byte
918 buf := make([]byte, 32*1024)
919 read := func() (int, error) {
920 written := 0
921 for {
922 n, err := f.Read(buf)
923 if n > 0 {
924 pending = append(pending, buf[:n]...)
925 for {
926 idx := bytes.IndexByte(pending, '\n')
927 if idx < 0 {
928 break
929 }
930 line := pending[:idx]
931 pending = pending[idx+1:]
932 ok, werr := emitLine(line, flt, asJSON, out)
933 if werr != nil {
934 return written, werr
935 }
936 cursor += int64(idx) + 1
937 if ok {
938 written++
939 }
940 }
941 }
942 if err == io.EOF {
943 return written, nil
944 }
945 if err != nil {
946 return written, fmt.Errorf("reading events file: %w", err)
947 }
948 }
949 }
950
951 ticker := time.NewTicker(500 * time.Millisecond)
952 defer ticker.Stop()
953 for {
954 written, err := read()
955 if err != nil {
956 return err
957 }
958 if written > 0 {
959 return trailer()
960 }
961 select {
962 case <-ctx.Done():
963 return trailer()
964 case _, ok := <-watcher.Events:
965 if !ok {
966 return trailer()
967 }
968 case werr, ok := <-watcher.Errors:
969 if !ok {
970 return trailer()
971 }
972 fmt.Fprintf(os.Stderr, "valley flow watch: watcher error: %v\n", werr)
973 case <-ticker.C:
974 // Catches a missed notification, and a session or events file
975 // removed under us. Offsets into a file that was replaced say
976 // nothing about the new one, so that ends the watch too.
977 if err := checkSessionDir(path); err != nil {
978 return err
979 }
980 if inode != 0 && statInode(path) != inode {
981 return fmt.Errorf("%s was replaced or removed while this watch read it: its offsets don't apply to the new file", path)
982 }
983 }
984 }
985}
986
987// nextWatchCommand is the valley flow watch --once command line that reads on from
988// cursor with the given flags.
989func nextWatchCommand(sessionID string, filterIn, filterOut, runs []string, asJSON bool, cursor int64) string {
990 args := []string{"valley", "flow", "watch", "--once", "--after", strconv.FormatInt(cursor, 10)}
991 if sessionID != "" {
992 args = append(args, "--session-id", shellWord(sessionID))
993 }
994 for _, flag := range []struct {
995 name string
996 values []string
997 }{{"--filter", filterIn}, {"--filter-out", filterOut}, {"--run", runs}} {
998 for _, v := range flag.values {
999 args = append(args, flag.name, shellWord(v))
1000 }
1001 }
1002 if asJSON {
1003 args = append(args, "--json")
1004 }
1005 return strings.Join(args, " ")
1006}
1007
1008// statInode returns the inode for path, or 0 if unavailable.
1009// Used to detect log rotation when fsnotify drops a notification.
1010func statInode(path string) uint64 {
1011 info, err := os.Stat(path)
1012 if err != nil {
1013 return 0
1014 }
1015 sys, ok := info.Sys().(*syscall.Stat_t)
1016 if !ok {
1017 return 0
1018 }
1019 return sys.Ino
1020}
1021
1022func printKnownEventTypes(out io.Writer) {
1023 // Group live first, then reserved, alphabetically within each group.
1024 live := make([]eventTypeInfo, 0)
1025 reserved := make([]eventTypeInfo, 0)
1026 for _, t := range knownEventTypes {
1027 if t.Status == "reserved" {
1028 reserved = append(reserved, t)
1029 } else {
1030 live = append(live, t)
1031 }
1032 }
1033 sort.Slice(live, func(i, j int) bool { return live[i].Type < live[j].Type })
1034 sort.Slice(reserved, func(i, j int) bool { return reserved[i].Type < reserved[j].Type })
1035
1036 fmt.Fprintln(out, "Live event types (currently emitted by flow):")
1037 for _, t := range live {
1038 fmt.Fprintf(out, " %-24s %s\n", t.Type, t.Desc)
1039 }
1040 fmt.Fprintln(out)
1041 fmt.Fprintln(out, "Reserved event types (not currently emitted; included in default filter for forward-compat):")
1042 for _, t := range reserved {
1043 fmt.Fprintf(out, " %-24s %s\n", t.Type, t.Desc)
1044 }
1045 fmt.Fprintln(out)
1046 fmt.Fprintln(out, "Default filter:")
1047 def := append([]string{}, defaultWatchFilter...)
1048 sort.Strings(def)
1049 fmt.Fprintln(out, " "+strings.Join(def, ", "))
1050}
1051
1052// checkNames joins the check names an event's failed field carries, as
1053// JSON decodes them.
1054func checkNames(v interface{}) string {
1055 list, _ := v.([]interface{})
1056 var names []string
1057 for _, n := range list {
1058 if s, ok := n.(string); ok && s != "" {
1059 names = append(names, s)
1060 }
1061 }
1062 return strings.Join(names, ", ")
1063}