package inbox import ( "fmt" "time" "ai-workflow-skill/packages/coord-core/protocol" "ai-workflow-skill/packages/coord-core/store" "github.com/spf13/cobra" ) type watchOptions struct { agent string statuses string timeoutSeconds int afterEventID int64 } func newWatchCmd(root *rootOptions) *cobra.Command { opts := &watchOptions{} cmd := &cobra.Command{ Use: "watch", Short: "Block until new matching activity appears", Long: helpLong( "Use watch to wait for new matching thread activity across the inbox.", "This is useful for operator-style inspection or lightweight agents that need to observe when new work, blocked work, or terminal results appear without polling manually.", "watch is broader than wait-reply: it watches many matching threads, while wait-reply is the worker-side primitive for one blocked thread.", ), Example: ` inbox --db .agents/coord.db watch --status pending,blocked inbox --db .agents/coord.db watch --agent worker-a --status pending --after-event 100 --timeout-seconds 300`, RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() agent := opts.agent if agent == "" { agent = root.agent } sqlDB, err := openInboxDB(ctx, root.dbPath) if err != nil { return err } defer sqlDB.Close() s := store.NewInboxStore(sqlDB) result, err := s.WatchThreads(ctx, store.WatchInput{ Agent: agent, Statuses: parseCSV(opts.statuses), AfterEventID: opts.afterEventID, StartFromNow: !cmd.Flags().Changed("after-event"), Timeout: time.Duration(opts.timeoutSeconds) * time.Second, }) if err != nil { return err } if !result.Woke { return protocol.NoMatchingWork("no matching work before watch timeout") } data := map[string]any{ "woke": result.Woke, "next_event_id": result.NextEventID, } if result.Thread != nil { data["thread"] = result.Thread } if result.Message != nil { data["message"] = result.Message } if result.Event != nil { data["event"] = result.Event } resp := protocol.Success{ OK: true, Command: "watch", Data: data, } if root.json { return protocol.WriteJSON(cmd.OutOrStdout(), resp) } _, err = fmt.Fprintf(cmd.OutOrStdout(), "watch woke on thread %s at event %d\n", result.Thread.ThreadID, result.NextEventID) return err }, } cmd.Flags().StringVar(&opts.agent, "agent", "", "Only wake for threads assigned to this agent") cmd.Flags().StringVar(&opts.statuses, "status", "pending,blocked,done,failed", "Comma-separated thread status filter") cmd.Flags().IntVar(&opts.timeoutSeconds, "timeout-seconds", 0, "Maximum time to wait; 0 means wait forever") cmd.Flags().Int64Var(&opts.afterEventID, "after-event", 0, "Resume after a known inbox event ID") return cmd }