Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .changeset/effect-rewrite-cli.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
"clerk": major
---

Rebuild the CLI on Effect's CLI toolkit: every command is defined with it, and it parses the command line and renders help, prompts and shell completion. Breaking changes:

- A malformed command line (unknown flag or subcommand, missing value, value outside the allowed choices) now exits 2 with a usage error, printed as the `usage_error` JSON envelope in agent mode, instead of exiting 1 with plain text. The error messages are worded differently.
- Help has a new layout: `DESCRIPTION`, `USAGE`, `FLAGS`, `GLOBAL FLAGS`, `SUBCOMMANDS` and `EXAMPLES` sections replace `Usage:`, `Options:` and `Commands:`. Flags are listed in declaration order, and a switch that defaults on is shown as `--x` with its `--no-x` form implied.
- `clerk help <command>` and the `help` subcommand of command groups (`clerk migrate help`) are gone: use `clerk <command> --help`.
- `-h` or `--help` anywhere before `--` prints help for the most specific command named, even after `--version` or where a flag's value was expected. `clerk -hv` prints help.
- Shell completion is a static script generated from the command tree. Regenerate it (`clerk completion <shell>`) after upgrading. The hidden `clerk __complete` command is gone, and values that came from the CLI at completion time (`mcp install --client`, `migrate --source` and similar hints) are no longer completed. `clerk completion` with no shell is a usage error.
- A command has at most one alias: `clerk auth login` keeps `signin` (`signup` and `sign-in` are gone) and `clerk auth logout` keeps `signout` (`sign-out` is gone).
- `--keys` (`clerk config pull`, `clerk config schema`), `--for` (`clerk enable billing`, `clerk disable billing`) and `--android-fingerprint` (`clerk init`, `clerk doctor`) take one value per flag: repeat the flag or separate values with commas. `--keys a b` no longer works.
- Any other flag given twice is a usage error; the last value no longer wins. This includes `--help` and `-h` (`clerk --help --help`) and `--version` written with a value (`--version=true --version=true`); a bare `clerk --version --version` still prints the version (with any other word on the line, such as `--mode agent`, it is a usage error).
- `--help` and `--version` answer whatever form they are written in: `--no-help`, `--help=false`, `--no-version` and `--version=false` print help or the version and exit 0, instead of failing as unknown options.
- `clerk open help` no longer prints help: `help` is read as a dashboard subpath. Use `clerk open --help`.
- A `clerk feedback --outcome` outside the allowed values (an empty or space-padded one included) is rejected while parsing: the usage error is worded differently, carries no examples, and sends no usage telemetry event.
- A short flag's value is its own word: `-X POST`, not `-XPOST`. A value that starts with `-` must be attached with `=` (`--attempted=-v printed nothing`); as the next word it is read as a flag, except a negative number (`--limit -5`). An `--input-json` value always reaches its flag, whatever it looks like.
- A group's flags go after the group name and before or after the subcommand (`clerk users --app app_1 list` and `clerk users list --app app_1` both work), but a flag a subcommand does not take is a usage error. The duplicate copies of a parent's flag on its children are gone: `clerk impersonate revoke --open` is now a usage error.
- `clerk deploy run` is gone: run `clerk deploy`, which usage telemetry still records as `deploy run`. `clerk deploy status --domain` reports an unknown flag.
- `--=<value>` (a flag with no name) is read as an argument: a usage error where the command takes none, and the endpoint where one is expected (`clerk api --=users`).
- `clerk mcp run` no longer passes its flags through: it still prints the removed-command error, but a flag after it is now a usage error.
- An invalid `--mode` value is a usage error raised before the command starts, so it sends no usage telemetry event.
- An explicit flag next to `--input-json` replaces the JSON key of the same name instead of being appended after it.
- Prompts look and respond differently: confirm takes y or n, multi-select adds select-all and invert rows, and an invalid answer is corrected in place.
- Pressing Ctrl-C while a spinner is running now exits 130 instead of 0, so scripts see the interruption.
121 changes: 51 additions & 70 deletions .claude/rules/command-registration.md
Original file line number Diff line number Diff line change
@@ -1,103 +1,84 @@
---
description: Command registration conventions — every command group registers via register<Name>(program) from its index.ts, listed in the registrants array
description: Command registration conventions — every command group defines an effect/cli Command in its index.ts, listed in COMMANDS
paths:
- "packages/cli-core/src/cli.ts"
- "packages/cli-core/src/cli-program.ts"
- "packages/cli-core/src/commands/*/index.ts"
- "packages/cli-core/src/lib/command.ts"
- "packages/cli-core/src/startup/**"
- "packages/cli-core/src/test/surface/**"
- "packages/cli-core/src/startup-boundary.test.ts"
- "packages/cli-core/src/test/lib/startup-boundary.ts"
alwaysApply: false
---

