-
Notifications
You must be signed in to change notification settings - Fork 1.6k
[STG-2278] feat(cli): did-you-mean + telemetry for unknown commands #2249
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
cea788a
feat(cli): did-you-mean suggestions + telemetry for unknown commands
shrey150 340fb4e
fix(cli): segment-aligned fuzzy matching so trailing user tokens neve…
shrey150 e8520c4
fix(cli): drop auth/login -> doctor alias suggestions
shrey150 37ae41c
refactor(cli): use fastest-levenshtein instead of hand-rolled edit di…
shrey150 bcee6ed
test(cli): table-ize command-suggestion units, split out built-CLI in…
shrey150 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| --- | ||
| "browse": patch | ||
| --- | ||
|
|
||
| Add did-you-mean suggestions and telemetry for unknown commands. | ||
|
|
||
| - Unknown commands (e.g. `browse sessions`, `browse search`, `browse auth status` — old Commander-era syntax — plus plain typos like `browse opne`) now print an actionable suggestion on stderr: an explicit alias table maps old syntax to the current command tree, with a Levenshtein nearest-match fallback for typos. The clause is omitted when there is no decent match. | ||
| - A new `cli.command_not_found` telemetry event makes this failure class measurable. Privacy: only the sanitized attempted command id and the computed suggestion are sent — never raw argv, which can contain URLs, selectors, or secrets. | ||
| - oclif's standard "command not found" error and exit code 2 are preserved; no new runtime dependency (deliberately avoids `@oclif/plugin-not-found`, which prompts interactively and is agent-hostile). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| import { Errors, type Hook } from "@oclif/core"; | ||
|
|
||
| import { suggestCommand } from "../lib/command-suggestions.js"; | ||
| import { captureCommandNotFound } from "../lib/telemetry.js"; | ||
|
|
||
| function toSpaced(commandId: string): string { | ||
| return commandId.replaceAll(":", " "); | ||
| } | ||
|
|
||
| const hook: Hook.CommandNotFound = async function ({ config, id }) { | ||
| let attempted = ""; | ||
| let suggestion: string | null = null; | ||
|
|
||
| try { | ||
| const commandIds = config.commands | ||
| .filter((command) => !command.hidden) | ||
| .map((command) => command.id); | ||
| const result = suggestCommand(id, commandIds); | ||
| attempted = result.attempted; | ||
| suggestion = result.suggestion; | ||
| if ( | ||
| suggestion && | ||
| !config.findCommand(suggestion) && | ||
| !config.findTopic(suggestion) | ||
| ) { | ||
| // Guards against alias targets drifting out of the command tree. | ||
| suggestion = null; | ||
| } | ||
|
|
||
| const displayAttempted = toSpaced(attempted || (id.split(":")[0] ?? id)); | ||
| const didYouMean = suggestion | ||
| ? ` Did you mean "${config.bin} ${toSpaced(suggestion)}"?` | ||
| : ""; | ||
| process.stderr.write( | ||
| `"${config.bin} ${displayAttempted}" is not a ${config.bin} command.${didYouMean} Run ${config.bin} --help for all commands.\n`, | ||
| ); | ||
| } catch { | ||
| // Suggestions are best-effort and must never mask the not-found error. | ||
| } | ||
|
|
||
| try { | ||
| // Awaited so the event is delivered before the process exits; the | ||
| // transport aborts after a short timeout, so this cannot hang the CLI. | ||
| await captureCommandNotFound(config.version, attempted || null, suggestion); | ||
| } catch { | ||
| // Best-effort telemetry should never affect CLI behavior. | ||
| } | ||
|
|
||
| // Re-throw oclif's standard not-found error. Returning normally from a | ||
| // command_not_found hook makes oclif treat the invocation as handled | ||
| // (exit 0), so this throw preserves the default error and exit code 2. | ||
| throw new Errors.CLIError(`command ${id} not found`); | ||
| }; | ||
|
|
||
| export default hook; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| /** | ||
| * Suggestion engine for unknown commands. | ||
| * | ||
| * oclif's spaced-topic parsing glues unknown leading argv tokens into the | ||
| * attempted command id (e.g. `browse opne https://example.com` arrives as | ||
| * `opne:https://example.com`), so the id may contain user-provided values. | ||
| * Everything here works on a sanitized token prefix and never returns raw | ||
| * argv content beyond the tokens that matched a known command shape. | ||
| */ | ||
|
|
||
| import { distance } from "fastest-levenshtein"; | ||
|
|
||
| /** | ||
| * Old Commander-era syntax (and common agent guesses) mapped to the current | ||
| * command tree. Keys and values are colon-separated oclif ids; values may | ||
| * also be topics (e.g. `cloud:contexts`, which prints topic help). | ||
| */ | ||
| export const aliasSuggestions: ReadonlyMap<string, string> = new Map([ | ||
| ["sessions", "cloud:sessions:list"], | ||
| ["sessions:list", "cloud:sessions:list"], | ||
| ["sessions:create", "cloud:sessions:create"], | ||
| ["sessions:get", "cloud:sessions:get"], | ||
| ["projects", "cloud:projects:list"], | ||
| ["projects:list", "cloud:projects:list"], | ||
| ["contexts", "cloud:contexts"], | ||
| ["extensions", "cloud:extensions"], | ||
| ["search", "cloud:search"], | ||
| ["fetch", "cloud:fetch"], | ||
| ["goto", "open"], | ||
| ["navigate", "open"], | ||
| ]); | ||
|
|
||
| const safeTokenPattern = /^[A-Za-z][A-Za-z0-9_-]*$/; | ||
| const maxCommandTokens = 4; | ||
| const maxSuggestionDistance = 5; | ||
|
|
||
| export interface CommandSuggestion { | ||
| /** Sanitized colon-separated tokens treated as the attempted command. */ | ||
| attempted: string; | ||
| /** Colon-separated suggested command or topic, when a decent match exists. */ | ||
| suggestion: string | null; | ||
| } | ||
|
|
||
| /** | ||
| * Extracts the leading command-shaped tokens from an attempted id, stopping | ||
| * at the first token that does not look like a command word (URLs, selectors, | ||
| * flags, and other argument-like values). | ||
| */ | ||
| export function extractCommandTokens(id: string): string[] { | ||
| const tokens: string[] = []; | ||
| for (const token of id.split(":")) { | ||
| if (tokens.length >= maxCommandTokens || !safeTokenPattern.test(token)) { | ||
| break; | ||
| } | ||
| tokens.push(token.toLowerCase()); | ||
| } | ||
| return tokens; | ||
| } | ||
|
|
||
| function tokenThreshold(token: string): number { | ||
| return Math.max(2, Math.floor(token.length / 3)); | ||
| } | ||
|
|
||
| /** | ||
| * Segment-aligned fuzzy distance between a token prefix and a command id. | ||
| * Only command ids with the same number of segments are considered, and every | ||
| * token must be within its own edit-distance threshold of the corresponding | ||
| * segment. This means a trailing token can only ever be retained in the | ||
| * attempted command when it itself looks like a typo of a real command | ||
| * segment — free-form user values can never ride along. | ||
| */ | ||
| function prefixDistance( | ||
| tokens: readonly string[], | ||
| commandId: string, | ||
| ): number | null { | ||
| const segments = commandId.split(":"); | ||
| if (segments.length !== tokens.length) { | ||
| return null; | ||
| } | ||
|
|
||
| let total = 0; | ||
| for (let i = 0; i < tokens.length; i++) { | ||
| const token = tokens[i] ?? ""; | ||
| const segmentDistance = distance(token, segments[i] ?? ""); | ||
| if (segmentDistance > tokenThreshold(token)) { | ||
| return null; | ||
| } | ||
| total += segmentDistance; | ||
| } | ||
|
|
||
| return total > maxSuggestionDistance ? null : total; | ||
| } | ||
|
|
||
| /** | ||
| * Computes a suggestion for an unknown command id. Explicit aliases win over | ||
| * fuzzy matches, and longer token prefixes win over shorter ones so that | ||
| * `auth status` resolves before `auth`. Returns only the matched prefix as | ||
| * `attempted` (or the first token when nothing matches) so user-provided | ||
| * values never escape into messaging or telemetry. | ||
| */ | ||
| export function suggestCommand( | ||
| id: string, | ||
| commandIds: readonly string[], | ||
| ): CommandSuggestion { | ||
| const tokens = extractCommandTokens(id); | ||
| if (tokens.length === 0) { | ||
| return { attempted: "", suggestion: null }; | ||
| } | ||
|
|
||
| for (let length = tokens.length; length >= 1; length--) { | ||
| const attempted = tokens.slice(0, length).join(":"); | ||
| const alias = aliasSuggestions.get(attempted); | ||
| if (alias) { | ||
| return { attempted, suggestion: alias }; | ||
| } | ||
| } | ||
|
|
||
| let best: (CommandSuggestion & { distance: number }) | undefined; | ||
| for (let length = tokens.length; length >= 1; length--) { | ||
| const prefix = tokens.slice(0, length); | ||
| for (const commandId of commandIds) { | ||
| const prefixDist = prefixDistance(prefix, commandId); | ||
| if (prefixDist !== null && (!best || prefixDist < best.distance)) { | ||
| best = { | ||
| attempted: prefix.join(":"), | ||
| suggestion: commandId, | ||
| distance: prefixDist, | ||
| }; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if (best) { | ||
| return { attempted: best.attempted, suggestion: best.suggestion }; | ||
| } | ||
|
|
||
| return { attempted: tokens[0] ?? "", suggestion: null }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.