Skip to content

Commit 87e3ff9

Browse files
authored
refactor(cli): move CLI head dispatch into src/cli/root.ts (#1444)
* refactor(cli): move CLI head dispatch into src/cli/root.ts Phase 1 of the CLI deepening: version/help early exits, the ocx ready pre-parse (exit 64 before any preflight), and the bounded Codex-shim auto-restore preflight move from src/cli/index.ts into a new pure module src/cli/root.ts. index.ts now awaits runCli() and dispatches via its existing switch; behavior is preserved byte-for-byte. - parseCliHead is pure and unit-tested (tests/cli-head.test.ts) - P1 source-guards in tests/cli-ready.test.ts relocate to root.ts - cli-head/cli-ready/cli-help: 74 pass; typecheck green * test(cli): cover the trailing help alias in parseCliHead CodeRabbit finding on #1444: the help-flag test covered --help and -h after position 0 but not the bare 'help' token, which hasHelpFlag also matches.
1 parent 8716629 commit 87e3ff9

4 files changed

Lines changed: 265 additions & 55 deletions

File tree

‎src/cli/index.ts‎

Lines changed: 18 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,12 @@ import {
3535
} from "./tray-proxy";
3636
import { requestBoundSystemRestart } from "./system-restart-client";
3737
import { installCrashGuards } from "../lib/crash-guard";
38-
import { hasHelpFlag, printSubcommandUsage, printUsage, printVersion } from "./help";
38+
import { hasHelpFlag, printSubcommandUsage, printUsage } from "./help";
3939
import { findAvailablePort, isAddrInUse, PortUnavailableError, shouldPersistSelectedPort, waitForPortAvailable } from "../server/ports";
4040
import { findLiveProxy, probeHostname, type LiveProxy } from "../server/proxy-liveness";
4141
import { createReadinessGate } from "../server/readiness";
42-
import { parseReadyArgs, runReady, type ReadyArgs } from "./ready";
42+
import { runReady, type ReadyArgs } from "./ready";
43+
import { runCli } from "./root";
4344
import { ProxyOwnershipRefusedError, stopProxy } from "../lib/process-control";
4445
import { loadServiceTokenFromFile } from "../lib/service-secrets";
4546
import { diagnoseService, isServiceOwnershipError, serviceCommand, serviceEnvironmentOwnedHere, serviceStartableFromTray, serviceStatusSummary, stopServiceIfInstalled, uninstallServiceIfInstalled } from "../service";
@@ -50,7 +51,6 @@ import { buildDesktop3pRegistry } from "../claude/desktop-3p";
5051
import { installShellHook, uninstallShellHook } from "../server/system-env";
5152
import { startTokenGuardian } from "../oauth/token-guardian";
5253
import { startHistoryMigrationGuardian } from "../codex/history-migration-guardian";
53-
import { maybeAutoRestoreCodexShim } from "./codex-shim-autorestore";
5454
import { maybeShowStarPrompt } from "./star-prompt";
5555
import { scheduleCatalogPrewarm } from "./catalog-prewarm";
5656
import { maybeShowUpdatePrompt } from "../update/notify";
@@ -65,43 +65,15 @@ import { createLocalAttestationSecret } from "../lib/local-management-attestatio
6565
import { MEMORY_DRAIN_RESTART_MS, REPLACEMENT_READY_TIMEOUT_MS } from "../lib/system-restart-contract";
6666

6767
initializeNodeLauncherContext();
68-
const args = process.argv.slice(2);
69-
const command = args[0];
7068

71-
if (command === "--version" || command === "-v" || command === "version") {
72-
printVersion();
73-
process.exit(0);
74-
}
75-
76-
if (command === undefined || command === "help" || command === "--help" || command === "-h") {
77-
if (command === "help" && args[1]) printSubcommandUsage(args[1]);
78-
else printUsage();
79-
process.exit(0);
80-
}
81-
82-
if (command !== undefined && command !== "help" && hasHelpFlag(args.slice(1))) {
83-
printSubcommandUsage(command);
84-
process.exit(0);
85-
}
86-
87-
// P1: pre-parse `ocx ready` and reject invalid arguments with exit 64 BEFORE
88-
// maybeAutoRestoreCodexShim (or any discovery/probe/filesystem-capable global
89-
// preflight) runs. `ready --help` / `help ready` already exited above, so this
90-
// only sees ready args without a help flag. Valid args are stashed so the
91-
// switch dispatch can call runReady without a second parse.
92-
let readyArgs: ReadyArgs | undefined;
93-
if (command === "ready") {
94-
const parsed = parseReadyArgs(args.slice(1));
95-
if (!parsed.ok) {
96-
console.error("Usage: ocx ready [--json] [--wait [--timeout <seconds>]]");
97-
console.error(" --timeout requires --wait; <seconds> must be a positive integer (1..300).");
98-
console.error(" Default wait timeout is 45 seconds.");
99-
process.exit(parsed.code);
100-
}
101-
readyArgs = parsed.args;
102-
}
103-
104-
maybeAutoRestoreCodexShim(command, args);
69+
// Head: version/help early exits, `ready` pre-parse (exit 64 before any
70+
// preflight), and the bounded Codex-shim auto-restore preflight live in
71+
// src/cli/root.ts (Phase 1 of the CLI deepening). runCli exits for
72+
// version/help and returns the dispatchable head otherwise; the switch below
73+
// owns command dispatch.
74+
const head = await runCli(process.argv.slice(2));
75+
const args = head.args;
76+
const command = head.command;
10577

10678
function parsePortOption(): number | undefined {
10779
if (args.length === 1) return undefined;
@@ -1258,14 +1230,17 @@ switch (command) {
12581230
}
12591231
process.exit(live ? 0 : 1);
12601232
}
1261-
case "ready":
1233+
case "ready": {
12621234
// Fail-closed impossible-state guard: readyArgs is populated by the
1263-
// preparse block before maybeAutoRestoreCodexShim, so reaching here
1264-
// without it means dispatch diverged. Refuse with code 64 and perform
1265-
// NO I/O (no discovery/probe). process.exit is `never`, narrowing below.
1235+
// preparse block in src/cli/root.ts before maybeAutoRestoreCodexShim, so
1236+
// reaching here without it means dispatch diverged. Refuse with code 64
1237+
// and perform NO I/O (no discovery/probe). process.exit is `never`,
1238+
// narrowing below.
1239+
const readyArgs = head.readyArgs;
12661240
if (!readyArgs) process.exit(64);
12671241
await handleReady(readyArgs);
12681242
break;
1243+
}
12691244
case "provider": {
12701245
const { handleProviderCommand } = await import("./provider");
12711246
await handleProviderCommand(args.slice(1));

‎src/cli/root.ts‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/**
2+
* CLI head: version/help early exits, `ocx ready` pre-parse, and the bounded
3+
* Codex-shim auto-restore preflight, in that order (Phase 1 of the CLI
4+
* deepening — moved out of src/cli/index.ts).
5+
*
6+
* `parseCliHead` is pure (no I/O, no process access) so the ordering and the
7+
* single-parse contract are unit-testable without a subprocess. `runCli` owns
8+
* the exit paths and the shim preflight, then returns the dispatchable head
9+
* for the command switch in src/cli/index.ts.
10+
*/
11+
import { hasHelpFlag, printSubcommandUsage, printUsage, printVersion } from "./help";
12+
import { parseReadyArgs, type ReadyArgs } from "./ready";
13+
import { maybeAutoRestoreCodexShim } from "./codex-shim-autorestore";
14+
15+
export interface CliHead {
16+
kind: "version" | "help" | "ready" | "command";
17+
command: string | undefined;
18+
args: string[];
19+
/** For kind "help": the subcommand whose usage should print, if any. */
20+
helpTarget?: string;
21+
/** Present only for `ready`; undefined when the ready args failed to parse. */
22+
readyArgs?: ReadyArgs;
23+
}
24+
25+
export function parseCliHead(argv: string[]): CliHead {
26+
const command = argv[0];
27+
const args = argv;
28+
if (command === "--version" || command === "-v" || command === "version") {
29+
return { kind: "version", command, args };
30+
}
31+
if (command === undefined || command === "help" || command === "--help" || command === "-h") {
32+
// `ocx help <sub>` carries the subcommand; bare/flag help prints the full usage.
33+
return {
34+
kind: "help",
35+
command,
36+
args,
37+
...(command === "help" && args[1] ? { helpTarget: args[1] } : {}),
38+
};
39+
}
40+
if (command !== "help" && hasHelpFlag(args.slice(1))) {
41+
// `ocx <cmd> --help|-h|help` prints that command's usage, not the full list.
42+
return { kind: "help", command, args, helpTarget: command };
43+
}
44+
// P1: pre-parse `ocx ready` and reject invalid arguments with exit 64 BEFORE
45+
// maybeAutoRestoreCodexShim (or any discovery/probe/filesystem-capable global
46+
// preflight) runs. `ready --help` / `help ready` already exited above, so this
47+
// only sees ready args without a help flag. Valid args are stashed so the
48+
// switch dispatch can call runReady without a second parse.
49+
if (command === "ready") {
50+
const parsed = parseReadyArgs(args.slice(1));
51+
if (!parsed.ok) return { kind: "ready", command, args, readyArgs: undefined };
52+
return { kind: "ready", command, args, readyArgs: parsed.args };
53+
}
54+
return { kind: "command", command, args };
55+
}
56+
57+
export async function runCli(argv: string[]): Promise<CliHead> {
58+
const head = parseCliHead(argv);
59+
switch (head.kind) {
60+
case "version":
61+
printVersion();
62+
process.exit(0);
63+
case "help": {
64+
if (head.helpTarget) printSubcommandUsage(head.helpTarget);
65+
else printUsage();
66+
process.exit(0);
67+
}
68+
case "ready": {
69+
// Fail-closed impossible-state guard: parseCliHead already ran the
70+
// pre-parse before any shim/preflight side effect, so reaching here
71+
// without readyArgs means dispatch diverged. Refuse with code 64 and
72+
// perform NO I/O (no discovery/probe).
73+
if (!head.readyArgs) {
74+
console.error("Usage: ocx ready [--json] [--wait [--timeout <seconds>]]");
75+
console.error(" --timeout requires --wait; <seconds> must be a positive integer (1..300).");
76+
console.error(" Default wait timeout is 45 seconds.");
77+
process.exit(64);
78+
}
79+
maybeAutoRestoreCodexShim(head.command, head.args);
80+
return head;
81+
}
82+
case "command":
83+
maybeAutoRestoreCodexShim(head.command, head.args);
84+
return head;
85+
}
86+
}

‎tests/cli-head.test.ts‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
import { describe, expect, test } from "bun:test";
2+
import { parseCliHead } from "../src/cli/root";
3+
import { DEFAULT_READY_WAIT_TIMEOUT_SECONDS } from "../src/cli/ready";
4+
5+
describe("parseCliHead (pure CLI head, Phase 1)", () => {
6+
test("version flags exit as version", () => {
7+
expect(parseCliHead(["--version"])).toEqual({ kind: "version", command: "--version", args: ["--version"] });
8+
expect(parseCliHead(["-v"])).toEqual({ kind: "version", command: "-v", args: ["-v"] });
9+
expect(parseCliHead(["version"])).toEqual({ kind: "version", command: "version", args: ["version"] });
10+
});
11+
12+
test("bare help forms exit as help", () => {
13+
expect(parseCliHead([])).toEqual({ kind: "help", command: undefined, args: [] });
14+
expect(parseCliHead(["help"])).toEqual({ kind: "help", command: "help", args: ["help"] });
15+
expect(parseCliHead(["--help"])).toEqual({ kind: "help", command: "--help", args: ["--help"] });
16+
expect(parseCliHead(["-h"])).toEqual({ kind: "help", command: "-h", args: ["-h"] });
17+
});
18+
19+
test("help with a subcommand carries the subcommand", () => {
20+
expect(parseCliHead(["help", "service"])).toEqual({
21+
kind: "help",
22+
command: "help",
23+
args: ["help", "service"],
24+
helpTarget: "service",
25+
});
26+
});
27+
28+
test("help with an unknown subcommand still carries the helpTarget", () => {
29+
expect(parseCliHead(["help", "nosuch"])).toEqual({
30+
kind: "help",
31+
command: "help",
32+
args: ["help", "nosuch"],
33+
helpTarget: "nosuch",
34+
});
35+
});
36+
37+
test("help flag after position 0 is a help exit for that command", () => {
38+
expect(parseCliHead(["sync", "--help"])).toEqual({
39+
kind: "help",
40+
command: "sync",
41+
args: ["sync", "--help"],
42+
helpTarget: "sync",
43+
});
44+
expect(parseCliHead(["sync", "help"])).toEqual({
45+
kind: "help",
46+
command: "sync",
47+
args: ["sync", "help"],
48+
helpTarget: "sync",
49+
});
50+
expect(parseCliHead(["provider", "-h"])).toEqual({
51+
kind: "help",
52+
command: "provider",
53+
args: ["provider", "-h"],
54+
helpTarget: "provider",
55+
});
56+
});
57+
58+
test("helpTarget routes the subcommand or command whose usage should print", () => {
59+
expect(parseCliHead(["help", "service"])).toEqual({
60+
kind: "help",
61+
command: "help",
62+
args: ["help", "service"],
63+
helpTarget: "service",
64+
});
65+
expect(parseCliHead(["sync", "--help"])).toEqual({
66+
kind: "help",
67+
command: "sync",
68+
args: ["sync", "--help"],
69+
helpTarget: "sync",
70+
});
71+
expect(parseCliHead(["provider", "-h"])).toEqual({
72+
kind: "help",
73+
command: "provider",
74+
args: ["provider", "-h"],
75+
helpTarget: "provider",
76+
});
77+
expect(parseCliHead(["ready", "--help"])).toEqual({
78+
kind: "help",
79+
command: "ready",
80+
args: ["ready", "--help"],
81+
helpTarget: "ready",
82+
});
83+
});
84+
85+
test("valid ready args are pre-parsed and stashed", () => {
86+
expect(parseCliHead(["ready"])).toEqual({
87+
kind: "ready",
88+
command: "ready",
89+
args: ["ready"],
90+
readyArgs: { json: false, wait: false, timeoutSeconds: DEFAULT_READY_WAIT_TIMEOUT_SECONDS },
91+
});
92+
expect(parseCliHead(["ready", "--json", "--wait", "--timeout", "120"])).toEqual({
93+
kind: "ready",
94+
command: "ready",
95+
args: ["ready", "--json", "--wait", "--timeout", "120"],
96+
readyArgs: { json: true, wait: true, timeoutSeconds: 120 },
97+
});
98+
});
99+
100+
test("invalid ready args fail closed with no readyArgs", () => {
101+
expect(parseCliHead(["ready", "--timeout", "5"])).toEqual({
102+
kind: "ready",
103+
command: "ready",
104+
args: ["ready", "--timeout", "5"],
105+
readyArgs: undefined,
106+
});
107+
expect(parseCliHead(["ready", "--nope"])).toEqual({
108+
kind: "ready",
109+
command: "ready",
110+
args: ["ready", "--nope"],
111+
readyArgs: undefined,
112+
});
113+
expect(parseCliHead(["ready", "--wait", "--timeout", "abc"])).toEqual({
114+
kind: "ready",
115+
command: "ready",
116+
args: ["ready", "--wait", "--timeout", "abc"],
117+
readyArgs: undefined,
118+
});
119+
});
120+
121+
test("ordinary commands dispatch as command", () => {
122+
expect(parseCliHead(["status"])).toEqual({ kind: "command", command: "status", args: ["status"] });
123+
expect(parseCliHead(["start", "--port", "8080"])).toEqual({
124+
kind: "command",
125+
command: "start",
126+
args: ["start", "--port", "8080"],
127+
});
128+
expect(parseCliHead(["sync"])).toEqual({ kind: "command", command: "sync", args: ["sync"] });
129+
expect(parseCliHead(["provider", "list"])).toEqual({
130+
kind: "command",
131+
command: "provider",
132+
args: ["provider", "list"],
133+
});
134+
expect(parseCliHead([""])).toEqual({ kind: "command", command: "", args: [""] });
135+
});
136+
});

‎tests/cli-ready.test.ts‎

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -681,29 +681,36 @@ describe("handleStart readinessGate wiring (source-level)", () => {
681681
// maybeAutoRestoreCodexShim preflight (or any discovery/probe/filesystem-capable
682682
// step) runs. These source-level guards pin that ordering and the single-parse
683683
// contract so a future edit cannot silently move parsing back into handleReady
684-
// or after auto-restore. No subprocess/network/HOME is used.
684+
// or after auto-restore. The head block lives in src/cli/root.ts (Phase 1 of the
685+
// CLI deepening); the dispatch switch stays in src/cli/index.ts. No
686+
// subprocess/network/HOME is used.
685687
describe("ready pre-parse before maybeAutoRestoreCodexShim (source-level, P1)", () => {
688+
const rootSource = readFileSync(join(import.meta.dir, "../src/cli/root.ts"), "utf8");
686689
const cliSource = readFileSync(join(import.meta.dir, "../src/cli/index.ts"), "utf8");
687690

688691
test("ready pre-parse call runs BEFORE maybeAutoRestoreCodexShim", () => {
689-
const preparseIdx = cliSource.indexOf("parseReadyArgs(args.slice(1))");
692+
const preparseIdx = rootSource.indexOf("parseReadyArgs(args.slice(1))");
690693
expect(preparseIdx, "pre-parse must call parseReadyArgs(args.slice(1))").toBeGreaterThanOrEqual(0);
691-
const autoIdx = cliSource.indexOf("maybeAutoRestoreCodexShim(command, args)");
692-
expect(autoIdx, "maybeAutoRestoreCodexShim(command, args) call must be present").toBeGreaterThanOrEqual(0);
694+
const autoIdx = rootSource.indexOf("maybeAutoRestoreCodexShim(head.command, head.args)");
695+
expect(autoIdx, "maybeAutoRestoreCodexShim must be called in runCli").toBeGreaterThanOrEqual(0);
693696
expect(preparseIdx, "ready pre-parse must precede maybeAutoRestoreCodexShim").toBeLessThan(autoIdx);
694697
});
695698

696699
test("invalid ready exits 64 inside the pre-parse block, before auto-restore", () => {
697-
const autoIdx = cliSource.indexOf("maybeAutoRestoreCodexShim(command, args)");
698-
const beforeAuto = cliSource.slice(0, autoIdx);
700+
// parseCliHead (pure) returns readyArgs: undefined for invalid args; the
701+
// fail-closed runCli guard then exits 64 before any shim/discovery side
702+
// effect can run.
703+
const autoIdx = rootSource.indexOf("maybeAutoRestoreCodexShim(head.command, head.args)");
704+
const beforeAuto = rootSource.slice(0, autoIdx);
699705
expect(beforeAuto).toContain('command === "ready"');
700706
expect(beforeAuto).toContain("parseReadyArgs(args.slice(1))");
701-
expect(beforeAuto).toContain("process.exit(parsed.code)");
707+
expect(beforeAuto).toContain("process.exit(64)");
702708
});
703709

704-
test("exactly one runtime parseReadyArgs(args.slice(1)) call site in cli/index.ts", () => {
705-
const matches = cliSource.match(/parseReadyArgs\(args\.slice\(1\)\)/g);
706-
expect(matches, "parseReadyArgs(args.slice(1)) must appear exactly once (no re-parse)").toHaveLength(1);
710+
test("exactly one runtime parseReadyArgs(args.slice(1)) call site across the CLI head", () => {
711+
const rootMatches = rootSource.match(/parseReadyArgs\(args\.slice\(1\)\)/g);
712+
expect(rootMatches, "parseReadyArgs(args.slice(1)) must appear exactly once in root.ts (no re-parse)").toHaveLength(1);
713+
expect(cliSource).not.toContain("parseReadyArgs(");
707714
});
708715

709716
test("handleReady accepts pre-parsed ReadyArgs and never re-parses", () => {
@@ -720,10 +727,16 @@ describe("ready pre-parse before maybeAutoRestoreCodexShim (source-level, P1)",
720727
});
721728

722729
test("valid ready dispatch reaches handleReady AFTER maybeAutoRestoreCodexShim, with fail-closed guard", () => {
723-
const autoIdx = cliSource.indexOf("maybeAutoRestoreCodexShim(command, args)");
730+
// Ordering: index.ts awaits runCli (which runs parseCliHead and the shim
731+
// preflight inside root.ts) BEFORE the switch dispatches the ready case.
732+
const runCliIdx = cliSource.indexOf("await runCli(process.argv.slice(2))");
733+
expect(runCliIdx, "index.ts must await runCli before dispatch").toBeGreaterThanOrEqual(0);
734+
const switchIdx = cliSource.indexOf("switch (command)");
735+
expect(switchIdx, "the command switch must exist").toBeGreaterThanOrEqual(0);
736+
expect(runCliIdx).toBeLessThan(switchIdx);
737+
expect(rootSource).toContain("maybeAutoRestoreCodexShim(head.command, head.args)");
724738
const readyCaseIdx = cliSource.indexOf('case "ready":');
725739
expect(readyCaseIdx, 'a "ready" switch case must exist').toBeGreaterThanOrEqual(0);
726-
expect(autoIdx).toBeLessThan(readyCaseIdx);
727740
// Slice the whole ready case body (up to the next case), not a fixed width.
728741
const nextCaseIdx = cliSource.indexOf("case ", readyCaseIdx + 1);
729742
const caseBody = cliSource.slice(readyCaseIdx, nextCaseIdx === -1 ? undefined : nextCaseIdx);

0 commit comments

Comments
 (0)