gunk-dev/the-valley

watch.go

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