Skip to content

Commit 0803173

Browse files
committed
refactor(cli): make the process entry importable and test it directly
bin.ts ran its dispatch at import time, so the only way to prove that an alias --help never loads the full CLI was to spawn the process under NODE_V8_COVERAGE and grep the report for process-entry.ts. That oracle needed a paragraph to justify; the code was wrong, not the comment. The dispatch now lives in src/cli/entry.ts as runEntry(argv, modules, io), with the five lazy imports injected by bin.ts. entry.test.ts drives it with recording loaders and the real help module: every registry alias prints its canonical help with only the help module loaded, an unknown topic falls through to the CLI loader, --version, bare usage, mcp, and startup failures each have one case. The subprocess coverage machinery, the alias table pin, and the multi-line comments are gone; the smoke test keeps one registry-derived byte-identical alias --help check against the real bin.ts. Seen red: hand-routing long-press and relaunch to the CLI loader inside entry.ts failed "every registered alias prints its canonical help without loading the CLI"; restored.
1 parent 3135749 commit 0803173

6 files changed

Lines changed: 238 additions & 273 deletions

File tree

‎src/bin.ts‎

Lines changed: 21 additions & 121 deletions
Original file line numberDiff line numberDiff line change
@@ -1,124 +1,24 @@
1-
const argv = process.argv.slice(2);
1+
import { runEntry } from './cli/entry.ts';
22

33
declare const __AGENT_DEVICE_VERSION__: string;
44

