sugarcraft / sugar-colorprofile
Terminal color profile detection and color degradation (TrueColor → ANSI256 → ANSI → ASCII), inspired by charmbracelet/colorprofile.
Requires
- php: ^8.3
- ext-mbstring: *
- react/child-process: ^0.6
- react/event-loop: ^1.2
- react/promise: ^3.3
- sugarcraft/sugar-core: dev-master
Requires (Dev)
- phpstan/phpstan: ^2.1
- phpstan/phpstan-phpunit: ^2.0
- phpunit/phpunit: ^10.5
- sugarcraft/sugar-testing: dev-master
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-20 01:04:04 UTC
README
SugarColorprofile
Formerly published as
sugarcraft/candy-palette(renamed 2026-10). Namespace changed:SugarCraft\Palette\→SugarCraft\ColorProfile\.
sugar-colorprofile — terminal color profile detection and color degradation for PHP 8.3+.
Features
- Detect terminal color profile from environment variables and TTY info
- ColorProfile enum: the color-depth vocabulary shared by every surface of
this library. It carries eight levels:
TrueColor(24-bit),Ansi256(256-color),Ansi240(fixed slots 16-255),Ansi(16-color),Ansi8(basic 8),Fgbg(two-color fg/bg),Ascii(colorless, decoration kept) andNoTTY. The former renderer-facingProfileenum is now a deprecatedclass_aliasfacade over it; every oldProfile::Xspelling still resolves - Color conversion: downsample RGBA colors to any target profile
- ProfileWriter: wrap a stream and automatically match its output to the terminal —
degrade()on the color rungs, fullstripAnsi()onNoTTY - ANSI stripping:
NoTTYoutput runs throughPalette::stripAnsi(), which removes SGR/CSI/OSC/DCS sequences plus SS3, APC/PM/SOS strings, the enumerated Fe escape pairs and charset selectors — decoration (\x1b[1m,\x1b[4m) is stripped too. Since CP-05 (Shape B) the suppressions land on the colorlessAsciirung instead — color codes dropped, decoration kept;NoTTYis reserved for hardware absence (a non-TTY stream) - Environment-aware: reads
CLICOLOR_FORCE,FORCE_COLOR,NO_COLOR,CLICOLOR,TERM,COLORTERM,TERM_PROGRAM,WT_SESSION,GOOGLE_CLOUD_SHELL,TMUX,STY,REDUCE_MOTION,PREFERS_REDUCED_MOTION - Probe class: static convenience layer over the shared detection chain and the infocmp phase-2 upgrade
- Perceptual color distance: CIELAB conversion + ΔE₇₆ / ΔE₉₄ / ΔE*₀₀ (CIEDE2000) metrics with an opt-in nearest-palette matcher (
NearestColor), palette Lab values memoized for hot loops, a PCA-bucketed exact lookup index for repeated queries (PaletteIndex), and error-compensated quantization for dither chains (NearestColor::withError())
Install
composer require sugarcraft/sugar-colorprofile
Requires PHP 8.3+ and the ext-mbstring extension — Env::sanitize's
UTF-8 sweep and the TERM cap run through mb_convert_encoding /
mb_strcut unguarded, and until this was declared the dependency was
satisfied only transitively via sugar-core while the text here claimed the
opposite. The probes' optional posix_* calls remain feature-detected, and
an absent/unreadable infocmp child degrades the phase-2 answer instead of
failing. The package's direct dependencies are sugarcraft/sugar-core
(foundational utilities) and the ReactPHP trio react/event-loop,
react/child-process, react/promise — the last three back the
AsyncProbe infocmp child.
Supported targets: POSIX terminals. The phase-2 infocmp consult is
POSIX-only by design — it queries the compiled terminfo database. The env
ladder's Windows/macOS legs (WT_SESSION, the iTerm/Apple_Terminal hints)
are untested by this repository's CI, whose ladder legs run on Linux only;
on Windows the library answers from the env ladder alone. Case matters more
there than anywhere else: env keys are matched case-exactly, while the
Windows environment block is case-insensitive at the OS layer — an unusual
spelling such as No_Color can exist in the shell's view and still miss
detection, because the library deliberately does not alias-match env keys
(Env::resolve).
Quickstart
use SugarCraft\ColorProfile\Color; use SugarCraft\ColorProfile\Palette; use SugarCraft\ColorProfile\ProfileWriter; // Detect the terminal's color profile (hero idiom — pass a stream to gate on // its TTY-ness; a null stream means env-only detection — no TTY gate) $profile = Palette::detect(STDOUT); echo "Your terminal supports: {$profile->label()}\n"; // Downsample a TrueColor color to the detected profile. The reusable-palette // instance form memoizes the detection for repeated conversions: $palette = new Palette(STDOUT); $color = new Color(0x6b, 0x50, 0xff); // #6b50ff $converted = $palette->convert($color); echo "Converted: {$converted->toHex()}\n"; // Wrap a stream for automatic color degradation on write $writer = ProfileWriter::wrap(STDOUT); $writer->write("\x1b[38;2;107;80;255mFancy text\x1b[0m\n");
Expected output. Run with STDOUT piped (CI,
php examples/detect.php | cat — that demo ends with exactly the statements
above), the two
echo lines print exactly Your terminal supports: No TTY and
Converted: #000000 — the step-0 stream gate forces NoTTY, and NoTTY
degrades the TrueColor test color to black. On a real terminal both lines depend
on the detected profile: the label names whatever rung won, and #6b50ff
collapses toward the nearest color the profile can actually render.
Terms used here.
- SGR — the
ESC[ …mescape sequence that carries colors and decoration in terminal output bytes. - terminfo /
infocmp— the on-disk per-TERMcapability database, and the CLI that prints one entry (consulted by the optional phase-2 probe). COLORTERM,NO_COLOR,FORCE_COLOR(withCLICOLOR,CLICOLOR_FORCE) — the env vars users set to override what a terminal advertises; the ladder below resolves them in a fixed order.- CIELAB / ΔE — a perceptually-uniform color space and its distance metric; they define "nearest" for the color reduction above.
- TTY vs pipe —
stream_isatty()tells an interactive terminal from redirected output; the same environment answers differently on each. - Rung words for assistive tech — the
Asciirung means no color codes (decoration kept); the name is a depth label, not a character-set claim.Fgbgmeans two-color foreground/background (the terminal's own colors, brightness-selected);Ansi240means 240-color fixed palette (slots 16-255, the themeable system 16 excluded). These glosses mirrorColorProfile::description().
Profiles
| ColorProfile | Colors | Description | Detection emits? |
|---|---|---|---|
| TrueColor | 16.7M | Full 24-bit RGB (SGR 38;2, de-facto xterm) | yes |
| Ansi256 | 256 | 216 cube + 24 gray + 16 standard | yes |
| Ansi240 | 240 | Fixed palette only — slots 16-255 (chafa INDEXED_240) | no — request-only |
| Ansi | 16 | Standard terminal colors | yes |
| Ansi8 | 8 | Basic ANSI, no bright variants | no — request-only |
| Fgbg | 2 | Two-color fg/bg by brightness (chafa FGBG) | no — request-only |
| Ascii | 0 | Colorless — no color codes; decoration kept (CP-05) | yes — suppression + falsy-FORCE_COLOR floor (steps 2-5) |
| NoTTY | 0 | No color — stripAnsi() drops every escape including decoration |
yes |
Profile is the deprecated alias of ColorProfile; Profile::ANSI256
and Profile::ANSI keep resolving through deprecated constant bridges.
The detection ladder
The color-depth answer comes from one canonical 14-step chain (DetectionChain) —
canonical across every surface of this library; sugar-core carries a separate
fork with its own ladder, see Fleet integration below.
Probe, Palette and Probe\TerminalProbe all consult it, so the same
environment never answers differently at the env-ladder rung. The surfaces
can still arrive at different final answers, because each one may add phases
after the ladder: Probe layers an opt-in terminfo phase (Phase 2) on top,
and TerminalProbe layers the terminfo and TERM_PROGRAM upgrade phases
(Phases 2-3). The chain's answer is the floor those phases can raise, never
the ceiling. Measured: {TERM_PROGRAM: WezTerm, TERM: xterm}
answers Ansi on Palette but TrueColor on TerminalProbe (Phase-3 upgrade) —
quoted on an interactive stream: on a piped Palette the step-0 stream gate
floors the answer before any rung gets to speak.
README, the DetectionChain docblock and the tests follow this one numbering
(the chain levels truecolor/ansi256/ansi/ascii/none map to the enum
cases TrueColor/Ansi256/Ansi/Ascii/NoTTY respectively; the numbered
list below and the docblock are twins pinned by LadderDriftTest — see
Maintenance):
CLICOLOR_FORCE=1→ TrueColor (overrides every env leg — and since CP-07 outranks the step-0 stream gate too)FORCE_COLOR(non-empty) → level: numeric 3+ → TrueColor (as dotrue/yes/onin any case),2→ Ansi256,1→ Ansi; every other spelling (0/false/no/off/…) →Asciifloor (colorless — color codes dropped, decoration kept)NO_COLOR(set and non-empty;""= unset — the NO_COLOR standard treats any present-and-not-empty value as "off" — content never matters) → the colorlessAsciirung — color codes dropped, decoration (\x1b[1m/\x1b[4m) kept; the explicit way to pin this same floor is in Color Degradation belowCLICOLOR=0→Ascii(the colorless rung)TERM=dumb(case-insensitive) →Ascii(the colorless rung)TMUX/STYset + base TERM beginsscreen→ Ansi256 — the multiplexer cap runs beforeCOLORTERM(CP-09): GNU screen never forwards the 24-bit set, andCOLORTERMsurvives multiplexer inheritance, so evaluating the cap after it would let an inherited variable undo the capCOLORTERM=truecolor|24bit→ TrueColor;COLORTERM=yes→ Ansi256 (CP-09 —yesis the legacy "this is a color terminal" marker, a 256-color promise, not a 24-bit one; legacy VTE builds advertised it falsely. Theyesrung stays inside Phase 2's promotion reach, so a genuine RGB terminfo still raises it back)TERM_PROGRAM=iTerm.app(exact spelling, case-sensitive) → TrueColor (inline image + 24-bit history)WT_SESSION(set, non-empty) → TrueColor (Windows Terminal)GOOGLE_CLOUD_SHELLset to exactlytrue→ TrueColor (CP-09: any other value —falseand1included — carries no 24-bit promise; one-way tightening of the old set-and-non-empty grant)TMUXorSTYset + base TERM beginstmux→ Ansi256 (behindCOLORTERM— modern tmux may honestly forward truecolor; the screen/tmux split is the documented answer, pinned by twin tests)- TERM contains
-256color, or equalsxterm-kitty/xterm-ghostty(case-insensitive) → Ansi256 (termenv promotes kitty/ghostty to TrueColor by NAME; this fork keeps the 256 promise the TERM value carries and defers name-based promotion to phase-2 terminfo — WezTerm has no TERM-only twin) - TERM begins
xterm/screen/tmux/vt/linux(case-insensitive) → Ansi (the KNOWN-family set — CP-10) - Default — unknown or empty TERM → Ascii (the colorless floor, CP-10: an unfamiliar family no longer over-detects 16-color support; decoration is kept, color codes are dropped)
Steps 1-2 outrank step 3 deliberately: FORCE_COLOR/CLICOLOR_FORCE are an
active "give me color anyway" override (the chalk/support-colors convention),
while NO_COLOR is a passive preference. The asymmetry is pinned by tests — and
carries an accessibility cost, spelled out under the env-var precedence table
below.
Interpolated env values that ride in source strings are sanitized via
Env::sanitize() — TERM and friends are attacker-influenced over SSH and a
source string gets printed by downstream diagnostics. The guarantee it gives
is exact: the output is always valid UTF-8 of at most 128 bytes —
C0/C1/DEL are stripped as code points (so multibyte characters whose UTF-8
form merely contains a 0x80-0x9F byte, like €, survive intact), hostile
malformed input is scrubbed to U+FFFD-substituted well-formed text instead of
emitting orphan lead bytes that would break json_encode() of a probe report,
and the length cap lands on a character boundary, never mid-sequence.
Step 0 — the output-stream TTY gate
A Palette constructed with a non-null stream that is not a TTY answers
NoTTY and outranks the ladder — except when the answer came from one of
the two explicit force legs, CLICOLOR_FORCE or FORCE_COLOR (sources
env:CLICOLOR_FORCE / env:FORCE_COLOR; CP-07, upstream's
Detect() = isatty() || forced() parity: a PINNED color declaration outranks
hardware absence). The bypass enumerates by SOURCE, not depth: a falsy
FORCE_COLOR spelling is still the force machinery answering its colorless
Ascii floor, so it crosses the gate colorless — no pipe ever sees color vomit
through the seam. Capability answers (COLORTERM, TERM_PROGRAM,
GOOGLE_CLOUD_SHELL, the TERM rungs) and suppressions (NO_COLOR,
CLICOLOR=0, TERM=dumb) keep the gate: piping into a file stays
decoration-safe by default. NO_COLOR=1 with CLICOLOR_FORCE=1 still lands
on the force rung — step 1 outranks step 3 by the deliberate ordering above,
and the gate no longer undoes it either.
Measured: piped STDOUT with FORCE_COLOR=3 now gives Palette::detect(STDOUT)
→ TrueColor, at one with Probe::colorProfile() (before CP-07 the same
environment answered NoTTY — a fork-only divergence from the env-anchored
surfaces). ProfileWriter::wrap($stream, …)
inherits the gate because it delegates to Palette::detect($stream, …), and a
NoTTY answer makes ProfileWriter::write() strip the ANSI. Every claim
below that a force variable outranks all the color-suppressing ones therefore
holds literally: the force legs outrank the gate too. Surfaces that gate: Palette::detect($stream, …) and ProfileWriter
with a non-TTY stream. Surfaces that never gate: Probe, AsyncProbe and
Probe\TerminalProbe — they report what the environment can do, not where
the bytes are about to land.
Phase 2 (infocmp) — probe surfaces only: Probe/AsyncProbe consult
infocmp -1 only when the ladder answers Ansi or Ansi256; Tc/RGB
capability names (name-position match via Probe\TerminfoParser, never a
whole-output regex) upgrade the answer to TrueColor. The Sixel leg accepts
exactly the folded names sixel/sixl/sixelscreenmode; the legacy Ss1/Ss2
user caps are deliberately NOT markers — they initialize X3.64 status lines, not
sixel graphics. Before any surface execs
the binary, TERM must pass one shared name-shape predicate
(Probe\InfocmpBinary::isSafeTermName()): alnum first byte, then only the
characters real terminfo names use — so a value beginning with - never
reaches infocmp: measured with TERM=-D, infocmp exits 0 and prints its
terminfo search path to the probe's stdout, because quoting it still leaves it
an option to the program. The env-anchored chain answer stands. TerminalProbe runs its
terminfo phase more broadly: unless the env phase delivered a suppression
decision (the NoColor capability — NO_COLOR, CLICOLOR=0, TERM=dumb) or
the falsy-FORCE_COLOR Ascii floor, it queries the database even when the
env rung already answered TrueColor — its report covers capabilities beyond
color depth. That suppression check is a decision, not one more input to
weigh: an operator who said "no color" means no color, queried upgrades
included — which is why the same check gates the escape-query phase. A bare Palette::detect()
never runs terminfo; it is the ladder plus the step-0 stream gate.
The synchronous probe is bounded: every infocmp child on the sync surfaces
launches through one door (Probe\InfocmpBinary::runBounded()): a 5 s
wall-clock deadline with SIGTERM → 1 s grace → SIGKILL escalation, an 8 KiB
keep-a-prefix stdout cap, an array-form argv launch with no shell in the
path, the child's stderr drained rather than redirected, and fail-open
semantics — anything short of a clean, on-time dump leaves the env-anchored
chain answer standing. Results are memoized per TERM for the process
lifetime: a completed child (any exit code) and a recorded miss (an overrun or
a signal kill on this sync door), so a long-lived consumer pays at most one
child per terminal type. A failed launch is transient and mints no entry, so
the next call may spawn again. Probe::_reset() drains the table in tests.
Env-var precedence
The ladder's env legs, one table row per variable, in ladder order:
| Env var | Ladder step | Effect |
|---|---|---|
CLICOLOR_FORCE=1 |
1 | force TrueColor past every other env variable, NO_COLOR included (since CP-07 the step-0 stream TTY gate yields to it too). Silently re-enables color over NO_COLOR — see the a11y caveat under this table |
FORCE_COLOR |
2 | non-empty level override honored by all surfaces through the chain (like CLICOLOR_FORCE it outranks the step-0 gate since CP-07, colorless floor included): numeric 3+ → TrueColor (as do true/yes/on in any case), 2 → Ansi256, 1 → Ansi; every other spelling (0/false/no/off/…) lands on the Ascii floor — decoration kept, color codes dropped. Outranks NO_COLOR by design — see the a11y caveat under this table |
NO_COLOR |
3 | set to a non-empty value ("" = unset — the NO_COLOR standard treats any present-and-not-empty value as "off" — content never matters) → the colorless Ascii rung / NoColor capability — color codes dropped, decoration (\x1b[1m/\x1b[4m) kept, the reading no-color.org itself states (color attributes only). Contrast: NoTTY's full strip answers only hardware absence (the step-0 stream gate). Report surfaces still observe the NoColor capability for every suppression leg (Probe::isNoColor() names the NO_COLOR one) |
CLICOLOR=0 |
4 | suppress color |
TERM=dumb |
5 | case-insensitive; suppresses color — outranks COLORTERM (dumb is a promise of minimal capabilities) |
TMUX / STY |
6 | set + base TERM begins screen* → capped at Ansi256 before COLORTERM is consulted (CP-09): GNU screen never forwards the 24-bit set and COLORTERM survives multiplexer inheritance — the cap cannot be inherited away. Under tmux/screen the inner TERM is the base — no re-anchoring to the outer terminal happens |
COLORTERM |
7 | truecolor/24bit → TrueColor (exact value match, case-insensitive); yes → Ansi256 — the legacy "this is a color terminal" marker is a 256-color promise, not a 24-bit one (CP-09 demotion from the old TrueColor grant; a phase-2 terminfo that proves RGB still raises the rung back) |
TERM_PROGRAM |
8 | iTerm.app (exact spelling, case-sensitive) → TrueColor rung (step 8); phase 3 additionally maps WezTerm/vscode/Ghostty → TrueColor, iTerm.app → ITerm2, Hyper → Hyperlinks |
WT_SESSION |
9 | set, non-empty → Windows Terminal, TrueColor |
GOOGLE_CLOUD_SHELL |
10 | set to exactly true → TrueColor; any other value (false and 1 included) carries no 24-bit promise — CP-09 one-way tightening of the old set-and-non-empty grant |
TMUX / STY |
11 | set + base TERM begins tmux* → Ansi256, consulted behind COLORTERM — modern tmux may honestly forward truecolor (the screen/tmux split behind step 6, pinned by twin tests) |
TERM |
12-13 | ladder levels: *-256color/xterm-kitty/xterm-ghostty → Ansi256; xterm*/screen*/tmux* prefix → Ansi (all case-insensitive) |
REDUCE_MOTION / PREFERS_REDUCED_MOTION |
— | non-empty and not 0/false/no/off → Probe::reducedMotion() true (motion preference, outside the color ladder). Either variable on ⇒ reduced; one does not cancel the other — REDUCE_MOTION=0 ahead of a positive PREFERS_REDUCED_MOTION=1 does not mask it (accessibility bias, intentional, pinned by ProbeTest). No mainstream desktop exports either variable (unlike the no-color.org crowd), so apps bridging an OS-level setting should putenv() them |
Accessibility caveat for the force rows. An exported FORCE_COLOR/
CLICOLOR_FORCE — from a shell alias, a dotfile, or a CI image — silently
re-enables color for users who set NO_COLOR as an accessibility signal,
because steps 1-2 outrank step 3. Integrators honoring NO_COLOR as an
accessibility contract should check Probe::isNoColor() explicitly before
honoring any force override.
Since CP-05 the suppressions answer the colorless Ascii rung, not NoTTY;
NoTTY labels the full-strip rung reached by hardware absence (the step-0
stream gate). The two names that surface suppression are not synonyms:
Probe::isNoColor() names
the NO_COLOR leg only, while the NoColor capability is broader — it covers
all three suppression vars (NO_COLOR, CLICOLOR=0, TERM=dumb).
ProbeReport::colorDescription() is report prose; the enum's label() and
description() are the canonical vocabulary. The provenance door is
DetectionChain::userOptedOut() (CP-20): it reports whether one of the
suppression legs actually FIRED the answer, so a CLI can tell an operator
opt-out — repairable with --color=always — from a stream that simply has
no TTY in front of it. A force leg outranking a suppression reads false:
the rung in force is not a suppression.
Color degradation
use SugarCraft\ColorProfile\Color; use SugarCraft\ColorProfile\ColorProfile; use SugarCraft\ColorProfile\Palette; $color = new Color(100, 50, 255, 255); // Downsample to an explicit profile (static one-off shortcut) $ansi256 = Palette::toProfile($color, ColorProfile::Ansi256); // nearest cube/gray index $ansi = Palette::toProfile($color, ColorProfile::Ansi); // nearest of the 16 slots echo $ansi256->toAnsi256Foreground(); // "\x1b[38;5;…m" echo $ansi256->toAnsi256Background(); // "\x1b[48;5;…m" echo $ansi->toAnsi16Foreground(); // "\x1b[…m" — 4-bit SGR echo $color->toTrueColorForeground(); // "\x1b[38;2;…m" — honest name; the old // toAnsiForeground()/toAnsiBackground() // pair emitted these same 24-bit bytes // under an "ANSI" misnomer and now bridge // here (deprecated, REMOVED-IN: 2.0.0) // Or convert against the detected terminal $auto = (new Palette())->convert($color);
One door per rung (CP-18). Color::toAnsiFor() emits the SGR that renders
the color on a given profile — the value-object sibling of Palette's wire
degradation, exhaustive over all eight cases so a rung cannot silently fall
off a hand-rolled match:
$color->toAnsiFor(ColorProfile::TrueColor); // "\x1b[38;2;…m" $color->toAnsiFor(ColorProfile::Ansi256, background: true); // "\x1b[48;5;…m" $color->toAnsiFor(ColorProfile::Fgbg); // black-or-white SGR $color->toAnsiFor(ColorProfile::Ascii); // "" — colorless rung
Constructors from the indexed rungs. The writers that turn a Color into
SGR now have exact inverse doors (CP-17):
Color::fromName('BrightRed'); // case-insensitive over StandardColors::catalog(); // reads the LIVE slot (a process override of // StandardColors::$brightRed is reflected) — throws // OutOfBoundsException on an unknown name Color::fromAnsi16Index(9); // reference palette value of slot 9 — table-sourced, // NOT affected by slot overrides (the frozen sibling of // StandardColors::fromIndex()); throws outside 0-15 Color::fromAnsi8Index(3); // base-8 half, slots 0-7 only; throws outside 0-7
The two "no color" rungs differ. Since CP-05 the suppression variables
(NO_COLOR, CLICOLOR=0, TERM=dumb) and a falsy FORCE_COLOR spelling all
land on the colorless Ascii rung: Palette::rewriteSgr() drops every color
SGR (30-37, 40-47, 90-97, 100-107 and the 38/48/58 specs) while
decoration survives — \x1b[1m bold and \x1b[4m underline pass through.
The NoTTY palette (what the step-0 stream gate forces when the stream is not
a TTY and the ladder's answer is not a force leg — hardware absence, not an
opt-out variable; the force legs cross the gate since CP-07) instead runs every write
through Palette::stripAnsi(): SGR, full ECMA-48 CSI, OSC, DCS/APC/PM/SOS
strings, SS3, the enumerated Fe pairs (since CP-32 including ESC Z, ESC %…,
ESC #… and the reserved ESC |/}/~ pairs), and charset selectors all
disappear — color and decoration together. Consumer-facing caveat:
assistive-tech exposure. The full-strip rung is what a genuine pipe hands
downstream, and a raw escape initiator that reaches a screen reader or braille
display is an accessibility hazard, not an aesthetics one. stripAnsi() consumes
well-formed sequences; a truncated introducer at end of input has no operand to
match and stays. Consumers that pipe results onward to assistive tech may run a
residual scrub over untrusted byte streams:
// CP-32 residual scrub: swallow any remaining introducer, then drop orphans. $out = preg_replace('/\x1b[@-~][\x20-\x2f]*[0-7]?[\x20-\x7e]|\x1b/", '', $in); $out = str_replace("\x1b", '', $out);
To keep bold/underline while
dropping color regardless of environment, pin the same floor the suppressions
already answer: (new Palette())->withProfile(ColorProfile::Ascii).
Accessibility
Four settled texts, linked rather than copied (single-source discipline — this section adds no facts):
- Force variables outrank suppression by design.
CLICOLOR_FORCEandFORCE_COLORsilently re-enable color overNO_COLOR— the accessibility caveat under the env-var precedence table warns about exactly this override. - Suppression lands on the colorless rung. Since CP-05
NO_COLOR,CLICOLOR=0andTERM=dumbanswerAscii(color codes dropped, decoration kept);NoTTYand itsstripAnsi()full strip are reserved for hardware absence — the story and the pin-your-floor recipe live under Color Degradation. - Residual escape fragments. Output rewritten through the degradation
path can carry a lone
ESCfrom a truncated introducer; the consumer-facing caveat and the residual-scrub snippet sit under Color Degradation (CP-32). - Reduced motion.
REDUCE_MOTION/PREFERS_REDUCED_MOTIONdriveProbe::reducedMotion()with a deliberate one-way bias — see the env-var precedence row.
Perceptual color distance (opt-in)
Default nearest-color matching stays Euclidean (RGB) for byte-for-byte back-compat. For perceptual matching — where blues, greens and near-grays rank correctly — opt in:
use SugarCraft\ColorProfile\Color; use SugarCraft\ColorProfile\ColorDistance; use SugarCraft\ColorProfile\ColorMath; use SugarCraft\ColorProfile\DeltaE; use SugarCraft\ColorProfile\NearestColor; use SugarCraft\ColorProfile\PaletteIndex; // sRGB -> linear -> XYZ (D65) -> CIELAB $lab = ColorMath::toLab(64, 96, 128); // ['l' => …, 'a' => …, 'b' => …] $lab2 = (new Color(200, 30, 90))->toLab(); // same chain, from a Color // ΔE metrics (CIE 15:2004; CIEDE2000 per Sharma/Wu/Dalal 2005) $d76 = DeltaE::cie76($lab, $lab2); $d94 = DeltaE::cie94($lab, $lab2); // graphic-arts kL = 1 $d00 = DeltaE::cie2000($lab, $lab2); // Nearest ANSI-256 palette index under a chosen strategy (default: EUCLIDEAN) $matcher = new NearestColor(ColorDistance::Cie2000); $index = $matcher->ansi256(new Color(30, 120, 30)); // Arbitrary palette (list or map), returns the key of the winner $brand = ['logo' => new Color(10, 20, 30), 'accent' => new Color(240, 250, 255)]; $key = $matcher->closest(new Color(12, 34, 56), $brand); // Repeated lookups over one fixed palette: the PCA-bucketed index. // Answers EXACTLY what the brute-force scan answers (lowest index on ties) — // it only trades construction cost for a sublinear lookup. Euclidean and Cie76 // only; those are the metrics that admit a distance-preserving rotation. $idx = PaletteIndex::fromPalette(NearestColor::palette256(), ColorDistance::Cie76); $near = $idx->nearest(new Color(30, 120, 30)); // === (new NearestColor(ColorDistance::Cie76))->ansi256(...) // Error-compensated lookup, chafa chafa-palette.c:1160-1197: pass the // per-channel accumulator by reference; the query is pushed by error * 0.9/16 // before matching, and the new residual is written back for the next pixel. $acc = [0.0, 0.0, 0.0]; // start of the scanline $d1 = $matcher->withError(new Color(90, 90, 90), $acc); // dither chain step 1 $d2 = $matcher->withError(new Color(91, 90, 89), $acc); // ... inherits the push $none = null; $plain = $matcher->withError(new Color(12, 34, 56), $none); // null accumulator = plain ansi256() behaviour
The 256-entry and 16-entry palette Lab tables are memoized statically (fingerprint-guarded
against StandardColors reassignments, so the cache can never freeze a stale table), so a warm
CIEDE2000 search costs ~1 ms on a stock laptop; recomputing the 256 sRGB→Lab
conversions per search would add an estimated 40 % on top — the figure comes from the
NearestColor header note, while NearestColorTest pins the absolute warm-search
cost and the memoization itself, not the ratio.
The matcher's 256-entry table is the canonical xterm palette, slot for slot:
- slots 0-15 are the ANSI-16 set,
- slots 16-231 are the 6×6×6 cube at channel levels 0/95/135/175/215/255, and
- slots 232-255 are the
8+10ngray ramp —
all derived from Color::fromAnsi256Index() and
cross-pinned to sugar-core's decoder (Ansi256TableParityTest). Earlier
versions shipped a private even-51-step cube; that table never matched a real
terminal and is gone.
Probe — static environment detection
The Probe class provides the static convenience layer over the ladder above —
color profile, explicit no-color/force-color flags, and reduced-motion
preference. Use it directly when you need raw detection values without
constructing a Palette instance.
use SugarCraft\ColorProfile\Probe; use SugarCraft\ColorProfile\ColorProfile; // Detect the negotiated color profile $profile = Probe::colorProfile(); // ColorProfile::TrueColor|Ansi256|Ansi|Ascii|NoTTY echo $profile->label(); // "TrueColor" // Check for explicit disable/enable flags if (Probe::isNoColor()) { // NO_COLOR is set to a non-empty value — disable all color output } if (Probe::isForceColor()) { // CLICOLOR_FORCE=1 — force full color regardless of terminal } // Reduced-motion preference (REDUCE_MOTION or PREFERS_REDUCED_MOTION, // non-empty and not 0/false/no/off) if (Probe::reducedMotion()) { // Skip animations, spinners, and other motion }
Trust boundary
Detection's inputs are the env vars in the precedence table above — and,
through phase 2, the terminfo database the infocmp child consults. The
binary is launched from a fixed absolute-path roster, and every exec surface hands the child a minimal environment built in one place (Probe\InfocmpBinary::childEnvironment(): the queried TERM and a fixed PATH only). TERMINFO, TERMINFO_DIRS and HOME all steer infocmp's lookup (a search path you can inspect with infocmp -1 -D), and inheriting them from a parent whose environment an attacker controls would hand that attacker the database; they are therefore never passed. The stripped child environment is the correct security default, but it also silently defeats the classic tic-compiled TrueColor entry living in ~/.terminfo: the child's search will not find it, so export COLORTERM=truecolor instead — that rides the env ladder directly (step 7). What remains outside this library's reach is the database itself: an attacker who can write to the system terminfo directories still controls what the probe reports, so the name-position guard in Probe\TerminfoParser protects the parse from a hostile database but cannot vouch for the source. Treat every detection answer as a rendering hint, never as an authorization signal. A detected capability describes what the environment provides, not what this library guarantees: choosing a feature, granting trust, or selecting a transport on the basis of a Tc/RGB/Sixel answer opts into a promise the environment made — one this library cannot enforce.
ColorProfile enum
ColorProfile is this library's color-depth vocabulary, shared by every surface of it: the detection chain speaks it, Palette/ProfileWriter degrade against it, and libs that need the raw profile value consume it directly (live roster, derived from use SugarCraft\ColorProfile\ imports in the production src/ trees of the monorepo — candy-code references the library in its own tests/ only: sugar-log, sugar-image, sugar-spring, sugar-video, candy-mdview). Profile remains only as a deprecated class_alias facade over it. Five of the arms are detection-emittable (TrueColor/Ansi256/Ansi/Ascii/NoTTY — Ascii lands from a falsy FORCE_COLOR spelling, step 2 of the ladder); Ansi240, Ansi8 and Fgbg are request-side vocabulary only.
use SugarCraft\ColorProfile\ColorProfile; use SugarCraft\ColorProfile\Probe; use SugarCraft\ColorProfile\ProfileWriter; $profile = Probe::colorProfile(); // Human-readable label echo $profile->label(); // "TrueColor" // Request-side arms (Ansi240/Ansi8/Fgbg — detection never emits these): $writer = ProfileWriter::wrap(STDOUT)->withProfile(ColorProfile::Ansi240); // never touch slots 0-15
| Case | Value | Label |
|---|---|---|
TrueColor |
'truecolor' |
TrueColor |
Ansi256 |
'ansi256' |
ANSI 256 |
Ansi240 |
'ansi240' |
ANSI 240 |
Ansi |
'ansi' |
ANSI |
Ansi8 |
'ansi8' |
ANSI 8 |
Fgbg |
'fgbg' |
FGBG |
Ascii |
'ascii' |
ASCII |
NoTTY |
'notty' |
No TTY |
Fleet integration
sugar-core carries a second, parallel color-depth enum —
SugarCraft\Core\Util\ColorProfile — with its own detect() implementation.
It is a distinct type (int-backed, five cases NoTty=0/Ascii=1/Ansi=2/
Ansi256=3/TrueColor=4, against this library's string-backed eight-case
enum), and its consumers do not require this library: sugar-style and
candy-top resolve their color depth through the Core fork. The
"canonical chain"/"shared vocabulary" language in this README is scoped to
this library's surfaces (DetectionChain/Probe/Palette/ProfileWriter);
it never held across the two forks, and the forks answer the same environment
differently. Measured divergences (fresh process, TERM=xterm-256color, no
stream argument):
| Env | Core ColorProfile::detect() |
This library (ladder) |
|---|---|---|
NO_COLOR=1 |
Ascii — suppression floors at the black/white pair, decoration kept |
Ascii colorless rung (source env:NO_COLOR) — name converged since CP-05, semantics still divergent: ours drops color SGR entirely, Core repaints the nearest black/white ink |
FORCE_COLOR=1 |
TrueColor — any truthy force var jumps straight to full color |
Ansi — the level table is honored (1 → 16 colors) |
| TERM unset, nothing else | Ascii — since CP-10 the NAME matches ours, the rung does not: core's Ascii repaints the black/white pair |
Ascii colorless floor (fallback:default) — unknown or empty TERM claims no color since CP-10 |
TERM unset + CI=true |
Ansi — core honors its documented CI leg |
Ascii — this ladder reads the env TERM rungs only; with no TERM it lands on the CP-10 floor |
The structural roots of those flips: the Core fork has no level table and no
full-strip rung for suppression — any truthy FORCE_COLOR is TrueColor, and
Ascii is its suppression floor (NoTty arises there only from a non-TTY
stream or TERM=dumb, never from NO_COLOR/CLICOLOR=0); it answers from the
environment alone, with no terminfo phase. This library keeps Chalk's level
semantics, floors a falsy FORCE_COLOR at Ascii, and since CP-05 floors
suppression at the same colorless Ascii rung — the names agree, the semantics
do not (Core repaints the nearest black/white ink; this library drops color and
keeps decoration) — with Probe adding the opt-in terminfo phase on top. Neither
is wrong on its own terms — but anything that can observe both enums must not
assume agreement, and should pin which ladder produced a given value.
Reconciling the forks (a single enum, or a documented bridge between the two)
is an owner-level ruling, tracked as follow-up #26 — status: OPEN (the audit
record lives outside this repository; the divergence table above is its public
data and must stay current while the ruling is pending).
Maintenance
The ladder twins. The numbered ladder above and the DetectionChain
class docblock are maintained as a hand-copied pair — the README is prose,
the docblock is the source the code comments quote. tests/LadderDriftTest
re-derives both lists (step count, ascending numbering, per-step env-key and
answer-rung vocabulary outside parentheses) and fails naming the side that
moved, so an edit to one twin cannot land silently. The guard pins
vocabulary, not commas: parenthetical commentary may be phrased freely on
either side. sugar-core's forked ladder is deliberately NOT pinned to
equality — the divergence is public data, documented (with its drift-pinned
rows) under Fleet integration rather than guarded into sameness.
Architecture
SugarCraft\ColorProfile\
├── Color — RGBA color value object with conversion methods (Color::namedColors() lists standard names)
├── ColorProfile — THE color-depth enum (8 levels, richest→simplest)
├── Profile — deprecated class_alias facade over ColorProfile
├── DetectionChain — shared env ladder (the one precedence core; see the ladder above) + userOptedOut() provenance door
├── Env — env resolution (hermetic-replace rule), value read, source sanitize
├── Palette — instance detection over the chain + degrade/strip; adds the stream TTY gate and the describe()/comment() plain-language capability announcements
├── Probe — static env-probe layer (colorProfile/isNoColor/isForceColor/reducedMotion/resetForTesting)
├── AsyncProbe — ReactPHP child-process infocmp probe (bounded children, settles from the chain)
├── Probe\TerminalProbe — phased capability report (env chain → terminfo → escape queries → fallbacks)
├── Probe\Capability / Probe\ProbeReport / Probe\InfocmpBinary / Probe\TerminfoParser — capability enum, sourced report, resolved infocmp path, name-position terminfo parser
├── ColorMath — sRGB→linear→XYZ (D65)→Lab conversion
├── DeltaE — ΔE*₇₆ / ΔE*₉₄ / ΔE*₀₀ metrics
├── ColorDistance — distance strategy enum (Euclidean/Cie76/Cie94/Cie2000)
├── NearestColor — nearest-palette matcher (key-guarded memoized Lab, error-compensation carrier)
├── PaletteIndex — PCA-bucketed exact accelerator for repeated lookups
├── StandardColors — the 16 ANSI colors (mutable statics deprecated in favour of all()/fromIndex()/catalog(); see the deprecation window below)
├── ProfileWriter — stream wrapper for automatic color degradation (write() and printf() both emit at the stream's level)
└── Lang — i18n strings
Terminal capability probes
Beyond the env ladder above, the library exposes a richer capability surface
(exercised end-to-end by php examples/probe-report.php — hermetic env maps,
the sourced capability table, the toColorProfile() bridge and the
degradedTo() walk, all offline and exiting 0 with or without an infocmp
binary on PATH):
-
Probe\TerminalProbe(@deprecated, REMOVED-IN 2.0.0: useAsyncProbe::report()) — phased probe returning aProbe\ProbeReport: phase 1 runs the sharedDetectionChainfor the color-depth rung (so the ladder cannot drift between surfaces), phase 2 reads terminfo viainfocmp -1, phase 3 mapsTERM_PROGRAMadvertised capabilities (interactive streams only), phase 4 applies floors. Each detectedProbe\Capabilitycarries its source string (env:VAR,terminfo:caporfallback:reason). The live roster is the 11 enum cases —TrueColor,Color256,Color16,NoColor,Sixel,KittyKeyboard,ITerm2,Hyperlinks,BracketedPaste,FocusEvents,BasicAscii— withBracketedPasteandFocusEventsRESERVED: no probe producer sets them yet, sohas()stays false until one is wired. Terminfo capabilities are matched at the NAME position byProbe\TerminfoParser(ades=string mentioning "Tc" does not promote anything) and exec'd at theProbe\InfocmpBinary-resolved absolute path (the same path the availability gate checked — the binary is never looked up on PATH, and becauseinfocmpAvailable()is an overridable seam the terminfo leg re-reads that path and fails closed: a null composes no command, so an override can never demote the absolute binary into a TERM-shaped command word).TERM_PROGRAMmaps only terminals that actually implement what they advertise — notablyApple_Terminaldoes NOT setITerm2(Terminal.app has no OSC 1337 images). Reports answer throughallWithSource()/has()/source()plus thecolorDescription()prose, and bridge into the shared vocabulary viatoColorProfile()(TrueColor→TrueColor, Color256→Ansi256, Color16→Ansi, NoColor→Ascii— CP-20 moved it offNoTTY, the opt-out is not hardware absence, empty report→Ansiladder-default parity, BasicAscii-only report→Ascii). -
AsyncProbe::colorProfile(?LoopInterface $loop = null)— the same infocmp check in a ReactPHP child process; returns a promise. The child spawns ONLY on the loop you pass in: called without one, the promise resolves in-place through the bounded sync surface (an implicit singleton pickup would park the child on a loop its caller may never run, settling only in somebody else'sLoop::run()). Env suppression, a missing infocmp binary, an unset ordumbTERM, a TERM whose shape infocmp would read as an option, a chain rung other than Ansi/Ansi256, the cap being reached, or a timeout/kill all settle to the chain's answer. Results are advisory only. Both shapes are executable:php examples/async-probe.phpdemonstrates the explicit-loop spawn and the in-place no-loop resolve side by side.Every child is bounded: a 5 s wall-clock ceiling sends SIGTERM, a 1 s grace escalates to SIGKILL, and the exit handler cancels the SIGKILL timer when the child exits first. Both pipes drain into keep-a-prefix 8 KiB buffers, so a chatty child can neither wedge on a full pipe nor grow the accumulator without end. A spawn that fails to launch releases its concurrency slot and settles from the chain instead of throwing, and slot reclamation kills AND reaps children whose loop was abandoned — so the public
AsyncProbe::MAX_CONCURRENT_PROBES = 4cap can never wedge, and abandoned probes leave neither zombies nor pipe fds behind.Every async settle answers from the detection chain, with one carve-out: the TrueColor promotion read from a
Tc-declaring child dump — which itself only runs on the Ansi and Ansi256 rungs and sees at most the capped prefix. No blocking exec ever runs on the loop thread.The no-loop fallback is the sync
Probe::colorProfile(). Its phase-2infocmpexec rides the same bounded door as the child (previous paragraph), but it still blocks the calling thread for up to that ceiling — inside a live loop, pass the loop and stay off the tick path. -
AsyncProbe::report(?LoopInterface $loop = null)— the full capability report (Sixel, KittyKeyboard, ITerm2, Hyperlinks, TrueColor and theTERM_PROGRAMtable), returned as a promise of aProbe\ProbeReport. It is the async replacement for the synchronousProbe\TerminalProbe, which is@deprecated(REMOVED-IN: 2.0.0). The class is unchanged for backward compatibility and raises no runtime notice. The report is composed by the same pipelineTerminalProbe::run()uses: a recording pass finds out whether the terminfo leg needs a child, and a replaying pass feeds that child's capped dump into the same leg (Probe\TerminfoReplayProbe,@internal). The child spawns only on the loop you pass in, and it shares the oneAsyncProbespawn ladder, slot cap and deadline withcolorProfile(). Completed dumps are memoized per TERM (the cardinality ceiling is the same 256 entries); a deadline overrun, a signal kill and a failed launch mint no entry, and a signal-killed child replays as "no dump". Without a loop the promise resolves in place throughTerminalProbe::run().
Overriding detection
CLICOLOR_FORCE=1forces TrueColor past every other env variable — and since CP-07 past the step-0 stream TTY gate as well (upstream'sisatty() || forced()parity): on a non-TTY stream thePalette/ProfileWriteranswer keeps the forced rung. Non-forced rungs stay gated — piping into a file is decoration-safe by default.FORCE_COLORpicks the level (3/2/1, falsy →Asciifloor).- Program-side, pin the answer:
(new Palette())->withProfile(ColorProfile::Ansi)(immutable clone) orProfileWriter::wrap(STDOUT)->withProfile(...). - A
Palette/TerminalProbeconstructed with a non-empty injected$envmap is hermetic: the map completely replaces the ambient environment (Env::resolve()), it does not overlay it — pass every key you care about. - The empty map is not hermetic:
Env::resolve([])falls through to the ambient environment —[]means "use what the process already has", never "no environment". A test wanting a controlled env must inject at least one key.
Deprecation: StandardColors mutable statics
Deprecated as of 2026-10-24.
The 16 public static Color properties on StandardColors ($black …
$brightWhite) are now deprecated as a writable surface. They are
process-global mutables: an assignment anywhere rewrites the value for every
reader, and nothing pins them against reassignment.
Nothing changes today. The properties keep working byte-for-byte — reads,
writes, and every current consumer behave exactly as before. They are removed
in favor of an immutable, constant-backed equivalent no earlier than 2.0.0
(each tagged REMOVED-IN: 2.0.0). Until then this is a deprecation window:
migrate now, no rush, no breakage.
Use the non-mutating read API instead (not deprecated):
| Instead of | Use |
|---|---|
StandardColors::$red |
StandardColors::fromIndex(1) or StandardColors::all()[1] |
StandardColors::$brightBlack |
StandardColors::fromIndex(8) |
| enumerating the palette | StandardColors::all() (indexed 0-15) · StandardColors::catalog() (names) |
| a private/global override table | build your own array from all() — the Color values are immutable, so a local array is already isolated |
| constructing fresh standard colors | new Color(0xcd, 0x00, 0x00), Color::parse('#cd0000'), Color::fromName('red') (a fromIndex() read in disguise) or Color::fromAnsi256Index(1) |
fromIndex(int) is bounds-checked and throws OutOfBoundsException outside
0..15. A structural test pins both halves of the window: every deprecated
property is still a live writable static (no accidental neuter), and the
16-property count here matches the code.
License
MIT
Credits & inspiration
Originally inspired by the Go Charm ecosystem; SugarCraft is developed as a native PHP project.