package cmd import ( "context" "fmt" "io" "log" "os" "os/signal" "syscall" "github.com/david/knox/internal/db" "github.com/david/knox/internal/watch" "github.com/spf13/cobra" ) func NewWatchCmd(kdb *db.KnoxDB) *cobra.Command { var dirs []string var quiet bool cmd := &cobra.Command{ Use: "watch", Short: "Watch directories for new session data and ingest into index", Run: func(cmd *cobra.Command, args []string) { if len(dirs) == 0 { dirs = defaultWatchDirs() } if quiet { log.SetOutput(io.Discard) } log.Printf("[knox] starting watcher, scanning %d directories", len(dirs)) w := watch.New(kdb, dirs) // A container sends SIGTERM on stop; shut down the HTTP servers so // restarts are clean instead of dropping the listeners abruptly. ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() go func() { <-ctx.Done() w.Shutdown() }() if err := w.Start(); err != nil { // Not log.Fatalf: --quiet redirects the logger to io.Discard, // so a fatal exit must reach the user on stderr directly. fmt.Fprintf(os.Stderr, "watcher error: %v\n", err) os.Exit(1) } }, } cmd.Flags().StringSliceVarP(&dirs, "dir", "d", nil, "Directories to watch (default: opencode storage/log + skills)") cmd.Flags().BoolVarP(&quiet, "quiet", "q", false, "Suppress per-entry log output") return cmd } func defaultWatchDirs() []string { home, _ := getHomeDir() candidates := []string{ home + "/.local/share/opencode/log", home + "/.skills", } // A headless node has none of these; watch nothing rather than logging a // failed watch for every missing path. dirs := make([]string, 0, len(candidates)) for _, d := range candidates { if info, err := os.Stat(d); err == nil && info.IsDir() { dirs = append(dirs, d) } } return dirs }