gunk-dev/the-valley

watch.go

sourcec14b0e68e9c3main's published tip history
41.2 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 sessionsDir, err := run.SessionsDir()
280 if err != nil {
281 return err
282 }
283 cmd.SilenceUsage = true // flags are valid; later errors are not usage errors
284
285 sessionDir := filepath.Join(sessionsDir, sessionID)
286 if _, err := os.Stat(sessionDir); errors.Is(err, os.ErrNotExist) {
287 return fmt.Errorf("unknown session %s: %s does not exist", sessionID, sessionDir)
288 } else if err != nil {
289 return fmt.Errorf("stat session dir: %w", err)
290 }
291 eventsPath := event.NewLog(sessionDir).Path()
292
293 flt := buildFilter(filterIn, filterOut, runs)
294
295 ctx, stop := signal.NotifyContext(cmd.Context(), syscall.SIGINT, syscall.SIGTERM)
296 defer stop()
297
298 if waitQueue {
299 store := run.NewHomeDirStoreFromPath(sessionDir)
300 src := queueSource{
301 compute: func(ctx context.Context) (queue, bool, error) { return computeQueue(ctx, store) },
302 events: eventsPath,
303 runs: store.StateDir(),
304 }
305 next := func(digest string) string { return nextQueueWatchCommand(sessionOverride, digest) }
306 return watchQueue(ctx, src, seen, next, cmd.OutOrStdout())
307 }
308 if once {
309 start := int64(-1) // the end of the file
310 if sinceStart {
311 start = 0
312 }
313 if hasAfter {
314 start = after
315 }
316 next := func(cursor int64) string {
317 return nextWatchCommand(sessionOverride, filterIn, filterOut, runs, asJSON, cursor)
318 }
319 return watchOnce(ctx, eventsPath, flt, start, asJSON, next, cmd.OutOrStdout())
320 }
321 return streamEvents(ctx, eventsPath, flt, sinceStart, asJSON, cmd.OutOrStdout())
322}
323
324// watchFilter decides whether a given event should be emitted.
325type watchFilter struct {
326 include map[string]struct{} // empty means "match anything"
327 exclude map[string]struct{}
328 runs map[string]struct{} // empty means every run
329}
330
331func buildFilter(includeFlags, excludeFlags, runFlags []string) watchFilter {
332 include := includeFlags
333 if len(include) == 0 {
334 include = defaultWatchFilter
335 }
336 inc := make(map[string]struct{}, len(include))
337 for _, t := range include {
338 t = strings.TrimSpace(t)
339 if t == "" {
340 continue
341 }
342 inc[t] = struct{}{}
343 }
344 exc := make(map[string]struct{}, len(excludeFlags))
345 for _, t := range excludeFlags {
346 t = strings.TrimSpace(t)
347 if t == "" {
348 continue
349 }
350 exc[t] = struct{}{}
351 }
352 runs := make(map[string]struct{}, len(runFlags))
353 for _, r := range runFlags {
354 r = strings.TrimSpace(r)
355 if r == "" {
356 continue
357 }
358 runs[r] = struct{}{}
359 }
360 return watchFilter{include: inc, exclude: exc, runs: runs}
361}
362
363// accepts reports whether evt passes both the type and the run filters.
364func (f watchFilter) accepts(evt event.Event) bool {
365 if len(f.runs) > 0 {
366 if _, ok := f.runs[evt.RunID]; !ok {
367 return false
368 }
369 }
370 return f.matches(evt.Type)
371}
372
373func (f watchFilter) matches(eventType string) bool {
374 if _, blocked := f.exclude[eventType]; blocked {
375 return false
376 }
377 if len(f.include) == 0 {
378 return true
379 }
380 _, ok := f.include[eventType]
381 return ok
382}
383
384// streamEvents waits for the events file to exist, then follows it with
385// fsnotify until ctx is cancelled. New lines that pass the filter are written
386// to out as either formatted summaries or raw JSON. A file it had to wait for
387// is new, so it reads that one from the start.
388func streamEvents(ctx context.Context, path string, flt watchFilter, sinceStart, asJSON bool, out io.Writer) error {
389 if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
390 sinceStart = true
391 }
392 if err := waitForFile(ctx, path); err != nil {
393 return err
394 }
395 // If ctx was cancelled during the wait, exit cleanly without trying to
396 // open the file (it may never have appeared).
397 if ctx.Err() != nil {
398 return nil
399 }
400
401 dir := filepath.Dir(path)
402 watcher, err := fsnotify.NewWatcher()
403 if err != nil {
404 return fmt.Errorf("creating file watcher: %w", err)
405 }
406 defer watcher.Close()
407 if err := watcher.Add(dir); err != nil {
408 return fmt.Errorf("watching %s: %w", dir, err)
409 }
410
411 f, err := os.Open(path)
412 if err != nil {
413 return fmt.Errorf("opening events file: %w", err)
414 }
415 defer func() {
416 if f != nil {
417 f.Close()
418 }
419 }()
420
421 currentInode := statInode(path)
422
423 if !sinceStart {
424 if _, err := f.Seek(0, io.SeekEnd); err != nil {
425 return fmt.Errorf("seeking to end of events file: %w", err)
426 }
427 }
428
429 // Buffer for accumulating partial lines across reads.
430 var pending []byte
431
432 drain := func() error {
433 buf := make([]byte, 32*1024)
434 for {
435 n, err := f.Read(buf)
436 if n > 0 {
437 pending = append(pending, buf[:n]...)
438 for {
439 idx := bytes.IndexByte(pending, '\n')
440 if idx < 0 {
441 break
442 }
443 line := pending[:idx]
444 pending = pending[idx+1:]
445 if len(line) == 0 {
446 continue
447 }
448 if _, err := emitLine(line, flt, asJSON, out); err != nil {
449 return err
450 }
451 }
452 }
453 if err == io.EOF {
454 return nil
455 }
456 if err != nil {
457 return fmt.Errorf("reading events file: %w", err)
458 }
459 }
460 }
461
462 if err := drain(); err != nil {
463 return err
464 }
465
466 reopen := func() error {
467 if f != nil {
468 f.Close()
469 }
470 nf, err := os.Open(path)
471 if err != nil {
472 return err
473 }
474 f = nf
475 pending = pending[:0]
476 currentInode = statInode(path)
477 return nil
478 }
479
480 // Even with fsnotify, a periodic inode/size check catches edge cases
481 // (e.g. file replaced after a notification was missed).
482 const poll = 500 * time.Millisecond
483 ticker := time.NewTicker(poll)
484 defer ticker.Stop()
485
486 for {
487 select {
488 case <-ctx.Done():
489 return nil
490 case ev, ok := <-watcher.Events:
491 if !ok {
492 return nil
493 }
494 if filepath.Clean(ev.Name) != filepath.Clean(path) {
495 continue
496 }
497 if ev.Op&(fsnotify.Create|fsnotify.Rename|fsnotify.Remove) != 0 {
498 if _, err := os.Stat(path); err == nil {
499 if err := reopen(); err != nil {
500 return fmt.Errorf("reopening events file after rotation: %w", err)
501 }
502 if err := drain(); err != nil {
503 return err
504 }
505 }
506 continue
507 }
508 if ev.Op&(fsnotify.Write|fsnotify.Chmod) != 0 {
509 if err := drain(); err != nil {
510 return err
511 }
512 }
513 case werr, ok := <-watcher.Errors:
514 if !ok {
515 return nil
516 }
517 // Watcher errors are non-fatal — log to stderr and keep going.
518 fmt.Fprintf(os.Stderr, "valley flow watch: watcher error: %v\n", werr)
519 case <-ticker.C:
520 // Defensive: catch missed write notifications and inode swaps.
521 newInode := statInode(path)
522 if newInode != 0 && newInode != currentInode {
523 if err := reopen(); err != nil {
524 return fmt.Errorf("reopening events file after inode change: %w", err)
525 }
526 }
527 if err := drain(); err != nil {
528 return err
529 }
530 }
531 }
532}
533
534// emitLine writes line to out if it is an event that passes flt, and
535// reports whether it did.
536func emitLine(line []byte, flt watchFilter, asJSON bool, out io.Writer) (bool, error) {
537 var evt event.Event
538 if err := json.Unmarshal(line, &evt); err != nil {
539 // Skip malformed lines silently — matches event.Log.Read behavior.
540 return false, nil
541 }
542 if !flt.accepts(evt) {
543 return false, nil
544 }
545 return true, writeEvent(line, evt, asJSON, out)
546}
547
548func writeEvent(line []byte, evt event.Event, asJSON bool, out io.Writer) error {
549 if asJSON {
550 if _, err := out.Write(line); err != nil {
551 return err
552 }
553 _, err := out.Write([]byte{'\n'})
554 return err
555 }
556 if _, err := fmt.Fprintln(out, formatEvent(evt)); err != nil {
557 return err
558 }
559 return nil
560}
561
562// formatEvent renders a single event as a one-line summary. Output shape:
563//
564// HH:MM:SS <run_id> <type> <one-line summary>
565func formatEvent(evt event.Event) string {
566 ts := evt.Timestamp
567 if parsed, err := time.Parse(time.RFC3339, evt.Timestamp); err == nil {
568 ts = parsed.Local().Format("15:04:05")
569 }
570 runID := evt.RunID
571 if runID == "" {
572 runID = "-"
573 }
574 return fmt.Sprintf("%s %s %-22s %s", ts, runID, evt.Type, eventSummary(evt))
575}
576
577func eventSummary(evt event.Event) string {
578 d := evt.Data
579 get := func(k string) string {
580 if d == nil {
581 return ""
582 }
583 v, ok := d[k]
584 if !ok || v == nil {
585 return ""
586 }
587 switch x := v.(type) {
588 case string:
589 return x
590 case float64:
591 // JSON numbers come back as float64 — trim trailing .0 for integer-ish values.
592 if x == float64(int64(x)) {
593 return fmt.Sprintf("%d", int64(x))
594 }
595 return fmt.Sprintf("%g", x)
596 default:
597 return fmt.Sprintf("%v", v)
598 }
599 }
600
601 prNum := get("pr_number")
602 prURL := get("pr_url")
603
604 switch evt.Type {
605 case event.ConsultStarted, event.ConsultCompleted:
606 parts := []string{get("backend")}
607 if m := get("model"); m != "" {
608 parts[0] += "/" + m
609 }
610 for _, k := range []string{"effort", "role"} {
611 if v := get(k); v != "" {
612 parts = append(parts, v)
613 }
614 }
615 for _, k := range []string{"thread", "repo"} {
616 if v := get(k); v != "" {
617 parts = append(parts, k+"="+v)
618 }
619 }
620 if get("panel") == "true" {
621 parts = append(parts, "panel")
622 }
623 head := strings.Join(parts, " ")
624 if evt.Type == event.ConsultStarted {
625 return truncateLine(head+": "+get("prompt"), 160)
626 }
627 status := "ok"
628 if get("success") != "true" {
629 status = "failed"
630 if e := get("error"); e != "" {
631 status += ": " + e
632 }
633 }
634 return truncateLine(fmt.Sprintf("%s (%sms) %s", head, get("duration_ms"), status), 160)
635 case event.ReviewStarted, event.ReviewCompleted:
636 head := get("backend")
637 if m := get("model"); m != "" {
638 head += "/" + m
639 }
640 head += " " + get("repo") + "#" + prNum
641 if get("post") == "true" {
642 head += " post"
643 }
644 if evt.Type == event.ReviewStarted {
645 return head
646 }
647 status := "ok: " + get("findings") + " findings"
648 if get("success") != "true" {
649 status = "failed"
650 if e := get("error"); e != "" {
651 status += ": " + e
652 }
653 }
654 return truncateLine(fmt.Sprintf("%s (%sms) %s", head, get("duration_ms"), status), 160)
655 case event.AgentStarted:
656 prompt := get("prompt")
657 if m := get("model"); m != "" {
658 prompt = "[" + m + "] " + prompt
659 }
660 if prompt != "" {
661 return truncateLine(prompt, 80)
662 }
663 return "agent started"
664 case event.AgentCompleted:
665 cost := get("cost_usd")
666 if cost != "" {
667 return fmt.Sprintf("agent completed (cost $%s)", cost)
668 }
669 return "agent completed"
670 case event.AgentPRCreated:
671 if prNum != "" && prURL != "" {
672 return fmt.Sprintf("PR #%s: %s", prNum, prURL)
673 }
674 if prURL != "" {
675 return prURL
676 }
677 return "PR created"
678 case event.AgentBranchPushed:
679 msg := "branch " + get("branch")
680 if sha := get("sha"); sha != "" {
681 msg += "@" + shortSHA(sha)
682 }
683 msg += " pushed, awaiting integration"
684 if repo := get("repo"); repo != "" {
685 msg += " (" + repo + ")"
686 }
687 return msg
688 case event.AgentChangeReady, event.AgentChangeDraft:
689 msg := strings.TrimSpace(get("repo") + " " + get("handle"))
690 if v := get("version"); v != "" {
691 msg += " v" + v
692 }
693 if evt.Type == event.AgentChangeDraft {
694 msg += " draft, awaiting review"
695 } else {
696 msg += " ready, awaiting approval"
697 }
698 if title := get("title"); title != "" {
699 msg += ": " + title
700 }
701 return truncateLine(msg, 160)
702 case event.AgentCIPassed:
703 if prNum != "" {
704 return fmt.Sprintf("CI passed on PR #%s", prNum)
705 }
706 return "CI passed"
707 case event.AgentCIFailed:
708 if prNum != "" {
709 return fmt.Sprintf("CI failed on PR #%s", prNum)
710 }
711 return "CI failed"
712 case event.AgentNeedsAttention:
713 msg := "needs attention"
714 if reason := get("reason"); reason != "" {
715 msg += " — " + reason
716 }
717 if branch := get("branch"); branch != "" {
718 msg += fmt.Sprintf(" (branch %s)", branch)
719 }
720 return msg
721 case event.AgentDataRefPushFailed:
722 rec := &run.DataRefPush{Ref: get("ref"), Class: get("class"), Message: get("message")}
723 return truncateLine("warning: at finalize: "+dataRefFailure(rec), 160)
724 case event.AgentDataRefPush:
725 if get("status") == run.DataRefNotAttempted {
726 return "kept " + oneLine(get("ref")) + " local at finalize (push_data_ref off)"
727 }
728 return "published " + oneLine(get("ref")) + " at finalize"
729 case event.PRAwaitingApproval:
730 if prNum != "" {
731 return fmt.Sprintf("PR #%s awaiting approval", prNum)
732 }
733 return "PR awaiting approval"
734 case event.PRApproved:
735 if prNum != "" {
736 return fmt.Sprintf("PR #%s approved", prNum)
737 }
738 return "PR approved"
739 case event.PRMerged:
740 if prNum != "" {
741 return fmt.Sprintf("PR #%s merged", prNum)
742 }
743 return "PR merged"
744 case event.ChangeApproved, event.ChangeIntegrated, event.ChangeStale, event.ChangeRejected,
745 event.ChangeFailed, event.ChangeWithdrawn, event.ChangeNewVersion,
746 event.ChangeChecksFailed, event.ChangeChecksPassed:
747 msg := strings.TrimSpace(get("repo") + " " + get("handle"))
748 if v := get("version"); v != "" {
749 msg += " v" + v
750 }
751 switch evt.Type {
752 case event.ChangeIntegrated:
753 msg += " integrated"
754 if c := get("landed_commit"); c != "" {
755 msg += " as " + shortSHA(c)
756 }
757 case event.ChangeChecksFailed:
758 msg += " checks failed"
759 if names := checkNames(evt.Data["failed"]); names != "" {
760 msg += ": " + names
761 }
762 case event.ChangeChecksPassed:
763 msg += " checks passed"
764 case event.ChangeNewVersion:
765 msg += " new version"
766 if h := get("head"); h != "" {
767 msg += " at " + shortSHA(h)
768 }
769 if u := get("uploader"); u != "" {
770 msg += " by " + u
771 }
772 default:
773 msg += " " + strings.TrimPrefix(evt.Type, "change:")
774 }
775 if title := get("title"); title != "" {
776 msg += ": " + title
777 }
778 return truncateLine(msg, 160)
779 case event.PhaseStarted:
780 return get("phase")
781 case event.PhaseCompleted:
782 return fmt.Sprintf("%s (%sms)", get("phase"), get("duration_ms"))
783 case event.CheckStarted:
784 return truncateLine(get("kind")+": "+get("command"), 160)
785 case event.CheckCompleted:
786 status := "ok"
787 if get("success") == "false" {
788 status = "failed"
789 }
790 return truncateLine(fmt.Sprintf("%s (%sms) %s: %s", get("kind"), get("duration_ms"), status, get("command")), 160)
791 case event.ChangeChecksStalled:
792 msg := strings.TrimSpace(get("repo") + " " + get("handle"))
793 if v := get("version"); v != "" {
794 msg += " v" + v
795 }
796 msg += " checks failed"
797 if names := checkNames(evt.Data["failed"]); names != "" {
798 msg += ": " + names
799 }
800 return truncateLine(msg+"; flow won't fix them — "+get("reason"), 160)
801 case event.ChangeRestackDispatched, event.ChangeRestackStalled:
802 msg := strings.TrimSpace(get("repo") + " " + get("handle"))
803 if v := get("version"); v != "" {
804 msg += " v" + v
805 }
806 if evt.Type == event.ChangeRestackDispatched {
807 msg += fmt.Sprintf(": resolving its restack conflict (attempt %s of %s)", get("attempt"), get("max_attempts"))
808 } else {
809 msg += ": restack conflict left unresolved — " + get("reason")
810 }
811 return truncateLine(msg, 160)
812 case event.PipelineStalled:
813 reason := get("reason")
814 switch {
815 case prNum != "" && reason != "":
816 return fmt.Sprintf("PR #%s stalled — %s", prNum, reason)
817 case prNum != "":
818 return fmt.Sprintf("PR #%s stalled", prNum)
819 case reason != "":
820 return fmt.Sprintf("pipeline stalled — %s", reason)
821 }
822 return "pipeline stalled"
823 }
824
825 // Generic fallback: list known fields in a stable order.
826 if d == nil {
827 return ""
828 }
829 keys := make([]string, 0, len(d))
830 for k := range d {
831 keys = append(keys, k)
832 }
833 sort.Strings(keys)
834 parts := make([]string, 0, len(keys))
835 for _, k := range keys {
836 v := get(k)
837 if v == "" {
838 continue
839 }
840 parts = append(parts, fmt.Sprintf("%s=%s", k, v))
841 }
842 return strings.Join(parts, " ")
843}
844
845func truncateLine(s string, max int) string {
846 s = strings.Join(strings.Fields(s), " ")
847 runes := []rune(s)
848 if len(runes) <= max {
849 return s
850 }
851 if max <= 1 {
852 return string(runes[:max])
853 }
854 return string(runes[:max-1]) + "…"
855}
856
857// waitForFile blocks until path exists, polling every 500ms, for as long as
858// the session directory holding it does: a session created before klaus made
859// the file at session start has none until its first event. It returns nil
860// once the file exists or ctx is cancelled, and an error if the session
861// directory is removed.
862func waitForFile(ctx context.Context, path string) error {
863 for {
864 if _, err := os.Stat(path); err == nil {
865 return nil
866 } else if !errors.Is(err, os.ErrNotExist) {
867 return fmt.Errorf("stat events file: %w", err)
868 }
869 if err := checkSessionDir(path); err != nil {
870 return err
871 }
872 select {
873 case <-ctx.Done():
874 return nil
875 case <-time.After(500 * time.Millisecond):
876 }
877 }
878}
879
880// checkSessionDir returns an error if the session directory holding the
881// events file at path no longer exists.
882func checkSessionDir(path string) error {
883 dir := filepath.Dir(path)
884 if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
885 return fmt.Errorf("session directory %s was removed", dir)
886 } else if err != nil {
887 return fmt.Errorf("stat session dir: %w", err)
888 }
889 return nil
890}
891
892// watchOnce is klaus watch --once. It reads the events file from byte offset
893// start (the end of the file if start is negative) and waits until at least
894// one complete line there is an event that passes flt. It writes every such
895// event in the file at that moment to out, then the next: line, built by
896// next from the offset just past the last complete line it read. The offset
897// only ever advances past whole lines, all of which it has written or
898// filtered out, so starting the next watch from it neither repeats nor skips
899// an event. Cancelling ctx ends the wait early with just the next: line.
900func watchOnce(ctx context.Context, path string, flt watchFilter, start int64, asJSON bool, next func(int64) string, out io.Writer) error {
901 cursor := int64(0)
902 if start > 0 {
903 cursor = start
904 }
905 trailer := func() error {
906 cmdline := next(cursor)
907 if asJSON {
908 data, err := json.Marshal(struct {
909 After int64 `json:"after"`
910 Next string `json:"next"`
911 }{cursor, cmdline})
912 if err != nil {
913 return err
914 }
915 _, err = fmt.Fprintln(out, string(data))
916 return err
917 }
918 _, err := fmt.Fprintln(out, "next: "+cmdline)
919 return err
920 }
921
922 // Watch the directory before reading, so a write that lands between a
923 // read and the wait still wakes the loop.
924 watcher, err := fsnotify.NewWatcher()
925 if err != nil {
926 return fmt.Errorf("creating file watcher: %w", err)
927 }
928 defer watcher.Close()
929 if err := watcher.Add(filepath.Dir(path)); err != nil {
930 return fmt.Errorf("watching %s: %w", filepath.Dir(path), err)
931 }
932
933 f, err := os.Open(path)
934 if errors.Is(err, os.ErrNotExist) {
935 // No file yet, so the end of the file is its start: every event
936 // that lands in it is new.
937 if start < 0 {
938 start = 0
939 }
940 if err := waitForFile(ctx, path); err != nil {
941 return err
942 }
943 if ctx.Err() != nil {
944 return trailer()
945 }
946 f, err = os.Open(path)
947 }
948 if err != nil {
949 return fmt.Errorf("opening events file: %w", err)
950 }
951 defer f.Close()
952 info, err := f.Stat()
953 if err != nil {
954 return fmt.Errorf("stat events file: %w", err)
955 }
956 var inode uint64
957 if sys, ok := info.Sys().(*syscall.Stat_t); ok {
958 inode = sys.Ino
959 }
960 switch {
961 case start < 0:
962 cursor = info.Size()
963 case start > info.Size():
964 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())
965 case start > 0:
966 // An offset from a next: line is always just past a newline.
967 b := make([]byte, 1)
968 if _, err := f.ReadAt(b, start-1); err != nil {
969 return fmt.Errorf("reading events file: %w", err)
970 }
971 if b[0] != '\n' {
972 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)
973 }
974 }
975 if _, err := f.Seek(cursor, io.SeekStart); err != nil {
976 return fmt.Errorf("seeking events file: %w", err)
977 }
978
979 // read consumes every complete line from the cursor on, writing those
980 // that pass flt, and reports how many it wrote. A partial last line,
981 // still being written, stays in pending, short of the cursor.
982 var pending []byte
983 buf := make([]byte, 32*1024)
984 read := func() (int, error) {
985 written := 0
986 for {
987 n, err := f.Read(buf)
988 if n > 0 {
989 pending = append(pending, buf[:n]...)
990 for {
991 idx := bytes.IndexByte(pending, '\n')
992 if idx < 0 {
993 break
994 }
995 line := pending[:idx]
996 pending = pending[idx+1:]
997 ok, werr := emitLine(line, flt, asJSON, out)
998 if werr != nil {
999 return written, werr
1000 }
1001 cursor += int64(idx) + 1
1002 if ok {
1003 written++
1004 }
1005 }
1006 }
1007 if err == io.EOF {
1008 return written, nil
1009 }
1010 if err != nil {
1011 return written, fmt.Errorf("reading events file: %w", err)
1012 }
1013 }
1014 }
1015
1016 ticker := time.NewTicker(500 * time.Millisecond)
1017 defer ticker.Stop()
1018 for {
1019 written, err := read()
1020 if err != nil {
1021 return err
1022 }
1023 if written > 0 {
1024 return trailer()
1025 }
1026 select {
1027 case <-ctx.Done():
1028 return trailer()
1029 case _, ok := <-watcher.Events:
1030 if !ok {
1031 return trailer()
1032 }
1033 case werr, ok := <-watcher.Errors:
1034 if !ok {
1035 return trailer()
1036 }
1037 fmt.Fprintf(os.Stderr, "valley flow watch: watcher error: %v\n", werr)
1038 case <-ticker.C:
1039 // Catches a missed notification, and a session or events file
1040 // removed under us. Offsets into a file that was replaced say
1041 // nothing about the new one, so that ends the watch too.
1042 if err := checkSessionDir(path); err != nil {
1043 return err
1044 }
1045 if inode != 0 && statInode(path) != inode {
1046 return fmt.Errorf("%s was replaced or removed while this watch read it: its offsets don't apply to the new file", path)
1047 }
1048 }
1049 }
1050}
1051
1052// nextWatchCommand is the valley flow watch --once command line that reads on from
1053// cursor with the given flags.
1054func nextWatchCommand(sessionID string, filterIn, filterOut, runs []string, asJSON bool, cursor int64) string {
1055 args := []string{"valley", "flow", "watch", "--once", "--after", strconv.FormatInt(cursor, 10)}
1056 if sessionID != "" {
1057 args = append(args, "--session-id", shellWord(sessionID))
1058 }
1059 for _, flag := range []struct {
1060 name string
1061 values []string
1062 }{{"--filter", filterIn}, {"--filter-out", filterOut}, {"--run", runs}} {
1063 for _, v := range flag.values {
1064 args = append(args, flag.name, shellWord(v))
1065 }
1066 }
1067 if asJSON {
1068 args = append(args, "--json")
1069 }
1070 return strings.Join(args, " ")
1071}
1072
1073// nextQueueWatchCommand is the valley flow watch --queue command line that
1074// waits for the queue to differ from the one digest names; an empty
1075// queue's needs no --seen.
1076func nextQueueWatchCommand(sessionID, digest string) string {
1077 args := []string{"valley", "flow", "watch", "--queue"}
1078 if digest != "" && digest != (queue{}).digest() {
1079 args = append(args, "--seen", shellWord(digest))
1080 }
1081 if sessionID != "" {
1082 args = append(args, "--session-id", shellWord(sessionID))
1083 }
1084 return strings.Join(args, " ")
1085}
1086
1087// queueSource is what valley flow watch --queue reads: the queue,
1088// provisional when a run record didn't parse, and the files whose writes
1089// may change it.
1090type queueSource struct {
1091 compute func(context.Context) (q queue, provisional bool, err error)
1092 events string // the session's event log
1093 runs string // the directory of the session's run records
1094}
1095
1096// queueCoalesce is how long the watch lets a burst of writes run on
1097// before it reads the queue: finalize emits a run's events and then saves
1098// its record, and one read after both does for the two. A write after it
1099// wakes the watch again, so the window saves reads and loses nothing.
1100const queueCoalesce = 200 * time.Millisecond
1101
1102// watchQueue is valley flow watch --queue. It reads the queue, and returns
1103// it once its digest differs from seen (an empty queue's when seen is "")
1104// and no run record read half written; otherwise it waits for a write to
1105// the event log or the run records and reads it again. It keeps nothing
1106// between reads: the queue is all there is to compare. Cancelling ctx ends
1107// the wait with just the next: line, which waits from seen again.
1108func watchQueue(ctx context.Context, src queueSource, seen string, next func(string) string, out io.Writer) error {
1109 want := seen
1110 if want == "" {
1111 want = queue{}.digest()
1112 }
1113 if err := os.MkdirAll(src.runs, 0o755); err != nil {
1114 return fmt.Errorf("creating %s: %w", src.runs, err)
1115 }
1116 // Watch before the first read, so a write during it wakes the watch.
1117 watcher, err := fsnotify.NewWatcher()
1118 if err != nil {
1119 return fmt.Errorf("creating file watcher: %w", err)
1120 }
1121 defer watcher.Close()
1122 for _, dir := range []string{filepath.Dir(src.events), src.runs} {
1123 if err := watcher.Add(dir); err != nil {
1124 return fmt.Errorf("watching %s: %w", dir, err)
1125 }
1126 }
1127 for ctx.Err() == nil {
1128 q, provisional, err := src.compute(ctx)
1129 if ctx.Err() != nil {
1130 break
1131 }
1132 if err != nil {
1133 return err
1134 }
1135 if d := q.digest(); d != want && !provisional {
1136 q.write(out, time.Now())
1137 _, err := fmt.Fprintln(out, "next: "+next(d))
1138 return err
1139 }
1140 if err := awaitQueueWrite(ctx, watcher, src); err != nil {
1141 return err
1142 }
1143 }
1144 _, err = fmt.Fprintln(out, "next: "+next(seen))
1145 return err
1146}
1147
1148// awaitQueueWrite waits for a write to src's event log or run records,
1149// then for the burst it starts to pass (queueCoalesce). A watcher that lost
1150// events counts as a write.
1151func awaitQueueWrite(ctx context.Context, w *fsnotify.Watcher, src queueSource) error {
1152 var settled <-chan time.Time
1153 wrote := func() {
1154 if settled == nil {
1155 settled = time.After(queueCoalesce)
1156 }
1157 }
1158 for {
1159 select {
1160 case <-ctx.Done():
1161 return nil
1162 case <-settled:
1163 return nil
1164 case ev, ok := <-w.Events:
1165 if !ok {
1166 return fmt.Errorf("the file watcher stopped")
1167 }
1168 name := filepath.Clean(ev.Name)
1169 if ev.Op != fsnotify.Chmod && (name == filepath.Clean(src.events) || filepath.Dir(name) == filepath.Clean(src.runs)) {
1170 wrote()
1171 }
1172 case werr, ok := <-w.Errors:
1173 if !ok {
1174 return fmt.Errorf("the file watcher stopped")
1175 }
1176 fmt.Fprintf(os.Stderr, "valley flow watch: watcher error: %v\n", werr)
1177 wrote()
1178 }
1179 }
1180}
1181
1182// statInode returns the inode for path, or 0 if unavailable.
1183// Used to detect log rotation when fsnotify drops a notification.
1184func statInode(path string) uint64 {
1185 info, err := os.Stat(path)
1186 if err != nil {
1187 return 0
1188 }
1189 sys, ok := info.Sys().(*syscall.Stat_t)
1190 if !ok {
1191 return 0
1192 }
1193 return sys.Ino
1194}
1195
1196func printKnownEventTypes(out io.Writer) {
1197 // Group live first, then reserved, alphabetically within each group.
1198 live := make([]eventTypeInfo, 0)
1199 reserved := make([]eventTypeInfo, 0)
1200 for _, t := range knownEventTypes {
1201 if t.Status == "reserved" {
1202 reserved = append(reserved, t)
1203 } else {
1204 live = append(live, t)
1205 }
1206 }
1207 sort.Slice(live, func(i, j int) bool { return live[i].Type < live[j].Type })
1208 sort.Slice(reserved, func(i, j int) bool { return reserved[i].Type < reserved[j].Type })
1209
1210 fmt.Fprintln(out, "Live event types (currently emitted by flow):")
1211 for _, t := range live {
1212 fmt.Fprintf(out, " %-24s %s\n", t.Type, t.Desc)
1213 }
1214 fmt.Fprintln(out)
1215 fmt.Fprintln(out, "Reserved event types (not currently emitted; included in default filter for forward-compat):")
1216 for _, t := range reserved {
1217 fmt.Fprintf(out, " %-24s %s\n", t.Type, t.Desc)
1218 }
1219 fmt.Fprintln(out)
1220 fmt.Fprintln(out, "Default filter:")
1221 def := append([]string{}, defaultWatchFilter...)
1222 sort.Strings(def)
1223 fmt.Fprintln(out, " "+strings.Join(def, ", "))
1224}
1225
1226// checkNames joins the check names an event's failed field carries, as
1227// JSON decodes them.
1228func checkNames(v interface{}) string {
1229 list, _ := v.([]interface{})
1230 var names []string
1231 for _, n := range list {
1232 if s, ok := n.(string); ok && s != "" {
1233 names = append(names, s)
1234 }
1235 }
1236 return strings.Join(names, ", ")
1237}