cli

package
v0.25.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 37 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const (
	// SectionBreak adds visual separation between major sections
	SectionBreak = "\n"

	// SubsectionBreak adds minimal separation within sections
	SubsectionBreak = ""
)

Section spacing for CLI output

View Source
const AnnotationLongRunning = "ox.long_running"

AnnotationLongRunning marks a cobra command whose invocation is a long-running service process rather than a discrete command.

A service process blocks for the lifetime of the service — hours or days — so cobra's PersistentPostRunE fires at *shutdown*, not at completion of any unit of work. Instrumenting it like a normal command reports the service lifetime as command latency: `ox daemon start --foreground` was landing in command-duration telemetry with a p50 of 70 minutes and a max of 8.8 days, swamping every real command in the same aggregate.

Supported values:

"true"        — every invocation of this command is a service
"flag:<name>" — a service only when boolean flag <name> is set

The flag form exists because `ox daemon start` is two different things depending on one flag: without --foreground it spawns a child and returns in milliseconds (a real command, worth measuring); with --foreground it *is* the daemon.

Variables

View Source
var (
	ColorPrimary   = theme.Adapt(theme.ColorPrimary)
	ColorSecondary = theme.Adapt(theme.ColorSecondary)
	ColorAccent    = theme.Adapt(theme.ColorAccent)
	ColorSuccess   = theme.Adapt(theme.ColorSuccess)
	ColorWarning   = theme.Adapt(theme.ColorWarning)
	ColorError     = theme.Adapt(theme.ColorError)
	ColorInfo      = theme.Adapt(theme.ColorInfo)
	ColorDim       = theme.Adapt(theme.ColorDim)
	ColorPublic    = theme.Adapt(theme.ColorPublic)
	ColorPrivate   = theme.Adapt(theme.ColorPrivate)
)

Re-export theme colors for backward compatibility.

theme.Adapt downgrades each adaptive color to the terminal's real color depth. The generated tokens are 24-bit, and Style.Render() no longer degrades them in lipgloss v2 — see internal/theme/profile.go for what that does to a 256-color terminal.

View Source
var (
	StyleBrand = lipgloss.NewStyle().
				Foreground(ColorPrimary).
				Bold(true)

	StyleSecondary = lipgloss.NewStyle().
					Foreground(ColorSecondary)

	StyleAccent = lipgloss.NewStyle().
				Foreground(ColorAccent)

	StyleSuccess = lipgloss.NewStyle().
					Foreground(ColorSuccess)

	StyleWarning = lipgloss.NewStyle().
					Foreground(ColorWarning)

	StyleError = lipgloss.NewStyle().
				Foreground(ColorError)

	StyleInfo = lipgloss.NewStyle().
				Foreground(ColorInfo)

	StyleDim = lipgloss.NewStyle().
				Foreground(ColorDim)

	StyleBold = lipgloss.NewStyle().
				Bold(true)

	StyleCommand = lipgloss.NewStyle().
					Foreground(ColorSecondary)

	StyleFlag = lipgloss.NewStyle().
				Foreground(ColorInfo)

	StyleGroupHeader = lipgloss.NewStyle().
						Foreground(ColorPrimary).
						Bold(true)

	// StyleFile for file/directory paths (uses accent color for visual distinction)
	StyleFile = lipgloss.NewStyle().
				Foreground(ColorAccent)

	// SpinnerStyle for spinner animations
	SpinnerStyle = lipgloss.NewStyle().
					Foreground(ColorPrimary)

	// StyleCallout for contextual highlights (stars, step indicators, guided actions)
	// Used to draw attention to recommended next actions based on user state
	StyleCallout = lipgloss.NewStyle().
					Foreground(ColorAccent)

	// StyleCalloutBold for emphasized callout elements (command names in guided actions)
	StyleCalloutBold = lipgloss.NewStyle().
						Foreground(ColorSecondary).
						Bold(true)

	// Visibility styles (public=teal, private=amber)
	StylePublic = lipgloss.NewStyle().
				Foreground(ColorPublic)

	StylePrivate = lipgloss.NewStyle().
					Foreground(ColorPrivate)
)

Text styles

