| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "io" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | "time" |
| 11 | |
| 12 | "the-valley/flow/internal/consult" |
| 13 | "the-valley/flow/internal/jobs" |
| 14 | "the-valley/flow/internal/review" |
| 15 | "the-valley/flow/internal/run" |
| 16 | "github.com/spf13/cobra" |
| 17 | ) |
| 18 | |
| 19 | // recentJobs is how long a finished job stays in klaus status, klaus jobs |
| 20 | // and the dashboard after it ends. |
| 21 | const recentJobs = 3 * time.Hour |
| 22 | |
| 23 | func newJobsCmd() *cobra.Command { |
| 24 | var rawKinds []string |
| 25 | c := &cobra.Command{ |
| 26 | Use: "jobs", |
| 27 | Short: "List running and recent consults, reviews and prose passes", |
| 28 | Long: `Lists the read-only background jobs of the current flow session (or the |
| 29 | most recent session outside a pane): each valley flow consult backend call, one per |
| 30 | member of a --panel, each valley flow review, and each prose pass of a worker's |
| 31 | _pre-review, with the run's ID under THREAD/PR. Running jobs come first, then the |
| 32 | jobs that finished in the last 3 hours, newest first; --all lists every |
| 33 | record kept, and --kind filters by kind (consult, review or prose). |
| 34 | |
| 35 | STATUS is running, succeeded, failed, timed out or interrupted, as the job |
| 36 | recorded it, or died: the job's flow process is gone (it was killed with |
| 37 | SIGKILL, or the machine restarted) without recording an end. |
| 38 | |
| 39 | Records live in ~/.klaus/sessions/<session-id>/jobs/<id>.json. A consult's |
| 40 | ID is the run_id of its consult:started and consult:completed events, and a |
| 41 | review's that of its review:started and review:completed events. Records of |
| 42 | jobs that finished more than 7 days ago are removed when a new job starts. |
| 43 | |
| 44 | Use 'valley flow jobs show <id>' to read a job's answer.`, |
| 45 | Args: cobra.NoArgs, |
| 46 | RunE: func(cmd *cobra.Command, args []string) error { |
| 47 | kinds, err := parseJobKinds(rawKinds) |
| 48 | if err != nil { |
| 49 | return err |
| 50 | } |
| 51 | store, err := sessionJobStore() |
| 52 | if err != nil { |
| 53 | return err |
| 54 | } |
| 55 | list, err := store.List() |
| 56 | if err != nil { |
| 57 | return err |
| 58 | } |
| 59 | now := time.Now() |
| 60 | if all, _ := cmd.Flags().GetBool("all"); !all { |
| 61 | list = jobs.Recent(list, now, recentJobs) |
| 62 | } |
| 63 | if len(kinds) > 0 { |
| 64 | var filtered []*jobs.Job |
| 65 | for _, j := range list { |
| 66 | if kinds[j.Kind] { |
| 67 | filtered = append(filtered, j) |
| 68 | } |
| 69 | } |
| 70 | list = filtered |
| 71 | } |
| 72 | if len(list) == 0 { |
| 73 | fmt.Fprintln(cmd.OutOrStdout(), "No jobs.") |
| 74 | return nil |
| 75 | } |
| 76 | printJobsTable(cmd.OutOrStdout(), list, now) |
| 77 | return nil |
| 78 | }, |
| 79 | } |
| 80 | c.Flags().Bool("all", false, "List every job record kept, not only running and recent ones") |
| 81 | c.Flags().StringArrayVar(&rawKinds, "kind", nil, "Only jobs of this kind: consult, review or prose (repeatable or comma-separated)") |
| 82 | c.AddCommand(newJobsShowCmd()) |
| 83 | return c |
| 84 | } |
| 85 | |
| 86 | func newJobsShowCmd() *cobra.Command { |
| 87 | c := &cobra.Command{ |
| 88 | Use: "show <job-id>", |
| 89 | Short: "Print a job's record and its answer", |
| 90 | Long: `Prints a job's record, then its answer: for a threaded |
| 91 | consult, its turn's answer from the thread's log; for a one-shot consult, |
| 92 | the answer saved beside the record; for a review, its verdict, findings and |
| 93 | summary; for a prose pass, its rewrites, fact-check failures and, once the |
| 94 | run finalized, which were applied. A job that didn't succeed shows its error and where its raw output |
| 95 | was saved. |
| 96 | |
| 97 | <job-id> is a job's ID, the ID of a panel (every member is shown), or a |
| 98 | unique ending of a job's ID, such as the four characters the dashboard |
| 99 | shows. --answer prints only the answer, and fails when there is none.`, |
| 100 | Args: cobra.ExactArgs(1), |
| 101 | RunE: func(cmd *cobra.Command, args []string) error { |
| 102 | store, err := sessionJobStore() |
| 103 | if err != nil { |
| 104 | return err |
| 105 | } |
| 106 | found, err := store.Find(args[0]) |
| 107 | if err != nil { |
| 108 | return err |
| 109 | } |
| 110 | cmd.SilenceUsage = true |
| 111 | out := cmd.OutOrStdout() |
| 112 | if only, _ := cmd.Flags().GetBool("answer"); only { |
| 113 | for _, j := range found { |
| 114 | answer, ok, err := jobAnswer(store, j) |
| 115 | if err != nil { |
| 116 | return err |
| 117 | } |
| 118 | if !ok { |
| 119 | return fmt.Errorf("job %s has no answer: %s", j.ID, jobStatusText(j)) |
| 120 | } |
| 121 | fmt.Fprint(out, answer) |
| 122 | } |
| 123 | return nil |
| 124 | } |
| 125 | for i, j := range found { |
| 126 | if i > 0 { |
| 127 | fmt.Fprintln(out) |
| 128 | } |
| 129 | if err := showJob(out, store, j, time.Now()); err != nil { |
| 130 | return err |
| 131 | } |
| 132 | } |
| 133 | return nil |
| 134 | }, |
| 135 | } |
| 136 | c.Flags().Bool("answer", false, "Print only the answer") |
| 137 | return c |
| 138 | } |
| 139 | |
| 140 | func init() { rootCmd.AddCommand(newJobsCmd()) } |
| 141 | |
| 142 | // sessionJobStore is the job store of the current session, or the most |
| 143 | // recent one outside a pane. |
| 144 | func sessionJobStore() (jobs.Store, error) { |
| 145 | store, err := sessionStore() |
| 146 | if err != nil { |
| 147 | return jobs.Store{}, err |
| 148 | } |
| 149 | return jobs.NewStore(store.(*run.HomeDirStore).BaseDir()), nil |
| 150 | } |
| 151 | |
| 152 | // jobOutcome classifies how a consult or review call ended, for its |
| 153 | // completion event and its record: succeeded; interrupted when SIGINT or |
| 154 | // SIGTERM cancelled the command; timed out at its deadline, said as |
| 155 | // timeoutMsg; else failed, with the error's first line. |
| 156 | func jobOutcome(err error, interrupted, timedOut bool, timeoutMsg string) (jobs.Status, string) { |
| 157 | switch { |
| 158 | case err == nil: |
| 159 | return jobs.Succeeded, "" |
| 160 | case interrupted: |
| 161 | return jobs.Interrupted, "interrupted" |
| 162 | case timedOut: |
| 163 | return jobs.TimedOut, timeoutMsg |
| 164 | } |
| 165 | return jobs.Failed, errorLine(err) |
| 166 | } |
| 167 | |
| 168 | // errorLine is an error's first line, cut to 200 characters. |
| 169 | func errorLine(err error) string { |
| 170 | return truncateLine(strings.SplitN(err.Error(), "\n", 2)[0], 200) |
| 171 | } |
| 172 | |
| 173 | // warnJob reports a job record klaus couldn't write. It never fails the |
| 174 | // job: the record is for watching it, not part of it. |
| 175 | func warnJob(w io.Writer, j *jobs.Job, err error) { |
| 176 | if err != nil { |
| 177 | fmt.Fprintf(w, "warning: recording job %s: %v\n", j.ID, err) |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | // parseJobKinds validates --kind flag values (each repeatable or |
| 182 | // comma-separated) and returns them as a set. |
| 183 | func parseJobKinds(raw []string) (map[string]bool, error) { |
| 184 | if len(raw) == 0 { |
| 185 | return nil, nil |
| 186 | } |
| 187 | out := make(map[string]bool, len(raw)) |
| 188 | for _, item := range raw { |
| 189 | for _, part := range strings.Split(item, ",") { |
| 190 | k := strings.TrimSpace(part) |
| 191 | switch k { |
| 192 | case jobs.KindConsult, jobs.KindReview, jobs.KindProse: |
| 193 | out[k] = true |
| 194 | default: |
| 195 | return nil, fmt.Errorf("unknown job kind %q: want %s, %s or %s", k, jobs.KindConsult, jobs.KindReview, jobs.KindProse) |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | return out, nil |
| 200 | } |
| 201 | |
| 202 | // proseSummary counts finished prose passes and how many did not succeed. |
| 203 | type proseSummary struct { |
| 204 | total int |
| 205 | failed int |
| 206 | } |
| 207 | |
| 208 | func (p *proseSummary) add(j *jobs.Job) { |
| 209 | p.total++ |
| 210 | if j.Status != jobs.Succeeded { |
| 211 | p.failed++ |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | func (p proseSummary) String() string { |
| 216 | if p.total == 0 { |
| 217 | return "" |
| 218 | } |
| 219 | noun := "prose passes" |
| 220 | if p.total == 1 { |
| 221 | noun = "prose pass" |
| 222 | } |
| 223 | if p.failed > 0 { |
| 224 | return fmt.Sprintf("%d %s, %d failed", p.total, noun, p.failed) |
| 225 | } |
| 226 | return fmt.Sprintf("%d %s", p.total, noun) |
| 227 | } |
| 228 | |
| 229 | // partitionJobs splits js into the jobs listed as rows (consults, reviews, |
| 230 | // and running prose passes) and a count of finished prose passes. |
| 231 | func partitionJobs(js []*jobs.Job) (listed []*jobs.Job, prose proseSummary) { |
| 232 | for _, j := range js { |
| 233 | if j.Kind == jobs.KindProse && j.Finished() { |
| 234 | prose.add(j) |
| 235 | continue |
| 236 | } |
| 237 | listed = append(listed, j) |
| 238 | } |
| 239 | return listed, prose |
| 240 | } |
| 241 | |
| 242 | // printJobsTable prints jobs as klaus status and klaus jobs show them. |
| 243 | func printJobsTable(w io.Writer, list []*jobs.Job, now time.Time) { |
| 244 | const format = "%-30s %-7s %-20s %-24s %-11s %-7s %s\n" |
| 245 | fmt.Fprintf(w, format, "JOB ID", "KIND", "THREAD/PR", "BACKEND/MODEL", "STATUS", "TIME", "PROMPT") |
| 246 | fmt.Fprintf(w, format, "------", "----", "---------", "-------------", "------", "----", "------") |
| 247 | for _, j := range list { |
| 248 | fmt.Fprintf(w, format, j.ID, j.Kind, truncateLine(jobTarget(j), 20), truncateLine(jobBackendModel(j), 24), |
| 249 | j.Status, jobTime(j, now), truncateLine(j.Prompt, 40)) |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // jobTarget names what a job works on: a consult's thread, a review's PR, |
| 254 | // "panel" for a member of a panel, else "-". |
| 255 | func jobTarget(j *jobs.Job) string { |
| 256 | switch { |
| 257 | case j.Thread != "": |
| 258 | return j.Thread |
| 259 | case j.PR != "": |
| 260 | return j.PR |
| 261 | case j.Panel != "": |
| 262 | return "panel" |
| 263 | case j.Run != "": |
| 264 | return j.Run |
| 265 | } |
| 266 | return "-" |
| 267 | } |
| 268 | |
| 269 | // jobBackendModel is a job's backend and model, e.g. codex/gpt-5.5. |
| 270 | func jobBackendModel(j *jobs.Job) string { |
| 271 | return review.BackendModel(j.Backend, j.Model) |
| 272 | } |
| 273 | |
| 274 | // jobTime is how long a running job has run, or how long a finished one |
| 275 | // took; "-" for one that died, whose end isn't known. |
| 276 | func jobTime(j *jobs.Job, now time.Time) string { |
| 277 | switch { |
| 278 | case j.Status == jobs.Running: |
| 279 | return formatElapsed(now.Sub(j.StartedAt)) |
| 280 | case j.FinishedAt != nil: |
| 281 | return formatElapsed(j.FinishedAt.Sub(j.StartedAt)) |
| 282 | } |
| 283 | return "-" |
| 284 | } |
| 285 | |
| 286 | // formatElapsed renders a job's time compactly: "45s", "12m", "1h05m". |
| 287 | func formatElapsed(d time.Duration) string { |
| 288 | switch { |
| 289 | case d < time.Minute: |
| 290 | return fmt.Sprintf("%ds", max(int(d.Seconds()), 0)) |
| 291 | case d < time.Hour: |
| 292 | return fmt.Sprintf("%dm", int(d.Minutes())) |
| 293 | } |
| 294 | return fmt.Sprintf("%dh%02dm", int(d.Hours()), int(d.Minutes())%60) |
| 295 | } |
| 296 | |
| 297 | // jobStatusText is a job's status with its error, e.g. |
| 298 | // "failed: consult codex: exit status 7". |
| 299 | func jobStatusText(j *jobs.Job) string { |
| 300 | switch { |
| 301 | case j.Status == jobs.Died: |
| 302 | return fmt.Sprintf("died: process %d ended without recording how the job ended", j.PID) |
| 303 | case j.Error != "" && j.Error != string(j.Status): |
| 304 | return string(j.Status) + ": " + j.Error |
| 305 | } |
| 306 | return string(j.Status) |
| 307 | } |
| 308 | |
| 309 | // showJob prints a job's record and then its answer, for klaus jobs show |
| 310 | // and the dashboard. |
| 311 | func showJob(w io.Writer, store jobs.Store, j *jobs.Job, now time.Time) error { |
| 312 | var fields [][2]string |
| 313 | add := func(k, v string) { |
| 314 | if v != "" { |
| 315 | fields = append(fields, [2]string{k, v}) |
| 316 | } |
| 317 | } |
| 318 | add("job", j.ID) |
| 319 | kind := j.Kind |
| 320 | if j.Panel != "" { |
| 321 | kind += ", panel " + j.Panel |
| 322 | } |
| 323 | add("kind", kind) |
| 324 | add("status", jobStatusText(j)) |
| 325 | backend := jobBackendModel(j) |
| 326 | if j.Effort != "" { |
| 327 | backend += ", effort " + j.Effort |
| 328 | } |
| 329 | if j.Role != "" { |
| 330 | backend += ", role " + truncateLine(j.Role, 60) |
| 331 | } |
| 332 | add("backend", backend) |
| 333 | if j.Thread != "" { |
| 334 | thread := j.Thread |
| 335 | if j.Turn > 0 { |
| 336 | thread += fmt.Sprintf(", turn %d", j.Turn) |
| 337 | } |
| 338 | add("thread", thread) |
| 339 | } |
| 340 | add("pr", j.PR) |
| 341 | if j.PR == "" { |
| 342 | add("repo", j.Repo) |
| 343 | } |
| 344 | add("commit", j.Commit) |
| 345 | add("dir", j.Dir) |
| 346 | add("started", j.StartedAt.Local().Format("2006-01-02 15:04:05")) |
| 347 | if j.FinishedAt != nil { |
| 348 | add("finished", fmt.Sprintf("%s, after %s", j.FinishedAt.Local().Format("2006-01-02 15:04:05"), jobTime(j, now))) |
| 349 | } else if j.Status == jobs.Running { |
| 350 | add("running", jobTime(j, now)) |
| 351 | } |
| 352 | add("pid", fmt.Sprint(j.PID)) |
| 353 | add("run", j.Run) |
| 354 | add("prompt", j.Prompt) |
| 355 | if j.Review != nil { |
| 356 | add("posted", j.Review.ReviewURL) |
| 357 | } |
| 358 | add("answer", j.AnswerFile) |
| 359 | add("raw output", j.RawOutput) |
| 360 | for _, f := range fields { |
| 361 | fmt.Fprintf(w, "%-11s %s\n", f[0]+":", f[1]) |
| 362 | } |
| 363 | |
| 364 | answer, ok, err := jobAnswer(store, j) |
| 365 | switch { |
| 366 | case err != nil: |
| 367 | fmt.Fprintf(w, "\n(answer unavailable: %v)\n", err) |
| 368 | case ok: |
| 369 | fmt.Fprintln(w) |
| 370 | fmt.Fprint(w, answer) |
| 371 | if !strings.HasSuffix(answer, "\n") { |
| 372 | fmt.Fprintln(w) |
| 373 | } |
| 374 | case j.Status == jobs.Running: |
| 375 | fmt.Fprintln(w, "\n(still running)") |
| 376 | } |
| 377 | return nil |
| 378 | } |
| 379 | |
| 380 | // jobAnswer is a job's answer: a succeeded consult's, from its thread's log |
| 381 | // or the file beside its record, or a review's findings. ok is false when |
| 382 | // the job has none to show. |
| 383 | func jobAnswer(store jobs.Store, j *jobs.Job) (answer string, ok bool, err error) { |
| 384 | if j.Kind == jobs.KindProse { |
| 385 | if j.Prose == nil { |
| 386 | return "", false, nil |
| 387 | } |
| 388 | var b bytes.Buffer |
| 389 | printProse(&b, j.Prose) |
| 390 | return b.String(), true, nil |
| 391 | } |
| 392 | if j.Kind == jobs.KindReview { |
| 393 | if j.Review == nil { |
| 394 | return "", false, nil |
| 395 | } |
| 396 | var b bytes.Buffer |
| 397 | printPRReview(&b, &review.ReviewResult{Verdict: j.Review.Verdict, Summary: j.Review.Summary, Findings: j.Review.Findings}) |
| 398 | return strings.TrimPrefix(b.String(), "\n"), true, nil |
| 399 | } |
| 400 | if j.Status != jobs.Succeeded { |
| 401 | return "", false, nil |
| 402 | } |
| 403 | switch { |
| 404 | case j.AnswerFile != "": |
| 405 | data, err := os.ReadFile(j.AnswerFile) |
| 406 | if err != nil { |
| 407 | return "", false, err |
| 408 | } |
| 409 | return string(data), true, nil |
| 410 | case j.Thread != "" && j.Turn > 0: |
| 411 | // The job store sits beside consults/ in the session directory. |
| 412 | turn, err := consult.NewStore(filepath.Dir(store.Dir)).Turn(j.Thread, j.Turn) |
| 413 | if err != nil { |
| 414 | return "", false, err |
| 415 | } |
| 416 | return turn.Answer, true, nil |
| 417 | } |
| 418 | return "", false, nil |
| 419 | } |