Skip to content

Implement global UI formatter pattern for simplified output - #1714

Merged
Erik Osterman (Cloud Posse) (osterman) merged 52 commits into
mainfrom
osterman/io-handling-prd
Nov 4, 2025
Merged

Erik Osterman (Cloud Posse) (osterman) merged 52 commits into
mainfrom
osterman/io-handling-prd

Conversation

@osterman

@osterman Erik Osterman (Cloud Posse) (osterman) commented Oct 25, 2025 •

Copy link
Copy Markdown
Member

what

  • Implements package-level output functions that encode destination in the function name
  • Eliminates the need to decide "where should this output go?" (stdout vs stderr)
  • Adds pkg/io/ for I/O channel management with automatic routing and secret masking
  • Adds pkg/ui/ for stderr output with automatic formatting and icons
  • Adds pkg/terminal/ for terminal capability detection
  • Adds --mask flag for controlling automatic secret masking
  • Enforces programmatic consistency across all commands

why

The Core Problem

In the main branch, developers must constantly decide:

  • "Should this go to stdout or stderr?"
  • "Is this data or a message?"
  • "Do I need fmt.Fprintf(os.Stdout, ...) or fmt.Fprintf(os.Stderr, ...)?"

This creates inconsistency - different developers make different choices, leading to:

  • Help text appearing on stderr in some commands, stdout in others
  • Status messages mixed with data output
  • Inconsistent use of colors and formatting

The Solution

The function name IS the destination. Developers no longer think about streams:

// ❌ OLD: Developer decides where output goes
fmt.Fprintf(os.Stderr, "Starting...\n")  // Why stderr?
fmt.Fprintf(os.Stdout, result)          // Why stdout?

// ✅ NEW: Function name encodes destination
ui.Write("Starting...\n")   // Obviously stderr (it's UI)
data.Write(result)          // Obviously stdout (it's data)

Key insight: ui.* functions always go to stderr. data.* functions always go to stdout. No decisions, no mistakes, no inconsistency.

Key Changes

Eliminates Stream Decision Making

Old pattern (main branch):

// Developer must know:
// - stdout vs stderr semantics
// - When to use which stream
// - How to format output consistently

fmt.Fprintf(os.Stderr, "Starting deployment...\n")
fmt.Fprintf(os.Stdout, "%s\n", jsonOutput)
fmt.Println("Done!")  // Wait, where does this go? stdout? Is that right?

New pattern (this PR):

// Developer thinks in terms of WHAT, not WHERE:
// - Is this a message for the user? → ui.*
// - Is this data to pipe/process? → data.*
// Function name = destination. No thinking required.

ui.Write("Starting deployment...\n")  // Message → stderr (automatic)
data.Write(jsonOutput)                // Data → stdout (automatic)
ui.Success("Done!")                   // Status → stderr with ✓ icon (automatic)

Enforces Consistency

Before: Each command could do it differently

// Command A
fmt.Fprintf(os.Stderr, "Error: %s\n", err)

// Command B
fmt.Fprintf(os.Stdout, "Error: %s\n", err)  // Wrong stream!

// Command C
fmt.Println("Error:", err)  // Wrong stream! No color!

After: All commands use the same pattern

// Command A, B, C - all identical, all correct
ui.Error(err.Error())  // Always stderr, always red, always ✗ icon

Complete API

Data Output (stdout - pipeable)

Use when: Output should be processed by other tools (jq, grep, etc.)

Available via pkg/io global writers:

  • io.Data - Global stdout writer with automatic masking
  • Can use with fmt.Fprintf(io.Data, ...) or pass to third-party libraries

Convenience functions via pkg/data:

  • data.Write(text) - plain text → stdout
  • data.Writef(format, args...) - formatted text → stdout
  • data.Writeln(text) - text with newline → stdout
  • data.WriteJSON(v) - JSON → stdout
  • data.WriteYAML(v) - YAML → stdout

UI Output (stderr - human messages)

Use when: Output is for human eyes (status, errors, prompts)

  • ui.Success(text) - ✓ text → stderr (green with icon)
  • ui.Error(text) - ✗ text → stderr (red with icon)
  • ui.Warning(text) - ⚠ text → stderr (yellow with icon)
  • ui.Info(text) - ℹ text → stderr (cyan with icon)
  • ui.Write(text) - plain text → stderr (no icon, no color)
  • ui.Writef(format, args...) - formatted text → stderr
  • ui.Writeln(text) - text with newline → stderr

Markdown Rendering

Function name encodes destination:

  • ui.Markdown(content) - rendered markdown → stdout (help/docs are pipeable)
  • ui.MarkdownMessage(content) - rendered markdown → stderr (error messages are UI)

Why two functions? Because markdown can be either:

  • Documentation (help, usage) → stdout → use ui.Markdown()
  • Messages (errors, warnings) → stderr → use ui.MarkdownMessage()

The function name tells you where it goes. No guessing.

Example: The Decision Elimination

Before - Developer must think about streams:

// 🤔 "Help text... is that data or UI? stdout or stderr?"
// 🤔 "Let me check what other commands do..."
// 🤔 "I think help should be pipeable, so stdout?"
fmt.Fprintf(os.Stdout, "%s\n", helpText)

// 🤔 "Status messages... definitely stderr, right?"
fmt.Fprintf(os.Stderr, "Processing...\n")

// 🤔 "JSON output... that's data, so stdout"
fmt.Fprintf(os.Stdout, "%s\n", jsonData)

// 🤔 "Success message... stderr? or stdout? should it be green?"
fmt.Fprintf(os.Stderr, "Done!\n")

After - Function name IS the answer:

// Help is documentation → Markdown → stdout
ui.Markdown(helpText)

// Status is a message → UI → stderr
ui.Write("Processing...\n")

// JSON is data → data channel → stdout
data.WriteJSON(result)

// Success is UI feedback → UI → stderr with formatting
ui.Success("Done!")

Zero cognitive overhead. The function name encodes:

  • Destination (stdout vs stderr)
  • Formatting (plain, colored, icons)
  • Behavior (automatic masking, terminal detection)

Automatic Secret Masking

All output (stdout and stderr) is automatically masked using 8 built-in patterns covering common secrets:

  • AWS credentials (AKIA*, access keys, session tokens)
  • GitHub tokens (ghp_, gho_, github_pat_*)
  • GitLab tokens (glpat-*)
  • OpenAI API keys (sk-*)
  • Bearer tokens
  • Environment variables (AWS_SECRET_ACCESS_KEY, GITHUB_TOKEN, etc.)

Command line:

atmos terraform apply --mask=false  # Disable for debugging

Environment:

export ATMOS_MASK=false

Config file:

settings:
  terminal:
    mask:
      enabled: true
      replacement: "***MASKED***"

Precedence: --mask flag > ATMOS_MASK env > config > default (true)

Programmatic API:

import iolib "github.com/cloudposse/atmos/pkg/io"

// Register custom secrets
iolib.RegisterSecret("my-api-key-abc123")           // Masks literal + encodings
iolib.RegisterPattern(`COMPANY_KEY_[A-Z0-9]{32}`)   // Masks regex pattern
iolib.RegisterValue(os.Getenv("CUSTOM_SECRET"))     // Masks literal only

// Pass global writers to third-party libraries
logger := log.New(iolib.Data, "", 0)  // Automatically masked
bar := progressbar.NewOptions(100, progressbar.OptionSetWriter(iolib.UI))

Future: Config-based pattern registration (schema exists, loading not implemented yet):

settings:
  terminal:
    mask:
      patterns: ['ACME_[A-Z0-9]{32}']  # Custom regex patterns
      literals: ['my-secret']          # Literal values to mask

Benefits

1. Programmatic Consistency

  • All commands use identical patterns
  • ui.Success() always behaves the same way
  • data.WriteJSON() always goes to stdout
  • No per-command variations

2. No Stream Knowledge Required

  • Don't need to understand stdout vs stderr
  • Don't need to know POSIX conventions
  • Function name = destination
  • "Is this a message or data?" → use ui.* or data.*

3. Automatic Correctness

  • Can't accidentally write data to stderr
  • Can't accidentally write UI to stdout
  • Can't forget to add colors/icons
  • Secrets automatically masked

4. Simple Mental Model

Is it for users to read? → ui.*  (goes to stderr)
Is it for tools to process? → data.* (goes to stdout)

That's it. That's the whole model.

Architecture

  • pkg/io/ - I/O context, streams, masking engine, global writers, terminal detection
  • pkg/ui/ - Formatter, markdown renderer, stderr output functions
  • pkg/data/ - Stdout output functions (wraps io.Data)
  • pkg/terminal/ - Terminal capabilities (color, TTY, width)

All initialized automatically in cmd/root.go - commands just import and call.

Documentation

Testing

  • 17+ test cases for I/O context and masking
  • Unit tests for all output functions
  • Terminal capability detection tests
  • Integration tests with golden snapshots
  • 42 help command snapshots verify --mask flag presence

references

  • Eliminates "where should this go?" decisions
  • Enforces programmatic consistency across all commands
  • Makes correct output handling automatic and effortless
  • Prevents secret leakage with automatic masking

Summary by CodeRabbit

  • New Features

    • Automatic masking of sensitive data in command output (8 built-in patterns).
    • New global flags: --force-color, --force-tty, --mask (with env var support).
    • Clear separation of machine-readable data (stdout) and human UI output (stderr); improved UI formatting including Markdown rendering.
    • Global writers (io.Data, io.UI) for third-party library integration.
    • Programmatic API for registering custom secrets and patterns.
  • Documentation

    • Added comprehensive I/O/UI, masking, terminal, and logging guides; published blog post about zero-config terminal output.

This change introduces a global formatter pattern that makes UI output
as simple as logging, eliminating boilerplate and context fishing.

## Key Changes

### Global Formatter Pattern (pkg/ui/formatter.go)
- Added `ui.InitFormatter()` - called once at startup in root.go
- Package-level functions write output automatically:
  - `ui.Success(text)` - writes to stderr with ✓ checkmark
  - `ui.Error(text)` - writes to stderr with ✗ mark
  - `ui.Warning(text)` - writes to stderr with ⚠ mark
  - `ui.Info(text)` - writes to stderr with ℹ mark
  - `ui.Data(text)` - writes plain text to stdout
  - `ui.Markdown(content)` - renders and writes to stdout
- Advanced API via `ui.Format` variable for custom handling

### Simplified Commands
- about command (cmd/about/about.go) - now one line
- version command (internal/exec/version.go) - uses ui.Data()
- No more fmt.Println/Printf calls in commands
- No context fishing or fallback logic

### I/O Foundation (pkg/io/)
- New io.Context for channel management
- Separate Data (stdout) and UI (stderr) channels
- Terminal capability detection
- Secret masking support

### Documentation
- docs/io-and-ui-output.md - UI output guide
- docs/logging.md - Updated with UI vs logging distinction
- docs/prd/io-handling-strategy.md - Architecture decisions

## Key Principle

**UI output is required** - Without it, users can't use the command
**Logging is optional metadata** - Adds diagnostic context

## Migration

Old pattern (deprecated):
```go
ioCtx, ok := cmd.Context().Value(key).(io.Context)
formatter := ui.NewFormatter(ioCtx)
msg := formatter.Success("Done!")
fmt.Fprintf(ioCtx.UI(), "%s\n", msg)
```