View Source
var ErrConfirmationRequired = errors.New("confirmation required: re-run in a terminal, or pass --yes")

ErrConfirmationRequired is returned by ConfirmYesNoRequired when nobody was there to answer — stdin produced no input at all (closed, empty, or unreadable) — as opposed to a user who was actually present and pressed Enter to accept the default. Reaching this means the command must stop rather than guess: a silent default here has repeatedly meant a login that never happened, a logout that never happened, and an uninstall that cleaned up locally while leaving cloud records behind.

View Source
var ErrHeadless = errors.New("cannot open browser: no graphical display available (SSH or headless environment)")

ErrHeadless is returned by OpenInBrowser when the environment has no graphical display (SSH session, no DISPLAY). Callers should handle this to provide context-appropriate guidance (e.g., upload to view online, or copy the file).

View Source
var ErrNoInteractiveInput = errors.New("no interactive input available to make this selection")

ErrNoInteractiveInput means a required answer could not be gathered, or --no-input forbids prompting. Without --no-input, SelectOne still falls back to its default on empty stdin; use SelectOneRequired when guessing has a cost.

View Source
var ErrSilent = SilentError{}

ErrSilent is a sentinel error indicating output was already printed.

View Source
var Styles = struct {
	Success   lipgloss.Style
	Preserved lipgloss.Style
	Error     lipgloss.Style
	Warning   lipgloss.Style
	Info      lipgloss.Style
	Hint      lipgloss.Style
	Code      lipgloss.Style
}{
	Success:   successStyle,
	Preserved: preservedStyle,
	Error:     errorStyle,
	Warning:   warningStyle,
	Info:      infoStyle,
	Hint:      hintStyle,
	Code:      codeStyle,
}

Styles exposes lipgloss styles for use in commands

Functions

func AssumeYes added in v0.16.0

func AssumeYes() bool

AssumeYes reports whether confirmations should be auto-approved.

func ColumnWidths

func ColumnWidths(rows [][]string, minWidths []int, maxWidths []int) []int

ColumnWidths calculates optimal widths for columns based on content

func ConfirmDangerousOperation

func ConfirmDangerousOperation(operationName, exactMatch string, force bool) error

ConfirmDangerousOperation is a generic confirmation prompt for destructive operations Requires user to type exactMatch string to proceed Returns error if user cancels or input doesn't match

Example

Example demonstrates generic dangerous operation confirmation

package main

import (
	"fmt"

	"github.com/sageox/ox/internal/cli"
)

func main() {
	// for operations where you want user to type a specific string
	operation := "delete all production data"
	confirmText := "DELETE-PROD"

	if err := cli.ConfirmDangerousOperation(operation, confirmText, false); err != nil {
		fmt.Println("Operation canceled")
		return
	}

	fmt.Println("User confirmed, proceeding...")
}

func ConfirmUninstall

func ConfirmUninstall(repoName string, force bool) error

ConfirmUninstall prompts user to confirm a destructive uninstall operation Returns error if user cancels or input fails, nil if confirmed Bypasses prompt if force is true

Example

Example demonstrates how to use the uninstall confirmation flow

package main

import (
	"fmt"

	"github.com/sageox/ox/internal/cli"
)

func main() {
	// in actual use, these would come from scanning the repository
	items := []cli.RemovalItem{
		{
			Type:        "directory",
			Path:        ".sageox",
			Description: "SageOx state and configuration",
		},
		{
			Type:        "file",
			Path:        "AGENTS.md",
			Description: "agent guidance document",
		},
		{
			Type:        "file",
			Path:        ".claude/CLAUDE.md",
			Description: "Claude-specific guidance",
		},
		{
			Type:        "hook",
			Path:        ".git/hooks/pre-commit",
			Description: "git pre-commit hook",
		},
	}

	// show what will be removed
	cli.ShowUninstallPreview(items, false)

	// display warning
	cli.DangerousOperationWarning("UNINSTALL SAGEOX", "my-awesome-repo")

	// get confirmation (would use force flag from command line)
	force := false // in real code: cmd.Flags().GetBool("force")
	if err := cli.ConfirmUninstall("my-awesome-repo", force); err != nil {
		fmt.Println("Uninstall canceled")
		return
	}

	fmt.Println("Proceeding with uninstall...")
	// ... actual uninstall logic here ...
}

