From b1b0211c284f06e67d697dd8e016925f833eca6c Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Wed, 14 Oct 2026 07:11:55 +0800 Subject: [PATCH 1/3] fix(native): preserve observed function dossier coverage Declare observed Ghidra and Hopper facets, preserve unavailable pseudocode, and attach dossier call-set coverage. Version the analysis profiles to invalidate older snapshots and remove the retired include_assembly fixture branch. Add MCP comparison and snapshot-replay regressions plus real-provider checks for empty and unavailable facets. Fixes #2980. --- bridge/ghidra/ReaGhidraBridge.java | 19 +++- bridge/hopper_bridge.py | 10 +- docs/mcp-contracts.md | 8 +- scripts/lib/native-value-e2e.mjs | 6 +- scripts/lib/real-ghidra-boundaries.mjs | 19 ++++ scripts/lib/real-hopper-semantic.mjs | 53 ++++++++++- src/domain/ghidraValues.fixture.ts | 16 +++- src/ghidra/GhidraAnalysisProfile.ts | 3 + src/ghidra/GhidraProvider.behavior.test.ts | 1 + src/ghidra/GhidraProviderCapabilities.ts | 4 +- src/hopper/HopperAnalysisProfile.ts | 1 + src/hopper/HopperProvider.ts | 3 +- tests/boundary/mcp/ghidraEvidenceMcp.test.ts | 92 +++++++++++++++++++ tests/boundary/mcp/ghidraMcpHarness.ts | 5 +- .../hopper/hopperAnalysisProfile.test.ts | 2 + .../hopper/hopperBridgeFacade.test.ts | 13 +++ 16 files changed, 232 insertions(+), 23 deletions(-) diff --git a/bridge/ghidra/ReaGhidraBridge.java b/bridge/ghidra/ReaGhidraBridge.java index 84e809ccb..f91f003e4 100644 --- a/bridge/ghidra/ReaGhidraBridge.java +++ b/bridge/ghidra/ReaGhidraBridge.java @@ -1490,9 +1490,6 @@ public final class ReaGhidraBridge extends HeadlessScript { InstructionScan scan = scanInstructions(function, Integer.MAX_VALUE); DecompileResults decompilation = decompile(function); String pseudocode = decompiledText(decompilation); - if (pseudocode == null) { - pseudocode = ""; - } List incomingReferences = collectReferences(function, "incoming") .stream() .filter(reference -> !function.getBody().contains(reference.getFromAddress())) @@ -1514,7 +1511,7 @@ public final class ReaGhidraBridge extends HeadlessScript { procedure.add("locals", functionLocals(function)); JsonObject result = new JsonObject(); result.add("procedure", procedure); - result.addProperty("pseudocode", pseudocode); + result.addProperty("pseudocode", pseudocode == null ? "" : pseudocode); result.add("assembly", assembly); result.add("comments", comments); result.add("callers", callers); @@ -1523,6 +1520,20 @@ public final class ReaGhidraBridge extends HeadlessScript { result.add("outgoing_references", outgoing); result.add("referenced_strings", referencedStrings); result.add("referenced_names", referencedNames); + JsonObject facets = new JsonObject(); + JsonObject pseudocodeAvailability = new JsonObject(); + pseudocodeAvailability.addProperty("available", pseudocode != null); + if (pseudocode == null) { + pseudocodeAvailability.addProperty("reason", "Ghidra did not supply pseudocode."); + } + facets.add("pseudocode", pseudocodeAvailability); + for (String facet : List.of("assembly", "comments", "callers", "callees", + "references", "strings_names", "cfg")) { + JsonObject available = new JsonObject(); + available.addProperty("available", true); + facets.add(facet, available); + } + result.add("facet_availability", facets); boolean swift = swiftProgram(); boolean aarch64 = currentProgram.getLanguageID().getIdAsString().startsWith("AARCH64:"); SwiftStringLiteralDecode swiftLiterals = swift && aarch64 ? swiftStringLiterals(function) : null; diff --git a/bridge/hopper_bridge.py b/bridge/hopper_bridge.py index 92a473c06..4188fe0da 100644 --- a/bridge/hopper_bridge.py +++ b/bridge/hopper_bridge.py @@ -644,7 +644,7 @@ def _analyze_function(document, params): "end": _hex(_basic_block_end(procedure, block)), "successors": sorted(set(successors), key=lambda value: int(value, 16)), }) - pseudo = _pseudocode(document, procedure) or "" + pseudo = _pseudocode(document, procedure) assembly_lines = _assembly(procedure).splitlines() callers = sorted((_procedure_identity(item) for item in procedure.getAllCallerProcedures()), key=lambda item: int(item["address"], 16)) callees = sorted((_procedure_identity(item) for item in procedure.getAllCalleeProcedures()), key=lambda item: int(item["address"], 16)) @@ -706,7 +706,7 @@ def _analyze_function(document, params): "signature": procedure.signatureString(), "locals": _procedure_locals(procedure), }, - "pseudocode": pseudo, + "pseudocode": pseudo or "", "assembly": assembly_lines, "comments": comments, "callers": callers, "callees": callees, @@ -718,6 +718,12 @@ def _analyze_function(document, params): "basic_blocks": blocks, "native_api": None, "native_value_flow": None, + "facet_availability": { + "pseudocode": {"available": True} if pseudo is not None else _unavailable("Hopper did not supply pseudocode."), + **{facet: {"available": True} for facet in ( + "assembly", "comments", "callers", "callees", "references", "strings_names", "cfg" + )}, + }, "limitations": [ "Native CallReference classifications are observed where available; detailed reference flags remain unknown.", "Hopper's public Python API does not expose equivalent external or thunk classification in this dossier.", diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md index 307d323df..557c98ab4 100644 --- a/docs/mcp-contracts.md +++ b/docs/mcp-contracts.md @@ -58,7 +58,13 @@ side declares a required facet unavailable. An empty legacy facet without a coverage declaration is also unknown. A producer that actually observed an empty facet can declare it available so observed absence remains comparable. Call comparison additionally retains the Evidence relationship coverage -checks. IDA declares the facets its selected adapter cannot provide; an empty +checks. Ghidra and Hopper declare their observed dossier facets and complete +provider-observed caller/callee sets, including empty sets. Missing decompiler +output remains unavailable; complete call coverage does not claim every runtime +target. Hopper's unavailable reference-kind metadata and reported unresolved +calls still prevent equality conclusions for those dimensions. Analysis profiles +version these declarations so older snapshots are not reused as current results. +IDA declares the facets its selected adapter cannot provide; an empty unsupported array does not prove observed absence. Evidence and bundle imports reject unsupported fields in their envelopes, identities, manifests and other fixed metadata before authentication. Imports diff --git a/scripts/lib/native-value-e2e.mjs b/scripts/lib/native-value-e2e.mjs index 513259b30..d329bc822 100644 --- a/scripts/lib/native-value-e2e.mjs +++ b/scripts/lib/native-value-e2e.mjs @@ -235,7 +235,11 @@ async function verifyNativeValueAdapters( ); assert.notEqual(comparison.isError, true, JSON.stringify(comparison)); const comparisonEvidence = parseEvidence(comparison.structuredContent); - assert.equal(comparisonEvidence.normalized_result.status, "unchanged"); + assert.equal( + comparisonEvidence.normalized_result.status, + "unchanged", + JSON.stringify(comparisonEvidence.normalized_result.dimensions), + ); assert.deepEqual( comparisonEvidence.normalized_result, comparison.structuredContent?.normalized_result, diff --git a/scripts/lib/real-ghidra-boundaries.mjs b/scripts/lib/real-ghidra-boundaries.mjs index f6ee1527a..c2347dde1 100644 --- a/scripts/lib/real-ghidra-boundaries.mjs +++ b/scripts/lib/real-ghidra-boundaries.mjs @@ -131,6 +131,25 @@ export async function verifyGhidraBoundaries( const externalDossier = await call("analyze_function", { procedure: external.address, }); + assert.equal(externalDossier.pseudocode, ""); + assert.deepEqual(externalDossier.assembly, []); + assert.deepEqual(externalDossier.callees, []); + assert.deepEqual(externalDossier.facet_availability.pseudocode, { + available: false, + reason: "Ghidra did not supply pseudocode.", + }); + for (const facet of [ + "assembly", + "comments", + "callers", + "callees", + "references", + "strings_names", + "cfg", + ]) + assert.deepEqual(externalDossier.facet_availability[facet], { + available: true, + }); const externalEntry = await call("resolve_containing_procedure", { address: external.address, }); diff --git a/scripts/lib/real-hopper-semantic.mjs b/scripts/lib/real-hopper-semantic.mjs index cb11b433c..7739db6be 100644 --- a/scripts/lib/real-hopper-semantic.mjs +++ b/scripts/lib/real-hopper-semantic.mjs @@ -327,14 +327,57 @@ export const analyzeFixtureProcedure = async ( options, procedure, normalizedResult, -) => - normalizedResult( +) => { + const reply = await client.callTool( + { + name: "analyze_function", + arguments: { procedure: procedure.address }, + }, + options, + ); + const dossier = normalizedResult(reply, "analyze_function"); + assert.deepEqual(reply.structuredContent.relationship_coverage, { + status: "complete", + }); + for (const facet of [ + "pseudocode", + "assembly", + "comments", + "callers", + "callees", + "references", + "strings_names", + "cfg", + ]) + assert.deepEqual(dossier.facet_availability[facet], { available: true }); + const comparison = normalizedResult( await client.callTool( { - name: "analyze_function", - arguments: { procedure: procedure.address }, + name: "compare_functions", + arguments: { + left: reply.structuredContent, + right: reply.structuredContent, + }, }, options, ), - "analyze_function", + "compare_functions", ); + assert.deepEqual( + Object.fromEntries( + comparison.dimensions.map(({ dimension, status }) => [dimension, status]), + ), + { + identity: "unchanged", + pseudocode: "unchanged", + assembly: "unchanged", + comments: "unchanged", + calls: "unchanged", + references: "unknown", + strings_names: "unchanged", + cfg: "unchanged", + }, + JSON.stringify(comparison.dimensions), + ); + return dossier; +}; diff --git a/src/domain/ghidraValues.fixture.ts b/src/domain/ghidraValues.fixture.ts index d0c6d183c..4927cf210 100644 --- a/src/domain/ghidraValues.fixture.ts +++ b/src/domain/ghidraValues.fixture.ts @@ -147,7 +147,7 @@ export const ghidraNativeApiBoundary = () => ({ ], }); -export const ghidraFunctionDossier = (includeAssembly = true): JsonValue => { +export const ghidraFunctionDossier = (): JsonValue => { const pseudocode = "int fixture_main(void) { return 42; }"; return { procedure: { @@ -156,10 +156,18 @@ export const ghidraFunctionDossier = (includeAssembly = true): JsonValue => { locals: [], }, pseudocode, - assembly: includeAssembly - ? ["0x401000: CALL 0x401020", "0x401005: RET"] - : [], + assembly: ["0x401000: CALL 0x401020", "0x401005: RET"], comments: [], + facet_availability: { + pseudocode: { available: true }, + assembly: { available: true }, + comments: { available: true }, + callers: { available: true }, + callees: { available: true }, + references: { available: true }, + strings_names: { available: true }, + cfg: { available: true }, + }, callers: [], callees: [], incoming_references: [], diff --git a/src/ghidra/GhidraAnalysisProfile.ts b/src/ghidra/GhidraAnalysisProfile.ts index 8175b776b..da39ce53c 100644 --- a/src/ghidra/GhidraAnalysisProfile.ts +++ b/src/ghidra/GhidraAnalysisProfile.ts @@ -126,6 +126,8 @@ export const resolveGhidraAnalysisProfile = async ( function_body_evidence: "complete-inclusive-ranges-v1", function_references: "complete-body-and-entry-reference-manager-v2", call_relationship_coverage: "resolved-call-reference-diagnostics-v1", + function_dossier_coverage: + "observed-facets-and-call-relationships-v1", string_inventory_evidence: "defined-data-coverage-v1", location_resolution: "explicit-address-exact-entry-symbol-first-v3", procedure_file_offset_resolution: @@ -221,6 +223,7 @@ export const resolveGhidraAnalysisProfile = async ( function_body_evidence: "complete-inclusive-ranges-v1", function_references: "complete-body-and-entry-reference-manager-v2", call_relationship_coverage: "resolved-call-reference-diagnostics-v1", + function_dossier_coverage: "observed-facets-and-call-relationships-v1", string_inventory_evidence: "defined-data-coverage-v1", location_resolution: "explicit-address-exact-entry-symbol-first-v3", procedure_file_offset_resolution: diff --git a/src/ghidra/GhidraProvider.behavior.test.ts b/src/ghidra/GhidraProvider.behavior.test.ts index b485f6ab3..4a052aaef 100644 --- a/src/ghidra/GhidraProvider.behavior.test.ts +++ b/src/ghidra/GhidraProvider.behavior.test.ts @@ -628,6 +628,7 @@ describe("Ghidra client projection", () => { language_id: "auto-from-header", compiler_spec_id: "auto-default", call_relationship_coverage: "resolved-call-reference-diagnostics-v1", + function_dossier_coverage: "observed-facets-and-call-relationships-v1", }); const result = await ghidra diff --git a/src/ghidra/GhidraProviderCapabilities.ts b/src/ghidra/GhidraProviderCapabilities.ts index 0714d1ce0..f4bff8d9c 100644 --- a/src/ghidra/GhidraProviderCapabilities.ts +++ b/src/ghidra/GhidraProviderCapabilities.ts @@ -51,7 +51,9 @@ const resolvedCallReferenceLimitation = export const relationshipCoverageFor = ( operation: string, ): RelationshipCoverage | undefined => - operation === "procedure_callers" || operation === "procedure_callees" + operation === "procedure_callers" || + operation === "procedure_callees" || + operation === "analyze_function" ? { status: "complete", diagnostics: [resolvedCallReferenceLimitation], diff --git a/src/hopper/HopperAnalysisProfile.ts b/src/hopper/HopperAnalysisProfile.ts index 79ba3ab50..74618a60c 100644 --- a/src/hopper/HopperAnalysisProfile.ts +++ b/src/hopper/HopperAnalysisProfile.ts @@ -82,6 +82,7 @@ export const resolveHopperAnalysisProfile = async ( profile: createAnalysisProfile(provider, { target_kind: target.kind, target_format: target.format, + function_dossier_coverage: "observed-facets-and-call-relationships-v1", architecture: target.architecture ?? null, available_architectures: [ ...(target.availableArchitectures ?? []), diff --git a/src/hopper/HopperProvider.ts b/src/hopper/HopperProvider.ts index f9826575b..e4d7c8381 100644 --- a/src/hopper/HopperProvider.ts +++ b/src/hopper/HopperProvider.ts @@ -272,7 +272,8 @@ export class HopperProvider implements AnalysisProviderCandidate { rawResult, ...(profile === undefined ? {} : { analysisProfile: profile }), ...(operation === "procedure_callers" || - operation === "procedure_callees" + operation === "procedure_callees" || + operation === "analyze_function" ? { relationshipCoverage: { status: "complete" as const } } : {}), limitations: [ diff --git a/tests/boundary/mcp/ghidraEvidenceMcp.test.ts b/tests/boundary/mcp/ghidraEvidenceMcp.test.ts index ed82400aa..e786fc3cc 100644 --- a/tests/boundary/mcp/ghidraEvidenceMcp.test.ts +++ b/tests/boundary/mcp/ghidraEvidenceMcp.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest"; import { EnhancedTools } from "../../../src/application/EnhancedTools.js"; import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js"; import { functionDossierSchema } from "../../../src/domain/hopperValues.js"; +import { functionComparisonResultSchema } from "../../../src/domain/functionComparisonSchemas.js"; import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js"; import { jsonValueSchema, @@ -14,6 +15,97 @@ import { type GhidraFunctionOperation, } from "../../../src/ghidra/GhidraFunctionValues.js"; +it.each([true, false])( + "compares observed empty Ghidra facets while preserving pseudocode availability (%s)", + async (pseudocodeAvailable) => { + const dossier = functionDossierSchema.parse(ghidraFunctionDossier()); + Object.assign(dossier, { + comments: [], + callers: [], + callees: [], + incoming_references: [], + outgoing_references: [], + referenced_strings: [], + referenced_names: [], + pseudocode: pseudocodeAvailable ? dossier.pseudocode : "", + facet_availability: { + pseudocode: pseudocodeAvailable + ? { available: true } + : { available: false, reason: "Ghidra did not supply pseudocode." }, + assembly: { available: true }, + comments: { available: true }, + callers: { available: true }, + callees: { available: true }, + references: { available: true }, + strings_names: { available: true }, + cfg: { available: true }, + }, + }); + const harness = await connectGhidraMcp( + "ghidra-empty-dossier-coverage", + (operation) => { + if (operation !== "analyze_function") + throw new Error(`Unexpected operation: ${operation}`); + return Promise.resolve( + ok({ value: jsonValueSchema.parse(dossier), limitations: [] }), + ); + }, + ); + try { + const analyzed = await harness.mcp.callTool({ + name: "analyze_function", + arguments: { procedure: dossier.procedure.address }, + }); + expect(analyzed.isError).not.toBe(true); + const evidence = sessionEvidence( + harness.session, + analyzed.structuredContent, + ); + expect(evidence.relationship_coverage).toMatchObject({ + status: "complete", + }); + expect(evidence.normalized_result).toEqual(dossier); + const reply = await harness.mcp.callTool({ + name: "compare_functions", + arguments: { left: evidence, right: evidence }, + }); + expect(reply.isError).not.toBe(true); + const comparison = functionComparisonResultSchema.parse( + sessionEvidence(harness.session, reply.structuredContent) + .normalized_result, + ); + expect( + Object.fromEntries( + comparison.dimensions.map(({ dimension, status }) => [ + dimension, + status, + ]), + ), + ).toEqual({ + identity: "unchanged", + pseudocode: pseudocodeAvailable ? "unchanged" : "unknown", + assembly: "unchanged", + comments: "unchanged", + calls: "unchanged", + references: "unchanged", + strings_names: "unchanged", + cfg: "unchanged", + }); + const replay = await harness.session.execute( + "analyze_function", + evidence.parameters, + ); + if (!replay.ok) throw replay.error; + expect(replay.value.relationshipCoverage).toEqual( + evidence.relationship_coverage, + ); + expect(harness.calls).toEqual(["analyze_function"]); + } finally { + await harness.close(); + } + }, +); + it("retains terminal-call qualifications across function views and snapshot replay", async () => { const limitation = "Ghidra Listing reports a terminal call at 0x401000 to EXTERNAL:0x20 __tls_get_addr (external=true, thunk=false, hasNoReturn=true); fallthrough is excluded by Ghidra's flow model. This records Ghidra's FunctionManager flag, not an independent verification that the callee cannot return."; diff --git a/tests/boundary/mcp/ghidraMcpHarness.ts b/tests/boundary/mcp/ghidraMcpHarness.ts index fea27b037..43e49b551 100644 --- a/tests/boundary/mcp/ghidraMcpHarness.ts +++ b/tests/boundary/mcp/ghidraMcpHarness.ts @@ -246,10 +246,7 @@ const resultBuilders = new Map([ }), ], ["xrefs", () => ["0x401001"]], - [ - "analyze_function", - (input) => ghidraFunctionDossier(input.include_assembly === true), - ], + ["analyze_function", () => ghidraFunctionDossier()], ]); const resultFor = ( diff --git a/tests/boundary/providers/hopper/hopperAnalysisProfile.test.ts b/tests/boundary/providers/hopper/hopperAnalysisProfile.test.ts index a8f121e61..46b71deb7 100644 --- a/tests/boundary/providers/hopper/hopperAnalysisProfile.test.ts +++ b/tests/boundary/providers/hopper/hopperAnalysisProfile.test.ts @@ -106,6 +106,8 @@ describe("Hopper analysis profiles", () => { value: { profile: { parameters: { + function_dossier_coverage: + "observed-facets-and-call-relationships-v1", loader: { source: scenario.source, arguments: scenario.arguments, diff --git a/tests/boundary/providers/hopper/hopperBridgeFacade.test.ts b/tests/boundary/providers/hopper/hopperBridgeFacade.test.ts index 515172eab..a4be45673 100644 --- a/tests/boundary/providers/hopper/hopperBridgeFacade.test.ts +++ b/tests/boundary/providers/hopper/hopperBridgeFacade.test.ts @@ -167,6 +167,19 @@ describe("Hopper API facade", () => { }, native_api: null, native_value_flow: null, + facet_availability: { + pseudocode: { + available: false, + reason: "Hopper did not supply pseudocode.", + }, + assembly: { available: true }, + comments: { available: true }, + callers: { available: true }, + callees: { available: true }, + references: { available: true }, + strings_names: { available: true }, + cfg: { available: true }, + }, }); expect(result.provider_faults.map((reply) => reply.error.message)).toEqual([ "TypeError: Hopper bridge operation failed", From 02987d8e8ce47f1e34b1e8a7b918a1f62f0560f1 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Wed, 14 Oct 2026 07:12:10 +0800 Subject: [PATCH 2/3] test(hopper): bind string assertions to observed source extents Remove OS-based assumptions about long and non-ASCII string recognition. Require the dedicated fragmented fixture, independently verify full source bytes, and reject gaps, overlaps, incomplete reads and corrupted decoding. Report unrecognized native strings explicitly and retain the actual procedure count. Verified through 14 verifier regressions and the complete macOS arm64 Hopper 6.6.0-demo CLI/MCP lane with cleanup. --- scripts/lib/real-hopper-search.d.mts | 19 +++ scripts/lib/real-hopper-search.mjs | 140 +++++++++++------- scripts/verify-real-hopper.mjs | 2 +- tests/conformance/c/fixture.c | 2 +- .../providers/hopper/realHopperSearch.test.ts | 99 ++++++++++++- 5 files changed, 203 insertions(+), 59 deletions(-) diff --git a/scripts/lib/real-hopper-search.d.mts b/scripts/lib/real-hopper-search.d.mts index e64031652..0a7260227 100644 --- a/scripts/lib/real-hopper-search.d.mts +++ b/scripts/lib/real-hopper-search.d.mts @@ -10,6 +10,25 @@ interface StringExpectation { readonly recognitionOptional?: boolean; } +/** Verify native fragments against a complete, independently read source extent. */ +export function verifyHopperStringFragments( + call: VerifierCall, + inventory: readonly z.output[], + expectation: { + readonly value: string; + readonly symbol: string; + readonly recognitionOptional?: boolean; + }, +): Promise<{ + readonly sourceBytes: number; + readonly recognition: { + readonly address: string; + readonly state: "observed" | "not_observed"; + readonly decodedObject: "verified" | "unverified"; + }; + readonly fragments: readonly z.output[]; +}>; + /** Verify source bytes, observed decoding, address filters and literal searches. */ export function verifyHopperStringObjects( call: VerifierCall, diff --git a/scripts/lib/real-hopper-search.mjs b/scripts/lib/real-hopper-search.mjs index 3456bc6b2..0efd2bfb7 100644 --- a/scripts/lib/real-hopper-search.mjs +++ b/scripts/lib/real-hopper-search.mjs @@ -106,27 +106,18 @@ async function verifySearchModes(call, address) { [{ address, value: "REA_Search_Upper" }], ); const strings = await call("list_strings"); - const linux = process.platform === "linux"; - const fullLiteral = "REA_LONG_LITERAL_" + "x".repeat(4096) + "needle"; - // Recognition is a provider/loader capability, not an adapter guarantee. - // Always retain the original size in raw-byte coverage; Linux additionally - // requires an extent observed to produce native fragmented string objects. - const fullBytes = Buffer.from(fullLiteral + "\0"); - const raw = await call("read_bytes", { - address: `${fixtureSymbolPrefix}rea_long_literal`, - length: fullBytes.length, + const fullLiteral = await verifyHopperStringFragments(call, strings, { + symbol: `${fixtureSymbolPrefix}rea_long_literal`, + value: "REA_LONG_LITERAL_" + "x".repeat(4096) + "needle", + recognitionOptional: true, }); - assert.equal(raw.complete, true); - assert.equal(raw.bytes_hex, fullBytes.toString("hex")); - const long = linux - ? "REA_FRAGMENTED_LITERAL_" + "x".repeat(512) + "fragment_tail" - : fullLiteral; - const longItem = strings.find( - (item) => long.startsWith(item.value) && item.value.startsWith("REA_"), - ); - assert.ok(longItem, "fixture omitted its real long literal"); - if (!linux) assert.equal(longItem.address, raw.address); - assert.ok(long.startsWith(longItem.value)); + const fragmentedLiteral = await verifyHopperStringFragments(call, strings, { + symbol: `${fixtureSymbolPrefix}rea_fragmented_literal`, + value: "REA_FRAGMENTED_LITERAL_" + "x".repeat(512) + "fragment_tail", + }); + const [longItem] = fragmentedLiteral.fragments; + assert.ok(longItem, "fixture omitted its typed fragmented literal"); + assert.ok(fragmentedLiteral.fragments.length > 1); assert.ok(longItem.provider_value.endsWith("…")); assert.equal(longItem.string.termination, "missing"); const literalProcedure = (await call("list_procedures")).find((item) => @@ -154,33 +145,13 @@ async function verifySearchModes(call, address) { "function dossier discarded typed string provenance", ); - const fragments = strings.filter((item) => { - const offset = BigInt(item.address) - BigInt(longItem.address); - return offset >= 0n && offset < BigInt(Buffer.byteLength(long)); - }); - assert.equal(fragments.map((item) => item.value).join(""), long); - for (const fragment of fragments) { - assert.equal( - Buffer.byteLength(fragment.value), - fragment.string.byte_length - - (fragment.string.termination === "missing" ? 0 : 1), - ); - const bytes = await call("read_bytes", { - address: fragment.address, - length: fragment.string.byte_length, - }); - const expected = Buffer.from( - fragment.value + (fragment.string.termination === "missing" ? "" : "\0"), - ); - assert.equal(bytes.bytes_hex, expected.toString("hex")); - } assert.deepEqual( await call("search_strings", { - pattern: linux ? "fragment_tail" : "needle", + pattern: "fragment_tail", mode: "literal", case_sensitive: true, }), - [fragments.at(-1)], + [fragmentedLiteral.fragments.at(-1)], ); const expected = strings.filter((item) => /^REA_C_(?:ENTRY|LEAF)$/u.test(item.value), @@ -201,7 +172,7 @@ async function verifySearchModes(call, address) { value: "REA_UTF8_Γ©_πŸ˜€", encoding: "utf-8", symbol: `${fixtureSymbolPrefix}rea_utf8_literal`, - recognitionOptional: linux, + recognitionOptional: true, }, { value: 'REA_ESCAPED_"\\line\nend\t\r', encoding: "utf-8" }, { value: "REA_LITERAL_BACKSLASH_\\n", encoding: "utf-8" }, @@ -209,33 +180,90 @@ async function verifySearchModes(call, address) { value: "REA_LITERAL_…", encoding: "utf-8", symbol: `${fixtureSymbolPrefix}rea_ellipsis_literal`, - recognitionOptional: linux, + recognitionOptional: true, }, { value: "REA_LATIN1_ΓΏ", encoding: "latin-1", symbol: `${fixtureSymbolPrefix}rea_latin1_literal`, - recognitionOptional: linux, + recognitionOptional: true, }, ], strings, ); return { - fullLiteralSourceBytes: fullBytes.length, - fragmentedLiteralSourceBytes: Buffer.byteLength(long), - fullLiteralRecognition: { - address: raw.address, - state: strings.some((item) => item.address === raw.address) - ? "observed" - : "not_observed", - // Linux validates the original through raw bytes; its required decoded - // fragment/dossier checks exercise the separate supported-size literal. - decodedObject: linux ? "unverified" : "verified", - }, + fullLiteralSourceBytes: fullLiteral.sourceBytes, + fragmentedLiteralSourceBytes: fragmentedLiteral.sourceBytes, + fullLiteralRecognition: fullLiteral.recognition, ...objects, }; } +/** Bind native fragments to exact source bytes without assuming loader recognition. */ +export async function verifyHopperStringFragments( + call, + strings, + { symbol, value, recognitionOptional = false }, +) { + const expectedBytes = Buffer.from(value + "\0"); + const raw = await call("read_bytes", { + address: symbol, + length: expectedBytes.length, + }); + assert.equal(raw.complete, true); + assert.equal(raw.bytes_hex, expectedBytes.toString("hex")); + const start = BigInt(raw.address); + const end = start + BigInt(expectedBytes.length); + const fragments = strings.filter((item) => { + const address = BigInt(item.address); + return address >= start && address < end; + }); + if (fragments.length === 0 && recognitionOptional) + return { + sourceBytes: expectedBytes.length, + recognition: { + address: raw.address, + state: "not_observed", + decodedObject: "unverified", + }, + fragments, + }; + assert.ok(fragments.length > 0, "fixture omitted its typed string fragments"); + let next = start; + for (const [index, fragment] of fragments.entries()) { + assert.equal( + BigInt(fragment.address), + next, + "string fragments have a gap, overlap or wrong source identity", + ); + const terminal = index === fragments.length - 1; + assert.equal( + fragment.string.termination, + terminal ? "present_or_not_required" : "missing", + ); + const expected = Buffer.from(fragment.value + (terminal ? "\0" : "")); + assert.equal(fragment.string.byte_length, expected.length); + const bytes = await call("read_bytes", { + address: fragment.address, + length: expected.length, + }); + assert.equal(bytes.complete, true); + assert.equal(bytes.bytes_hex, expected.toString("hex")); + next += BigInt(expected.length); + } + assert.equal(next, end, "string fragments do not cover the source extent"); + assert.equal(fragments.map((item) => item.value).join(""), value); + return { + sourceBytes: expectedBytes.length, + recognition: { + address: raw.address, + state: "observed", + decodedObject: "verified", + }, + fragments, + }; +} + /** Compare native string identities and values with the source fixture's bytes. */ export async function verifyHopperStringObjects( call, diff --git a/scripts/verify-real-hopper.mjs b/scripts/verify-real-hopper.mjs index 8cad9a256..a82c1429a 100644 --- a/scripts/verify-real-hopper.mjs +++ b/scripts/verify-real-hopper.mjs @@ -213,7 +213,7 @@ const verifyCurrentTarget = async (client, options) => { ); return { procedure: dossier.procedure, - procedureCount: procedures.total, + procedureCount: procedures.length, boundedPseudocodeChars: boundedPseudocode.length, analyzedPseudocodeChars: [...dossier.pseudocode].length, callerCount: relationships.procedure_callers.length, diff --git a/tests/conformance/c/fixture.c b/tests/conformance/c/fixture.c index e1dff9a9c..4f519a922 100644 --- a/tests/conformance/c/fixture.c +++ b/tests/conformance/c/fixture.c @@ -8,7 +8,7 @@ volatile int rea_c_global = 7; /* Keep the full-size literal even when a loader does not type it as a string. */ __attribute__((used)) const char rea_long_literal[] = "REA_LONG_LITERAL_" REA_LONG_1024 REA_LONG_1024 REA_LONG_1024 REA_LONG_1024 "needle"; -/* Linux Hopper 6.4.2 recognizes this extent and splits it into native objects. */ +/* Verified Hopper loaders recognize this extent and split it into native objects. */ __attribute__((used)) const char rea_fragmented_literal[] = "REA_FRAGMENTED_LITERAL_" REA_LONG_256 REA_LONG_256 "fragment_tail"; __attribute__((used)) const char rea_utf8_literal[] = "REA_UTF8_Γ©_πŸ˜€"; diff --git a/tests/conformance/providers/hopper/realHopperSearch.test.ts b/tests/conformance/providers/hopper/realHopperSearch.test.ts index 10aedb433..14909c14b 100644 --- a/tests/conformance/providers/hopper/realHopperSearch.test.ts +++ b/tests/conformance/providers/hopper/realHopperSearch.test.ts @@ -1,6 +1,9 @@ import { expect, it } from "vitest"; -import { verifyHopperStringObjects } from "../../../../scripts/lib/real-hopper-search.mjs"; +import { + verifyHopperStringFragments, + verifyHopperStringObjects, +} from "../../../../scripts/lib/real-hopper-search.mjs"; const value = "REA_UTF8_Γ©_πŸ˜€"; const address = "0x402020"; @@ -22,6 +25,100 @@ const expectation = { recognitionOptional: true, }; +const fragments = [ + { + ...item, + value: "REA_", + string: { ...item.string, termination: "missing" as const, byte_length: 4 }, + }, + { + ...item, + address: "0x402024", + value: value.slice(4), + string: { ...item.string, byte_length: bytes.length - 4 }, + }, +] as const; + +const fragmentBytes = async ( + name: string, + args: Record = {}, +) => { + if (name !== "read_bytes") throw new Error(`Unmodeled call: ${name}`); + const offset = + args.address === expectation.symbol + ? 0 + : Number(BigInt(String(args.address)) - BigInt(address)); + return { + address: `0x${(BigInt(address) + BigInt(offset)).toString(16)}`, + complete: true, + bytes_hex: bytes + .subarray(offset, offset + Number(args.length)) + .toString("hex"), + }; +}; + +it("verifies contiguous native fragments against the complete source bytes", async () => { + const result = await verifyHopperStringFragments( + fragmentBytes, + fragments, + expectation, + ); + expect(result.recognition).toEqual({ + address, + state: "observed", + decodedObject: "verified", + }); + expect(result.sourceBytes).toBe(bytes.length); +}); + +it("reports unrecognized source bytes without accepting identical text at another address", async () => { + const elsewhere = [{ ...item, address: "0x403000" }]; + const result = await verifyHopperStringFragments( + fragmentBytes, + elsewhere, + expectation, + ); + expect(result.recognition).toEqual({ + address, + state: "not_observed", + decodedObject: "unverified", + }); + await expect( + verifyHopperStringFragments(fragmentBytes, elsewhere, { + ...expectation, + recognitionOptional: false, + }), + ).rejects.toThrow(/typed string fragments/u); +}); + +it.each([ + ["gap", [fragments[0], { ...fragments[1], address: "0x402025" }]], + ["overlap", [fragments[0], { ...fragments[1], address: "0x402023" }]], + ["missing prefix", [fragments[1]]], + ["wrong decoded value", [{ ...item, value: "X" + value.slice(1) }]], + ["missing tail", [fragments[0]]], +])( + "rejects %s even when fragment recognition is optional", + async (_label, inventory) => { + await expect( + verifyHopperStringFragments(fragmentBytes, inventory, expectation), + ).rejects.toThrow(); + }, +); + +it("rejects incomplete source bytes even with no native string objects", async () => { + await expect( + verifyHopperStringFragments( + async (name: string, args: Record = {}) => ({ + ...(await fragmentBytes(name, args)), + complete: false, + }), + [], + expectation, + ), + ).rejects.toThrow(); +}); + it("keeps source identity and unknown decoding when the same text exists elsewhere", async () => { const report = await verifyHopperStringObjects( fixtureCall(), From 1ae90005874034b59741bf59809b75150b54a257 Mon Sep 17 00:00:00 2001 From: hhang <17309584214@163.com> Date: Wed, 14 Oct 2026 07:18:50 +0800 Subject: [PATCH 3/3] fix(javascript): exclude TypeScript this annotations from runtime parameters (#2761) * fix(javascript): exclude TypeScript this annotations from runtime parameters * test(javascript): assert exact typed argument bindings * test(apple): keep dyld slice regression portable * fix(process): report no remaining time after a provider deadline fires Node timers can fire while performance.now() is still a fraction of a millisecond short of the monotonic deadline. ProviderStartupDeadline then reported interruption "timeout" and an aborted signal while remainingMs() returned ceil(0.x) = 1, so polling loops guarded by remainingMs() > 0 (Hopper and Ghidra startup) could run past an elapsed deadline, and the real-timer test "aborts a bounded wait when its real monotonic deadline expires" failed intermittently in CI (expected 1 to be 0). Once the deadline's own timer has classified a timeout, report zero remaining time. A deterministic regression test fires the timer with the monotonic clock 0.4 ms short of the deadline. Co-Authored-By: Claude Opus 5.5 * fix(ci): restore descriptor and fixture validation * test(ci): retain verification coverage within lint limits * fix(test): share admitted Ghidra profile installation fixtures * fix(ci): isolate timing report fixtures from workflow state --------- Co-authored-by: hhang <169027046+xu91102@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- native/windows/README.md | 4 +- scripts/verify-windows-native-inspection.mjs | 22 ++- src/domain/android/androidAnalysis.ts | 2 +- .../javascript/electronWrappedCallPaths.ts | 5 +- .../javascript/javascriptAstFingerprint.ts | 15 +- src/domain/javascript/javascriptAstValues.ts | 8 + src/domain/javascript/javascriptBootstrap.ts | 11 +- .../javascript/javascriptModuleInterop.ts | 5 +- .../javascript/javascriptSemanticAnalysis.ts | 7 +- .../javascriptSemanticCallResolution.ts | 10 +- .../javascriptSemanticFingerprints.ts | 3 +- .../javascriptSemanticIterationSources.ts | 4 +- .../javascriptStaticAnalysisBundler.ts | 3 +- .../javascriptStaticAnalysisHelpers.ts | 3 +- .../javascript/javascriptSymbolicBindings.ts | 7 +- src/ghidra/GhidraAnalysisSeeds.test.ts | 15 +- src/ghidra/GhidraInstallation.fixture.ts | 16 ++ src/ghidra/GhidraLanguageOverride.test.ts | 17 +-- src/ghidra/GhidraMipsProfile.test.ts | 32 ++-- src/ghidra/GhidraPowerPcProfile.test.ts | 25 ++-- src/ghidra/GhidraRiscvProfile.test.ts | 16 +- .../typescriptThisParametersCli.test.ts | 140 ++++++++++++++++++ .../boundary/filesystem/ciTestReports.test.ts | 105 +++++++------ 23 files changed, 309 insertions(+), 166 deletions(-) create mode 100644 src/ghidra/GhidraInstallation.fixture.ts create mode 100644 tests/acceptance/applications/typescriptThisParametersCli.test.ts diff --git a/native/windows/README.md b/native/windows/README.md index 86103ce9a..ec2fb1bde 100644 --- a/native/windows/README.md +++ b/native/windows/README.md @@ -154,7 +154,9 @@ node scripts/verify-windows-native-inspection.mjs This artifact injects one access-denied disposition result while using a real NTFS directory. The verifier checks retained ownership, recovery on a later query, cached successful admission, and cleanup on environment teardown. It -does not reproduce or identify the host-dependent cause reported in #1701. +renames the retained probe and recreates its old path, checking that cleanup +removes the owned inode while preserving the replacement directory. +It does not reproduce or identify the host-dependent cause reported in #1701. The fixture is stored under `.cache/` and is excluded from the shipped addon. The native lane checks DACL readback independently, source write/replacement diff --git a/scripts/verify-windows-native-inspection.mjs b/scripts/verify-windows-native-inspection.mjs index 5b3c2e726..94adaf5a6 100644 --- a/scripts/verify-windows-native-inspection.mjs +++ b/scripts/verify-windows-native-inspection.mjs @@ -5,7 +5,9 @@ import { mkdir, mkdtemp, readdir, + rmdir, rm, + stat, symlink, writeFile, } from "node:fs/promises"; @@ -52,7 +54,7 @@ try { join(workspace, "dist", "windows", "WindowsNativeLoader.js"), ).href; const source = `import assert from 'node:assert/strict'; -import {readdirSync,renameSync,statSync} from 'node:fs'; +import {existsSync,mkdirSync,readdirSync,renameSync,statSync} from 'node:fs'; import {join} from 'node:path'; import {systemWindowsNativeAuthority} from ${JSON.stringify(loader)}; const temp=process.env.TEMP; @@ -63,14 +65,19 @@ assert.match(first.reason,/Delete owned object by handle failed.*Win32 5/s); const [name,...extra]=readdirSync(temp);assert.ok(name);assert.equal(extra.length,0); const path=join(temp,name);const identity=statSync(path,{bigint:true}); // Ownership follows the retained NTFS handle even when the directory moves. +// A replacement at its old pathname must remain caller-owned. const moved=path+'-renamed';renameSync(path,moved); assert.equal(statSync(moved,{bigint:true}).ino,identity.ino); +mkdirSync(path);const replacement=statSync(path,{bigint:true}); +assert.notEqual(replacement.ino,identity.ino); if(process.argv[2]!=='teardown'){ const second=systemWindowsNativeAuthority();assert.equal(second.available,true); - assert.equal(readdirSync(temp).length,0); + assert.equal(existsSync(moved),false); + assert.deepEqual(readdirSync(temp),[name]); + assert.equal(statSync(path,{bigint:true}).ino,replacement.ino); assert.equal(systemWindowsNativeAuthority(),second); } -console.log(JSON.stringify({mode:process.argv[2],firstFailed:true,retainedOwner:true,inode:identity.ino.toString()})); +console.log(JSON.stringify({mode:process.argv[2],firstFailed:true,retainedOwner:true,inode:identity.ino.toString(),replacementName:name,replacementInode:replacement.ino.toString()})); `; const fixture = join(workspace, "probe.mjs"); await writeFile(fixture, source); @@ -86,10 +93,17 @@ console.log(JSON.stringify({mode:process.argv[2],firstFailed:true,retainedOwner: }), ); assert.equal(observed.retainedOwner, true); + assert.deepEqual(await readdir(temp), [observed.replacementName]); + const replacement = join(temp, observed.replacementName); + assert.equal( + (await stat(replacement, { bigint: true })).ino.toString(), + observed.replacementInode, + ); + await rmdir(replacement); assert.deepEqual(await readdir(temp), []); } process.stdout.write( - `${JSON.stringify({ ok: true, controlledDispositionFailure: true, retainedOwner: true, retryRecovers: true, successfulAdmissionCached: true, environmentTeardownCleansProbe: true, issue1701HostCauseReproduced: false })}\n`, + `${JSON.stringify({ ok: true, controlledDispositionFailure: true, retainedOwner: true, renamedOwnerCleanup: true, replacementPreserved: true, retryRecovers: true, successfulAdmissionCached: true, environmentTeardownCleansProbe: true, issue1701HostCauseReproduced: false })}\n`, ); } finally { await rm(workspace, { recursive: true, force: true }); diff --git a/src/domain/android/androidAnalysis.ts b/src/domain/android/androidAnalysis.ts index caa3bf5ee..eaf521a50 100644 --- a/src/domain/android/androidAnalysis.ts +++ b/src/domain/android/androidAnalysis.ts @@ -98,7 +98,7 @@ const textCoverage = z.strictObject({ text: z.string(), reported_total_bytes: z.number().int().nonnegative().nullable(), }); -/** A DEX prototype: parameter descriptors followed by the return descriptor. */ +/** A DEX prototype; hex parentheses also keep the advertised class valid in v mode. */ export const dexDescriptorSchema = z .string() .regex( diff --git a/src/domain/javascript/electronWrappedCallPaths.ts b/src/domain/javascript/electronWrappedCallPaths.ts index 051595eb6..979ab1455 100644 --- a/src/domain/javascript/electronWrappedCallPaths.ts +++ b/src/domain/javascript/electronWrappedCallPaths.ts @@ -1,4 +1,5 @@ import * as t from "@babel/types"; +import { runtimeFunctionParameters } from "./javascriptAstValues.js"; import { JavaScriptSymbolicBindings } from "./javascriptSymbolicBindings.js"; import { symbolicVariants, @@ -447,7 +448,9 @@ export const collectElectronWrappedCallPaths = ( const entry = `${key.value}.${name}`; functionBody( fn, - fn.node.params.map(() => symbolicUnknown("public API argument")), + runtimeFunctionParameters(fn.node).map(() => + symbolicUnknown("public API argument"), + ), { ...memberContext, entryNode: node, diff --git a/src/domain/javascript/javascriptAstFingerprint.ts b/src/domain/javascript/javascriptAstFingerprint.ts index c85700da9..b9e53f975 100644 --- a/src/domain/javascript/javascriptAstFingerprint.ts +++ b/src/domain/javascript/javascriptAstFingerprint.ts @@ -7,6 +7,7 @@ import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js"; import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; import { propertyName, + runtimeFunctionParameters, semanticStaticPropertyKey, } from "./javascriptAstValues.js"; import { stringValue } from "./javascriptStaticAnalysisHelpers.js"; @@ -38,15 +39,13 @@ export const collectJavaScriptExports = ( bindings?: JavaScriptSemanticAnalysisState, ): StaticExports => { const exports = new Set(); + const parameter = t.isFunction(node) + ? runtimeFunctionParameters(node)[1] + : undefined; const factoryExports = - bindings !== undefined && - t.isFunction(node) && - t.isIdentifier(node.params[1]) - ? resolveSemanticBindingState( - bindings, - node.params[1], - node.params[1].name, - )?.bindingId + bindings !== undefined && t.isFunction(node) && t.isIdentifier(parameter) + ? resolveSemanticBindingState(bindings, parameter, parameter.name) + ?.bindingId : undefined; const isExportsAlias = (reference: t.Node | null): boolean => { if (!t.isIdentifier(reference)) return false; diff --git a/src/domain/javascript/javascriptAstValues.ts b/src/domain/javascript/javascriptAstValues.ts index cb3a533fe..26ff26a49 100644 --- a/src/domain/javascript/javascriptAstValues.ts +++ b/src/domain/javascript/javascriptAstValues.ts @@ -1,6 +1,14 @@ import * as t from "@babel/types"; import type { JavaScriptSemanticPrimitive } from "./javascriptSemanticValueTypes.js"; +/** TypeScript receiver annotations occupy no positional runtime parameter slot. */ +export const runtimeFunctionParameters = ( + node: t.Function, +): t.Function["params"] => + t.isIdentifier(node.params[0], { name: "this" }) + ? node.params.slice(1) + : node.params; + /** * Remove wrappers that affect TypeScript or Flow checking but not runtime * expression identity. The returned depth lets bounded evaluators account for diff --git a/src/domain/javascript/javascriptBootstrap.ts b/src/domain/javascript/javascriptBootstrap.ts index cdb33d024..2cc20ffdf 100644 --- a/src/domain/javascript/javascriptBootstrap.ts +++ b/src/domain/javascript/javascriptBootstrap.ts @@ -1,6 +1,9 @@ import * as t from "@babel/types"; -import { semanticStaticPropertyKey } from "./javascriptAstValues.js"; +import { + semanticStaticPropertyKey, + runtimeFunctionParameters, +} from "./javascriptAstValues.js"; import { moduleFactory } from "./javascriptStaticAnalysisHelpers.js"; import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js"; import { @@ -27,7 +30,7 @@ export const javascriptBootstrapAt = ( (!t.isFunctionExpression(call.callee) && !t.isArrowFunctionExpression(call.callee)) || !t.isBlockStatement(call.callee.body) || - call.callee.params.length !== 0 || + runtimeFunctionParameters(call.callee).length !== 0 || call.arguments.length !== 0 ) return undefined; @@ -63,10 +66,10 @@ export const javascriptBootstrapAt = ( !t.isFunctionDeclaration(loader) || loader.id === null || loader.id === undefined || - loader.params.length !== 1 + runtimeFunctionParameters(loader).length !== 1 ) continue; - const parameter = loader.params[0]; + const parameter = runtimeFunctionParameters(loader)[0]; if (!t.isIdentifier(parameter)) continue; const loaderName = loader.id.name; const loaderBindingId = bindingId(state, loader.id); diff --git a/src/domain/javascript/javascriptModuleInterop.ts b/src/domain/javascript/javascriptModuleInterop.ts index c2e26d6fe..6f8eb9980 100644 --- a/src/domain/javascript/javascriptModuleInterop.ts +++ b/src/domain/javascript/javascriptModuleInterop.ts @@ -26,6 +26,7 @@ import { import { SemanticPropertyPathCoverage } from "./javascriptSemanticPropertyPaths.js"; import { readExactJavaScriptLiteral, + runtimeFunctionParameters, unwrapJavaScriptExpression, } from "./javascriptAstValues.js"; @@ -662,10 +663,10 @@ const identityFunction = ( !t.isFunction(node) || node.async || node.generator || - node.params.length !== 1 + runtimeFunctionParameters(node).length !== 1 ) return false; - const parameter = node.params[0]; + const parameter = runtimeFunctionParameters(node)[0]; const result = t.isBlockStatement(node.body) ? node.body.body.length === 1 && t.isReturnStatement(node.body.body[0]) ? node.body.body[0].argument diff --git a/src/domain/javascript/javascriptSemanticAnalysis.ts b/src/domain/javascript/javascriptSemanticAnalysis.ts index 7e20c0e13..578789ad5 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.ts @@ -18,6 +18,7 @@ import { } from "./javascriptSemanticProjection.js"; import { semanticObjectPatternKeys, + runtimeFunctionParameters, semanticStaticPropertyKey, semanticWriteTargets, } from "./javascriptAstValues.js"; @@ -717,7 +718,7 @@ function* collectDefinitionsSteps( functionBodies.push({ body: node, scope: nested, - parameters: parent.params, + parameters: runtimeFunctionParameters(parent), }); } const scope = currentSemanticScope(stack); @@ -1076,7 +1077,7 @@ const scopeKind = ( }; const functionParametersHaveExpressions = (node: t.Function): boolean => { - const pending: t.Node[] = [...node.params]; + const pending: t.Node[] = [...runtimeFunctionParameters(node)]; while (pending.length > 0) { const parameter = pending.pop(); if (t.isAssignmentPattern(parameter)) return true; @@ -1133,7 +1134,7 @@ const bindFunctionLocals = ( scope: JavaScriptSemanticScopeState, state: JavaScriptSemanticAnalysisState, ): void => { - for (const parameter of node.params) + for (const parameter of runtimeFunctionParameters(node)) bindPattern({ pattern: t.isTSParameterProperty(parameter) ? parameter.parameter diff --git a/src/domain/javascript/javascriptSemanticCallResolution.ts b/src/domain/javascript/javascriptSemanticCallResolution.ts index 9292ea265..3ed09dca0 100644 --- a/src/domain/javascript/javascriptSemanticCallResolution.ts +++ b/src/domain/javascript/javascriptSemanticCallResolution.ts @@ -6,7 +6,10 @@ import type { } from "./javascriptSemanticIr.js"; import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; import { semanticCallableIdForNode } from "./javascriptSemanticProjection.js"; -import { unwrapJavaScriptExpression } from "./javascriptAstValues.js"; +import { + unwrapJavaScriptExpression, + runtimeFunctionParameters, +} from "./javascriptAstValues.js"; import { resolveSemanticBindingState, type JavaScriptSemanticAnalysisState, @@ -194,14 +197,15 @@ const parameterAcceptsArgument = ( ): boolean => { const node = state.callableNodesById.get(callable.callableId); if (!t.isFunction(node)) return false; - const parameterIndex = node.params.findIndex((parameter) => + const parameters = runtimeFunctionParameters(node); + const parameterIndex = parameters.findIndex((parameter) => rangeContains(range(parameter), location), ); if (parameterIndex === argumentIndex) return true; return ( parameterIndex >= 0 && parameterIndex < argumentIndex && - t.isRestElement(node.params[parameterIndex]) + t.isRestElement(parameters[parameterIndex]) ); }; diff --git a/src/domain/javascript/javascriptSemanticFingerprints.ts b/src/domain/javascript/javascriptSemanticFingerprints.ts index 8b6edc036..c8615788c 100644 --- a/src/domain/javascript/javascriptSemanticFingerprints.ts +++ b/src/domain/javascript/javascriptSemanticFingerprints.ts @@ -1,6 +1,7 @@ import { createHash } from "node:crypto"; import * as t from "@babel/types"; +import { runtimeFunctionParameters } from "./javascriptAstValues.js"; import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; import type { JavaScriptSemanticCallAnalysis } from "./javascriptSemanticCalls.js"; @@ -279,7 +280,7 @@ const relationShape = ( ]; const callableParameterArity = (node: t.Node): number => - t.isFunction(node) ? node.params.length : 0; + t.isFunction(node) ? runtimeFunctionParameters(node).length : 0; const isAsyncCallable = (node: t.Node): boolean => t.isFunction(node) && node.async; diff --git a/src/domain/javascript/javascriptSemanticIterationSources.ts b/src/domain/javascript/javascriptSemanticIterationSources.ts index ea3708e51..0521f76b8 100644 --- a/src/domain/javascript/javascriptSemanticIterationSources.ts +++ b/src/domain/javascript/javascriptSemanticIterationSources.ts @@ -2,6 +2,7 @@ import * as t from "@babel/types"; import { semanticObjectPatternKeys, + runtimeFunctionParameters, semanticStaticPropertyKey, } from "./javascriptAstValues.js"; import { @@ -212,7 +213,8 @@ export const semanticIterationSources = ( else if (t.isYieldExpression(node) && node.delegate && node.argument != null) add(sources, { node: node.argument, projection: [] }, node, {}); else if (t.isFunction(node)) - for (const parameter of node.params) visit(context, parameter, undefined); + for (const parameter of runtimeFunctionParameters(node)) + visit(context, parameter, undefined); return sources; }; diff --git a/src/domain/javascript/javascriptStaticAnalysisBundler.ts b/src/domain/javascript/javascriptStaticAnalysisBundler.ts index 773f88d7d..b49f4c2ae 100644 --- a/src/domain/javascript/javascriptStaticAnalysisBundler.ts +++ b/src/domain/javascript/javascriptStaticAnalysisBundler.ts @@ -1,4 +1,5 @@ import * as t from "@babel/types"; +import { runtimeFunctionParameters } from "./javascriptAstValues.js"; import { javascriptBootstrapAt } from "./javascriptBootstrap.js"; import { resolveSemanticBindingState, @@ -304,7 +305,7 @@ const runtimeMetadata = (node: t.Node | null | undefined): RuntimeMetadata => { asyncChunkKeys: [], unknownAsyncChunkKeys: 0, }; - const parameter = node.params[0]; + const parameter = runtimeFunctionParameters(node)[0]; const requireName = t.isIdentifier(parameter) ? parameter.name : null; if (requireName === null) return { diff --git a/src/domain/javascript/javascriptStaticAnalysisHelpers.ts b/src/domain/javascript/javascriptStaticAnalysisHelpers.ts index 71628bc8c..e2cc73f20 100644 --- a/src/domain/javascript/javascriptStaticAnalysisHelpers.ts +++ b/src/domain/javascript/javascriptStaticAnalysisHelpers.ts @@ -13,6 +13,7 @@ import type { } from "./javascriptStaticAnalysisTypes.js"; import { readExactJavaScriptLiteral, + runtimeFunctionParameters, semanticStaticPropertyKey, semanticStaticPropertyName, unwrapJavaScriptExpression, @@ -147,7 +148,7 @@ export const modulePropertyName = ( export const factoryRequireName = ( factory: t.FunctionExpression | t.ArrowFunctionExpression | t.ObjectMethod, ): string | null => { - const parameter = factory.params[2]; + const parameter = runtimeFunctionParameters(factory)[2]; return t.isIdentifier(parameter) ? parameter.name : null; }; diff --git a/src/domain/javascript/javascriptSymbolicBindings.ts b/src/domain/javascript/javascriptSymbolicBindings.ts index 62c70f953..faddf545f 100644 --- a/src/domain/javascript/javascriptSymbolicBindings.ts +++ b/src/domain/javascript/javascriptSymbolicBindings.ts @@ -1,6 +1,7 @@ import * as t from "@babel/types"; import { semanticStaticPropertyKey, + runtimeFunctionParameters, unwrapJavaScriptExpression, } from "./javascriptAstValues.js"; import { javascriptBootstrapAt } from "./javascriptBootstrap.js"; @@ -387,7 +388,7 @@ export class JavaScriptSymbolicBindings { invocationNode?: t.Node, ): SymbolicEnvironment { const values = new Map(); - fn.node.params.forEach((param, index) => { + runtimeFunctionParameters(fn.node).forEach((param, index) => { const target = t.isRestElement(param) ? param.argument : param; if (!t.isIdentifier(target)) return; const binding = resolveSemanticBindingState( @@ -866,9 +867,7 @@ export class JavaScriptSymbolicBindings { ? {} : { scopeId: this.state.scopeByNode.get(factory)!.scopeId }), }; - const first = factory.params[0]; - const second = factory.params[1]; - const third = factory.params[2]; + const [first, second, third] = runtimeFunctionParameters(factory); const binding = (n: t.Node | undefined) => t.isIdentifier(n) ? resolveSemanticBindingState(this.state, n, n.name)?.bindingId diff --git a/src/ghidra/GhidraAnalysisSeeds.test.ts b/src/ghidra/GhidraAnalysisSeeds.test.ts index 37437ebf7..769357373 100644 --- a/src/ghidra/GhidraAnalysisSeeds.test.ts +++ b/src/ghidra/GhidraAnalysisSeeds.test.ts @@ -23,7 +23,7 @@ import { type GhidraSeedCommitment, type GhidraSeedReport, } from "./GhidraAnalysisSeeds.js"; -import type { GhidraInstallationHost } from "./GhidraInstallation.js"; +import { ghidraProfileInstallationHost as host } from "./GhidraInstallation.fixture.js"; import { GhidraProvider } from "./GhidraProvider.js"; const directories: string[] = []; @@ -193,19 +193,6 @@ describe("Ghidra seed session verification", () => { }); describe("Ghidra seed profile", () => { - const host: GhidraInstallationHost = { - platform: "linux", - architecture: "x64", - readText: () => "application.version=12.1.4\napplication.java.min=21\n", - executable: () => true, - probeJava: () => ({ - version: "21.0.11", - major: 21, - home: "/jdk-21", - bits: 64, - runtime: "jdk", - }), - }; const pe: BinaryTarget = { path: "/fixture.exe", sha256: "a".repeat(64), diff --git a/src/ghidra/GhidraInstallation.fixture.ts b/src/ghidra/GhidraInstallation.fixture.ts new file mode 100644 index 000000000..cb81fa0de --- /dev/null +++ b/src/ghidra/GhidraInstallation.fixture.ts @@ -0,0 +1,16 @@ +import type { GhidraInstallationHost } from "./GhidraInstallation.js"; + +/** Simulated valid installation for profile tests; never starts Ghidra or Java. */ +export const ghidraProfileInstallationHost: GhidraInstallationHost = { + platform: "linux", + architecture: "x64", + readText: () => "application.version=12.1.4\napplication.java.min=21\n", + executable: () => true, + probeJava: () => ({ + version: "21.0.11", + major: 21, + home: "/jdk-21", + bits: 64, + runtime: "jdk", + }), +}; diff --git a/src/ghidra/GhidraLanguageOverride.test.ts b/src/ghidra/GhidraLanguageOverride.test.ts index 02c5bf245..86909112e 100644 --- a/src/ghidra/GhidraLanguageOverride.test.ts +++ b/src/ghidra/GhidraLanguageOverride.test.ts @@ -11,7 +11,7 @@ import { ghidraProfileLanguageOverride, sameGhidraLanguageOverride, } from "./GhidraAnalysisProfile.js"; -import type { GhidraInstallationHost } from "./GhidraInstallation.js"; +import { ghidraProfileInstallationHost as host } from "./GhidraInstallation.fixture.js"; import { admitGhidraLanguageOverride, parseGhidraLanguageDefinitions, @@ -39,21 +39,6 @@ const X86_LDEFS = ` `; -// Fake installation inspection; the language catalog is a real directory. -const host: GhidraInstallationHost = { - platform: "linux", - architecture: "x64", - readText: () => "application.version=12.1.4\napplication.java.min=21\n", - executable: () => true, - probeJava: () => ({ - version: "21.0.11", - major: 21, - home: "/jdk-21", - bits: 64, - runtime: "jdk", - }), -}; - const pe: BinaryTarget = { path: "/fixture.exe", sha256: "a".repeat(64), diff --git a/src/ghidra/GhidraMipsProfile.test.ts b/src/ghidra/GhidraMipsProfile.test.ts index 800de9490..57c04daef 100644 --- a/src/ghidra/GhidraMipsProfile.test.ts +++ b/src/ghidra/GhidraMipsProfile.test.ts @@ -14,7 +14,7 @@ import { ghidraMipsProfileParameters, ghidraPinnedMipsLanguage, } from "./GhidraMipsProfile.js"; -import type { GhidraInstallationHost } from "./GhidraInstallation.js"; +import { ghidraProfileInstallationHost as host } from "./GhidraInstallation.fixture.js"; import { GHIDRA_SESSION_CAPABILITIES } from "./GhidraSessionValues.js"; import type { GhidraMipsSoftFloatReport } from "./GhidraMipsProfile.js"; import { @@ -22,20 +22,6 @@ import { ghidraProfileLanguageOverride, } from "./GhidraAnalysisProfile.js"; -// Fake installation inspection tests admission/profile contracts, not Ghidra. -const host: GhidraInstallationHost = { - platform: "linux", - architecture: "x64", - readText: () => "application.version=12.1.4\napplication.java.min=21\n", - executable: () => true, - probeJava: () => ({ - version: "21.0.11", - major: 21, - home: "/jdk-21", - bits: 64, - runtime: "jdk", - }), -}; const parsed = parseConfig({ GHIDRA_INSTALL_DIR: "/ghidra" }); if (!parsed.ok) throw parsed.error; const config = parsed.value; @@ -155,7 +141,13 @@ describe("bounded Ghidra MIPS admission", () => { reason: expect.stringContaining(reason), }); const resolved = await ghidra.resolveAnalysisProfile(value); - expect(resolved.ok).toBe(false); + expect(resolved).toMatchObject({ + ok: false, + error: { + _tag: "AnalysisUnsupportedTargetError", + reason: expect.stringContaining(reason), + }, + }); }, ); @@ -180,7 +172,13 @@ describe("recordless legacy MIPS32 admission", () => { status: "unsupported", }); const resolved = await ghidra.resolveAnalysisProfile(object); - expect(resolved.ok).toBe(false); + expect(resolved).toMatchObject({ + ok: false, + error: { + _tag: "AnalysisUnsupportedTargetError", + reason: expect.stringContaining("ET_EXEC"), + }, + }); }); it.each([ diff --git a/src/ghidra/GhidraPowerPcProfile.test.ts b/src/ghidra/GhidraPowerPcProfile.test.ts index 831a47f3b..0be7aa898 100644 --- a/src/ghidra/GhidraPowerPcProfile.test.ts +++ b/src/ghidra/GhidraPowerPcProfile.test.ts @@ -16,7 +16,7 @@ import { ghidraProfileLanguageOverride, } from "./GhidraAnalysisProfile.js"; import { GhidraProvider } from "./GhidraProvider.js"; -import type { GhidraInstallationHost } from "./GhidraInstallation.js"; +import { ghidraProfileInstallationHost as host } from "./GhidraInstallation.fixture.js"; // Abbreviated from Ghidra 12.1.4 Processors/PowerPC/data/languages/ppc.ldefs. const PPC_LDEFS = ` @@ -32,20 +32,6 @@ const PPC_LDEFS = ` `; -// Fake installation inspection tests admission/profile contracts, not Ghidra. -const host: GhidraInstallationHost = { - platform: "linux", - architecture: "x64", - readText: () => "application.version=12.1.4\n", - executable: () => true, - probeJava: () => ({ - version: "21.0.11", - major: 21, - home: "/jdk-21", - bits: 64, - runtime: "jdk", - }), -}; const configFor = (environment: NodeJS.ProcessEnv) => { const parsed = parseConfig({ GHIDRA_INSTALL_DIR: "/ghidra", ...environment }); if (!parsed.ok) throw parsed.error; @@ -65,6 +51,7 @@ const target = (change: Partial = {}): BinaryTarget => ({ describe("bounded Ghidra PowerPC admission", () => { it("binds the generic language instead of the loader's e500 choice", async () => { const ghidra = new GhidraProvider(config, silentLogger, {}, host); + expect(ghidra.inspectAvailability()).toMatchObject({ status: "available" }); expect(ghidra.inspectTargetSupport(target()).status).toBe("supported"); const resolved = await ghidra.resolveAnalysisProfile(target()); if (!resolved.ok) throw resolved.error; @@ -152,7 +139,13 @@ describe("bounded Ghidra PowerPC admission", () => { reason: expect.stringContaining(reason), }); const resolved = await ghidra.resolveAnalysisProfile(value); - expect(resolved.ok).toBe(false); + expect(resolved).toMatchObject({ + ok: false, + error: { + _tag: "AnalysisUnsupportedTargetError", + reason: expect.stringContaining(reason), + }, + }); }, ); diff --git a/src/ghidra/GhidraRiscvProfile.test.ts b/src/ghidra/GhidraRiscvProfile.test.ts index 718fe8d46..3ada4d15b 100644 --- a/src/ghidra/GhidraRiscvProfile.test.ts +++ b/src/ghidra/GhidraRiscvProfile.test.ts @@ -13,7 +13,7 @@ import { hopperLoaderArgsForTarget } from "../hopper/HopperAnalysisProfile.js"; import { IdaProvider } from "../ida/IdaProvider.js"; import { GhidraProvider } from "./GhidraProvider.js"; import { ghidraRiscvLimitations } from "./GhidraRiscvProfile.js"; -import type { GhidraInstallationHost } from "./GhidraInstallation.js"; +import { ghidraProfileInstallationHost as host } from "./GhidraInstallation.fixture.js"; import { ghidraPinnedLanguage, ghidraProfileLanguageOverride, @@ -49,20 +49,6 @@ const RISCV_LDEFS = ` `; -// Fake installation inspection tests admission/profile contracts, not Ghidra. -const host: GhidraInstallationHost = { - platform: "linux", - architecture: "x64", - readText: () => "application.version=12.1.4\napplication.java.min=21\n", - executable: () => true, - probeJava: () => ({ - version: "21.0.11", - major: 21, - home: "/jdk-21", - bits: 64, - runtime: "jdk", - }), -}; const configOf = ( installDir: string, environment: Record = {}, diff --git a/tests/acceptance/applications/typescriptThisParametersCli.test.ts b/tests/acceptance/applications/typescriptThisParametersCli.test.ts new file mode 100644 index 000000000..a90dddec5 --- /dev/null +++ b/tests/acceptance/applications/typescriptThisParametersCli.test.ts @@ -0,0 +1,140 @@ +import { join } from "node:path"; + +import { expect } from "vitest"; + +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; +import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js"; +import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js"; + +cliTest.for(["CLI", "stdio MCP"] as const)( + "maps arguments to runtime TypeScript parameters through %s", + async (surface, { cli, processes }) => { + const root = await createTestTempDirectory("rea-this-parameters-"); + await writeFixtureFiles(root, { + "bundle.mts": [ + "self.webpackChunkApp.push([[1], { 7: function(this: void, module: unknown, exports: Record, require: (id: number) => unknown) { exports.answer = 42; } }, function(this: void, require: (id: number) => unknown) { require(7); }]);", + ].join("\n"), + "interop.cts": [ + "function identity(this: void, value: T) { return value; }", + 'const electron = identity(require("electron"));', + 'electron.ipcRenderer.send("typed-identity");', + ].join("\n"), + "ipc-wrapper.cts": [ + 'const { ipcRenderer } = require("electron");', + "function send(this: void, channel: string) { ipcRenderer.send(channel); }", + "function sendRest(this: void, ...channels: string[]) { ipcRenderer.send(...channels); }", + 'send("typed-channel");', + 'sendRest("typed-rest");', + ].join("\n"), + "entry.mts": [ + "function first(this: void, value: number) { return value; }", + "function rest(this: void, ...values: number[]) { return values; }", + "function destructured({ left }: { left: number }, right: number) { return left + right; }", + "function mixed(this: void, head: number, ...tail: number[]) { return [head, ...tail]; }", + "const a = first(7);", + "const b = rest(1, 2);", + "const c = destructured({ left: 3 }, 4);", + "const d = mixed(9, 10, 11);", + "console.log(JSON.stringify([a, b, c, d, first.length, rest.length, mixed.length]));", + ].join("\n"), + }); + const control = await processes.run( + process.execPath, + [join(root, "entry.mts")], + { timeoutMs: 15_000 }, + ); + expect(control.exitCode, control.stderr).toBe(0); + expect(JSON.parse(control.stdout)).toEqual([ + 7, + [1, 2], + 7, + [9, 10, 11], + 1, + 0, + 1, + ]); + const analysis = await analyzeJavaScriptDirectory(surface, cli, root); + const graph = analysis.semantic_graph; + const parameters = graph.nodes.filter( + (node) => + node.kind === "parameter" && node.identity.module_path === "entry.mts", + ); + expect(parameters.map((node) => node.label).sort()).toEqual([ + "head", + "left", + "right", + "tail", + "value", + "values", + ]); + const parameterIds = new Set(parameters.map((node) => node.node_id)); + const flows = graph.relations.filter( + (relation) => + relation.relation === "argument-to-parameter" && + parameterIds.has(relation.target_node_id), + ); + expect( + flows + .map((flow) => { + const source = graph.nodes.find( + (node) => node.node_id === flow.source_node_id, + ); + const target = parameters.find( + (node) => node.node_id === flow.target_node_id, + ); + const owner = graph.nodes.find( + (node) => node.node_id === target?.function_node_id, + ); + return [ + source?.identity.source_range?.start.line, + source?.label, + owner?.label, + target?.label, + ]; + }) + .sort(), + ).toEqual([ + [5, "argument 0", "first", "value"], + [6, "argument 0", "rest", "values"], + [6, "argument 1", "rest", "values"], + [7, "argument 0", "destructured", "left"], + [7, "argument 1", "destructured", "right"], + [8, "argument 0", "mixed", "head"], + [8, "argument 1", "mixed", "tail"], + [8, "argument 2", "mixed", "tail"], + ]); + expect( + analysis.graph.nodes + .flatMap((node) => node.observations) + .some( + (observation) => + Array.isArray(observation.properties.exports) && + observation.properties.exports.includes("answer"), + ), + ).toBe(true); + const channels = analysis.graph.nodes + .filter((node) => node.kind === "ipc-channel") + .flatMap((node) => + node.observations.map((observation) => observation.properties.channel), + ); + expect(channels).toEqual( + expect.arrayContaining(["typed-channel", "typed-rest", "typed-identity"]), + ); + for (const [name, arity] of [ + ["first", 1], + ["rest", 1], + ["destructured", 2], + ["mixed", 2], + ] as const) { + const callable = graph.nodes.find( + (node) => node.kind === "function" && node.label === name, + ); + expect(callable, name).toBeDefined(); + const fingerprint = graph.fingerprints.find( + (value) => value.function_node_id === callable?.node_id, + ); + expect(fingerprint?.components.parameter_arity, name).toBe(arity); + } + }, +); diff --git a/tests/boundary/filesystem/ciTestReports.test.ts b/tests/boundary/filesystem/ciTestReports.test.ts index 6a5942448..48ba18c11 100644 --- a/tests/boundary/filesystem/ciTestReports.test.ts +++ b/tests/boundary/filesystem/ciTestReports.test.ts @@ -17,6 +17,32 @@ import { workflowGit } from "../../support/workflowGit.js"; const execute = promisify(execFile); const script = new URL("../../../scripts/ci/test-report.mjs", import.meta.url); + +// Each report invocation owns its CI state and summary destination. Inherited +// workflow flags must not change fixture outcomes or append to the real job. +const executeTimingReport = async ( + root: string, + environment: NodeJS.ProcessEnv = {}, +) => { + const summary = join(root, "summary.md"); + await writeFile(summary, ""); + const output = await execute(process.execPath, [fileURLToPath(script)], { + cwd: root, + env: { + ...process.env, + SHARD_RESULT: "success", + MERGE_RESULT: "success", + SOURCE_REQUIRED: "false", + SOURCE_RESULT: "", + CI_VERIFY_TEST_INVENTORY: "false", + CI_TEST_SELECTION: "", + ...environment, + GITHUB_STEP_SUMMARY: summary, + }, + }); + return { ...output, summary: await readFile(summary, "utf8") }; +}; + const stepsSchema = z.array( z.object({ name: z.string().optional(), @@ -225,14 +251,8 @@ it("rejects successful shard reports with missing or duplicate portable files", files: names.map((name) => ({ name, durationMs: 1 })), }), ); - return execute(process.execPath, [fileURLToPath(script)], { - cwd: root, - env: { - ...process.env, - SHARD_RESULT: "success", - MERGE_RESULT: "success", - CI_VERIFY_TEST_INVENTORY: "true", - }, + return executeTimingReport(root, { + CI_VERIFY_TEST_INVENTORY: "true", }); }; await expect( @@ -308,17 +328,11 @@ it("exports portable timing history and removes it on a failed, partial, or inva source?: string, ) => { await writeFile(join(root, "test-timings.json"), JSON.stringify(value)); - await writeFile(summary, ""); - return execute(process.execPath, [fileURLToPath(script)], { - cwd: root, - env: { - ...process.env, - GITHUB_STEP_SUMMARY: summary, - SHARD_RESULT: shards, - SOURCE_REQUIRED: String(source !== undefined), - SOURCE_RESULT: source ?? "", - MERGE_RESULT: merge, - }, + return executeTimingReport(root, { + SHARD_RESULT: shards, + SOURCE_REQUIRED: String(source !== undefined), + SOURCE_RESULT: source ?? "", + MERGE_RESULT: merge, }); }; await run(report); @@ -458,25 +472,17 @@ it("recovers complete module costs from real blob reports without executing test expect(file.durationMs).toBeCloseTo( Object.values(file.phases).reduce((sum, value) => sum + value, 0), ); - const partial = await execute(process.execPath, [fileURLToPath(script)], { - cwd: root, - env: { - ...process.env, - SHARD_RESULT: "skipped", - SOURCE_REQUIRED: "true", - SOURCE_RESULT: "success", - MERGE_RESULT: "success", - }, + const partial = await executeTimingReport(root, { + SHARD_RESULT: "skipped", + SOURCE_REQUIRED: "true", + SOURCE_RESULT: "success", }); - expect(partial.stdout).toContain("Partial test diagnostics"); - expect(partial.stdout).toContain("sample.test.js"); + expect(partial.summary).toContain("Partial test diagnostics"); + expect(partial.summary).toContain("sample.test.js"); await expect( readFile(join(root, ".cache/ci-test-history/test-results.json")), ).rejects.toMatchObject({ code: "ENOENT" }); - await execute(process.execPath, [fileURLToPath(script)], { - cwd: root, - env: { ...process.env, SHARD_RESULT: "success", MERGE_RESULT: "success" }, - }); + await executeTimingReport(root); expect( parseTestDurations( await readFile( @@ -508,10 +514,7 @@ it("recovers complete module costs from real blob reports without executing test files: [{ state: "failed" }], }); // Even a caller accidentally marking the merge successful cannot publish this report. - await execute(process.execPath, [fileURLToPath(script)], { - cwd: root, - env: { ...process.env, SHARD_RESULT: "success", MERGE_RESULT: "success" }, - }); + await executeTimingReport(root); await expect( readFile(join(root, ".cache/ci-test-history/test-results.json")), ).rejects.toMatchObject({ code: "ENOENT" }); @@ -543,21 +546,17 @@ it("records failed omissions from full reports without treating partial or unhan }; const run = async (report: unknown, source = "failure") => { await writeFile(join(root, "test-timings.json"), JSON.stringify(report)); - await execute(process.execPath, [fileURLToPath(script)], { - cwd: root, - env: { - ...process.env, - SHARD_RESULT: "failure", - SOURCE_REQUIRED: "true", - SOURCE_RESULT: source, - MERGE_RESULT: "failure", - CI_VERIFY_TEST_INVENTORY: "true", - CI_TEST_SELECTION: JSON.stringify( - planTestSelection(["src/sqlite/Provider.ts"], "pull_request", "fast"), - ), - GITHUB_SHA: "merge-sha", - CI_PR_HEAD_SHA: "pr-head-sha", - }, + await executeTimingReport(root, { + SHARD_RESULT: "failure", + SOURCE_REQUIRED: "true", + SOURCE_RESULT: source, + MERGE_RESULT: "failure", + CI_VERIFY_TEST_INVENTORY: "true", + CI_TEST_SELECTION: JSON.stringify( + planTestSelection(["src/sqlite/Provider.ts"], "pull_request", "fast"), + ), + GITHUB_SHA: "merge-sha", + CI_PR_HEAD_SHA: "pr-head-sha", }); return JSON.parse( await readFile(