-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogs.go
More file actions
513 lines (459 loc) · 15.3 KB
/
Copy pathlogs.go
File metadata and controls
513 lines (459 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
package cli
import (
"database/sql"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"github.com/dvflw/mantle/internal/auth"
"github.com/dvflw/mantle/internal/config"
"github.com/dvflw/mantle/internal/db"
"github.com/spf13/cobra"
)
// subStep represents a sub-step (tool call) within a step execution.
type subStep struct {
StepName string `json:"step_name"`
Status string `json:"status"`
Started *time.Time `json:"started_at,omitempty"`
Completed *time.Time `json:"completed_at,omitempty"`
}
// stepInfo represents a top-level step execution.
type stepInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
Error string `json:"error,omitempty"`
StartedAt *time.Time `json:"started_at,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
SubSteps []subStep `json:"sub_steps,omitempty"`
}
func newLogsCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "logs [execution-id]",
Short: "View execution logs",
Long: `Shows step-by-step execution history with timing, status, and outputs.
When called with an execution ID, shows detailed step information.
When called without arguments, lists recent executions with optional filters.`,
Example: ` mantle logs abc123
mantle logs --workflow my-workflow --status failed
mantle logs --since 24h --limit 10
mantle logs abc123 --output json`,
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 1 {
return showExecutionDetail(cmd, args[0])
}
return listExecutions(cmd)
},
}
cmd.Flags().String("workflow", "", "filter by workflow name")
cmd.Flags().String("status", "", "filter by status (pending, running, completed, failed, cancelled)")
cmd.Flags().String("since", "", "filter by time (e.g., 1h, 24h, 7d)")
cmd.Flags().Int("limit", 20, "max results to return")
cmd.Flags().Bool("shallow", false, "suppress child workflow details")
return cmd
}
// showExecutionDetail displays detailed step info for a single execution (original behavior).
func showExecutionDetail(cmd *cobra.Command, execID string) error {
cfg := config.FromContext(cmd.Context())
if cfg == nil {
return fmt.Errorf("config not loaded")
}
database, err := db.Open(cfg.Database)
if err != nil {
return fmt.Errorf("failed to connect to database: %w", err)
}
defer database.Close()
// Fetch execution info.
var workflowName string
var version int
var status string
var startedAt, completedAt *time.Time
teamID := auth.TeamIDFromContext(cmd.Context())
err = database.QueryRowContext(cmd.Context(),
`SELECT workflow_name, workflow_version, status, started_at, completed_at
FROM workflow_executions WHERE id = $1 AND team_id = $2`, execID, teamID,
).Scan(&workflowName, &version, &status, &startedAt, &completedAt)
if err != nil {
return fmt.Errorf("execution %q not found", execID)
}
// Fetch top-level step executions.
rows, err := database.QueryContext(cmd.Context(),
`SELECT id, step_name, status, error, started_at, completed_at
FROM step_executions WHERE execution_id = $1 AND parent_step_id IS NULL
ORDER BY created_at ASC`, execID,
)
if err != nil {
return fmt.Errorf("querying steps: %w", err)
}
defer rows.Close()
// Fetch sub-steps grouped by parent.
subStepsByParent := make(map[string][]subStep)
subRows, err := database.QueryContext(cmd.Context(),
`SELECT parent_step_id, step_name, status, started_at, completed_at
FROM step_executions WHERE execution_id = $1 AND parent_step_id IS NOT NULL
ORDER BY created_at ASC`, execID,
)
if err == nil {
defer subRows.Close()
for subRows.Next() {
var parentID, sName, sStatus string
var sStarted, sCompleted *time.Time
if err := subRows.Scan(&parentID, &sName, &sStatus, &sStarted, &sCompleted); err == nil {
subStepsByParent[parentID] = append(subStepsByParent[parentID], subStep{sName, sStatus, sStarted, sCompleted})
}
}
}
// Collect step data.
var stepsData []stepInfo
for rows.Next() {
var stepID, stepName, stepStatus string
var stepError *string
var stepStarted, stepCompleted *time.Time
if err := rows.Scan(&stepID, &stepName, &stepStatus, &stepError, &stepStarted, &stepCompleted); err != nil {
return fmt.Errorf("scanning step: %w", err)
}
si := stepInfo{
ID: stepID,
Name: stepName,
Status: stepStatus,
StartedAt: stepStarted,
CompletedAt: stepCompleted,
}
if stepError != nil && *stepError != "" {
si.Error = *stepError
}
if subs, ok := subStepsByParent[stepID]; ok {
si.SubSteps = subs
}
stepsData = append(stepsData, si)
}
if err := rows.Err(); err != nil {
return fmt.Errorf("iterating steps: %w", err)
}
// JSON output mode.
outputFormat, _ := cmd.Flags().GetString("output")
if outputFormat == "json" {
detail := map[string]any{
"execution_id": execID,
"workflow": workflowName,
"version": version,
"status": status,
"started_at": startedAt,
"completed_at": completedAt,
"steps": stepsData,
}
return json.NewEncoder(cmd.OutOrStdout()).Encode(detail)
}
// Text output.
fmt.Fprintf(cmd.OutOrStdout(), "Execution: %s\n", execID)
fmt.Fprintf(cmd.OutOrStdout(), "Workflow: %s (version %d)\n", workflowName, version)
fmt.Fprintf(cmd.OutOrStdout(), "Status: %s\n", status)
if startedAt != nil {
fmt.Fprintf(cmd.OutOrStdout(), "Started: %s\n", startedAt.Format(time.RFC3339))
}
if completedAt != nil {
fmt.Fprintf(cmd.OutOrStdout(), "Completed: %s\n", completedAt.Format(time.RFC3339))
if startedAt != nil {
fmt.Fprintf(cmd.OutOrStdout(), "Duration: %s\n", completedAt.Sub(*startedAt).Round(time.Millisecond))
}
}
fmt.Fprintln(cmd.OutOrStdout())
shallow, _ := cmd.Flags().GetBool("shallow")
fmt.Fprintln(cmd.OutOrStdout(), "Steps:")
printSteps(cmd, database, execID, teamID, stepsData, shallow, " ")
return nil
}
// printSteps renders step details, optionally recursing into child workflow executions.
func printSteps(cmd *cobra.Command, database *sql.DB, execID, teamID string, stepsData []stepInfo, shallow bool, indent string) {
for _, si := range stepsData {
icon := statusIcon(si.Status)
duration := ""
if si.StartedAt != nil && si.CompletedAt != nil {
duration = fmt.Sprintf(" %s", si.CompletedAt.Sub(*si.StartedAt).Round(time.Millisecond))
}
fmt.Fprintf(cmd.OutOrStdout(), "%s%s %-20s %s%s\n", indent, icon, si.Name, si.Status, duration)
if si.Error != "" {
fmt.Fprintf(cmd.OutOrStdout(), "%s error: %s\n", indent, si.Error)
}
// Render sub-steps (tool calls) as indented tree.
if len(si.SubSteps) > 0 {
// Group by round (last segment of step name: parent/tool/name/round).
rounds := make(map[string][]subStep)
var roundOrder []string
for _, s := range si.SubSteps {
parts := strings.Split(s.StepName, "/")
round := "0"
if len(parts) >= 4 {
round = parts[len(parts)-1]
}
if _, seen := rounds[round]; !seen {
roundOrder = append(roundOrder, round)
}
rounds[round] = append(rounds[round], s)
}
for ri, round := range roundOrder {
isLastRound := ri == len(roundOrder)-1
connector := "├─"
if isLastRound {
connector = "└─"
}
fmt.Fprintf(cmd.OutOrStdout(), "%s %s round %s\n", indent, connector, round)
for si, s := range rounds[round] {
isLast := si == len(rounds[round])-1
prefix := "│ "
if isLastRound {
prefix = " "
}
subConn := "├─"
if isLast {
subConn = "└─"
}
toolName := s.StepName
parts := strings.Split(s.StepName, "/")
if len(parts) >= 3 {
toolName = parts[2]
}
subDur := ""
if s.Started != nil && s.Completed != nil {
subDur = fmt.Sprintf(" %s", s.Completed.Sub(*s.Started).Round(time.Millisecond))
}
fmt.Fprintf(cmd.OutOrStdout(), "%s %s %s %-16s %s%s\n", indent, prefix, subConn, toolName, s.Status, subDur)
}
}
}
// Show child workflow execution details if not in shallow mode.
if !shallow {
printChildExecution(cmd, database, execID, si.Name, teamID, indent+" ")
}
}
}
// printChildExecution queries for a child workflow execution spawned by a given step
// and recursively renders its steps.
func printChildExecution(cmd *cobra.Command, database *sql.DB, parentExecID, parentStepName, teamID, indent string) {
rows, err := database.QueryContext(cmd.Context(),
`SELECT id, workflow_name, status FROM workflow_executions
WHERE parent_execution_id = $1 AND parent_step_name = $2 AND team_id = $3`,
parentExecID, parentStepName, teamID,
)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var childID, childWorkflow, childStatus string
if err := rows.Scan(&childID, &childWorkflow, &childStatus); err != nil {
continue
}
fmt.Fprintf(cmd.OutOrStdout(), "%s↳ child: %s (%s) [%s]\n", indent, childWorkflow, childID, childStatus)
// Fetch child's steps.
childSteps := fetchStepsForExecution(cmd, database, childID)
if len(childSteps) > 0 {
printSteps(cmd, database, childID, teamID, childSteps, false, indent+" ")
}
}
}
// fetchStepsForExecution retrieves step data for a given execution ID.
func fetchStepsForExecution(cmd *cobra.Command, database *sql.DB, execID string) []stepInfo {
stepRows, err := database.QueryContext(cmd.Context(),
`SELECT id, step_name, status, error, started_at, completed_at
FROM step_executions WHERE execution_id = $1 AND parent_step_id IS NULL
ORDER BY created_at ASC`, execID,
)
if err != nil {
return nil
}
defer stepRows.Close()
// Fetch sub-steps for the child execution.
subStepsByParent := make(map[string][]subStep)
subRows, err := database.QueryContext(cmd.Context(),
`SELECT parent_step_id, step_name, status, started_at, completed_at
FROM step_executions WHERE execution_id = $1 AND parent_step_id IS NOT NULL
ORDER BY created_at ASC`, execID,
)
if err == nil {
defer subRows.Close()
for subRows.Next() {
var parentID, sName, sStatus string
var sStarted, sCompleted *time.Time
if err := subRows.Scan(&parentID, &sName, &sStatus, &sStarted, &sCompleted); err == nil {
subStepsByParent[parentID] = append(subStepsByParent[parentID], subStep{sName, sStatus, sStarted, sCompleted})
}
}
}
var steps []stepInfo
for stepRows.Next() {
var stepID, stepName, stepStatus string
var stepError *string
var stepStarted, stepCompleted *time.Time
if err := stepRows.Scan(&stepID, &stepName, &stepStatus, &stepError, &stepStarted, &stepCompleted); err != nil {
continue
}
si := stepInfo{
ID: stepID,
Name: stepName,
Status: stepStatus,
StartedAt: stepStarted,
CompletedAt: stepCompleted,
}
if stepError != nil && *stepError != "" {
si.Error = *stepError
}
if subs, ok := subStepsByParent[stepID]; ok {
si.SubSteps = subs
}
steps = append(steps, si)
}
return steps
}
// listExecutions lists recent executions with optional filters.
func listExecutions(cmd *cobra.Command) error {
cfg := config.FromContext(cmd.Context())
if cfg == nil {
return fmt.Errorf("config not loaded")
}
database, err := db.Open(cfg.Database)
if err != nil {
return fmt.Errorf("failed to connect to database: %w", err)
}
defer database.Close()
workflow, _ := cmd.Flags().GetString("workflow")
status, _ := cmd.Flags().GetString("status")
since, _ := cmd.Flags().GetString("since")
limit, _ := cmd.Flags().GetInt("limit")
if limit <= 0 {
limit = 20
}
// Validate status if provided.
if status != "" {
validStatuses := map[string]bool{
"pending": true, "running": true, "completed": true,
"failed": true, "cancelled": true,
}
if !validStatuses[strings.ToLower(status)] {
return fmt.Errorf("invalid status %q: must be one of pending, running, completed, failed, cancelled", status)
}
status = strings.ToLower(status)
}
// Build query dynamically with parameterized filters.
teamID := auth.TeamIDFromContext(cmd.Context())
query := `SELECT id, workflow_name, workflow_version, status, started_at, completed_at
FROM workflow_executions WHERE team_id = $1`
params := []any{teamID}
paramIdx := 2
if workflow != "" {
query += " AND workflow_name = $" + strconv.Itoa(paramIdx)
params = append(params, workflow)
paramIdx++
}
if status != "" {
query += " AND status = $" + strconv.Itoa(paramIdx)
params = append(params, status)
paramIdx++
}
if since != "" {
duration, err := parseDuration(since)
if err != nil {
return fmt.Errorf("invalid --since value %q: %w", since, err)
}
cutoff := time.Now().Add(-duration)
query += " AND started_at >= $" + strconv.Itoa(paramIdx)
params = append(params, cutoff)
paramIdx++
}
query += " ORDER BY started_at DESC NULLS LAST"
query += " LIMIT $" + strconv.Itoa(paramIdx)
params = append(params, limit)
rows, err := database.QueryContext(cmd.Context(), query, params...)
if err != nil {
return fmt.Errorf("querying executions: %w", err)
}
defer rows.Close()
type execRow struct {
ID string `json:"id"`
Workflow string `json:"workflow"`
Version int `json:"version"`
Status string `json:"status"`
StartedAt *time.Time `json:"started_at,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
}
var executions []execRow
for rows.Next() {
var r execRow
if err := rows.Scan(&r.ID, &r.Workflow, &r.Version, &r.Status, &r.StartedAt, &r.CompletedAt); err != nil {
return fmt.Errorf("scanning execution: %w", err)
}
executions = append(executions, r)
}
if err := rows.Err(); err != nil {
return fmt.Errorf("iterating executions: %w", err)
}
// JSON output mode.
outputFormat, _ := cmd.Flags().GetString("output")
if outputFormat == "json" {
return json.NewEncoder(cmd.OutOrStdout()).Encode(executions)
}
// Text output mode.
out := cmd.OutOrStdout()
fmt.Fprintf(out, "%-38s %-20s %7s %-10s %-20s %-20s\n",
"ID", "WORKFLOW", "VERSION", "STATUS", "STARTED", "COMPLETED")
fmt.Fprintln(out, strings.Repeat("-", 120))
for _, r := range executions {
started := "-"
if r.StartedAt != nil {
started = r.StartedAt.Format("2006-01-02 15:04:05")
}
completed := "-"
if r.CompletedAt != nil {
completed = r.CompletedAt.Format("2006-01-02 15:04:05")
}
fmt.Fprintf(out, "%-38s %-20s %7d %-10s %-20s %-20s\n",
r.ID, r.Workflow, r.Version, r.Status, started, completed)
}
if len(executions) == 0 {
fmt.Fprintln(out, "No executions found. Run a workflow with: mantle run <workflow>")
} else {
fmt.Fprintf(out, "\n%d execution(s) shown.\n", len(executions))
}
return nil
}
func statusIcon(status string) string {
switch status {
case "completed":
return "✓"
case "failed":
return "✗"
case "running":
return "▶"
case "skipped":
return "⊘"
case "cancelled":
return "■"
default:
return "○"
}
}
// parseDuration parses duration strings like "1h", "24h", "7d".
// Supports Go-standard durations plus "d" suffix for days.
func parseDuration(s string) (time.Duration, error) {
if strings.HasSuffix(s, "d") {
numStr := strings.TrimSuffix(s, "d")
days, err := strconv.Atoi(numStr)
if err != nil {
return 0, fmt.Errorf("invalid day count: %s", numStr)
}
if days <= 0 {
return 0, fmt.Errorf("duration must be positive")
}
return time.Duration(days) * 24 * time.Hour, nil
}
d, err := time.ParseDuration(s)
if err != nil {
return 0, err
}
if d <= 0 {
return 0, fmt.Errorf("duration must be positive")
}
return d, nil
}