5-
if (runFastPath(argv)) {
6-
// Fast path owns process output and exit behavior.
7-
} else if (argv[0] === 'mcp' && !argv.includes('--help') && !argv.includes('-h')) {
8-
import('./mcp/server.ts')
9-
.then(({ runAgentDeviceMcpServer }) => runAgentDeviceMcpServer())
10-
.catch(handleStartupError);
11-
} else {
12-
runCli(argv);
13-
}
14-
15-
function runFastPath(argv: string[]): boolean {
16-
return runVersionFastPath(argv) || runNoCommandFastPath(argv) || runHelpFastPath(argv);
17-
}
18-
19-
function runVersionFastPath(argv: string[]): boolean {
20-
if (argv.length !== 1 || !isVersionFlag(argv[0])) return false;
21-
if (typeof __AGENT_DEVICE_VERSION__ === 'string') {
22-
process.stdout.write(`${__AGENT_DEVICE_VERSION__}\n`);
23-
return true;
24-
}
25-
import('@agent-device/host-kit/version')
26-
.then(({ readVersion }) => {
27-
process.stdout.write(`${readVersion()}\n`);
28-
})
29-
.catch(handleStartupError);
30-
return true;
31-
}
32-
33-
function runNoCommandFastPath(argv: string[]): boolean {
34-
if (argv.length !== 0) return false;
35-
import('./cli-schema/cli-help.ts')
36-
.then(async ({ buildUsageText }) => {
37-
process.stdout.write(`${buildUsageText()}\n`);
38-
// #1596: exitAfterFlush (not a bare process.exit) so the full usage
39-
// text reaches a piped caller before the process terminates.
40-
const { exitAfterFlush } = await import('./cli/process-exit.ts');
41-
await exitAfterFlush(1);
42-
})
43-
.catch(handleStartupError);
44-
return true;
45-
}
46-
47-
function runHelpFastPath(argv: string[]): boolean {
48-
const helpTarget = resolveSimpleHelpTarget(argv);
49-
if (helpTarget === undefined) return false;
50-
51-
import('./cli-schema/cli-help.ts')
52-
.then(({ resolveHelpTargetUsageText, buildUsageText }) => {
53-
if (helpTarget === null) {
54-
process.stdout.write(`${buildUsageText()}\n`);
55-
return;
56-
}
57-
const commandHelp = resolveHelpTargetUsageText(helpTarget);
58-
if (commandHelp) {
59-
process.stdout.write(commandHelp);
60-
return;
61-
}
62-
// Unknown help topics still need full CLI parsing for the normal error path.
63-
runCli(argv);
64-
})
65-
.catch(handleStartupError);
66-
return true;
67-
}
68-
69-
function resolveSimpleHelpTarget(argv: string[]): string | null | undefined {
70-
switch (argv.length) {
71-
case 1:
72-
return resolveSingleArgHelpTarget(argv[0]);
73-
case 2:
74-
return resolveTwoArgHelpTarget(argv[0], argv[1]);
75-
default:
76-
return undefined;
77-
}
78-
}
79-
80-
function resolveSingleArgHelpTarget(arg: string | undefined): null | undefined {
81-
if (arg === 'help') return null;
82-
return isHelpFlag(arg) ? null : undefined;
83-
}
84-
85-
function resolveTwoArgHelpTarget(
86-
command: string | undefined,
87-
helpArg: string | undefined,
88-
): string | undefined {
89-
if (isHelpCommand(command)) return helpArg;
90-
return resolveTrailingHelpTarget(command, helpArg);
91-
}
92-
93-
function resolveTrailingHelpTarget(
94-
command: string | undefined,
95-
helpArg: string | undefined,
96-
): string | undefined {
97-
return isHelpFlag(helpArg) ? command : undefined;
98-
}
99-
100-
function isHelpCommand(command: string | undefined): boolean {
101-
return command === 'help';
102-
}
103-
104-
function isHelpFlag(arg: string | undefined): boolean {
105-
return arg === '--help' || arg === '-h';
106-
}
107-
108-
function isVersionFlag(arg: string | undefined): boolean {
109-
return arg === '--version' || arg === '-V';
110-
}
111-
112-
function runCli(argv: string[]): void {
113-
import('./cli/process-entry.ts')
114-
.then(({ runCliProcess }) => runCliProcess(argv))
115-
.catch(handleStartupError);
116-
}
117-
118-
function handleStartupError(error: unknown): void {
119-
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
120-
// #1596: exitAfterFlush so the message above isn't dropped on a piped stderr.
121-
import('./cli/process-exit.ts')
122-
.then(({ exitAfterFlush }) => exitAfterFlush(1))
123-
.catch(() => process.exit(1));
124-
}
5+
runEntry(
6+
process.argv.slice(2),
7+
{
8+
help: () => import('./cli-schema/cli-help.ts'),
9+
cli: () => import('./cli/process-entry.ts'),
10+
mcp: () => import('./mcp/server.ts'),
11+
version: () => import('@agent-device/host-kit/version'),
12+
processExit: () => import('./cli/process-exit.ts'),
13+
},
14+
{
15+
bundledVersion:
16+
typeof __AGENT_DEVICE_VERSION__ === 'string' ? __AGENT_DEVICE_VERSION__ : undefined,
17+
stdout: (text) => {
18+
process.stdout.write(text);
19+
},
20+
stderr: (text) => {
21+
process.stderr.write(text);
22+
},
23+
},
24+
).catch(() => process.exit(1));
Lines changed: 10 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,64 +1,22 @@
1-
// Pins `resolveHelpTargetUsageText`, the function `bin.ts`'s `--help` fast path calls to
2-
// resolve a help target through alias normalization before rendering usage text. Before this
3-
// fix, `bin.ts` used its own hand-written two-entry table instead of the shared alias registry,
4-
// so `tap`, `launch`, and `relaunch` silently missed the fast path and fell through to a full
5-
// CLI bootstrap just to print static help text. `bin.ts` runs unguarded top-level dispatch on
6-
// import (and is deliberately excluded from coverage — see vitest.config.ts), so it cannot be
7-
// imported directly in a test; these tests instead pin the function it calls. That makes them a
8-
// real regression pin for a *future* alias missing help text (test 2 is durable for that), but
9-
// not a substitute for the manual proof, run outside this suite, that bin.ts itself calls this
10-
// function (see test/integration/smoke-cli.test.ts for the process-level proof: `tap --help`
11-
// spawned as a real process is byte-identical to `press --help`).
121
import { test } from 'vitest';
132
import assert from 'node:assert/strict';
143
import { buildCommandUsageText, resolveHelpTargetUsageText } from './cli-help.ts';
154
import { cliAliasesForCommand } from '../commands/cli-command-aliases.ts';
165
import { listCliCommandNames } from '../command-catalog.ts';
176