Every command group is wired into the root program through a **registrant function**, never inline in `createProgram()`.
Commands are `effect/cli` commands. Every command group builds its `Command` in its own `commands/<name>/index.ts` with `Command.make`, `Flag`, `Argument` and `Command.withSubcommands`, never inline in `cli-program.ts`.

## The pattern

1. Each command group exports `register<Name>(program: Program): void` from `packages/cli-core/src/commands/<name>/index.ts`. It builds the whole `program.command("<name>")` subtree (options, arguments, `.setExamples()`, subcommands) and wires each `.action()` to the handler functions in sibling files.
2. `cli-program.ts` imports that function and adds it to the `registrants: CommandRegistrant[]` array. `createProgram()` only configures the root program + global hooks, then loops `for (const register of registrants) register(program)`.

**Do not** build a command tree inline inside `createProgram()`. If you're adding a `program.command(...)` (or `webhooks`-style group) directly in `cli-program.ts`, stop — move it to a `register<Name>` in the group's `index.ts` and append the function to `registrants` instead.
1. Each command group exports `<name>Command` from its `index.ts`.
2. `cli-program.ts` imports it and adds it to `COMMANDS`. `rootCommand` is `clerk` with `COMMANDS` as subcommands and the global flags from `lib/command.ts` (`--input-json`, `--mode`, `--verbose`).

## `index.ts` shape

```ts
import type { Program } from "../../cli-program.ts";

export function registerApps(program: Program): void {
const apps = program.command("apps").description("Manage your Clerk applications");

apps
.command("list")
.description("List your Clerk applications")
.option("--json", "Output as JSON")
.setExamples([{ command: "clerk apps list", description: "List all applications" }])
.action(async (options) => {
// Loaded on demand so other commands don't pay Effect's startup cost.
const { list } = await import("./list.ts");
await list(options);
});

apps
.command("create")
.argument("<name>", "Application name")
.action(async (name: string, options) => {
// Loaded on demand so other commands don't pay Effect's startup cost.
const { create } = await import("./create.ts");
await create(name, options);
});
}
import { Argument, Command } from "effect/cli";
import { action, switchFlag } from "../../lib/command.ts";

const json = switchFlag("json", "Output as JSON");

const list = Command.make(
"list",
{ json },
action("apps list", async (input) => (await import("./list.ts")).list(input)),
).pipe(
Command.withDescription("List your Clerk applications"),
Command.withExamples([{ command: "clerk apps list", description: "List all applications" }]),
);

const create = Command.make(
"create",
{ name: Argument.String("name").pipe(Argument.withDescription("Application name")), json },
action("apps create", async ({ name, ...options }) =>
(await import("./create.ts")).create(name, options),
),
).pipe(Command.withDescription("Create a new Clerk application"));

export const appsCommand = Command.make("apps").pipe(
Command.withDescription("Manage your Clerk applications"),
Command.withSubcommands([list, create]),
);
```

- Import the `Program` type from `../../cli-program.ts` (type-only — no runtime cycle, this is the established pattern).
- Keep handler _logic_ in sibling files (`list.ts`, `create.ts`, …); `index.ts` is wiring only. A type-only import from a handler file (e.g. `import type { UsersOpenOptions } from "./open.ts"`) is fine for typing an action's options, because it is erased.

