Documentation
¶
Overview ¶
Package design implements pattern-based CLI output visualization.
This file provides lipgloss-idiomatic box rendering. Instead of rendering borders piecemeal (top, content lines, bottom), we build complete content and apply box styling in one pass.
Package design implements pattern-based CLI output visualization ¶
cmd/internal/design/config.go
Package design implements pattern-based CLI output visualization ¶
Package design provides JSON serialization for structured output mode.
Package design implements pattern-based CLI output visualization ¶
Package design implements pattern-based CLI output visualization ¶
cmd/internal/design/render.go
Package design implements pattern-based CLI output visualization ¶
Package design implements a research-backed design system for CLI output.
Research foundations:
- Cognitive Load Theory (Sweller, 1988): Adaptive rendering based on cognitive load
- Tufte's Information Visualization (1983): Data-ink ratio, sparklines, small multiples
- Miller's Law (1956): Working memory limits inform error threshold heuristics
See docs/RESEARCH_FOUNDATIONS.md and docs/TUFTE_PRINCIPLES.md for detailed citations.
Package design implements pattern-based CLI output visualization.
This file provides the TaskView renderer - a clean separation between task data and its visual representation. This design enables: 1. Easy testing of rendering logic 2. Future migration to Bubble Tea (TaskView becomes a View() function) 3. Different renderers for different contexts (terminal, CI, JSON)
Package design implements pattern-based CLI output visualization.
This file defines the new lipgloss-idiomatic theming system. Colors use lipgloss.Color format (color names, hex, or 256-color numbers). Styles are composed using lipgloss methods, not manual ANSI escapes.
Index ¶
- Constants
- func ApplyMonochromeDefaults(cfg *Config)
- func DefaultThemes() map[string]*Config
- func IsInteractiveTerminal() bool
- func IsValidPatternType(s string) bool
- func JoinVertical(components ...string) string
- func PadLeft(s string, width int) string
- func PadRight(s string, width int) string
- func RenderBox(theme *Theme, title string, lines ...string) string
- func RenderDirectMessage(cfg *Config, messageType, customIcon, message string, indentLevel int) string
- func RenderInlineStatus(theme *Theme, status, message, duration string) string
- func ToJSON(p Pattern, metadata JSONMetadata) ([]byte, error)
- func VisualWidth(s string) int
- type BorderChars
- type BorderStyle
- type Box
- type BoxLayout
- type CognitiveLoadContext
- type Color
- type Comparison
- type ComparisonItem
- type CompiledPattern
- type ComplexityDashboard
- type ComplexityHotspot
- type ComplexityMetric
- type Config
- func (c *Config) BuildStyle(elementName string, fallbackColorKey ...string) lipgloss.Style
- func (c *Config) GetColor(colorKeyOrName string, elementName ...string) lipgloss.Color
- func (c *Config) GetColorObj(colorKeyOrName string) Color
- func (c *Config) GetElementStyle(elementName string) ElementStyleDef
- func (c *Config) GetIcon(iconKey string) string
- func (c *Config) GetIndentation(level int) string
- func (c *Config) GetStyle(colorKey string) lipgloss.Style
- func (c *Config) GetStyleFromElement(element ElementStyleDef, fallbackColorKey string) lipgloss.Style
- func (c *Config) GetStyleWithBackground(fgKey, bgKey string) lipgloss.Style
- func (c *Config) GetStyleWithBold(colorKey string) lipgloss.Style
- func (c *Config) GetStyleWithFallback(colorKeys ...string) lipgloss.Style
- func (c *Config) NewBoxLayout(termWidth int) *BoxLayout
- func (c *Config) ResetColor() lipgloss.Color
- func (c *Config) ResolveBorderChars() BorderChars
- type ConstraintViolation
- type DensityMode
- type DesignTokens
- type ElementStyleDef
- type Housekeeping
- type HousekeepingCheck
- type HousekeepingCheckType
- type Inventory
- type InventoryItem
- type JSONMetadata
- type JSONOutput
- type Leaderboard
- type LeaderboardItem
- type LineContext
- type LineData
- type OutputLine
- type Pattern
- type PatternMatcher
- func (pm *PatternMatcher) ClassifyOutputLine(line, cmd string, args []string) (string, LineContext)
- func (pm *PatternMatcher) DetectCommandIntent(cmd string, args []string) string
- func (pm *PatternMatcher) DetermineCognitiveLoad(lines []OutputLine) CognitiveLoadContext
- func (pm *PatternMatcher) FindSimilarLines(lines []OutputLine) map[string][]OutputLine
- type PatternType
- type PatternsRepo
- type QualityCategory
- type QualityIssue
- type QualityReport
- type Sparkline
- type Summary
- type SummaryItem
- type Task
- func (t *Task) AddOutputLine(content, lineType string, context LineContext)
- func (t *Task) Complete(exitCode int)
- func (t *Task) GetOutputLinesSnapshot() []OutputLine
- func (t *Task) ProcessOutputLines(fn func(lines []OutputLine))
- func (t *Task) RenderEndLine() string
- func (t *Task) RenderOutputLine(line OutputLine) string
- func (t *Task) RenderStartLine() string
- func (t *Task) RenderSummary() string
- func (t *Task) UpdateTaskContext()
- type TaskContext
- type TaskData
- type TaskView
- type TestTable
- type TestTableItem
- type Theme
- type ThemeBorder
- type ThemeColors
- type ThemeIcons
- type ThemeStyles
- type ToolConfig
Constants ¶
const ( IconStart = "[START]" IconSuccess = "[SUCCESS]" IconWarning = "[WARNING]" IconFailed = "[FAILED]" IconInfo = "[INFO]" IconBullet = "*" )
Icon constants for monochrome/ASCII mode.
const ( ColorKeyProcess = "Process" ColorKeySuccess = "Success" ColorKeyWarning = "Warning" ColorKeyError = "Error" ColorKeyMuted = "Muted" )
Color key constants for theme color lookups.
const ( IconCharError = "✗" IconCharWarning = "⚠" BorderCharDash = "─" )
Icon character constants.
const ( TypeDetail = "detail" // Default for unclassified lines. TypeError = "error" // Error messages. TypeWarning = "warning" // Warning messages. TypeSuccess = "success" // Success indicators. TypeInfo = "info" // Informational messages (e.g., from stderr not being errors). TypeProgress = "progress" // Progress updates. TypeSummary = "summary" // Lines that are part of a generated summary. )
LineType constants for consistent classification of output lines.
const ( StatusRunning = "running" // Task is currently executing. StatusSuccess = "success" // Task completed successfully. StatusWarning = "warning" // Task completed with warnings. StatusError = "error" // Task failed or completed with errors. )
TaskStatus constants for consistent representation of a task's overall status.
const ( MessageTypeRaw = "raw" // Raw output without any formatting MessageTypeH1 = "h1" // Level 1 header MessageTypeH2 = "h2" // Level 2 header MessageTypeH3 = "h3" // Level 3 header MessageTypeSuccess = "success" // Success message (alias for StatusSuccess) MessageTypeWarning = "warning" // Warning message (alias for StatusWarning) MessageTypeError = "error" // Error message (alias for StatusError) MessageTypeInfo = "info" // Info message (alias for TypeInfo) )
MessageType constants for RenderDirectMessage to provide type safety and prevent typos.
const ANSIBrightWhite = "\033[0;97m"
ANSI color code constant.
const ANSIReset = "\033[0m"
ANSIReset is the escape code to reset all styling.
const DefaultSpinnerChars = "-\\|/"
Default spinner characters for ASCII mode.
const MessageTypeHeader = "header"
MessageType constant for legacy support.
Variables ¶
This section is empty.
Functions ¶
func ApplyMonochromeDefaults ¶
func ApplyMonochromeDefaults(cfg *Config)
func DefaultThemes ¶
DefaultThemes returns a map of all built-in themes. This is the single source of truth for default theme definitions.
func IsInteractiveTerminal ¶
func IsInteractiveTerminal() bool
IsInteractiveTerminal checks if stdout is connected to a terminal.
func IsValidPatternType ¶
IsValidPatternType checks if a string represents a valid pattern type.
func JoinVertical ¶ added in v0.2.1
JoinVertical composes multiple rendered strings vertically using lipgloss. This is useful for combining multiple patterns or sections into a single output. The components are joined with proper alignment and spacing.
Example:
summary := renderSummary() testTable := renderTestTable() combined := JoinVertical(summary, testTable)
func PadLeft ¶ added in v0.2.1
PadLeft pads a string to the specified visual width, using spaces. This correctly handles Unicode characters, emojis, and wide characters that occupy multiple terminal cells. Replaces fmt.Sprintf("%*s", width, s) with correct rune width handling.
func PadRight ¶ added in v0.2.1
PadRight pads a string to the specified visual width, using spaces. This correctly handles Unicode characters, emojis, and wide characters that occupy multiple terminal cells. Replaces fmt.Sprintf("%-*s", width, s) with correct rune width handling.
func RenderBox ¶ added in v0.2.1
RenderBox is a convenience function for simple box rendering. Usage: RenderBox(theme, "Title", "Line 1", "Line 2")
func RenderDirectMessage ¶
func RenderDirectMessage(cfg *Config, messageType, customIcon, message string, indentLevel int) string
RenderDirectMessage creates the formatted status line.
func RenderInlineStatus ¶ added in v0.2.1
RenderInlineStatus renders a status line (icon + message + optional duration). This is commonly used for task completion messages.
func ToJSON ¶
func ToJSON(p Pattern, metadata JSONMetadata) ([]byte, error)
ToJSON converts a Pattern to JSON output format.
func VisualWidth ¶ added in v0.2.1
VisualWidth returns the display width of a string in terminal cells. This correctly handles Unicode characters, emojis, and wide characters that occupy multiple terminal cells. This is a wrapper around lipgloss.Width for consistency.
Types ¶
type BorderChars ¶ added in v0.2.1
type BorderChars struct {
TopLeft string
TopRight string
BottomLeft string
BottomRight string
Horizontal string
Vertical string
}
BorderChars encapsulates all border characters for consistent rendering.
type BorderStyle ¶
type BorderStyle string
BorderStyle defines the type of border to use for task output.
const ( BorderLeftOnly BorderStyle = "left_only" BorderLeftDouble BorderStyle = "left_double" BorderHeaderBox BorderStyle = "header_box" BorderFull BorderStyle = "full_box" BorderNone BorderStyle = "none" BorderASCII BorderStyle = "ascii" )
type Box ¶ added in v0.2.1
type Box struct {
// contains filtered or unexported fields
}
Box renders content inside a styled box using lipgloss. This is the idiomatic way to use lipgloss - build content, then style.
func (*Box) Footer ¶ added in v0.2.1
Footer sets a footer line (rendered after content, before bottom border).
func (*Box) String ¶ added in v0.2.1
String renders the box to a string. This is where lipgloss does the work - we build content, apply style once.
type BoxLayout ¶ added in v0.2.1
type BoxLayout struct {
TotalWidth int // Total terminal width
ContentWidth int // Available width for content (TotalWidth - borders - padding)
LeftPadding int // Left padding inside box
RightPadding int // Right padding inside box
BorderColor lipgloss.Color // Color for borders
BorderChars BorderChars // Border characters
BorderStyle lipgloss.Style // Lip Gloss style for borders
Config *Config // Reference to config for border chars
}
BoxLayout is the single source of truth for box dimensions. It centralizes all box-related calculations to eliminate magic numbers and ensure consistent rendering across all box functions.
func (*BoxLayout) RenderBottomBorder ¶ added in v0.2.1
RenderBottomBorder renders the bottom border line. Uses lipgloss for consistent border rendering.
func (*BoxLayout) RenderContentLine ¶ added in v0.2.1
RenderContentLine renders a single content line with proper padding and borders. Uses lipgloss for consistent rendering with automatic width handling.
func (*BoxLayout) RenderTopBorder ¶ added in v0.2.1
RenderTopBorder renders the top border line with optional title. Uses lipgloss for consistent border rendering.
type CognitiveLoadContext ¶
type CognitiveLoadContext string
CognitiveLoadContext represents the user's likely cognitive state when processing information.
const ( LoadLow CognitiveLoadContext = "low" // Simple, routine information. LoadMedium CognitiveLoadContext = "medium" // Standard operational information. LoadHigh CognitiveLoadContext = "high" // Complex errors, dense information requiring focus. )
type Color ¶
type Color struct {
// contains filtered or unexported fields
}
Color wraps an ANSI escape code for safer and more readable color handling. Use Sprint to wrap text in color codes, which automatically resets styling.
type Comparison ¶
type Comparison struct {
Label string // Title for the comparison
Changes []ComparisonItem // Items being compared
}
Comparison represents a before/after comparison of metrics. Useful for showing changes over time or between versions.
func (*Comparison) PatternType ¶
func (c *Comparison) PatternType() PatternType
PatternType implements the Pattern interface.
func (*Comparison) Render ¶
func (c *Comparison) Render(cfg *Config) string
Render creates the comparison visualization.
type ComparisonItem ¶
type ComparisonItem struct {
Label string // Metric label
Before string // Before value (formatted)
After string // After value (formatted)
Change float64 // Numeric change (positive or negative)
Unit string // Unit for the change (e.g., "%", "MB", "ms")
}
ComparisonItem represents a single metric comparison.
type CompiledPattern ¶
CompiledPattern holds a precompiled regex pattern with metadata.
type ComplexityDashboard ¶ added in v0.2.1
type ComplexityDashboard struct {
Title string // Section title (default: "COMPLEXITY")
Metrics []ComplexityMetric // Current metrics with historical comparison
Hotspots []ComplexityHotspot // Top files by combined size x complexity score
TrendWindow string // Time window for comparison (e.g., "4w")
ShowSparklines bool // Whether to show inline sparklines for trends
}
ComplexityDashboard represents a unified complexity metrics view with trend tracking. Combines file size metrics with cyclomatic complexity and surfaces actionable hotspots.
func (*ComplexityDashboard) PatternType ¶ added in v0.2.1
func (c *ComplexityDashboard) PatternType() PatternType
PatternType returns the pattern type identifier.
func (*ComplexityDashboard) Render ¶ added in v0.2.1
func (c *ComplexityDashboard) Render(cfg *Config) string
Render formats the complexity dashboard using the provided theme.
type ComplexityHotspot ¶ added in v0.2.1
type ComplexityHotspot struct {
Path string // File path
LOC int // Lines of code
MaxComplexity int // Highest cyclomatic complexity in the file
Score int // Combined score (LOC x MaxComplexity)
}
ComplexityHotspot represents a file that needs attention based on size and complexity.
type ComplexityMetric ¶ added in v0.2.1
type ComplexityMetric struct {
Label string // Metric name (e.g., "Files >500 LOC")
Current float64 // Current value
Previous float64 // Previous value (from trend window ago)
Trend string // "improving", "stable", "degrading"
Unit string // Optional unit (e.g., "files", "avg")
LowerBetter bool // Whether lower values are better (true for most complexity metrics)
History []float64 // Optional: historical values for sparkline (8 values for 8 weeks)
}
ComplexityMetric represents a single complexity metric with trend data.
type Config ¶
type Config struct {
ThemeName string `yaml:"-"`
IsMonochrome bool `yaml:"-"`
CI bool `yaml:"-"` // Explicit CI mode flag (takes precedence over heuristics)
// DesignTokens provides centralized, semantic design values
// This is the new extensible system (Phase 1)
Tokens *DesignTokens `yaml:"-"`
Style struct {
UseBoxes bool `yaml:"use_boxes"`
Indentation string `yaml:"indentation"`
ShowTimestamps bool `yaml:"show_timestamps"`
NoTimer bool `yaml:"no_timer"`
Density string `yaml:"density"`
NoSpinner bool `yaml:"no_spinner"`
SpinnerInterval int `yaml:"spinner_interval"`
HeaderWidth int `yaml:"header_width"` // Visual width of header content (default: 40)
} `yaml:"style"`
Border struct {
TaskStyle BorderStyle `yaml:"task_style"`
HeaderChar string `yaml:"header_char"`
VerticalChar string `yaml:"vertical_char"`
TopCornerChar string `yaml:"top_corner_char"`
TopRightChar string `yaml:"top_right_char"`
BottomCornerChar string `yaml:"bottom_corner_char"`
BottomRightChar string `yaml:"bottom_right_char"`
FooterContinuationChar string `yaml:"footer_continuation_char"`
TableHChar string `yaml:"table_h_char"`
TableVChar string `yaml:"table_v_char"`
TableXChar string `yaml:"table_x_char"`
TableCornerTL string `yaml:"table_corner_tl"`
TableCornerTR string `yaml:"table_corner_tr"`
TableCornerBL string `yaml:"table_corner_bl"`
TableCornerBR string `yaml:"table_corner_br"`
TableTDown string `yaml:"table_t_down"`
TableTUp string `yaml:"table_t_up"`
TableTLeft string `yaml:"table_t_left"`
TableTRight string `yaml:"table_t_right"`
} `yaml:"border"`
Colors struct {
Process lipgloss.Color `yaml:"process"`
Success lipgloss.Color `yaml:"success"`
Warning lipgloss.Color `yaml:"warning"`
Error lipgloss.Color `yaml:"error"`
Detail lipgloss.Color `yaml:"detail"`
Muted lipgloss.Color `yaml:"muted"`
Reset lipgloss.Color `yaml:"reset"`
White lipgloss.Color `yaml:"white,omitempty"`
GreenFg lipgloss.Color `yaml:"green_fg,omitempty"`
BlueFg lipgloss.Color `yaml:"blue_fg,omitempty"`
BlueBg lipgloss.Color `yaml:"blue_bg,omitempty"`
PaleBlue lipgloss.Color `yaml:"pale_blue,omitempty"`
Bold lipgloss.Color `yaml:"bold,omitempty"`
Italic lipgloss.Color `yaml:"italic,omitempty"`
} `yaml:"colors"`
Icons struct {
Start string `yaml:"start"`
Success string `yaml:"success"`
Warning string `yaml:"warning"`
Error string `yaml:"error"`
Info string `yaml:"info"`
Bullet string `yaml:"bullet"`
} `yaml:"icons"`
Elements map[string]ElementStyleDef `yaml:"elements"`
Patterns PatternsRepo `yaml:"patterns"`
Tools map[string]*ToolConfig `yaml:"tools"`
CognitiveLoad struct {
AutoDetect bool `yaml:"auto_detect"`
Default CognitiveLoadContext `yaml:"default"`
} `yaml:"cognitive_load"`
ComplexityThresholds struct {
VeryHigh int `yaml:"very_high"` // Output lines threshold for complexity level 5
High int `yaml:"high"` // Output lines threshold for complexity level 4
Medium int `yaml:"medium"` // Output lines threshold for complexity level 3
ErrorCountHigh int `yaml:"error_count_high"` // Error count threshold for high cognitive load
WarningCountMedium int `yaml:"warning_count_medium"` // Warning count threshold for medium cognitive load
} `yaml:"complexity_thresholds"`
Tests struct {
SparkbarFilled string `yaml:"sparkbar_filled"`
SparkbarEmpty string `yaml:"sparkbar_empty"`
SparkbarLength int `yaml:"sparkbar_length"`
ShowPercentage bool `yaml:"show_percentage"`
NoTestIcon string `yaml:"no_test_icon"`
NoTestColor string `yaml:"no_test_color"`
CoverageGoodMin float64 `yaml:"coverage_good_min"` // Minimum coverage for "good" (green)
CoverageWarningMin float64 `yaml:"coverage_warning_min"` // Minimum coverage for "warning" (yellow)
} `yaml:"tests"`
// contains filtered or unexported fields
}
Config holds theme configuration.
func ASCIIMinimalTheme ¶
func ASCIIMinimalTheme() *Config
func DeepCopyConfig ¶
DeepCopyConfig creates a deep copy of the Config using JSON marshal/unmarshal. This automatically handles all fields, preventing bugs when new fields are added. The small overhead of JSON encoding is acceptable since this is not in a hot path.
func DefaultConfig ¶
func DefaultConfig() *Config
func NoColorConfig ¶
func NoColorConfig() *Config
func UnicodeVibrantTheme ¶
func UnicodeVibrantTheme() *Config
func (*Config) BuildStyle ¶ added in v0.2.1
BuildStyle is a convenience method that gets an element style by name and builds a lipgloss.Style from it. Styles are cached for performance. This combines GetElementStyle and GetStyleFromElement.
func (*Config) GetColorObj ¶
GetColorObj returns a Color wrapper for the given color key. This provides a safer interface for color handling with automatic reset. Example: cfg.GetColorObj("Error").Sprint("Error message").
func (*Config) GetElementStyle ¶
func (c *Config) GetElementStyle(elementName string) ElementStyleDef
func (*Config) GetIndentation ¶
func (*Config) GetStyle ¶ added in v0.2.1
GetStyle returns a lipgloss.Style for the given color key. Styles are cached for performance - subsequent calls return the same Style object. Returns a style with foreground color set, or empty style if monochrome or color not found.
func (*Config) GetStyleFromElement ¶ added in v0.2.1
func (c *Config) GetStyleFromElement(element ElementStyleDef, fallbackColorKey string) lipgloss.Style
GetStyleFromElement builds a lipgloss.Style from an ElementStyleDef. This is the unified way to convert element styles to lipgloss styles. Parameters:
- element: The ElementStyleDef containing style configuration
- fallbackColorKey: Used if element.ColorFG is empty
Handles: foreground color, background color, bold, italic, and underline.
func (*Config) GetStyleWithBackground ¶ added in v0.2.1
GetStyleWithBackground returns a lipgloss.Style with foreground and background colors.
func (*Config) GetStyleWithBold ¶ added in v0.2.1
GetStyleWithBold returns a lipgloss.Style with color and bold text.
func (*Config) GetStyleWithFallback ¶ added in v0.2.1
GetStyleWithFallback returns the first available lipgloss.Style from the provided color keys. If all color keys are empty or unavailable, an empty style is returned. This helper keeps color fallback logic centralized for callers that want a preferred color but need a graceful secondary option.
func (*Config) NewBoxLayout ¶ added in v0.2.1
NewBoxLayout creates a BoxLayout with single-point dimension calculation. termWidth is the terminal width. If 0 or negative, defaults to 80.
func (*Config) ResetColor ¶
func (*Config) ResolveBorderChars ¶ added in v0.2.1
func (c *Config) ResolveBorderChars() BorderChars
ResolveBorderChars returns the appropriate border characters with matching corners.
type ConstraintViolation ¶ added in v0.2.1
type ConstraintViolation struct {
Code string // Short code (e.g., "OTC")
Message string // Human-readable message
Severity string // "error" or "warning"
Details int // Actual value
Limit int // Limit that was exceeded
}
ConstraintViolation represents a violated constraint.
type DensityMode ¶
type DensityMode string
DensityMode controls the space-efficiency of pattern rendering. Based on Tufte's data-ink ratio principle: maximize information per line.
const ( // DensityDetailed shows one item per line with full context (current default). DensityDetailed DensityMode = "detailed" // DensityBalanced shows 2 columns where appropriate. DensityBalanced DensityMode = "balanced" // DensityCompact shows 3 columns with minimal spacing. DensityCompact DensityMode = "compact" )
type DesignTokens ¶ added in v0.2.1
type DesignTokens struct {
Colors struct {
// Status colors (semantic naming)
Process lipgloss.Color `yaml:"process"` // Primary process/task color
Success lipgloss.Color `yaml:"success"` // Success state
Warning lipgloss.Color `yaml:"warning"` // Warning state
Error lipgloss.Color `yaml:"error"` // Error state
Detail lipgloss.Color `yaml:"detail"` // Detail text
Muted lipgloss.Color `yaml:"muted"` // Muted/secondary text
Reset lipgloss.Color `yaml:"reset"` // Reset/clear formatting
// Base colors
White lipgloss.Color `yaml:"white,omitempty"`
GreenFg lipgloss.Color `yaml:"green_fg,omitempty"`
BlueFg lipgloss.Color `yaml:"blue_fg,omitempty"`
BlueBg lipgloss.Color `yaml:"blue_bg,omitempty"`
// Component-specific colors (semantic naming)
Spinner lipgloss.Color `yaml:"spinner,omitempty"` // Spinner active state (was PaleBlue)
// Text styling
Bold lipgloss.Color `yaml:"bold,omitempty"`
Italic lipgloss.Color `yaml:"italic,omitempty"`
} `yaml:"colors"`
Styles struct {
Box lipgloss.Style `yaml:"-"` // Pre-configured box style
Header lipgloss.Style `yaml:"-"` // Pre-configured header style
Content lipgloss.Style `yaml:"-"` // Pre-configured content style
} `yaml:"styles"`
Spacing struct {
Progress int `yaml:"progress,omitempty"` // Progress indicator spacing
Indent int `yaml:"indent,omitempty"` // Indentation level spacing
} `yaml:"spacing"`
Typography struct {
HeaderWidth int `yaml:"header_width,omitempty"` // Visual width of headers
} `yaml:"typography"`
}
DesignTokens centralizes all design values with semantic naming. This provides a single source of truth for design values and enables extensibility without code changes. Uses Lip Gloss types for proper color/style handling.
func (*DesignTokens) GetColor ¶ added in v0.2.1
func (dt *DesignTokens) GetColor(name string) lipgloss.Color
GetColor returns the lipgloss.Color for a color token by name. This provides type-safe access to color values.
func (*DesignTokens) GetColorString ¶ added in v0.2.1
func (dt *DesignTokens) GetColorString(name string) string
GetColorString returns the ANSI color code string for a color token. This is a convenience method for backwards compatibility.
type ElementStyleDef ¶
type ElementStyleDef struct {
Text string `yaml:"text,omitempty"`
Prefix string `yaml:"prefix,omitempty"`
Suffix string `yaml:"suffix,omitempty"`
TextContent string `yaml:"text_content,omitempty"`
TextCase string `yaml:"text_case,omitempty"`
TextStyle []string `yaml:"text_style,omitempty"`
ColorFG string `yaml:"color_fg,omitempty"`
ColorBG string `yaml:"color_bg,omitempty"`
IconKey string `yaml:"icon_key,omitempty"`
BulletChar string `yaml:"bullet_char,omitempty"`
LineChar string `yaml:"line_char,omitempty"`
LineLengthType string `yaml:"line_length_type,omitempty"`
FramingCharStart string `yaml:"framing_char_start,omitempty"`
FramingCharEnd string `yaml:"framing_char_end,omitempty"`
AdditionalChars string `yaml:"additional_chars,omitempty"`
DateTimeFormat string `yaml:"date_time_format,omitempty"`
}
ElementStyleDef defines visual styling properties for a specific UI element.
type Housekeeping ¶ added in v0.2.1
type Housekeeping struct {
Title string // Section title (default: "HOUSEKEEPING")
Checks []HousekeepingCheck // Individual hygiene checks
}
Housekeeping represents a collection of project hygiene checks. These are "clean up your room" items - not blocking, but worth tracking.
func (*Housekeeping) FailCount ¶ added in v0.2.1
func (h *Housekeeping) FailCount() int
FailCount returns the number of failing checks.
func (*Housekeeping) PassCount ¶ added in v0.2.1
func (h *Housekeeping) PassCount() int
PassCount returns the number of passing checks.
func (*Housekeeping) PatternType ¶ added in v0.2.1
func (h *Housekeeping) PatternType() PatternType
PatternType returns the pattern type identifier.
func (*Housekeeping) Render ¶ added in v0.2.1
func (h *Housekeeping) Render(cfg *Config) string
Render formats the housekeeping section using the provided theme.
func (*Housekeeping) WarnCount ¶ added in v0.2.1
func (h *Housekeeping) WarnCount() int
WarnCount returns the number of warning checks.
type HousekeepingCheck ¶ added in v0.2.1
type HousekeepingCheck struct {
Name string // Check name (e.g., "Markdown files", "TODO comments")
Status string // "pass", "warn", "fail"
Current int // Current value
Threshold int // Threshold value (for comparison)
Details string // Additional details (e.g., "7 older than 90 days")
Items []string // Optional: specific files or issues needing attention
}
HousekeepingCheck represents a single hygiene check result.
func NewHousekeepingCheck ¶ added in v0.2.1
func NewHousekeepingCheck(name string, current, threshold int) HousekeepingCheck
NewHousekeepingCheck creates a check with sensible defaults.
type HousekeepingCheckType ¶ added in v0.2.1
type HousekeepingCheckType string
HousekeepingCheckType represents standard check types for consistency.
const ( // CheckMarkdownCount tracks documentation sprawl. CheckMarkdownCount HousekeepingCheckType = "markdown_count" // CheckTodoComments tracks technical debt markers. CheckTodoComments HousekeepingCheckType = "todo_comments" // CheckOrphanTests finds test files without corresponding source. CheckOrphanTests HousekeepingCheckType = "orphan_tests" // CheckPackageDocs verifies package documentation exists. CheckPackageDocs HousekeepingCheckType = "package_docs" // CheckDeadCode identifies unused exports. CheckDeadCode HousekeepingCheckType = "dead_code" // CheckDeprecatedDeps finds deprecated dependencies. CheckDeprecatedDeps HousekeepingCheckType = "deprecated_deps" // CheckLicenseHeaders verifies required license headers. CheckLicenseHeaders HousekeepingCheckType = "license_headers" // CheckGeneratedFreshness checks if generated files are stale. CheckGeneratedFreshness HousekeepingCheckType = "generated_freshness" )
type Inventory ¶
type Inventory struct {
Label string // Title for the inventory
Items []InventoryItem // Items in the inventory
}
Inventory represents a list of generated artifacts or files. Useful for showing build outputs, generated files, or deployment artifacts.
func (*Inventory) PatternType ¶
func (i *Inventory) PatternType() PatternType
PatternType implements the Pattern interface.
type InventoryItem ¶
type InventoryItem struct {
Name string // File or artifact name
Size string // Formatted size (e.g., "2.3MB", "450KB")
Path string // Optional: full path or additional context
}
InventoryItem represents a single file or artifact.
type JSONMetadata ¶
type JSONMetadata struct {
ExitCode int `json:"exit_code"`
Duration string `json:"duration"`
DurationMs int64 `json:"duration_ms"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
Command string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
Label string `json:"label,omitempty"`
Classification string `json:"classification,omitempty"`
}
JSONMetadata contains metadata about the command execution and pattern.
type JSONOutput ¶
type JSONOutput struct {
Version string `json:"version"`
PatternType string `json:"pattern_type"`
Metadata JSONMetadata `json:"metadata"`
Data map[string]interface{} `json:"data"`
}
JSONOutput represents the structured JSON output format for AI/automation consumption.
type Leaderboard ¶
type Leaderboard struct {
Label string // Title for the leaderboard (e.g., "Slowest Tests")
MetricName string // Name of the metric being ranked (e.g., "Duration", "Size", "Warnings")
Items []LeaderboardItem // Ranked items
Direction string // "highest" or "lowest" - what's being shown
TotalCount int // Total items before filtering to top N
ShowRank bool // Whether to show rank numbers
}
Leaderboard represents a ranked list of items sorted by a specific metric. Shows only the top/bottom N items to highlight optimization targets or achievements.
Use cases:
- Slowest N tests (optimization targets)
- Largest N binaries (size analysis)
- Files with most linting warnings (quality hotspots)
- Packages with lowest coverage (test gap identification)
- Top contributors by commits
func (*Leaderboard) PatternType ¶
func (l *Leaderboard) PatternType() PatternType
PatternType implements the Pattern interface.
func (*Leaderboard) Render ¶
func (l *Leaderboard) Render(cfg *Config) string
Render creates the leaderboard visualization.
type LeaderboardItem ¶
type LeaderboardItem struct {
Name string // Item name (e.g., test name, file name, package name)
Metric string // Formatted metric value (e.g., "2.3s", "45MB", "12 warnings")
Value float64 // Numeric value for ranking/comparison
Rank int // Position in ranking (1-based)
Context string // Additional context or details
}
LeaderboardItem represents a single entry in a leaderboard.
type LineContext ¶
type LineContext struct {
// CognitiveLoad at the point this line is processed/displayed.
CognitiveLoad CognitiveLoadContext
// Importance rating (1-5) for prioritization in display or summary.
Importance int
// IsHighlighted indicates if the line should receive special emphasis.
IsHighlighted bool
// IsSummary indicates if this line is part of a generated summary.
IsSummary bool
// IsInternal indicates if this error originated from fo itself (not the wrapped command).
IsInternal bool
}
LineContext holds information about the context of an individual output line used for fine-grained styling decisions.
type LineData ¶ added in v0.2.1
type LineData struct {
Content string
Type string // "detail", "error", "warning", "info", "success"
Indent int
}
LineData holds data for a single output line.
type OutputLine ¶
type OutputLine struct {
// Content and metadata
Content string
Type string // "detail", "error", "warning", "success", "info", "progress"
Timestamp time.Time
Indentation int
// Context for cognitive load-based formatting
Context LineContext
}
OutputLine represents a classified line of command output.
type Pattern ¶
type Pattern interface {
// Render returns the formatted string representation of the pattern
// using the provided theme configuration.
// The Config parameter controls visual presentation (colors, icons, density, etc.)
// while the pattern itself controls semantic content (data, structure, meaning).
Render(cfg *Config) string
// PatternType returns the standard type identifier for this pattern.
// This enables type-based routing, validation, and theme selection.
PatternType() PatternType
}
Pattern is the interface that all output patterns implement. Patterns represent different ways of visualizing command output data.
Contract:
- Patterns are semantic: they represent what to show, not how to show it
- Patterns are theme-independent: the same pattern can be rendered with different themes
- Patterns are composable: multiple patterns can be combined to create dashboards
- Patterns implement Render() which takes a Config (theme) and returns formatted output
type PatternMatcher ¶
type PatternMatcher struct {
Config *Config
// contains filtered or unexported fields
}
PatternMatcher provides intelligent pattern detection for commands and output.
func NewPatternMatcher ¶
func NewPatternMatcher(config *Config) *PatternMatcher
NewPatternMatcher creates a pattern matcher with the given configuration. All regex patterns are precompiled at initialization time for performance.
func (*PatternMatcher) ClassifyOutputLine ¶
func (pm *PatternMatcher) ClassifyOutputLine(line, cmd string, args []string) (string, LineContext)
ClassifyOutputLine determines the type of an output line. Uses fast-path string prefix checks before falling back to regex patterns for performance. When multiple patterns match, the category with the highest accumulated score wins.
func (*PatternMatcher) DetectCommandIntent ¶
func (pm *PatternMatcher) DetectCommandIntent(cmd string, args []string) string
DetectCommandIntent identifies the purpose of a command.
func (*PatternMatcher) DetermineCognitiveLoad ¶
func (pm *PatternMatcher) DetermineCognitiveLoad(lines []OutputLine) CognitiveLoadContext
DetermineCognitiveLoad analyzes output to determine overall cognitive load.
func (*PatternMatcher) FindSimilarLines ¶
func (pm *PatternMatcher) FindSimilarLines(lines []OutputLine) map[string][]OutputLine
FindSimilarLines groups similar output lines for summarization.
type PatternType ¶
type PatternType string
PatternType represents the six standard semantic pattern types in the design system. These types map semantic meaning (what to show) to visual presentation (how to show it).
const ( // PatternTypeSparkline represents word-sized trend graphics using Unicode blocks. // Use for: test duration trends, coverage changes, build size progression, error count trends. PatternTypeSparkline PatternType = "sparkline" // PatternTypeLeaderboard represents ranked lists showing top/bottom N items by metric. // Use for: slowest tests, largest binaries, files with most warnings, packages with lowest coverage. PatternTypeLeaderboard PatternType = "leaderboard" // PatternTypeTestTable represents comprehensive test results with status and timing. // Use for: complete test suite results, package-level test summaries. PatternTypeTestTable PatternType = "test-table" // PatternTypeSummary represents high-level summaries with key metrics and counts. // Use for: at-a-glance understanding of overall results, rollup statistics. PatternTypeSummary PatternType = "summary" // PatternTypeComparison represents before/after comparisons of metrics. // Use for: showing changes over time, version comparisons, delta analysis. PatternTypeComparison PatternType = "comparison" // PatternTypeInventory represents lists of generated artifacts or files. // Use for: build outputs, generated files, deployment artifacts, file listings. PatternTypeInventory PatternType = "inventory" )
const PatternTypeComplexityDashboard PatternType = "complexity-dashboard"
PatternTypeComplexityDashboard represents complexity metrics dashboards. Use for: codebase health metrics, file size trends, cyclomatic complexity tracking.
const PatternTypeHousekeeping PatternType = "housekeeping"
PatternTypeHousekeeping represents project hygiene check dashboards. Use for: documentation sprawl warnings, technical debt markers, lint-adjacent concerns.
const PatternTypeQualityReport PatternType = "quality-report"
PatternTypeQualityReport represents quality assessment reports. Use for: MCP Interviewer output, code quality dashboards, audit results.
func AllPatternTypes ¶
func AllPatternTypes() []PatternType
AllPatternTypes returns all standard pattern types.
type PatternsRepo ¶
type QualityCategory ¶ added in v0.2.1
type QualityCategory struct {
Name string // Category name (e.g., "Name", "Description")
Passed int // Number of passed checks
Total int // Total number of checks
}
QualityCategory represents a scoring category with pass/total counts.
type QualityIssue ¶ added in v0.2.1
type QualityIssue struct {
Category string // Issue type (e.g., "description.examples")
ToolCount int // Number of tools affected
ToolNames []string // Names of affected tools
}
QualityIssue represents a grouped failure type.
type QualityReport ¶ added in v0.2.1
type QualityReport struct {
ServerName string // Server or project name being assessed
ServerVersion string // Version of the server/project
Protocol string // Protocol version (for MCP)
ToolCount int // Number of tools assessed
ResourceCount int // Number of resources
Categories []QualityCategory // Score categories (Name, Description, Schema, etc.)
Issues []QualityIssue // Grouped failures that need attention
Constraints []ConstraintViolation // Constraint violations (limits exceeded)
}
QualityReport represents a quality assessment with category scores and issues. Designed for MCP Interviewer tool scorecards but generalizable to other quality metrics.
func (*QualityReport) PatternType ¶ added in v0.2.1
func (r *QualityReport) PatternType() PatternType
PatternType returns the pattern type identifier.
func (*QualityReport) Render ¶ added in v0.2.1
func (r *QualityReport) Render(cfg *Config) string
Render formats the quality report using the provided theme.
type Sparkline ¶
type Sparkline struct {
Label string // Label for the sparkline (e.g., "Build time trend")
Values []float64 // Data points to visualize
Min float64 // Optional: explicit minimum for scale (0 = auto-detect)
Max float64 // Optional: explicit maximum for scale (0 = auto-detect)
Unit string // Optional: unit suffix (e.g., "ms", "%", "MB")
}
Sparkline represents a word-sized graphic showing trends using Unicode blocks. Inspired by Tufte's sparklines - intense, simple, word-sized graphics.
Use cases:
- Test duration trends over last N runs
- Coverage percentage changes
- Build size progression
- Error count trends
func (*Sparkline) PatternType ¶
func (s *Sparkline) PatternType() PatternType
PatternType implements the Pattern interface.
type Summary ¶
type Summary struct {
Label string // Title for the summary
Metrics []SummaryItem // Metrics to display
}
Summary represents a high-level summary with key metrics and counts. Provides at-a-glance understanding of overall results.
func (*Summary) PatternType ¶
func (s *Summary) PatternType() PatternType
PatternType implements the Pattern interface.
type SummaryItem ¶
type SummaryItem struct {
Label string // Metric label (e.g., "Total Tests", "Passed", "Failed")
Value string // Formatted value (e.g., "142", "98.5%")
Type string // "success", "error", "warning", "info" - affects coloring
}
SummaryItem represents a single summary metric.
type Task ¶
type Task struct {
// Core properties
Label string
Intent string
Command string
Args []string
StartTime time.Time
EndTime time.Time
Duration time.Duration
ExitCode int
Status string // "running", "success", "warning", "error"
// Output content
OutputLines []OutputLine
// Configuration and context
Config *Config
Context TaskContext
// contains filtered or unexported fields
}
Task represents a command execution as a visual task with formatted output.
func (*Task) AddOutputLine ¶
func (t *Task) AddOutputLine(content, lineType string, context LineContext)
AddOutputLine appends a new classified output line to the task's OutputLines. This method is thread-safe due to the use of outputLock. It also updates incremental error/warning counters for O(1) context updates.
func (*Task) Complete ¶
Complete finalizes the task's status based on its exit code and output analysis. This should be called after all output has been processed.
func (*Task) GetOutputLinesSnapshot ¶ added in v0.2.1
func (t *Task) GetOutputLinesSnapshot() []OutputLine
GetOutputLinesSnapshot returns a thread-safe copy of the output lines. This is the preferred way to read output lines from external code.
func (*Task) ProcessOutputLines ¶ added in v0.2.1
func (t *Task) ProcessOutputLines(fn func(lines []OutputLine))
ProcessOutputLines calls the provided function with the output lines while holding the lock. This is useful when you need to iterate over the lines without making a copy. The function should not modify the slice or store references to it beyond the function call.
func (*Task) RenderEndLine ¶
RenderEndLine returns the formatted end line for the task.
func (*Task) RenderOutputLine ¶
func (t *Task) RenderOutputLine(line OutputLine) string
func (*Task) RenderStartLine ¶
RenderStartLine returns the formatted start line for the task.
func (*Task) RenderSummary ¶
func (*Task) UpdateTaskContext ¶
func (t *Task) UpdateTaskContext()
UpdateTaskContext heuristically adjusts the task's cognitive load and complexity based on the analysis of its output lines. This method is thread-safe and O(1) due to incremental counters maintained by AddOutputLine.
type TaskContext ¶
type TaskContext struct {
// CognitiveLoad determines styling based on research (e.g., simplify for high load).
// Thresholds: High (>5 errors or >100 lines), Medium (>0 errors or >3 warnings or >30 lines), Low (otherwise).
// See pkg/design/recognition.go:estimateCognitiveLoad() for implementation.
CognitiveLoad CognitiveLoadContext
// IsDetailView indicates if a detailed view is active, affecting verbosity.
IsDetailView bool
// Complexity is a heuristic (1-5) of the task's output or nature.
Complexity int
}
TaskContext holds information about the cognitive context of the task (e.g., complexity, user's likely cognitive load).
Cognitive load assessment is based on Sweller's Cognitive Load Theory (1988), which suggests that information presentation should adapt to reduce cognitive processing demands when load is high.
type TaskData ¶ added in v0.2.1
type TaskData struct {
Label string
Status string // "running", "success", "warning", "error"
Duration time.Duration
Lines []LineData
ShowLines bool // Whether to show output lines
}
TaskData holds the data needed to render a task. This is separate from Task to enable clean rendering without coupling.
func TaskDataFromTask ¶ added in v0.2.1
TaskDataFromTask converts a Task to TaskData for rendering. This bridges the existing Task type to the new rendering system.
type TaskView ¶ added in v0.2.1
type TaskView struct {
// contains filtered or unexported fields
}
TaskView renders task data using a theme.
func NewTaskView ¶ added in v0.2.1
NewTaskView creates a task renderer with the given theme.
func (*TaskView) RenderComplete ¶ added in v0.2.1
RenderComplete renders the task completion state.
func (*TaskView) RenderStart ¶ added in v0.2.1
RenderStart renders the task start state (header + "Running...").
func (*TaskView) RenderUpdate ¶ added in v0.2.1
RenderUpdate renders an in-progress update (for live mode). Returns just the content lines without the box frame.
type TestTable ¶
type TestTable struct {
Label string // Title for the test table
Results []TestTableItem // Test results to display
Density DensityMode // Rendering density (detailed, balanced, compact)
}
TestTable represents a table of test results showing packages/tests with status and timing. Provides a comprehensive view of all test outcomes.
func (*TestTable) PatternType ¶
func (t *TestTable) PatternType() PatternType
PatternType implements the Pattern interface.
type TestTableItem ¶
type TestTableItem struct {
Name string // Test or package name
Status string // "pass", "fail", "skip"
Duration string // Formatted duration
Count int // Number of tests (for package-level results)
Details string // Additional details or error message
}
TestTableItem represents a single test result entry.
type Theme ¶ added in v0.2.1
type Theme struct {
Name string
// Semantic colors for status and UI elements
Colors ThemeColors
// Pre-built styles for common elements
Styles ThemeStyles
// Icons for status indicators
Icons ThemeIcons
// Border configuration
Border ThemeBorder
}
Theme defines all visual styling for fo output. Colors use lipgloss format: color names ("red"), hex ("#ff0000"), or 256-color ("120").
func DefaultTheme ¶ added in v0.2.1
func DefaultTheme() *Theme
DefaultTheme returns the default fo theme.
func MonochromeTheme ¶ added in v0.2.1
func MonochromeTheme() *Theme
MonochromeTheme returns a theme with no colors.
func NewTheme ¶ added in v0.2.1
func NewTheme(name string, colors ThemeColors, icons ThemeIcons) *Theme
NewTheme creates a theme with computed styles from colors.
func OrcaTheme2 ¶ added in v0.2.1
func OrcaTheme2() *Theme
OrcaTheme returns the Orca-inspired theme.
func ThemeFromConfig ¶ added in v0.2.1
ThemeFromConfig creates a Theme from an existing Config. This bridges the old Config system to the new Theme system during migration.
type ThemeBorder ¶ added in v0.2.1
ThemeBorder defines border characters and style.
type ThemeColors ¶ added in v0.2.1
type ThemeColors struct {
// Status colors
Primary lipgloss.Color // Main accent color (headers, labels)
Success lipgloss.Color // Success state
Warning lipgloss.Color // Warning state
Error lipgloss.Color // Error state
// Text colors
Text lipgloss.Color // Normal text
Muted lipgloss.Color // De-emphasized text
Subtle lipgloss.Color // Very subtle (borders, separators)
Inverse lipgloss.Color // Inverse text (on colored backgrounds)
}
ThemeColors defines semantic color values. All colors use lipgloss format, NOT raw ANSI escapes.
type ThemeIcons ¶ added in v0.2.1
type ThemeIcons struct {
Running string
Success string
Warning string
Error string
Info string
Bullet string
}
ThemeIcons defines icon characters for status indicators.
type ThemeStyles ¶ added in v0.2.1
type ThemeStyles struct {
// Box style for task output containers
Box lipgloss.Style
// Header style for task labels
Header lipgloss.Style
// Status line styles
StatusSuccess lipgloss.Style
StatusWarning lipgloss.Style
StatusError lipgloss.Style
// Text styles
TextNormal lipgloss.Style
TextMuted lipgloss.Style
TextBold lipgloss.Style
}
ThemeStyles provides pre-built lipgloss styles. These are computed from colors and cached for reuse.