18-
test('alias help output matches its canonical command', () => {
19-
const cases: ReadonlyArray<readonly [string, string]> = [
20-
['tap', 'press'],
21-
['launch', 'open'],
22-
['relaunch', 'open'],
23-
['long-press', 'longpress'],
24-
];
25-
for (const [alias, canonical] of cases) {
26-
const aliasHelp = resolveHelpTargetUsageText(alias);
27-
// The canonical side deliberately calls `buildCommandUsageText` directly (no alias
28-
// normalization), not `resolveHelpTargetUsageText`, so this keeps two independent
29-
// sources instead of comparing one composition against itself. If both sides went
30-
// through `resolveHelpTargetUsageText`, a degenerate normalizer that maps every
31-
// input to one canonical command would still make every case pass.
32-
const canonicalHelp = buildCommandUsageText(canonical);
33-
assert.notEqual(aliasHelp, null, `expected help text for alias "${alias}"`);
34-
assert.equal(
35-
aliasHelp,
36-
canonicalHelp,
37-
`expected "${alias} --help" to be byte-identical to "${canonical} --help"`,
38-
);
39-
}
40-
});
7+
const ALIASES = listCliCommandNames().flatMap((command) =>
8+
cliAliasesForCommand(command).map((entry) => [entry.alias, command] as const),
9+
);
4110

