Skip to content

feat(completion): add shell autocompletion - #141

Open
nicknisi wants to merge 10 commits into
mainfrom
feat/shell-completion
Open

nicknisi wants to merge 10 commits into
mainfrom
feat/shell-completion

Conversation

@nicknisi

@nicknisi nicknisi commented May 4, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Add workos completion <shell> command supporting bash, zsh, fish, and powershell
  • Add hidden --get-yargs-completions fast path intercepted before yargs parses, avoiding validation errors on partial tab input
  • Completion engine walks the existing help-json.ts command registry with normalization to handle the mixed flat/nested naming (e.g. auth login vs skills > install)
  • Descriptions appear alongside candidates in shells that support them (zsh with fzf-tab, fish, powershell)
  • Add README setup instructions for session and persistent shell completion installation
  • Address review findings:
    • Use BSD/macOS-portable bash parsing instead of head -n-1
    • Escape : in zsh descriptions before passing candidates to _describe
    • Split PowerShell completion output on a real tab character using `t
    • Exclude completion from unclaimed-environment warning middleware
    • Avoid mutating the original help-json command registry during normalization
  • Add unit coverage for command/subcommand/option completion, compound name normalization, shell script generation, and the review fixes above

Review & Testing Checklist for Human

  • Verify eval "$(workos completion bash)", eval "$(workos completion zsh)", fish, and PowerShell setup each produce usable completions in a real shell session
  • On macOS/BSD bash, confirm completion still works and no head: illegal line count error appears
  • In zsh, confirm completion descriptions containing : render correctly and do not break candidate parsing
  • In PowerShell, confirm accepting a completion inserts only the command/flag name, not the tab-separated description text
  • Confirm workos completion <shell> does not show an unclaimed-environment warning

Notes

Usage examples:

eval "$(workos completion zsh)"   # load into current session
workos completion bash > /etc/bash_completion.d/workos  # permanent

Local validation run:

  • pnpm test -- src/utils/completion.spec.ts — full Vitest suite passed, 125 files / 1675 tests
  • pnpm lint
  • pnpm typecheck
  • pnpm format:check
  • pnpm build
  • Smoke test generated bash/zsh/PowerShell scripts and workos --get-yargs-completions auth ""

Open in Devin Review

Summary by CodeRabbit

  • New Features

    • Adds a new workos completion command to generate shell autocompletion scripts for Bash, Zsh, Fish, and PowerShell; validates the shell argument and writes the script to stdout.
    • Provides smarter tab-completion: suggests subcommands and options, handles nested commands, respects hidden/used options, and suppresses file completions when appropriate.
  • Documentation

    • Adds a "Shell Completion" README section with usage and session vs. permanent installation examples.
  • Tests

    • Adds unit tests covering completion generation, suggestion behavior, and shell script output for supported shells.

Link to Devin session: https://app.devin.ai/sessions/d1f3c75f768e47d49b8fa040482284bd
Requested by: @nicknisi


Riker job 361: Rebase shell-completion PR

  • Check: (test -x node_modules/.bin/vitest || timeout 300 bun install --frozen-lockfile … passed on 99692e2 (run 3)
  • Review: needs changes (8755e45..5810742), still flags [blocker] Tests: Unknown-word test passes even if command context is lost — src/utils/completion.spec.ts:131; [should fix] PowerShell counts the current word twice — src/utils/completion.ts:373; [should fix] Bash and Zsh include arguments after the cursor — src/utils/completion.ts:251 and 2 more
  • Open it: riker job 361 · riker watch 361
  • Riker: 0.88.0 (build 750095c)

Review still flags

Riker's review of this code didn't approve it; it went out as it is with these findings:

  • [blocker] Tests: Unknown-word test passes even if command context is lost — src/utils/completion.spec.ts:131
  • [should fix] PowerShell counts the current word twice — src/utils/completion.ts:373
  • [should fix] Bash and Zsh include arguments after the cursor — src/utils/completion.ts:251
  • [should fix] Nested commands lose inherited options — src/utils/completion.ts:174
  • [should fix] Tests: Shell tests never exercise empty-token forwarding — src/utils/completion.spec.ts:161

Verification: Riker's check passed on exactly this code. Head 99692e2, 2026-11-23 16:59 UTC.

@coderabbitai

coderabbitai Bot commented May 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds shell autocompletion: a completion engine that normalizes the command registry, computes completions for commands and options, emits a server-format response, and generates Bash/Zsh/Fish/PowerShell scripts. Adds an early CLI fast-path for yargs completion requests and a workos completion <shell> command; tests and README docs added.

Changes

Shell Completion Engine

Layer / File(s) Summary
Help registry (data shape)
src/utils/help-json.ts
Adds a completion top-level command with a required shell positional and exports commands/globalOptions as commandRegistry/globalOptionRegistry.
Completion Engine (core API & behavior)
src/utils/completion.ts
Adds generateCompletions(args) and completeHandler(args), normalization/caching of the command registry, command-tree walking, option-use detection, completion filtering (skip hidden/already-used options), and returns a no-file-completion directive. Exports SUPPORTED_SHELLS, SupportedShell, and generateShellScript.
Registry normalization & caching
src/utils/completion.ts
Normalize mixed flat/compound command names into a virtual-parent tree and cache cloned normalized registry for traversal.
Command tree traversal & option tracking
src/utils/completion.ts
Walk input tokens to find active command node and collect used option flags (skipping option values when appropriate).
Completion generation helpers
src/utils/completion.ts
Produce subcommand and option candidates, filter hidden/already-used options, and package results with a no-file-completion directive.
Shell Script Generators
src/utils/completion.ts
Implement Bash, Zsh, Fish, and PowerShell script generators and generateShellScript(shell, binaryName) that invoke --get-yargs-completions and parse the returned lines.
CLI Fast Path & Command
src/bin.ts
Add top-level rawArgs fast-path intercepting --get-yargs-completions (dynamic import + completeHandler + exit) and a workos completion [shell] command that prints the generated script.
Tests
src/utils/completion.spec.ts, src/utils/help-json.spec.ts
Adds Vitest suites for generateCompletions (many completion cases) and generateShellScript (per-shell output and escaping), and registry-parity assertions in help-json tests.
Documentation
README.md
Add "Shell Completion" section with session and permanent install examples for Bash, Zsh, Fish, and PowerShell and workos completion <shell> usage.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.58% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title 'feat(completion): add shell autocompletion' directly and clearly describes the main change: adding shell completion functionality to the workos CLI.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/shell-completion

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

coderabbitai[bot]

This comment was marked as resolved.

@greptile-apps

greptile-apps Bot commented May 4, 2026 •

Copy link
Copy Markdown

Greptile Summary

Shell autocompletion is added for the WorkOS CLI.

  • Adds a completion engine backed by the existing static command registry.
  • Generates completion scripts for Bash, Zsh, Fish, and PowerShell.
  • Adds a pre-yargs completion fast path and a public completion <shell> command.
  • Documents shell setup and adds completion and registry-parity tests.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains; the previously reported Bash portability, Zsh escaping, registry mutation, and PowerShell tab-splitting issues are corrected in the current code.

Important Files Changed

Filename Overview
src/bin.ts Adds the pre-parser completion path, completion command registration, and warning-middleware exclusion.
src/utils/completion.ts Implements registry normalization, completion generation, and scripts for four supported shells, including the requested portability and escaping fixes.
src/utils/completion.spec.ts Covers command and option suggestions, normalization immutability, supported generators, and the prior review fixes.
src/utils/help-json.ts Exports the command and option registries and mirrors the new completion command.
src/utils/help-json.spec.ts Adds explicit parity checks between public CLI commands and the static registry.
README.md Documents session and persistent installation for supported shells.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  Shell[Shell completion function] -->|partial argv| FastPath[bin.ts completion fast path]
  FastPath --> Engine[completion.ts]
  Registry[help-json command registry] --> Engine
  Engine -->|tab-separated candidates and directive| Shell
  User[workos completion shell] --> Generator[Shell script generator]
  Generator --> Shell
Loading

Reviews (5): Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." | Re-trigger Greptile

greptile-apps[bot]

This comment was marked as resolved.

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Note

Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

Devin Review found 2 potential issues.

View 5 additional findings in Devin Review.

Open in Devin Review

Comment thread src/bin.ts

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 completion command not excluded from unclaimed-env middleware

The completion command is missing from the middleware exclusion list at src/bin.ts:200. The middleware comment explicitly states that utility commands like skills, doctor, env, and debug are excluded because the warning is unnecessary — completion is also a utility command but was not added. When completion runs through the middleware, maybeWarnUnclaimed() may make an API call (adding latency) and emit a stderr warning. While it won't corrupt the stdout script output, running eval "$(workos completion bash)" could flash a confusing "Unclaimed environment" warning.

(Refers to lines 200-202)

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/utils/completion.ts Outdated
if ($line -match '^:(\\d+)$') {
$directive = [int]$matches[1]
} elseif ($line.Trim()) {
$parts = $line.Split("\\t", 2)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 PowerShell completion script splits on literal \t instead of tab character

The generated PowerShell completion script uses $line.Split("\t", 2) to parse tab-separated completions. However, in PowerShell, "\t" is the literal two-character string backslash-t — PowerShell uses backtick escapes ("`t") for tab characters, not backslash escapes. The .Split() method is not regex-based, so it won't interpret \t as a tab.

