--- type: Module title: "@effected/cli-kit" description: The presentation boundary of an effect/cli program — audience, colour, theme, messages, logging, failure reporting and schema-issue renderers in a React-free root, with interactive Ink screens behind ./ui and their test harness behind ./ui/testing. status: stable kind: package resource: ../../packages/cli-kit tags: [dx] generated: by: "okfit/claude-code" at: 2026-11-05T17:16:21Z integrity: generated: body: a0a90d909180dbba --- # @effected/cli-kit `@effected/cli-kit` is the presentation boundary of a command-line program built on `effect/cli`: who the output is for, how it reaches them, how a failure is reported, and how a schema issue is rendered into a sentence a user can act on. The [presentation layer](../decisions/cli-grows-presentation-layer.md) — audience, interactivity, theme, a status vocabulary, messages and logging composition — lives in a React-free root; interactive screens live behind a `./ui` subpath the root never reaches, with their test harness behind `./ui/testing`. It is still not a CLI framework: `effect/cli` owns argument parsing, flags, the command tree and the help system, and this package must never grow a second one. The distinguishing property of everything in scope: a consumer only discovers the need by shipping bad output to a person. None of it fails a type-check, a test, or a review of the code in isolation — the default behaviour is wrong in a way the author cannot see from the call site. ## Motivation: three defaults that are wrong at a terminal Each of these is found by running a binary, never by reading the code. 1. **Effect's default logger is a service log line, not CLI output.** It emits `[00:33:56.619] INFO (#2): message` — correct for a long-running service being scraped, wrong for a tool a person is watching. Every `effect/cli` program needs a logger that renders the message plainly. 2. **An unhandled failure reports through the default logger, on stdout.** `NodeRuntime.runMain` reports an unhandled failure using Effect's default logger, which sits outside the layers the program was provided — so a program that carefully installs a CLI logger still prints its failures in the structured format that logger exists to replace, and prints them on stdout, the one stream errors must not use (`mytool run > log.txt` must still show failures on the terminal). 3. **A `SchemaIssue` tree is not a sentence.** A config validation failure arrives as a structured tree; a user needs `unknown key at groups.g.cleanup.rulesetz`. Core ships formatters (`SchemaIssue.makeFormatterStandardSchemaV1`), but they are near-undiscoverable — named `makeFormatter*` rather than anything containing "render", living in `SchemaIssue` rather than `SchemaError` or `Schema`, and `SchemaError.message` does not use them. ## Kit positioning **Tier: boundary.** It performs IO — writing to a terminal is IO — but discharges it through core contracts required in `R`, takes no external runtime dependency (`string-width` is a test-only `devDependency`; see [the display-width decision](../decisions/own-display-width.md)), and must not import a platform package. `@effected/env` is a required peer, so the audience and terminal decisions are made once and read as services ([its own package](../decisions/env-is-its-own-package.md)); `ink` and `react` are never imported from the root. This is the same posture as `@effected/config-file`, and deliberately not `@effected/github-actions`', which is the one package carrying `@effect/platform-node` as a required peer. The dependency closure is declared in full. Required peers: `effect`, `@effected/env`, and `@effected/walker` with `@effected/glob` beneath it (`CliLinks` finds the project root with `Walker`: [the walker edge](../decisions/cli-takes-the-walker-edge.md)). Optional peers: `ink`, `react` and `@types/react` (for `./ui`). Four regular dependencies, none of them carrying a shared-instance contract and none with an `@effected` peer of its own, so they leave the peer closure unchanged: the pure [`@effected/github-commands`](github-commands.md); [`@effected/source`](source.md), which `Fmt.suggest` delegates to for its `EditDistance.suggest`; [`@effected/kit`](kit.md), for `MainOptions.distribution`, whose `CurrentDistribution` is a string-keyed `Context.Reference` a duplicate copy still meets ([decision](../decisions/cli-engine-edge.md)); and [`@effected/commands`](commands.md), of which only the `./node-sync` subpath is imported, lazily, by `./ui`'s Ink loader for `ModuleResolution` ([the `./ui` Node licence](../decisions/ui-binds-process-streams.md)). The boundary test pins that `.` and `./testing` reach no `@effected/commands` module at all. **Nothing in the kit may depend on it except an application**, the same rule `@effected/app` carries. A library that reaches for CLI output has made a decision that belongs to the program at the top. `app` and `cli-kit` are siblings, not layers: `app` is the control plane (directories, state, cache, config), `cli-kit` is the presentation boundary. Neither imports the other. `@effected/cli-kit` is one of the surfaces the consumer register describes — see [`reposets`](../consumers/reposets.md), the first repository to weigh a new request against it. ## Public surface Exports are static classes with a private constructor — never an `as const` namespace object, which loses its members' TSDoc in the built `.d.ts`. | Export | What it is | | --- | --- | | `CliLogger` | A `Logger` rendering messages plainly, routing to stderr from `stderrFrom` down and everything else to stdout | | `CliRuntime` | The failure-reporting wrapper: report through the program's own logger, set the exit code | | `CliRuntime.main` | The full-program combinator: provides the platform layer inside failure reporting, a fresh `CliExit`, the `ShowHelp` remap, and the logger outermost. See "Findings are success" below. | | `MainOptions` | `ReportFailuresOptions & { platform: Layer; logger?: Layer }` — `platform` is passed in rather than owned so this package never imports one; `logger` defaults to `CliLogger.layer()`. | | `MainOptions.distribution` | `Distribution \| null \| undefined`, engine's `Distribution`: the carrier package the bin was installed through. Given (even as `null`), `main` provides engine's `CurrentDistribution` around the program with `withDistribution`, so the program and the engine it calls read one value. With a carrier, it updates core's `CliOutput.Formatter` so `formatVersion` is wrapped by `withDistributionVersion`: `--version` ends with a space and `via `, appended to whatever formatter is in effect, the coloured default or `env.formatter`'s, so `env.formatter` must not also append it. Core's default prints ` v`; a program keeping another shape passes it as `env.formatter.formatVersion` and still gets the suffix. [Why cli depends on engine](../decisions/cli-engine-edge.md). | | `ReportFailuresOptions.exitCodes` | `Readonly>`: a typed failure whose `_tag` is a key exits with that code. Checked after the error's own `Runtime.errorExitCode` (an error that chose its code keeps it) and before `exitCode`, which stays the fallback for every other failure, defects included. Only a typed failure is looked up: a defect carrying a `_tag` exits with `exitCode`, and a usage error, a cancel (130) and a non-interactive prompt (64) keep their own codes. Lookup is own-key (`Object.hasOwn`). Every code must be an integer in `1..255` (`0` would pass a failed run, `256` wraps to `0`); anything else throws a `RangeError` when the options are passed, a wiring mistake. | | `CliExit` | A `Context.Service` holding a `MutableRef`; `CliExit.set(code)`, `CliExit.report(code, line)` (one stderr line, records the code, succeeds; it does not stop the program, and an invalid code dies before writing) and `CliExit.reportCause(cause, codeOf)` (the same for a cause, as ` : ` sanitized, tag read guarded; an interrupt-only cause reports nothing and re-interrupts), and `CliExit.layer` for in-process tests. **`CliExit.layer` is `Layer.fresh`** — every provide mints a new cell, so a program run under `CliRuntime.main` must not provide `CliExit.layer` itself, or `CliExit.set` writes to a second, unread cell and the run silently exits `0`. See "Findings are success" below. | | `CliColor.enabled` | `Effect` — `TerminalEnv.colorLevel("stdout") !== "none"`, so it honours `FORCE_COLOR` with Node's precedence ([D-C](../decisions/force-color-honoured-node-precedence.md)). Reads go through `Config`, never `process`. | | `CliColor.formatterLayer` | `(overrides?: Partial, helpFlags?: CliHelpFlags) => Layer` — builds `CliOutput.defaultFormatter({ colors, ...helpFlags })` from the same `CliColor.enabled` decision, so help text, parse errors and rendered output always agree. | | `MainOptions.helpOnUsageError` | `"stdout" \| "stderr"`, default `"stdout"` (core's behaviour). Under `"stderr"`, `main` provides core's `CliOutput.Presenter` around `program` (`internal/HelpRouting.ts`): an `InvalidInvocation` event runs core's `defaultPresenter` under a `Console` whose `log` is the ambient `error`, so the help and its errors both go to stderr with core's rendering and Formatter resolution; `Help` (an explicit `--help`, a bare group invocation) and `Version` events are core's, on stdout. Because the presenter renders where `Command.runWith` runs, a Formatter or Console provided inside `program` is honoured. With `env` set, that usage help is painted under **stderr's** colour decision rather than stdout's (the `formatHelpDoc`, `formatError` and `formatErrors` methods are rebuilt from core's default formatter under it and `env.helpFlags`, unless `env.formatter` supplies them), so help on a terminal stderr and a piped stdout is coloured, and the reverse is not. Caveats: a Presenter provided inside `program` replaces the routing, and under `renderErrors: false` core presents the help as plain `Help`, so it stays on stdout. | | `ReportFailuresOptions.render` | `(error: unknown, details: FailureDetails) => string \| ReadonlyArray`. `error` is `Cause.squash(cause)`; `FailureDetails` is `{ cause, isDefect, isCancelled, isNotInteractive, exitCode, defaultLines, lines }`, with `exitCode` the code this failure exits with (the error's own `Runtime.errorExitCode`, else its `exitCodes` entry for a typed failure, else `exitCode`, else `1`), decided before `render` runs so a render can print it (a hook that parses a fixed stderr shape reads the tag off `error` itself, `Predicate.hasProperty(error, "_tag")`, and the code from here; constructing a `FailureDetails` literal now needs `exitCode`), and `isDefect = !Cause.hasFails(cause)` (the literal absence of a typed failure, unchanged) and `isCancelled` / `isNotInteractive` true when the squashed `error` is the kit's `Cancelled` / `NotInteractive`, whichever channel it arrived through (a `CliPrompt.fallback` quit is a defect, a `CliUi.run` one a typed failure), so a `render` that gives defects an issue-report footer checks them first; the flags change no exit code and no default line and `defaultLines` the report the kit would write for this run (its audience, colour, links and `displayPath`), so a `render` returning them writes exactly the default report — exact because `squash` prefers a `Fail` over a `Die`. `lines({ status? })` is the same report (`lines()` equals `defaultLines`); `status: false` drops the leading status and keeps the run's settings, so a prefixing render keeps `displayPath` (vitest-agent A2). Added so a consumer stops guessing "typed" from an `Error` carrying a string `_tag`, which a defect can also be. A one-parameter renderer still fits. A consumer `render`'s lines are text the kit did not build, so the report applies the output policy to them: neutralized under GitHub Actions (always when no environment services exist), and stripped of escapes for an agent or a CI audience (GitHub Actions detects as `ci`); for a person their own escapes are kept (the kit cannot tell colour from injection), so a `render` sanitises the data it interpolates. If that rendering dies, the report falls back to the plain path and then to the error's own text, sanitised and neutralized. The default is `CliFailure.toDoc` rendered through `Render.context("stderr")` and the audience-chosen renderer, still written through `CliLogger` (so `--log-level` and the logger options are unchanged). `reportFailures` catches outside the layers `main` provides, so `main` gives it a per-run cell the environment layer fills with the render target, and `CliAudience.runWith` rewrites it once an audience flag is read. `CliRuntime.defaultRender(error, details, { status? })` is the same document as plain lines, exported so a consumer `render` hands the failures it does not own back (`Cancelled` and `NotInteractive` are their own fixed line); `status: false` leaves off the leading status glyph or `[FAIL]`, so a program-name prefix reads cleanly. | | `ReportFailuresOptions.usageExitCode` | Remaps a `ShowHelp` that carries errors to this code, default 64 (D7). A `ShowHelp` with no errors keeps exit 0. | | `SchemaIssueRenderer` | `SchemaIssue` tree → actionable lines, over core's formatter | | `ConfigIssueRenderer` | The same for `@effected/config-file`'s `ConfigValidationError` (the parameter is the structural `ConfigIssueSource`, `{ readonly issue?: unknown }`), plus a "did you mean" hint on an `unknown key` line when the struct at that path declares a near match (#1114): `unknown key at theme.colour (did you mean "color"?)`. The candidates are the declared keys core's `UnexpectedKey` leaf carries on its `ast` (an `Objects` node's string property names; every branch's under a union), so no schema is passed and nothing from `@effected/config-file` is loaded; the list is `Fmt.suggest`'s, each key sanitised, joined `"a", "b" or "c"`. A key with no near match is drawn exactly as `SchemaIssueRenderer` draws it. `SchemaIssueRenderer` and the failure report do not add the hint. | ### The presentation layer Exports the interactive CLI kit adds to the root. See [the presentation-layer decision](../decisions/cli-grows-presentation-layer.md) for why the package owns them. | Export | Contract | | --- | --- | | `CliEnv.layer` | `(options?: CliEnvOptions) => Layer` with `CliEnvServices = CurrentRuntimeEnv \| TerminalEnv \| Audience \| CliTheme \| CliLinks \| Terminal` — builds the environment services once, in the right order, **sets** the `CliInteractive` reference from the audience and terminal, and installs `CliPrompt.gateTerminal`, `gateWizard` and `CliTheme.promptTheme` (core's prompts follow the theme), so the layer also outputs the gated `Terminal`, which `CliEnvServices` lists. It also sets core's `TerminalCapabilities` from `TerminalEnv` (an internal layer over env's pure `TerminalEnv.capabilities`, reading `TERM` through `Config`; it lives here, not in env, because only `effect/cli`'s barrel exports the reference), so core's own help, version and error colour follows the kit's colour rule, with `canPrompt` held at `true` by `CliInteractive.layer`: core skips a fallback prompt entirely when `canPrompt` is `false`, which would lose every kit fallback's `otherwise` in a piped run, and `CliInteractive` with `gateTerminal` already owns the prompt decision. Not interactive, that terminal's `readLine` fails as a quit and its `display` writes nothing. A reference's key type is `never`, so `CliInteractive` is not in the output type. Every read degrades to unset when `Config` fails, so only `Stdio` or `Terminal` failing fails the layer. `CliEnvOptions` is `{ audienceEnvVar?, stderrIsTerminal?, theme?, log?, editorLinks?, editorLinksEnvVar?, helpFlags? }`; `log` and `helpFlags` are read only by `CliRuntime.main`. `helpFlags` is a `CliHelpFlags`, `{ inheritedFlags?, globalFlags? }`, each `"full"` (core's default), `"summary"` (a one-line pointer) or `"none"`: it sets how subcommand help lists the flags a parent shares (the audience flags) and the built-ins (`--help`, `--version`), and passes through to core's formatter beside the colour decision, so choosing a mode costs no colour. Without `stderrIsTerminal`, stderr's terminal check is core's `Stdio.stderrIsTerminal`, which the platform `Stdio` answers from the host; the option replaces it for a `Stdio` that cannot say (`Stdio.make` without the field answers `false`). The kit never reads the host for it — the root reads no `process` ([ui-binds-process-streams](../decisions/ui-binds-process-streams.md)). | | `MainOptions.env` | `CliEnvOptions`. When present, `CliRuntime.main` builds `CliEnv.layer(env)` inside failure reporting, where the platform sits, together with `CliColor.formatterLayer` so help text follows the same colour decision, so a failure building it renders one line and exits through the `exitCode` option rather than reaching the runtime's stack trace. `env.displayPath` is the run's path display: a function, or `{ relativeTo: root }` (an absolute `root`; a path under it shows relative, while `root` itself and a path outside it stay absolute, since a `../..` chain says less; it uses the platform's `Path` when there is one, else a prefix test on `/` and `\`). `CliEnv.layer` sets it as the run's default, so `Render.context`, `Doc.print`, a `Doc.path` or file link, a live view's `final` document, `CliUi.context`'s `UiContextValue.displayPath` (and so a `DocView`) and the default report's stack frames all follow it; an explicit `displayPath` passed to `Doc.print` or `Render.context` still wins. It also covers and `env.stackFrames` (`app` by default, or `all`) which of them it shows, in the report, `defaultLines` and `lines()`; an audience flag's rewrite of the report target keeps both. `env.formatter` replaces methods of the coloured `CliOutput.Formatter` `main` installs (for example `formatVersion`). With `env.log`, `main` builds the platform UNDER the logger, so a line it logs while building goes to stderr, at the run's level and, under `format: "auto"`, in the format the build-time audience gets: an audience flag in `env.log.argv` (a Node host passes `process.argv.slice(2)`, since `Stdio` is the platform's own and the kit never reads `process`), else the `audienceEnvVar` override, else agent/CI detection from the environment, never the terminal; an agent or a CI gets NDJSON and anything else plain, the same audience-only rule the runtime lines follow, so a human piping stderr gets plain lines throughout and stderr's terminal state never decides the format (vitest-agent r5 F2; pass `format: "json"` for machine-readable logs) (vitest-agent A1, ruled (a)+(c): a buffer-and-replay was rejected because a hanging build would hide those lines); no `CurrentRuntimeEnv` exists while the platform builds, so the build-time logger detects one from the environment and uses it (or `env.log.runtimeEnv`) as the neutralization fallback in every format, the plain branch included, so a build-time line is neutralized under GitHub Actions as a runtime one is (r4 review, fix 3); the environment layer is built under its own build-time logger (`envBuildLogLayer`), so the audience-override warning, which interpolates the variable's value, is written exactly once in the build-time format (NDJSON alone for an agent or a CI, floored at `Warning`; a plain line otherwise), neutralized, and never silenced by `plainLogger: false` or an unset diagnostics level, since it is a configuration error; it goes to stderr alone, whatever `logger.stderrFrom` raises (the env build's plain logger alone is pinned at `stderrFrom: "All"`; the platform's build-time logger keeps the host's `stderrFrom`, which is the host's routing choice), and never to `extraLoggers` or the file sink (r4 re-review nit 2); it installs no `MinimumLogLevel` (fix 1 addendum, r4 fix round 2 R1), and uses `CliLog.layer(env.log)` as the logger set (`env.log` may carry the `file` option when the platform provides `FileSystem` and `Path`) instead of the default `CliLogger.layer()` (an explicit `logger` option still wins); the logger is built over the same env layer and falls back to `CliLogger` if that build fails. Not interactive, the program's `Terminal` is gated: `readLine` fails as a quit, so a program reading piped data must read `Stdio.stdin`. Without `env`, nothing is provided and `CliInteractive` keeps its non-interactive default, so forgetting it yields a CLI that never prompts. | | `CliEnv.layerTest` | `(options?: CliEnvTestOptions) => Layer` with `CliEnvTestServices = TerminalEnv \| Audience \| CliTheme`: the environment a test fixes in one layer, in the same build order as `CliEnv.layer`, and it sets `CliInteractive`. `CliEnvTestOptions` is `{ tty?, term?, audience?, columns?, color?, theme? }`: `tty` makes stdin, stdout and stderr all terminals (default `false`, a pipe), `audience` defaults to `human`, `color` to `none` for both streams and is fixed as given (`term` does not change it), `columns` to none, and `term` is the `TERM` that only the theme's glyph choice and the interactivity decision read while the layer builds, whatever the host's `TERM` is (`dumb` is not interactive and draws ASCII). It composes `TerminalEnv.layerTest`, `Audience.layerTest`, `CliTheme.layer`, the same internal capabilities layer and `CliInteractive.layer` (so core's `TerminalCapabilities` comes from the fixed answers, never the host's process), so a test of a screen or a live view fakes a terminal without composing them by hand. It is in the root, not `./testing`, because it is a pure layer over the root's own services and needs none of the testing entry's platform requirements. | | `CliAudience.flags` | `(options?: { hidden? }) =>` the four shared flags `audience`, `human`, `agent`, `ci`, each `Flag.atLeast(0)`; spread into `Command.withSharedFlags` on the root. `hidden` applies `Flag.withHidden`. `--audience` names its values once, through core's own `(choices: human, agent, ci)` suffix: it sets no metavar, which would list them a second time (so its placeholder is core's generic `choice`). Core lists shared flags in every subcommand's help, which is upstream (Effect-TS/effect issue 8642). Core's help formatter lists them under the declaring command's `FLAGS` and, on every subcommand below it, in an `INHERITED FLAGS` section between `FLAGS` and `GLOBAL FLAGS`; the kit adds nothing to that rendering. | | `CliAudience.provide` | Piped onto the composite root (after `withSubcommands`): resolves the flags with `Command.provideEffect` and re-provides env's `Audience` with `source: "flag"`. More than one occurrence is a `CliError.UserError`, exit 64. `run` and `runWith` apply it themselves, so it is the path for a bare `Command.run` only; it then covers the subcommand handler (with the same interactivity decision) but not a fallback prompt. See [the audience flag decision](../decisions/audience-flag-is-shared-root-flags.md). | | `CliAudience.runWith`, `CliAudience.run` | THE wiring for the audience flag: `Command.make(...).pipe(Command.withSharedFlags(CliAudience.flags()), Command.withSubcommands([...]))`, then `CliRuntime.main(CliAudience.run(root, { version }), { platform, env })`. `runWith(root, config)(argv)` and `run(root, config)` (reads `Stdio.args` like `Command.run`) scan argv for the four flags BEFORE core parses, apply `provide` themselves, and run core inside a provided `Audience` (`{ kind, source: "flag" }` for exactly one flag) and a `CliInteractive` the flag decides from the audience and the TTY facts (`--human` is interactive when `TerminalEnv` reports a terminal on stdin and stdout, even under a detected agent, and never in a pipe; a non-human flag or a conflict makes it false; with no `TerminalEnv` a flag only narrows), with `--wizard` following that decision (restored only into the exact config object `gateWizard` produced when it dropped it, so a consumer's own `CliConfig`, from outside the gate or inside, never gets it back) and diagnostics switched to NDJSON for a non-human flag. A root without the shared flags does not compile (`RequiresAudienceFlags`). The scan and the resolver share one counting rule (true occurrences only). | | `CliInteractive` | A `Context.Reference` defaulting to `false`, read with `yield* CliInteractive` and never in `R`: `Audience` is `human`, stdin is a terminal, stdout is a terminal and `TERM` is not `dumb` (a dumb terminal cannot move the cursor or take synchronized output, so it gets what a pipe gets: a live view prints its final frame once, a screen is `NotInteractive`). The decision is `internal/canPrompt.ts`, shared by `layer` and the audience flag's recompute; `TERM` is read through `Config`, only when both streams are terminals, so it adds no requirement. Static `layer` (from `Audience` and `TerminalEnv`), `layerTest(value)` and `unless(condition)`, a scoped override that can only turn it off. Both layers are typed `Layer` because they set the reference. Both also hold core's `TerminalCapabilities.canPrompt` at `true`, keeping `canColor` and `canAnimate` as they find them, because core decides `canPrompt` from the process's terminal and skips a `withFallbackPrompt` fallback when it is `false`; with the gate held open the kit's fallbacks are always called and this reference decides. A `TerminalCapabilities` with `canPrompt: false` provided inside the program bypasses the kit's fallbacks, so the parameter fails as missing even with an `otherwise`. | | `Token`, `Style`, `TokenName` | A token is a style; applying it is identity when colour is `none`. `TokenName` is `success`, `failure`, `warning`, `info`, `error`, `muted`, `accent` or `emphasis`. `Token.hex`, `Token.named` and `Token.style` build custom styles. `Token.defaults` is the frozen default style of every token and `Token.resolve(token, overrides?)` the pure resolution `CliTheme.paint` applies (a name that is not a token resolves to the empty style), so a renderer with no Effect context reads styles as data. `NamedColor`'s bright variants are spelled as chalk and Ink spell them (`redBright`, `blackBright`, with `gray` as an alias); the `Style` to Ink props mapping is `inkProps` in `./ui`. A colour name that is not a `NamedColor` paints nothing. | | `Status` | An open vocabulary: `Status.core` (`success`, `failure`, `warning`, `info`, `skip`, `pending`) and `Status.extend(extra)`, each entry a glyph, an ASCII glyph, a token and a rank. `resolve(name)` returns the full definition as a frozen copy, which the document IR stores, and, like `def`, throws on a name the vocabulary lacks (reachable only through a cast). `worst(names)` takes a non-empty list and returns the highest rank, ties to the first (rank is severity, not an aggregation policy: a consumer whose rule differs folds its own); `worstOption(names)` takes any array and returns an `Option`, `None` when empty. `glyph(name, glyphSet)` is the unpainted glyph from a set. Names are typed, so a misspelt one is a compile error. | | `Glyphs` | `Glyphs.unicode` and `Glyphs.ascii`: the status glyphs, bullet, arrow, ellipsis, spinner frames, `spinnerIntervalMs` (80), `tree` segments (`branch`, `last`, `pipe`, `blank`: box-drawing in Unicode, `-`, `\` and pipe characters in ASCII) and `pathSeparator` (`human`, `agent`: `›` and ` > `, or `>` and ` > ` in ASCII). ASCII is chosen under `TERM=dumb` or by option. `Glyphs.select({ ascii?, term? })` is that choice as a pure function (`auto` is ASCII only for `term` `dumb`, passed in because `StreamEnv` carries no `TERM`), which `CliTheme.layer` calls after reading `TERM` through `Config`. | | `CliTheme` | A `Context.Service` with `paint`, `style` (the resolved style `paint` renders, whatever the colour level), `sgr`, `glyphs`, `color` and `status` (the stdout ones) and `forStream("stdout" \| "stderr")`, a `StreamTheme` painting with THAT stream's colour from `TerminalEnv.stderr.color` or `.stdout.color`; anything written to stderr is painted through `forStream("stderr")`, as `CliMessage` does. `layer({ tokens?, glyphs? })` needs `TerminalEnv`; `layerTest` fixes the colour level; `promptTheme` sets core's `Prompt.Theme` from the tokens, with empty colour strings when colour is `none`. `CliTheme.forAudience(theme, audience)` is the audience rule as public API: an agent gets the theme at colour `none` (identity `paint`, empty `sgr`, unpainted `status`), anyone else, or an unknown audience, the theme itself. `Render.context`, `./ui`'s mounts and `CliLog.status` all apply it, so a consumer painting its own lines applies the kit's rule instead of copying it. | | `Fmt` | `sanitize` (the renderers' own: escapes and controls removed, a tab a space, line breaks kept), `width`, `truncate` (grapheme-safe, ANSI-safe, result never wider than asked), `duration` (`250ms`, `1.2s`, `1m 3s`, `1h 2m`; takes any `Duration.Input`, a number used as given in milliseconds rather than rounded through a `Duration`'s nanoseconds, and an invalid input is `0ms`, never a throw: #1045), `percent` (a 0 to 1 ratio, or a 0 to 100 number with `{ scale: 100 }`), `plural`, and six more, each never throwing: `pad(text, width, { align?, fill? })` (`PadOptions`; measured as `width` measures, so coloured text pads to the same column; `left` by default, `center` puts the odd column on the right; a fill not exactly one plain column is a space; text already as wide is unchanged, and a non-finite width pads nothing), `stripAnsi` (CSI, OSC ending in BEL or ST, DCS, SOS, PM and APC strings, the nF sequences such as `ESC ( B`, and the two-byte ones `ESC 7`, `ESC 8`, `ESC =`, `ESC c`; only complete sequences go, so a lone ESC, an ESC before a lowercase letter other than `c`, and an unterminated CSI's `[` stay), `isEscapeOnly` (nothing but escape sequences; empty text and a bare control character are not), `ranges` (integers as `"1-3,5,10-11"`, sorted and deduplicated, non-integers dropped), `describe` (any value as text: a string as itself, a value with a string `message` as that message, else its JSON, else `String(value)`, else `"[unprintable value]"`; a throwing getter is a value without a message; not sanitised) and `causeMessage` (every distinct non-empty message along the `cause` chain, nearest first, joined with a colon and a space, a deeper message the text already contains not repeated and one containing the text replacing it; eight nodes at most; a throwing `message` getter leaves that node without text and a throwing `cause` getter ends the walk; `undefined` when nothing has a message, so `?? Fmt.describe(value)` applies). `causeMessage` is the [error-standards](../conventions/error-standards.md) helper, the guarded copy every kit package's errors render a preserved cause with. `describe` and `causeMessage` are `@effected/kit`'s `ErrorText.describe` and `ErrorText.causeMessage`, the same functions (#1141): the implementation and the `internal/causeMessage.ts` copy moved to engine, a regular dependency already, so an MCP front end, which may not depend on this package, describes a failure with the same words. `errorText` is engine's `ErrorText.of`, exactly `causeMessage(value) ?? describe(value)` (#1134). `suggest(input, candidates, { maxDistance? })` (`SuggestOptions`; #1114) is a "did you mean" list: the candidates at the smallest Levenshtein distance up to `maxDistance` (2, the threshold `effect/cli`'s internal `auto-suggest` uses for an unknown subcommand, whose ties-all-kept rule it also follows, held to it by a differential test over every word up to length four), in the order given, each once; only the band of the edit matrix within `maxDistance` of its diagonal is computed and a candidate whose length is further off is skipped, so a long typed value costs nothing against short names; a `maxDistance` that is not a non-negative integer throws a `RangeError` (wiring). The distance and the search are `@effected/source`'s `EditDistance.suggest`, a regular dependency, which `Fmt.suggest` calls after checking its own number-only `maxDistance` (so the `RangeError` message names `Fmt.suggest`). `ConfigIssueRenderer` uses it for its `unknown key` hint. Width comes from [the package's own implementation](../decisions/own-display-width.md). | | `CliFormat` | A `--format` flag and the one print that honours it, so a command builds its report once as a `Doc` and its data once as a value. `CliFormatName` is `auto`, `plain`, `ansi`, `markdown`, `githubLog` or `json`. `flag(formats, { default?, name?, description?, aliases?, custom? }?)` is core's `Flag.ChoiceWithValue` (`format` by default), defaulting to `options.default` (spelled as on the command line), else `auto` when offered, else the first format; any other value is core's usage error naming the accepted ones. `aliases` (#1128) maps the caller's names onto built-in formats (`{ human: "auto" }` offers `human`, yields `auto`; the target need not be offered by its own name, so okfit's `human\|json` contract is `["json"]` plus that alias); `custom` offers names the caller renders itself, yielded as themselves (`mermaid`, `dot`), which the caller branches on before `print`. The result is one plain core `Flag`, so core's combinators (`Flag.withAlias`, the fallbacks, `--wizard`) apply to it unchanged. A retired `--json` is not accepted: an earlier `legacyJson` option (#1133) joined a hidden boolean into the flag by rebuilding core's `Param.Transform` node, which relied on that node's private shape, left one flag holding two params (so `Flag.withAlias` on the result was a duplicate alias, and core's single-param lookup behind `--wizard` and `withFallbackConfig`/`withFallbackPrompt` threw), and was removed; a consumer that still takes `--json` declares that flag itself and prints through `printJson`. A name offered twice, an alias or custom name reusing a built-in name, or an unoffered default throws at construction (wiring). `print(format, { doc, json? }, { stream?, indent? }?)`: `Effect`; a document format goes to `Doc.print`, and `json` writes `json()` as one `Console.log` (or `Console.error`) indented by `indent` (`2`; `0` for one line), with every `##[` written as `#\u0023[` under GitHub Actions (a JSON escape that decodes to the same text) so the runner cannot read it as a command. Both thunks are built only when their format is chosen; `json` with no `json` thunk, or a value JSON cannot hold, is a defect. `printJson(value, { stream?, indent? }?)` (#1128) is that `json` half on its own, `Effect` with no requirement (GitHub Actions is read from `CurrentRuntimeEnv` when present), for a CLI that keeps a JSON flag of its own; `print` delegates its `json` format to it, so the two cannot drift. | | `CliMessage` | `success`, `info`, `warning`, `failure` and `status(vocab, name, text)`: one themed line each through `Console`, never the logger, so no log level silences them. `warning` and `failure` go to stderr; the others to stdout, and `status` defaults to stderr for a rank at or above `warning`'s. Only the glyph is painted and the text stays plain; an `agent` audience gets the glyph and text, never colour, even when the theme has colour. A `ci` audience is themed like a human, with colour still gated by `TerminalEnv`. Empty text prints the glyph alone. Every kit path that writes consumer-supplied text — `Doc.print`, `CliMessage`, the failure report — sanitises it and neutralizes it under GitHub Actions, and so do the loggers: `CliLogger` sanitises the line (with the default render; a custom `render` receives sanitised string parts and owns its own output, a colour included) and `CliLog`'s pretty line sanitises the message, component and cause before painting, and both neutralize under Actions by reading `CurrentRuntimeEnv` from the logging fiber's context (a `Logger` callback is synchronous; `fiber.context` is how it reaches a service). NDJSON is not safe merely because `JSON.stringify` escapes controls: the runner's legacy parser reads `##[` anywhere in a line, so under Actions `##[` is written as the JSON escape `#\u0023[`, which decodes to the same text. The failure report's pre-rendered lines are marked trusted so the logger does not strip the escapes the kit painted into them. | | `CliLog` | Diagnostics, kept apart from `CliMessage`. `CliLog.parseLevel(text): Option` reads a level as the layer reads its environment variable: case-insensitive, not trimmed, the spellings `all`, `trace`, `debug`, `info`, `warn` (or `warning`), `error`, `fatal` and `none`, looked up in a `Map` so an inherited key such as `constructor` is no level. `Level` is a reference defaulting to `None`, filtered on its own threshold rather than `MinimumLogLevel`. `layer({ level?, envVar?, format?, plainLogger?, logger?, extraLoggers? })` **owns the whole logger set** (`extraLoggers`, for example a telemetry logger, are kept and floored like the `CliLogger`): it builds the `CliLogger` (floored at the minimum level it had) and the stderr sink, NDJSON or pretty, and replaces whatever was installed without reading it, so there is no order to get wrong; use it instead of `CliLogger.layer`, never on top of it, and a platform that installs its own `Logger.layer([...])` replaces it silently. `level` beats `envVar` and loses to core's `--log-level`; `plainLogger: false` is the diagnostics-only mode (no plain `CliLogger`, so no level means no stderr). The requirements follow a fixed `format`: `json` needs neither `Audience` nor `TerminalEnv`, `pretty` needs `TerminalEnv`, `auto` needs both. The NDJSON line is core's `Logger.formatJson`, whose `message` is a string for one argument and an array for several. Stderr is not pure NDJSON while diagnostics are on, so a parser reads the lines that start with `{`. `component(name)` annotates a line. `neutralize` is `"auto"` by default (the logging fiber's `CurrentRuntimeEnv`, else the one captured when the layer was built, so a host-built layer neutralizes records from fibers without one; a `runtimeEnv` option, when given, replaces and beats that capture, which is invisible in the layer's `R = never`: vitest-agent A9), or `true` or `false`; the layer's own plain `CliLogger` takes the same decision as its diagnostics sink, so both lines are neutralized alike. Under `CliRuntime.main` with `env.log`, the platform is built under the run's level too (the full `CliLog` in NDJSON for `json`, and for `auto` when the build-time audience is an agent or a CI; a floored `CliLogger` otherwise, both neutralizing under GitHub Actions from the detected environment). The `file: { envVar } \| { path }` option (or `undefined`, which keeps the file requirements in `R` for a stable host type) adds an async NDJSON file sink (a queue drained by a scoped fiber, the same NDJSON line as the stderr sink in json format) that reports its first write error once (a defect counts too) and then drops further lines, and closing the scope waits at most two seconds for the drain so a hung filesystem cannot hang exit; only a layer given `file` requires `FileSystem` and `Path`. `CliLog.status(vocab, name, text, { level?, indent? })`: `Effect` (`indent`, round 2: a number of spaces or a string, sanitised and stripped of line breaks, written before the glyph on the trusted line) logs a status line on the log channel: the glyph painted with stderr's theme through `CliTheme.forAudience` (an `Audience` read with `serviceOption`), `text` sanitised, and the line marked with the internal `TrustedLine` so the plain `CliLogger` keeps the glyph's colour; the level follows the status's rank (`Error` at or above `failure`'s, `Warn` at or above `warning`'s, else `Info`) unless given. The CliLog sink's pretty line still sanitises it (bare glyph) and NDJSON JSON-escapes it. Review fix: the status glyph was raw on that trusted line (and in `CliMessage.status`), so a hostile vocabulary glyph reached an agent verbatim; `Status.glyph` now sanitises, and `StreamTheme.status`, `CliMessage` (through `CliTheme.forAudience`) and `CliLog.status` all draw through it, as `Doc`'s layout already sanitised its `StatusMark`. | | `Cancelled` | A tagged error, `reason: "escape" \| "interrupt"`, carrying exit code 130 through the runtime-marker mechanism. Its `message` is the fixed line `cancelled; nothing written` (a prototype getter, not part of the encoded form), so a consumer `render` can print `error.message`; `NotInteractive` does the same with `not interactive: run in a terminal or pass the flag`. See [one Cancelled for two engines](../decisions/one-cancelled-for-two-prompt-engines.md). | | `NotInteractive` | A tagged error for a prompt reached in a non-interactive run; exits 64. | | `CliPrompt.fallback` | `(prompt, { flag \| argument, otherwise? }) => Param.FallbackPrompt` — prompts only when `CliInteractive` is true, else returns `otherwise` (`undefined` counts as not given), else fails as a missing flag or argument built from the given name (exit 64). The prompt runs inside the fallback so a quit becomes `Cancelled` (exit 130) instead of core's missing-flag error; `Cancelled` travels as a defect, so a handler's `catchTag` cannot see it and only `CliRuntime.main` renders it as one line. Core calls it only while `TerminalCapabilities.canPrompt` is `true`, which `CliInteractive.layer` and `layerTest` hold; a program that sets `CliInteractive` with neither layer keeps core's own gate, and a piped run then fails as missing without calling it. | | `CliPrompt.gateTerminal` | `Layer`, deciding on EVERY call from the current `CliInteractive`, not at build, so a later narrowing (an audience flag under `CliAudience.runWith`) reaches it. Not interactive, it behaves as a quiet `Terminal` (input an already-ended queue, `readLine` a quit, `display` a no-op) that delegates `columns` and `rows` to the real one; interactive, the real terminal passes through. It exists because core runs `Prompt.run` even on an answered fallback, and on the real Node terminal subscribing the input attaches a readline to stdin, dropping piped bytes and putting a TTY into raw mode. `CliEnv.layer` installs it (and `gateWizard`) after `TerminalEnv` is built from the real terminal, so consumers never compose it. | | `CliPrompt.gateWizard` | A layer that drops core's `--wizard` built-in from the run when it is not interactive. | | `Doc` | The document IR, plain frozen nodes discriminated by `_tag` and built by constructors (inlines `Doc.text`, `code`, `link` (with a `suffix` option, and a missing target as its label), `status`, `path`, `strong`, `em`, `file`; blocks `heading`, `paragraph`, `line` (optionally truncating), `lines`, `list` (optionally `compact`), `table` (optionally `style: "pipe"`), `tree`, `collapsible`, `callout`, `codeBlock`, `verbatim`, `diff`, `diffText` (with `truncate`, which cuts each line to the width with the glyph ellipsis in plain and `ansi`; inside a compact list item a blank line of an item's own content keeps the item's indent there: vitest-agent A5), `section`, `counts` (with `share`, `paint` and `suffix`), `countsTable` (every zero cell shows `0` and a counter's `showZero` has no effect there, only in `counts`; a counter `label` may be `{ one, other }` (`one` at exactly 1), chosen by the counter's own `n` everywhere except the share headline, which reads by the total, the noun it counts (`1/3 repos`; round 2, reposets' ask: `counterLabel(counter, count)` takes the total there, in plain, ansi and markdown, the markdown row's header included), and a `countsTable` column is headed by `other` — vitest-agent r5 F5, ruled docs only; with `labelHeader`, and a per-row `durationMs` that adds a `Fmt.duration` column, headed `durationHeader`, summed in the total row: vitest-agent A4), and `annotation`, which only `githubLog` writes, as one escaped workflow command), and `Doc.print(doc, { stream?, format?, displayPath?, width? })`, the effectful edge: it builds the context with `Render.context`, picks the renderer (`auto`: `plain` for an agent, `githubLog` for a CI that an optional `CurrentRuntimeEnv` says is GitHub Actions and `plain` for any other, `ansi` for a human; an explicit format wins) and writes with `Console.log` or `Console.error`; a document that renders to nothing prints nothing. A status node stores a `Status.resolve` definition. See [the IR decision](../decisions/doc-ir-is-plain-data.md). `Doc.line(content, { truncate?, wrap? })`: `wrap: false` keeps a line atomic in every renderer and audience (one line whatever the width) while carrying glyphs, tokens and links, which `verbatim`'s plain string cannot; `truncate` wins over it. | | `Render` | Pure `plain`, `ansi`, `markdown` and `githubLog` renderers over a `RenderContext`, `Render.contextOf(options)` for a pure context outside Effect (escape-free by default and always for an agent, neutralizing by default for a `ci` audience; `RenderContext.linkBase` links markdown file targets to a repository URL), and `Render.context(stream, { width?, displayPath? })` to build one from `CliTheme`, `TerminalEnv`, `Audience` and `CliLinks`: the audience in force, THAT stream's colour and hyperlink support, `CliLinks.linker` as `link`, and for an agent colour `none` with an identity `paint` (an agent never gets an escape of any kind, so even an explicit `ansi` is escape-free for it), and a width that is `TerminalEnv.width()` for a human whose stream is a terminal and unbounded (`Infinity`) for a human whose stream is not one (a pipe or a file: `TerminalEnv[stream].isTerminal` false), an agent or a CI, so nothing a reader needs is cut or wrapped for a terminal that is not there (#911: a piped `path:line:col` finding used to split at a guessed 80 columns); an explicit width wins. The context also carries `neutralizeWorkflowCommands`, set whenever an optional `CurrentRuntimeEnv` says GitHub Actions, for every audience: the runner reads a line that starts with `::` or `##` as a command, so every renderer then puts a braille pattern blank (U+2800) in front of such a line (the one `neutralizeLines` that `githubLog` uses, which is idempotent, so it is never doubled). The failure report without any environment services always sets it. `Render.ansi` (for people) is built on the same walk as `Render.plain`: the same layout painted with the context's tokens and linked through `ctx.link`, and identical to plain at colour none apart from code markers and the path separator. `Render.githubLog` is plain text with a top-level collapsible as a `::group::`, nested collapsibles flattened, and any line a runner would read as a command neutralized. A group already open around the output counts as nesting too: `Render.context` reads the fiber-local keyed by `@effected/github-commands`' `WorkflowCommand.groupDepthKey`, the count `@effected/github-actions`' `ActionLogger.group` provides around a group's body, into `RenderContext.groupDepth` (set when above `0`; `Render.contextOf` takes it as an option), and at a depth above `0` `githubLog` renders a top-level collapsible as plain does, so `Doc.print` inside an `ActionLogger.group` opens no second group. The depth is read when the context is built, which `Doc.print` does at print time. What no depth fixes: the runner has one log stream, so groups written by two fibers at once interleave. The runner has TWO parsers (`actions/runner`, `ActionCommand.cs`): V2 trims .NET whitespace then looks for `::` at the start, and the legacy one finds `##[` ANYWHERE in the line (a bare `##` is no command), so neutralizing puts a braille pattern blank (U+2800) before such a `::` and inside every `##[`; a markdown heading is untouched, and under Actions a braille pattern blank (U+2800) can land inside code or table text where it would otherwise have formed a command. That neutralizing is not `githubLog`'s alone: every format does it, through the same function, whenever the context says the runner is GitHub Actions (`neutralizeWorkflowCommands`, set by `Render.context`), whoever the audience is; `githubLog` always does. `Render.markdown` (GFM, for step summaries and files) is built and verified against `@effected/markdown` as a test-only oracle: text is escaped so it cannot become markdown, and links are only emitted for a safe scheme. `Render.plain` (for agents) is built: no escape of any kind, a path joined with `>`, a link as its label plus the target in parentheses, a long URL kept whole. No JSON renderer ([decision](../decisions/no-json-renderer.md)). | | `GithubAnnotation` | `format(annotation, message)` for a GitHub workflow-command annotation: the message escapes `%`, CR and LF, a property also `:` and `,`, written in the order `WorkflowCommand` uses, because it renders through `WorkflowCommand` from the pure `@effected/github-commands` (a regular dependency: it has no shared-instance contract, so a duplicate copy is harmless): one escaping, no copy. `Render.githubLog` builds its groups with the same `WorkflowCommand` and neutralizes with `CommandNeutralizer`; the runner-command oracle in the cli tests is a separate, independent copy. | | `CliLinks` | Where a file link opens: `vscode://file/::`, `file://` or none. `auto` is `vscode` on the `vscode` terminal signal or a `.vscode/` directory at the project root (the nearest ancestor with `.git` or `pnpm-workspace.yaml`, found with `Walker.ascend`, at most 64 directories up, and `Walker.findRoot`: [decision](../decisions/cli-takes-the-walker-edge.md)); an environment variable the consumer names beats the option. `CliLinks.linker({ links, hyperlinks, audience })` is the `RenderContext.link` policy: OSC 8 only when hyperlinks are on and the audience is not an agent. `CliEnv.layer` provides it and takes `FileSystem` and `Path` from the environment when it has them, without requiring them. One link-scheme allow-list (`internal/linkScheme.ts`: `http`, `https`, `mailto`, `file`, `vscode`, `vscode-insiders` or a relative URL) serves the OSC 8 linker and `Render.markdown`, and one path-to-URL builder (`internal/linkTarget.ts`) serves both, so a file links the same way in each: a Windows drive path (`C:\x\y.ts`, `C:/x`) is absolute on any `Path` flavour and keeps its drive (`file:///C:/x/y.ts`); a colon anywhere else in a POSIX path is data and stays encoded (the one false positive is a relative `a:/b.txt`, read as drive `a`); a UNC path (`\\server\share`, `//server/share`) has no link target. The linker percent-encodes every character outside printable ASCII in a `{ url }` target without touching what is already encoded, and a bad `editorLinksEnvVar` value warns once and falls back to the option. | | `CliFailure`, `CliDoc` | `CliFailure.toDoc(cause, { render?, displayPath?, stackFrames?, spans? })` is a failure as a `Document`, and building it never throws: an error whose `_tag`, `message`, `stack`, `cause` or `issue` getter throws is drawn without that part (an unreadable `stack` as `no stack`, an unreadable `cause` ending the chain there). One run of blocks per `Cause` reason: an error that implements the `CliDoc` protocol draws itself, else the per-`_tag` `render` map, else `Cancelled` and `NotInteractive` as their fixed line, else a `Tree` of a schema error's rejected values (nested by path), else a failure status line. A defect is its message, a collapsible `stack` of the program's own frames as file links through `displayPath` (every `node:` frame, every frame with no file, and every `node_modules` frame, Effect's or any other dependency's, hidden, classified by the frame's file alone and never its function name, so a thunk V8 names by Effect's method alias stays the program's — vitest-agent r5 B1; the count follows the shown frames as `(+N internal frames hidden)`, or is `no user frames (N internal frames hidden)` when none are left — r5 F1; `stackFrames: "all"` keeps every frame — vitest-agent A3; when dropping `node_modules` frames would leave none, as for a program run from its own install under `node_modules` (a global install, `npx`, a pnpm store), only the runtime's and Effect's are dropped, so an installed CLI still shows its own frames — r4 review, fix 2), and an `Error.cause` chain as a tree. A reason that ran under spans is followed by `in: outer › inner`, read from the `Cause.StackTrace` annotation chain (innermost first). `spans` (#920) mirrors `stackFrames`: `app`, the default (following `stackFrames`' precedent), drops a span whose definition site is a file under `node_modules/@effected/` or `node_modules/effect/` (review fix: the bare `packages/effect/src/` rule is gone, since it hid any monorepo's own `packages/effect`), an `Effect.fn` call being judged by its `name (definition)` parent's site, so a kit function the program calls goes with its definition; a span with no captured stack is kept; `all` is every span, `off` no trail. The kit is identified by file, never by span name, as frames are: kit span names carry no common prefix (`ConfigFile.loadFrom`). In this monorepo the kit's own sources are not under `node_modules`, so its tests see every span as the program's. `appModule` (`CliFailureOptions`, `env.appModule`) names the running program: its package is derived lexically (through the last `node_modules/` in the path, no file system; both sides compared with `/` separators and a lower-cased drive letter, so a backslashed CommonJS frame on Windows and a `c:`/`C:` mismatch still match), and spans defined in it are kept even under `node_modules/@effected/`, so a kit tool's bin (`effected`) keeps its own command spans; nested and sibling kit packages are still dropped. The review asked for the entry to be resolved automatically from `process.argv[1]`; the root cannot read `process` or touch the file system (`boundary.test.ts`), and core's `Stdio.args` is `argv.slice(2)`, so the program names itself instead, which also avoids a realpath. The rule fails open (a linked kit, a bundle: more shown, never less), documented on `spans`. Round 2 (reposets' asks): an `Effect.fn` call and its `name (definition)` parent collapse into one entry under every setting (a lone or differently named definition frame is kept as it is); and `env.spansEnvVar` reads the setting at run time through `readSpans` in `failureTarget.ts`, exactly as `readLevel` reads `log.envVar`: `env.spans` beats it (then unread), unset or empty is the default, case-insensitive, and an invalid value logs one `VAR=value is not a span setting (app\|all\|off); ignoring it` warning. An interrupt-only cause is `interrupted`. The two issue renderers read the same rejected values, so `SchemaIssueRenderer.render` returns exactly the lines it always did, and `ConfigIssueRenderer.render` the same lines with a hint appended to an unknown key that has a near match. | | `./ui`, `./ui/testing` | Built: see the two sections below. `CliUi.live` (a scoped live view over a `Stream`, [runs and modes](../decisions/live-view-runs-and-modes.md), [tick](../decisions/live-tick-is-a-scoped-schedule.md), [never clears](../decisions/live-never-clears.md), [height clamp](../decisions/live-height-clamp-not-width.md), [logs through Ink](../decisions/live-logs-through-ink.md), [React's dev-build entries, fixed upstream](../gotchas/react-dev-performance-entries.md)) has landed (tick, degrade and non-interactive output included), with `CliUiTest.live` and `DocView`. Behind the optional peers `ink` and `react`, which the root never reaches and `./ui` loads only when a screen mounts ([subpath](../decisions/ui-is-a-subpath-with-optional-peers.md), [tier](../decisions/ui-tier-is-integrated-on-opt-in.md), [process streams](../decisions/ui-binds-process-streams.md), [Ink's colour level](../decisions/ink-colour-via-inks-own-chalk.md), [reachability boundary](../decisions/root-boundary-is-reachability.md), [declarations](../decisions/ui-declarations-reference-the-root-by-name.md)). | ### `@effected/cli-kit/ui` Optional peers `ink` (^7.1.1), `react` (^19.2.0) and `@types/react` (^19.2.0, for the declarations). Kit files hold only type imports from them; the modules are loaded on a screen's first mount, so importing `./ui`, or running a program that is not interactive, loads neither, except that an owned live view loads them to print its final frame as a string. A missing peer in an interactive run is a defect naming both. The reviewed export list is pinned in `__test__/declarations.test.ts`. | Export | Contract | | --- | --- | | `CliUi` | `run(screen, { clear? })`: `Effect`; not interactive, it fails with `NotInteractive` and loads nothing; interactive, it mounts the screen as one scoped resource (unmounted, raw mode off, cursor shown, bracketed paste off and Ink's colour level restored however it ends), Esc cancels with `"escape"` and Ctrl-C with `"interrupt"`, a throwing component or `useKeys` handler is a defect with nothing of Ink's crash screen on stdout, and screens run one at a time process-wide. A screen draws on stdout at stdout's colour level; there is no option to draw on stderr, since interactivity (`CliInteractive`) reads stdout's terminal, and a stderr screen needs it read per stream first ("human and not narrowed" apart from each stream's terminal fact), which can then add the option without a break. `clear` (default `false`) erases the last frame as the screen unmounts; without it the frame stays as a record of the answer. Nothing may log while a screen is mounted: Ink runs with `patchConsole` off, so a line written to the terminal from elsewhere tears the frame. `prompt(screen, { otherwise?, clear? })` is `run` with a non-interactive default, for a handler. It is a typed static with two overloads: a real `otherwise` (`Exclude`, `A` read from the screen) gives `Effect`, and no `otherwise`, or `otherwise: undefined` (not given at runtime), keeps `Cancelled \| NotInteractive`. The body is one implementation, widened to `never` errors under a documented cast. `fallback(screen, CliUiFallbackOptions)` (`CliPromptFallbackOptions` plus `clear`) is `CliPrompt.fallback` for screens: a `Param.FallbackPrompt` that reads `CliTheme` if present (none counts as not interactive, said once at debug level when `CliInteractive` is on), raises `Cancelled` as a defect (exit 130), and answers `otherwise` or core's missing-parameter error (exit 64) when not interactive. `lazy(load)` defers a screen's module to its mount. `map(screen, f)` is a `Screen` from a `Screen`: it passes the inner screen a control whose `resolve` applies `f` and whose `cancel` is the outer one untouched, so a `Confirm` backs a `Flag.Boolean` fallback with no hand-written adapter; data-first only, like every `CliUi` static. `context` is `Effect`: stdout's theme and glyph set for a tree the kit did not mount, loading Ink and React on the way so `UiProvider` can render. | | `CliUi.live`, `LiveOptions`, `LiveHandle` | `live({ events, initial, reduce, render, isStart, isTerminal, mode?, tickMillis? })`: `Effect, never, Scope \| CliTheme>`. It returns its handle without waiting for Ink: Ink and React load at the first run's mount (or the first owned print), and `close` before any mount is safe and drains. It makes the first pull of `events` before returning (the drain is forked with `startImmediately`, because a `PubSub`-backed stream subscribes on its first pull: `Channel.unwrap` is lazy), so `Stream.fromPubSub` is subscribed by then; a stream that forks its upstream (`merge`, `buffer`, a concurrent `flatMap`) subscribes later and loses what is published before, so the certain form is `PubSub.subscribe` first, passing the `PubSub.Subscription` itself as `events` (taken as `Stream.fromSubscription` takes it, ending when its `PubSub` is shut down); folds them in a fiber of the caller's scope, and draws runs on `UiStreams` when interactive: a run begins at `isStart` (or where an optional `begins(event, before, after)` says, for a consumer that joins mid-run; an event outside a run that begins none is folded and not drawn, so post-run events never mount a second copy), ends at `isTerminal` with Ink's own unmount (its frame committed, never `clear()`), and a start while drawn redraws in place. Each run holds the mount permit, `withInkColour` and its Ink instance in a scope of its own (released at once if the mount fails partway), so a `CliUi.run` during a run waits; closing the caller's scope runs one finalizer that interrupts the drain first and then ends the run drawn, so nothing is folded or drawn during the close. The tree is `ErrorBoundary > providers > console bridge > height clamp (rows - 1, from`useTerminalSize`, no width; the content keeps its own height,`flexShrink: 0`, and is clipped, never squeezed into a sample) > Holder > render(state, frame)`; a push swaps the Holder's element and waits for React's commit, resumed on a microtask so the controller never runs inside the commit (where a frame that threw is not yet reported), before the next event or the unmount. Clearing a run and closing its scope is one uninterruptible step, so an interrupt between them can never orphan the permit, the instance or the tick. No input is mounted. `LiveHandle` is `state`, `logConsole` (the bridge: lines above the frame while drawn), `printAbove(stream, line): boolean` (#963: the bridge's attached check and Ink's writer in one synchronous step; `false`, writing nothing, when no `Bridge` is attached, so between runs, before the first, after `close`, in a degraded run and whenever not interactive; chosen over an `isAttached` query because a query and a later write can straddle a run's unmount, and sync rather than `Effect` because its caller is a Node stream's `write` callback, as `logConsole` is sync; `true` means Ink's writer took the line, which Ink drops while a render has suspended the terminal with `useApp().suspendTerminal`, as it drops `logConsole`'s; each stream's routing and the degraded-run `false` are pinned in `CliUiTest.live.write.test.ts`), `done` and `close`. `close` (once, `Effect.cached`; later calls wait on the same end) interrupts the pump, then posts `Ended`; on any `Ended` the controller first takes what a subscription still holds (`PubSub.remainingUnsafe`, then `takeUpTo` without waiting, plus an ended PubSub's final message if not yet taken; a shut-down subscription is never asked, since a take from it interrupts) and folds it, then ends the run as the events ending does. A subscription is taken from directly, never through `Stream.fromSubscription`: each step is `uninterruptibleMask` around `restore(PubSub.takeAll)` and the inbox offer, under `PreventSchedulerYield`, so an interrupt can land only while it waits and a taken message is always in the subscription or the inbox (a test sweeps `MaxOpsBeforeYield` 3-18; through the stream machinery the tail was lost at 7, 8 and 13-18, and without `PreventSchedulerYield` at 3). The step is end-aware: `PubSub.end`'s final message is sticky in core (every later take returns it), so once `Subscription.ended` is `Some` the step takes the buffer and the final message once and ends; a take interrupted by the subscription's shutdown ends the events too. A plain stream keeps the masked `Stream.toPull` pull, made in the caller's scope; a chunk in flight inside the stream's own machinery can still be lost to a yield there, which is the stream's concern. `PubSub.shutdown` drops a subscriber's unread messages (pinned), so `close` or `PubSub.end` is the lossless end. `close` dies as `done` dies, except that after the caller's scope closed (interrupt only) it completes. One controller fiber owns every transition, fed by an unbounded inbox it drains with `Queue.takeAll` (event chunks queued together are folded as one and drawn once; a source that applies backpressure buffers there while the view draws): a pump of event chunks, which also reports the stream ending or dying (a dying stream unmounts the run, then `done` dies with its cause), the run's tick (`Schedule.spaced(tickMillis)` forked into the run's scope, carrying `floor(Clock.currentTimeMillis / tickMillis)` from when it fired; a `tickMillis` that is not positive and finite is a defect) and render-failure wake-ups. A failed render or mount degrades the run: unmounted first (an inner boundary draws the last good frame in place of the one that threw, so that frame stays), then one `Effect.logWarning`, the fold going on; a degraded run that never painted prints its final frame once at its terminal event; a render that throws only as the run ends is warned once at its end, after the unmount; a start during a degraded run ends it and mounts a fresh run. A throwing `reduce` unmounts, then `done` dies. Not interactive: `owned` prints each run's final frame once via `renderToString` at stdout's width (80 when unknown) with an unbounded `rows` size override (`useTerminalSize().rows` is `Infinity` there), loading Ink only then, escape-free at colour `none` and for an agent `Audience` when one is provided (read with `serviceOption`, so `Audience` is not in `R`): the tree is given the audience's theme, `CliTheme.forAudience` (public since #918; it was the internal `CliTheme.forAudience`) (colour `none`, identity `paint`, empty `sgr`, unpainted `status` for an agent), the same function `Render.context` takes its colour and `paint` from, so `useTheme`, `Styled` and the widgets' colour-`none` markers agree; `CliUi.run` and `CliUi.context` apply it too; `hosted` prints nothing. The frame index is monotonic: a stale tick never steps the spinner back. If the last good frame throws too, the run counts as unpainted and its end prints the string. Since #908: `LiveOptions.final?: (state) => Document`, given, makes an owned, not-interactive run print `final(state)` once per run at its end (replacing the Ink string, never both), rendered through `Render` with the renderer `autoFormat` picks and `Render.context("stdout")` when `TerminalEnv`, `Audience` and `CliLinks` are all in context (else `Render.contextOf` from the stdout theme and the optional `Audience`, unbounded width), and written through the console bridge to `UiStreams` stdout rather than `Console`, so `R` stays `Scope \| CliTheme` and `CliUiTest.live`'s transcript shows it; a throwing `final` degrades the run (`warnOnce`). `CliUi.lazyView(load)` (internal `ui/internal/lazyView.ts`; `load` resolves to the view itself or a module whose default export it is, so a named export needs no shim) returns a `render` carrying its loader under `Symbol.for("@effected/cli-kit/ui/lazyView")`: `loadView` awaits it before a mount builds its first element and before `printFrame`, a failed import degrades the run and is retried by the next (review fixes: `pick` takes a function, else a function `default`, else throws a descriptive `LazyViewShapeError` naming what was received; a rejected IMPORT clears the shared load so the next run, and the run's own end, retry, so a transient failure still prints that run's frame; a SHAPE error is deterministic and stays the handle's one rejected load, and `CliUiLive` warns about each `LazyViewShapeError` once per handle by identity, so a watch session does not warn per run), and calling the render before load throws. `render` stays required and its type unchanged, so a consumer passes either a component or a thunk (vitest-agent's request); a `view` option beside `render` was rejected because `LiveOptions["render"]` would have turned optional, breaking `exactOptionalPropertyTypes` consumers. A live view never renders in Ink's debug mode (#917). | | `CliUi.liveDetached`, `DetachedLiveOptions`, `DetachedLive` | `liveDetached(options, env)`: a live view hosted by code not built on Effect (a test runner's reporter, a bundler plugin, a build hook). It runs `CliUi.live` on a fiber of its own, under `env` (a `Layer` the host builds; under Node `CliEnv.layer().pipe(Layer.provide(NodeServices.layer))`, in a test `CliEnv.layerTest` with a session's layer) in a scope of its own, and returns at once. `events` is a `PubSub` (subscribed before return, in the view's scope, so the first event published after the call is not lost) or a `Stream`. `render` is `live`'s render, or an `Effect` that makes it, run once under `env` before setup, so `CliLinks` or `TerminalEnv` come from the same build (a render effect that dies is a failed setup). `DetachedLive` is `{ handle, printAbove, close, exit }`: `handle` resolves to the `LiveHandle` (a handled rejection on a failed setup); `printAbove` is `false`, writing nothing, before setup, with no frame mounted, and from the moment `close` is called; `close()` stops `printAbove`, awaits setup, folds every message still queued in the subscription, commits the last run and closes the scope, is idempotent and never rejects; `exit` says how the view ended. **Shut the `PubSub` down only after `close()` resolves**: a shutdown before it drops the queued tail. | | `CliUi.routeStream`, `RouteStreamOptions`, `RoutedStream` | `routeStream(original, printer, { stream, maxHeld?, carriageReturn?, onText? })`: a `Writable` to hand a writer the program does not own (a child's stderr, an in-process test runner or bundler) in place of a terminal stream. Each complete line is offered to `printer` (usually a live view's `printAbove`); a `false` writes it, with its line break, to `original`. Every write is decoded as UTF-8 across writes, and everything reaching `original` is the decoded text, so a character split between two writes arrives once and whole. Text without a line break is held until one comes, until `flush`, or past `maxHeld` characters (8192; a non-negative integer, else a `RangeError`), when it is offered as its own line. A write of nothing but escape sequences goes straight to `original` when nothing is held. `carriageReturn: "last"` keeps only the text after a line's last `\r` (a redrawn progress bar). `onText` taps every decoded write. `RoutedStream` is `{ writable, route(on), flush() }`: `writable` reports the original's `isTTY`, `columns`, `rows`, `getColorDepth`, `hasColors` and `getWindowSize` where present; `route(false)` writes the held text and passes later writes straight through; `flush()` (and `writable.end()`) offers the held text and ends decoding, an incomplete character becoming U+FFFD, so a last line without a break is never lost. A printer that throws fails the write. Its `node:stream` import is one of the three files of [the `./ui` Node licence](../decisions/ui-binds-process-streams.md). | | `Screen`, `ScreenControl`, `CliUiRunOptions`, `CliUiPromptOptions`, `CliUiFallbackOptions` | A `Screen` is `(control) => ReactElement \| Promise`; `ScreenControl` is `resolve(value)` and `cancel(reason)`, first call wins. Text from data in a screen's own components (Ink's `Text`, `Styled`) is the screen author's to sanitise. | | `UiStreams`, `UiStreamsShape` | A `Context.Reference` of the stdin, stdout and stderr a screen binds to, the process streams by default ([decision](../decisions/ui-binds-process-streams.md)). | | `UiKey`, `KeyName` | The kit's own key model: `Named` (`up`, `down`, `left`, `right`, `enter`, `escape`, `space`, `tab`, `shift+tab`, `backspace`, `delete`, `home`, `end`, `pageup`, `pagedown`, `ctrl+c`) or `Char`. `UiKey.fromInk(input, key)` normalises Ink's input. | | `KeyTable`, `Binding`, `KeyHelpRow`, `useKeys`, `UseKeysOptions` | A widget's keys as data, the one source for dispatch and help: `make(bindings)` (first binding wins), `match(key)`, `help(glyphs)`, and `KeyTable.root` (Esc and Ctrl-C). `useKeys(table, dispatch, { isActive? })` is one Ink `useInput`; text read in one go is split into a key per grapheme (CR LF one enter), a `{ char }` binding matches in NFC, a bracketed paste never reaches it (the screen takes pastes on Ink's paste channel; `TextInput` reads them as text), and several keys from one read are dispatched before React re-renders, so a handler steps from current state ([gotcha](../gotchas/ink-delivers-a-chunk-of-keys-before-rerender.md)). Ink calls input handlers outside React's error boundary, so inside a screen a `dispatch` that throws is caught and ends the screen as a defect, as do the kit's own paste handlers; a consumer's raw Ink `useInput` or `usePaste` is not guarded. | | `KeyHelp`, `KeyHelpProps` | The help line from key tables, merged with the root keys and cut to the width with the root hint pinned. | | `Styled`, `StyledProps`, `inkProps`, `InkTextProps`, `useTheme`, `useGlyphs`, `useTerminalSize`, `useStyle`, `TerminalSize` | The theme bridge: `useStyle(token)` is the hook a component takes to honour the theme, the Ink `Text` props for a token resolved through the mounted screen's theme (a consumer's overrides and the test marker palette included, none at colour `none`), where `inkProps(Token.resolve(token))` resolves against the default palette and ignores the mounted theme; `inkProps(style, color?)` maps a `Style` to Ink `Text` props (none at colour `none`; with `color` omitted, for an Ink tree the kit did not mount, every prop is emitted for Ink's chalk to gate: vitest-agent A7), `Styled` paints a token through the mounted screen's theme (its children drawn as given), and the hooks read the screen's `StreamTheme`, `GlyphSet` and usable terminal size (a width or height reported as 0 or not at all is unknown and reads as 80x24 before the one-cell margin: a pty `script` opens reports `0 0`, which drew every row as a bare ellipsis, okfit O1; `TerminalEnv.layer` already maps a 0 width to `None`. This is NOT Ink's fallback chain, which asks `terminal-size` (tty, `COLUMNS`, `tput`) before 80x24: `./ui` reads no `process`, so on a 0x0 pty with `COLUMNS=50` Ink lays out at 50 while the kit cuts rows at 79). | | `UiProvider`, `UiContextValue` | `UiProvider({ value, children })` gives an Ink tree the kit did not mount the context `useTheme`, `useGlyphs`, `Styled` and `useTerminalSize` read; take `value` from `CliUi.context`. `UiContextValue` is `{ theme, glyphs, size?, displayPath? }`. `displayPath` is how a `DocView` under it shows an absolute path: `CliUi.context` sets it from the run's `env.displayPath`, so a frame shows a path as `Doc.print` and a live view's `final` do; absent, a nested provider keeps its parent's, and with none a path is shown as given. With `size`, `useTerminalSize` reads it instead of the stdout (less one column and one row as ever), which `renderToString` needs because its terminal hooks see the process's own stdout whatever width it lays out at (probe L1). There is no screen under it: `useScreenCancel` does nothing and a kit widget's input handler is not guarded. `CliUi.run`'s screens are wrapped by the same internal provider. | | `DocView`, `DocViewProps` | The `Doc` IR as Ink rows, laid out by the kit's own renderer (strategy S1, string passthrough): the whole document (or one block, as a one-block document) through `Render.ansi`, or `Render.plain` at colour `none`, split into one `Text` row per line with `wrap: "truncate-end"` (Ink never re-wraps; an empty line is a one-space row), in a `flexShrink: 0` column so a clipping parent shows the first rows. A collapsible is open and an annotation skipped, as in the static renderers, so a static report and a live view show a document byte for byte alike (pinned against `Render.plain` for a table, counts, a tree, a diff and a code block). Without `ctx` it builds a `RenderContext` from the tree's theme (its own `paint`, so token overrides hold; colour; glyphs; for an agent the audience-adjusted colourless theme), width `useTerminalSize().columns`, a human audience, links off and the tree's `displayPath` (the run's `env.displayPath` through the screen context or `UiContextValue.displayPath`, the identity outside one): the public `RenderContext` shape, so the root's surface and `R` are unchanged. Under the GitHub Actions runner (`CurrentRuntimeEnv`, read with `serviceOption` through the shared `underGithubActions` by `CliUi.run`, `CliUi.live` and `CliUi.context`, and carried in the screen context and `UiContextValue.neutralizeWorkflowCommands`) the built context sets `neutralizeWorkflowCommands`, so text from data never forms a workflow command; the live view also neutralizes a frame it prints as a string whole, a consumer's raw `Text` included. A `ctx` prop replaces that entirely, neutralizing included, and needs no provider. The layout is memoised (`React.memo` and `useMemo`) on the document's identity and the context. | | `Viewport` | A pure reducer over a window of items (`init`, `step`, `resize`, `keys`) and `View`, which never draws more lines than fit (so Ink never clears the scrollback), re-emits a section header scrolled off the top, clips each row to one line, and dies on a repeated item key. | | `Select`, `TextInput`, `MultiSelect`, `Confirm`, `Toggle`, `Tabs` | Each a pure `init`/`step` (or `step` alone), a `keys` table, a `View`, and, except `Toggle` and `Tabs`, a ready-made `screen(options)`. Every string a widget draws from data (message, label, detail, placeholder, validation message, section title, toggle and tab label, tab separator, key help) is sanitised as `Fmt.sanitize` does and its line breaks folded to spaces before it is measured or cut, so data cannot paint colour at colour `none`, plant a hyperlink, or add a row the height budget did not count (which would make Ink wipe the scrollback). `Select` resolves the chosen value and skips disabled choices, which end in a `(disabled)` mark at colour `none`, where muted paints nothing; `TextInput` edits one line by code point, validates on submit, and types text read in one go as it reads; `MultiSelect` resolves the selected values in section order, with unique keys across sections; `Confirm` resolves `{ confirmed, toggles }` (`toggles` partial by key), its toggles scrolling in a window; `Tabs` is a controlled or uncontrolled component for a consumer's screen, with Tab and Shift-Tab cycling, digits jumping, `columnKeys` for a column, and brackets marking the active tab at colour `none`. The state, action, option and props types are exported beside each. `TextInput`'s `mask?: string \| true \| ((value) => boolean)` (#916; the predicate, round 2, is asked with the real value and LATCHES (a `useRef` in the View) from the first render it answers true until the value is empty: review found an unlatched predicate redrew `hp_SECRET123` in clear after home+delete; the advice is a giveaway anywhere, `/gh[pousr]_\|github_pat_/`, since a prefix match never masks `op://v/` plus a pasted token; a no-latch mutant turns the home+delete test red) draws one mask per grapheme (`Intl.Segmenter`), `•` for `true` (`*` under ASCII glyphs), a string through `lineText`; only the drawing changes: `validate`, the cursor and the result use the real text, and the placeholder is unchanged. No reveal key: not trivial beside paste handling, so left out. Review fix: the cursor now moves and deletes by grapheme (`Intl.Segmenter`, contained to `TextInput`'s `previous`/`following`), and the mask counts come from one segmentation of the whole value, graphemes starting before the cursor then the rest, so they always total the value's graphemes; a `validate` message is drawn unmasked (documented). | ### `@effected/cli-kit/ui/testing` | Export | Contract | | --- | --- | | `CliUiTest.render` | `(screen, options?) => Effect, never, Scope>`: mounts one screen on in-memory streams under a marker-palette theme, with Ink in debug mode, and returns once it has drawn. Options are `columns`, `rows`, `color`, `glyphs` and `interactive`. A crash (a thunk or a component that throws, a classic-JSX `React is not defined` included) is never swallowed: `result` dies with it and so does the next read, key, resize or rerender (vitest-agent r5 B2). The guard lives once in `makeTerminal`'s `screen`, which `render`, `view` and a session's screens all build on; the run's `onMount`/`onUnmount` bracket now spans the whole run, so a thunk that throws before Ink draws still has a capture, and `onUnmount` carries the defect. | | `CliUiTest.view` | `(element, options?) => Effect`: mounts a display-only element (a status line, a live view) under the same harness as `render` (marker theme, fake streams, debug frames), wrapped in the kit's providers so `useTheme`, `useGlyphs` and `Styled` work in it; its handle has the frame readers, `press`/`type`/`chunk`, `resize` and `rerender(element)` but no `result`, since a display-only element never ends on its own (vitest-agent A10). With no `result` to re-raise how its run ended, a crash or a refusal (`interactive: false`, `NotInteractive`) is surfaced instead: `view` dies with the error when it happens before the first frame, and otherwise the next read, key, resize or rerender does, never a silent empty frame or the misleading "screen has ended" defect (r4 review, fix 1). A deliberate end (Esc or Ctrl-C, a `Cancelled`) is not a crash: the frames stay readable and only a later key, resize or rerender dies, saying the screen has ended (fix round 2, R2). After a crash every read dies with it, `frames` included, so the frames drawn before it are not readable (R3). `render` and `view` share one mount helper over `makeTerminal`. | | `CliUiTest.live`, `CliUiTestLive` | `(options) => Effect, never, Scope>`: `CliUi.live`'s options without `events` plus the terminal's (`columns`, `rows`, `color`, `glyphs`, `interactive`). It mounts the live view on the PRODUCTION render path (Ink interactive, not debug) over an in-memory terminal whose stderr is its stdout, as on a tty. The handle has `publish(event)` (offers to the view's stream and settles like a key press), `end` (ends the stream and joins `done`, dying with what the view died of), `advance(duration)` (`TestClock.adjust`, which fires the run's tick, then settles: live tests use `it.effect`), `resize`, `frame`/`rawFrame`/`plainFrame`/`frames` (each frame is Ink's write after a render without its erase moves; a write of moves alone is Ink clearing for a log line, not a frame), `transcript` (what the terminal shows, scrollback included, through the shared terminal model `ui/testing/terminalModel.ts`, which the kit's own production-path tests import; it applies Ink's erases and its clear-terminal `ESC[2J`/`ESC[3J`/`ESC[H` against the terminal's rows, so a scrollback wipe shows as the loss of what was above the frame), `written` (every raw byte, the place to assert no `ESC[3J`), `stdoutWritten`/`stderrWritten` (each stream's bytes alone: Ink's erase and repaint around a line logged above the frame go to stdout whichever stream the line is for, so a line's stream is asserted here), `write(stream, bytes)` (#964: raw bytes to the fake stdout or stderr, past Ink and with no settle, so a test reproduces a foreign line under the frame; at the next redraw the terminal model shows the frame's top row stranded and the line erased, the control `CliUiTest.live.write.test.ts` pins beside the `printAbove`/`logConsole` fix) and `handle` (the `LiveHandle`). Frames are best-effort (an unchanged or empty render adds none, and a write after a run's unmount is never one); `transcript` and `written` are authoritative, and with `interactive: false` the printed strings show only there. `advance` needs `it.effect`'s `TestClock`; under `it.live` it dies. vitest-agent's eight live-view behaviours are pinned against it, each with a mutation that fails it. The harness mounts its production path with Ink's `maxFps: 1000` (internal `UiRenderOverrides.maxFps`): Ink 7 throttles renders and log writes to 30 fps by default, a trailing ~33 ms timer, so a second render right after a leading one landed after the settle (8 ms trailing quiet, then only timers already due) and a test read the previous frame under load (the flaky `CliUiTest.live` frame-index test). Every consumer of `CliUiTest.live` and of `session({ renderPath: "production" })` gets the same fix; `CliUiTest.throttle.test.ts` pins the option. | | `CliUiTest.cancelReason` | `(exitOrCause) => Option<"escape" \| "interrupt">`: pure; finds a `Cancelled` in an `Exit` or `Cause`, typed or as a defect, matched by shape (`_tag` and `reason`) so a copy of the class bundled into this entry still matches, so a test never walks `cause.reasons` (okfit O2b). | | `CliUiTest.session` | `(options?) => Effect` for a program that runs several screens: `layer` (fake streams, theme, `CliInteractive`, frame capture and a capturing `Console`; anything the program provides closer to its screens, `CliEnv` under `CliRuntime.main` with `env`, wins), `next({ contains? })` for each screen as it mounts (2 s cap, a defect naming what it waited for), `mounts`, `stdout` and `stderr`. Its TSDoc carries the recipe for driving a whole `Command` handler (the session's `layer`, a fresh `CliExit.layer`, a sandboxing `ConfigProvider` for `HOME`/XDG and the platform, forked, then `next`), pinned by a kit test, and says `mounts === 0` is the "nothing mounted" assertion, a test that itself sleeps needs `it.live`, and debug frames show neither `clear` nor the final scrollback (okfit O2c, O2e). A screen that crashes makes `next` die with the crash, whatever `contains` waited for, or else its next read, key or resize does; `mounts` counts a run whose thunk threw before Ink drew (r5 B2). Since #917 it also has `transcript` (the terminal model, `screenAfter`, over everything written to `UiStreams`) and `written` (every byte), stdout and stderr merged in write order as on a terminal, so lines a handler's live view writes through `handle.logConsole` are observable (review fix: the fake streams stay two streams with a combined log, `fakeStreams.written`, and the session also exposes `stdoutWritten`/`stderrWritten`, so a line on the wrong stream is catchable, and `stdoutTranscript`/`stderrTranscript`, each stream's bytes through the same `screenAfter` pipeline as `transcript`, for per-stream text assertions free of paint breaks; `CliUiTest.live` has no per-stream accessors); a live view never renders in Ink's debug mode (`CliUiLive` no longer reads `UiRenderOverrides.debug`), so in a session it runs on the production path; `onMount(kind)` tells the harness whether a screen or a live run mounted, and each capture reads writes by its own mode. `CliUiTestSessionOptions.renderPath: "debug" \| "production"` (default `debug`) puts screens on the production path too, which makes `clear: true` observable in `transcript`. Round 2 (reposets' ask 6): `layer` stays `Layer`, which is honest: `UiStreams`, `CliInteractive`, the capture and `Console` are `Context.Reference`s with defaults, so they can never appear in a requirement and a type cannot carry them; the TSDoc instead states the ordering loudly (provide it closer to the program than a presentation layer whose values it should replace; shadowed, it fails quietly to the defaults). | | `CliUiTestScreen`, `CliUiTestHandle`, `CliUiTestView`, `CliUiTestSession`, `CliUiTestNextOptions`, `CliUiTestOptions` | A screen handle: `press` (named keys, or `{ char }` items typed as `chunk` sends them; a bare string that names no key dies naming `type(...)` and `{ char }`, never a Node stream error: okfit O2a), `type`, `chunk` (keys or characters in ONE stdin write, which `press` can never show), `resize`, `frame` (token markup), `rawFrame`, `plainFrame`, `frames`; a key for a screen that has ended is a defect. `render`'s handle adds `rerender` and `result`; `view`'s adds `rerender(element)` only. | | `CliUiTest.styled`, `CliUiTest.serializer` | ANSI decoded back to token markup, and a Vitest snapshot serializer that prints it. Since #909 the serializer is also the default export of its own subpath, `@effected/cli-kit/ui/testing/serializer` (`src/ui-testing-serializer.ts`, built as `ui-testing-serializer.js`), so a consumer registers it with Vitest's `snapshotSerializers` config and no shim file; the root `vitest.config.ts` registers it that way for this package's own project, and the `./ui` boundary test counts the entry as a testing module. Snapshots are the one place a test here uses `expect`. | ### `@effected/cli-kit/testing` | Export | Contract | | --- | --- | | `CliTest.sandbox` | `Effect`. A temporary directory with a fresh `HOME` and `XDG_{CONFIG,DATA,STATE,CACHE}_HOME`, and `NO_COLOR=1`. `PATH` is taken from an injected value and never inherited through `extendEnv`. | | `TestTerminal.make` | `(options?: { columns?, rows?, forbidInput? }) =>` an `Effect` of a `Terminal` layer with `input(keys)`, `type(text)`, `end`, captured `output`, and `resize(size)`. With `forbidInput`, `readInput` and `readLine` die with a message saying this path must not read the terminal, where the default double hands back an empty queue (a stray read hangs) or quits `readLine`, so a test can prove an agent or CI path never prompts; `size`, `columns`, `rows`, `display` and `resize` behave as ever. It implements core's `Terminal.size`: each subscription gets the current size, then every resize, and `columns` and `rows` read live. A hand-built `Terminal.make` double must supply `size` too. Core's own mock terminal is test-only and unexported; this one drives core `Prompt` and `CliPrompt.fallback` in tests. | | `CliTest.run` | `(bin, args, { sandbox, execPath, cwd?, env?, stdin?, forceKillAfter?, expectExit? }) => Effect<{ exitCode; signal; stdout; stderr }, PlatformError \| CliTestFailure, ChildProcessSpawner>`. `expectExit` is the exit code the run must end with; any other ending, a signal included, fails with a `CliTestFailure` whose message carries the code, the signal and the child's stderr, and omitted, a non-zero exit is data. A child a signal ended is data too: `exitCode: null` and `signal` (`SIGTERM`, `SIGKILL`), else `signal: null`. Core's handle fails `exitCode` for a signalled child and names the signal only in the error text (`Process interrupted due to receipt of signal: '…'`), so `CliTest` reads it back out of that text; any other `exitCode` failure stays a failure. A test pins the wording, so a change upstream goes red rather than silently failing again. Two deliberate differences from the original design: there is **no `path?` option** (`PATH` is fixed once by `CliTest.sandbox({ path })`, and a per-run override goes through `env`, which merges over the sandbox environment), and it **scopes itself** (`Effect.scoped` around the spawn), so `Scope` is not in `R` and a caller need not wrap each run. A non-zero exit is data, not a failure. Spawns `execPath` with `[bin, ...args]` over core `ChildProcess` (D9), no peer on `@effected/commands`. **When `stdin` is omitted OR passed as `""`, the spawned child receives an already-ended empty input, never an open pipe** — a test that does not pass `stdin` never hangs waiting for one. | | `CliTest.spawn` | `(bin, args, RunOptions) => Effect` (#1120): starts the bin and returns at once, for a `--follow` or watch command `run` would wait on forever. `SpawnedBin` is `{ stdout, stderr, kill, exitCode, result }`: each stream is the child's lines (`\r\n` split off, an unterminated last line at the end), captured into a `SubscriptionRef` from the first byte so every reader replays from the start and a stream nobody reads is still drained (a child writing more than a pipe buffers never blocks); `kill(signal?)` is core's handle `kill` with `killSignal` and `forceKillAfter`, which waits for the exit, and a failed kill on a child whose exit has landed (`isRunning` false) succeeds: core fails a kill once nothing is left to signal (its process-group recovery swallows only `EPERM`, so `ESRCH` falls through to Node's `kill`, which answers `false` for an exited child), so a cleanup `kill()` after a short-lived child exited failed on a race (PR #1151 review); a kill that fails on a running child keeps its `PlatformError`; `exitCode` is `null` for a signalled child (the default `kill` included), never a failure; `result` waits for the exit and both streams and returns a `RunResult`. The child lives in the caller's scope, so a test ending first kills it. `forceKillAfter` (`RunOptions`, `2 seconds` by default, a finite non-negative `Duration.Input` or the call throws a `RangeError`) goes on the command, so the scope's release and `kill` both send `SIGKILL` to a child still running that long after `SIGTERM`: without it core's release waits on such a child with no limit, uninterruptibly, so no `Effect.timeout` cut it short and the child was left behind (runtime review). Same entrypoint rule as `run`: `./testing` only, pinned by `entrypoints.test.ts`. | See [D9: `CliTest` uses core `ChildProcess`](../decisions/cli-testing-uses-core-child-process.md) for why this subpath takes no dependency on `@effected/commands`. ### CliLogger, and why it does not need `Stdio` The obvious design — write through `Stdio`'s `stdout()` / `stderr()` sinks — does not fit: `Logger.make(log)` takes a synchronous callback, while a `Sink` write is an `Effect`, and a logger cannot `yield*`. The sanctioned path is the one core's own `defaultLogger` takes: read the `Console` reference off the fiber, synchronously, and route the write based on the log level. Levels are compared ordinally, never by string equality — `LogLevel.isGreaterThanOrEqualTo(logLevel, stderrFrom)`, never `logLevel === "Error" || logLevel === "Fatal"`, which hard-codes two names and silently misses any level added upstream above `Fatal`. **`stderrFrom` defaults to `"All"`** ([D3](../decisions/cli-logger-defaults-all-to-stderr.md)): every log level routes to stderr unless a consumer narrows it explicitly, so a CLI's stdout carries only what the program writes with `Console.log` — never a diagnostic `Effect.logInfo` line a consumer never chose to print as output. This is a breaking 0.x change; the changeset says so. Any consumer relying on the old `"Error"`-only default now sees `Info`-level log lines move to stderr. `Console.Console` is a public `Context.Reference` with `globalThis.console` as its default value, so nothing is imposed on the consumer's layer stack, the stderr/stdout split is directly expressible as `console.error` versus `console.log`, and the surface is testable by construction — swapping the reference is how `TestConsole` already works. `References.LogToStderr` is a public reference too, and `CliLogger` honours it only as a force-all-to-stderr override, never as a per-level one — a consumer who sets it meant "this whole program's output is diagnostic". ### CliRuntime — wrap the reporting, not the runtime The failure in motivation 2 is *where the report happens*, not that `runMain` exists. The fix is to catch inside the effect, render through the program's own logger, and set the exit code — all before any `runMain` is called. This package provides a combinator applied inside the program, and the consumer still calls their platform's `runMain` themselves: ```ts NodeRuntime.runMain(program.pipe(CliRuntime.reportFailures, Effect.provide(MainLive))) ``` Wrapping `runMain` itself would drag a platform choice into a library that has no business making one, and would make the package unusable from Bun or Deno for no gain. ### Findings are success, exit codes still reach teardown A handler that reports findings — validation errors, lint violations, any result a program needs to surface with a non-zero exit but that is not itself a crash — *succeeds*, and calls `CliExit.set(code)` to record the code it wants. `CliExit` is a `Context.Service` holding a `MutableRef`, not a `Reference`: forgetting to provide it inside `CliRuntime.main` is a type error, not a silently-ignored global. On success, `main` reads the cell; if it is non-zero, `main` turns the success into a failure carrying a private sentinel, marked with `CliRuntime.reported(sentinel, code)`. This exists because `process.exitCode` cannot be trusted to reach teardown. Node's `runMain` skips `process.exit(0)` on success — it calls `process.exit` only when the fiber received a signal or its own exit code is non-zero (`@effect/platform-node-shared` `NodeRuntime.ts:58-65`) — so a handler that only sets `process.exitCode` on an otherwise-successful fiber relies on Node's own process-exit machinery to eventually notice that field, well after Effect's own finalizers had their chance to run. Turning the non-zero code into a failure instead routes it through core's `defaultTeardown` on any runtime, exactly like an ordinary error, so finalizers run before the process exits with the recorded code. `main` packages no numeric taxonomy beyond 64 ([D7](../decisions/usage-exit-code-defaults-to-64.md)) and 130 (signal interrupt); codes 1 to 3 stay each consumer's own to assign. ### `reportFailures` never renders `ShowHelp` `Command.runWith` already printed the help text or the parse errors before a `ShowHelp` reaches `reportFailures` (the `ShowHelp` `catchFilter` in `runWith`: `Command.ts:1996-2001` in the vendored `.repos/effect` tree) — rendering it a second time is what produced the stray "Help requested" line every consumer previously worked around by hand. `reportFailures` now never renders a `ShowHelp`, and never renders the `CliExit` sentinel either. Nor does it render a `CliError.UserError` `runWith` already printed (`showUserError` flips its `Runtime.errorReported` mark to `false` after printing); that one exits with `usageExitCode`. The same holds for any handler failure carrying a `CliError.userMessage`: `runWith` renders it and flips the mark too, keeping its tag, so `reportFailures` skips it, but it exits as a handler failure (`exitCodes` by tag, then `exitCode`), not with `usageExitCode`. Under `renderErrors: false` the mark stays `true` and the error renders normally. It still renders every other `errorReported: false` error (one with no `userMessage`): `effected schema`'s `GateError` summary relies on that render path staying intact. A `ShowHelp` that carries errors is remapped to `usageExitCode` ([D7](../decisions/usage-exit-code-defaults-to-64.md), default 64); a bare `--help` invocation (`ShowHelp` with no errors) keeps exit 0. ### The renderers `SchemaIssueRenderer` wraps `SchemaIssue.makeFormatterStandardSchemaV1` rather than reimplementing it. Its job is discoverability, deduplication — a three-member union otherwise prints the same unknown-key line three times, once per member — and one phrasing override: core's `UnexpectedKey` message is `"Expected no excess property"`, which describes the schema's rule rather than the user's mistake, so it is rewritten to `unknown key "rulesetz"`. `ConfigIssueRenderer` is the same treatment for `@effected/config-file`'s `ConfigValidationError`, whose `issue` tree is the same shape. It takes the structural `ConfigIssueSource`, so this package names nothing from `@effected/config-file` and carries no peer on it: a real `ConfigValidationError` is assignable, and rendering stays at the boundary. ## Decisions settled against core's source See the linked Decisions for full reasoning: - [the exit code is set through core's own error markers](../decisions/cli-exit-code-via-runtime-markers.md) - [`CliLogger` honours `LogToStderr` in one direction only](../decisions/cli-logger-force-all-stderr-only.md) - [the `Command` handler-accessor gap is filed upstream, not shimmed](../decisions/cli-handler-accessor-gap-filed-upstream.md) The presentation layer adds its own: - [`@effected/cli-kit` grows a presentation layer](../decisions/cli-grows-presentation-layer.md) - [two prompt engines raise one `Cancelled`](../decisions/one-cancelled-for-two-prompt-engines.md) - [the audience flag is four shared root flags](../decisions/audience-flag-is-shared-root-flags.md) - [the package owns its display width](../decisions/own-display-width.md) - [the document IR is plain data](../decisions/doc-ir-is-plain-data.md), [it has no JSON renderer](../decisions/no-json-renderer.md) and [`CliLinks` finds the project root with `@effected/walker`](../decisions/cli-takes-the-walker-edge.md), which supersedes the draft that had it [inline](../decisions/cli-links-inline-ascent.md) (all drafts, awaiting a human to verify them) - [`FORCE_COLOR` is honoured](../decisions/force-color-honoured-node-precedence.md) and [`@effected/env` is its own package](../decisions/env-is-its-own-package.md), both recorded against the [`env` Module](env.md) ## Errors **Two error classes, both about prompts:** `Cancelled` and `NotInteractive`. Everything else here is presentation: it renders errors other packages raise and must not wrap them. A renderer that fails has a defect, not a domain error — a `SchemaIssue` tree that cannot be rendered is a bug in the renderer. ## Observability **No spans.** Rendering a string and writing a line are not operations an operator traces, and a span around a logger write would appear in every log line's own trace. The package stays telemetry-agnostic, like every library in the kit. ## Testing The `Console` reference makes the whole surface testable without stubbing globals: provide a capturing `Console`, run the program, and assert on what was written and on which stream — the property most worth pinning, since it is the one that silently regresses and the one `mytool run > log.txt` depends on. The discriminating mutant for `CliLogger` is routing everything to stdout; a suite that still passes is asserting on content and not on stream, which is half a test. Drive levels with `References.MinimumLogLevel`, provided as a service. `Logger.withMinimumLogLevel` does not exist on the v4 line and is the obvious first reach — verified absent from core's `Logger.ts` rather than assumed. `@effect/vitest`, `it.effect`, `assert.*` — never `expect`. ## Non-goals Out of scope, and staying out: argument parsing, flags, the command tree and help (`effect/cli` owns them), a platform package, and a dependency edge from anything but an application. Prompts and interactive UI used to be on this list; [the presentation-layer decision](../decisions/cli-grows-presentation-layer.md) moved them in, and the old boundary limitation is deprecated. ## Build Standard package setup. Expected to need no API Extractor suppression: no class factories here, so no synthesized `_base` symbol. Gate on a cold `pnpm build --filter @effected/cli-kit`, never the raw script.