## Handlers load lazily
- The keys of a command's config are the keys its handler's options object reads; flag names are kebab-case (`Flag.String("dry-run")` under the key `dryRun`).
- `lib/command.ts` has the shapes the CLI spells often: `booleanFlag` (every boolean flag: a `Flag.Boolean` that never takes the next word as its value, so `--json true` is the switch and an argument; use it instead of `Flag.Boolean`), `switchFlag` (`true` when given, `undefined` when not; a boolean flag without a default is a required flag), `stringFlag` and `optional` (`undefined` when absent), `repeatedFlag` (`--tag a --tag b`), `integerFlag` (range-checked), `optionalArgument`, `restArguments`. Choices are `Flag.Literals` / `Argument.Literals`: a value outside them is a usage error and shell completion offers them.
- A negated switch is `booleanFlag("browser").pipe(Flag.withDefault(true))`; `--no-browser` comes with every boolean flag. A tri-state switch is `optional(booleanFlag(...))`.
- `Command.withAlias` (one alias), `Command.unlisted` (hidden from help and completion), `Command.withShortDescription` (the one-liner the parent's help lists), `Command.withExamples`, and `Command.annotate(HelpText, text)` (free text after the help screen) cover the rest.
- Keep handler _logic_ in sibling files (`list.ts`, `create.ts`, …); `index.ts` is the command definition only. Never name a handler module `index.ts`.

Every command runs `createProgram()`, so whatever a registrant imports statically loads before even `clerk --version` can answer. Every handler runs on Effect, and Effect's modules add about 12 ms to that, so a handler is always loaded with a dynamic `import()` inside its action, never imported at the top of `index.ts`. What `index.ts` may import statically is what registration itself needs: `@commander-js/extra-typings` helpers, option parsers (`startup/option-parsers.ts`), and the constants that feed `.choices()` (`FRAMEWORK_NAMES` in `startup/framework.ts`, `KEYLESS_TEMPLATES` in `startup/keyless.ts`, `PACKAGE_MANAGERS` in `startup/package-manager.ts`).
## Handlers

The handler's promise adapter (`list(options)` above) is the only thing an action calls: it runs the command's Effect program with `runCliEffect(program, MainLayer)`. One command reusing another calls the other's program, not its adapter, since it is already on Effect (autoclaim runs `envPullProgram`; `link` runs the login program; `init` and `doctor --fix` run the login, link, and env pull programs; `migrate import` runs the login and link programs).
`action(path, run)` is every command's handler. `path` is the command path below `clerk` (`"users list"`), which telemetry records. Around `run` it does the startup work: telemetry with the flags the line set (`flagsSet`), `--verbose` and `--mode`, the active environment and its banner; after it, the update notice (except for `doctor` and `update`, which check themselves). `run` loads the handler module with a dynamic `import()`, so a command only loads its own code, and calls its promise adapter, which runs the command's Effect program with `runCliEffect(program, MainLayer)`. One command reusing another calls the other's program, not its adapter (autoclaim runs `envPullProgram`; `link` runs the login program; `init` and `doctor --fix` run the login, link, and env pull programs; `migrate import` runs the login and link programs).

## The startup boundary
A group whose flags apply to every subcommand declares them with `Command.withSharedFlags` on a base command, and its subcommands use `actionWith(path, base, run)`, which hands `run` the shared flags merged into the subcommand's input. A subcommand must not redeclare a shared flag (`effect/cli` throws `DuplicateOption`). `commands/users/index.ts` is the example: a group with its own handler, shared targeting flags and subcommands.

The code that runs before an action is the startup boundary, declared in `src/test/lib/startup-boundary.ts`:
A group with its own handler runs when it is named without a subcommand (`clerk deploy` runs the deploy wizard). A group without one prints its help on stderr and exits 1.

- `src/startup/`, the Effect-free modules `cli-program.ts` loads: the global error handler and the `startup/failure.ts` data it reads, `startup/telemetry.ts` and its `loggedFetch` send, the post-command `startup/update-check.ts` notice, `startup/config.ts` and `startup/environment.ts` for the `preAction` hook, `startup/input-json.ts`, and the clack renderers (`startup/prompts.ts`, `startup/spinner.ts`, `startup/ui.ts`)
- the entry points `cli.ts` (with its `__complete` fast path) and `cli-program.ts`
- each `commands/<name>/index.ts` registrant
- `REGISTRATION_HELPERS`, the few command-local files a registrant needs to build its options (the completion scripts, the MCP client table, the migrate sources)
## Parsing

Two tests hold it closed:

- `startup-boundary.test.ts` scans the static imports of every module inside the boundary and fails on one that resolves outside it, or that names `effect` or an `@effect/*` package. A dynamic `import()` and an `import type` are allowed.
- `cli-program.subprocess.test.ts` runs `createProgram()` and the `__complete` path in a child process and fails if any module outside the boundary, or any `effect` / `@effect/*` module, has loaded.
`runProgram` in `cli-program.ts` runs `expandInputJson`, then `Command.runWith(rootCommand, …)`. `effect/cli` parses the line, renders help (`--help`, with `formatHelp` adding the `HelpText` annotation) and the version, and runs the handler. A parse error is a usage error: exit 2, `usage_error` in agent mode's JSON envelope. A handler's failure reaches the global handler (`reportError`) as the thrown error inside `ActionFailure`.

Because `commands/<name>/index.ts` is inside the boundary by name, never use `index.ts` for a command's handler module: name it after the command (`orgs/orgs.ts`, not `orgs/index.ts`). When a registrant genuinely needs another Effect-free file at registration, add it to `REGISTRATION_HELPERS`; anything a handler shares with startup belongs in `startup/`. Effect services live in `lib/`, and several share a base name with a `startup/` module (`lib/log.ts` is the `Log` service, `startup/log.ts` the plain `log`), so a registrant importing `../../lib/log.ts` fails the boundary check. See [errors.md](./errors.md) for how a tagged failure reaches the handler as plain data.
## The startup boundary

## `cli-program.ts` shape
Only `clerk --version` answers before Effect loads: `cli.ts` prints it, then dynamically imports `cli-program.ts` for everything else. The boundary is `cli.ts` and the `startup/` directory (`src/test/lib/startup-boundary.ts`), which stays Effect-free because `cli.ts` and the handler hooks in `lib/command.ts` read it:

```ts
import { registerApps } from "./commands/apps/index.ts";
// …
const registrants: CommandRegistrant[] = [
registerInit,
registerApps,
// … one entry per command group, in display order …
registerExtras,
];

export function createProgram(): Program {
const program = new Command() /* … global options … */ as Program;
program.hook("preAction" /* … */);
for (const register of registrants) register(program);
return program;
}
```
- `startup-boundary.test.ts` scans the static imports of every module inside the boundary and fails on one that resolves outside it, or that names `effect` or an `@effect/*` package. A dynamic `import()` and an `import type` are allowed.
- `cli-program.subprocess.test.ts` runs `cli.ts --version` in a child process and fails if any module outside the boundary, or any `effect` / `@effect/*` module, has loaded.

Helpers used by only one group (e.g. `createOption`, `parseIntegerOption`, `getAuthToken`) belong in that group's `index.ts`, not imported into `cli-program.ts`.
Effect services live in `lib/`, and several share a base name with a `startup/` module (`lib/log.ts` is the `Log` service, `startup/log.ts` the plain `log`). See [errors.md](./errors.md) for how a tagged failure reaches the handler as plain data.

## Groups with global options, an optional group-level hook, and subcommands
## The surface snapshots

Build the group exactly as above and attach its concerns inside the same `register<Name>`: parent `.option(...)` flags inherited via `optsWithGlobals()`, an optional group `.hook("preAction", …)` for shared gating (e.g. auth), and one `.command(...)` per subcommand. See `commands/users/index.ts` (`registerUsers`) for a multi-subcommand group with a handler-map and options inherited via `optsWithGlobals()`. A group only needs a `preAction` gate when its subcommands require shared setup; auth-free groups like `commands/webhooks/index.ts` (`registerWebhooks`) — `token` (relay token generator), `listen` (relay tunnel), and `verify` (offline HMAC) — omit it entirely.
`src/test/surface/surface.test.ts` records the CLI's surface as file snapshots in `src/test/surface/__snapshots__/`: the command tree (`Completions.fromCommand`), `--help` for every listed command, each shell's completion script, and the parse errors' exit codes and envelopes. A diff there is a change users see: review it, list it in the changeset when it breaks something, then re-record with `bun --bun vitest run --project unit packages/cli-core/src/test/surface -u`.

Related: [commands.md](./commands.md) (per-command directory + README + agent-mode rules) and [completion.md](./completion.md) (keep `.choices()` / `__complete.ts` in sync when adding commands or options).
Related: [commands.md](./commands.md) (per-command directory + README + agent-mode rules) and [completion.md](./completion.md).
Loading
Loading