chore(native): reconcile compact reference verification with main
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const MARKER = "REA_TEST_RESOLVED ";
|
||||
// Dependencies that only one command uses; startup must not resolve them.
|
||||
const DEFERRED_PACKAGES = ["playwright-core", "isomorphic-git"] as const;
|
||||
// Report each resolved deferred package on stderr without changing resolution.
|
||||
const RESOLUTION_HOOK = `data:text/javascript,${encodeURIComponent(`
|
||||
import { registerHooks } from "node:module";
|
||||
const packages = ${JSON.stringify(DEFERRED_PACKAGES)};
|
||||
registerHooks({
|
||||
resolve(specifier, context, next) {
|
||||
const resolved = next(specifier, context);
|
||||
const name = packages.find((item) =>
|
||||
resolved.url.includes("/node_modules/" + item + "/"),
|
||||
);
|
||||
if (name !== undefined)
|
||||
process.stderr.write(${JSON.stringify(MARKER)} + name + "\\n");
|
||||
return resolved;
|
||||
},
|
||||
});
|
||||
`)}`;
|
||||
|
||||
const resolvedPackages = async (
|
||||
arguments_: readonly string[],
|
||||
): Promise<ReadonlySet<string>> => {
|
||||
const { stderr } = await execute(
|
||||
process.execPath,
|
||||
[`--import=${RESOLUTION_HOOK}`, ...arguments_],
|
||||
{ cwd: process.cwd(), maxBuffer: 16 * 1_024 * 1_024 },
|
||||
);
|
||||
return new Set(
|
||||
stderr
|
||||
.split("\n")
|
||||
.filter((line) => line.startsWith(MARKER))
|
||||
.map((line) => line.slice(MARKER.length)),
|
||||
);
|
||||
};
|
||||
|
||||
const evaluate = (source: string): readonly string[] => [
|
||||
"--input-type=module",
|
||||
"--eval",
|
||||
source,
|
||||
];
|
||||
|
||||
describe("CLI startup imports", () => {
|
||||
it("detects each deferred package when its command code loads", async () => {
|
||||
await expect(
|
||||
resolvedPackages(
|
||||
evaluate('await import("./dist/composition/browserScenario.js");'),
|
||||
),
|
||||
).resolves.toContain("playwright-core");
|
||||
const source = await createTestTempDirectory("rea-startup-imports-");
|
||||
await mkdir(join(source, ".git"));
|
||||
await expect(
|
||||
resolvedPackages(
|
||||
evaluate(
|
||||
`const { readReferenceSourceVcs } = await import("./dist/application/ReferenceSourceVcsAdapter.js"); await readReferenceSourceVcs(${JSON.stringify(source)});`,
|
||||
),
|
||||
),
|
||||
).resolves.toContain("isomorphic-git");
|
||||
});
|
||||
|
||||
it("does not load command-specific packages to register commands", async () => {
|
||||
await expect(
|
||||
resolvedPackages(["scripts/rea.mjs", "--help"]),
|
||||
).resolves.toEqual(new Set());
|
||||
});
|
||||
});
|
||||
@@ -169,7 +169,7 @@ const createBuildCacheFixture = async (): Promise<string> => {
|
||||
"scripts/clean-build-output.mjs",
|
||||
"scripts/generate-package-metadata.mjs",
|
||||
"scripts/lib/generated-file.mjs",
|
||||
"skill-src/reverse-engineer-anything/SKILL.md",
|
||||
".agents/skills/reverse-engineer-anything/SKILL.md",
|
||||
"src/generatedPackageMetadata.ts",
|
||||
];
|
||||
await Promise.all(
|
||||
|
||||
@@ -21,7 +21,7 @@ async function fixture(eol = "\n") {
|
||||
await mkdir(dirname(join(root, path)), { recursive: true });
|
||||
await copyFile(join(repositoryRoot, path), join(root, path));
|
||||
}
|
||||
const sourceRoot = join(root, "skill-src/reverse-engineer-anything");
|
||||
const sourceRoot = join(root, ".agents/skills/reverse-engineer-anything");
|
||||
const outputRoot = join(root, "skills/reverse-engineer-anything");
|
||||
await mkdir(join(sourceRoot, "references"), { recursive: true });
|
||||
await mkdir(join(root, "dist"));
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it("analyzes direct returns after deep source without exhausting the default process stack", async () => {
|
||||
const root = await createTestTempDirectory("rea-deep-direct-returns-");
|
||||
await writeFile(
|
||||
join(root, "app.js"),
|
||||
`export function render() { object${".property".repeat(20_000)}; function nested() { return "nested"; } class Inner { method() { return "method"; } } return "ready"; }`,
|
||||
);
|
||||
const service = new URL(
|
||||
"../../../dist/application/javascript/JavaScriptApplicationService.js",
|
||||
import.meta.url,
|
||||
).href;
|
||||
const script = `
|
||||
import { analyzeJavaScriptApplication } from ${JSON.stringify(service)};
|
||||
const result = await analyzeJavaScriptApplication({ input_path: ${JSON.stringify(root)}, format: "directory" });
|
||||
if (!result.ok) throw result.error;
|
||||
const nodes = result.value.normalized_result.semantic_graph.nodes;
|
||||
console.log(JSON.stringify(nodes.filter(node => node.kind === "return-site").map(node => node.function_node_id)));
|
||||
`;
|
||||
const { stdout, stderr } = await promisify(execFile)(
|
||||
process.execPath,
|
||||
["--input-type=module", "-e", script],
|
||||
{
|
||||
timeout: 10_000,
|
||||
// Bound the child heap while retaining Node's default stack size.
|
||||
env: {
|
||||
HOME: root,
|
||||
TMPDIR: root,
|
||||
NODE_OPTIONS: "--max-old-space-size=768",
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(stderr).toBe("");
|
||||
const owners: unknown = JSON.parse(stdout);
|
||||
expect(owners).toHaveLength(3);
|
||||
expect(new Set(Array.isArray(owners) ? owners : []).size).toBe(3);
|
||||
});
|
||||
@@ -1,4 +1,6 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
@@ -43,6 +45,79 @@ describe("production MCP doctor", () => {
|
||||
);
|
||||
}, 30_000);
|
||||
|
||||
it("rejects a schema-invalid probe while retaining the discovered inventory", async () => {
|
||||
const root = await createTestTempDirectory("rea-mcp-doctor-reply-");
|
||||
const snapshotPath = join(root, "reply.json");
|
||||
const environment = { PATH: process.env.PATH ?? "" };
|
||||
const client = new Client({ name: "doctor-reply-capture", version: "1" });
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("scripts/rea.mjs"), "mcp"],
|
||||
cwd: process.cwd(),
|
||||
env: environment,
|
||||
stderr: "pipe",
|
||||
});
|
||||
transport.stderr?.on("data", () => undefined);
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const tools = await client.listTools();
|
||||
const prompts = await client.listPrompts();
|
||||
const toolDefinition = tools.tools.find(
|
||||
({ name }) => name === "binary_session",
|
||||
);
|
||||
if (toolDefinition === undefined)
|
||||
throw new Error("Production binary_session contract is missing");
|
||||
const reply = await client.callTool(
|
||||
{ name: "binary_session", arguments: {} },
|
||||
{ toolDefinition },
|
||||
);
|
||||
await writeFile(
|
||||
snapshotPath,
|
||||
JSON.stringify({
|
||||
serverInfo: client.getServerVersion(),
|
||||
protocolVersion: client.getNegotiatedProtocolVersion(),
|
||||
tools,
|
||||
prompts,
|
||||
reply,
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await client.close();
|
||||
await transport.close();
|
||||
}
|
||||
// Replay real production metadata through a synthetic stdio producer.
|
||||
for (const mode of ["valid", "invalid"]) {
|
||||
const result = await runProductionMcpDoctor({
|
||||
command: process.execPath,
|
||||
args: [
|
||||
resolve("tests/fixtures/mcpDoctorReply.mjs"),
|
||||
snapshotPath,
|
||||
mode,
|
||||
],
|
||||
cwd: process.cwd(),
|
||||
environment,
|
||||
});
|
||||
expect(result.healthy).toBe(mode === "valid");
|
||||
expect(result.inventory?.tools.observed).toBe(
|
||||
CATALOG_IDENTITY.counts.mcp_tools,
|
||||
);
|
||||
expect(result.inventory?.prompts.observed).toBe(
|
||||
CATALOG_IDENTITY.counts.mcp_prompts,
|
||||
);
|
||||
expect(result.checks).toContainEqual({
|
||||
name: "initialize",
|
||||
ok: true,
|
||||
detail: expect.any(String),
|
||||
});
|
||||
if (mode === "invalid")
|
||||
expect(result.checks).toContainEqual({
|
||||
name: "request-flow",
|
||||
ok: false,
|
||||
detail: expect.stringMatching(/output schema/iu),
|
||||
});
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
it("reports exact missing, unexpected, and duplicate inventory names", () => {
|
||||
expect(compareInventory(["a", "b"], ["b", "c", "c"])).toEqual({
|
||||
expected: 2,
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { toolOutputSchemaWithMetadata } from "../../../src/contracts/toolSchemaMetadata.js";
|
||||
|
||||
const advertised = <
|
||||
Schema extends z.ZodType<Readonly<Record<string, unknown>>>,
|
||||
>(
|
||||
schema: Schema,
|
||||
): Schema =>
|
||||
toolOutputSchemaWithMetadata({
|
||||
...toolContract("binary_session"),
|
||||
outputSchema: schema,
|
||||
});
|
||||
|
||||
const connect = async (server: McpServer, client: Client): Promise<void> => {
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
};
|
||||
|
||||
it("validates changed schemas after catalog refreshes and availability changes", async () => {
|
||||
const client = new Client({ name: "output-reuse-test", version: "1" });
|
||||
const server = new McpServer({ name: "output-reuse-fixture", version: "1" });
|
||||
const schema = advertised(z.strictObject({ state: z.literal("ready") }));
|
||||
let state = "ready";
|
||||
const selected = server.registerTool(
|
||||
"selected",
|
||||
{ inputSchema: z.strictObject({}), outputSchema: schema },
|
||||
() => ({ content: [], structuredContent: { state } }),
|
||||
);
|
||||
server.registerTool(
|
||||
"equivalent",
|
||||
{ inputSchema: z.strictObject({}), outputSchema: schema },
|
||||
() => ({ content: [], structuredContent: { state: "ready" } }),
|
||||
);
|
||||
try {
|
||||
await connect(server, client);
|
||||
await client.listTools();
|
||||
expect(
|
||||
(await client.callTool({ name: "selected" })).structuredContent,
|
||||
).toEqual({
|
||||
state: "ready",
|
||||
});
|
||||
await client.listTools();
|
||||
await client.callTool({ name: "equivalent" });
|
||||
|
||||
selected.update({
|
||||
outputSchema: advertised(z.strictObject({ state: z.literal("updated") })),
|
||||
});
|
||||
state = "updated";
|
||||
await client.listTools();
|
||||
expect(
|
||||
(await client.callTool({ name: "selected" })).structuredContent,
|
||||
).toEqual({
|
||||
state: "updated",
|
||||
});
|
||||
selected.disable();
|
||||
const unavailable = await client.listTools();
|
||||
expect(unavailable.tools.some((tool) => tool.name === "selected")).toBe(
|
||||
false,
|
||||
);
|
||||
await expect(client.callTool({ name: "selected" })).rejects.toThrow(
|
||||
/not found|disabled/iu,
|
||||
);
|
||||
await client.callTool({ name: "equivalent" });
|
||||
selected.enable();
|
||||
await client.listTools();
|
||||
await client.callTool({ name: "selected" });
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the new server's schema after reconnecting the client", async () => {
|
||||
const client = new Client({ name: "output-reconnect-test", version: "1" });
|
||||
const servers: McpServer[] = [];
|
||||
try {
|
||||
for (const state of ["first", "second"]) {
|
||||
const server = new McpServer({ name: `fixture-${state}`, version: "1" });
|
||||
servers.push(server);
|
||||
server.registerTool(
|
||||
"selected",
|
||||
{
|
||||
inputSchema: z.strictObject({}),
|
||||
outputSchema: advertised(z.strictObject({ state: z.literal(state) })),
|
||||
},
|
||||
() => ({ content: [], structuredContent: { state } }),
|
||||
);
|
||||
await connect(server, client);
|
||||
await client.listTools();
|
||||
expect(
|
||||
(await client.callTool({ name: "selected" })).structuredContent,
|
||||
).toEqual({ state });
|
||||
await client.close();
|
||||
await server.close();
|
||||
}
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
...servers.map((server) => server.close()),
|
||||
]);
|
||||
}
|
||||
});
|
||||
@@ -64,6 +64,7 @@ itWithCaptureCapability(
|
||||
).toBe(true);
|
||||
expect(capture.manifest.comparison_contract).toMatchObject({
|
||||
port_normalization_version: "contextual-endpoints-v2",
|
||||
rendered_line_format: "trailing-spaces-trimmed-v1",
|
||||
});
|
||||
expect(capture.exit).toMatchObject({ code: 0, reason: "exited" });
|
||||
expect(capture.cleanup).toMatchObject({
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
@@ -7,6 +8,7 @@ import { expect, it, onTestFinished } from "vitest";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { compareProcessCaptures } from "../../../src/domain/process/processComparison.js";
|
||||
import { parseProcessCapture } from "../../../src/domain/process/processCaptureParsing.js";
|
||||
import { parseProcessScenario } from "../../../src/domain/process/processScenario.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
@@ -58,6 +60,108 @@ const captureViaMcp = async (scenario: Record<string, unknown>) => {
|
||||
return evidence;
|
||||
};
|
||||
|
||||
itWithCaptureCapability.each(["cli", "mcp"] as const)(
|
||||
"hashes the documented complete report despite omitted terminal output through %s",
|
||||
async (adapter) => {
|
||||
const document = await readFile("docs/process-capture.md", "utf8");
|
||||
const example = document
|
||||
.split("## Hash a report independently of terminal output")[1]
|
||||
?.match(/```json\n([\s\S]*?)\n```/u)?.[1];
|
||||
if (example === undefined)
|
||||
throw new Error("Missing report capture example");
|
||||
const scenario = parseProcessScenario(JSON.parse(example));
|
||||
const root = await createTestTempDirectory("rea-full-report-adapter-");
|
||||
const evidence = await (adapter === "cli" ? captureViaCli : captureViaMcp)({
|
||||
...scenario,
|
||||
executable: process.execPath,
|
||||
working_directory: root,
|
||||
filesystem_observation_paths: [join(root, "reports")],
|
||||
});
|
||||
const capture = parseProcessCapture(evidence.normalized_result);
|
||||
const bytes = await readFile(join(root, "reports", "final.json"));
|
||||
expect(JSON.parse(bytes.toString())).toEqual({
|
||||
status: "complete",
|
||||
data: "X".repeat(131072),
|
||||
});
|
||||
expect(bytes.length).toBeGreaterThan(scenario.limits.output_bytes);
|
||||
expect(capture.files_after).toContainEqual(
|
||||
expect.objectContaining({
|
||||
path: "root_0:final.json",
|
||||
size: bytes.length,
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
}),
|
||||
);
|
||||
expect(capture.truncation_details.filesystem_after).toMatchObject({
|
||||
enumeration_truncated: false,
|
||||
hash_budget_bytes: scenario.limits.file_bytes,
|
||||
hashed_bytes: bytes.length,
|
||||
hash_omissions: [],
|
||||
});
|
||||
expect(capture.truncation_details.raw_terminal.retained_bytes).toBeLessThan(
|
||||
capture.truncation_details.raw_terminal.observed_bytes,
|
||||
);
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability.each(["cli", "mcp"] as const)(
|
||||
"accounts for exact cumulative hash budgets independently at each %s checkpoint",
|
||||
async (adapter) => {
|
||||
const runCapture = adapter === "cli" ? captureViaCli : captureViaMcp;
|
||||
for (const shortfall of [0, 1]) {
|
||||
const root = await createTestTempDirectory("rea-report-cumulative-");
|
||||
const periodic = Buffer.from('{"status":"running"}');
|
||||
const final = Buffer.from('{"status":"complete"}');
|
||||
await writeFile(join(root, "periodic.json"), periodic);
|
||||
const budget = periodic.length + final.length - shortfall;
|
||||
const evidence = await runCapture({
|
||||
executable: process.execPath,
|
||||
arguments: [
|
||||
"-e",
|
||||
"require('node:fs').writeFileSync('final.json','{\"status\":\"complete\"}')",
|
||||
],
|
||||
working_directory: root,
|
||||
filesystem_observation_paths: [root],
|
||||
limits: { output_bytes: 1, file_bytes: budget },
|
||||
});
|
||||
const capture = parseProcessCapture(evidence.normalized_result);
|
||||
expect(capture.truncation_details.filesystem_before).toMatchObject({
|
||||
hashed_bytes: periodic.length,
|
||||
hash_omissions: [],
|
||||
});
|
||||
expect(capture.files_after).toContainEqual(
|
||||
expect.objectContaining({
|
||||
path: "root_0:final.json",
|
||||
sha256: createHash("sha256").update(final).digest("hex"),
|
||||
}),
|
||||
);
|
||||
expect(capture.truncation_details.filesystem_after).toMatchObject({
|
||||
enumeration_truncated: false,
|
||||
hashed_bytes: final.length + (shortfall === 0 ? periodic.length : 0),
|
||||
hash_omissions:
|
||||
shortfall === 0
|
||||
? []
|
||||
: [
|
||||
{
|
||||
path: "root_0:periodic.json",
|
||||
reason: "file_bytes_budget",
|
||||
remaining_budget_bytes: periodic.length - 1,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(
|
||||
capture.files_after.find(({ path }) => path === "root_0:periodic.json")
|
||||
?.sha256,
|
||||
).toBe(
|
||||
shortfall === 0
|
||||
? createHash("sha256").update(periodic).digest("hex")
|
||||
: null,
|
||||
);
|
||||
}
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability.each(["cli", "mcp"] as const)(
|
||||
"reports unknown absence instead of deletion in truncated %s capture Evidence",
|
||||
async (adapter) => {
|
||||
|
||||
@@ -552,6 +552,43 @@ describe("native macOS provider inspection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("native macOS provider raw results", () => {
|
||||
it("records command provenance once, in the normalized result", async () => {
|
||||
directory = await createTestTempDirectory("rea-native-");
|
||||
const app = join(directory, "Fixture.app");
|
||||
const executable = join(app, "Contents/MacOS/Fixture");
|
||||
await mkdir(join(app, "Contents/MacOS"), { recursive: true });
|
||||
await writeFile(executable, "fixture");
|
||||
await writeFile(join(app, "Contents/Info.plist"), "fixture");
|
||||
const client = new NativeMacOSProvider(
|
||||
{},
|
||||
new FixtureRunner(),
|
||||
"darwin",
|
||||
).createClient(await nativeMachoTargetForFile(executable, app));
|
||||
const requests: readonly (readonly [
|
||||
Parameters<typeof client.execute>[0],
|
||||
Parameters<typeof client.execute>[1],
|
||||
])[] = [
|
||||
["inspect_macho", {}],
|
||||
["list_architectures", {}],
|
||||
["inspect_signature", {}],
|
||||
["inspect_plist", {}],
|
||||
["demangle_swift", { symbols: ["$s4Test3fooyyF", "plain_symbol"] }],
|
||||
];
|
||||
|
||||
for (const [operation, parameters] of requests) {
|
||||
const execution = await client.execute(operation, parameters);
|
||||
if (!execution.ok) throw execution.error;
|
||||
expect(execution.value.rawResult, operation).toBeNull();
|
||||
expect(execution.value.result, operation).toMatchObject({
|
||||
provenance: expect.arrayContaining([
|
||||
expect.objectContaining({ tool: expect.any(String) }),
|
||||
]),
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("native plist defaults for iOS-style bundles", () => {
|
||||
it("defaults to the Info.plist the bundle program was resolved from", async () => {
|
||||
directory = await createTestTempDirectory("rea-native-flat-");
|
||||
|
||||
Reference in New Issue
Block a user