New pattern:
```go
ui.Success("Done!")  // One line, automatic output
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@github-actions github-actions Bot added the size/xl Extra large size PR label Oct 25, 2025
@mergify

mergify Bot commented Oct 25, 2025

Copy link
Copy Markdown
Contributor

Warning

This PR exceeds the recommended limit of 1,000 lines.

Large PRs are difficult to review and may be rejected due to their size.

Please verify that this PR does not address multiple issues.
Consider refactoring it into smaller, more focused PRs to facilitate a smoother review process.

@github-actions

github-actions Bot commented Oct 25, 2025 •

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

Scanned Files

None

@coderabbitai

coderabbitai Bot commented Oct 25, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR introduces a layered I/O/UI/terminal subsystem: new io Context, masking engine, masked streams and global Data/UI writers; a UI formatter with Markdown/status helpers; terminal/color detection and flags; wiring in cmd/root and command tests; plus extensive tests and documentation for masking, output patterns, and CLI flags.

Changes

Cohort / File(s) Summary
Core I/O API & implementation
pkg/io/interfaces.go, pkg/io/context.go, pkg/io/masker.go, pkg/io/streams.go, pkg/io/global.go, pkg/io/terminal_adapter.go
New public io API (Context, Streams, Masker, Config, Stream), NewContext builder, masker implementation (literals + regex + encodings), streams with maskedWriter, global Init/Initialize and global Data/UI writers, TerminalWriter adapter.
I/O unit & example tests
pkg/io/context_test.go, pkg/io/masker_test.go, pkg/io/streams_test.go, pkg/io/global_test.go, pkg/io/example_test.go
Comprehensive tests covering context creation, masking behavior, masked streams, global initialization, concurrency, and Example_ functions demonstrating new patterns.
UI formatter & interfaces
pkg/ui/interfaces.go, pkg/ui/formatter.go, pkg/ui/formatter_test.go, pkg/ui/output_test.go
New Formatter interface and StyleSet; InitFormatter, global Format and package-level helpers (Markdown/Success/Warning/Error/Info/Write/Writeln/etc.); Glamour-based Markdown rendering and routing to UI/Data channels; extensive formatter tests.
Data writer
pkg/data/data.go, pkg/data/data_test.go
Global data writer initialized via InitWriter(io.Context) with Write/Writef/Writeln/WriteJSON/WriteYAML convenience functions and tests.
Terminal abstraction
pkg/terminal/terminal.go, pkg/terminal/terminal_test.go
New Terminal interface, ColorProfile, Stream/Config, New() constructor, TTY detection, color-profile detection, width/height, title/alert handling and tests.
Schema updates
pkg/schema/schema.go, pkg/schema/schema_test.go
Terminal struct gains Title, Alerts, Mask (MaskSettings); IsColorEnabled signature changed to IsColorEnabled(isTTY bool); tests updated for isTTY scenarios.
Command wiring & small command updates
cmd/root.go, cmd/internal/registry.go, cmd/about/about.go, cmd/about/about_test.go, internal/exec/version.go, internal/tui/utils/utils.go, internal/exec/version_test.go
Root initializes io.NewContext, ui.InitFormatter, data.InitWriter and adds flags (--force-color, --force-tty, --mask) + env bindings; registry adds IoContextKey; about now uses ui.Markdown; tests updated to initialize io/UI/data; version delegates JSON/YAML to data wrappers; tui utils exposes WriteJSON/WriteYAML.
Errors
errors/errors.go
Added I/O/UI-related errors: ErrUIFormatterNotInitialized, ErrIOContextNotInitialized, ErrBuildIOConfig, ErrUnknownStream, ErrWriteToStream, ErrMaskingContent.
Internal TUI utils
internal/tui/utils/utils.go
Added WriteJSON/WriteYAML wrappers delegating to data package.
Docs: guides, PRD, blog, CLAUDE
docs/io-and-ui-output.md, docs/prd/io-handling-strategy.md, docs/prd/secrets-masking/*, docs/logging.md, docs/structured-logging.md, docs/developing-atmos-commands.md, CLAUDE.md, website/blog/*, website/docs/cli/*, website/docs/cli/configuration/mask.mdx
New and updated documentation covering I/O/UI model, masking strategy, PRD/implementation notes, logging vs UI guidance, global flags and mask configuration, blog post and author entry.
Help snapshots / CLI docs
tests/snapshots/TestCLICommands_atmos_*.golden, tests/snapshots/TestCLICommands_atmos_describe_config.stdout.golden
Updated ~25+ help snapshots to include new global flags --force-color, --force-tty, --mask; snapshot for config shows new mask settings.
Misc / LICENSE
NOTICE, website/blog/authors.yml
Updated dependency license URL; added blog author entry.

Sequence Diagram(s)

sequenceDiagram
    participant Root as Root Command
    participant IO as io.NewContext()
    participant Mask as Masker
    participant UI as ui.InitFormatter()
    participant Data as data.InitWriter()
    participant Term as terminal.New()
    participant Cmd as Command Run

    Root->>IO: NewContext(opts...)
    IO->>Mask: newMasker(cfg)
    Mask-->>IO: Masker ready
    IO-->>Root: io.Context ready
    Root->>UI: InitFormatter(ioCtx)
    UI-->>Root: Formatter initialized
    Root->>Data: InitWriter(ioCtx)
    Data-->>Root: Data writer ready
    Root->>Term: New(config)
    Term-->>Root: Terminal ready
    Root->>Cmd: Execute
    Cmd->>UI: ui.Success("...") / ui.Markdown(...)
    UI->>IO: Write(UIStream, content) (masked)
    Cmd->>Data: data.WriteJSON(result)
    Data->>IO: Write(DataStream, content) (masked)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Areas requiring close attention:

  • pkg/io/masker.go — regex compilation, literal ordering, encoding variants, concurrency.
  • pkg/io/context.go & pkg/io/global.go — init sequencing, global state, thread-safety, error paths.
  • pkg/terminal/terminal.go & schema changes — color/TTY precedence logic and IsColorEnabled signature change; verify all call sites updated.
  • cmd/root.go — flag/env bindings, init order, and failure fallbacks.
  • Snapshot updates — ensure help text matches implemented flags and defaults.

Possibly related PRs

Suggested reviewers

  • aknysh

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: implementing a global UI formatter pattern to simplify output across the codebase.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch osterman/io-handling-prd

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/exec/version.go (1)

139-164: Fix: Test fails due to missing UI formatter initialization.

The pipeline failure shows TestDisplayVersionInFormat panics with "ui.InitFormatter() must be called before using UI functions." The test must initialize the I/O context and UI formatter before calling this function.

The test file needs to initialize the formatter:

// In the test setup
ioCtx, err := io.NewContext()
require.NoError(t, err)
ui.InitFormatter(ioCtx)

See cmd/about/about_test.go (lines 14-16) for the pattern.

🧹 Nitpick comments (22)
docs/prd/io-handling-strategy.md (2)

51-86: Add language identifier to fenced code block.

The ASCII diagram should have a language identifier for proper rendering. Use text or leave blank quotes to explicitly mark it as plain text.

Apply this diff:

-```
+```text
 ┌─────────────────────────────────────────────────────────────────┐

418-435: Add language identifier to fenced code block.

The decision tree diagram should have a language identifier for consistency.

Apply this diff:

-```
+```text
 When I need to output something:
pkg/io/masker.go (2)

112-136: Consider literal replacement order.

The comment on line 123 mentions sorting by length (longest first) but the implementation doesn't do this. If you have literals like "secret" and "secret123", the current implementation might mask "secret" first, leaving "123" exposed. Consider implementing the length-based sorting or document why it's not needed.

 func (m *masker) Mask(input string) string {
 	if !m.enabled || input == "" {
 		return input
 	}
 
 	m.mu.RLock()
 	defer m.mu.RUnlock()
 
 	masked := input
 
-	// Mask literals (exact matches)
-	// Sort by length (longest first) to avoid partial replacements
+	// Mask literals (exact matches) - sorted by length
+	literals := make([]string, 0, len(m.literals))
 	for literal := range m.literals {
-		if literal != "" {
-			masked = strings.ReplaceAll(masked, literal, MaskReplacement)
-		}
+		literals = append(literals, literal)
 	}
+	sort.Slice(literals, func(i, j int) bool {
+		return len(literals[i]) > len(literals[j])
+	})
+	for _, literal := range literals {
+		masked = strings.ReplaceAll(masked, literal, MaskReplacement)
+	}
 
 	// Mask regex patterns
 	for _, pattern := range m.patterns {
 		masked = pattern.ReplaceAllString(masked, MaskReplacement)
 	}
 
 	return masked
 }

95-110: AWS secret key pattern may be too broad.

The pattern [A-Za-z0-9/+=]{40} (line 108) will match any 40-character base64-like string, which could cause false positives for non-secret data. Consider whether this should be more restrictive or documented as best-effort.

Optionally, you could:

  1. Add a comment documenting the potential for false positives
  2. Consider requiring more context (e.g., proximity to the access key)
  3. Make this pattern configurable

The current approach is reasonable as a best-effort heuristic.

pkg/ui/formatter_test.go (2)

421-424: Initialize IO context with error checks in helpers.

createTestIOContext[WithProfile] ignores errors from iolib.NewContext(). Fail fast to avoid false positives when config/env break context construction.

Apply:

-func createTestIOContext() iolib.Context {
-	ctx, _ := iolib.NewContext()
-	return ctx
-}
+func createTestIOContext() iolib.Context {
+	ctx, err := iolib.NewContext()
+	if err != nil {
+		panic(err) // tests should fail loudly if IO context can't be built
+	}
+	return ctx
+}
-ctx, _ := iolib.NewContext(
+ctx, err := iolib.NewContext(
 	iolib.WithTerminal(&mockTerminal{profile: profile}),
 )
+if err != nil {
+	panic(err)
+}

Also applies to: 426-431


433-462: Prefer generated mocks via mockgen.

Guidelines require go.uber.org/mock-generated mocks; handwritten mockTerminal is fine for now but please add a //go:generate to produce a mock for iolib.Terminal in pkg/ui tests and migrate when convenient. This simplifies future interface changes.
Would you like a mockgen snippet added?

pkg/ui/output_test.go (1)

154-170: Add a negative test for Markdown errors.

Today you can’t inject a renderer failure. Add an option to inject a custom Formatter into Output, then add a test where RenderMarkdown returns an error and assert Markdown/MarkdownUI propagate it.
Follow-up diff for product code provided in pkg/ui/output.go comment.

pkg/io/terminal.go (1)

87-91: RestoreTitle is a no-op.

originalTitle is never populated. Either:

  • store the first set title and restore to it, or
  • call SetTitle("") to clear, and document behavior.
-func (t *terminal) RestoreTitle() {
-	if t.originalTitle != "" {
-		t.SetTitle(t.originalTitle)
-	}
-}
+func (t *terminal) RestoreTitle() {
+	// Best-effort: clear title if supported.
+	if t.IsTTY(StreamError) {
+		fmt.Fprint(os.Stderr, "\033]0;\007")
+	}
+}
pkg/io/masker_test.go (1)

123-131: Refactor AWS access key literal to avoid scanners.

Same approach for AWS key.

-accessKey := "AKIAIOSFODNN7EXAMPLE"
+accessKey := "AKIA" + "IOSFODNN7" + "EXAMPLE" // split to avoid scanners
docs/logging.md (1)

321-330: Update examples to the new UI API.

Docs earlier recommend ui.Success/Error/Data. Replace utils.PrintfMessageToTUI with ui helpers for consistency with this PR’s pattern.
Apply:

-// User feedback via TextUI
-utils.PrintfMessageToTUI("Deploying component 'vpc'...\n")
-utils.PrintfMessageToTUI("✓ Component deployed successfully!\n")
+// User feedback via UI
+ui.Info("Deploying component 'vpc'...")
+ui.Success("Component deployed successfully!")

Optionally add a note that UI writes to stderr and Data/Markdown to stdout. Based on learnings.

pkg/io/context_test.go (1)

385-403: Consider generated mocks.

Per guidelines, prefer mockgen-based mocks for Streams/Terminal/Masker to reduce drift. Keep as-is for now; migrate when convenient.

pkg/ui/output.go (2)

17-31: Add Go doc comments (and perf hook if applicable).

Exported functions must be documented; also add defer perf.Track(...) at the start if required by project conventions.

Apply:

-// NewOutput creates a new Output.
+// NewOutput creates a new Output with the given IO context and options.
+// It defaults to no trailing-whitespace trimming.
 func NewOutput(ioCtx io.Context, opts ...OutputOption) Output {
+	// defer perf.Track(ioCtx.Config().AtmosConfig, "ui.NewOutput")()
 	o := &output{
 		ioCtx:                  ioCtx,
 		formatter:              newFormatter(ioCtx),
 		trimTrailingWhitespace: false, // Default to false
 	}
@@
-// WithTrimTrailingWhitespace enables/disables trailing whitespace trimming.
+// WithTrimTrailingWhitespace enables or disables trailing whitespace trimming.
 func WithTrimTrailingWhitespace(enabled bool) OutputOption {

Please confirm the correct import path for perf.Track before adding.

Also applies to: 33-41


17-31: Optional: allow injecting a custom Formatter.

For better testability (e.g., forcing RenderMarkdown errors), add:

 type output struct {
 	ioCtx                  io.Context
 	formatter              Formatter
 	trimTrailingWhitespace bool
 }
 
 // NewOutput creates a new Output.
 func NewOutput(ioCtx io.Context, opts ...OutputOption) Output {
 	o := &output{
 		ioCtx:                  ioCtx,
-		formatter:              newFormatter(ioCtx),
+		formatter:              newFormatter(ioCtx),
 		trimTrailingWhitespace: false, // Default to false
 	}
@@
 type OutputOption func(*output)
 
+// WithFormatter overrides the default formatter (for testing/customization).
+func WithFormatter(f Formatter) OutputOption {
+	return func(o *output) { o.formatter = f }
+}

Update tests to inject a failing formatter where needed.

pkg/io/context.go (2)

134-141: Don’t silently ignore viper.Unmarshal errors.

If settings is set but unmarshal fails, return a wrapped error (or at least log it) to aid troubleshooting.

-	if viper.IsSet("settings") {
-		var atmosConfig schema.AtmosConfiguration
-		if err := viper.Unmarshal(&atmosConfig); err == nil {
-			cfg.AtmosConfig = atmosConfig
-		}
-	}
+	if viper.IsSet("settings") {
+		var atmosConfig schema.AtmosConfiguration
+		if err := viper.Unmarshal(&atmosConfig); err != nil {
+			return nil, fmt.Errorf("io: unmarshal atmos settings: %w", err)
+		}
+		cfg.AtmosConfig = atmosConfig
+	}

Follow Go error‑wrapping idioms. As per coding guidelines.


54-92: Exported method doc comments should start with the identifier.

Comments like “Channel access – explicit and clear.” won’t satisfy godoc/godot linters for exported methods (Data/UI/RawData/RawUI/...).

  • Rewrite to “Data returns the stdout writer.”, “UI returns the stderr writer.”, etc., ending with periods. As per coding guidelines.
pkg/ui/formatter.go (4)

280-293: Prefer standard style options over WithStylePath.

Use built‑in style selectors (WithAutoStyle or WithStandardStyle("notty"/"dark")) rather than WithStylePath("dark"), which expects a file path in some versions.

-	// Select style based on color profile
-	var styleName string
-	switch f.ioCtx.Terminal().ColorProfile() {
-	case io.ColorNone:
-		styleName = "notty"
-	case io.Color16, io.Color256, io.ColorTrue:
-		// Use dark style as default - this will be theme-aware in PR #1433
-		styleName = "dark"
-	}
-
-	if styleName != "" {
-		opts = append(opts, glamour.WithStylePath(styleName))
-	}
+	// Select style based on color profile.
+	switch f.ioCtx.Terminal().ColorProfile() {
+	case io.ColorNone:
+		opts = append(opts, glamour.WithStandardStyle("notty"))
+	default:
+		opts = append(opts, glamour.WithAutoStyle())
+	}

References: Glamour README and pkg docs. (github.com)


241-257: Ignore error intentionally or handle it explicitly.

rendered, _ := f.RenderMarkdown(content) drops the error. If intentional, add a short comment (“// best‑effort; fall back handled in RenderMarkdown”). Otherwise, propagate/log.


136-145: Add perf tracking to exported constructor.

Mirror perf tracking in NewFormatter if your project requires it.


1-14: Lint: ensure top comments end with periods.

A few exported doc comments lack trailing periods and may trip godot in golangci‑lint. Quick pass recommended.

As per coding guidelines.

pkg/ui/interfaces.go (2)

1-8: Generate mocks for interfaces.

Add //go:generate mockgen for Formatter and Output to satisfy testability guidance.

Example (paths to adjust):

//go:generate mockgen -destination=../../mocks/mock_ui_formatter.go -package=mocks github.com/cloudposse/atmos/pkg/ui Formatter
//go:generate mockgen -destination=../../mocks/mock_ui_output.go -package=mocks github.com/cloudposse/atmos/pkg/ui Output

As per coding guidelines.


62-81: Doc nits: periods and concise summaries.

Tighten comments and end sentences with periods to appease godot.

As per coding guidelines.

pkg/io/interfaces.go (1)

152-176: API surface LGTM; minor doc polish.

Interfaces and enums read clean. Consider running godot and adding //go:generate stringer if you want auto‑stringers later (optional).

Also applies to: 178-200, 202-239

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1bc8f40 and 7c51795.

📒 Files selected for processing (27)
  • cmd/about/about.go (2 hunks)
  • cmd/about/about_test.go (1 hunks)
  • cmd/internal/registry.go (1 hunks)
  • cmd/root.go (2 hunks)
  • docs/developing-atmos-commands.md (1 hunks)
  • docs/io-and-ui-output.md (1 hunks)
  • docs/logging.md (1 hunks)
  • docs/prd/io-handling-strategy.md (1 hunks)
  • docs/structured-logging.md (1 hunks)
  • internal/exec/version.go (1 hunks)
  • internal/tui/utils/utils.go (1 hunks)
  • pkg/io/context.go (1 hunks)
  • pkg/io/context_test.go (1 hunks)
  • pkg/io/example_test.go (1 hunks)
  • pkg/io/interfaces.go (1 hunks)
  • pkg/io/masker.go (1 hunks)
  • pkg/io/masker_test.go (1 hunks)
  • pkg/io/streams.go (1 hunks)
  • pkg/io/streams_test.go (1 hunks)
  • pkg/io/terminal.go (1 hunks)
  • pkg/io/terminal_test.go (1 hunks)
  • pkg/schema/schema.go (1 hunks)
  • pkg/ui/formatter.go (1 hunks)
  • pkg/ui/formatter_test.go (1 hunks)
  • pkg/ui/interfaces.go (1 hunks)
  • pkg/ui/output.go (1 hunks)
  • pkg/ui/output_test.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
cmd/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

cmd/**/*.go: Use Cobra's recommended command structure with a root command and subcommands
Implement each CLI command in a separate file under cmd/
Use Viper for managing configuration, environment variables, and flags in the CLI
Keep separation of concerns between CLI interface (cmd) and business logic
Use kebab-case for command-line flags
Provide comprehensive help text for all commands and flags
Include examples in Cobra command help
Use Viper for configuration management; support files, env vars, and flags with precedence flags > env > config > defaults
Follow single responsibility; separate command interface from business logic
Provide meaningful user feedback and include progress indicators for long-running operations
Provide clear error messages to users and troubleshooting hints where appropriate

cmd/**/*.go: New CLI commands must use the command registry pattern via CommandProvider and register through the command registry (see cmd/internal/registry.go).
Commands should embed *_usage.md via //go:embed and render with utils.PrintfMarkdown().
UI (prompts/status) must write to stderr; data outputs to stdout; logging only for system events (never for UI).
For non-standard execution paths, capture telemetry with telemetry.CaptureCmd(); normal paths are auto-enabled via RootCmd.ExecuteC(). Never capture user data.

Files:

  • cmd/internal/registry.go
  • cmd/about/about_test.go
  • cmd/root.go
  • cmd/about/about.go
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments

**/*.go: Define interfaces for major functionality and use dependency injection to enable testability.
Generate mocks using go.uber.org/mock/mockgen via //go:generate directives (never manual mocks).
Prefer functional Options pattern instead of functions with many parameters for configuration.
Use context.Context only for cancellation, deadlines/timeouts, and request-scoped values; never for configuration or dependencies; context should be the first parameter.
All comments must end with periods (godot linter).
Preserve helpful existing comments; update them to match code when refactoring; only remove when incorrect, redundant, or code removed.
Organize imports in three groups (stdlib, third-party, Atmos) separated by blank lines and sorted alphabetically; maintain aliases cfg, log, u, errUtils.
Add defer perf.Track(atmosConfig, "pkg.FuncName")() (or nil if no atmosConfig) plus a blank line at the start of all public functions for performance tracking.
Use static errors from errors/errors.go; wrap with fmt.Errorf("%w") for chaining; use errors.Join for independent errors; avoid dynamic errors and string comparison; use errors.Is for checks.
Never use //revive:disable:file-length-limit to bypass file size limits; keep files small and focused (<600 lines).
Environment variables must be bound with viper.BindEnv using ATMOS_ prefix (e.g., viper.BindEnv("ATMOS_VAR", "ATMOS_VAR", "FALLBACK")).
Ensure cross-platform compatibility: use filepath.Join instead of hardcoded path separators and prefer SDKs over shelling out to binaries.

Files:

  • cmd/internal/registry.go
  • pkg/ui/output_test.go
  • internal/tui/utils/utils.go
  • cmd/about/about_test.go
  • pkg/ui/interfaces.go
  • cmd/root.go
  • pkg/schema/schema.go
  • pkg/ui/output.go
  • pkg/io/streams_test.go
  • pkg/io/terminal.go
  • pkg/io/context_test.go
  • pkg/io/masker_test.go
  • internal/exec/version.go
  • pkg/io/masker.go
  • pkg/io/terminal_test.go
  • pkg/ui/formatter_test.go
  • pkg/io/context.go
  • cmd/about/about.go
  • pkg/io/example_test.go
  • pkg/io/streams.go
  • pkg/ui/formatter.go
  • pkg/io/interfaces.go
**/!(*_test).go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Document all exported functions, types, and methods with Go doc comments

Files:

  • cmd/internal/registry.go
  • internal/tui/utils/utils.go
  • pkg/ui/interfaces.go
  • cmd/root.go
  • pkg/schema/schema.go
  • pkg/ui/output.go
  • pkg/io/terminal.go
  • internal/exec/version.go
  • pkg/io/masker.go
  • pkg/io/context.go
  • cmd/about/about.go
  • pkg/io/streams.go
  • pkg/ui/formatter.go
  • pkg/io/interfaces.go
{cmd,pkg/ui}/**/*.go

📄 CodeRabbit inference engine (CLAUDE.md)

Use theme colors from pkg/ui/theme/colors.go for UI elements.

Files:

  • cmd/internal/registry.go
  • pkg/ui/output_test.go
  • cmd/about/about_test.go
  • pkg/ui/interfaces.go
  • cmd/root.go
  • pkg/ui/output.go
  • pkg/ui/formatter_test.go
  • cmd/about/about.go
  • pkg/ui/formatter.go
pkg/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Place business logic in pkg rather than in cmd

Files:

  • pkg/ui/output_test.go
  • pkg/ui/interfaces.go
  • pkg/schema/schema.go
  • pkg/ui/output.go
  • pkg/io/streams_test.go
  • pkg/io/terminal.go
  • pkg/io/context_test.go
  • pkg/io/masker_test.go
  • pkg/io/masker.go
  • pkg/io/terminal_test.go
  • pkg/ui/formatter_test.go
  • pkg/io/context.go
  • pkg/io/example_test.go
  • pkg/io/streams.go
  • pkg/ui/formatter.go
  • pkg/io/interfaces.go
**/*_test.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*_test.go: Every new feature must include comprehensive unit tests
Test both happy paths and error conditions
Use table-driven tests for multiple scenarios

**/*_test.go: Prefer unit tests with mocks over integration tests; use interfaces + DI; table-driven tests for coverage; target >80% coverage.
Tests must exercise production code paths; avoid duplicating implementation logic in tests.
Use t.Skipf("reason") with clear context when skipping tests; CLI tests may auto-build temp binaries.

Files:

  • pkg/ui/output_test.go
  • cmd/about/about_test.go
  • pkg/io/streams_test.go
  • pkg/io/context_test.go
  • pkg/io/masker_test.go
  • pkg/io/terminal_test.go
  • pkg/ui/formatter_test.go
  • pkg/io/example_test.go
cmd/**/*_test.go

📄 CodeRabbit inference engine (CLAUDE.md)

Use cmd.NewTestKit(t) for any tests that touch RootCmd to auto-clean RootCmd state.

Files:

  • cmd/about/about_test.go
docs/prd/[a-z0-9-]*.md

📄 CodeRabbit inference engine (CLAUDE.md)

All PRDs must be placed under docs/prd/ with kebab-case filenames.

Files:

  • docs/prd/io-handling-strategy.md
🧠 Learnings (4)
📚 Learning: 2025-09-13T18:06:07.674Z
Learnt from: samtholiya
PR: cloudposse/atmos#1466
File: toolchain/list.go:39-42
Timestamp: 2025-09-13T18:06:07.674Z
Learning: In the cloudposse/atmos repository, for UI messages in the toolchain package, use utils.PrintfMessageToTUI instead of log.Error or fmt.Fprintln(os.Stderr, ...). Import pkg/utils with alias "u" to follow the established pattern.

Applied to files:

  • cmd/root.go
  • docs/logging.md
📚 Learning: 2024-12-11T18:40:12.808Z
Learnt from: Listener430
PR: cloudposse/atmos#844
File: cmd/helmfile.go:37-37
Timestamp: 2024-12-11T18:40:12.808Z
Learning: In the atmos project, `cliConfig` is initialized within the `cmd` package in `root.go` and can be used in other command files.

Applied to files:

  • cmd/root.go
📚 Learning: 2025-10-24T14:51:19.340Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T14:51:19.340Z
Learning: Applies to cmd/**/*.go : UI (prompts/status) must write to stderr; data outputs to stdout; logging only for system events (never for UI).

Applied to files:

  • docs/io-and-ui-output.md
  • docs/logging.md
📚 Learning: 2025-09-23T02:30:42.362Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-09-23T02:30:42.362Z
Learning: Applies to **/*_test.go : Every new feature must include comprehensive unit tests

Applied to files:

  • pkg/io/masker_test.go
  • pkg/io/example_test.go
🧬 Code graph analysis (20)
pkg/ui/output_test.go (4)
pkg/ui/output.go (2)
  • NewOutput (18-31)
  • WithTrimTrailingWhitespace (37-41)
pkg/ui/interfaces.go (2)
  • Formatter (24-60)
  • Output (97-124)
pkg/io/interfaces.go (1)
  • Context (18-39)
pkg/io/context.go (3)
  • NewContext (23-52)
  • WithStreams (97-101)
  • WithTerminal (104-108)
internal/tui/utils/utils.go (1)
pkg/ui/formatter.go (1)
  • Data (45-48)
cmd/about/about_test.go (2)
pkg/io/context.go (1)
  • NewContext (23-52)
pkg/ui/formatter.go (1)
  • InitFormatter (23-28)
pkg/ui/interfaces.go (3)
pkg/ui/formatter.go (9)
  • Success (70-74)
  • Successf (77-81)
  • Warning (98-102)
  • Warningf (105-109)
  • Error (84-88)
  • Errorf (91-95)
  • Info (112-116)
  • Infof (119-123)
  • Markdown (59-61)
pkg/io/interfaces.go (2)
  • ColorProfile (153-153)
  • Context (18-39)
internal/tui/utils/utils.go (1)
  • RenderMarkdown (52-89)
cmd/root.go (2)
pkg/io/context.go (1)
  • NewContext (23-52)
pkg/ui/formatter.go (2)
  • Errorf (91-95)
  • InitFormatter (23-28)
pkg/ui/output.go (4)
pkg/io/interfaces.go (2)
  • Context (18-39)
  • Streams (44-67)
pkg/ui/interfaces.go (2)
  • Formatter (24-60)
  • Output (97-124)
pkg/ui/formatter.go (5)
  • Error (84-88)
  • Success (70-74)
  • Warning (98-102)
  • Info (112-116)
  • Markdown (59-61)
internal/tui/utils/utils.go (1)
  • RenderMarkdown (52-89)
pkg/io/streams_test.go (1)
pkg/io/interfaces.go (1)
  • Config (134-150)
pkg/io/terminal.go (2)
pkg/io/interfaces.go (11)
  • Config (134-150)
  • ColorProfile (153-153)
  • Terminal (71-98)
  • StreamOutput (184-184)
  • StreamError (185-185)
  • Channel (204-204)
  • DataChannel (207-207)
  • UIChannel (208-208)
  • InputChannel (209-209)
  • StreamType (180-180)
  • StreamInput (183-183)
pkg/schema/schema.go (1)
  • Terminal (208-218)
pkg/io/context_test.go (3)
pkg/io/context.go (4)
  • NewContext (23-52)
  • WithStreams (97-101)
  • WithTerminal (104-108)
  • WithMasker (111-115)
pkg/io/interfaces.go (13)
  • Streams (44-67)
  • Terminal (71-98)
  • Config (134-150)
  • Masker (101-131)
  • ColorProfile (153-153)
  • ColorNone (156-156)
  • ColorTrue (159-159)
  • Color256 (158-158)
  • Color16 (157-157)
  • StreamType (180-180)
  • StreamInput (183-183)
  • StreamOutput (184-184)
  • StreamError (185-185)
pkg/schema/schema.go (4)
  • Terminal (208-218)
  • AtmosConfiguration (27-65)
  • Settings (758-762)
  • AtmosSettings (253-273)
pkg/io/masker_test.go (1)
pkg/io/interfaces.go (2)
  • Config (134-150)
  • Masker (101-131)
internal/exec/version.go (2)
internal/tui/utils/utils.go (1)
  • Data (24-26)
pkg/ui/formatter.go (1)
  • Data (45-48)
pkg/io/masker.go (1)
pkg/io/interfaces.go (2)
  • Config (134-150)
  • Masker (101-131)
pkg/io/terminal_test.go (2)
pkg/io/interfaces.go (9)
  • Config (134-150)
  • ColorProfile (153-153)
  • ColorNone (156-156)
  • ColorTrue (159-159)
  • StreamInput (183-183)
  • StreamOutput (184-184)
  • StreamError (185-185)
  • StreamType (180-180)
  • Terminal (71-98)
pkg/schema/schema.go (4)
  • AtmosConfiguration (27-65)
  • Settings (758-762)
  • AtmosSettings (253-273)
  • Terminal (208-218)
pkg/ui/formatter_test.go (5)
pkg/ui/formatter.go (8)
  • Error (84-88)
  • Errorf (91-95)
  • Success (70-74)
  • Warning (98-102)
  • Info (112-116)
  • Successf (77-81)
  • Warningf (105-109)
  • Infof (119-123)
pkg/io/interfaces.go (7)
  • ColorProfile (153-153)
  • ColorNone (156-156)
  • Color16 (157-157)
  • Color256 (158-158)
  • ColorTrue (159-159)
  • Context (18-39)
  • Config (134-150)
internal/tui/utils/utils.go (1)
  • RenderMarkdown (52-89)
pkg/io/context.go (2)
  • NewContext (23-52)
  • WithTerminal (104-108)
pkg/ui/interfaces.go (1)
  • Formatter (24-60)
pkg/io/context.go (2)
pkg/io/interfaces.go (10)
  • Streams (44-67)
  • Terminal (71-98)
  • Config (134-150)
  • Masker (101-131)
  • Context (18-39)
  • ColorProfile (153-153)
  • ColorNone (156-156)
  • ColorTrue (159-159)
  • Color256 (158-158)
  • Color16 (157-157)
pkg/schema/schema.go (4)
  • Terminal (208-218)
  • Context (411-426)
  • AtmosConfiguration (27-65)
  • Settings (758-762)
cmd/about/about.go (2)
pkg/ui/formatter.go (1)
  • Markdown (59-61)
cmd/markdown/content.go (1)
  • AboutMarkdown (8-8)
pkg/io/example_test.go (3)
pkg/io/context.go (1)
  • NewContext (23-52)
pkg/ui/formatter.go (6)
  • NewFormatter (138-145)
  • Data (45-48)
  • Success (70-74)
  • Warning (98-102)
  • Error (84-88)
  • Info (112-116)
pkg/io/interfaces.go (4)
  • Terminal (71-98)
  • UIChannel (208-208)
  • DataChannel (207-207)
  • ColorProfile (153-153)
pkg/io/streams.go (2)
pkg/io/interfaces.go (3)
  • Masker (101-131)
  • Config (134-150)
  • Streams (44-67)
pkg/ui/formatter.go (1)
  • Error (84-88)
pkg/ui/formatter.go (4)
pkg/ui/interfaces.go (2)
  • Formatter (24-60)
  • StyleSet (64-81)
pkg/io/interfaces.go (8)
  • Context (18-39)
  • Terminal (71-98)
  • ColorProfile (153-153)
  • ColorNone (156-156)
  • Config (134-150)
  • Color16 (157-157)
  • Color256 (158-158)
  • ColorTrue (159-159)
pkg/schema/schema.go (2)
  • Context (411-426)
  • Terminal (208-218)
pkg/ui/theme/colors.go (6)
  • ColorCyan (12-12)
  • ColorBlue (14-14)
  • ColorWhite (20-20)
  • ColorGreen (11-11)
  • ColorOrange (18-18)
  • ColorRed (16-16)
pkg/io/interfaces.go (4)
internal/tui/utils/utils.go (1)
  • Data (24-26)
pkg/ui/formatter.go (2)
  • Data (45-48)
  • Error (84-88)
pkg/schema/schema.go (2)
  • Terminal (208-218)
  • AtmosConfiguration (27-65)
pkg/ui/interfaces.go (1)
  • Output (97-124)
🪛 GitHub Actions: Tests
internal/exec/version.go

[error] 154-154: TestDisplayVersionInFormat failed with panic: ui.InitFormatter() must be called before using UI functions.

pkg/ui/formatter.go

[error] 36-36: ui.InitFormatter() must be called before using UI functions. This panic occurred during TestDisplayVersionInFormat in internal/exec version tests.

🪛 Gitleaks (8.28.0)
pkg/io/masker_test.go

[high] 111-111: Uncovered a GitHub Personal Access Token, potentially leading to unauthorized repository access and sensitive content exposure.

(github-pat)


[high] 52-52: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🪛 LanguageTool
docs/io-and-ui-output.md

[grammar] ~11-~11: Please add a punctuation mark at the end of paragraph.
Context: ...* - Help/docs → ui.Markdown() → stdout ## UI vs Logging: When to Use What ...

(PUNCTUATION_PARAGRAPH_END)


[typographical] ~13-~13: In American English, use a period after an abbreviation.
Context: ...* → ui.Markdown() → stdout ## UI vs Logging: When to Use What **Don't conf...

(MISSING_PERIOD_AFTER_ABBREVIATION)


[typographical] ~19-~19: Consider using a typographic opening quote here.
Context: ...Success(), ui.Error(), ui.Data()` | "✓ Configuration loaded", JSON output | |...

(EN_QUOTES)


[typographical] ~19-~19: Consider using a typographic close quote here.
Context: ..., ui.Data()` | "✓ Configuration loaded", JSON output | | Logging | Develope...

(EN_QUOTES)


[typographical] ~20-~20: Consider using a typographic opening quote here.
Context: ...rators | log.Debug(), log.Error() | "config.LoadAtmosYAML: parsing file" | *...

(EN_QUOTES)


[typographical] ~20-~20: Consider using a typographic close quote here.
Context: ...)` | "config.LoadAtmosYAML: parsing file" | Key distinction: - **UI output i...

