diff --git a/cmd/skillshare/list_tui.go b/cmd/skillshare/list_tui.go index 755fb3ed0..4f1fb7963 100644 --- a/cmd/skillshare/list_tui.go +++ b/cmd/skillshare/list_tui.go @@ -36,8 +36,18 @@ var ( tuiTargetStyle = lipgloss.NewStyle(). Foreground(lipgloss.Color("6")) // cyan + + tuiFilterStyle = lipgloss.NewStyle(). + Foreground(lipgloss.Color("6")) // cyan — shared by list and log TUI ) +// applyTUIFilterStyle sets filter prompt, cursor, and input cursor to the shared style. +func applyTUIFilterStyle(l *list.Model) { + l.Styles.FilterPrompt = tuiFilterStyle + l.Styles.FilterCursor = tuiFilterStyle + l.FilterInput.Cursor.Style = tuiFilterStyle +} + // listTUIModel is the bubbletea model for the interactive skill list. type listTUIModel struct { list list.Model @@ -80,6 +90,7 @@ func newListTUIModel(skills []skillItem, totalCount int, modeLabel, sourcePath s Bold(true).Foreground(lipgloss.Color("6")) // cyan l.SetShowStatusBar(true) l.SetFilteringEnabled(true) + applyTUIFilterStyle(&l) l.SetShowHelp(false) // We render our own help // Custom status bar showing count diff --git a/cmd/skillshare/log.go b/cmd/skillshare/log.go index 1fa73400c..f6153e932 100644 --- a/cmd/skillshare/log.go +++ b/cmd/skillshare/log.go @@ -6,30 +6,14 @@ import ( "io" "os" "path/filepath" - "regexp" - "strconv" + "sort" "strings" - "time" - - "github.com/mattn/go-runewidth" - "github.com/pterm/pterm" "skillshare/internal/config" "skillshare/internal/oplog" "skillshare/internal/ui" ) -const ( - logDetailTruncateLen = 96 - logTimeWidth = 16 - logCmdWidth = 9 - logStatusWidth = 7 - logDurationWidth = 7 - logMinWrapWidth = 24 -) - -var logANSIRegex = regexp.MustCompile(`\x1b\[[0-9;]*m`) - func cmdLog(args []string) error { mode, rest, err := parseModeArgs(args) if err != nil { @@ -62,6 +46,7 @@ func runLog(args []string, configPath string) error { auditOnly := false clear := false jsonOutput := false + noTUI := false limit := 20 var filter oplog.Filter @@ -73,6 +58,8 @@ func runLog(args []string, configPath string) error { clear = true case "--json": jsonOutput = true + case "--no-tui": + noTUI = true case "--cmd": if i+1 < len(args) { i++ @@ -106,6 +93,11 @@ func runLog(args []string, configPath string) error { } } + modeLabel := "global" + if isProjectLogConfig(configPath) { + modeLabel = "project" + } + if clear { filename := oplog.OpsFile label := "Operations" @@ -120,6 +112,11 @@ func runLog(args []string, configPath string) error { return nil } + // TUI dispatch: interactive viewer when TTY and not explicitly disabled + if !noTUI && !jsonOutput && ui.IsTTY() { + return runLogTUIDispatch(configPath, auditOnly, limit, filter, modeLabel) + } + if auditOnly { return printLogSection(configPath, oplog.AuditFile, "Audit", limit, filter, jsonOutput) } @@ -143,22 +140,9 @@ func runLog(args []string, configPath string) error { } func printLogSection(configPath, filename, label string, limit int, f oplog.Filter, jsonOutput bool) error { - // When filtering, read all entries then filter, then apply limit - readLimit := limit - if !f.IsEmpty() { - readLimit = 0 // read all, filter will narrow down - } - - entries, err := oplog.Read(configPath, filename, readLimit) + entries, err := readAndFilter(configPath, filename, limit, f) if err != nil { - return fmt.Errorf("failed to read log: %w", err) - } - - if !f.IsEmpty() { - entries = oplog.FilterEntries(entries, f) - if limit > 0 && len(entries) > limit { - entries = entries[:limit] - } + return err } if jsonOutput { @@ -195,652 +179,6 @@ func printLogEntriesJSON(w io.Writer, entries []oplog.Entry) error { return nil } -func printLogEntries(entries []oplog.Entry) { - if ui.IsTTY() { - printLogEntriesTTYTwoLine(os.Stdout, entries, logTerminalWidth()) - return - } - - printLogEntriesNonTTY(os.Stdout, entries) -} - -func printLogEntriesTTYTwoLine(w io.Writer, entries []oplog.Entry, termWidth int) { - printLogTableHeaderTTY(w) - - for i, e := range entries { - if i > 0 { - fmt.Fprintln(w) - } - - ts := formatLogTimestamp(e.Timestamp) - cmd := padLogCell(strings.ToUpper(e.Command), logCmdWidth) - status := colorizeLogStatusCell(padLogCell(e.Status, logStatusWidth), e.Status) - dur := formatLogDuration(e.Duration) - durCell := padLogCell(dur, logDurationWidth) - - fmt.Fprintf(w, " %s%s%s | %s | %s | %s\n", - ui.Gray, - padLogCell(ts, logTimeWidth), - ui.Reset, - cmd, - status, - durCell, - ) - - printLogDetailMultiLine(w, e, termWidth) - } -} - -// logDetailPair represents a structured key-value for multi-line detail output. -type logDetailPair struct { - key string - value string - isList bool - listValues []string -} - -func printLogDetailMultiLine(w io.Writer, e oplog.Entry, termWidth int) { - pairs := formatLogDetailPairs(e) - - if e.Message != "" { - pairs = append(pairs, logDetailPair{key: "message", value: e.Message}) - } - - if len(pairs) == 0 { - return - } - - const indent = " " - const listIndent = " - " - wrapWidth := termWidth - logDisplayWidth(indent) - 20 // leave room for key - if wrapWidth < logMinWrapWidth { - wrapWidth = logMinWrapWidth - } - - for _, p := range pairs { - if p.isList && len(p.listValues) > 0 { - fmt.Fprintf(w, "%s%s%s:%s\n", indent, ui.Gray, p.key, ui.Reset) - for _, v := range p.listValues { - fmt.Fprintf(w, "%s%s%s%s%s\n", indent, ui.Gray, listIndent, ui.Reset, v) - } - } else if p.value != "" { - fmt.Fprintf(w, "%s%s%s:%s %s\n", indent, ui.Gray, p.key, ui.Reset, p.value) - } - } -} - -func formatLogDetailPairs(e oplog.Entry) []logDetailPair { - if e.Args == nil { - return nil - } - - switch e.Command { - case "sync": - return formatSyncLogPairs(e.Args) - case "install": - return formatInstallLogPairs(e.Args) - case "audit": - return formatAuditLogPairs(e.Args) - default: - return formatGenericLogPairs(e.Args) - } -} - -func formatSyncLogPairs(args map[string]any) []logDetailPair { - var pairs []logDetailPair - - if total, ok := logArgInt(args, "targets_total", "targets"); ok { - pairs = append(pairs, logDetailPair{key: "targets", value: fmt.Sprintf("%d", total)}) - } - if failed, ok := logArgInt(args, "targets_failed"); ok && failed > 0 { - pairs = append(pairs, logDetailPair{key: "failed", value: fmt.Sprintf("%d", failed)}) - } - if dryRun, ok := logArgBool(args, "dry_run"); ok && dryRun { - pairs = append(pairs, logDetailPair{key: "dry-run", value: "yes"}) - } - if force, ok := logArgBool(args, "force"); ok && force { - pairs = append(pairs, logDetailPair{key: "force", value: "yes"}) - } - if scope, ok := logArgString(args, "scope"); ok && scope != "" { - pairs = append(pairs, logDetailPair{key: "scope", value: scope}) - } - - return pairs -} - -func formatInstallLogPairs(args map[string]any) []logDetailPair { - var pairs []logDetailPair - - if mode, ok := logArgString(args, "mode"); ok && mode != "" { - pairs = append(pairs, logDetailPair{key: "mode", value: mode}) - } - if threshold, ok := logArgString(args, "threshold"); ok && threshold != "" { - pairs = append(pairs, logDetailPair{key: "threshold", value: strings.ToUpper(threshold)}) - } - if skillCount, ok := logArgInt(args, "skill_count"); ok && skillCount > 0 { - pairs = append(pairs, logDetailPair{key: "skills", value: fmt.Sprintf("%d", skillCount)}) - } - if source, ok := logArgString(args, "source"); ok && source != "" { - pairs = append(pairs, logDetailPair{key: "source", value: source}) - } - if dryRun, ok := logArgBool(args, "dry_run"); ok && dryRun { - pairs = append(pairs, logDetailPair{key: "dry-run", value: "yes"}) - } - if tracked, ok := logArgBool(args, "tracked"); ok && tracked { - pairs = append(pairs, logDetailPair{key: "tracked", value: "yes"}) - } - if skipAudit, ok := logArgBool(args, "skip_audit"); ok && skipAudit { - pairs = append(pairs, logDetailPair{key: "skip-audit", value: "yes"}) - } - if installedSkills, ok := logArgStringSlice(args, "installed_skills"); ok && len(installedSkills) > 0 { - pairs = append(pairs, logDetailPair{key: "installed", isList: true, listValues: installedSkills}) - } - if failedSkills, ok := logArgStringSlice(args, "failed_skills"); ok && len(failedSkills) > 0 { - pairs = append(pairs, logDetailPair{key: "failed", isList: true, listValues: failedSkills}) - } - - return pairs -} - -func formatAuditLogPairs(args map[string]any) []logDetailPair { - var pairs []logDetailPair - - scope, hasScope := logArgString(args, "scope") - name, hasName := logArgString(args, "name") - if hasScope && scope == "single" && hasName && name != "" { - pairs = append(pairs, logDetailPair{key: "skill", value: name}) - } else if hasScope && scope == "all" { - pairs = append(pairs, logDetailPair{key: "scope", value: "all-skills"}) - } else if hasName && name != "" { - pairs = append(pairs, logDetailPair{key: "name", value: name}) - } - if path, ok := logArgString(args, "path"); ok && path != "" { - pairs = append(pairs, logDetailPair{key: "path", value: path}) - } - - if mode, ok := logArgString(args, "mode"); ok && mode != "" { - pairs = append(pairs, logDetailPair{key: "mode", value: mode}) - } - if threshold, ok := logArgString(args, "threshold"); ok && threshold != "" { - pairs = append(pairs, logDetailPair{key: "threshold", value: strings.ToUpper(threshold)}) - } - if scanned, ok := logArgInt(args, "scanned"); ok { - pairs = append(pairs, logDetailPair{key: "scanned", value: fmt.Sprintf("%d", scanned)}) - } - if passed, ok := logArgInt(args, "passed"); ok { - pairs = append(pairs, logDetailPair{key: "passed", value: fmt.Sprintf("%d", passed)}) - } - if warning, ok := logArgInt(args, "warning"); ok && warning > 0 { - pairs = append(pairs, logDetailPair{key: "warning", value: fmt.Sprintf("%d", warning)}) - } - if failed, ok := logArgInt(args, "failed"); ok && failed > 0 { - pairs = append(pairs, logDetailPair{key: "failed", value: fmt.Sprintf("%d", failed)}) - } - - critical, hasCritical := logArgInt(args, "critical") - high, hasHigh := logArgInt(args, "high") - medium, hasMedium := logArgInt(args, "medium") - low, hasLow := logArgInt(args, "low") - info, hasInfo := logArgInt(args, "info") - if (hasCritical && critical > 0) || (hasHigh && high > 0) || (hasMedium && medium > 0) || (hasLow && low > 0) || (hasInfo && info > 0) { - pairs = append(pairs, logDetailPair{key: "severity(c/h/m/l/i)", value: fmt.Sprintf("%d/%d/%d/%d/%d", critical, high, medium, low, info)}) - } - - riskScore, hasRiskScore := logArgInt(args, "risk_score") - riskLabel, hasRiskLabel := logArgString(args, "risk_label") - if hasRiskScore { - if hasRiskLabel && riskLabel != "" { - pairs = append(pairs, logDetailPair{key: "risk", value: fmt.Sprintf("%s (%d/100)", strings.ToUpper(riskLabel), riskScore)}) - } else { - pairs = append(pairs, logDetailPair{key: "risk", value: fmt.Sprintf("%d/100", riskScore)}) - } - } - - if scanErrors, ok := logArgInt(args, "scan_errors"); ok && scanErrors > 0 { - pairs = append(pairs, logDetailPair{key: "scan-errors", value: fmt.Sprintf("%d", scanErrors)}) - } - - if failedSkills, ok := logArgStringSlice(args, "failed_skills"); ok && len(failedSkills) > 0 { - pairs = append(pairs, logDetailPair{key: "failed skills", isList: true, listValues: failedSkills}) - } - if warningSkills, ok := logArgStringSlice(args, "warning_skills"); ok && len(warningSkills) > 0 { - pairs = append(pairs, logDetailPair{key: "warning skills", isList: true, listValues: warningSkills}) - } - if lowSkills, ok := logArgStringSlice(args, "low_skills"); ok && len(lowSkills) > 0 { - pairs = append(pairs, logDetailPair{key: "low skills", isList: true, listValues: lowSkills}) - } - if infoSkills, ok := logArgStringSlice(args, "info_skills"); ok && len(infoSkills) > 0 { - pairs = append(pairs, logDetailPair{key: "info skills", isList: true, listValues: infoSkills}) - } - - return pairs -} - -func formatGenericLogPairs(args map[string]any) []logDetailPair { - var pairs []logDetailPair - - if source, ok := logArgString(args, "source"); ok { - pairs = append(pairs, logDetailPair{key: "source", value: source}) - } - if name, ok := logArgString(args, "name"); ok { - pairs = append(pairs, logDetailPair{key: "name", value: name}) - } - if names, ok := logArgStringSlice(args, "names"); ok && len(names) > 0 { - pairs = append(pairs, logDetailPair{key: "names", isList: true, listValues: names}) - } - if target, ok := logArgString(args, "target"); ok { - pairs = append(pairs, logDetailPair{key: "target", value: target}) - } - if targets, ok := logArgInt(args, "targets"); ok { - pairs = append(pairs, logDetailPair{key: "targets", value: fmt.Sprintf("%d", targets)}) - } - if summary, ok := logArgString(args, "summary"); ok { - pairs = append(pairs, logDetailPair{key: "summary", value: summary}) - } - - return pairs -} - -func printLogEntriesNonTTY(w io.Writer, entries []oplog.Entry) { - for _, e := range entries { - ts := formatLogTimestamp(e.Timestamp) - detail := formatLogDetail(e, true) - dur := formatLogDuration(e.Duration) - - fmt.Fprintf(w, " %s %-9s %-96s %-7s %s\n", - ts, e.Command, detail, e.Status, dur) - - printLogAuditSkillLinesNonTTY(w, e) - } -} - -func printLogAuditSkillLinesNonTTY(w io.Writer, e oplog.Entry) { - if e.Command != "audit" || e.Args == nil { - return - } - - if failedSkills, ok := logArgStringSlice(e.Args, "failed_skills"); ok && len(failedSkills) > 0 { - printLogNamedSkillsNonTTY(w, "failed skills", failedSkills) - } - if warningSkills, ok := logArgStringSlice(e.Args, "warning_skills"); ok && len(warningSkills) > 0 { - printLogNamedSkillsNonTTY(w, "warning skills", warningSkills) - } - if lowSkills, ok := logArgStringSlice(e.Args, "low_skills"); ok && len(lowSkills) > 0 { - printLogNamedSkillsNonTTY(w, "low skills", lowSkills) - } - if infoSkills, ok := logArgStringSlice(e.Args, "info_skills"); ok && len(infoSkills) > 0 { - printLogNamedSkillsNonTTY(w, "info skills", infoSkills) - } -} - -func printLogNamedSkillsNonTTY(w io.Writer, label string, skills []string) { - const namesPerLine = 4 - for i := 0; i < len(skills); i += namesPerLine { - end := i + namesPerLine - if end > len(skills) { - end = len(skills) - } - - currentLabel := label - if i > 0 { - currentLabel = label + " (cont)" - } - fmt.Fprintf(w, " -> %s: %s\n", currentLabel, strings.Join(skills[i:end], ", ")) - } -} - -func printLogTableHeaderTTY(w io.Writer) { - header := fmt.Sprintf(" %-16s | %-9s | %-7s | %-7s", "TIME", "CMD", "STATUS", "DUR") - separator := fmt.Sprintf( - " %s-+-%s-+-%s-+-%s", - strings.Repeat("-", logTimeWidth), - strings.Repeat("-", logCmdWidth), - strings.Repeat("-", logStatusWidth), - strings.Repeat("-", logDurationWidth), - ) - - fmt.Fprintf(w, "%s%s%s\n", ui.Cyan, header, ui.Reset) - fmt.Fprintf(w, "%s%s%s\n", ui.Gray, separator, ui.Reset) -} - -func formatLogTimestamp(ts string) string { - t, err := time.Parse(time.RFC3339, ts) - if err != nil { - if len(ts) >= 16 { - return ts[:16] - } - return ts - } - return t.Format("2006-01-02 15:04") -} - -func formatLogDetail(e oplog.Entry, truncate bool) string { - detail := "" - if e.Args != nil { - switch e.Command { - case "sync": - detail = formatSyncLogDetail(e.Args) - case "install": - detail = formatInstallLogDetail(e.Args) - case "audit": - detail = formatAuditLogDetail(e.Args) - default: - detail = formatGenericLogDetail(e.Args) - } - } - - if e.Message != "" && detail != "" { - return formatLogDetailValue(detail+" ("+e.Message+")", truncate) - } - if e.Message != "" { - return formatLogDetailValue(e.Message, truncate) - } - if detail != "" { - return formatLogDetailValue(detail, truncate) - } - return "" -} - -func formatLogDetailValue(value string, truncate bool) string { - if !truncate { - return value - } - return truncateLogString(value, logDetailTruncateLen) -} - -func formatSyncLogDetail(args map[string]any) string { - parts := make([]string, 0, 5) - - if total, ok := logArgInt(args, "targets_total", "targets"); ok { - parts = append(parts, fmt.Sprintf("targets=%d", total)) - } - if failed, ok := logArgInt(args, "targets_failed"); ok && failed > 0 { - parts = append(parts, fmt.Sprintf("failed=%d", failed)) - } - if dryRun, ok := logArgBool(args, "dry_run"); ok && dryRun { - parts = append(parts, "dry-run") - } - if force, ok := logArgBool(args, "force"); ok && force { - parts = append(parts, "force") - } - if scope, ok := logArgString(args, "scope"); ok && scope != "" { - parts = append(parts, "scope="+scope) - } - - if len(parts) == 0 { - return formatGenericLogDetail(args) - } - return strings.Join(parts, ", ") -} - -func formatInstallLogDetail(args map[string]any) string { - parts := make([]string, 0, 8) - - if mode, ok := logArgString(args, "mode"); ok && mode != "" { - parts = append(parts, "mode="+mode) - } - if threshold, ok := logArgString(args, "threshold"); ok && threshold != "" { - parts = append(parts, "threshold="+strings.ToUpper(threshold)) - } - if skillCount, ok := logArgInt(args, "skill_count"); ok && skillCount > 0 { - parts = append(parts, fmt.Sprintf("skills=%d", skillCount)) - } - if installedSkills, ok := logArgStringSlice(args, "installed_skills"); ok && len(installedSkills) > 0 { - parts = append(parts, "installed="+strings.Join(installedSkills, ", ")) - } - if failedSkills, ok := logArgStringSlice(args, "failed_skills"); ok && len(failedSkills) > 0 { - parts = append(parts, "failed="+strings.Join(failedSkills, ", ")) - } - if dryRun, ok := logArgBool(args, "dry_run"); ok && dryRun { - parts = append(parts, "dry-run") - } - if tracked, ok := logArgBool(args, "tracked"); ok && tracked { - parts = append(parts, "tracked") - } - if skipAudit, ok := logArgBool(args, "skip_audit"); ok && skipAudit { - parts = append(parts, "skip-audit") - } - if source, ok := logArgString(args, "source"); ok && source != "" { - parts = append(parts, "source="+source) - } - - if len(parts) == 0 { - return formatGenericLogDetail(args) - } - return strings.Join(parts, ", ") -} - -func formatAuditLogDetail(args map[string]any) string { - parts := make([]string, 0, 12) - - scope, hasScope := logArgString(args, "scope") - name, hasName := logArgString(args, "name") - if hasScope && scope == "single" && hasName && name != "" { - parts = append(parts, "skill="+name) - } else if hasScope && scope == "all" { - parts = append(parts, "all-skills") - } else if hasName && name != "" { - parts = append(parts, name) - } - if path, ok := logArgString(args, "path"); ok && path != "" { - parts = append(parts, "path="+path) - } - - if mode, ok := logArgString(args, "mode"); ok && mode != "" { - parts = append(parts, "mode="+mode) - } - if threshold, ok := logArgString(args, "threshold"); ok && threshold != "" { - parts = append(parts, "threshold="+strings.ToUpper(threshold)) - } - if scanned, ok := logArgInt(args, "scanned"); ok { - parts = append(parts, fmt.Sprintf("scanned=%d", scanned)) - } - if passed, ok := logArgInt(args, "passed"); ok { - parts = append(parts, fmt.Sprintf("passed=%d", passed)) - } - if warning, ok := logArgInt(args, "warning"); ok && warning > 0 { - parts = append(parts, fmt.Sprintf("warning=%d", warning)) - } - if failed, ok := logArgInt(args, "failed"); ok && failed > 0 { - parts = append(parts, fmt.Sprintf("failed=%d", failed)) - } - - critical, hasCritical := logArgInt(args, "critical") - high, hasHigh := logArgInt(args, "high") - medium, hasMedium := logArgInt(args, "medium") - low, hasLow := logArgInt(args, "low") - info, hasInfo := logArgInt(args, "info") - if (hasCritical && critical > 0) || (hasHigh && high > 0) || (hasMedium && medium > 0) || (hasLow && low > 0) || (hasInfo && info > 0) { - parts = append(parts, fmt.Sprintf("sev(c/h/m/l/i)=%d/%d/%d/%d/%d", critical, high, medium, low, info)) - } - - if riskScore, ok := logArgInt(args, "risk_score"); ok { - riskLabel, hasRiskLabel := logArgString(args, "risk_label") - if hasRiskLabel && riskLabel != "" { - parts = append(parts, fmt.Sprintf("risk=%s(%d/100)", strings.ToUpper(riskLabel), riskScore)) - } else { - parts = append(parts, fmt.Sprintf("risk=%d/100", riskScore)) - } - } - - if scanErrors, ok := logArgInt(args, "scan_errors"); ok && scanErrors > 0 { - parts = append(parts, fmt.Sprintf("scan-errors=%d", scanErrors)) - } - - if len(parts) == 0 { - return formatGenericLogDetail(args) - } - return strings.Join(parts, ", ") -} - -func formatGenericLogDetail(args map[string]any) string { - parts := make([]string, 0, 4) - - if source, ok := logArgString(args, "source"); ok { - parts = append(parts, source) - } - if name, ok := logArgString(args, "name"); ok { - parts = append(parts, name) - } - if names, ok := logArgStringSlice(args, "names"); ok && len(names) > 0 { - parts = append(parts, strings.Join(names, ", ")) - } - if target, ok := logArgString(args, "target"); ok { - parts = append(parts, target) - } - if targets, ok := logArgInt(args, "targets"); ok { - parts = append(parts, fmt.Sprintf("targets=%d", targets)) - } - if summary, ok := logArgString(args, "summary"); ok { - parts = append(parts, summary) - } - - return strings.Join(parts, ", ") -} - -func logArgString(args map[string]any, key string) (string, bool) { - v, ok := args[key] - if !ok || v == nil { - return "", false - } - - switch s := v.(type) { - case string: - return s, true - default: - return fmt.Sprintf("%v", v), true - } -} - -func logArgInt(args map[string]any, keys ...string) (int, bool) { - for _, key := range keys { - v, ok := args[key] - if !ok || v == nil { - continue - } - - switch n := v.(type) { - case int: - return n, true - case int64: - return int(n), true - case float64: - return int(n), true - case string: - parsed, err := strconv.Atoi(strings.TrimSpace(n)) - if err == nil { - return parsed, true - } - } - } - return 0, false -} - -func logArgBool(args map[string]any, key string) (bool, bool) { - v, ok := args[key] - if !ok || v == nil { - return false, false - } - - switch b := v.(type) { - case bool: - return b, true - case string: - parsed, err := strconv.ParseBool(strings.TrimSpace(b)) - if err == nil { - return parsed, true - } - } - return false, false -} - -func logArgStringSlice(args map[string]any, key string) ([]string, bool) { - v, ok := args[key] - if !ok || v == nil { - return nil, false - } - - switch raw := v.(type) { - case []string: - if len(raw) == 0 { - return nil, false - } - return raw, true - case []any: - items := make([]string, 0, len(raw)) - for _, it := range raw { - s := strings.TrimSpace(fmt.Sprintf("%v", it)) - if s != "" { - items = append(items, s) - } - } - if len(items) == 0 { - return nil, false - } - return items, true - case string: - s := strings.TrimSpace(raw) - if s == "" { - return nil, false - } - return []string{s}, true - default: - return nil, false - } -} - -func colorizeLogStatusCell(cell, status string) string { - switch status { - case "ok": - return ui.Green + cell + ui.Reset - case "error": - return ui.Red + cell + ui.Reset - case "partial": - return ui.Yellow + cell + ui.Reset - case "blocked": - return ui.Red + cell + ui.Reset - default: - return cell - } -} - -func formatLogDuration(ms int64) string { - if ms <= 0 { - return "" - } - if ms < 1000 { - return fmt.Sprintf("%dms", ms) - } - return fmt.Sprintf("%.1fs", float64(ms)/1000) -} - -func truncateLogString(s string, maxLen int) string { - if len(s) <= maxLen { - return s - } - return s[:maxLen-3] + "..." -} - -func logTerminalWidth() int { - width := pterm.GetTerminalWidth() - if width > 0 { - return width - } - return 120 -} - -func padLogCell(value string, width int) string { - current := logDisplayWidth(value) - if current >= width { - return value - } - return value + strings.Repeat(" ", width-current) -} - -func logDisplayWidth(s string) int { - return runewidth.StringWidth(logANSIRegex.ReplaceAllString(s, "")) -} - // statusFromErr returns "ok" for nil errors and "error" otherwise. // Used by all command instrumentation to derive oplog status. func statusFromErr(err error) string { @@ -862,6 +200,7 @@ Options: --status Filter by status (ok, error, partial, blocked) --since Filter by time (e.g. 30m, 2h, 2d, 1w, 2006-01-02) --json Output raw JSONL (one JSON object per line) + --no-tui Disable interactive TUI, print plain text --clear, -c Clear the selected log file --project, -p Use project-level log --global, -g Use global log @@ -884,3 +223,81 @@ Examples: func isProjectLogConfig(configPath string) bool { return filepath.Base(filepath.Dir(configPath)) == ".skillshare" } + +// runLogTUIDispatch reads log entries and launches the interactive TUI viewer. +func runLogTUIDispatch(configPath string, auditOnly bool, limit int, filter oplog.Filter, modeLabel string) error { + var items []logItem + + if auditOnly { + entries, err := readAndFilter(configPath, oplog.AuditFile, limit, filter) + if err != nil { + return err + } + items = toLogItems(entries, "audit") + return runLogTUI(items, "Audit", modeLabel) + } + + // When filtering by command, only read the relevant log + if filter.Cmd != "" { + if filter.Cmd == "audit" { + entries, err := readAndFilter(configPath, oplog.AuditFile, limit, filter) + if err != nil { + return err + } + items = toLogItems(entries, "audit") + return runLogTUI(items, "Audit", modeLabel) + } + entries, err := readAndFilter(configPath, oplog.OpsFile, limit, filter) + if err != nil { + return err + } + items = toLogItems(entries, "operations") + return runLogTUI(items, "Operations", modeLabel) + } + + // Read both logs, merge, and sort by timestamp (newest first) + opsEntries, err := readAndFilter(configPath, oplog.OpsFile, 0, filter) + if err != nil { + return err + } + auditEntries, err := readAndFilter(configPath, oplog.AuditFile, 0, filter) + if err != nil { + return err + } + + items = append(toLogItems(opsEntries, "operations"), toLogItems(auditEntries, "audit")...) + + // Sort by timestamp descending (newest first) + sort.Slice(items, func(i, j int) bool { + return items[i].entry.Timestamp > items[j].entry.Timestamp + }) + + // Apply limit after merge + if limit > 0 && len(items) > limit { + items = items[:limit] + } + + return runLogTUI(items, "Operations & Audit", modeLabel) +} + +// readAndFilter reads entries from a log file, applies filter, and limits results. +func readAndFilter(configPath, filename string, limit int, f oplog.Filter) ([]oplog.Entry, error) { + readLimit := limit + if !f.IsEmpty() { + readLimit = 0 // read all, filter narrows down + } + + entries, err := oplog.Read(configPath, filename, readLimit) + if err != nil { + return nil, fmt.Errorf("failed to read log: %w", err) + } + + if !f.IsEmpty() { + entries = oplog.FilterEntries(entries, f) + if limit > 0 && len(entries) > limit { + entries = entries[:limit] + } + } + + return entries, nil +} diff --git a/cmd/skillshare/log_format.go b/cmd/skillshare/log_format.go new file mode 100644 index 000000000..fdc0bdd7b --- /dev/null +++ b/cmd/skillshare/log_format.go @@ -0,0 +1,495 @@ +package main + +import ( + "fmt" + "strconv" + "strings" + "time" + + "skillshare/internal/oplog" +) + +// logDetailPair represents a structured key-value for multi-line detail output. +type logDetailPair struct { + key string + value string + isList bool + listValues []string +} + +func formatLogDetailPairs(e oplog.Entry) []logDetailPair { + if e.Args == nil { + return nil + } + + switch e.Command { + case "sync": + return formatSyncLogPairs(e.Args) + case "install": + return formatInstallLogPairs(e.Args) + case "audit": + return formatAuditLogPairs(e.Args) + default: + return formatGenericLogPairs(e.Args) + } +} + +func formatSyncLogPairs(args map[string]any) []logDetailPair { + var pairs []logDetailPair + + if total, ok := logArgInt(args, "targets_total", "targets"); ok { + pairs = append(pairs, logDetailPair{key: "targets", value: fmt.Sprintf("%d", total)}) + } + if failed, ok := logArgInt(args, "targets_failed"); ok && failed > 0 { + pairs = append(pairs, logDetailPair{key: "failed", value: fmt.Sprintf("%d", failed)}) + } + if dryRun, ok := logArgBool(args, "dry_run"); ok && dryRun { + pairs = append(pairs, logDetailPair{key: "dry-run", value: "yes"}) + } + if force, ok := logArgBool(args, "force"); ok && force { + pairs = append(pairs, logDetailPair{key: "force", value: "yes"}) + } + if scope, ok := logArgString(args, "scope"); ok && scope != "" { + pairs = append(pairs, logDetailPair{key: "scope", value: scope}) + } + + return pairs +} + +func formatInstallLogPairs(args map[string]any) []logDetailPair { + var pairs []logDetailPair + + if mode, ok := logArgString(args, "mode"); ok && mode != "" { + pairs = append(pairs, logDetailPair{key: "mode", value: mode}) + } + if threshold, ok := logArgString(args, "threshold"); ok && threshold != "" { + pairs = append(pairs, logDetailPair{key: "threshold", value: strings.ToUpper(threshold)}) + } + if skillCount, ok := logArgInt(args, "skill_count"); ok && skillCount > 0 { + pairs = append(pairs, logDetailPair{key: "skills", value: fmt.Sprintf("%d", skillCount)}) + } + if source, ok := logArgString(args, "source"); ok && source != "" { + pairs = append(pairs, logDetailPair{key: "source", value: source}) + } + if dryRun, ok := logArgBool(args, "dry_run"); ok && dryRun { + pairs = append(pairs, logDetailPair{key: "dry-run", value: "yes"}) + } + if tracked, ok := logArgBool(args, "tracked"); ok && tracked { + pairs = append(pairs, logDetailPair{key: "tracked", value: "yes"}) + } + if skipAudit, ok := logArgBool(args, "skip_audit"); ok && skipAudit { + pairs = append(pairs, logDetailPair{key: "skip-audit", value: "yes"}) + } + if installedSkills, ok := logArgStringSlice(args, "installed_skills"); ok && len(installedSkills) > 0 { + pairs = append(pairs, logDetailPair{key: "installed", isList: true, listValues: installedSkills}) + } + if failedSkills, ok := logArgStringSlice(args, "failed_skills"); ok && len(failedSkills) > 0 { + pairs = append(pairs, logDetailPair{key: "failed", isList: true, listValues: failedSkills}) + } + + return pairs +} + +func formatAuditLogPairs(args map[string]any) []logDetailPair { + var pairs []logDetailPair + + scope, hasScope := logArgString(args, "scope") + name, hasName := logArgString(args, "name") + if hasScope && scope == "single" && hasName && name != "" { + pairs = append(pairs, logDetailPair{key: "skill", value: name}) + } else if hasScope && scope == "all" { + pairs = append(pairs, logDetailPair{key: "scope", value: "all-skills"}) + } else if hasName && name != "" { + pairs = append(pairs, logDetailPair{key: "name", value: name}) + } + if path, ok := logArgString(args, "path"); ok && path != "" { + pairs = append(pairs, logDetailPair{key: "path", value: path}) + } + + if mode, ok := logArgString(args, "mode"); ok && mode != "" { + pairs = append(pairs, logDetailPair{key: "mode", value: mode}) + } + if threshold, ok := logArgString(args, "threshold"); ok && threshold != "" { + pairs = append(pairs, logDetailPair{key: "threshold", value: strings.ToUpper(threshold)}) + } + if scanned, ok := logArgInt(args, "scanned"); ok { + pairs = append(pairs, logDetailPair{key: "scanned", value: fmt.Sprintf("%d", scanned)}) + } + if passed, ok := logArgInt(args, "passed"); ok { + pairs = append(pairs, logDetailPair{key: "passed", value: fmt.Sprintf("%d", passed)}) + } + if warning, ok := logArgInt(args, "warning"); ok && warning > 0 { + pairs = append(pairs, logDetailPair{key: "warning", value: fmt.Sprintf("%d", warning)}) + } + if failed, ok := logArgInt(args, "failed"); ok && failed > 0 { + pairs = append(pairs, logDetailPair{key: "failed", value: fmt.Sprintf("%d", failed)}) + } + + critical, hasCritical := logArgInt(args, "critical") + high, hasHigh := logArgInt(args, "high") + medium, hasMedium := logArgInt(args, "medium") + low, hasLow := logArgInt(args, "low") + info, hasInfo := logArgInt(args, "info") + if (hasCritical && critical > 0) || (hasHigh && high > 0) || (hasMedium && medium > 0) || (hasLow && low > 0) || (hasInfo && info > 0) { + pairs = append(pairs, logDetailPair{key: "severity(c/h/m/l/i)", value: fmt.Sprintf("%d/%d/%d/%d/%d", critical, high, medium, low, info)}) + } + + riskScore, hasRiskScore := logArgInt(args, "risk_score") + riskLabel, hasRiskLabel := logArgString(args, "risk_label") + if hasRiskScore { + if hasRiskLabel && riskLabel != "" { + pairs = append(pairs, logDetailPair{key: "risk", value: fmt.Sprintf("%s (%d/100)", strings.ToUpper(riskLabel), riskScore)}) + } else { + pairs = append(pairs, logDetailPair{key: "risk", value: fmt.Sprintf("%d/100", riskScore)}) + } + } + + if scanErrors, ok := logArgInt(args, "scan_errors"); ok && scanErrors > 0 { + pairs = append(pairs, logDetailPair{key: "scan-errors", value: fmt.Sprintf("%d", scanErrors)}) + } + + if failedSkills, ok := logArgStringSlice(args, "failed_skills"); ok && len(failedSkills) > 0 { + pairs = append(pairs, logDetailPair{key: "failed skills", isList: true, listValues: failedSkills}) + } + if warningSkills, ok := logArgStringSlice(args, "warning_skills"); ok && len(warningSkills) > 0 { + pairs = append(pairs, logDetailPair{key: "warning skills", isList: true, listValues: warningSkills}) + } + if lowSkills, ok := logArgStringSlice(args, "low_skills"); ok && len(lowSkills) > 0 { + pairs = append(pairs, logDetailPair{key: "low skills", isList: true, listValues: lowSkills}) + } + if infoSkills, ok := logArgStringSlice(args, "info_skills"); ok && len(infoSkills) > 0 { + pairs = append(pairs, logDetailPair{key: "info skills", isList: true, listValues: infoSkills}) + } + + return pairs +} + +func formatGenericLogPairs(args map[string]any) []logDetailPair { + var pairs []logDetailPair + + if source, ok := logArgString(args, "source"); ok { + pairs = append(pairs, logDetailPair{key: "source", value: source}) + } + if name, ok := logArgString(args, "name"); ok { + pairs = append(pairs, logDetailPair{key: "name", value: name}) + } + if names, ok := logArgStringSlice(args, "names"); ok && len(names) > 0 { + pairs = append(pairs, logDetailPair{key: "names", isList: true, listValues: names}) + } + if target, ok := logArgString(args, "target"); ok { + pairs = append(pairs, logDetailPair{key: "target", value: target}) + } + if targets, ok := logArgInt(args, "targets"); ok { + pairs = append(pairs, logDetailPair{key: "targets", value: fmt.Sprintf("%d", targets)}) + } + if summary, ok := logArgString(args, "summary"); ok { + pairs = append(pairs, logDetailPair{key: "summary", value: summary}) + } + + return pairs +} + +func formatLogTimestamp(ts string) string { + t, err := time.Parse(time.RFC3339, ts) + if err != nil { + if len(ts) >= 16 { + return ts[:16] + } + return ts + } + return t.Format("2006-01-02 15:04") +} + +func formatLogDetail(e oplog.Entry, truncate bool) string { + detail := "" + if e.Args != nil { + switch e.Command { + case "sync": + detail = formatSyncLogDetail(e.Args) + case "install": + detail = formatInstallLogDetail(e.Args) + case "audit": + detail = formatAuditLogDetail(e.Args) + default: + detail = formatGenericLogDetail(e.Args) + } + } + + if e.Message != "" && detail != "" { + return formatLogDetailValue(detail+" ("+e.Message+")", truncate) + } + if e.Message != "" { + return formatLogDetailValue(e.Message, truncate) + } + if detail != "" { + return formatLogDetailValue(detail, truncate) + } + return "" +} + +func formatLogDetailValue(value string, truncate bool) string { + if !truncate { + return value + } + return truncateLogString(value, logDetailTruncateLen) +} + +func formatSyncLogDetail(args map[string]any) string { + parts := make([]string, 0, 5) + + if total, ok := logArgInt(args, "targets_total", "targets"); ok { + parts = append(parts, fmt.Sprintf("targets=%d", total)) + } + if failed, ok := logArgInt(args, "targets_failed"); ok && failed > 0 { + parts = append(parts, fmt.Sprintf("failed=%d", failed)) + } + if dryRun, ok := logArgBool(args, "dry_run"); ok && dryRun { + parts = append(parts, "dry-run") + } + if force, ok := logArgBool(args, "force"); ok && force { + parts = append(parts, "force") + } + if scope, ok := logArgString(args, "scope"); ok && scope != "" { + parts = append(parts, "scope="+scope) + } + + if len(parts) == 0 { + return formatGenericLogDetail(args) + } + return strings.Join(parts, ", ") +} + +func formatInstallLogDetail(args map[string]any) string { + parts := make([]string, 0, 8) + + if mode, ok := logArgString(args, "mode"); ok && mode != "" { + parts = append(parts, "mode="+mode) + } + if threshold, ok := logArgString(args, "threshold"); ok && threshold != "" { + parts = append(parts, "threshold="+strings.ToUpper(threshold)) + } + if skillCount, ok := logArgInt(args, "skill_count"); ok && skillCount > 0 { + parts = append(parts, fmt.Sprintf("skills=%d", skillCount)) + } + if installedSkills, ok := logArgStringSlice(args, "installed_skills"); ok && len(installedSkills) > 0 { + parts = append(parts, "installed="+strings.Join(installedSkills, ", ")) + } + if failedSkills, ok := logArgStringSlice(args, "failed_skills"); ok && len(failedSkills) > 0 { + parts = append(parts, "failed="+strings.Join(failedSkills, ", ")) + } + if dryRun, ok := logArgBool(args, "dry_run"); ok && dryRun { + parts = append(parts, "dry-run") + } + if tracked, ok := logArgBool(args, "tracked"); ok && tracked { + parts = append(parts, "tracked") + } + if skipAudit, ok := logArgBool(args, "skip_audit"); ok && skipAudit { + parts = append(parts, "skip-audit") + } + if source, ok := logArgString(args, "source"); ok && source != "" { + parts = append(parts, "source="+source) + } + + if len(parts) == 0 { + return formatGenericLogDetail(args) + } + return strings.Join(parts, ", ") +} + +func formatAuditLogDetail(args map[string]any) string { + parts := make([]string, 0, 12) + + scope, hasScope := logArgString(args, "scope") + name, hasName := logArgString(args, "name") + if hasScope && scope == "single" && hasName && name != "" { + parts = append(parts, "skill="+name) + } else if hasScope && scope == "all" { + parts = append(parts, "all-skills") + } else if hasName && name != "" { + parts = append(parts, name) + } + if path, ok := logArgString(args, "path"); ok && path != "" { + parts = append(parts, "path="+path) + } + + if mode, ok := logArgString(args, "mode"); ok && mode != "" { + parts = append(parts, "mode="+mode) + } + if threshold, ok := logArgString(args, "threshold"); ok && threshold != "" { + parts = append(parts, "threshold="+strings.ToUpper(threshold)) + } + if scanned, ok := logArgInt(args, "scanned"); ok { + parts = append(parts, fmt.Sprintf("scanned=%d", scanned)) + } + if passed, ok := logArgInt(args, "passed"); ok { + parts = append(parts, fmt.Sprintf("passed=%d", passed)) + } + if warning, ok := logArgInt(args, "warning"); ok && warning > 0 { + parts = append(parts, fmt.Sprintf("warning=%d", warning)) + } + if failed, ok := logArgInt(args, "failed"); ok && failed > 0 { + parts = append(parts, fmt.Sprintf("failed=%d", failed)) + } + + critical, hasCritical := logArgInt(args, "critical") + high, hasHigh := logArgInt(args, "high") + medium, hasMedium := logArgInt(args, "medium") + low, hasLow := logArgInt(args, "low") + info, hasInfo := logArgInt(args, "info") + if (hasCritical && critical > 0) || (hasHigh && high > 0) || (hasMedium && medium > 0) || (hasLow && low > 0) || (hasInfo && info > 0) { + parts = append(parts, fmt.Sprintf("sev(c/h/m/l/i)=%d/%d/%d/%d/%d", critical, high, medium, low, info)) + } + + if riskScore, ok := logArgInt(args, "risk_score"); ok { + riskLabel, hasRiskLabel := logArgString(args, "risk_label") + if hasRiskLabel && riskLabel != "" { + parts = append(parts, fmt.Sprintf("risk=%s(%d/100)", strings.ToUpper(riskLabel), riskScore)) + } else { + parts = append(parts, fmt.Sprintf("risk=%d/100", riskScore)) + } + } + + if scanErrors, ok := logArgInt(args, "scan_errors"); ok && scanErrors > 0 { + parts = append(parts, fmt.Sprintf("scan-errors=%d", scanErrors)) + } + + if len(parts) == 0 { + return formatGenericLogDetail(args) + } + return strings.Join(parts, ", ") +} + +func formatGenericLogDetail(args map[string]any) string { + parts := make([]string, 0, 4) + + if source, ok := logArgString(args, "source"); ok { + parts = append(parts, source) + } + if name, ok := logArgString(args, "name"); ok { + parts = append(parts, name) + } + if names, ok := logArgStringSlice(args, "names"); ok && len(names) > 0 { + parts = append(parts, strings.Join(names, ", ")) + } + if target, ok := logArgString(args, "target"); ok { + parts = append(parts, target) + } + if targets, ok := logArgInt(args, "targets"); ok { + parts = append(parts, fmt.Sprintf("targets=%d", targets)) + } + if summary, ok := logArgString(args, "summary"); ok { + parts = append(parts, summary) + } + + return strings.Join(parts, ", ") +} + +func formatLogDuration(ms int64) string { + if ms <= 0 { + return "" + } + if ms < 1000 { + return fmt.Sprintf("%dms", ms) + } + return fmt.Sprintf("%.1fs", float64(ms)/1000) +} + +func truncateLogString(s string, maxLen int) string { + if len(s) <= maxLen { + return s + } + return s[:maxLen-3] + "..." +} + +// logArg* helpers extract typed values from oplog.Entry.Args. + +func logArgString(args map[string]any, key string) (string, bool) { + v, ok := args[key] + if !ok || v == nil { + return "", false + } + + switch s := v.(type) { + case string: + return s, true + default: + return fmt.Sprintf("%v", v), true + } +} + +func logArgInt(args map[string]any, keys ...string) (int, bool) { + for _, key := range keys { + v, ok := args[key] + if !ok || v == nil { + continue + } + + switch n := v.(type) { + case int: + return n, true + case int64: + return int(n), true + case float64: + return int(n), true + case string: + parsed, err := strconv.Atoi(strings.TrimSpace(n)) + if err == nil { + return parsed, true + } + } + } + return 0, false +} + +func logArgBool(args map[string]any, key string) (bool, bool) { + v, ok := args[key] + if !ok || v == nil { + return false, false + } + + switch b := v.(type) { + case bool: + return b, true + case string: + parsed, err := strconv.ParseBool(strings.TrimSpace(b)) + if err == nil { + return parsed, true + } + } + return false, false +} + +func logArgStringSlice(args map[string]any, key string) ([]string, bool) { + v, ok := args[key] + if !ok || v == nil { + return nil, false + } + + switch raw := v.(type) { + case []string: + if len(raw) == 0 { + return nil, false + } + return raw, true + case []any: + items := make([]string, 0, len(raw)) + for _, it := range raw { + s := strings.TrimSpace(fmt.Sprintf("%v", it)) + if s != "" { + items = append(items, s) + } + } + if len(items) == 0 { + return nil, false + } + return items, true + case string: + s := strings.TrimSpace(raw) + if s == "" { + return nil, false + } + return []string{s}, true + default: + return nil, false + } +} diff --git a/cmd/skillshare/log_render.go b/cmd/skillshare/log_render.go new file mode 100644 index 000000000..eae36f234 --- /dev/null +++ b/cmd/skillshare/log_render.go @@ -0,0 +1,189 @@ +package main + +import ( + "fmt" + "io" + "os" + "regexp" + "strings" + + "github.com/mattn/go-runewidth" + "github.com/pterm/pterm" + + "skillshare/internal/oplog" + "skillshare/internal/ui" +) + +const ( + logDetailTruncateLen = 96 + logTimeWidth = 16 + logCmdWidth = 9 + logStatusWidth = 7 + logDurationWidth = 7 + logMinWrapWidth = 24 +) + +var logANSIRegex = regexp.MustCompile(`\x1b\[[0-9;]*m`) + +func printLogEntries(entries []oplog.Entry) { + if ui.IsTTY() { + printLogEntriesTTYTwoLine(os.Stdout, entries, logTerminalWidth()) + return + } + + printLogEntriesNonTTY(os.Stdout, entries) +} + +func printLogEntriesTTYTwoLine(w io.Writer, entries []oplog.Entry, termWidth int) { + printLogTableHeaderTTY(w) + + for i, e := range entries { + if i > 0 { + fmt.Fprintln(w) + } + + ts := formatLogTimestamp(e.Timestamp) + cmd := padLogCell(strings.ToUpper(e.Command), logCmdWidth) + status := colorizeLogStatusCell(padLogCell(e.Status, logStatusWidth), e.Status) + dur := formatLogDuration(e.Duration) + durCell := padLogCell(dur, logDurationWidth) + + fmt.Fprintf(w, " %s%s%s | %s | %s | %s\n", + ui.Gray, + padLogCell(ts, logTimeWidth), + ui.Reset, + cmd, + status, + durCell, + ) + + printLogDetailMultiLine(w, e, termWidth) + } +} + +func printLogDetailMultiLine(w io.Writer, e oplog.Entry, termWidth int) { + pairs := formatLogDetailPairs(e) + + if e.Message != "" { + pairs = append(pairs, logDetailPair{key: "message", value: e.Message}) + } + + if len(pairs) == 0 { + return + } + + const indent = " " + const listIndent = " - " + wrapWidth := termWidth - logDisplayWidth(indent) - 20 // leave room for key + if wrapWidth < logMinWrapWidth { + wrapWidth = logMinWrapWidth + } + + for _, p := range pairs { + if p.isList && len(p.listValues) > 0 { + fmt.Fprintf(w, "%s%s%s:%s\n", indent, ui.Gray, p.key, ui.Reset) + for _, v := range p.listValues { + fmt.Fprintf(w, "%s%s%s%s%s\n", indent, ui.Gray, listIndent, ui.Reset, v) + } + } else if p.value != "" { + fmt.Fprintf(w, "%s%s%s:%s %s\n", indent, ui.Gray, p.key, ui.Reset, p.value) + } + } +} + +func printLogEntriesNonTTY(w io.Writer, entries []oplog.Entry) { + for _, e := range entries { + ts := formatLogTimestamp(e.Timestamp) + detail := formatLogDetail(e, true) + dur := formatLogDuration(e.Duration) + + fmt.Fprintf(w, " %s %-9s %-96s %-7s %s\n", + ts, e.Command, detail, e.Status, dur) + + printLogAuditSkillLinesNonTTY(w, e) + } +} + +func printLogAuditSkillLinesNonTTY(w io.Writer, e oplog.Entry) { + if e.Command != "audit" || e.Args == nil { + return + } + + if failedSkills, ok := logArgStringSlice(e.Args, "failed_skills"); ok && len(failedSkills) > 0 { + printLogNamedSkillsNonTTY(w, "failed skills", failedSkills) + } + if warningSkills, ok := logArgStringSlice(e.Args, "warning_skills"); ok && len(warningSkills) > 0 { + printLogNamedSkillsNonTTY(w, "warning skills", warningSkills) + } + if lowSkills, ok := logArgStringSlice(e.Args, "low_skills"); ok && len(lowSkills) > 0 { + printLogNamedSkillsNonTTY(w, "low skills", lowSkills) + } + if infoSkills, ok := logArgStringSlice(e.Args, "info_skills"); ok && len(infoSkills) > 0 { + printLogNamedSkillsNonTTY(w, "info skills", infoSkills) + } +} + +func printLogNamedSkillsNonTTY(w io.Writer, label string, skills []string) { + const namesPerLine = 4 + for i := 0; i < len(skills); i += namesPerLine { + end := i + namesPerLine + if end > len(skills) { + end = len(skills) + } + + currentLabel := label + if i > 0 { + currentLabel = label + " (cont)" + } + fmt.Fprintf(w, " -> %s: %s\n", currentLabel, strings.Join(skills[i:end], ", ")) + } +} + +func printLogTableHeaderTTY(w io.Writer) { + header := fmt.Sprintf(" %-16s | %-9s | %-7s | %-7s", "TIME", "CMD", "STATUS", "DUR") + separator := fmt.Sprintf( + " %s-+-%s-+-%s-+-%s", + strings.Repeat("-", logTimeWidth), + strings.Repeat("-", logCmdWidth), + strings.Repeat("-", logStatusWidth), + strings.Repeat("-", logDurationWidth), + ) + + fmt.Fprintf(w, "%s%s%s\n", ui.Cyan, header, ui.Reset) + fmt.Fprintf(w, "%s%s%s\n", ui.Gray, separator, ui.Reset) +} + +func colorizeLogStatusCell(cell, status string) string { + switch status { + case "ok": + return ui.Green + cell + ui.Reset + case "error": + return ui.Red + cell + ui.Reset + case "partial": + return ui.Yellow + cell + ui.Reset + case "blocked": + return ui.Red + cell + ui.Reset + default: + return cell + } +} + +func logTerminalWidth() int { + width := pterm.GetTerminalWidth() + if width > 0 { + return width + } + return 120 +} + +func padLogCell(value string, width int) string { + current := logDisplayWidth(value) + if current >= width { + return value + } + return value + strings.Repeat(" ", width-current) +} + +func logDisplayWidth(s string) int { + return runewidth.StringWidth(logANSIRegex.ReplaceAllString(s, "")) +} diff --git a/cmd/skillshare/log_tui.go b/cmd/skillshare/log_tui.go new file mode 100644 index 000000000..40b61e339 --- /dev/null +++ b/cmd/skillshare/log_tui.go @@ -0,0 +1,254 @@ +package main + +import ( + "fmt" + "strings" + + "github.com/charmbracelet/bubbles/list" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +// logDetailLabelStyle uses a wider width than the shared tuiDetailLabelStyle +// because log keys like "severity(c/h/m/l/i):" are longer than skill detail keys. +var logDetailLabelStyle = lipgloss.NewStyle(). + Foreground(lipgloss.Color("8")). + Width(22) + +// logTUIModel is the bubbletea model for the interactive log viewer. +type logTUIModel struct { + list list.Model + modeLabel string // "global" or "project" + quitting bool +} + +// newLogTUIModel creates a new TUI model from log items. +func newLogTUIModel(items []logItem, logLabel, modeLabel string) logTUIModel { + listItems := make([]list.Item, len(items)) + for i, item := range items { + listItems[i] = item + } + + delegate := list.NewDefaultDelegate() + delegate.ShowDescription = true + // Title: no foreground — let embedded lipgloss colors (command, status) show through + delegate.Styles.NormalTitle = lipgloss.NewStyle().PaddingLeft(2) + delegate.Styles.NormalDesc = lipgloss.NewStyle(). + Foreground(lipgloss.Color("8")).PaddingLeft(2) + delegate.Styles.SelectedTitle = lipgloss.NewStyle(). + Bold(true). + Border(lipgloss.NormalBorder(), false, false, false, true). + BorderForeground(lipgloss.Color("6")).PaddingLeft(1) + delegate.Styles.SelectedDesc = lipgloss.NewStyle(). + Foreground(lipgloss.Color("8")). + Border(lipgloss.NormalBorder(), false, false, false, true). + BorderForeground(lipgloss.Color("6")).PaddingLeft(1) + + l := list.New(listItems, delegate, 0, 0) + l.Title = fmt.Sprintf("Log: %s (%s)", logLabel, modeLabel) + l.Styles.Title = lipgloss.NewStyle(). + Bold(true).Foreground(lipgloss.Color("6")) + l.SetShowStatusBar(true) + l.SetFilteringEnabled(true) + l.SetShowHelp(false) + l.SetStatusBarItemName("entry", "entries") + applyTUIFilterStyle(&l) + + return logTUIModel{ + list: l, + modeLabel: modeLabel, + } +} + +func (m logTUIModel) Init() tea.Cmd { + return nil +} + +func (m logTUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.list.SetSize(msg.Width, msg.Height-20) + return m, nil + + case tea.KeyMsg: + if m.list.FilterState() == list.Filtering { + break + } + + switch msg.String() { + case "q", "ctrl+c": + m.quitting = true + return m, tea.Quit + } + } + + var cmd tea.Cmd + m.list, cmd = m.list.Update(msg) + return m, cmd +} + +func (m logTUIModel) View() string { + if m.quitting { + return "" + } + + var b strings.Builder + + b.WriteString(m.list.View()) + b.WriteString("\n") + + // Detail panel for selected item + if item, ok := m.list.SelectedItem().(logItem); ok { + b.WriteString(renderLogDetailPanel(item)) + } + + help := "↑↓ navigate / filter q quit" + b.WriteString(tuiHelpStyle.Render(help)) + b.WriteString("\n") + + return b.String() +} + +// renderLogDetailPanel renders structured details for the selected log entry. +func renderLogDetailPanel(item logItem) string { + var b strings.Builder + b.WriteString(tuiSeparatorStyle.Render(" ─────────────────────────────────────────")) + b.WriteString("\n") + + row := func(label, value string) { + b.WriteString(" ") + b.WriteString(logDetailLabelStyle.Render(label)) + b.WriteString(tuiDetailValueStyle.Render(value)) + b.WriteString("\n") + } + + e := item.entry + + cyanStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("6")) + greenStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("2")) + redStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("1")) + yellowStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("3")) + + // Full timestamp + row("Timestamp:", e.Timestamp) + + // Command — cyan to match CLI palette + row("Command:", cyanStyle.Render(strings.ToUpper(e.Command))) + + // Status with color + statusDisplay := e.Status + switch e.Status { + case "ok": + statusDisplay = greenStyle.Render(e.Status) + case "error", "blocked": + statusDisplay = redStyle.Render(e.Status) + case "partial": + statusDisplay = yellowStyle.Render(e.Status) + } + row("Status:", statusDisplay) + + // Duration + if dur := formatLogDuration(e.Duration); dur != "" { + row("Duration:", dur) + } + + // Source log file + if item.source != "" { + row("Source:", item.source) + } + + // Message + if e.Message != "" { + row("Message:", e.Message) + } + + // Structured args via formatLogDetailPairs — colorize semantic values + pairs := formatLogDetailPairs(e) + for _, p := range pairs { + value := p.value + if p.isList && len(p.listValues) > 0 { + value = strings.Join(p.listValues, ", ") + } + if value == "" { + continue + } + + // Colorize only severity/status fields to avoid visual noise + switch { + case strings.Contains(p.key, "failed") || strings.Contains(p.key, "scan-errors"): + value = redStyle.Render(value) + case strings.Contains(p.key, "warning"): + value = yellowStyle.Render(value) + case p.key == "risk": + value = colorizeRiskValue(value, redStyle, yellowStyle, greenStyle) + case p.key == "threshold": + value = colorizeThreshold(value, redStyle, yellowStyle, greenStyle) + case strings.HasPrefix(p.key, "severity"): + value = colorizeSeverityBreakdown(value) + } + + row(p.key+":", value) + } + + return b.String() +} + +// colorizeSeverityBreakdown colors each number in "0/0/1/0/0" to match audit summary: +// critical=red, high=orange(208), medium=yellow, low=gray, info=default +func colorizeSeverityBreakdown(value string) string { + parts := strings.Split(value, "/") + if len(parts) != 5 { + return value + } + styles := []lipgloss.Style{ + lipgloss.NewStyle().Foreground(lipgloss.Color("1")), // critical — red + lipgloss.NewStyle().Foreground(lipgloss.Color("208")), // high — orange + lipgloss.NewStyle().Foreground(lipgloss.Color("3")), // medium — yellow + lipgloss.NewStyle().Foreground(lipgloss.Color("8")), // low — gray + lipgloss.NewStyle(), // info — default + } + for i, p := range parts { + parts[i] = styles[i].Render(p) + } + return strings.Join(parts, lipgloss.NewStyle().Foreground(lipgloss.Color("8")).Render("/")) +} + +// colorizeThreshold applies color based on audit threshold level. +func colorizeThreshold(value string, red, yellow, green lipgloss.Style) string { + upper := strings.ToUpper(value) + switch { + case upper == "CRITICAL" || upper == "HIGH": + return red.Render(value) + case upper == "MEDIUM": + return yellow.Render(value) + default: + return green.Render(value) + } +} + +// colorizeRiskValue applies color based on the risk label embedded in the value string. +// e.g. "CRITICAL (85/100)" → red, "LOW (15/100)" → green +func colorizeRiskValue(value string, red, yellow, green lipgloss.Style) string { + upper := strings.ToUpper(value) + switch { + case strings.HasPrefix(upper, "CRITICAL") || strings.HasPrefix(upper, "HIGH"): + return red.Render(value) + case strings.HasPrefix(upper, "MEDIUM"): + return yellow.Render(value) + default: + return green.Render(value) + } +} + +// runLogTUI starts the bubbletea TUI for the log viewer. +func runLogTUI(items []logItem, logLabel, modeLabel string) error { + if len(items) == 0 { + fmt.Printf("No %s log entries\n", strings.ToLower(logLabel)) + return nil + } + + model := newLogTUIModel(items, logLabel, modeLabel) + p := tea.NewProgram(model, tea.WithAltScreen()) + _, err := p.Run() + return err +} diff --git a/cmd/skillshare/log_tui_item.go b/cmd/skillshare/log_tui_item.go new file mode 100644 index 000000000..f93393a0e --- /dev/null +++ b/cmd/skillshare/log_tui_item.go @@ -0,0 +1,69 @@ +package main + +import ( + "fmt" + "strings" + + "skillshare/internal/oplog" +) + + +// logItem wraps oplog.Entry to implement bubbles/list.Item interface. +type logItem struct { + entry oplog.Entry + source string // "operations" or "audit" — identifies which log file +} + +// Title returns a one-line header: [2024-01-15 14:30] SYNC — ok +// Plain text only — embedded ANSI breaks bubbletea's DefaultDelegate truncation. +func (i logItem) Title() string { + ts := formatLogTimestamp(i.entry.Timestamp) + return fmt.Sprintf("[%s] %s — %s", + ts, + strings.ToUpper(i.entry.Command), + i.entry.Status, + ) +} + +// Description returns duration + one-line summary for the list delegate. +func (i logItem) Description() string { + var parts []string + + if dur := formatLogDuration(i.entry.Duration); dur != "" { + parts = append(parts, dur) + } + if detail := formatLogDetail(i.entry, true); detail != "" { + parts = append(parts, detail) + } + + if len(parts) == 0 { + return "" + } + return strings.Join(parts, " | ") +} + +// FilterValue returns searchable text for bubbletea's built-in fuzzy filter. +func (i logItem) FilterValue() string { + parts := []string{ + formatLogTimestamp(i.entry.Timestamp), + i.entry.Command, + i.entry.Status, + i.source, + } + if i.entry.Message != "" { + parts = append(parts, i.entry.Message) + } + if detail := formatLogDetail(i.entry, false); detail != "" { + parts = append(parts, detail) + } + return strings.Join(parts, " ") +} + +// toLogItems converts oplog entries to logItem slice. +func toLogItems(entries []oplog.Entry, source string) []logItem { + items := make([]logItem, len(entries)) + for i, e := range entries { + items[i] = logItem{entry: e, source: source} + } + return items +} diff --git a/skills/skillshare/SKILL.md b/skills/skillshare/SKILL.md index 1a6b2fd63..a987b6583 100644 --- a/skills/skillshare/SKILL.md +++ b/skills/skillshare/SKILL.md @@ -38,7 +38,7 @@ Force with `-p` (project) or `-g` (global). | **Targets** | `target add/remove/list` | ✓ (`-p`) | | **Security** | `audit [name]` | ✓ (`-p`) | | **Trash** | `trash list\|restore\|delete\|empty` | ✓ (`-p`) | -| **Log** | `log [--audit] [--tail N]` | ✓ (`-p`) | +| **Log** | `log [--json\|--no-tui] [--audit] [--tail N]` | ✓ (`-p`) | | **Backup** | `backup`, `restore` | ✗ | | **Web UI** | `ui` (`-g` global, `-p` project) | ✓ (`-p`) | | **Upgrade** | `upgrade [--cli\|--skill]` | — | diff --git a/skills/skillshare/references/log.md b/skills/skillshare/references/log.md index 387aa3165..22a6de1a3 100644 --- a/skills/skillshare/references/log.md +++ b/skills/skillshare/references/log.md @@ -4,14 +4,16 @@ JSONL-based persistent audit trail. All mutating commands (sync, install, uninst ## Usage +Default launches interactive TUI on TTY. Use `--json` (structured) or `--no-tui` (plain text) for programmatic access. + ```bash -skillshare log # Show operations + audit logs +skillshare log --json # JSONL output (recommended for scripts/AI) +skillshare log --no-tui # Plain text output skillshare log --audit # Audit log only skillshare log --tail 50 # Last 50 entries per section skillshare log --cmd sync # Show only sync entries skillshare log --status error # Show only errors skillshare log --since 2d # Entries from last 2 days -skillshare log --json # Output as JSONL skillshare log --clear # Clear operations log skillshare log --clear --audit # Clear audit log skillshare log -p # Project logs @@ -26,7 +28,8 @@ skillshare log -p # Project logs | `--cmd ` | Filter by command name (e.g. sync, install, audit) | | `--status ` | Filter by status (ok, error, partial, blocked) | | `--since ` | Filter by time (30m, 2h, 2d, 1w, or 2006-01-02) | -| `--json` | Output raw JSONL | +| `--json` | Output raw JSONL (recommended for scripts/AI) | +| `--no-tui` | Plain text output (skip interactive TUI) | | `--clear, -c` | Clear selected log file | | `-p, --project` | Project-level logs | | `-g, --global` | Global logs | diff --git a/website/docs/commands/log.md b/website/docs/commands/log.md index 3b45bb2bc..90496a25b 100644 --- a/website/docs/commands/log.md +++ b/website/docs/commands/log.md @@ -7,23 +7,41 @@ sidebar_position: 4 View persistent operations and audit logs for debugging and compliance. ```bash -skillshare log # Show operations + audit sections +skillshare log # Interactive TUI (default on TTY) skillshare log --audit # Show only audit log -skillshare log --tail 50 # Show last 50 entries per section +skillshare log --tail 50 # Show last 50 entries skillshare log --cmd sync # Show only sync entries skillshare log --status error # Show only errors skillshare log --since 2d # Entries from last 2 days skillshare log --json # Output as JSONL +skillshare log --no-tui # Plain text output skillshare log --clear # Clear operations log -skillshare log -p # Show project operations + audit logs +skillshare log -p # Project operations + audit logs ``` ## When to Use +- Browse and filter log entries interactively - Debug what happened during a failed operation - Review the audit trail for compliance or troubleshooting - Filter logs by command, status, or time range for investigation +## Interactive TUI + +On a TTY, `skillshare log` launches an interactive terminal UI with: + +- **Fuzzy filtering** — type to filter by timestamp, command, status, source, or detail content +- **Keyboard navigation** — arrow keys to browse, `q` to quit +- **Detail panel** — shows full timestamp, command, status, duration, source, and structured args for the selected entry +- **Merged view** — operations and audit entries are merged and sorted by time when viewing both + +Use `--no-tui` to skip the TUI and print plain text instead: + +```bash +skillshare log --no-tui # Plain text output +skillshare log --no-tui | less # Pipe to pager manually +``` + ## What Gets Logged Every mutating CLI and Web UI operation is recorded as a JSONL entry with timestamp, command, status, duration, and contextual args. @@ -75,7 +93,9 @@ skillshare log --json # All entries as JSONL skillshare log --json --cmd sync # Filtered JSONL ``` -## Example Output +## Example Output (Plain Text) + +When using `--no-tui` or in a non-TTY environment: ``` ┌─ skillshare log ────────────────────────────────────┐ @@ -161,6 +181,7 @@ If your repository root `.gitignore` also ignores `.skillshare/`, add matching u | `--status ` | Filter by status (`ok`, `error`, `partial`, `blocked`) | | `--since ` | Filter by time (`30m`, `2h`, `2d`, `1w`, or `2006-01-02`) | | `--json` | Output raw JSONL (one JSON object per line) | +| `--no-tui` | Disable interactive TUI, use plain text output | | `-c`, `--clear` | Clear selected log file (operations by default, audit with `--audit`) | | `-p`, `--project` | Use project-level log | | `-g`, `--global` | Use global log |