mirror of
https://github.com/morluto/rea.git
synced 2026-11-23 23:15:58 +00:00
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
This commit is contained in:
1 parent
365bbd9008
commit
3f83c87201
11 files changed
+206
-95
No files matched your search
@@ -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" },
|
||||
})
|
||||
|
||||
@@ -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,
|
||||
|
||||
+10
-8
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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<string> = 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.
|
||||
|
||||
@@ -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<NodeJS.ProcessEnv>,
|
||||
options: ServeOptions,
|
||||
): Promise<void> | 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 (
|
||||
|
||||
@@ -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 },
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -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 = <Shape extends Record<string, z.ZodType>>(
|
||||
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 },
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -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<string> =>
|
||||
|
||||
const resolvedPackages = async (
|
||||
arguments_: readonly string[],
|
||||
entries: readonly {
|
||||
readonly name: string;
|
||||
readonly path: string;
|
||||
}[] = DEFERRED_IMPORTS,
|
||||
): Promise<ReadonlySet<string>> => {
|
||||
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 ?? "",
|
||||
|
||||
Reference in new issue
Block a user