Impact on different PowerShell versions

On PowerShell 7+ (.NET 6+): .Split("\t", 2) matches String.Split(String, Int32) and looks for the literal two-character string \t, which never appears in the output (the actual output uses real tab characters from src/utils/completion.ts:29). The entire line becomes $comp, including the tab and description text.

On PowerShell 5 (.NET Framework): .Split("\t", 2) resolves to Split(Char[], Int32), splitting on either \ or t as individual characters. This incorrectly splits any completion containing the letter t (e.g., --git-check splits into --gi and -check...).

Prompt for agents
In src/utils/completion.ts, the generatePowershell function at line 364 outputs `$parts = $line.Split("\\t", 2)` which generates PowerShell code `$parts = $line.Split("\t", 2)`. In PowerShell, `"\t"` is a literal backslash-t, not a tab character. PowerShell uses backtick escapes for special characters.

The fix needs to produce PowerShell code that splits on an actual tab character. Two options:

1. Use PowerShell's [char]9 for a tab: change the line to produce `$parts = $line.Split([char]9, 2)` — this works on both PowerShell 5 and 7.

2. Use PowerShell's backtick escape: change to produce `$parts = $line.Split("`t", 2)` — but this requires careful escaping in the JavaScript template literal since backtick is the template delimiter.

Option 1 is simpler and avoids JS escaping complexity. In the JS template literal, the line should be: `$parts = $line.Split([char]9, 2)`
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

