Skip to content

Commit 07d0a0b

Browse files
committed
fix: address review — dead export, case-insensitive suggestions, tighter nearest-name matching
- Drop the export on getNearestCommandNames (module-private; only suggestCommandFor uses it) to satisfy the Fallow unused-export gate. - Lowercase the input token before both the curated-map lookup and the nearest-name pass, so RELAUNCH/Relaunch/TAP/Touch get the same hint as their lowercase forms. Added a curated `tap` entry: lowercase `tap` is normalized to press before the unknown-command check, so the entry only catches case variants like TAP. - Tighten the nearest-name fallback: exact prefix matches win outright (`clos` now suggests only `close`, not "one of: close, logs"), otherwise only ties at the minimum edit distance are kept, and 1-2 character tokens never get a suggestion (`ls` no longer suggests `is`). - Share the "open <app> --relaunch" example string between the curated map and the unknown-flag hint, and extend the registry-drift tests to parse each curated example end-to-end (validates open --relaunch as a registered flag) plus assert keyboard dismiss is a real keyboard action.
1 parent bf9b66b commit 07d0a0b

2 files changed

Lines changed: 103 additions & 25 deletions

File tree

‎src/cli/parser/__tests__/command-suggestions.test.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import assert from 'node:assert/strict';
22
import { test } from 'vitest';
33
import { isKnownCliCommandName } from '../../../command-catalog.ts';
4+
import { keyboardCliReader } from '../../../commands/system/index.ts';
45
import { AppError } from '../../../kernel/errors.ts';
56
import { parseArgs } from '../args.ts';
7+
import type { CliFlags } from '../cli-flags.ts';
68
import { listCommandAliasSuggestionEntries, suggestCommandFor } from '../command-suggestions.ts';
79

810
// Guards against the curated alias map drifting to a command that no longer
@@ -21,6 +23,26 @@ test('every curated alias suggestion target resolves to a registered command', (
2123
}
2224
});
2325