(EN_QUOTES)


[typographical] ~26-~26: Consider using a typographic opening quote here.
Context: ...t user doesn't need it Quick test: "What happens if I disable logging?" - **...

(EN_QUOTES)


[typographical] ~26-~26: Consider using a typographic close quote here.
Context: ...t:** "What happens if I disable logging?" - Breaks user experience → It's UI ...

(EN_QUOTES)


[grammar] ~28-~28: Please add a punctuation mark at the end of paragraph.
Context: ... unaffected** → It's logging, use log package Examples: ```go // ❌ WRONG - usin...

(PUNCTUATION_PARAGRAPH_END)


[grammar] ~755-~755: Please add a punctuation mark at the end of paragraph.
Context: ....) - Respect TTY detection for adaptive behavior

(PUNCTUATION_PARAGRAPH_END)

docs/logging.md

[typographical] ~15-~15: Consider using a typographic opening quote here.
Context: ...io-and-ui-output.md)). Quick test: "What happens if I disable logging (`--lo...

(EN_QUOTES)

docs/prd/io-handling-strategy.md

[typographical] ~17-~17: In American English, use a period after an abbreviation.
Context: ...* to know: - Where to send data (stdout vs stderr) - When to use formatting (UI) v...

(MISSING_PERIOD_AFTER_ABBREVIATION)


[typographical] ~34-~34: Consider using typographic quotation marks here.
Context: ...) ``` The confusion: - Is markdown "data" or "UI"? - Why does ui.Output handle ...

(EN_QUOTES)


[typographical] ~34-~34: Consider using typographic quotation marks here.
Context: ...he confusion:** - Is markdown "data" or "UI"? - Why does ui.Output handle both dat...

(EN_QUOTES)


[typographical] ~39-~39: Consider using a typographic opening quote here.
Context: .../O and UI? ### Root Cause We conflated "where to write" (I/O concern) with "how ...

(EN_QUOTES)


[typographical] ~39-~39: Consider using a typographic close quote here.
Context: ... Root Cause We conflated "where to write" (I/O concern) with "how to format" (UI ...

(EN_QUOTES)


[typographical] ~39-~39: Consider using a typographic opening quote here.
Context: ...ted "where to write" (I/O concern) with "how to format" (UI concern). **Markdown...

(EN_QUOTES)


[typographical] ~39-~39: Consider using a typographic close quote here.
Context: ...write" (I/O concern) with "how to format" (UI concern). **Markdown rendering is ...

(EN_QUOTES)


[grammar] ~43-~43: Please add a punctuation mark at the end of paragraph.
Context: ... Interactive prompts, status messages → stderr The current design doesn't make this d...

(PUNCTUATION_PARAGRAPH_END)


[typographical] ~90-~90: Consider using a typographic opening quote here.
Context: ...ion of Concerns I/O Layer answers: "Where does it go?" (stdout/stderr) and "...

(EN_QUOTES)


[typographical] ~90-~90: Consider using a typographic close quote here.
Context: ...I/O Layer answers:* "Where does it go?" (stdout/stderr) and "What can the termi...

(EN_QUOTES)


[typographical] ~90-~90: Consider using a typographic opening quote here.
Context: ..."Where does it go?" (stdout/stderr) and "What can the terminal do?" (color/width)...

(EN_QUOTES)


[typographical] ~90-~90: Consider using a typographic close quote here.
Context: ...t/stderr) and "What can the terminal do?" (color/width) **Presentation Layer ans...

(EN_QUOTES)


[typographical] ~92-~92: Consider using a typographic opening quote here.
Context: ...width) Presentation Layer answers: "How should it look?" (markdown/colors/st...

(EN_QUOTES)


[typographical] ~92-~92: Consider using a typographic close quote here.
Context: ...on Layer answers:** "How should it look?" (markdown/colors/styles) **Application...

(EN_QUOTES)


[typographical] ~94-~94: Consider using a typographic opening quote here.
Context: ...styles) Application Layer answers: "What do I show?" (data/messages/help) #...

(EN_QUOTES)


[typographical] ~94-~94: Consider using a typographic close quote here.
Context: ...cation Layer answers:** "What do I show?" (data/messages/help) ## Proposed Solut...

(EN_QUOTES)


[grammar] ~133-~133: Please add a punctuation mark at the end of paragraph.
Context: ...)` to write formatted strings to chosen channel ### Core Interfaces - I/O Layer **Pur...

(PUNCTUATION_PARAGRAPH_END)


[grammar] ~206-~206: Please add a punctuation mark at the end of paragraph.
Context: ...down()` methods - those are application concerns ### Core Interfaces - Presentation Lay...

(PUNCTUATION_PARAGRAPH_END)


[grammar] ~261-~261: Please add a punctuation mark at the end of paragraph.
Context: ...olors/styles - Pure functions - no side effects ### Usage Patterns #### Pattern 1: Da...

(PUNCTUATION_PARAGRAPH_END)


[typographical] ~476-~476: In American English, use a period after an abbreviation.
Context: ...Human display } ``` ## Comparison: Old vs New ### Old Approach (Current Implemen...

(MISSING_PERIOD_AFTER_ABBREVIATION)


[typographical] ~491-~491: In American English, use a period after an abbreviation.
Context: ...- Unclear which methods write to stdout vs stderr - Markdown can be data or UI, bu...

(MISSING_PERIOD_AFTER_ABBREVIATION)


[grammar] ~519-~519: Please add a punctuation mark at the end of paragraph.
Context: ...Fprintf()` - no need to learn new Print methods ## Implementation Strategy ### Phase ...

(PUNCTUATION_PARAGRAPH_END)


[style] ~601-~601: Consider using the typographical ellipsis character here instead.
Context: ...on A:** Minimal - developers always use fmt.Fprintf(io.Data(), ...) directly - ✅ Simple, explicit, no mag...

(ELLIPSIS)


[grammar] ~603-~603: Please add a punctuation mark at the end of paragraph.
Context: ...e, explicit, no magic - ❌ More verbose, repetitive Option B: Provide `uihelper.Helper...

(PUNCTUATION_PARAGRAPH_END)


[grammar] ~607-~607: Please add a punctuation mark at the end of paragraph.
Context: ...common cases - ❌ Another abstraction to learn Recommendation: Start with Option ...

(PUNCTUATION_PARAGRAPH_END)


[style] ~644-~644: Since ownership is already implied, this phrasing may be redundant.
Context: ...rrent:** Separate markdown package with its own renderer Proposed: Keep it, but ha...

(PRP_OWN)


[grammar] ~646-~646: Please add a punctuation mark at the end of paragraph.
Context: ...Formatter.RenderMarkdown()` delegate to it ```go func (f *formatter) RenderMarkdo...

(PUNCTUATION_PARAGRAPH_END)


[grammar] ~671-~671: Please add a punctuation mark at the end of paragraph.
Context: ...es in CLAUDE.md for all common output scenarios ### Code Quality - ✅ I/O layer has ZER...

(PUNCTUATION_PARAGRAPH_END)


[typographical] ~676-~676: In American English, use a period after an abbreviation.
Context: ... always explicitly choose channel (data vs UI) - ✅ Lint rules prevent mixing conce...

(MISSING_PERIOD_AFTER_ABBREVIATION)


[grammar] ~677-~677: Please add a punctuation mark at the end of paragraph.
Context: ...ta vs UI) - ✅ Lint rules prevent mixing concerns ### Testability - ✅ All I/O is mockabl...

(PUNCTUATION_PARAGRAPH_END)


[grammar] ~682-~682: Please add a punctuation mark at the end of paragraph.
Context: ...✅ 90%+ test coverage for both pkg/io/ and pkg/ui/ ## Next Steps 1. **Review t...

(PUNCTUATION_PARAGRAPH_END)


[grammar] ~693-~693: Please add a punctuation mark at the end of paragraph.
Context: ... Gather feedback before rolling out broadly ## References - [NO_COLOR Standard](h...

(PUNCTUATION_PARAGRAPH_END)

🪛 markdownlint-cli2 (0.18.1)
docs/prd/io-handling-strategy.md

51-51: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


144-144: Hard tabs
Column: 1

(MD010, no-hard-tabs)


145-145: Hard tabs
Column: 1

(MD010, no-hard-tabs)


146-146: Hard tabs
Column: 1

(MD010, no-hard-tabs)


147-147: Hard tabs
Column: 1

(MD010, no-hard-tabs)


149-149: Hard tabs
Column: 1

(MD010, no-hard-tabs)


150-150: Hard tabs
Column: 1

(MD010, no-hard-tabs)


151-151: Hard tabs
Column: 1

(MD010, no-hard-tabs)


153-153: Hard tabs
Column: 1

(MD010, no-hard-tabs)


154-154: Hard tabs
Column: 1

(MD010, no-hard-tabs)


156-156: Hard tabs
Column: 1

(MD010, no-hard-tabs)


157-157: Hard tabs
Column: 1

(MD010, no-hard-tabs)


159-159: Hard tabs
Column: 1

(MD010, no-hard-tabs)


160-160: Hard tabs
Column: 1

(MD010, no-hard-tabs)


166-166: Hard tabs
Column: 1

(MD010, no-hard-tabs)


167-167: Hard tabs
Column: 1

(MD010, no-hard-tabs)


168-168: Hard tabs
Column: 1

(MD010, no-hard-tabs)


169-169: Hard tabs
Column: 1

(MD010, no-hard-tabs)


170-170: Hard tabs
Column: 1

(MD010, no-hard-tabs)


172-172: Hard tabs
Column: 1

(MD010, no-hard-tabs)


173-173: Hard tabs
Column: 1

(MD010, no-hard-tabs)


174-174: Hard tabs
Column: 1

(MD010, no-hard-tabs)


175-175: Hard tabs
Column: 1

(MD010, no-hard-tabs)


177-177: Hard tabs
Column: 1

(MD010, no-hard-tabs)


178-178: Hard tabs
Column: 1

(MD010, no-hard-tabs)


179-179: Hard tabs
Column: 1

(MD010, no-hard-tabs)


186-186: Hard tabs
Column: 1

(MD010, no-hard-tabs)


187-187: Hard tabs
Column: 1

(MD010, no-hard-tabs)


188-188: Hard tabs
Column: 1

(MD010, no-hard-tabs)


195-195: Hard tabs
Column: 1

(MD010, no-hard-tabs)


196-196: Hard tabs
Column: 1

(MD010, no-hard-tabs)


197-197: Hard tabs
Column: 1

(MD010, no-hard-tabs)


198-198: Hard tabs
Column: 1

(MD010, no-hard-tabs)


218-218: Hard tabs
Column: 1

(MD010, no-hard-tabs)


219-219: Hard tabs
Column: 1

(MD010, no-hard-tabs)


220-220: Hard tabs
Column: 1

(MD010, no-hard-tabs)


221-221: Hard tabs
Column: 1

(MD010, no-hard-tabs)


222-222: Hard tabs
Column: 1

(MD010, no-hard-tabs)


223-223: Hard tabs
Column: 1

(MD010, no-hard-tabs)


225-225: Hard tabs
Column: 1

(MD010, no-hard-tabs)


226-226: Hard tabs
Column: 1

(MD010, no-hard-tabs)


227-227: Hard tabs
Column: 1

(MD010, no-hard-tabs)


228-228: Hard tabs
Column: 1

(MD010, no-hard-tabs)


230-230: Hard tabs
Column: 1

(MD010, no-hard-tabs)


231-231: Hard tabs
Column: 1

(MD010, no-hard-tabs)


233-233: Hard tabs
Column: 1

(MD010, no-hard-tabs)


234-234: Hard tabs
Column: 1

(MD010, no-hard-tabs)


236-236: Hard tabs
Column: 1

(MD010, no-hard-tabs)


237-237: Hard tabs
Column: 1

(MD010, no-hard-tabs)


238-238: Hard tabs
Column: 1

(MD010, no-hard-tabs)


246-246: Hard tabs
Column: 1

(MD010, no-hard-tabs)


247-247: Hard tabs
Column: 1

(MD010, no-hard-tabs)


248-248: Hard tabs
Column: 1

(MD010, no-hard-tabs)


249-249: Hard tabs
Column: 1

(MD010, no-hard-tabs)


250-250: Hard tabs
Column: 1

(MD010, no-hard-tabs)


251-251: Hard tabs
Column: 1

(MD010, no-hard-tabs)


252-252: Hard tabs
Column: 1

(MD010, no-hard-tabs)


253-253: Hard tabs
Column: 1

(MD010, no-hard-tabs)


324-324: Hard tabs
Column: 1

(MD010, no-hard-tabs)


325-325: Hard tabs
Column: 1

(MD010, no-hard-tabs)


341-341: Hard tabs
Column: 1

(MD010, no-hard-tabs)


342-342: Hard tabs
Column: 1

(MD010, no-hard-tabs)


346-346: Hard tabs
Column: 1

(MD010, no-hard-tabs)


351-351: Hard tabs
Column: 1

(MD010, no-hard-tabs)


355-355: Hard tabs
Column: 1

(MD010, no-hard-tabs)


356-356: Hard tabs
Column: 1

(MD010, no-hard-tabs)


357-357: Hard tabs
Column: 1

(MD010, no-hard-tabs)


358-358: Hard tabs
Column: 1

(MD010, no-hard-tabs)


359-359: Hard tabs
Column: 1

(MD010, no-hard-tabs)


360-360: Hard tabs
Column: 1

(MD010, no-hard-tabs)


361-361: Hard tabs
Column: 1

(MD010, no-hard-tabs)


366-366: Hard tabs
Column: 1

(MD010, no-hard-tabs)


370-370: Hard tabs
Column: 1

(MD010, no-hard-tabs)


371-371: Hard tabs
Column: 1

(MD010, no-hard-tabs)


372-372: Hard tabs
Column: 1

(MD010, no-hard-tabs)


376-376: Hard tabs
Column: 1

(MD010, no-hard-tabs)


377-377: Hard tabs
Column: 1

(MD010, no-hard-tabs)


378-378: Hard tabs
Column: 1

(MD010, no-hard-tabs)


382-382: Hard tabs
Column: 1

(MD010, no-hard-tabs)


383-383: Hard tabs
Column: 1

(MD010, no-hard-tabs)


384-384: Hard tabs
Column: 1

(MD010, no-hard-tabs)


388-388: Hard tabs
Column: 1

(MD010, no-hard-tabs)


389-389: Hard tabs
Column: 1

(MD010, no-hard-tabs)


390-390: Hard tabs
Column: 1

(MD010, no-hard-tabs)


391-391: Hard tabs
Column: 1

(MD010, no-hard-tabs)


392-392: Hard tabs
Column: 1

(MD010, no-hard-tabs)


393-393: Hard tabs
Column: 1

(MD010, no-hard-tabs)


394-394: Hard tabs
Column: 1

(MD010, no-hard-tabs)


399-399: Hard tabs
Column: 1

(MD010, no-hard-tabs)


400-400: Hard tabs
Column: 1

(MD010, no-hard-tabs)


402-402: Hard tabs
Column: 1

(MD010, no-hard-tabs)


404-404: Hard tabs
Column: 1

(MD010, no-hard-tabs)


405-405: Hard tabs
Column: 1

(MD010, no-hard-tabs)


406-406: Hard tabs
Column: 1

(MD010, no-hard-tabs)


408-408: Hard tabs
Column: 1

(MD010, no-hard-tabs)


418-418: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


470-470: Hard tabs
Column: 1

(MD010, no-hard-tabs)


472-472: Hard tabs
Column: 1

(MD010, no-hard-tabs)


528-528: Hard tabs
Column: 1

(MD010, no-hard-tabs)


529-529: Hard tabs
Column: 1

(MD010, no-hard-tabs)


534-534: Hard tabs
Column: 1

(MD010, no-hard-tabs)


535-535: Hard tabs
Column: 1

(MD010, no-hard-tabs)


536-536: Hard tabs
Column: 1

(MD010, no-hard-tabs)


545-545: Hard tabs
Column: 1

(MD010, no-hard-tabs)


546-546: Hard tabs
Column: 1

(MD010, no-hard-tabs)


547-547: Hard tabs
Column: 1

(MD010, no-hard-tabs)


552-552: Hard tabs
Column: 1

(MD010, no-hard-tabs)


553-553: Hard tabs
Column: 1

(MD010, no-hard-tabs)


569-569: Hard tabs
Column: 1

(MD010, no-hard-tabs)


570-570: Hard tabs
Column: 1

(MD010, no-hard-tabs)


574-574: Hard tabs
Column: 1

(MD010, no-hard-tabs)


575-575: Hard tabs
Column: 1

(MD010, no-hard-tabs)


576-576: Hard tabs
Column: 1

(MD010, no-hard-tabs)


577-577: Hard tabs
Column: 1

(MD010, no-hard-tabs)


582-582: Hard tabs
Column: 1

(MD010, no-hard-tabs)


586-586: Hard tabs
Column: 1

(MD010, no-hard-tabs)


587-587: Hard tabs
Column: 1

(MD010, no-hard-tabs)


588-588: Hard tabs
Column: 1

(MD010, no-hard-tabs)


592-592: Hard tabs
Column: 1

(MD010, no-hard-tabs)


593-593: Hard tabs
Column: 1

(MD010, no-hard-tabs)


622-622: Hard tabs
Column: 1

(MD010, no-hard-tabs)


626-626: Hard tabs
Column: 1

(MD010, no-hard-tabs)


627-627: Hard tabs
Column: 1

(MD010, no-hard-tabs)


632-632: Hard tabs
Column: 1

(MD010, no-hard-tabs)


633-633: Hard tabs
Column: 1

(MD010, no-hard-tabs)


634-634: Hard tabs
Column: 1

(MD010, no-hard-tabs)


635-635: Hard tabs
Column: 1

(MD010, no-hard-tabs)


636-636: Hard tabs
Column: 1

(MD010, no-hard-tabs)


650-650: Hard tabs
Column: 1

(MD010, no-hard-tabs)


651-651: Hard tabs
Column: 1

(MD010, no-hard-tabs)


652-652: Hard tabs
Column: 1

(MD010, no-hard-tabs)


653-653: Hard tabs
Column: 1

(MD010, no-hard-tabs)


654-654: Hard tabs
Column: 1

(MD010, no-hard-tabs)


655-655: Hard tabs
Column: 1

(MD010, no-hard-tabs)


656-656: Hard tabs
Column: 1

(MD010, no-hard-tabs)


657-657: Hard tabs
Column: 1

(MD010, no-hard-tabs)


658-658: Hard tabs
Column: 1

(MD010, no-hard-tabs)


659-659: Hard tabs
Column: 1

(MD010, no-hard-tabs)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Summary
🔇 Additional comments (24)
docs/developing-atmos-commands.md (1)

662-662: Verify: Possible duplicate link entry.

The AI summary mentions "two identical entries linking to I/O and UI Output Guide" but the annotated code shows only one entry at line 662. Verify whether this is accurate or if there's a duplicate that needs to be removed.

internal/tui/utils/utils.go (1)

22-26: LGTM! Clean wrapper for data output.

The convenience wrapper properly delegates to ui.Data() and includes clear documentation. The error handling is appropriately propagated.

docs/prd/io-handling-strategy.md (1)

1-700: Strong foundation for I/O separation.

The PRD clearly articulates the three-layer separation (I/O, Presentation, Application) and provides comprehensive examples. The mental model and decision tree will help developers understand when to use data vs UI channels.

pkg/schema/schema.go (1)

216-217: LGTM! Clean schema extension.

The new Title and Alerts fields are properly tagged and follow the existing struct patterns. The field names are self-documenting.

cmd/about/about.go (1)

17-19: Cleaner API with new UI formatter.

The migration to ui.Markdown() simplifies the call and aligns with the new I/O/UI pattern. The test properly initializes the formatter before execution.

docs/structured-logging.md (1)

7-13: Helpful clarification for developers.

This addition clearly separates logging concerns (diagnostics) from user-facing output concerns (UI/data), preventing common confusion. The cross-reference to the I/O and UI Output Guide provides a natural navigation path.

cmd/about/about_test.go (1)

12-21: Proper test migration to new I/O context.

The test correctly initializes both the I/O context and UI formatter before executing the command. This is the right pattern for testing commands using the new UI system and prevents the initialization panic seen in other tests.

cmd/internal/registry.go (1)

12-16: LGTM! Clean context key pattern.

The unexported contextKey type with exported IoContextKey constant follows Go best practices for context keys, preventing external packages from accidentally colliding with this key.

cmd/root.go (2)

30-30: Good import alias.

The iolib alias for pkg/io follows the coding guidelines for avoiding conflicts with the standard io package.


517-522: The review comment is incorrect—no cleanup is required.

The Context interface (pkg/io/interfaces.go) intentionally excludes a Close() method because NewContext() doesn't acquire resources needing explicit cleanup. It only wraps in-memory configuration, masking, terminal detection, and standard OS streams (stdin/stdout/stderr). Standard I/O streams are never closed by application code; they're managed by the OS. The code is correct as-is.

Likely an incorrect or invalid review comment.

pkg/io/terminal_test.go (1)

1-159: Excellent test coverage!

The tests comprehensively cover terminal capabilities including color profiles, TTY detection, dimensions, titles, and alerts. The table-driven approach for SetTitle and Alert tests is clean and the edge case handling (invalid stream types) is thorough.

pkg/io/example_test.go (3)

10-80: Outstanding example documentation!

This example perfectly demonstrates the new I/O and UI separation pattern. The step-by-step progression from basic data output to advanced terminal capabilities is clear and instructive. The conditional formatting based on TTY detection (lines 58-61) is particularly valuable.


82-114: Clear migration guidance.

The comparison between old and new patterns (especially the commented-out old pattern with explanatory questions) effectively highlights the improvements. The explicit channel choices make the code's intent immediately clear.


165-203: Excellent architectural principles.

The three-layer principle (I/O provides channels, UI provides formatting, Application combines both) is clearly articulated with concrete examples. This will help developers understand the separation of concerns.

pkg/io/streams_test.go (1)

1-195: Comprehensive test suite!

The tests cover all critical paths: basic masking, multiple secrets, edge cases (secret at start/end), large data (1MB), disabled masking, and error propagation. The errorWriter helper (lines 190-195) is a clean approach to testing error handling.

docs/io-and-ui-output.md (4)

1-46: Excellent documentation structure!

The clear distinction between UI output (required for users) and logging (optional metadata) is well articulated. The "Quick test" on line 26 is particularly helpful: "What happens if I disable logging?" provides an intuitive way for developers to categorize their output.


48-85: Clear and concise API reference.

The API reference is well-organized, showing both simple helpers (ui.Success()) and advanced patterns (ui.Format.Success()). The separation between UI messages (stderr), data output (stdout), and markdown is immediately clear.


622-666: Valuable migration guidance.

The migration guide clearly shows the problems with the old pattern and the benefits of the new approach. The side-by-side comparison makes the improvements obvious, and the step-by-step migration instructions will ease the transition.


280-330: Good security coverage.

The masking documentation clearly explains automatic masking, when to use raw channels, and the requirement for justification when bypassing masking. The examples show proper secret registration before output.

pkg/ui/formatter_test.go (1)

321-361: Clarify empty-markdown behavior contract.

RenderMarkdown test treats empty input as non-error. Confirm formatter.RenderMarkdown explicitly guarantees empty input → empty string, nil error so downstream callers rely on it. If not guaranteed in code, document and enforce.

pkg/ui/output_test.go (1)

