Compare commits

..
Author SHA1 Message Date
Kaoru0822andClaude Opus 5.5 23ec9931ba fix(native): mark Objective-C declarations partial when the budget cuts their methods
inspect-native-dispatch-metadata returned protocols, classes and categories
with decode status "decoded" and a short or empty method list when the
max_records budget stopped inside that list, which made a truncated list
indistinguishable from a genuinely empty one. Each method-list reader now
reports whether the budget stopped it, and the declaring record reports
partial / method_list_record_budget_exhausted.

Fixes #5543

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 15:00:52 +00:00
15 changed files with 172 additions and 391 deletions

No files matched your search

@@ -1,9 +1,6 @@
import { expect, it } from "vitest";
import {
AnalysisCancelledError,
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import { parseEvidence } from "../domain/evidence.js";
import { browserScenarioInputSchema } from "../domain/browserScenario.js";
@@ -80,45 +77,6 @@ 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,13 +53,7 @@ export const captureBrowserScenario = async (
provider.identity(),
);
} else if (!report.success) {
// 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
)
if (captured.error instanceof AnalysisCancelledError)
return err(
new AnalysisOutputError(
OPERATION,
-2
View File
@@ -74,8 +74,6 @@ 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,23 +73,6 @@ 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,11 +368,7 @@ const timerDelay = (candidate: TimerCandidate): number | null => {
if (candidate.kind !== "schedule" || candidate.method === "setImmediate")
return null;
const delay = candidate.node.arguments[1];
// 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;
return t.isNumericLiteral(delay) ? delay.value : null;
};
const timerId = (candidate: TimerCandidate): string =>
+41
View File
@@ -1193,3 +1193,44 @@ 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",
]),
);
});
});
+23 -16
View File
@@ -31,7 +31,7 @@ export const decodeObjcCategories = (input: {
className: string,
methodType: "instance" | "class",
category: string,
) => string[];
) => { selectors: string[]; budgetExhausted: boolean };
readonly protocols: (list: bigint) => string[];
/** Name of a class defined in this image, from its class_ro_t. */
readonly localClassName: (address: bigint) => string;
@@ -71,6 +71,18 @@ 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,
@@ -80,18 +92,8 @@ export const decodeObjcCategories = (input: {
: className === null
? "unresolved"
: "local",
instance_methods: input.methods(
read.pointer(category + 16n),
owner,
"instance",
name,
),
class_methods: input.methods(
read.pointer(category + 24n),
owner,
"class",
name,
),
instance_methods: instanceMethods.selectors,
class_methods: classMethods.selectors,
protocols: input.protocols(read.pointer(category + 32n)),
properties: readObjcPropertiesOf(read, read.pointer(category + 40n), {
owner: `category ${name}`,
@@ -101,9 +103,14 @@ export const decodeObjcCategories = (input: {
}),
location: read.location(category),
decode:
className === null
? { status: "partial", reason: "category_class_unresolved" }
: { status: "decoded", reason: null },
instanceMethods.budgetExhausted || classMethods.budgetExhausted
? {
status: "partial",
reason: "method_list_record_budget_exhausted",
}
: className === null
? { status: "partial", reason: "category_class_unresolved" }
: { status: "decoded", reason: null },
evidence: read.evidence(category, "Objective-C category_t record"),
});
} catch (cause: unknown) {
+12 -7
View File
@@ -103,9 +103,9 @@ export const decodeObjcDispatchFacets = (input: {
className: string,
methodType: "instance" | "class",
category?: string,
): string[] => {
): { selectors: string[]; budgetExhausted: boolean } => {
const selectors: string[] = [];
if (list === 0n) return selectors;
if (list === 0n) return { selectors, budgetExhausted: false };
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()) break;
if (!budget.admit()) return { selectors, budgetExhausted: true };
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;
return { selectors, budgetExhausted: false };
};
const protocolReader = createObjcProtocolReader({
readers: {
@@ -326,7 +326,11 @@ export const decodeObjcDispatchFacets = (input: {
});
}
}
methods(read.pointer(ro + 32n), name, meta ? "class" : "instance");
const { budgetExhausted } = methods(
read.pointer(ro + 32n),
name,
meta ? "class" : "instance",
);
result.objc_classes.push({
name,
super_class: superclass.name,
@@ -362,8 +366,9 @@ export const decodeObjcDispatchFacets = (input: {
location: read.location(address),
superclass_address: superclass.address,
metaclass_address: meta ? null : hex(read.pointer(address)),
decode:
superclass.name === null && !root
decode: budgetExhausted
? { status: "partial", reason: "method_list_record_budget_exhausted" }
: superclass.name === null && !root
? { status: "partial", reason: "superclass_binding_unresolved" }
: decoded,
evidence: read.evidence(
+16 -7
View File
@@ -39,6 +39,8 @@ 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;
@@ -49,7 +51,10 @@ 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()) break;
if (!read.admit()) {
budget.exhausted = true;
break;
}
const entry = address + 8n + BigInt(index * stride);
let selector = relative
? entry + BigInt(read.i32(entry))
@@ -88,13 +93,14 @@ 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),
...methods(read.pointer(address + 32n), true, false, skipped),
...methods(read.pointer(address + 24n), true, true, skipped, budget),
...methods(read.pointer(address + 32n), true, false, skipped, budget),
];
const optional = [
...methods(read.pointer(address + 40n), false, true, skipped),
...methods(read.pointer(address + 48n), false, false, skipped),
...methods(read.pointer(address + 40n), false, true, skipped, budget),
...methods(read.pointer(address + 48n), false, false, skipped, budget),
];
for (const message of skipped)
failures.push(
@@ -112,8 +118,11 @@ export const createObjcProtocolReader = (input: {
methods: required,
optional_methods: optional,
location: read.location(address),
decode:
skipped.length === 0
// 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
? { status: "decoded", reason: null }
: { status: "partial", reason: "protocol_method_selector_empty" },
evidence: read.evidence(
@@ -217,8 +217,6 @@ cliTest(
issues: [
{
path: ["executable_path"],
reason: "invalid_format",
message: expect.stringContaining("absolute local filesystem path"),
},
],
},
+64 -69
View File
@@ -557,75 +557,70 @@ captureTest(
},
);
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 }) => {
captureTest(
"keeps malformed gRPC-web trailers partial through CLI and MCP without changing capture bytes",
async ({ cli, mcp }) => {
const root = await createTestTempDirectory("rea-grpc-web-trailers-");
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);
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);
}
},
);
@@ -125,41 +125,6 @@ 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,63 +1,13 @@
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",
@@ -446,11 +396,10 @@ it("keeps a parsed terminal failure primary over startup-close abort", async ()
});
it.each([false, true])(
"admits valid static facts and honors cancellation before terminal admission (%s)",
"admits a valid complete response with static facts before EOF cancellation (%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 },
@@ -462,13 +411,10 @@ 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) {
observeWorkerFrames(launched.process.stdout, (frame, beforeEof) => {
if (frame.kind !== "complete") return;
abortedBeforeEof = beforeEof;
controller.abort(reason);
});
}
if (abortAfterTerminal)
launched.process.once("close", () =>
queueMicrotask(() => controller.abort(reason)),
);
return launched;
},
);
@@ -480,7 +426,6 @@ 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");
@@ -1131,13 +1076,15 @@ it.each([
...request,
arguments: [
"-e",
`${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); });`,
`${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); });`,
],
});
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")
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"')
)
failureFrameSeenAfterAbort = true;
});
return launched;
@@ -1,109 +0,0 @@
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,13 +176,7 @@ it.each(["caller", "host"] as const)(
);
let closing: ReturnType<NonNullable<typeof host.close>> | undefined;
try {
// 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);
await expect.poll(async () => (await fakeKunaCalls(kuna)).length).toBe(1);
const probe = (await fakeKunaCalls(kuna))[0];
if (probe === undefined) throw new Error("Missing Kuna version probe");
expect(probe.argv).toEqual(["--version"]);