Files
reverse-engineering-anything/src/cli/guidanceCommands.ts
T
gensokyo-devandgensokyo-dev b990eb496d perf(cli): load only the registrar a one-shot command needs
Every rea process imported and registered all 52 command registrars
(about 1,900 modules) before running any command. A one-shot command
now loads only the registrar that defines its top-level command.

- src/cli/cliCommandRegistrations.ts holds every registrar in one table,
  grouped by tool family, with its module loader and its call. The
  complete createCli registers the table with static imports, and the
  types check that each entry matches its module.
- src/cli/cliShell.ts owns what does not depend on which commands are
  registered: identity, globals, argument policy, completions and the
  registration builtins. The full and lazy paths share it.
- scripts/record-cli-commands.mjs records, after tsc, which registrar
  defines each top-level command, from the same compiled table. The
  bundle keeps the record as an external dist module.
- cli/cliLoader.ts selects the recorded registrar when a known top-level
  command runs. It loads the complete CLI for help, --schema, --llms,
  completions, builtins, unknown names ("did you mean"), or a missing
  record.
- Process-owned CLI resources register their closers when their module
  loads (cli/cliResources.ts), so the shell no longer imports
  JavaScript-analysis and guidance owners just to close them.

Measured on one pinned core (median of 5 warm runs, base main vs this
change):
- guidance: 1.95 s / 253 MB → 0.42 s / 101 MB
- list-cutter-sessions: 1.97 s → 0.49 s
- inspect-go-binary: 1.95 s → 0.95 s
- setup --dry-run: 2.40 s → 1.88 s
- analyze: 2.39 s → 1.78 s
- --help: 1.99 s → 2.04 s (complete CLI, as before)

Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
2026-11-14 20:25:11 +08:00

137 lines
4.9 KiB
TypeScript

import { z } from "incur";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import {
readGuidanceSection,
searchGuidance,
} from "../application/GuidanceAccess.js";
import {
readGuidanceSectionInputSchema,
searchGuidanceLimitSchema,
searchGuidanceInputSchema,
} from "../contracts/guidanceContracts.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { cliDecimalField } from "./options.js";
import { ownCliProcessResource } from "./cliResources.js";
/** Guidance descriptors owned by one CLI host. */
export class CliGuidanceResources {
#retained: ArtifactResourceScope | undefined;
resources(): ArtifactResourceScope {
this.#retained ??= new ArtifactResourceScope();
return this.#retained;
}
/** Release this host's descriptors, retaining failed cleanup for retry. */
async close(): Promise<void> {
const resources = this.#retained;
if (resources === undefined) return;
await resources.close();
if (this.#retained === resources) this.#retained = undefined;
}
}
/** Process CLI host used when a caller does not pass its own resources. */
const processGuidanceResources = new CliGuidanceResources();
/** Release CLI-owned guidance descriptors, retaining failed cleanup for retry. */
export const closeCliGuidanceResources = (
resources: CliGuidanceResources = processGuidanceResources,
): Promise<void> => resources.close();
ownCliProcessResource("guidance", () => closeCliGuidanceResources());
/** Register offline search and retrieval for the installed REA guide bundle. */
export const registerGuidanceCommands = (
cli: CliInstance,
logger: Logger,
resources: CliGuidanceResources = processGuidanceResources,
): void => {
cli.command(CLI_COMMANDS.guidance, {
description: "Search or read the installed REA workflow guidance",
args: z.object({}),
options: z
.object({
action: z
.enum(["search", "read"])
.default("search")
.describe("Guidance action to perform: search or read"),
query: searchGuidanceInputSchema.shape.query
.optional()
.describe(
"Required with search; all non-generic query words must match",
),
locator: readGuidanceSectionInputSchema.shape.locator
.optional()
.describe("Required with --action read; locator returned by search"),
// Decimal tokens only: numeric coercion would read "0x2" as 2.
limit: cliDecimalField(searchGuidanceLimitSchema.optional()).describe(
"Maximum search matches; search only, defaults to 8",
),
cursor: searchGuidanceInputSchema.shape.cursor
.optional()
.describe("Continue a search page; search only"),
})
.superRefine((options, context) => {
if (options.action === "search") {
if (options.query === undefined)
context.addIssue({
code: "custom",
path: ["query"],
message: "--query is required with --action search",
});
if (options.locator !== undefined)
context.addIssue({
code: "custom",
path: ["locator"],
message: "--locator can only be used with --action read",
});
} else {
if (options.locator === undefined)
context.addIssue({
code: "custom",
path: ["locator"],
message: "--locator is required with --action read",
});
for (const option of ["query", "limit", "cursor"] as const)
if (options[option] !== undefined)
context.addIssue({
code: "custom",
path: [option],
message: `--${option} can only be used with --action search`,
});
}
}),
run: ({ options }) =>
logCliCommand(logger, CLI_COMMANDS.guidance, async () => {
const result =
options.action === "search"
? await searchGuidance(
{
...(options.query === undefined
? {}
: { query: options.query }),
...(options.limit === undefined
? {}
: { limit: options.limit }),
...(options.cursor === undefined
? {}
: { cursor: options.cursor }),
},
resources.resources(),
)
: await readGuidanceSection(
{
locator: options.locator,
},
resources.resources(),
);
return result.ok ? result.value : projectAnalysisError(result.error);
}),
});
};