26+
// Guards the full example shapes, not just the leading command token: every
27+
// example must parse as a valid invocation (placeholders substituted), so a
28+
// renamed flag (e.g. open --relaunch) or a dropped subcommand fails here.
29+
test('every curated alias suggestion example parses as a valid invocation', () => {
30+
for (const [guess, suggestion] of listCommandAliasSuggestionEntries()) {
31+
const tokens = suggestion.example
32+
.split(' ')
33+
.map((token) => (token.startsWith('<') ? 'com.example.app' : token));
34+
assert.doesNotThrow(
35+
() => parseArgs(tokens, { strictFlags: true }),
36+
`alias suggestion example for "${guess}" ("${suggestion.example}") no longer parses`,
37+
);
38+
}
39+
});
40+
41+
test('the keyboard dismiss example uses a real keyboard action', () => {
42+
const baseFlags: CliFlags = { json: false, help: false, version: false };
43+
assert.doesNotThrow(() => keyboardCliReader(['dismiss'], baseFlags));
44+
});
45+
2446
test('relaunch suggests the canonical open --relaunch shape', () => {
2547
assert.throws(
2648
() => parseArgs(['relaunch', 'com.example.app']),
@@ -87,6 +109,18 @@ test('screencap and capture suggest screenshot', () => {
87109
}
88110
});
89111

112+
test('curated suggestions are case-insensitive', () => {
113+
assert.equal(suggestCommandFor('RELAUNCH'), 'open <app> --relaunch');
114+
assert.equal(suggestCommandFor('Relaunch'), 'open <app> --relaunch');
115+
assert.equal(suggestCommandFor('TAP'), 'press');
116+
assert.equal(suggestCommandFor('Touch'), 'press');
117+
});
118+
119+
test('known command names in the wrong case suggest their lowercase form', () => {
120+
assert.equal(suggestCommandFor('OPEN'), 'open');
121+
assert.equal(suggestCommandFor('Press'), 'press');
122+
});
123+
90124
test('nonsense command names fall back to nearest-name suggestion or a plain error, never a crash', () => {
91125
assert.throws(
92126
() => parseArgs(['frobnicate']),
@@ -107,6 +141,28 @@ test('near-miss typos of real commands are suggested via edit distance', () => {
107141
);
108142
});
109143

144+
test('a prefix match wins outright instead of bundling weaker edit-distance ties', () => {
145+
// Without the prefix rule, `clos` would suggest "one of: close, logs".
146+
assert.throws(
147+
() => parseArgs(['clos']),
148+
(error: unknown) =>
149+
error instanceof AppError &&
150+
error.code === 'INVALID_ARGS' &&
151+
error.message === 'Unknown command: clos. Did you mean close?',
152+
);
153+
});
154+
155+
test('1-2 character tokens never get a nearest-name suggestion', () => {
156+
// `ls` is one edit from `is`, but suggesting `is` would be a false positive.
157+
assert.throws(
158+
() => parseArgs(['ls']),
159+
(error: unknown) =>
160+
error instanceof AppError &&
161+
error.code === 'INVALID_ARGS' &&
162+
error.message === 'Unknown command: ls',
163+
);
164+
});
165+
110166
test('suggestCommandFor never throws for arbitrary input', () => {
111167
const inputs = ['', ' ', '@#$%', 'a'.repeat(200), 'RELAUNCH', 'Relaunch'];
112168
for (const input of inputs) {

‎src/cli/parser/command-suggestions.ts‎

Lines changed: 47 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,14 @@ import { listCliCommandNames } from '../../command-catalog.ts';
44
* Curated guess -> canonical command mapping for unknown CLI command names.
55
*
66
* Agents (and humans) commonly guess command names that don't exist under that
7-
* spelling, such as `relaunch` instead of `open <app> --relaunch`. Each entry's
8-
* `command` must resolve to a real, registered CLI command name; the
9-
* "alias suggestion targets exist" test in
10-
* `src/cli/parser/__tests__/command-suggestions.test.ts` fails the build on drift.
7+
* spelling, such as `relaunch` instead of `open <app> --relaunch`. Keys must be
8+
* lowercase (lookups lowercase the input token first). Each entry's `command`
9+
* must resolve to a real, registered CLI command name, and each `example` must
10+
* parse as a valid invocation of it; the registry-drift tests in
11+
* `src/cli/parser/__tests__/command-suggestions.test.ts` fail the build on drift.
12+
*
13+
* `tap` is normalized to `press` as a true alias before the unknown-command
14+
* check runs, so its entry here only catches case variants such as `TAP`.
1115
*/
1216
type CommandAliasSuggestion = {
1317
/** Canonical command name this guess should have used. */
@@ -16,11 +20,14 @@ type CommandAliasSuggestion = {
1620
example: string;
1721
};
1822

23+
const OPEN_RELAUNCH_EXAMPLE = 'open <app> --relaunch';
24+
1925
const COMMAND_ALIAS_SUGGESTIONS: Record<string, CommandAliasSuggestion> = {
20-
launch: { command: 'open', example: 'open <app> --relaunch' },
21-
relaunch: { command: 'open', example: 'open <app> --relaunch' },
22-
start: { command: 'open', example: 'open <app> --relaunch' },
23-
restart: { command: 'open', example: 'open <app> --relaunch' },
26+
launch: { command: 'open', example: OPEN_RELAUNCH_EXAMPLE },
27+
relaunch: { command: 'open', example: OPEN_RELAUNCH_EXAMPLE },
28+
start: { command: 'open', example: OPEN_RELAUNCH_EXAMPLE },
29+
restart: { command: 'open', example: OPEN_RELAUNCH_EXAMPLE },
30+
tap: { command: 'press', example: 'press' },
2431
touch: { command: 'press', example: 'press' },
2532
input: { command: 'fill', example: 'fill' },
2633
settext: { command: 'fill', example: 'fill' },
@@ -34,29 +41,42 @@ export function listCommandAliasSuggestionEntries(): Array<[string, CommandAlias
3441
return Object.entries(COMMAND_ALIAS_SUGGESTIONS);
3542
}
3643

37-
function getCuratedCommandSuggestion(command: string): string | undefined {
38-
return COMMAND_ALIAS_SUGGESTIONS[command]?.example;
39-
}
40-
4144
const NEAREST_COMMAND_SUGGESTION_LIMIT = 3;
4245

4346
/**
44-
* Nearest registered command names for an unrecognized command, ranked by a
45-
* prefix-aware edit distance. Names are derived from the live command
46-
* descriptor registry (via `listCliCommandNames`), never hardcoded, so the
47-
* suggestion list can't drift from what the CLI actually supports.
47+
* Nearest registered command names for an unrecognized (lowercased) command
48+
* token. Names are derived from the live command descriptor registry (via
49+
* `listCliCommandNames`), never hardcoded, so the suggestion list can't drift
50+
* from what the CLI actually supports.
51+
*
52+
* Precision rules: 1-2 character tokens never get a suggestion, exact prefix
53+
* matches win outright, and otherwise only ties at the minimum edit distance
54+
* are kept so a strong match is not bundled with a coincidental weak one.
4855
*/
49-
export function getNearestCommandNames(command: string): string[] {
56+
function getNearestCommandNames(command: string): string[] {
57+
if (command.length <= 2) return [];
5058
const names = listCliCommandNames();
59+
const prefixMatches = names.filter((name) => name.startsWith(command));
60+
if (prefixMatches.length > 0) {
61+
return prefixMatches
62+
.sort((a, b) => a.length - b.length || a.localeCompare(b))
63+
.slice(0, NEAREST_COMMAND_SUGGESTION_LIMIT);
64+
}
65+
const threshold = nearestMatchThreshold(command);
5166
const scored = names
5267
.map((name) => ({ name, distance: commandNameDistance(command, name) }))
53-
.filter((entry) => entry.distance <= nearestMatchThreshold(command))
54-
.sort((a, b) => a.distance - b.distance || a.name.localeCompare(b.name));
55-
return scored.slice(0, NEAREST_COMMAND_SUGGESTION_LIMIT).map((entry) => entry.name);
68+
.filter((entry) => entry.distance <= threshold);
69+
if (scored.length === 0) return [];
70+
const best = Math.min(...scored.map((entry) => entry.distance));
71+
return scored
72+
.filter((entry) => entry.distance === best)
73+
.sort((a, b) => a.name.localeCompare(b.name))
74+
.slice(0, NEAREST_COMMAND_SUGGESTION_LIMIT)
75+
.map((entry) => entry.name);
5676
}
5777

5878
function nearestMatchThreshold(command: string): number {
59-
if (command.length <= 3) return 1;
79+
if (command.length < 4) return 1;
6080
if (command.length <= 6) return 2;
6181
return 3;
6282
}
@@ -91,12 +111,14 @@ function levenshteinDistance(a: string, b: string): number {
91111
/**
92112
* Builds the "Did you mean ...?" fragment for an unknown command, or
93113
* `undefined` when neither the curated alias map nor the nearest-name
94-
* fallback has a confident suggestion.
114+
* fallback has a confident suggestion. Matching is case-insensitive so
115+
* `RELAUNCH` and `Touch` get the same hint as their lowercase forms.
95116
*/
96117
export function suggestCommandFor(command: string): string | undefined {
97-
const curated = getCuratedCommandSuggestion(command);
118+
const normalized = command.toLowerCase();
119+
const curated = COMMAND_ALIAS_SUGGESTIONS[normalized]?.example;
98120
if (curated) return curated;
99-
const nearest = getNearestCommandNames(command);
121+
const nearest = getNearestCommandNames(normalized);
100122
if (nearest.length === 0) return undefined;
101123
if (nearest.length === 1) return nearest[0];
102124
return `one of: ${nearest.join(', ')}`;
@@ -121,7 +143,7 @@ const POSITIONAL_APP_FLAG_GUESSES = new Set([
121143

122144
export function formatUnknownFlagMessage(token: string): string {
123145
if (POSITIONAL_APP_FLAG_GUESSES.has(token.toLowerCase())) {
124-
return `Unknown flag: ${token}. The app or bundle id is a positional argument, e.g. open <app> --relaunch.`;
146+
return `Unknown flag: ${token}. The app or bundle id is a positional argument, e.g. ${OPEN_RELAUNCH_EXAMPLE}.`;
125147
}
126148
return `Unknown flag: ${token}`;
127149
}

0 commit comments

Comments
 (0)