gunk-dev/the-valley

watch.go

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