func ConfirmYesNo

func ConfirmYesNo(prompt string, defaultYes bool) bool

ConfirmYesNo displays a yes/no prompt and loops until valid input. Returns true if user confirms with y/yes, false for n/no. Empty input uses the default specified by defaultYes. With --no-input, declines unless --yes was explicitly supplied.

Otherwise, when no input can be gathered at all, this silently returns defaultYes — unchanged from its long-standing behavior, preserved here for every existing caller. Callers for whom that silent guess has a real cost should call ConfirmYesNoRequired instead.

Example

Example demonstrates yes/no prompts

package main

import (
	"fmt"

	"github.com/sageox/ox/internal/cli"
)

func main() {
	// simple yes/no with default to No (safer for destructive ops)
	if cli.ConfirmYesNo("Remove user-level config too?", false) {
		fmt.Println("Will remove user config")
	}

	// with default to Yes (for non-destructive confirmations)
	if cli.ConfirmYesNo("Install recommended plugins?", true) {
		fmt.Println("Will install plugins")
	}
}

func ConfirmYesNoRequired added in v0.16.0

func ConfirmYesNoRequired(prompt string, defaultYes, force bool) (bool, error)

ConfirmYesNoRequired behaves like ConfirmYesNo, but returns ErrConfirmationRequired instead of silently taking the default when no one was there to answer. force (a command's own --force/--yes) and the global --yes both short-circuit to an affirmative answer without prompting.

Use this wherever taking the default silently would lose work or leave an operation half-done.

func DangerousOperationWarning

func DangerousOperationWarning(operation, target string)

DangerousOperationWarning displays a styled warning box for destructive operations

func FormatKBSlug added in v0.9.0

func FormatKBSlug(slug string) string

FormatKBSlug returns the canonical human-display form of a KB slug: "#<slug>". Use in CLI tables, headers, banners, and error messages. Do NOT use in JSON envelope fields, on-disk paths, or shell-composable stdout (e.g. `ox kb path`); those stay bare.

func FormatRow

func FormatRow(row []string, widths []int) string

FormatRow formats a row with dynamic widths

func FormatSlogLine added in v0.4.0

func FormatSlogLine(line string) string

FormatSlogLine parses a raw slog log line and returns a colorized version. Malformed lines are returned as-is.

func FormatTipText

func FormatTipText(tip string) string

FormatTipText formats tip text by highlighting backtick-wrapped commands

func HasMultipleEndpoints

func HasMultipleEndpoints(sageoxDir string) bool

HasMultipleEndpoints is a quick check for whether endpoint selection is needed.

func InputWithDefault

func InputWithDefault(title, defaultVal string) (string, error)

InputWithDefault prompts for text input with a placeholder showing the default. If user enters empty string, returns the default value. Falls back to a text prompt without a TTY or with --no-interactive. With --no-input, returns ErrNoInteractiveInput without accepting the default.

func IsHeadless

func IsHeadless() bool

IsHeadless returns true when no graphical display is available. Detects SSH sessions and missing display servers so callers can skip browser-open calls that would launch broken text-mode browsers (lynx, w3m).

func IsInteractive

func IsInteractive() bool

IsInteractive returns true if interactive mode is enabled. Interactive mode is disabled by --no-input, --no-interactive, CI=true, or stdin not being a terminal (e.g., running inside an AI coworker).

func IsLongRunning added in v0.13.0

func IsLongRunning(cmd *cobra.Command) bool

IsLongRunning reports whether this invocation is a long-running service process, per the command's AnnotationLongRunning annotation.

Callers use this to suppress command-scoped instrumentation — duration telemetry and the wall-clock OTel root span. Service processes carry their own instrumentation (the daemon emits ox-daemon spans and its own telemetry events), so nothing is lost by skipping the CLI-level wrapper.

func IsSilent

func IsSilent(err error) bool

IsSilent checks if an error is a silent error (already displayed).

func MarshalJSONIndent added in v0.17.1

func MarshalJSONIndent(v any) ([]byte, error)

MarshalJSONIndent is the canonical encoding: two-space indent, one trailing newline, never colorized.

For callers that need the bytes themselves — to measure the payload an AI coworker will actually consume, to embed it in a markdown fence, or to hash it. Pair it with WriteJSONBytes to print what you measured instead of encoding the value twice.

func NoInput added in v0.17.0

func NoInput() bool

NoInput reports whether --no-input forbids reading prompt answers from stdin. Commands may still read data explicitly supplied through stdin.

func NoInteractive added in v0.25.0

func NoInteractive() bool

NoInteractive reports whether --no-interactive disabled spinners and TUI elements. IsInteractive also folds in --no-input and the stdin TTY check.

func OpenInBrowser

func OpenInBrowser(url string) error

OpenInBrowser opens a URL in the user's default browser. Returns ErrHeadless if the environment is headless (SSH, no display). Silently returns nil when SKIP_BROWSER=1 (used by automated tests and demo scripts to suppress browser popups during non-interactive runs). This is the single entry point for browser-opening across the CLI.

func PrintActionHint

func PrintActionHint(command, description string, step int)

PrintActionHint prints a prominent actionable hint with star, command, and optional step. Matches the visual styling used in help output for contextual next-action guidance. Example: "★ ox login Authenticate with SageOx (Step 1)"

func PrintActionHintTo added in v0.13.0

func PrintActionHintTo(w io.Writer, command, description string)

PrintActionHintTo is PrintActionHint against an explicit writer.

The package-level variant hardcodes os.Stdout, which makes it unusable from renderers that take an io.Writer so they can be unit-tested. Every other Print* helper here already has a *To twin; this closes the one gap, so commands no longer hand-roll the ★ hint and drift from the canonical styling.

func PrintDisclaimer

func PrintDisclaimer()

PrintDisclaimer prints the Claude Code compatibility disclaimer in brand gold.

func PrintError

func PrintError(msg string)

PrintError writes an error to stderr in both text and JSON modes.

func PrintErrorTo added in v0.8.0

func PrintErrorTo(w io.Writer, msg string)

PrintErrorTo writes an error to w as formatted text or JSON. Parallel-safe.

func PrintHint

func PrintHint(msg string)

PrintHint prints a dimmed hint message (e.g., "Run 'ox login' to authenticate")

func PrintHintTo added in v0.8.0

func PrintHintTo(w io.Writer, msg string)

PrintHintTo writes a hint to w. Parallel-safe. Suppressed in jsonMode.

func PrintInfo

func PrintInfo(msg string)

func PrintInfoTo added in v0.8.0

func PrintInfoTo(w io.Writer, msg string)

PrintInfoTo writes an info message to w. Parallel-safe.

func PrintJSON

func PrintJSON(v any)

PrintJSON writes v to stdout as indented JSON, colorized when — and only when — a human is looking at it.

Returns nothing: a broken stdout is not actionable for a CLI, matching PrintSuccess and the errcheck exclusions for terminal output. Use PrintJSONTo when the caller can act on the error.

func PrintJSONTo added in v0.17.1

func PrintJSONTo(w io.Writer, v any) error

PrintJSONTo writes v to w and reports an encoding or write failure, so a command can `return cli.PrintJSONTo(cmd.OutOrStdout(), payload)` in place of `return enc.Encode(payload)`.

Color is decided by the process-wide profile (the TTY-ness of os.Stdout), not by w: w is usually cmd.OutOrStdout() or a test buffer standing in for stdout, and asking whether a *bytes.Buffer is a terminal has no answer. A test that wants color forces OX_COLOR_PROFILE.

func PrintPreserved

func PrintPreserved(msg string)

PrintPreserved prints a message indicating an existing file was preserved (not overwritten). Uses cyan color to distinguish from green success (created) messages.

func PrintPreservedTo added in v0.8.0

func PrintPreservedTo(w io.Writer, msg string)

PrintPreservedTo writes a preserved-file notice to w. Parallel-safe.

func PrintSectionBreak

func PrintSectionBreak()

PrintSectionBreak prints consistent spacing between sections

func PrintSubsectionBreak

func PrintSubsectionBreak()

PrintSubsectionBreak prints minimal spacing within sections

func PrintSuccess

func PrintSuccess(msg string)

func PrintSuccessTo added in v0.8.0

func PrintSuccessTo(w io.Writer, msg string)

PrintSuccessTo writes a success message to w. Parallel-safe — does not touch os.Stdout. Honors jsonMode (encodes JSON to w) so output shape is identical to PrintSuccess.

func PrintSuggestionBox

func PrintSuggestionBox(title, message, fix string)

PrintSuggestionBox prints a bordered suggestion box to stderr.

func PrintTip

func PrintTip(tip string)

PrintTip prints a helpful tip message with command highlighting

func PrintWarning

func PrintWarning(msg string)

PrintWarning writes a warning to stderr in both text and JSON modes.

func PrintWarningTo added in v0.8.0

func PrintWarningTo(w io.Writer, msg string)

PrintWarningTo writes a warning to w as formatted text or JSON. Parallel-safe.

func SanitizeTerminalLines added in v0.13.0

func SanitizeTerminalLines(s string) []string

SanitizeTerminalLines is the multi-line counterpart to SanitizeTerminalText, for untrusted values a caller wants to render across several rows instead of collapsing onto one.

It splits on line breaks FIRST, then sanitizes each line independently, and drops lines that sanitize to nothing. Splitting first is what makes legitimate multi-line content readable while still denying the forgery SanitizeTerminalText guards against: the caller controls the indent of every emitted line, so untrusted text cannot start a line at column zero and pose as a label, a prompt, or a separate instruction.

Returns nil when nothing survives, so callers can skip the row entirely.

func SanitizeTerminalText added in v0.13.0

func SanitizeTerminalText(s string) string

SanitizeTerminalText makes server-provided or otherwise untrusted text safe to write to a terminal.

Any string that originates outside this binary — a knowledge bubble's name/description/steering, a team name, an API error body — can carry ANSI CSI/OSC escape sequences. Written raw to a TTY those can repaint the screen, hide or forge output, retitle the window, or (with OSC 8 and OSC 52) smuggle hyperlinks and clipboard writes past the user. The rendering call site is the only place that knows the value is about to hit a terminal, so sanitizing belongs here rather than at the API decode boundary.

Behavior: escape sequences are dropped whole, in both their 7-bit (ESC-introduced) and 8-bit (C1 introducer) forms; remaining C0/C1 control characters are dropped; printable text is preserved verbatim. Tab is preserved; newline and carriage return are NOT — a control character that ends the current line lets untrusted text escape the row it was rendered into, which is the specific forgery this guards against. Callers that legitimately need multi-line untrusted content should split on newlines first and sanitize each line.

func SelectEndpoint

func SelectEndpoint(endpoints []EndpointInfo, defaultEndpoint, flagEndpoint string) (string, error)

SelectEndpoint prompts the user to select an endpoint when multiple are available. If only one endpoint exists, returns it without prompting. If flagEndpoint is provided, validates it exists and returns it. Returns the selected endpoint URL.

func SelectMany added in v0.6.2

func SelectMany(title string, options []MultiSelectOption) ([]string, error)

SelectMany displays an interactive multi-select with checkboxes. Returns the Values of all selected options, or error if canceled. Falls back to selectManySimple in non-TTY mode.

func SelectOne

func SelectOne(title string, options []string, defaultIdx int) (int, error)

SelectOne displays an interactive selection menu with arrow key navigation. Returns the index of the selected option (0-based) or -1 if canceled. Falls back to a numbered prompt without a TTY or with --no-interactive. With --no-input, returns ErrNoInteractiveInput without reading stdin.

Otherwise, when no interactive input can be gathered at all (e.g. piped/CI/agent harness with nothing on stdin), this silently returns (defaultIdx, nil) — unchanged from its long-standing behavior, preserved here for every existing caller. Callers for whom that silent guess is unsafe should call SelectOneRequired instead.

func SelectOneRequired added in v0.15.0

func SelectOneRequired(title string, options []string, defaultIdx int) (int, error)

SelectOneRequired behaves like SelectOne, but returns ErrNoInteractiveInput instead of silently accepting defaultIdx when no one was actually there to answer (non-TTY stdin with nothing piped in, EOF, or a read error). A caller that receives this error must not proceed as if a choice were made — it should ask for an explicit flag/argument instead of guessing.

func SelectOneValue

func SelectOneValue[T comparable](title string, options []SelectOption[T], defaultIdx int) (T, error)

SelectOneValue displays an interactive selection menu and returns the selected value.

func SetAssumeYes added in v0.16.0

func SetAssumeYes(enabled bool)

SetAssumeYes sets the global "answer yes to every confirmation" flag, from --yes or OX_YES=1. Deliberately separate from SetNoInteractive: "there is no human watching" must never imply "the absent human agrees."

func SetJSONMode

func SetJSONMode(enabled bool)

func SetNoInput added in v0.17.0

func SetNoInput(enabled bool)

SetNoInput disables prompts without treating missing input as consent.

func SetNoInteractive

func SetNoInteractive(enabled bool)

SetNoInteractive sets the global non-interactive mode flag. When enabled, spinners and TUI elements are disabled.

func ShowUninstallPreview

func ShowUninstallPreview(items []RemovalItem, dryRun bool)

ShowUninstallPreview displays what will be removed, grouped by type Shows summary first, then details if items exist

Example (DryRun)

Example demonstrates dry-run mode

package main

import (
	"github.com/sageox/ox/internal/cli"
)

func main() {
	items := []cli.RemovalItem{
		{Type: "directory", Path: ".sageox", Description: "state directory"},
		{Type: "file", Path: "AGENTS.md", Description: "guidance"},
	}

	// dry-run mode shows what would be removed without doing it
	cli.ShowUninstallPreview(items, true)
}

func Silent added in v0.21.0

func Silent(err error) error

Silent marks a failure whose output was already displayed, like ErrSilent, and keeps err in the chain so errors.Is and errors.As (and usage telemetry) still see what failed. Its message is empty, exactly like ErrSilent's, so nothing that prints or parses error text behaves differently. Use it, not errors.Join(ErrSilent, err), whose message is err's. Silent(nil) is ErrSilent.

func StreamFormattedLogs added in v0.4.0

func StreamFormattedLogs(r io.Reader, w io.Writer)

StreamFormattedLogs reads log lines from r, colorizes each, and writes to w. Blocks until r is closed or an error occurs.

func SuggestionBox

func SuggestionBox(title, message, fix string) string

SuggestionBox renders a bordered box with a title, message, and fix command. Used for actionable suggestions that need visual emphasis.

func TruncateID

func TruncateID(id string, verbose bool) string

TruncateID shortens an ID for display, keeping prefix and suffix Examples:

  • "oxsid_01JBCDEFGHIJKLMNOPQRSTUVWXYZ" -> "oxsid_01JB...WXYZ" (verbose=false)
  • "oxsid_01JBCDEFGHIJKLMNOPQRSTUVWXYZ" -> "oxsid_01JBCDEFGHIJKLMNOPQRSTUVWXYZ" (verbose=true)
  • "Oxa7b3" -> "Oxa7b3" (already short)

Returns full ID if verbose=true or ID is already short (<=16 chars).

func TruncateUUID

func TruncateUUID(uuid string, verbose bool) string

TruncateUUID shortens a UUID for display Examples:

  • "a1b2c3d4-e5f6-7890-abcd-ef1234567890" -> "a1b2c3d4..." (verbose=false)
  • "a1b2c3d4-e5f6-7890-abcd-ef1234567890" -> "a1b2c3d4-e5f6-7890-abcd-ef1234567890" (verbose=true)

Returns full UUID if verbose=true or UUID is already short (<=12 chars).

func WithSpinner

func WithSpinner[T any](message string, fn func() (T, error)) (T, error)

WithSpinner runs an async function with a spinner displayed. Shows spinner after a short delay to avoid flicker for fast operations. In non-interactive mode (CI or --no-interactive), runs without spinner. Returns the result of the function, or tea.ErrInterrupted if dismissed before the function finishes. Interrupting stops the wait, not the function itself.

func WithSpinnerNoResult

func WithSpinnerNoResult(message string, fn func() error) error

WithSpinnerNoResult runs an async function with a spinner displayed. Use when the function returns only an error.

func Wordmark

func Wordmark() string

Wordmark returns the two-tone "SageOx" brand wordmark as a rendered string.

func WriteJSONBytes added in v0.17.1

func WriteJSONBytes(w io.Writer, b []byte) error

WriteJSONBytes writes already-encoded JSON to w, colorized under the same rule as PrintJSONTo.

This is the seam for callers whose encoding is not the default: a SetEscapeHTML(false) encoder whose URLs must not become \u0026, or a command with a --pretty flag choosing between indented and compact. They keep their own encoder and still get themed output, instead of opting out of the printer entirely — which is how ox accumulated 100+ JSON emitters.

b is written verbatim when color is off, so it must already end in whatever newline the caller wants.

Types

type Context

type Context struct {
	// Config holds the loaded configuration
	Config *config.Config

	// Logger provides structured logging
	Logger *slog.Logger

	// Telemetry client for tracking command usage
	TelemetryClient *telemetry.Client

	// CommandStartTime tracks when the command started (for telemetry)
	CommandStartTime time.Time

	// Ctx provides the Go context for cancellation and timeouts
	Ctx context.Context

	// LongRunning is true when this invocation is a service process rather
	// than a discrete command (e.g. `ox daemon start --foreground`).
	// Command-scoped instrumentation — duration telemetry and the wall-clock
	// OTel root span — is suppressed for these, because it would report the
	// service lifetime as command latency. See IsLongRunning.
	LongRunning bool

	// Cmd is the command cobra resolved for this invocation.
	Cmd *cobra.Command

	// ProjectRoot is what config.FindProjectRoot returned when the command
	// started: the working directory or its nearest parent holding .sageox/,
	// or "". A .sageox/ directory alone does not make a project initialized;
	// see config.IsInitialized.
	ProjectRoot string

	// Err is what the command returned, set by cmd/ox's
	// executeWithFrictionRecovery after Execute so usage telemetry can report
	// how it failed.
	Err error
	// contains filtered or unexported fields
}

Context holds common dependencies for CLI commands. It provides centralized initialization and access to shared resources like configuration, logging, and telemetry.

func NewContext

func NewContext(cmd *cobra.Command, args []string) (*Context, error)

NewContext creates a new CLI context from a Cobra command. This centralizes all the initialization logic that was previously scattered across PersistentPreRunE in root.go.

func (*Context) CommandPath added in v0.19.0

func (c *Context) CommandPath(cmd *cobra.Command) string

CommandPath names the invoked command for telemetry: the full path below the root ("plan viz lint", not "viz lint", which is also a top-level command), or the path set by SetCommandPath.

func (*Context) Fprintf

func (c *Context) Fprintf(w *os.File, format string, args ...any)

Fprintf writes formatted output to a writer (useful for stderr)

func (*Context) IsJSON

func (c *Context) IsJSON() bool

IsJSON returns true if JSON output mode is enabled

func (*Context) IsNoInteractive

func (c *Context) IsNoInteractive() bool

IsNoInteractive returns true if non-interactive mode is enabled (CI or --no-interactive)

func (*Context) IsQuiet

func (c *Context) IsQuiet() bool

IsQuiet returns true if quiet mode is enabled

func (*Context) IsReview

func (c *Context) IsReview() bool

IsReview returns true if review (security audit) mode is enabled

func (*Context) IsText

func (c *Context) IsText() bool

IsText returns true if text output mode is enabled

func (*Context) IsVerbose

func (c *Context) IsVerbose() bool

IsVerbose returns true if verbose logging is enabled

func (*Context) LogDebug

func (c *Context) LogDebug(msg string, args ...any)

LogDebug logs a debug-level message

func (*Context) LogError

func (c *Context) LogError(msg string, args ...any)

LogError logs an error-level message

func (*Context) LogInfo

func (c *Context) LogInfo(msg string, args ...any)

LogInfo logs an info-level message

func (*Context) LogWarn

func (c *Context) LogWarn(msg string, args ...any)

LogWarn logs a warning-level message

func (*Context) Outcome added in v0.20.0

func (c *Context) Outcome() map[string]any

Outcome returns what SetOutcome recorded; nil for a nil Context.

func (*Context) PrintError

func (c *Context) PrintError(msg string)

PrintError prints an error message

func (*Context) PrintPreserved

func (c *Context) PrintPreserved(msg string)

PrintPreserved prints a preserved/unchanged message (unless quiet mode)

func (*Context) PrintSuccess

func (c *Context) PrintSuccess(msg string)

PrintSuccess prints a success message (unless quiet mode)

func (*Context) PrintWarning

func (c *Context) PrintWarning(msg string)

PrintWarning prints a warning message (unless quiet mode)

func (*Context) Printf

func (c *Context) Printf(format string, args ...any)

Printf prints a formatted message to stdout (respects quiet/json modes)

func (*Context) Println

func (c *Context) Println(msg string)

Println prints a message to stdout (respects quiet/json modes)

func (*Context) SetCommandPath added in v0.19.0

func (c *Context) SetCommandPath(path string)

SetCommandPath records the path for a command that dispatches its own subcommands, which cobra sees only as the dispatcher: `ox agent <id> session stop` is "agent session stop", not "agent".

func (*Context) SetOutcome added in v0.20.0

func (c *Context) SetOutcome(key string, value any)

SetOutcome records how a command ended, for its usage event, when the exit code cannot say (a review session exits 0 whether it was approved or abandoned). Counts and fixed words only: ADR-008's PostHog addendum lists each key, and no value may carry anything a person wrote. A nil Context records nothing.

func (*Context) Shutdown

func (c *Context) Shutdown()

Shutdown performs cleanup operations. Should be called in PersistentPostRunE or deferred.

Note: this intentionally does NOT shut down OTel tracing. PostRunE only runs on success — cobra skips it when RunE returns an error. To make cli.exit_code observable on both success and error paths, the OTel root span is ended from main() *after* Execute returns, where the final exit code is known. See cmd/ox/main.go.

func (*Context) TrackCommandCompletion

func (c *Context) TrackCommandCompletion(cmd *cobra.Command)

TrackCommandCompletion tracks a successful command completion via telemetry

func (*Context) TrackCommandError

func (c *Context) TrackCommandError(cmd *cobra.Command, err error)

TrackCommandError tracks a command error via telemetry

type EndpointInfo

type EndpointInfo struct {
	Endpoint string
	RepoID   string
	InitAt   string
}

EndpointInfo holds information about an endpoint from a repo marker

func DiscoverEndpoints

func DiscoverEndpoints(sageoxDir string) ([]EndpointInfo, error)

DiscoverEndpoints scans .sageox/ for .repo_* marker files and returns unique endpoints found. Returns endpoints sorted by their first appearance.

type MultiSelectOption added in v0.6.2

type MultiSelectOption struct {
	Label    string
	Value    string
	Selected bool
	Disabled bool   // cannot be toggled (renders dimmed)
	Hint     string // shown after label in dim text (e.g., "installed")
}

MultiSelectOption represents an item in a multi-select menu.

type RemovalItem

type RemovalItem struct {
	Type        string // e.g., "directory", "file", "hook"
	Path        string // relative path from repo root
	Description string // brief description of what this is
}

RemovalItem represents an item to be removed during uninstall

type SelectOption

type SelectOption[T any] struct {
	Label string
	Value T
}

SelectOption represents a single option in a selection menu.

type SilentError

type SilentError struct{}

SilentError is an error type that signals the error was already displayed. main.go checks for this and skips printing "Error:" prefix.

func (SilentError) Error

func (e SilentError) Error() string

type SlogLine added in v0.4.0

type SlogLine struct {
	Time    string // raw timestamp value
	Level   string // DEBUG, INFO, WARN, ERROR
	Message string // msg value (unquoted)
	Attrs   string // remaining key=value pairs
}

SlogLine holds parsed fields from a slog TextHandler line.

func ParseSlogLine added in v0.4.0

func ParseSlogLine(line string) (SlogLine, bool)

ParseSlogLine parses a slog TextHandler line into its components. Returns false if the line doesn't match the expected format.

type SpinnerResult

type SpinnerResult[T any] struct {
	Value T
	Err   error
}

SpinnerResult holds the result of an async operation

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址