369-385: Nice test harness.

Buffered streams and mockStreams make channel assertions straightforward. LGTM.

Also applies to: 387-411

pkg/io/context_test.go (1)

318-383: Good coverage.

Initialization, options, and profile logic are well exercised. LGTM.

Also applies to: 385-415

pkg/ui/formatter.go (2)

125-129: Global Format is fine; note substitutability risk.

If anyone sets Format to a custom implementation, previous .(*formatter) assertions (now removed per above) would panic. The new guards avoid that. Keep avoiding concrete type assertions in this package.

Add a safeguard test ensuring helpers don’t panic if Format is replaced with a mock.


21-28: The scan confirms the approach is sound. All UI helper call sites are properly ordered after initialization:

  • Root initialization (cmd/root.go:522) executes first as the entry point
  • UI helper calls (cmd/about/about.go and internal/tui/utils/utils.go) occur in subcommands that run after root setup
  • Tests explicitly initialize before use
  • Nil-guard (pkg/ui/formatter.go:36) provides runtime safety

No issues found. The code is correct.

Comment thread pkg/io/context.go Resolved
Comment thread pkg/io/context.go Resolved
Comment thread pkg/io/masker_test.go Resolved
Comment thread pkg/io/masker_test.go Resolved
Comment thread pkg/io/streams.go Resolved
Comment thread pkg/ui/formatter.go Resolved
Comment thread pkg/ui/formatter.go Resolved
Comment thread pkg/ui/interfaces.go Resolved
Comment thread pkg/ui/output.go Resolved
Comment thread pkg/ui/output.go Resolved
- Keep only new simplified ui.Success()/ui.Data() API
- Remove 600+ lines of verbose old I/O context examples
- Mention automatic masking briefly (implementation detail)
- Focus on what developers need: simple API reference and examples

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@osterman Erik Osterman (Cloud Posse) (osterman) added the minor New features that do not break anything label Oct 25, 2025
@github-actions

github-actions Bot commented Oct 25, 2025 •

Copy link
Copy Markdown

Warning

Changelog Entry Required

This PR is labeled minor or major but doesn't include a changelog entry.

Action needed: Add a new blog post in website/blog/ to announce this change.

Example filename: website/blog/2025-10-26-feature-name.mdx

Alternatively: If this change doesn't require a changelog entry, remove the minor or major label.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
docs/io-and-ui-output.md (2)

9-11: Fix punctuation and improve formatting consistency in bullet points.

Lines 11 and other bullet points are missing terminal punctuation. Consider adding periods at the end of each bullet for consistency, or ensure all bullets follow the same pattern.

- **Use `ui` package functions directly - no setup required.**
+ **Use `ui` package functions directly—no setup required.**

- - **UI messages** (status, errors, warnings) → `ui.Success()`, `ui.Error()`, etc. → **stderr**
- - **Data output** (JSON, YAML, results) → `ui.Data()` → **stdout**
- - **Help/docs** → `ui.Markdown()` → **stdout**
+ - **UI messages** (status, errors, warnings) → `ui.Success()`, `ui.Error()`, etc. → **stderr**.
+ - **Data output** (JSON, YAML, results) → `ui.Data()` → **stdout**.
+ - **Help/docs** → `ui.Markdown()` → **stdout**.

13-28: Address typographical conventions for quotes and abbreviations.

LanguageTool flags straight quotes (should use typographic/smart quotes) and abbreviations missing periods. This file uses "UI" frequently—no period needed after "UI" as it's an acronym (not an abbreviation that ends a sentence). However, single-letter abbreviations in table cells and narrative should be consistent. The quotes in the table and examples should use typographic quotes for polish.

- ## UI vs Logging: When to Use What
+ ## UI vs. Logging: When to Use What

For quotes in markdown tables and code comments, convert straight quotes to smart quotes:

- | "✓ Configuration loaded", JSON output |
+ | "✓ Configuration loaded", JSON output |
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7c51795 and d604111.

📒 Files selected for processing (1)
  • docs/io-and-ui-output.md (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-09-13T18:06:07.674Z
Learnt from: samtholiya
PR: cloudposse/atmos#1466
File: toolchain/list.go:39-42
Timestamp: 2025-09-13T18:06:07.674Z
Learning: In the cloudposse/atmos repository, for UI messages in the toolchain package, use utils.PrintfMessageToTUI instead of log.Error or fmt.Fprintln(os.Stderr, ...). Import pkg/utils with alias "u" to follow the established pattern.

Applied to files:

  • docs/io-and-ui-output.md
📚 Learning: 2025-10-24T14:51:19.340Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T14:51:19.340Z
Learning: Applies to cmd/**/*.go : UI (prompts/status) must write to stderr; data outputs to stdout; logging only for system events (never for UI).

Applied to files:

  • docs/io-and-ui-output.md
🪛 LanguageTool
docs/io-and-ui-output.md

[grammar] ~11-~11: Please add a punctuation mark at the end of paragraph.
Context: ...* - Help/docs → ui.Markdown() → stdout ## UI vs Logging: When to Use What ...

(PUNCTUATION_PARAGRAPH_END)


[typographical] ~13-~13: In American English, use a period after an abbreviation.
Context: ...* → ui.Markdown() → stdout ## UI vs Logging: When to Use What **Don't conf...

(MISSING_PERIOD_AFTER_ABBREVIATION)


[typographical] ~19-~19: Consider using a typographic opening quote here.
Context: ...Success(), ui.Error(), ui.Data()` | "✓ Configuration loaded", JSON output | |...

(EN_QUOTES)


[typographical] ~19-~19: Consider using a typographic close quote here.
Context: ..., ui.Data()` | "✓ Configuration loaded", JSON output | | Logging | Develope...

(EN_QUOTES)


[typographical] ~20-~20: Consider using a typographic opening quote here.
Context: ...rators | log.Debug(), log.Error() | "config.LoadAtmosYAML: parsing file" | *...

(EN_QUOTES)


[typographical] ~20-~20: Consider using a typographic close quote here.
Context: ...)` | "config.LoadAtmosYAML: parsing file" | Key distinction: - **UI output i...

(EN_QUOTES)


[typographical] ~26-~26: Consider using a typographic opening quote here.
Context: ...t user doesn't need it Quick test: "What happens if I disable logging?" - **...

(EN_QUOTES)


[typographical] ~26-~26: Consider using a typographic close quote here.
Context: ...t:** "What happens if I disable logging?" - Breaks user experience → It's UI ...

(EN_QUOTES)


[grammar] ~28-~28: Please add a punctuation mark at the end of paragraph.
Context: ... unaffected** → It's logging, use log package Examples: ```go // ❌ WRONG - usin...

(PUNCTUATION_PARAGRAPH_END)


[typographical] ~145-~145: In American English, use a period after an abbreviation.
Context: ...ines](logging.md) - When to use logging vs UI output - [Developing Atmos Commands]...

(MISSING_PERIOD_AFTER_ABBREVIATION)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Build (linux)
  • GitHub Check: Build (windows)
  • GitHub Check: Build (macos)
  • GitHub Check: Analyze (go)
  • GitHub Check: autofix
  • GitHub Check: Review Dependency Licenses
  • GitHub Check: Summary
🔇 Additional comments (6)
docs/io-and-ui-output.md (6)

32-39: Clear and practical guidance on the distinction.

The examples here correctly illustrate the UI/logging boundary and align well with the learnings (UI to stderr, logging for diagnostics). The pattern is concrete and helpful.


50-84: API reference is complete and well-documented.

Covers both simple (write-only) and advanced (return-only) APIs. The examples show function signatures, intent, and return behavior clearly. This matches the PR objectives and supports both the simple and advanced usage patterns.


88-101: Example 1 is clear and demonstrates proper stdout pipelining.

The JSON output example shows correct use of ui.Data() to stdout and adds a helpful note about piping. Good practical guidance for users who need structured output.


103-120: Example 2 effectively demonstrates status flow and stderr/stdout separation.

Status messages go to stderr (via UI functions), and data goes to stdout. The comment clarifies that UI messages don't interfere with piped output—a key insight for command authors. Solid.


122-130: Example 3 is concise and shows the elegance of the pattern.

One-line command return for help rendering. This reinforces the theme of simplicity and automatic formatting without boilerplate.


134-145: Automatic secret masking and references are well-positioned.

Notes correctly explain that masking is transparent and point readers to the PRD for advanced scenarios. Links to related docs are appropriate and support further learning. Consistent with PR objectives.

One small note: Line 145 should have a period after abbreviation ("UI" → "U.I." if treating as abbreviation, but "UI" as acronym needs no period). Keep "UI" as-is (common modern style for acronyms). The LanguageTool flag here may be overly strict.

Create pkg/data/ package for data output:
- data.Write() - plain text to stdout
- data.Writef() - formatted text to stdout
- data.WriteJSON() - marshal and write JSON
- data.WriteYAML() - marshal and write YAML

UI package now only handles UI messages (stderr):
- ui.Success/Error/Warning/Info - status messages
- ui.Markdown/MarkdownMessage - formatted content

I/O package is the foundation for both:
- Channels (stdout/stderr separation)
- Masking (automatic secret redaction)
- Terminal capabilities (TTY detection, colors)

Architecture:
┌─────────────┐
│   Commands  │
└──┬────────┬─┘
   │        │
   ▼        ▼
┌────┐   ┌────┐
│ UI │   │Data│  Both use I/O
└─┬──┘   └─┬──┘
  │        │
  └───┬────┘
      ▼
   ┌─────┐
   │ I/O │ Foundation
   └─────┘

Updated:
- Version command uses data.WriteJSON/WriteYAML
- About command uses ui.Markdown
- Documentation reflects three-layer architecture

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

♻️ Duplicate comments (3)
pkg/io/masker_test.go (2)

40-60: Avoid static encoded secrets; generate at runtime and actually URL‑encode.

Inline base64 and unencoded “URL encoded” cases can trip gitleaks and don’t test the right thing. Compute encodings during the test.

Apply:

@@
-import (
-	"regexp"
-	"testing"
-)
+import (
+	"encoding/base64"
+	"net/url"
+	"regexp"
+	"strings"
+	"testing"
+)
@@
 	secret := "mySecretToken"
 	m.RegisterSecret(secret)
@@
-		{
-			name:  "base64 encoded",
-			input: "Token: bXlTZWNyZXRUb2tlbg==",
-			want:  "Token: ***MASKED***",
-		},
-		{
-			name:  "URL encoded",
-			input: "Token: mySecretToken",
-			want:  "Token: ***MASKED***",
-		},
+		{
+			name: "base64 encoded",
+			input: func() string {
+				enc := base64.StdEncoding.EncodeToString([]byte(secret))
+				return "Token: " + enc
+			}(),
+			want: "Token: ***MASKED***",
+		},
+		{
+			name: "URL encoded",
+			input: "Token: " + url.QueryEscape(secret),
+			want: "Token: ***MASKED***",
+		},

108-116: Build fake PAT at runtime to keep scanners happy.

Construct the token string; don’t embed a literal PAT-looking value.

Apply:

-	re := regexp.MustCompile(`ghp_[A-Za-z0-9]{36}`)
-	m.RegisterRegex(re)
-
-	input := "GitHub token: ghp_123456789012345678901234567890123456"
+	re := regexp.MustCompile(`ghp_[A-Za-z0-9]{36}`)
+	m.RegisterRegex(re)
+	fake := "ghp_" + strings.Repeat("1", 36)
+	input := "GitHub token: " + fake
 	expected := "GitHub token: ***MASKED***"
pkg/ui/interfaces.go (1)

9-10: Resolve the doc inconsistency flagged earlier.

The principle at lines 9-10 states Formatter "never writes to streams," but Markdown() at line 48 performs I/O and returns an error. This was flagged in the previous review and remains unresolved—either update the principle to acknowledge Markdown as an exception or refactor Markdown out of the Formatter interface.

Also applies to: 46-48

🧹 Nitpick comments (4)
pkg/io/masker.go (1)

27-33: Guard against nil Config in constructor.

Small safety net: avoid panics if newMasker(nil) is ever called (tests, future code).

Apply:

 func newMasker(config *Config) Masker {
-	m := &masker{
+	enabled := true
+	if config != nil {
+		enabled = !config.DisableMasking
+	}
+	m := &masker{
 		literals: make(map[string]bool),
 		patterns: make([]*regexp.Regexp, 0),
-		enabled:  !config.DisableMasking,
+		enabled:  enabled,
 	}
pkg/ui/formatter_test.go (2)

421-431: Don’t ignore NewContext errors in test helpers.

If IO context init fails, tests may proceed with a nil context and panic later. Make helpers assert/abort on error.

Example:

-func createTestIOContext() iolib.Context {
-	ctx, _ := iolib.NewContext()
-	return ctx
-}
+func createTestIOContext(t *testing.T) iolib.Context {
+	t.Helper()
+	ctx, err := iolib.NewContext()
+	if err != nil {
+		t.Fatalf("NewContext failed: %v", err)
+	}
+	return ctx
+}

Repeat for createTestIOContextWithProfile. Update call sites accordingly.


463-471: Remove unused mockIOContext.

It’s defined but not referenced.

pkg/ui/output_test.go (1)

369-385: Assert NewContext errors in buffer-based helper.

Guard against failures when constructing the test IO context.

Apply:

-	ctx, _ := iolib.NewContext(
+	ctx, err := iolib.NewContext(
 		iolib.WithStreams(streams),
 		iolib.WithTerminal(&mockTerminal{profile: iolib.Color16}),
 	)
+	if err != nil {
+		panic(err) // or pass *testing.T in and t.Fatalf
+	}
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d604111 and 210660f.

📒 Files selected for processing (11)
  • cmd/root.go (2 hunks)
  • pkg/io/context_test.go (1 hunks)
  • pkg/io/example_test.go (1 hunks)
  • pkg/io/interfaces.go (1 hunks)
  • pkg/io/masker.go (1 hunks)
  • pkg/io/masker_test.go (1 hunks)
  • pkg/io/streams.go (1 hunks)
  • pkg/io/terminal.go (1 hunks)
  • pkg/ui/formatter_test.go (1 hunks)
  • pkg/ui/interfaces.go (1 hunks)
  • pkg/ui/output_test.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • pkg/io/example_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • pkg/io/terminal.go
  • pkg/io/streams.go
  • pkg/io/context_test.go
🧰 Additional context used
📓 Path-based instructions (6)
pkg/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Place business logic in pkg rather than in cmd

Files:

  • pkg/ui/output_test.go
  • pkg/ui/interfaces.go
  • pkg/io/masker.go
  • pkg/io/interfaces.go
  • pkg/ui/formatter_test.go
  • pkg/io/masker_test.go
**/*_test.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*_test.go: Every new feature must include comprehensive unit tests
Test both happy paths and error conditions
Use table-driven tests for multiple scenarios

**/*_test.go: Prefer unit tests with mocks over integration tests; use interfaces + DI; table-driven tests for coverage; target >80% coverage.
Tests must exercise production code paths; avoid duplicating implementation logic in tests.
Use t.Skipf("reason") with clear context when skipping tests; CLI tests may auto-build temp binaries.

Files:

  • pkg/ui/output_test.go
  • pkg/ui/formatter_test.go
  • pkg/io/masker_test.go
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments

**/*.go: Define interfaces for major functionality and use dependency injection to enable testability.
Generate mocks using go.uber.org/mock/mockgen via //go:generate directives (never manual mocks).
Prefer functional Options pattern instead of functions with many parameters for configuration.
Use context.Context only for cancellation, deadlines/timeouts, and request-scoped values; never for configuration or dependencies; context should be the first parameter.
All comments must end with periods (godot linter).
Preserve helpful existing comments; update them to match code when refactoring; only remove when incorrect, redundant, or code removed.
Organize imports in three groups (stdlib, third-party, Atmos) separated by blank lines and sorted alphabetically; maintain aliases cfg, log, u, errUtils.
Add defer perf.Track(atmosConfig, "pkg.FuncName")() (or nil if no atmosConfig) plus a blank line at the start of all public functions for performance tracking.
Use static errors from errors/errors.go; wrap with fmt.Errorf("%w") for chaining; use errors.Join for independent errors; avoid dynamic errors and string comparison; use errors.Is for checks.
Never use //revive:disable:file-length-limit to bypass file size limits; keep files small and focused (<600 lines).
Environment variables must be bound with viper.BindEnv using ATMOS_ prefix (e.g., viper.BindEnv("ATMOS_VAR", "ATMOS_VAR", "FALLBACK")).
Ensure cross-platform compatibility: use filepath.Join instead of hardcoded path separators and prefer SDKs over shelling out to binaries.

Files:

  • pkg/ui/output_test.go
  • cmd/root.go
  • pkg/ui/interfaces.go
  • pkg/io/masker.go
  • pkg/io/interfaces.go
  • pkg/ui/formatter_test.go
  • pkg/io/masker_test.go
{cmd,pkg/ui}/**/*.go

📄 CodeRabbit inference engine (CLAUDE.md)

Use theme colors from pkg/ui/theme/colors.go for UI elements.

Files:

  • pkg/ui/output_test.go
  • cmd/root.go
  • pkg/ui/interfaces.go
  • pkg/ui/formatter_test.go
cmd/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

cmd/**/*.go: Use Cobra's recommended command structure with a root command and subcommands
Implement each CLI command in a separate file under cmd/
Use Viper for managing configuration, environment variables, and flags in the CLI
Keep separation of concerns between CLI interface (cmd) and business logic
Use kebab-case for command-line flags
Provide comprehensive help text for all commands and flags
Include examples in Cobra command help
Use Viper for configuration management; support files, env vars, and flags with precedence flags > env > config > defaults
Follow single responsibility; separate command interface from business logic
Provide meaningful user feedback and include progress indicators for long-running operations
Provide clear error messages to users and troubleshooting hints where appropriate

cmd/**/*.go: New CLI commands must use the command registry pattern via CommandProvider and register through the command registry (see cmd/internal/registry.go).
Commands should embed *_usage.md via //go:embed and render with utils.PrintfMarkdown().
UI (prompts/status) must write to stderr; data outputs to stdout; logging only for system events (never for UI).
For non-standard execution paths, capture telemetry with telemetry.CaptureCmd(); normal paths are auto-enabled via RootCmd.ExecuteC(). Never capture user data.

Files:

  • cmd/root.go
**/!(*_test).go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Document all exported functions, types, and methods with Go doc comments

Files:

  • cmd/root.go
  • pkg/ui/interfaces.go
  • pkg/io/masker.go
  • pkg/io/interfaces.go
🧠 Learnings (2)
📚 Learning: 2025-09-13T18:06:07.674Z
Learnt from: samtholiya
PR: cloudposse/atmos#1466
File: toolchain/list.go:39-42
Timestamp: 2025-09-13T18:06:07.674Z
Learning: In the cloudposse/atmos repository, for UI messages in the toolchain package, use utils.PrintfMessageToTUI instead of log.Error or fmt.Fprintln(os.Stderr, ...). Import pkg/utils with alias "u" to follow the established pattern.

Applied to files:

  • cmd/root.go
📚 Learning: 2024-12-11T18:40:12.808Z
Learnt from: Listener430
PR: cloudposse/atmos#844
File: cmd/helmfile.go:37-37
Timestamp: 2024-12-11T18:40:12.808Z
Learning: In the atmos project, `cliConfig` is initialized within the `cmd` package in `root.go` and can be used in other command files.

Applied to files:

  • cmd/root.go
🧬 Code graph analysis (7)
pkg/ui/output_test.go (4)
pkg/ui/output.go (2)
  • NewOutput (18-31)
  • WithTrimTrailingWhitespace (37-41)
pkg/ui/interfaces.go (2)
  • Formatter (24-60)
  • Output (97-124)
pkg/io/interfaces.go (2)
  • Context (18-39)
  • Color16 (157-157)
pkg/io/context.go (3)
  • NewContext (23-52)
  • WithStreams (97-101)
  • WithTerminal (104-108)
cmd/root.go (2)
pkg/io/context.go (1)
  • NewContext (23-52)
pkg/ui/formatter.go (2)
  • Errorf (91-95)
  • InitFormatter (23-28)
pkg/ui/interfaces.go (2)
pkg/ui/formatter.go (9)
  • Success (70-74)
  • Successf (77-81)
  • Warning (98-102)
  • Warningf (105-109)
  • Error (84-88)
  • Errorf (91-95)
  • Info (112-116)
  • Infof (119-123)
  • Markdown (59-61)
pkg/io/interfaces.go (2)
  • ColorProfile (153-153)
  • Context (18-39)
pkg/io/masker.go (1)
pkg/io/interfaces.go (2)
  • Config (134-150)
  • Masker (101-131)
pkg/io/interfaces.go (4)
internal/tui/utils/utils.go (1)
  • Data (24-26)
pkg/ui/formatter.go (2)
  • Data (45-48)
  • Error (84-88)
pkg/schema/schema.go (2)
  • Terminal (208-218)
  • AtmosConfiguration (27-65)
pkg/ui/interfaces.go (1)
  • Output (97-124)
pkg/ui/formatter_test.go (5)
pkg/ui/formatter.go (8)
  • Error (84-88)
  • Errorf (91-95)
  • Success (70-74)
  • Warning (98-102)
  • Info (112-116)
  • Successf (77-81)
  • Warningf (105-109)
  • Infof (119-123)
pkg/io/interfaces.go (7)
  • ColorProfile (153-153)
  • ColorNone (156-156)
  • Color16 (157-157)
  • Color256 (158-158)
  • ColorTrue (159-159)
  • Context (18-39)
  • Config (134-150)
internal/tui/utils/utils.go (1)
  • RenderMarkdown (52-89)
pkg/io/context.go (2)
  • NewContext (23-52)
  • WithTerminal (104-108)
pkg/ui/interfaces.go (1)
  • Formatter (24-60)
pkg/io/masker_test.go (1)
pkg/io/interfaces.go (2)
  • Config (134-150)
  • Masker (101-131)
🪛 Gitleaks (8.28.0)
pkg/io/masker_test.go

[high] 52-52: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


[high] 111-111: Uncovered a GitHub Personal Access Token, potentially leading to unauthorized repository access and sensitive content exposure.

(github-pat)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Summary
🔇 Additional comments (2)
pkg/ui/formatter_test.go (1)

321-361: Clarify contract for empty markdown.

Test expects no error on empty input. Confirm formatter’s spec; internal/tui/utils.RenderMarkdown returns an error for empty input. Align behavior and tests.

Would you like me to search for and reconcile the current formatter spec across the codebase?

pkg/io/interfaces.go (1)

10-39: Well-designed I/O abstraction.

The Context interface clearly separates channels (Data/UI/Input) from capabilities (Terminal/Config/Masker), making the I/O layer intent explicit. Good documentation of the design principle.

Comment thread cmd/root.go Resolved
Comment thread pkg/io/masker.go Resolved
Comment thread pkg/io/masker.go Resolved
Comment thread pkg/io/masker.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (3)
cmd/root.go (1)

518-524: Move I/O initialization to PersistentPreRun after flag parsing.

Creating the I/O context in Execute() means it runs before Cobra parses flags, so --no-color, --redirect-stderr, and --disable-masking flags won't affect the I/O context. Move this initialization to the root command's PersistentPreRun (after the telemetry disclosure at line 193) so flags are available.

Apply this fix:

-	// Initialize I/O context and global formatter.
-	ioCtx, ioErr := iolib.NewContext()
-	if ioErr != nil {
-		return fmt.Errorf("failed to initialize I/O context: %w", ioErr)
-	}
-	ui.InitFormatter(ioCtx)
-	data.InitData(ioCtx)
+	// (I/O context initialization moved to PersistentPreRun)

And add in PersistentPreRun after line 193:

 		// Print telemetry disclosure if needed (skip for completion commands and when CLI config not found).
 		if !isCompletionCommand(cmd) && err == nil {
 			telemetry.PrintTelemetryDisclosure()
 		}
+
+		// Initialize I/O context and global formatter after flags are parsed.
+		ioCtx, ioErr := iolib.NewContext()
+		if ioErr != nil {
+			errUtils.CheckErrorPrintAndExit(ioErr, "Failed to initialize I/O context", "")
+		}
+		ui.InitFormatter(ioCtx)
+		data.InitData(ioCtx)
 	},
pkg/ui/formatter.go (2)

30-39: Replace panic with error returns and remove type assertions.

The panic on line 36 causes CI failures and violates library best practices. The .(*formatter) type assertions in wrapper functions (lines 57, 64, 71, 78, 85, 92, 99, 106) are brittle and unnecessary.

Refactor by storing the io.Context separately:

 var (
 	// Global formatter instance (like the logger).
 	globalFormatter Formatter
+	// Global IO context used by package-level helpers.
+	globalIO io.Context
 	formatterMu     sync.RWMutex
 )

 func InitFormatter(ioCtx io.Context) {
 	formatterMu.Lock()
 	defer formatterMu.Unlock()
 	globalFormatter = NewFormatter(ioCtx)
 	Format = globalFormatter // Also expose for advanced use
+	globalIO = ioCtx
 }

-func getFormatter() Formatter {
+func getFormatter() (Formatter, io.Context) {
 	formatterMu.RLock()
 	defer formatterMu.RUnlock()
-	if globalFormatter == nil {
-		panic("ui.InitFormatter() must be called before using UI functions")
-	}
-	return globalFormatter
+	return globalFormatter, globalIO
 }

Then update wrapper functions to check and return errors:

 func Success(text string) error {
-	f := getFormatter().(*formatter)
-	_, err := fmt.Fprintln(f.ioCtx.UI(), f.Success(text))
+	f, ioCtx := getFormatter()
+	if f == nil || ioCtx == nil {
+		return fmt.Errorf("ui formatter not initialized")
+	}
+	_, err := fmt.Fprintln(ioCtx.UI(), f.Success(text))
 	return err
 }

Apply similar changes to all wrapper functions (Successf, Error, Errorf, Warning, Warningf, Info, Infof).


280-285: Add defer to close the Glamour renderer.

The TermRenderer exposes Close() to release resources. Add defer renderer.Close() after successful creation.

 	renderer, err := glamour.NewTermRenderer(opts...)
 	if err != nil {
 		// Degrade gracefully: return plain content if renderer creation fails
 		return content, nil
 	}
+	defer renderer.Close()
 
 	rendered, err := renderer.Render(content)
🧹 Nitpick comments (1)
pkg/data/data.go (1)

26-37: Consider returning an error instead of panicking.

The panic here assumes InitData() was called at startup. While this is documented as a programming error, returning a typed error would be more robust and testable. If the I/O context isn't available, functions could return an error that callers can handle gracefully.

Example refactor:

 func getIOContext() io.Context {
 	ioMu.RLock()
 	defer ioMu.RUnlock()
 
 	if globalIOContext == nil {
-		panic("data.InitData() must be called before using data package functions")
+		// Return nil and let callers check/handle
+		return nil
 	}
 
 	return globalIOContext
 }

Then guard in each function:

 func Write(content string) error {
+	ioCtx := getIOContext()
+	if ioCtx == nil {
+		return fmt.Errorf("data layer not initialized")
+	}
-	_, err := fmt.Fprint(getIOContext().Data(), content)
+	_, err := fmt.Fprint(ioCtx.Data(), content)
 	return err
 }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 210660f and 9034085.

📒 Files selected for processing (6)
  • cmd/root.go (2 hunks)
  • docs/io-and-ui-output.md (1 hunks)
  • internal/exec/version.go (1 hunks)
  • internal/tui/utils/utils.go (1 hunks)
  • pkg/data/data.go (1 hunks)
  • pkg/ui/formatter.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/exec/version.go
  • internal/tui/utils/utils.go
🧰 Additional context used
📓 Path-based instructions (5)
pkg/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Place business logic in pkg rather than in cmd

Files:

  • pkg/data/data.go
  • pkg/ui/formatter.go
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments

**/*.go: Define interfaces for major functionality and use dependency injection to enable testability.
Generate mocks using go.uber.org/mock/mockgen via //go:generate directives (never manual mocks).
Prefer functional Options pattern instead of functions with many parameters for configuration.
Use context.Context only for cancellation, deadlines/timeouts, and request-scoped values; never for configuration or dependencies; context should be the first parameter.
All comments must end with periods (godot linter).
Preserve helpful existing comments; update them to match code when refactoring; only remove when incorrect, redundant, or code removed.
Organize imports in three groups (stdlib, third-party, Atmos) separated by blank lines and sorted alphabetically; maintain aliases cfg, log, u, errUtils.
Add defer perf.Track(atmosConfig, "pkg.FuncName")() (or nil if no atmosConfig) plus a blank line at the start of all public functions for performance tracking.
Use static errors from errors/errors.go; wrap with fmt.Errorf("%w") for chaining; use errors.Join for independent errors; avoid dynamic errors and string comparison; use errors.Is for checks.
Never use //revive:disable:file-length-limit to bypass file size limits; keep files small and focused (<600 lines).
Environment variables must be bound with viper.BindEnv using ATMOS_ prefix (e.g., viper.BindEnv("ATMOS_VAR", "ATMOS_VAR", "FALLBACK")).
Ensure cross-platform compatibility: use filepath.Join instead of hardcoded path separators and prefer SDKs over shelling out to binaries.

Files:

  • pkg/data/data.go
  • cmd/root.go
  • pkg/ui/formatter.go
**/!(*_test).go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Document all exported functions, types, and methods with Go doc comments

Files:

  • pkg/data/data.go
  • cmd/root.go
  • pkg/ui/formatter.go
cmd/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

cmd/**/*.go: Use Cobra's recommended command structure with a root command and subcommands
Implement each CLI command in a separate file under cmd/
Use Viper for managing configuration, environment variables, and flags in the CLI
Keep separation of concerns between CLI interface (cmd) and business logic
Use kebab-case for command-line flags
Provide comprehensive help text for all commands and flags
Include examples in Cobra command help
Use Viper for configuration management; support files, env vars, and flags with precedence flags > env > config > defaults
Follow single responsibility; separate command interface from business logic
Provide meaningful user feedback and include progress indicators for long-running operations
Provide clear error messages to users and troubleshooting hints where appropriate

cmd/**/*.go: New CLI commands must use the command registry pattern via CommandProvider and register through the command registry (see cmd/internal/registry.go).
Commands should embed *_usage.md via //go:embed and render with utils.PrintfMarkdown().
UI (prompts/status) must write to stderr; data outputs to stdout; logging only for system events (never for UI).
For non-standard execution paths, capture telemetry with telemetry.CaptureCmd(); normal paths are auto-enabled via RootCmd.ExecuteC(). Never capture user data.

Files:

  • cmd/root.go
{cmd,pkg/ui}/**/*.go

📄 CodeRabbit inference engine (CLAUDE.md)

Use theme colors from pkg/ui/theme/colors.go for UI elements.

Files:

  • cmd/root.go
  • pkg/ui/formatter.go
🧠 Learnings (3)
📚 Learning: 2025-09-13T18:06:07.674Z
Learnt from: samtholiya
PR: cloudposse/atmos#1466
File: toolchain/list.go:39-42
Timestamp: 2025-09-13T18:06:07.674Z
Learning: In the cloudposse/atmos repository, for UI messages in the toolchain package, use utils.PrintfMessageToTUI instead of log.Error or fmt.Fprintln(os.Stderr, ...). Import pkg/utils with alias "u" to follow the established pattern.

Applied to files:

  • cmd/root.go
  • docs/io-and-ui-output.md
📚 Learning: 2024-12-11T18:40:12.808Z
Learnt from: Listener430
PR: cloudposse/atmos#844
File: cmd/helmfile.go:37-37
Timestamp: 2024-12-11T18:40:12.808Z
Learning: In the atmos project, `cliConfig` is initialized within the `cmd` package in `root.go` and can be used in other command files.

Applied to files:

  • cmd/root.go
📚 Learning: 2025-10-24T14:51:19.340Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T14:51:19.340Z
Learning: Applies to cmd/**/*.go : UI (prompts/status) must write to stderr; data outputs to stdout; logging only for system events (never for UI).

Applied to files:

  • docs/io-and-ui-output.md
🧬 Code graph analysis (3)
pkg/data/data.go (1)
internal/tui/utils/utils.go (2)
  • WriteJSON (24-26)
  • WriteYAML (30-32)
cmd/root.go (3)
pkg/io/context.go (1)
  • NewContext (23-52)
pkg/ui/formatter.go (2)
  • Errorf (77-81)
  • InitFormatter (23-28)
pkg/data/data.go (1)
  • InitData (20-24)
pkg/ui/formatter.go (5)
pkg/ui/interfaces.go (2)
  • Formatter (23-59)
  • StyleSet (63-80)
pkg/io/interfaces.go (8)
  • Context (18-39)
  • Terminal (71-98)
  • ColorProfile (153-153)
  • ColorNone (156-156)
  • Config (134-150)
  • Color16 (157-157)
  • Color256 (158-158)
  • ColorTrue (159-159)
pkg/schema/schema.go (2)
  • Context (411-426)
  • Terminal (208-218)
internal/tui/utils/utils.go (1)
  • RenderMarkdown (58-95)
pkg/ui/theme/colors.go (6)
  • ColorCyan (12-12)
  • ColorBlue (14-14)
  • ColorWhite (20-20)
  • ColorGreen (11-11)
  • ColorOrange (18-18)
  • ColorRed (16-16)
🪛 LanguageTool
docs/io-and-ui-output.md

[grammar] ~11-~11: Please add a punctuation mark at the end of paragraph.
Context: ...ls, masking, terminal) → Foundation for both All use the same I/O context initializ...

(PUNCTUATION_PARAGRAPH_END)


[typographical] ~15-~15: In American English, use a period after an abbreviation.
Context: ...- no setup required in commands. ## UI vs Logging: When to Use What **Don't conf...

(MISSING_PERIOD_AFTER_ABBREVIATION)


[typographical] ~21-~21: Consider using a typographic opening quote here.
Context: ... users | ui.Success(), ui.Error() | "✓ Configuration loaded" | | **Data Outpu...

(EN_QUOTES)


[typographical] ~21-~21: Consider using a typographic close quote here.
Context: ..., ui.Error() | "✓ Configuration loaded" | | Data Output | Machines/pipes | ...

(EN_QUOTES)


[typographical] ~23-~23: Consider using a typographic opening quote here.
Context: ...rators | log.Debug(), log.Error() | "config.LoadAtmosYAML: parsing file" | *...

(EN_QUOTES)


[typographical] ~23-~23: Consider using a typographic close quote here.
Context: ...)` | "config.LoadAtmosYAML: parsing file" | Key distinction: - **UI output i...

(EN_QUOTES)


[typographical] ~29-~29: Consider using a typographic opening quote here.
Context: ...t user doesn't need it Quick test: "What happens if I disable logging?" - **...

(EN_QUOTES)


[typographical] ~29-~29: Consider using a typographic close quote here.
Context: ...t:** "What happens if I disable logging?" - Breaks user experience → It's UI ...

(EN_QUOTES)


[grammar] ~31-~31: Please add a punctuation mark at the end of paragraph.
Context: ... unaffected** → It's logging, use log package Examples: ```go // ❌ WRONG - usin...

(PUNCTUATION_PARAGRAPH_END)


[typographical] ~146-~146: In American English, use a period after an abbreviation.
Context: ...ines](logging.md) - When to use logging vs UI output - [Developing Atmos Commands]...

(MISSING_PERIOD_AFTER_ABBREVIATION)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Build (linux)
  • GitHub Check: Build (windows)
  • GitHub Check: Build (macos)
  • GitHub Check: autofix
  • GitHub Check: Review Dependency Licenses
  • GitHub Check: Lint (golangci)
  • GitHub Check: Analyze (go)
  • GitHub Check: Summary
🔇 Additional comments (1)
docs/io-and-ui-output.md (1)

1-147: Documentation looks solid.

This guide clearly separates UI output, data output, and logging with practical examples. The distinction between required UI output and optional logging is well explained. The API reference and examples provide good developer guidance.

Now both follow the same naming pattern:
- ui.InitFormatter(ioCtx)
- data.InitWriter(ioCtx)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (7)
pkg/io/masker_test.go (2)

108-117: Avoid static GitHub PAT literals in tests.

Construct a fake token at runtime to keep CI scanners happy.

Apply:

-    input := "GitHub token: ghp_123456789012345678901234567890123456"
+    fake := "ghp_" + strings.Repeat("1", 36)
+    input := "GitHub token: " + fake

51-59: Compute encodings at runtime; fix URL-encoded case.

Avoid embedding base64 literals and make the URL-encoded case actually URL-encoded.

Apply:

         {
             name:  "plain secret",
             input: "Token: mySecretToken",
             want:  "Token: ***MASKED***",
         },
         {
             name:  "base64 encoded",
-            input: "Token: bXlTZWNyZXRUb2tlbg==",
+            input: func() string {
+                enc := base64.StdEncoding.EncodeToString([]byte(secret))
+                return "Token: " + enc
+            }(),
             want:  "Token: ***MASKED***",
         },
         {
             name:  "URL encoded",
-            input: "Token: mySecretToken",
+            input: func() string {
+                return "Token: " + url.QueryEscape(secret)
+            }(),
             want:  "Token: ***MASKED***",
         },
cmd/root.go (1)

518-525: Initialize IO/UI after Cobra parses flags (move to PersistentPreRun).

Current init runs before flags/env/config are resolved, so flags like --no-color/--redirect-stderr/--disable-masking won’t apply. Move init to PersistentPreRun after telemetry disclosure; remove from Execute().

Apply:

@@
-    // Initialize I/O context and global formatter.
-    ioCtx, ioErr := iolib.NewContext()
-    if ioErr != nil {
-        return fmt.Errorf("failed to initialize I/O context: %w", ioErr)
-    }
-    ui.InitFormatter(ioCtx)
-    data.InitWriter(ioCtx)
+    // (moved to PersistentPreRun after flags/env/config are resolved)

And add inside PersistentPreRun after telemetry disclosure:

@@
-        if !isCompletionCommand(cmd) && err == nil {
+        if !isCompletionCommand(cmd) && err == nil {
             telemetry.PrintTelemetryDisclosure()
         }
+
+        // Initialize I/O context and global formatters after flags/env/config are resolved.
+        ioCtx, ioErr := iolib.NewContext()
+        if ioErr != nil {
+            errUtils.CheckErrorPrintAndExit(ioErr, "Failed to initialize I/O context", "")
+        }
+        ui.InitFormatter(ioCtx)
+        data.InitWriter(ioCtx)
pkg/io/terminal.go (1)

70-85: SetTitle checks wrong stream; also gate consistently.

You write to stderr but gate on stdout. Gate on stderr to avoid no-ops in common cases (stdout piped).

Apply:

-    // Only set title if stdout is a TTY
-    if !t.IsTTY(StreamOutput) {
+    // Only set title if stderr is a TTY (UI channel)
+    if !t.IsTTY(StreamError) {
         return
     }
pkg/io/masker.go (3)

64-71: Register JSON-encoded variants correctly (quoted and unquoted).

Only the inner text is registered; most JSON logs include quotes too.

Apply:

-    // Register JSON encoded version
-    if jsonBytes, err := json.Marshal(secret); err == nil {
-        // Remove surrounding quotes
-        jsonStr := string(jsonBytes)
-        if len(jsonStr) > 2 {
-            m.RegisterValue(jsonStr[1 : len(jsonStr)-1])
-        }
-    }
+    // Register JSON-encoded versions (quoted and unquoted).
+    if jsonBytes, err := json.Marshal(secret); err == nil {
+        jsonStr := string(jsonBytes) // e.g., "mySecret"
+        m.RegisterValue(jsonStr)
+        if len(jsonStr) >= 2 && jsonStr[0] == '"' && jsonStr[len(jsonStr)-1] == '"' {
+            m.RegisterValue(jsonStr[1 : len(jsonStr)-1])
+        }
+    }

102-109: AWS secret regex is too broad; include ASIA and add context.

Avoid masking arbitrary 40‑char blobs; scope to labeled secrets and support temporary keys.

Apply:

-    // AWS access keys follow pattern: AKIA[0-9A-Z]{16}
-    // If this is a valid AWS access key, register a pattern to catch the paired secret key
-    if strings.HasPrefix(accessKeyID, "AKIA") && len(accessKeyID) == 20 {
-        // AWS secret keys are 40 characters of base64-like characters
-        // Register a pattern to catch anything that looks like an AWS secret key near this access key
-        // This is a best-effort approach
-        _ = m.RegisterPattern(`[A-Za-z0-9/+=]{40}`)
-    }
+    // If this looks like an AWS access key, also mask the paired secret when labeled.
+    if len(accessKeyID) == 20 && (strings.HasPrefix(accessKeyID, "AKIA") || strings.HasPrefix(accessKeyID, "ASIA")) {
+        // Match common labeling to reduce false positives.
+        _ = m.RegisterPattern(`(?i)\bAWS_SECRET_ACCESS_KEY\b[=:]\s*[A-Za-z0-9/+=]{40}`)
+    }

122-129: Fix unordered literal masking to prevent partial leaks.

Map iteration order can replace substrings first. Mask longest literals first.

Apply:

+    // Mask literals (exact matches) longest-first to avoid partial replacements.
-    // Mask literals (exact matches)
-    // Sort by length (longest first) to avoid partial replacements
-    for literal := range m.literals {
-        if literal != "" {
-            masked = strings.ReplaceAll(masked, literal, MaskReplacement)
-        }
-    }
+    lits := make([]string, 0, len(m.literals))
+    for k := range m.literals {
+        if k != "" {
+            lits = append(lits, k)
+        }
+    }
+    sort.Slice(lits, func(i, j int) bool { return len(lits[i]) > len(lits[j]) })
+    for _, literal := range lits {
+        masked = strings.ReplaceAll(masked, literal, MaskReplacement)
+    }

And add import:

 import (
     "encoding/base64"
     "encoding/json"
     "fmt"
     "net/url"
     "regexp"
+    "sort"
     "strings"
     "sync"
 )
🧹 Nitpick comments (13)
pkg/io/example_test.go (1)

15-15: Handle example errors or annotate intent to ignore.

Ignoring errors may upset errcheck. Either check and early-return, or add a brief comment “// example: ignore error” per call to document intent.

Also applies to: 27-27, 52-53, 106-107, 140-141, 161-162

cmd/root.go (2)

221-227: Route UI banner to stderr.

The “ATMOS” banner is UI and should go to stderr to keep stdout pipeable.

Apply:

-    fmt.Println()
-    err := tuiUtils.PrintStyledText("ATMOS")
+    utils.PrintfMessageToTUI("\n")
+    err := tuiUtils.PrintStyledText("ATMOS")

(PrintfMessageToTUI writes to stderr.) Based on learnings.


787-790: Help banner: prefer stderr for UI paths.

Use the same TUI helper to write the banner to stderr for consistency with the new pattern.

Apply:

-    fmt.Println()
-    err := tuiUtils.PrintStyledText("ATMOS")
+    utils.PrintfMessageToTUI("\n")
+    err := tuiUtils.PrintStyledText("ATMOS")
pkg/io/terminal.go (1)

87-91: RestoreTitle is a no‑op; make it best‑effort.

Without querying the current title, restore to a neutral title (empty) on stderr when enabled.

Apply:

-func (t *terminal) RestoreTitle() {
-    if t.originalTitle != "" {
-        t.SetTitle(t.originalTitle)
-    }
-}
+func (t *terminal) RestoreTitle() {
+    if !t.config.AtmosConfig.Settings.Terminal.Title {
+        return
+    }
+    if !t.IsTTY(StreamError) {
+        return
+    }
+    // Best-effort: reset to default by setting empty title.
+    fmt.Fprint(os.Stderr, "\033]0;\007")
+}
pkg/io/masker_test.go (1)

3-6: Update imports for runtime-encoded test values.

Bring in url and strings to construct tokens at runtime; avoids secret scanner noise.

Apply:

-import (
-    "regexp"
-    "testing"
-)
+import (
+    "encoding/base64"
+    "net/url"
+    "regexp"
+    "strings"
+    "testing"
+)
pkg/io/context_test.go (3)

267-316: Use t.Setenv to isolate env; avoid manual save/restore.

This test mutates global env and viper; prefer t.Setenv for restoration and clarity. Keep tests non-parallel here due to globals.

Apply:

- // Save original env
- origNoColor := os.Getenv("NO_COLOR")
- origCLIColor := os.Getenv("CLICOLOR")
- origCLIColorForce := os.Getenv("CLICOLOR_FORCE")
- origTerm := os.Getenv("TERM")
- origColorTerm := os.Getenv("COLORTERM")
-
- // Restore env after test
- defer func() {
-   os.Setenv("NO_COLOR", origNoColor)
-   os.Setenv("CLICOLOR", origCLIColor)
-   os.Setenv("CLICOLOR_FORCE", origCLIColorForce)
-   os.Setenv("TERM", origTerm)
-   os.Setenv("COLORTERM", origColorTerm)
- }()
+ // Use t.Setenv for automatic restore.
+ t.Setenv("NO_COLOR", "")
+ t.Setenv("CLICOLOR", "")
+ t.Setenv("CLICOLOR_FORCE", "")
+ t.Setenv("TERM", "")
+ t.Setenv("COLORTERM", "")
@@
- // Set test env vars
- os.Setenv("NO_COLOR", "1")
- os.Setenv("CLICOLOR", "0")
- os.Setenv("TERM", "xterm-256color")
+ // Set test env vars
+ t.Setenv("NO_COLOR", "1")
+ t.Setenv("CLICOLOR", "0")
+ t.Setenv("TERM", "xterm-256color")

318-383: Strengthen option wiring assertions.

Validate referential equality to ensure options really take effect.

Apply:

@@
- // Test WithStreams option
+ // Test WithStreams option
   t.Run("WithStreams", func(t *testing.T) {
     mockStreams := &mockStreams{}
     ctx, err := NewContext(WithStreams(mockStreams))
@@
-   // Verify custom streams were set by checking it's not nil
-   if ctx.Streams() == nil {
-     t.Error("WithStreams() did not set custom streams")
-   }
+   if ctx.Streams() != mockStreams {
+     t.Errorf("WithStreams() expected %T, got %T", mockStreams, ctx.Streams())
+   }
   })
@@
- // Test WithTerminal option
+ // Test WithTerminal option
   t.Run("WithTerminal", func(t *testing.T) {
     mockTerm := &mockTerminal{}
     ctx, err := NewContext(WithTerminal(mockTerm))
@@
-   // Verify terminal was set - check that it returns our mock's color profile
-   if ctx.Terminal().ColorProfile() != ColorNone {
-     t.Error("WithTerminal() did not set custom terminal (wrong color profile)")
-   }
+   if ctx.Terminal() != mockTerm {
+     t.Errorf("WithTerminal() expected %T, got %T", mockTerm, ctx.Terminal())
+   }
   })
@@
- // Test WithMasker option
+ // Test WithMasker option
   t.Run("WithMasker", func(t *testing.T) {
     mockMask := &mockMasker{}
     ctx, err := NewContext(WithMasker(mockMask))
@@
-   // Verify masker was set - check it's not nil
-   if ctx.Masker() == nil {
-     t.Error("WithMasker() did not set custom masker")
-   }
+   if ctx.Masker() != mockMask {
+     t.Errorf("WithMasker() expected %T, got %T", mockMask, ctx.Masker())
+   }
   })

44-126: Add precedence edge cases for color heuristics.

Cover config vs env precedence to lock behavior:

  • atmos settings Terminal.NoColor=true should disable color even on TTY.
  • NO_COLOR + --color should still disable.

Example table rows to add:

@@
   tests := []struct {
@@
   }{
+   {
+     name: "Atmos Terminal.NoColor overrides TTY",
+     config: &Config{
+       AtmosConfig: func() schema.AtmosConfiguration {
+         c := newDefaultAtmosConfig()
+         c.Settings.Terminal.Color = false
+         c.Settings.Terminal.NoColor = true
+         return c
+       }(),
+     },
+     isTTY: true,
+     want:  false,
+   },
+   {
+     name: "NO_COLOR wins over --color",
+     config: &Config{
+       EnvNoColor: true,
+       Color:      true,
+     },
+     isTTY: true,
+     want:  false,
+   },
   }

If precedence differs by design, reply with the intended order so tests match it.

pkg/data/data.go (3)

39-49: Wrap errors with context and normalize newlines.

Propagate actionable errors and keep JSON/YAML outputs consistent with trailing newline.

Apply:

 func Write(content string) error {
-  _, err := fmt.Fprint(getIOContext().Data(), content)
-  return err
+  _, err := fmt.Fprint(getIOContext().Data(), content)
+  if err != nil {
+    return fmt.Errorf("data.Write: %w", err)
+  }
+  return nil
 }
@@
 func Writef(format string, a ...interface{}) error {
-  _, err := fmt.Fprintf(getIOContext().Data(), format, a...)
-  return err
+  _, err := fmt.Fprintf(getIOContext().Data(), format, a...)
+  if err != nil {
+    return fmt.Errorf("data.Writef: %w", err)
+  }
+  return nil
 }
@@
 func WriteJSON(v interface{}) error {
   output, err := json.MarshalIndent(v, "", "  ")
   if err != nil {
-    return err
+    return fmt.Errorf("data.WriteJSON: %w", err)
   }
   return Write(string(output) + "\n")
 }
@@
 func WriteYAML(v interface{}) error {
   output, err := yaml.Marshal(v)
   if err != nil {
-    return err
+    return fmt.Errorf("data.WriteYAML: %w", err)
   }
-  return Write(string(output))
+  return Write(string(output) + "\n")
 }

As per coding guidelines.

Also applies to: 51-58, 60-67


18-25: Guard against double initialization; make init idempotent or explicit.

Calling InitWriter twice can silently swap the global. Either no-op on subsequent calls or panic with a clear message. Pick one and document it.

Option A (idempotent):

 func InitWriter(ioCtx io.Context) {
   ioMu.Lock()
   defer ioMu.Unlock()
-  globalIOContext = ioCtx
+  if globalIOContext != nil {
+    return
+  }
+  globalIOContext = ioCtx
 }

Option B (fail fast):

-  globalIOContext = ioCtx
+  if globalIOContext != nil {
+    panic("data.InitWriter called more than once")
+  }
+  globalIOContext = ioCtx

Also consider a test-only Reset for isolation. Based on learnings.

Also applies to: 26-37


18-25: Add perf tracking to exported functions (if required).

Guidelines call for defer perf.Track(...) at start of public functions. Add to InitWriter/Write/Writef/WriteJSON/WriteYAML.

Confirm the correct import path for perf.Track and the preferred label format so we can send a precise diff.

pkg/ui/formatter_test.go (1)

1-642: Great coverage; add channel-routing tests.

Two gaps:

  • Verify top-level UI wrappers (ui.Success/Warning/Error/Info) actually write to stderr.
  • Verify Markdown(useDataChannel) routes to stdout vs stderr.

Add tests:

// at end of file
func TestUI_Wrappers_WriteToUI(t *testing.T) {
  var uiBuf, dataBuf strings.Builder
  // minimal streams that direct UI->uiBuf, Data->dataBuf
  type bufStreams struct{}
  func (bufStreams) Input() io.Reader     { return strings.NewReader("") }
  func (bufStreams) Output() io.Writer    { return &dataBuf }
  func (bufStreams) Error() io.Writer     { return &uiBuf }
  func (bufStreams) RawOutput() io.Writer { return &dataBuf }
  func (bufStreams) RawError() io.Writer  { return &uiBuf }

  ioCtx, _ := iolib.NewContext(iolib.WithStreams(bufStreams{}), iolib.WithTerminal(&mockTerminal{profile: iolib.ColorNone}))
  InitFormatter(ioCtx) // if required by package
  // Exercise wrappers
  _ = Success("ok")
  _ = Warning("care")
  _ = Error("bad")
  _ = Info("note")

  if uiBuf.Len() == 0 {
    t.Fatal("UI wrappers did not write to UI (stderr)")
  }
  if dataBuf.Len() != 0 {
    t.Fatalf("UI wrappers wrote to data (stdout): %q", dataBuf.String())
  }
}

func TestUI_Markdown_ChannelRouting(t *testing.T) {
  var uiBuf, dataBuf strings.Builder
  type bufStreams struct{}
  func (bufStreams) Input() io.Reader     { return strings.NewReader("") }
  func (bufStreams) Output() io.Writer    { return &dataBuf }
  func (bufStreams) Error() io.Writer     { return &uiBuf }
  func (bufStreams) RawOutput() io.Writer { return &dataBuf }
  func (bufStreams) RawError() io.Writer  { return &uiBuf }

  ioCtx, _ := iolib.NewContext(iolib.WithStreams(bufStreams{}), iolib.WithTerminal(&mockTerminal{profile: iolib.ColorNone}))
  InitFormatter(ioCtx)
  _ = Markdown("# Title", true)  // to data
  _ = Markdown("# Title", false) // to UI

  if !strings.Contains(dataBuf.String(), "Title") {
    t.Error("Markdown(useDataChannel=true) did not write to data (stdout)")
  }
  if !strings.Contains(uiBuf.String(), "Title") {
    t.Error("Markdown(useDataChannel=false) did not write to UI (stderr)")
  }
}

Optional: consider generating mocks via mockgen for iolib.Terminal to align with guidelines. As per coding guidelines.

pkg/io/interfaces.go (1)

178-201: Add reverse converter for symmetry (optional).

Consider StreamType.ToChannel() to ease migrations the other way.

Example:

 type StreamType int
@@
 func (st StreamType) String() string { /* existing */ }
+
+// ToChannel converts legacy StreamType to Channel.
+func (st StreamType) ToChannel() Channel {
+  switch st {
+  case StreamInput:
+    return InputChannel
+  case StreamError:
+    return UIChannel
+  case StreamOutput:
+    fallthrough
+  default:
+    return DataChannel
+  }
+}

Also applies to: 202-239

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9034085 and fcd561f.

📒 Files selected for processing (12)
  • cmd/root.go (2 hunks)
  • pkg/data/data.go (1 hunks)
  • pkg/io/context_test.go (1 hunks)
  • pkg/io/example_test.go (1 hunks)
  • pkg/io/interfaces.go (1 hunks)
  • pkg/io/masker.go (1 hunks)
  • pkg/io/masker_test.go (1 hunks)
  • pkg/io/streams.go (1 hunks)
  • pkg/io/terminal.go (1 hunks)
  • pkg/ui/formatter_test.go (1 hunks)
  • pkg/ui/interfaces.go (1 hunks)
  • pkg/ui/output_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • pkg/ui/output_test.go
  • pkg/io/streams.go
  • pkg/ui/interfaces.go
🧰 Additional context used
📓 Path-based instructions (6)
cmd/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

cmd/**/*.go: Use Cobra's recommended command structure with a root command and subcommands
Implement each CLI command in a separate file under cmd/
Use Viper for managing configuration, environment variables, and flags in the CLI
Keep separation of concerns between CLI interface (cmd) and business logic
Use kebab-case for command-line flags
Provide comprehensive help text for all commands and flags
Include examples in Cobra command help
Use Viper for configuration management; support files, env vars, and flags with precedence flags > env > config > defaults
Follow single responsibility; separate command interface from business logic
Provide meaningful user feedback and include progress indicators for long-running operations
Provide clear error messages to users and troubleshooting hints where appropriate

cmd/**/*.go: New CLI commands must use the command registry pattern via CommandProvider and register through the command registry (see cmd/internal/registry.go).
Commands should embed *_usage.md via //go:embed and render with utils.PrintfMarkdown().
UI (prompts/status) must write to stderr; data outputs to stdout; logging only for system events (never for UI).
For non-standard execution paths, capture telemetry with telemetry.CaptureCmd(); normal paths are auto-enabled via RootCmd.ExecuteC(). Never capture user data.

Files:

  • cmd/root.go
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments

**/*.go: Define interfaces for major functionality and use dependency injection to enable testability.
Generate mocks using go.uber.org/mock/mockgen via //go:generate directives (never manual mocks).
Prefer functional Options pattern instead of functions with many parameters for configuration.
Use context.Context only for cancellation, deadlines/timeouts, and request-scoped values; never for configuration or dependencies; context should be the first parameter.
All comments must end with periods (godot linter).
Preserve helpful existing comments; update them to match code when refactoring; only remove when incorrect, redundant, or code removed.
Organize imports in three groups (stdlib, third-party, Atmos) separated by blank lines and sorted alphabetically; maintain aliases cfg, log, u, errUtils.
Add defer perf.Track(atmosConfig, "pkg.FuncName")() (or nil if no atmosConfig) plus a blank line at the start of all public functions for performance tracking.
Use static errors from errors/errors.go; wrap with fmt.Errorf("%w") for chaining; use errors.Join for independent errors; avoid dynamic errors and string comparison; use errors.Is for checks.
Never use //revive:disable:file-length-limit to bypass file size limits; keep files small and focused (<600 lines).
Environment variables must be bound with viper.BindEnv using ATMOS_ prefix (e.g., viper.BindEnv("ATMOS_VAR", "ATMOS_VAR", "FALLBACK")).
Ensure cross-platform compatibility: use filepath.Join instead of hardcoded path separators and prefer SDKs over shelling out to binaries.

Files:

  • cmd/root.go
  • pkg/io/terminal.go
  • pkg/ui/formatter_test.go
  • pkg/io/masker.go
  • pkg/data/data.go
  • pkg/io/interfaces.go
  • pkg/io/example_test.go
  • pkg/io/context_test.go
  • pkg/io/masker_test.go
**/!(*_test).go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Document all exported functions, types, and methods with Go doc comments

Files:

  • cmd/root.go
  • pkg/io/terminal.go
  • pkg/io/masker.go
  • pkg/data/data.go
  • pkg/io/interfaces.go
{cmd,pkg/ui}/**/*.go

📄 CodeRabbit inference engine (CLAUDE.md)

Use theme colors from pkg/ui/theme/colors.go for UI elements.

Files:

  • cmd/root.go
  • pkg/ui/formatter_test.go
pkg/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Place business logic in pkg rather than in cmd

Files:

  • pkg/io/terminal.go
  • pkg/ui/formatter_test.go
  • pkg/io/masker.go
  • pkg/data/data.go
  • pkg/io/interfaces.go
  • pkg/io/example_test.go
  • pkg/io/context_test.go
  • pkg/io/masker_test.go
**/*_test.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*_test.go: Every new feature must include comprehensive unit tests
Test both happy paths and error conditions
Use table-driven tests for multiple scenarios

**/*_test.go: Prefer unit tests with mocks over integration tests; use interfaces + DI; table-driven tests for coverage; target >80% coverage.
Tests must exercise production code paths; avoid duplicating implementation logic in tests.
Use t.Skipf("reason") with clear context when skipping tests; CLI tests may auto-build temp binaries.

Files:

  • pkg/ui/formatter_test.go
  • pkg/io/example_test.go
  • pkg/io/context_test.go
  • pkg/io/masker_test.go
🧠 Learnings (3)
📚 Learning: 2025-09-13T18:06:07.674Z
Learnt from: samtholiya
PR: cloudposse/atmos#1466
File: toolchain/list.go:39-42
Timestamp: 2025-09-13T18:06:07.674Z
Learning: In the cloudposse/atmos repository, for UI messages in the toolchain package, use utils.PrintfMessageToTUI instead of log.Error or fmt.Fprintln(os.Stderr, ...). Import pkg/utils with alias "u" to follow the established pattern.

Applied to files:

  • cmd/root.go
📚 Learning: 2024-12-11T18:40:12.808Z
Learnt from: Listener430
PR: cloudposse/atmos#844
File: cmd/helmfile.go:37-37
Timestamp: 2024-12-11T18:40:12.808Z
Learning: In the atmos project, `cliConfig` is initialized within the `cmd` package in `root.go` and can be used in other command files.

Applied to files:

  • cmd/root.go
📚 Learning: 2025-09-23T02:30:42.362Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-09-23T02:30:42.362Z
Learning: Applies to **/*_test.go : Every new feature must include comprehensive unit tests

Applied to files:

  • pkg/io/example_test.go
  • pkg/io/masker_test.go
🧬 Code graph analysis (9)
cmd/root.go (3)
pkg/io/context.go (1)
  • NewContext (23-52)
pkg/ui/formatter.go (2)
  • Errorf (77-81)
  • InitFormatter (23-28)
pkg/data/data.go (1)
  • InitWriter (20-24)
pkg/io/terminal.go (2)
pkg/io/interfaces.go (11)
  • Config (134-150)
  • ColorProfile (153-153)
  • Terminal (71-98)
  • StreamOutput (184-184)
  • StreamError (185-185)
  • Channel (204-204)
  • DataChannel (207-207)
  • UIChannel (208-208)
  • InputChannel (209-209)
  • StreamType (180-180)
  • StreamInput (183-183)
pkg/schema/schema.go (1)
  • Terminal (208-218)
pkg/ui/formatter_test.go (5)
pkg/ui/formatter.go (8)
  • Error (70-74)
  • Errorf (77-81)
  • Success (56-60)
  • Warning (84-88)
  • Info (98-102)
  • Successf (63-67)
  • Warningf (91-95)
  • Infof (105-109)
pkg/io/interfaces.go (7)
  • ColorProfile (153-153)
  • ColorNone (156-156)
  • Color16 (157-157)
  • Color256 (158-158)
  • ColorTrue (159-159)
  • Context (18-39)
  • Config (134-150)
internal/tui/utils/utils.go (1)
  • RenderMarkdown (58-95)
pkg/io/context.go (2)
  • NewContext (23-52)
  • WithTerminal (104-108)
pkg/ui/interfaces.go (1)
  • Formatter (24-60)
pkg/io/masker.go (1)
pkg/io/interfaces.go (2)
  • Config (134-150)
  • Masker (101-131)
pkg/data/data.go (1)
internal/tui/utils/utils.go (2)
  • WriteJSON (24-26)
  • WriteYAML (30-32)
pkg/io/interfaces.go (2)
pkg/schema/schema.go (2)
  • Terminal (208-218)
  • AtmosConfiguration (27-65)
pkg/ui/interfaces.go (1)
  • Output (97-124)
pkg/io/example_test.go (4)
pkg/io/context.go (1)
  • NewContext (23-52)
pkg/ui/formatter.go (5)
  • NewFormatter (124-131)
  • Success (56-60)
  • Warning (84-88)
  • Error (70-74)
  • Info (98-102)
internal/tui/utils/utils.go (1)
  • RenderMarkdown (58-95)
pkg/io/interfaces.go (4)
  • Terminal (71-98)
  • UIChannel (208-208)
  • DataChannel (207-207)
  • ColorProfile (153-153)
pkg/io/context_test.go (3)
pkg/io/context.go (4)
  • NewContext (23-52)
  • WithStreams (97-101)
  • WithTerminal (104-108)
  • WithMasker (111-115)
pkg/io/interfaces.go (13)
  • Streams (44-67)
  • Terminal (71-98)
  • Config (134-150)
  • Masker (101-131)
  • ColorProfile (153-153)
  • ColorNone (156-156)
  • ColorTrue (159-159)
  • Color256 (158-158)
  • Color16 (157-157)
  • StreamType (180-180)
  • StreamInput (183-183)
  • StreamOutput (184-184)
  • StreamError (185-185)
pkg/schema/schema.go (4)
  • Terminal (208-218)
  • AtmosConfiguration (27-65)
  • Settings (758-762)
  • AtmosSettings (253-273)
pkg/io/masker_test.go (1)
pkg/io/interfaces.go (2)
  • Config (134-150)
  • Masker (101-131)
🪛 Gitleaks (8.28.0)
pkg/io/masker_test.go

[high] 111-111: Uncovered a GitHub Personal Access Token, potentially leading to unauthorized repository access and sensitive content exposure.

(github-pat)


[high] 52-52: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Build (windows)
  • GitHub Check: Build (linux)
  • GitHub Check: Build (macos)
  • GitHub Check: Analyze (go)
  • GitHub Check: Review Dependency Licenses
  • GitHub Check: autofix
  • GitHub Check: Summary
🔇 Additional comments (3)
pkg/io/example_test.go (1)

10-80: Examples clearly show the “where vs how” split. LGTM.

Nice separation of Data (stdout) vs UI (stderr) and instance-formatter usage. Good coverage of TTY-conditional paths.

Also applies to: 82-114, 116-163, 165-203

pkg/io/interfaces.go (1)

1-239: Solid, clear API surface.

Interfaces and enums are well documented; deprecation notes help migration.

pkg/data/data.go (1)

26-37: Current panic message is sufficient; suggested hint references non-existent function.

The review's suggestion to add hint about "cmd/root.Init()" is inaccurate. There is no cmd/root.Init() function—initialization actually occurs in Execute() (the root command handler), which is called by main() before any command handlers run. The current panic message "data.InitWriter() must be called before using data package functions" is already explicit about the requirement and correctly guides developers. No change needed.

Likely an incorrect or invalid review comment.

Comment thread pkg/io/terminal.go Resolved
Created pkg/terminal/ package with:
- Terminal interface and implementation
- ColorProfile detection
- TTY detection, width/height
- Terminal title and alerts
- Config for terminal-specific settings

Removed Terminal() from io.Context interface - terminal capabilities
are UI concerns, not I/O concerns.

I/O package should only handle:
- Channels (stdin/stdout/stderr)
- Masking (secret redaction)

Terminal package handles:
- TTY detection
- Color capabilities
- Terminal dimensions
- Terminal control (title, alerts)

Still TODO:
- Update io.Config to remove terminal fields
- Remove Terminal interface from io/interfaces.go
- Update ui.Formatter to use terminal package
- Update all io.Terminal references

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Comment thread pkg/io/context.go Fixed

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (2)
pkg/terminal/terminal.go (2)

223-247: Prefer viper.BindEnv for env wiring; keep raw reads for standard vars if intended.

Guidelines prefer env via viper.BindEnv, using ATMOS_* for project variables. For standard cross-tooling vars (NO_COLOR, CLICOLOR, CLICOLOR_FORCE, TERM, COLORTERM), direct os.Getenv is acceptable, but consider binding for consistency and testability.

Optional cleanup:

- EnvNoColor:       os.Getenv("NO_COLOR") != "",
- EnvCLIColor:      os.Getenv("CLICOLOR"),
- EnvCLIColorForce: os.Getenv("CLICOLOR_FORCE") != "",
- EnvTerm:          os.Getenv("TERM"),
- EnvColorTerm:     os.Getenv("COLORTERM"),
+ _ = viper.BindEnv("no_color_env", "NO_COLOR")
+ _ = viper.BindEnv("clicolor", "CLICOLOR")
+ _ = viper.BindEnv("clicolor_force", "CLICOLOR_FORCE")
+ _ = viper.BindEnv("term_env", "TERM")
+ _ = viper.BindEnv("colorterm_env", "COLORTERM")
+ EnvNoColor:       viper.GetString("no_color_env") != "",
+ EnvCLIColor:      viper.GetString("clicolor"),
+ EnvCLIColorForce: viper.GetString("clicolor_force") != "",
+ EnvTerm:          viper.GetString("term_env"),
+ EnvColorTerm:     viper.GetString("colorterm_env"),

60-74: Minor: comment nits for godot linter and clarity.

  • Ensure all exported identifier comments end with periods.
  • Inline trailing comments like “// No color support” don’t need godot, but top-of-decl comments should be full sentences.

Low priority.

Also applies to: 76-92

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between fcd561f and ab789b7.

📒 Files selected for processing (2)
  • pkg/io/interfaces.go (1 hunks)
  • pkg/terminal/terminal.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/io/interfaces.go
🧰 Additional context used
📓 Path-based instructions (3)
pkg/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Place business logic in pkg rather than in cmd

Files:

  • pkg/terminal/terminal.go
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments

**/*.go: Define interfaces for major functionality and use dependency injection to enable testability.
Generate mocks using go.uber.org/mock/mockgen via //go:generate directives (never manual mocks).
Prefer functional Options pattern instead of functions with many parameters for configuration.
Use context.Context only for cancellation, deadlines/timeouts, and request-scoped values; never for configuration or dependencies; context should be the first parameter.
All comments must end with periods (godot linter).
Preserve helpful existing comments; update them to match code when refactoring; only remove when incorrect, redundant, or code removed.
Organize imports in three groups (stdlib, third-party, Atmos) separated by blank lines and sorted alphabetically; maintain aliases cfg, log, u, errUtils.
Add defer perf.Track(atmosConfig, "pkg.FuncName")() (or nil if no atmosConfig) plus a blank line at the start of all public functions for performance tracking.
Use static errors from errors/errors.go; wrap with fmt.Errorf("%w") for chaining; use errors.Join for independent errors; avoid dynamic errors and string comparison; use errors.Is for checks.
Never use //revive:disable:file-length-limit to bypass file size limits; keep files small and focused (<600 lines).
Environment variables must be bound with viper.BindEnv using ATMOS_ prefix (e.g., viper.BindEnv("ATMOS_VAR", "ATMOS_VAR", "FALLBACK")).
Ensure cross-platform compatibility: use filepath.Join instead of hardcoded path separators and prefer SDKs over shelling out to binaries.

Files:

  • pkg/terminal/terminal.go
**/!(*_test).go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Document all exported functions, types, and methods with Go doc comments

Files:

  • pkg/terminal/terminal.go
🧬 Code graph analysis (1)
pkg/terminal/terminal.go (1)
pkg/io/interfaces.go (7)
  • ColorProfile (151-151)
  • ColorNone (154-154)
  • Color16 (155-155)
  • Color256 (156-156)
  • ColorTrue (157-157)
  • Config (132-148)
  • Terminal (69-96)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Build (windows)
  • GitHub Check: Build (linux)
  • GitHub Check: Analyze (go)
  • GitHub Check: Review Dependency Licenses
  • GitHub Check: autofix
  • GitHub Check: Summary
🔇 Additional comments (1)
pkg/terminal/terminal.go (1)

120-128: Add perf.Track to exported functions/methods per guidelines.

Repository guideline requires defer perf.Track(atmosConfig, "pkg.FuncName")() at the start of all public functions. Add it to:

  • New, WithConfig, IsTTY, ColorProfile, Width, Height, SetTitle, RestoreTitle, Alert, ShouldUseColor, DetectColorProfile.

Example pattern:

func New(opts ...Option) Terminal {
+ defer perf.Track(t?.config?.AtmosConfig, "terminal.New")() // pass nil or cfg as applicable
+
  cfg := buildConfig()
  ...
}

For methods, pass t.config.AtmosConfig (or nil). Import perf in the Atmos group.

Also applies to: 130-140, 142-168, 170-206, 223-247, 249-327

⛔ Skipped due to learnings
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T14:51:19.340Z
Learning: Applies to **/*.go : Add defer perf.Track(atmosConfig, "pkg.FuncName")() (or nil if no atmosConfig) plus a blank line at the start of all public functions for performance tracking.
Learnt from: osterman
PR: cloudposse/atmos#1599
File: pkg/ui/markdown/renderer.go:247-259
Timestamp: 2025-10-11T19:06:16.131Z
Learning: Performance tracking with `defer perf.Track()` should be reserved for functions that perform actual computational work, I/O operations, or have measurable performance impact. Simple wrapper methods that immediately delegate to other functions do not require performance tracking, as it adds unnecessary overhead without providing meaningful insights.
Learnt from: osterman
PR: cloudposse/atmos#1599
File: pkg/ui/markdown/renderer.go:143-182
Timestamp: 2025-10-11T19:12:23.475Z
Learning: High-frequency utility and formatting functions (e.g., markdown renderers, formatters) that are called repeatedly during command execution should not have `defer perf.Track()` even if they are public methods. Performance tracking at these levels introduces unnecessary overhead without meaningful insights, as tracking is already present at higher command-execution levels where it provides actionable data.

Comment thread pkg/terminal/terminal.go Resolved
Comment thread pkg/terminal/terminal.go Resolved
Comment thread pkg/terminal/terminal.go Resolved
Comment thread pkg/terminal/terminal.go Resolved
Comment thread pkg/terminal/terminal.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

♻️ Duplicate comments (6)
pkg/io/masker_test.go (2)

108-116: Refactor PAT literal; construct at runtime.
Prevents gitleaks hits while keeping the test meaningful.

-	re := regexp.MustCompile(`ghp_[A-Za-z0-9]{36}`)
-	m.RegisterRegex(re)
-
-	input := "GitHub token: ghp_123456789012345678901234567890123456"
+	re := regexp.MustCompile(`ghp_[A-Za-z0-9]{36}`)
+	m.RegisterRegex(re)
+	fake := "ghp_" + strings.Repeat("1", 36)
+	input := "GitHub token: " + fake
 	expected := "GitHub token: ***MASKED***"

3-6: Avoid secret-scanner false positives; encode at runtime + fix URL case.
Build encodings at runtime and actually URL-encode.

-import (
-	"regexp"
-	"testing"
-)
+import (
+	"net/url"
+	"regexp"
+	"strings"
+	"testing"
+)
@@
-		{
-			name:  "base64 encoded",
-			input: "Token: bXlTZWNyZXRUb2tlbg==",
-			want:  "Token: ***MASKED***",
-		},
-		{
-			name:  "URL encoded",
-			input: "Token: mySecretToken",
-			want:  "Token: ***MASKED***",
-		},
+		{
+			name: "base64 encoded",
+			input: func() string {
+				enc := "bXlTZWNyZXRUb2tlbg==" // base64("mySecretToken") without importing base64 to keep test minimal.
+				return "Token: " + enc
+			}(),
+			want: "Token: ***MASKED***",
+		},
+		{
+			name:  "URL encoded",
+			input: "Token: " + url.QueryEscape(secret),
+			want:  "Token: ***MASKED***",
+		},

Also applies to: 51-59

pkg/ui/interfaces.go (1)

9-11: Align docs: Formatter mostly returns strings; Markdown is the one writer.
Doc says “never writes,” but Markdown performs I/O. Reword to avoid confusion.

-// Formatter provides text formatting with automatic degradation.
-// Key Principle: Formatter RETURNS FORMATTED STRINGS - it never writes to streams.
+// Formatter provides text formatting with automatic degradation.
+// Key Principle: Formatter returns formatted strings. Markdown is the only method that writes to streams for convenience.
@@
-	// Markdown rendering - writes rendered markdown to channel (degrades gracefully to plain text)
-	// Automatically chooses Data or UI channel based on useDataChannel parameter
+	// Markdown rendering - writes rendered markdown to a channel (degrades gracefully to plain text).
+	// Automatically chooses Data or UI channel based on useDataChannel.

Also applies to: 46-49

pkg/io/masker.go (3)

64-71: Register JSON-encoded variants correctly.
You only add the unquoted inner string; most logs contain the quoted JSON, too.

-	// Register JSON encoded version
-	if jsonBytes, err := json.Marshal(secret); err == nil {
-		// Remove surrounding quotes
-		jsonStr := string(jsonBytes)
-		if len(jsonStr) > 2 {
-			m.RegisterValue(jsonStr[1 : len(jsonStr)-1])
-		}
-	}
+	// Register JSON-encoded versions (quoted and unquoted).
+	if jsonBytes, err := json.Marshal(secret); err == nil {
+		jsonStr := string(jsonBytes) // e.g., "mySecret"
+		m.RegisterValue(jsonStr)
+		if len(jsonStr) >= 2 && jsonStr[0] == '"' && jsonStr[len(jsonStr)-1] == '"' {
+			m.RegisterValue(jsonStr[1 : len(jsonStr)-1])
+		}
+	}

102-109: AWS secret regex is too broad; include ASIA and add context.

[A-Za-z0-9/+=]{40} will over-mask unrelated blobs. Scope to common labels and support ASIA temp keys.

-	// AWS access keys follow pattern: AKIA[0-9A-Z]{16}
-	// If this is a valid AWS access key, register a pattern to catch the paired secret key
-	if strings.HasPrefix(accessKeyID, "AKIA") && len(accessKeyID) == 20 {
-		// AWS secret keys are 40 characters of base64-like characters
-		// Register a pattern to catch anything that looks like an AWS secret key near this access key
-		// This is a best-effort approach
-		_ = m.RegisterPattern(`[A-Za-z0-9/+=]{40}`)
-	}
+	// If this looks like an AWS access key, also mask the paired secret when labeled.
+	if len(accessKeyID) == 20 && (strings.HasPrefix(accessKeyID, "AKIA") || strings.HasPrefix(accessKeyID, "ASIA")) {
+		// Match common labeling to reduce false positives.
+		_ = m.RegisterPattern(`(?i)\bAWS_SECRET_ACCESS_KEY\b[=:]\s*[A-Za-z0-9/+=]{40}`)
+	}

3-11: Fix unordered literal masking; ensure longest-first.

Map iteration is random; shorter literals can preempt longer ones and leak suffixes. Sort by length desc first.

 import (
 	"encoding/base64"
 	"encoding/json"
 	"fmt"
 	"net/url"
 	"regexp"
+	"sort"
 	"strings"
 	"sync"
 )
@@
-	// Mask literals (exact matches)
-	// Sort by length (longest first) to avoid partial replacements
-	for literal := range m.literals {
-		if literal != "" {
-			masked = strings.ReplaceAll(masked, literal, MaskReplacement)
-		}
-	}
+	// Mask literals (exact matches) longest-first to avoid partial replacements.
+	lits := make([]string, 0, len(m.literals))
+	for k := range m.literals {
+		if k != "" {
+			lits = append(lits, k)
+		}
+	}
+	sort.Slice(lits, func(i, j int) bool { return len(lits[i]) > len(lits[j]) })
+	for _, literal := range lits {
+		masked = strings.ReplaceAll(masked, literal, MaskReplacement)
+	}

Also applies to: 122-129

🧹 Nitpick comments (8)
pkg/io/example_test.go (1)

3-8: Organize imports per coding guidelines.

Imports should be organized in three groups (stdlib, third-party, Atmos) separated by blank lines. Add a blank line after the fmt import.

Apply this diff:

 import (
 	"fmt"
+
 	iolib "github.com/cloudposse/atmos/pkg/io"
 	"github.com/cloudposse/atmos/pkg/ui"
 )

As per coding guidelines.

pkg/io/interfaces.go (3)

69-73: Tighten IsTTY signature; avoid interface{}.

Accept a concrete type (Channel) and optionally provide a legacy helper for StreamType. This preserves type safety and simplifies callsites.

-	IsTTY(stream interface{}) bool
+	IsTTY(ch Channel) bool
+
+	// Legacy helper for migration.
+	// DEPRECATED: prefer IsTTY(Channel).
+	IsTTYStream(stream StreamType) bool

224-237: Ambiguous default in ToStreamType().

Returning StreamOutput for unknown channels can misroute output. Either return a sentinel (StreamType(-1)) or document the fallback strongly.

-	default:
-		return StreamOutput
+	default:
+		// Unknown; prefer explicit handling by caller.
+		return StreamType(-1)

1-1: Add mockgen directives for interfaces.

Generate mocks to support unit tests and DI.

 package io
+//go:generate mockgen -destination=./mocks/io_context_mock.go -package io github.com/cloudposse/atmos/pkg/io Context,Streams,Terminal,Masker

As per coding guidelines.

pkg/io/masker_test.go (1)

133-190: Add an overlap test to lock in longest-first behavior.
Catches regressions where shorter literals mask parts of longer ones.

@@
 		{
 			name: "combined literal and pattern",
 			setup: func(m Masker) {
 				m.RegisterValue("token123")
 				_ = m.RegisterPattern(`api_key=\w+`)
 			},
 			input: "token123 and api_key=xyz789",
 			want:  "***MASKED*** and ***MASKED***",
 		},
+		{
+			name: "overlapping literals longest-first",
+			setup: func(m Masker) {
+				m.RegisterValue("abcd")
+				m.RegisterValue("abc")
+			},
+			input: "xyz abcd abc",
+			want:  "xyz ***MASKED*** ***MASKED***",
+		},
pkg/ui/formatter_test.go (1)

1-643: Solid coverage; consider asserting write targets.

Nice breadth across color profiles and icons. If IO DI allows in-memory writers, add tests to verify ui.Success()/Error()/Info()/Warning() write to UI (stderr) and Markdown() writes to Data by default, to guard routing regressions.

If you want, I can sketch a buffer-backed io.Context and tests.

pkg/ui/interfaces.go (2)

12-23: Update usage example to avoid context value fishing.

Guidelines discourage using context for dependencies. Show DI or explicit variables instead.

-//	io := cmd.Context().Value(ioContextKey).(io.Context)
-//	ui := cmd.Context().Value(uiFormatterKey).(ui.Formatter)
+//	io := buildIOContext() // via dependency injection or constructor options.
+//	ui := buildFormatter(io)
@@
-//	fmt.Fprintf(io.UI(), "%s\n", msg)  // UI message → stderr
+//	fmt.Fprintf(io.UI(), "%s\n", msg)  // UI message → stderr.

As per coding guidelines.


1-8: Add mockgen directives for UI interfaces.

Generate mocks for Formatter and Output.

 package ui
+//go:generate mockgen -destination=./mocks/ui_formatter_mock.go -package ui github.com/cloudposse/atmos/pkg/ui Formatter,Output
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between ab789b7 and bade93e.

📒 Files selected for processing (11)
  • cmd/root.go (2 hunks)
  • pkg/io/context_test.go (1 hunks)
  • pkg/io/example_test.go (1 hunks)
  • pkg/io/interfaces.go (1 hunks)
  • pkg/io/masker.go (1 hunks)
  • pkg/io/masker_test.go (1 hunks)
  • pkg/io/streams.go (1 hunks)
  • pkg/io/terminal.go (1 hunks)
  • pkg/ui/formatter_test.go (1 hunks)
  • pkg/ui/interfaces.go (1 hunks)
  • pkg/ui/output_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • pkg/io/context_test.go
  • pkg/io/terminal.go
  • cmd/root.go
  • pkg/io/streams.go
  • pkg/ui/output_test.go
🧰 Additional context used
📓 Path-based instructions (5)
pkg/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Place business logic in pkg rather than in cmd

Files:

  • pkg/io/masker_test.go
  • pkg/io/example_test.go
  • pkg/io/interfaces.go
  • pkg/io/masker.go
  • pkg/ui/interfaces.go
  • pkg/ui/formatter_test.go
**/*_test.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*_test.go: Every new feature must include comprehensive unit tests
Test both happy paths and error conditions
Use table-driven tests for multiple scenarios

**/*_test.go: Prefer unit tests with mocks over integration tests; use interfaces + DI; table-driven tests for coverage; target >80% coverage.
Tests must exercise production code paths; avoid duplicating implementation logic in tests.
Use t.Skipf("reason") with clear context when skipping tests; CLI tests may auto-build temp binaries.

Files:

  • pkg/io/masker_test.go
  • pkg/io/example_test.go
  • pkg/ui/formatter_test.go
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments

**/*.go: Define interfaces for major functionality and use dependency injection to enable testability.
Generate mocks using go.uber.org/mock/mockgen via //go:generate directives (never manual mocks).
Prefer functional Options pattern instead of functions with many parameters for configuration.
Use context.Context only for cancellation, deadlines/timeouts, and request-scoped values; never for configuration or dependencies; context should be the first parameter.
All comments must end with periods (godot linter).
Preserve helpful existing comments; update them to match code when refactoring; only remove when incorrect, redundant, or code removed.
Organize imports in three groups (stdlib, third-party, Atmos) separated by blank lines and sorted alphabetically; maintain aliases cfg, log, u, errUtils.
Add defer perf.Track(atmosConfig, "pkg.FuncName")() (or nil if no atmosConfig) plus a blank line at the start of all public functions for performance tracking.
Use static errors from errors/errors.go; wrap with fmt.Errorf("%w") for chaining; use errors.Join for independent errors; avoid dynamic errors and string comparison; use errors.Is for checks.
Never use //revive:disable:file-length-limit to bypass file size limits; keep files small and focused (<600 lines).
Environment variables must be bound with viper.BindEnv using ATMOS_ prefix (e.g., viper.BindEnv("ATMOS_VAR", "ATMOS_VAR", "FALLBACK")).
Ensure cross-platform compatibility: use filepath.Join instead of hardcoded path separators and prefer SDKs over shelling out to binaries.

Files:

  • pkg/io/masker_test.go
  • pkg/io/example_test.go
  • pkg/io/interfaces.go
  • pkg/io/masker.go
  • pkg/ui/interfaces.go
  • pkg/ui/formatter_test.go
**/!(*_test).go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Document all exported functions, types, and methods with Go doc comments

Files:

  • pkg/io/interfaces.go
  • pkg/io/masker.go
  • pkg/ui/interfaces.go
{cmd,pkg/ui}/**/*.go

📄 CodeRabbit inference engine (CLAUDE.md)

Use theme colors from pkg/ui/theme/colors.go for UI elements.

Files:

  • pkg/ui/interfaces.go
  • pkg/ui/formatter_test.go
🧠 Learnings (1)
📚 Learning: 2025-09-23T02:30:42.362Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-09-23T02:30:42.362Z
Learning: Applies to **/*_test.go : Every new feature must include comprehensive unit tests

Applied to files:

  • pkg/io/masker_test.go
  • pkg/io/example_test.go
🧬 Code graph analysis (6)
pkg/io/masker_test.go (1)
pkg/io/interfaces.go (2)
  • Config (132-148)
  • Masker (99-129)
pkg/io/example_test.go (5)
pkg/io/context.go (1)
  • NewContext (23-52)
pkg/ui/formatter.go (5)
  • NewFormatter (124-131)
  • Success (56-60)
  • Warning (84-88)
  • Error (70-74)
  • Info (98-102)
internal/tui/utils/utils.go (1)
  • RenderMarkdown (58-95)
pkg/io/interfaces.go (4)
  • Terminal (69-96)
  • UIChannel (206-206)
  • DataChannel (205-205)
  • ColorProfile (151-151)
pkg/schema/schema.go (1)
  • Terminal (208-218)
pkg/io/interfaces.go (4)
pkg/terminal/terminal.go (6)
  • Config (77-91)
  • ColorProfile (51-51)
  • ColorNone (54-54)
  • Color16 (55-55)
  • Color256 (56-56)
  • ColorTrue (57-57)
pkg/ui/interfaces.go (1)
  • Output (97-124)
pkg/ui/formatter.go (1)
  • Error (70-74)
pkg/schema/schema.go (1)
  • AtmosConfiguration (27-65)
pkg/io/masker.go (1)
pkg/io/interfaces.go (2)
  • Config (132-148)
  • Masker (99-129)
pkg/ui/interfaces.go (3)
pkg/ui/formatter.go (9)
  • Success (56-60)
  • Successf (63-67)
  • Warning (84-88)
  • Warningf (91-95)
  • Error (70-74)
  • Errorf (77-81)
  • Info (98-102)
  • Infof (105-109)
  • Markdown (45-47)
pkg/io/interfaces.go (2)
  • ColorProfile (151-151)
  • Context (19-37)
internal/tui/utils/utils.go (1)
  • RenderMarkdown (58-95)
pkg/ui/formatter_test.go (5)
pkg/ui/formatter.go (8)
  • Error (70-74)
  • Errorf (77-81)
  • Success (56-60)
  • Warning (84-88)
  • Info (98-102)
  • Successf (63-67)
  • Warningf (91-95)
  • Infof (105-109)
pkg/io/interfaces.go (7)
  • ColorProfile (151-151)
  • ColorNone (154-154)
  • Color16 (155-155)
  • Color256 (156-156)
  • ColorTrue (157-157)
  • Context (19-37)
  • Config (132-148)
internal/tui/utils/utils.go (1)
  • RenderMarkdown (58-95)
pkg/io/context.go (2)
  • NewContext (23-52)
  • WithTerminal (104-108)
pkg/ui/interfaces.go (1)
  • Formatter (24-60)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Summary
🔇 Additional comments (1)
pkg/io/interfaces.go (1)

131-148: The architectural separation is intentional; ColorProfile duplication is the only legitimate concern.

The review conflates two distinct patterns. The Config types serve different purposes—pkg/terminal/Config handles TTY detection and color capabilities, while pkg/io/Config handles channels and masking with I/O-specific fields like RedirectStderr and DisableMasking. This separation is documented in the code itself.

ColorProfile is genuinely duplicated with identical definitions and methods, but there are no cross-package conversions, no imports between packages, and zero evidence of the "awkward conversions" or "drift" claimed. Rather than full unification, consider a single ColorProfile export from pkg/terminal that pkg/io reuses—acknowledging their architectural roles.

Likely an incorrect or invalid review comment.

Comment thread pkg/io/example_test.go Resolved
Comment thread pkg/io/example_test.go Resolved
- Move terminal capability detection from pkg/io/ to pkg/terminal/
- Separate concerns: I/O handles channels+masking, terminal handles TTY/color/dimensions
- Update io.Context to remove Terminal() method and terminal field
- Simplify io.Config to only I/O concerns (RedirectStderr, DisableMasking)
- Update UI layer to create its own terminal instance
- Update formatter to use terminal.Terminal instead of io.Terminal
- Update all tests to use new terminal package
- Remove pkg/io/terminal.go and pkg/io/terminal_test.go
- Update example_test.go with correct usage patterns

Architecture:
┌─────────────┐
│   Commands  │
└──┬────────┬─┘
   │        │
   ▼        ▼
┌────┐   ┌────┐
│ UI │   │Data│
└─┬──┘   └─┬──┘
  │        │
  └───┬────┘
      ▼
   ┌─────┐
   │ I/O │ Channels + Masking
   └─────┘
      ▲
      │
   ┌──────────┐
   │ Terminal │ TTY/Color/Capabilities
   └──────────┘
Implement the core architecture where all output flows through io.Write() for automatic masking:

- Add io.Context.Write(stream, content) as central masking choke point
- Add io.Stream type (DataStream=0, UIStream=1) for stream routing
- Update Terminal interface to include Write() method
- Terminal.Write() flows through io.Write(UIStream) for masking
- Create io.TerminalWriter adapter to connect terminal→io without circular dependency
- Update UI package-level functions to use terminal.Write() flow
- Update InitFormatter() to wire terminal with I/O context

Flow architecture:
  ui.Success()   → terminal.Write() → io.Write(UIStream) → masking → stderr
  data.Write()   → io.Write(DataStream) → masking → stdout (next commit)

The terminal.IOWriter interface uses int for stream parameter to avoid
circular dependency, with values 0=Data and 1=UI matching io.Stream values.

This establishes the foundation for consistent masking across all output channels.
Update data package to use centralized io.Write() for automatic masking:

- data.Write() → io.Write(DataStream) → masking → stdout
- data.Writef() → io.Write(DataStream) → masking → stdout
- data.WriteJSON() → io.Write(DataStream) → masking → stdout
- data.WriteYAML() → io.Write(DataStream) → masking → stdout

Add Write() method to mockTerminal in tests to satisfy terminal.Terminal interface.

All output now flows through io.Write() for centralized masking:
  UI:   ui.Success()   → terminal.Write() → io.Write(UIStream)   → stderr
  Data: data.Write()   → io.Write(DataStream) → stdout

Tests pass for pkg/io, pkg/ui, pkg/ui/heatmap, pkg/ui/markdown.
Add comprehensive documentation for the new I/O architecture:

- Add mermaid diagram showing four-layer architecture (Commands → UI/Data → Terminal → I/O)
- Document the complete flow: ui.Success() → terminal.Write() → io.Write() → masking → stderr
- Add secret masking section with detailed flow diagram
- Explain how io.Write() is the central choke point for ALL output
- Document masking registration API and examples
- Show how masking works transparently across both UI and Data channels

Key architecture principles documented:
1. All output flows through io.Write() for centralized masking
2. Terminal handles UI output with capabilities (TTY, color, width)
3. Data writes directly to io.Write(DataStream)
4. Masking is automatic - no developer action required

Includes visual diagrams for:
- Overall architecture flow
- Masking process (io.Write → masker.Mask → ***MASKED*** → output)
Improvements:
- Add ANSI escape sequence constants (escBEL, escOSC, escST) in terminal package
- Update SetTitle() to use terminal.Write() instead of direct os.Stderr
- Update Alert() to use terminal.Write() instead of direct os.Stderr
- Add I/O sentinel errors: ErrBuildIOConfig, ErrUnknownStream, ErrWriteToStream, ErrMaskingContent
- Use sentinel error wrapping throughout io.Context.Write()
- Proper error chain: fmt.Errorf("%w: %w", sentinelErr, err)

All terminal control sequences now flow through io.Write() for consistency,
and all errors use standard sentinel error patterns for better error handling.
Remove _archive-*.md files - we have git history for reference.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Correct major oversight in documentation - we DO support user-defined patterns today:
- Public API: io.RegisterPattern(), io.RegisterValue(), io.RegisterSecret()
- Configuration schema exists (mask.patterns, mask.literals)
- Config loading NOT implemented (Phase 2 priority)

This is THE reason we're not implementing pattern libraries - users can already
define custom patterns, we just need to hook up config loading.

Updated "Decision: Why Not Now?" section to reflect this accurately.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
docs/prd/secrets-masking/implementation.md (1)

333-337: Add language hints to non-code output blocks.

Lines 333 and 443 show output examples without language specifiers. Consider adding language hints to satisfy markdown linters (e.g., triple-backtick marks for benchmarks and plain text for help output).

Apply this diff to add language hints:

-\`\`\`
+\`\`\`text
 BenchmarkMaskingNoSecrets-8       500000    2847 ns/op    # No secrets

And:

-\`\`\`
+\`\`\`text
 Global Flags:
   --mask    Enable automatic masking of sensitive data

Also applies to: 443-448

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a1666b8 and a58e44a.

📒 Files selected for processing (3)
  • docs/prd/secrets-masking/README.md (1 hunks)
  • docs/prd/secrets-masking/future-considerations.md (1 hunks)
  • docs/prd/secrets-masking/implementation.md (1 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: Listener430
Repo: cloudposse/atmos PR: 934
File: tests/fixtures/scenarios/docs-generate/README.md.gotmpl:99-118
Timestamp: 2025-01-25T03:51:57.689Z
Learning: For the cloudposse/atmos repository, changes to template contents should be handled in dedicated PRs and are typically considered out of scope for PRs focused on other objectives.
Learnt from: samtholiya
Repo: cloudposse/atmos PR: 1466
File: toolchain/list.go:39-42
Timestamp: 2025-09-13T18:06:07.674Z
Learning: In the cloudposse/atmos repository, for UI messages in the toolchain package, use utils.PrintfMessageToTUI instead of log.Error or fmt.Fprintln(os.Stderr, ...). Import pkg/utils with alias "u" to follow the established pattern.
Learnt from: osterman
Repo: cloudposse/atmos PR: 808
File: pkg/config/config.go:478-483
Timestamp: 2024-12-02T21:26:32.337Z
Learning: In the 'atmos' project, when reviewing Go code like `pkg/config/config.go`, avoid suggesting file size checks after downloading remote configs if such checks aren't implemented elsewhere in the codebase.
Learnt from: aknysh
Repo: cloudposse/atmos PR: 1185
File: internal/exec/yaml_func_store.go:26-26
Timestamp: 2025-04-04T02:03:23.676Z
Learning: The Atmos codebase currently uses `log.Fatal` for error handling in multiple places. The maintainers are aware this isn't an ideal pattern (should only be used in main() or init() functions) and plan to address it comprehensively in a separate PR. CodeRabbit should not flag these issues or push for immediate changes until that refactoring is complete.
Learnt from: osterman
Repo: cloudposse/atmos PR: 727
File: internal/exec/terraform_clean.go:233-235
Timestamp: 2024-10-31T19:25:41.298Z
Learning: When specifying color values in functions like `confirmDeleteTerraformLocal` in `internal/exec/terraform_clean.go`, avoid hardcoding color values. Instead, use predefined color constants or allow customization through configuration settings to improve accessibility and user experience across different terminals and themes.
Learnt from: samtholiya
Repo: cloudposse/atmos PR: 1466
File: cmd/markdown/atmos_toolchain_aliases.md:2-4
Timestamp: 2025-09-13T16:39:20.007Z
Learning: In the cloudposse/atmos repository, CLI documentation files in cmd/markdown/ follow a specific format that uses " $ atmos command" (with leading space and dollar sign prompt) in code blocks. This is the established project convention and should not be changed to comply with standard markdownlint rules MD040 and MD014.
Learnt from: osterman
Repo: cloudposse/atmos PR: 740
File: cmd/cmd_utils.go:340-359
Timestamp: 2024-10-23T21:36:40.262Z
Learning: In the Go codebase for Atmos, when reviewing functions like `checkAtmosConfig` in `cmd/cmd_utils.go`, avoid suggesting refactoring to return errors instead of calling `os.Exit` if such changes would significantly increase the scope due to the need to update multiple call sites.
📚 Learning: 2025-01-25T03:51:57.689Z
Learnt from: Listener430
Repo: cloudposse/atmos PR: 934
File: tests/fixtures/scenarios/docs-generate/README.md.gotmpl:99-118
Timestamp: 2025-01-25T03:51:57.689Z
Learning: For the cloudposse/atmos repository, changes to template contents should be handled in dedicated PRs and are typically considered out of scope for PRs focused on other objectives.

Applied to files:

  • docs/prd/secrets-masking/future-considerations.md
📚 Learning: 2025-09-08T01:25:44.958Z
Learnt from: osterman
Repo: cloudposse/atmos PR: 1466
File: website/docs/cli/commands/toolchain/usage.mdx:117-121
Timestamp: 2025-09-08T01:25:44.958Z
Learning: XDG Base Directory Specification compliance implementation for atmos toolchain is complete: created toolchain/xdg_cache.go with GetXDGCacheDir() and GetXDGTempCacheDir() functions, updated toolchain/installer.go and cmd/toolchain_clean.go to use these XDG helpers, and changed all cache paths from hardcoded ~/.cache/tools-cache to XDG-compliant ${XDG_CACHE_HOME}/atmos-toolchain (or ~/.cache/atmos-toolchain fallback).

Applied to files:

  • docs/prd/secrets-masking/README.md
📚 Learning: 2025-09-08T01:25:44.958Z
Learnt from: osterman
Repo: cloudposse/atmos PR: 1466
File: website/docs/cli/commands/toolchain/usage.mdx:117-121
Timestamp: 2025-09-08T01:25:44.958Z
Learning: Final XDG Base Directory Specification implementation for atmos toolchain is complete and verified: toolchain/xdg_cache.go provides GetXDGCacheDir() and GetXDGTempCacheDir() functions, all hardcoded ~/.cache/tools-cache paths have been replaced with XDG-compliant paths using ${XDG_CACHE_HOME}/atmos-toolchain (or ~/.cache/atmos-toolchain fallback), and tests have been updated to expect the new path structure.

Applied to files:

  • docs/prd/secrets-masking/README.md
🪛 LanguageTool
docs/prd/secrets-masking/future-considerations.md

[uncategorized] ~44-~44: The official name of this software platform is spelled with a capital “H”.
Context: ... formats - Category-based control (aws, github, generic, etc.) Challenges: - Exte...

(GITHUB)


[typographical] ~200-~200: Consider using a typographic opening quote here.
Context: ... # 7 ← TOO DEEP! ``` User feedback: "That's just insane at that point." ### ...

(EN_QUOTES)


[typographical] ~200-~200: Consider using a typographic close quote here.
Context: ...back: "That's just insane at that point." ### Design Option A: Simplified Two-Le...

(EN_QUOTES)


[grammar] ~361-~361: Please add a punctuation mark at the end of paragraph.
Context: ...ne list to rule them all - Super simple config Challenges: - String parsing requi...

(PUNCTUATION_PARAGRAPH_END)


[grammar] ~392-~392: Please add a punctuation mark at the end of paragraph.
Context: ... flag - ✅ Format-aware masking - ✅ Test coverage ### Phase 2: Load Custom Patterns from...

(PUNCTUATION_PARAGRAPH_END)


[grammar] ~401-~401: Please add a punctuation mark at the end of paragraph.
Context: ...()` - ✅ Validation and thread safety in masker What's Missing: - ❌ Load patterns/...

(PUNCTUATION_PARAGRAPH_END)


[grammar] ~481-~481: Ensure spelling is correct
Context: ...L + compile regex) - Per-operation: ~50-100μs (more patterns to check) - Still neglig...

(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)


[typographical] ~492-~492: Insert a space between the numerical value and the unit symbol.
Context: ...tputs ### Memory Impact Current: ~100KB (8 compiled patterns) **With Gitleaks:...

(UNIT_SPACE)


[typographical] ~494-~494: Insert a space between the numerical value and the unit symbol.
Context: ...ompiled patterns) With Gitleaks: ~2-5MB (120+ patterns + metadata) **Mitigatio...

(UNIT_SPACE)


[grammar] ~499-~499: Please add a punctuation mark at the end of paragraph.
Context: ...oroutines - Use sync.Pool for temporary buffers ### Maintenance Burden **Current (8 p...

(PUNCTUATION_PARAGRAPH_END)


[typographical] ~550-~550: Consider using a typographic opening quote here.
Context: ...s:** Medium-High (generic patterns like "password=...") Mitigation: - Disabl...

(EN_QUOTES)


[style] ~550-~550: Consider using the typographical ellipsis character here instead.
Context: ...m-High (generic patterns like "password=...") Mitigation: - Disable generic ca...

(ELLIPSIS)


[typographical] ~632-~632: In American English, use a period after an abbreviation.
Context: ... Performance impact - 120+ patterns vs 8 (3-5x slower) 5. **Diminishing return...

(MISSING_PERIOD_AFTER_ABBREVIATION)

docs/prd/secrets-masking/README.md

[uncategorized] ~32-~32: The official name of this software platform is spelled with a capital “H”.
Context: ...al Access Tokens (classic: ghp_, new: github_pat_) - GitHub OAuth tokens (gho_, `...

(GITHUB)


[typographical] ~148-~148: In American English, use a period after an abbreviation.
Context: ... debug - ❌ Limited coverage (8 patterns vs 120+ in Gitleaks) - ❌ Manual pattern ma...

(MISSING_PERIOD_AFTER_ABBREVIATION)

🪛 markdownlint-cli2 (0.18.1)
docs/prd/secrets-masking/implementation.md

11-11: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


41-41: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


333-333: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


443-443: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Build (windows)
  • GitHub Check: Build (linux)
  • GitHub Check: website-deploy-preview
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Review Dependency Licenses
  • GitHub Check: autofix
  • GitHub Check: Summary
🔇 Additional comments (10)
docs/prd/secrets-masking/README.md (2)

72-85: Example package usage is clear and well-motivated.

The code samples show proper integration points for both command developers (using ui package) and third-party libraries (using io.Data/io.UI). This follows the architecture described in the PR objectives.


111-124: Custom secrets API documentation is helpful.

Showing RegisterSecret, RegisterPattern, and RegisterValue APIs demonstrates the flexibility for users to extend masking beyond hardcoded patterns. This aligns well with Phase 2 plans in future-considerations.md.

docs/prd/secrets-masking/future-considerations.md (3)

1-6: Clear upfront positioning of non-implementation status.

The warning banner (line 6) effectively prevents misunderstanding about what's actually shipped. This is good practice for forward-looking design docs.


408-419: Phase 2 implementation approach is concrete and pragmatic.

Loading config patterns in cmd/root.go after io.Initialize() matches the deployment model described in implementation.md. The code snippet correctly shows error handling with warnings rather than failures.


394-419: Verify Phase 2 scope against current PR deliverables.

Line 404 states "Load patterns/literals from atmos.yaml during initialization" is not implemented, but PR objectives mention "Config-file settings (replacement, patterns, literals) with precedence: CLI flag > env var > config > default." Please confirm whether Phase 2 config loading is included in this PR or deferred to follow-up work. If included, update this section to reflect completed status.

docs/prd/secrets-masking/implementation.md (5)

59-68: Initialization pattern shown is correct but incomplete.

The example shows io.Initialize() in cobra.OnInitialize, which is sound. However, the comment "Falls back to unmasked os.Stdout/os.Stderr" should note that this fallback is set as safe defaults per the error handling section (lines 255-284). Consider cross-referencing that section for clarity.


90-111: Hardcoded pattern list aligns with README.md.

The 8 patterns shown here match the "8 Hardcoded Patterns" section in README.md (lines 31-38). Consistency is good. Note: The comment on line 106 uses Bearer\s+... which is shown in README as item 7—verify this regex is actually implemented in code.


255-284: Safe defaults and sync.Once pattern is correct.

Using sync.Once to ensure single initialization with safe fallback to os.Stdout/os.Stderr is a proven defensive pattern. This ensures the global writers are always usable, even if Initialize() errors. Well done.


331-342: Benchmark results demonstrate acceptable performance.

The quantified performance impact (<16μs with secrets) is negligible for terminal output operations. This justifies the masking overhead as transparent to users. Benchmarks appear to use standard Go test output format.


427-437: Cobra PersistentFlags propagation is correctly explained.

The note that all subcommands inherit the --mask flag through Cobra's flag inheritance is accurate and important for users understanding global flag availability.

The previous version documented Gitleaks integration that doesn't exist.
This corrects the documentation to reflect what we actually built:

- 8 built-in patterns (not 120+ from Gitleaks)
- Auto-masking of environment variables
- CLI --mask flag
- No pattern library integration (yet)
- No custom pattern configuration loading (yet - schema exists but not wired up)

Removed broken links to PRD documents that aren't in the website docs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
website/docs/cli/configuration/mask.mdx (1)

23-23: Resolve pattern count mismatch (previously flagged).

Lines 23 and 78 claim "8 built-in patterns," but lines 80–99 list only 6 concrete patterns. The past review flagged this discrepancy; ensure the count aligns with the actual list. Either update the count to 6 or add the missing 7th and 8th patterns.

Also applies to: 78-99

🧹 Nitpick comments (1)
website/docs/cli/configuration/mask.mdx (1)

156-156: Add spaces between numeric values and unit symbols.

Lines 156 and 273 are missing spaces between values and units per typographical convention.

Apply this diff:

-  - **Per-operation:** <50ms (no secrets), <16μs (with secrets)
+  - **Per-operation:** <50ms (no secrets), <16 μs (with secrets)

-1. Check for extremely large output (>10MB)
+1. Check for very large output (>10 MB)

Note: The diff above also replaces "extremely" with "very" to reduce intensifier overuse per style guidance.

Also applies to: 273-273

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a58e44a and d62c3c3.

📒 Files selected for processing (1)
  • website/docs/cli/configuration/mask.mdx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
website/**

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

website/**: Update website documentation in website/ when adding features
Ensure consistency between CLI help text and website documentation
Follow the website's documentation structure and style
Keep website code in website/ and follow its architecture/style; test changes locally
Keep CLI and website documentation in sync; document new features with examples and use cases

Files:

  • website/docs/cli/configuration/mask.mdx
🧠 Learnings (4)
📓 Common learnings
Learnt from: Listener430
Repo: cloudposse/atmos PR: 934
File: tests/fixtures/scenarios/docs-generate/README.md.gotmpl:99-118
Timestamp: 2025-01-25T03:51:57.689Z
Learning: For the cloudposse/atmos repository, changes to template contents should be handled in dedicated PRs and are typically considered out of scope for PRs focused on other objectives.
Learnt from: samtholiya
Repo: cloudposse/atmos PR: 1466
File: toolchain/list.go:39-42
Timestamp: 2025-09-13T18:06:07.674Z
Learning: In the cloudposse/atmos repository, for UI messages in the toolchain package, use utils.PrintfMessageToTUI instead of log.Error or fmt.Fprintln(os.Stderr, ...). Import pkg/utils with alias "u" to follow the established pattern.
Learnt from: osterman
Repo: cloudposse/atmos PR: 808
File: pkg/config/config.go:478-483
Timestamp: 2024-12-02T21:26:32.337Z
Learning: In the 'atmos' project, when reviewing Go code like `pkg/config/config.go`, avoid suggesting file size checks after downloading remote configs if such checks aren't implemented elsewhere in the codebase.
Learnt from: aknysh
Repo: cloudposse/atmos PR: 1185
File: internal/exec/yaml_func_store.go:26-26
Timestamp: 2025-04-04T02:03:23.676Z
Learning: The Atmos codebase currently uses `log.Fatal` for error handling in multiple places. The maintainers are aware this isn't an ideal pattern (should only be used in main() or init() functions) and plan to address it comprehensively in a separate PR. CodeRabbit should not flag these issues or push for immediate changes until that refactoring is complete.
Learnt from: samtholiya
Repo: cloudposse/atmos PR: 1466
File: cmd/markdown/atmos_toolchain_aliases.md:2-4
Timestamp: 2025-09-13T16:39:20.007Z
Learning: In the cloudposse/atmos repository, CLI documentation files in cmd/markdown/ follow a specific format that uses " $ atmos command" (with leading space and dollar sign prompt) in code blocks. This is the established project convention and should not be changed to comply with standard markdownlint rules MD040 and MD014.
Learnt from: osterman
Repo: cloudposse/atmos PR: 727
File: internal/exec/terraform_clean.go:233-235
Timestamp: 2024-10-31T19:25:41.298Z
Learning: When specifying color values in functions like `confirmDeleteTerraformLocal` in `internal/exec/terraform_clean.go`, avoid hardcoding color values. Instead, use predefined color constants or allow customization through configuration settings to improve accessibility and user experience across different terminals and themes.
Learnt from: osterman
Repo: cloudposse/atmos PR: 740
File: cmd/cmd_utils.go:340-359
Timestamp: 2024-10-23T21:36:40.262Z
Learning: In the Go codebase for Atmos, when reviewing functions like `checkAtmosConfig` in `cmd/cmd_utils.go`, avoid suggesting refactoring to return errors instead of calling `os.Exit` if such changes would significantly increase the scope due to the need to update multiple call sites.
Learnt from: RoseSecurity
Repo: cloudposse/atmos PR: 1448
File: cmd/ansible.go:26-28
Timestamp: 2025-09-05T14:57:37.360Z
Learning: The Atmos codebase uses a consistent pattern for commands that delegate to external tools: `PersistentFlags().Bool("", false, doubleDashHint)` where doubleDashHint provides help text about using double dashes to separate Atmos options from native command arguments. This pattern is used across terraform, packer, helmfile, atlantis, aws, and ansible commands.
📚 Learning: 2025-09-23T02:30:42.362Z
Learnt from: CR
Repo: cloudposse/atmos PR: 0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-09-23T02:30:42.362Z
Learning: Applies to website/** : Keep CLI and website documentation in sync; document new features with examples and use cases

Applied to files:

  • website/docs/cli/configuration/mask.mdx
📚 Learning: 2025-09-23T02:30:42.362Z
Learnt from: CR
Repo: cloudposse/atmos PR: 0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-09-23T02:30:42.362Z
Learning: Applies to website/** : Ensure consistency between CLI help text and website documentation

Applied to files:

  • website/docs/cli/configuration/mask.mdx
📚 Learning: 2025-09-13T16:39:20.007Z
Learnt from: samtholiya
Repo: cloudposse/atmos PR: 1466
File: cmd/markdown/atmos_toolchain_aliases.md:2-4
Timestamp: 2025-09-13T16:39:20.007Z
Learning: In the cloudposse/atmos repository, CLI documentation files in cmd/markdown/ follow a specific format that uses " $ atmos command" (with leading space and dollar sign prompt) in code blocks. This is the established project convention and should not be changed to comply with standard markdownlint rules MD040 and MD014.

Applied to files:

  • website/docs/cli/configuration/mask.mdx
🪛 Gitleaks (8.28.0)
website/docs/cli/configuration/mask.mdx

[high] 144-144: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


[high] 145-145: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🪛 LanguageTool
website/docs/cli/configuration/mask.mdx

[typographical] ~156-~156: Insert a space between the numerical value and the unit symbol.
Context: ... <16μs (with secrets) - Memory: ~100KB for pattern storage ## Use Cases ### ...

(UNIT_SPACE)


[style] ~258-~258: This word has been used in one of the immediately preceding sentences. Using a synonym could make your text more interesting to read, unless the repetition is intentional.
Context: ...rectly ### Legitimate Values Masked Problem: Non-secret values are being masked. ...

(EN_REPEATEDWORDS_PROBLEM)


[style] ~270-~270: This word has been used in one of the immediately preceding sentences. Using a synonym could make your text more interesting to read, unless the repetition is intentional.
Context: ...tive pattern ### Performance Issues Problem: Masking slows down output. **Soluti...

(EN_REPEATEDWORDS_PROBLEM)


[style] ~273-~273: As an alternative to the over-used intensifier ‘extremely’, consider replacing this phrase.
Context: ...wn output. Solutions: 1. Check for extremely large output (>10MB) 2. Disable masking if...

(EN_WEAK_ADJECTIVE)


[typographical] ~273-~273: Insert a space between the numerical value and the unit symbol.
Context: .... Check for extremely large output (>10MB) 2. Disable masking if performance is c...

(UNIT_SPACE)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Build (linux)
  • GitHub Check: Build (windows)
  • GitHub Check: Review Dependency Licenses
  • GitHub Check: website-deploy-preview
  • GitHub Check: Run pre-commit hooks
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: autofix
  • GitHub Check: Summary

@osterman
Erik Osterman (Cloud Posse) (osterman) deleted the osterman/io-handling-prd branch November 4, 2025 15:31
Erik Osterman (Cloud Posse) (osterman) added a commit that referenced this pull request Nov 4, 2025
…GlobalFlags

Add new terminal and I/O configuration flags from main branch IO release:
- ForceColor: Force color output even when not a TTY (--force-color)
- ForceTTY: Force TTY mode with sane defaults (--force-tty)
- Mask: Enable automatic masking of sensitive data (--mask, default=true)

Changes:
- Added three new fields to GlobalFlags struct with documentation
- Updated NewGlobalFlags() to include defaults (Mask=true for security)
- Added WithForceColor(), WithForceTTY(), WithMask() to StandardOptionsBuilder
- All three methods include perf tracking and proper env var bindings
- CLICOLOR_FORCE is an alias for ATMOS_FORCE_COLOR (standard env var)

This integrates the global UI formatter pattern and I/O foundation from
PR #1714 into the unified flag parsing system.

Related: PR #1714 - Implement global UI formatter pattern for simplified output
Erik Osterman (Cloud Posse) (osterman) added a commit that referenced this pull request Nov 4, 2025
Update container.Runtime interface to accept io.Writer parameters for methods
with user-facing output (Exec, Attach, Logs). This enables automatic masking
of sensitive data through the IO/UI framework.

Changes:
- pkg/container/runtime.go: Add stdout/stderr io.Writer parameters to Exec(), Attach(), Logs()
- pkg/container/docker.go: Implement io.Writer parameters, default to iolib.Data/UI
- pkg/container/podman.go: Implement io.Writer parameters, default to iolib.Data/UI
- pkg/container/common.go: Update execWithRuntime helper to accept and use io.Writers
- internal/exec/devcontainer.go: Pass nil to use default masked IO channels
- internal/exec/devcontainer_helpers.go: Use ui.Infof/Writef for user-facing output
- pkg/container/*_test.go: Update test calls to include nil io.Writer parameters

This integration allows devcontainer operations to automatically benefit from
centralized masking configured in the IO layer, without needing auth-specific
code in the devcontainer implementation.

Part of IO/UI framework integration (PR #1714).
Erik Osterman (Cloud Posse) (osterman) added a commit that referenced this pull request Nov 4, 2025
Refactored container runtime interface to remove lint violations and improve
API design by moving IO stream parameters into ExecOptions and AttachOptions
structs instead of passing them as separate parameters.

Changes:
- pkg/container/runtime.go: Add Stdin/Stdout/Stderr fields to ExecOptions and AttachOptions
- pkg/container/runtime.go: Remove separate stdout/stderr parameters from Exec() and Attach()
- pkg/container/docker.go: Update implementations to use IO streams from opts
- pkg/container/podman.go: Update implementations to use IO streams from opts
- pkg/container/common.go: Refactor execWithRuntime into smaller focused functions
- pkg/container/common.go: Add getIOStreams, attachIOStreams, runCommand helpers
- pkg/container/common.go: Copy IO streams from AttachOptions to ExecOptions in buildAttachCommand
- internal/exec/devcontainer.go: Remove extra parameters from Attach() calls
- pkg/container/*_test.go: Update test calls to match new signatures
- pkg/container/docker.go: Add nolint for Logs argument-limit
- pkg/container/podman.go: Add nolint for Logs argument-limit

Benefits:
- Removes revive lint violations for cyclomatic complexity and nil pointer dereference
- Interactive TTY sessions now use masked IO channels (iolib.Data/UI) by default
- Cleaner API with fewer parameters (except Logs which keeps current signature)
- IO configuration centralized in options structs
- Safer nil handling with explicit checks

Part of IO/UI framework integration (PR #1714).
@github-actions

github-actions Bot commented Nov 5, 2025

Copy link
Copy Markdown

These changes were released in v1.198.0-rc.1.

This branch was successfully deployed

1 active deployment
preview — 1e30bff7 Deployed Nov 4, 2025 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

minor New features that do not break anything size/xl Extra large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants