From 3f83c8720158bb90a480355b449fb98aa903fa61 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:29:07 -0500 Subject: [PATCH] perf(cli): decouple lazy CLI startup from AnalysisView, session contracts, and MCP registration (#13435) * perf(cli): decouple lazy CLI startup from AnalysisView, session contracts, and MCP registration * test(cli): use bundled CLI runs for heavy startup positive controls --- src/cli/analysisEvidenceDelivery.ts | 5 +- src/cli/analysisViewCommands.ts | 10 +- src/cli/cliShell.ts | 18 +-- src/cli/coreBinaryCommands.ts | 2 +- src/cli/coreNativeCommands.ts | 2 +- src/cli/decompileDirectoryCommand.ts | 2 +- src/cli/mcpBuiltinCommands.ts | 13 ++ src/cli/mcpRegistration.ts | 16 +-- src/cli/nativeTargetOption.ts | 54 ++++++++ src/cli/options.ts | 55 -------- tests/boundary/cli/cliStartupImports.test.ts | 124 +++++++++++++++++-- 11 files changed, 206 insertions(+), 95 deletions(-) create mode 100644 src/cli/nativeTargetOption.ts diff --git a/src/cli/analysisEvidenceDelivery.ts b/src/cli/analysisEvidenceDelivery.ts index ba220589ed..61a51a1dc7 100644 --- a/src/cli/analysisEvidenceDelivery.ts +++ b/src/cli/analysisEvidenceDelivery.ts @@ -28,7 +28,6 @@ import { evidenceDeliveryCommitted, publishEvidenceDelivery, } from "../application/EvidenceBundleCommands.js"; -import { inspectAnalysisViewValidated } from "../application/analysisView/AnalysisViewService.js"; import { localPathStringSchema } from "../domain/localPath.js"; import { absoluteCallerPath } from "../filesystem/callerPath.js"; import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; @@ -267,7 +266,9 @@ const publishDeliveredEvidence = async ( > => { const delivered = input.detail === "summary" - ? inspectAnalysisViewValidated({ + ? ( + await import("../application/analysisView/AnalysisViewService.js") + ).inspectAnalysisViewValidated({ source: { kind: "inline", evidence: complete }, view: input.view ?? { kind: "summary" }, }) diff --git a/src/cli/analysisViewCommands.ts b/src/cli/analysisViewCommands.ts index 24190cef17..bf9dd25dbc 100644 --- a/src/cli/analysisViewCommands.ts +++ b/src/cli/analysisViewCommands.ts @@ -1,6 +1,5 @@ import { z } from "zod"; -import { inspectAnalysisView } from "../application/analysisView/AnalysisViewService.js"; import { ArtifactResourceScope } from "../resources/index.js"; import { ANALYSIS_VIEW_PROVIDER } from "../domain/investigationProviders.js"; import { inspectEvidenceBundleCommand } from "../application/EvidenceBundleCommands.js"; @@ -101,14 +100,17 @@ export const registerAnalysisViewCommands = ( const resources = new ArtifactResourceScope(); const bundlePath = cliOptions.evidenceBundle; const result = await finishAnalysisCommand( - () => - inspectAnalysisView(document, undefined, { + async () => { + const { inspectAnalysisView } = + await import("../application/analysisView/AnalysisViewService.js"); + return inspectAnalysisView(document, undefined, { signal, resources, ...(bundlePath === undefined ? {} : { evidenceBundlePath: bundlePath }), - }), + }); + }, resources, ANALYSIS_VIEW_PROVIDER.id, operation, diff --git a/src/cli/cliShell.ts b/src/cli/cliShell.ts index 6e13530d1a..01d917f8af 100644 --- a/src/cli/cliShell.ts +++ b/src/cli/cliShell.ts @@ -15,8 +15,10 @@ import type { CliResultOutput } from "./cliResultOutput.js"; import { runCliCommand } from "./runCliCommand.js"; import { completionHelpNote, createCliCompletions } from "./completions.js"; import { serveDiscovery } from "./discovery.js"; -import { reportUnknownMcpSubcommand } from "./mcpBuiltinCommands.js"; -import { serveMcpRegistration } from "./mcpRegistration.js"; +import { + isMcpRegistrationCommand, + reportUnknownMcpSubcommand, +} from "./mcpBuiltinCommands.js"; import { presentOmittableDefaults } from "./omittableDefaults.js"; import type { CliInstance, CliServeOptions } from "./types.js"; @@ -108,12 +110,12 @@ export const createCliShell = (options: CliShellOptions): CliInstance => { const global = parseCliGlobalArguments(arguments_); if (completions.writeScript(global, serveOptions ?? {})) return Promise.resolve(); - const registration = serveMcpRegistration( - global, - environment, - serveOptions ?? {}, - ); - if (registration !== undefined) return registration; + if (isMcpRegistrationCommand(global)) + return import("./mcpRegistration.js").then( + ({ serveMcpRegistration }) => + serveMcpRegistration(global, environment, serveOptions ?? {}) ?? + Promise.resolve(), + ); const result = reportUnknownMcpSubcommand( cli.name, global, diff --git a/src/cli/coreBinaryCommands.ts b/src/cli/coreBinaryCommands.ts index feca796454..15600ce4c8 100644 --- a/src/cli/coreBinaryCommands.ts +++ b/src/cli/coreBinaryCommands.ts @@ -11,7 +11,7 @@ import { import type { DirectAnalysis } from "../composition/directAnalysis.js"; import { CLI_COMMANDS } from "../contracts/cliCommandNames.js"; import type { Logger } from "pino"; -import { nativeTarget } from "./options.js"; +import { nativeTarget } from "./nativeTargetOption.js"; import type { CliInstance } from "./types.js"; import { javaScriptApplicationCliProjection, diff --git a/src/cli/coreNativeCommands.ts b/src/cli/coreNativeCommands.ts index f38b19d07e..eb2cd268e3 100644 --- a/src/cli/coreNativeCommands.ts +++ b/src/cli/coreNativeCommands.ts @@ -6,7 +6,7 @@ import { import type { DirectAnalysis } from "../composition/directAnalysis.js"; import { cliCommandFor } from "../contracts/cliCommandNames.js"; import type { Logger } from "pino"; -import { nativeTarget } from "./options.js"; +import { nativeTarget } from "./nativeTargetOption.js"; import type { CliInstance } from "./types.js"; import { contractNamed } from "./contractCliDescription.js"; import { ENHANCED_TOOL_CONTRACTS } from "../contracts/enhancedToolContracts.js"; diff --git a/src/cli/decompileDirectoryCommand.ts b/src/cli/decompileDirectoryCommand.ts index 5645ac9ed2..aafe2121e6 100644 --- a/src/cli/decompileDirectoryCommand.ts +++ b/src/cli/decompileDirectoryCommand.ts @@ -6,7 +6,7 @@ import { registerContractCommand, type runDirectOnTarget, } from "./contractCommand.js"; -import { nativeTarget } from "./options.js"; +import { nativeTarget } from "./nativeTargetOption.js"; import type { CliInstance } from "./types.js"; /** Register `rea decompile-all`, the directory export of provider pseudocode. */ diff --git a/src/cli/mcpBuiltinCommands.ts b/src/cli/mcpBuiltinCommands.ts index 95c61dbbed..fb71c809b1 100644 --- a/src/cli/mcpBuiltinCommands.ts +++ b/src/cli/mcpBuiltinCommands.ts @@ -1,4 +1,5 @@ import { mcpRegistrationOptionsSchema } from "../contracts/mcpRegistration.js"; +import { PRODUCT_IDENTITY } from "../identity.js"; import type { CliGlobalArguments } from "../cliBuiltinArguments.js"; import { readCliOutputArguments, renderCliDocument } from "../cliOutput.js"; @@ -32,6 +33,18 @@ const PRECEDING_BUILTIN_FLAGS: ReadonlySet = new Set([ "--mcp", ]); +/** Whether this invocation targets `rea mcp add` rather than global discovery. */ +export const isMcpRegistrationCommand = ( + global: CliGlobalArguments, +): boolean => { + const offset = global.command[0] === PRODUCT_IDENTITY.cliBinary ? 1 : 0; + if (global.command[offset] !== "mcp" || global.command[offset + 1] !== "add") + return false; + for (const flag of global.flags) + if (PRECEDING_BUILTIN_FLAGS.has(flag)) return false; + return true; +}; + /** * Report an unknown MCP subcommand through REA's diagnostic renderer, retaining * caller arguments for suggestions and explicit sensitive-value declarations. diff --git a/src/cli/mcpRegistration.ts b/src/cli/mcpRegistration.ts index dbec0cba6c..3d64fd9770 100644 --- a/src/cli/mcpRegistration.ts +++ b/src/cli/mcpRegistration.ts @@ -51,6 +51,7 @@ import { redactExplicitText } from "../domain/explicitSensitiveValues.js"; import { err, ok, type Result } from "../domain/result.js"; import { PRODUCT_IDENTITY } from "../identity.js"; import { createCliResultOutput } from "./cliResultOutput.js"; +import { isMcpRegistrationCommand } from "./mcpBuiltinCommands.js"; import { formatCommandHelp } from "./help.js"; import { withCommandCancellation } from "./commandCancellation.js"; import type { CliInstance } from "./types.js"; @@ -91,27 +92,14 @@ interface RegistrationPresentation { fail(): void; } -const precedingFlags = [ - "--llms", - "--llms-full", - "--mcp", - "--update", - "--incur-update-check", -]; - /** Route only the named REA registration operation; other builtin commands keep their owners. */ export const serveMcpRegistration = ( global: CliGlobalArguments, environment: Readonly, options: ServeOptions, ): Promise | undefined => { + if (!isMcpRegistrationCommand(global)) return undefined; const offset = global.command[0] === PRODUCT_IDENTITY.cliBinary ? 1 : 0; - if ( - global.command[offset] !== "mcp" || - global.command[offset + 1] !== "add" || - precedingFlags.some((flag) => global.flags.has(flag)) - ) - return undefined; return (async () => { const presentation = createRegistrationPresentation(global, options); if ( diff --git a/src/cli/nativeTargetOption.ts b/src/cli/nativeTargetOption.ts new file mode 100644 index 0000000000..30a23f6d95 --- /dev/null +++ b/src/cli/nativeTargetOption.ts @@ -0,0 +1,54 @@ +import { OPEN_BINARY_TOOL_CONTRACT } from "../contracts/sessionToolContracts.js"; +import type { CliSessionTarget } from "./contractCliDescription.js"; + +/** Help of the flags that bind a native target interpretation. */ +const NATIVE_OPEN_HELP = { + format: + "Explicit interpretation: dos-com or raw-binary (headerless), or gamecube-dol (GameCube/Wii DOL, never auto-detected); omission preserves header-based detection", + architecture: + "Caller-supplied CPU family; required with --target-format raw-binary, must be omitted with gamecube-dol", + entryPoint: + "Caller-supplied load and entry address (0xhex); required with --target-format raw-binary, optional with gamecube-dol (must equal the DOL header entry)", + provider: + "Bind deep analysis to a provider ID or use deterministic auto selection", + snapshot: "Load and update a local analysis snapshot", +} as const; + +/** + * A native executable opened as an MCP client opens it, with `open_binary`'s + * format, architecture, entry point and provider fields. An operation that + * loads and updates an analysis snapshot also takes `snapshot_path`, with + * `snapshot` as its help when it differs from the shared one. + */ +export const nativeTarget = ( + description: string, + snapshot?: true | string, +): CliSessionTarget => ({ + description, + open: { + contract: OPEN_BINARY_TOOL_CONTRACT, + fields: { + ...(snapshot === undefined + ? {} + : { + snapshot_path: { + name: "snapshot", + callerPath: true, + description: + snapshot === true ? NATIVE_OPEN_HELP.snapshot : snapshot, + }, + }), + format: { + name: "target-format", + values: ["dos-com", "raw-binary", "gamecube-dol"], + description: NATIVE_OPEN_HELP.format, + }, + architecture: { description: NATIVE_OPEN_HELP.architecture }, + entry_point: { + name: "entry-point", + description: NATIVE_OPEN_HELP.entryPoint, + }, + provider_id: { name: "provider", description: NATIVE_OPEN_HELP.provider }, + }, + }, +}); diff --git a/src/cli/options.ts b/src/cli/options.ts index f4190d2e99..183aa83191 100644 --- a/src/cli/options.ts +++ b/src/cli/options.ts @@ -3,9 +3,6 @@ import { z } from "zod"; import { declaredTokenPattern } from "../domain/schemaConstraints.js"; import { decimalTokenPattern } from "./decimalTokenPattern.js"; -import { OPEN_BINARY_TOOL_CONTRACT } from "../contracts/sessionToolContracts.js"; -import type { CliSessionTarget } from "./contractCliDescription.js"; - /** Decimal integer argv text. Leading zeros stay decimal; `0x` and exponent spellings do not. */ const DECIMAL_INTEGER_TOKEN = /^[0-9]+$/u; @@ -150,55 +147,3 @@ export const cliDecimalShape = >( numericStack(field) === undefined ? field : cliDecimalField(field), ]), ) as Shape; - -/** Help of the flags that bind a native target interpretation. */ -const NATIVE_OPEN_HELP = { - format: - "Explicit interpretation: dos-com or raw-binary (headerless), or gamecube-dol (GameCube/Wii DOL, never auto-detected); omission preserves header-based detection", - architecture: - "Caller-supplied CPU family; required with --target-format raw-binary, must be omitted with gamecube-dol", - entryPoint: - "Caller-supplied load and entry address (0xhex); required with --target-format raw-binary, optional with gamecube-dol (must equal the DOL header entry)", - provider: - "Bind deep analysis to a provider ID or use deterministic auto selection", - snapshot: "Load and update a local analysis snapshot", -} as const; - -/** - * A native executable opened as an MCP client opens it, with `open_binary`'s - * format, architecture, entry point and provider fields. An operation that - * loads and updates an analysis snapshot also takes `snapshot_path`, with - * `snapshot` as its help when it differs from the shared one. - */ -export const nativeTarget = ( - description: string, - snapshot?: true | string, -): CliSessionTarget => ({ - description, - open: { - contract: OPEN_BINARY_TOOL_CONTRACT, - fields: { - ...(snapshot === undefined - ? {} - : { - snapshot_path: { - name: "snapshot", - callerPath: true, - description: - snapshot === true ? NATIVE_OPEN_HELP.snapshot : snapshot, - }, - }), - format: { - name: "target-format", - values: ["dos-com", "raw-binary", "gamecube-dol"], - description: NATIVE_OPEN_HELP.format, - }, - architecture: { description: NATIVE_OPEN_HELP.architecture }, - entry_point: { - name: "entry-point", - description: NATIVE_OPEN_HELP.entryPoint, - }, - provider_id: { name: "provider", description: NATIVE_OPEN_HELP.provider }, - }, - }, -}); diff --git a/tests/boundary/cli/cliStartupImports.test.ts b/tests/boundary/cli/cliStartupImports.test.ts index 911969d9b7..c325e20f93 100644 --- a/tests/boundary/cli/cliStartupImports.test.ts +++ b/tests/boundary/cli/cliStartupImports.test.ts @@ -130,19 +130,45 @@ const DEFERRED_IMPORTS = [ name: "environment-server", path: "/dist/server/environment/serveEnvironment.js", }, + { + name: "mcp-registration", + path: "/dist/cli/mcpRegistration.js", + }, ] as const; + +const HEAVY_SHARED_MODULES = [ + { + name: "analysis-view-service", + path: "/dist/application/analysisView/AnalysisViewService.js", + }, + { + name: "analysis-view-result", + path: "/dist/domain/analysisView/analysisViewResult.js", + }, + { + name: "session-tool-contracts", + path: "/dist/contracts/sessionToolContracts.js", + }, + ...DEFERRED_IMPORTS, +] as const; + // Report each resolved deferred package on stderr without changing resolution. -const RESOLUTION_HOOK = `data:text/javascript,${encodeURIComponent(` +const createResolutionHook = ( + entries: readonly { readonly name: string; readonly path: string }[], +): string => + `data:text/javascript,${encodeURIComponent(` import { registerHooks } from "node:module"; -const imports = ${JSON.stringify(DEFERRED_IMPORTS)}; +const imports = ${JSON.stringify(entries)}; registerHooks({ resolve(specifier, context, next) { const resolved = next(specifier, context); - const name = imports.find((item) => - resolved.url.includes(item.path) || - (item.path.startsWith("/dist/") && item.path.endsWith(".js") && - resolved.url.includes("/dist/cli-runtime/" + item.path.slice(6, -3).split("/").join("__") + "-")), - ); + const name = imports.find((item) => { + if (resolved.url.includes(item.path)) return true; + if (!item.path.startsWith("/dist/") || !item.path.endsWith(".js")) return false; + const facade = "/dist/cli-runtime/" + item.path.slice(6, -3).split("/").join("__") + "-"; + const shared = "/dist/cli-runtime/" + item.path.slice(item.path.lastIndexOf("/") + 1, -3) + "-"; + return resolved.url.includes(facade) || resolved.url.includes(shared); + }); if (name !== undefined) process.stderr.write(${JSON.stringify(MARKER)} + name.name + "\\n"); return resolved; @@ -160,6 +186,10 @@ const resolvedMarkers = (stderr: string): ReadonlySet => const resolvedPackages = async ( arguments_: readonly string[], + entries: readonly { + readonly name: string; + readonly path: string; + }[] = DEFERRED_IMPORTS, ): Promise> => { const commands = await createVerifierCommands(); onTestFinished(() => commands.close()); @@ -167,7 +197,7 @@ const resolvedPackages = async ( () => commands.exec( process.execPath, - [`--import=${RESOLUTION_HOOK}`, ...arguments_], + [`--import=${createResolutionHook(entries)}`, ...arguments_], { cwd: process.cwd(), maxBuffer: 16 * 1_024 * 1_024, timeout: 15_000 }, ), [() => commands.close()], @@ -221,6 +251,9 @@ describe("CLI startup imports", () => { ), ), ).resolves.toContain("isomorphic-git"); + await expect( + resolvedPackages(["scripts/rea.mjs", "mcp", "add", "--help"]), + ).resolves.toContain("mcp-registration"); }); it("does not load command-specific code to register the command catalog", async () => { @@ -289,11 +322,84 @@ describe("CLI startup imports", () => { }); }); +describe("Bundled heavy startup controls", () => { + it("detects bundled heavy modules through native command and AnalysisView runs", async () => { + await expect( + resolvedPackages( + ["scripts/rea.mjs", "decompile-all", "--help"], + HEAVY_SHARED_MODULES, + ), + ).resolves.toContain("session-tool-contracts"); + await expect( + resolvedPackages( + ["scripts/rea.mjs", "inspect-wasm-artifact", "--help"], + HEAVY_SHARED_MODULES, + ), + ).resolves.toContain("analysis-view-result"); + const viewDir = await createTestTempDirectory("rea-startup-view-"); + const samplePath = join(viewDir, "sample.bin"); + const viewInputPath = join(viewDir, "view.json"); + await writeFile(samplePath, "hello world 1234".repeat(40)); + const entropyCommands = await createVerifierCommands(); + onTestFinished(() => entropyCommands.close()); + const { stdout: evidenceJson } = await withVerifierCleanup( + () => + entropyCommands.exec( + process.execPath, + ["scripts/rea.mjs", "inspect-byte-entropy", samplePath, "--json"], + { + cwd: process.cwd(), + maxBuffer: 16 * 1_024 * 1_024, + timeout: 15_000, + }, + ), + [() => entropyCommands.close()], + ); + await writeFile( + viewInputPath, + JSON.stringify({ + source: { kind: "inline", evidence: JSON.parse(evidenceJson) }, + view: { kind: "summary" }, + }), + ); + const viewResolved = await resolvedPackages( + ["scripts/rea.mjs", "inspect-analysis-view", viewInputPath, "--json"], + HEAVY_SHARED_MODULES, + ); + expect(viewResolved).toContain("analysis-view-service"); + expect(viewResolved).toContain("analysis-view-result"); + }); + + it("does not load AnalysisView or session contracts for single-command startup", async () => { + for (const command of ["inspect-uefi-nvram", "inspect-sqlite-database"]) { + await expect( + resolvedPackages( + ["scripts/rea.mjs", command, "--help"], + HEAVY_SHARED_MODULES, + ), + ).resolves.toEqual(new Set()); + } + for (const command of ["inspect-wasm-artifact", "guided-workflows"]) { + const loaded = await resolvedPackages( + ["scripts/rea.mjs", command, "--help"], + HEAVY_SHARED_MODULES, + ); + expect(loaded).not.toContain("analysis-view-service"); + expect(loaded).not.toContain("session-tool-contracts"); + expect(loaded).not.toContain("mcp-registration"); + } + }); +}); + describe("MCP startup imports", () => { it("initializes and lists tools over stdio with HTTP-only environment settings present", async () => { const transport = new StdioClientTransport({ command: process.execPath, - args: [`--import=${RESOLUTION_HOOK}`, "scripts/rea.mjs", "mcp"], + args: [ + `--import=${createResolutionHook(DEFERRED_IMPORTS)}`, + "scripts/rea.mjs", + "mcp", + ], cwd: process.cwd(), env: { PATH: process.env.PATH ?? "",