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