greptile-apps[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

@devin-ai-integration

Copy link
Copy Markdown
Contributor

❌ Cannot revive Devin session - the session is too old. Please start a new session instead.

nicknisi and others added 10 commits November 23, 2026 10:59
…owershell

Add `workos completion <shell>` command that generates shell-specific
completion scripts. A hidden `--get-yargs-completions` fast path is
intercepted before yargs parses to avoid validation errors on partial
tab input.

The completion engine walks the existing help-json.ts command registry,
normalizing its mixed flat/nested naming into a uniform tree so both
`auth login` style entries and `skills > install` style entries resolve
correctly for subcommand drilling.

Supports descriptions alongside candidates in shells that render them
(zsh with fzf-tab, fish, powershell).

Riker-Verification: check
Riker-Verification: check
- Hoist completion intercept above heavy imports (yargs, clack, semver)
  so Tab presses skip ~150ms of module loading
- Export raw command/option arrays from help-json.ts, eliminating double
  buildCommandTree() call and 'in' type narrowing in completion.ts
- Remove dead DIRECTIVE.DEFAULT constant
- Remove unused _resetCache export
- Remove duplicate shell validation in bin.ts (yargs choices +
  generateShellScript throw already cover it)
- Add 7 new tests (option value skipping, empty args, partial prefix
  filtering, hidden commands, descriptions)

Riker-Verification: check
Add parameterized test that asserts every public bin.ts command has a
matching entry in the help-json registry. Catches forgotten registry
updates at CI time (which would cause missing tab completions and
missing --help --json entries).

Also add 7 completion edge case tests: option value skipping, empty
args, partial prefix filtering, hidden commands, descriptions.

Riker-Verification: check
Co-Authored-By: nick.nisi@workos.com <nick.nisi@workos.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Riker-Verification: check
Co-Authored-By: nick.nisi@workos.com <nick.nisi@workos.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Riker-Verification: check
Co-Authored-By: nick.nisi@workos.com <nick.nisi@workos.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Riker-Verification: check
@nicknisi
nicknisi force-pushed the feat/shell-completion branch from a6a3c57 to 99692e2 Compare November 23, 2026 16:59
@devin-ai-integration

Copy link
Copy Markdown
Contributor

❌ Cannot revive Devin session - the session is too old. Please start a new session instead.

View session

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Devin Review found 4 potential issues.

7 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment thread src/utils/completion.ts
Comment on lines +134 to +137
const sub = currentCommands.find((c) => c.name === word);
if (sub) {
current = sub;
currentCommands = sub.commands ?? [];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Missing completions after command aliases

After workos org l, walkCommandTree misses the org alias and never enters the organization command. Tab omits list and other organization-specific suggestions.

Learn more

The CLI registers org as an alias of organization in the organization command. The alias map records the same mapping, along with other aliases including one that expands to a command and subcommand. Completion only looks for canonical names in the normalized tree, so it remains at the root when an alias is already on the command line.

Example: Press Tab at workos org l. list is available after workos organization l, but the alias returns only global flags from the engine.

Recommended fix: Resolve supported aliases for the first command word before walking the tree. Add tests for org list and env list, and handle multi-part targets without matching aliases against option values.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/utils/completion.ts

local IFS=$'\\n'
local output
output=$("${bin}" --get-yargs-completions "\${COMP_WORDS[@]:1}" 2>/dev/null)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Bash and Zsh complete the wrong word

When editing an earlier word, _workos_completions passes the words after the cursor too. Zsh’s _workos does the same. The completion engine completes the last word, so --ver before --fix loses its matches.

Learn more

The shell scripts pass an argument list to generateCompletions, which treats the last element as the word being completed. Bash already has the index and current word in cword and cur, but sends all of COMP_WORDS. generateZsh also sends every word instead of stopping at Zsh's CURRENT index.

Example: Type workos doctor --ver --fix, move the cursor back to the end of --ver, and press Tab. The engine matches --fix rather than returning --verbose or --version for --ver.

Recommended fix: Forward only the arguments before the cursor and the current prefix. In Bash, use the normalized words from _init_completion when available. In Zsh, bound the slice by CURRENT. Preserve an explicit empty string for an empty current word.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/utils/completion.ts
Comment on lines +368 to +373
$words = $commandAst.ToString().Split(' ', [StringSplitOptions]::RemoveEmptyEntries)
$args = @()
if ($words.Count -gt 1) {
$args = $words[1..($words.Count - 1)]
}
$args += $wordToComplete

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 PowerShell counts the current word twice

At workos auth without a trailing space, $args includes auth from the command AST and again as the prefix. The completion engine enters auth too early, so Tab no longer offers authkit.

Learn more

PowerShell provides the current word, a parsed command, and the cursor position. The callback splits the entire command text on spaces and then appends the current word, so the command portion includes the token being completed. generateCompletions treats everything except the final element as already entered. The split also preserves quote characters in a quoted command name rather than using its parsed value.

Example: Press Tab at workos auth without a space. The engine receives auth twice and searches for subcommands of auth, instead of offering auth and authkit at the root.

Recommended fix: Take completed arguments from the AST's command elements and their source extents, exclude the element at the cursor and all later elements, and append the current prefix once. Test exact matches, empty prefixes, and quoted command names.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/utils/completion.ts
partial: string,
usedOptions: Set<string>,
): Completion[] {
const opts = [...(command?.options ?? []), ...globalOptions];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Missing inherited flags after subcommands

After workos vault list --api, completeOptions omits --api-key. The Vault list command accepts that flag from its parent.

Learn more

The Vault parent declares the API-key option once rather than repeating it on each subcommand. The Vault list handler uses the inherited value. Completion keeps only the leaf and global options for both suggestions and option lookup, so it neither suggests inherited flags nor recognizes their values when walking the input.

Example: workos vault --api<Tab> offers --api-key, but workos vault list --api<Tab> does not, even though both positions are accepted by the parser.

Recommended fix: Keep the ancestor path while walking, and use one effective option list for suggestions and lookup. Prefer the nearest declaration when names overlap, while preserving hidden-option and used-option handling.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant