Unix-composable CLI design patterns. Use when building CLI tools, designing command trees, implementing output layers, or testing CLI behavior. Covers stream separation (stdout/stderr), format flags (--json/--plain), exit codes, TTY detection, composability, and error design. Language-agnostic principles; TypeScript implementation patterns in resources/. For API design (REST, HTTP), see api-design.
This skill covers language-agnostic CLI design principles. The rules about stream separation, exit codes, format flags, and composability apply regardless of implementation language.
This bundle adapts the CC BY-SA 4.0 Command Line Interface Guidelines.
Pinned provenance, modification notes, and license scope are recorded in
resources/source-notes.md and LICENSE.
For API contract stability and Hyrum's Law, see the api-design skill. For config, env vars, and graceful shutdown, see the twelve-factor skill.
TypeScript implementation patterns are in the resources/ directory. Load them on demand when building a CLI in TypeScript:
Resource
Load when...
output-architecture.md
Implementing Result types, entry point wiring, formatters, logger, JSON envelope schemas
stdout is for DATA only — the product the user asked for.stderr is for EVERYTHING ELSE — diagnostics, progress, spinners, warnings, errors.
This separation is what makes mycli --json | jq ... work. One spinner character on stdout breaks every downstream pipe.
"Whatever software you're building, you can be absolutely certain that people will use it in ways you didn't anticipate. Your software will become a part in a larger system — your only choice is over whether it will be a well-behaved part." — clig.dev
The Unix Stream Contract
Content
Stream
Why
Primary output (data, results, JSON)
stdout
Pipeable, buffered for throughput
Progress bars, spinners, status
stderr, and only when stderr is a TTY (process.stderr.isTTY) — a piped stderr carries warnings and errors and nothing else
Not data — must not corrupt pipes, and a pipe consumer never wants a spinner
Warnings, errors, diagnostics
stderr
Visible to user even when stdout is piped
Debug/verbose output
stderr
Diagnostic, never data
Stream behavior:
Check stdout and stderr independently; stdout being piped does not mean stderr is piped
Do not assume C stdio's line/block/unbuffered rules describe every language runtime
In Node.js, sync/async process-stream behavior varies by operating system and destination; always respect .write() backpressure for high-volume output
When stdout is piped, the user doesn't want your status messages in their data. All non-data output must go to stderr.
For a deep dive on buffering behavior and performance implications, see resources/stream-contracts.md.
Keep Handlers Pure
The practical rule: functions that do the work should return data, not write to stdout. The CLI entry point handles all I/O.
Entry point (CLI main) Your logic (handlers)
───────────────────── ─────────────────────
parse args (input) → structured result
detect format (json/plain/human) no printing to stdout
call handler no writing to stderr
format the result no calling exit
write to correct stream just returns data
set exit code
This isn't an architecture mandate — it's just clean function design with one hard edge: the entry-point file is the only file that writes to a stream or ends the process. When you extend or edit a module that already prints or exits, move that writing into the entry point as part of the same change — do not leave it there, and never add more printing alongside it because "that function already did it". The benefits are concrete:
Testable without subprocess spawning — call the handler, assert on the returned value
Format flexibility for free — same data renders as JSON, plain text, or coloured tables by swapping one function
Reusable — the same handler works from a CLI, MCP server, HTTP API, or programmatic import
For simple CLIs where the "handler" is just calling a library, this separation already exists naturally — your library returns data, your CLI formats it. No extra layers needed.
If your project uses hexagonal architecture, the mapping is direct: the CLI entry point is a driving adapter, and the handler is a use case that returns a result through a port. See the hexagonal-architecture skill — the patterns reinforce each other, but hex arch is not required to benefit from keeping handlers pure.
For TypeScript implementation patterns (Result types, entry point wiring, formatters, logger interfaces), see resources/output-architecture.md.
Selecting a TypeScript Stack
Prefer the command and prompt libraries the repository already owns when they can satisfy the contracts in this skill. For a new material dependency, inspect current versions and project constraints and use evaluate-existing-solutions; do not select from remembered popularity or stale package characteristics.
Stricli can fit typed, injected command handlers, and @clack/prompts can fit optional TTY-gated interactivity. Treat them as candidates, not defaults. Compare them with the existing stack and alternatives on handler testability, type safety, startup cost measured in the target runtime, maintenance, dependency weight, non-interactive behavior, and migration cost.
Format Flag Contract
Three-tier output hierarchy:
Default: Human-Readable
Colors, tables, formatted text
Progress bars and spinners on stderr
Output tailored for terminal width
May change between versions — this is not a contract
--plain: Grep/Awk-Friendly
One record per line, no formatting, no colors
Stable between minor versions — this is a contract
Flat table rows, no borders, no grouped sections
Enables: mycli list --plain | grep error | wc -l
"Encourage your users to use --plain or --json in scripts to keep output stable." — clig.dev
--json: Structured Data
On success, stdout contains ONLY valid JSON — no spinners, no color, no progress
On any non-zero exit, stdout stays empty and the final non-empty stderr line
is the structured JSON error envelope
That includes a domain failure (exit 1) where the run completed and the numbers
exist — an unmet threshold, gate, or budget is a failure, not a success envelope
carrying a false flag inside it. If the caller still needs the figures, put them
inside error (a details field), never on stdout
Other diagnostics may precede that final stderr line and never contaminate stdout;
consumers parse the final non-empty line rather than the entire diagnostic stream
Schema is versioned — breaking changes to JSON output are breaking changes to the CLI
--json implies non-interactive regardless of TTY
Consistent envelopes:
Success on stdout:
{ "ok": true, "data": { ... } }
The envelope is not optional and renames nothing: field names a consumer asked for
live unchanged inside data, and a list of records goes in data rather than
replacing the envelope with a bare array.
For large datasets, use NDJSON (one JSON text per record, terminated by \n):
Each line is independently parseable
Any JSON value is valid NDJSON syntax; the application's decoder owns its schema
The examples in this skill use an optional local event profile with a type
discriminator and an optional final summary record; neither is required by NDJSON
Document whether readers ignore or reject empty lines
Enables: mycli run --format ndjson | while read -r line; do ...; done
For NDJSON specification details, see resources/stream-contracts.md.
Exit Codes
Code
Meaning
When
0
Success
Operation completed as expected
1
Domain failure
Tool-specific failure (e.g. quality threshold not met)
2
Invalid usage
Bad flags, missing required args, validation error
78
Configuration error
Invalid config file, missing required config
75
Temporary, retry-safe failure
Failure occurred before dispatch, or the operation is documented and demonstrably safe to retry
130
SIGINT
User pressed Ctrl-C (128 + 2)
143
SIGTERM-style status
Optional documented status when preserving signal termination (128 + 15); a handled graceful shutdown may instead return 0
Rules:
Non-zero exit code MUST have a stderr explanation
Document exit codes in --help
Never use codes above 125 for application errors (reserved for signals: 128 + signal number)
Use exit 75 only when no mutation was dispatched or retry safety is established
through idempotency/reconciliation; a merely transient cause is not enough
If a mutating request may have reached its destination, report an ambiguous
outcome and direct the user to status/reconcile instead of inviting a blind retry
A handled SIGTERM may finish with 0 or a documented application status such as
143; Docker and Kubernetes do not require 143 for graceful shutdown
Map non-zero codes to the most important failure modes for your tool
A flag the caller simply did not pass is not invalid usage. Exit 2 is for input the
tool cannot act on; an added gate, threshold, or filter flag is opt-in — its absence
means the check is off and the command still succeeds with 0. Make a new flag
required only when the command has no meaning without it, or every plain
invocation becomes a usage error and hides the failures the codes exist to separate
Order the checks so each failure reaches the code that names it: a later validation
must not intercept a config or data error and report it as bad usage
TTY Detection
Check priority order (first match wins):
Priority
Condition
Effect
1
--format json or --json flag
Non-interactive, no color, no animation
2
--no-color flag
Disable color (output may still be interactive)
3
FORCE_COLOR env
Empty, 1, 2, 3, or true enables color; every other value (including 0) disables it. Supported values override NO_COLOR and NODE_DISABLE_COLORS
4
NO_COLOR (non-empty) or NODE_DISABLE_COLORS (defined), with FORCE_COLOR unset
Disable color
5
TERM=dumb
Disable color and animations
6
CI=true
No interactive prompts
7
stdout is not a TTY (!isatty(stdout))
Plain output, no animations on stdout
8
Default
Full interactive with colors
Resolve the output mode once, in the entry point, before anything is written. Walk the table above — format flags, --no-color, FORCE_COLOR, NO_COLOR, TERM, CI, and each stream's TTY status (isatty/isTTY) — into a single mode value and pass it to the formatters. Write that check even when today's output has no color and no animation yet: it is what keeps the decision in one place the day either is added.
Check stdout and stderr independently. When stdout is piped but stderr is a TTY, you can still show spinners on stderr while keeping stdout clean for the pipe consumer. Status lines, spinners and progress are written only when the stream carrying them is a TTY; when stderr is a pipe it carries warnings and errors and nothing else.
Gate prompts on stdin independently. Prompt only when stdin and the prompt's
output stream are TTYs; stdout TTY status controls data formatting, not whether
input is safe to request.
Optionally support MYCLI_NO_COLOR for app-specific color override.
3+ positional args: prefer named flags unless a familiar command grammar
makes the positions obvious
Exception: variadic args of the same type are fine (rm a.txt b.txt c.txt), as are universal idioms (cp source dest)
Flags are self-documenting, order-independent, and future-proof.
# Bad — which is source, which is destination?
mycli copy myapp backup
# Good — explicit
mycli copy --from myapp --to backup
Standard Flags
Always provide long forms. Short flags only for the most common operations.
Flag
Meaning
-h, --help
Show help (this should only mean help)
--version
Print version to stdout
-q, --quiet
Suppress non-essential output
-v, --verbose
More detail in human output
-d, --debug
Diagnostic output to stderr
-f, --force
Skip confirmation prompts
-n, --dry-run
Show what would happen without doing it
--json
Structured JSON output
--plain
Stable, grep-friendly plain text
--no-color
Disable color output
--no-input
Disable all prompts/interactivity
-o, --output
Output file
--fields
Select output columns
Prompts and Interactivity
All prompts MUST be bypassable via flags for scriptability
Confirmation → --yes or --force
Selection → --type=value
Text input → --name=value
Passwords → --password-file=path or stdin pipe
If stdin is not a TTY, never prompt — fail with a clear error or use defaults
Secrets: never via flag values (leak to ps output and shell history). Prefer, in order: OS keychain or a 0600 credential file (~/.config/mycli/credentials), then stdin (mycli login --with-token < token.txt), then env vars only where the platform injects them (CI secret stores) — env leaks to child processes and crash reports, so never make it the primary documented path
Scale confirmation to severity: mild → y/N prompt with --yes bypass; moderate → prompt plus suggest --dry-run first; severe/irreversible (delete a database, overwrite production) → require typing the resource name to confirm
Conventions
Support -- to stop flag parsing: mycli run -- --flag-for-child-process
Support - for stdin/stdout file arguments: curl ... | mycli process -
Accept both --flag=value and --flag value
If stdin is expected but is an interactive terminal, display help immediately (don't hang like cat)
What went wrong — context: which resource, operation, input
How to fix it — exact command or action the user should take
Reference — docs URL or mycli help <topic> (optional)
Human Mode
Error: CONFIG_MISSING — Configuration file not found
No configuration file found at ./mycli.config.ts or ~/.config/mycli/config.ts
Fix: Run `mycli init` to create a default configuration file
Docs: https://mycli.dev/docs/configuration
Put the most important information last (the eye is drawn to the end)
Use red sparingly and intentionally
Suggest corrections for typos ("Did you mean 'deploy'?")
Group similar errors under one header — don't repeat 50 similar-looking lines
Write debug logs to a file, not the terminal (unless --debug)
JSON Mode
Errors are structured too — not just success responses:
{
"ok": false,
"error": {
"code": "CONFIG_MISSING",
"message": "No configuration file found at ./mycli.config.ts",
"fix": "Run `mycli init` to create a default configuration file",
"transient": false
}
}
The transient boolean says the cause may clear. It does not by itself authorize
a retry: callers also need exit code 75 or an explicit retry-safe contract.
State Changes and Transparency
Confirm state changes — say what changed and show (or point to) the resulting state; traditionally-silent commands look broken to humans
Make current state easy to see — a status-style command for anything with complex state (the git status pattern)
Make hidden actions explicit — if you read/write files not passed as arguments or talk to remote servers, say so (stderr in human mode)
Resolve ambiguous mutations — if transport fails after dispatch, tell the
user how to inspect or reconcile state; do not label the result retry-safe
Page long output through $PAGER only when stdout is a TTY, never when
piped; do not execute the value through a shell, and document whether it is an
executable token or parsed by a reviewed shell-word parser
Robustness
Validate input early — fail before any side effects, with a clear message
Responsiveness for ongoing human work — in interactive human mode, unless
--quiet, show progress on stderr if an operation is still running after roughly
100ms; keep machine modes quiet unless their protocol explicitly defines progress,
and include time estimates when interactive progress can stall
Timeouts on all network operations — configurable; use exit 75 only before
dispatch or when retry safety/idempotency is established
Recoverable operations — re-running may resume only when safe; ambiguous
mutation outcomes need an explicit status or reconciliation path
Crash-only design — exit fast on failure, defer cleanup to the next run;
distinguish visibility-atomic replacement from crash-durable persistence, and
keep bounded-cleanup timers referenced so Ctrl-C cannot bypass the bound — see
resources/stream-contracts.md
Expect misuse — script wrapping, bad connections, concurrent instances, environments you never tested
Composability Patterns
Design for real-world pipes: filtering with jq, streaming NDJSON line-by-line, feeding stdin, chaining commands through emitted identifiers, selecting columns with --fields, and fanning out with xargs -P.
See resources/composability.md for the worked shell examples covering each of these patterns.
Key patterns:
Create commands output identifiers so subsequent commands can chain
List commands support --fields for column selection (reduces output size, critical for agent efficiency)
--quiet for CI scripts that only care about the exit code
NDJSON for streaming large datasets without buffering everything in memory
--dry-run with --json outputs planned changes as structured data
Subcommand Design
noun verb pattern is most common: mycli config set, mycli report generate
Be consistent across all subcommands — same flag names for same things
No ambiguous pairs (update vs upgrade is confusing)
No catch-all subcommands (you can never add subcommands with conflicting names)
No arbitrary abbreviations — aliases must be explicit and stable
With no args: list subcommands (multi-command CLI) or show help (single-command CLI)
Help
mycli --help — top-level help
mycli help <subcommand> — subcommand help
mycli <subcommand> --help — same as above
If run with missing required args, show concise help + 1-2 examples + "use --help for more"
Examples are the most-read section — lead with them
Include flag types, defaults, and allowed values for finite sets
Include a support/bug-report link in top-level help; pre-populate issue URLs with diagnostics where possible
Suggest the likely command on obvious typos ("Did you mean 'deploy'?") — ask, never auto-execute
Output Stability Contract
Stdout is a public API. Breaking changes to stdout format are breaking changes to the CLI.
Change
Impact
Adding new optional JSON fields
Safe (additive)
Adding new subcommands
Safe
Adding new flags with preserving defaults
Safe
Removing or renaming flags
Breaking
Removing or renaming JSON fields
Breaking
Changing exit codes
Breaking
Changing default behavior
Breaking
Changing human-readable output
Usually OK (not a contract)
When in doubt, add alongside — don't modify. Deprecate with stderr warnings before removing — and once you can detect that users have migrated, stop warning.
Naming, Distribution, Telemetry
Name: short, memorable, lowercase, easy to type; not so generic it collides with existing commands
Distribution: prefer a single binary; language-ecosystem tools (npm, pip) may reasonably assume their interpreter. Make uninstalling easy and documented
Telemetry: never collect usage/crash data without explicit consent — opt-in, stating what, why, and retention. Instrumented web docs or download counts are usually enough
Anti-Patterns
#
Anti-Pattern
Why It's Wrong
1
Mixing data and diagnostics on stdout
Breaks every pipe: mycli list | jq . fails if warnings are on stdout
Secrets never via flags; keychain/credential-file/stdin preferred, env only when platform-injected (CI)
Severe destructive actions require typed confirmation (resource name), not just y/N
Network operations have configurable timeouts; exit 75 is reserved for
pre-dispatch or demonstrably retry-safe failures
Interactive human operations still running after roughly 100ms show progress
on stderr unless --quiet; machine-mode protocols stay clean
Ctrl-C exits fast with bounded cleanup
--help includes 2-3 realistic examples
Human output is grep-parseable (flat rows, no table borders)
Quick Reference
Stream routing, exit codes, and standard flags are tabled in the body — see "The Unix Stream Contract", "Exit Codes", and "Standard Flags" above.
Format Hierarchy
Default (TTY) → colors, tables, formatted text
--plain → one record per line, stable, grep-friendly
--json → structured JSON, versioned schema
--format ndjson → streaming, one JSON object per line
Config Precedence
flags > env vars > project config > user config > defaults
1---2name: cli-design3description: Unix-composable CLI design patterns. Use when building CLI tools, designing command trees, implementing output layers, or testing CLI behavior. Covers stream separation (stdout/stderr), format flags (--json/--plain), exit codes, TTY detection, composability, and error design. Language-agnostic principles; TypeScript implementation patterns in resources/. For API design (REST, HTTP), see api-design.4metadata:5 source: https://skillmd.com/skills/citypaul/cli-design6---78# CLI Design: Unix-Composable Command-Line Interfaces910This skill covers **language-agnostic** CLI design principles. The rules about stream separation, exit codes, format flags, and composability apply regardless of implementation language.1112This bundle adapts the CC BY-SA 4.0 [Command Line Interface Guidelines](https://clig.dev/).13Pinned provenance, modification notes, and license scope are recorded in14[`resources/source-notes.md`](resources/source-notes.md) and [`LICENSE`](LICENSE).1516For API contract stability and Hyrum's Law, see the `api-design` skill. For config, env vars, and graceful shutdown, see the `twelve-factor` skill.1718**TypeScript implementation patterns** are in the `resources/` directory. Load them on demand when building a CLI in TypeScript:1920| Resource | Load when... |21|----------|-------------|22| `output-architecture.md` | Implementing Result types, entry point wiring, formatters, logger, JSON envelope schemas |23| `testing-cli.md` | Writing Vitest tests for CLI behavior (streams, exit codes, pipes, contract tests) |24| `stream-contracts.md` | Understanding Node.js buffering, NDJSON, signal handling, crash-only design |25| `composability.md` | Designing or testing pipe behavior — worked shell examples (jq filtering, NDJSON streaming, stdin, chaining, `--fields`, parallel `xargs`) |2627---2829## When to Use3031- Building any command-line tool (any language)32- Designing command tree, flags, and I/O contracts33- Implementing the output layer (format detection, stream routing)34- Testing CLI behavior (stdout/stderr separation, exit codes)35- Reviewing a CLI for Unix composability3637---3839## Core Principle4041**stdout is for DATA only — the product the user asked for.**42**stderr is for EVERYTHING ELSE — diagnostics, progress, spinners, warnings, errors.**4344This separation is what makes `mycli --json | jq ...` work. One spinner character on stdout breaks every downstream pipe.4546> "Whatever software you're building, you can be absolutely certain that people will use it in ways you didn't anticipate. Your software will become a part in a larger system — your only choice is over whether it will be a well-behaved part." — clig.dev4748---4950## The Unix Stream Contract5152| Content | Stream | Why |53|---------|--------|-----|54| Primary output (data, results, JSON) | stdout | Pipeable, buffered for throughput |55| Progress bars, spinners, status | stderr, and only when stderr is a TTY (`process.stderr.isTTY`) — a piped stderr carries warnings and errors and nothing else | Not data — must not corrupt pipes, and a pipe consumer never wants a spinner |56| Warnings, errors, diagnostics | stderr | Visible to user even when stdout is piped |57| Debug/verbose output | stderr | Diagnostic, never data |5859**Stream behavior:**6061- Check stdout and stderr independently; stdout being piped does not mean stderr is piped62- Do not assume C stdio's line/block/unbuffered rules describe every language runtime63- In Node.js, sync/async process-stream behavior varies by operating system and destination; always respect `.write()` backpressure for high-volume output6465When stdout is piped, the user doesn't want your status messages in their data. All non-data output must go to stderr.6667For a deep dive on buffering behavior and performance implications, see `resources/stream-contracts.md`.6869---7071## Keep Handlers Pure7273The practical rule: **functions that do the work should return data, not write to stdout.** The CLI entry point handles all I/O.7475```76Entry point (CLI main) Your logic (handlers)77───────────────────── ─────────────────────78parse args (input) → structured result79detect format (json/plain/human) no printing to stdout80call handler no writing to stderr81format the result no calling exit82write to correct stream just returns data83set exit code84```8586This isn't an architecture mandate — it's just clean function design with one hard edge: **the entry-point file is the only file that writes to a stream or ends the process.** When you extend or edit a module that already prints or exits, move that writing into the entry point as part of the same change — do not leave it there, and never add more printing alongside it because "that function already did it". The benefits are concrete:8788- **Testable without subprocess spawning** — call the handler, assert on the returned value89- **Format flexibility for free** — same data renders as JSON, plain text, or coloured tables by swapping one function90- **Reusable** — the same handler works from a CLI, MCP server, HTTP API, or programmatic import9192For simple CLIs where the "handler" is just calling a library, this separation already exists naturally — your library returns data, your CLI formats it. No extra layers needed.9394If your project uses hexagonal architecture, the mapping is direct: the CLI entry point is a **driving adapter**, and the handler is a **use case** that returns a result through a port. See the `hexagonal-architecture` skill — the patterns reinforce each other, but hex arch is not required to benefit from keeping handlers pure.9596For TypeScript implementation patterns (Result types, entry point wiring, formatters, logger interfaces), see `resources/output-architecture.md`.9798---99100## Selecting a TypeScript Stack101102Prefer the command and prompt libraries the repository already owns when they can satisfy the contracts in this skill. For a new material dependency, inspect current versions and project constraints and use `evaluate-existing-solutions`; do not select from remembered popularity or stale package characteristics.103104Stricli can fit typed, injected command handlers, and `@clack/prompts` can fit optional TTY-gated interactivity. Treat them as candidates, not defaults. Compare them with the existing stack and alternatives on handler testability, type safety, startup cost measured in the target runtime, maintenance, dependency weight, non-interactive behavior, and migration cost.105106---107108## Format Flag Contract109110Three-tier output hierarchy:111112### Default: Human-Readable113114- Colors, tables, formatted text115- Progress bars and spinners on **stderr**116- Output tailored for terminal width117- May change between versions — this is **not** a contract118119### `--plain`: Grep/Awk-Friendly120121- One record per line, no formatting, no colors122- Stable between minor versions — this **is** a contract123- Flat table rows, no borders, no grouped sections124- Enables: `mycli list --plain | grep error | wc -l`125126> "Encourage your users to use `--plain` or `--json` in scripts to keep output stable." — clig.dev127128### `--json`: Structured Data129130- On success, stdout contains **ONLY** valid JSON — no spinners, no color, no progress131- On **any** non-zero exit, stdout stays empty and the final non-empty stderr line132 is the structured JSON error envelope133- That includes a domain failure (exit 1) where the run completed and the numbers134 exist — an unmet threshold, gate, or budget is a failure, not a success envelope135 carrying a `false` flag inside it. If the caller still needs the figures, put them136 inside `error` (a `details` field), never on stdout137- Other diagnostics may precede that final stderr line and never contaminate stdout;138 consumers parse the final non-empty line rather than the entire diagnostic stream139- Schema is versioned — breaking changes to JSON output are breaking changes to the CLI140- `--json` implies non-interactive regardless of TTY141142**Consistent envelopes:**143144Success on stdout:145```json146{ "ok": true, "data": { ... } }147```148149The envelope is not optional and renames nothing: field names a consumer asked for150live unchanged inside `data`, and a list of records goes in `data` rather than151replacing the envelope with a bare array.152153Failure on stderr:154```json155{ "ok": false, "error": { "code": "CONFIG_MISSING", "message": "...", "fix": "..." } }156```157158### NDJSON for Streaming159160For large datasets, use NDJSON (one JSON text per record, terminated by `\n`):161162- Each line is independently parseable163- Any JSON value is valid NDJSON syntax; the application's decoder owns its schema164- The examples in this skill use an optional local event profile with a `type`165 discriminator and an optional final summary record; neither is required by NDJSON166- Document whether readers ignore or reject empty lines167- Enables: `mycli run --format ndjson | while read -r line; do ...; done`168169For NDJSON specification details, see `resources/stream-contracts.md`.170171---172173## Exit Codes174175| Code | Meaning | When |176|------|---------|------|177| 0 | Success | Operation completed as expected |178| 1 | Domain failure | Tool-specific failure (e.g. quality threshold not met) |179| 2 | Invalid usage | Bad flags, missing required args, validation error |180| 78 | Configuration error | Invalid config file, missing required config |181| 75 | Temporary, retry-safe failure | Failure occurred before dispatch, or the operation is documented and demonstrably safe to retry |182| 130 | SIGINT | User pressed Ctrl-C (128 + 2) |183| 143 | SIGTERM-style status | Optional documented status when preserving signal termination (128 + 15); a handled graceful shutdown may instead return 0 |184185**Rules:**186187- Non-zero exit code **MUST** have a stderr explanation188- Document exit codes in `--help`189- Never use codes above 125 for application errors (reserved for signals: 128 + signal number)190- Use exit 75 only when no mutation was dispatched or retry safety is established191 through idempotency/reconciliation; a merely transient cause is not enough192- If a mutating request may have reached its destination, report an ambiguous193 outcome and direct the user to `status`/reconcile instead of inviting a blind retry194- A handled SIGTERM may finish with 0 or a documented application status such as195 143; Docker and Kubernetes do not require 143 for graceful shutdown196- Map non-zero codes to the most important failure modes for your tool197- A flag the caller simply did not pass is not invalid usage. Exit 2 is for input the198 tool cannot act on; an added gate, threshold, or filter flag is opt-in — its absence199 means the check is off and the command still succeeds with 0. Make a new flag200 required only when the command has no meaning without it, or every plain201 invocation becomes a usage error and hides the failures the codes exist to separate202- Order the checks so each failure reaches the code that names it: a later validation203 must not intercept a config or data error and report it as bad usage204205---206207## TTY Detection208209Check priority order (first match wins):210211| Priority | Condition | Effect |212|----------|-----------|--------|213| 1 | `--format json` or `--json` flag | Non-interactive, no color, no animation |214| 2 | `--no-color` flag | Disable color (output may still be interactive) |215| 3 | `FORCE_COLOR` env | Empty, `1`, `2`, `3`, or `true` enables color; every other value (including `0`) disables it. Supported values override `NO_COLOR` and `NODE_DISABLE_COLORS` |216| 4 | `NO_COLOR` (non-empty) or `NODE_DISABLE_COLORS` (defined), with `FORCE_COLOR` unset | Disable color |217| 5 | `TERM=dumb` | Disable color and animations |218| 6 | `CI=true` | No interactive prompts |219| 7 | stdout is not a TTY (`!isatty(stdout)`) | Plain output, no animations on stdout |220| 8 | Default | Full interactive with colors |221222**Resolve the output mode once, in the entry point, before anything is written.** Walk the table above — format flags, `--no-color`, `FORCE_COLOR`, `NO_COLOR`, `TERM`, `CI`, and each stream's TTY status (`isatty`/`isTTY`) — into a single mode value and pass it to the formatters. Write that check even when today's output has no color and no animation yet: it is what keeps the decision in one place the day either is added.223224**Check stdout and stderr independently.** When stdout is piped but stderr is a TTY, you can still show spinners on stderr while keeping stdout clean for the pipe consumer. Status lines, spinners and progress are written only when the stream carrying them is a TTY; when stderr is a pipe it carries warnings and errors and nothing else.225226**Gate prompts on stdin independently.** Prompt only when stdin and the prompt's227output stream are TTYs; stdout TTY status controls data formatting, not whether228input is safe to request.229230Optionally support `MYCLI_NO_COLOR` for app-specific color override.231232---233234## Input Design235236### Flags Over Arguments237238- **1 positional arg**: acceptable (the "main thing")239- **2 positional args**: suspicious — consider flags instead240- **3+ positional args**: prefer named flags unless a familiar command grammar241 makes the positions obvious242- **Exception**: variadic args of the same type are fine (`rm a.txt b.txt c.txt`), as are universal idioms (`cp source dest`)243244Flags are self-documenting, order-independent, and future-proof.245246```bash247# Bad — which is source, which is destination?248mycli copy myapp backup249250# Good — explicit251mycli copy --from myapp --to backup252```253254### Standard Flags255256Always provide long forms. Short flags only for the most common operations.257258| Flag | Meaning |259|------|---------|260| `-h`, `--help` | Show help (this should only mean help) |261| `--version` | Print version to stdout |262| `-q`, `--quiet` | Suppress non-essential output |263| `-v`, `--verbose` | More detail in human output |264| `-d`, `--debug` | Diagnostic output to stderr |265| `-f`, `--force` | Skip confirmation prompts |266| `-n`, `--dry-run` | Show what would happen without doing it |267| `--json` | Structured JSON output |268| `--plain` | Stable, grep-friendly plain text |269| `--no-color` | Disable color output |270| `--no-input` | Disable all prompts/interactivity |271| `-o`, `--output` | Output file |272| `--fields` | Select output columns |273274### Prompts and Interactivity275276- **All prompts MUST be bypassable** via flags for scriptability277- Confirmation → `--yes` or `--force`278- Selection → `--type=value`279- Text input → `--name=value`280- Passwords → `--password-file=path` or stdin pipe281- If stdin is not a TTY, never prompt — fail with a clear error or use defaults282- **Secrets: never via flag values** (leak to `ps` output and shell history). Prefer, in order: OS keychain or a `0600` credential file (`~/.config/mycli/credentials`), then stdin (`mycli login --with-token < token.txt`), then env vars **only where the platform injects them** (CI secret stores) — env leaks to child processes and crash reports, so never make it the primary documented path283- **Scale confirmation to severity**: mild → `y/N` prompt with `--yes` bypass; moderate → prompt plus suggest `--dry-run` first; severe/irreversible (delete a database, overwrite production) → require typing the resource name to confirm284285### Conventions286287- Support `--` to stop flag parsing: `mycli run -- --flag-for-child-process`288- Support `-` for stdin/stdout file arguments: `curl ... | mycli process -`289- Accept both `--flag=value` and `--flag value`290- If stdin is expected but is an interactive terminal, display help immediately (don't hang like `cat`)291292---293294## Config Precedence295296Highest to lowest priority:2972981. **Flags** — per-invocation overrides2992. **Environment variables** — `MYCLI_*` prefix, per-session3003. **Project config** — `.myclirc`, `mycli.config.ts`, or in `package.json`3014. **User config** — `~/.config/mycli/` (follow XDG spec)3025. **Defaults** — sensible built-in values303304**Rules:**305306- Follow the [XDG Base Directory Specification](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html) for config file locations307- Env var naming: `MYCLI_*` prefix, uppercase letters + digits + underscores; keep values single-line; don't commandeer POSIX names308- Respect the general-purpose env vars where relevant: `NO_COLOR`, `FORCE_COLOR`, `DEBUG`, `EDITOR`, `PAGER`, `HTTP_PROXY`/`HTTPS_PROXY`/`NO_PROXY`, `TMPDIR`, `TERM`, `LINES`/`COLUMNS`309- Never accept secrets via flags; prefer keychain/credential files or stdin, env vars only when platform-injected (CI) — see "Prompts and Interactivity"310- Read `.env` where appropriate, but don't use it as a substitute for proper config311- If you modify configuration that belongs to another program, ask consent first312313---314315## Error Design316317Every error needs:3183191. **Machine-readable code** — `UPPER_SNAKE_CASE` (e.g. `CONFIG_MISSING`, `AUTH_EXPIRED`)3202. **What went wrong** — context: which resource, operation, input3213. **How to fix it** — exact command or action the user should take3224. **Reference** — docs URL or `mycli help <topic>` (optional)323324### Human Mode325326```327Error: CONFIG_MISSING — Configuration file not found328No configuration file found at ./mycli.config.ts or ~/.config/mycli/config.ts329330Fix: Run `mycli init` to create a default configuration file331Docs: https://mycli.dev/docs/configuration332```333334- Put the most important information **last** (the eye is drawn to the end)335- Use red sparingly and intentionally336- Suggest corrections for typos ("Did you mean 'deploy'?")337- Group similar errors under one header — don't repeat 50 similar-looking lines338- Write debug logs to a file, not the terminal (unless `--debug`)339340### JSON Mode341342Errors are structured too — not just success responses:343344```json345{346 "ok": false,347 "error": {348 "code": "CONFIG_MISSING",349 "message": "No configuration file found at ./mycli.config.ts",350 "fix": "Run `mycli init` to create a default configuration file",351 "transient": false352 }353}354```355356The `transient` boolean says the cause may clear. It does not by itself authorize357a retry: callers also need exit code 75 or an explicit retry-safe contract.358359---360361## State Changes and Transparency362363- **Confirm state changes** — say what changed and show (or point to) the resulting state; traditionally-silent commands look broken to humans364- **Make current state easy to see** — a `status`-style command for anything with complex state (the `git status` pattern)365- **Make hidden actions explicit** — if you read/write files not passed as arguments or talk to remote servers, say so (stderr in human mode)366- **Resolve ambiguous mutations** — if transport fails after dispatch, tell the367 user how to inspect or reconcile state; do not label the result retry-safe368- **Page long output** through `$PAGER` only when stdout is a TTY, never when369 piped; do not execute the value through a shell, and document whether it is an370 executable token or parsed by a reviewed shell-word parser371372---373374## Robustness375376- **Validate input early** — fail before any side effects, with a clear message377- **Responsiveness for ongoing human work** — in interactive human mode, unless378 `--quiet`, show progress on stderr if an operation is still running after roughly379 100ms; keep machine modes quiet unless their protocol explicitly defines progress,380 and include time estimates when interactive progress can stall381- **Timeouts on all network operations** — configurable; use exit 75 only before382 dispatch or when retry safety/idempotency is established383- **Recoverable operations** — re-running may resume only when safe; ambiguous384 mutation outcomes need an explicit status or reconciliation path385- **Crash-only design** — exit fast on failure, defer cleanup to the next run;386 distinguish visibility-atomic replacement from crash-durable persistence, and387 keep bounded-cleanup timers referenced so Ctrl-C cannot bypass the bound — see388 `resources/stream-contracts.md`389- **Expect misuse** — script wrapping, bad connections, concurrent instances, environments you never tested390391---392393## Composability Patterns394395Design for real-world pipes: filtering with `jq`, streaming NDJSON line-by-line, feeding stdin, chaining commands through emitted identifiers, selecting columns with `--fields`, and fanning out with `xargs -P`.396397See `resources/composability.md` for the worked shell examples covering each of these patterns.398399**Key patterns:**400401- Create commands output identifiers so subsequent commands can chain402- List commands support `--fields` for column selection (reduces output size, critical for agent efficiency)403- `--quiet` for CI scripts that only care about the exit code404- NDJSON for streaming large datasets without buffering everything in memory405- `--dry-run` with `--json` outputs planned changes as structured data406407---408409## Subcommand Design410411- **noun verb** pattern is most common: `mycli config set`, `mycli report generate`412- Be consistent across all subcommands — same flag names for same things413- No ambiguous pairs (`update` vs `upgrade` is confusing)414- No catch-all subcommands (you can never add subcommands with conflicting names)415- No arbitrary abbreviations — aliases must be explicit and stable416- With no args: list subcommands (multi-command CLI) or show help (single-command CLI)417418### Help419420- `mycli --help` — top-level help421- `mycli help <subcommand>` — subcommand help422- `mycli <subcommand> --help` — same as above423- If run with missing required args, show concise help + 1-2 examples + "use --help for more"424- **Examples are the most-read section** — lead with them425- Include flag types, defaults, and allowed values for finite sets426- Include a support/bug-report link in top-level help; pre-populate issue URLs with diagnostics where possible427- Suggest the likely command on obvious typos ("Did you mean 'deploy'?") — ask, never auto-execute428429---430431## Output Stability Contract432433**Stdout is a public API.** Breaking changes to stdout format are breaking changes to the CLI.434435| Change | Impact |436|--------|--------|437| Adding new optional JSON fields | Safe (additive) |438| Adding new subcommands | Safe |439| Adding new flags with preserving defaults | Safe |440| Removing or renaming flags | **Breaking** |441| Removing or renaming JSON fields | **Breaking** |442| Changing exit codes | **Breaking** |443| Changing default behavior | **Breaking** |444| Changing human-readable output | Usually OK (not a contract) |445446When in doubt, add alongside — don't modify. Deprecate with stderr warnings before removing — and once you can detect that users have migrated, stop warning.447448---449450## Naming, Distribution, Telemetry451452- **Name**: short, memorable, lowercase, easy to type; not so generic it collides with existing commands453- **Distribution**: prefer a single binary; language-ecosystem tools (npm, pip) may reasonably assume their interpreter. Make uninstalling easy and documented454- **Telemetry**: never collect usage/crash data without explicit consent — opt-in, stating what, why, and retention. Instrumented web docs or download counts are usually enough455456---457458## Anti-Patterns459460| # | Anti-Pattern | Why It's Wrong |461|---|-------------|----------------|462| 1 | Mixing data and diagnostics on stdout | Breaks every pipe: `mycli list \| jq .` fails if warnings are on stdout |463| 2 | Colors/ANSI in piped output | ANSI sequences corrupt downstream parsing. Check `isatty(stdout)` + `NO_COLOR` |464| 3 | Interactive prompts with no flag bypass | Agents can't type 'y'. Every prompt needs `--yes`/`--force`. Non-TTY without bypass = hang |465| 4 | Printing nothing on success | Silence is ambiguous — show brief confirmation. Offer `-q` for scripts that want silence |466| 5 | Designing for humans OR machines, not both | Detect context (TTY vs pipe), adapt automatically |467| 6 | Output that doesn't guide the next action | Every output is a signpost: success = next command, failure = fix command |468| 7 | Breaking existing CLI contracts | Flag names, exit codes, output shape are contracts. Add alongside, never modify |469| 8 | `console.log` anywhere except the CLI adapter | Handlers must return data; only the presentation layer writes to streams |470| 9 | Handlers that exit the process directly | Let the entry point decide. Handlers return errors as data |471| 10 | Non-zero exit without stderr explanation | Scripts need both the code and the reason |472| 11 | Verbose default output | A single test run can generate 419KB. Support `--fields`, `--quiet`, `--json` |473474---475476## Verification Checklist477478After designing or reviewing a CLI:479480- [ ] stdout has ONLY data; stderr has everything else481- [ ] Every command supports `--json` with success data on stdout and structured failures on stderr482- [ ] Exit codes are semantic and documented in `--help`483- [ ] Every prompt has a `--yes`/`--force`/`--flag` bypass484- [ ] Errors include: code, message, fix suggestion485- [ ] `--dry-run` available for mutating commands486- [ ] Progress/spinners go to stderr, never stdout487- [ ] `NO_COLOR`, `TERM=dumb`, and `--no-color` respected488- [ ] Piped output contains zero ANSI escape codes489- [ ] Success output includes next-action guidance490- [ ] Existing flags, exit codes, output fields never removed or renamed491- [ ] JSON schema is versioned (additions safe, removals breaking)492- [ ] Config follows flags > env > project > user > defaults493- [ ] Secrets never via flags; keychain/credential-file/stdin preferred, env only when platform-injected (CI)494- [ ] Severe destructive actions require typed confirmation (resource name), not just y/N495- [ ] Network operations have configurable timeouts; exit 75 is reserved for496 pre-dispatch or demonstrably retry-safe failures497- [ ] Interactive human operations still running after roughly 100ms show progress498 on stderr unless `--quiet`; machine-mode protocols stay clean499- [ ] Ctrl-C exits fast with bounded cleanup500- [ ] `--help` includes 2-3 realistic examples501- [ ] Human output is grep-parseable (flat rows, no table borders)502503---504505## Quick Reference506507Stream routing, exit codes, and standard flags are tabled in the body — see "The Unix Stream Contract", "Exit Codes", and "Standard Flags" above.508509### Format Hierarchy510511```512Default (TTY) → colors, tables, formatted text513--plain → one record per line, stable, grep-friendly514--json → structured JSON, versioned schema515--format ndjson → streaming, one JSON object per line516```517518### Config Precedence519520```521flags > env vars > project config > user config > defaults522```
Run npx get-skill add citypaul/cli-design in your terminal (requires Node.js), paste this page's agent-chat prompt into Claude, Cursor, or any MCP-connected agent, or download the SKILL.md file and copy it into your agent's skills directory.
Unix-composable CLI design patterns. Use when building CLI tools, designing command trees, implementing output layers, or testing CLI behavior. Covers stream separation (stdout/stderr), format flags (--json/--plain), exit codes, TTY detection, composability, and error design. Language-agnostic principles; TypeScript implementation patterns in resources/. For API design (REST, HTTP), see api-design. It is listed under Integrations & APIs on SkillMD.
This skill has not completed SkillMD's automated safety review yet. Independent scanners report: SkillSpector: PASS, Skill Scanner: PASS. Capability flags: makes network calls, reads secrets. SkillMD never runs a skill's scripts for you; review the SKILL.md before installing.
This skill is tagged as working with Claude Code, Claude.ai, OpenAI Codex. SKILL.md is an open format, so most agents that read a skills directory can load it too.
Yes. Installing skills from SkillMD is free, and the skill stays under its author's original license.
citypaul (@citypaul) published this skill. Their other Agent Skills are listed on their SkillMD profile.