Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
38998e465f | ||
|
|
e52a71602d | ||
|
|
8443692e2b | ||
|
|
7b2087e449 |
No files matched your search
@@ -1,6 +1,9 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisOutputError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { BrowserObservationError } from "../domain/browserObservationError.js";
|
||||
import { parseEvidence } from "../domain/evidence.js";
|
||||
import { browserScenarioInputSchema } from "../domain/browserScenario.js";
|
||||
@@ -77,6 +80,45 @@ it("converts a raw scenario capture retained after cleanup failure", async () =>
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps cancellation and the incomplete capture retained before navigation finished", async () => {
|
||||
const { completeness: _completeness, ...complete } = capture;
|
||||
// The startup failure path retains no steps and no completeness.
|
||||
const incomplete = { ...complete, steps: [] };
|
||||
const failure = new AnalysisCancelledError("capture_browser_scenario", {
|
||||
partialObservation: {
|
||||
kind: "browser-scenario-observation",
|
||||
capture: incomplete,
|
||||
},
|
||||
});
|
||||
const provider: BrowserScenarioCapturePort = {
|
||||
identity: () => ({ id: "fixture", name: "fixture", version: "1" }),
|
||||
captureScenario: async () => err(failure),
|
||||
};
|
||||
const result = await captureBrowserScenario(provider, scenario);
|
||||
if (result.ok) throw new Error("Expected cancellation");
|
||||
expect(result.error).toBe(failure);
|
||||
expect(result.error.partialObservation).toEqual({
|
||||
kind: "browser-scenario-observation",
|
||||
capture: incomplete,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a cancelled capture that claims completeness but is malformed", async () => {
|
||||
const failure = new AnalysisCancelledError("capture_browser_scenario", {
|
||||
partialObservation: {
|
||||
kind: "browser-scenario-observation",
|
||||
capture: { ...capture, steps: [] },
|
||||
},
|
||||
});
|
||||
const provider: BrowserScenarioCapturePort = {
|
||||
identity: () => ({ id: "fixture", name: "fixture", version: "1" }),
|
||||
captureScenario: async () => err(failure),
|
||||
};
|
||||
const result = await captureBrowserScenario(provider, scenario);
|
||||
if (result.ok) throw new Error("Expected failure");
|
||||
expect(result.error).toBeInstanceOf(AnalysisOutputError);
|
||||
});
|
||||
|
||||
it.each([
|
||||
null,
|
||||
{ request: "opaque cancellation" },
|
||||
|
||||
@@ -53,7 +53,13 @@ export const captureBrowserScenario = async (
|
||||
provider.identity(),
|
||||
);
|
||||
} else if (!report.success) {
|
||||
if (captured.error instanceof AnalysisCancelledError)
|
||||
// Only a capture that reports completeness claims to be a completed
|
||||
// report; one cancelled earlier, e.g. during initial navigation, is a
|
||||
// legitimately incomplete observation and keeps its cancellation.
|
||||
if (
|
||||
captured.error instanceof AnalysisCancelledError &&
|
||||
"completeness" in partial.capture
|
||||
)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
|
||||
@@ -74,6 +74,8 @@ describe("CLI JSON path normalization", () => {
|
||||
expect(parsed.error.issues).toEqual([
|
||||
expect.objectContaining({
|
||||
path: ["executable_path"],
|
||||
code: "invalid_format",
|
||||
message: expect.stringContaining("absolute local filesystem path"),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -73,6 +73,23 @@ describe("JavaScript semantic analysis: runtime boundaries 1", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps an overflowing timer delay unknown in a complete semantic result", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
function greet() { return "hello"; }
|
||||
setTimeout(() => greet(), 1e999);
|
||||
`);
|
||||
|
||||
expect(ir.timerOperations).toEqual([
|
||||
expect.objectContaining({
|
||||
kind: "schedule",
|
||||
method: "setTimeout",
|
||||
delayMilliseconds: null,
|
||||
resolution: "complete",
|
||||
}),
|
||||
]);
|
||||
expect(ir.callables.some(({ name }) => name === "greet")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not treat shadowed timer globals as Node timers", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
function run(setTimeout, clearTimeout) {
|
||||
|
||||
@@ -368,7 +368,11 @@ const timerDelay = (candidate: TimerCandidate): number | null => {
|
||||
if (candidate.kind !== "schedule" || candidate.method === "setImmediate")
|
||||
return null;
|
||||
const delay = candidate.node.arguments[1];
|
||||
return t.isNumericLiteral(delay) ? delay.value : null;
|
||||
// An overflowing literal such as 1e999 parses to Infinity, which JSON
|
||||
// Evidence cannot carry; keep that delay unknown like any other.
|
||||
return t.isNumericLiteral(delay) && Number.isFinite(delay.value)
|
||||
? delay.value
|
||||
: null;
|
||||
};
|
||||
|
||||
const timerId = (candidate: TimerCandidate): string =>
|
||||
|
||||
@@ -1193,44 +1193,3 @@ describe("malformed Objective-C protocol method lists", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Objective-C method lists cut by the record budget", () => {
|
||||
it("never reports a declaration decoded while the budget omitted its methods", () => {
|
||||
const complete = decodeAppleDispatchMetadata(fixture(), 100, provenance);
|
||||
const classKey = (item: { name: string; is_meta_class: boolean | null }) =>
|
||||
`${item.name}:${String(item.is_meta_class)}`;
|
||||
const completeProtocols = new Map(
|
||||
complete.objc_protocol_records.map((item) => [item.name, item]),
|
||||
);
|
||||
const completeClasses = new Map(
|
||||
complete.objc_classes.map((item) => [classKey(item), item]),
|
||||
);
|
||||
const cutReasons = new Set<string>();
|
||||
for (let budget = 1; budget < 40; budget++) {
|
||||
const result = decodeAppleDispatchMetadata(fixture(), budget, provenance);
|
||||
for (const record of result.objc_protocol_records) {
|
||||
const full = completeProtocols.get(record.name);
|
||||
if (record.decode.status === "decoded") {
|
||||
expect(record.methods).toEqual(full?.methods);
|
||||
expect(record.optional_methods).toEqual(full?.optional_methods);
|
||||
} else if (record.decode.reason !== null)
|
||||
cutReasons.add(`protocol:${record.decode.reason}`);
|
||||
}
|
||||
for (const record of result.objc_classes) {
|
||||
const full = completeClasses.get(classKey(record));
|
||||
if (record.decode?.status === "decoded")
|
||||
expect(record.methods).toEqual(full?.methods);
|
||||
else if (record.decode?.reason != null)
|
||||
cutReasons.add(`class:${record.decode.reason}`);
|
||||
}
|
||||
}
|
||||
// The fixture has methods on both declaration kinds, so some budget must
|
||||
// admit each declaration but stop inside its method list.
|
||||
expect([...cutReasons]).toEqual(
|
||||
expect.arrayContaining([
|
||||
"protocol:method_list_record_budget_exhausted",
|
||||
"class:method_list_record_budget_exhausted",
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -31,7 +31,7 @@ export const decodeObjcCategories = (input: {
|
||||
className: string,
|
||||
methodType: "instance" | "class",
|
||||
category: string,
|
||||
) => { selectors: string[]; budgetExhausted: boolean };
|
||||
) => string[];
|
||||
readonly protocols: (list: bigint) => string[];
|
||||
/** Name of a class defined in this image, from its class_ro_t. */
|
||||
readonly localClassName: (address: bigint) => string;
|
||||
@@ -71,18 +71,6 @@ export const decodeObjcCategories = (input: {
|
||||
);
|
||||
}
|
||||
const owner = className ?? `(${name})`;
|
||||
const instanceMethods = input.methods(
|
||||
read.pointer(category + 16n),
|
||||
owner,
|
||||
"instance",
|
||||
name,
|
||||
);
|
||||
const classMethods = input.methods(
|
||||
read.pointer(category + 24n),
|
||||
owner,
|
||||
"class",
|
||||
name,
|
||||
);
|
||||
result.objc_categories.push({
|
||||
name,
|
||||
class_name: className,
|
||||
@@ -92,8 +80,18 @@ export const decodeObjcCategories = (input: {
|
||||
: className === null
|
||||
? "unresolved"
|
||||
: "local",
|
||||
instance_methods: instanceMethods.selectors,
|
||||
class_methods: classMethods.selectors,
|
||||
instance_methods: input.methods(
|
||||
read.pointer(category + 16n),
|
||||
owner,
|
||||
"instance",
|
||||
name,
|
||||
),
|
||||
class_methods: input.methods(
|
||||
read.pointer(category + 24n),
|
||||
owner,
|
||||
"class",
|
||||
name,
|
||||
),
|
||||
protocols: input.protocols(read.pointer(category + 32n)),
|
||||
properties: readObjcPropertiesOf(read, read.pointer(category + 40n), {
|
||||
owner: `category ${name}`,
|
||||
@@ -103,14 +101,9 @@ export const decodeObjcCategories = (input: {
|
||||
}),
|
||||
location: read.location(category),
|
||||
decode:
|
||||
instanceMethods.budgetExhausted || classMethods.budgetExhausted
|
||||
? {
|
||||
status: "partial",
|
||||
reason: "method_list_record_budget_exhausted",
|
||||
}
|
||||
: className === null
|
||||
? { status: "partial", reason: "category_class_unresolved" }
|
||||
: { status: "decoded", reason: null },
|
||||
className === null
|
||||
? { status: "partial", reason: "category_class_unresolved" }
|
||||
: { status: "decoded", reason: null },
|
||||
evidence: read.evidence(category, "Objective-C category_t record"),
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
|
||||
@@ -103,9 +103,9 @@ export const decodeObjcDispatchFacets = (input: {
|
||||
className: string,
|
||||
methodType: "instance" | "class",
|
||||
category?: string,
|
||||
): { selectors: string[]; budgetExhausted: boolean } => {
|
||||
): string[] => {
|
||||
const selectors: string[] = [];
|
||||
if (list === 0n) return { selectors, budgetExhausted: false };
|
||||
if (list === 0n) return selectors;
|
||||
const flags = read.u32(list),
|
||||
count = read.u32(list + 4n),
|
||||
relative = (flags & 0x80000000) !== 0;
|
||||
@@ -113,7 +113,7 @@ export const decodeObjcDispatchFacets = (input: {
|
||||
if (stride !== (relative ? 12 : 24))
|
||||
throw new TypeError(`Unsupported method stride/flags at ${hex(list)}`);
|
||||
for (let index = 0; index < count; index++) {
|
||||
if (!budget.admit()) return { selectors, budgetExhausted: true };
|
||||
if (!budget.admit()) break;
|
||||
const entry = list + 8n + BigInt(index * stride);
|
||||
const rel = (field: bigint) => {
|
||||
const displacement = bytes.readInt32LE(read.offset(field, 4));
|
||||
@@ -196,7 +196,7 @@ export const decodeObjcDispatchFacets = (input: {
|
||||
),
|
||||
});
|
||||
}
|
||||
return { selectors, budgetExhausted: false };
|
||||
return selectors;
|
||||
};
|
||||
const protocolReader = createObjcProtocolReader({
|
||||
readers: {
|
||||
@@ -326,11 +326,7 @@ export const decodeObjcDispatchFacets = (input: {
|
||||
});
|
||||
}
|
||||
}
|
||||
const { budgetExhausted } = methods(
|
||||
read.pointer(ro + 32n),
|
||||
name,
|
||||
meta ? "class" : "instance",
|
||||
);
|
||||
methods(read.pointer(ro + 32n), name, meta ? "class" : "instance");
|
||||
result.objc_classes.push({
|
||||
name,
|
||||
super_class: superclass.name,
|
||||
@@ -366,9 +362,8 @@ export const decodeObjcDispatchFacets = (input: {
|
||||
location: read.location(address),
|
||||
superclass_address: superclass.address,
|
||||
metaclass_address: meta ? null : hex(read.pointer(address)),
|
||||
decode: budgetExhausted
|
||||
? { status: "partial", reason: "method_list_record_budget_exhausted" }
|
||||
: superclass.name === null && !root
|
||||
decode:
|
||||
superclass.name === null && !root
|
||||
? { status: "partial", reason: "superclass_binding_unresolved" }
|
||||
: decoded,
|
||||
evidence: read.evidence(
|
||||
|
||||
@@ -39,8 +39,6 @@ export const createObjcProtocolReader = (input: {
|
||||
instance: boolean,
|
||||
/** Entries skipped for an empty selector, reported by the declaring protocol. */
|
||||
emptySelectors: string[],
|
||||
/** Set when the record budget stops the list before its last entry. */
|
||||
budget: { exhausted: boolean },
|
||||
) => {
|
||||
const output: ObjcSwiftMetadata["objc_protocols"][number]["methods"] = [];
|
||||
if (address === 0n) return output;
|
||||
@@ -51,10 +49,7 @@ export const createObjcProtocolReader = (input: {
|
||||
if (stride !== (relative ? 12 : 24))
|
||||
throw new TypeError("Unsupported Objective-C protocol method entry size");
|
||||
for (let index = 0; index < count; index++) {
|
||||
if (!read.admit()) {
|
||||
budget.exhausted = true;
|
||||
break;
|
||||
}
|
||||
if (!read.admit()) break;
|
||||
const entry = address + 8n + BigInt(index * stride);
|
||||
let selector = relative
|
||||
? entry + BigInt(read.i32(entry))
|
||||
@@ -93,14 +88,13 @@ export const createObjcProtocolReader = (input: {
|
||||
if (protocolName.length === 0)
|
||||
throw new TypeError("Objective-C protocol has an empty name");
|
||||
const skipped: string[] = [];
|
||||
const budget = { exhausted: false };
|
||||
const required = [
|
||||
...methods(read.pointer(address + 24n), true, true, skipped, budget),
|
||||
...methods(read.pointer(address + 32n), true, false, skipped, budget),
|
||||
...methods(read.pointer(address + 24n), true, true, skipped),
|
||||
...methods(read.pointer(address + 32n), true, false, skipped),
|
||||
];
|
||||
const optional = [
|
||||
...methods(read.pointer(address + 40n), false, true, skipped, budget),
|
||||
...methods(read.pointer(address + 48n), false, false, skipped, budget),
|
||||
...methods(read.pointer(address + 40n), false, true, skipped),
|
||||
...methods(read.pointer(address + 48n), false, false, skipped),
|
||||
];
|
||||
for (const message of skipped)
|
||||
failures.push(
|
||||
@@ -118,11 +112,8 @@ export const createObjcProtocolReader = (input: {
|
||||
methods: required,
|
||||
optional_methods: optional,
|
||||
location: read.location(address),
|
||||
// A budget-cut list is recoverable with a larger budget, so that
|
||||
// cause is reported first; an empty list is otherwise complete.
|
||||
decode: budget.exhausted
|
||||
? { status: "partial", reason: "method_list_record_budget_exhausted" }
|
||||
: skipped.length === 0
|
||||
decode:
|
||||
skipped.length === 0
|
||||
? { status: "decoded", reason: null }
|
||||
: { status: "partial", reason: "protocol_method_selector_empty" },
|
||||
evidence: read.evidence(
|
||||
|
||||
@@ -217,6 +217,8 @@ cliTest(
|
||||
issues: [
|
||||
{
|
||||
path: ["executable_path"],
|
||||
reason: "invalid_format",
|
||||
message: expect.stringContaining("absolute local filesystem path"),
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -557,70 +557,75 @@ captureTest(
|
||||
},
|
||||
);
|
||||
|
||||
captureTest(
|
||||
"keeps malformed gRPC-web trailers partial through CLI and MCP without changing capture bytes",
|
||||
async ({ cli, mcp }) => {
|
||||
const trailerCases = [
|
||||
["valid", "grpc-status", "0", "complete"],
|
||||
["uppercase", "Grpc-Status", "0", "partial"],
|
||||
["nul", "grpc-status", "0\u0000bad", "partial"],
|
||||
["lf", "grpc-status", "0\nbad", "partial"],
|
||||
["cr", "grpc-status", "0\rbad", "partial"],
|
||||
["vt", "grpc-status", "0\u000bbad", "partial"],
|
||||
["del", "grpc-status", "0\u007fbad", "partial"],
|
||||
] as const;
|
||||
|
||||
captureTest.for(
|
||||
(["grpc-web", "grpc-web-text"] as const).flatMap((framing) =>
|
||||
trailerCases.map(([name, headerName, value, status]) => ({
|
||||
framing,
|
||||
name,
|
||||
headerName,
|
||||
value,
|
||||
status,
|
||||
})),
|
||||
),
|
||||
)(
|
||||
"preserves $framing trailer case $name through CLI and MCP without changing capture bytes",
|
||||
async ({ framing, name, headerName, value, status }, { cli, mcp }) => {
|
||||
const root = await createTestTempDirectory("rea-grpc-web-trailers-");
|
||||
for (const framing of ["grpc-web", "grpc-web-text"] as const)
|
||||
for (const [name, headerName, value, status] of [
|
||||
["valid", "grpc-status", "0", "complete"],
|
||||
["uppercase", "Grpc-Status", "0", "partial"],
|
||||
["nul", "grpc-status", "0\u0000bad", "partial"],
|
||||
["lf", "grpc-status", "0\nbad", "partial"],
|
||||
["cr", "grpc-status", "0\rbad", "partial"],
|
||||
["vt", "grpc-status", "0\u000bbad", "partial"],
|
||||
["del", "grpc-status", "0\u007fbad", "partial"],
|
||||
] as const) {
|
||||
const path = join(root, `${framing}-${name}.har`);
|
||||
const trailer = Buffer.from(`${headerName}: ${value}\r\n`);
|
||||
const body = Buffer.concat([
|
||||
protobufFrame(Buffer.from([8, 1])),
|
||||
protobufFrame(trailer, 128),
|
||||
]);
|
||||
const original = protobufHar(
|
||||
framing === "grpc-web-text"
|
||||
? Buffer.from(body.toString("base64"))
|
||||
: body,
|
||||
`application/${framing}`,
|
||||
);
|
||||
await writeFile(path, original);
|
||||
const response = await cli.run({
|
||||
arguments: [
|
||||
"inspect-web-network-capture",
|
||||
path,
|
||||
"har",
|
||||
"--record",
|
||||
"0",
|
||||
"--protobuf-framing",
|
||||
"auto",
|
||||
"--json",
|
||||
],
|
||||
});
|
||||
expect(response.exitCode, response.stdout + response.stderr).toBe(0);
|
||||
const evidence = parseEvidence(response.json);
|
||||
const report = webNetworkCaptureSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
expect(report.protobuf_coverage?.status, name).toBe(status);
|
||||
expect(report.records[0]?.protobuf?.[0]).toMatchObject({
|
||||
status,
|
||||
framing,
|
||||
examined_bytes: body.length,
|
||||
frames: [
|
||||
{ kind: "data", status: "complete", examined_bytes: 2 },
|
||||
{ kind: "trailer", status, examined_bytes: trailer.length },
|
||||
],
|
||||
fields: [{ number: 1, wire_type: "varint", value: "1" }],
|
||||
});
|
||||
const reply = await mcp.call("inspect_web_network_capture", {
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
record_ordinals: [0],
|
||||
protobuf: { framing: "auto" },
|
||||
});
|
||||
expect(reply.isError, JSON.stringify(reply)).not.toBe(true);
|
||||
expect(reply.structuredContent).toEqual(response.json);
|
||||
expect(await readFile(path, "utf8")).toBe(original);
|
||||
}
|
||||
const path = join(root, `${framing}-${name}.har`);
|
||||
const trailer = Buffer.from(`${headerName}: ${value}\r\n`);
|
||||
const body = Buffer.concat([
|
||||
protobufFrame(Buffer.from([8, 1])),
|
||||
protobufFrame(trailer, 128),
|
||||
]);
|
||||
const original = protobufHar(
|
||||
framing === "grpc-web-text" ? Buffer.from(body.toString("base64")) : body,
|
||||
`application/${framing}`,
|
||||
);
|
||||
await writeFile(path, original);
|
||||
const response = await cli.run({
|
||||
arguments: [
|
||||
"inspect-web-network-capture",
|
||||
path,
|
||||
"har",
|
||||
"--record",
|
||||
"0",
|
||||
"--protobuf-framing",
|
||||
"auto",
|
||||
"--json",
|
||||
],
|
||||
});
|
||||
expect(response.exitCode, response.stdout + response.stderr).toBe(0);
|
||||
const evidence = parseEvidence(response.json);
|
||||
const report = webNetworkCaptureSchema.parse(evidence.normalized_result);
|
||||
expect(report.protobuf_coverage?.status, name).toBe(status);
|
||||
expect(report.records[0]?.protobuf?.[0]).toMatchObject({
|
||||
status,
|
||||
framing,
|
||||
examined_bytes: body.length,
|
||||
frames: [
|
||||
{ kind: "data", status: "complete", examined_bytes: 2 },
|
||||
{ kind: "trailer", status, examined_bytes: trailer.length },
|
||||
],
|
||||
fields: [{ number: 1, wire_type: "varint", value: "1" }],
|
||||
});
|
||||
const reply = await mcp.call("inspect_web_network_capture", {
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
record_ordinals: [0],
|
||||
protobuf: { framing: "auto" },
|
||||
});
|
||||
expect(reply.isError, JSON.stringify(reply)).not.toBe(true);
|
||||
expect(reply.structuredContent).toEqual(response.json);
|
||||
expect(await readFile(path, "utf8")).toBe(original);
|
||||
},
|
||||
);
|
||||
+35
@@ -125,6 +125,41 @@ it("resolves erased wrappers through the composed application graph", async () =
|
||||
expect(parseJavaScriptSource(source, "app.mts")?.errors).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "earlier",
|
||||
source: 'export const target = () => "ready", result = target();',
|
||||
resolved: true,
|
||||
},
|
||||
{
|
||||
name: "later",
|
||||
source: 'export const result = target(), target = () => "ready";',
|
||||
resolved: false,
|
||||
},
|
||||
])(
|
||||
"orders $name exported declarator reads in the composed application graph",
|
||||
async ({ source, resolved }) => {
|
||||
const analysis = await analyzeFiles(new Map([["app.mts", source]]));
|
||||
const calls = analysis.semantic_graph.relations.filter(
|
||||
({ relation }) => relation === "calls",
|
||||
);
|
||||
if (resolved) {
|
||||
expect(calls).toEqual([
|
||||
expect.objectContaining({ resolution: "resolved" }),
|
||||
]);
|
||||
} else {
|
||||
expect(calls.some(({ resolution }) => resolution === "resolved")).toBe(
|
||||
false,
|
||||
);
|
||||
expect(analysis.semantic_graph.unknowns).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation_kinds: expect.arrayContaining(["calls"]),
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "path-value wrappers",
|
||||
|
||||
@@ -1,13 +1,63 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { once } from "node:events";
|
||||
import { createInterface } from "node:readline";
|
||||
import { PassThrough, type Readable } from "node:stream";
|
||||
import { setImmediate as yieldToIo } from "node:timers/promises";
|
||||
import { expect, it } from "vitest";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisOutputError,
|
||||
} from "../../../src/domain/analysisErrorCore.js";
|
||||
import { JavaScriptAnalysisWorker } from "../../../src/javascript/analysis/JavaScriptAnalysisWorker.js";
|
||||
import {
|
||||
javaScriptWorkerMessageSchema,
|
||||
type JavaScriptWorkerMessage,
|
||||
} from "../../../src/javascript/analysis/JavaScriptAnalysisWorkerProtocol.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import type { JavaScriptArtifactFile } from "../../../src/domain/javascript/javascriptArtifactFiles.js";
|
||||
|
||||
const observeWorkerFrames = (
|
||||
stdout: Readable | null | undefined,
|
||||
observe: (frame: JavaScriptWorkerMessage, beforeEof: boolean) => void,
|
||||
): void => {
|
||||
if (stdout === null || stdout === undefined)
|
||||
throw new Error("Expected fixture worker stdout pipe");
|
||||
// The runtime attaches its diagnostic and protocol readers together after
|
||||
// adopting the launch. Wait for that owner before starting a flowing reader.
|
||||
const attach = (event: string | symbol): void => {
|
||||
if (event !== "data") return;
|
||||
stdout.off("newListener", attach);
|
||||
createInterface({ input: stdout }).on("line", (line) =>
|
||||
observe(
|
||||
javaScriptWorkerMessageSchema.parse(JSON.parse(line)),
|
||||
!stdout.readableEnded,
|
||||
),
|
||||
);
|
||||
};
|
||||
stdout.on("newListener", attach);
|
||||
};
|
||||
|
||||
it("preserves buffered startup bytes until the runtime owns stdout", async () => {
|
||||
const stdout = new PassThrough();
|
||||
const frame = { kind: "ready", heap_limit_bytes: 1 } as const;
|
||||
const encoded = JSON.stringify(frame) + "\n";
|
||||
const observed: JavaScriptWorkerMessage[] = [];
|
||||
const owned: Buffer[] = [];
|
||||
observeWorkerFrames(stdout, (message) => observed.push(message));
|
||||
try {
|
||||
stdout.write(encoded);
|
||||
await yieldToIo();
|
||||
expect(observed).toEqual([]);
|
||||
stdout.on("data", (chunk: Buffer) => owned.push(chunk));
|
||||
stdout.end();
|
||||
await once(stdout, "end");
|
||||
expect(observed).toEqual([frame]);
|
||||
expect(Buffer.concat(owned).toString()).toBe(encoded);
|
||||
} finally {
|
||||
stdout.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
const sourceText = "export const observed = 1;";
|
||||
const file: JavaScriptArtifactFile = {
|
||||
path: "app.mjs",
|
||||
@@ -396,10 +446,11 @@ it("keeps a parsed terminal failure primary over startup-close abort", async ()
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
"admits a valid complete response with static facts before EOF cancellation (%s)",
|
||||
"admits valid static facts and honors cancellation before terminal admission (%s)",
|
||||
async (abortAfterTerminal) => {
|
||||
const controller = new AbortController();
|
||||
const reason = { requested: "abort after valid terminal frame" };
|
||||
let abortedBeforeEof = false;
|
||||
const encodedStatic = JSON.stringify(staticCheckpointFacts);
|
||||
const worker = new JavaScriptAnalysisWorker(
|
||||
{ heapMb: 128, timeoutMs: 30_000 },
|
||||
@@ -411,10 +462,13 @@ it.each([false, true])(
|
||||
`${ready} const fs=require("node:fs"); const {createHash}=require("node:crypto"); const staticFacts=JSON.parse(${JSON.stringify(encodedStatic)}); let id; require("node:readline").createInterface({input:process.stdin}).on("line", line => { const request=JSON.parse(line); if(request.file){ id=request.id; const text=JSON.stringify(staticFacts); fs.writeFileSync(id+".static.json",text); process.stdout.write(JSON.stringify({kind:"static",id,bytes:Buffer.byteLength(text),sha256:createHash("sha256").update(text).digest("hex")})+"\\n"); } else { process.stdout.write(JSON.stringify({kind:"complete",id,descriptor:null})+"\\n",()=>process.exit(0)); } });`,
|
||||
],
|
||||
});
|
||||
if (abortAfterTerminal)
|
||||
launched.process.once("close", () =>
|
||||
queueMicrotask(() => controller.abort(reason)),
|
||||
);
|
||||
if (abortAfterTerminal) {
|
||||
observeWorkerFrames(launched.process.stdout, (frame, beforeEof) => {
|
||||
if (frame.kind !== "complete") return;
|
||||
abortedBeforeEof = beforeEof;
|
||||
controller.abort(reason);
|
||||
});
|
||||
}
|
||||
return launched;
|
||||
},
|
||||
);
|
||||
@@ -426,6 +480,7 @@ it.each([false, true])(
|
||||
);
|
||||
expect(controller.signal.aborted).toBe(abortAfterTerminal);
|
||||
if (abortAfterTerminal) {
|
||||
expect(abortedBeforeEof).toBe(true);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error.error._tag).toBe("AnalysisCancelledError");
|
||||
@@ -1076,15 +1131,13 @@ it.each([
|
||||
...request,
|
||||
arguments: [
|
||||
"-e",
|
||||
`${ready} process.stdin.once("data", chunk => { const id=JSON.parse(String(chunk)).id; process.stdout.write(JSON.stringify({kind:"phase",id,phase:"parse"})+"\\n"); const failure=${JSON.stringify(failure)}; failure.kind="failure"; failure.id=id; setTimeout(() => process.stdout.write(JSON.stringify(failure)+"\\n"),20); setInterval(()=>{},1000); });`,
|
||||
`${ready} process.stdin.once("data", chunk => { const id=JSON.parse(String(chunk)).id; const phase={kind:"phase",id,phase:"parse"}; const failure={...${JSON.stringify(failure)},kind:"failure",id,message:"fixture failure delivered after caller cancellation"}; process.stdout.write(JSON.stringify(phase)+"\\n"+JSON.stringify(failure)+"\\n"); setInterval(()=>{},1000); });`,
|
||||
],
|
||||
});
|
||||
launched.process.stdout?.on("data", (chunk: Buffer | string) => {
|
||||
if (String(chunk).includes('"kind":"phase"')) controller.abort(null);
|
||||
if (
|
||||
controller.signal.aborted &&
|
||||
String(chunk).includes('"kind":"failure"')
|
||||
)
|
||||
observeWorkerFrames(launched.process.stdout, (frame) => {
|
||||
// This launcher observer precedes the worker's protocol reader.
|
||||
if (frame.kind === "phase") controller.abort(null);
|
||||
if (controller.signal.aborted && frame.kind === "failure")
|
||||
failureFrameSeenAfterAbort = true;
|
||||
});
|
||||
return launched;
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"retains unknown timer delays and unrelated facts through public CLI and MCP",
|
||||
{ timeout: 60_000 },
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-timer-delay-");
|
||||
const source = [
|
||||
'export function greet() { return "hello"; }',
|
||||
"setTimeout(() => greet(), 1e999);",
|
||||
"setInterval(() => greet(), 1e309);",
|
||||
"setTimeout(() => greet(), 100);",
|
||||
"setTimeout(() => greet(), 1e308);",
|
||||
"setTimeout(() => greet(), Infinity);",
|
||||
"setImmediate(() => greet());",
|
||||
].join("\n");
|
||||
const path = join(root, "main.js");
|
||||
await writeFile(path, source);
|
||||
const digest = createHash("sha256").update(source).digest("hex");
|
||||
const cliResult = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--json"],
|
||||
});
|
||||
expect(cliResult.exitCode).toBe(0);
|
||||
const contract = toolContract("analyze_javascript_application");
|
||||
const cliEvidence = contract.outputSchema.parse(cliResult.json);
|
||||
const graph = javascriptApplicationAnalysisResultSchema.parse(
|
||||
cliEvidence.normalized_result,
|
||||
).semantic_graph;
|
||||
const timers = graph.nodes.filter(({ kind }) => kind === "timer");
|
||||
const pairs = timers.map(({ properties }) => [
|
||||
properties.method,
|
||||
properties.delay_milliseconds,
|
||||
]);
|
||||
const sorted = (values: unknown[]) =>
|
||||
values.map((value) => JSON.stringify(value)).sort();
|
||||
expect(sorted(pairs)).toEqual(
|
||||
sorted([
|
||||
["setTimeout", null],
|
||||
["setInterval", null],
|
||||
["setTimeout", 100],
|
||||
["setTimeout", 1e308],
|
||||
["setTimeout", null],
|
||||
["setImmediate", null],
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
graph.nodes.find(
|
||||
({ kind, label }) => kind === "function" && label === "greet",
|
||||
)?.identity,
|
||||
).toMatchObject({ module_path: "main.js", artifact_sha256: digest });
|
||||
for (const timer of timers) {
|
||||
expect(Object.hasOwn(timer.properties, "delay_milliseconds")).toBe(true);
|
||||
expect(timer.identity).toMatchObject({
|
||||
module_path: "main.js",
|
||||
artifact_sha256: digest,
|
||||
});
|
||||
}
|
||||
|
||||
const client = new Client({ name: "timer-delay-boundary", version: "1" });
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("scripts/rea.mjs"), "mcp"],
|
||||
cwd: process.cwd(),
|
||||
env: { PATH: process.env.PATH ?? "" },
|
||||
stderr: "pipe",
|
||||
});
|
||||
transport.stderr?.on("data", () => undefined);
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const reply = await client.callTool({
|
||||
name: contract.name,
|
||||
arguments: { input_path: root },
|
||||
});
|
||||
expect(reply.isError).not.toBe(true);
|
||||
const evidence = contract.outputSchema.parse(reply.structuredContent);
|
||||
expect(evidence.evidence_id).toBe(cliEvidence.evidence_id);
|
||||
const text = reply.content.find((item) => item.type === "text");
|
||||
if (text?.type !== "text") throw new Error("Missing inline Evidence");
|
||||
expect(
|
||||
contract.outputSchema.parse(JSON.parse(text.text)).evidence_id,
|
||||
).toBe(evidence.evidence_id);
|
||||
const retained = javascriptApplicationAnalysisResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
).semantic_graph;
|
||||
expect(retained.nodes.filter(({ kind }) => kind === "timer")).toEqual(
|
||||
timers,
|
||||
);
|
||||
expect(
|
||||
retained.nodes.some(
|
||||
({ kind, label }) => kind === "function" && label === "greet",
|
||||
),
|
||||
).toBe(true);
|
||||
await expect(client.ping()).resolves.toEqual({});
|
||||
} finally {
|
||||
await Promise.all([client.close(), transport.close()]);
|
||||
}
|
||||
expect(await readFile(path, "utf8")).toBe(source);
|
||||
},
|
||||
);
|
||||
@@ -176,7 +176,13 @@ it.each(["caller", "host"] as const)(
|
||||
);
|
||||
let closing: ReturnType<NonNullable<typeof host.close>> | undefined;
|
||||
try {
|
||||
await expect.poll(async () => (await fakeKunaCalls(kuna)).length).toBe(1);
|
||||
// The preceding Ghidra probe may prepare Darwin process ownership before
|
||||
// Kuna starts; keep startup separate from the bounded post-abort join.
|
||||
await expect
|
||||
.poll(async () => (await fakeKunaCalls(kuna)).length, {
|
||||
timeout: 10_000,
|
||||
})
|
||||
.toBe(1);
|
||||
const probe = (await fakeKunaCalls(kuna))[0];
|
||||
if (probe === undefined) throw new Error("Missing Kuna version probe");
|
||||
expect(probe.argv).toEqual(["--version"]);
|
||||
|
||||
Reference in new issue
Block a user