42-
test('every CLI alias resolves to a command with help text', () => {
43-
// Derive the alias list from the registry itself (via the canonical
44-
// commands it targets) rather than hard-coding the five current alias
45-
// names — a hard-coded list would silently stop covering a future sixth
46-
// alias, reintroducing exactly the drift this test exists to catch.
47-
const aliases = listCliCommandNames().flatMap((command) =>
48-
cliAliasesForCommand(command).map((entry) => entry.alias),
49-
);
50-
assert.ok(aliases.length > 0, 'expected at least one alias to exercise this test');
51-
for (const alias of aliases) {
11+
test('every registered alias resolves to its canonical command help', () => {
12+
assert.ok(ALIASES.length > 0);
13+
for (const [alias, canonical] of ALIASES) {
5214
const help = resolveHelpTargetUsageText(alias);
53-
assert.notEqual(help, null, `expected resolveHelpTargetUsageText to resolve alias "${alias}"`);
15+
assert.notEqual(help, null, alias);
16+
assert.equal(help, buildCommandUsageText(canonical), alias);
5417
}
5518
});
5619

57-
test('rotate still has no fast-path help', () => {
58-
// `rotate` is not in the alias registry, so it must fall through to the
59-
// slow path (`src/cli/parser/args.ts`'s `normalizeCommandAlias`), which is
60-
// where the "renamed to orientation" migration error is raised. The fast
61-
// path must never special-case `rotate` itself.
62-
const help = resolveHelpTargetUsageText('rotate');
63-
assert.equal(help, null);
20+
test('a retired command has no help text and is left to the full CLI', () => {
21+
assert.equal(resolveHelpTargetUsageText('rotate'), null);
6422
});

‎src/cli-schema/cli-help.ts‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1213,14 +1213,7 @@ ${helpBody(schema.text)}${flagsSections}
12131213
`;
12141214
}
12151215

1216-
/**
1217-
* `bin.ts`'s `--help` fast path calls this instead of composing
1218-
* `buildCommandUsageText(normalizeCliCommandAlias(...))` itself, so an alias like `tap` or
1219-
* `launch` cannot silently miss alias resolution by calling `buildCommandUsageText` raw. A
1220-
* command name the alias registry does not recognize (including `rotate`, which is retired
1221-
* rather than aliased) passes through unchanged and falls back to `null` exactly as
1222-
* `buildCommandUsageText` would.
1223-
*/
1216+
/** `--help` text for a command name or one of its aliases; `null` when neither has any. */
12241217
export function resolveHelpTargetUsageText(helpTarget: string): string | null {
12251218
return buildCommandUsageText(normalizeCliCommandAlias(helpTarget));
12261219
}

‎src/cli/entry.test.ts‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'vitest';
3+
import * as cliHelp from '../cli-schema/cli-help.ts';
4+
import { listCliCommandNames } from '../command-catalog.ts';
5+
import { cliAliasesForCommand } from '../commands/cli-command-aliases.ts';
6+
import { runEntry, type EntryModules } from './entry.ts';
7+
8+
const ALIASES = listCliCommandNames().flatMap((command) =>
9+
cliAliasesForCommand(command).map((entry) => [entry.alias, command] as const),
10+
);
11+
12+
function harness(options: { bundledVersion?: string; cli?: EntryModules['cli'] } = {}) {
13+
const loaded: string[] = [];
14+
const stdout: string[] = [];
15+
const stderr: string[] = [];
16+
const cliArgv: string[][] = [];
17+
const exits: number[] = [];
18+
const modules: EntryModules = {
19+
help: async () => {
20+
loaded.push('help');
21+
return cliHelp;
22+
},
23+
cli:
24+
options.cli ??
25+
(async () => {
26+
loaded.push('cli');
27+
return {
28+
runCliProcess: async (argv) => {
29+
cliArgv.push(argv);
30+
},
31+
};
32+
}),
33+
mcp: async () => {
34+
loaded.push('mcp');
35+
return { runAgentDeviceMcpServer: async () => {} };
36+
},
37+
version: async () => {
38+
loaded.push('version');
39+
return { readVersion: () => '9.9.9-source' };
40+
},
41+
processExit: async () => ({
42+
exitAfterFlush: async (code) => {
43+
exits.push(code);
44+
},
45+
}),
46+
};
47+
const run = (argv: string[]) =>
48+
runEntry(argv, modules, {
49+
bundledVersion: options.bundledVersion,
50+
stdout: (text) => stdout.push(text),
51+
stderr: (text) => stderr.push(text),
52+
});
53+
return { run, loaded, stdout, stderr, cliArgv, exits };
54+
}
55+
56+
test('every registered alias prints its canonical help without loading the CLI', async () => {
57+
assert.ok(ALIASES.length > 0);
58+
for (const [alias, canonical] of ALIASES) {
59+
const entry = harness();
60+
await entry.run([alias, '--help']);
61+
assert.equal(entry.stdout.join(''), cliHelp.buildCommandUsageText(canonical), alias);
62+
assert.deepEqual(entry.loaded, ['help'], alias);
63+
}
64+
});
65+
66+
test('an unknown help topic falls through to the full CLI', async () => {
67+
const entry = harness();
68+
await entry.run(['rotate', '--help']);
69+
assert.deepEqual(entry.stdout, []);
70+
assert.deepEqual(entry.loaded, ['help', 'cli']);
71+
assert.deepEqual(entry.cliArgv, [['rotate', '--help']]);
72+
});
73+
74+
test('--version prints the bundled version, or reads it when running from source', async () => {
75+
const bundled = harness({ bundledVersion: '1.2.3' });
76+
await bundled.run(['--version']);
77+
assert.deepEqual([bundled.stdout, bundled.loaded], [['1.2.3\n'], []]);
78+
79+
const source = harness();
80+
await source.run(['-V']);
81+
assert.deepEqual([source.stdout, source.loaded], [['9.9.9-source\n'], ['version']]);
82+
});
83+
84+
test('no command prints usage and exits 1 after flushing', async () => {
85+
const entry = harness();
86+
await entry.run([]);
87+
assert.equal(entry.stdout.join(''), `${cliHelp.buildUsageText()}\n`);
88+
assert.deepEqual(entry.exits, [1]);
89+
});
90+
91+
test('mcp starts the server unless help is requested', async () => {
92+
const server = harness();
93+
await server.run(['mcp']);
94+
assert.deepEqual(server.loaded, ['mcp']);
95+
96+
const help = harness();
97+
await help.run(['mcp', '--help']);
98+
assert.deepEqual(help.loaded, ['help']);
99+
assert.equal(help.stdout.join(''), cliHelp.buildCommandUsageText('mcp'));
100+
});
101+
102+
test('a startup failure is reported on stderr and exits 1', async () => {
103+
const entry = harness({
104+
cli: async () => {
105+
throw new Error('boom');
106+
},
107+
});
108+
await entry.run(['press', 'Sign in']);
109+
assert.deepEqual(entry.stderr, ['boom\n']);
110+
assert.deepEqual(entry.exits, [1]);
111+
});

0 commit comments

Comments
 (0)